diff --git a/docs/skill/references/README.md b/docs/skill/references/README.md index 424acc0c..4986f2be 100644 --- a/docs/skill/references/README.md +++ b/docs/skill/references/README.md @@ -37,7 +37,9 @@ whole API index up front. Cross-cutting capabilities — QL grounding, semantic tags, GraphSession replay, units/tolerances, incremental validation — are not routing targets; each -workflow pulls them in as conditions require. +workflow pulls them in as conditions require. Verified QL selection patterns +for operation outputs (extrude-family slots, boolean seam curves, seam +fillets) live in `ql-playbook.md`. ## Workflows diff --git a/docs/skill/references/ql-playbook.md b/docs/skill/references/ql-playbook.md new file mode 100644 index 00000000..7fe3cd73 --- /dev/null +++ b/docs/skill/references/ql-playbook.md @@ -0,0 +1,209 @@ +# QL Selection Playbook + +Verified query patterns for selecting **what an operation produced**: side +faces and rims of extrude-like features, output slots of primitives, and the +intersection curves (seams) of booleans — then feeding those selections into +modifiers such as fillet. + +Every pattern in this file was executed and checked against `dev` @ `88f251c` +(2026-09-02, 33/33 checks across four harnesses: extrude family, primitives, +sweep/loft, D-boss seam). Snippets are trimmed copies of the passing harness +code. Anything listed under "Verified boundaries" is a real, current engine +limitation — do not work around it silently; route around it as shown. + +## Ground rules + +1. **Model inside `scad.GraphSession`.** Topology tracking, role tags, and + name projection only exist on session paths. Legacy (session-less) calls + attach whole-solid tags at most: no per-face roles, no projection, no + `origin_role`/`output_role` evidence. + +2. **Tag subshapes through the scope that will consume them.** Bindings live + in a shape's own entity cache: + + ```python + profile = scad.apply_tag_rselection(profile, [edge], "profile.long.a") + ``` + + Tagging an edge resolved from the *wire* under a face is invisible to the + face (different cache). `apply_tag_rselection` returns a clone — always + reassign the returned view. + +3. **Enumerate with QL, not plural getters.** `ql.edges().resolve(shape)`, + never bare `get_edges()` (raises by design; enumeration is QL-exclusive). + +4. **Pick the naming channel by the reach you need:** + + | Channel | Example | Survives boolean | Survives fillet/chamfer | + | --- | --- | --- | --- | + | op-kwarg role naming | `extrude_rsolid(..., end_face_tag="cap.top")`, `make_box_rsolid(..., top_face_tag="base.top")` | yes (verified) | **no** (face channel gap) | + | source-edge naming | `apply_tag_rselection(profile, [edge], "profile.long.a")` → side face; `apply_tag_rselection(result, [seam], "seam.d")` → fillet patch | yes (via kernel images) | **yes** (edge→patch projection) | + | `origin_role("body"/"tool")` | parent argument of a boolean | single-step only | no | + | `output_role("")` | `extrusion.end`, `box.top`, `fillet.patch` | single-step only | own op only | + | plain user tag on a face | `apply_tag_rselection(solid, [face], "base.body")` | **no** (face-source gate) | **no** | + + "Single-step" means the metadata describes the last operation that touched + the shape; the next tracked operation overwrites it. Long-range identity = + op-kwarg names (across booleans) and edge-source names (across modifiers). + +## Pattern A — extrude-like outputs + +The five canonical moves, on `extrude_rsolid` (identical selectors work for +`sweep_rsolid` / `loft_rsolid` and for primitives, which are the kernel-native +extrudes): + +```python +with scad.GraphSession(): + wire = scad.make_rectangle_rwire(30.0, 10.0, (0, 0, 0), (0, 0, 1)) + profile = scad.make_face_from_wire_rface(wire) + + # 1) name profile edges through the profile scope (classifying by length + # and center sign stays the most robust addressing) + for ent in ql.edges().resolve(profile): + if abs(ent.get_length() - 30.0) < 1e-6 and ent.get_center().x > 0: + profile = scad.apply_tag_rselection(profile, [ent], "profile.long.a") + elif abs(ent.get_length() - 10.0) < 1e-6 and ent.get_center().y > 0: + profile = scad.apply_tag_rselection(profile, [ent], "profile.short.a") + + solid = scad.extrude_rsolid( + profile, (0, 0, 1), 8.0, + start_face_tag="cap.bottom", end_face_tag="cap.top", + side_faces_tag="wall.side", + ) + + # 1. side face by inherited profile-edge name (also: wall.side group = 4) + ql.faces().where(ql.tag("profile.long.a")).resolve(solid) + + # 2. vertical corner edge shared by two side faces + side_long = ql.faces().where(ql.tag("profile.long.a")).exactly(1) + side_short = ql.faces().where(ql.tag("profile.short.a")).exactly(1) + side_long.shared_boundary(side_short, "edge").resolve(solid) + + # 3. edge shared by the end face and one side face + cap = ql.faces().where(ql.tag("cap.top")).exactly(1) + cap.shared_boundary(side_long, "edge").resolve(solid) + + # 4. end face (kernel-role channel; kwarg name gives the same face) + ql.faces().where(ql.output_role("extrusion.end")).resolve(solid) + + # 5. the end-face rim + cap.boundary("edge").resolve(solid) +``` + +Verified extensions: + +- **Primitives** carry the same slots natively: `box.top/bottom/front/back/ + left/right`, `cylinder.start/end/side/start_boundary/end_boundary/seam`, + `cone.start/end/side/start_boundary/end_boundary/seam`. Query with + `output_role(...)` or the matching `*_face_tag` / `*_edge_tag` kwarg. + Box orientation for `width=x, height=y, depth=z`: front/back = ±x, + left/right = ±y, top/bottom = ±z. +- **Seam edges without any name** — select by topology signature (the seam is + the only full-height edge with a single incident face): + + ```python + ql.edges().incident_face_count(exactly=1).resolve(solid) + ``` + +- **sweep**: profile-edge names reach the swept side face exactly as with + extrude (verified: circle edge name → cylindrical wall). `sweep.start/end` + name the caps; cap rim and cap∩side shared edge select identically. +- **loft**: `loft.start/end` caps and the `side_faces_tag` group work; per-side + identity is NOT stable (section correspondence is kernel-matched), so select + sides as a group or post-hoc — never index them. + +## Pattern B — boolean seam curves (D-boss recipe) + +A D-shaped boss standing on the long side face of a bar base, unioned with a +1 mm dip into the base and a top that rises 4 mm above the bar: the seam is a +closed 3-D curve set running across the base side face, the base top face and +the bottom imprint. All of it is selectable, then filletable, in two moves. + +```python +with scad.GraphSession(): + base = scad.make_box_rsolid(120.0, 30.0, 20.0, (0, 0, 0), + top_face_tag="base.top") + + # D boss = box U cylinder; cylinder bottom-face center sits at the + # midpoint of the boss box's +y bottom edge -> classic D outline + boss_box = scad.make_box_rsolid(24.0, 10.0, 24.0, (0, 19.0, 0.0)) + boss_cyl = scad.make_cylinder_rsolid(12.0, 24.0, (0, 24.0, 0.0), (0, 0, 1)) + boss = scad.union_rsolid(boss_box, boss_cyl) + + result = scad.union_rsolid(base, boss, clean=False) + + # parents by kernel-proven boolean origin role (arg 0 = body, arg 1 = tool) + body_sel = ql.faces().where(ql.origin_role("body")) + tool_sel = ql.faces().where(ql.origin_role("tool")) + + # the seam: edges with one distinct incident face per parent + seam = ql.edges().incident_to(body_sel, tool_sel, distinct=True).resolve(result) + + # name the seam, then fillet it — the selector feeds fillet directly + result = scad.apply_tag_rselection(result, seam, "seam.d") + seam_sel = ql.edges().incident_to(body_sel, tool_sel, distinct=True) + filleted = scad.fillet_rsolid(result, seam_sel, 2.0) + + # the patches inherit the seam-edge name (verified 7/7 patches) + ql.faces().where(ql.tag("seam.d")).resolve(filleted) +``` + +Verified seam inventory for the dimensions above (`clean=False`): 13 edges — +2 vertical lines on the side face (±12, y=15), 5 edges on the base top plane +(the D outline where the boss crosses z=20: 1.0 + 5.367 + 14.056 + 5.367 + +1.0), 6 on the bottom plane (same outline at z=0 plus the 24-long dip +imprint). With `clean=True` the coplanar bottom pieces unify and part of the +imprint seam disappears — keep `clean=False` when the seam itself is the +selection target. + +Facts that matter when filleting a seam: + +- **`fillet_rsolid` accepts a `ShapeSelector`** for its `edges` argument; no + need to materialize the list twice. +- A boss/base seam is mostly **concave**: the fillet ADDS volume + (82780.7 → 82841.1 at r=2). Never assert `v1 < v0` on seam fillets. +- The whole seam filleted at once is a hard kernel case; if a radius fails, + step down (2.0 → 1.5 → 1.0 verified ladder pattern). + +## Verified boundaries + +Current engine gaps found by the harnesses — each has a workaround above: + +1. **Plain user tags on faces do not project through any later op.** The + face-source projection gate (`autotag._project_source_bindings` with + `require_lineage_policy=True`) passes only operation-output and topology + naming; plain user bindings project from **edge** sources only. Use + op-kwarg names for cross-boolean face identity, edge names for + cross-modifier identity. +2. **Modifier face-source projection lacks `project_source_tags`** + (`tracking.py`, `tracked_fillet`/`tracked_chamfer` face query). Face names + — even op-kwarg ones that survive booleans — are dropped when the face is + trimmed by a fillet/chamfer. The edge→patch channel is complete (7/7). +3. **`origin_role` / `output_role` are single-step metadata.** After the seam + fillet, every face reports the fillet's own roles; the boolean body/tool + partition is gone. Query parent identity immediately after the boolean, or + carry it as a name. +4. **Primitive auto role tags (`face.box.top`, ...) do not project through + booleans** — only kwarg-named slots (`top_face_tag="base.top"`) do. +5. **Planar profile axes now match the box convention** (fixed by + `fix/plane-axes-convention`): `_orthonormal_plane_axes` builds the in-plane + basis by projecting the reference vector (Gram-Schmidt), so for a +z normal + width spans global x, exactly like `make_box_rsolid`. Before the fix, + `make_rectangle_rwire(30, 10)` silently spanned 10 in x and 30 in y; the + harnesses classified profile edges by length and center sign, which stays + the most robust addressing. Known residual behavior (separate issue): the + reference-axis branch (`|z_z| > 0.9`) still switches the in-plane basis + discontinuously near ~25° from vertical. +6. **N-ary cut unrolls hop-by-hop**; multi-hop modification chains can lose + projected bindings (later hops overwrite earlier witnesses for the same + output). For long-range names across a cut chain, prefer naming after the + final cut, or union-side naming. + +## Verification harnesses (2026-09-02, dev @ 88f251c) + +| Harness | Checks | Result | +| --- | --- | --- | +| extrude family (5 capabilities + group naming + geometry identity) | 8 | PASS | +| primitives (box slots, rim, shared edge, kwarg naming, cylinder seam/rim/topology signature) | 8 | PASS | +| sweep + loft (profile-edge inheritance, caps, rims, shared edges, seam-by-topology) | 9 | PASS | +| D-boss seam (origin-role partition, 13-edge seam inventory, dual-parent witnesses, fillet, 7/7 patch naming) | 8 | PASS | diff --git a/src/simplecadapi/operators/_support.py b/src/simplecadapi/operators/_support.py index 93000674..1286c7fa 100644 --- a/src/simplecadapi/operators/_support.py +++ b/src/simplecadapi/operators/_support.py @@ -474,7 +474,11 @@ def _orthonormal_plane_axes( ref_vec = ( np.array([1.0, 0.0, 0.0]) if abs(z_axis[2]) > 0.9 else np.array([0.0, 0.0, 1.0]) ) - x_axis = np.cross(z_axis, ref_vec) + # In-plane x = ref projected onto the plane (Gram-Schmidt): for a +z normal + # the frame is exactly the global (x, y, z), matching make_box_rsolid's + # width-along-x convention. The ref branch above keeps ref away from z, so + # the projection never degenerates. + x_axis = ref_vec - float(ref_vec @ z_axis) * z_axis x_norm = float(np.linalg.norm(x_axis)) if x_norm <= 1e-12: raise ValueError("无法根据给定法向量构建局部坐标系") diff --git a/test/test_plane_axes_convention.py b/test/test_plane_axes_convention.py new file mode 100644 index 00000000..9a5e7551 --- /dev/null +++ b/test/test_plane_axes_convention.py @@ -0,0 +1,96 @@ +"""Plane-axis convention regression tests. + +`_orthonormal_plane_axes` must build the in-plane frame by projecting the +reference vector onto the plane, so a +z normal yields exactly the global +(x, y, z) frame. Planar profile makers that use the helper (currently +`make_rectangle_rwire`, session and legacy paths) then agree with +`make_box_rsolid`'s width-along-x convention. The previous cross-product +basis rotated every profile by 90 degrees for +z normals (width landed on +global y). +""" + +import unittest + +import numpy as np + +import simplecadapi as scad +from simplecadapi import ql +from simplecadapi.operators._support import _orthonormal_plane_axes + + +class TestOrthonormalPlaneAxes(unittest.TestCase): + def test_z_normal_frame_matches_box_convention(self): + z_axis, x_axis, y_axis = _orthonormal_plane_axes((0.0, 0.0, 1.0)) + np.testing.assert_allclose(z_axis, (0.0, 0.0, 1.0), atol=1e-12) + np.testing.assert_allclose(x_axis, (1.0, 0.0, 0.0), atol=1e-12) + np.testing.assert_allclose(y_axis, (0.0, 1.0, 0.0), atol=1e-12) + + def test_frames_are_unit_right_handed_and_transverse(self): + normals = [ + (0.3, -0.4, 0.86), + (1.0, 0.0, 0.0), + (0.0, 1.0, 0.0), + (0.0, 0.0, -1.0), + (0.2, 0.98, 0.05), + ] + for normal in normals: + with self.subTest(normal=normal): + z_axis, x_axis, y_axis = _orthonormal_plane_axes(normal) + np.testing.assert_allclose(np.linalg.norm(z_axis), 1.0, atol=1e-12) + np.testing.assert_allclose(np.linalg.norm(x_axis), 1.0, atol=1e-12) + np.testing.assert_allclose(np.linalg.norm(y_axis), 1.0, atol=1e-12) + np.testing.assert_allclose(x_axis @ z_axis, 0.0, atol=1e-12) + np.testing.assert_allclose(y_axis @ z_axis, 0.0, atol=1e-12) + np.testing.assert_allclose( + np.cross(x_axis, y_axis), z_axis, atol=1e-12 + ) + + def test_zero_normal_is_rejected(self): + with self.assertRaises(ValueError): + _orthonormal_plane_axes((0.0, 0.0, 0.0)) + + +class TestRectangleAxisConvention(unittest.TestCase): + @staticmethod + def _edge_inventory(use_session: bool): + def build(): + return scad.make_rectangle_rwire(30.0, 10.0, (0.0, 0.0, 0.0), (0.0, 0.0, 1.0)) + + if use_session: + with scad.GraphSession(graph_id="rect_axes_session"): + wire = build() + else: + wire = build() + inventory = [] + for edge in ql.edges().resolve(wire): + center = edge.get_center() + inventory.append( + (round(center.x, 3), round(center.y, 3), round(edge.get_length(), 3)) + ) + return sorted(inventory) + + def test_width_spans_x_on_session_path(self): + self.assertEqual( + self._edge_inventory(use_session=True), + [ + (-15.0, -0.0, 10.0), + (0.0, -5.0, 30.0), + (0.0, 5.0, 30.0), + (15.0, 0.0, 10.0), + ], + ) + + def test_width_spans_x_on_legacy_path(self): + self.assertEqual( + self._edge_inventory(use_session=False), + [ + (-15.0, -0.0, 10.0), + (0.0, -5.0, 30.0), + (0.0, 5.0, 30.0), + (15.0, 0.0, 10.0), + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_surface_api.py b/test/test_surface_api.py index 260291d2..ed3a9002 100644 --- a/test/test_surface_api.py +++ b/test/test_surface_api.py @@ -401,9 +401,12 @@ class TestSurfaceApi(unittest.TestCase): scad.make_rectangle_rwire(4.0, 4.0), ) + # 2(x) x 4(y) loop poking out on +x: same footprint the test has + # always exercised; the dims read (4, 2) under the pre-fix transposed + # plane basis, (2, 4) under the width-along-x convention. trimmed = scad.trim_surface_rface( carrier, - scad.make_rectangle_rwire(4.0, 2.0, center=(1.5, 0.0, 0.0)), + scad.make_rectangle_rwire(2.0, 4.0, center=(1.5, 0.0, 0.0)), ) self.assertAlmostEqual(trimmed.get_area(), 6.0, places=6)