Files
make-cad/src/cpp/include/scad/ops/features/diagnostics.hpp
T
Ni Jingzhe 35a4e5efa9 fix(kernel): cut and intersect unify what they leave split, and a blend never returns an invalid solid (#88)
DECISION: three changes, in this order of importance, each independent of the others.
(1) a fillet or chamfer whose result OCCT calls invalid is an error; (2) cut_rsolid, cut_rsolid_list and
intersect_rsolid unify the same-domain faces and edges of their result by default, with `clean=False` to keep the raw
result, as union already does; (3) the diagnosis names split faces instead of blaming the radius. No compatibility
shim for records made before `clean` existed: replay requires the parameter, like every other recorded one.

PROBLEM (reproduced on the issue's two cases, current dev build on Windows, OCCT 7.9.3)
A cut through the side of a box with a cylinder splits the cylinder wall along the cylinder's parametric seam into two
faces, and the top edge of the notch into a long and a short arc. union unified (ShapeUpgrade_UnifySameDomain) and cut
did not. OCCT then fillets that top edge wrongly:
- case A: BRepCheck-invalid solid, volume 28305.59 (should be 29604.46), no error at all: `fillet_rsolid` checked only
  IsDone and volume > 0;
- case B: refusal, and the diagnosis said "the radius exceeds the 2.5 mm of face room" - the half of the wall the seam cut
  off - so the advised radius was not the limit.
Same geometry, other libraries: CadQuery and build123d clean after a boolean by default and give 29604.46 / 29811.31.

(1) THE EXIT CHECK IS THE MOST IMPORTANT
`assert_blend_valid`, next to the volume check in `finish_blend` (fillet and chamfer): BRepCheck_Analyzer on the result;
invalid while the input was valid is a BlendValidityViolation, which leads the error message ("the kernel returned broken
geometry"), like the existing volume violation. Not raised when the input was already invalid (an imported solid is not
the blend's fault). It turns "wrong volume found three operations later" into an error at the operation that caused it,
whatever else is or is not done about cleaning.

(2) CLEAN BY DEFAULT, WITH THE HISTORY FOLLOWING
SDK booleans go through `tracked_cut` / `tracked_intersect`, which ask the kernel's history what became of every face
(that is how tags and lineage survive), so cleaning only the shape would break tracking. `BooleanOptions::clean` makes
`run_boolean` unify the result, merge the unifier's history into the boolean's, and follow the section edges through it;
the section-edge following was lifted out of `fuse_shapes_with_history` into one helper both use (fuse behaves as
before). The unified shape replaces the result only when it has the same number of solids and is valid whenever the raw
result was; otherwise the raw result stands. FreeCAD and build123d fall back the same way, and replicad's unconditional
SimplifyResult has been seen to invalidate results (BarbourSmith/Abundance#1934), so the fallback is not decoration.
`clean` is a keyword of the three functions (default True), recorded as params.clean like union's. C++ `cut_shapes`,
`common_shapes` and `tracked_*` keep `clean=false` as their default so other callers (diagnosis, set booleans, std
parts) are unchanged.
Not done on purpose: OCCT's own SimplifyResult(true, true) that the issue suggests: the explicit unifier already gives
the same merge and history, with a fallback we control.

REPLAY: NO LEGACY BRANCH (owner's rule: do not keep old formats alive)
`flag(p, "clean")` and `ctx.require_params(..., "clean")` fail on a graph recorded before this change, as they do for
any missing parameter. Such a graph has to be recorded again.

(3) THE DIAGNOSIS
`classify_split_faces`, before the face-room probe: unify the solid, carry the selected edges over with the unifier's
history, blend again with the same size; if that works the split faces are the cause, and the message says so and how to
fix it (clean=True, or union_rsolid(clean=True)). The room probe stays for a radius that really is too large (test:
radius 50 on the cleaned case is still reported as too large).

EVIDENCE
- Both cases now give valid fillets with volumes 29604.46 and 29811.31, equal to CadQuery's.
- clean=False: A raises "not a valid solid" (it was returned), B raises "faces ... split on a surface ... clean=True".
- test/test_boolean_clean.py (10 tests): face counts 8 against 9, volume unchanged by cleaning, cut_list and intersect,
  both cases, both clean=False diagnoses, a really-too-large radius, `clean` recorded, replay giving 8 / 9 faces.
- A random sample, 120 cases of the issue's recipe (box minus 2-4 vertical boxes/cylinders on a grid, top edges, r 1-3),
  both modes: 240 results, none invalid and returned (clean=True 84 valid / 36 errors, clean=False 83 / 37).
- Full Python suite on this machine: 2674 passed; 22 failed and 9 errors, none touching booleans (Windows paths,
  encodings, file locks, addon and shell integration, missing OCP, a math-library last digit in test_tolerance).

NOT DONE / NOT KNOWN
- The C++ unit tests (ctest) were not built or run here (SCAD_BUILD_TESTS is off for the wheel build). CutOptions::clean
  defaults to true, so a C++ test that compares a cut's topology may need its expectation updated: CI will say.
- The issue's 16000-case run was not repeated, only the small sample above; it shows that no invalid result is
  returned, not the 0.4% rate of the issue (there is no old binary here to compare with).
- A stored artifact or fingerprint of a model with a cut that left split faces changes: the faces are fewer. That is the
  point of the change; rebuild such models.
- Unifying can still make a later blend worse on rare inputs (the issue saw 6 segfaults after unify in other libraries
  too); here the unify is inside the boolean, so a crash would show in the boolean.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 03:31:21 +08:00

92 lines
4.5 KiB
C++

// Why a feature operator failed (operators/_diagnostics.py): the geometric facts behind a
// fillet, chamfer, boolean or loft failure, found by re-measuring the operands once the
// operation has failed.
//
// Every entry is best effort: a probe that cannot decide says nothing, and a diagnosis
// never replaces the error it explains. A diagnosis names what to draw (`evidence_edges`,
// `evidence_caption`): the operator that raises asks `diagnostic_image` for the picture.
#pragma once
#include <functional>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include "scad/core/error.hpp"
#include "scad/topo/shape.hpp"
namespace scad {
// A classified fillet / chamfer failure.
struct BlendDiagnosis {
// "tangent_adjacent_faces" | "sliver_edges_in_selection" | "size_exceeds_face" |
// "partial_smooth_chain_on_periodic_face" | "blends_tangency_critical" | "vertex_blend_conflict" |
// "faces_split_on_one_surface"
std::string failure_kind;
std::string what_happened;
std::vector<std::string> possible_causes;
std::vector<ErrorMeasurement> measurements;
std::vector<std::string> repair;
std::vector<Edge> evidence_edges; // the edges the picture marks in orange (the solid itself is drawn)
std::string evidence_caption;
};
// Does the blend succeed on this one edge alone? The per-edge diagnostic rerun.
using BlendRetry = std::function<bool(const Edge&)>;
// Classify why blending `edges` of `solid` by `size_value` failed. Probe order, cheapest
// explanation first: sliver edges, tangent faces, size against the room on adjacent faces,
// a partially selected smooth chain, then (via `retry_single`, up to 64 edges) interaction
// between blends and corner conflicts. `operation_kind` is "fillet" or "chamfer".
std::optional<BlendDiagnosis> diagnose_blend_failure(const Solid& solid, const std::vector<Edge>& edges,
double size_value, std::string_view operation_kind,
const BlendRetry& retry_single = {});
// The kernel handed back geometry no blend can produce.
class BlendVolumeViolation : public ValueError {
public:
using ValueError::ValueError;
};
// Exit check of a blend: an all-convex blend may only remove material. Throws
// BlendVolumeViolation, naming the measured volumes, for an empty result or a convex blend
// that grew the solid. Volumes that cannot be measured pass.
void assert_blend_volume_monotonic(const Solid& source, const Solid& result, std::string_view operation_kind,
std::optional<double> size_value, const std::vector<Edge>& edges);
// Exit check of a blend, next to the volume check: the result must be a valid solid (BRepCheck_Analyzer) whenever
// the input was. OCCT reports `IsDone` for fillets it got wrong (a face split along a seam, issue #88) and hands back
// an invalid solid with a wrong volume, which only a later boolean or an export finds. Throws BlendValidityViolation.
class BlendValidityViolation : public BlendVolumeViolation {
public:
using BlendVolumeViolation::BlendVolumeViolation;
};
void assert_blend_valid(const Solid& source, const Solid& result, std::string_view operation_kind,
std::optional<double> size_value, const std::vector<Edge>& edges);
// A classified boolean failure.
struct BooleanDiagnosis {
std::string failure_kind; // "disjoint" | "non_manifold_contact"
std::string what_happened;
std::vector<std::string> possible_causes;
std::vector<ErrorMeasurement> measurements;
std::vector<std::string> repair;
std::vector<Solid> evidence_shapes; // the two operands the diagnosis is about, in order
std::string evidence_caption;
};
// Why `operands` do not combine: separated (the nearest pair across clusters of operands
// within `effective_tol` of each other) or touching without volume. `operation_kind` is
// "union", "cut" or "intersect".
std::optional<BooleanDiagnosis> diagnose_boolean_failure(const std::vector<Solid>& operands,
std::optional<double> effective_tol,
std::string_view operation_kind = "union");
// Re-read the loft `sections` after the kernel failed and, when they explain it (coincident
// stations, differing edge counts, open wires, out-of-order stations), throw the Error that
// says so. Returns silently otherwise.
void raise_loft_failure_if_diagnosed(const std::vector<Shape>& sections, std::string_view operation);
} // namespace scad