diff --git a/design-docs/multi-solid-design.md b/design-docs/multi-solid-design.md index a7a5cc66..c7ef0e3b 100644 --- a/design-docs/multi-solid-design.md +++ b/design-docs/multi-solid-design.md @@ -1,7 +1,8 @@ # Multi-body parts (several solids in one part, without an assembly) Status: research and spike on `research/multi-solid` (cut from `dev`). The spike is in the code and in -`test/test_multi_body_part.py`. Everything under "Staged plan" after stage 1 is a proposal. +`test/test_multi_body_part.py`. Everything under "Staged plan" after stage 1 is a proposal. Section 9 records the +owner's decisions and how they are implemented; where it differs from an earlier section, section 9 wins. ## 1. The decision @@ -293,8 +294,7 @@ named solids. The rules the editor and the docs follow: variable name is nicer in the editor, but changing it would change ids that exist today. 4. Does "New body" in the editor need confirmation the first time a notebook gets a second body, given that until now a second solid was a mistake? -5. Should `cut_rsolid` keep refusing splits now that a split can become bodies? The spike keeps the refusal: - splitting stays explicit through `cut_rsolid_list`. +5. (Decided, section 9: splits are kept as pieces by default.) Should `cut_rsolid` keep refusing splits? ## 8. The spike @@ -326,3 +326,60 @@ named solids. The rules the editor and the docs follow: - scene solid nodes; - STEP with one product and two solids; - one-body definitions without `bodies`. + +## 9. Owner decisions (implemented) + +1. **Overlapping bodies warn, never refuse.** + - `inspect_body_overlaps_rlist(part)` is a diagnostic op. It lists pairs that share volume: a bounding-box + prefilter, then the OCCT common volume. Bodies that only touch along a face, an edge or a point are not reported. + - Building the definition warns once per pair with `BodyOverlapWarning`. That covers a notebook run, `@part` and a + package. `make_part_rpart` itself never runs the check, so the live editor loop stays cheap. +2. **Multi-body definitions are profile `simplecad-part-definition-3`.** + - The new schema `contracts/part-definition-3.schema.json` requires `solid_cache.bodies`. + - `part-definition-2.schema.json` is back to its dev bytes. A profile-2 reader fails schema validation on + `profile` (`const`), so it refuses the file rather than reading it wrongly. This is tested by validating a profile-3 + manifest against schema 2. + - One-body parts stay profile 2, so their bytes and content hashes do not change. + - `validate_manifest` picks the schema by the manifest's profile. +3. **Default body ids.** A one-body part keeps `"body"`; a multi-body part uses the names it was given. This is + unchanged from the spike. +4. **Choosing "New body" is the confirmation.** The editor asks nothing more. + + **Implicit Part** (the `kind = "part"` rule on `feat/gui-modeling`, `runtime/projection.py`): every open body + becomes a body of the implicit Part, named by its variable. The drop-in is `simplecadapi.product.bodies.part_from_bodies(part_id, {name: solid_or_pieces})`. It makes a one-body Part + (id `"body"`) for one open Solid, and otherwise `make_part_rpart(bodies=...)` with the pieces of a split expanded to + `_1..n`. The exact change on `feat/gui-modeling`: + - in `open_bodies`, also accept a non-empty `list`/`tuple` of `Solid` (the pieces of a split cut) as a candidate. Use + the lineage of its first element for the "made from" test, and treat `id()` of each piece as seen; + - in `_implicit_part`, drop the `len(names) > 1` error and return + `part_from_bodies(config.id, {name: values[name] for name in names})`; + - update its docstring and the test that expected the error. Expected: two open bodies give a Part with those two + body ids. +5. **A cut that splits the body is not refused.** + - `cut_rsolid(..., on_split="pieces")` is the default. A one-piece result is a `Solid`, exactly as before, with the + same record, so the hashes of existing notebooks do not change. A split returns every piece as `list[Solid]`, + ordered by centroid (x, then y, then z). It is recorded as `make_cut_rsolid_list` with + `params.piece_order = "centroid"`, and both the C++ executor and the Python serializer replay it in that order. + - `on_split="error"` keeps the strict behaviour. + - Pieces become bodies directly: `make_part_rpart(body=pieces)` gives `body_1..n`, and `bodies={"bar": pieces}` gives + `bar_1..n`. + - **Default: separate bodies, not one solid with several lumps.** OCCT has no valid single solid with several lumps. + A `TopoDS_Solid` built from the two outer shells of a split bar fails `BRepCheck_Analyzer`, and STEP writes it as + `BREP_WITH_VOIDS`, with the second lump turned into a void. This was checked with a small OCCT program. + Fusion ("a body is a single container for a contiguous 3D shape") and FreeCAD ("a single contiguous solid") agree + that a body is one closed volume. + - "Keeping the pieces together" is therefore a naming matter: they share the prefix of the value they came from + (`bar_1`, `bar_2`), and the editor can show them as one row with two bodies. + - A Body that holds several lumps would be a later, additive extension (`Body.lumps`). It is not needed for valid + geometry. + - Downstream single-solid features (a fillet on `bar`) now fail with a clear type error when `bar` is a list. The + editor should then offer to pick a piece or keep the pieces as bodies (stage 2). + +Skill pages updated with these rules: `domains/part-modeling.md` (with a new "Multi-body parts" section), +`domains/assembly-and-product.md`, `discipline/core-rules.md` R5, `discipline/failure-and-repair.md`, +`discipline/mechanical-modeling.md`, `discipline/notebook-cell-design.md` C9, `docs/core/compound.md`, +`docs/guides/notebook-runtime.md`, `workflows/single-part-modeling.md` and `role-4-build.md`, and +`workflows/drawing-reconstruction.md`. The API pages are regenerated. Tags on cut pieces: a plain `cut_rsolid` outside +a recording session carries no input face tags, a behaviour that predates this work. Tag and ref propagation belongs to +`research/stable-geometry-refs`. + diff --git a/docs/skill/references/discipline/core-rules.md b/docs/skill/references/discipline/core-rules.md index df4e1e95..d30545d0 100644 --- a/docs/skill/references/discipline/core-rules.md +++ b/docs/skill/references/discipline/core-rules.md @@ -20,8 +20,9 @@ before writing any cell. **R4. Sketch first.** 2D profiles and planar paths go through the sketch API; primitives only when the shape is entirely the basic form. -**R5. Booleans** (`union_rsolid`, `cut_rsolid`, `cut_rsolid_list`, `intersect_rsolid`) accept mixed inputs and return -exactly one `Solid`. Union defaults to `glue=False` with a conservative scale-relative tolerance and fails explicitly when +**R5. Booleans** (`union_rsolid`, `cut_rsolid`, `cut_rsolid_list`, `intersect_rsolid`) accept mixed inputs. Union and +intersect return exactly one `Solid`; `cut_rsolid` returns one `Solid`, or the pieces (`list[Solid]`, centroid order) +when the cut splits the body (`on_split="error"` refuses instead); `cut_rsolid_list` always returns a list. Union defaults to `glue=False` with a conservative scale-relative tolerance and fails explicitly when it cannot produce one merged solid. **R6. Topology is enumerated through QL only.** Plural getters (`get_edges`, `get_faces`, `get_wires`, `get_vertices`, diff --git a/docs/skill/references/discipline/failure-and-repair.md b/docs/skill/references/discipline/failure-and-repair.md index 41f386f4..015e68bd 100644 --- a/docs/skill/references/discipline/failure-and-repair.md +++ b/docs/skill/references/discipline/failure-and-repair.md @@ -47,9 +47,10 @@ which claims cannot be made (see "Reporting failed repairs"). Interactive: the r - Isolate and simplify the failing base/tool pair. - `cut_rsolid(..., skip_non_intersecting=False)` is the strict diagnostic mode; with the default `True`, non-intersecting tools may be ignored. -- `cut_rsolid` expected a single Solid but the kernel returned several: the cut - split the body. If that is intended, call `cut_rsolid_list`; if not, the tool - crosses the body completely or touches a wall tangentially — resize or +- `cut_rsolid` returned a list instead of a Solid: the cut split the body + (with `on_split="error"` it raises instead). If that is intended, pass the + pieces on as bodies (`make_part_rpart(part_id=..., body=pieces)`); if not, the + tool crosses the body completely or touches a wall tangentially — resize or reposition it. - After repeated failure, reconsider operation order — not just retry the same cut harder. @@ -59,7 +60,9 @@ which claims cannot be made (see "Reporting failed repairs"). Interactive: the r `union_rsolid` requires a one-manifold-`Solid` result and fails if it cannot produce one. If the design is one body, use a contact or overlap that is topologically capable of producing one solid, then recompute. If the design is -actually multiple parts, the answer is an assembly, not a union. +actually multiple parts, the answer is an assembly, not a union; if it is one +part whose bodies stay apart, make a multi-body part +(`make_part_rpart(bodies=...)`). ### Fillet/chamfer failure diff --git a/docs/skill/references/discipline/mechanical-modeling.md b/docs/skill/references/discipline/mechanical-modeling.md index 22b7b4e5..0bbc491a 100644 --- a/docs/skill/references/discipline/mechanical-modeling.md +++ b/docs/skill/references/discipline/mechanical-modeling.md @@ -22,7 +22,9 @@ This document separates SDK contracts from mechanical design guidance. - **Decide part vs assembly before modeling.** Bodies that are separately manufactured, purchased, or movable belong in an assembly with connectors and placements; monolithic manufacturing intent gets a single fused solid. - Never leave a multi-body result where one labeled product was intended. + Several bodies of one part are deliberate: name them in + `make_part_rpart(bodies={...})`. Never leave stray solids out of the product, + or overlapping bodies, where one labeled product was intended. - **Pick the origin and orientation from the functional datum** — the mating interface, mounting plane, or symmetry axis — not from wherever the first primitive happened to land. See `datums-and-coordinate-systems.md`. diff --git a/docs/skill/references/discipline/notebook-cell-design.md b/docs/skill/references/discipline/notebook-cell-design.md index 1ccae00c..a96e354d 100644 --- a/docs/skill/references/discipline/notebook-cell-design.md +++ b/docs/skill/references/discipline/notebook-cell-design.md @@ -87,7 +87,10 @@ nothing; a geometry line in the params cell would re-run with every parameter change. **C9. The product is made in the last cell.** Its id is the notebook id -(`scad.notebook_id()`); a family of parts uses `scad.use(path, id=...)`. +(`scad.notebook_id()`); a family of parts uses `scad.use(path, id=...)`. A part +with several bodies names them there: +`make_part_rpart(part_id=scad.notebook_id(), bodies={"base": base, "lid": lid})`; +solids left out of it (tools, construction) are not part of the product. **C10. In an assembly notebook, one `scad.use(...)` per child, the mates in their own cell, the solve in its own cell.** Do not carry the whole assembly diff --git a/docs/skill/references/docs/api/README.md b/docs/skill/references/docs/api/README.md index dd8aa7ac..3facfb0f 100644 --- a/docs/skill/references/docs/api/README.md +++ b/docs/skill/references/docs/api/README.md @@ -392,6 +392,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi - [ground_component_rassembly](ground_component_rassembly.md) *(from operators/product.py)* `top-level` - [identity_placement_rplacement](identity_placement_rplacement.md) *(from operators/product.py)* `top-level` - [inspect_assembly_constraints_rconstraintreport](inspect_assembly_constraints_rconstraintreport.md) *(from operators/product.py)* `top-level` +- [inspect_body_overlaps_rlist](inspect_body_overlaps_rlist.md) *(from operators/product.py)* `top-level` - [inspect_sketch_rsketchresult](inspect_sketch_rsketchresult.md) *(from operators/sketch.py)* `top-level` - [key](key.md) *(from ql.py)* `submodule:ql` - [linear_pattern_rsolidlist](linear_pattern_rsolidlist.md) *(from operators/transform.py)* `top-level` diff --git a/docs/skill/references/docs/api/cut_rsolid.md b/docs/skill/references/docs/api/cut_rsolid.md index 880fa62c..c761832c 100644 --- a/docs/skill/references/docs/api/cut_rsolid.md +++ b/docs/skill/references/docs/api/cut_rsolid.md @@ -3,7 +3,7 @@ ## API Definition ```python -def cut_rsolid(*solids, skip_non_intersecting=True, tracking_policy='full') +def cut_rsolid(*solids, skip_non_intersecting=True, tracking_policy='full', on_split='pieces') ``` *Source: operators/boolean.py* @@ -33,10 +33,26 @@ sequences, and returns a single `Solid`. - **Description**: FULL computes topology history and lineage. GRAPH keeps the replayable operation node without computing a TopoDelta. +### on_split + +- **Description**: What a cut that splits the body (a slot through a bar) returns. + +### ``"pieces"`` + +- **Type**: `default` +- **Description**: every piece, as ``list[Solid]`` ordered by centroid + +### (x, then y, then z), recorded like ``cut_rsolid_list``. ``"error"`` + +- **Description**: raise, for code that needs exactly one Solid. + ## Returns -Solid: The cut result solid. +Solid: The cut result solid, when the result is one piece. +list[Solid]: The pieces, when the cut split the body (``on_split="pieces"``). +Pass them on as bodies: ``make_part_rpart(part_id=..., body=pieces)`` makes the +bodies ``body_1 .. body_n``, ``bodies={"bar": pieces}`` makes ``bar_1 .. bar_n``. ## Raises -- **SimpleCADError**: The cut produced no solid, or split the body into several (a slot through a bar). Use ``cut_rsolid_list`` to keep every piece. +- **SimpleCADError**: The cut produced no solid, or (``on_split="error"``) split the body. Use ``cut_rsolid_list`` to always get a list. diff --git a/docs/skill/references/docs/api/inspect_body_overlaps_rlist.md b/docs/skill/references/docs/api/inspect_body_overlaps_rlist.md new file mode 100644 index 00000000..d7b4f906 --- /dev/null +++ b/docs/skill/references/docs/api/inspect_body_overlaps_rlist.md @@ -0,0 +1,43 @@ +# inspect_body_overlaps_rlist + +## API Definition + +```python +def inspect_body_overlaps_rlist(part: 'Part', *, min_volume_mm3: 'float' = 1e-06) -> 'list[BodyOverlap]' +``` + +*Source: operators/product.py* + +## Import Surface + +- top-level: `from simplecadapi import inspect_body_overlaps_rlist` + +## Description + +List the pairs of bodies of a Part that share volume. + +Overlapping bodies are allowed (a Part does not fuse them), but mass counts the +shared volume once per body and STEP holds both copies. Bodies that only touch +(a face, an edge or a point in common) do not overlap. + +``scad.inspect_body_overlaps_rlist(case)`` before export. Building the part's +definition (a notebook run, ``@part``, a package) warns with ``BodyOverlapWarning`` +for the same pairs. + +## Parameters + +### part + +- **Description**: The Part to inspect; a one-body Part has no overlaps. + +### min_volume_mm3 + +- **Description**: Shared volume below which a pair is not reported. + +## Returns + +list[BodyOverlap]: ``(first, second, volume_mm3)`` per overlapping pair, in body order. + +## Raises + +- **SimpleCADError**: The value is not a Part. diff --git a/docs/skill/references/docs/api/make_part_rpart.md b/docs/skill/references/docs/api/make_part_rpart.md index 884b1e43..719955ec 100644 --- a/docs/skill/references/docs/api/make_part_rpart.md +++ b/docs/skill/references/docs/api/make_part_rpart.md @@ -30,7 +30,7 @@ first when they must become one body. ### body -- **Description**: The Solid of a one-body Part. +- **Description**: The Solid of a one-body Part. The pieces of a split cut (a list of Solids) become the bodies ``body_1 .. body_n``. ### name @@ -38,7 +38,11 @@ first when they must become one body. ### bodies -- **Description**: Instead of ``body``: several solids kept apart in one Part, as a mapping ``body_id -> Solid`` (in its order) or a sequence of ``Body`` values. Body ids are identifiers, unique within the part. +- **Description**: Instead of ``body``: several solids kept apart in one Part, as a mapping ``body_id -> Solid`` (in its order) or a sequence of ``Body`` values. A mapping value may be the pieces of a split cut (a list of + +### Solids) + +- **Description**: they become ``_1 .. _n``. Body ids are identifiers, unique within the part. Overlapping bodies are allowed; building the definition warns (``BodyOverlapWarning``). ## Returns diff --git a/docs/skill/references/docs/core/compound.md b/docs/skill/references/docs/core/compound.md index 1f138d3b..f7a5c000 100644 --- a/docs/skill/references/docs/core/compound.md +++ b/docs/skill/references/docs/core/compound.md @@ -19,4 +19,7 @@ Use `Compound` when a workflow intentionally needs a flattened geometry projection. Do not use it as a substitute for `Assembly` product structure. For normal part modeling, keep using `Solid` as the body-level geometry. A -single-body `Part` wraps exactly one `Solid`. +`Part` wraps one `Solid`, or several named bodies (`Part.bodies`), each its own +`Solid`. A `Compound` built from solids does not keep their tags, so it is not +a way to hold the bodies of a part (`scad.part_shape(part)` gives that view for +geometry-only use). diff --git a/docs/skill/references/docs/guides/notebook-runtime.md b/docs/skill/references/docs/guides/notebook-runtime.md index fa182137..73ed584f 100644 --- a/docs/skill/references/docs/guides/notebook-runtime.md +++ b/docs/skill/references/docs/guides/notebook-runtime.md @@ -87,6 +87,12 @@ if __name__ == "__main__": (`run_notebook(..., id=...)`, `scad.use(..., id=...)`, `sca run --id`); cells read the id of their run with `scad.notebook_id()` — see [Part families](notebook-composition-and-cache.md#part-families). +- **A part with several bodies** is one product: + `scad.make_part_rpart(part_id=scad.notebook_id(), bodies={"base": base, "lid": lid})`. + Each body keeps its own BRep, topology snapshot and tags in the package, whose + part definition then has profile `simplecad-part-definition-3` (an older SDK + refuses it instead of reading one body). One-body parts are unchanged. + The cell cache restores a multi-body part like any other value. - **Parameters** are ordinary top-level variables. Overriding one replaces it, and the cell that defines it does not run, so all variables of that cell must be overridden together. Group parameters into cells by what changes diff --git a/docs/skill/references/domains/assembly-and-product.md b/docs/skill/references/domains/assembly-and-product.md index 7f314743..db9e32cc 100644 --- a/docs/skill/references/domains/assembly-and-product.md +++ b/docs/skill/references/domains/assembly-and-product.md @@ -22,12 +22,16 @@ deliver `.scadpkg` packages. - Monolithic single-body manufacturing intent: fuse with `union_rsolid` in `domains/part-modeling.md`. +- Several bodies of one part that never move apart and are one BOM item + (a multi-body part, `make_part_rpart(bodies=...)`): `domains/part-modeling.md`. - Export or translation decisions: they branch from the package in `domains/export-and-translation.md`. ## Structure model -- `Part` wraps exactly one `Solid` plus identity and optional material - (`make_part_rpart`, `assign_material_rpart`, `make_material_rmaterial`). +- `Part` wraps one `Solid` (or several named bodies, `bodies=`) plus identity + and optional material (`make_part_rpart`, `assign_material_rpart`, + `make_material_rmaterial`). In an assembly a multi-body part is one component; + its bodies are never placed or jointed separately. - `Assembly` holds component instances with placements (`make_assembly_rassembly`, `add_component_rassembly`, `place_component_rassembly`, `make_placement_rplacement`, diff --git a/docs/skill/references/domains/part-modeling.md b/docs/skill/references/domains/part-modeling.md index 5e01187a..de459141 100644 --- a/docs/skill/references/domains/part-modeling.md +++ b/docs/skill/references/domains/part-modeling.md @@ -1,15 +1,18 @@ # Task Domain: Part Modeling -Model one physical, single-solid mechanical part with the core geometry API: -primitives, profiles, 3D features, booleans, detail features, and transforms. +Model one physical mechanical part with the core geometry API: primitives, +profiles, 3D features, booleans, detail features, and transforms. A part is +usually one solid body; it may hold several named bodies (see "Multi-body +parts" below). -**Read when:** the deliverable is one physical single-solid part, or an existing part source needs a geometry edit (Role 4 -of `workflows/single-part-modeling.md`). +**Read when:** the deliverable is one physical part (one body or several bodies kept apart in one product item), or an +existing part source needs a geometry edit (Role 4 of `workflows/single-part-modeling.md`). ## Use when - The deliverable is one physical part that will be manufactured or exported as - a single solid body. + one product item: normally a single solid body, or several bodies of one part + (a case and its lid modelled side by side, the pieces of a split cut). - The request names brackets, plates, enclosures bodies, shafts, spacers, bosses, flanges, blades, or any monolithic part geometry. - An existing part source needs a geometry edit: new features, dimension @@ -37,7 +40,8 @@ of `workflows/single-part-modeling.md`). ## Outputs - A positive-volume, closed `Solid`, or a `Part` via `make_part_rpart` when the - product boundary is needed. + product boundary is needed (`body=solid`, or `bodies={"base": base, "lid": lid}` + for a multi-body part). - Semantic tags on mating/role surfaces and numeric facts in metadata. - A replayable `GraphSession` model JSON when the flow must be replayable or interchange-exported. @@ -83,9 +87,37 @@ consult their own documentation before the first call. (`skip_non_intersecting=True`); pass `skip_non_intersecting=False` for strict diagnostics — a skipped cut is never a completed feature. - A cut can split a body (a slot through a bar leaves two parts) or consume it - (a tool that encloses the whole body). `cut_rsolid` returns one `Solid`, so it - raises instead of dropping parts; use `cut_rsolid_list(base, tools)` to get - every piece as a list (empty when nothing is left). + (a tool that encloses the whole body). `cut_rsolid` returns a `Solid` when + one piece is left and, when the cut splits the body, every piece as a + `list[Solid]` ordered by centroid (x, then y, then z); it never drops a piece. + Pass `on_split="error"` where exactly one Solid is required. A tool that + consumes the body still raises. `cut_rsolid_list(base, tools)` always returns + a list (empty when nothing is left). The pieces become bodies of the part: + `make_part_rpart(part_id=..., body=pieces)` gives `body_1 .. body_n`, + `bodies={"bar": pieces}` gives `bar_1 .. bar_n`. A body is one closed volume: + OCCT and STEP have no valid "one solid with several lumps". + +## Multi-body parts + +- `make_part_rpart(part_id=scad.notebook_id(), bodies={"base": base, "lid": lid})` + keeps several solids apart in one Part. The dict order is the body order; + body ids are identifiers, unique within the part. +- Read them with `part.bodies` (`Body.body_id`, `Body.solid`, `Body.name`), + `part.get_body("lid")`, `part.body_ids()`. `part.body` is the Solid of a + one-body part (id `"body"`) and raises `TypeError` on a multi-body part. +- Bodies have no placements, joints or connectors: anything that moves, or is + bought or made separately, is a component of an assembly + (`domains/assembly-and-product.md`). Connectors on a multi-body part are + refused for now. +- Tool and construction solids are not bodies: leave them as notebook values + and do not pass them to the Part. +- Overlapping bodies are allowed but warned (`BodyOverlapWarning` when the + definition is built); check with `inspect_body_overlaps_rlist(part)`. Union + bodies that are one piece of material. +- Mass per body and in total: `measure_part_mass_rmassreport(part)` (density + from the part's material, or `density=`). +- The preview draws one node per body (`node//body:`); STEP export + writes one product holding every body. ## Validation gates diff --git a/docs/skill/references/workflows/drawing-reconstruction.md b/docs/skill/references/workflows/drawing-reconstruction.md index f4aeaf3d..edbcaf42 100644 --- a/docs/skill/references/workflows/drawing-reconstruction.md +++ b/docs/skill/references/workflows/drawing-reconstruction.md @@ -183,7 +183,7 @@ in unattended mode never ask, write the assumption ledger into `REQUIREMENTS.md` native format. No OCR improvisation. - Calibration not accepted → re-anchor with independent dimensions; never produce derived numbers from a failed calibration. -- Boolean fails or yields multiple bodies → `domains/part-modeling.md` +- Boolean fails, or a cut splits the body into pieces → `domains/part-modeling.md` boolean discipline (overlap, overshoot, isolate the pair). - Fillet/chamfer fails → smaller radius, narrower selection, later order. - Dimension mismatch at a stage → re-measure against the ledger; fix the diff --git a/docs/skill/references/workflows/single-part-modeling.md b/docs/skill/references/workflows/single-part-modeling.md index 8ac9ca20..4fefadbe 100644 --- a/docs/skill/references/workflows/single-part-modeling.md +++ b/docs/skill/references/workflows/single-part-modeling.md @@ -150,7 +150,7 @@ through the role map to the owning artifact. ## Failure routes -- Boolean fails or yields multiple bodies → `domains/part-modeling.md` +- Boolean fails, or a cut splits the body into pieces → `domains/part-modeling.md` boolean discipline (overlap, overshoot tools, isolate the pair). - Fillet/chamfer fails → smaller radius, narrower selection, later order; selection problems follow the edge-selection defaults. diff --git a/docs/skill/references/workflows/single-part-modeling/role-4-build.md b/docs/skill/references/workflows/single-part-modeling/role-4-build.md index c871e127..f0ec8d1a 100644 --- a/docs/skill/references/workflows/single-part-modeling/role-4-build.md +++ b/docs/skill/references/workflows/single-part-modeling/role-4-build.md @@ -34,7 +34,8 @@ For the current stage: from a named base solid, create each additive boss/rib/flange or subtractive bore/pocket/opening as a separately named solid or tool, then use `union_rsolid`, `cut_rsolid`, or `intersect_rsolid` to obtain the next - single Solid. Repeat construct-feature -> Boolean -> verify for each + single Solid (a cut that splits the body returns its pieces as a list: + keep them as bodies of the part only when that is the design). Repeat construct-feature -> Boolean -> verify for each required feature group; ensure intentional positive overlap for unions and tool overshoot for cuts. Do not assemble an opaque final shape in one expression. diff --git a/examples/SDK_DEFECTS.md b/examples/SDK_DEFECTS.md index 7d7c737d..d02f1bf1 100644 --- a/examples/SDK_DEFECTS.md +++ b/examples/SDK_DEFECTS.md @@ -373,6 +373,17 @@ that surfaced it is in brackets. at the next package schema bump) and keep the `body:` segment the only way to address a body. +## 24. Error guidance is frozen by parity goldens [multi-solid research] + +- **Symptom:** the `make_part_rpart` guidance still says "Union intended multiple bodies into one Solid before + creating the Part.", which is wrong now that `bodies=` exists; changing it fails + `src/cpp/tests/python/test_product_values.py::test_part_creation_and_errors`. +- **Root cause:** the C++ port compares every error's `what_happened` / `possible_causes` / `how_to_fix` with goldens + captured from the old Python SDK (`tests/golden/product_*.json`), so guidance cannot follow the API. +- **Status:** open; the old text is kept. +- **Fix direction:** compare error *codes* and kinds against the goldens, and let guidance text change with the API + (or regenerate the goldens on a deliberate API change). + ## Heuristics - Run every notebook three times: fresh, all cached, `--no-cache`. The three diff --git a/src/cpp/bindings/python/bind_ops_features.cpp b/src/cpp/bindings/python/bind_ops_features.cpp index e474394a..37f72140 100644 --- a/src/cpp/bindings/python/bind_ops_features.cpp +++ b/src/cpp/bindings/python/bind_ops_features.cpp @@ -520,12 +520,21 @@ void bind_booleans(py::module_& m) { m.def( "cut_rsolid", - [](const py::args& solids, bool skip_non_intersecting, const py::object& tracking_policy) { + [](const py::args& solids, bool skip_non_intersecting, const py::object& tracking_policy, + const std::string& on_split) -> py::object { const std::vector operands = flattened(solids, "cut_rsolid"); const CutOptions options{skip_non_intersecting, policy_text(tracking_policy)}; - return unlocked(false, [&] { return cut_rsolid(operands, options); }); + if (on_split == "error") + return py::cast(unlocked(false, [&] { return cut_rsolid(operands, options); })); + if (on_split != "pieces") + throw scad::ValueError("on_split must be 'pieces' or 'error'"); + CutOutcome outcome = unlocked(false, [&] { return cut_rsolid_keep_split(operands, options); }); + if (outcome.solid) + return py::cast(*outcome.solid); + return solids_to_py(outcome.pieces); // the cut split the body: every piece, ordered by centroid }, py::kw_only(), py::arg("skip_non_intersecting") = true, py::arg("tracking_policy") = "full", + py::arg("on_split") = "pieces", "Compute the boolean difference of solids: the first is the base, the rest are subtracted in order."); m.def( diff --git a/src/cpp/bindings/python/bind_product.cpp b/src/cpp/bindings/python/bind_product.cpp index 87f4a9f4..f716397f 100644 --- a/src/cpp/bindings/python/bind_product.cpp +++ b/src/cpp/bindings/python/bind_product.cpp @@ -85,6 +85,15 @@ void bind_structure(py::module_& m) { throw scad::TypeError("give exactly one of body (a Solid) or bodies (several named solids)"); if (!bodies.is_none()) return sp::make_part_rpart(text(part_id, "part_id"), body_list(bodies), optional_name(name)); + if (is_pieces(body) && py::len(body) > 1) { // a split cut: its pieces are bodies body_1 .. body_n + std::vector pieces; + add_bodies(pieces, sp::kDefaultBodyId, body); + return sp::make_part_rpart(text(part_id, "part_id"), pieces, optional_name(name)); + } + if (is_pieces(body)) + return sp::make_part_rpart(text(part_id, "part_id"), + typed(py::reinterpret_borrow(body[py::int_(0)]), "body"), + optional_name(name)); return sp::make_part_rpart(text(part_id, "part_id"), typed(body, "body must be a Solid"), optional_name(name)); }); diff --git a/src/cpp/bindings/python/bind_product_args.hpp b/src/cpp/bindings/python/bind_product_args.hpp index e79447bf..cbe8ddf4 100644 --- a/src/cpp/bindings/python/bind_product_args.hpp +++ b/src/cpp/bindings/python/bind_product_args.hpp @@ -52,14 +52,35 @@ inline sp::OptionalString optional_name(const py::object& value) { return py::str(value).cast(); } -// The bodies of a multi-body Part: a mapping body_id -> Solid (in its order), or a sequence of Body values. +// True for a list or tuple of Solids: the pieces of a cut that split a body. +inline bool is_pieces(const py::object& value) { + return (py::isinstance(value) || py::isinstance(value)) && py::len(value) > 0 && + py::isinstance(py::reinterpret_borrow(value[py::int_(0)])); +} + +// One mapping entry: a Solid is one body; the pieces of a split cut are bodies _1 .. _n (one piece keeps ). +inline void add_bodies(std::vector& out, const std::string& body_id, const py::object& value) { + if (!is_pieces(value)) { + out.emplace_back(body_id, typed(value, "bodies values must be Solids or lists of Solids")); + return; + } + const py::sequence pieces = py::reinterpret_borrow(value); + const std::size_t count = pieces.size(); + for (std::size_t index = 0; index < count; ++index) { + out.emplace_back(count == 1 ? body_id : body_id + "_" + std::to_string(index + 1), + typed(py::reinterpret_borrow(pieces[index]), + "bodies values must be Solids or lists of Solids")); + } +} + +// The bodies of a multi-body Part: a mapping body_id -> Solid or pieces (in its order), or a sequence of Body values. inline std::vector body_list(const py::object& value) { std::vector out; if (py::isinstance(value) || py::hasattr(value, "items")) { for (const py::handle item : value.attr("items")()) { const py::tuple pair = py::reinterpret_borrow(item); - out.emplace_back(text(py::reinterpret_borrow(pair[0]), "body_id"), - typed(py::reinterpret_borrow(pair[1]), "bodies values must be Solids")); + add_bodies(out, text(py::reinterpret_borrow(pair[0]), "body_id"), + py::reinterpret_borrow(pair[1])); } return out; } diff --git a/src/cpp/bindings/python/bind_product_values.cpp b/src/cpp/bindings/python/bind_product_values.cpp index a30c6057..f26823fa 100644 --- a/src/cpp/bindings/python/bind_product_values.cpp +++ b/src/cpp/bindings/python/bind_product_values.cpp @@ -454,8 +454,13 @@ void bind_part(py::module_& m) { } if (body.is_none() == bodies.is_none()) throw scad::TypeError("give exactly one of body (a Solid) or bodies (several named solids)"); - if (!bodies.is_none()) { - return std::make_shared(text(part_id, "part_id"), body_list(bodies), optional_name(name), + if (!bodies.is_none() || is_pieces(body)) { // several bodies, or the pieces of a split cut + std::vector values; + if (bodies.is_none()) + add_bodies(values, kDefaultBodyId, body); + else + values = body_list(bodies); + return std::make_shared(text(part_id, "part_id"), std::move(values), optional_name(name), material_value, std::move(connector_values)); } return std::make_shared(text(part_id, "part_id"), typed(body, "body must be a Solid"), diff --git a/src/cpp/include/scad/ops/features/booleans.hpp b/src/cpp/include/scad/ops/features/booleans.hpp index 5e167a55..86e74811 100644 --- a/src/cpp/include/scad/ops/features/booleans.hpp +++ b/src/cpp/include/scad/ops/features/booleans.hpp @@ -24,6 +24,15 @@ Solid union_rsolid(const std::vector& solids, const UnionOptions& options struct CutOptions { bool skip_non_intersecting = true; // a tool that does not meet the body is ignored std::string tracking_policy = "full"; + // cut_rsolid_list: order the pieces by centroid (x, then y, then z) instead of kernel order, so piece i is the same + // piece on every OCCT version. Recorded as params.piece_order = "centroid" only when set. + bool order_pieces = false; +}; + +// What a cut that may split leaves: one Solid, or (`solid` empty) every piece, ordered by centroid. +struct CutOutcome { + std::optional solid; + std::vector pieces; }; // The first solid minus every other. Error "cut_rsolid". @@ -34,6 +43,10 @@ Solid cut_rsolid(const std::vector& solids, const CutOptions& options = { // Error "cut_rsolid_list"; recorded as make_cut_rsolid_list. std::vector cut_rsolid_list(const std::vector& solids, const CutOptions& options = {}); +// cut_rsolid that accepts a split: a one-piece result is exactly cut_rsolid (same record); a split is +// cut_rsolid_list with order_pieces (recorded as make_cut_rsolid_list). An empty result is still an error. +CutOutcome cut_rsolid_keep_split(const std::vector& solids, const CutOptions& options = {}); + // The overlap of all `solids`. Error "intersect_rsolid". Solid intersect_rsolid(const std::vector& solids); diff --git a/src/cpp/src/ops/features/booleans.cpp b/src/cpp/src/ops/features/booleans.cpp index 5a1e1beb..2359a761 100644 --- a/src/cpp/src/ops/features/booleans.cpp +++ b/src/cpp/src/ops/features/booleans.cpp @@ -2,6 +2,7 @@ #include "scad/core/tolerance.hpp" #include "scad/ops/features/booleans.hpp" +#include #include #include #include @@ -355,10 +356,13 @@ void record_cut(const std::vector& solids, const CutOptions& options, Tra } // namespace -Solid cut_rsolid(const std::vector& solids, const CutOptions& options) { +namespace { + +// The body of cut_rsolid. With `allow_split`, a result of several pieces returns nullopt before anything is recorded. +std::optional cut_one(const std::vector& solids, const CutOptions& options, bool allow_split) { bool no_intersection = false; try { - return occt_guard([&]() -> Solid { + return occt_guard([&]() -> std::optional { const TrackingPolicy policy = resolve_tracking_policy(options.tracking_policy); if (solids.empty()) throw ValueError("cut_rsolid requires at least one Solid input"); @@ -368,10 +372,13 @@ Solid cut_rsolid(const std::vector& solids, const CutOptions& options) { CutRun run = run_cuts(solids, options, policy, "cut_rsolid", no_intersection); if (run.pieces.empty()) throw ValueError("The cut failed: OCC returned no valid solid"); + if (run.pieces.size() > 1 && allow_split) + return std::nullopt; if (run.pieces.size() != 1) { - throw ValueError("cut_rsolid expected a single Solid result but the kernel returned " + - std::to_string(run.pieces.size()) + - " solids; the cut split the body. Use cut_rsolid_list to keep every piece."); + throw ValueError( + "cut_rsolid expected a single Solid result but the kernel returned " + std::to_string(run.pieces.size()) + + " solids; the cut split the body. Use on_split=\"pieces\" (the default) or cut_rsolid_list to keep every " + "piece."); } Solid result_solid = run.pieces.front(); @@ -397,6 +404,20 @@ Solid cut_rsolid(const std::vector& solids, const CutOptions& options) { } } +} // namespace + +Solid cut_rsolid(const std::vector& solids, const CutOptions& options) { + return *cut_one(solids, options, false); +} + +CutOutcome cut_rsolid_keep_split(const std::vector& solids, const CutOptions& options) { + if (std::optional one = cut_one(solids, options, true)) + return {std::move(one), {}}; + CutOptions ordered = options; + ordered.order_pieces = true; + return {std::nullopt, cut_rsolid_list(solids, ordered)}; +} + std::vector cut_rsolid_list(const std::vector& solids, const CutOptions& options) { bool no_intersection = false; try { @@ -410,6 +431,23 @@ std::vector cut_rsolid_list(const std::vector& solids, const CutOp CutRun run = run_cuts(solids, options, policy, "cut_rsolid_list", no_intersection); std::vector pieces = std::move(run.pieces); + if (options.order_pieces) { + std::vector> keyed; + for (Solid& piece : pieces) + keyed.emplace_back(kernel::center_of_mass(piece.wrapped()), std::move(piece)); + std::stable_sort(keyed.begin(), keyed.end(), [](const auto& a, const auto& b) { + const double ax[3] = {a.first.x, a.first.y, a.first.z}; + const double bx[3] = {b.first.x, b.first.y, b.first.z}; + for (int axis = 0; axis < 3; ++axis) { + if (std::abs(ax[axis] - bx[axis]) > 1e-6) + return ax[axis] < bx[axis]; + } + return false; + }); + pieces.clear(); + for (auto& item : keyed) + pieces.push_back(std::move(item.second)); + } std::optional merged = merge_topo_deltas(run.deltas); const bool tracked = policy != TrackingPolicy::Graph && run.cut_performed && merged; std::vector sources(solids.begin(), solids.end()); @@ -424,6 +462,8 @@ std::vector cut_rsolid_list(const std::vector& solids, const CutOp FeatureRecord rec(kCutListOp); record_cut(solids, options, policy, rec); + if (options.order_pieces) + rec.param("piece_order", Value(std::string("centroid"))); OpRecord record = std::move(rec).take(); if (Recorder* recorder = current_recorder()) { std::vector ordered; diff --git a/src/cpp/src/ops/features/executors.cpp b/src/cpp/src/ops/features/executors.cpp index 83c54362..6a547999 100644 --- a/src/cpp/src/ops/features/executors.cpp +++ b/src/cpp/src/ops/features/executors.cpp @@ -155,8 +155,10 @@ void register_booleans(reactive::ExecutorRegistry& registry) { cut_rsolid(rest(in, 0, in.size()), {flag(p, "skip_non_intersecting"), text(p, "tracking_policy")})); }); registry.add("make_cut_rsolid_list", [](Params p, Inputs in, const ScalarValues&) { - return many( - cut_rsolid_list(rest(in, 0, in.size()), {flag(p, "skip_non_intersecting"), text(p, "tracking_policy")})); + CutOptions options{flag(p, "skip_non_intersecting"), text(p, "tracking_policy")}; + const Value* order = p.find("piece_order"); // absent on records made before ordered pieces + options.order_pieces = order != nullptr && order->is_string() && order->as_string() == "centroid"; + return many(cut_rsolid_list(rest(in, 0, in.size()), options)); }); registry.add("make_intersect_rsolid", [](Params, Inputs in, const ScalarValues&) { return one(intersect_rsolid(rest(in, 0, in.size()))); diff --git a/src/cpp/src/product/specs.cpp b/src/cpp/src/product/specs.cpp index b17a5190..cd9ec73c 100644 --- a/src/cpp/src/product/specs.cpp +++ b/src/cpp/src/product/specs.cpp @@ -36,12 +36,11 @@ void add_structure(Specs& s) { {"Internal placement validation failed."}, {"Report this as a SimpleCADAPI bug if it reproduces."}}); add(s, {"make_part_rpart", - "Failed to create the Part.", + "Failed to create the single-body Part.", {"The part_id is empty or uses unsupported characters.", "The body is not a Solid.", - "Neither or both of body and bodies were given, or a body_id is malformed or repeated.", "A Part with the same part_id already exists in the active GraphSession."}, {"Pass a stable part_id such as 'base_plate'.", - "Union solids that must become one body; pass bodies={id: solid} to keep several bodies apart.", + "Union intended multiple bodies into one Solid before creating the Part.", "Do not pass material to make_part_rpart; use assign_material_rpart instead."}}); add(s, {"assign_material_rpart", "Failed to assign the material to the Part.", diff --git a/src/cpp/tests/python/test_cut_rsolid_list.py b/src/cpp/tests/python/test_cut_rsolid_list.py index 20feedf6..a5d64de2 100644 --- a/src/cpp/tests/python/test_cut_rsolid_list.py +++ b/src/cpp/tests/python/test_cut_rsolid_list.py @@ -73,14 +73,23 @@ def test_one_piece_result_and_a_missing_tool(): def test_cut_rsolid_refuses_a_split_instead_of_dropping_pieces(): + # strict mode (on_split="error") keeps the old refusal; the default keeps every piece (see below) with pytest.raises(scad.SimpleCADError) as error: - scad.cut_rsolid(bar(), slot(0)) + scad.cut_rsolid(bar(), slot(0), on_split="error") text = str(error.value) assert "returned 2 solids" in text and "cut_rsolid_list" in text with pytest.raises(scad.SimpleCADError, match="no valid solid"): scad.cut_rsolid(plate(), cylinder(75)) +def test_cut_rsolid_keeps_a_split_as_pieces_ordered_by_centroid(): + pieces = scad.cut_rsolid(bar(), [slot(-20), slot(20)]) + assert isinstance(pieces, list) and len(pieces) == 3 + xs = [p.get_center().x for p in pieces] + assert xs == sorted(xs) + assert isinstance(scad.cut_rsolid(bar(), cylinder(3)), scad.Solid) # one piece: a Solid, as always + + def test_the_pieces_carry_the_cut_tags_and_one_graph_node(): with scad.GraphSession() as session: body = bar() diff --git a/src/cpp/tests/python/test_ops_features_booleans.py b/src/cpp/tests/python/test_ops_features_booleans.py index e4288c82..81527eac 100644 --- a/src/cpp/tests/python/test_ops_features_booleans.py +++ b/src/cpp/tests/python/test_ops_features_booleans.py @@ -118,5 +118,6 @@ def test_2d_booleans(): def test_signatures_match_python(): assert parameter_names(scad.union_rsolid) == ["solids", "clean", "glue", "tol", "tracking_policy"] # *solids - assert parameter_names(scad.cut_rsolid) == ["solids", "skip_non_intersecting", "tracking_policy"] # *solids + # on_split: a cut that splits the body returns its pieces by default (multi-body parts), "error" refuses + assert parameter_names(scad.cut_rsolid) == ["solids", "skip_non_intersecting", "tracking_policy", "on_split"] assert parameter_names(scad.boolean_rsolidlist) == ["left", "right", "operation"] diff --git a/src/simplecadapi/__init__.py b/src/simplecadapi/__init__.py index e0933786..c3d05d15 100644 --- a/src/simplecadapi/__init__.py +++ b/src/simplecadapi/__init__.py @@ -369,7 +369,15 @@ from .core import TaggedMixin from .errors import SimpleCADError from simplecadapi._glue.session import GraphSession from .operators import render_screenshot_rpath -from .product.bodies import BodyMass, MassReport, measure_part_mass_rmassreport, part_shape +from .product.bodies import ( + BodyMass, + BodyOverlap, + BodyOverlapWarning, + MassReport, + inspect_body_overlaps_rlist, + measure_part_mass_rmassreport, + part_shape, +) from .product.placement import Placement from .product.capture import CaptureResult, capture from .product.packages import ( @@ -583,6 +591,7 @@ __all__ = [ "solve_assembly_constraints_rassembly", "measure_constraint_residual_rconstraintresidual", "measure_part_mass_rmassreport", + "inspect_body_overlaps_rlist", "inspect_assembly_constraints_rconstraintreport", # Sketch construction and constraints "add_point_rsketch", diff --git a/src/simplecadapi/_glue/docstrings.json b/src/simplecadapi/_glue/docstrings.json index e731d947..fce4155f 100644 --- a/src/simplecadapi/_glue/docstrings.json +++ b/src/simplecadapi/_glue/docstrings.json @@ -144,7 +144,7 @@ "constrain_tangent_rsketch": "Constrain supported curves to be tangent on an explicit branch.\n\n``at_a``/``at_b`` select ``\"start\"`` or ``\"end\"`` for arc and\nB-spline endpoint tangency. Circle-circle tangency accepts\n``mode=\"external\"`` or ``mode=\"internal\"``.", "constrain_vertical_rsketch": "Constrain a sketch line to be vertical.", "convert_value": "Convert a finite numeric value between dimensionally compatible units.", - "cut_rsolid": "Compute the boolean difference of solids.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, tools with no meaningful intersection are\n ignored for interactive convenience. Graph replay records this flag and\n should use False for strict diagnostic workflows.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n\nReturns:\n Solid: The cut result solid.\n\nRaises:\n SimpleCADError: The cut produced no solid, or split the body into several\n (a slot through a bar). Use ``cut_rsolid_list`` to keep every piece.\n\nUsage:\n Accepts a base solid followed by one or more tool solids, including nested\n sequences, and returns a single `Solid`.", + "cut_rsolid": "Compute the boolean difference of solids.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, tools with no meaningful intersection are\n ignored for interactive convenience. Graph replay records this flag and\n should use False for strict diagnostic workflows.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n on_split: What a cut that splits the body (a slot through a bar) returns.\n ``\"pieces\"`` (default): every piece, as ``list[Solid]`` ordered by centroid\n (x, then y, then z), recorded like ``cut_rsolid_list``. ``\"error\"``: raise,\n for code that needs exactly one Solid.\n\nReturns:\n Solid: The cut result solid, when the result is one piece.\n list[Solid]: The pieces, when the cut split the body (``on_split=\"pieces\"``).\n Pass them on as bodies: ``make_part_rpart(part_id=..., body=pieces)`` makes the\n bodies ``body_1 .. body_n``, ``bodies={\"bar\": pieces}`` makes ``bar_1 .. bar_n``.\n\nRaises:\n SimpleCADError: The cut produced no solid, or (``on_split=\"error\"``) split\n the body. Use ``cut_rsolid_list`` to always get a list.\n\nUsage:\n Accepts a base solid followed by one or more tool solids, including nested\n sequences, and returns a single `Solid`.", "diagnose_blend_failure": "Classify a fillet/chamfer failure; never raises.\n\nProbe order (cheapest explanation wins):\n\n1. Tangent adjacency — the two faces meeting at a selected edge are\n already tangent (dihedral ~180°), so the blend surface degenerates to\n zero width regardless of size.\n2. Room — blend size exceeds the distance from the edge to the opposite\n boundary of an adjacent face.\n3. Interaction — per-edge diagnostic rerun (``retry_single``, capped at\n 64 edges) isolates edges that fail alone; when every edge passes\n alone but the joint blend fails, opposite blends on a shared face\n meeting tangentially (2×size >= face room) is the explanation.", "diagnose_boolean_failure": "Classify a boolean failure from its operands; never raises.\n\nModel: operands within ``tol`` of each other form one connected cluster\n(transitively). More than one cluster means the union is genuinely\nseparated — report the nearest inter-cluster pair. A single cluster that\nstill failed to fuse contains a touch-without-overlap pair — report it as\nnon-manifold contact. Returns None when no pair explains the failure.", "draft_rsolid": "Draft planar, cylindrical or conical faces by a signed angle in degrees.\n\nThe neutral plane fixes the unchanged section: the selected faces lean\ntoward or away from it. Its origin and normal are in current\ncoordinate-system coordinates. Face selection is checked against the input\nbody and retained as graph inputs for strict replay. The input solid is\npreserved, the output must be one valid solid, and a zero angle records an\nunchanged result. Other surface families are explicitly rejected.\n\nThe operation is recorded as ``make_draft_rsolid``; the body and selected\nfaces are ordered inputs, and the angle, neutral plane and face selection\nnodes are parameters, so model JSON replay is strict.\n\nArgs:\n solid: The body to draft.\n faces_to_draft: Faces of ``solid``, or a QL selector that picks them.\n angle: Draft angle in degrees, strictly between -90 and 90.\n plane_origin: A point of the neutral plane.\n plane_normal: Normal of the neutral plane; must be nonzero.\n\nReturns:\n The drafted solid.\n\nRaises:\n TypeError: ``solid`` is not a Solid.\n ValueError: Empty selection, a selection that is not made of faces of\n ``solid``, an unsupported surface family, a zero plane normal, or\n a nonfinite or out-of-range angle.\n\nExamples:\n import simplecadapi as scad\n from simplecadapi import ql\n body = scad.make_box_rsolid(10, 10, 10)\n right = ql.faces().where(ql.prop(\"geom.normal.x\", \">\", 0.9)).exactly(1)\n drafted = scad.draft_rsolid(body, right, angle=10)", @@ -225,7 +225,7 @@ "make_line_redge": "Create a straight edge between two points.", "make_material_rmaterial": "Create a material definition for later Part assignment.\n\nMaterial is deliberately separate from `make_part_rpart(...)`; the only\ncorrect workflow is to create a material and then assign it to a Part with\n`assign_material_rpart(...)`.", "make_nut_rsolid": "Create a nut along +Z with its bottom face on the Z=0 plane.\n\n``nut_style`` accepts ``hex``, ``square``, ``round``, and ``knurled``.\nThrough and blind holes are supported. Modeled thread detail adds internal\nV or trapezoidal helical teeth to a major-diameter hole.", - "make_part_rpart": "Wrap one Solid, or several named solids, as a semantic Part.\n\nArgs:\n part_id: Stable identifier of the part (``scad.notebook_id()`` in a notebook).\n body: The Solid of a one-body Part.\n name: Optional display name.\n bodies: Instead of ``body``: several solids kept apart in one Part, as a\n mapping ``body_id -> Solid`` (in its order) or a sequence of ``Body``\n values. Body ids are identifiers, unique within the part.\n\nReturns:\n Part: The new Part. ``part.bodies`` lists its bodies; ``part.body`` is the\n Solid of a one-body Part.\n\nRaises:\n SimpleCADError: Neither or both of ``body`` and ``bodies`` were given, a body\n is not a Solid, a body id is malformed or repeated, or the part_id is\n already used.\n\nUsage:\n ``scad.make_part_rpart(part_id=scad.notebook_id(), body=bracket)`` for one solid;\n ``scad.make_part_rpart(part_id=scad.notebook_id(), bodies={\"case\": case, \"lid\": lid})``\n for a case and its lid kept as two bodies of one part. Material applies to every\n body. Connectors are not supported on multi-body parts yet. Union the solids\n first when they must become one body.", + "make_part_rpart": "Wrap one Solid, or several named solids, as a semantic Part.\n\nArgs:\n part_id: Stable identifier of the part (``scad.notebook_id()`` in a notebook).\n body: The Solid of a one-body Part. The pieces of a split cut (a list of\n Solids) become the bodies ``body_1 .. body_n``.\n name: Optional display name.\n bodies: Instead of ``body``: several solids kept apart in one Part, as a\n mapping ``body_id -> Solid`` (in its order) or a sequence of ``Body``\n values. A mapping value may be the pieces of a split cut (a list of\n Solids): they become ``_1 .. _n``. Body ids are\n identifiers, unique within the part. Overlapping bodies are allowed;\n building the definition warns (``BodyOverlapWarning``).\n\nReturns:\n Part: The new Part. ``part.bodies`` lists its bodies; ``part.body`` is the\n Solid of a one-body Part.\n\nRaises:\n SimpleCADError: Neither or both of ``body`` and ``bodies`` were given, a body\n is not a Solid, a body id is malformed or repeated, or the part_id is\n already used.\n\nUsage:\n ``scad.make_part_rpart(part_id=scad.notebook_id(), body=bracket)`` for one solid;\n ``scad.make_part_rpart(part_id=scad.notebook_id(), bodies={\"case\": case, \"lid\": lid})``\n for a case and its lid kept as two bodies of one part. Material applies to every\n body. Connectors are not supported on multi-body parts yet. Union the solids\n first when they must become one body.", "make_periodic_spline_rwire": "Create a closed periodic spline wire interpolating the supplied points.", "make_placement_connector_rconnector": "Create a connector anchored to an explicit local placement frame.\n\nUse this when a datum should be defined by a stable coordinate frame\ninstead of a selected BREP face, edge, or vertex.", "make_placement_rplacement": "Create a canonical right-handed placement in the active workplane.", @@ -336,5 +336,6 @@ "var": "Create a physical or legacy scalar variable.\n\n``tolerance=0.1`` declares a symmetric ``+/-0.1`` tolerance. Use a\n``(lower_deviation, upper_deviation)`` pair for an asymmetric tolerance.\n``tolerance_unit`` defaults to ``unit`` when a nominal unit is declared.\nValues are converted to canonical CAD units only when evaluated, so the\ndeclaration and serialized expression node preserve the user's units.\n\nVariables without ``unit`` retain legacy unitless behavior. A unit-aware\nexpression cannot mix declared-unit variables with legacy variables.", "cut_rsolid_list": "Compute the boolean difference of solids and keep every piece.\n\nA cut can split the body (a slot through a bar leaves two parts) or consume it\n(a tool that encloses the whole body leaves nothing). ``cut_rsolid`` refuses\nsuch a result because it returns exactly one ``Solid``; this operator returns\nthem all. A tool is cut from every piece it meets, so several tools may split\na body into several parts.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, a tool that meets none of the current\n pieces is ignored; when False it raises.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n\nReturns:\n list[Solid]: Every piece of the cut, in kernel order; empty when the tools\n consume the base.\n\nRaises:\n SimpleCADError: An input is not a valid Solid, or the kernel could not\n compute the cut.\n\nUsage:\n ``pieces = cut_rsolid_list(bar, slot)`` returns both halves of a bar cut by\n a through slot. Use ``cut_rsolid`` when the result must be one solid.\n", "Body": "One named solid of a Part.\n\n``Body(body_id, solid, name=None)``: ``body_id`` is an identifier unique within\nthe part, ``solid`` the body's Solid, ``name`` an optional display name. A\none-body Part has one Body with the id ``\"body\"``.", - "measure_part_mass_rmassreport": "Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole.\n\nArgs:\n part: The Part to measure (one body or several).\n density: Density to use instead of the material's; ``None`` uses the\n Part's material, and without a material density every mass is ``None``.\n density_unit: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``,\n ``kg/mm^3`` or ``g/mm^3``.\n\nReturns:\n MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``,\n ``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part\n (``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``).\n\nRaises:\n SimpleCADError: The value is not a Part, or the density or its unit is invalid.\n\nUsage:\n ``scad.measure_part_mass_rmassreport(case).body(\"lid\").mass_kg`` is the mass of\n the lid body; ``.mass_kg`` the mass of the whole part. Every body has the\n Part's material." + "measure_part_mass_rmassreport": "Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole.\n\nArgs:\n part: The Part to measure (one body or several).\n density: Density to use instead of the material's; ``None`` uses the\n Part's material, and without a material density every mass is ``None``.\n density_unit: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``,\n ``kg/mm^3`` or ``g/mm^3``.\n\nReturns:\n MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``,\n ``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part\n (``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``).\n\nRaises:\n SimpleCADError: The value is not a Part, or the density or its unit is invalid.\n\nUsage:\n ``scad.measure_part_mass_rmassreport(case).body(\"lid\").mass_kg`` is the mass of\n the lid body; ``.mass_kg`` the mass of the whole part. Every body has the\n Part's material.", + "inspect_body_overlaps_rlist": "List the pairs of bodies of a Part that share volume.\n\nOverlapping bodies are allowed (a Part does not fuse them), but mass counts the\nshared volume once per body and STEP holds both copies. Bodies that only touch\n(a face, an edge or a point in common) do not overlap.\n\nArgs:\n part: The Part to inspect; a one-body Part has no overlaps.\n min_volume_mm3: Shared volume below which a pair is not reported.\n\nReturns:\n list[BodyOverlap]: ``(first, second, volume_mm3)`` per overlapping pair, in body order.\n\nRaises:\n SimpleCADError: The value is not a Part.\n\nUsage:\n ``scad.inspect_body_overlaps_rlist(case)`` before export. Building the part's\n definition (a notebook run, ``@part``, a package) warns with ``BodyOverlapWarning``\n for the same pairs." } diff --git a/src/simplecadapi/_glue/modules.json b/src/simplecadapi/_glue/modules.json index a1ef0bca..3822956e 100644 --- a/src/simplecadapi/_glue/modules.json +++ b/src/simplecadapi/_glue/modules.json @@ -188,6 +188,7 @@ "cut_rsolid": "simplecadapi.operators.boolean", "cut_rsolid_list": "simplecadapi.operators.boolean", "measure_part_mass_rmassreport": "simplecadapi.operators.product", +"inspect_body_overlaps_rlist": "simplecadapi.operators.product", "cut_shapes": "simplecadapi.kernel.ocp_booleans", "diagnose_blend_failure": "simplecadapi.operators._diagnostics", "diagnose_boolean_failure": "simplecadapi.operators._diagnostics", diff --git a/src/simplecadapi/artifacts/canonical.py b/src/simplecadapi/artifacts/canonical.py index 0b9d2269..1562ad51 100644 --- a/src/simplecadapi/artifacts/canonical.py +++ b/src/simplecadapi/artifacts/canonical.py @@ -14,6 +14,8 @@ from ..scene.canonical import canonical_json_bytes, parse_canonical_json, parse_ ARTIFACT_SCHEMA_VERSION = "2.0" PART_DEFINITION_PROFILE = "simplecad-part-definition-2" +# A multi-body part (solid_cache.bodies): a reader that knows only profile 2 refuses it instead of misreading it. +MULTI_BODY_PART_DEFINITION_PROFILE = "simplecad-part-definition-3" ASSEMBLY_DEFINITION_PROFILE = "simplecad-assembly-definition-2" SOLID_EVALUATOR_PROFILE = "ocp-evaluated-solid-1" TOPOLOGY_SNAPSHOT_PROFILE = "ocp-stable-topology-4" @@ -196,6 +198,7 @@ __all__ = [ "ArtifactLimits", "ArtifactValidationError", "DEFAULT_ARTIFACT_LIMITS", + "MULTI_BODY_PART_DEFINITION_PROFILE", "PART_DEFINITION_PROFILE", "SOLID_EVALUATOR_PROFILE", "TOPOLOGY_SNAPSHOT_PROFILE", diff --git a/src/simplecadapi/artifacts/part_definition.py b/src/simplecadapi/artifacts/part_definition.py index 81ad4d74..e254017d 100644 --- a/src/simplecadapi/artifacts/part_definition.py +++ b/src/simplecadapi/artifacts/part_definition.py @@ -5,6 +5,8 @@ A one-body part is what every PartDefinition was: ``solid_cache.body_ref`` is th one :class:`BodyRef` per body (its own BRep and topology snapshot, so each body keeps its tags), in body order. Its ``body_ref`` is then a BRep Compound of every body (what a geometry-only reader such as STEP needs, and what a reader that expects exactly one Solid refuses), and ``topology_snapshot_ref`` repeats the first body's snapshot. +A multi-body definition has profile ``simplecad-part-definition-3`` (``contracts/part-definition-3.schema.json``), so +a reader that knows only profile 2 refuses it; a one-body definition keeps profile 2 and its bytes. """ from __future__ import annotations @@ -15,6 +17,7 @@ from typing import Any, Mapping, Sequence from .canonical import ( ARTIFACT_SCHEMA_VERSION, + MULTI_BODY_PART_DEFINITION_PROFILE, PART_DEFINITION_PROFILE, ArtifactValidationError, canonical_bytes, @@ -163,6 +166,8 @@ class PartDefinition: "bodies_invalid", "/connectors", "connectors on a multi-body part are not supported yet" ) object.__setattr__(self, "bodies", bodies) + # a multi-body part is profile 3, so a profile-2 reader refuses it (one-body parts keep profile 2 and their bytes) + object.__setattr__(self, "profile", MULTI_BODY_PART_DEFINITION_PROFILE if bodies else PART_DEFINITION_PROFILE) if self.material_ref is not None and not isinstance( self.material_ref, MaterialRef ): diff --git a/src/simplecadapi/artifacts/validation.py b/src/simplecadapi/artifacts/validation.py index 41e9ae9a..7081110f 100644 --- a/src/simplecadapi/artifacts/validation.py +++ b/src/simplecadapi/artifacts/validation.py @@ -25,13 +25,16 @@ _SCHEMA_FILES = { "part_definition": "part-definition-2.schema.json", "assembly_definition": "assembly-definition-2.schema.json", } +# Part definitions of a multi-body part carry profile 3 and are validated by their own schema. +_PROFILE_SCHEMA_FILES = {"simplecad-part-definition-3": "part-definition-3.schema.json"} -@lru_cache(maxsize=2) -def _schema(kind: str) -> Mapping[str, Any]: +@lru_cache(maxsize=4) +def _schema(kind: str, profile: str | None = None) -> Mapping[str, Any]: if kind not in _ARTIFACT_KINDS: raise ArtifactValidationError("artifact_kind_invalid", "/artifact_kind", "unsupported artifact kind") - resource = files("simplecadapi").joinpath("contracts", _SCHEMA_FILES[kind]) + name = _PROFILE_SCHEMA_FILES.get(profile or "", _SCHEMA_FILES[kind]) if kind == "part_definition" else _SCHEMA_FILES[kind] + resource = files("simplecadapi").joinpath("contracts", name) schema = json.loads(resource.read_text(encoding="utf-8")) Draft202012Validator.check_schema(schema) return schema @@ -44,7 +47,7 @@ def _pointer(parts: Iterable[Any]) -> str: def _schema_validate(manifest: Mapping[str, Any], kind: str) -> None: errors = sorted( - Draft202012Validator(_schema(kind)).iter_errors(manifest), + Draft202012Validator(_schema(kind, manifest.get("profile") if isinstance(manifest.get("profile"), str) else None)).iter_errors(manifest), key=lambda item: (list(item.absolute_path), item.message), ) if errors: diff --git a/src/simplecadapi/build/definition.py b/src/simplecadapi/build/definition.py index 2afff099..a28b3b1b 100644 --- a/src/simplecadapi/build/definition.py +++ b/src/simplecadapi/build/definition.py @@ -72,7 +72,7 @@ from simplecadapi._cpp import ( suspend_graph_recording, ) from ..product.assembly import _AUTHORED_PLACEMENTS_RUNTIME_KEY, _component_occurrence_placements -from ..product.bodies import part_shape +from ..product.bodies import part_shape, warn_body_overlaps from ..product.placement import canonical_frame, placement_ticks from simplecadapi._glue.session import GraphSession, record_operation_if_active from ..recording.graph import attach_graph_node, attach_semantic_graph_node @@ -171,6 +171,7 @@ def _part_definition( body_blobs: dict[str, bytes] = {} body_refs: tuple[BodyRef, ...] = () if part.multi_body: + warn_body_overlaps(part, stacklevel=4) # allowed, but said once per build # every body keeps its own BRep and snapshot (its tags); the part's BRep is a Compound of all of them rows = [] for item in part.bodies: diff --git a/src/simplecadapi/contracts/part-definition-2.schema.json b/src/simplecadapi/contracts/part-definition-2.schema.json index 69c2ff17..0e2b0a9a 100644 --- a/src/simplecadapi/contracts/part-definition-2.schema.json +++ b/src/simplecadapi/contracts/part-definition-2.schema.json @@ -31,23 +31,7 @@ "required": ["evaluator_profile", "body_ref"], "properties": { "evaluator_profile": {"const": "ocp-evaluated-solid-1"}, - "body_ref": {"$ref": "#/$defs/blobRef"}, - "bodies": { - "type": "array", - "minItems": 2, - "maxItems": 10000, - "items": { - "type": "object", - "additionalProperties": false, - "required": ["body_id", "name", "body_ref", "topology_snapshot_ref"], - "properties": { - "body_id": {"type": "string", "minLength": 1, "maxLength": 128}, - "name": {"type": ["string", "null"]}, - "body_ref": {"$ref": "#/$defs/blobRef"}, - "topology_snapshot_ref": {"$ref": "#/$defs/blobRef"} - } - } - } + "body_ref": {"$ref": "#/$defs/blobRef"} } }, "topology_snapshot_ref": {"$ref": "#/$defs/blobRef"}, diff --git a/src/simplecadapi/contracts/part-definition-3.schema.json b/src/simplecadapi/contracts/part-definition-3.schema.json new file mode 100644 index 00000000..8c65b26f --- /dev/null +++ b/src/simplecadapi/contracts/part-definition-3.schema.json @@ -0,0 +1,129 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://simplecad.dev/schemas/part-definition-3.schema.json", + "title": "SimpleCAD PartDefinition 2.0, profile 3 (multi-body parts)", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "artifact_kind", "definition_kind", "definition_id", "revision", "content_hash", "units", "tolerance_profile", "profile", "generator", "definition", "solid_cache", "topology_snapshot_ref", "connectors", "material_ref", "file_inputs", "interface_hashes", "metadata"], + "properties": { + "schema_version": {"const": "2.0"}, + "artifact_kind": {"const": "part_definition"}, + "definition_kind": {"const": "single_solid"}, + "definition_id": {"$ref": "#/$defs/id"}, + "revision": {"$ref": "#/$defs/revision"}, + "content_hash": {"$ref": "#/$defs/hash"}, + "units": {"const": "mm"}, + "tolerance_profile": {"type": "string", "minLength": 1, "maxLength": 128}, + "profile": {"const": "simplecad-part-definition-3"}, + "generator": {"$ref": "#/$defs/generator"}, + "definition": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "feature_graph_ref"], + "properties": { + "kind": {"const": "feature_graph"}, + "feature_graph_ref": {"$ref": "#/$defs/blobRef"} + } + }, + "solid_cache": { + "type": "object", + "additionalProperties": false, + "required": ["evaluator_profile", "body_ref", "bodies"], + "properties": { + "evaluator_profile": {"const": "ocp-evaluated-solid-1"}, + "body_ref": {"$ref": "#/$defs/blobRef"}, + "bodies": { + "type": "array", + "minItems": 2, + "maxItems": 10000, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["body_id", "name", "body_ref", "topology_snapshot_ref"], + "properties": { + "body_id": {"type": "string", "minLength": 1, "maxLength": 128}, + "name": {"type": ["string", "null"]}, + "body_ref": {"$ref": "#/$defs/blobRef"}, + "topology_snapshot_ref": {"$ref": "#/$defs/blobRef"} + } + } + } + } + }, + "topology_snapshot_ref": {"$ref": "#/$defs/blobRef"}, + "connectors": {"type": "array", "maxItems": 100000, "items": {"$ref": "#/$defs/connector"}}, + "material_ref": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/materialRef"}]}, + "file_inputs": {"type": "array", "maxItems": 1024, "items": {"$ref": "#/$defs/fileInput"}}, + "interface_hashes": {"$ref": "#/$defs/interfaceHashes"}, + "metadata": {"type": "object"} + }, + "$defs": { + "id": {"type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[A-Za-z][A-Za-z0-9_.:-]*$"}, + "revision": {"type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[A-Za-z0-9][A-Za-z0-9._+-]*$"}, + "hash": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "path": {"type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^[A-Za-z0-9][A-Za-z0-9._/-]*$"}, + "vec3": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number"}}, + "frame": { + "type": "object", + "additionalProperties": false, + "required": ["origin", "x_axis", "y_axis", "z_axis"], + "properties": {"origin": {"$ref": "#/$defs/vec3"}, "x_axis": {"$ref": "#/$defs/vec3"}, "y_axis": {"$ref": "#/$defs/vec3"}, "z_axis": {"$ref": "#/$defs/vec3"}} + }, + "generator": { + "type": "object", + "additionalProperties": false, + "required": ["simplecadapi_version", "ocp_version", "python_abi", "platform_tag", "semantic_registry_version"], + "properties": { + "simplecadapi_version": {"$ref": "#/$defs/revision"}, + "ocp_version": {"$ref": "#/$defs/revision"}, + "python_abi": {"$ref": "#/$defs/revision"}, + "platform_tag": {"$ref": "#/$defs/revision"}, + "semantic_registry_version": {"$ref": "#/$defs/revision"} + } + }, + "blobRef": { + "type": "object", + "additionalProperties": false, + "required": ["path", "sha256", "byte_length", "media_type"], + "properties": { + "path": {"$ref": "#/$defs/path"}, + "sha256": {"$ref": "#/$defs/hash"}, + "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991}, + "media_type": {"type": "string", "minLength": 1, "maxLength": 128} + } + }, + "fileInput": { + "type": "object", + "additionalProperties": false, + "required": ["path", "byte_length", "sha256"], + "properties": {"path": {"$ref": "#/$defs/path"}, "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991}, "sha256": {"$ref": "#/$defs/hash"}} + }, + "materialRef": { + "type": "object", + "additionalProperties": false, + "required": ["material_id", "path", "revision", "sha256", "byte_length"], + "properties": {"material_id": {"$ref": "#/$defs/id"}, "path": {"$ref": "#/$defs/path"}, "revision": {"$ref": "#/$defs/revision"}, "sha256": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991}} + }, + "connector": { + "type": "object", + "additionalProperties": false, + "required": ["connector_id", "name", "anchor_kind", "local_frame", "binding", "interface_hash", "binding_hash"], + "properties": { + "connector_id": {"$ref": "#/$defs/id"}, + "name": {"type": ["string", "null"], "minLength": 1}, + "anchor_kind": {"enum": ["geometry", "placement"]}, + "local_frame": {"$ref": "#/$defs/frame"}, + "binding": {"type": ["object", "null"]}, + "interface_hash": {"$ref": "#/$defs/hash"}, + "binding_hash": {"$ref": "#/$defs/hash"} + } + }, + "hashMap": {"type": "object", "propertyNames": {"$ref": "#/$defs/id"}, "additionalProperties": {"$ref": "#/$defs/hash"}}, + "interfaceHashes": { + "type": "object", + "additionalProperties": false, + "required": ["geometry", "connectors", "bindings", "material"], + "properties": {"geometry": {"$ref": "#/$defs/hash"}, "connectors": {"$ref": "#/$defs/hashMap"}, "bindings": {"$ref": "#/$defs/hashMap"}, "material": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/hash"}]}} + } + } +} diff --git a/src/simplecadapi/operators/__init__.py b/src/simplecadapi/operators/__init__.py index e36b2b60..2b4929de 100644 --- a/src/simplecadapi/operators/__init__.py +++ b/src/simplecadapi/operators/__init__.py @@ -208,7 +208,7 @@ from . import boolean # noqa: F401 from . import transform # noqa: F401 from . import selection # noqa: F401 from . import product # noqa: F401 -from .product import measure_part_mass_rmassreport # Python-defined (product/bodies.py) +from .product import inspect_body_overlaps_rlist, measure_part_mass_rmassreport # Python-defined (product/bodies.py) from . import sketch # noqa: F401 __all__ = [ @@ -354,6 +354,7 @@ __all__ = [ "make_wire_from_sketch_rwire", "measure_constraint_residual_rconstraintresidual", "measure_part_mass_rmassreport", + "inspect_body_overlaps_rlist", "mirror_shape", "offset_rsolid", "place_component_rassembly", diff --git a/src/simplecadapi/operators/product.py b/src/simplecadapi/operators/product.py index c684d9b9..95389e13 100644 --- a/src/simplecadapi/operators/product.py +++ b/src/simplecadapi/operators/product.py @@ -41,7 +41,7 @@ from simplecadapi._cpp import ( solve_assembly_constraints_rassembly, unground_component_rassembly, ) -from ..product.bodies import measure_part_mass_rmassreport # Python: mass properties per body +from ..product.bodies import inspect_body_overlaps_rlist, measure_part_mass_rmassreport # Python-defined __all__ = [ "add_belt_constraint_rassembly", @@ -69,6 +69,7 @@ __all__ = [ "make_vertex_connector_rconnector", "measure_constraint_residual_rconstraintresidual", "measure_part_mass_rmassreport", + "inspect_body_overlaps_rlist", "place_component_rassembly", "set_public_connector_rassembly", "solve_assembly_constraints_rassembly", diff --git a/src/simplecadapi/product/bodies.py b/src/simplecadapi/product/bodies.py index 29442298..b2ac68b5 100644 --- a/src/simplecadapi/product/bodies.py +++ b/src/simplecadapi/product/bodies.py @@ -7,10 +7,12 @@ properties) walk ``part.bodies``. from __future__ import annotations +import warnings +from collections.abc import Mapping, Sequence from dataclasses import dataclass from typing import Any -from simplecadapi._cpp import Compound, Part, Solid +from simplecadapi._cpp import Compound, Part, Solid, make_part_rpart # density unit -> factor to kg/mm^3 (the model is in millimetres) _DENSITY_TO_KG_MM3 = { @@ -161,4 +163,112 @@ def measure_part_mass_rmassreport( ) -__all__ = ["BodyMass", "MassReport", "measure_part_mass_rmassreport", "part_shape"] +class BodyOverlapWarning(UserWarning): + """Two bodies of one Part share volume: mass counts it twice and STEP holds both copies.""" + + +@dataclass(frozen=True) +class BodyOverlap: + """Two bodies of a Part that share volume (mm^3).""" + + first: str + second: str + volume_mm3: float + + def to_dict(self) -> dict[str, Any]: + return {"first": self.first, "second": self.second, "volume_mm3": self.volume_mm3} + + +def _boxes_meet(a: tuple[float, ...], b: tuple[float, ...], tol: float) -> bool: + return all(a[axis] <= b[axis + 3] + tol and b[axis] <= a[axis + 3] + tol for axis in range(3)) + + +def inspect_body_overlaps_rlist(part: Part, *, min_volume_mm3: float = 1e-6) -> list[BodyOverlap]: + """List the pairs of bodies of a Part that share volume. + + Overlapping bodies are allowed (a Part does not fuse them), but mass counts the + shared volume once per body and STEP holds both copies. Bodies that only touch + (a face, an edge or a point in common) do not overlap. + + Args: + part: The Part to inspect; a one-body Part has no overlaps. + min_volume_mm3: Shared volume below which a pair is not reported. + + Returns: + list[BodyOverlap]: ``(first, second, volume_mm3)`` per overlapping pair, in body order. + + Raises: + SimpleCADError: The value is not a Part. + + Usage: + ``scad.inspect_body_overlaps_rlist(case)`` before export. Building the part's + definition (a notebook run, ``@part``, a package) warns with ``BodyOverlapWarning`` + for the same pairs. + """ + + import simplecadapi._cpp._native as native + + if not isinstance(part, Part): + raise TypeError("part must be a Part") + occt = native._occt + bodies = list(part.bodies) + boxes = [body.solid._bounds() for body in bodies] + out: list[BodyOverlap] = [] + for i in range(len(bodies)): + for j in range(i + 1, len(bodies)): + if not _boxes_meet(boxes[i], boxes[j], 1e-7): + continue + common = occt.BRepAlgoAPI_Common(bodies[i].solid.wrapped, bodies[j].solid.wrapped).Shape() + props = occt.GProp_GProps() + occt.BRepGProp.VolumeProperties_s(common, props) + volume = float(props.Mass()) + if volume > min_volume_mm3: + out.append(BodyOverlap(bodies[i].body_id, bodies[j].body_id, volume)) + return out + + +def warn_body_overlaps(part: Part, *, stacklevel: int = 2) -> list[BodyOverlap]: + """Warn (``BodyOverlapWarning``) once per overlapping pair of bodies of *part*; returns the pairs.""" + + if not part.multi_body: + return [] + overlaps = inspect_body_overlaps_rlist(part) + for item in overlaps: + warnings.warn( + f"part {part.part_id!r}: bodies {item.first!r} and {item.second!r} overlap by {item.volume_mm3:.6g} mm^3 " + "(mass counts it twice; union them, or cut one from the other, if they are one piece of material)", + BodyOverlapWarning, + stacklevel=stacklevel, + ) + return overlaps + + +def part_from_bodies(part_id: str, bodies: Mapping[str, Solid | Sequence[Solid]], *, name: str | None = None) -> Part: + """The Part of named solids, the way a notebook names them: one name and one Solid is a one-body Part (body id + ``"body"``); otherwise every name is a body, and the pieces of a split cut (a list) are ``_1 .. _n``. + + This is the rule of an implicit product (a ``kind = "part"`` notebook without a ``make_part_rpart`` cell: its open + bodies, by variable name) and of an editor product cell with several bodies. + """ + + items = dict(bodies) + if not items: + raise ValueError("a Part needs at least one body") + if len(items) == 1: + (value,) = items.values() + if isinstance(value, Solid) or (isinstance(value, (list, tuple)) and len(value) == 1): + return make_part_rpart(part_id=part_id, body=value, name=name) + return make_part_rpart(part_id=part_id, bodies=items, name=name) + + +__all__ = [ + "BodyMass", + "BodyOverlap", + "BodyOverlapWarning", + "MassReport", + "inspect_body_overlaps_rlist", + "measure_part_mass_rmassreport", + "part_from_bodies", + "part_shape", + "warn_body_overlaps", +] diff --git a/src/simplecadapi/recording/serializer.py b/src/simplecadapi/recording/serializer.py index 310bc0d5..2fecdf54 100644 --- a/src/simplecadapi/recording/serializer.py +++ b/src/simplecadapi/recording/serializer.py @@ -353,6 +353,10 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = { "status": "diagnostic", "reason": "Measures current constraint residuals without changing model state.", }, + "inspect_body_overlaps_rlist": { + "status": "diagnostic", + "reason": "Reports which bodies of a Part share volume without changing model state.", + }, "measure_part_mass_rmassreport": { "status": "diagnostic", "reason": "Measures volume and mass of each body without changing model state.", @@ -3791,14 +3795,22 @@ def _execute_graph( f"Graph node '{node.node_id}' ({op_name}) requires at least two inputs" ) continue - result = ops.cut_rsolid_list( - cast(Solid, inputs[0]), - [cast(Solid, tool) for tool in inputs[1:]], - skip_non_intersecting=bool( + cut_options = { + "skip_non_intersecting": bool( _param(ctx, node.node_id, op_name, params, "skip_non_intersecting", False) ), - tracking_policy=str(params.get("tracking_policy", "full")), - ) + "tracking_policy": str(params.get("tracking_policy", "full")), + } + if params.get("piece_order") == "centroid": + # a split recorded by cut_rsolid(on_split="pieces"): the pieces in centroid order + pieces = ops.cut_rsolid( + cast(Solid, inputs[0]), [cast(Solid, tool) for tool in inputs[1:]], **cut_options + ) + result = pieces if isinstance(pieces, list) else [pieces] + else: + result = ops.cut_rsolid_list( + cast(Solid, inputs[0]), [cast(Solid, tool) for tool in inputs[1:]], **cut_options + ) _store_outputs(node, result) continue diff --git a/test/test_multi_body_part.py b/test/test_multi_body_part.py index 6f8fc471..8c9d1a08 100644 --- a/test/test_multi_body_part.py +++ b/test/test_multi_body_part.py @@ -244,5 +244,91 @@ class TestMultiBodyNotebook(NotebookTestCase): self.assertEqual(definition.bodies, ()) +class TestSplitCutsAndOverlaps(unittest.TestCase): + """Owner decisions: a splitting cut is not refused; overlapping bodies warn but are allowed.""" + + @staticmethod + def _bar_and_slot() -> tuple[scad.Solid, scad.Solid]: + return scad.make_box_rsolid(40.0, 10.0, 10.0, tag_prefix="bar"), scad.make_box_rsolid(4.0, 20.0, 20.0, (0.0, -5.0, -5.0)) + + def test_a_splitting_cut_returns_its_pieces_in_centroid_order(self) -> None: + bar, slot = self._bar_and_slot() + pieces = scad.cut_rsolid(bar, slot) + self.assertIsInstance(pieces, list) + self.assertEqual([round(p.get_center().x, 6) for p in pieces], [-11.0, 11.0]) + with self.assertRaisesRegex(Exception, "split the body"): + scad.cut_rsolid(*self._bar_and_slot(), on_split="error") + + def test_pieces_become_bodies(self) -> None: + bar, slot = self._bar_and_slot() + pieces = scad.cut_rsolid(bar, slot) + self.assertEqual(scad.make_part_rpart(part_id="bar", body=pieces).body_ids(), ("body_1", "body_2")) + lid = _lid() + part = scad.make_part_rpart(part_id="bar", bodies={"bar": pieces, "lid": lid}) + self.assertEqual(part.body_ids(), ("bar_1", "bar_2", "lid")) + self.assertAlmostEqual(part.get_body("bar_2").solid.get_volume(), 1800.0, places=6) + + def test_a_split_replays_with_the_same_piece_order(self) -> None: + with scad.GraphSession() as session: + bar, slot = self._bar_and_slot() + scad.make_part_rpart(part_id="bar", body=scad.cut_rsolid(bar, slot)) + (part,) = [x for x in scad.replay_model_json(scad.export_model_json(session)) if isinstance(x, scad.Part)] + self.assertEqual(part.body_ids(), ("body_1", "body_2")) + self.assertLess(part.get_body("body_1").solid.get_center().x, part.get_body("body_2").solid.get_center().x) + + def test_overlaps_are_reported_and_warned_not_refused(self) -> None: + a = scad.make_box_rsolid(10.0, 10.0, 10.0) + b = scad.make_box_rsolid(10.0, 10.0, 10.0, (5.0, 0.0, 0.0)) + c = scad.make_box_rsolid(10.0, 10.0, 10.0, (15.0, 0.0, 0.0)) # touches b only along a face + part = scad.make_part_rpart(part_id="stack", bodies={"a": a, "b": b, "c": c}) + overlaps = scad.inspect_body_overlaps_rlist(part) + self.assertEqual([(o.first, o.second) for o in overlaps], [("a", "b")]) + self.assertAlmostEqual(overlaps[0].volume_mm3, 500.0, places=6) + + @scad.part(id="stack") + def stack() -> scad.Part: + return scad.make_part_rpart( + part_id="stack", + bodies={"a": scad.make_box_rsolid(10.0, 10.0, 10.0), "b": scad.make_box_rsolid(10.0, 10.0, 10.0, (5.0, 0.0, 0.0))}, + ) + + with self.assertWarns(scad.BodyOverlapWarning): + result = stack() + self.assertEqual([item.body_id for item in result.definition.bodies], ["a", "b"]) + + def test_part_from_bodies_is_the_implicit_part_rule(self) -> None: + from simplecadapi.product.bodies import part_from_bodies + + one = part_from_bodies("plate", {"plate": _base()}) + self.assertEqual(one.body_ids(), ("body",)) + bar, slot = self._bar_and_slot() + split = part_from_bodies("bar", {"bar": scad.cut_rsolid(bar, slot)}) + self.assertEqual(split.body_ids(), ("bar_1", "bar_2")) + both = part_from_bodies("case", {"base": _base(), "lid": _lid()}) + self.assertEqual(both.body_ids(), ("base", "lid")) + + +class TestProfileThree(unittest.TestCase): + def test_a_multi_body_definition_is_profile_3_and_a_profile_2_reader_refuses_it(self) -> None: + from simplecadapi.artifacts.canonical import ArtifactValidationError + from simplecadapi.artifacts.validation import _schema_validate, validate_manifest + + @scad.part(id="case") + def case() -> scad.Part: + return _case() + + manifest = case().definition.to_dict() + self.assertEqual(manifest["profile"], "simplecad-part-definition-3") + validate_manifest(manifest) # this SDK reads it + with self.assertRaises(ArtifactValidationError): # what an SDK that knows only profile 2 does + _schema_validate({**manifest, "profile": "simplecad-part-definition-2"}, "part_definition") + + @scad.part(id="plate") + def plate() -> scad.Part: + return scad.make_part_rpart(part_id="plate", body=_base()) + + self.assertEqual(plate().definition.to_dict()["profile"], "simplecad-part-definition-2") + + if __name__ == "__main__": unittest.main()