diff --git a/docs/skill/references/docs/api/CellReport.md b/docs/skill/references/docs/api/CellReport.md index b95d4985..7a072560 100644 --- a/docs/skill/references/docs/api/CellReport.md +++ b/docs/skill/references/docs/api/CellReport.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class CellReport(name: str, key: str, status: CellStatus) +class CellReport(name: str, key: str, status: CellStatus, tag_splits: tuple[dict, ...] = ()) ``` *Source: runtime/runner.py* diff --git a/docs/skill/references/docs/api/ElementRef.md b/docs/skill/references/docs/api/ElementRef.md index 8e689281..7e800da2 100644 --- a/docs/skill/references/docs/api/ElementRef.md +++ b/docs/skill/references/docs/api/ElementRef.md @@ -14,7 +14,7 @@ class ElementRef(kind: str, feature: str = '', op: str = '', role: Optional[str] ## Description -A stable reference to one face, edge or vertex; ``repr()`` is the code that makes it. +A stable reference to one face, edge, vertex or solid; ``repr()`` is the code that makes it. Fields: ``kind``; ``feature`` and ``op`` (where the entity was born); then exactly one of ``role`` (its kernel role, with ``ordinal`` saying which of the entities with that role), ``topo`` (its position in that output, for an diff --git a/docs/skill/references/docs/api/README.md b/docs/skill/references/docs/api/README.md index 65f0022f..2f701424 100644 --- a/docs/skill/references/docs/api/README.md +++ b/docs/skill/references/docs/api/README.md @@ -419,6 +419,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi - [inspect_surface_rsurfacedata](inspect_surface_rsurfacedata.md) *(from operators/geometry.py)* `top-level` - [key](key.md) *(from ql.py)* `submodule:ql` - [linear_pattern_rsolidlist](linear_pattern_rsolidlist.md) *(from operators/transform.py)* `top-level` +- [list_tag_splits](list_tag_splits.md) *(from operators/selection.py)* `top-level` - [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` diff --git a/docs/skill/references/docs/api/apply_tag_rselection.md b/docs/skill/references/docs/api/apply_tag_rselection.md index 3f42f46a..c817661a 100644 --- a/docs/skill/references/docs/api/apply_tag_rselection.md +++ b/docs/skill/references/docs/api/apply_tag_rselection.md @@ -50,7 +50,7 @@ later. A body of a Part is named with ``set_body_appearance_rpart(part, body_id, ### (default ``"continuation_fragment"`` -- **Description**: kept on continued faces and on the fragments of a split face). +- **Description**: kept on continued faces; the pieces of a split face carry ``.split1`` .. ``.split`` instead, see ``list_tag_splits``). ## Returns diff --git a/docs/skill/references/docs/api/list_tag_splits.md b/docs/skill/references/docs/api/list_tag_splits.md new file mode 100644 index 00000000..204a2b6c --- /dev/null +++ b/docs/skill/references/docs/api/list_tag_splits.md @@ -0,0 +1,45 @@ +# list_tag_splits + +## API Definition + +```python +def list_tag_splits(shape) +``` + +*Source: operators/selection.py* + +## Import Surface + +- top-level: `from simplecadapi import list_tag_splits` + +## Description + +The tagged entities that the operations behind a shape split into pieces. + +A tag follows its entity the way a reference does: while the entity stays one entity it keeps the tag; when an +operation splits it (a slot cut across a tagged face, a cut through a tagged body), the tag does not go to every +piece. Each piece carries ``.split1`` .. ``.split`` instead, numbered as the operation recorded them (by +centre, then size), and ``ql.tag("")`` finds none of them. Name the pieces you mean with tags of your own after the +split, or select them with ``ql.tag(".split1")`` / ``ql.tag(".*")``. + +## Parameters + +### shape + +- **Description**: A shape made in a recording session (its history is read). + +## Returns + +list[dict]: One row per split, upstream first: ``tag`` (the tag the entity had), ``into`` (the tags of the pieces, +in piece order), ``node_id`` and ``op`` (the operation that split it), ``source_topo_id`` and ``pieces`` +(``output_slot``, ``kind``, ``topo_id`` of each piece in that operation's output). Empty for a shape without +recorded history. + +## Examples + +```python +>>> top = scad.apply_tag_rselection(box, scad.ql.faces().where(scad.ql.prop("geom.center.z", ">=", 9.9)), "mount.top") +>>> halves = scad.cut_rsolid(top, slot) # the slot splits the top face (and the body) +>>> [row["into"] for row in scad.list_tag_splits(halves[0])] +[['mount.top.split1', 'mount.top.split2']] +``` diff --git a/docs/skill/references/docs/api/tag.md b/docs/skill/references/docs/api/tag.md index afab3f6a..84dd0e10 100644 --- a/docs/skill/references/docs/api/tag.md +++ b/docs/skill/references/docs/api/tag.md @@ -18,8 +18,10 @@ Build a tag predicate for QL filtering. Tags are a view over the recorded history: a tag assigned in a ``GraphSession`` reaches every entity its target became through later -operations (a face cut in two keeps it on both pieces), as its lineage -policy allows. ``local`` is what the entity itself stores, ``inherited`` +operations as its lineage policy allows. A tag follows its entity as a +reference does: an entity an operation splits keeps it on none of its +pieces, which carry ``.split1`` .. ``.split`` instead +(``list_tag_splits``); ``ql.tag(".*")`` finds them all. ``local`` is what the entity itself stores, ``inherited`` what containing entities pass down, ``lineage`` what the history carries, and ``effective`` (the default) all three. diff --git a/docs/skill/references/docs/guides/notebook-runtime.md b/docs/skill/references/docs/guides/notebook-runtime.md index 0b3086aa..ffd1ffac 100644 --- a/docs/skill/references/docs/guides/notebook-runtime.md +++ b/docs/skill/references/docs/guides/notebook-runtime.md @@ -143,7 +143,9 @@ sca run bracket.py --no-cache # run every cell `--set` values are Python literals, else strings; the option may repeat. The report lists the definition id, kind, revision, `content_hash`, and every cell's status: `ran`, `cached` (restored from the cell cache), or `skipped` -(replaced by an override). +(replaced by an override). A cell whose operations split a tagged entity also +lists `tag_splits` (`{tag, into, op}`: the pieces carry `.split1` ..), ran or +restored; a cell that runs prints a `TagSplitWarning` at its place in the file. From Python: diff --git a/docs/skill/references/domains/editor-gui-features.md b/docs/skill/references/domains/editor-gui-features.md index e257238f..15838720 100644 --- a/docs/skill/references/domains/editor-gui-features.md +++ b/docs/skill/references/domains/editor-gui-features.md @@ -65,6 +65,10 @@ HOLE_DIAMETER = scad.var(name="hole_diameter", default=6.0, unit="mm", comment=" - A sketch on a workplane has `plane={"workplane": "wp", origin, x_axis, y_axis}` in its `# gui:` document and `plane=wp` in its code: the frame in the document is only for drawing before the cell runs; the cell follows `wp`. A workplane cell reads the body without consuming it (the body stays the open body / product). +- A split tag is shown, not hidden: when an operation splits a tagged entity (its pieces carry `.split1` ..), the + viewport highlights each piece in its own colour and a notice names the tag, the operation and the pieces' tags + (hide the highlight or dismiss it there). `sca snapshot` lists the same as `tag_splits`. Read it as a question: + was the split meant? If later code needs a piece, tag it after the split. - Unattended: the buttons are not available; write the cells yourself (see `discipline/notebook-cell-design.md`). ## The same operations from the command line diff --git a/docs/skill/references/ql-playbook.md b/docs/skill/references/ql-playbook.md index 39507466..a873e54e 100644 --- a/docs/skill/references/ql-playbook.md +++ b/docs/skill/references/ql-playbook.md @@ -55,8 +55,11 @@ around it as shown. (`apply_tag_rselection`, an op-kwarg tag such as `top_face_tag=`) is a graph node; `ql.tag(...)` on a later shape finds the entities the tagged ones became, through each operation's kernel history, as the tag's - lineage policy allows (default `continuation_fragment`: a face cut in two - keeps the tag on both pieces). Verified per family in + lineage policy allows. A tag follows its entity as a reference does: an + entity an operation **splits** keeps it on no piece; the pieces carry + `.split1` .. (by centre, then size), reported by `TagSplitWarning`, + `sca run` (`tag_splits`), `scad.list_tag_splits(shape)` and the editor's + highlight. Tag the pieces later code needs. Verified per family in `test/test_element_ref_history.py` (audit). For one particular entity, prefer a reference (rule 6) over a tag made only to find it again: @@ -68,22 +71,19 @@ around it as shown. | `origin_role("body"/"tool")` | parent argument of a boolean | single-step only | no | | `output_role("")` | `extrusion.end`, `box.top`, `fillet.patch` | single-step only | own op only | - "Single-step" means the metadata describes the last operation that touched - the shape; the next tracked operation overwrites it. A tag ends where the - history says the entity ends: a face a cut removes, a face a feature - replaces by a generated one (a fillet's patch is a new face, not the - edge), or an operation that records no history. `scad.explain_tag(face, - tag)` shows the binding and the lineage that carried it. The `lineage` - scope is the carried part alone; `effective` (the default) includes it. + "Single-step": the next tracked operation overwrites it. A tag ends where the history says + the entity ends (a face a cut removes, one a fillet's patch replaces, an op without history). + `scad.explain_tag(face, tag)` shows the binding and what carried it; scope `lineage` is + the carried part alone, `effective` (default) includes it. 6. **A rule is a query; a particular entity is a reference.** `ql` picks - whatever matches a rule; `scad.ref` means *this* face or edge and stays it - through booleans, blends, copies and edits, e.g. - `scad.ref.faces(scad.ref.face("base", "make_box_rsolid", role="box.top"))` - or `scad.ref.edge("base", "make_box_rsolid", between=("box.front", "box.top"))` - (`scad.ref.of(face, part)` makes one; `scad.ql.ref(r)` uses one in a query). - A split or lost reference raises `ElementRefError` with the candidates; - never fall back to a geometric window. See `ql-recipes.md` (stable reference). + whatever matches a rule; `scad.ref` means *this* face, edge or solid through booleans, + blends, copies and edits, e.g. + `scad.ref.faces(scad.ref.face("base", "make_box_rsolid", role="box.top"))` or + `scad.ref.edge("base", "make_box_rsolid", between=("box.front", "box.top"))` + (`scad.ref.of(face, part)` makes one, of a solid too; `scad.ql.ref(r)` uses one in a query). + A split or lost reference raises `ElementRefError` with the candidates; never fall back to a + geometric window. See `ql-recipes.md` (stable reference). ## The selection loop (card before cardinality) diff --git a/docs/skill/references/ql-recipes.md b/docs/skill/references/ql-recipes.md index a9e671b1..e53f72e3 100644 --- a/docs/skill/references/ql-recipes.md +++ b/docs/skill/references/ql-recipes.md @@ -169,6 +169,11 @@ with scad.GraphSession(namespace="base"): # in a notebook: the cell's "# - Outcomes: `ok`; `merged` (one face that absorbed others: a coplanar union; it runs); `split` (several pieces, listed in a geometric order, until `piece=i` says which); `lost` (where and why; with a guard, the closest look-alikes). `ref.choose(i, part)` writes a choice back: a piece, or a new reference at a look-alike. +- A **solid** (a body) has a reference too: `scad.ref.of(piece, piece)` gives `scad.ref.solid("slot", "make_cut_rsolid_list", + slot=1, guard=("SOLID", centre, volume))`, its place in the output of the op that made it. A fillet, shell or move + continues it, a union merges it, a cut that splits it splits it. Resolve it in a solid or in the pieces of a split + body (`r.one(pieces)`); `scad.ref.solids(r)` is the selection. Over pieces, a face or edge reference selects on the + piece it lies on (`scad.fillet_rsolid(pieces, scad.ref.edges(rim), 1.0)` blends that piece only). Write the printed code into the cell that uses it (not the query that found it): it reads as what it means and the editor reads it back. When a reference fails, read the error, do not widen anything: diff --git a/editor-web/src/App.tsx b/editor-web/src/App.tsx index ed74c978..c27477b9 100644 --- a/editor-web/src/App.tsx +++ b/editor-web/src/App.tsx @@ -15,6 +15,7 @@ import { sideStyle, useModeTransition } from "@/lib/useModeTransition"; import { AssemblyPanel } from "@/components/AssemblyPanel"; import { ConnectorGizmos, type Gizmo } from "@/components/ConnectorGizmos"; import { WorkplanePatches } from "@/components/WorkplanePatches"; +import { TagSplits, parseTagSplits, type TagSplit } from "@/components/TagSplits"; import { parseWorkplanes, resolvePlane, workplanePlane, workplaneRequest, type WorkplaneFrame } from "@/lib/workplanes"; import { fitDistanceMm } from "@/lib/sketch-view"; import { viewPose } from "@/lib/sketch-plane"; @@ -101,6 +102,7 @@ export function App() { const [picked, setPicked] = useState[]>([]); // The notebook's workplanes as the kernel reported them, and the one Space made (or chose) last: new sketches go on it. const [workplanes, setWorkplanes] = useState([]); + const [tagSplits, setTagSplits] = useState([]); const [activeWorkplane, setActiveWorkplane] = useState(null); const [selectionMode, setSelectionMode] = useState("solid"); const [sceneVersion, setSceneVersion] = useState(0); @@ -307,6 +309,7 @@ export function App() { }); socket.on("notebook.features", (envelope) => setFeatures((envelope["features"] as NotebookFeature[]) ?? [])); socket.on("workplanes", (envelope) => setWorkplanes(parseWorkplanes(envelope["workplanes"]))); + socket.on("tag_splits", (envelope) => setTagSplits(parseTagSplits(envelope["splits"]))); socket.on("preview", (envelope) => { setLoading(null); @@ -1093,6 +1096,7 @@ export function App() { onHover={setHoverSketch} /> {viewRef.current && workplanes.length > 0 && } + {!sketching && viewRef.current && } {!sketching && viewRef.current && gizmos.length > 0 && ( )} diff --git a/editor-web/src/components/TagSplits.tsx b/editor-web/src/components/TagSplits.tsx new file mode 100644 index 00000000..fbaf18a4 --- /dev/null +++ b/editor-web/src/components/TagSplits.tsx @@ -0,0 +1,80 @@ +import { useEffect, useMemo, useState } from "react"; +import { Scissors } from "lucide-react"; + +import type { SceneView } from "@/scene/scene-view"; + +/** A tagged entity an operation split (the server's `tag_splits`, from `scad.list_tag_splits`): the pieces carry + * `.split`, and `pieces` lists the scene entities of each. */ +export type TagSplit = { + tag: string; + into: string[]; + op: string; + pieces: { piece: number; node_id: string; entity_id: string }[]; +}; + +/** One colour per piece, told apart at a glance on any body colour. */ +export const PIECE_COLORS = ["#e4572e", "#17a3b8", "#e8b10c", "#5fa83a", "#8a5cc2", "#d9479a"]; + +export function parseTagSplits(value: unknown): TagSplit[] { + if (!Array.isArray(value)) return []; + return value.filter( + (row): row is TagSplit => + !!row && typeof row.tag === "string" && Array.isArray(row.into) && typeof row.op === "string" && Array.isArray(row.pieces), + ); +} + +/** Highlights the pieces of every split tag in the viewport, each piece its own colour, and says what was split, so the + * person (or an agent reading the viewport image) can judge whether the split was meant. Dismissed until the splits + * change; the highlight can be turned off while the notice stays. */ +export function TagSplits({ view, splits, sceneVersion }: { view: SceneView; splits: TagSplit[]; sceneVersion: number }) { + const signature = useMemo(() => JSON.stringify(splits.map((row) => [row.tag, row.into, row.op])), [splits]); + const [dismissed, setDismissed] = useState(null); + const [shown, setShown] = useState(true); + const open = splits.length > 0 && dismissed !== signature; + const highlight = open && shown; + + useEffect(() => { + if (!highlight) return; + const keys: string[] = []; + for (const row of splits) { + for (const piece of row.pieces) { + view.addMark(piece.node_id, piece.entity_id, PIECE_COLORS[piece.piece % PIECE_COLORS.length]); + keys.push(`${piece.node_id}::${piece.entity_id}`); + } + } + return () => keys.forEach((key) => view.removeMark(key)); + }, [view, splits, highlight, sceneVersion]); + + if (!open) return null; + return ( +
+
+ + {splits.length === 1 ? "A tagged entity was split" : `${splits.length} tagged entities were split`} +
+ {splits.map((row) => ( +
+ + {row.op} split {row.tag} into {row.into.length}; the tag names none of them: + + + {row.into.map((name, index) => ( + + + {name} + + ))} + +
+ ))} +
+ + +
+
+ ); +} diff --git a/src/cpp/bindings/python/bind_semantic.cpp b/src/cpp/bindings/python/bind_semantic.cpp index bdd6655f..4510e78e 100644 --- a/src/cpp/bindings/python/bind_semantic.cpp +++ b/src/cpp/bindings/python/bind_semantic.cpp @@ -12,6 +12,7 @@ #include "scad/core/error.hpp" #include "scad/ql/selector.hpp" #include "scad/semantic/finalize.hpp" +#include "scad/reactive/tag_view.hpp" #include "scad/semantic/selection.hpp" #include "scad/topo/tag_factories.hpp" @@ -682,6 +683,36 @@ void bind_operators(py::module_& m) { [](const Shape& shape, const std::string& tag, TagScope scope) { return explain_tag(shape, tag, scope); }, py::arg("shape"), py::arg("tag"), py::arg("scope") = TagScope::Effective, "Explain every visible binding that produces a tag token."); + m.def( + "list_tag_splits", + [](const Shape& shape) { + py::list out; + const auto opaque = shape.root().graph_node(); + if (!opaque) + return out; + for (const reactive::TagSplit& split : + reactive::tag_splits(std::static_pointer_cast(opaque))) { + py::list pieces; + for (const TopoRef& piece : split.pieces) { + py::dict item; + item["output_slot"] = piece.output_slot; + item["kind"] = std::string(kind_name(piece.kind)); + item["topo_id"] = piece.topo_id; + pieces.append(item); + } + py::dict row; + row["tag"] = split.tag; + row["into"] = split.into; + row["node_id"] = split.node_id; + row["op"] = split.op; + row["source_topo_id"] = split.source_topo_id; + row["pieces"] = pieces; + out.append(row); + } + return out; + }, + py::arg("shape"), + "The tagged entities the operations behind a shape split into pieces (each piece carries .split)."); m.def( "select_faces_by_tag", [](const Solid& solid, const std::string& tag, TagScope scope) { return select_faces_by_tag(solid, tag, scope); }, diff --git a/src/cpp/include/scad/reactive/tag_view.hpp b/src/cpp/include/scad/reactive/tag_view.hpp index 121ff392..f2970c67 100644 --- a/src/cpp/include/scad/reactive/tag_view.hpp +++ b/src/cpp/include/scad/reactive/tag_view.hpp @@ -43,14 +43,36 @@ struct CarriedTag { std::string op; // the op of the last step that carried it }; -// "\x1f\x1f" -> the bindings carried to that entity. -using TagView = std::unordered_map>; +// A tagged entity an operation split into pieces. A tag follows its entity as a reference does: one entity keeps the +// tag, several do not. The pieces carry ".split1" .. ".split" instead, numbered as the operation +// recorded them (the "piece" of their witnesses: by centre, then size), and the split is reported so whoever reads the +// model can see it happened and name the pieces it wants by tags of its own. +struct TagSplit { + std::string tag; // the tag the entity had + std::vector into; // the tags the pieces carry, in piece order + std::vector pieces; // the pieces in the node's output, in piece order + std::string node_id; // the operation that split it + std::string op; + std::string source_topo_id; // the entity it was (recorded form, in the operation's input) +}; + +// "\x1f\x1f" -> the bindings carried to that entity; `splits`: the tagged entities this +// node split. +struct TagView : std::unordered_map> { + std::vector splits; +}; + +// The tag a piece of a split entity carries: ".split". +std::string split_tag_name(std::string_view tag, int piece); std::string tag_view_key(int output_slot, Kind kind, const std::string& recorded_topo_id); // The view of `node` (memoised). Never null for a non-null node. std::shared_ptr tag_view(const NodePtr& node); +// The tagged entities split by `node` and by every node upstream of it, upstream first. +std::vector tag_splits(const NodePtr& node); + // The lineage witnesses the history carries to `entity`, a sub-shape of a recorded output (empty otherwise). std::vector history_witnesses(const Shape& entity); diff --git a/src/cpp/src/reactive/element_ref.cpp b/src/cpp/src/reactive/element_ref.cpp index 5a3ee2dc..12441d55 100644 --- a/src/cpp/src/reactive/element_ref.cpp +++ b/src/cpp/src/reactive/element_ref.cpp @@ -161,7 +161,13 @@ ResolvedRef resolve_by_history(const NodePtr& target, const ElementAnchor& ancho for (std::size_t order = start + 1; order < closure.size(); ++order) { const OperationNode& node = *closure[order]; - // The members this node consumed: entities of the outputs of its inputs. + // The members this node consumed: entities of the outputs of its inputs it was given (one piece of a split body + // is one output of the split; the other pieces go elsewhere). + std::set> bound; + for (const InputBinding& binding : node.bindings) { + if (!binding.external()) + bound.emplace(binding.node_id, binding.output_slot); + } std::vector consumed; std::unordered_set seen_inputs; for (const NodePtr& input : node.inputs) { @@ -170,8 +176,11 @@ ResolvedRef resolve_by_history(const NodePtr& target, const ElementAnchor& ancho const auto found = members.by_node.find(input->node_id); if (found == members.by_node.end()) continue; - for (const std::string& key : found->second) - consumed.push_back(members.by_key.at(key)); + for (const std::string& key : found->second) { + const TopoRef& member = members.by_key.at(key); + if (bound.empty() || bound.count({input->node_id, member.output_slot}) != 0) + consumed.push_back(member); + } } if (consumed.empty()) continue; @@ -300,6 +309,16 @@ ResolvedRef resolve_by_history(const NodePtr& target, const ElementAnchor& ancho out.lost_at = target->node_id; out.reason = "not_in_target"; } + // The lineage reached the target node, in another of its outputs (another piece of a split body): not lost, only + // not in this one. + for (const std::string& key : members.by_node[target->node_id]) { + const TopoRef& ref = members.by_key.at(key); + if (ref.output_slot != target_slot && (mode == FollowMode::Derived || ref.kind == anchor.kind)) { + out.lost_at = target->node_id; + out.reason = "other_output"; + break; + } + } return out; } // Keep the hops on the way to the targets (a branch that leads elsewhere is not this reference's history), @@ -563,10 +582,10 @@ StableAnchor stabilize(const NodePtr& within, const ElementAnchor& picked) { return out; } -std::optional locate(const NodePtr& within, const StableAnchor& anchor) { - const NodePtr node = pick_by_stable_key(within, anchor.node); - if (!node) - return std::nullopt; +namespace { + +// The entity `anchor` names in `node` (a node with the anchor's key). +std::optional anchor_in(const NodePtr& node, const StableAnchor& anchor) { if (anchor.role.empty()) return ElementAnchor{node->node_id, anchor.output_slot, anchor.kind, anchor.topo_id}; std::vector all = anchors_for_role(node, anchor.role); @@ -577,6 +596,29 @@ std::optional locate(const NodePtr& within, const StableAnchor& a return all[static_cast(anchor.role_ordinal)]; } +} // namespace + +std::optional locate(const NodePtr& within, const StableAnchor& anchor) { + if (const NodePtr node = pick_by_stable_key(within, anchor.node)) + return anchor_in(node, anchor); + // Several nodes share the key and the parameters do not tell them apart (a reference made before a second box of + // the cell existed). The history can: the one whose entity still reaches `within` is the one meant (a cut's tool + // box is consumed by the cut, its body continues). One survivor is the answer; none or several stay ambiguous. + std::optional alive; + for (const NodePtr& candidate : find_by_stable_key(within, anchor.node)) { + const std::optional found = anchor_in(candidate, anchor); + if (!found) + continue; + const ResolvedRef resolved = resolve_by_history(within, *found, 0); + if (resolved.status == RefStatus::Lost && resolved.reason != "other_output") + continue; + if (alive) + return std::nullopt; + alive = found; + } + return alive; +} + Value to_value(const StableAnchor& anchor) { Value out = Value::object(); out.set("feature", anchor.node.feature); diff --git a/src/cpp/src/reactive/session.cpp b/src/cpp/src/reactive/session.cpp index 8686aeea..ae1682b7 100644 --- a/src/cpp/src/reactive/session.cpp +++ b/src/cpp/src/reactive/session.cpp @@ -2,6 +2,7 @@ #include "scad/reactive/tag_view.hpp" #include +#include #include #include #include @@ -14,6 +15,8 @@ #include "internal.hpp" #include "scad/core/coordinate_system.hpp" #include "scad/core/error.hpp" +#include "scad/kernel/properties.hpp" +#include "scad/reactive/element_ref.hpp" #include "scad/reactive/digest.hpp" #include "scad/reactive/geo_selection.hpp" #include "scad/reactive/lineage.hpp" @@ -324,6 +327,109 @@ struct RefResolver { } }; +// The pieces an operation split an entity into, numbered. An entity of the inputs that continues as several entities +// of its kind (a face cut in two by a slot, a solid by a through cut) gives each of them "piece" (0-based) and "pieces" +// in its witness's metadata, in a geometric order that does not depend on OCCT's numbering: by centre, then size (the +// order a split reference lists its candidates in). Tag lineage names the pieces after it (.split1 ..), so the +// number is a recorded fact of the operation, not something a later reader re-derives. +void number_pieces(TopoDelta& delta, const std::vector& outputs) { + std::map> children; // parent key -> entries continuing it + for (std::size_t i = 0; i < delta.entries.size(); ++i) { + const TopoEntry& entry = delta.entries[i]; + if (entry.event == TopoEvent::Deleted || entry.event == TopoEvent::Generated) + continue; + const TopoRef* parent = nullptr; + int same_kind = 0; + for (const TopoRef& candidate : entry.parent_refs) { + if (candidate.kind == entry.ref.kind) { + parent = &candidate; + ++same_kind; + } + } + if (same_kind != 1) + continue; // a merge (or no parent of its kind) continues no single entity + children[ref_key(*parent)].push_back(i); + } + for (const auto& [parent, indices] : children) { + if (indices.size() < 2) + continue; + struct Piece { + std::size_t entry; + std::tuple key; + }; + std::vector pieces; + for (const std::size_t i : indices) { + const TopoRef& ref = delta.entries[i].ref; + if (ref.output_slot < 0 || static_cast(ref.output_slot) >= outputs.size()) + return; // an entity this node does not output: leave the split unnumbered rather than half-numbered + Shape sub = outputs[static_cast(ref.output_slot)]; + try { + sub = subshapes_by_recorded_id(sub, ref.kind, {ref.topo_id}).front(); + } catch (const ValueError&) { + return; + } + const auto round6 = [](double v) { return std::round(v * 1e6) / 1e6; }; + const Vec3 c = kernel::center_of_mass(sub.wrapped()); + double size = 0.0; + if (ref.kind == Kind::Face || ref.kind == Kind::Shell) + size = kernel::surface_area(sub.wrapped()); + else if (ref.kind == Kind::Edge || ref.kind == Kind::Wire) + size = kernel::linear_length(sub.wrapped()); + else if (ref.kind == Kind::Solid) + size = kernel::volume(sub.wrapped()); + pieces.push_back({i, {round6(c.x), round6(c.y), round6(c.z), round6(size)}}); + } + std::stable_sort(pieces.begin(), pieces.end(), [](const Piece& a, const Piece& b) { return a.key < b.key; }); + for (std::size_t n = 0; n < pieces.size(); ++n) { + Value& metadata = delta.entries[pieces[n].entry].metadata; + if (!metadata.is_object()) + metadata = Value::object(); + metadata.set("piece", static_cast(n)); + metadata.set("pieces", static_cast(pieces.size())); + } + } +} + +// An operation that takes one solid and gives one solid back (a fillet, a shell, a move) makes that solid's +// continuation: the kernel's history speaks of faces and edges only, so the solid itself is continued here, as the one +// thing the operation can have made of it. Booleans and splits say what became of their solids themselves. +void continue_single_solid(TopoDelta& delta, const std::string& graph_id, const std::string& node_id, + const std::vector& outputs, const std::vector& inputs) { + if (delta.entries.empty() || outputs.size() != 1 || outputs.front().kind() != Kind::Solid) + return; + const OpInput* solid = nullptr; + for (const OpInput& input : inputs) { + if (input.shape.kind() != Kind::Solid) + continue; + if (solid != nullptr) + return; // several solids: not this rule's to say + solid = &input; + } + if (solid == nullptr) + return; + for (const TopoEntry& entry : delta.entries) { + if (entry.ref.kind == Kind::Solid) + return; + } + const std::optional source = topo_ref_of(solid->shape); + if (!source) + return; + TopoRef parent = *source; + parent.topo_id = "solid_" + parent.topo_id; + TopoEntry entry; + entry.ref = TopoRef{graph_id, node_id, 0, Kind::Solid, "solid_" + outputs.front().topo_id()}; + entry.event = TopoEvent::Modified; + entry.origin_role = solid->role.empty() ? std::string("body") : solid->role; + entry.parent_refs = {parent}; + entry.metadata = Value::object(); + entry.metadata.set("derivation", "continuation"); + entry.metadata.set("coverage", "complete"); + entry.metadata.set("status", "proven"); + entry.metadata.set("evidence_kind", "operation_rule"); + entry.metadata.set("source_kind", "SOLID"); + delta.entries.push_back(std::move(entry)); +} + TopoDelta resolve_recorded_delta(const TopoDelta& raw, const std::string& graph_id, const std::string& node_id, const std::vector& outputs, const std::vector& inputs, const OperationGraph& graph) { @@ -365,6 +471,8 @@ TopoDelta resolve_recorded_delta(const TopoDelta& raw, const std::string& graph_ } out.section_edges = refs.resolve_many(raw.section_edges, false); out.raw_event = raw.raw_event; + number_pieces(out, outputs); + continue_single_solid(out, graph_id, node_id, outputs, inputs); return out; } diff --git a/src/cpp/src/reactive/tag_view.cpp b/src/cpp/src/reactive/tag_view.cpp index cfd271e0..8d54dfee 100644 --- a/src/cpp/src/reactive/tag_view.cpp +++ b/src/cpp/src/reactive/tag_view.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -62,6 +63,46 @@ void carry(std::vector& into, CarriedTag tag) { into.push_back(std::move(tag)); } +// Which piece of a split the witness's entity is (the operation numbered them when it was recorded), if it is one. +std::optional piece_of(const TopoEntry& entry) { + const Value* piece = member(entry.metadata, "piece"); + const Value* pieces = member(entry.metadata, "pieces"); + if (piece == nullptr || pieces == nullptr || !piece->is_number() || !pieces->is_number() || pieces->as_double() < 2) + return std::nullopt; + return static_cast(piece->as_double()); +} + +// The binding a piece carries: the same assignment under the piece's tag, with an id of its own (bindings are told +// apart by id), derived from the original, the operation and the piece so a replay names it alike. +TagBinding piece_binding(const TagBinding& binding, const std::string& node_id, int piece) { + TagBinding out = binding; + out.tag = Symbol(split_tag_name(binding.tag.str(), piece)); + out.binding_id = + BindingId("tag_binding_" + uuid5_url_hex("simplecad:split-tag:" + std::string(binding.binding_id.str()) + ":" + + node_id + ":" + std::to_string(piece))); + return out; +} + +void note_split(const TagView& view, std::map, TagSplit>& splits, + const CarriedTag& tag, const TopoRef& parent, const TopoEntry& entry, const OperationNode& node, + const std::string& piece_tag) { + (void)view; + TagSplit& split = splits[{std::string(tag.binding.binding_id.str()), parent.node_id + '\x1f' + parent.topo_id}]; + if (split.node_id.empty()) { + split.tag = tag.binding.tag.str(); + split.node_id = node.node_id; + split.op = node.op; + split.source_topo_id = parent.topo_id; + } + const int piece = *piece_of(entry); + if (split.into.size() <= static_cast(piece)) { + split.into.resize(static_cast(piece) + 1); + split.pieces.resize(static_cast(piece) + 1); + } + split.into[static_cast(piece)] = piece_tag; + split.pieces[static_cast(piece)] = entry.ref; +} + // The entities a tag assignment targets, as keys of its own output (slot 0). std::vector> targets_of(const TagBinding& binding) { std::vector refs; @@ -163,6 +204,8 @@ TagView build_view(const OperationNode& node, return out; }; + // The splits of this node, by (binding, entity it was), in the order they are met. + std::map, TagSplit> splits; for (const TopoEntry& entry : node.topo_delta->entries) { if (entry.event == TopoEvent::Deleted) continue; @@ -174,6 +217,7 @@ TagView build_view(const OperationNode& node, if (entry.event == TopoEvent::Generated) continue; const std::string key = tag_view_key(entry.ref.output_slot, entry.ref.kind, entry.ref.topo_id); + const std::optional piece = piece_of(entry); for (const TopoRef& parent : entry.parent_refs) { for (const CarriedTag* tag : carried_by(parent)) { if (parent.kind != entry.ref.kind || !lineage_policy_allows(tag->binding.propagation(), *derivation)) @@ -181,10 +225,16 @@ TagView build_view(const OperationNode& node, CarriedTag next = *tag; next.derivation = *derivation; next.op = node.op; + if (piece) { + next.binding = piece_binding(tag->binding, node.node_id, *piece); + note_split(view, splits, *tag, parent, entry, node, next.binding.tag.str()); + } carry(view[key], std::move(next)); } } } + for (auto& [_, split] : splits) + view.splits.push_back(std::move(split)); return view; } @@ -206,6 +256,30 @@ std::vector provider(const Shape& entity) { } // namespace +std::string split_tag_name(std::string_view tag, int piece) { + return std::string(tag) + ".split" + std::to_string(piece + 1); +} + +std::vector tag_splits(const NodePtr& node) { + std::vector out; + if (!node) + return out; + tag_view(node); // builds (and caches) the views of the whole closure + Cache& c = cache(); + for (const NodePtr& item : upstream_closure({node})) { + std::shared_ptr view; + { + const std::lock_guard lock(c.mutex); + if (const auto found = c.views.find(item.get()); found != c.views.end() && found->second.first.lock() == item) + view = found->second.second; + } + if (!view) + view = tag_view(item); + out.insert(out.end(), view->splits.begin(), view->splits.end()); + } + return out; +} + std::string tag_view_key(int output_slot, Kind kind, const std::string& recorded_topo_id) { return std::to_string(output_slot) + '\x1f' + std::string(kind_name(kind)) + '\x1f' + recorded_topo_id; } diff --git a/src/cpp/src/semantic/tracking_booleans.cpp b/src/cpp/src/semantic/tracking_booleans.cpp index a44569c0..fa51049c 100644 --- a/src/cpp/src/semantic/tracking_booleans.cpp +++ b/src/cpp/src/semantic/tracking_booleans.cpp @@ -25,7 +25,8 @@ TrackedBooleanResult to_boolean_result(std::optional solid, std::vector& solids, const for (std::size_t i = 0; i < solids.size(); ++i) { query_input_faces(retained, solids[i], input_role(i), in_result, delta); } + // The fuse reports its input solids deleted: the one solid of the answer is new to it. It is the merge of them + // all (that is what a union is), so it continues each of them as a merge, not as nothing. + std::erase_if(delta.witnesses, + [](const tracking::Witness& w) { return w.kind == Kind::Solid && w.event == TopoEvent::Deleted; }); + for (std::size_t i = 0; i < solids.size(); ++i) { + tracking::Witness merged; + merged.topo_id = kernel_topo_id(result_solid.wrapped()); + merged.event = TopoEvent::Modified; + merged.kind = Kind::Solid; + merged.source_kind = Kind::Solid; + merged.origin_role = input_role(i); + merged.input_topo_id = kernel_topo_id(solids[i].wrapped()); + merged.derivation = "merge"; + delta.witnesses.push_back(std::move(merged)); + } } // The section edges that survive into the result, each once. diff --git a/src/cpp/tests/cpp/reactive/test_element_ref.cpp b/src/cpp/tests/cpp/reactive/test_element_ref.cpp index 4b5977dc..99007539 100644 --- a/src/cpp/tests/cpp/reactive/test_element_ref.cpp +++ b/src/cpp/tests/cpp/reactive/test_element_ref.cpp @@ -251,8 +251,11 @@ TEST_CASE("a stable anchor names the node by feature, op and occurrence upstream // The value form round-trips. CHECK(stable_anchor_from_value(to_value(stable)).node.params_digest == stable.node.params_digest); - // Same key, same parameters: ambiguous, so nothing is located (never the first one). + // Same key, and the parameters do not tell them apart: the history does. Only the plate's box face continues to the + // cut (the inserted box's does not), so that one is located: by what happened, never by being first. StableAnchor blind = stable; blind.node.params_digest = "0000000000000000"; - CHECK_FALSE(locate(cut2, blind)); + const auto by_history = locate(cut2, blind); + REQUIRE(by_history); + CHECK(by_history->node_id == "c_node_00000002"); } diff --git a/src/cpp/tests/cpp/semantic/test_tracking_behaviour.cpp b/src/cpp/tests/cpp/semantic/test_tracking_behaviour.cpp index 56bcf5c9..64235774 100644 --- a/src/cpp/tests/cpp/semantic/test_tracking_behaviour.cpp +++ b/src/cpp/tests/cpp/semantic/test_tracking_behaviour.cpp @@ -398,13 +398,36 @@ TEST_CASE("a cut that removes everything has no solid, only deletions") { const Solid big = box_solid(10, 10, 10); const TrackedBooleanResult tracked = tracked_cut(tiny, big); CHECK_FALSE(tracked.solid.has_value()); - CHECK(tracked.delta.deleted.size() == 12); // all six faces of each input + CHECK(tracked.delta.deleted.size() == 14); // all six faces of each input, and both input solids std::map by_role; for (const TopoEntry& entry : tracked.delta.entries) { CHECK(entry.event == TopoEvent::Deleted); ++by_role[*entry.origin_role]; } - CHECK(by_role == std::map{{"body", 6}, {"tool", 6}}); + CHECK(by_role == std::map{{"body", 7}, {"tool", 7}}); +} + +TEST_CASE("a boolean says what became of its solids: a split cut continues the body in every piece") { + const Solid bar = box_solid(40, 10, 10); + const Solid slot = box_solid(2, 20, 20, {0, 0, -5}); + const TrackedBooleanResult tracked = tracked_cut(bar, slot); + REQUIRE(tracked.solids.size() == 2); + std::map solids; // "|" -> count + for (const TopoEntry& entry : tracked.delta.entries) { + if (entry.ref.kind == Kind::Solid) + ++solids[std::string(to_string(entry.event)) + "|" + entry.origin_role.value_or("-")]; + } + // the bar continues as both pieces, the slot is consumed + CHECK(solids == std::map{{"deleted|tool", 1}, {"modified|body", 2}}); + + // a fuse reports its inputs deleted; the one solid of the answer merges them + const TrackedBooleanResult fused = tracked_union(bar, box_solid(4, 4, 20), false, 0.0); + std::map merged; + for (const TopoEntry& entry : fused.delta.entries) { + if (entry.ref.kind == Kind::Solid) + ++merged[std::string(to_string(entry.event)) + "|" + entry.metadata.find("derivation")->as_string()]; + } + CHECK(merged == std::map{{"modified|merge", 2}}); } TEST_CASE("the same boolean twice gives the same delta") { diff --git a/src/cpp/tests/cpp/semantic/test_tracking_support.hpp b/src/cpp/tests/cpp/semantic/test_tracking_support.hpp index 95ba07e7..f1a1a7ae 100644 --- a/src/cpp/tests/cpp/semantic/test_tracking_support.hpp +++ b/src/cpp/tests/cpp/semantic/test_tracking_support.hpp @@ -100,8 +100,26 @@ inline std::string join(const Value* list) { } // counts first, then the sorted E/R/S/D lines of tracking_golden_record.py. -inline std::vector summarise(const TopoDelta& delta, const DeltaEntries& entries, +// The delta without its solid history: the Python reference the goldens were recorded from tracks faces and edges +// only (what became of the input solids is SimpleCAD's own, tested in test_tracking_behaviour.cpp). +inline TopoDelta without_solids(const TopoDelta& delta) { + TopoDelta out = delta; + const auto solid = [](const TopoRef& ref) { return ref.kind == Kind::Solid; }; + for (auto* list : {&out.preserved, &out.modified, &out.generated, &out.deleted}) + std::erase_if(*list, solid); + std::erase_if(out.entries, [&](const TopoEntry& e) { return solid(e.ref); }); + return out; +} + +inline std::vector summarise(const TopoDelta& full, const DeltaEntries& all_entries, const std::vector& inputs, const TopoDS_Shape& result) { + const TopoDelta delta = without_solids(full); + DeltaEntries entries; + for (const auto& [id, value] : all_entries) { + const Value* kind = value.find("kind"); + if (kind == nullptr || upper(kind->as_string()) != "SOLID") + entries.emplace(id, value); + } std::vector roots = inputs; roots.push_back(result); const ShapeIndex index = index_shapes(roots); diff --git a/src/simplecadapi/__init__.py b/src/simplecadapi/__init__.py index 26e8f781..7adc9a58 100644 --- a/src/simplecadapi/__init__.py +++ b/src/simplecadapi/__init__.py @@ -308,6 +308,7 @@ from simplecadapi._cpp import ( apply_tag, apply_tag_rselection, explain_tag, + list_tag_splits, list_tags, select_edges_by_tag, select_faces_by_tag, @@ -462,7 +463,7 @@ __description__ = "Simplified OpenCASCADE-native CAD modeling Python API" # Convenience aliases Workplane = SimpleWorkplane -from ._glue.pieces import Pieces # noqa: E402 (the pieces of a split body) +from ._glue.pieces import Pieces, TagSplitWarning # noqa: E402 (the pieces of a split body; a split tag) # Creation-function aliases create_angle_arc = make_angle_arc_redge @@ -536,6 +537,7 @@ __all__ = [ # Core classes "CoordinateSystem", "Pieces", + "TagSplitWarning", "SimpleWorkplane", "Workplane", "Vertex", @@ -729,6 +731,7 @@ __all__ = [ "apply_tag", "apply_tag_rselection", "explain_tag", + "list_tag_splits", "list_tags", "select_edges_by_tag", "select_faces_by_tag", diff --git a/src/simplecadapi/_cpp/_native/__init__.pyi b/src/simplecadapi/_cpp/_native/__init__.pyi index 11161216..57515449 100644 --- a/src/simplecadapi/_cpp/_native/__init__.pyi +++ b/src/simplecadapi/_cpp/_native/__init__.pyi @@ -151,6 +151,7 @@ from simplecadapi.operators.product import unground_component_rassembly from simplecadapi.operators.selection import apply_tag from simplecadapi.operators.selection import apply_tag_rselection from simplecadapi.operators.selection import explain_tag +from simplecadapi.operators.selection import list_tag_splits from simplecadapi.operators.selection import list_tags from simplecadapi.operators.selection import select_edges_by_tag from simplecadapi.operators.selection import select_faces_by_tag @@ -340,7 +341,7 @@ import numpy.typing import simplecadapi.core import simplecadapi.params.units import typing -__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_to_bspline_redge', 'convert_to_bspline_rface', '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', 'elevate_curve_degree_redge', 'elevate_surface_degree_rface', '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_current_frame_source', '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', 'insert_curve_knot_redge', 'insert_surface_knot_rface', 'inspect_assembly_constraints', 'inspect_assembly_constraints_rconstraintreport', 'inspect_curve_rcurvedata', 'inspect_sketch_rsketchcrossings', 'inspect_sketch_rsketchprofiles', 'inspect_sketch_rsketchresult', 'inspect_surface_rsurfacedata', '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', 'make_workplane_from_axis_rworkplane', 'make_workplane_from_face_rworkplane', 'make_workplane_from_points_rworkplane', 'make_workplane_midplane_rworkplane', 'make_workplane_normal_to_curve_rworkplane', 'make_workplane_rworkplane', 'math', 'measure_constraint_residual_rconstraintresidual', 'mesh', 'mirror_shape', 'move_curve_poles_redge', 'move_surface_poles_rface', 'offset_rsolid', 'parse_ui_comment', 'place_component_rassembly', 'project_rsketch', 'ql', 'radial_pattern_rsolidlist', 'raise_loft_failure_if_diagnosed', 'rebuild_curve_redge', 'rebuild_surface_rface', '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', 'sample_curve_rcurvature', 'sample_surface_risocurves', 'scale_rsolid', 'select_edges_by_tag', 'select_faces_by_tag', 'serialize_shape', 'set_body_appearance_rpart', 'set_curve_poles_redge', 'set_curve_weights_redge', 'set_default_sketch_solver_backend', 'set_producer_version', 'set_public_connector_rassembly', 'set_surface_poles_rface', 'set_surface_weights_rface', '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_to_bspline_redge', 'convert_to_bspline_rface', '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', 'elevate_curve_degree_redge', 'elevate_surface_degree_rface', '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_current_frame_source', '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', 'insert_curve_knot_redge', 'insert_surface_knot_rface', 'inspect_assembly_constraints', 'inspect_assembly_constraints_rconstraintreport', 'inspect_curve_rcurvedata', 'inspect_sketch_rsketchcrossings', 'inspect_sketch_rsketchprofiles', 'inspect_sketch_rsketchresult', 'inspect_surface_rsurfacedata', 'intersect_rsolid', 'isolated_recording', 'lift_scalar', 'linear_pattern_rsolidlist', 'list_tag_splits', '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', 'make_workplane_from_axis_rworkplane', 'make_workplane_from_face_rworkplane', 'make_workplane_from_points_rworkplane', 'make_workplane_midplane_rworkplane', 'make_workplane_normal_to_curve_rworkplane', 'make_workplane_rworkplane', 'math', 'measure_constraint_residual_rconstraintresidual', 'mesh', 'mirror_shape', 'move_curve_poles_redge', 'move_surface_poles_rface', 'offset_rsolid', 'parse_ui_comment', 'place_component_rassembly', 'project_rsketch', 'ql', 'radial_pattern_rsolidlist', 'raise_loft_failure_if_diagnosed', 'rebuild_curve_redge', 'rebuild_surface_rface', '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', 'sample_curve_rcurvature', 'sample_surface_risocurves', 'scale_rsolid', 'select_edges_by_tag', 'select_faces_by_tag', 'serialize_shape', 'set_body_appearance_rpart', 'set_curve_poles_redge', 'set_curve_weights_redge', 'set_default_sketch_solver_backend', 'set_producer_version', 'set_public_connector_rassembly', 'set_surface_poles_rface', 'set_surface_weights_rface', '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/compat.py b/src/simplecadapi/_glue/compat.py index f4d01dfe..e5bd1e94 100644 --- a/src/simplecadapi/_glue/compat.py +++ b/src/simplecadapi/_glue/compat.py @@ -581,14 +581,17 @@ def with_signature(function: Any) -> Any: name = getattr(function, "__name__", "") if name.endswith(_OP_SUFFIXES) or name in _SHAPE_FUNCTIONS: - from .pieces import SPLITS, TAKES_PIECES, Pieces, apply_to_pieces + from .pieces import SPLITS, TAKES_PIECES, Pieces, apply_to_pieces, run_on_pieces @functools.wraps(function) def wrapper(*args: Any, **kwargs: Any) -> Any: # the pieces of a split body: one operation per piece, unless the operation takes them together - if name not in TAKES_PIECES and any(isinstance(a, Pieces) for a in (*args, *kwargs.values())): - return apply_to_pieces(name, function, args, kwargs) - result = function(*args, **kwargs) + if any(isinstance(a, Pieces) for a in (*args, *kwargs.values())): + if name not in TAKES_PIECES: + return apply_to_pieces(name, function, args, kwargs) + result = run_on_pieces(function, args, kwargs) + else: + result = function(*args, **kwargs) return Pieces(result) if name in SPLITS and isinstance(result, list) else result else: diff --git a/src/simplecadapi/_glue/docstrings.json b/src/simplecadapi/_glue/docstrings.json index 23900fbd..9ecb3ab2 100644 --- a/src/simplecadapi/_glue/docstrings.json +++ b/src/simplecadapi/_glue/docstrings.json @@ -96,7 +96,7 @@ "add_revolute_constraint_rassembly": "Constrain two connectors as a revolute axis pair.", "and_": "Combine predicates so all of them must match.", "apply_tag": "Attach a local user tag with continuation/fragment lineage policy.", - "apply_tag_rselection": "Return a semantic shape view with a canonical tag assignment.\n\nA tag is also how a face, an edge or a vertex gets a name people read: there is no\nsecond naming system. Tags resolve through the recorded history, so a tagged face\nkeeps its name through later features (``ql.tag(...)`` and\n``select_faces_by_tag(...)`` find it again); the editor's \"name a face\" form is this\noperation with the picked faces as ``targets``.\n\nArgs:\n scope: The shape the tag is assigned in (a Solid, usually the body).\n targets: What to tag: a ``ql`` selection (``scad.ql.faces().where(...)``) or a\n list of sub-shapes of ``scope``.\n tag: The name, a normalized token such as ``\"lid_seat\"`` or\n ``\"role.mounting_surface\"``.\n topology_propagation: ``\"local\"`` tags the targets only; ``\"downward\"`` also\n their edges and vertices.\n lineage_policy: How the tag follows the targets through later operations\n (default ``\"continuation_fragment\"``: kept on continued faces and on the\n fragments of a split face).\n\nReturns:\n AnyShape: A view of ``scope`` with the tag assigned (the same geometry).\n\nRaises:\n SimpleCADError: The selection resolved nothing, a target is not inside the\n scope, or the tag is malformed.\n\nUsage:\n ``block = scad.apply_tag_rselection(block, scad.ql.faces().where(scad.ql.prop(\"geom.normal.z\", \">=\", 0.999)), \"lid_seat\")``\n names the top face; ``scad.ql.faces().where(scad.ql.tag(\"lid_seat\"))`` selects it\n later. A body of a Part is named with ``set_body_appearance_rpart(part, body_id, name=...)``.", + "apply_tag_rselection": "Return a semantic shape view with a canonical tag assignment.\n\nA tag is also how a face, an edge or a vertex gets a name people read: there is no\nsecond naming system. Tags resolve through the recorded history, so a tagged face\nkeeps its name through later features (``ql.tag(...)`` and\n``select_faces_by_tag(...)`` find it again); the editor's \"name a face\" form is this\noperation with the picked faces as ``targets``.\n\nArgs:\n scope: The shape the tag is assigned in (a Solid, usually the body).\n targets: What to tag: a ``ql`` selection (``scad.ql.faces().where(...)``) or a\n list of sub-shapes of ``scope``.\n tag: The name, a normalized token such as ``\"lid_seat\"`` or\n ``\"role.mounting_surface\"``.\n topology_propagation: ``\"local\"`` tags the targets only; ``\"downward\"`` also\n their edges and vertices.\n lineage_policy: How the tag follows the targets through later operations\n (default ``\"continuation_fragment\"``: kept on continued faces; the\n pieces of a split face carry ``.split1`` .. ``.split`` instead,\n see ``list_tag_splits``).\n\nReturns:\n AnyShape: A view of ``scope`` with the tag assigned (the same geometry).\n\nRaises:\n SimpleCADError: The selection resolved nothing, a target is not inside the\n scope, or the tag is malformed.\n\nUsage:\n ``block = scad.apply_tag_rselection(block, scad.ql.faces().where(scad.ql.prop(\"geom.normal.z\", \">=\", 0.999)), \"lid_seat\")``\n names the top face; ``scad.ql.faces().where(scad.ql.tag(\"lid_seat\"))`` selects it\n later. A body of a Part is named with ``set_body_appearance_rpart(part, body_id, name=...)``.", "apply_tracking_tags_to_delta": "Apply evidence-gated tracking projections for one operation result.", "assert_blend_volume_monotonic": "Mechanism E exit check: an all-convex blend may only remove material.\n\nObserved kernel behavior (and the reason this check exists): filleting\nevery edge of a 10 mm cube with r=6 *succeeds* and returns a solid whose\nvolume (1036.35) exceeds the input (1000) — geometrically impossible\noutput that the kernel hands back without a word. Fillet and chamfer\noutputs on convex edges are subsets of the input solid, so a volume\nincrease beyond measurement noise means the kernel silently produced\ngarbage; we name it instead of returning it.\n\nThe increase check only fires for provably all-convex selections:\nblending a *concave* edge legitimately adds material (the corner fill —\ne.g. a bolt's underhead fillet gains exactly the quarter-circle deficit\ntimes its circumference), and undeterminable edges mean the check\ncannot prove impossibility. A non-positive result volume is garbage\nregardless of convexity and always fires.\n\nThe check runs on the success path, so it must stay cheap: two GProp\nvolume evaluations plus one side-probe per selected edge. Raised as a\n``BlendVolumeViolation`` so the caller's ``_wrap_blend_failure`` handler\npromotes the measured facts and layers the standard blend diagnosis\n(probes, evidence render) on top.", "assign_material_rpart": "Assign a Material to a Part and return the updated Part.", @@ -308,7 +308,7 @@ "suspend_graph_recording": "Temporarily suspend automatic graph recording for internal API composition.", "sweep_multisection_rsolid": "Sweep through explicit ordered sections along a continuous path.\n\nAt least two ordered sections are needed. Face sections supply their outer\nwire, matching build123d's multi-section sweep contract. ``binormal`` is an\noptional direction vector or an auxiliary spine. The kernel must produce\none valid solid. Every section and the path are recorded as inputs of\n``make_sweep_multisection_rsolid``, so model JSON preserves the\nconstruction.\n\nArgs:\n profiles: Ordered section faces or wires (at least two).\n path: The continuous path wire.\n is_frenet: Use the Frenet frame along the path.\n binormal: A direction, or an auxiliary spine wire, that fixes the\n section orientation.\n\nReturns:\n The swept solid.\n\nRaises:\n TypeError: A section is neither a Face nor a Wire.\n ValueError: Fewer than two sections, a zero ``binormal`` direction, or\n the kernel could not make a solid.", "sweep_rsolid": "Create a swept solid, with optional kernel-role-based tags.", - "tag": "Build a tag predicate for QL filtering.\n\nTags are a view over the recorded history: a tag assigned in a\n``GraphSession`` reaches every entity its target became through later\noperations (a face cut in two keeps it on both pieces), as its lineage\npolicy allows. ``local`` is what the entity itself stores, ``inherited``\nwhat containing entities pass down, ``lineage`` what the history carries,\nand ``effective`` (the default) all three.\n\nArgs:\n pattern: Exact tag string or a trailing `*` prefix match.\n scope: One of ``local``, ``inherited``, ``effective``, or ``lineage``.\n\nReturns:\n Serializable predicate that can be used in `Query.where(...)`.", + "tag": "Build a tag predicate for QL filtering.\n\nTags are a view over the recorded history: a tag assigned in a\n``GraphSession`` reaches every entity its target became through later\noperations as its lineage policy allows. A tag follows its entity as a\nreference does: an entity an operation splits keeps it on none of its\npieces, which carry ``.split1`` .. ``.split`` instead\n(``list_tag_splits``); ``ql.tag(\".*\")`` finds them all. ``local`` is what the entity itself stores, ``inherited``\nwhat containing entities pass down, ``lineage`` what the history carries,\nand ``effective`` (the default) all three.\n\nArgs:\n pattern: Exact tag string or a trailing `*` prefix match.\n scope: One of ``local``, ``inherited``, ``effective``, or ``lineage``.\n\nReturns:\n Serializable predicate that can be used in `Query.where(...)`.", "topo_ref_from_dict": "Reconstruct a TopoRef from serialized data.", "topo_ref_to_dict": "Serialize a TopoRef into a JSON-compatible dictionary.", "track_union_history": "Build one face-level union delta from retained N-ary OCC history.", @@ -371,5 +371,6 @@ "make_workplane_from_points_rworkplane": "Create a workplane through three points: origin at ``a``, x towards ``b``, normal = (b - a) x (c - a).\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n a: A Vertex of the model or a point (current coordinate system): the origin.\n b: A Vertex or a point: x points from ``a`` towards it.\n c: A Vertex or a point on the positive-y side of the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: The three points lie on one line or two coincide.\n\nUsage:\n ``scad.make_workplane_from_points_rworkplane(v0, v1, v2)`` with three picked vertices; points given as\n numbers are recorded as numbers.\n", "make_workplane_from_axis_rworkplane": "Create a workplane through an axis, turned about it by an angle.\n\nThe axis is a straight edge (from its start, along it) or a circular edge (its centre line: through the centre,\nalong the circle's normal). x = the axis direction. At ``angle=0`` the plane is the plane of ``face`` (a planar face\ncontaining the axis direction, usually one the edge bounds) or, without one, the plane whose normal is global Z\n(global X for an axis along Z) made square to the axis; ``angle`` turns it right-handed about the axis.\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n axis: A straight or circular Edge.\n angle: The turn about the axis, in degrees.\n face: The planar Face the plane starts from at angle 0.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: The edge is neither straight nor circular, the face is not planar, or the face's normal is\n along the axis.\n\nUsage:\n ``scad.make_workplane_from_axis_rworkplane(edge, 30, face=top)``: a plane hinged on an edge of the top\n face, tilted 30 degrees.\n", "make_workplane_midplane_rworkplane": "Create the workplane halfway between two parallel planar faces (a symmetry plane).\n\nnormal and x come from ``face_a``; origin = the middle between the centre of ``face_a`` and its projection onto the\nplane of ``face_b``.\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n face_a: A planar Face; it gives the normal and x.\n face_b: A planar Face parallel to it.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: A face is not planar or the faces are not parallel.\n\nUsage:\n ``mid = scad.make_workplane_midplane_rworkplane(left_wall, right_wall)``; mirror or sketch on it.\n", - "make_workplane_normal_to_curve_rworkplane": "Create a workplane normal to a curve: the plane of a sweep profile.\n\norigin = the point at ``at`` (a fraction of the curve's length: 0 = start, 1 = end); normal = the direction of\ntravel there; x = ``x_dir`` projected onto the plane, or global Z made square to the normal (global X when the\ntangent is near Z).\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n curve: An Edge or a Wire (the sweep path).\n at: The fraction of the length, in [0, 1].\n x_dir: The direction of x, projected onto the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: ``at`` is outside [0, 1], the curve has no length, or ``x_dir`` is along the tangent.\n\nUsage:\n ``start = scad.make_workplane_normal_to_curve_rworkplane(path, 0)``;\n ``profile = ... make_sketch_rsketch(\"profile\", plane=start) ...``; ``sweep_rsolid(profile, path)``.\n" + "make_workplane_normal_to_curve_rworkplane": "Create a workplane normal to a curve: the plane of a sweep profile.\n\norigin = the point at ``at`` (a fraction of the curve's length: 0 = start, 1 = end); normal = the direction of\ntravel there; x = ``x_dir`` projected onto the plane, or global Z made square to the normal (global X when the\ntangent is near Z).\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n curve: An Edge or a Wire (the sweep path).\n at: The fraction of the length, in [0, 1].\n x_dir: The direction of x, projected onto the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: ``at`` is outside [0, 1], the curve has no length, or ``x_dir`` is along the tangent.\n\nUsage:\n ``start = scad.make_workplane_normal_to_curve_rworkplane(path, 0)``;\n ``profile = ... make_sketch_rsketch(\"profile\", plane=start) ...``; ``sweep_rsolid(profile, path)``.\n", + "list_tag_splits": "The tagged entities that the operations behind a shape split into pieces.\n\nA tag follows its entity the way a reference does: while the entity stays one entity it keeps the tag; when an\noperation splits it (a slot cut across a tagged face, a cut through a tagged body), the tag does not go to every\npiece. Each piece carries ``.split1`` .. ``.split`` instead, numbered as the operation recorded them (by\ncentre, then size), and ``ql.tag(\"\")`` finds none of them. Name the pieces you mean with tags of your own after the\nsplit, or select them with ``ql.tag(\".split1\")`` / ``ql.tag(\".*\")``.\n\nArgs:\n shape: A shape made in a recording session (its history is read).\n\nReturns:\n list[dict]: One row per split, upstream first: ``tag`` (the tag the entity had), ``into`` (the tags of the pieces,\n in piece order), ``node_id`` and ``op`` (the operation that split it), ``source_topo_id`` and ``pieces``\n (``output_slot``, ``kind``, ``topo_id`` of each piece in that operation's output). Empty for a shape without\n recorded history.\n\nExamples:\n >>> top = scad.apply_tag_rselection(box, scad.ql.faces().where(scad.ql.prop(\"geom.center.z\", \">=\", 9.9)), \"mount.top\")\n >>> halves = scad.cut_rsolid(top, slot) # the slot splits the top face (and the body)\n >>> [row[\"into\"] for row in scad.list_tag_splits(halves[0])]\n [['mount.top.split1', 'mount.top.split2']]" } diff --git a/src/simplecadapi/_glue/modules.json b/src/simplecadapi/_glue/modules.json index 080af6e1..f0af74ff 100644 --- a/src/simplecadapi/_glue/modules.json +++ b/src/simplecadapi/_glue/modules.json @@ -201,6 +201,7 @@ "evaluate_scalar": "simplecadapi.params.expr", "evaluate_value": "simplecadapi.params.expr", "explain_tag": "simplecadapi.operators.selection", +"list_tag_splits": "simplecadapi.operators.selection", "explode_rassembly": "simplecadapi.operators.product", "expression_uses_units": "simplecadapi.params.units", "extend_rsketch": "simplecadapi.operators.sketch", diff --git a/src/simplecadapi/_glue/pieces.py b/src/simplecadapi/_glue/pieces.py index 2b1494cb..ca11cb6a 100644 --- a/src/simplecadapi/_glue/pieces.py +++ b/src/simplecadapi/_glue/pieces.py @@ -21,6 +21,57 @@ SPLITS = frozenset({"cut_rsolid", "fillet_rsolid", "chamfer_rsolid"}) """Operations whose list result is the pieces of one body.""" +class TagSplitWarning(UserWarning): + """An operation split a tagged entity: the tag went to none of the pieces, each carries ``.split``. + + A diagnostic, not a failure: a tag follows its entity as a reference does, and a split is where that ends. Look at + the pieces (the editor highlights them), and tag the ones you mean after the split if later code needs them. + """ + + +def tag_splits(values: Any, namespace: str) -> list[dict]: + """The tag splits the operations of one cell (node ids ``_...``) made, in the shapes *values* hold.""" + + from simplecadapi._cpp import Solid, list_tag_splits + + shapes: list = [] + + def collect(value: Any) -> None: + if isinstance(value, Solid): + shapes.append(value) + elif isinstance(value, (list, tuple)): + for item in value: + collect(item) + elif type(value).__name__ == "Part": + for body in value.bodies: + collect(body.solid) + + for value in values: + collect(value) + seen: set = set() + out: list[dict] = [] + for shape in shapes: + try: + rows = list_tag_splits(shape) + except Exception: # noqa: BLE001 - a diagnostic never fails the cell + continue + for row in rows: + if not row["node_id"].startswith(namespace + "_"): + continue + key = (row["node_id"], row["tag"], row["source_topo_id"]) + if key not in seen: + seen.add(key) + out.append(row) + return out + + +def split_message(row: dict) -> str: + into = ", ".join(row["into"]) + return (f"{row['op']} split the entity tagged {row['tag']!r} into {len(row['into'])} pieces; " + f"they carry {into} and {row['tag']!r} names none of them. Tag the pieces you mean after this operation " + f"if later code selects them (scad.list_tag_splits(shape) lists the splits).") + + class Pieces(list): """The solids one body was split into, in a stable order (``cut_rsolid``: by centroid).""" @@ -59,6 +110,21 @@ def apply_to_pieces(name: str, function: Callable[..., Any], args: tuple, kwargs selectors = {("arg", i): _open(a) for i, a in enumerate(args) if _is_selector(a)} selectors.update({("kw", k): _open(v) for k, v in kwargs.items() if _is_selector(v)}) found = {slot: 0 for slot in selectors} + from ..ref import IN_PIECES + + token = IN_PIECES.set(True) + try: + out = _each_piece(function, pieces, side, key, args, kwargs, selectors, found) + finally: + IN_PIECES.reset(token) + for slot, (_, cardinality) in selectors.items(): + if found[slot] == 0: + raise ValueError(f"{name}: the selection found nothing on any piece of the split body") + _check(name, cardinality, found[slot]) + return out + + +def _each_piece(function, pieces, side, key, args, kwargs, selectors, found) -> Pieces: out = Pieces() for piece in pieces: call_args, call_kwargs = list(args), dict(kwargs) @@ -84,9 +150,18 @@ def apply_to_pieces(name: str, function: Callable[..., Any], args: tuple, kwargs out.extend(result) else: out.append(result) - for slot, (_, cardinality) in selectors.items(): - _check(name, cardinality, found[slot]) return out -__all__ = ["Pieces", "SPLITS", "TAKES_PIECES", "apply_to_pieces"] +def run_on_pieces(function: Callable[..., Any], args: tuple, kwargs: dict) -> Any: + """Run an operation that takes the pieces together (:data:`TAKES_PIECES`), its selectors resolved per piece.""" + from ..ref import IN_PIECES + + token = IN_PIECES.set(True) + try: + return function(*args, **kwargs) + finally: + IN_PIECES.reset(token) + + +__all__ = ["Pieces", "SPLITS", "TAKES_PIECES", "TagSplitWarning", "apply_to_pieces", "run_on_pieces", "split_message", "tag_splits"] diff --git a/src/simplecadapi/editor/kernel.py b/src/simplecadapi/editor/kernel.py index 0c8ab555..bbe8e190 100644 --- a/src/simplecadapi/editor/kernel.py +++ b/src/simplecadapi/editor/kernel.py @@ -596,6 +596,13 @@ class MarimoKernel: " print('SCA-WORKPLANES', _wjson.dumps(_workplanes()))\n" "except Exception:\n" " pass\n" + # the tagged entities the model's operations split, with the entities of their pieces (a diagnostic) + "try:\n" + " from simplecadapi.runtime.live import live_tag_splits as _splits\n" + " import json as _sjson\n" + " print('SCA-TAGSPLITS', _sjson.dumps(_splits()))\n" + "except Exception:\n" + " pass\n" ) @staticmethod @@ -607,6 +614,11 @@ class MarimoKernel: out["workplanes"] = json.loads(line[len("SCA-WORKPLANES "):]) except ValueError: pass + elif line.startswith("SCA-TAGSPLITS "): + try: + out["tag_splits"] = json.loads(line[len("SCA-TAGSPLITS "):]) + except ValueError: + pass return out @staticmethod diff --git a/src/simplecadapi/editor/server.py b/src/simplecadapi/editor/server.py index 4f347a00..ba7a6869 100644 --- a/src/simplecadapi/editor/server.py +++ b/src/simplecadapi/editor/server.py @@ -122,6 +122,7 @@ class WorkspaceState: "preview", "selection", "workplanes", + "tag_splits", ) def __init__(self, workspace: Path, notebook: Path | None = None) -> None: @@ -133,6 +134,7 @@ class WorkspaceState: self.lock = threading.Lock() self.latest: dict[str, dict] = {} self._workplanes: list[dict] | None = None # the frames last sent (see _push_workplanes) + self._tag_splits: list[dict] | None = None # the tag splits last sent (see _push_tag_splits) self.latest_package_bytes: bytes | None = None # a full package, made on demand (export) # The latest preview (replaced as a whole, so a reader on another thread never sees half of one) and the # parts of it by key: a page is sent only the parts it lacks. @@ -269,6 +271,7 @@ class WorkspaceState: return restored = self._restore(notebook, generation) self._workplanes = None # a new notebook: its workplanes are sent on its first settle, whatever they are + self._tag_splits = None kernel = MarimoKernel( notebook, server_port=self.port, @@ -1141,6 +1144,8 @@ class WorkspaceState: published = time.perf_counter() self.push_cells() self._push_workplanes(result.get("workplanes")) + if result.get("ok"): # a failed preview keeps what was last shown + self._push_tag_splits(result.get("tag_splits")) if os.environ.get("SCA_EDITOR_TRACE"): print( f"[sca edit] settle: kernel call {(published - signed) * 1000:.0f} ms " @@ -1169,6 +1174,14 @@ class WorkspaceState: self._last_publish_error = message self.hub.broadcast({"type": "status", "error": message[-300:]}) + def _push_tag_splits(self, splits: Any) -> None: + """The tagged entities the model's operations split, and the entities of their pieces: sent when they change.""" + if not isinstance(splits, list) or splits == (self._tag_splits or []): + return + self._tag_splits = splits + self.emit({"type": "tag_splits", "splits": splits}) + self.write_snapshot() + def _push_workplanes(self, workplanes: Any) -> None: """The notebook's workplanes and their frames, as the kernel computed them: sent when they change.""" if not isinstance(workplanes, list) or workplanes == self._workplanes: @@ -1660,6 +1673,10 @@ class WorkspaceState: }, "modified_parameters": sorted(saved), "model_revision": self.preview_revision, + # tagged entities the model's operations split: the pieces carry .split, highlighted in the viewport + "tag_splits": [ + {"tag": row.get("tag"), "into": row.get("into"), "op": row.get("op")} for row in self._tag_splits or [] + ], } def write_endpoint(self, host: str) -> None: diff --git a/src/simplecadapi/operators/__init__.py b/src/simplecadapi/operators/__init__.py index 00a51a4b..13cd23ed 100644 --- a/src/simplecadapi/operators/__init__.py +++ b/src/simplecadapi/operators/__init__.py @@ -125,6 +125,7 @@ from simplecadapi._cpp import ( apply_tag, apply_tag_rselection, explain_tag, + list_tag_splits, list_tags, select_edges_by_tag, select_faces_by_tag, @@ -315,6 +316,7 @@ __all__ = [ "elevate_curve_degree_redge", "elevate_surface_degree_rface", "explain_tag", + "list_tag_splits", "explode_rassembly", "extend_rsketch", "extrude_rsolid", diff --git a/src/simplecadapi/operators/selection.py b/src/simplecadapi/operators/selection.py index 9a2ac1b9..87558a33 100644 --- a/src/simplecadapi/operators/selection.py +++ b/src/simplecadapi/operators/selection.py @@ -15,6 +15,7 @@ from simplecadapi._cpp import ( apply_tag, apply_tag_rselection, explain_tag, + list_tag_splits, list_tags, select_edges_by_tag, select_faces_by_tag, @@ -24,6 +25,7 @@ __all__ = [ "apply_tag", "apply_tag_rselection", "explain_tag", + "list_tag_splits", "list_tags", "select_edges_by_tag", "select_faces_by_tag", diff --git a/src/simplecadapi/ref.py b/src/simplecadapi/ref.py index c73c6485..e6c9cc02 100644 --- a/src/simplecadapi/ref.py +++ b/src/simplecadapi/ref.py @@ -34,6 +34,7 @@ reference without it was made under version 1). from __future__ import annotations import ast +import contextvars import dataclasses import math from dataclasses import dataclass @@ -49,14 +50,14 @@ _native = _cpp._native if hasattr(_cpp, "_native") else None NAMING: int = int(_er.NAMING_VERSION.rsplit("/", 1)[-1]) """The naming version references are made under now (``scad-naming/``).""" -Kind = Literal["face", "edge", "vertex"] +Kind = Literal["face", "edge", "vertex", "solid"] Follow = Literal["identity", "derived"] Guard = Union[Tuple[str, Tuple[float, float, float], float], Tuple[str, Tuple[float, float, float], float, Tuple[float, float, float]]] """``(geometry type, centre, size)`` or ``(geometry type, centre, size, normal)``: what the entity looked like when it -was picked (size: area of a face, length of an edge). It never chooses between history results; it checks a +was picked (size: area of a face, length of an edge, volume of a solid). It never chooses between history results; it checks a positional anchor and ranks look-alikes of a lost reference.""" -_KINDS = ("face", "edge", "vertex") +_KINDS = ("face", "edge", "vertex", "solid") _RECORD_VERSION = 1 @@ -137,7 +138,7 @@ def _check_between(between: Any) -> tuple: @dataclass(frozen=True) class ElementRef: - """A stable reference to one face, edge or vertex; ``repr()`` is the code that makes it. + """A stable reference to one face, edge, vertex or solid; ``repr()`` is the code that makes it. Fields: ``kind``; ``feature`` and ``op`` (where the entity was born); then exactly one of ``role`` (its kernel role, with ``ordinal`` saying which of the entities with that role), ``topo`` (its position in that output, for an @@ -166,9 +167,11 @@ class ElementRef: def __post_init__(self) -> None: if self.kind not in _KINDS: - raise ValueError(f"a reference names a face, an edge or a vertex, not {self.kind!r}") + raise ValueError(f"a reference names a face, an edge, a vertex or a solid, not {self.kind!r}") if sum(x is not None for x in (self.role, self.topo, self.between)) != 1: raise ValueError("a reference names its entity by role=, by topo= or (an edge) by between=, exactly one of them") + if self.kind == "solid" and self.topo is None: + raise ValueError("a solid has no kernel role: a solid reference names it by topo= (its place in the output)") if self.between is not None: if self.kind != "edge": raise ValueError("between= names an edge by the two faces it lies between") @@ -277,16 +280,50 @@ class ElementRef: # -- resolving --------------------------------------------------------------------------------------------------- def resolve(self, shape: Any) -> Resolution: - """Follow the reference to the entities of *shape*; never raises for a split or a lost reference.""" + """Follow the reference to the entities of *shape*; never raises for a split or a lost reference. + + *shape* may be the pieces of a split body (``scad.Pieces``, a list of solids): the reference is resolved in each, + and ``bodies`` says which piece each entity lies in. + """ + if isinstance(shape, (list, tuple)): + return self._resolve_in_pieces(list(shape)) if self.between is not None: return self._resolve_between(shape) resolved = _er.resolve(self.anchor(), shape, follow=self.follow, guard=self._guard_dict()) if resolved.version_changed and self.guard is not None and resolved.status in ("ok", "merged"): # Made under other naming rules: the answer stands only if it still looks like what was picked. - if any(entity._geom_type() != self.guard[0] for entity in resolved.entities): + if any(_er._geom_type(entity) != self.guard[0] for entity in resolved.entities): return Resolution("lost", [], [], list(resolved.hops), None, "version_changed", self._lookalikes(shape), [], True) return resolved + def _resolve_in_pieces(self, pieces: list) -> Resolution: + found: list = [] + bodies: list = [] + hops: list = [] + merged = changed = False + missing: Optional[Resolution] = None + for index, piece in enumerate(pieces): + resolved = self.resolve(piece) + changed = changed or resolved.version_changed + if resolved.status == "lost": + if missing is None or missing.reason == "other_output": + missing = resolved + continue + merged = merged or resolved.status == "merged" + hops = hops or list(resolved.hops) + found.extend(resolved.entities) + bodies.extend(index for _ in resolved.entities) + if not found: + if missing is None: + return Resolution("lost", [], [], [], None, "no_pieces", [], [], changed) + return dataclasses.replace(missing, reason="not_in_pieces" if missing.reason == "other_output" else missing.reason) + if len(found) == 1: + return Resolution("merged" if merged else "ok", found, [], hops, None, None, [], bodies, changed) + candidates = _er._geometric_order([_er._candidate(e, str(getattr(e, "topo_id", ""))) for e in found]) + order = {id(c.entity): i for i, c in enumerate(candidates)} + ranked = sorted(zip(found, bodies), key=lambda pair: order[id(pair[0])]) + return Resolution("split", [e for e, _ in ranked], [], hops, None, None, candidates, [b for _, b in ranked], changed) + def _resolve_between(self, shape: Any) -> Resolution: """The edges of *shape* that lie between (a piece of) each of the two faces.""" sides = [] @@ -464,6 +501,34 @@ def vertex( piece=piece, guard=guard, digest=digest, naming=naming) +def solid( + feature: str, + op: str, + *, + topo: str = "solid_0", + occurrence: int = 0, + slot: int = 0, + piece: Optional[int] = None, + guard: Optional[Guard] = None, + digest: Optional[str] = None, + naming: int = 1, +) -> ElementRef: + """A reference to a solid (a body) born in *feature* by *op*. + + A solid has no kernel role: it is named by its position in the output of the operation that made it (``slot``: a + cut that splits a body outputs its pieces in order, by centre then size) and checked by its ``guard`` + (``("SOLID", centre, volume)``). Through later operations it is followed like a face: a fillet, a shell or a move + continues it, a union merges it, a cut that splits it splits it (``piece`` then says which piece is meant). Resolve + it in a solid, or in the pieces of a split body (a list of solids). + + Examples: + >>> left = scad.ref.solid("slot", "make_cut_rsolid_list", slot=0, guard=("SOLID", (-10.5, 0, 5), 1900)) + >>> left.one(pieces) # the solid of the pieces it names + """ + return _make("solid", feature, op, topo=topo, occurrence=occurrence, slot=slot, piece=piece, guard=guard, + digest=digest, naming=naming) + + def of(entity: Any, shape: Any, *, follow: Follow = "identity", guard: bool = True) -> ElementRef: """The stable reference of *entity*, a face, edge or vertex of *shape* (or of a shape *shape* descends from). @@ -497,7 +562,7 @@ def _born(entity: Any, shape: Any, *, follow: str = "identity", fingerprint: Any anchor = _er.stable_anchor_of(entity, shape) kind = str(anchor["kind"]).lower() if kind not in _KINDS: - raise ValueError(f"a reference names a face, an edge or a vertex, not a {kind}") + raise ValueError(f"a reference names a face, an edge, a vertex or a solid, not a {kind}") shared = len(_cpp._native._stable_candidates(node, anchor)) > 1 role = anchor.get("role") or None return ElementRef( @@ -599,7 +664,7 @@ def _selector(kind: str, refs: Sequence[ElementRef]) -> Any: wrong = [r for r in refs if r.kind != kind] if wrong: raise ValueError(f"{kind}s(...) takes {kind} references; {wrong[0].code()} is a {wrong[0].kind}") - factory = {"face": _ql.faces, "edge": _ql.edges, "vertex": _ql.vertices}[kind] + factory = {"face": _ql.faces, "edge": _ql.edges, "vertex": _ql.vertices, "solid": _ql.solids}[kind] predicates = [predicate(r) for r in refs] return factory().where(predicates[0] if len(predicates) == 1 else _ql.or_(*predicates)) @@ -633,10 +698,15 @@ def vertices(*refs: Union[ElementRef, Sequence[ElementRef]]) -> Any: return _selector("vertex", _flatten(refs)) +def solids(*refs: Union[ElementRef, Sequence[ElementRef]]) -> Any: + """The selection of the solids the references name (see :func:`faces`).""" + return _selector("solid", _flatten(refs)) + + # ---- reading the spelling back -------------------------------------------------------------------------------------- -_FACTORIES = {"face": "face", "edge": "edge", "vertex": "vertex"} -_SELECTIONS = {"faces": "face", "edges": "edge", "vertices": "vertex"} +_FACTORIES = {"face": "face", "edge": "edge", "vertex": "vertex", "solid": "solid"} +_SELECTIONS = {"faces": "face", "edges": "edge", "vertices": "vertex", "solids": "solid"} def _call_name(node: ast.expr) -> Optional[str]: @@ -701,7 +771,7 @@ def parse_selection(node: ast.expr) -> Tuple[str, list[ElementRef]]: def selection_code(kind: str, refs: Sequence[ElementRef], prefix: str = "scad.ref") -> str: """The code of a selection: one reference on one line, several one per line.""" - plural = {"face": "faces", "edge": "edges", "vertex": "vertices"}[kind] + plural = {"face": "faces", "edge": "edges", "vertex": "vertices", "solid": "solids"}[kind] if len(refs) == 1: return f"{prefix}.{plural}({refs[0].code(prefix)})" inner = "".join(f"\n {r.code(prefix)}," for r in refs) @@ -711,8 +781,19 @@ def selection_code(kind: str, refs: Sequence[ElementRef], prefix: str = "scad.re # ---- the resolver ql.ref asks --------------------------------------------------------------------------------------- +IN_PIECES: contextvars.ContextVar[bool] = contextvars.ContextVar("scad_ref_in_pieces", default=False) +"""Set while an operation runs on the pieces of a split body one piece at a time (``simplecadapi._glue.pieces``).""" + + def _resolve_record(scope: Any, record: Mapping[str, Any]) -> list: - return ElementRef.from_dict(record).all(scope) + reference = ElementRef.from_dict(record) + if IN_PIECES.get(): + resolved = reference.resolve(scope) + if resolved.status == "lost" and resolved.reason in ("other_output", "not_in_target"): + # Alive in another piece of the split body this scope is one piece of: nothing of it here. The operation + # over the pieces checks what the selection found on all of them together. + return [] + return reference.all(scope) _ql._set_reference_resolver(_resolve_record) @@ -738,6 +819,8 @@ __all__ = [ "predicate", "resolve", "selection_code", + "solid", + "solids", "vertex", "vertices", ] diff --git a/src/simplecadapi/runtime/cli.py b/src/simplecadapi/runtime/cli.py index 7db5ee13..4b135747 100644 --- a/src/simplecadapi/runtime/cli.py +++ b/src/simplecadapi/runtime/cli.py @@ -126,6 +126,8 @@ def _execute(args: argparse.Namespace) -> tuple[dict[str, Any], int]: "notebook": str(run.config.path), "cells": [ {"name": cell.name, "key": cell.key, "status": cell.status} + | ({"tag_splits": [{"tag": r["tag"], "into": r["into"], "op": r["op"]} for r in cell.tag_splits]} + if cell.tag_splits else {}) for cell in run.cells ], } diff --git a/src/simplecadapi/runtime/executor.py b/src/simplecadapi/runtime/executor.py index b492017b..1997000f 100644 --- a/src/simplecadapi/runtime/executor.py +++ b/src/simplecadapi/runtime/executor.py @@ -27,6 +27,7 @@ from __future__ import annotations import os import time +import warnings from collections.abc import Iterator from contextlib import contextmanager from contextvars import ContextVar @@ -34,6 +35,7 @@ from dataclasses import dataclass from pathlib import Path from typing import Any +from simplecadapi._glue.pieces import TagSplitWarning, split_message, tag_splits from simplecadapi._glue.session import GraphSession from ..recording.source_mapping import cell_sources from ._marimo import ( @@ -351,10 +353,25 @@ def _cell_recording( _running.reset(token) # Reached only when the body succeeded; failures propagate untouched. _check_bound(session, cell, glbls) + _warn_tag_splits(scope, cell, glbls) # The cell cache writes the nodes of the session beside the cell's entry. _sessions[cell.cell_id] = session +def _warn_tag_splits(scope: NotebookScope, cell: CellImpl, glbls: MutableGlobals) -> None: + """Warn, in the cell's output and at the cell's place in the notebook, about the tagged entities its operations + split (see TagSplitWarning).""" + + key = scope.cells.key(cell.cell_id) + rows = tag_splits((glbls[name] for name in cell.defs if name in glbls), key) + if not rows: + return + placement = scope.cells.place(key) + line = placement.line_offset + 1 if placement is not None else 1 + for row in rows: + warnings.warn_explicit(TagSplitWarning(split_message(row)), TagSplitWarning, str(scope.config.path), line) + + def _check_bound(session: GraphSession, cell: CellImpl, glbls: MutableGlobals) -> None: held = { id(requirement) diff --git a/src/simplecadapi/runtime/live.py b/src/simplecadapi/runtime/live.py index e581f07e..53594cac 100644 --- a/src/simplecadapi/runtime/live.py +++ b/src/simplecadapi/runtime/live.py @@ -224,6 +224,52 @@ def live_workplanes() -> list[dict[str, Any]]: return workplane_frames(values) +def scene_tag_splits(scene: PreviewScene) -> list[dict[str, Any]]: + """The tag splits behind the solids of *scene*, with the entities of each piece (``scad.list_tag_splits``). + + One row per split: ``tag``, ``into`` (the pieces' tags), ``op``, and ``pieces``: per entity that carries a piece's + tag, ``piece`` (its index in ``into``), ``node_id`` (the scene node drawing it) and ``entity_id``. The editor + highlights the pieces and says what was split, so whoever looks can judge whether the split was meant. + """ + + from .._cpp import list_tag_splits, ql + + rows: dict[tuple, dict[str, Any]] = {} + for key, solid in scene.solids.items(): + try: + splits = list_tag_splits(solid) + except Exception: # noqa: BLE001 - a diagnostic never breaks the preview + continue + if not splits: + continue + definition, body = scene.definitions[key], scene.bodies.get(key) + prefix = f"entity/{definition}/" if body is None else f"entity/{definition}/body:{body}/" + nodes = [node.node_id for node in scene.nodes if node.part_key == key] + entities = [("solid", solid)] + [("face", f) for f in ql.faces().resolve(solid)] + [ + ("edge", e) for e in ql.edges().resolve(solid) + ] + tagged = [(kind, entity, set(entity._list_tags())) for kind, entity in entities] + for split in splits: + row = rows.setdefault( + (split["node_id"], split["tag"], split["source_topo_id"]), + {"tag": split["tag"], "into": list(split["into"]), "op": split["op"], "pieces": []}, + ) + for index, name in enumerate(split["into"]): + for kind, entity, tags in tagged: + if name in tags: + for node_id in nodes: + row["pieces"].append( + {"piece": index, "node_id": node_id, "entity_id": f"{prefix}{kind}/{entity.topo_id}"} + ) + return list(rows.values()) + + +def live_tag_splits() -> list[dict[str, Any]]: + """:func:`scene_tag_splits` of the scene last previewed in this kernel (empty before the first preview).""" + + return scene_tag_splits(_last_preview) if _last_preview is not None else [] + + def preview_entity_info(entity_id: str) -> dict[str, Any] | None: """The properties of one entity of the scene last previewed (see :func:`entity_info`).""" @@ -251,7 +297,9 @@ def publish_live(url: str, *, step: str = "", timeout: float = 60.0) -> LivePack __all__ = [ + "live_tag_splits", "live_workplanes", + "scene_tag_splits", "workplane_frames", "LivePackage", "LiveUnavailableError", diff --git a/src/simplecadapi/runtime/runner.py b/src/simplecadapi/runtime/runner.py index 32126a3a..5d17e614 100644 --- a/src/simplecadapi/runtime/runner.py +++ b/src/simplecadapi/runtime/runner.py @@ -32,6 +32,7 @@ from dataclasses import dataclass, replace from pathlib import Path from typing import Any, Literal, TypeVar +from simplecadapi._glue.pieces import tag_splits from ..artifacts.assembly_io import attached_definition from ..artifacts.canonical import validate_logical_id from ..build.definition import Definition @@ -90,6 +91,9 @@ class CellReport: key: str """The cell's key: the namespace of its ids (see :mod:`.cells`).""" status: CellStatus + tag_splits: tuple[dict, ...] = () + """The tagged entities this cell's operations split (``scad.list_tag_splits`` rows): each piece carries + ``.split`` and the tag names none of them. Reported whether the cell ran or was restored.""" @dataclass(frozen=True) @@ -342,6 +346,9 @@ def _run( if cell.cell_id in restored else "ran" if cell.cell_id in progress.ran else "skipped" ), + tag_splits=tuple( + tag_splits((values[name] for name in cell.defs if name in values), cells.key(cell.cell_id)) + ), ) for cell in ordered ) diff --git a/src/simplecadapi/topology/element_ref.py b/src/simplecadapi/topology/element_ref.py index c94ae92c..6a94ec41 100644 --- a/src/simplecadapi/topology/element_ref.py +++ b/src/simplecadapi/topology/element_ref.py @@ -61,7 +61,7 @@ class Candidate: kind: str geom_type: str center: tuple - size: float # area of a face, length of an edge + size: float # area of a face, length of an edge, volume of a solid score: float = 0.0 # lost only: distance to the guard, smaller is closer def describe(self) -> Dict[str, Any]: @@ -165,16 +165,22 @@ def anchors_for_role(shape: Any, role: str) -> List[Dict[str, Any]]: def _size(entity: Any) -> float: + if type(entity).__name__ == "Solid": + return float(entity.get_volume()) return float(entity.get_area()) if hasattr(entity, "get_area") else float(entity.get_length()) +def _geom_type(entity: Any) -> str: + return "SOLID" if type(entity).__name__ == "Solid" else entity._geom_type() + + def guard_of(entity: Any) -> Dict[str, Any]: """A geometric fingerprint of *entity*: checks a resolution and ranks candidates for a lost one, never more.""" c = entity.get_center() guard: Dict[str, Any] = { "kind": type(entity).__name__.lower(), - "geom_type": entity._geom_type(), + "geom_type": _geom_type(entity), "center": [c.x, c.y, c.z], "size": _size(entity), } @@ -190,7 +196,7 @@ def _candidate(entity: Any, topo_id: str, score: float = 0.0) -> Candidate: entity=entity, topo_id=topo_id, kind=type(entity).__name__.lower(), - geom_type=entity._geom_type(), + geom_type=_geom_type(entity), center=(c.x, c.y, c.z), size=_size(entity), score=score, @@ -205,7 +211,7 @@ def _geometric_order(candidates: List[Candidate]) -> List[Candidate]: def _ranked_lookalikes(shape: Any, guard: Dict[str, Any], kind: str, limit: int = 5) -> List[Candidate]: from .. import ql - factory = {"face": ql.faces, "edge": ql.edges}.get(kind) + factory = {"face": ql.faces, "edge": ql.edges, "solid": ql.solids}.get(kind) if factory is None: return [] out: List[Candidate] = [] @@ -215,7 +221,7 @@ def _ranked_lookalikes(shape: Any, guard: Dict[str, Any], kind: str, limit: int distance = math.dist((c.x, c.y, c.z), guard["center"]) size = _size(entity) score = distance + abs(size - guard["size"]) / max(guard["size"], 1e-9) - if entity._geom_type() != guard.get("geom_type"): + if _geom_type(entity) != guard.get("geom_type"): score += 1000.0 if "normal" in guard and hasattr(entity, "get_normal_at"): n = entity.get_normal_at() @@ -243,6 +249,11 @@ def _bodies_of(shape: Any, entities: List[Any]) -> List[Optional[int]]: kind = type(entity).__name__ found = None for index, solid in enumerate(solids): + if kind == "Solid": + if solid == entity: + found = index + break + continue members = ql.faces().resolve(solid) if kind == "Face" else ql.edges().resolve(solid) if any(member == entity for member in members): found = index diff --git a/test/test_element_ref_history.py b/test/test_element_ref_history.py index 86c615fc..081f4c52 100644 --- a/test/test_element_ref_history.py +++ b/test/test_element_ref_history.py @@ -465,10 +465,11 @@ def test_an_n_ary_cut_composes_its_steps(): r = er.resolve(anchor, cut) assert r.status == "split" assert sorted(round(f.get_area(), 2) for f in r.entities) == [80.0, round(640 - 13 * math.pi, 2)] - assert sorted(round(f.get_area(), 2) for f in ql.faces().where(ql.tag("user.top")).resolve(cut)) == [ - 80.0, - round(640 - 13 * math.pi, 2), - ] + # the tag follows its face as the reference does: split, it names the pieces .split1, .split2 + assert ql.faces().where(ql.tag("user.top")).resolve(cut) == [] + pieces = {name: ql.faces().where(ql.tag(name)).exactly(1).resolve(cut)[0] for name in ("user.top.split1", "user.top.split2")} + assert sorted(round(f.get_area(), 2) for f in pieces.values()) == [80.0, round(640 - 13 * math.pi, 2)] + assert [c.center for c in r.candidates] == [tuple(f.get_center()) for f in (pieces["user.top.split1"], pieces["user.top.split2"])] def test_a_tag_survives_pickling_with_its_history(): diff --git a/test/test_ref_api.py b/test/test_ref_api.py index 854b9a1b..236d2786 100644 --- a/test/test_ref_api.py +++ b/test/test_ref_api.py @@ -82,7 +82,8 @@ def test_a_reference_reads_as_code_and_parses_back(): ("scad.ref.edge('base', 'make_box_rsolid', role='x', piece=-1)", "piece"), ("scad.ref.face('base', 'make_box_rsolid', role=__import__('os').name)", "literal values only"), ("scad.ref.face('base', 'make_box_rsolid', role='box.top', guard=('PLANE', (0, 0), 1))", "guard"), - ("scad.ref.solid('base', 'make_box_rsolid', role='box')", "not a reference"), + ("scad.ref.solid('base', 'make_box_rsolid', role='box')", "a solid has no kernel role"), + ("scad.ref.shell('base', 'make_box_rsolid', topo='shell_0')", "not a reference"), ], ) def test_a_malformed_reference_is_refused(text, message): diff --git a/test/test_tag_splits.py b/test/test_tag_splits.py new file mode 100644 index 00000000..9eab3928 --- /dev/null +++ b/test/test_tag_splits.py @@ -0,0 +1,157 @@ +"""A tag follows its entity as a reference does: a split names the pieces .split; solids have history and refs. + +The pieces of a split are numbered when the operation is recorded (by centre, then size), the order a split reference +lists its candidates in; the split is reported (list_tag_splits, the cell's TagSplitWarning, the run report). +""" + +from __future__ import annotations + +import json +import subprocess +import sys +import warnings +from pathlib import Path + +import pytest + +import simplecadapi as scad +from simplecadapi.runtime import run_notebook +from test_notebook_runtime import NotebookTestCase, cell, notebook_text + +ql = scad.ql + + +def _tags(shape, prefix: str) -> list[str]: + return sorted(t for f in ql.faces().resolve(shape) for t in f._list_tags() if t.startswith(prefix)) + + +def _top(box): + return scad.apply_tag_rselection(box, ql.faces().where(ql.prop("geom.center.z", ">=", 9.9)).exactly(1), "mount.top") + + +def test_a_split_tagged_face_names_its_pieces_and_the_tag_none_of_them(): + with scad.GraphSession(): + box = _top(scad.make_box_rsolid(40.0, 10.0, 10.0)) + grooved = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 4.0, bottom_face_center=(0.0, 0.0, 8.0))) + assert _tags(grooved, "mount") == ["mount.top.split1", "mount.top.split2"] + assert ql.faces().where(ql.tag("mount.top")).resolve(grooved) == [] + assert len(ql.faces().where(ql.tag("mount.top.*")).resolve(grooved)) == 2 + left = ql.faces().where(ql.tag("mount.top.split1")).exactly(1).resolve(grooved)[0] + assert left.get_center().x < 0 # piece 1 is the one with the smaller centre + [row] = scad.list_tag_splits(grooved) + assert (row["tag"], row["into"], row["op"]) == ("mount.top", ["mount.top.split1", "mount.top.split2"], "make_cut_rsolid") + # a hole is no split: the face keeps its tag + drilled = scad.cut_rsolid(box, scad.make_cylinder_rsolid(1.0, 30.0, (10.0, 0.0, -5.0))) + assert _tags(drilled, "mount") == ["mount.top"] and scad.list_tag_splits(drilled) == [] + + +def test_the_pieces_follow_on_and_a_second_split_numbers_again(): + with scad.GraphSession(): + box = _top(scad.make_box_rsolid(40.0, 10.0, 10.0)) + halves = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 20.0)) # splits the body, and the top face + moved = scad.translate_shape(halves, (0.0, 0.0, 1.0)) + assert [_tags(piece, "mount") for piece in moved] == [["mount.top.split1"], ["mount.top.split2"]] + quarter = scad.cut_rsolid(moved[1], scad.make_box_rsolid(2.0, 20.0, 20.0, bottom_face_center=(10.0, 0.0, -5.0))) + assert sorted(_tags(piece, "mount") for piece in quarter) == [["mount.top.split2.split1"], ["mount.top.split2.split2"]] + + +def test_a_solid_is_continued_by_one_solid_operations_merged_by_a_union_and_split_by_a_cut(): + with scad.GraphSession(): + box = scad.apply_tag_rselection(scad.make_box_rsolid(40.0, 10.0, 10.0), ql.solids().exactly(1), "part.base") + rounded = scad.fillet_rsolid(box, ql.edges().where(ql.prop("geom.center.z", ">=", 9.9)), 1.0) + moved = scad.translate_shape(rounded, (1.0, 0.0, 0.0)) + assert "part.base" in moved._list_tags() + joined = scad.union_rsolid(moved, scad.make_cylinder_rsolid(2.0, 20.0)) # another op: no second box to confuse it with + reference = scad.ref.of(rounded, rounded) + assert reference.kind == "solid" and reference.resolve(joined).status in ("ok", "merged") + pieces = scad.cut_rsolid(moved, scad.make_box_rsolid(2.0, 20.0, 20.0, bottom_face_center=(1.0, 0.0, -5.0))) + assert [sorted(t for t in p._list_tags() if t.startswith("part")) for p in pieces] == [["part.base.split1"], ["part.base.split2"]] + resolved = reference.resolve(pieces) + assert resolved.status == "split" and resolved.bodies == [0, 1] + + +def test_a_solid_reference_names_one_piece_through_later_operations(): + with scad.GraphSession(): + box = scad.make_box_rsolid(40.0, 10.0, 10.0) + # made before the cut's tool box exists: two make_box_rsolid nodes later, and the history tells them apart + early = scad.ref.of(box, box) + pieces = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 20.0)) + assert early.resolve(pieces).status == "split" + right = scad.ref.of(pieces[1], pieces[1]) + assert right.kind == "solid" and right.slot == 1 and scad.ref.parse(repr(right)) == right + moved = scad.translate_shape(pieces, (0.0, 0.0, 3.0)) + assert right.one(moved).get_center().x > 0 + assert right.resolve(moved[0]).status == "lost" + with pytest.raises(ValueError, match="a solid has no kernel role"): + scad.ref.parse("scad.ref.solid('base', 'make_box_rsolid', role='box')") + + +def test_a_reference_selection_works_over_the_pieces_and_refuses_one_that_finds_nothing(): + with scad.GraphSession(): + box = scad.make_box_rsolid(40.0, 10.0, 10.0) + pieces = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 20.0)) + moved = scad.translate_shape(pieces, (0.0, 0.0, 3.0)) + rim = ql.edges().where(ql.prop("geom.center.x", ">=", 15)).where(ql.prop("geom.center.z", ">=", 9)).resolve(pieces[1])[0] + edge = scad.ref.of(rim, pieces[1]) + rounded = scad.fillet_rsolid(moved, scad.ref.edges(edge), 0.3) + assert rounded[0].get_volume() == pytest.approx(moved[0].get_volume()) + assert rounded[1].get_volume() < moved[1].get_volume() + top = scad.ref.of(ql.faces().where(ql.prop("geom.center.z", ">=", 12)).resolve(moved[0])[0], moved[0]) + shelled = scad.shell_rsolid(moved, scad.ref.faces(top), 0.5) + assert shelled[0].get_volume() < moved[0].get_volume() + assert shelled[1].get_volume() == pytest.approx(moved[1].get_volume()) + with pytest.raises(scad.ref.ElementRefError): + scad.fillet_rsolid(moved[0], scad.ref.edges(edge), 0.3) # one piece, the edge is on the other + + +SPLIT = notebook_text( + cell( + "box = scad.apply_tag_rselection(scad.make_box_rsolid(40.0, 10.0, 10.0)," + " scad.ql.faces().where(scad.ql.prop('geom.center.z', '>=', 9.9)).exactly(1), 'mount.top')", + returns="box", + ), + cell( + "grooved = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 4.0, bottom_face_center=(0.0, 0.0, 8.0)))", + reads="box", + returns="grooved", + ), + cell("part = scad.make_part_rpart(part_id='grooved', body=grooved)", reads="grooved", returns="part"), + table='id = "grooved"', +) + + +class TestTheRunReportsTheSplit(NotebookTestCase): + def test_a_split_is_reported_by_the_cell_that_made_it_ran_or_restored(self) -> None: + nb = self.write("grooved.py", SPLIT) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + first = run_notebook(nb) + assert any(issubclass(w.category, scad.TagSplitWarning) and "mount.top.split1" in str(w.message) for w in caught) + second = run_notebook(nb) + for run in (first, second): + splits = {report.key.split(".")[0]: report.tag_splits for report in run.cells if report.tag_splits} + assert len(splits) == 1 + [rows] = splits.values() + assert [row["into"] for row in rows] == [["mount.top.split1", "mount.top.split2"]] + assert self.statuses(second)[2] == "cached" + report = subprocess.run( + [sys.executable, "-m", "simplecadapi.cli", "run", str(nb)], capture_output=True, text=True, check=True + ) + cells = json.loads(report.stdout.strip().splitlines()[-1])["cells"] + assert [c["tag_splits"] for c in cells if "tag_splits" in c] == [ + [{"tag": "mount.top", "into": ["mount.top.split1", "mount.top.split2"], "op": "make_cut_rsolid"}] + ] + + +def test_the_preview_scene_lists_the_entities_of_each_piece(): + from simplecadapi.runtime.live import scene_tag_splits + from simplecadapi.scene.preview import compile_preview + + with scad.GraphSession(): + box = _top(scad.make_box_rsolid(40.0, 10.0, 10.0)) + grooved = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 4.0, bottom_face_center=(0.0, 0.0, 8.0))) + part = scad.make_part_rpart(part_id="grooved", body=grooved) + [row] = scene_tag_splits(compile_preview(part)) + assert row["into"] == ["mount.top.split1", "mount.top.split2"] + assert sorted(p["piece"] for p in row["pieces"]) == [0, 1] + assert all(p["entity_id"].startswith("entity/grooved/face/") for p in row["pieces"])