diff --git a/src/simplecadapi/__init__.py b/src/simplecadapi/__init__.py index 1e09ceed..16769cd4 100644 --- a/src/simplecadapi/__init__.py +++ b/src/simplecadapi/__init__.py @@ -69,7 +69,7 @@ from .core import ( get_current_cs, ) from .errors import SimpleCADError -from .operators.deformation import scale_rsolid, offset_rsolid, transform_rsolid +from .operators.deformation import scale_rsolid, offset_rsolid, transform_rsolid, boolean_rsolidlist from .operators.section_features import extrude_taper_rsolid, sweep_multisection_rsolid from .operators.limited_extrusion import extrude_until_rsolid from .operators.draft import draft_rsolid @@ -438,6 +438,7 @@ def notebook_id() -> str: __all__ = [ "scale_rsolid", + "boolean_rsolidlist", "transform_rsolid", "offset_rsolid", "extrude_taper_rsolid", diff --git a/src/simplecadapi/operators/_support.py b/src/simplecadapi/operators/_support.py index 57f7a77a..c5c1576e 100644 --- a/src/simplecadapi/operators/_support.py +++ b/src/simplecadapi/operators/_support.py @@ -1245,6 +1245,7 @@ def _record_geo_selection_nodes( op=op, params={ "target_kind": kind, + "source_output_slot": int(source_shape._get_runtime("graph.output_slot", 0)), "geo_selector": _make_geo_selector( selected, source_shape=source_shape, diff --git a/src/simplecadapi/operators/deformation.py b/src/simplecadapi/operators/deformation.py index e56cc95c..1121be9f 100644 --- a/src/simplecadapi/operators/deformation.py +++ b/src/simplecadapi/operators/deformation.py @@ -20,6 +20,7 @@ from ._support import ( _attach_lineage_from_source, _current_context_metadata, _ensure_geo_selection_node_ids, _resolve_selector_or_shapes, _serialize_shape_refs, + _ensure_geo_selection_input_nodes, ) @@ -44,6 +45,8 @@ def _finish(source: Solid, wrapped, op: str, params: dict, inputs: list) -> Soli result._metadata = source._metadata.copy() # These builders do not yet provide a complete face-history channel. _attach_lineage_from_source(source, result, derivation="continuation", op=op, coverage="partial") + _ensure_geo_selection_input_nodes(inputs) + params = {**params, "input_refs": _serialize_shape_refs(inputs)} record_operation_if_active(op=op, params=params, outputs=result, input_shapes=inputs, context=_current_context_metadata()) return result @@ -164,4 +167,51 @@ def offset_rsolid( return _finish(solid, builder.Shape(), "make_offset_rsolid", params, [solid, *faces]) -__all__ = ("scale_rsolid", "offset_rsolid", "transform_rsolid") +def boolean_rsolidlist( + left: Sequence[Solid], + right: Sequence[Solid], + operation: str, +) -> list[Solid]: + """Apply a set boolean to two body groups, retaining every result solid. + + Members of each group are a geometric set. Unlike single-solid booleans, + a cut or intersection may return several solids or an empty list. + Topology lineage is partial; the ordered inputs and all output slots are + recorded so downstream features can replay the same geometry. + """ + from ..kernel.ocp_booleans import cut_shapes, common_shapes, fuse_shapes + from ..kernel.ocp_export import make_compound_always + lhs, rhs = list(left), list(right) + if operation not in {"cut", "intersect", "union"}: + raise ValueError("operation must be cut, intersect or union") + inputs = [*lhs, *rhs] + if any(not isinstance(body, Solid) for body in inputs): + raise TypeError("boolean groups must contain Solid values") + if any(body.wrapped.IsNull() or not BRepCheck_Analyzer(body.wrapped).IsValid() for body in inputs): + raise ValueError("boolean groups must contain valid nonempty topology") + if operation == "union": + shape = fuse_shapes([body.wrapped for body in inputs]) if inputs else None + elif not lhs or (operation == "intersect" and not rhs): + shape = None + elif operation == "cut": + shape = cut_shapes(make_compound_always([body.wrapped for body in lhs]), + [body.wrapped for body in rhs]) + else: + shape = common_shapes([make_compound_always([body.wrapped for body in group]) + for group in (lhs, rhs)]) + if shape is not None and not BRepCheck_Analyzer(shape).IsValid(): + raise ValueError("set boolean produced invalid topology") + result = [Solid(solid) for solid in solids_of(shape)] if shape is not None else [] + for body in result: + for source in inputs: + _attach_lineage_from_source(source, body, derivation="continuation", + op="make_boolean_rsolidlist", coverage="partial") + _ensure_geo_selection_input_nodes(inputs) + record_operation_if_active(op="make_boolean_rsolidlist", + params={"operation": operation, "left_count": len(lhs), "right_count": len(rhs), + "input_refs": _serialize_shape_refs(inputs)}, outputs=result, + input_shapes=inputs, context=_current_context_metadata()) + return result + + +__all__ = ("scale_rsolid", "offset_rsolid", "transform_rsolid", "boolean_rsolidlist") diff --git a/src/simplecadapi/operators/product.py b/src/simplecadapi/operators/product.py index b6fb1fab..fede3b48 100644 --- a/src/simplecadapi/operators/product.py +++ b/src/simplecadapi/operators/product.py @@ -131,9 +131,10 @@ def make_part_rpart( try: part = Part(part_id, body, name=name) _reserve_semantic_id("part", part.part_id) + _ensure_geo_selection_input_nodes([body]) record_operation_if_active( _OP_MAKE_PART_RPART, - _part_params(part), + {**_part_params(part), "input_refs": _serialize_shape_refs([body])}, outputs=part, input_shapes=[body], semantic_delta=_semantic_created("Part", part.part_id, part.to_dict()), diff --git a/src/simplecadapi/ql.py b/src/simplecadapi/ql.py index 28821558..246f9fac 100644 --- a/src/simplecadapi/ql.py +++ b/src/simplecadapi/ql.py @@ -148,6 +148,15 @@ def _lookup_property(obj: Any, path: str) -> Any: gtype = _geom_type(obj) return gtype if gtype is not None else MISSING + if path.startswith("geom.bbox.") and hasattr(obj, "wrapped"): + from .kernel.ocp_properties import bounding_box + field = path.removeprefix("geom.bbox.") + names = {f"{side}.{axis}": axis + bound + for side, bound in (("min", "min"), ("max", "max")) for axis in "xyz"} + if field in names: + return float(getattr(bounding_box(obj.wrapped), names[field])) + return MISSING + if path == "geom.family": cls_name = obj.__class__.__name__.lower() if cls_name == "edge": diff --git a/src/simplecadapi/recording/serializer.py b/src/simplecadapi/recording/serializer.py index b0f58472..c0e9515b 100644 --- a/src/simplecadapi/recording/serializer.py +++ b/src/simplecadapi/recording/serializer.py @@ -424,6 +424,7 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = { "scale_rsolid": {"status": "replayable", "op": "make_scale_rsolid"}, "transform_rsolid": {"status": "replayable", "op": "make_transform_rsolid"}, "offset_rsolid": {"status": "replayable", "op": "make_offset_rsolid"}, + "boolean_rsolidlist": {"status": "replayable", "op": "make_boolean_rsolidlist"}, "extrude_taper_rsolid": {"status": "replayable", "op": "make_extrude_taper_rsolid"}, "sweep_multisection_rsolid": {"status": "replayable", "op": "make_sweep_multisection_rsolid"}, "extrude_until_rsolid": {"status": "replayable", "op": "make_extrude_until_rsolid"}, @@ -607,6 +608,7 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = ( "make_scale_rsolid", "make_transform_rsolid", "make_offset_rsolid", + "make_boolean_rsolidlist", "make_extrude_taper_rsolid", "make_sweep_multisection_rsolid", "make_extrude_until_rsolid", @@ -2159,6 +2161,14 @@ def _ordered_input_shapes( return resolved +def _feature_input_shapes(ctx, graph, outputs, node, params): + # New features preserve order and output slots, including repeated inputs. + # Older graphs only carried distinct upstream nodes. + if "input_refs" in params: + return _ordered_input_shapes(ctx, graph, outputs, node, params) + return _all_input_outputs(ctx, outputs, node) + + def _semantic_view_origin( ctx: _ReplayContext, graph: OperationGraph, @@ -2924,7 +2934,7 @@ def _execute_graph( if op_name == "make_part_rpart": ctx.require_params(node.node_id, op_name, params, ("part_id",)) - body_outputs = _input_outputs(ctx, outputs, node, 0) + body_outputs = _feature_input_shapes(ctx, graph, outputs, node, params) if body_outputs: result = ops.make_part_rpart( str(params["part_id"]), @@ -3418,8 +3428,11 @@ def _execute_graph( ) source_outputs = _input_outputs(ctx, outputs, node, 0) if source_outputs: + source_slot = int(params.get("source_output_slot", 0)) + if source_slot < 0 or source_slot >= len(source_outputs): + ctx.fail(f"Graph node '{node.node_id}' selection source output slot {source_slot} is missing") result = _resolve_shape_from_geo_selector( - source_outputs[0], + source_outputs[source_slot], cast(Dict[str, Any], params["geo_selector"]), ) _store_outputs(node, result) @@ -3926,7 +3939,9 @@ def _execute_graph( if op_name == "make_extrude_until_rsolid": ctx.require_params(node.node_id, op_name, params, ("direction", "until", "target_count")) count = int(params["target_count"]) - values = [_input_outputs(ctx, outputs, node, i)[0] for i in range(count + 1)] + values = _feature_input_shapes(ctx, graph, outputs, node, params) + if len(values) != count + 1: + ctx.fail(f"Graph node '{node.node_id}' requires a profile and {count} ordered targets") result = ops.extrude_until_rsolid(profile=values[0], target=values[1:], direction=params["direction"], until=params["until"]) _store_outputs(node, result) @@ -3934,7 +3949,7 @@ def _execute_graph( if op_name == "make_extrude_taper_rsolid": ctx.require_params(node.node_id, op_name, params, ("vector", "taper")) - input_values = _input_outputs(ctx, outputs, node, 0) + input_values = _feature_input_shapes(ctx, graph, outputs, node, params) if input_values: result = ops.extrude_taper_rsolid(profile=input_values[0], vector=params["vector"], taper=params["taper"], flip_inner=params.get("flip_inner", True)) @@ -3944,8 +3959,11 @@ def _execute_graph( if op_name == "make_sweep_multisection_rsolid": ctx.require_params(node.node_id, op_name, params, ("profile_count", "is_frenet")) count = int(params["profile_count"]) - values = [_input_outputs(ctx, outputs, node, i)[0] for i in range(count + 1)] - binormal = _input_outputs(ctx, outputs, node, count + 1)[0] if params.get("binormal_is_wire") else params.get("binormal") + values = _feature_input_shapes(ctx, graph, outputs, node, params) + expected = count + 1 + int(bool(params.get("binormal_is_wire"))) + if len(values) != expected: + ctx.fail(f"Graph node '{node.node_id}' requires {expected} ordered sweep inputs") + binormal = values[count + 1] if params.get("binormal_is_wire") else params.get("binormal") result = ops.sweep_multisection_rsolid(profiles=values[:count], path=values[count], is_frenet=params["is_frenet"], binormal=binormal) _store_outputs(node, result) @@ -3953,7 +3971,7 @@ def _execute_graph( if op_name == "make_transform_rsolid": ctx.require_params(node.node_id, op_name, params, ("matrix",)) - inputs = _input_outputs(ctx, outputs, node, 0) + inputs = _feature_input_shapes(ctx, graph, outputs, node, params) if inputs: result = ops.transform_rsolid(solid=inputs[0], matrix=params["matrix"]) _store_outputs(node, result) @@ -3961,7 +3979,7 @@ def _execute_graph( if op_name == "make_scale_rsolid": ctx.require_params(node.node_id, op_name, params, ("factors", "center")) - inputs = _input_outputs(ctx, outputs, node, 0) + inputs = _feature_input_shapes(ctx, graph, outputs, node, params) if inputs: result = ops.scale_rsolid(solid=inputs[0], factors=params["factors"], center=params["center"]) _store_outputs(node, result) @@ -3969,7 +3987,7 @@ def _execute_graph( if op_name == "make_offset_rsolid": ctx.require_params(node.node_id, op_name, params, ("amount", "removed_face_count")) - inputs = _input_outputs(ctx, outputs, node, 0) + inputs = _feature_input_shapes(ctx, graph, outputs, node, params) if inputs: solid = inputs[0] faces = _resolve_feature_selection(ctx, node=node, solid=solid, @@ -3981,6 +3999,18 @@ def _execute_graph( _store_outputs(node, result) continue + if op_name == "make_boolean_rsolidlist": + ctx.require_params(node.node_id, op_name, params, + ("operation", "left_count", "right_count", "input_refs")) + inputs = _ordered_input_shapes(ctx, graph, outputs, node, params) + count, right_count = int(params["left_count"]), int(params["right_count"]) + if count < 0 or right_count < 0 or len(inputs) != count + right_count: + ctx.fail(f"Graph node '{node.node_id}' boolean input counts do not match") + result = ops.boolean_rsolidlist(left=inputs[:count], right=inputs[count:], + operation=params["operation"]) + _store_outputs(node, result) + continue + if op_name == "make_extrude_rsolid": ctx.require_params( node.node_id, op_name, params, ("direction", "distance") diff --git a/test/test_build123d_review_regressions.py b/test/test_build123d_review_regressions.py new file mode 100644 index 00000000..cfe07ca2 --- /dev/null +++ b/test/test_build123d_review_regressions.py @@ -0,0 +1,90 @@ +"""Review reproductions cross the two isolated kernel environments end to end.""" +import json +from pathlib import Path +import subprocess +import sys + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools/research/build123dftc")) +from b3ftc.replay import replay_trace_to_ftc +from b3ftc.validation import compare_metrics +from b3ftc._validate_worker import run + + +def capture(source): + python = ROOT.parent / ".venv/bin/python" + if not python.is_file(): + pytest.skip("isolated build123d environment is unavailable") + worker = "import json,sys; sys.path.insert(0,'tools/research/build123dftc'); from b3ftc.tracer import trace_source; print(json.dumps(trace_source(sys.stdin.read())))" + process = subprocess.run([str(python), "-c", worker], input="from build123d import *\n" + source, + text=True, capture_output=True, cwd=ROOT, timeout=30, check=True) + trace = json.loads(process.stdout) + assert trace["b3d_status"] == "ok", trace + return trace + + +@pytest.mark.parametrize("source", [ + "result=Solid.make_torus(5,1,major_angle=120)", + "a=Solid.make_box(10,2,2)\nb=Solid.make_box(2,4,4).moved(Location((4,-1,-1)))\nresult=a.cut(b)", + "a=Solid.make_box(10,2,2)\nb=Solid.make_box(2,4,4).moved(Location((4,-1,-1)))\nresult=a.cut(b).solids()[1].moved(Location((0,5,0)))", + "a=Solid.make_box(10,2,2)\nb=Solid.make_box(2,4,4)\nc=Solid.make_box(2,4,4).moved(Location((8,0,0)))\nresult=a.intersect(Compound([b,c]))", + "a=Solid.make_box(2,2,2)\nb=Solid.make_box(2,2,2).moved(Location((4,0,0)))\nc=Compound([a,b])\nresult=c.fillet(.2, c.edges().filter_by(Axis.Z))", + "a=Solid.make_box(2,2,2)\nb=Solid.make_box(2,2,2).moved(Location((4,0,0)))\nc=Compound([a,b])\nresult=c.fillet(.2, a.edges().filter_by(Axis.Z))", + "a=Solid.make_box(2,2,2)\nresult=a.split(Plane.XY.offset(10), keep=Keep.BOTH)", +]) +def test_review_geometry_reconciles_with_actual_return(tmp_path, source): + trace = capture(source) + generated, meta = replay_trace_to_ftc(trace, stem="review") + assert meta["status"] == "ok", meta + ftc = tmp_path / "review.ftc.py" + ftc.write_text(generated) + stage = tmp_path / "staged" + stage.mkdir() + metrics = run(ftc, stage) + comparison = compare_metrics(trace, metrics, meta) + assert comparison["quality"] == "accepted", comparison + + +@pytest.mark.parametrize("angles", ["start_angle=-30", "end_angle=80", "start_angle=-30,end_angle=80,major_angle=140"]) +def test_partial_torus_tube_is_explicitly_unsupported(angles): + trace = capture(f"result=Solid.make_torus(5,1,{angles})") + generated, meta = replay_trace_to_ftc(trace) + assert meta["status"] == "partial" + assert any("partial torus tube" in str(note) for note in meta["unsupported"]) + assert "feature tree produced no solid" in generated + + +def test_solid_ordering_uses_bounds_when_centroids_differ_between_kernels(tmp_path): + trace = capture("a=Solid.make_box(2,2,2)\nb=a.moved(Location((4,0,0)))\nresult=Compound([a,b])") + for step in trace["steps"]: + for component in step.get("result_components", []): + component["center"] = [1234, 5678, 9000] + generated, meta = replay_trace_to_ftc(trace, stem="bounds") + assert meta["status"] == "ok" + ftc = tmp_path / "bounds.ftc.py" + ftc.write_text(generated) + stage = tmp_path / "stage" + stage.mkdir() + assert compare_metrics(trace, run(ftc, stage), meta)["quality"] == "accepted" + + +@pytest.mark.parametrize("source", [ + "b=Box(1,2,3)+Cylinder(.75,2.5)\nwith BuildPart() as bp:\n insert(b)\n Cylinder(.4,6,mode=Mode.SUBTRACT)\nresult=bp.part", + "a=Box(4,4,4)\nb=Box(4,4,4).moved(Location((2,0,0)))\nresult=Part([a]) & b", + "section=RegularPolygon(1,6).face()\nresult=Solid.extrude_linear_with_rotation(section,(0,0),(0,0,5),72)", + "face=Face(Wire.make_circle(2),[Wire.make_circle(1)])\nresult=Solid.sweep(face,Wire([Edge.make_three_point_arc((0,0,0),(3,0,2),(5,0,5))]))", + "v=[(1,1,1),(1,-1,-1),(-1,1,-1),(-1,-1,1)]\nf=[[0,1,2],[0,3,1],[0,2,3],[1,3,2]]\nresult=Solid(Shell([Face(Wire.make_polygon([v[i] for i in face])) for face in f])).clean()", + "result=ConvexPolyhedron([(0,0,0),(1,0,0),(0,1,0),(0,0,1)])", +]) +def test_additional_fix_candidates_reconcile(tmp_path, source): + trace = capture(source) + generated, meta = replay_trace_to_ftc(trace, stem="candidate") + assert meta["status"] == "ok", meta + ftc = tmp_path / "candidate.ftc.py" + ftc.write_text(generated) + stage = tmp_path / "stage" + stage.mkdir() + comparison = compare_metrics(trace, run(ftc, stage), meta) + assert comparison["quality"] == "accepted", comparison diff --git a/test/test_build123d_trace.py b/test/test_build123d_trace.py index dfb5b0ad..a1e68f0a 100644 --- a/test/test_build123d_trace.py +++ b/test/test_build123d_trace.py @@ -227,3 +227,34 @@ result = intersection[0].moved(Location((0,10,0))) assert any(s["op"] == "component" for s in trace["steps"]) assert trace["solid_count"] == 1 assert trace["b3d_volume"] == pytest.approx(8) + + +@pytest.mark.parametrize("result", ["a-a", "[]", "()", "None", "Compound([])"]) +def test_explicit_empty_result_never_promotes_old_solid(result): + trace = trace_source(f"from build123d import *\na=Box(2,2,2)\nresult={result}") + assert trace["b3d_status"] == "error" + assert trace["result_refs"] == [] + assert trace["solid_count"] == 0 + + +@pytest.mark.parametrize("z", [-10, 10]) +def test_both_split_with_empty_side_is_serializable(z): + trace = checked(f"""from build123d import * +a = Solid.make_box(2,2,2) +result = a.split(Plane.XY.offset({z}), keep=Keep.BOTH) +""") + assert trace["solid_count"] == 1 + assert trace["b3d_valid"] + assert trace["b3d_volume"] == pytest.approx(8) + + +@pytest.mark.parametrize("op", ["revolve", "sweep"]) +def test_face_section_ignores_explicit_inner_wires(op): + call = ("Solid.revolve(section, 360, Axis((0,0,0),(0,1,0)), inner_wires=[hole])" + if op == "revolve" else "Solid.sweep(section, Wire.make_polygon([(3,0,0),(3,0,5)]), inner_wires=[hole])") + trace = checked(f"""from build123d import * +section = Face(Wire.make_circle(1, plane=Plane((3,0,0)))) +hole = Wire.make_circle(.2, plane=Plane((3,0,0))) +result = {call} +""") + assert not trace["steps"][-1].get("inner_wires") diff --git a/test/test_build123d_translation_output.py b/test/test_build123d_translation_output.py index 260a4c01..701996e3 100644 --- a/test/test_build123d_translation_output.py +++ b/test/test_build123d_translation_output.py @@ -113,6 +113,20 @@ class FormatTests(unittest.TestCase): class GeometryTests(unittest.TestCase): + def test_many_holes_use_small_sketches_and_preserve_all_loops(self): + profile = rectangle(500, 600) + for i in range(25): + for j in range(25): + x, y = 5 + 10 * i, 5 + 10 * j + points = [(x, y, 0), (x + 1, y, 0), (x + 1, y + 1, 0), (x, y + 1, 0)] + profile['wires'].append({'edges': [{'kind': 'line', 'start': a, 'end': b} + for a, b in zip(points, points[1:] + points[:1])]}) + payload = trace({'id': 's1', 'op': 'extrude', 'profile': profile, + 'parameters': {'direction': (0, 0, 1), 'distance': 1}}) + source, _ = replay_trace_to_ftc(payload) + self.assertIn('scad.make_face_from_wires_rface(', source) + self.build(payload, 500 * 600 - 625) + def test_real_recorded_fixtures_reconcile(self): import json for path in sorted((ROOT / 'test/build123d_traces').glob('*.trace.json')): diff --git a/test/test_build123d_unknown_api.py b/test/test_build123d_unknown_api.py index 711ef336..3d77ccf6 100644 --- a/test/test_build123d_unknown_api.py +++ b/test/test_build123d_unknown_api.py @@ -13,7 +13,6 @@ from b3ftc.validation import compare_metrics @pytest.mark.parametrize("statement", [ - "result = ConvexPolyhedron([(0,0,0),(1,0,0),(0,1,0),(0,0,1)])", "result = Box(2,3,4).to_splines()", "from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox\nresult = Solid(BRepPrimAPI_MakeBox(2,3,4).Solid())", ]) diff --git a/test/test_build123d_validation.py b/test/test_build123d_validation.py index c8547825..94c55faf 100644 --- a/test/test_build123d_validation.py +++ b/test/test_build123d_validation.py @@ -213,3 +213,32 @@ def test_requested_missing_reference_rejected(tmp_path): row = validate_row(ftc, trace, timeout=30, reference_step=tmp_path / "absent.step") assert row["quality"] == "rejected", row assert "reference_error" in row["reasons"] + + +@pytest.mark.parametrize("returned", ["None", "scad.make_box_rsolid(1, 1, 1)", + "scad.translate_shape(body, (10, 0, 0))"]) +def test_actual_build_return_cannot_hide_behind_matching_bodies(tmp_path, returned): + source = box_source().replace("return body", f"return {returned}") + # A plain build allows None so the worker itself must reject it. + source = "\n".join(line for line in source.splitlines() if not line.startswith("@scad.part")) + ftc, trace = write_case(tmp_path, "wrong_return", source) + row = validate_row(ftc, trace, timeout=30) + assert row["quality"] == "rejected", row + + +def test_returned_assembly_is_checked_in_world_coordinates(tmp_path): + source = """import simplecadapi as scad +BODIES = None +def build(): + global BODIES + body = scad.make_box_rsolid(10, 10, 10) + BODIES = [body] + part = scad.make_part_rpart(part_id='box', body=body) + assembly = scad.make_assembly_rassembly(assembly_id='placed') + return scad.add_component_rassembly(assembly=assembly, item=part, + component_id='box', placement=scad.make_placement_rplacement(origin=(10,0,0))) +""" + ftc, trace = write_case(tmp_path, "placed", source) + row = validate_row(ftc, trace, timeout=30) + assert row["quality"] == "rejected", row + assert "does not match" in row["error"] diff --git a/test/test_deformation_features.py b/test/test_deformation_features.py index 8bb10622..88088d40 100644 --- a/test/test_deformation_features.py +++ b/test/test_deformation_features.py @@ -62,3 +62,36 @@ def test_affine_singular_matrix_rejected(): original = scad.make_box_rsolid(width=10, height=12, depth=14) with pytest.raises(ValueError): scad.transform_rsolid(solid=original, matrix=[[0]*4 for _ in range(4)]) + + +def test_set_boolean_keeps_all_output_slots_and_part_replay(): + with scad.GraphSession(graph_id="cut-pieces") as session: + base = scad.make_box_rsolid(10, 2, 2) + tool = scad.make_box_rsolid(2, 4, 4, bottom_face_center=(0, 0, -1)) + pieces = scad.boolean_rsolidlist(left=[base], right=[tool], operation="cut") + assert len(pieces) == 2 + final = scad.make_part_rpart(part_id="second", body=pieces[1]) + session.capture_result(value=final) + replayed = scad.replay_model_json(scad.export_model_json(session=session), strict=True)[0] + from simplecadapi.kernel.ocp_properties import center_of_mass + assert tuple(center_of_mass(replayed.body.wrapped)) == pytest.approx(tuple(center_of_mass(pieces[1].wrapped))) + assert replayed.body.get_volume() == pytest.approx(16) + + +@pytest.mark.parametrize("operation", ["cut", "intersect", "union"]) +def test_set_boolean_compound_members_and_graph_replay(operation): + with scad.GraphSession(graph_id="set-boolean") as session: + left = [scad.make_box_rsolid(2, 2, 2, bottom_face_center=(x, 0, 0)) for x in (-4, 4)] + right = [scad.make_box_rsolid(1, 4, 4, bottom_face_center=(x, 0, -1)) for x in (-4, 4)] + result = scad.boolean_rsolidlist(left=left, right=right, operation=operation) + session.capture_result(value=result) + expected = {"cut": 8, "intersect": 8, "union": 40}[operation] + assert sum(body.get_volume() for body in result) == pytest.approx(expected) + replayed = scad.replay_model_json(scad.export_model_json(session=session), strict=True) + assert len(replayed) == len(result) + assert sum(body.get_volume() for body in replayed) == pytest.approx(expected) + + +def test_set_boolean_complete_removal_returns_no_solid(): + base = scad.make_box_rsolid(2, 2, 2) + assert scad.boolean_rsolidlist(left=[base], right=[base], operation="cut") == [] diff --git a/test/test_limited_extrusion.py b/test/test_limited_extrusion.py index c5e648a3..4b1047cd 100644 --- a/test/test_limited_extrusion.py +++ b/test/test_limited_extrusion.py @@ -71,7 +71,10 @@ def test_operation_retains_profile_and_target_as_replay_inputs(): session.capture_result(value=output) node = next(n for n in session.graph.nodes if n.op == "make_extrude_until_rsolid") assert len(node.inputs) == 2 - assert node.params == {"direction": (0, 0, 1), "until": "NEXT", "target_count": 1} + assert {key: value for key, value in node.params.items() if key != "input_refs"} == { + "direction": (0, 0, 1), "until": "NEXT", "target_count": 1} + assert [ref["node_id"] for ref in node.params["input_refs"]] == [n.node_id for n in node.inputs] + assert [ref["output_slot"] for ref in node.params["input_refs"]] == [0, 0] replayed = s.replay_model_json(s.export_model_json(session))[0] assert replayed.get_volume() == pytest.approx(output.get_volume(), rel=1e-9) assert replayed.get_volume() == pytest.approx(20) diff --git a/test/test_ql.py b/test/test_ql.py index 56328ce6..2d6c9955 100644 --- a/test/test_ql.py +++ b/test/test_ql.py @@ -6,6 +6,14 @@ from simplecadapi.topology import tagging class TestQLTagPredicates(unittest.TestCase): + def test_solid_world_bounds_distinguish_equal_volume_components(self): + first = scad.make_box_rsolid(2, 2, 2, bottom_face_center=(3, 0, 4)) + second = scad.make_box_rsolid(2, 2, 2, bottom_face_center=(8, 0, 4)) + selector = Q.solids().where(Q.and_( + Q.prop("geom.bbox.min.x", "==", 7), + Q.prop("geom.bbox.max.z", "==", 6))).exactly(1) + self.assertEqual(selector.resolve([first, second]), [second]) + def test_tag_exact_and_wildcard(self): box = scad.make_box_rsolid(1.0, 1.0, 1.0) scad.apply_tag(box, "role.mounting_surface") diff --git a/test/test_section_features.py b/test/test_section_features.py index 04cb22f2..1ce5caa3 100644 --- a/test/test_section_features.py +++ b/test/test_section_features.py @@ -64,3 +64,42 @@ def test_taper_with_hole_tapers_inner_loop_oppositely(): slope = math.tan(math.radians(5)) expected = math.pi * ((100 - 4) * 3 - (10 + 2) * slope * 9) assert body.get_volume() == pytest.approx(expected, rel=1e-6) + + +def test_taper_ql_face_is_recorded_as_feature_input(): + with s.GraphSession(graph_id="selected-taper") as session: + base = s.make_box_rsolid(10, 6, 2) + profile = s.ql.faces().where(s.ql.prop("geom.normal.z", ">", .9)).exactly(1).resolve(base)[0] + result = s.extrude_taper_rsolid(profile=profile, vector=(0, 0, 4), taper=10) + session.capture_result(value=result) + replayed = s.replay_model_json(s.export_model_json(session=session), strict=True)[0] + assert replayed.get_volume() == pytest.approx(result.get_volume(), rel=1e-8) + from simplecadapi.kernel.ocp_properties import center_of_mass + assert tuple(center_of_mass(replayed.wrapped)) == pytest.approx(tuple(center_of_mass(result.wrapped))) + + +def test_multisection_uses_ordered_slots_from_one_boundary_node(): + with s.GraphSession(graph_id="boundary-sweep") as session: + first = s.make_circle_rwire(center=(0, 0, 0), radius=2) + last = s.make_circle_rwire(center=(0, 0, 6), radius=3) + shell = s.loft_rshell(sections=[first, last]) + boundaries = s.free_boundaries_rwirelist(shell) + assert len(boundaries) == 2 + path = s.make_segment_rwire(start=(0, 0, 0), end=(0, 0, 6)) + body = s.sweep_multisection_rsolid(profiles=list(reversed(boundaries)), path=path) + session.capture_result(value=body) + replayed = s.replay_model_json(s.export_model_json(session=session), strict=True)[0] + assert replayed.get_volume() == pytest.approx(body.get_volume(), rel=1e-7) + + +def test_taper_ql_face_from_second_boolean_output_replays_in_place(): + with s.GraphSession(graph_id="second-profile") as session: + base = s.make_box_rsolid(10, 2, 2) + tool = s.make_box_rsolid(2, 4, 4, bottom_face_center=(0, 0, -1)) + pieces = s.boolean_rsolidlist(left=[base], right=[tool], operation="cut") + profile = s.ql.faces().where(s.ql.prop("geom.normal.z", ">", .9)).exactly(1).resolve(pieces[1])[0] + body = s.extrude_taper_rsolid(profile=profile, vector=(0, 0, 1), taper=5) + session.capture_result(value=body) + replayed = s.replay_model_json(s.export_model_json(session=session), strict=True)[0] + from simplecadapi.kernel.ocp_properties import center_of_mass + assert tuple(center_of_mass(replayed.wrapped)) == pytest.approx(tuple(center_of_mass(body.wrapped))) diff --git a/test/test_serialization.py b/test/test_serialization.py index 880d4269..ccb5be6a 100644 --- a/test/test_serialization.py +++ b/test/test_serialization.py @@ -357,6 +357,14 @@ class TestCoverageMatrix(unittest.TestCase): "make_twisted_sweep_rsolid", "make_translate_rshape", "make_rotate_rshape", + "make_scale_rsolid", + "make_transform_rsolid", + "make_offset_rsolid", + "make_extrude_taper_rsolid", + "make_sweep_multisection_rsolid", + "make_extrude_until_rsolid", + "make_draft_rsolid", + "make_boolean_rsolidlist", "make_mirror_rshape", "make_cut_rsolid", "make_union_rsolid", diff --git a/tools/research/build123dftc/BENCHMARK.md b/tools/research/build123dftc/BENCHMARK.md index 77d6b3cc..c6a2be32 100644 --- a/tools/research/build123dftc/BENCHMARK.md +++ b/tools/research/build123dftc/BENCHMARK.md @@ -33,3 +33,27 @@ API、孤立进程崩溃、超时、同体积/同包围盒但孔位不同的反 标为 `verified_sampled_usage` 的条目仅说明相应已验收样例使用过该 API, 不代表其全部参数组合或全部公开 API 都已通过转换。复杂曲面构造等未接入 边界在 [API_RESEARCH.md](API_RESEARCH.md) 和转换 meta 中明确列出。 + +## 2026-10-13 审查修复与新增 41 个模型 + +修复 1 项 P1 和 9 项 P2,涵盖空输出识别、实际 build 返回值验收、多实体 +布尔及圆角、Face 截面孔、空侧分割、QL 输入录制和多输出槽重放。 +圆环的主圆周角度被保留,非完整管截面明确标为未转换。 + +| 检查 | 原有 50 个 | 新增 41 个 | +| --- | --- | --- | +| 源模型捕获 | 50 / 50 | 40 / 41 | +| 完整 FTC 生成 | 50 / 50 | 31 / 41 | +| 基础几何验收 | 50 / 50 | 21 / 41 | +| 参考 STEP 严格对账 | 49 / 50 | 21 / 41 | + +原有 50 个仅剩模型 46 的既有参考内核错误。新增模型 80 在 180 秒捕获 +上限内未完成;其他未通过项包括未录制的曲面/实体构造、草图与扫掠构建 +失败、选择失败、实际返回模型与 BODIES 不一致、几何差异及参考内核错误。 +未放宽验收阈值,未跳过失败模型。 + +最终相关回归 247 项通过,另有 137 个子测试。全仓库运行中的 3 项剩余失败 +在未修改的 HEAD 副本中复现,分别涉及圆角诊断、FreeCAD 关节计数和 Gordon +曲面体积断言。逐模型结果、生成代码和失败说明保存在相邻工作区 +`artifacts/build123dftc/REVIEW_RESULTS.md`;两批原始 JSON 分别在 +`review_fixed/validate.json` 和 `additional_review_fixed/validate.json`。 diff --git a/tools/research/build123dftc/README.md b/tools/research/build123dftc/README.md index 3ff8acf4..51ffb8c5 100644 --- a/tools/research/build123dftc/README.md +++ b/tools/research/build123dftc/README.md @@ -12,7 +12,8 @@ trace.json → build123d_profile.py → profile.json ``` 捕获执行模型的 Python;只对可信源文件运行。模型的 `__main__` 分支不会运行, -可在顶层将最终形状绑定为 `result`。捕获和验收分别在隔离子进程执行,设置 +可在顶层将最终形状绑定为 `result`。显式输出即使为空也具有优先级,不会回退 +到先前创建的实体。捕获和验收分别在隔离子进程执行,设置 超时,一例失败仍处理后续文件。 ## 环境 @@ -80,7 +81,9 @@ uv pip install --python ../.venv-sca/bin/python -e . 'cadquery-ocp==7.9.3.1' pyt ## 验收依据 -- 实际执行 FTC,检查非空实体、内核有效性、体积、表面积和实体数量。 +- 实际执行 FTC,以 `build()` 返回的 Solid、Part 或 Assembly 为验收对象, + 应用嵌套装配位置后检查非空实体、内核有效性、体积、表面积和实体数量。 + `BODIES` 必须非空,并与实际返回模型的实体数量和几何一致。 - 比较世界坐标中的六个包围盒边界;同尺寸但位置错误会失败。 - 指定参考 STEP 时,要求两个方向几何差集的总体积通过检查。 - `--reference-python` 让参考几何对账在指定内核执行,FTC 仍在 @@ -116,6 +119,16 @@ uv pip install --python ../.venv-sca/bin/python -e . 'cadquery-ocp==7.9.3.1' pyt 草图支持直线、圆弧、圆、椭圆、精确有理 B 样条与闭合/周期样条;曲线型 文字及三维路径使用实际曲线控制数据。多实体输出为完整 `@scad.assemble`。 +切割与交集使用录制的 `scad.boolean_rsolidlist` 保留全部输出实体;Compound +成员属于同一交集操作数,多参数交集仍按顺序取交。每块实体的圆角/倒角使用 +各自的选边基数,未选中的实体直接保留。多输出顺序通过实体几何指纹恢复; +截面特征保存有序输入引用及输出槽,QL 得到的截面也进入录制图。 +实体排序使用世界包围盒和体积,避免不同 OCCT 版本质心计算的差异。 +圆环支持 `major_angle` 主圆周角度;非完整管截面的 `start_angle/end_angle` +目前明确记录为未转换,不会生成完整圆环代替。 +更新工具后应重新捕获旧模型;缺少逐实体选边信息的旧多实体圆角图会被标为 +未转换,历史空结果图也需要重捕获才能纠正。 + 生成代码使用现行 FTC 块头、几何档标注、keyword 实参、QL 谓词和基数。 数字来源于实际调用,不虚构参数名。动态追踪只描述执行到的路径;输出不会 保留未执行的分支,也不承诺恢复源草图的约束或全部表达式。 @@ -145,3 +158,7 @@ fixture,并带出处。普通 FTC 测试不依赖 build123d;执行捕获测 test/test_section_features.py test/test_limited_extrusion.py \ test/test_rational_volume_precision.py test/test_sketch_closed_bspline.py -q ``` + +`test/test_build123d_review_regressions.py` 额外从专用 build123d 环境捕获审查 +反例,再在 SimpleCADAPI 环境执行生成代码并验收实际返回模型;运行该文件 +需要相邻的 `../.venv`。 diff --git a/tools/research/build123dftc/b3ftc/_validate_worker.py b/tools/research/build123dftc/b3ftc/_validate_worker.py index 506f2ce2..fd6371f6 100644 --- a/tools/research/build123dftc/b3ftc/_validate_worker.py +++ b/tools/research/build123dftc/b3ftc/_validate_worker.py @@ -86,10 +86,13 @@ def _read_step(step): def _compare_reference(shapes, step): + return _compare_shapes(shapes, _read_step(step)) + + +def _compare_shapes(shapes, reference): from OCP.BRepAlgoAPI import BRepAlgoAPI_Cut, BRepAlgoAPI_Fuse from OCP.BRepCheck import BRepCheck_Analyzer - reference = _read_step(step) - # Treat BODIES as a geometric set. Fuse disjoint bodies too, avoiding double + # Treat body groups as a geometric set. Fuse disjoint bodies too, avoiding double # counting overlap when comparing a multi-body result to STEP assemblies. actual = shapes[0] for shape in shapes[1:]: @@ -179,6 +182,30 @@ def _export_step(shapes, path, options=None): "rebuild_pcurves_on_import": not pcurves} +def _returned_shapes(value, placement=None): + """Extract world-space topology from the actual build result.""" + from simplecadapi import Solid, Part, Assembly, PartBuildResult, AssemblyBuildResult + from simplecadapi.product.placement import identity_placement + from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform + from OCP.gp import gp_Trsf + if isinstance(value, (PartBuildResult, AssemblyBuildResult)): + value = value.value + if isinstance(value, Part): + value = value.body + if isinstance(value, Assembly): + parent = placement or identity_placement() + return [shape for component in value.components + for shape in _returned_shapes(component.item, parent.compose(component.placement))] + if isinstance(value, Solid): + if placement is None or placement == identity_placement(): + return [value.wrapped] + x, y, z, o = placement.x_axis, placement.y_axis, placement.z_axis, placement.origin + transform = gp_Trsf() + transform.SetValues(x[0], y[0], z[0], o[0], x[1], y[1], z[1], o[1], x[2], y[2], z[2], o[2]) + return [BRepBuilderAPI_Transform(value.wrapped, transform, True).Shape()] + raise ValueError("build() must return an actual Solid, Part or Assembly build result") + + def run(ftc_path, staging_dir, reference_step=None, export_step=None, export_options=None): import OCP from OCP.Bnd import Bnd_Box @@ -197,19 +224,28 @@ def run(ftc_path, staging_dir, reference_step=None, export_step=None, export_opt build = getattr(module, "build", None) if not callable(build): raise ValueError("FTC module must define callable build()") - build() + built = build() bodies = getattr(module, "BODIES", None) if not isinstance(bodies, (list, tuple)) or not bodies: return {"status": "ok", "body_count": 0, "solid_count": 0, "is_valid": False, "volume": None, "bbox": None} - shapes = [] for index, body in enumerate(bodies): wrapped = getattr(body, "wrapped", None) if not isinstance(wrapped, TopoDS_Shape) or wrapped.IsNull(): raise ValueError(f"BODIES[{index}] is not actual nonempty CAD topology") if _solid_count(wrapped) < 1: raise ValueError(f"BODIES[{index}] contains no solid") - shapes.append(wrapped) + shapes = _returned_shapes(built) + if not shapes or len(shapes) != len(bodies): + raise ValueError("build() result body count does not match BODIES") + if any(shape.IsNull() or not _solid_count(shape) for shape in shapes): + raise ValueError("build() returned empty CAD topology") + if not all(body.wrapped.IsSame(shape) for body, shape in zip(bodies, shapes)): + from simplecadapi.kernel.ocp_export import make_compound_always + consistency = _compare_shapes(shapes, make_compound_always([body.wrapped for body in bodies])) + if (consistency["reference_status"] != "ok" or + consistency["symmetric_difference_volume"] > max(1e-7, abs(consistency["reference_volume"]) * 1e-7)): + raise ValueError("BODIES geometry does not match the actual build() result") bounds = Bnd_Box() for shape in shapes: BRepBndLib.AddOptimal_s(shape, bounds, False, False) diff --git a/tools/research/build123dftc/b3ftc/emit.py b/tools/research/build123dftc/b3ftc/emit.py index 0a7a1de7..c1abdddb 100644 --- a/tools/research/build123dftc/b3ftc/emit.py +++ b/tools/research/build123dftc/b3ftc/emit.py @@ -67,7 +67,16 @@ def fingerprint_selector(fingerprints: Sequence[Mapping[str, Any]], kind: str, t geom_type = fp.get('geom_type') or fp.get('type') if geom_type: terms.append(f"ql.prop('geom.type', '==', {str(geom_type).upper()!r})") + if kind == 'solid' and fp.get('bbox') is not None: + for index, value in enumerate(fp['bbox']): + side, axis = ('min' if index < 3 else 'max'), 'xyz'[index % 3] + terms.extend([ + f"ql.prop('geom.bbox.{side}.{axis}', '>=', {fmt_num(float(value) - tolerance)})", + f"ql.prop('geom.bbox.{side}.{axis}', '<=', {fmt_num(float(value) + tolerance)})", + ]) for name in ('center', 'normal'): + if kind == 'solid': + continue values = fp.get(name) if values is not None: for axis, value in zip('xyz', values): @@ -77,7 +86,9 @@ def fingerprint_selector(fingerprints: Sequence[Mapping[str, Any]], kind: str, t f"ql.prop('geom.{name}.{axis}', '>=', {fmt_num(value - tolerance_here)})", f"ql.prop('geom.{name}.{axis}', '<=', {fmt_num(value + tolerance_here)})", ]) - for name in ('length', 'area', 'radius'): + for name in ('length', 'area', 'radius', 'volume'): + if kind == 'solid' and name != 'volume': + continue if (kind == 'edge' and name == 'area') or (kind == 'face' and name == 'length'): continue if fp.get(name) is not None: @@ -97,7 +108,8 @@ def fingerprint_selector(fingerprints: Sequence[Mapping[str, Any]], kind: str, t raise ValueError(f'{kind} selection is empty') combined = predicates[0] if len(predicates) == 1 else 'ql.or_(' + ', '.join(predicates) + ')' count = len([fp for fp in fingerprints if fp.get('kind', kind) == kind]) - return f'ql.{kind}s().where({combined}).take({count}).exactly({count})' + limit = '' if kind == 'solid' else f'.take({count})' + return f'ql.{kind}s().where({combined}){limit}.exactly({count})' def emit_module(stem: str, lines: Sequence[str], refs: Sequence[str], unsupported: Sequence[str], uses_ql: bool, solid_count: int = 1) -> str: diff --git a/tools/research/build123dftc/b3ftc/profiles.py b/tools/research/build123dftc/b3ftc/profiles.py index 5f7bd469..2fe77107 100644 --- a/tools/research/build123dftc/b3ftc/profiles.py +++ b/tools/research/build123dftc/b3ftc/profiles.py @@ -149,6 +149,40 @@ class Sketch: raise ValueError(f'unsupported exact curve kind: {kind}') +def _polygon_loops(profile, wires, name, snapshots): + """Compact native sketch construction for a large set of closed polygons.""" + sketches = [Sketch(f'{name}_loop{i}_sketch', profile) for i in range(len(wires))] + points = [] + for sketch, wire in zip(sketches, wires): + edges = wire['edges'] + if any(edge['kind'] != 'line' or math.dist(edge['end'], following['start']) > 1e-7 + for edge, following in zip(edges, edges[1:] + edges[:1])): + return None + points.append([sketch.local(edge['start']) for edge in edges]) + if snapshots is not None: + for sketch, wire in zip(sketches, wires): + edges = wire['edges'] + for edge in edges: + sketch.entity(edge) + snapshots.append({'name': sketch.name, 'entities': sketch.snapshot_entities, + 'closed': True, 'compact': True, + 'plane': {'origin': list(sketch.origin), 'x_axis': list(sketch.u), 'y_axis': list(sketch.v)}}) + origin, u, v, normal = frame(profile) + plane_expr = "{'origin': " + fmt_vec(origin) + ", 'x_axis': " + fmt_vec(u) + ", 'y_axis': " + fmt_vec(v) + "}" + data, refs = name + '_polygon_points', name + '_loop_wires' + lines = [f' {data} = [', *[f' {fmt_literal(loop)},' for loop in points], ' ]', + f' {refs} = []', f' for _loop_index, _points in enumerate({data}):', + f' _loop_sketch = scad.make_sketch_rsketch(name={name!r} + f"_loop{{_loop_index}}_sketch", plane={plane_expr})', + ' for _point_index, (_x, _y) in enumerate(_points):', + ' _loop_sketch = scad.add_point_rsketch(sketch=_loop_sketch, point_id=f"p{_point_index + 1}", x=_x, y=_y)', + ' for _edge_index in range(len(_points)):', + ' _loop_sketch = scad.add_line_rsketch(sketch=_loop_sketch, entity_id=f"e{_edge_index + 1}", start=f"p{_edge_index + 1}", end=f"p{(_edge_index + 1) % len(_points) + 1}")', + f' {refs}.append(scad.make_wire_from_sketch_rwire(sketch=_loop_sketch, profile=0))'] + output = name + '_face' + lines.append(f' {output} = scad.make_face_from_wires_rface(outer_wire={refs}[0], inner_wires={refs}[1:], normal={fmt_vec(normal)})') + return lines, output + + def emit_profile(profile: Mapping[str, Any], name: str, *, as_wire: bool = False, snapshots=None): """Return source lines + face/wire expression; outer-first wire ordering.""" wires = profile.get('wires') or [{'edges': profile.get('edges', [])}] @@ -156,6 +190,23 @@ def emit_profile(profile: Mapping[str, Any], name: str, *, as_wire: bool = False raise ValueError('empty profile') if as_wire and len(wires) > 1: raise ValueError('a wire section cannot represent multiple disconnected loops') + if not as_wire and len(wires) > 1 and sum(len(wire.get('edges', [])) for wire in wires) > 256: + # A many-hole face can exceed libslvs' per-system unknown limit even + # without constraints. Promote each supplied loop in its own small + # sketch, then construct the same face from all its exact wires. + if all(wire.get('edges') and all(edge['kind'] == 'line' for edge in wire['edges']) for wire in wires): + compact = _polygon_loops(profile, wires, name, snapshots) + if compact is not None: + return compact + lines, refs = [], [] + for index, wire in enumerate(wires): + loop_lines, ref = emit_profile({**profile, 'wires': [wire]}, f'{name}_loop{index}', + as_wire=True, snapshots=snapshots) + lines.extend(loop_lines) + refs.append(ref) + output = name + '_face' + lines.append(f' {output} = scad.make_face_from_wires_rface(outer_wire={refs[0]}, inner_wires=[{", ".join(refs[1:])}], normal={fmt_vec(frame(profile)[3])})') + return lines, output sketch = Sketch(name + '_sketch', profile) profile_ids = [] for wire in wires: diff --git a/tools/research/build123dftc/b3ftc/replay.py b/tools/research/build123dftc/b3ftc/replay.py index 5b003bfd..3c903688 100644 --- a/tools/research/build123dftc/b3ftc/replay.py +++ b/tools/research/build123dftc/b3ftc/replay.py @@ -118,9 +118,9 @@ class TraceReplayer: ident = step.get('id', f's{self.feature_count + 1}') var = _variable(ident) inputs = self.source(step) - create = op in {'box', 'cylinder', 'cone', 'sphere', 'torus', 'extrude', 'revolve', 'loft', 'sweep', 'extrude_linear', 'extrude_linear_with_rotation', 'extrude_taper', 'extrude_twist', 'extrude_until', 'sweep_multi'} + create = op in {'box', 'cylinder', 'cone', 'sphere', 'torus', 'extrude', 'revolve', 'loft', 'sweep', 'sew_solid', 'extrude_linear', 'extrude_linear_with_rotation', 'extrude_taper', 'extrude_twist', 'extrude_until', 'sweep_multi'} role = 'build' if create else {'union': 'add', 'fuse': 'add', 'cut': 'subtract', 'intersect': 'intersect', 'compound': 'pattern'}.get(op, 'modify') - tiers = ['profile=geometry'] if op in {'extrude', 'revolve', 'loft', 'sweep', 'extrude_linear', 'extrude_linear_with_rotation', 'torus', 'extrude_taper', 'extrude_twist', 'extrude_until', 'sweep_multi'} else [] + tiers = ['profile=geometry'] if op in {'extrude', 'revolve', 'loft', 'sweep', 'sew_solid', 'extrude_linear', 'extrude_linear_with_rotation', 'torus', 'extrude_taper', 'extrude_twist', 'extrude_until', 'sweep_multi'} else [] if op in {'sweep', 'sweep_multi'}: tiers.append('path=geometry') self.lines.append(block_header(self.slugs.allocate(op), role, tiers)) @@ -152,7 +152,10 @@ class TraceReplayer: else: direction = _named(p, 'normal', 'direction', 'vector', default=(0, 0, 1)) distance = math.sqrt(dot(direction, direction)) - expression = f'scad.twisted_sweep_rsolid(profile=_profile, distance={fmt_num(distance)}, twist_angle={fmt_num(_named(p, "angle", "twist_angle", default=0))}, axis={fmt_vec(direction)}, origin={fmt_vec(_named(p, "center", "origin", default=(0, 0, 0)))}, guide_radius=1)' + origin = list(_named(p, 'center', 'origin', default=(0, 0, 0))) + if len(origin) == 2: + origin.append(0) + expression = f'scad.twisted_sweep_rsolid(profile=_profile, distance={fmt_num(distance)}, twist_angle={fmt_num(_named(p, "angle", "twist_angle", default=0))}, axis={fmt_vec(direction)}, origin={fmt_vec(origin)}, guide_radius=1)' self.lines.append(f' {var} = [{expression} for _profile in [{", ".join(refs)}]]') elif op == 'revolve': profiles = _profiles(step) @@ -168,6 +171,15 @@ class TraceReplayer: if len(refs) < 2: raise ValueError('loft needs at least two recorded sections') self.lines.append(f' {var} = [scad.loft_rsolid(profiles=[{", ".join(refs)}], ruled={bool(p.get("ruled", False))!r})]') + elif op == 'sew_solid': + if step.get('geometry_error'): + raise ValueError(step['geometry_error']) + profiles = step.get('profiles') or [] + if not profiles: + raise ValueError('solid shell requires recorded planar faces') + refs = [self.profile(profile, f'{var}_face{i}') for i, profile in enumerate(profiles)] + self.lines.append(f' {var}_shell = scad.sew_faces_rshell(faces=[{", ".join(refs)}])') + self.lines.append(f' {var} = [scad.make_solid_from_shell_rsolid(shell={var}_shell)]') elif op in {'sweep', 'sweep_multi'}: profiles = _profiles(step) path = step.get('path') @@ -175,7 +187,9 @@ class TraceReplayer: raise ValueError('sweep path missing') path_lines, path_expr = emit_path(path, var + '_path', snapshots=self.snapshots) self.lines.extend(path_lines) - refs = [self.profile(profile, f'{var}_profile{i}') for i, profile in enumerate(profiles)] + refs = ([self.profile(profile, f'{var}_profile{i}') for i, profile in enumerate(profiles)] + if op == 'sweep_multi' or not any(len(profile.get('wires', [])) > 1 for profile in profiles) + else []) frenet = bool(_named(p, 'is_frenet', 'frenet', default=False)) if op == 'sweep_multi': binormal = p.get('binormal') @@ -185,11 +199,28 @@ class TraceReplayer: else: if p.get('mode') is not None or str(p.get('transition', 'TRANSFORMED')) != 'TRANSFORMED': raise ValueError('sweep mode/transition needs a native advanced sweep operator') - self.lines.append(f' {var} = [scad.sweep_rsolid(profile=_profile, path={path_expr}, is_frenet={frenet!r}) for _profile in [{", ".join(refs)}]]') + if any(len(profile.get('wires', [])) > 1 for profile in profiles): + pieces = [] + for index, profile in enumerate(profiles): + loops = [self.profile({**profile, 'wires': [wire]}, f'{var}_loop{index}_{i}') + for i, wire in enumerate(profile['wires'])] + outer = var + f'_outer{index}' + self.lines.append(f' {outer} = [scad.sweep_rsolid(profile={loops[0]}, path={path_expr}, is_frenet={frenet!r})]') + tools = ', '.join(f'scad.sweep_rsolid(profile={loop}, path={path_expr}, is_frenet={frenet!r})' for loop in loops[1:]) + pieces.append(f'scad.boolean_rsolidlist(left={outer}, right=[{tools}], operation="cut")') + self.lines.append(f' {var} = [_b for _group in [{", ".join(pieces)}] for _b in _group]') + else: + self.lines.append(f' {var} = [scad.sweep_rsolid(profile=_profile, path={path_expr}, is_frenet={frenet!r}) for _profile in [{", ".join(refs)}]]') elif op == 'component': if len(inputs) != 1: raise ValueError('component requires one parent feature') - self.lines.append(f' {var} = [{inputs[0]}[{int(p["index"])}]]') + fingerprint = p.get('fingerprint', {}) + if fingerprint.get('bbox') is not None: + self.uses_ql = True + selector = fingerprint_selector([fingerprint], 'solid') + self.lines.append(f' {var} = {selector}.resolve({inputs[0]})') + else: + self.lines.append(f' {var} = [{inputs[0]}[{int(p["index"])}]]') elif op in {'compound', 'copy', 'clean'}: self.lines.append(f' {var} = [ _b for _group in [{", ".join(inputs)}] for _b in _group ]') elif op in {'union', 'fuse', 'cut', 'intersect'}: @@ -199,21 +230,23 @@ class TraceReplayer: self.lines.append(f' {var} = list({inputs[0]})') elif op == 'cut': tools = f'[_b for _group in [{", ".join(inputs[1:])}] for _b in _group]' - self.lines.append(f' {var} = [scad.cut_rsolid(_b, {tools}) for _b in {inputs[0]}]') + self.lines.append(f' {var} = scad.boolean_rsolidlist(left={inputs[0]}, right={tools}, operation="cut")') elif op == 'intersect': - self.lines.append(f' {var} = [scad.intersect_rsolid([{", ".join(inputs)}])]') + self.lines.append(f' {var} = list({inputs[0]})') + for group in inputs[1:]: + self.lines.append(f' {var} = scad.boolean_rsolidlist(left={var}, right={group}, operation="intersect")') else: groups = step.get('result_groups') if groups: values = [] for group in groups: group_refs = [self.variables[x] for x in group] - values.append(f'scad.union_rsolid([{", ".join(group_refs)}])' if len(group_refs) > 1 else f'{group_refs[0]}[0]') + values.append(f'scad.union_rsolid([{", ".join(group_refs)}], tracking_policy="graph")' if len(group_refs) > 1 else f'{group_refs[0]}[0]') self.lines.append(f' {var} = [{", ".join(values)}]') elif step.get('result', {}).get('solid_count', 1) > 1: raise ValueError('disconnected union requires recorded connected operand groups') else: - self.lines.append(f' {var} = [scad.union_rsolid([{", ".join(inputs)}])]') + self.lines.append(f' {var} = [scad.union_rsolid([{", ".join(inputs)}], tracking_policy="graph")]') elif op in {'fillet', 'chamfer'}: selector = fingerprint_selector(step.get('selection', []), 'edge') self.uses_ql = True @@ -232,7 +265,20 @@ class TraceReplayer: raise ValueError('per-edge chamfer reference normals vary; the native operator requires one reference direction') raise ValueError('asymmetric chamfer requires reference-face normal') extras += ', reference_direction=' + fmt_vec(direction) - self.lines.append(f' {var} = [scad.{op}_rsolid(solid=_b, edges={selector}, {extras}) for _b in {inputs[0]}]') + groups = step.get('component_selections') + if groups is not None: + self.lines.append(f' {var} = []') + for index, selection in enumerate(groups): + body = f'{inputs[0]}[{index}]' + if selection: + local = fingerprint_selector(selection, 'edge') + self.lines.append(f' {var}.append(scad.{op}_rsolid(solid={body}, edges={local}, {extras}))') + else: + self.lines.append(f' {var}.append({body})') + elif self.steps[step['inputs'][0]].get('result', {}).get('solid_count', 1) > 1: + raise ValueError('multi-body blend requires per-component selections') + else: + self.lines.append(f' {var} = [scad.{op}_rsolid(solid=_b, edges={selector}, {extras}) for _b in {inputs[0]}]') elif op == 'draft': if len(inputs) != 1: raise ValueError('draft requires one parent feature') @@ -259,6 +305,13 @@ class TraceReplayer: self.transform(op, p, inputs, var) else: raise ValueError(f'unsupported op: {op}') + components = step.get('result_components', []) + if components and all(fp.get('bbox') is not None for fp in components): + # Kernel output order is not stable across environments. Restore the + # traced component order before indexed selections and modifications. + self.uses_ql = True + selectors = [fingerprint_selector([fp], 'solid') for fp in components] + self.lines.append(f' {var} = [{", ".join(f"{selector}.resolve({var})[0]" for selector in selectors)}]') self.lines.append('') self.variables[ident] = var self.steps[ident] = step @@ -324,7 +377,9 @@ class TraceReplayer: return self.lines.append(f' {var} = [scad.make_sphere_rsolid(radius={fmt_num(p["radius"])}, center={fmt_vec(origin)})]') else: - if abs(float(p.get('angle1', 0))) > 1e-9 or abs(float(p.get('angle2', 360)) - 360) > 1e-9: + start = _named(p, 'start_angle', 'angle1', default=0) + end = _named(p, 'end_angle', 'angle2', default=360) + if abs(float(start)) > 1e-9 or abs(float(end) - 360) > 1e-9: raise ValueError('partial torus tube needs a traced meridian closure profile') major, minor = _named(p, 'major_radius', 'radius1'), _named(p, 'minor_radius', 'radius2') axis = unit(axis) @@ -333,7 +388,7 @@ class TraceReplayer: profile = {'origin': profile_origin, 'u': x_dir, 'v': axis, 'normal': cross(x_dir, axis), 'wires': [{'edges': [{'kind': 'circle', 'center': profile_origin, 'radius': minor}]}]} face = self.profile(profile, var + '_meridian') - self.lines.append(f' {var} = [scad.revolve_rsolid(profile={face}, axis={fmt_vec(axis)}, angle={fmt_num(_named(p, "angle3", "angle", default=360))}, origin={fmt_vec(origin)})]') + self.lines.append(f' {var} = [scad.revolve_rsolid(profile={face}, axis={fmt_vec(axis)}, angle={fmt_num(_named(p, "major_angle", "angle3", "angle", default=360))}, origin={fmt_vec(origin)})]') def transform(self, op, p, inputs, var): if len(inputs) != 1: @@ -408,10 +463,10 @@ class TraceReplayer: tool = var + '_' + label self.lines.extend([f' with scad.SimpleWorkplane(origin={fmt_vec(tool_origin)}, normal={fmt_vec([sign * x for x in normal])}, x_dir={fmt_vec(u)}):', f' {tool} = scad.make_box_rsolid(width={fmt_num(width)}, height={fmt_num(height)}, depth={fmt_num(depth)}, bottom_face_center=(0, 0, 0))']) - refs.append(f'scad.intersect_rsolid(_b, [{tool}])') + refs.append(f'scad.boolean_rsolidlist(left={inputs[0]}, right=[{tool}], operation="intersect")') if not refs: raise ValueError(f'unknown split keep mode: {keep}') - self.lines.append(f' {var} = [_piece for _b in {inputs[0]} for _piece in [{", ".join(refs)}]]') + self.lines.append(f' {var} = [_piece for _group in [{", ".join(refs)}] for _piece in _group]') def replay(self): for step in self.trace.get('steps', []): @@ -464,6 +519,10 @@ class TraceReplayer: sys.path.insert(0, sibling) from cqftc.constraints import emit_constraint_lines, recover_constraints_guarded for snapshot in self.snapshots: + if snapshot.get('compact'): + self.constraint_reports.append({'name': snapshot['name'], 'status': 'unsupported', + 'reason': 'constraint emission is unavailable for compact multi-loop sketches', 'constraints': []}) + continue if any(entity['kind'] not in {'point', 'line', 'circle', 'arc'} for entity in snapshot['entities']): self.constraint_reports.append({'name': snapshot['name'], 'status': 'unsupported', 'reason': 'constraint recovery does not handle ellipse/B-spline entities', 'constraints': []}) diff --git a/tools/research/build123dftc/b3ftc/tracer.py b/tools/research/build123dftc/b3ftc/tracer.py index 607f3194..fc3a43c5 100644 --- a/tools/research/build123dftc/b3ftc/tracer.py +++ b/tools/research/build123dftc/b3ftc/tracer.py @@ -194,10 +194,22 @@ class Recorder: extra["path"] = geometry.path(value) elif field in {"edge_list", "faces", "openings"}: extra["selection"] = [geometry.fingerprint(v, receiver) for v in value or []] + if receiver is not None and len(receiver.solids()) > 1: + kind = "edge" if field == "edge_list" else "face" + extra["component_selections"] = [ + [geometry.fingerprint(v, solid) for v in value or [] + if any(child.wrapped.IsSame(v.wrapped) for child in + (solid.edges() if kind == "edge" else solid.faces()))] + for solid in receiver.solids()] elif field in {"to_fuse", "to_cut", "to_intersect", "target"}: inputs.extend(self.reference(value)) elif field == "inner_wires": - extra["inner_wires"] = [geometry.wire(v) for v in value or []] + # build123d uses explicit holes only for Wire sections. + # A Face already owns the loops actually consumed by the feature. + import build123d as b + section = params.get("section") + extra["inner_wires"] = ([] if isinstance(section, b.Face) else + [geometry.wire(v) for v in value or []]) else: encoded[field] = geometry.serialize(value) except Exception as exc: @@ -278,6 +290,56 @@ class Recorder: def install(self): import build123d as b + # Compound algebra and Builder insertion can call the kernel boolean + # boundary directly, without Shape.fuse/cut/intersect. + original_boolean = b.Shape._bool_op + + @functools.wraps(original_boolean) + def boolean(shape, args, tools, operation): + if self.depth: + return original_boolean(shape, args, tools, operation) + args, tools = list(args), list(tools) + from OCP.BRepAlgoAPI import BRepAlgoAPI_Fuse, BRepAlgoAPI_Cut, BRepAlgoAPI_Common + op = next((name for cls, name in ((BRepAlgoAPI_Fuse, "union"), + (BRepAlgoAPI_Cut, "cut"), (BRepAlgoAPI_Common, "intersect")) + if isinstance(operation, cls)), None) + if op is None or not args or any(not self.is_solid(s) for s in [*args, *tools]): + return original_boolean(shape, args, tools, operation) + # Each side is a set of bodies, not a chain of intersections. + inputs = self.reference(b.Compound(args)) + if tools: + inputs.extend(self.reference(b.Compound(tools))) + self.depth += 1 + try: + result = original_boolean(shape, args, tools, operation) + finally: + self.depth -= 1 + if result is not None and self.is_solid(result): + self.emit(op, inputs, {}, result, "Shape._bool_op") + return result + + self.patch(b.Shape, "_bool_op", boolean) + original_solid_init = b.Solid.__init__ + + @functools.wraps(original_solid_init) + def solid_init(solid, obj=None, *args, **kwargs): + if self.depth or not isinstance(obj, b.Shell): + return original_solid_init(solid, obj, *args, **kwargs) + extra = {} + try: + extra["profiles"] = [geometry.profile(face) for face in obj.faces()] + except Exception as exc: + extra["geometry_error"] = str(exc) + self.unsupported(f"Cannot transcribe Solid(Shell) inputs: {exc}", source="Solid.__init__") + self.depth += 1 + try: + original_solid_init(solid, obj, *args, **kwargs) + finally: + self.depth -= 1 + if self.is_solid(solid): + self.emit("sew_solid", [], {}, solid, "Solid.__init__", **extra) + + self.patch(b.Solid, "__init__", solid_init) factories = {"make_box": "box", "make_cylinder": "cylinder", "make_cone": "cone", "make_sphere": "sphere", "make_torus": "torus", "make_wedge": "wedge", "extrude": "extrude", "extrude_taper": "extrude_taper", "extrude_until": "extrude_until", @@ -350,13 +412,13 @@ class Recorder: def _find_result(namespace): from build123d import BuildPart, Shape for name in ("result", "part", "model", "solid", "body"): - value = namespace.get(name) + if name not in namespace: + continue + value = namespace[name] if isinstance(value, BuildPart): return value.part - if isinstance(value, Shape) and value.solids(): - return value - if isinstance(value, (list, tuple)) and any(isinstance(v, Shape) and v.solids() for v in value): - return value + # An explicit output is authoritative, including an empty or invalid one. + return value for value in reversed(list(namespace.values())): if isinstance(value, BuildPart) and value.part is not None: return value.part @@ -380,7 +442,10 @@ def trace_source(source: str, filename: str = "") -> dict[str, recorder.trace["b3d_status"] = "error" recorder.trace["error"] = traceback.format_exc() result = _find_result(namespace) - if result is None: + values = result if isinstance(result, (list, tuple)) else [result] + from build123d import Shape + if (not values or any(v is not None and not isinstance(v, Shape) for v in values) + or not any(v is not None and recorder.is_solid(v) for v in values)): recorder.trace["b3d_status"] = "error" recorder.trace["error"] += "\nNo solid result found in model namespace" else: @@ -389,8 +454,7 @@ def trace_source(source: str, filename: str = "") -> dict[str, recorder.trace.update(b3d_volume=summary["volume"], b3d_bbox=summary["bbox"], solid_count=summary["solid_count"]) recorder.trace["b3d_default_volume"] = summary.get("default_volume", summary["volume"]) recorder.trace["b3d_volume_gk"] = summary["volume"] - values = result if isinstance(result, (list, tuple)) else [result] - recorder.trace["b3d_valid"] = all(v.is_valid for v in values) + recorder.trace["b3d_valid"] = all(v.is_valid for v in values if v is not None) recorder.trace["b3d_area"] = summary["area"] finally: recorder.restore()