diff --git a/design-docs/multi-solid-design.md b/design-docs/multi-solid-design.md new file mode 100644 index 00000000..c7ef0e3b --- /dev/null +++ b/design-docs/multi-solid-design.md @@ -0,0 +1,385 @@ +# 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. 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 + +**A Part holds an ordered set of named bodies. A body is a Solid with an id that is unique within its part. +A one-body Part is the special case that every existing Part already is.** + +- `make_part_rpart(part_id=..., bodies={"base": base, "lid": lid})` makes a part with two bodies. + `make_part_rpart(part_id=..., body=solid)` is unchanged. +- `part.bodies` returns `(Body, ...)` in order. `part.get_body("lid")` returns one body and `part.body_ids()` returns the ids. +- `part.body` keeps returning the Solid of a one-body part. On a multi-body part it raises a `TypeError` that names the + bodies. It never silently returns the first body: a caller that reads `part.body` would otherwise export, weigh or + draw only part of the part. +- A Body is product geometry and nothing more. It has no placement, joint, constraint or connector of its own in + stage 1. Anything that moves relative to something else is a component of an Assembly. This is the line every + surveyed CAD system draws (see section 3): Fusion says it outright, and SolidWorks says "one part = one BOM line". +- Construction solids, tool solids and "kept for a later boolean" solids are **not bodies**. They stay plain notebook + values, as they are today. The product is exactly what the product cell puts into the Part. This one rule covers + "tool bodies that must stay hidden" with no `visible` flag in the data model: hiding is an editor view state, and + being part of the product is a modelling fact. + +Why not a `Compound` inside the Part: a Compound is a new shape root and drops the tags of the solids it is built from +(verified: `scad.Compound([a, b])` of two tagged boxes has no face tags; SDK_DEFECTS.md #21). Each body therefore stays +its own Solid root, with its own tags, lineage, graph node and topology snapshot. A Compound appears only as a +geometry view (`scad.part_shape(part)`), for consumers that do not care which body a face belongs to (STEP, STL, +MJCF). + +Why not "a part studio of several Parts" (Onshape style): that would make each body a separate product definition +with its own `part_id`, BOM line and package unit. That is a real feature, but it is a different one: it amounts to +"one notebook, several products". This design keeps one product per notebook. + +## 2. The data model today (evidence) + +| Piece | Where | One-solid assumption | +|---|---|---| +| `Part` (C++) | `src/cpp/include/scad/product/part.hpp:19` (before), `part.cpp` | `Solid body_` field. Header comment: "exactly one Solid" | +| `make_part_rpart` | `bindings/python/bind_product.cpp:81`, `src/product/ops_structure.cpp:105` | `typed(body)`. Docstring: "Wrap exactly one Solid" | +| guidance | `src/cpp/src/product/specs.cpp:43` | "Union intended multiple bodies into one Solid before creating the Part." | +| `Solid` | `src/cpp/src/topo/shape.cpp:15` | the kind is checked, so a `Solid` is exactly one `TopoDS_Solid` | +| `Compound` | `include/scad/topo/shape.hpp:290` | `solids()`. A new root, so the tags of its parts are lost (#21) | +| solid lists | `cut_rsolid_list`, `boolean_rsolidlist`, `*_pattern_rsolidlist` | `list[Solid]` values in the notebook. Never a product | +| `cut_rsolid` | `src/cpp/src/ops/features/booleans.cpp:372` | refuses a split result (since bd36d58) | +| assembly flatten | `src/cpp/src/product/ops_projection.cpp:20` | `part->body()` | +| session children | `src/simplecadapi/_glue/session.py:53` | `yield item.body` | +| cell cache | `runtime/cache.py:255` (`_semantic_state`) | "A Part is its body" | +| pickling | `_glue/values.py` `_reduce` | rebuilds `Part(part_id, body, ...)` from attributes (#22) | +| `@part` builder | `build/part_builder.py:43` | "must return exactly one Solid or one Part" (still true: one Part) | +| PartDefinition | `artifacts/part_definition.py:30`, schema `contracts/part-definition-2.schema.json` | "exactly one evaluated Solid": one `solid_cache.body_ref`, one `topology_snapshot_ref` | +| definition build | `build/definition.py:169-225` | BRep, snapshot, geometry hash and validation of `part.body` | +| BRep reader | `artifacts/brep.py:44` `read_brep_solid` | "BRep root must be exactly one Solid" | +| part archive load | `artifacts/part_io.py:93` | `read_brep_solid` | +| materialize | `artifacts/assembly_io.py:762` | `Part(body=read_brep_solid(...))` | +| package blob roles | `product/packages.py:180` | one body and one topology blob per part | +| live preview | `scene/preview.py:271` (`compile_preview`) | one `PreviewNode` per part, `entity///` | +| package scene | `scene/product_scene.py:322`, `:822` (`_camera`) | one GLB and one entity document per part | +| legacy scene | `scene/compiler.py:330, 339, 697, 928` | `part.body`. "a standalone Compound must contain exactly one solid" | +| prewarm | `scene/prewarm.py:39` | one body per part | +| STEP | `exporter/step.py:76` | `"shape": value.body` | +| STL / surface mesh | `exporter/_surface_mesh.py:45` | `(value.body,)` | +| MJCF | `exporter/mjcf.py:680` | `part.body` | +| definition kind | 20 places | `"single_solid"`. The kind name means "a part" (#23) | +| editor features | `feat/gui-modeling:src/simplecadapi/editor/features.py:677` `_with_combine` | "A part holds one solid": every new solid must join, cut or intersect, or start the body | +| editor product | `feat/gui-modeling:.../gui_features.py:99, 489` | the product cell is `make_part_rpart(..., body=)`, re-pointed after each feature | +| editor defaults | `gui_features.py:_defaults` | `operation = "join" if last is not None else "new"` ("do not leave a second") | +| editor-web | `editor-web/src/components/NotebookList.tsx:155` | "a notebook that builds one solid" | + +The editor already tracks the "open bodies" of a notebook: solids that no later feature consumed +(`gui_features.py:129`). Today only one of them reaches the product. A multi-body part is the missing link between +"open bodies" and the product. + +## 3. Other CAD systems + +The research used primary documentation read in a browser. V means read on the page. I means inferred or not +confirmed. + +- **Onshape Part Studio.** One feature list "drives the shape of multiple parts" (V, + cad.onshape.com/help/Content/PartStudio/part_studios.htm). Each part is its own BOM item. Features choose + New / Add / Remove / Intersect with a merge scope; when several touching parts are ambiguous the user must choose, + and an empty scope is an error (V, .../extrude.htm). Boolean has "Keep tools", and a merge keeps the name of the + first-selected part (V, .../boolean.htm). Mass properties are additive, overlaps count twice, and parts without a + material are left out (V, .../View/mass_properties_tool.htm). Several parts export to one file by default (V, + .../File/exporting_files.htm). A composite part groups bodies into one BOM line (V, .../composite_part.htm). +- **SolidWorks multibody part.** "Part documents can contain multiple solid bodies", kept in a Solid Bodies folder, + each with its own name and colour (V, help.solidworks.com/2024 .../c_Multibody_Overview.htm). "One part (multibody + or not) should represent one part number in a Bill of Materials", and bodies are "not dynamic" (V, + .../c_Multibody_Parts_Vs_Assemblies.htm). Material is set per part; a per-body material overrides it (V, + .../c_multibody_materials.htm). Extrude has "Merge result"; without it the feature creates a distinct solid body + (V, .../r_extrude_propertymanager.htm). Feature Scope limits which bodies a feature touches (V). Combine does + Add / Subtract / Common (V). Mass properties exclude hidden bodies unless asked (V, + .../hidd_massproperty_text_dlg.htm). Export offers all bodies or selected bodies (V); Save Bodies writes each body + to its own part and can build an assembly (V, .../hidd_dve_feat_split.htm). +- **Autodesk Fusion.** "A Body is a single container for a contiguous 3D shape". Components hold bodies, and "you + cannot create joints or motion between bodies" (V, help.autodesk.com ...GUID-C1AB4941...). Extrude operations are + Join / Cut / Intersect / New Body / New Component (V, ...SLD-REF-EXTRUDE). Combine has a target, tool bodies and + "Keep Tools" (V, ...SLD-COMBINE). Per-body material and appearance are inferred (I). +- **FreeCAD.** A PartDesign Body "is intended to hold a single contiguous solid", and 1.0 adds an experimental + "Allow Compound" (V, wiki.freecad.org/PartDesign_Body). Part Compound groups shapes, and a compound whose members + touch or intersect "is invalid for Boolean operations", which is not checked (V, .../Part_Compound). PartDesign + Boolean pulls tool bodies into the active body and hides them (V, .../PartDesign_Boolean). +- **CadQuery / build123d.** `combine=False` keeps a new solid apart. Results are Compounds, and `.Solids()` lists them + (V, cadquery.readthedocs.io .../workplane.html). build123d modes are ADD / SUBTRACT / INTERSECT / REPLACE / PRIVATE. + `BuildPart.part` "may contain more than one shape" (V, build123d.readthedocs.io .../build_part.html). STEP export + carries a label and colour per node, and repeated labels are numbered (V, .../import_export.html). + +What this design takes from them: + +1. A body is named geometry inside one product item (every system). +2. "New body" is an explicit per-feature choice beside join/cut/intersect, and an ambiguous target is an error, never a + guess (Onshape, SolidWorks, Fusion). +3. A boolean between bodies says whether it consumes its tools, and the result keeps the name of the target body + (Onshape, Fusion). +4. Mass is the sum over bodies, with explicit rules for overlaps and missing material (Onshape, SolidWorks). +5. A multi-body part exports as one product holding several solids, with an option to split it (SolidWorks, Onshape). +6. A bare compound is not a body set. It must not quietly become the input of a boolean (FreeCAD). + +## 4. Design + +### 4.1 Body + +```text +Body(body_id: identifier, solid: Solid, name: str | None = None) +``` + +- **Identity.** `body_id` is unique within its part and has the same rules as a `part_id` (`validate_identifier`). In a + notebook it is normally the name of the variable or feature slug that produced the solid ("base", "lid"). A one-body + Part has one Body with the id `"body"` (`kDefaultBodyId`). +- **Order.** Bodies keep the order they are given in, which is the order of the dict. Order is part of the product: + it decides the STEP solid order and the order of the scene nodes. +- **Names.** `name` is an optional display name. +- **Colour** (stage 2). An optional `color` on Body, an appearance only, exported as the STEP colour of that solid. +- **Material** (stage 3). The part material applies to every body. A per-body material override follows + SolidWorks' rule: the body material wins, and bodies without one inherit the part's. Mass already reads density per + body (`measure_part_mass_rmassreport`), so stage 3 only changes where the density comes from. +- **Visibility.** None in the product. See section 1: a hidden tool is not a body. + +### 4.2 API + +Stage 1, implemented: + +| Name | Kind | Notes | +|---|---|---| +| `scad.Body(body_id, solid, name=None)` | value | C++ `scad::product::Body`. Pickles | +| `scad.make_part_rpart(part_id, body=None, name=None, *, bodies=None)` | op | exactly one of `body` / `bodies`. `bodies` is `{id: Solid}` or `[Body, ...]`. Recorded with one `body` input per body and `params.bodies = [{body_id, name}]`. Replays | +| `scad.Part(..., bodies=...)` | ctor | same rule. ValueError for no bodies, a duplicate `body_id`, or connectors on several bodies | +| `Part.bodies`, `Part.multi_body`, `Part.body_ids()`, `Part.get_body(id)` | read | | +| `Part.body` | read | the Solid of a one-body part. TypeError on a multi-body part | +| `scad.part_shape(part)` | helper | the Solid, or a Compound of every body (a geometry view, no tags) | +| `scad.measure_part_mass_rmassreport(part, *, density=None, density_unit=None)` | op (diagnostic) | per body: `volume_mm3`, `mass_kg`, `centroid_mm`; plus totals. Density comes from the material or from the arguments | + +Stage 2, proposed (each one an SDK op, so agents and the editor call the same thing): + +- `add_body_rpart(part, body_id, solid, name=None) -> Part` and `remove_body_rpart(part, body_id) -> Part`: the + functional edits the editor's bodies list needs, in the style of `add_connector_rpart`. +- `split_rpart(part, body_ids=None) -> Assembly` ("Save Bodies"): one component per body, with identity placements + and part ids `_`. This is the explicit exit from bodies to an assembly when the bodies need motion. +- `cut_rsolid_list` naming help: pieces come out in kernel order, which is not stable across OCCT versions. A + `bodies_from_pieces(prefix, pieces)` that orders pieces by centroid (x, then y, then z) gives stable ids + `piece_1..n` for "a part with disjoint pieces after a cut". + +Stage 3, proposed: + +- `combine_bodies_rpart(part, target, tools, operation="join"|"cut"|"intersect", keep_tools=False) -> Part`. The + result keeps the target's `body_id` (Onshape's rule). Consumed tools leave the part. It is needed only when a Part + arrives without its notebook (an imported multi-solid STEP). In a notebook, bodies are still plain solids before the + product cell, and `union_rsolid(base, lid)` is already "combine". A part is the end of the pipeline, not a workspace. +- Per-body material and colour (4.1). +- Connectors on multi-body parts: a connector anchor names `body_id` plus the entity within that body. The + `GeometryRef` and the binding checks in `build/definition.py` then run per body. + +### 4.3 Booleans between named bodies + +In a notebook, bodies are named before they meet the product, so booleans between them are ordinary operators on +named solids. The rules the editor and the docs follow: + +- Join, cut and intersect consume their inputs as they do today. A consumed solid is no longer an "open body", so it + leaves the product's bodies at the next re-point (4.4). +- "Keep tools" is the default behaviour of a functional SDK anyway: the tool variable still exists. Whether it stays + a body is the product cell's choice, and the editor offers that choice explicitly. +- `cut_rsolid` keeps refusing a split. `cut_rsolid_list` keeps every piece, and those pieces become bodies through + `bodies={...}` (stage 2 helper above). +- Overlapping bodies are allowed, as in SolidWorks and Onshape. Mass counts every body whole, which is the Onshape + rule, and the report says so. A stage-2 diagnostic `check_bodies_disjoint` (pairwise common volume) can warn before + export. Whether `make_part_rpart` should refuse overlaps is an open question for the owner (section 7). + +### 4.4 Editor UX (the editor only adapts SDK ops) + +- **Bodies list.** The product cell becomes the list. `make_part_rpart(part_id=..., bodies={"base": base, "lid": lid})` + is parsed like `_PRODUCT_BODY` today, with one row per entry. A notebook with one body keeps writing `body=...`, so + existing notebooks are untouched. +- **Operation choice.** Each combinable feature keeps join / cut / intersect / new body. The changes: + - "New body" becomes a real choice. The feature makes a new open body, and the editor adds it to the product's + bodies with `add_body_rpart` semantics (an edit of the dict literal in the product cell). + - The default stays "join" when a body exists (Onshape's default is New only for the first feature, too). The help + text no longer says "a part holds one solid". + - "Combine with" stays an explicit body choice. When more than one body exists the target has no default: the form + asks, which is Onshape's rule for an ambiguous merge. +- **Re-pointing.** `_repoint_product` today swaps the one body name. With bodies it does the same for the dict entry + whose solid the new feature consumed, and keeps the `body_id`. A body keeps its id while it is joined, cut and + filleted, the way a SolidWorks body keeps its name through features. +- **Construction solids.** Open solids that are not in the bodies dict are listed under "Construction", drawn ghosted + and never exported. That covers tool bodies and solids kept for a later boolean, with no flag in the product. +- **Viewer.** Preview nodes are `node//body:`, and entities are `entity//body://`. The + scene tree shows the part with its bodies as children (`node_kind: "solid"`, which the scene schema and + `editor-web/src/scene/scene2.ts:27` already accept). Picking a face says which body it belongs to. +- **Assemblies stay separate.** Assembly documents (`assembly_doc.py`) keep placing Parts. A multi-body part is one + component there. "Make components from bodies" is `split_rpart`. + +### 4.5 Export, mass, preview, package + +- **Live preview** (`scene/preview.py`, implemented): one node per body, all at the part's placement. The part key + includes the body id, so two equal-shaped bodies stay two entity namespaces. `entity_info` understands the `body:` + segment. +- **Package** (`PartDefinition`, implemented): + - A one-body part writes the same manifest bytes as before, so its content hash is unchanged. + - A multi-body part adds `solid_cache.bodies = [{body_id, name, body_ref, topology_snapshot_ref}]`, one BRep and + one snapshot per body, so every body keeps its tags. + - `solid_cache.body_ref` is then a BRep Compound of every body. That is what a geometry-only reader needs, and what a + reader that expects exactly one Solid refuses (`read_brep_solid`), so old readers fail closed instead of dropping + bodies. + - `topology_snapshot_ref` repeats the first body's snapshot, because the schema requires it. + - The geometry interface hash covers `[{body_id, geometry}]`. + - Validation (`validate_artifact_blobs`, package blob roles, `part_io`) covers every body blob and checks that the + Compound holds as many solids as there are bodies. +- **Package scene** (`scene/product_scene.py`, implemented): the part node has no geometry. Each body is a child node + of kind `solid` with its own GLB and entity document, `node_id` `node//body:`. The camera frames every + body. +- **STEP** (implemented): one PRODUCT whose shape holds every body. The test checks one `PRODUCT(` and two + `MANIFOLD_SOLID_BREP`. Stage 2 writes the body name and colour on each solid (an XCAF sub-shape label), as + build123d does. +- **STL / MJCF** (implemented): every body goes into the mesh. In MJCF a multi-body part is one rigid body with one + mesh, which is correct because bodies never move apart. +- **Mass** (implemented): `measure_part_mass_rmassreport`. Totals are sums; the centroid is volume-weighted. +- **Cell cache** (implemented): `Part` pickles with its bodies (`_glue/values.py` `_ARGUMENTS`), and the + semantic-state guard watches every body (`runtime/cache.py`). +- **Legacy `scene/compiler.py`** (`compile_scene` / `export_scene`): not converted. A multi-body part raises the + `Part.body` TypeError there (stage 2). + +### 4.6 Boundary with assemblies + +| | Bodies of one Part | Components of an Assembly | +|---|---|---| +| Product items / BOM lines | one | one per component | +| Placement | none (bodies share the part frame) | per component | +| Joints / constraints / motion | never | yes | +| Connectors | per part (stage 3: anchored on one body) | per part, public per assembly | +| Material | part (stage 3: per-body override) | per part | +| From one to the other | `split_rpart` (stage 2) | `make_compound_from_assembly_rcompound` flattens (every body of every part) | + +## 5. Staged plan + +1. **Stage 1, done in this spike:** Body, `Part.bodies`, `make_part_rpart(bodies=...)` with recording and replay, + pickling and cache, live preview, package format, package scene, STEP, STL and MJCF geometry, assembly flattening, + and the mass report. One-body parts are unchanged byte for byte. +2. **Stage 2:** + - Editor: bodies list, a real "New body", construction group, re-pointing by `body_id`. + - `add_body_rpart`, `remove_body_rpart`, `split_rpart`, ordered piece naming, `check_bodies_disjoint`. + - STEP body names and colours. + - `scene/compiler.py`. + - Body colour. + - Skill docs: when to use bodies and when to use an assembly. +3. **Stage 3:** + - Per-body material. + - Connectors on a body. + - `combine_bodies_rpart` for parts without a notebook (STEP import with several solids becomes a multi-body Part + instead of an error). + - Rename the `single_solid` definition kind at the next package schema bump. + +## 6. Risks + +- **Silent partial readers.** Any code still reading `part.body` raises on a multi-body part. That is loud, not + silent, but it is a runtime failure on paths no test covers, e.g. `scene/compiler.py:330` and the translators. The + `grep '\.body\b'` list in section 2 is the checklist. +- **Package compatibility.** A package with `solid_cache.bodies` validates under the same `part-definition-2` profile. + An old SDK reading it fails at `read_brep_solid` (Compound root) or at the closed schema (`additionalProperties: + false` on `solid_cache`), which is the right failure. A profile bump to `part-definition-3` would make the change + explicit, at the cost of every reader (open question). +- **Body id stability.** The ids come from the notebook. If a person renames a variable, the body is renamed with it. + Pieces of `cut_rsolid_list` arrive in kernel order (stage-2 helper). +- **Overlaps.** Overlapping bodies make mass and FEM meaningless and STEP ambiguous. The policy is open (section 7). +- **Editor complexity.** Re-pointing a dict entry is more state than swapping one name. The bodies list must stay a + parse of the product cell, never a second store. + +## 7. Open questions for the owner + +1. May `make_part_rpart(bodies=...)` refuse overlapping or touching bodies (FreeCAD's warning), or only warn through a + diagnostic? The spike allows overlaps. +2. Should the package profile move to `part-definition-3`, or does the additive `solid_cache.bodies` under profile 2 + stay (the spike's choice, which keeps one-body hashes)? +3. Should the default body id of a one-body part stay `"body"`, or should it be the notebook variable name? The + 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. (Decided, section 9: splits are kept as pieces by default.) Should `cut_rsolid` keep refusing splits? + +## 8. The spike + +- **C++:** + - `include/scad/product/part.hpp`, `src/product/part.cpp`: Body, the bodies of a Part, the `body()` TypeError. + - `src/product/ops_structure.cpp`: the `make_part_rpart` overload and its record. + - `src/product/ops_projection.cpp`: assembly flattening takes every body. + - Bindings: `bind_product_values.cpp`, `bind_product.cpp`, `bind_product_args.hpp` (`body_list`). +- **Python:** + - `product/bodies.py`: `part_shape`, `measure_part_mass_rmassreport`. + - `_glue/values.py`, `_glue/session.py`, `runtime/cache.py`. + - `artifacts/part_definition.py` (`BodyRef`), `artifacts/part_io.py` (`read_part_bodies`), `artifacts/assembly_io.py`, + `artifacts/validation.py`, `contracts/part-definition-2.schema.json`. + - `build/definition.py`, `product/packages.py`. + - `scene/preview.py`, `scene/product_scene.py`, `scene/prewarm.py`. + - `exporter/step.py`, `exporter/_surface_mesh.py`, `exporter/mjcf.py`. + - `recording/serializer.py` (replay and the diagnostic row). + - Docs, stubs and `docstrings.json` / `modules.json` registration. +- **Tests:** `test/test_multi_body_part.py`, 20 tests: + - value rules; + - pickle and deepcopy with tags; + - connectors refused; + - assembly flattening; + - graph replay; + - mass per body and totals; + - preview nodes and entity namespaces, including two equal-shaped bodies; + - a notebook run twice, with every cell after setup cached and the same content hash; + - a package that round-trips with tags per body; + - 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 39b88717..b3d7cf7e 100644 --- a/docs/skill/references/discipline/notebook-cell-design.md +++ b/docs/skill/references/discipline/notebook-cell-design.md @@ -86,11 +86,15 @@ depends only on the parameters it reads, so many parameters in one cell cost nothing; a geometry line in the params cell would re-run with every parameter change. -**C9. A part notebook (`kind = "part"`) leaves exactly one open body; the -runtime makes the Part from it.** Write a product cell (last, id -`scad.notebook_id()`) only for connectors, a material, or a body that is not -the last; an assembly notebook ends with its layout cell. A family of parts -uses `scad.use(path, id=...)`. +**C9. A part notebook (`kind = "part"`) needs no product cell: the runtime +makes the Part from its open bodies** (each public top-level solid no other cell +reads becomes a body named by its variable; the pieces of a split cut become +`_1..n`). Write the product cell (last, id `scad.notebook_id()`) only for +connectors, a material, or to choose and name the bodies yourself: +`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. An +assembly notebook ends with its layout cell. A family of parts uses +`scad.use(path, id=...)`. **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/Body.md b/docs/skill/references/docs/api/Body.md new file mode 100644 index 00000000..75b51a89 --- /dev/null +++ b/docs/skill/references/docs/api/Body.md @@ -0,0 +1,21 @@ +# Body + +## Class Definition + +```python +class Body(body_id, solid, name=None) +``` + +*Source: product/part.py* + +## Import Surface + +- top-level: `from simplecadapi import Body` + +## Description + +One named solid of a Part. + +``Body(body_id, solid, name=None)``: ``body_id`` is an identifier unique within +the part, ``solid`` the body's Solid, ``name`` an optional display name. A +one-body Part has one Body with the id ``"body"``. diff --git a/docs/skill/references/docs/api/Part.md b/docs/skill/references/docs/api/Part.md index 13ea84da..52b6bc33 100644 --- a/docs/skill/references/docs/api/Part.md +++ b/docs/skill/references/docs/api/Part.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class Part(part_id, body, name=None, material=None, connectors=()) +class Part(part_id, body=None, name=None, material=None, connectors=(), bodies=None) ``` *Source: product/part.py* @@ -14,4 +14,11 @@ class Part(part_id, body, name=None, material=None, connectors=()) ## Description -Single-body product item wrapping exactly one Solid. +Product item holding one Solid (``body``) or several named bodies (``bodies``). + +A one-body Part is the common case: ``part.body`` is its Solid. A multi-body +Part keeps several solids apart inside one product item (a case and its lid +modelled side by side, the pieces of a split cut): ``part.bodies`` lists them +as ``Body`` values in order, ``part.get_body(body_id)`` finds one, and +``part.body`` raises ``TypeError``. Bodies of one Part are never placed +relative to each other and carry no joints; use an Assembly for that. diff --git a/docs/skill/references/docs/api/README.md b/docs/skill/references/docs/api/README.md index ec9753d8..0e66cd26 100644 --- a/docs/skill/references/docs/api/README.md +++ b/docs/skill/references/docs/api/README.md @@ -316,6 +316,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Other - [Assembly](Assembly.md) *(from product/assembly.py)* `top-level` +- [Body](Body.md) *(from product/part.py)* `top-level` - [CaptureResult](CaptureResult.md) *(from product/capture.py)* `top-level` - [Component](Component.md) *(from product/assembly.py)* `top-level` - [Connector](Connector.md) *(from product/connector.py)* `top-level` @@ -396,6 +397,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_rsketchcrossings](inspect_sketch_rsketchcrossings.md) *(from operators/sketch.py)* `top-level` - [inspect_sketch_rsketchprofiles](inspect_sketch_rsketchprofiles.md) *(from operators/sketch.py)* `top-level` - [inspect_sketch_rsketchresult](inspect_sketch_rsketchresult.md) *(from operators/sketch.py)* `top-level` @@ -404,6 +406,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi - [load_brep_region_rshell](load_brep_region_rshell.md) *(from operators/geometry.py)* `top-level` - [load_brep_region_rsolid](load_brep_region_rsolid.md) *(from operators/geometry.py)* `top-level` - [measure_constraint_residual_rconstraintresidual](measure_constraint_residual_rconstraintresidual.md) *(from operators/product.py)* `top-level` +- [measure_part_mass_rmassreport](measure_part_mass_rmassreport.md) *(from operators/product.py)* `top-level` - [meta](meta.md) *(from ql.py)* `submodule:ql` - [not_](not_.md) *(from ql.py)* `submodule:ql` - [offset_rsolid](offset_rsolid.md) *(from operators/features.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 99d53ff1..719955ec 100644 --- a/docs/skill/references/docs/api/make_part_rpart.md +++ b/docs/skill/references/docs/api/make_part_rpart.md @@ -3,7 +3,7 @@ ## API Definition ```python -def make_part_rpart(part_id, body, name=None) +def make_part_rpart(part_id, body=None, name=None, bodies=None) ``` *Source: operators/product.py* @@ -14,4 +14,41 @@ def make_part_rpart(part_id, body, name=None) ## Description -Wrap exactly one Solid as a semantic single-body Part. +Wrap one Solid, or several named solids, as a semantic Part. + +``scad.make_part_rpart(part_id=scad.notebook_id(), body=bracket)`` for one solid; +``scad.make_part_rpart(part_id=scad.notebook_id(), bodies={"case": case, "lid": lid})`` +for a case and its lid kept as two bodies of one part. Material applies to every +body. Connectors are not supported on multi-body parts yet. Union the solids +first when they must become one body. + +## Parameters + +### part_id + +- **Description**: Stable identifier of the part (``scad.notebook_id()`` in a notebook). + +### body + +- **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 + +- **Description**: Optional display name. + +### 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. 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 + +Part: The new Part. ``part.bodies`` lists its bodies; ``part.body`` is the +Solid of a one-body Part. + +## Raises + +- **SimpleCADError**: Neither or both of ``body`` and ``bodies`` were given, a body is not a Solid, a body id is malformed or repeated, or the part_id is already used. diff --git a/docs/skill/references/docs/api/measure_part_mass_rmassreport.md b/docs/skill/references/docs/api/measure_part_mass_rmassreport.md new file mode 100644 index 00000000..5068c3fa --- /dev/null +++ b/docs/skill/references/docs/api/measure_part_mass_rmassreport.md @@ -0,0 +1,45 @@ +# measure_part_mass_rmassreport + +## API Definition + +```python +def measure_part_mass_rmassreport(part: 'Part', *, density: 'float | None' = None, density_unit: 'str | None' = None) -> 'MassReport' +``` + +*Source: operators/product.py* + +## Import Surface + +- top-level: `from simplecadapi import measure_part_mass_rmassreport` + +## Description + +Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole. + +``scad.measure_part_mass_rmassreport(case).body("lid").mass_kg`` is the mass of +the lid body; ``.mass_kg`` the mass of the whole part. Every body has the +Part's material. + +## Parameters + +### part + +- **Description**: The Part to measure (one body or several). + +### density + +- **Description**: Density to use instead of the material's; ``None`` uses the Part's material, and without a material density every mass is ``None``. + +### density_unit + +- **Description**: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``, ``kg/mm^3`` or ``g/mm^3``. + +## Returns + +MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``, +``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part +(``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``). + +## Raises + +- **SimpleCADError**: The value is not a Part, or the density or its unit is invalid. 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 d7044d64..0b3086aa 100644 --- a/docs/skill/references/docs/guides/notebook-runtime.md +++ b/docs/skill/references/docs/guides/notebook-runtime.md @@ -81,12 +81,13 @@ if __name__ == "__main__": - **The kind** is fixed when the notebook is made: the header says `kind = "part"` or `kind = "assembly"` (`sca new` and the editor write it). A `kind = "part"` notebook needs **no product cell**: when no top-level - `Part` has the notebook id, the runtime makes one from the notebook's one - *open body* (a public top-level `Solid` that no other cell reads and that no - other such solid was built from) with the notebook id. Several open bodies - are an error that names them: join them, or write the Part cell yourself. + `Part` has the notebook id, the runtime makes one from the notebook's + *open bodies* (public top-level `Solid`s, or the piece lists of split cuts, + that no other cell reads and that no other such value was built from), with + the notebook id. One open body is a one-body Part (body id `"body"`); several + are the bodies of one Part, named by their variables (pieces `_1..n`). Write a `make_part_rpart` cell only to add connectors or a material, or to - ship a body other than the last one; it then wins. The headless run and the + choose and name the bodies yourself; it then wins. The headless run and the editor use the same rule (`runtime/projection.py`, `find_product`). - **The product** is the top-level variable whose id (`Part.part_id` or `Assembly.assembly_id`) equals the notebook id. An assembly built up over @@ -97,6 +98,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 caffc0c2..23c18f09 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/editor-collaboration.md b/docs/skill/references/domains/editor-collaboration.md index 88ae1a64..14501d4d 100644 --- a/docs/skill/references/domains/editor-collaboration.md +++ b/docs/skill/references/domains/editor-collaboration.md @@ -221,7 +221,8 @@ HOLE_DIAMETER = scad.var(name="hole_diameter", default=6.0, unit="mm", comment=" geometry second, with the count checked (`.exactly(n)`). If the model moved so that nothing matches, the cell fails and the feature turns red: ask the person to pick again, never widen the selector until it matches. - A blank notebook (`sca new NAME --kind blank`) has no cells and a `kind = "part"` header: no product cell is written, - the runtime makes the Part from the open body (see `docs/guides/notebook-runtime.md`), so every new feature previews + the runtime makes the Part from the open bodies (see `docs/guides/notebook-runtime.md`; a solid made with "New body" + is one more body of the same Part, not an assembly), so every new feature previews and a deleted cell cannot leave the notebook without a product. Setting connectors (or "use as product" on a body that is not the last) writes an explicit `make_part_rpart` cell, which then wins. - Besides the curated features (box, hole, pull face, extrude of a sketch ...), every SDK and standard-library operation 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/editor-web/src/components/FeatureTree.tsx b/editor-web/src/components/FeatureTree.tsx index 8b37e112..792ea230 100644 --- a/editor-web/src/components/FeatureTree.tsx +++ b/editor-web/src/components/FeatureTree.tsx @@ -115,7 +115,8 @@ export function FeatureTree({ {state.features.map((feature) => { const spec = feature.gui ? catalog?.specs.find((item) => item.id === feature.gui?.spec) : undefined; const problem = errorText(feature); - const isProduct = state.product !== null && feature.makes.includes(state.product.body); + const productBodies = state.product ? (state.product.bodies ?? [state.product.body]) : []; + const isProduct = feature.makes.some((name) => productBodies.includes(name)); const canEdit = Boolean(feature.gui && spec); const sketch = sketches?.infos.find((info) => info.cell === feature.cell); const hiddenSketch = sketch ? sketches?.hidden.has(sketch.name) : false; diff --git a/editor-web/src/lib/features.ts b/editor-web/src/lib/features.ts index 2cd87d04..90b4184e 100644 --- a/editor-web/src/lib/features.ts +++ b/editor-web/src/lib/features.ts @@ -67,7 +67,7 @@ export type FeatureState = { open: string[]; tip: string | null; /** The body the notebook's Part is built from: by a product cell, or (`implicit`, no cell) by the runtime from the open body. */ - product: { cell: string | null; body: string; implicit?: boolean } | null; + product: { cell: string | null; body: string; bodies?: string[]; implicit?: boolean } | null; defaults: Record>; /** The face-making sketches of the notebook (what a `profile` slot chooses from). */ profiles?: { name: string; plane: string | { origin: number[]; x_axis: number[]; y_axis: number[] }; normal: string; normal_vec?: [number, number, number] }[]; diff --git a/examples/SDK_DEFECTS.md b/examples/SDK_DEFECTS.md index 85338595..b5939c39 100644 --- a/examples/SDK_DEFECTS.md +++ b/examples/SDK_DEFECTS.md @@ -412,6 +412,62 @@ that surfaced it is in brackets. deprecation path), and `Scalar` for the chamfer angle so it records an expression like the other parameters. +## 27. `Compound([solids])` silently drops the solids' tags [multi-solid research] + +- **Symptom:** `scad.Compound([a, b])` of two tagged boxes has no face tags; + `compound._copy_semantic_state_from(a)` copies nothing either. +- **Trigger:** any code that bundles solids into a Compound and later selects + by tag (the first multi-body spike stored a part's bodies as one Compound). +- **Root cause:** a Compound is a new shape root with its own entity registry; + the semantic state of the input roots is not carried over, and the copy + helper only works within one root. +- **Status:** open. Multi-body parts keep their bodies as separate Solid roots + (`Part.bodies`), so they are not affected; `product.bodies.part_shape` + documents that its Compound is a geometry view without tags. +- **Fix direction:** either carry tags into a Compound built from tagged + roots (sub-shapes are shared, so the mapping is exact), or refuse + `_copy_semantic_state_from` across roots instead of doing nothing. + +## 28. Value pickling reads constructor arguments back by attribute name [multi-solid research] + +- **Symptom:** adding `Part(bodies=...)` broke pickling of multi-body parts: + the reducer called `part.body`, which (rightly) raises for several bodies. +- **Trigger:** any product value whose constructor parameter is not a plain + readable attribute of the same name. +- **Root cause:** `_glue/values.py` parses the parameter names out of the + pybind11 `__init__` docstring and reads each back with `getattr`. +- **Status:** worked around: `_ARGUMENTS` maps a class to per-parameter + readers (Part: `body`/`bodies`). +- **Fix direction:** give the C++ values an explicit `__getstate__`/ + `py::pickle` (as `ql` selectors have) instead of docstring parsing. + +## 29. "One solid per definition" is spelled into ids and kinds [multi-solid research] + +- **Symptom:** a second body of a part has nowhere to live in the existing + names: entity ids are `entity///` with root-local + topo ids (every body has a `face_0`), preview nodes are one per part, and + the definition kind is called `single_solid` (about 20 places in Python). +- **Trigger:** any part with more than one solid. +- **Root cause:** "is a part" and "has one solid" were the same fact until + now. +- **Status:** worked around: bodies get an id segment `body:` + (`entity//body:/...`, `node//body:`), one-body parts + keep their old ids byte for byte; the kind stays `single_solid`. +- **Fix direction:** treat `single_solid` as the name of the part kind (rename + at the next package schema bump) and keep the `body:` segment the only + way to address a body. + +## 30. 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 dce6be68..00f7fa6e 100644 --- a/src/cpp/bindings/python/bind_ops_features.cpp +++ b/src/cpp/bindings/python/bind_ops_features.cpp @@ -32,34 +32,35 @@ using scad::pybind::Vector3; // ---- what the signatures say ------------------------------------------------------------------------------------ // The parameters below that the binding reads as a Python object (and checks itself, with its own errors) print these. -#define SCAD_SIGNATURE_NAME(Tag, text) \ - struct Tag { \ - static constexpr auto name = pybind11::detail::const_name(text); \ - } -SCAD_SIGNATURE_NAME(EdgesTag, +// SCAD_SIGNATURE_NAME and the vocabulary are in semantic_types.hpp; these name what the operations here accept. +#define SCAD_SIGNATURE_TEXT(Tag, text) SCAD_SIGNATURE_NAME(Tag, pybind11::detail::const_name(text)) +SCAD_SIGNATURE_TEXT(EdgesTag, "collections.abc.Iterable[simplecadapi._cpp._native.Edge] | " "simplecadapi._cpp._native.ql.ShapeSelector"); -SCAD_SIGNATURE_NAME(FacesTag, +SCAD_SIGNATURE_TEXT(FacesTag, "collections.abc.Iterable[simplecadapi._cpp._native.Face] | " "simplecadapi._cpp._native.ql.ShapeSelector"); -SCAD_SIGNATURE_NAME(LoftSectionsTag, +SCAD_SIGNATURE_TEXT(LoftSectionsTag, "collections.abc.Iterable[simplecadapi._cpp._native.Wire | simplecadapi._cpp._native.Vertex]"); -SCAD_SIGNATURE_NAME(SweepSectionsTag, +SCAD_SIGNATURE_TEXT(SweepSectionsTag, "collections.abc.Iterable[simplecadapi._cpp._native.Face | simplecadapi._cpp._native.Wire]"); -SCAD_SIGNATURE_NAME(ShapesTag, "collections.abc.Iterable[simplecadapi._cpp._native.Shape]"); -SCAD_SIGNATURE_NAME(SolidsTag, "collections.abc.Iterable[simplecadapi._cpp._native.Solid]"); -SCAD_SIGNATURE_NAME(TargetTag, +SCAD_SIGNATURE_TEXT(ShapesTag, "collections.abc.Iterable[simplecadapi._cpp._native.Shape]"); +SCAD_SIGNATURE_TEXT(SolidsTag, "collections.abc.Iterable[simplecadapi._cpp._native.Solid]"); +SCAD_SIGNATURE_TEXT(TargetTag, "simplecadapi._cpp._native.Solid | collections.abc.Iterable[simplecadapi._cpp._native.Solid]"); -SCAD_SIGNATURE_NAME(FaceOperandTag, "simplecadapi._cpp._native.Face"); -SCAD_SIGNATURE_NAME(BinormalTag, "simplecadapi._cpp._native.Wire | simplecadapi.types.Direction3 | None"); -SCAD_SIGNATURE_NAME(FactorsTag, "collections.abc.Sequence[float | Expr]"); +SCAD_SIGNATURE_TEXT(FaceOperandTag, "simplecadapi._cpp._native.Face"); +SCAD_SIGNATURE_TEXT(BinormalTag, "simplecadapi._cpp._native.Wire | simplecadapi.types.Direction3 | None"); +SCAD_SIGNATURE_TEXT(FactorsTag, "collections.abc.Sequence[float | Expr]"); // A TrackingPolicy member or its value. -SCAD_SIGNATURE_NAME(PolicyTag, "typing.Literal['full', 'graph'] | simplecadapi._cpp.TrackingPolicy"); +SCAD_SIGNATURE_TEXT(PolicyTag, "typing.Literal['full', 'graph'] | simplecadapi._cpp.TrackingPolicy"); // The name of the mode, or an enum member with that name (build123d's Until). -SCAD_SIGNATURE_NAME(UntilTag, "typing.Literal['NEXT', 'LAST', 'PREVIOUS', 'FIRST'] | enum.Enum"); -SCAD_SIGNATURE_NAME(HandednessTag, "typing.Literal['Right', 'Left']"); -SCAD_SIGNATURE_NAME(OffsetKindTag, "typing.Literal['ARC', 'INTERSECTION']"); -SCAD_SIGNATURE_NAME(SetOperationTag, "typing.Literal['cut', 'intersect', 'union']"); +SCAD_SIGNATURE_TEXT(UntilTag, "typing.Literal['NEXT', 'LAST', 'PREVIOUS', 'FIRST'] | enum.Enum"); +SCAD_SIGNATURE_TEXT(HandednessTag, "typing.Literal['Right', 'Left']"); +// cut_rsolid: what a cut that splits the body gives (every piece, or an error), and what it returns. +SCAD_SIGNATURE_TEXT(OnSplitTag, "typing.Literal['pieces', 'error']"); +SCAD_SIGNATURE_TEXT(SolidOrPiecesTag, "simplecadapi._cpp._native.Solid | list[simplecadapi._cpp._native.Solid]"); +SCAD_SIGNATURE_TEXT(OffsetKindTag, "typing.Literal['ARC', 'INTERSECTION']"); +SCAD_SIGNATURE_TEXT(SetOperationTag, "typing.Literal['cut', 'intersect', 'union']"); #undef SCAD_SIGNATURE_NAME using EdgesOrQuery = AnyOf; @@ -577,12 +578,21 @@ void bind_booleans(py::module_& m) { m.def( "cut_rsolid", - [](const py::args& solids, bool skip_non_intersecting, const Policy& tracking_policy) { + [](const py::args& solids, bool skip_non_intersecting, const Policy& tracking_policy, + const Choice& on_split) -> AnyOf { 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.value == "error") + return {py::cast(unlocked(false, [&] { return cut_rsolid(operands, options); }))}; + if (on_split.value != "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 f55928b4..2751c404 100644 --- a/src/cpp/bindings/python/bind_product.cpp +++ b/src/cpp/bindings/python/bind_product.cpp @@ -38,6 +38,12 @@ SCAD_SIGNATURE_NAME(DirectionOrNone, scad::pybind::DirectionTag::name + kOrNone) SCAD_SIGNATURE_NAME(Directions, const_name("dict[str, ") + scad::pybind::DirectionTag::name + const_name("] | None")); SCAD_SIGNATURE_NAME(Weights, const_name("dict[str, float | Expr] | None")); SCAD_SIGNATURE_NAME(Solid, type_name()); +// make_part_rpart: one Solid, or the pieces of a split cut (each a body), or several named bodies. +SCAD_SIGNATURE_NAME(SolidOrPieces, type_name() + kOr + const_name("collections.abc.Sequence[") + + type_name() + const_name("] | None")); +SCAD_SIGNATURE_NAME(Bodies, const_name("dict[str, ") + type_name() + kOr + + const_name("collections.abc.Sequence[") + type_name() + + const_name("]] | None")); SCAD_SIGNATURE_NAME(Face, type_name()); SCAD_SIGNATURE_NAME(Edge, type_name()); SCAD_SIGNATURE_NAME(Vertex, type_name()); @@ -69,6 +75,8 @@ using DirectionOrNoneArg = AnyOf; using DirectionsArg = AnyOf; using WeightsArg = AnyOf; using SolidArg = AnyOf; +using SolidOrPiecesArg = AnyOf; +using BodiesArg = AnyOf; using FaceArg = AnyOf; using EdgeArg = AnyOf; using VertexArg = AnyOf; @@ -145,14 +153,27 @@ void bind_structure(py::module_& m) { m.def( "make_part_rpart", - [](const TextArg& part_id, const SolidArg& body, const NameArg& name) { + [](const TextArg& part_id, const SolidOrPiecesArg& body, const NameArg& name, const BodiesArg& bodies) { return guard_operation("make_part_rpart", [&] { + 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 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.value[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)); }); }, - py::arg("part_id"), py::arg("body"), py::arg("name") = py::none(), - "Wrap exactly one Solid as a semantic single-body Part."); + py::arg("part_id"), py::arg("body") = py::none(), py::arg("name") = py::none(), py::arg("bodies") = py::none(), + "Wrap one Solid (body) or several named solids (bodies) as a semantic Part."); m.def( "assign_material_rpart", [](const PartArg& part, const MaterialArg& material) { diff --git a/src/cpp/bindings/python/bind_product_args.hpp b/src/cpp/bindings/python/bind_product_args.hpp index 7589c7b4..cbe8ddf4 100644 --- a/src/cpp/bindings/python/bind_product_args.hpp +++ b/src/cpp/bindings/python/bind_product_args.hpp @@ -52,6 +52,47 @@ inline sp::OptionalString optional_name(const py::object& value) { return py::str(value).cast(); } +// 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); + add_bodies(out, text(py::reinterpret_borrow(pair[0]), "body_id"), + py::reinterpret_borrow(pair[1])); + } + return out; + } + if (py::isinstance(value) || !py::isinstance(value)) + throw scad::TypeError("bodies must be a mapping body_id -> Solid or a sequence of Body values"); + for (const py::handle item : value) { + out.push_back(typed(py::reinterpret_borrow(item), + "bodies must be a mapping body_id -> Solid or a sequence of Body values")); + } + return out; +} + inline scad::Scalar scalar(const py::object& value, const char* field) { try { return value.cast(); diff --git a/src/cpp/bindings/python/bind_product_values.cpp b/src/cpp/bindings/python/bind_product_values.cpp index 798edd6c..f26823fa 100644 --- a/src/cpp/bindings/python/bind_product_values.cpp +++ b/src/cpp/bindings/python/bind_product_values.cpp @@ -424,9 +424,24 @@ void bind_constraints(py::module_& m) { void bind_part(py::module_& m) { using namespace sp; - py::class_ cls(m, "Part", "Single-body product item wrapping exactly one Solid."); + py::class_(m, "Body", "One named solid of a Part; a multi-body Part keeps several apart.") + .def(py::init([](const py::object& body_id, const py::object& solid, const py::object& name) { + return std::make_shared(text(body_id, "body_id"), typed(solid, "solid must be a Solid"), + optional_name(name)); + }), + py::arg("body_id"), py::arg("solid"), py::arg("name") = py::none()) + .def_property_readonly("body_id", &Body::body_id) + .def_property_readonly("solid", &Body::solid) + .def_property_readonly("name", [](const Body& self) { return optional_object(self.name()); }) + .def("to_dict", [](const Body& self) { return self.to_dict(); }) + .def("__repr__", [](const Body& self) { + return "Body(body_id=" + str_repr(self.body_id()) + ", name=" + opt_str_repr(self.name()) + ")"; + }); + + py::class_ cls( + m, "Part", "Product item holding one Solid (`body`) or several named bodies (`bodies`), never placed apart."); cls.def(py::init([](const py::object& part_id, const py::object& body, const py::object& name, - const py::object& material, const py::object& connectors) { + const py::object& material, const py::object& connectors, const py::object& bodies) { std::optional material_value; if (!material.is_none()) material_value = typed(material, "material must be a Material"); @@ -437,13 +452,30 @@ void bind_part(py::module_& m) { "connectors must contain Connector values")); } } + 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() || 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"), optional_name(name), material_value, std::move(connector_values)); }), - py::arg("part_id"), py::arg("body"), py::arg("name") = py::none(), py::arg("material") = py::none(), - py::arg("connectors") = py::tuple()) + py::arg("part_id"), py::arg("body") = py::none(), py::arg("name") = py::none(), + py::arg("material") = py::none(), py::arg("connectors") = py::tuple(), py::arg("bodies") = py::none()) + .def_property_readonly("bodies", [](const Part& self) { return to_tuple(self.bodies()); }) + .def_property_readonly("multi_body", &Part::multi_body) + .def("body_ids", [](const Part& self) { return to_tuple(self.body_ids()); }) + .def( + "get_body", [](const Part& self, const py::object& id) { return self.get_body(text(id, "body_id")); }, + py::arg("body_id")) .def_property_readonly("part_id", &Part::part_id) - .def_property_readonly("body", &Part::body) + .def_property_readonly("body", &Part::body, "The Solid of a one-body Part; TypeError for a multi-body Part.") .def_property_readonly("name", [](const Part& self) { return optional_object(self.name()); }) .def_property_readonly( "material", 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/include/scad/product/operators.hpp b/src/cpp/include/scad/product/operators.hpp index ab6e44a6..05e30063 100644 --- a/src/cpp/include/scad/product/operators.hpp +++ b/src/cpp/include/scad/product/operators.hpp @@ -39,6 +39,8 @@ Placement make_placement_rplacement(const Scalar3& origin, const Scalar3& x_axis Placement identity_placement_rplacement(); PartPtr make_part_rpart(const std::string& part_id, const Solid& body, const OptionalString& name = {}); +// A Part of several named bodies, kept apart (no boolean between them), in this order. +PartPtr make_part_rpart(const std::string& part_id, const std::vector& bodies, const OptionalString& name = {}); PartPtr assign_material_rpart(const Part& part, const Material& material); // ---- connectors ------------------------------------------------------------------------------------- diff --git a/src/cpp/include/scad/product/part.hpp b/src/cpp/include/scad/product/part.hpp index 469e1a9c..ac83ce51 100644 --- a/src/cpp/include/scad/product/part.hpp +++ b/src/cpp/include/scad/product/part.hpp @@ -1,5 +1,9 @@ -// A Part: exactly one Solid, with an optional material and its connector datums +// A Part: one or more named bodies (Solids), with an optional material and its connector datums // (product/part.py). Values are immutable: every `with_*` returns a new Part. +// +// A one-body Part is what every Part was before multi-body parts: `body()` is its Solid. A multi-body +// Part keeps several solids apart inside one product item (bodies of one part are not components: they +// have no placements, joints or constraints between them). See design-docs/multi-solid-design.md. #pragma once #include @@ -16,14 +20,45 @@ namespace scad::product { +// One named solid of a Part. The body id is a stable identifier within its Part ("base", "lid"). +class Body { + public: + // ValueError for a malformed id or an empty name. + Body(std::string body_id, Solid solid, OptionalString name = {}); + + const std::string& body_id() const noexcept { return body_id_; } + const Solid& solid() const noexcept { return solid_; } + const OptionalString& name() const noexcept { return name_; } + + Value to_dict() const; // {"body_id", "name"} (the solid is geometry, not a dict field) + + private: + std::string body_id_; + Solid solid_; + OptionalString name_; +}; + +// The body id of a Part made from one Solid. +inline constexpr const char* kDefaultBodyId = "body"; + class Part : public SemanticValue { public: // ValueError for a malformed id, an empty name, or duplicate connector ids. Part(std::string part_id, Solid body, OptionalString name = {}, std::optional material = {}, std::vector connectors = {}); + // A Part of several bodies, in this order. ValueError for no bodies, duplicate body ids, or connectors on + // more than one body (connectors of a multi-body part are not supported yet). + Part(std::string part_id, std::vector bodies, OptionalString name = {}, std::optional material = {}, + std::vector connectors = {}); const std::string& part_id() const noexcept { return part_id_; } - const Solid& body() const noexcept { return body_; } + // The Solid of a one-body Part. TypeError for a multi-body Part: read bodies() instead. + const Solid& body() const; + const std::vector& bodies() const noexcept { return bodies_; } + bool multi_body() const noexcept { return bodies_.size() > 1; } + std::vector body_ids() const; + // KeyError ("part has no body_id 'x'") for an unknown id. + const Body& get_body(std::string_view body_id) const; const OptionalString& name() const noexcept { return name_; } const std::optional& material() const noexcept { return material_; } const std::vector& connectors() const noexcept { return connectors_; } @@ -40,7 +75,7 @@ class Part : public SemanticValue { private: std::string part_id_; - Solid body_; + std::vector bodies_; OptionalString name_; std::optional material_; std::vector connectors_; 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/ops_projection.cpp b/src/cpp/src/product/ops_projection.cpp index 665856e4..85f9777d 100644 --- a/src/cpp/src/product/ops_projection.cpp +++ b/src/cpp/src/product/ops_projection.cpp @@ -17,8 +17,10 @@ namespace { // Every Part body below `item`, placed by `placement` composed with the component chain. void collect_placed_solids(const Item& item, const Placement& placement, std::vector& out) { if (const auto* part = std::get_if(&item)) { - out.emplace_back(kernel::place_shape((*part)->body().wrapped(), placement.origin(), placement.x_axis(), - placement.y_axis(), placement.z_axis())); + for (const Body& body : (*part)->bodies()) { // every body of a multi-body part, in order + out.emplace_back(kernel::place_shape(body.solid().wrapped(), placement.origin(), placement.x_axis(), + placement.y_axis(), placement.z_axis())); + } return; } for (const Component& component : std::get(item)->components()) { diff --git a/src/cpp/src/product/ops_structure.cpp b/src/cpp/src/product/ops_structure.cpp index 4bce4e58..899e3279 100644 --- a/src/cpp/src/product/ops_structure.cpp +++ b/src/cpp/src/product/ops_structure.cpp @@ -122,6 +122,36 @@ PartPtr make_part_rpart(const std::string& part_id, const Solid& body, const Opt }); } +PartPtr make_part_rpart(const std::string& part_id, const std::vector& bodies, const OptionalString& name) { + return guard_operation("make_part_rpart", [&] { + auto part = std::make_shared(part_id, bodies, name); + reserve_semantic_id("part", part->part_id()); + record_value( + [&] { + Value params = Value::object(); + params.set("part_id", part->part_id()); + params.set("name", optional_name(part->name())); + Value rows = Value::array(); + Value refs = Value::array(); + for (const Body& body : part->bodies()) { + rows.push_back(body.to_dict()); + const Value body_refs = input_refs(body.solid()); + for (const Value& ref : body_refs.as_array()) + refs.push_back(ref); + } + params.set("bodies", std::move(rows)); + params.set("input_refs", std::move(refs)); + OpRecord record = op_record("make_part_rpart", std::move(params)); + for (const Body& body : part->bodies()) + record.inputs.push_back(OpInput{body.solid(), "body"}); + record.semantic_delta = semantic_created("Part", part->part_id(), part->to_dict()); + return record; + }, + part); + return part; + }); +} + PartPtr assign_material_rpart(const Part& part, const Material& material) { return guard_operation("assign_material_rpart", [&] { auto result = std::make_shared(part.with_material(material)); diff --git a/src/cpp/src/product/part.cpp b/src/cpp/src/product/part.cpp index a9f70057..daf5d78a 100644 --- a/src/cpp/src/product/part.cpp +++ b/src/cpp/src/product/part.cpp @@ -23,18 +23,84 @@ std::vector unique_connectors(std::vector connectors) { return connectors; } +std::vector checked_bodies(std::vector bodies) { + if (bodies.empty()) + throw ValueError("a Part needs at least one body"); + std::map counts; + for (const Body& body : bodies) + ++counts[body.body_id()]; + std::string duplicates; + for (const auto& [id, count] : counts) { + if (count > 1) + duplicates += (duplicates.empty() ? "" : ", ") + id; + } + if (!duplicates.empty()) + throw ValueError("duplicate body_id: " + duplicates); + return bodies; +} + +std::string joined_ids(const std::vector& bodies) { + std::string out; + for (const Body& body : bodies) + out += (out.empty() ? "" : ", ") + body.body_id(); + return out; +} + } // namespace +Body::Body(std::string body_id, Solid solid, OptionalString name) + : body_id_(validate_identifier(body_id, "body_id")), solid_(std::move(solid)), name_(clean_name(name)) {} + +Value Body::to_dict() const { + Value out = Value::object(); + out.set("body_id", body_id_); + out.set("name", name_ ? Value(*name_) : Value()); + return out; +} + Part::Part(std::string part_id, Solid body, OptionalString name, std::optional material, std::vector connectors) + : Part(std::move(part_id), std::vector{Body(kDefaultBodyId, std::move(body))}, std::move(name), + std::move(material), std::move(connectors)) {} + +Part::Part(std::string part_id, std::vector bodies, OptionalString name, std::optional material, + std::vector connectors) : part_id_(validate_identifier(part_id, "part_id")), - body_(std::move(body)), + bodies_(checked_bodies(std::move(bodies))), name_(clean_name(name)), material_(std::move(material)), - connectors_(unique_connectors(std::move(connectors))) {} + connectors_(unique_connectors(std::move(connectors))) { + if (bodies_.size() > 1 && !connectors_.empty()) + throw ValueError("connectors on a multi-body part are not supported yet (part '" + part_id_ + "')"); +} + +const Solid& Part::body() const { + if (bodies_.size() != 1) { + throw TypeError("part '" + part_id_ + "' has " + std::to_string(bodies_.size()) + " bodies (" + + joined_ids(bodies_) + "); read Part.bodies or Part.get_body(body_id)"); + } + return bodies_.front().solid(); +} + +std::vector Part::body_ids() const { + std::vector ids; + ids.reserve(bodies_.size()); + for (const Body& body : bodies_) + ids.push_back(body.body_id()); + return ids; +} + +const Body& Part::get_body(std::string_view body_id) const { + const std::string target = validate_identifier(body_id, "body_id"); + for (const Body& body : bodies_) { + if (body.body_id() == target) + return body; + } + throw LookupError("part has no body_id '" + target + "'"); +} Part Part::with_material(const Material& material) const { - Part result(part_id_, body_, name_, material, connectors_); + Part result(part_id_, bodies_, name_, material, connectors_); result.inherit_metadata(*this); return result; } @@ -46,7 +112,7 @@ Part Part::with_connector(const Connector& connector) const { } std::vector connectors = connectors_; connectors.push_back(connector); - Part result(part_id_, body_, name_, material_, std::move(connectors)); + Part result(part_id_, bodies_, name_, material_, std::move(connectors)); result.inherit_metadata(*this); return result; } @@ -77,6 +143,12 @@ Value Part::to_dict() const { for (const Connector& connector : connectors_) rows.push_back(connector.to_dict()); out.set("connectors", std::move(rows)); + if (bodies_.size() > 1) { // a one-body Part keeps the dict it always had + Value bodies = Value::array(); + for (const Body& body : bodies_) + bodies.push_back(body.to_dict()); + out.set("bodies", std::move(bodies)); + } return out; } 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 c6f5679e..fc4b561a 100644 --- a/src/simplecadapi/__init__.py +++ b/src/simplecadapi/__init__.py @@ -95,6 +95,7 @@ from simplecadapi._cpp import ( asin, Assembly, atan, + Body, CM, Connector, ConnectorAnchor, @@ -377,6 +378,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, + 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 ( @@ -590,6 +600,8 @@ __all__ = [ "add_rack_pinion_constraint_rassembly", "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", @@ -847,6 +859,7 @@ __all__ = [ "ConstraintResidual", "GeometryRef", "Material", + "Body", "Part", "Placement", "ScalarLimit", diff --git a/src/simplecadapi/_cpp/_native/__init__.pyi b/src/simplecadapi/_cpp/_native/__init__.pyi index 53f5ee7d..2cd33e85 100644 --- a/src/simplecadapi/_cpp/_native/__init__.pyi +++ b/src/simplecadapi/_cpp/_native/__init__.pyi @@ -252,6 +252,7 @@ from simplecadapi.product.constraint import ConstraintReport from simplecadapi.product.constraint import ConstraintResidual from simplecadapi.product.constraint import ScalarLimit from simplecadapi.product.material import Material +from simplecadapi.product.part import Body from simplecadapi.product.part import Part from simplecadapi.product.placement import Placement from simplecadapi.product.solver import inspect_assembly_constraints @@ -314,7 +315,7 @@ import numpy.typing import simplecadapi.core import simplecadapi.params.units import typing -__all__: list[str] = ['ANGLE', 'AREA', 'AnyShape', 'Assembly', 'BSplineFitResult', 'BlendDiagnosis', 'BooleanDiagnosis', 'CM', 'CUBIC_CM', 'CUBIC_FOOT', 'CUBIC_INCH', 'CUBIC_M', 'CUBIC_MM', 'Component', 'Compound', 'Connector', 'ConnectorAnchor', 'ConnectorRef', 'Const', 'Constraint', 'ConstraintReport', 'ConstraintResidual', 'CoordinateSystem', 'DEGREE', 'DIMENSIONLESS', 'Dimension', 'DimensionTolerance', 'Edge', 'ExecutorRegistry', 'Expr', 'ExprBase', 'ExpressionGraph', 'FOOT', 'Face', 'FrameGraph', 'FrameNode', 'GeometryRef', 'GraphSession', 'INCH', 'LENGTH', 'LineageDerivation', 'LineagePolicy', 'M', 'MM', 'Material', 'Mesh', 'NodeFailure', 'ONE', 'OperationGraph', 'OperationNode', 'PERCENT', 'Part', 'Placement', 'PublicConnectorRef', 'RADIAN', 'RecomputeReport', 'RenderFrame', 'RenderPanel', 'RenderScene', 'SQUARE_CM', 'SQUARE_FOOT', 'SQUARE_INCH', 'SQUARE_M', 'SQUARE_MM', 'ScalarLimit', 'SemanticDelta', 'SemanticRef', 'Shell', 'SimpleWorkplane', 'Sketch', 'SketchConstraint', 'SketchConstraintDiagnostic', 'SketchEntity', 'SketchRef', 'SketchSolveResult', 'SketchSolverBackend', 'SketchSolverOptions', 'Solid', 'StaleLineageError', 'SurfaceBoundary', 'SurfaceFillingSettings', 'TagAttachment', 'TagBinding', 'TagBindingScope', 'TagCertainty', 'TagEvidence', 'TagEvidenceKind', 'TagLifecycle', 'TagLineageWitness', 'TagPolicy', 'TagProducer', 'TagProducerKind', 'TagPropagation', 'TagScope', 'TagTarget', 'TagTargetKind', 'TopologyPropagation', 'TrackingPolicy', 'Unit', 'UnitValidationError', 'VOLUME', 'Var', 'Vec3', 'Vertex', 'WORLD_CS', 'Wire', 'Workplane', 'acos', 'add_arc_rsketch', 'add_belt_constraint_rassembly', 'add_bspline_rsketch', 'add_circle_rsketch', 'add_component_rassembly', 'add_connector_rpart', 'add_ellipse_rsketch', 'add_fixed_constraint_rassembly', 'add_gear_constraint_rassembly', 'add_line_rsketch', 'add_point_rsketch', 'add_prismatic_constraint_rassembly', 'add_rack_pinion_constraint_rassembly', 'add_revolute_constraint_rassembly', 'apply_tag', 'apply_tag_rselection', 'asin', 'assert_blend_volume_monotonic', 'assign_material_rpart', 'atan', 'atan2', 'boolean_rsolidlist', 'canonical_brep_bytes', 'canonical_bytes', 'canonical_hash', 'canonical_unit_for_dimension', 'canonicalize_params', 'chamfer_corner_rsketch', 'chamfer_rsolid', 'clone_semantic_view', 'const', 'constrain_angle_rsketch', 'constrain_coincident_rsketch', 'constrain_collinear_rsketch', 'constrain_concentric_rsketch', 'constrain_connect_rsketch', 'constrain_diameter_rsketch', 'constrain_distance_rsketch', 'constrain_distance_x_rsketch', 'constrain_distance_y_rsketch', 'constrain_equal_length_rsketch', 'constrain_equal_radius_rsketch', 'constrain_fix_rsketch', 'constrain_horizontal_rsketch', 'constrain_length_rsketch', 'constrain_line_distance_rsketch', 'constrain_major_radius_rsketch', 'constrain_midpoint_points_rsketch', 'constrain_midpoint_rsketch', 'constrain_minor_radius_rsketch', 'constrain_mirror_rsketch', 'constrain_normal_rsketch', 'constrain_parallel_rsketch', 'constrain_perpendicular_rsketch', 'constrain_point_on_rsketch', 'constrain_points_horizontal_rsketch', 'constrain_points_vertical_rsketch', 'constrain_radius_rsketch', 'constrain_symmetric_rsketch', 'constrain_tangent_rsketch', 'constrain_vertical_rsketch', 'constraint_reports_match', 'convert_value', 'cos', 'create_angle_arc', 'create_angle_arc_wire', 'create_arc', 'create_arc_wire', 'create_box', 'create_circle_edge', 'create_circle_face', 'create_circle_wire', 'create_cylinder', 'create_face_from_wire', 'create_face_from_wires', 'create_helix', 'create_helix_wire', 'create_interpolated_spline', 'create_interpolated_spline_wire', 'create_line', 'create_periodic_spline_wire', 'create_point', 'create_polyline_wire', 'create_rectangle_face', 'create_rectangle_wire', 'create_segment', 'create_segment_wire', 'create_sphere', 'create_spline', 'create_spline_wire', 'create_wire_from_edges', 'current_tracking_policy', 'cut_rsolid', 'cut_rsolid_list', 'deserialize_shape', 'diagnose_blend_failure', 'diagnose_boolean_failure', 'diff_sketch_rsketchdiff', 'draft_rsolid', 'evaluate_scalar', 'evaluate_value', 'explain_tag', 'explode_rassembly', 'export_brep', 'export_glb', 'export_obj', 'export_step', 'export_step_assembly', 'export_stl', 'expression_uses_units', 'extend_rsketch', 'extrude_rsolid', 'extrude_taper_rsolid', 'extrude_until_rsolid', 'fill_holes_rshell', 'fillet_corner_rsketch', 'fillet_rsolid', 'find_registered_node', 'fit_cubic_bspline_control_points', 'fit_point_grid_rface', 'forget_graph_nodes', 'free_boundaries_rwirelist', 'from_brep', 'get_active_session', 'get_current_cs', 'get_default_sketch_solver_backend', 'get_sketch_entity_rsketchref', 'get_sketch_point_rsketchref', 'get_sketch_solver_backend', 'get_unit', 'global_executor_registry', 'ground_component_rassembly', 'helical_sweep_rsolid', 'identity_placement_rplacement', 'import_brep', 'import_step', 'import_stl', 'import_stl_shape', 'infer_dimension', 'inspect_assembly_constraints', 'inspect_assembly_constraints_rconstraintreport', 'inspect_sketch_rsketchcrossings', 'inspect_sketch_rsketchprofiles', 'inspect_sketch_rsketchresult', 'intersect_rsolid', 'isolated_recording', 'lift_scalar', 'linear_pattern_rsolidlist', 'list_tags', 'load_brep_region_rshell', 'load_brep_region_rsolid', 'loft_rshell', 'loft_rsolid', 'make_2d_cut_rface', 'make_2d_intersect_rface', 'make_2d_union_rface', 'make_angle_arc_redge', 'make_angle_arc_rwire', 'make_assembly_rassembly', 'make_bezier_surface_rface', 'make_box_rsolid', 'make_circle_redge', 'make_circle_rface', 'make_circle_rwire', 'make_compound_from_assembly_rcompound', 'make_cone_rsolid', 'make_connector_ref_rconnectorref', 'make_cylinder_rsolid', 'make_cylindrical_surface_rface', 'make_edge_connector_rconnector', 'make_ellipse_redge', 'make_ellipse_rface', 'make_ellipse_rwire', 'make_face_connector_rconnector', 'make_face_from_sketch_rface', 'make_face_from_wire_rface', 'make_face_from_wires_rface', 'make_gordon_surface_rface', 'make_helix_redge', 'make_helix_rwire', 'make_interpolated_spline_redge', 'make_interpolated_spline_rwire', 'make_line_redge', 'make_material_rmaterial', 'make_param_spec', 'make_part_rpart', 'make_periodic_spline_rwire', 'make_placement_connector_rconnector', 'make_placement_rplacement', 'make_point_rvertex', 'make_polyline_rwire', 'make_rectangle_rface', 'make_rectangle_rwire', 'make_ruled_surface_rface', 'make_scalar_limit_rscalarlimit', 'make_segment_redge', 'make_segment_rwire', 'make_sketch_rsketch', 'make_solid_from_shell_rsolid', 'make_sphere_rsolid', 'make_spline_redge', 'make_spline_rwire', 'make_surface_patch_rface', 'make_three_point_arc_redge', 'make_three_point_arc_rwire', 'make_vertex_connector_rconnector', 'make_wire_from_edges_rwire', 'make_wire_from_sketch_rwire', 'math', 'measure_constraint_residual_rconstraintresidual', 'mesh', 'mirror_shape', 'offset_rsolid', 'parse_ui_comment', 'place_component_rassembly', 'project_rsketch', 'ql', 'radial_pattern_rsolidlist', 'raise_loft_failure_if_diagnosed', 'record_operation_if_active', 'recording_active', 'referenced_expressions', 'register_executor', 'register_graph_nodes', 'register_node', 'register_sketch_solver_backend', 'render_auto_view', 'render_default_threads', 'render_edge_polylines', 'render_scene', 'render_view_preset', 'resolve_connector', 'resolve_connector_placement', 'resolve_connector_ref_placement', 'resolve_item_connector', 'resolve_item_connector_placement', 'revolve_rsolid', 'rotate_shape', 'same_node_content', 'scale_rsolid', 'select_edges_by_tag', 'select_faces_by_tag', 'serialize_shape', 'set_default_sketch_solver_backend', 'set_producer_version', 'set_public_connector_rassembly', 'sew_faces_rshell', 'shell_rsolid', 'sin', 'sketch_solver_backend', 'solve_assembly_constraints', 'solve_assembly_constraints_rassembly', 'sqrt', 'std', 'step_bytes', 'surface', 'suspend_graph_recording', 'sweep_multisection_rsolid', 'sweep_rsolid', 'tagging', 'tan', 'tessellate_solid', 'tracking_policy_scope', 'transform_rsolid', 'translate_shape', 'trim_rsketch', 'trim_surface_rface', 'twisted_sweep_rsolid', 'unground_component_rassembly', 'union_rsolid', 'unit_from_payload', 'unit_to_payload', 'upstream_closure', 'use_coordinate_system', 'var'] +__all__: list[str] = ['ANGLE', 'AREA', 'AnyShape', 'Assembly', 'BSplineFitResult', 'BlendDiagnosis', 'Body', 'BooleanDiagnosis', 'CM', 'CUBIC_CM', 'CUBIC_FOOT', 'CUBIC_INCH', 'CUBIC_M', 'CUBIC_MM', 'Component', 'Compound', 'Connector', 'ConnectorAnchor', 'ConnectorRef', 'Const', 'Constraint', 'ConstraintReport', 'ConstraintResidual', 'CoordinateSystem', 'DEGREE', 'DIMENSIONLESS', 'Dimension', 'DimensionTolerance', 'Edge', 'ExecutorRegistry', 'Expr', 'ExprBase', 'ExpressionGraph', 'FOOT', 'Face', 'FrameGraph', 'FrameNode', 'GeometryRef', 'GraphSession', 'INCH', 'LENGTH', 'LineageDerivation', 'LineagePolicy', 'M', 'MM', 'Material', 'Mesh', 'NodeFailure', 'ONE', 'OperationGraph', 'OperationNode', 'PERCENT', 'Part', 'Placement', 'PublicConnectorRef', 'RADIAN', 'RecomputeReport', 'RenderFrame', 'RenderPanel', 'RenderScene', 'SQUARE_CM', 'SQUARE_FOOT', 'SQUARE_INCH', 'SQUARE_M', 'SQUARE_MM', 'ScalarLimit', 'SemanticDelta', 'SemanticRef', 'Shell', 'SimpleWorkplane', 'Sketch', 'SketchConstraint', 'SketchConstraintDiagnostic', 'SketchEntity', 'SketchRef', 'SketchSolveResult', 'SketchSolverBackend', 'SketchSolverOptions', 'Solid', 'StaleLineageError', 'SurfaceBoundary', 'SurfaceFillingSettings', 'TagAttachment', 'TagBinding', 'TagBindingScope', 'TagCertainty', 'TagEvidence', 'TagEvidenceKind', 'TagLifecycle', 'TagLineageWitness', 'TagPolicy', 'TagProducer', 'TagProducerKind', 'TagPropagation', 'TagScope', 'TagTarget', 'TagTargetKind', 'TopologyPropagation', 'TrackingPolicy', 'Unit', 'UnitValidationError', 'VOLUME', 'Var', 'Vec3', 'Vertex', 'WORLD_CS', 'Wire', 'Workplane', 'acos', 'add_arc_rsketch', 'add_belt_constraint_rassembly', 'add_bspline_rsketch', 'add_circle_rsketch', 'add_component_rassembly', 'add_connector_rpart', 'add_ellipse_rsketch', 'add_fixed_constraint_rassembly', 'add_gear_constraint_rassembly', 'add_line_rsketch', 'add_point_rsketch', 'add_prismatic_constraint_rassembly', 'add_rack_pinion_constraint_rassembly', 'add_revolute_constraint_rassembly', 'apply_tag', 'apply_tag_rselection', 'asin', 'assert_blend_volume_monotonic', 'assign_material_rpart', 'atan', 'atan2', 'boolean_rsolidlist', 'canonical_brep_bytes', 'canonical_bytes', 'canonical_hash', 'canonical_unit_for_dimension', 'canonicalize_params', 'chamfer_corner_rsketch', 'chamfer_rsolid', 'clone_semantic_view', 'const', 'constrain_angle_rsketch', 'constrain_coincident_rsketch', 'constrain_collinear_rsketch', 'constrain_concentric_rsketch', 'constrain_connect_rsketch', 'constrain_diameter_rsketch', 'constrain_distance_rsketch', 'constrain_distance_x_rsketch', 'constrain_distance_y_rsketch', 'constrain_equal_length_rsketch', 'constrain_equal_radius_rsketch', 'constrain_fix_rsketch', 'constrain_horizontal_rsketch', 'constrain_length_rsketch', 'constrain_line_distance_rsketch', 'constrain_major_radius_rsketch', 'constrain_midpoint_points_rsketch', 'constrain_midpoint_rsketch', 'constrain_minor_radius_rsketch', 'constrain_mirror_rsketch', 'constrain_normal_rsketch', 'constrain_parallel_rsketch', 'constrain_perpendicular_rsketch', 'constrain_point_on_rsketch', 'constrain_points_horizontal_rsketch', 'constrain_points_vertical_rsketch', 'constrain_radius_rsketch', 'constrain_symmetric_rsketch', 'constrain_tangent_rsketch', 'constrain_vertical_rsketch', 'constraint_reports_match', 'convert_value', 'cos', 'create_angle_arc', 'create_angle_arc_wire', 'create_arc', 'create_arc_wire', 'create_box', 'create_circle_edge', 'create_circle_face', 'create_circle_wire', 'create_cylinder', 'create_face_from_wire', 'create_face_from_wires', 'create_helix', 'create_helix_wire', 'create_interpolated_spline', 'create_interpolated_spline_wire', 'create_line', 'create_periodic_spline_wire', 'create_point', 'create_polyline_wire', 'create_rectangle_face', 'create_rectangle_wire', 'create_segment', 'create_segment_wire', 'create_sphere', 'create_spline', 'create_spline_wire', 'create_wire_from_edges', 'current_tracking_policy', 'cut_rsolid', 'cut_rsolid_list', 'deserialize_shape', 'diagnose_blend_failure', 'diagnose_boolean_failure', 'diff_sketch_rsketchdiff', 'draft_rsolid', 'evaluate_scalar', 'evaluate_value', 'explain_tag', 'explode_rassembly', 'export_brep', 'export_glb', 'export_obj', 'export_step', 'export_step_assembly', 'export_stl', 'expression_uses_units', 'extend_rsketch', 'extrude_rsolid', 'extrude_taper_rsolid', 'extrude_until_rsolid', 'fill_holes_rshell', 'fillet_corner_rsketch', 'fillet_rsolid', 'find_registered_node', 'fit_cubic_bspline_control_points', 'fit_point_grid_rface', 'forget_graph_nodes', 'free_boundaries_rwirelist', 'from_brep', 'get_active_session', 'get_current_cs', 'get_default_sketch_solver_backend', 'get_sketch_entity_rsketchref', 'get_sketch_point_rsketchref', 'get_sketch_solver_backend', 'get_unit', 'global_executor_registry', 'ground_component_rassembly', 'helical_sweep_rsolid', 'identity_placement_rplacement', 'import_brep', 'import_step', 'import_stl', 'import_stl_shape', 'infer_dimension', 'inspect_assembly_constraints', 'inspect_assembly_constraints_rconstraintreport', 'inspect_sketch_rsketchcrossings', 'inspect_sketch_rsketchprofiles', 'inspect_sketch_rsketchresult', 'intersect_rsolid', 'isolated_recording', 'lift_scalar', 'linear_pattern_rsolidlist', 'list_tags', 'load_brep_region_rshell', 'load_brep_region_rsolid', 'loft_rshell', 'loft_rsolid', 'make_2d_cut_rface', 'make_2d_intersect_rface', 'make_2d_union_rface', 'make_angle_arc_redge', 'make_angle_arc_rwire', 'make_assembly_rassembly', 'make_bezier_surface_rface', 'make_box_rsolid', 'make_circle_redge', 'make_circle_rface', 'make_circle_rwire', 'make_compound_from_assembly_rcompound', 'make_cone_rsolid', 'make_connector_ref_rconnectorref', 'make_cylinder_rsolid', 'make_cylindrical_surface_rface', 'make_edge_connector_rconnector', 'make_ellipse_redge', 'make_ellipse_rface', 'make_ellipse_rwire', 'make_face_connector_rconnector', 'make_face_from_sketch_rface', 'make_face_from_wire_rface', 'make_face_from_wires_rface', 'make_gordon_surface_rface', 'make_helix_redge', 'make_helix_rwire', 'make_interpolated_spline_redge', 'make_interpolated_spline_rwire', 'make_line_redge', 'make_material_rmaterial', 'make_param_spec', 'make_part_rpart', 'make_periodic_spline_rwire', 'make_placement_connector_rconnector', 'make_placement_rplacement', 'make_point_rvertex', 'make_polyline_rwire', 'make_rectangle_rface', 'make_rectangle_rwire', 'make_ruled_surface_rface', 'make_scalar_limit_rscalarlimit', 'make_segment_redge', 'make_segment_rwire', 'make_sketch_rsketch', 'make_solid_from_shell_rsolid', 'make_sphere_rsolid', 'make_spline_redge', 'make_spline_rwire', 'make_surface_patch_rface', 'make_three_point_arc_redge', 'make_three_point_arc_rwire', 'make_vertex_connector_rconnector', 'make_wire_from_edges_rwire', 'make_wire_from_sketch_rwire', 'math', 'measure_constraint_residual_rconstraintresidual', 'mesh', 'mirror_shape', 'offset_rsolid', 'parse_ui_comment', 'place_component_rassembly', 'project_rsketch', 'ql', 'radial_pattern_rsolidlist', 'raise_loft_failure_if_diagnosed', 'record_operation_if_active', 'recording_active', 'referenced_expressions', 'register_executor', 'register_graph_nodes', 'register_node', 'register_sketch_solver_backend', 'render_auto_view', 'render_default_threads', 'render_edge_polylines', 'render_scene', 'render_view_preset', 'resolve_connector', 'resolve_connector_placement', 'resolve_connector_ref_placement', 'resolve_item_connector', 'resolve_item_connector_placement', 'revolve_rsolid', 'rotate_shape', 'same_node_content', 'scale_rsolid', 'select_edges_by_tag', 'select_faces_by_tag', 'serialize_shape', 'set_default_sketch_solver_backend', 'set_producer_version', 'set_public_connector_rassembly', 'sew_faces_rshell', 'shell_rsolid', 'sin', 'sketch_solver_backend', 'solve_assembly_constraints', 'solve_assembly_constraints_rassembly', 'sqrt', 'std', 'step_bytes', 'surface', 'suspend_graph_recording', 'sweep_multisection_rsolid', 'sweep_rsolid', 'tagging', 'tan', 'tessellate_solid', 'tracking_policy_scope', 'transform_rsolid', 'translate_shape', 'trim_rsketch', 'trim_surface_rface', 'twisted_sweep_rsolid', 'unground_component_rassembly', 'union_rsolid', 'unit_from_payload', 'unit_to_payload', 'upstream_closure', 'use_coordinate_system', 'var'] class AnyShape: """ Tag mixin that provides tagging support for geometry objects. diff --git a/src/simplecadapi/_glue/docstrings.json b/src/simplecadapi/_glue/docstrings.json index 3565957b..0e3211c5 100644 --- a/src/simplecadapi/_glue/docstrings.json +++ b/src/simplecadapi/_glue/docstrings.json @@ -28,7 +28,7 @@ "Material": "Material definition assigned to a Part through `assign_material_rpart`.", "OperationGraph": "A directed acyclic graph of CAD operations.\n\nThe graph tracks nodes (operations) and edges (data-flow dependencies).\nIt supports topological ordering, upstream/downstream queries, and\nroot/leaf enumeration.\n\nUsage::\n\n g = OperationGraph()\n e1 = g.add_node(\"make_line_redge\", {\"start\": (0, 0, 0), \"end\": (1, 0, 0)})\n e2 = g.add_node(\"make_line_redge\", {\"start\": (1, 0, 0), \"end\": (1, 1, 0)})\n wire = g.add_node(\"make_wire_from_edges_rwire\", {\"edge_count\": 2}, inputs=[e1, e2])\n assert wire.node_id == g.leaf_nodes()[0].node_id\n\nA *namespace* prefixes every id the graph allocates\n(``_node_00000001``). Graphs that share a ``graph_id`` but\nallocate ids independently, such as the per-cell graphs of a notebook,\nuse distinct namespaces so their nodes can later meet in one graph\n(:meth:`adopt`) without id clashes.", "OperationNode": "A single node in the operation DAG.\n\nAttributes:\n node_id: Unique identifier within the graph.\n op: Operation type (e.g. ``\"make_line_redge\"``, ``\"make_cut_rsolid\"``).\n params: Serialisable parameters for re-creation.\n inputs: Upstream nodes whose outputs feed into this node.\n context: Work-plane / coordinate-system snapshot taken at creation time.\n output_count: Number of output shapes this node produces (usually 1).\n topo_delta: Topological change set (may be ``None`` for simple primitives).\n tags: Free-form labels for annotation.\n source: Best-effort Python source provenance; ignored by replay.\n expressions: The expressions ``param_exprs`` refers to.\n frame: The coordinate frame current when the node was recorded.\n\n``expressions`` and ``frame`` duplicate what the recording session keeps\nin its expression and frame graphs. They travel with the node so a node\nthat outlives its session (a notebook cell's result, restored from the\ncell cache) can still be registered in a new one. They are excluded from\nequality and from :meth:`OperationGraph.to_dict`.\n\nNodes pickle and deep-copy without recursion (see :meth:`__reduce__`).", - "Part": "Single-body product item wrapping exactly one Solid.", + "Part": "Product item holding one Solid (``body``) or several named bodies (``bodies``).\n\nA one-body Part is the common case: ``part.body`` is its Solid. A multi-body\nPart keeps several solids apart inside one product item (a case and its lid\nmodelled side by side, the pieces of a split cut): ``part.bodies`` lists them\nas ``Body`` values in order, ``part.get_body(body_id)`` finds one, and\n``part.body`` raises ``TypeError``. Bodies of one Part are never placed\nrelative to each other and carry no joints; use an Assembly for that.", "Placement": "Right-handed placement mapping child-local coordinates to parent coordinates.", "PublicConnectorRef": "Public alias for an existing connector on a direct child component.", "ScalarExprBase": "Base class for scalar expression nodes.", @@ -145,7 +145,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.", "diff_sketch_rsketchdiff": "Report what an edit did: entity and constraint ids created, removed or changed between two sketches.\n\nReturns a dict with ``created``, ``removed``, ``changed`` (entity ids, points included) and\n``created_constraints``, ``removed_constraints``, ``changed_constraints``. Not recorded in the graph.", @@ -232,7 +232,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 exactly one Solid as a semantic single-body Part.", + "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.", @@ -343,5 +343,8 @@ "validate_placement_ticks": "Validate a persisted tick frame with exact integer arithmetic.", "value": "Build a value key extractor for ordering and projection in QL.\n\nArgs:\n path: Property or metadata path to resolve.\n default: Fallback value when the path is missing.\n\nReturns:\n Serializable key function for `Query.order_by(...)`.", "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" + "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.", + "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 944599a3..57657ca2 100644 --- a/src/simplecadapi/_glue/modules.json +++ b/src/simplecadapi/_glue/modules.json @@ -33,6 +33,7 @@ "OperationGraph": "simplecadapi.topology.model", "OperationNode": "simplecadapi.topology.model", "Part": "simplecadapi.product.part", +"Body": "simplecadapi.product.part", "Placement": "simplecadapi.product.placement", "PublicConnectorRef": "simplecadapi.product.assembly", "Query": "simplecadapi.ql", @@ -187,6 +188,8 @@ "curve_type": "simplecadapi.ql", "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/_glue/session.py b/src/simplecadapi/_glue/session.py index d96e5bd5..77e4ef0c 100644 --- a/src/simplecadapi/_glue/session.py +++ b/src/simplecadapi/_glue/session.py @@ -47,10 +47,15 @@ def lineage_of(value: Any) -> Optional[Tuple[str, str]]: return graph_id, node_id +_PRODUCT_KINDS = frozenset({"Part", "Assembly", "Component", "Connector"}) +"""The product values whose children :func:`_children` lists (not walked as plain dataclasses).""" + + def _children(item: Any) -> Iterable[Any]: kind = type(item).__name__ if kind == "Part": - yield item.body + for body in item.bodies: # one Solid, or every body of a multi-body part + yield body.solid yield from item.connectors if item.material is not None: yield item.material @@ -85,7 +90,9 @@ def walk_values(value: Any, *, deep: bool, seen: Optional[Set[int]] = None) -> I for item in value: yield from walk_values(item, deep=deep, seen=seen) elif deep: - if dataclasses.is_dataclass(value) and not isinstance(value, type): # a result wrapped in the caller's own dataclass + # a result wrapped in the caller's own dataclass (the product values have their own children: a multi-body Part's + # `body` field refuses to name one body) + if dataclasses.is_dataclass(value) and not isinstance(value, type) and type(value).__name__ not in _PRODUCT_KINDS: for field in dataclasses.fields(value): if not field.name.startswith("_"): yield from walk_values(getattr(value, field.name), deep=True, seen=seen) diff --git a/src/simplecadapi/_glue/values.py b/src/simplecadapi/_glue/values.py index 1740c7e2..17e2847c 100644 --- a/src/simplecadapi/_glue/values.py +++ b/src/simplecadapi/_glue/values.py @@ -21,6 +21,7 @@ from typing import Any, Dict, Tuple # class name -> (constructor parameter names, has state dictionaries) _VALUES: Dict[str, bool] = { "Part": True, + "Body": False, "Assembly": True, "Placement": True, "Material": True, @@ -93,9 +94,20 @@ def _token_for(key: str, item: Any) -> str: return f"{_TOKEN}{key}:{id(item):x}" +# Constructor arguments that are not read back by the attribute of the same name. A Part holds one ``body`` or +# several ``bodies``, and is rebuilt from exactly one of them (``Part.body`` raises for a multi-body Part). +_ARGUMENTS: Dict[str, Dict[str, Any]] = { + "Part": { + "body": lambda value: None if value.multi_body else value.body, + "bodies": lambda value: value.bodies if value.multi_body else None, + }, +} + + def _reduce(has_state: bool, names: Tuple[str, ...]): def reduce(value: Any) -> tuple: - args = tuple(getattr(value, name) for name in names) + readers = _ARGUMENTS.get(type(value).__name__, {}) + args = tuple(readers[name](value) if name in readers else getattr(value, name) for name in names) state = None if has_state: runtime = value._runtime_dict() diff --git a/src/simplecadapi/artifacts/assembly_io.py b/src/simplecadapi/artifacts/assembly_io.py index 123dfb10..6cd00f4a 100644 --- a/src/simplecadapi/artifacts/assembly_io.py +++ b/src/simplecadapi/artifacts/assembly_io.py @@ -43,7 +43,7 @@ from .part_definition import ( mark_part_definition_validated, take_validated_part_body, ) -from .part_io import encode_part_definition, load_part_definition +from .part_io import encode_part_definition, load_part_definition, read_part_bodies from .references import ConnectorInterface, PartRef from .topology_snapshot import ( restore_topology_snapshot, @@ -759,17 +759,14 @@ def materialize_definition( body = take_validated_part_body(node) if body is None: validate_artifact_blobs(node.to_dict(), node.blobs) - body = read_brep_solid(node.blobs[node.solid_cache_ref.path]) - restore_topology_snapshot( - body, - node.blobs[node.topology_snapshot_ref.path], - ) - validate_connector_entity_bindings(body, node.connectors) + body = read_part_bodies(node) mark_part_definition_validated(node) + multi = isinstance(body, tuple) # the Body values of a multi-body part value: Part | Assembly = Part( part_id=node.definition_id, name=node.metadata.get("name"), - body=body, + body=None if multi else body, + bodies=body if multi else None, material=_material_from_definition(node), connectors=tuple(_runtime_connector(item) for item in node.connectors), ) 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 9555113f..e254017d 100644 --- a/src/simplecadapi/artifacts/part_definition.py +++ b/src/simplecadapi/artifacts/part_definition.py @@ -1,4 +1,13 @@ -"""Persistent single-solid PartDefinition contract.""" +"""Persistent PartDefinition contract: one evaluated Solid, or several named bodies. + +A one-body part is what every PartDefinition was: ``solid_cache.body_ref`` is the BRep of its Solid and +``topology_snapshot_ref`` the semantic state of that Solid. A multi-body part also lists ``solid_cache.bodies``: +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 @@ -8,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, @@ -26,6 +36,40 @@ from .references import ( ) +@dataclass(frozen=True, slots=True) +class BodyRef: + """One body of a multi-body PartDefinition: its id, display name, BRep and topology snapshot.""" + + body_id: str + name: str | None + body_ref: BlobRef + topology_snapshot_ref: BlobRef + + def __post_init__(self) -> None: + object.__setattr__(self, "body_id", validate_logical_id(self.body_id, "/solid_cache/bodies/body_id")) + if self.name is not None and (not isinstance(self.name, str) or not self.name): + raise ArtifactValidationError("name_invalid", "/solid_cache/bodies/name", "expected a name or null") + if not isinstance(self.body_ref, BlobRef) or not isinstance(self.topology_snapshot_ref, BlobRef): + raise ArtifactValidationError("reference_invalid", "/solid_cache/bodies", "expected BlobRef values") + + def to_dict(self) -> dict[str, Any]: + return { + "body_id": self.body_id, + "name": self.name, + "body_ref": self.body_ref.to_dict(), + "topology_snapshot_ref": self.topology_snapshot_ref.to_dict(), + } + + @classmethod + def from_dict(cls, data: Mapping[str, Any], path: str) -> "BodyRef": + return cls( + body_id=str(data["body_id"]), + name=data.get("name"), + body_ref=BlobRef.from_dict(data["body_ref"], f"{path}/body_ref"), + topology_snapshot_ref=BlobRef.from_dict(data["topology_snapshot_ref"], f"{path}/topology_snapshot_ref"), + ) + + @dataclass(frozen=True, slots=True) class PartDefinition: """Validated durable definition for exactly one evaluated Solid.""" @@ -44,6 +88,7 @@ class PartDefinition: metadata: Mapping[str, Any] = field(default_factory=dict) content_hash: str = "" blobs: Mapping[str, bytes] = field(default_factory=dict, compare=False, repr=False) + bodies: tuple[BodyRef, ...] = () # empty for a one-body part; else every body, in order (at least two) _validated_manifest: bytes | None = field( default=None, init=False, @@ -107,6 +152,22 @@ class PartDefinition: "connector_invalid", "/connectors", "connector IDs must be unique" ) object.__setattr__(self, "connectors", connectors) + bodies = tuple(self.bodies) + if bodies: + if len(bodies) < 2 or not all(isinstance(item, BodyRef) for item in bodies): + raise ArtifactValidationError( + "bodies_invalid", "/solid_cache/bodies", "expected two or more BodyRef values" + ) + body_ids = [item.body_id for item in bodies] + if len(set(body_ids)) != len(body_ids): + raise ArtifactValidationError("bodies_invalid", "/solid_cache/bodies", "body IDs must be unique") + if connectors: + raise ArtifactValidationError( + "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 ): @@ -203,6 +264,8 @@ class PartDefinition: "solid_cache": { "evaluator_profile": "ocp-evaluated-solid-1", "body_ref": self.solid_cache_ref.to_dict(), + # a one-body part writes the manifest it always wrote (same bytes, same content hash) + **({"bodies": [item.to_dict() for item in self.bodies]} if self.bodies else {}), }, "topology_snapshot_ref": self.topology_snapshot_ref.to_dict(), "connectors": [item.to_dict() for item in self.connectors], @@ -264,6 +327,10 @@ class PartDefinition: metadata=dict(data["metadata"]), content_hash=str(data["content_hash"]), blobs=blobs or {}, + bodies=tuple( + BodyRef.from_dict(item, f"/solid_cache/bodies/{index}") + for index, item in enumerate(cache.get("bodies") or ()) + ), ) @@ -299,4 +366,4 @@ def validated_part_feature_graph(definition: PartDefinition) -> Any: return definition._validated_feature_graph -__all__ = ["PartDefinition"] +__all__ = ["BodyRef", "PartDefinition"] diff --git a/src/simplecadapi/artifacts/part_io.py b/src/simplecadapi/artifacts/part_io.py index ec202e42..8b098dbe 100644 --- a/src/simplecadapi/artifacts/part_io.py +++ b/src/simplecadapi/artifacts/part_io.py @@ -5,7 +5,7 @@ from __future__ import annotations from pathlib import Path from typing import Any -from .brep import read_brep_solid +from .brep import read_brep_shape, read_brep_solid from .canonical import ArtifactValidationError from .part_definition import ( PartDefinition, @@ -64,6 +64,9 @@ def load_part_definition( material_ref = manifest["material_ref"] if material_ref is not None: expected_paths.add(str(material_ref["path"])) + for body in manifest["solid_cache"].get("bodies") or (): # a multi-body part: each body's BRep and snapshot + expected_paths.add(str(body["body_ref"]["path"])) + expected_paths.add(str(body["topology_snapshot_ref"]["path"])) expected_members = { _PART_DEFINITION_MANIFEST, *(_BLOB_PREFIX + path for path in expected_paths), @@ -90,12 +93,7 @@ def load_part_definition( "/definition/feature_graph_ref", "feature graph owner differs from PartDefinition identity", ) - body = read_brep_solid(definition.blobs[definition.solid_cache_ref.path]) - restore_topology_snapshot( - body, - definition.blobs[definition.topology_snapshot_ref.path], - ) - validate_connector_entity_bindings(body, definition.connectors) + body = read_part_bodies(definition) mark_part_definition_validated( definition, body=body, @@ -104,6 +102,35 @@ def load_part_definition( return definition +def read_part_bodies(definition: PartDefinition) -> Any: + """The Solid of a one-body definition, or the ``Body`` values of a multi-body one, with their semantic state. + + A multi-body definition's ``body_ref`` must be a Compound of exactly as many solids as it lists bodies. + """ + + if not definition.bodies: + body = read_brep_solid(definition.blobs[definition.solid_cache_ref.path]) + restore_topology_snapshot(body, definition.blobs[definition.topology_snapshot_ref.path]) + validate_connector_entity_bindings(body, definition.connectors) + return body + from simplecadapi._cpp import Body + + compound = read_brep_shape(definition.blobs[definition.solid_cache_ref.path]) + count = len(compound.solids()) if hasattr(compound, "solids") else 1 + if count != len(definition.bodies): + raise ArtifactValidationError( + "solid_cardinality_invalid", + "/solid_cache/body_ref", + f"BRep holds {count} solids, the definition lists {len(definition.bodies)} bodies", + ) + bodies = [] + for item in definition.bodies: + solid = read_brep_solid(definition.blobs[item.body_ref.path]) + restore_topology_snapshot(solid, definition.blobs[item.topology_snapshot_ref.path]) + bodies.append(Body(item.body_id, solid, item.name)) + return tuple(bodies) + + def export_part_definition( value: PartDefinition | Any, path: str | Path, diff --git a/src/simplecadapi/artifacts/validation.py b/src/simplecadapi/artifacts/validation.py index 5247cad9..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: @@ -136,6 +139,9 @@ def _blob_refs(manifest: Mapping[str, Any]) -> list[tuple[str, Mapping[str, Any] material = manifest["material_ref"] if material is not None: refs.append(("/material_ref", material)) + for index, body in enumerate(manifest["solid_cache"].get("bodies") or ()): # a multi-body part + refs.append((f"/solid_cache/bodies/{index}/body_ref", body["body_ref"])) + refs.append((f"/solid_cache/bodies/{index}/topology_snapshot_ref", body["topology_snapshot_ref"])) return refs return [("/feature_graph_ref", manifest["feature_graph_ref"])] diff --git a/src/simplecadapi/build/definition.py b/src/simplecadapi/build/definition.py index 91a9a307..a28b3b1b 100644 --- a/src/simplecadapi/build/definition.py +++ b/src/simplecadapi/build/definition.py @@ -39,7 +39,7 @@ from ..artifacts.feature_graph import ( encode_feature_graph_artifact, ) from ..artifacts.geometry_interface import geometry_interface_fingerprint -from ..artifacts.part_definition import PartDefinition, mark_part_definition_validated +from ..artifacts.part_definition import BodyRef, PartDefinition, mark_part_definition_validated from ..artifacts.references import ( BlobRef, ConnectorInterface, @@ -72,6 +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, 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 @@ -166,13 +167,44 @@ def _part_definition( """Assemble and validate the ``PartDefinition`` of one built Part.""" feature_payload = encode_feature_graph_artifact(feature_graph) - body_payload = write_brep_bytes(part.body) - topology_payload = encode_topology_snapshot(part.body) feature_path = _feature_graph_path(feature_graph) - body_path = f"body/{sha256_bytes(body_payload).removeprefix('sha256:')}.brep" - topology_path = ( - f"topology/{sha256_bytes(topology_payload).removeprefix('sha256:')}.json" - ) + 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: + brep, brep_path = _brep_blob(item.solid) + snapshot, snapshot_path = _snapshot_blob(item.solid) + body_blobs[brep_path], body_blobs[snapshot_path] = brep, snapshot + rows.append( + BodyRef( + body_id=item.body_id, + name=item.name, + body_ref=_blob_ref(brep_path, brep, "application/vnd.opencascade.brep"), + topology_snapshot_ref=_blob_ref(snapshot_path, snapshot, "application/json"), + ) + ) + body_refs = tuple(rows) + body_payload, body_path = _brep_blob(part_shape(part)) + topology_payload, topology_path = _snapshot_blob(part.bodies[0].solid) + geometry_hash = content_hash( + { + "bodies": [ + { + "body_id": item.body_id, + "geometry": geometry_interface_fingerprint(item.solid, tolerance_profile=tolerance_profile), + } + for item in part.bodies + ] + }, + omit=(), + ) + else: + body_payload, body_path = _brep_blob(part.body) + topology_payload, topology_path = _snapshot_blob(part.body) + geometry_hash = geometry_interface_fingerprint(part.body, tolerance_profile=tolerance_profile) material_ref, material_blobs = _material_ref(part.material) connectors = tuple( sorted( @@ -181,10 +213,7 @@ def _part_definition( ) ) interface_hashes = InterfaceHashes( - geometry=geometry_interface_fingerprint( - part.body, - tolerance_profile=tolerance_profile, - ), + geometry=geometry_hash, connectors={item.connector_id: item.interface_hash for item in connectors}, bindings={item.connector_id: item.binding_hash for item in connectors}, material=material_ref.sha256 if material_ref is not None else None, @@ -193,6 +222,7 @@ def _part_definition( feature_path: feature_payload, body_path: body_payload, topology_path: topology_payload, + **body_blobs, **material_blobs, } definition = PartDefinition( @@ -217,17 +247,29 @@ def _part_definition( interface_hashes=interface_hashes, metadata={"name": part.name}, blobs=blobs, + bodies=body_refs, ) validate_artifact_blobs(definition.to_dict(), definition.blobs) - validate_connector_entity_bindings(part.body, definition.connectors) + if not part.multi_body: # a multi-body part has no connectors yet + validate_connector_entity_bindings(part.body, definition.connectors) mark_part_definition_validated( definition, - body=part.body, + body=part.bodies if part.multi_body else part.body, feature_graph=feature_graph, ) return definition +def _brep_blob(shape: Any) -> tuple[bytes, str]: + payload = write_brep_bytes(shape) + return payload, f"body/{sha256_bytes(payload).removeprefix('sha256:')}.brep" + + +def _snapshot_blob(solid: Solid) -> tuple[bytes, str]: + payload = encode_topology_snapshot(solid) + return payload, f"topology/{sha256_bytes(payload).removeprefix('sha256:')}.json" + + def _attach_feature_graph_result( part: Part, feature_graph: FeatureGraphArtifact, @@ -246,7 +288,8 @@ def _attach_feature_graph_result( raise ArtifactValidationError( "result_invalid", "/result_node_ids/0", "result node does not exist" ) - attach_graph_node(part.body, node, graph_id=session.graph.graph_id) + for item in part.bodies: # one Solid, or every body of a multi-body part + attach_graph_node(item.solid, node, graph_id=session.graph.graph_id) attach_semantic_graph_node(part, node, graph_id=session.graph.graph_id) session._captured_values.append(part) session.validate_graph_ownership(part) diff --git a/src/simplecadapi/catalog.py b/src/simplecadapi/catalog.py index e81fc8f1..cf844b9b 100644 --- a/src/simplecadapi/catalog.py +++ b/src/simplecadapi/catalog.py @@ -162,9 +162,9 @@ def classify(type_text: str) -> dict[str, Any]: if mapping: # a value per name (component id, tag ...): ``direction3_map``, ``number_map``, ``text_map`` key_and_value = _split_top(mapping.group(1), ",") inner = classify(key_and_value[-1]) - if inner["kind"] == "unknown" or inner["many"]: + if inner["kind"] == "unknown": return {"kind": "unknown", "many": False, "optional": optional, "choices": ()} - return {"kind": f"{inner['kind']}_map", "many": False, "optional": optional, "choices": inner["choices"]} + return {"kind": f"{inner['kind']}_map", "many": inner["many"], "optional": optional, "choices": inner["choices"]} return _classify_names([text], optional) 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/editor/features.py b/src/simplecadapi/editor/features.py index aa51d607..c5ce2487 100644 --- a/src/simplecadapi/editor/features.py +++ b/src/simplecadapi/editor/features.py @@ -1002,7 +1002,7 @@ def render_feature( ) role = _COMBINE_ROLE[operation] if spec.combinable else spec.role # the recipe resolves against the body slot of the feature ({BODY} is filled with that name) - body_name = clean.get(spec.body_slot) or clean.get("body") or "" + body_name = next((v for v in (clean.get(spec.body_slot), clean.get("body")) if isinstance(v, str)), "") code = [line.replace("{BODY}", body_name) for line in code] gui = {"spec": spec.id, "v": VERSION, "values": clean} if selections: diff --git a/src/simplecadapi/editor/gui_features.py b/src/simplecadapi/editor/gui_features.py index 66fea478..108cd3a5 100644 --- a/src/simplecadapi/editor/gui_features.py +++ b/src/simplecadapi/editor/gui_features.py @@ -143,8 +143,8 @@ class FeatureService: } ) if product is None and open_bodies and self._implicit_part(): - # no cell builds the Part: the runtime makes it from the open body (one; several are an error it reports) - product = {"cell": None, "body": open_bodies[-1], "implicit": True} + # no cell builds the Part: the runtime makes it from the open bodies (several are the bodies of one Part) + product = {"cell": None, "body": open_bodies[-1], "bodies": list(open_bodies), "implicit": True} return { "features": features, "bodies": [{"name": name, "produces": bodies[name]} for name in order], diff --git a/src/simplecadapi/exporter/_surface_mesh.py b/src/simplecadapi/exporter/_surface_mesh.py index 27d74bc9..1eaaede3 100644 --- a/src/simplecadapi/exporter/_surface_mesh.py +++ b/src/simplecadapi/exporter/_surface_mesh.py @@ -42,7 +42,7 @@ class TessellatedSurfaceMesh: def _product_solids(value: Part | Assembly) -> tuple[Any, ...]: if isinstance(value, Part): - return (value.body,) + return tuple(body.solid for body in value.bodies) # every body of a multi-body part projection = make_compound_from_assembly_rcompound(assembly=value) solids = tuple(projection.solids()) if not solids: diff --git a/src/simplecadapi/exporter/mjcf.py b/src/simplecadapi/exporter/mjcf.py index 455df56f..be6cd0f9 100644 --- a/src/simplecadapi/exporter/mjcf.py +++ b/src/simplecadapi/exporter/mjcf.py @@ -18,6 +18,7 @@ from ..artifacts.assembly_io import materialize_definition from ..artifacts.canonical import parse_canonical_json from ..artifacts.part_definition import PartDefinition from simplecadapi._cpp import Assembly, Part +from ..product.bodies import part_shape from ..product.placement import Placement, relative_placement from ..translator.package_units import ( ProductPackageInput, @@ -677,7 +678,7 @@ def export_product_package_to_mjcf( mesh_path = mesh_root / f"{mesh_name}.obj" _write_obj( mesh_path, - part.body, + part_shape(part), linear_deflection=float(linear_deflection), angular_deflection_degrees=float(angular_deflection_degrees), ) diff --git a/src/simplecadapi/exporter/step.py b/src/simplecadapi/exporter/step.py index 1ef8edfc..79e83881 100644 --- a/src/simplecadapi/exporter/step.py +++ b/src/simplecadapi/exporter/step.py @@ -12,6 +12,7 @@ from typing import Any from ..artifacts import materialize_definition from simplecadapi._cpp import Assembly, Part +from ..product.bodies import part_shape from ..translator.package_units import ( ProductPackageInput, read_product_package_translation_units, @@ -73,7 +74,8 @@ def _native_definitions(root_value: Part | Assembly, units: Any) -> list[dict[st "id": definition_id, "kind": kind, "name": value.name or value.part_id, - "shape": value.body, + # a multi-body part is one STEP product whose shape holds every body + "shape": part_shape(value), "metadata": { "record_kind": "definition", "definition_id": value.part_id, diff --git a/src/simplecadapi/operators/__init__.py b/src/simplecadapi/operators/__init__.py index 26453dc1..d974f9bd 100644 --- a/src/simplecadapi/operators/__init__.py +++ b/src/simplecadapi/operators/__init__.py @@ -217,6 +217,7 @@ from . import boolean # noqa: F401 from . import transform # noqa: F401 from . import selection # noqa: F401 from . import product # noqa: F401 +from .product import inspect_body_overlaps_rlist, measure_part_mass_rmassreport # Python-defined (product/bodies.py) from . import sketch # noqa: F401 __all__ = [ @@ -368,6 +369,8 @@ __all__ = [ "make_wire_from_edges_rwire", "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 12554e16..afbe9ff3 100644 --- a/src/simplecadapi/operators/product.py +++ b/src/simplecadapi/operators/product.py @@ -42,6 +42,7 @@ from simplecadapi._cpp import ( solve_assembly_constraints_rassembly, unground_component_rassembly, ) +from ..product.bodies import inspect_body_overlaps_rlist, measure_part_mass_rmassreport # Python-defined __all__ = [ "add_belt_constraint_rassembly", @@ -69,6 +70,8 @@ __all__ = [ "make_scalar_limit_rscalarlimit", "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 new file mode 100644 index 00000000..b2ac68b5 --- /dev/null +++ b/src/simplecadapi/product/bodies.py @@ -0,0 +1,274 @@ +"""The bodies of a Part: its shape as one value, and the mass of each body. + +A Part holds one Solid or several named bodies (see ``Part.bodies``). Geometry consumers that do not care which body a +face belongs to (STEP, STL, MJCF meshes) read :func:`part_shape`; consumers that do (the preview, the package, mass +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, make_part_rpart + +# density unit -> factor to kg/mm^3 (the model is in millimetres) +_DENSITY_TO_KG_MM3 = { + "kg/mm^3": 1.0, + "kg/mm3": 1.0, + "kg/m^3": 1.0e-9, + "kg/m3": 1.0e-9, + "g/cm^3": 1.0e-6, + "g/cm3": 1.0e-6, + "g/mm^3": 1.0e-3, + "g/mm3": 1.0e-3, +} + + +def part_shape(part: Part) -> Solid | Compound: + """The Solid of a one-body Part, or a Compound of every body of a multi-body Part (in body order). + + The Compound is a geometry view: it is a new shape root and does not carry the bodies' tags. + """ + + if not isinstance(part, Part): + raise TypeError("part must be a Part") + if not part.multi_body: + return part.body + return Compound([body.solid for body in part.bodies]) + + +@dataclass(frozen=True) +class BodyMass: + """Volume, mass and centre of mass of one body (millimetres, kilograms).""" + + body_id: str + name: str | None + volume_mm3: float + mass_kg: float | None + centroid_mm: tuple[float, float, float] + + def to_dict(self) -> dict[str, Any]: + return { + "body_id": self.body_id, + "name": self.name, + "volume_mm3": self.volume_mm3, + "mass_kg": self.mass_kg, + "centroid_mm": list(self.centroid_mm), + } + + +@dataclass(frozen=True) +class MassReport: + """Mass properties of a Part: every body, and the part as a whole.""" + + part_id: str + density_kg_mm3: float | None + bodies: tuple[BodyMass, ...] + volume_mm3: float + mass_kg: float | None + centroid_mm: tuple[float, float, float] + + def body(self, body_id: str) -> BodyMass: + for item in self.bodies: + if item.body_id == body_id: + return item + raise KeyError(f"part has no body_id {body_id!r}") + + def to_dict(self) -> dict[str, Any]: + return { + "part_id": self.part_id, + "density_kg_mm3": self.density_kg_mm3, + "bodies": [item.to_dict() for item in self.bodies], + "volume_mm3": self.volume_mm3, + "mass_kg": self.mass_kg, + "centroid_mm": list(self.centroid_mm), + } + + +def _density(part: Part, density: float | None, density_unit: str | None) -> float | None: + if density is None: + material = part.material + if material is None or material.density is None: + return None + density, density_unit = float(material.density), material.density_unit + unit = str(density_unit or "kg/m^3") + factor = _DENSITY_TO_KG_MM3.get(unit) + if factor is None: + raise ValueError(f"unsupported density unit {unit!r}; use one of {', '.join(sorted(_DENSITY_TO_KG_MM3))}") + if not float(density) > 0.0: + raise ValueError("density must be positive") + return float(density) * factor + + +def measure_part_mass_rmassreport( + part: Part, + *, + density: float | None = None, + density_unit: str | None = None, +) -> MassReport: + """Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole. + + Args: + part: The Part to measure (one body or several). + density: Density to use instead of the material's; ``None`` uses the + Part's material, and without a material density every mass is ``None``. + density_unit: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``, + ``kg/mm^3`` or ``g/mm^3``. + + Returns: + MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``, + ``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part + (``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``). + + Raises: + SimpleCADError: The value is not a Part, or the density or its unit is invalid. + + Usage: + ``scad.measure_part_mass_rmassreport(case).body("lid").mass_kg`` is the mass of + the lid body; ``.mass_kg`` the mass of the whole part. Every body has the + Part's material. + """ + + if not isinstance(part, Part): + raise TypeError("part must be a Part") + rho = _density(part, density, density_unit) + rows: list[BodyMass] = [] + for body in part.bodies: + volume = float(body.solid.get_volume()) + center = body.solid.get_center() # the centre of mass of the solid + rows.append( + BodyMass( + body_id=body.body_id, + name=body.name, + volume_mm3=volume, + mass_kg=None if rho is None else volume * rho, + centroid_mm=(float(center.x), float(center.y), float(center.z)), + ) + ) + total = sum(item.volume_mm3 for item in rows) + centroid = tuple( + sum(item.volume_mm3 * item.centroid_mm[axis] for item in rows) / total if total > 0.0 else 0.0 + for axis in range(3) + ) + return MassReport( + part_id=part.part_id, + density_kg_mm3=rho, + bodies=tuple(rows), + volume_mm3=total, + mass_kg=None if rho is None else total * rho, + centroid_mm=centroid, # type: ignore[arg-type] + ) + + +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/product/packages.py b/src/simplecadapi/product/packages.py index db1f4d77..4ba0152f 100644 --- a/src/simplecadapi/product/packages.py +++ b/src/simplecadapi/product/packages.py @@ -212,9 +212,19 @@ def _definition_refs(definition: Definition) -> list[Mapping[str, Any]]: f"definition blob path {path!r} outside its semantic domain {role.path_prefix!r}" ) refs.append(ref.to_dict()) + for body in getattr(definition, "bodies", ()) or (): # every body of a multi-body part has its own BRep and snapshot + refs.extend(_checked_body_refs((body.body_ref.to_dict(), body.topology_snapshot_ref.to_dict()))) return refs +def _checked_body_refs(refs: tuple[Mapping[str, Any], ...]) -> list[Mapping[str, Any]]: + for ref, prefix in zip(refs, ("body/", "topology/")): + path = str(ref["path"]) + if not path.startswith(prefix): + raise ProductPackageError(f"definition blob path {path!r} outside its semantic domain {prefix!r}") + return list(refs) + + def _definition_closure(root: Definition) -> dict[str, Definition]: definitions: dict[str, Definition] = {} active: set[str] = set() @@ -624,6 +634,10 @@ def _definition_refs_from_manifest(kind: str, manifest: Mapping[str, Any]) -> li f"definition blob path {path!r} outside its semantic domain {role.path_prefix!r}" ) refs.append(ref) + if kind == "single_solid": + cache = manifest.get("solid_cache") + for body in (cache.get("bodies") or ()) if isinstance(cache, Mapping) else (): + refs.extend(_checked_body_refs((body["body_ref"], body["topology_snapshot_ref"]))) return refs diff --git a/src/simplecadapi/product/part.py b/src/simplecadapi/product/part.py index ec9821af..9fd9327c 100644 --- a/src/simplecadapi/product/part.py +++ b/src/simplecadapi/product/part.py @@ -14,12 +14,14 @@ from simplecadapi._cpp import ( # bind_topo.cpp Solid, # (defined by the module itself) + Body, Connector, Material, Part, ) __all__ = [ + "Body", "Connector", "Material", "Part", diff --git a/src/simplecadapi/recording/serializer.py b/src/simplecadapi/recording/serializer.py index 7d22378f..ad2dbeb7 100644 --- a/src/simplecadapi/recording/serializer.py +++ b/src/simplecadapi/recording/serializer.py @@ -31,6 +31,7 @@ from ..errors import raise_harness_error from simplecadapi._cpp import ( AnyShape, Assembly, + Body, Compound, Connector, ConnectorRef, @@ -370,6 +371,14 @@ 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.", + }, "inspect_assembly_constraints_rconstraintreport": { "status": "diagnostic", "reason": "Inspects current constraint state without changing model state.", @@ -3071,7 +3080,24 @@ def _execute_graph( if op_name == "make_part_rpart": ctx.require_params(node.node_id, op_name, params, ("part_id",)) body_outputs = _feature_input_shapes(ctx, graph, outputs, node, params) - if body_outputs: + rows = params.get("bodies") + if body_outputs and isinstance(rows, list) and len(rows) > 1: + # a multi-body part: one recorded input per body, in the order of the rows + if len(body_outputs) != len(rows): + raise ValueError( + f"make_part_rpart node {node.node_id}: {len(rows)} bodies recorded, " + f"{len(body_outputs)} inputs resolved" + ) + result = ops.make_part_rpart( + str(params["part_id"]), + name=cast(Optional[str], params.get("name")), + bodies=[ + Body(str(row["body_id"]), cast(Solid, shape), row.get("name")) + for row, shape in zip(rows, body_outputs) + ], + ) + _store_outputs(node, result) + elif body_outputs: result = ops.make_part_rpart( str(params["part_id"]), cast(Solid, body_outputs[0]), @@ -3914,14 +3940,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/src/simplecadapi/runtime/cache.py b/src/simplecadapi/runtime/cache.py index 6afc296f..41befdc8 100644 --- a/src/simplecadapi/runtime/cache.py +++ b/src/simplecadapi/runtime/cache.py @@ -245,14 +245,14 @@ def _semantic_state(value: Any) -> tuple[int, ...]: ``set_metadata`` and ``auto_tag_faces`` change the shape they are called on, and return the very same object. A memory that hands the same object to a later run would hand out the change as well (the copy on the disk is a fresh object each time and has none of it). Each root of shapes counts its writes (``AnyShape._semantic_revision``); an - entry whose numbers moved since it was kept is not handed out again. A Part is its body, an Assembly its + entry whose numbers moved since it was kept is not handed out again. A Part is its bodies, an Assembly its components; reading a shape, or consuming it in an operator, does not count. """ if hasattr(value, "_semantic_revision"): return (value._semantic_revision(),) if isinstance(value, Part): - return _semantic_state(value.body) + return tuple(n for body in value.bodies for n in _semantic_state(body.solid)) if isinstance(value, Assembly): return tuple(n for component in value.components for n in _semantic_state(component.item)) if isinstance(value, (tuple, frozenset)): diff --git a/src/simplecadapi/runtime/projection.py b/src/simplecadapi/runtime/projection.py index a8399963..b04e74c1 100644 --- a/src/simplecadapi/runtime/projection.py +++ b/src/simplecadapi/runtime/projection.py @@ -36,11 +36,12 @@ from ..build.definition import ( ) from ..build.dependencies import snapshot_file_inputs from ..build.results import AssemblyBuildResult, PartBuildResult +import weakref from typing import Any from simplecadapi._cpp import Assembly, find_registered_node, isolated_recording, Part, Solid from simplecadapi._glue.session import lineage_of -from ..operators.product import make_part_rpart +from ..product.bodies import part_from_bodies from simplecadapi._glue.session import GraphSession from ..recording.source_mapping import cell_sources from .cells import NotebookCells, bound_requirements @@ -123,13 +124,16 @@ def open_bodies(values: Mapping[str, object], read: AbstractSet[str]) -> list[st seen: set[int] = set() candidates: list[tuple[str, object]] = [] for name, value in values.items(): - if name.startswith("_") or name in read or not isinstance(value, Solid) or id(value) in seen: + pieces = isinstance(value, (list, tuple)) and bool(value) and all(isinstance(v, Solid) for v in value) + if name.startswith("_") or name in read or not (isinstance(value, Solid) or pieces) or id(value) in seen: continue seen.add(id(value)) + if pieces: # the pieces of a split cut: one candidate, its lineage is the first piece's + seen.update(id(v) for v in value) # type: ignore[union-attr] candidates.append((name, value)) if len(candidates) < 2: return [name for name, _ in candidates] - nodes = {name: _node(value) for name, value in candidates} + nodes = {name: _node(value[0] if isinstance(value, (list, tuple)) else value) for name, value in candidates} upstream: set[str] = set() for name, node in nodes.items(): if node is not None: @@ -160,21 +164,22 @@ def _ancestors(node: Any) -> set[str]: def _implicit_part(config: NotebookConfig, values: Mapping[str, object], read: AbstractSet[str]) -> Part | None: - """The product of a ``kind = "part"`` notebook without a cell that builds it: its one open body, as a Part with the notebook id. + """The product of a ``kind = "part"`` notebook without a cell that builds it: its open bodies, as a Part with the notebook id. - ``None`` when there is no body yet; several open bodies are an error naming them (join them, or say which one in a - ``make_part_rpart`` cell). + One open body is a one-body Part (body id ``"body"``); several are the bodies of one Part, named by their variables + (the pieces of a split cut ``_1..n``). ``None`` when there is no body yet. """ names = open_bodies(values, read) if not names: return None - if len(names) > 1: - raise ProductNotFoundError( - f"{config.path.name}: a part holds one body and {len(names)} are left open ({', '.join(names)}): " - "join them, or build the Part from one in a cell (make_part_rpart)" - ) - return make_part_rpart(part_id=config.id, body=values[names[0]]) + part = part_from_bodies(config.id, {name: values[name] for name in names}) + _IMPLICIT[id(part)] = part + return part + + +_IMPLICIT: "weakref.WeakValueDictionary[int, Part]" = weakref.WeakValueDictionary() +"""The Parts :func:`_implicit_part` made (outside any cell): :func:`project_product` records them in the definition.""" def project_product( @@ -203,6 +208,11 @@ def project_product( # an assembly records its solve, which must not see the caller's session # or coordinate system. with isolated_recording(), cell_sources(cells): + if _IMPLICIT.get(id(product)) is product: + # the implicit Part of a kind = "part" notebook was made outside any cell: make it here, recorded, so the + # definition has its one result node (the Part), whatever the number of bodies + with session: + product = part_from_bodies(product.part_id, {body.body_id: body.solid for body in product.bodies}) session.validate_graph_ownership(product) for node in session.graph.topological_order(): for expression in node.expressions: diff --git a/src/simplecadapi/scene/preview.py b/src/simplecadapi/scene/preview.py index e014e7dc..a61e5315 100644 --- a/src/simplecadapi/scene/preview.py +++ b/src/simplecadapi/scene/preview.py @@ -29,7 +29,7 @@ import json import struct import threading from collections import OrderedDict -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any, Collection import numpy as np @@ -95,6 +95,8 @@ class PreviewScene: """The solid behind each part key, for :func:`entity_info` (not serialized).""" definitions: dict[str, str] """The definition id each part key belongs to.""" + bodies: dict[str, str] = field(default_factory=dict) + """The body id of each part key that draws one body of a multi-body part (one-body parts are not listed).""" # -- the per-part cache -------------------------------------------------------------- @@ -265,25 +267,46 @@ def compile_preview( parts: dict[str, PartPreview] = {} solids: dict[str, Solid] = {} definitions: dict[str, str] = {} + bodies: dict[str, str] = {} nodes: list[PreviewNode] = [] def add(part: Part, path: tuple[str, ...], placement: Placement, name: str) -> None: - body = part.body - if not isinstance(body, Solid): - raise PreviewError(f"part {part.part_id!r} has no solid body") - preview = preview_solid(body, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance) - parts[preview.key] = preview - solids.setdefault(preview.key, body) - definitions.setdefault(preview.key, part.part_id) - nodes.append( - PreviewNode( - node_id="node/" + "/".join(path), - part_key=preview.key, - definition_id=part.part_id, - display_name=name, - placement=placement, + if not part.multi_body: + body = part.body + if not isinstance(body, Solid): + raise PreviewError(f"part {part.part_id!r} has no solid body") + preview = preview_solid(body, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance) + parts[preview.key] = preview + solids.setdefault(preview.key, body) + definitions.setdefault(preview.key, part.part_id) + nodes.append( + PreviewNode( + node_id="node/" + "/".join(path), + part_key=preview.key, + definition_id=part.part_id, + display_name=name, + placement=placement, + ) + ) + return + # A multi-body part: one node per body, all with the part's placement (bodies are never placed apart). The + # part key names the body as well, so two bodies of the same shape stay two entity namespaces. + for item in part.bodies: + preview = preview_solid(item.solid, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance) + key = f"{preview.key}/body:{item.body_id}" + parts[key] = preview + solids.setdefault(key, item.solid) + definitions.setdefault(key, part.part_id) + bodies.setdefault(key, item.body_id) + nodes.append( + PreviewNode( + node_id="node/" + "/".join(path) + "/body:" + item.body_id, + part_key=key, + definition_id=part.part_id, + display_name=f"{name} / {item.name or item.body_id}", + placement=placement, + ) ) - ) def visit(item: Part | Assembly, path: tuple[str, ...], placement: Placement, name: str) -> None: if isinstance(item, Part): @@ -301,7 +324,7 @@ def compile_preview( visit(product, (root_id,), identity_placement(), root_id) if not nodes: raise PreviewError("the product has nothing to draw") - return PreviewScene(parts=parts, nodes=nodes, solids=solids, definitions=definitions) + return PreviewScene(parts=parts, nodes=nodes, solids=solids, definitions=definitions, bodies=bodies) # -- the wire format ----------------------------------------------------------------- @@ -333,11 +356,15 @@ def encode_preview(scene: PreviewScene, omit: Collection[str] = ()) -> bytes: if key in omit: continue definition = scene.definitions[key] - prefix = f"entity/{definition}/" + body_id = scene.bodies.get(key) + # entity///; a body of a multi-body part: entity//body:// (as in + # the package's scene, scene/product_scene.py) + prefix = f"entity/{definition}/" if body_id is None else f"entity/{definition}/body:{body_id}/" parts.append( { "key": key, "definition_id": definition, + **({"body_id": body_id} if body_id is not None else {}), "positions": array(part.positions, " dict[str, Any]: def entity_info(scene: PreviewScene, entity_id: str) -> dict[str, Any] | None: """The geometric properties of the entity *entity_id* of a part of *scene*. - ``entity///``; returns what the package's entity + ``entity///`` (``entity//body:/...`` for a body of a + multi-body part); returns what the package's entity sidecar holds for it (``properties``, ``geometry``, ``tags``) except the ``source`` links into the feature graph, or ``None`` if there is no such entity. """ _, _, rest = entity_id.partition("entity/") definition, _, tail = rest.partition("/") + body_id = "" + if tail.startswith("body:"): # a body of a multi-body part + segment, _, tail = tail.partition("/") + body_id = segment[len("body:") :] kind, _, topo_id = tail.partition("/") - key = next((k for k, d in scene.definitions.items() if d == definition), None) + key = next( + (k for k, d in scene.definitions.items() if d == definition and scene.bodies.get(k, "") == body_id), + None, + ) if key is None: return None solid = scene.solids[key] diff --git a/src/simplecadapi/scene/prewarm.py b/src/simplecadapi/scene/prewarm.py index 98cf4daa..63757d90 100644 --- a/src/simplecadapi/scene/prewarm.py +++ b/src/simplecadapi/scene/prewarm.py @@ -36,9 +36,9 @@ def solids_of(values: Iterable[Any]) -> Iterator[Solid]: return seen.add(id(item)) if isinstance(item, Part): - body = item.body - if isinstance(body, Solid): - yield body + for body in item.bodies: # every body of a multi-body part + if isinstance(body.solid, Solid): + yield body.solid elif isinstance(item, Assembly): for component in item.components: yield from visit(component.item) diff --git a/src/simplecadapi/scene/product_scene.py b/src/simplecadapi/scene/product_scene.py index 31091d30..5ab79142 100644 --- a/src/simplecadapi/scene/product_scene.py +++ b/src/simplecadapi/scene/product_scene.py @@ -319,6 +319,8 @@ def _part_geometry( str, ]: runtime = materialize_definition(definition) + if runtime.multi_body: + raise ProductSceneError(f"part {definition.definition_id!r} has several bodies: use _body_geometries") body = runtime.body if not isinstance(body, Solid): raise ProductSceneError(f"part {definition.definition_id!r} has no solid body") @@ -330,9 +332,70 @@ def _part_geometry( body=body, feature_graph=_feature_graph(definition), ) + return _solid_geometry( + definition.definition_id, + definition.definition_id, + body, + snapshot, + linear_tolerance=linear_tolerance, + angular_tolerance=angular_tolerance, + ) + + +def _body_geometries( + definition: PartDefinition, + *, + linear_tolerance: float, + angular_tolerance: float, +) -> list[tuple[str, str | None, tuple[list[dict[str, Any]], dict[str, Any], dict[str, bytes], str, str]]]: + """The geometry of every body of a multi-body part: ``(body_id, name, the _solid_geometry tuple)`` in body order. + + Each body has its own GLB and entity document; its entities are ``entity//body://``. + """ + + runtime = materialize_definition(definition) + mark_part_definition_validated(definition, body=runtime.bodies, feature_graph=_feature_graph(definition)) + refs = {item.body_id: item for item in definition.bodies} + out = [] + for body in runtime.bodies: + snapshot = parse_artifact_json(definition.blobs[refs[body.body_id].topology_snapshot_ref.path]) + out.append( + ( + body.body_id, + body.name, + _solid_geometry( + definition.definition_id, + f"{definition.definition_id}/body:{body.body_id}", + body.solid, + snapshot, + linear_tolerance=linear_tolerance, + angular_tolerance=angular_tolerance, + ), + ) + ) + return out + + +def _solid_geometry( + definition_id: str, + namespace: str, + body: Solid, + snapshot: Mapping[str, Any], + *, + linear_tolerance: float, + angular_tolerance: float, +) -> tuple[ + list[dict[str, Any]], + dict[str, Any], + dict[str, bytes], + str, + str, +]: + """GLBs and the entity document of one solid; entity ids are ``entity///``.""" + source_by_key = { (str(item["kind"]), str(item["topo_id"])): _entity_source( - definition.definition_id, item["feature_output"] + definition_id, item["feature_output"] ) for item in snapshot["entities"] } @@ -345,16 +408,16 @@ def _part_geometry( vertices_by_id.setdefault(vertex.topo_id, vertex) vertices = list(vertices_by_id.values()) face_ids = { - face.topo_id: _entity_id(definition.definition_id, "face", face.topo_id) + face.topo_id: _entity_id(namespace, "face", face.topo_id) for face in faces } edge_ids = { - edge.topo_id: _entity_id(definition.definition_id, "edge", edge.topo_id) + edge.topo_id: _entity_id(namespace, "edge", edge.topo_id) for edge in edges } vertex_ids = { vertex.topo_id: _entity_id( - definition.definition_id, "vertex", vertex.topo_id + namespace, "vertex", vertex.topo_id ) for vertex in vertices } @@ -381,7 +444,7 @@ def _part_geometry( _asset_record(line_glb, uri=edge_uri, media_type="model/gltf-binary"), ] - solid_id = _entity_id(definition.definition_id, "solid", body.topo_id) + solid_id = _entity_id(namespace, "solid", body.topo_id) entities: list[dict[str, Any]] = [ { "entity_id": solid_id, @@ -482,7 +545,7 @@ def _part_geometry( ) entity_document = { "schema_version": "2.0", - "definition_id": definition.definition_id, + "definition_id": definition_id, "geometry_asset_id": geometry_hash, "edge_asset_id": edge_hash, "entities": sorted(entities, key=lambda item: item["entity_id"]), @@ -544,6 +607,7 @@ def _build_nodes( definitions: Mapping[str, Definition], geometry_ids: Mapping[str, str], entity_ids: Mapping[str, str], + body_assets: Mapping[str, list[tuple[str, str | None, str, str]]] = {}, ) -> tuple[ list[dict[str, Any]], dict[str, list[str]], @@ -589,6 +653,26 @@ def _build_nodes( }, } ) + part_node = nodes[-1] + for body_id, body_name, geometry_id, entity_id in body_assets.get(definition.definition_id, ()): + # a body of a multi-body part: a solid node under the part node, at the part's origin + nodes.append( + { + "node_id": f"{node_id}/body:{body_id}", + "parent_node_id": node_id, + "display_name": body_name or body_id, + "node_kind": "solid", + "definition_id": definition.definition_id, + "definition_kind": definition.definition_kind, + "component_id": None, + "instance_id": None, + "transform": identity_placement().to_dict(), + "geometry_asset_id": geometry_id, + "entity_asset_id": entity_id, + "material_id": part_node["material_id"], + "properties": {"body_id": body_id}, + } + ) if isinstance(definition, AssemblyDefinition): for instance in definition.instances: child = definitions[instance.definition_id] @@ -819,7 +903,7 @@ def _camera(part_definitions: list[PartDefinition]) -> dict[str, Any]: bounds = [] for definition in part_definitions: part = materialize_definition(definition) - bounds.append(solid_asset_bounds(part.body)) + bounds.extend(solid_asset_bounds(body.solid) for body in part.bodies) minimum = [min(item[0][axis] for item in bounds) for axis in range(3)] maximum = [max(item[1][axis] for item in bounds) for axis in range(3)] target = [(minimum[axis] + maximum[axis]) * 0.5 for axis in range(3)] @@ -954,7 +1038,21 @@ def compile_product_scene( for definition in definitions.values() if isinstance(definition, PartDefinition) ] + body_assets: dict[str, list[tuple[str, str | None, str, str]]] = {} for definition in sorted(part_definitions, key=lambda item: item.definition_id): + if definition.bodies: # a multi-body part: one GLB and entity document per body, drawn by child nodes + rows = [] + for body_id, body_name, (records, entity_record, part_blobs, geometry_id, entity_id) in _body_geometries( + definition, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance + ): + for record in records: + geometry_assets_by_id.setdefault(record["asset_id"], record) + if all(item["asset_id"] != entity_record["asset_id"] for item in entity_assets): + entity_assets.append(entity_record) + blobs.update(part_blobs) + rows.append((body_id, body_name, geometry_id, entity_id)) + body_assets[definition.definition_id] = rows + continue geometry_records, entity_record, part_blobs, geometry_id, entity_id = ( _part_geometry( definition, @@ -970,7 +1068,7 @@ def compile_product_scene( entity_ids[definition.definition_id] = entity_id nodes, occurrences, children = _build_nodes( - root, definitions, geometry_ids, entity_ids + root, definitions, geometry_ids, entity_ids, body_assets ) connectors, connector_index = _connectors( definitions, feature_graphs, occurrences diff --git a/test/test_editor.py b/test/test_editor.py index c7e1e33b..208c6e04 100644 --- a/test/test_editor.py +++ b/test/test_editor.py @@ -857,7 +857,10 @@ class ApiIndexTest(unittest.TestCase): part = self.scad["Part"] self.assertEqual(part["k"], "c") names = [p["n"] for p in part["p"]] - self.assertEqual([p["n"] for p in part["p"] if p["r"]], ["part_id", "body"]) + # a Part takes one ``body`` or several ``bodies`` (multi-body parts), so only part_id is required + self.assertEqual([p["n"] for p in part["p"] if p["r"]], ["part_id"]) + self.assertIn("body", names) + self.assertIn("bodies", names) self.assertFalse([n for n in names if n.startswith("_")]) def test_namespaces_and_submodules(self) -> None: diff --git a/test/test_editor_features.py b/test/test_editor_features.py index c21afebb..a69c1d87 100644 --- a/test/test_editor_features.py +++ b/test/test_editor_features.py @@ -304,7 +304,7 @@ def test_a_blank_notebook_gets_its_product_with_the_first_feature(tmp_path): snap = service.snapshot() assert [f["slug"] for f in snap["features"]] == ["base"] # the header says kind = "part": the runtime makes the Part from the open body, no product cell is written - assert snap["product"] == {"cell": None, "body": "base", "implicit": True} + assert snap["product"] == {"cell": None, "body": "base", "bodies": ["base"], "implicit": True} assert "make_part_rpart" not in path.read_text() # a part holds one solid: the new cylinder says how it meets the body, so no second body is left behind assert service.snapshot()["defaults"]["cylinder"]["operation"] == "join" diff --git a/test/test_multi_body_part.py b/test/test_multi_body_part.py new file mode 100644 index 00000000..8c9d1a08 --- /dev/null +++ b/test/test_multi_body_part.py @@ -0,0 +1,334 @@ +"""Multi-body parts: one Part, several named solids kept apart (not an assembly). + +The spike of design-docs/multi-solid-design.md: a Part made from ``bodies={"base": ..., "lid": ...}`` keeps both +solids, previews them as two nodes, packages each with its own BRep and topology snapshot, exports one STEP product +holding both, reports the mass of each body, and survives the notebook cell cache. One-body Parts are unchanged. +""" + +from __future__ import annotations + +import copy +import pickle +import re +import tempfile +import unittest +from pathlib import Path + +import simplecadapi as scad +from simplecadapi.artifacts import materialize_definition +from simplecadapi.exporter.step import export_product_package_to_step +from simplecadapi.product.packages import build_product_package, encode_product_package, load_product_package +from simplecadapi.runtime import run_notebook +from simplecadapi.scene.preview import compile_preview, decode_preview_header, encode_preview, entity_info + +from test_notebook_runtime import NotebookTestCase, cell, notebook_text + + +def _base() -> scad.Solid: + return scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base") + + +def _lid() -> scad.Solid: + return scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid") + + +def _case() -> scad.Part: + return scad.make_part_rpart(part_id="case", bodies={"base": _base(), "lid": _lid()}) + + +def _tags(solid: scad.Solid) -> set[str]: + return {tag for face in solid.faces() for tag in face._tags} + + +class TestMultiBodyPartValue(unittest.TestCase): + def test_bodies_are_kept_apart_in_order(self) -> None: + case = _case() + self.assertTrue(case.multi_body) + self.assertEqual(case.body_ids(), ("base", "lid")) + self.assertEqual([type(body).__name__ for body in case.bodies], ["Body", "Body"]) + self.assertAlmostEqual(case.get_body("lid").solid.get_volume(), 800.0, places=6) + self.assertIn("lid.face.top", _tags(case.get_body("lid").solid)) + self.assertEqual(case.to_dict()["bodies"], [{"body_id": "base", "name": None}, {"body_id": "lid", "name": None}]) + + def test_body_is_refused_on_a_multi_body_part(self) -> None: + with self.assertRaisesRegex(TypeError, r"has 2 bodies \(base, lid\)"): + _case().body + with self.assertRaises(KeyError): + _case().get_body("hinge") + + def test_bodies_may_be_body_values_with_names(self) -> None: + case = scad.make_part_rpart( + part_id="case", bodies=[scad.Body("base", _base(), "Base"), scad.Body("lid", _lid(), name="Lid")] + ) + self.assertEqual([body.name for body in case.bodies], ["Base", "Lid"]) + + def test_bad_bodies_are_refused(self) -> None: + with self.assertRaises(Exception): + scad.make_part_rpart(part_id="case", body=_base(), bodies={"lid": _lid()}) + with self.assertRaises(Exception): + scad.make_part_rpart(part_id="case") + with self.assertRaisesRegex(Exception, "duplicate body_id"): + scad.Part(part_id="case", bodies=[scad.Body("a", _base()), scad.Body("a", _lid())]) + with self.assertRaises(Exception): + scad.make_part_rpart(part_id="case", bodies={"not an id": _base(), "lid": _lid()}) + with self.assertRaises(Exception): + scad.make_part_rpart(part_id="case", bodies={"base": _base(), "lid": "lid"}) + + def test_a_one_body_part_is_what_it_always_was(self) -> None: + part = scad.make_part_rpart(part_id="plate", body=_base()) + self.assertFalse(part.multi_body) + self.assertEqual(part.body_ids(), ("body",)) + self.assertTrue(part.body.same_topology(part.bodies[0].solid)) + self.assertNotIn("bodies", part.to_dict()) + + def test_pickle_and_deepcopy_keep_every_body_and_its_tags(self) -> None: + case = _case().with_material(scad.make_material_rmaterial(material_id="pp", density=900.0, density_unit="kg/m^3")) + for again in (pickle.loads(pickle.dumps(case)), copy.deepcopy(case)): + self.assertEqual(again.body_ids(), ("base", "lid")) + self.assertEqual(again.material.material_id, "pp") + self.assertEqual(_tags(again.get_body("lid").solid), _tags(case.get_body("lid").solid)) + one = pickle.loads(pickle.dumps(scad.make_part_rpart(part_id="plate", body=_base()))) + self.assertFalse(one.multi_body) + + def test_material_and_connectors(self) -> None: + material = scad.make_material_rmaterial(material_id="al", density=2.7, density_unit="g/cm^3") + case = scad.assign_material_rpart(_case(), material) + self.assertEqual(case.body_ids(), ("base", "lid")) + connector = scad.make_placement_connector_rconnector( + connector_id="mount", placement=scad.identity_placement_rplacement() + ) + with self.assertRaisesRegex(Exception, "multi-body"): + scad.add_connector_rpart(case, connector) + + def test_an_assembly_of_a_multi_body_part_flattens_every_body(self) -> None: + rig = scad.make_assembly_rassembly(assembly_id="rig") + rig = scad.add_component_rassembly( + assembly=rig, item=_case(), component_id="case", placement=scad.make_placement_rplacement(origin=(0, 0, 5)) + ) + compound = scad.make_compound_from_assembly_rcompound(assembly=rig) + self.assertEqual(len(compound.solids()), 2) + + +class TestMultiBodyReplay(unittest.TestCase): + def test_a_recorded_multi_body_part_replays_with_its_bodies(self) -> None: + with scad.GraphSession() as session: + _case() + replayed = [item for item in scad.replay_model_json(scad.export_model_json(session)) if isinstance(item, scad.Part)] + self.assertEqual([part.body_ids() for part in replayed], [("base", "lid")]) + self.assertAlmostEqual(replayed[0].get_body("lid").solid.get_volume(), 800.0, places=6) + + +class TestMultiBodyMass(unittest.TestCase): + def test_mass_of_each_body_and_of_the_part(self) -> None: + material = scad.make_material_rmaterial(material_id="al", density=2.7, density_unit="g/cm^3") + report = scad.measure_part_mass_rmassreport(scad.assign_material_rpart(_case(), material)) + self.assertEqual([item.body_id for item in report.bodies], ["base", "lid"]) + self.assertAlmostEqual(report.body("base").volume_mm3, 4000.0, places=6) + self.assertAlmostEqual(report.body("base").mass_kg, 4000.0 * 2.7e-6, places=12) + self.assertAlmostEqual(report.body("lid").mass_kg, 800.0 * 2.7e-6, places=12) + self.assertAlmostEqual(report.mass_kg, 4800.0 * 2.7e-6, places=12) + self.assertAlmostEqual(report.body("lid").centroid_mm[0], 40.0, places=6) + self.assertAlmostEqual(report.centroid_mm[0], 800.0 * 40.0 / 4800.0, places=6) + + def test_without_a_density_masses_are_none(self) -> None: + report = scad.measure_part_mass_rmassreport(_case()) + self.assertIsNone(report.mass_kg) + self.assertAlmostEqual(report.volume_mm3, 4800.0, places=6) + override = scad.measure_part_mass_rmassreport(_case(), density=1000.0) + self.assertAlmostEqual(override.body("lid").mass_kg, 800.0e-6, places=12) + + def test_a_one_body_part_has_one_row(self) -> None: + report = scad.measure_part_mass_rmassreport(scad.make_part_rpart(part_id="plate", body=_base())) + self.assertEqual([item.body_id for item in report.bodies], ["body"]) + + +class TestMultiBodyPreview(unittest.TestCase): + def test_each_body_is_a_node_with_its_own_entities(self) -> None: + scene = compile_preview(_case()) + header = decode_preview_header(encode_preview(scene)) + self.assertEqual([node["node_id"] for node in header["nodes"]], ["node/case/body:base", "node/case/body:lid"]) + self.assertEqual({part["body_id"] for part in header["parts"]}, {"base", "lid"}) + lid = next(part for part in header["parts"] if part["body_id"] == "lid") + self.assertTrue(lid["solid_entity_id"].startswith("entity/case/body:lid/solid/")) + self.assertTrue(all(g["entity_id"].startswith("entity/case/body:lid/face/") for g in lid["face_groups"])) + info = entity_info(scene, lid["solid_entity_id"]) + self.assertAlmostEqual(info["properties"]["volume"], 800.0, places=6) + face = entity_info(scene, lid["face_groups"][0]["entity_id"]) + self.assertEqual(face["kind"], "face") + self.assertTrue(any(tag.startswith("lid.face.") for tag in face["tags"])) + + def test_two_bodies_of_the_same_shape_stay_two(self) -> None: + a = scad.make_box_rsolid(5.0, 5.0, 5.0) + b = scad.make_box_rsolid(5.0, 5.0, 5.0) + scene = compile_preview(scad.make_part_rpart(part_id="pair", bodies={"a": a, "b": b})) + self.assertEqual(len(scene.nodes), 2) + self.assertEqual(len(scene.parts), 2) + + def test_a_one_body_part_previews_as_before(self) -> None: + header = decode_preview_header(encode_preview(compile_preview(scad.make_part_rpart(part_id="plate", body=_base())))) + self.assertEqual([node["node_id"] for node in header["nodes"]], ["node/plate"]) + self.assertNotIn("body_id", header["parts"][0]) + self.assertTrue(header["parts"][0]["solid_entity_id"].startswith("entity/plate/solid/")) + + +CASE = notebook_text( + cell( + """ + base = scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base") + lid = scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid") + """, + returns="base, lid", + ), + cell( + 'case = scad.make_part_rpart(part_id=scad.notebook_id(), bodies={"base": base, "lid": lid})', + reads="base, lid", + returns="case", + ), + table='id = "case"', +) + + +class TestMultiBodyNotebook(NotebookTestCase): + def setUp(self) -> None: + super().setUp() + self.case = self.write("case.py", CASE) + + def test_the_cell_cache_restores_a_multi_body_product(self) -> None: + first = run_notebook(self.case) + second = run_notebook(self.case) + self.assertEqual(self.statuses(second), ["ran", "cached", "cached"]) + self.assertEqual(first.definition.content_hash, second.definition.content_hash) + self.assertEqual([item.body_id for item in second.definition.bodies], ["base", "lid"]) + + def test_the_package_holds_both_bodies_with_their_tags(self) -> None: + definition = run_notebook(self.case).definition + manifest = definition.to_dict() + self.assertEqual([row["body_id"] for row in manifest["solid_cache"]["bodies"]], ["base", "lid"]) + loaded = load_product_package(encode_product_package(build_product_package(definition))) + part = materialize_definition(loaded) # the package's root definition, read back from its bytes + self.assertEqual(part.body_ids(), ("base", "lid")) + self.assertIn("lid.face.top", _tags(part.get_body("lid").solid)) + self.assertIn("base.face.top", _tags(part.get_body("base").solid)) + self.assertAlmostEqual(scad.measure_part_mass_rmassreport(part).body("lid").volume_mm3, 800.0, places=6) + + def test_the_scene_draws_each_body_as_a_solid_node(self) -> None: + from simplecadapi.scene.product_scene import compile_product_scene + + manifest = compile_product_scene(run_notebook(self.case).definition).manifest + nodes = {node["node_id"]: node for node in manifest["nodes"]} + self.assertIsNone(nodes["node/case"]["geometry_asset_id"]) + self.assertEqual(nodes["node/case/body:lid"]["node_kind"], "solid") + self.assertEqual(nodes["node/case/body:lid"]["parent_node_id"], "node/case") + self.assertIsNotNone(nodes["node/case/body:base"]["geometry_asset_id"]) + self.assertNotEqual(nodes["node/case/body:base"]["entity_asset_id"], nodes["node/case/body:lid"]["entity_asset_id"]) + + def test_step_export_writes_one_product_with_both_solids(self) -> None: + data = encode_product_package(build_product_package(run_notebook(self.case).definition)) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "case.step" + export_product_package_to_step(data, path) + text = path.read_text(encoding="utf-8", errors="replace") + self.assertEqual(len(re.findall(r"MANIFOLD_SOLID_BREP", text)), 2) + self.assertEqual(len(re.findall(r"= PRODUCT\(", text)), 1) + + def test_a_one_body_definition_has_no_bodies_list(self) -> None: + self.write( + "plate.py", + notebook_text( + cell("plate = scad.make_part_rpart(part_id=scad.notebook_id(), body=scad.make_box_rsolid(5.0, 5.0, 1.0))", returns="plate"), + table='id = "plate"', + ), + ) + definition = run_notebook(self.root / "plate.py").definition + self.assertNotIn("bodies", definition.to_dict()["solid_cache"]) + 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()