Merge remote-tracking branch 'github/dev' into feat/inspect-soft-render

This commit is contained in:
NiJingzhe
2026-10-25 16:03:01 +08:00
27 changed files with 433 additions and 74 deletions
+10 -1
View File
@@ -9,16 +9,25 @@ user-facing notes live in [`docs/updates/`](docs/updates/) (English and
## 2.2.7b1 — 2026-10-24
### Added
- `cut_rsolid_list(base, *tools)`: the boolean cut that keeps every piece. A slot through a bar returns both halves, a
tool that encloses the body returns an empty list. Recorded as `make_cut_rsolid_list` and replayable.
- Prebuilt wheels for Linux x86_64, Linux aarch64, macOS arm64 and Windows x86_64, each for Python 3.10-3.13,
built by the release workflow against one static OpenCASCADE 7.9.3.
### Changed
- The geometry engine is C++ on OpenCASCADE, shipped in the wheel as `simplecadapi._cpp`; one distribution, one
import package. The public API and the previous test suite are unchanged.
import package. The public API is unchanged, and the previous test suite passes (three tests that relied on a dropped
sliver of a tangent cut now use a tool clear of the wall).
- Every message the library writes is English; the tag-validation and semantic-query errors render in full with
possible causes and fixes.
- macOS wheels require macOS 14 or later.
### Fixed
- `cut_rsolid` no longer drops pieces silently. When a cut split the body it returned only the first piece (a slot
through a 100x20x10 bar reported half the volume); it now raises and points to `cut_rsolid_list`. A tool that only
touches a wall tangentially (a cylinder of radius 2 at (3, 3) in a 10x10 block) leaves a separate sliver and now
raises too.
### Removed
- Dependencies `cadquery-ocp`, `ocp-gordon` and `py-slvs`; the `SCA_BACKEND` switch.
+1 -1
View File
@@ -108,7 +108,7 @@ it and stop that route; never invent an alternative route.
boundary comment `# ---- feature: <slug> (<role>) ----`; 2D
profiles and planar paths go through the sketch API, primitives
only when the shape is completely contained in the basic form.
4. Booleans (`union_rsolid`, `cut_rsolid`, `intersect_rsolid`)
4. Booleans (`union_rsolid`, `cut_rsolid`, `cut_rsolid_list`, `intersect_rsolid`)
accept mixed inputs and return exactly one `Solid`; union
defaults to `glue=False` with a conservative scale-relative
tolerance and fails explicitly when it cannot produce one
@@ -34,6 +34,10 @@ no patching exported or solved artifacts.
- Isolate and simplify the failing base/tool pair.
- `cut_rsolid(..., skip_non_intersecting=False)` is the strict diagnostic mode;
with the default `True`, non-intersecting tools may be ignored.
- `cut_rsolid` expected a single Solid but the kernel returned several: the cut
split the body. If that is intended, call `cut_rsolid_list`; if not, the tool
crosses the body completely or touches a wall tangentially — resize or
reposition it.
- After repeated failure, reconsider operation order — not just retry the same
cut harder.
+1
View File
@@ -96,6 +96,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi
## Boolean Operations
- [cut_rsolid](cut_rsolid.md) *(from operators/boolean.py)* `top-level`
- [cut_rsolid_list](cut_rsolid_list.md) *(from operators/boolean.py)* `top-level`
- [intersect_rsolid](intersect_rsolid.md) *(from operators/boolean.py)* `top-level`
- [union_rsolid](union_rsolid.md) *(from operators/boolean.py)* `top-level`
@@ -36,3 +36,7 @@ sequences, and returns a single `Solid`.
## Returns
Solid: The cut result solid.
## Raises
- **SimpleCADError**: The cut produced no solid, or split the body into several (a slot through a bar). Use ``cut_rsolid_list`` to keep every piece.
@@ -0,0 +1,49 @@
# cut_rsolid_list
## API Definition
```python
def cut_rsolid_list(*solids, skip_non_intersecting=True, tracking_policy='full')
```
*Source: operators/boolean.py*
## Import Surface
- top-level: `from simplecadapi import cut_rsolid_list`
## Description
Compute the boolean difference of solids and keep every piece.
A cut can split the body (a slot through a bar leaves two parts) or consume it
(a tool that encloses the whole body leaves nothing). ``cut_rsolid`` refuses
such a result because it returns exactly one ``Solid``; this operator returns
them all. A tool is cut from every piece it meets, so several tools may split
a body into several parts.
``pieces = cut_rsolid_list(bar, slot)`` returns both halves of a bar cut by
a through slot. Use ``cut_rsolid`` when the result must be one solid.
## Parameters
### solids
- **Description**: One or more Solid objects or sequences of Solid. Nested sequences are flattened before processing; the first solid is the base, the rest are subtracted in order.
### skip_non_intersecting
- **Description**: When True, a tool that meets none of the current pieces is ignored; when False it raises.
### tracking_policy
- **Description**: FULL computes topology history and lineage. GRAPH keeps the replayable operation node without computing a TopoDelta.
## Returns
list[Solid]: Every piece of the cut, in kernel order; empty when the tools
consume the base.
## Raises
- **SimpleCADError**: An input is not a valid Solid, or the kernel could not compute the cut.
@@ -79,6 +79,10 @@ consult their own documentation before the first call.
- `cut_rsolid` skips non-intersecting tools by default
(`skip_non_intersecting=True`); pass `skip_non_intersecting=False` for strict
diagnostics — a skipped cut is never a completed feature.
- A cut can split a body (a slot through a bar leaves two parts) or consume it
(a tool that encloses the whole body). `cut_rsolid` returns one `Solid`, so it
raises instead of dropping parts; use `cut_rsolid_list(base, tools)` to get
every piece as a list (empty when nothing is left).
## Validation gates
+9
View File
@@ -45,6 +45,15 @@ The models computed are the same (volumes agree to 1e-12 relative).
* `simplecadapi.inspect.brep` renders with the same software renderer as `render_screenshot_rpath`: no VTK, no GPU,
no display server (no `xvfb`). The `inspect` extra is just `matplotlib`.
## Booleans that split a body
* New `cut_rsolid_list(base, *tools)` returns every piece of a cut: a slot through a bar gives both halves, a tool that
encloses the whole body gives an empty list. It is recorded as `make_cut_rsolid_list` and replays.
* `cut_rsolid` used to return only the first piece when a cut split the body, silently losing the rest (a slot through a
100x20x10 bar reported half the volume). It now raises and names `cut_rsolid_list`. A tool that only touches a wall
tangentially also leaves a separate sliver, so a script that relied on the dropped sliver needs a tool that does not
touch the wall, or `cut_rsolid_list`.
## Errors
* Every message the library writes is English.
+8
View File
@@ -40,6 +40,14 @@ macOS Intel、musl Linux、Windows ARM 没有预编译包;这些平台由源
* `SCA_BACKEND` 已删除:只有一个后端。
* `simplecadapi.inspect.brep` 使用与 `render_screenshot_rpath` 相同的软渲染:不依赖 VTK、GPU 和显示服务(无需 `xvfb`)。`inspect` 额外依赖只剩 `matplotlib`。
## 会把实体切成多段的布尔运算
* 新增 `cut_rsolid_list(base, *tools)`,返回切割产生的每一段:在棒上开通槽得到两段,工具把整个实体包住则得到空列表。
它记录为 `make_cut_rsolid_list`,可以回放。
* 以前切割把实体分成多段时,`cut_rsolid` 只返回第一段,其余静默丢失(100x20x10 的棒开通槽,体积只剩一半)。
现在它会报错并指向 `cut_rsolid_list`。工具只与壁面相切时也会留下一块独立的残片,所以依赖"丢掉残片"的脚本需要把工具
改成不碰壁面,或改用 `cut_rsolid_list`。
## 报错
* 库写出的所有消息都是英文。
@@ -473,6 +473,17 @@ void bind_booleans(py::module_& m) {
py::kw_only(), py::arg("skip_non_intersecting") = true, py::arg("tracking_policy") = "full",
"Compute the boolean difference of solids: the first is the base, the rest are subtracted in order.");
m.def(
"cut_rsolid_list",
[](const py::args& solids, bool skip_non_intersecting, const py::object& tracking_policy) {
const std::vector<Solid> operands = flattened(solids, "cut_rsolid_list");
const CutOptions options{skip_non_intersecting, policy_text(tracking_policy)};
return solids_to_py(unlocked(false, [&] { return cut_rsolid_list(operands, options); }));
},
py::kw_only(), py::arg("skip_non_intersecting") = true, py::arg("tracking_policy") = "full",
"Compute the boolean difference of solids and keep every piece: a cut that splits the body returns each part, "
"and one that consumes the body returns an empty list.");
m.def(
"intersect_rsolid",
[](const py::args& solids) {
@@ -29,6 +29,11 @@ struct CutOptions {
// The first solid minus every other. Error "cut_rsolid".
Solid cut_rsolid(const std::vector<Solid>& solids, const CutOptions& options = {});
// The same cut, keeping every piece: a cut that splits the body (a slot through a bar) returns each part, and one that
// consumes the body returns an empty list. cut_rsolid refuses such a result instead of dropping parts.
// Error "cut_rsolid_list"; recorded as make_cut_rsolid_list.
std::vector<Solid> cut_rsolid_list(const std::vector<Solid>& solids, const CutOptions& options = {});
// The overlap of all `solids`. Error "intersect_rsolid".
Solid intersect_rsolid(const std::vector<Solid>& solids);
@@ -5,6 +5,7 @@
#include <map>
#include <optional>
#include <vector>
#include <string>
#include "scad/core/value.hpp"
@@ -43,7 +44,8 @@ struct TrackedResult {
// A tracked boolean. `solid` is empty when the boolean produced no solid.
struct TrackedBooleanResult {
std::optional<Solid> solid;
std::optional<Solid> solid; // the first solid of the kernel's answer
std::vector<Solid> solids; // every solid of the answer (a cut can split the body)
TopoDelta delta;
DeltaEntries delta_entries;
};
+142 -56
View File
@@ -11,6 +11,7 @@
#include "scad/kernel/properties.hpp"
#include "scad/kernel/topology.hpp"
#include "scad/ops/features/diagnostics.hpp"
#include "scad/semantic/autotag.hpp"
#include "scad/semantic/tracking.hpp"
namespace scad {
@@ -19,6 +20,7 @@ namespace {
constexpr const char* kUnionOp = "make_union_rsolid";
constexpr const char* kCutOp = "make_cut_rsolid";
constexpr const char* kCutListOp = "make_cut_rsolid_list";
constexpr const char* kIntersectOp = "make_intersect_rsolid";
constexpr double kUnionTolFactor = 1e-7;
@@ -53,6 +55,18 @@ const ErrorSpec& cut_spec() {
return spec;
}
const ErrorSpec& cut_list_spec() {
static const ErrorSpec spec{
"cut_rsolid_list",
"Failed to compute the boolean cut.",
{"One or more inputs are not Solid objects.", "The base solid or tool solids are invalid.",
"The kernel could not compute a valid cut result for the current geometry."},
{"Pass a valid base solid followed by valid tool solids.",
"Check whether the tool geometry actually intersects the base solid.",
"If the cut depends on earlier union results, verify those results first."}};
return spec;
}
const ErrorSpec& intersect_spec() {
static const ErrorSpec spec{
"intersect_rsolid",
@@ -232,6 +246,83 @@ Solid union_rsolid(const std::vector<Solid>& solids, const UnionOptions& options
// ---------------------------------------------------------------------------
// cut
// ---------------------------------------------------------------------------
namespace {
// What a run of cuts left: every piece of the base, and the history of the steps that touched it.
struct CutRun {
std::vector<Solid> pieces;
std::vector<TopoDelta> deltas;
DeltaEntries entries;
bool cut_performed = false;
// Every intermediate result stays alive until the merged delta is recorded: step deltas name faces by kernel
// hashes, which come from the shapes' addresses, and a freed face's address could be reused by an output face.
std::vector<Solid> intermediates;
};
// The first solid minus every other. A tool is cut from each piece it meets, and a cut may split a piece in two
// (a slot through a bar), so the answer is a list: empty when the tools consume the base.
CutRun run_cuts(const std::vector<Solid>& solids, const CutOptions& options, TrackingPolicy policy,
std::string_view operation, bool& no_intersection) {
if (solids.empty()) throw ValueError(std::string(operation) + " requires at least one Solid input");
CutRun run;
run.pieces.push_back(solids.front());
for (std::size_t i = 1; i < solids.size(); ++i) {
const Solid& candidate = solids[i];
const TopoDS_Shape& s2 = candidate.wrapped();
if (s2.IsNull()) throw ValueError("The input solid is invalid; the cut cannot be computed.");
std::vector<Solid> next;
bool met = false; // some piece intersects this tool
bool too_small = false;
for (const Solid& piece : run.pieces) {
const TopoDS_Shape& s1 = piece.wrapped();
if (s1.IsNull()) throw ValueError("The input solid is invalid; the cut cannot be computed.");
const std::vector<TopoDS_Solid> overlap = kernel::solids_of(kernel::common_shapes({s1, s2}));
if (overlap.empty()) {
next.push_back(piece);
continue;
}
if (kernel::volume(overlap.front()) < 1e-12) {
too_small = true;
next.push_back(piece);
continue;
}
met = true;
std::vector<Solid> cut_pieces;
if (policy == TrackingPolicy::Full) {
TrackedBooleanResult tracked = tracked_cut(piece, candidate);
cut_pieces = std::move(tracked.solids);
run.deltas.push_back(std::move(tracked.delta));
merge_entries(run.entries, std::move(tracked.delta_entries));
} else {
for (const TopoDS_Solid& part : kernel::solids_of(kernel::cut_shapes(s1, {s2}))) cut_pieces.emplace_back(part);
}
run.intermediates.push_back(piece);
for (Solid& part : cut_pieces) next.push_back(std::move(part));
run.cut_performed = true;
}
if (!met && !options.skip_non_intersecting) {
no_intersection = true;
throw ValueError(too_small ? "The intersection of the cut tool solid and the current solid is too small."
: "The cut tool solid does not intersect the current solid.");
}
run.pieces = std::move(next);
}
return run;
}
void record_cut(const std::vector<Solid>& solids, const CutOptions& options, TrackingPolicy policy, FeatureRecord& rec) {
rec.param("tool_count", Value(static_cast<std::int64_t>(solids.size() - 1)))
.param("skip_non_intersecting", Value(options.skip_non_intersecting))
.param("tracking_policy", Value(std::string(to_string(policy))));
add_operands(rec, solids);
}
} // namespace
Solid cut_rsolid(const std::vector<Solid>& solids, const CutOptions& options) {
bool no_intersection = false;
try {
@@ -240,71 +331,26 @@ Solid cut_rsolid(const std::vector<Solid>& solids, const CutOptions& options) {
if (solids.empty()) throw ValueError("cut_rsolid requires at least one Solid input");
if (solids.size() == 1) return solids.front();
Solid result_solid = solids.front();
std::vector<TopoDelta> deltas;
DeltaEntries merged_entries;
// Step deltas name faces by kernel hashes, which come from the shapes' addresses. Every
// intermediate result stays alive until the merged delta is recorded: a freed face's
// address could otherwise be reused by an output face and a stale entry would resolve to it.
std::vector<Solid> intermediates;
bool cut_performed = false;
for (std::size_t i = 1; i < solids.size(); ++i) {
const Solid& candidate = solids[i];
const TopoDS_Shape& s1 = result_solid.wrapped();
const TopoDS_Shape& s2 = candidate.wrapped();
if (s1.IsNull() || s2.IsNull()) throw ValueError("The input solid is invalid; the cut cannot be computed.");
const std::vector<TopoDS_Solid> overlap = kernel::solids_of(kernel::common_shapes({s1, s2}));
if (overlap.empty()) {
if (options.skip_non_intersecting) continue;
no_intersection = true;
throw ValueError("The cut tool solid does not intersect the current solid.");
}
if (kernel::volume(overlap.front()) < 1e-12) {
if (options.skip_non_intersecting) continue;
no_intersection = true;
throw ValueError("The intersection of the cut tool solid and the current solid is too small.");
}
std::optional<TrackedBooleanResult> tracked;
Solid next = [&]() -> Solid {
if (policy == TrackingPolicy::Full) {
tracked = tracked_cut(result_solid, candidate);
if (!tracked->solid) throw ValueError("The cut failed: OCC returned no valid solid");
return *tracked->solid;
}
const std::vector<TopoDS_Solid> pieces = kernel::solids_of(kernel::cut_shapes(s1, {s2}));
if (pieces.empty()) throw ValueError("The cut failed: OCC returned no valid solid");
if (pieces.size() != 1) {
throw ValueError("cut_rsolid expected a single Solid result but the kernel returned " + std::to_string(pieces.size()) + " solids.");
}
return Solid(pieces.front());
}();
inherit_metadata(next, {&result_solid});
intermediates.push_back(result_solid);
result_solid = next;
if (tracked) {
deltas.push_back(std::move(tracked->delta));
merge_entries(merged_entries, std::move(tracked->delta_entries));
}
cut_performed = true;
CutRun run = run_cuts(solids, options, policy, "cut_rsolid", no_intersection);
if (run.pieces.empty()) throw ValueError("The cut failed: OCC returned no valid solid");
if (run.pieces.size() != 1) {
throw ValueError("cut_rsolid expected a single Solid result but the kernel returned " +
std::to_string(run.pieces.size()) +
" solids; the cut split the body. Use cut_rsolid_list to keep every piece.");
}
Solid result_solid = run.pieces.front();
inherit_metadata(result_solid, {&solids.front()});
result_solid.apply_tag("solid.boolean.cut", false);
std::optional<TopoDelta> merged = merge_topo_deltas(deltas);
std::optional<TopoDelta> merged = merge_topo_deltas(run.deltas);
FeatureRecord rec(kCutOp);
rec.param("tool_count", Value(static_cast<std::int64_t>(solids.size() - 1)))
.param("skip_non_intersecting", Value(options.skip_non_intersecting))
.param("tracking_policy", Value(std::string(to_string(policy))));
add_operands(rec, solids);
record_cut(solids, options, policy, rec);
FinalizeSpec spec;
spec.record = std::move(rec).take();
if (cut_performed && merged) {
return finalize_tracked<Solid>(std::move(result_solid), std::move(*merged), std::move(merged_entries), std::move(spec));
if (run.cut_performed && merged) {
return finalize_tracked<Solid>(std::move(result_solid), std::move(*merged), std::move(run.entries), std::move(spec));
}
if (policy == TrackingPolicy::Graph) return finalize_derived(std::move(result_solid), std::move(spec));
return finalize_primitive(std::move(result_solid), std::move(spec.record));
@@ -314,6 +360,46 @@ Solid cut_rsolid(const std::vector<Solid>& solids, const CutOptions& options) {
}
}
std::vector<Solid> cut_rsolid_list(const std::vector<Solid>& solids, const CutOptions& options) {
bool no_intersection = false;
try {
return occt_guard([&]() -> std::vector<Solid> {
const TrackingPolicy policy = resolve_tracking_policy(options.tracking_policy);
if (solids.empty()) throw ValueError("cut_rsolid_list requires at least one Solid input");
if (solids.size() == 1) return {solids.front()};
CutRun run = run_cuts(solids, options, policy, "cut_rsolid_list", no_intersection);
std::vector<Solid> pieces = std::move(run.pieces);
std::optional<TopoDelta> merged = merge_topo_deltas(run.deltas);
const bool tracked = policy != TrackingPolicy::Graph && run.cut_performed && merged;
std::vector<Shape> sources(solids.begin(), solids.end());
for (Solid& piece : pieces) {
inherit_metadata(piece, {&solids.front()});
piece.apply_tag("solid.boolean.cut", false);
if (tracked) {
apply_tracking_tags(piece, *merged, run.entries, TrackingContext{kCutListOp, sources});
}
attach_track_summary(piece, kCutListOp, tracked ? &*merged : nullptr, tracked ? &run.entries : nullptr);
}
FeatureRecord rec(kCutListOp);
record_cut(solids, options, policy, rec);
OpRecord record = std::move(rec).take();
if (Recorder* recorder = current_recorder()) {
std::vector<Shape> ordered;
for (const OpInput& input : record.inputs) ordered.push_back(input.shape);
if (auto refs = recorder->input_refs(ordered)) record.params.set("input_refs", std::move(*refs));
if (tracked) record.delta = *merged;
}
record_operation(std::move(record), std::vector<Shape>(pieces.begin(), pieces.end()));
return pieces;
});
} catch (const std::exception& error) {
raise_boolean_failure(cut_list_spec(), "cut", error, solids, std::nullopt, no_intersection);
}
}
// ---------------------------------------------------------------------------
// intersect
// ---------------------------------------------------------------------------
+3
View File
@@ -130,6 +130,9 @@ void register_booleans(reactive::ExecutorRegistry& registry) {
registry.add("make_cut_rsolid", [](Params p, Inputs in, const ScalarValues&) {
return one(cut_rsolid(rest<Solid>(in, 0, in.size()), {flag(p, "skip_non_intersecting"), text(p, "tracking_policy")}));
});
registry.add("make_cut_rsolid_list", [](Params p, Inputs in, const ScalarValues&) {
return many(cut_rsolid_list(rest<Solid>(in, 0, in.size()), {flag(p, "skip_non_intersecting"), text(p, "tracking_policy")}));
});
registry.add("make_intersect_rsolid", [](Params, Inputs in, const ScalarValues&) {
return one(intersect_rsolid(rest<Solid>(in, 0, in.size())));
});
+8 -4
View File
@@ -18,9 +18,11 @@ namespace scad {
namespace {
TrackedBooleanResult to_boolean_result(std::optional<Solid> solid, tracking::DeltaBuilder&& builder) {
TrackedBooleanResult to_boolean_result(std::optional<Solid> solid, std::vector<Solid> solids,
tracking::DeltaBuilder&& builder) {
tracking::Finished finished = std::move(builder).finish();
return TrackedBooleanResult{std::move(solid), std::move(finished.delta), std::move(finished.delta_entries)};
return TrackedBooleanResult{std::move(solid), std::move(solids), std::move(finished.delta),
std::move(finished.delta_entries)};
}
// Face history of one input of a boolean.
@@ -64,7 +66,9 @@ TrackedBooleanResult track_boolean(kernel::BooleanOp op, const Solid& body, cons
std::optional<Solid> solid;
TopoDS_Solid first;
if (kernel::first_solid(run.shape, first)) solid.emplace(first);
return to_boolean_result(std::move(solid), std::move(delta));
std::vector<Solid> solids;
for (const TopoDS_Solid& piece : kernel::solids_of(run.shape)) solids.emplace_back(piece);
return to_boolean_result(std::move(solid), std::move(solids), std::move(delta));
});
}
@@ -113,7 +117,7 @@ TrackedBooleanResult track_union_history(const std::vector<Solid>& solids, const
seen.Add(edge);
if (seen.Extent() > before) delta.section_edge_ids.push_back(kernel_topo_id(edge));
}
return to_boolean_result(result_solid, std::move(delta));
return to_boolean_result(result_solid, std::vector<Solid>{result_solid}, std::move(delta));
});
}
+35 -1
View File
@@ -52,8 +52,42 @@ def run_port(snippet: str):
return namespace["result"]
def compare(name: str, *parts: str, rel: float = GEOMETRY_REL, abs_: float = 1e-7):
PHASE_CANDIDATES = (0.0, 15.0, 30.0, 45.0, 60.0, 90.0, 120.0, 135.0, 150.0, 165.0, 180.0, 210.0, 240.0, 270.0, 300.0, 330.0)
PHASE_FIELDS = ("thread_phase_degrees", "faces", "edges", "rotations", "cuts", "unions")
def _without(value, keys):
if isinstance(value, dict):
return {k: _without(v, keys) for k, v in value.items() if k not in keys}
if isinstance(value, list):
return [_without(v, keys) for v in value]
return value
def _phases(value):
if isinstance(value, dict):
yield from ([value["thread_phase_degrees"]] if "thread_phase_degrees" in value else [])
for item in value.values():
yield from _phases(item)
elif isinstance(value, list):
for item in value:
yield from _phases(item)
def compare(name: str, *parts: str, rel: float = GEOMETRY_REL, abs_: float = 1e-7, phase_searched: bool = False):
"""Run the snippet on the port and on the reference and require the same JSON.
``phase_searched``: the modeled-thread builders try candidate phase angles and keep the first one whose Boolean
comes out valid. Which candidate that is depends on last-bit floating-point differences of the helix sweep (the
platform, the libm), so the angle and the topology counts it implies are not part of the contract: they are dropped
from the comparison, the angle must still be a real candidate, and the measures (volume, area, bounding box) are
compared at a looser tolerance because a different phase cuts the same thread at a different turn.
"""
snippet = "\n".join(textwrap.dedent(part) for part in parts)
expected = golden("std_" + name, PRELUDE + snippet)
actual = run_port(snippet)
if phase_searched:
assert all(angle in PHASE_CANDIDATES for angle in _phases(actual)), list(_phases(actual))
actual, expected = _without(actual, PHASE_FIELDS), _without(expected, PHASE_FIELDS)
rel = max(rel, 5e-3)
assert close(actual, expected, rel, abs_), _diff(actual, expected)
@@ -0,0 +1,92 @@
"""cut_rsolid_list: a cut that splits the body keeps every piece; cut_rsolid refuses to drop any.
The old SDK returned the first piece of a split silently (a slot through a bar lost half the bar), so there is no golden
to compare with: the expected volumes are worked out here.
"""
from __future__ import annotations
import math
import pytest
import simplecadapi as scad
from simplecadapi.recording.serializer import replay_graph
BAR = (100.0, 20.0, 10.0)
def bar():
return scad.make_box_rsolid(*BAR, bottom_face_center=(0, 0, 0))
def slot(x):
return scad.make_box_rsolid(10, 40, 30, bottom_face_center=(x, 0, -10))
def plate():
return scad.make_box_rsolid(100, 100, 10, bottom_face_center=(0, 0, 0))
def cylinder(radius):
return scad.make_cylinder_rsolid(radius, 30, bottom_face_center=(0, 0, -10))
def volumes(pieces):
return sorted(round(p.get_volume(), 3) for p in pieces)
def test_a_slot_through_a_bar_gives_both_halves():
assert volumes(scad.cut_rsolid_list(bar(), slot(0))) == [9000.0, 9000.0]
def test_several_tools_split_every_piece_they_meet():
pieces = scad.cut_rsolid_list(bar(), [slot(-20), slot(20)])
assert volumes(pieces) == [5000.0, 5000.0, 6000.0]
assert math.isclose(sum(p.get_volume() for p in pieces), 16000.0)
def test_a_tool_cutting_a_piece_made_by_an_earlier_tool():
# the second tool lies in the part the first one cut off
pieces = scad.cut_rsolid_list(bar(), slot(0), slot(30))
assert math.isclose(sum(p.get_volume() for p in pieces), 100 * 20 * 10 - 2 * 10 * 20 * 10)
assert len(pieces) == 3
def test_the_four_corners_left_by_a_big_cylinder_are_all_kept():
pieces = scad.cut_rsolid_list(plate(), cylinder(70))
assert len(pieces) == 4
assert all(math.isclose(p.get_volume(), 5.068, abs_tol=1e-3) for p in pieces)
def test_a_tool_that_encloses_the_body_leaves_nothing():
assert scad.cut_rsolid_list(plate(), cylinder(75)) == []
def test_one_piece_result_and_a_missing_tool():
(single,) = scad.cut_rsolid_list(plate(), cylinder(40))
assert math.isclose(single.get_volume(), 100 * 100 * 10 - math.pi * 40**2 * 10, rel_tol=1e-4)
far = scad.make_box_rsolid(5, 5, 5, bottom_face_center=(0, 100, 0))
assert volumes(scad.cut_rsolid_list(bar(), far)) == [20000.0]
with pytest.raises(scad.SimpleCADError, match="does not intersect"):
scad.cut_rsolid_list(bar(), far, skip_non_intersecting=False)
def test_cut_rsolid_refuses_a_split_instead_of_dropping_pieces():
with pytest.raises(scad.SimpleCADError) as error:
scad.cut_rsolid(bar(), slot(0))
text = str(error.value)
assert "returned 2 solids" in text and "cut_rsolid_list" in text
with pytest.raises(scad.SimpleCADError, match="no valid solid"):
scad.cut_rsolid(plate(), cylinder(75))
def test_the_pieces_carry_the_cut_tags_and_one_graph_node():
with scad.GraphSession() as session:
body = bar()
pieces = scad.cut_rsolid_list(body, [slot(-20), slot(20)])
assert all(p.get_metadata("track")["op"] == "make_cut_rsolid_list" for p in pieces)
nodes = [n for n in session.graph.to_dict()["nodes"] if n["op"] == "make_cut_rsolid_list"]
assert len(nodes) == 1
replayed = [x for r in replay_graph(session.graph) for x in (r if isinstance(r, (list, tuple)) else [r])]
assert volumes(replayed) == volumes(pieces)
@@ -87,7 +87,7 @@ def test_bolt_modeled_thread():
thread_detail="modeled", thread_form="v", thread_pitch=1.25,
thread_depth=0.65, thread_length=18.0, drive_style="cross")
result = {"shape": describe(bolt, detail=False), "meta": meta(bolt, "std.fastener.bolt")}
""")
""", phase_searched=True)
compare("bolt_modeled_full_phase", """
with scad.GraphSession() as session:
bolt = std.fastener.make_bolt_rsolid(diameter=6.0, length=18.0, thread_style="full", thread_detail="modeled",
@@ -96,7 +96,7 @@ def test_bolt_modeled_thread():
result = {"shape": describe(bolt, detail=False), "meta": meta(bolt, "std.fastener.bolt"),
"rotations": ops.count("make_rotate_rshape"), "helices": ops.count("make_helix_rwire") + ops.count("make_helix_redge"),
"sweeps": ops.count("make_sweep_rsolid"), "cuts": ops.count("make_cut_rsolid")}
""")
""", phase_searched=True)
def test_bolt_errors():
@@ -148,7 +148,7 @@ def test_nut_modeled_thread():
thread_pitch=1.25, thread_depth=0.65, knurl_count=18)
result = {"hex": {"shape": describe(nut, detail=False), "meta": meta(nut, "std.fastener.nut")},
"knurled": {"shape": describe(knurled, detail=False), "meta": meta(knurled, "std.fastener.nut")}}
""")
""", phase_searched=True)
compare("nut_phase", """
with scad.GraphSession() as session:
nut = std.fastener.make_nut_rsolid(diameter=6.0, width=10.0, height=5.0, thread_detail="modeled",
@@ -157,7 +157,7 @@ def test_nut_modeled_thread():
result = {"shape": describe(nut, detail=False), "meta": meta(nut, "std.fastener.nut"),
"rotations": ops.count("make_rotate_rshape"), "unions": ops.count("make_union_rsolid"),
"sweeps": ops.count("make_sweep_rsolid")}
""")
""", phase_searched=True)
def test_nut_errors():
+2
View File
@@ -179,6 +179,7 @@ from simplecadapi._cpp import (
boolean_rsolidlist,
chamfer_rsolid,
cut_rsolid,
cut_rsolid_list,
draft_rsolid,
extrude_rsolid,
extrude_taper_rsolid,
@@ -648,6 +649,7 @@ __all__ = [
# Boolean operations
"boolean_rsolidlist",
"cut_rsolid",
"cut_rsolid_list",
"make_2d_cut_rface",
"intersect_rsolid",
"make_2d_intersect_rface",
+4 -3
View File
@@ -144,7 +144,7 @@
"constrain_tangent_rsketch": "Constrain supported curves to be tangent on an explicit branch.\n\n``at_a``/``at_b`` select ``\"start\"`` or ``\"end\"`` for arc and\nB-spline endpoint tangency. Circle-circle tangency accepts\n``mode=\"external\"`` or ``mode=\"internal\"``.",
"constrain_vertical_rsketch": "Constrain a sketch line to be vertical.",
"convert_value": "Convert a finite numeric value between dimensionally compatible units.",
"cut_rsolid": "Compute the boolean difference of solids.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, tools with no meaningful intersection are\n ignored for interactive convenience. Graph replay records this flag and\n should use False for strict diagnostic workflows.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n\nReturns:\n Solid: The cut result solid.\n\nUsage:\n Accepts a base solid followed by one or more tool solids, including nested\n sequences, and returns a single `Solid`.",
"cut_rsolid": "Compute the boolean difference of solids.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, tools with no meaningful intersection are\n ignored for interactive convenience. Graph replay records this flag and\n should use False for strict diagnostic workflows.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n\nReturns:\n Solid: The cut result solid.\n\nRaises:\n SimpleCADError: The cut produced no solid, or split the body into several\n (a slot through a bar). Use ``cut_rsolid_list`` to keep every piece.\n\nUsage:\n Accepts a base solid followed by one or more tool solids, including nested\n sequences, and returns a single `Solid`.",
"diagnose_blend_failure": "Classify a fillet/chamfer failure; never raises.\n\nProbe order (cheapest explanation wins):\n\n1. Tangent adjacency — the two faces meeting at a selected edge are\n already tangent (dihedral ~180°), so the blend surface degenerates to\n zero width regardless of size.\n2. Room — blend size exceeds the distance from the edge to the opposite\n boundary of an adjacent face.\n3. Interaction — per-edge diagnostic rerun (``retry_single``, capped at\n 64 edges) isolates edges that fail alone; when every edge passes\n alone but the joint blend fails, opposite blends on a shared face\n meeting tangentially (2×size >= face room) is the explanation.",
"diagnose_boolean_failure": "Classify a boolean failure from its operands; never raises.\n\nModel: operands within ``tol`` of each other form one connected cluster\n(transitively). More than one cluster means the union is genuinely\nseparated — report the nearest inter-cluster pair. A single cluster that\nstill failed to fuse contains a touch-without-overlap pair — report it as\nnon-manifold contact. Returns None when no pair explains the failure.",
"draft_rsolid": "Draft planar, cylindrical or conical faces by a signed angle in degrees.\n\nThe neutral plane fixes the unchanged section: the selected faces lean\ntoward or away from it. Its origin and normal are in current\ncoordinate-system coordinates. Face selection is checked against the input\nbody and retained as graph inputs for strict replay. The input solid is\npreserved, the output must be one valid solid, and a zero angle records an\nunchanged result. Other surface families are explicitly rejected.\n\nThe operation is recorded as ``make_draft_rsolid``; the body and selected\nfaces are ordered inputs, and the angle, neutral plane and face selection\nnodes are parameters, so model JSON replay is strict.\n\nArgs:\n solid: The body to draft.\n faces_to_draft: Faces of ``solid``, or a QL selector that picks them.\n angle: Draft angle in degrees, strictly between -90 and 90.\n plane_origin: A point of the neutral plane.\n plane_normal: Normal of the neutral plane; must be nonzero.\n\nReturns:\n The drafted solid.\n\nRaises:\n TypeError: ``solid`` is not a Solid.\n ValueError: Empty selection, a selection that is not made of faces of\n ``solid``, an unsupported surface family, a zero plane normal, or\n a nonfinite or out-of-range angle.\n\nExamples:\n import simplecadapi as scad\n from simplecadapi import ql\n body = scad.make_box_rsolid(10, 10, 10)\n right = ql.faces().where(ql.prop(\"geom.normal.x\", \">\", 0.9)).exactly(1)\n drafted = scad.draft_rsolid(body, right, angle=10)",
@@ -333,5 +333,6 @@
"user_tag_binding": "Create a canonical user assertion with explicit frozen policies.",
"validate_placement_ticks": "Validate a persisted tick frame with exact integer arithmetic.",
"value": "Build a value key extractor for ordering and projection in QL.\n\nArgs:\n path: Property or metadata path to resolve.\n default: Fallback value when the path is missing.\n\nReturns:\n Serializable key function for `Query.order_by(...)`.",
"var": "Create a physical or legacy scalar variable.\n\n``tolerance=0.1`` declares a symmetric ``+/-0.1`` tolerance. Use a\n``(lower_deviation, upper_deviation)`` pair for an asymmetric tolerance.\n``tolerance_unit`` defaults to ``unit`` when a nominal unit is declared.\nValues are converted to canonical CAD units only when evaluated, so the\ndeclaration and serialized expression node preserve the user's units.\n\nVariables without ``unit`` retain legacy unitless behavior. A unit-aware\nexpression cannot mix declared-unit variables with legacy variables."
}
"var": "Create a physical or legacy scalar variable.\n\n``tolerance=0.1`` declares a symmetric ``+/-0.1`` tolerance. Use a\n``(lower_deviation, upper_deviation)`` pair for an asymmetric tolerance.\n``tolerance_unit`` defaults to ``unit`` when a nominal unit is declared.\nValues are converted to canonical CAD units only when evaluated, so the\ndeclaration and serialized expression node preserve the user's units.\n\nVariables without ``unit`` retain legacy unitless behavior. A unit-aware\nexpression cannot mix declared-unit variables with legacy variables.",
"cut_rsolid_list": "Compute the boolean difference of solids and keep every piece.\n\nA cut can split the body (a slot through a bar leaves two parts) or consume it\n(a tool that encloses the whole body leaves nothing). ``cut_rsolid`` refuses\nsuch a result because it returns exactly one ``Solid``; this operator returns\nthem all. A tool is cut from every piece it meets, so several tools may split\na body into several parts.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, a tool that meets none of the current\n pieces is ignored; when False it raises.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n\nReturns:\n list[Solid]: Every piece of the cut, in kernel order; empty when the tools\n consume the base.\n\nRaises:\n SimpleCADError: An input is not a valid Solid, or the kernel could not\n compute the cut.\n\nUsage:\n ``pieces = cut_rsolid_list(bar, slot)`` returns both halves of a bar cut by\n a through slot. Use ``cut_rsolid`` when the result must be one solid.\n"
}
+1
View File
@@ -185,6 +185,7 @@
"current_tracking_policy": "simplecadapi.topology.tracking",
"curve_type": "simplecadapi.ql",
"cut_rsolid": "simplecadapi.operators.boolean",
"cut_rsolid_list": "simplecadapi.operators.boolean",
"cut_shapes": "simplecadapi.kernel.ocp_booleans",
"diagnose_blend_failure": "simplecadapi.operators._diagnostics",
"diagnose_boolean_failure": "simplecadapi.operators._diagnostics",
+1
View File
@@ -1,6 +1,7 @@
{
"aggregate": "values",
"cut_rsolid": "solids",
"cut_rsolid_list": "solids",
"intersect_rsolid": "solids",
"union_rsolid": "solids"
}
+2
View File
@@ -24,6 +24,7 @@ from simplecadapi._cpp import (
boolean_rsolidlist,
chamfer_rsolid,
cut_rsolid,
cut_rsolid_list,
diagnose_blend_failure,
diagnose_boolean_failure,
draft_rsolid,
@@ -267,6 +268,7 @@ __all__ = [
"constrain_tangent_rsketch",
"constrain_vertical_rsketch",
"cut_rsolid",
"cut_rsolid_list",
"diagnose_blend_failure",
"diagnose_boolean_failure",
"diagnostics_dir",
+2
View File
@@ -14,6 +14,7 @@ from simplecadapi._cpp import (
# bind_ops_features.cpp
boolean_rsolidlist,
cut_rsolid,
cut_rsolid_list,
diagnose_boolean_failure,
intersect_rsolid,
union_rsolid,
@@ -28,6 +29,7 @@ __all__ = [
"BooleanDiagnosis",
"boolean_rsolidlist",
"cut_rsolid",
"cut_rsolid_list",
"diagnose_boolean_failure",
"intersect_rsolid",
"make_2d_cut_rface",
+24
View File
@@ -445,6 +445,7 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = {
},
"union_rsolid": {"status": "replayable", "op": "make_union_rsolid"},
"cut_rsolid": {"status": "replayable", "op": "make_cut_rsolid"},
"cut_rsolid_list": {"status": "replayable", "op": "make_cut_rsolid_list"},
"intersect_rsolid": {"status": "replayable", "op": "make_intersect_rsolid"},
"make_2d_cut_rface": {"status": "replayable", "op": "make_2d_cut_rface"},
"make_2d_union_rface": {"status": "replayable", "op": "make_2d_union_rface"},
@@ -615,6 +616,7 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = (
"make_draft_rsolid",
"make_mirror_rshape",
"make_cut_rsolid",
"make_cut_rsolid_list",
"make_union_rsolid",
"make_intersect_rsolid",
"make_2d_cut_rface",
@@ -3756,6 +3758,28 @@ def _execute_graph(
_store_outputs(node, result)
continue
if op_name == "make_cut_rsolid_list":
ctx.require_params(
node.node_id, op_name, params, ("tool_count", "input_refs")
)
inputs = _ordered_input_shapes(ctx, graph, outputs, node, params)
if len(inputs) < 2:
if ctx.strict:
ctx.fail(
f"Graph node '{node.node_id}' ({op_name}) requires at least two inputs"
)
continue
result = ops.cut_rsolid_list(
cast(Solid, inputs[0]),
[cast(Solid, tool) for tool in inputs[1:]],
skip_non_intersecting=bool(
_param(ctx, node.node_id, op_name, params, "skip_non_intersecting", False)
),
tracking_policy=str(params.get("tracking_policy", "full")),
)
_store_outputs(node, result)
continue
if op_name == "make_union_rsolid":
if ctx.strict:
ctx.require_params(
+2 -2
View File
@@ -12,7 +12,7 @@ from simplecadapi import ql as Q
class TestOriginalBooleanApiIntegration(unittest.TestCase):
def test_cut_rsolid_auto_applies_semantic_tags(self):
body = scad.make_box_rsolid(10, 10, 10)
tool = scad.make_cylinder_rsolid(2.0, 15.0, bottom_face_center=(3, 3, -2.5))
tool = scad.make_cylinder_rsolid(1.5, 15.0, bottom_face_center=(3, 3, -2.5))
result = scad.cut_rsolid(body, tool)
self.assertIsInstance(result, scad.Solid)
@@ -151,7 +151,7 @@ class TestOriginalApiGraphRecording(unittest.TestCase):
def test_original_apis_record_graph_automatically(self):
with GraphSession() as session:
body = scad.make_box_rsolid(10, 10, 10)
tool = scad.make_cylinder_rsolid(2.0, 15.0, bottom_face_center=(3, 3, -2.5))
tool = scad.make_cylinder_rsolid(1.5, 15.0, bottom_face_center=(3, 3, -2.5))
result = scad.cut_rsolid(body, tool)
graph = session.graph
+2 -1
View File
@@ -101,7 +101,7 @@ class TestExportImport(unittest.TestCase):
def test_export_graph_json_includes_display_payload(self):
with scad.GraphSession() as session:
body = scad.make_box_rsolid(10, 10, 10)
tool = scad.make_cylinder_rsolid(2.0, 15.0, bottom_face_center=(3, 3, -2.5))
tool = scad.make_cylinder_rsolid(1.5, 15.0, bottom_face_center=(3, 3, -2.5))
scad.cut_rsolid(body, tool)
payload = json.loads(export_graph_json(session.graph))
@@ -365,6 +365,7 @@ class TestCoverageMatrix(unittest.TestCase):
"make_extrude_until_rsolid",
"make_draft_rsolid",
"make_boolean_rsolidlist",
"make_cut_rsolid_list",
"make_mirror_rshape",
"make_cut_rsolid",
"make_union_rsolid",