Files
2026-09-24 10:40:57 +08:00

53 lines
2.5 KiB
Python

def validate(context, target, params):
errors = []
if target is None:
errors.append("NO_TARGET: boolean_combine 需要一个target实体")
if params["with_id"] not in context:
errors.append(f"UNKNOWN_ID: 上下文中不存在 '{params['with_id']}'")
return errors
def run(context, target, params):
other = context[params["with_id"]]
op = params["operation"]
if op == "union":
# Flatten solids explicitly: nested Part/Compound union can otherwise
# silently discard the carrier/core while reporting a valid shape.
solids = list(target.solids()) + list(other.solids())
if solids and len(target.solids()) and len(other.solids()):
result = solids[0].fuse(*solids[1:])
minimum_volume = max(s.volume for s in solids)
if result.volume < minimum_volume - max(1e-4, minimum_volume*1e-8):
raise ValueError("UNION_LOST_MATERIAL: 融合结果丢失原实体材料")
return result
return target + other
elif op == "cut":
metric = "volume" if len(target.solids()) else "area"
unit = "mm^3" if metric == "volume" else "mm^2"
before = getattr(target, metric)
result = target - other
removed = before - (getattr(result, metric) if result is not None else 0)
if removed <= max(1e-7, abs(before) * 1e-10):
raise ValueError(
f"CUT_NO_EFFECT: 减去的实体(with_id='{params['with_id']}')跟target几乎没有真实"
f"相交,{metric}只减少了{removed:.6f}{unit}——cutter大概率根本没有落在target内部,"
"检查cutter的位置坐标/旋转角度是否算错了,两者实际上完全没有接触上"
)
return result
elif op == "intersect":
return target & other
elif op == "group":
# 真实踩过的坑:像bearing这类结果本身是多实体装配体(球/内外圈天然互相接触),
# 如果用"+"做真正的布尔融合,OCCT会把装配体内部所有互相接触的独立实体也焊成
# 一坨,破坏了标准件内部本该能相对运动的多实体结构——即使这些实体跟target完全
# 不接触也一样会被波及。用Compound单纯归并两边的solid,不触发任何布尔运算,
# 各自的实体边界原样保留。
from build123d import Compound
return Compound(children=list(target.solids()) + list(other.solids()))
else:
raise ValueError(f"未知 operation: {op}")