diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fbb22d3..9b70e219 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,35 @@ All notable changes to SimpleCADAPI are documented here. Per-version user-facing notes live in [`docs/updates/`](docs/updates/) (English and 中文). +## Unreleased + +### Added +- `fillet_rsolid(..., strategy_auto_y_patch=True)`: the Y transition. Where a concave and a convex selected edge meet + tangentially or nearly so (a post flush with a plate side, a wall a few degrees off it), two rolling-ball fillets cannot + meet — one ball lies outside the material, the other inside — and the standard kernel fails or returns a + self-intersecting solid. With the flag both bands stop where they touch the shared face and two G1 ribbons, tangent to + each other and to both supports, close the junction. Everything else is the standard algorithm; without such a junction, + or if the transition fails its validity, self-interference and continuity checks, the standard algorithm runs alone. + Without the flag the kernel falls back at such a junction, when its standard result fails, is invalid or + self-intersects, to the pinch corner (both bands taper along one shared curve to a point at the junction vertex, + like Plasticity with Y-Blend off: the convex band stays G1 and the concave one keeps a crease of about 17 degrees + where the taper starts, shared between both sides where that layout does not fit), then to the Y + transition. A valid standard result is kept, and fillets without such a junction are unchanged. + + ![A post flush with both plate sides, r = 5, shaded and zebra](img/y-patch/flush-post-overview.png) +- `make_surface_patch_rface(..., strategy_graph_patch=True)`: fill one ordered loop of edges, each an edge of its support + face, with C0/G1/G2 per edge, with the kernel's degree-8 graph patch instead of plate filling; the boundary is met + exactly where a degree-8 graph can, and on curved supports (a window in a cylinder, a sphere, a B-spline sheet) the + patch continues the support's own surface within 1e-3 mm (a 40 x 24 window in an R30 tube: 2e-4 mm off the + cylinder, the plate filling 0.39 mm). No points, holes or settings with this strategy. +- `simplecadapi._cpp._kernel_capabilities()` reports which kernel strategies the linked OpenCASCADE carries; requesting one + the kernel lacks raises `ValueError` naming the patch set. +- `tools/render/zebra.py`: zebra (reflection-line) renderings of BREP files, side by side, to judge surface continuity. + +### Changed +- OpenCASCADE patch set `fillet-robustness-4`: patch `0004` adds `BRepFilletAPI_MakeFillet::SetYPatch` and the + `BRepFilletAPI_YPatch` overlay; the kernel's own checks (48 cases) live in `src/cpp/patches/occt/tests`. + ## 2.3.0.post1 — 2026-11-17 ### Changed diff --git a/design-docs/y-patch-and-graph-patch.md b/design-docs/y-patch-and-graph-patch.md new file mode 100644 index 00000000..41fa77f2 --- /dev/null +++ b/design-docs/y-patch-and-graph-patch.md @@ -0,0 +1,154 @@ +# Y-patch fillets and graph patches as kernel strategies + +Decision record for branch `feat/y-patch-graph-patch` (2026-11-23). Kernel patch set `fillet-robustness-4`; development +prefix `C:/OCCT-modified/static-ypatch` (MinGW 15.2, static), built from this checkout with +`src/cpp/tools/build_occt.py`. The earlier prefix `C:/OCCT-modified/static` is left untouched as the control. + +## What started it + +The owner's request (paraphrased): the Y-shaped fillet is a general situation, not one sample — it covers the whole family of +tangent or nearly tangent junctions of one convex and one concave fillet. Detect that geometric situation and run a specific +path for it, as a kernel capability with a proper strategy branch, not as judgement in the Python layer (slow) nor in the +SDK's C++ business layer (couples the SDK to one kernel). Expose it on `fillet_rsolid` as an explicit named boolean +(`strategy_auto_y_patch`). Do the same for the graph patch: a new kernel capability with a good SDK interface. Judge +continuity with zebra renderings and keep the pictures for the changelog. + +## What was found (checked by running) + +| Finding | Evidence | +| --- | --- | +| `BRepFilletAPI_TangentY` (PR #98) cannot serve a real part | `TryBuild` accepts only the canonical plate/post at the origin (plate `3R x 2R x h`, post `2h`) after a boolean comparison with it, then rebuilds the whole solid from hard-coded faces | +| Stock OCCT does not chain the two edges | `BRepFilletAPI_MakeFillet` makes two contours (arc, line); each alone gives an invalid solid with self-interference | +| The patched kernel (0001–0003) | concave arc alone: valid; convex line alone: invalid (2 interferences); both: `IsDone() == false` | +| The standard result depends on the order of `Add` | the same edges added in another order changed "not done" into "done" on some cases; the test harness adds in pick order | +| Two rolling-ball bands cannot meet at such a vertex | the concave ball centre lies outside the material and the convex one inside; both bands claim the same wedge of the common face | + +## Decisions + +**D1. The strategy lives in the kernel, behind the standard entry point.** `BRepFilletAPI_MakeFillet::SetYPatch(true)` +(patch `0004`) is the only switch; `Build()` runs the Y path when there is a junction and the transition passes its gates, +otherwise the standard algorithm, unchanged. `Generated` / `Modified` / `IsDeleted` answer from the Y path's history, so the +SDK's tracking and tags (`fillet.patch` on bands and ribbons) need no special case. `NbYPatches()` and `YPatchJunction(i)` +report what was done (vertex, P*, measured seam and band angles). Off by default: a result of the standard algorithm is +bit-identical to before. Rejected: dispatching in Python or in `src/cpp/src/ops` (the owner's constraint: speed and kernel +migration); keeping `TangentY` (canonical sample only). + +**D2. Detection is OCCT's own convexity, at a vertex.** A junction is a vertex V with a selected concave edge `Ein = T ∩ A` +and a selected convex edge `Eout = T ∩ B` (`ChFi3d::DefineConnectType`), sharing the face T, where A and B meet along an +unselected edge and their normals at V differ by at most 20° (near tangency included). Constant radius per contour; the two +radii may differ. + +**D3. Construction: the standard algorithm does everything it can; the kernel adds only the junction.** +1. P*: solve the two rolling balls (Newton on both contacts and the normal plane of the rail), find the first crossing of + their contact curves on T, refine (λin, λout). On the reference sample P* equals the analytic `x = 2√(Rr)` to 1e-5 mm. +2. Cut V's wedge out of T, A and B (`BRepAlgoAPI_Splitter` with edges on the supports: the end sections' traces, and the + ribbons' boundaries), leaving an open shell whose free boundary holds each band's end section at a vertex. +3. Fillet the open shell with the standard algorithm: both bands end at their sections through P*; their far ends, and + every other selected edge, are the standard algorithm's. +4. Two ribbons, each tangent to its own support (contact curve, then back along the support to V), to its band at the end + section, and to the other ribbon along a seam on T from V to P*. Clamped cubic Hermite tensor product on cosine-spaced + nodes (the construction `TangentY` validated); sections are cubic Bézier curves blended into the exact circular section + near the band; both ribbons share the seam's exact end derivatives so that they interpolate the same seam curve. +5. Sew, make the solid; gates: `BRepCheck_Analyzer`, `BOPAlgo_CheckerSI` level 5, every free edge closed. Any failure: + the Y path returns false and the standard algorithm runs. + +**D4. Explicit named booleans in the SDK.** `fillet_rsolid(..., strategy_auto_y_patch=False)` and +`make_surface_patch_rface(..., strategy_graph_patch=False)`; recorded in the operation graph only when true (records of the +standard path are unchanged), replayed by the serializer and the C++ executor. The SDK compiles against any OCCT: the +strategies are found with `__has_include`, a kernel without them raises `ValueError` naming the patch set, and +`simplecadapi._cpp._kernel_capabilities()` says which strategies the linked kernel has. + +**D5. The graph patch is a fill strategy, not a new operator.** It answers the same question as +`make_surface_patch_rface` (fill a constrained boundary loop) with a different kernel method; the SDK's `SurfaceFitter` +interface is where fill methods are chosen (`FillingProblem::graph_patch`). Preconditions are checked before the kernel +call: 3–64 boundaries, a support on each, each edge an edge of its support, no points, holes or settings. + +## Not done + +**D6. Periodic supports are re-seated first.** `make_cylinder_rsolid` puts the cylinder's parametric seam at +X, on the +post's root: the standard algorithm, starting a band at the open shell's free boundary and crossing that seam vertex, +built the band twice (coincident tori, self-intersecting wires). Scanning the seam angle in 45° steps showed the failure +exactly when the seam touches a chain the standard algorithm finishes. Before the pipeline, a periodic support (cylinder, +cone, sphere, torus, revolution) whose seam has a vertex on a selected edge is rebuilt on the same surface with its +parametric origin turned into the largest gap between the selected edges' pcurves (point set unchanged); the replacement +is part of the history. The old seam's vertex is then merged away (edges only, `ShapeUpgrade_UnifySameDomain`), so the +root is one edge again: with the vertex left in place, small radii (1, 2.5) still failed. Rejected: splitting the face without moving the origin (still fails); a text round trip of the +open shell (made a marginal case pass, but by perturbing digits). + +**D7. History is checked strictly through the public entry point.** The family's check calls +`BRepFilletAPI_MakeFillet` with `SetYPatch` and requires: no input face reported deleted (every one is trimmed, not +consumed), every image in the result, each junction edge generating at least its band and its ribbon, every result face +traced to an input face or edge. The lenient first check ("kept, modified or deleted") had hidden four defects (sewing +history queried for whole shapes instead of sub-shapes, chain-propagated edges without generated faces, a lossy +`BRepTools_History::Merge`, and a two-pass ordering that only the `MakeFillet` path exposed). + +## Case family (`src/cpp/patches/occt/tests`, `cases.exe`; 2026-11-23, static MinGW prefix) + +Every successful case: valid (`BRepCheck_Analyzer`), no self-interference (`BOPAlgo_CheckerSI` level 5), strict history +through `MakeFillet + SetYPatch`. Angles: largest normal angle across the ribbon seam / between a ribbon and its band or +support. "Standard" is the patched kernel without the strategy, edges added in pick order. + +| Cases | Standard | Y patch | Seam ° | Band ° | +| --- | --- | --- | --- | --- | +| post flush with the plate side, r = 1, 2.5, 5, 8, 12; one or both sides; arbitrary placement | not done (r = 12: valid) | ok, P* = 2√(Rr) to 1e-4 mm | 5e-4 – 4e-3 | 3e-3 – 1e-2 | +| cylinder seam at 0° … 315° (8 cases); seam on the root (the SDK's default) at r = 1, 2.5, 5, 8, 12, one or both sides, also on the SDK's own exported solid | mostly valid; seam at 90°: invalid, 2 interferences; on the root: not done | ok | 2.3e-3 | 6.9e-3 | +| unequal radii, concave 3 / convex 7 and 7 / 3 | valid | ok | 0.059 | 0.010 | +| plate side turned 2°, 5°, 10° outward; 2°, 5° inward | valid | ok | 2e-3 | 6e-3 | +| planar wall 5°, 10°, 15° off the plate side | 5°: not done; 10°, 15°: valid | ok | < 1e-9 | 2.2e-3 | +| wall 5° with a junction longer than the edge | not done | refused, as required | – | – | +| curved plate side (R 140 arc tangent to the post) | not done | ok | 3.9e-3 | 5.7e-3 | +| inclined common face (slope 0.15) | not done | ok | 3.7e-3 | 8.6e-3 | + +Times 175–560 ms per solid (one or two junctions), including both gates. + +Where the standard algorithm already returns a valid solid, the strategy replaces its corner by the Y transition; those +standard shapes were not compared visually. Pictures (`tools/render/zebra.py`): `img/y-patch/`. + +![Y transition at a flush post, shaded and zebra](../img/y-patch/flush-post-junction.png) + +## Not done + +- Variable-radius contours never take the Y path. +- The seam lies on T; Plasticity's seam dips slightly below T in the middle. Shape choice, not a defect. +- Near tangency (A and B meeting at a sharp edge of a few degrees) the ribbons inherit that kink at the junction vertex + itself (visible in the 10° wedge zebra picture); G1 holds along the seam, the bands and the supports. +- Unequal radii keep G1 to 0.06°, ten times the equal-radius figure; the seam normal field is a blend chosen for equal + radii. +- Only MinGW static builds were run. CI builds the kernel from this patch set on Linux; MSVC was not compiled here. +- The graph patch is exposed with its research acceptance (C0/G1/G2 loops, planar-representable); the SDK tests cover a + wall loop (C0) and a hole in a plane (G1, G2). + +## Addendum (2026-11-23, evening) + +**D8. A plain fillet falls back to the Y transition.** The owner asked that the tangent post/wall case work without the +flag. `MakeFillet::Build` runs the standard algorithm; at a detected junction, a standard result that is not done, +invalid or self-intersecting is replaced by the Y transition (`YPatchFallback()`). A valid standard result is kept: at a +wall 10° off the plate side the standard algorithm merges both bands into one tapering band whose zebra stripes are +smooth, while the Y transition is G1 only. The non-Y "pinch" corner (Plasticity with Y-Blend off) was built as research +code, off: valid on near-tangent cases, self-intersecting on exact tangency. + +**D9. The graph patch continues curved supports.** A tube window was refused because the exact boundary solve demanded +1e-5 that a degree-8 graph cannot meet on a cylinder. The patch now follows the supports' surfaces over the hole, fits +boundary and support together when the exact solve fails, and accepts on the built face (gap ≤ 1e-3 mm, angle ≤ 1e-3 rad, +G2 cross-curvature within 5 %). Tube window G1: 2.3e-4 mm from the cylinder (plate filling: 0.39 mm). + +Comparison report with code pairs and pictures: `out/report/REPORT.pdf` (local). + +**D10. The pinch corner is the default fallback (2026-11-24).** Owner: a qualified engine must make the non-Y corner +(Plasticity's Y-Blend off: both bands taper to one point, 10 faces) work, exact tangency included. The first attempt +folded near V because it fitted sampled positions with the ribbons' tensor Hermite fit, while the section radius +collapses like x²/4R. Each pinch band is now an exact variable-radius rolling-ball surface: exact circular sections +(rational quadratic, weight cos θ/2), only 1D data interpolated along the rail, a degenerated edge at V; the shared +curve on T is solved from radius laws h, g ~ s² whose sum fills the cusp width. All 47 non-refused cases succeed +as pinch (valid, SI(5) = 0, strict history); the plain `MakeFillet` rescues all 21 cases whose standard result fails, +none needing the Y. Geometric limit: at P*'s section a pinch band, tangent to T along the shared curve with circular +sections, cannot be G1 to both constant-radius bands, whose T-contacts cross at P* (≈35° at r = 5): the crease can only +be distributed. Default `pinchDir = 1` balances it (7.5° / 8.0° at flush r5); `0` makes the convex side G1 (17.3° on the +concave side), which Plasticity's face layout suggests it does. Against Plasticity Y-off (exact sample points to ours): +0.078 / 0.262 mm RMS / max at r5, about a third of the distance to its Y-on result. + +**D11. The pinch crease goes to the concave side, as in Plasticity (owner, 2026-11-24).** The pinch tries the law that +keeps the convex band G1 at P*'s section first (concave crease ≈ 17° at flush r5); where the cusp is too narrow for it +(r = 1, the curved side) or it would leave a crease above 30° (the inclined top measured 90°), the balanced law. Case +family: failures 0; 33 junctions convex-G1, 10 balanced, largest crease 23.6°; every case whose standard result fails +takes the pinch. diff --git a/docs/skill/references/docs/api/fillet_rsolid.md b/docs/skill/references/docs/api/fillet_rsolid.md index b2006e78..e064adfc 100644 --- a/docs/skill/references/docs/api/fillet_rsolid.md +++ b/docs/skill/references/docs/api/fillet_rsolid.md @@ -3,7 +3,7 @@ ## API Definition ```python -def fillet_rsolid(solid, edges, radius, *, result_tag=None, generated_faces_tag=None) +def fillet_rsolid(solid, edges, radius, *, result_tag=None, generated_faces_tag=None, strategy_auto_y_patch=False) ``` *Source: operators/features.py* @@ -17,3 +17,5 @@ def fillet_rsolid(solid, edges, radius, *, result_tag=None, generated_faces_tag= Apply fillets, with optional tagging of kernel-proven patch faces. ``solid`` may also be the list of pieces a cut that split a body returns: each piece gets the picked edges that lie on it, a piece with none is kept as it is, and the result is the list of pieces in the same order. A selector is resolved on every piece and its cardinality (``exactly``/``at_least``/``at_most``) is checked on the edges of all of them. + +Where a concave and a convex selected edge meet tangentially or nearly so (a post flush with a plate side, a wall a few degrees off it), two rolling-ball bands cannot meet: one ball lies outside the material, the other inside. By default the kernel runs its standard algorithm first and, only at such a junction and only when the standard result fails or is invalid or self-intersecting, closes the junction with the pinch corner: both bands taper along one shared curve on the common face to a single point at the junction vertex (each band an exact variable-radius rolling-ball surface, G1 to its supports and along the shared curve; at the section where the taper starts the convex band continues G1, as in Plasticity, and the concave band meets its constant-radius band with a crease, about 17 degrees at r = 5 on a post flush with a plate side; where that layout does not fit or would crease more than 30 degrees, the crease is shared between both sides). If the pinch fails its checks, the Y transition is tried: both bands stop where they touch the shared face and two G1 ribbons join them. A valid standard result is kept. ``strategy_auto_y_patch=True`` takes the Y transition first wherever there is such a junction. Every other edge, and both bands away from the junction, use the standard algorithm; the ribbons are tagged like the bands (``fillet.patch``). Needs a kernel built with the SDK's OCCT patch set (``fillet-robustness-4``); otherwise the flag raises ``ValueError``. diff --git a/docs/skill/references/docs/api/make_surface_patch_rface.md b/docs/skill/references/docs/api/make_surface_patch_rface.md index 4e09a2a2..02e5cc44 100644 --- a/docs/skill/references/docs/api/make_surface_patch_rface.md +++ b/docs/skill/references/docs/api/make_surface_patch_rface.md @@ -3,7 +3,7 @@ ## API Definition ```python -def make_surface_patch_rface(boundaries, *, points=[], settings=None, holes=[], tag_prefix=None) +def make_surface_patch_rface(boundaries, *, points=[], settings=None, holes=[], tag_prefix=None, strategy_graph_patch=False) ``` *Source: operators/geometry.py* @@ -21,3 +21,5 @@ with this operation do not keep identical shared boundary curves. When several patches must share exact boundary edges and sew into one closed shell, build each patch with ``make_gordon_surface_rface`` from a shared profile/guide edge network instead. + +``strategy_graph_patch=True`` fills with the kernel's graph patch instead: ``boundaries`` must be one ordered closed loop of 3 to 64 edges, each an edge of its ``support`` face, with continuity C0, G1 or G2 per edge; ``points``, ``holes`` and ``settings`` are not accepted. The patch is a degree-8 variational surface trimmed by the projected boundary. It meets its supports exactly where a degree-8 graph can (planar supports); on curved supports (cylinder, sphere, B-spline) it continues the supports' own surfaces over the hole and is accepted within 1e-3 mm of the support edges, 1e-3 rad of their normals (G1) and 5% of their curvature (G2), its edge tolerances covering that gap, so the face can be sewn to its supports. Loops that cannot be represented over one plane (seen along the fitted normal) are refused with ``ValueError``. Needs a kernel built with the SDK's OCCT patch set (``fillet-robustness-4``). diff --git a/img/y-patch/flush-post-junction.png b/img/y-patch/flush-post-junction.png new file mode 100644 index 00000000..7431df16 Binary files /dev/null and b/img/y-patch/flush-post-junction.png differ diff --git a/img/y-patch/flush-post-overview.png b/img/y-patch/flush-post-overview.png new file mode 100644 index 00000000..fe520972 Binary files /dev/null and b/img/y-patch/flush-post-overview.png differ diff --git a/img/y-patch/unequal-radii.png b/img/y-patch/unequal-radii.png new file mode 100644 index 00000000..eb10e359 Binary files /dev/null and b/img/y-patch/unequal-radii.png differ diff --git a/img/y-patch/wedge-10deg.png b/img/y-patch/wedge-10deg.png new file mode 100644 index 00000000..89b6f9d0 Binary files /dev/null and b/img/y-patch/wedge-10deg.png differ diff --git a/src/cpp/bindings/python/bind_ops_features.cpp b/src/cpp/bindings/python/bind_ops_features.cpp index 2a502ba3..cdfa5114 100644 --- a/src/cpp/bindings/python/bind_ops_features.cpp +++ b/src/cpp/bindings/python/bind_ops_features.cpp @@ -13,6 +13,7 @@ #include #include +#include "scad/surface/fitter.hpp" #include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/ops/features/features.hpp" @@ -281,22 +282,34 @@ void bind_blends(py::module_& m) { m.def( "fillet_rsolid", [](const AnyOf& solid, const EdgesOrQuery& edges, const Length& radius, - OptionalString result_tag, OptionalString generated_faces_tag) -> AnyOf { + OptionalString result_tag, OptionalString generated_faces_tag, + bool strategy_auto_y_patch) -> AnyOf { const BlendTags tags{std::move(result_tag), std::move(generated_faces_tag)}; + const FilletOptions options{strategy_auto_y_patch}; if (!py::isinstance(solid.value)) { return { blend_pieces(solid.value, edges, "fillet_rsolid", [&](const Solid& piece, const EdgeSelection& picked) { - return fillet_rsolid(piece, picked, radius, tags); + return fillet_rsolid(piece, picked, radius, tags, options); })}; } const Solid body = solid.value.cast(); const EdgeSelection selection = selection_from(edges); - return { - py::cast(unlocked(selection.is_selector(), [&] { return fillet_rsolid(body, selection, radius, tags); }))}; + return {py::cast( + unlocked(selection.is_selector(), [&] { return fillet_rsolid(body, selection, radius, tags, options); }))}; }, py::arg("solid"), py::arg("edges"), py::arg("radius"), py::kw_only(), py::arg("result_tag") = py::none(), - py::arg("generated_faces_tag") = py::none(), + py::arg("generated_faces_tag") = py::none(), py::arg("strategy_auto_y_patch") = false, "Apply fillets, with optional tagging of kernel-proven patch faces."); + m.def( + "_kernel_capabilities", + [] { + py::dict caps; + caps["y_patch"] = kernel_has_y_patch(); + caps["graph_patch"] = surface::kernel_has_graph_patch(); + return caps; + }, + "Kernel strategies the linked OpenCASCADE carries: y_patch (fillet_rsolid strategy_auto_y_patch), " + "graph_patch (make_surface_patch_rface strategy_graph_patch)."); m.def( "chamfer_rsolid", diff --git a/src/cpp/bindings/python/bind_surface.cpp b/src/cpp/bindings/python/bind_surface.cpp index f2fd824d..3ec1100e 100644 --- a/src/cpp/bindings/python/bind_surface.cpp +++ b/src/cpp/bindings/python/bind_surface.cpp @@ -256,12 +256,16 @@ void bind_surface(py::module_& m) { "make_surface_patch_rface", [](const std::vector& boundaries, const std::vector& points, const std::optional& settings, const std::vector& holes, - const TagPrefix& tag_prefix) { - return make_surface_patch_rface( - boundaries, {.points = points_of(points), .settings = settings, .holes = holes, .tag_prefix = tag_prefix}); + const TagPrefix& tag_prefix, bool strategy_graph_patch) { + return make_surface_patch_rface(boundaries, {.points = points_of(points), + .settings = settings, + .holes = holes, + .tag_prefix = tag_prefix, + .strategy_graph_patch = strategy_graph_patch}); }, py::arg("boundaries"), py::kw_only(), py::arg("points") = std::vector{}, py::arg("settings") = py::none(), py::arg("holes") = std::vector{}, py::arg("tag_prefix") = py::none(), + py::arg("strategy_graph_patch") = false, "Fill a constrained boundary network into one Face, optionally with holes."); m.def( diff --git a/src/cpp/include/scad/ops/features/blends.hpp b/src/cpp/include/scad/ops/features/blends.hpp index 58c1918f..f49513fd 100644 --- a/src/cpp/include/scad/ops/features/blends.hpp +++ b/src/cpp/include/scad/ops/features/blends.hpp @@ -12,11 +12,28 @@ namespace scad { +// Kernel strategies a fillet may use instead of the standard rolling-ball algorithm. +struct FilletOptions { + // Y transition (kernel patch set fillet-robustness-4, BRepFilletAPI_YPatch): where a concave + // and a convex selected edge meet tangentially or nearly so between two (nearly) tangent + // supports, both bands stop where they touch the common face and two G1 ribbons join them. + // On: the transition first at every such junction (the standard algorithm when it fails its + // checks). Off: at a junction where the standard result fails, is invalid or self-intersects, the + // kernel falls back to the pinch corner (both bands taper to the vertex), then to the Y transition; + // a valid standard result is kept. A kernel + // without the patch raises ValueError for `true`. + bool strategy_auto_y_patch = false; +}; + // Round `edges` (explicit, or a ql selector resolved in `solid`) by `radius`. Role: // fillet.patch. A failing blend is explained with measurements (size against face room, // tangent faces, ...), and a result no convex blend can produce is rejected. // Error "fillet_rsolid". -Solid fillet_rsolid(const Solid& solid, const EdgeSelection& edges, const Scalar& radius, const BlendTags& tags = {}); +Solid fillet_rsolid(const Solid& solid, const EdgeSelection& edges, const Scalar& radius, const BlendTags& tags = {}, + const FilletOptions& options = {}); + +// True when the linked kernel carries the Y transition (BRepFilletAPI_YPatch). +bool kernel_has_y_patch(); struct ChamferOptions { // Degrees between the chamfer face and the reference face; the second leg is diff --git a/src/cpp/include/scad/semantic/tracking.hpp b/src/cpp/include/scad/semantic/tracking.hpp index 77ab47df..023976fe 100644 --- a/src/cpp/include/scad/semantic/tracking.hpp +++ b/src/cpp/include/scad/semantic/tracking.hpp @@ -133,7 +133,10 @@ TrackedResult tracked_twisted_sweep(const Face& profile, const Vec3& axis, const // tracked_fillet. Face history of the solid (origin_role "body"), then the // contours OCCT actually filleted (origin_role "contour_edge"; generated // edges carry role fillet.patch). -TrackedResult tracked_fillet(const Solid& solid, const std::vector& edges, double radius); +// `auto_y_patch` turns on the kernel's Y transition (see FilletOptions); its ribbons are +// generated by the contour edges like the bands, so they carry fillet.patch too. +TrackedResult tracked_fillet(const Solid& solid, const std::vector& edges, double radius, + bool auto_y_patch = false); // tracked_chamfer. `distance2` makes the chamfer asymmetric and then needs one // (face1, face2) pair per edge -- face1 takes `distance` -- else ValueError. diff --git a/src/cpp/include/scad/surface/fitter.hpp b/src/cpp/include/scad/surface/fitter.hpp index 5990a8a7..2d79af74 100644 --- a/src/cpp/include/scad/surface/fitter.hpp +++ b/src/cpp/include/scad/surface/fitter.hpp @@ -45,6 +45,13 @@ struct FillingProblem { std::vector boundaries; std::vector points; // extra points the surface must pass through (global frame) SurfaceFillingSettings settings; + // Graph patch (kernel patch set fillet-robustness-4, BRepOffsetAPI_GraphPatch): the boundaries + // are one ordered closed loop, each edge an edge of its support face; a degree-8 variational + // patch meets every support in its order 0/1/2 (C0/G1/G2) and is trimmed by the projected + // boundary: exactly where a degree-8 graph can, otherwise (curved supports) within the + // kernel's limits (1e-3 mm, 1e-3 rad, 5% of the curvature), continuing the supports' own + // surfaces over the hole. No points, no holes. `settings` do not apply. + bool graph_patch = false; }; class SurfaceFitter { @@ -66,6 +73,9 @@ class SurfaceFitter { // The provider in use; the OpenCASCADE one unless replaced. std::shared_ptr surface_fitter(); + +// True when the linked kernel carries BRepOffsetAPI_GraphPatch (FillingProblem::graph_patch). +bool kernel_has_graph_patch(); std::shared_ptr occt_surface_fitter(); // nullptr restores the OpenCASCADE provider. void set_surface_fitter(std::shared_ptr fitter); diff --git a/src/cpp/include/scad/surface/operators.hpp b/src/cpp/include/scad/surface/operators.hpp index 71b36e0c..d86b9ee0 100644 --- a/src/cpp/include/scad/surface/operators.hpp +++ b/src/cpp/include/scad/surface/operators.hpp @@ -62,6 +62,9 @@ struct SurfacePatchOptions { std::optional settings; std::vector holes; TagPrefix tag_prefix; + // Kernel graph patch instead of the plate filling (see FillingProblem::graph_patch): one ordered + // loop, every boundary an edge of its support face, no points, holes or settings. + bool strategy_graph_patch = false; }; // A constrained boundary network filled into one Face, optionally with holes. The filling kernel diff --git a/src/cpp/patches/occt/0004-fillet-y-patch.patch b/src/cpp/patches/occt/0004-fillet-y-patch.patch new file mode 100644 index 00000000..8ca82a0e --- /dev/null +++ b/src/cpp/patches/occt/0004-fillet-y-patch.patch @@ -0,0 +1,257 @@ +diff --git a/src/BRepFilletAPI/BRepFilletAPI_MakeFillet.hxx b/src/BRepFilletAPI/BRepFilletAPI_MakeFillet.hxx +--- a/src/BRepFilletAPI/BRepFilletAPI_MakeFillet.hxx ++++ b/src/BRepFilletAPI/BRepFilletAPI_MakeFillet.hxx +@@ -32,6 +32,8 @@ + #include + #include + #include ++#include ++#include + class TopoDS_Shape; + class TopoDS_Edge; + class Law_Function; +@@ -324,6 +326,32 @@ + //! contours and fillet parameters in order to rebuild the shape. + Standard_EXPORT void Reset() Standard_OVERRIDE; + ++ //! Y-patch strategy for mixed-convexity junctions: places where a concave and a convex ++ //! constant-radius contour meet tangentially or nearly so between two (nearly) tangent ++ //! supports (see BRepFilletAPI_YPatch). ++ //! On: Build() tries the Y transition first; when it cannot be built and verified, the ++ //! standard algorithm runs. ++ //! Off (default): the standard algorithm runs. Only when the contours hold such a junction ++ //! and the standard result is not done, invalid or self-interfering, a pinch replaces it ++ //! (both bands narrow to the junction vertex along one shared curve), or, when the pinch ++ //! cannot be built and verified, the Y transition; YPatchFallback() then answers true and ++ //! YPatchJunction(i).Pinch tells which. Without a junction nothing is checked and the ++ //! result is the standard one, unchanged. ++ Standard_EXPORT void SetYPatch(const Standard_Boolean theOn); ++ ++ Standard_EXPORT Standard_Boolean YPatch() const; ++ ++ //! Number of junctions joined by a Y transition in the last Build() (0: standard result). ++ Standard_EXPORT Standard_Integer NbYPatches() const; ++ ++ //! True when the last Build() used the Y transition without SetYPatch(true), because the ++ //! standard result failed at a junction. ++ Standard_EXPORT Standard_Boolean YPatchFallback() const; ++ ++ //! Junction I (1 <= I <= NbYPatches()) with its measured continuity. ++ Standard_EXPORT const BRepFilletAPI_YPatch::Junction& YPatchJunction( ++ const Standard_Integer I) const; ++ + //! Returns the internal topology building algorithm. + Standard_EXPORT Handle(TopOpeBRepBuild_HBuilder) Builder() const; + +@@ -398,6 +426,12 @@ + private: + ChFi3d_FilBuilder myBuilder; + TopTools_MapOfShape myMap; ++ // Y-patch strategy ++ TopoDS_Shape myInput; ++ Standard_Boolean myYPatch; ++ Standard_Boolean myYFallback; ++ Handle(BRepTools_History) myYHistory; ++ NCollection_Vector myYReport; + }; + + #endif // _BRepFilletAPI_MakeFillet_HeaderFile +diff --git a/src/BRepFilletAPI/BRepFilletAPI_MakeFillet.cxx b/src/BRepFilletAPI/BRepFilletAPI_MakeFillet.cxx +--- a/src/BRepFilletAPI/BRepFilletAPI_MakeFillet.cxx ++++ b/src/BRepFilletAPI/BRepFilletAPI_MakeFillet.cxx +@@ -15,6 +15,9 @@ + // commercial license or contractual agreement. + + #include ++#include ++#include ++#include + #include + #include + #include +@@ -31,12 +34,51 @@ + + BRepFilletAPI_MakeFillet::BRepFilletAPI_MakeFillet(const TopoDS_Shape& S, + const ChFi3d_FilletShape FShape) +- : myBuilder(S, FShape) ++ : myBuilder(S, FShape), ++ myInput(S), ++ myYPatch(Standard_False), ++ myYFallback(Standard_False) + { + } + + //================================================================================================= + ++void BRepFilletAPI_MakeFillet::SetYPatch(const Standard_Boolean theOn) ++{ ++ myYPatch = theOn; ++} ++ ++//================================================================================================= ++ ++Standard_Boolean BRepFilletAPI_MakeFillet::YPatch() const ++{ ++ return myYPatch; ++} ++ ++//================================================================================================= ++ ++Standard_Integer BRepFilletAPI_MakeFillet::NbYPatches() const ++{ ++ return myYReport.Length(); ++} ++ ++//================================================================================================= ++ ++Standard_Boolean BRepFilletAPI_MakeFillet::YPatchFallback() const ++{ ++ return myYFallback; ++} ++ ++//================================================================================================= ++ ++const BRepFilletAPI_YPatch::Junction& BRepFilletAPI_MakeFillet::YPatchJunction( ++ const Standard_Integer I) const ++{ ++ return myYReport.Value(I - 1); ++} ++ ++//================================================================================================= ++ + void BRepFilletAPI_MakeFillet::SetParams(const Standard_Real Tang, + const Standard_Real Tesp, + const Standard_Real T2d, +@@ -372,13 +414,89 @@ + + void BRepFilletAPI_MakeFillet::Build(const Message_ProgressRange& /*theRange*/) + { +- myBuilder.Compute(); ++ myYHistory.Nullify(); ++ myYReport.Clear(); ++ myYFallback = Standard_False; ++ // The Y strategy takes constant-radius contours only. ++ TopTools_DataMapOfShapeReal radii; ++ Standard_Boolean constant = Standard_True; ++ for (Standard_Integer ic = 1; ic <= NbContours() && constant; ++ic) ++ { ++ constant = myBuilder.IsConstant(ic); ++ for (Standard_Integer ie = 1; ie <= NbEdges(ic) && constant; ++ie) ++ radii.Bind(Edge(ic, ie), myBuilder.Radius(ic)); ++ } ++ constant = constant && !radii.IsEmpty(); ++ if (myYPatch) ++ { ++ TopoDS_Shape result; ++ if (constant && BRepFilletAPI_YPatch::Perform(myInput, radii, result, myYHistory, myYReport)) ++ { ++ myShape = result; ++ Done(); ++ return; ++ } ++ myYHistory.Nullify(); ++ myYReport.Clear(); ++ } ++ // Without SetYPatch, a junction is the only case that pays for checking the standard result. ++ const Standard_Boolean junction = ++ !myYPatch && constant && !BRepFilletAPI_YPatch::Detect(myInput, radii).IsEmpty(); ++ if (!junction) ++ { ++ myBuilder.Compute(); ++ if (myBuilder.IsDone()) ++ { ++ Done(); ++ myShape = myBuilder.Shape(); ++ ++ // creation of the Map. ++ TopExp_Explorer ex; ++ for (ex.Init(myShape, TopAbs_FACE); ex.More(); ex.Next()) ++ { ++ myMap.Add(ex.Current()); ++ } ++ } ++ return; ++ } ++ Standard_Boolean sound = Standard_False; ++ try ++ { ++ myBuilder.Compute(); ++ if (myBuilder.IsDone() && BRepCheck_Analyzer(myBuilder.Shape()).IsValid()) ++ { ++ BOPAlgo_CheckerSI si; ++ si.SetLevelOfCheck(5); ++ si.AddArgument(myBuilder.Shape()); ++ si.Perform(); ++ sound = !si.HasErrors() && si.DS().Interferences().IsEmpty(); ++ } ++ } ++ catch (const Standard_Failure&) ++ { ++ sound = Standard_False; ++ } ++ if (!sound) ++ { ++ // the pinch first (no faces of its own between the bands), then the Y transition ++ for (const Standard_Boolean pinch : {Standard_True, Standard_False}) ++ { ++ TopoDS_Shape result; ++ if (BRepFilletAPI_YPatch::Perform(myInput, radii, result, myYHistory, myYReport, pinch)) ++ { ++ myShape = result; ++ myYFallback = Standard_True; ++ Done(); ++ return; ++ } ++ myYHistory.Nullify(); ++ myYReport.Clear(); ++ } ++ } + if (myBuilder.IsDone()) + { + Done(); + myShape = myBuilder.Shape(); +- +- // creation of the Map. + TopExp_Explorer ex; + for (ex.Init(myShape, TopAbs_FACE); ex.More(); ex.Next()) + { +@@ -394,6 +512,9 @@ + NotDone(); + myBuilder.Reset(); + myMap.Clear(); ++ myYHistory.Nullify(); ++ myYReport.Clear(); ++ myYFallback = Standard_False; + } + + //================================================================================================= +@@ -436,6 +557,8 @@ + + const TopTools_ListOfShape& BRepFilletAPI_MakeFillet::Generated(const TopoDS_Shape& EorV) + { ++ if (!myYHistory.IsNull()) ++ return myYHistory->Generated(EorV); + return myBuilder.Generated(EorV); + } + +@@ -444,6 +567,11 @@ + const TopTools_ListOfShape& BRepFilletAPI_MakeFillet::Modified(const TopoDS_Shape& F) + { + myGenerated.Clear(); ++ if (!myYHistory.IsNull()) ++ { ++ myGenerated = myYHistory->Modified(F); ++ return myGenerated; ++ } + + if (myBuilder.Builder()->IsSplit(F, TopAbs_OUT)) + { +@@ -476,6 +604,8 @@ + + Standard_Boolean BRepFilletAPI_MakeFillet::IsDeleted(const TopoDS_Shape& F) + { ++ if (!myYHistory.IsNull()) ++ return myYHistory->IsRemoved(F); + if (myMap.Contains(F) || myBuilder.Builder()->IsSplit(F, TopAbs_OUT) + || myBuilder.Builder()->IsSplit(F, TopAbs_IN) || myBuilder.Builder()->IsSplit(F, TopAbs_ON)) + return Standard_False; diff --git a/src/cpp/patches/occt/GUIDE.md b/src/cpp/patches/occt/GUIDE.md new file mode 100644 index 00000000..ba697ea3 --- /dev/null +++ b/src/cpp/patches/occt/GUIDE.md @@ -0,0 +1,147 @@ +# How to modify the OCCT kernel systematically + +This is the working method for SimpleCADAPI's modifications of OpenCASCADE (OCCT): where files go, how a geometric +special case becomes a strategy branch, how it is exposed to the SDK, and how it is verified and shipped. It comes from +the `fillet-robustness-4` patch set (Y transition, pinch corner, graph patch); the reasons behind each decision are in +`design-docs/y-patch-and-graph-patch.md`. + +## 1. Principles + +- **Geometric special cases are decided inside the kernel.** Not in Python (slow), not in the SDK's C++ operators + (that couples the SDK to one kernel and makes a kernel migration a rewrite). The SDK only forwards a switch. +- **Small patches, new capabilities in the overlay.** A patch changes existing OCCT code only where it must: a switch, + a call site, a fix. The algorithm itself is a new class in the overlay, separate from OCCT's sources, so that it + replays on an OCCT upgrade and could be offered upstream on its own. +- **A strategy that is off changes nothing.** It runs either when the caller asks for it, or only when a specific + situation is detected *and* the original algorithm fails there. An input that does not hit the detection takes the + original code path and gets a bit-identical result. +- **Every strategy has gates.** The result must pass `BRepCheck_Analyzer`, `BOPAlgo_CheckerSI` level 5 and the history + checks; if any fails, the original algorithm's behaviour is restored. Never return bad geometry silently. + +## 2. Where files go + +| Location | Content | +| --- | --- | +| `src/cpp/patches/occt/000N-.patch` | unified diffs of existing OCCT files, applied in number order | +| `src/cpp/patches/occt/manifest.json` | base version (tag, commit, archive sha256), patch-set name, patch list, before/after sha256 of every patched file | +| `src/cpp/patches/occt/overlay/_.{hxx,cxx}` | new classes; installed into OCCT's `src//` (the part of the file name before the first `_`) and registered in that package's `FILES` | +| `src/cpp/patches/occt/tests/` | kernel-level check tools (a standalone CMake project): `cases` (Y/pinch family), `graphpatch`, `yfillet`, `check`, `inspect`, `shellfillet`, `sidetail`, `wires`, `fixsmall` | +| `src/cpp/patches/occt/README.md` | what each patch changes and why | +| `src/cpp/tools/occt_patches.py` | verifies hashes, applies patches exactly (no fuzz, idempotent), installs the overlay; `recipe()` fingerprints the whole set | +| `src/cpp/tools/build_occt.py` | builds static OCCT from source into a prefix and writes the fingerprint to `share/simplecadapi/occt-recipe.sha256` | +| `src/cpp/cmake/ScadOcct.cmake` | the toolkits the SDK links | +| `.github/workflows/ci.yml`, `release.yml` | CI and releases build the kernel from this patch set with `build_occt.py`; the cache key includes `src/cpp/patches/occt/**`, so a patch change rebuilds it | + +When overlay code needs a new toolkit dependency, append it to that toolkit's `EXTERNLIB` in +`occt_patches.install_overlay()` (see how `TKPrim` is added to `TKFillet`). + +## 3. Writing a strategy branch + +A strategy has four parts. Example: the junction strategies in `overlay/BRepFilletAPI_YPatch*`. + +1. **Detect**: a pure function from the shape and the caller's selection to a struct with evidence (junction vertex, + concave and convex edges, the three supports, the support angle). Cheap, topological first, and reusing OCCT's own + predicates (convexity: `ChFi3d::DefineConnectType`) instead of a second definition. +2. **Construct**: let OCCT's standard algorithm do everything it can and build only the missing piece. The junction + strategies cut the junction wedge out, fillet the open shell with the standard algorithm, then add the corner faces + (pinch bands or Y ribbons) and sew; far band ends and all other edges stay the standard algorithm's. +3. **Gate**: `BRepCheck_Analyzer`, `BOPAlgo_CheckerSI` level 5, no free edges after sewing, measured continuity + (normal angles across seams). Any failure returns false. +4. **History**: `BRepTools_History` with Modified / Generated / Removed for every input sub-shape, composed explicitly + through every stage, sub-shape by sub-shape (do not rely on `Merge`, see section 6). + +Wiring into an existing OCCT entry point (patch `0004`): + +- explicit switch: `BRepFilletAPI_MakeFillet::SetYPatch(bool)`, strategy first; +- default fallback: with the switch off the standard algorithm runs first; only when detection fires and the standard + result fails, is invalid or self-intersects, the strategies replace it, in a fixed order (pinch, then Y). An input + without a detection pays one topological scan and is otherwise unchanged; +- report: `NbYPatches()`, `YPatchJunction(i)` (with measured angles), `YPatchFallback()` (requested vs fallback); +- history: `Generated` / `Modified` / `IsDeleted` answer from the strategy's history when it produced the result, so + callers that track faces and tags need no special case. + +The order of several strategies is written in the entry point, never implied by code order. + +## 4. Exposing a strategy in the SDK + +- Detect at compile time with `#if __has_include()`. The SDK must still compile against + stock OCCT; requesting a strategy the kernel lacks raises `ValueError` naming the patch set, never silently ignores it. +- Use an explicit named boolean parameter, default `False` (`strategy_auto_y_patch`, `strategy_graph_patch`). +- Record it in the operation graph only when true, so records of the standard path stay as they were; replay it in + `src/simplecadapi/recording/serializer.py` and in the C++ `executors.cpp`. +- Report capabilities through `simplecadapi._cpp._kernel_capabilities()`. +- Document in `src/simplecadapi/_glue/docstrings.json`, regenerate the API pages with `tools/auto_docs_gen.py` after + building, update `CHANGELOG.md`. +- Check preconditions in the SDK before the kernel call (e.g. each graph-patch boundary must be an edge of its support), + so the error says which one failed instead of a bare kernel refusal. + +## 5. Workflow + +Keep intermediate products outside the repository (e.g. `D:/occt-kernel/`). + +1. **Dev loop, no prefix rebuild**: build the `tests/` CMake project against the installed prefix with + `-DYPATCH_DEV=ON`; it compiles the checkout's overlay sources into the tools, shadowing the prefix's copies. When + the patched `MakeFillet` changes too, add `-DYPATCH_MAKEFILLET=`. A build-and-test + round takes seconds. +2. **Regenerate a patch**: pristine files under `a/src//`, edited ones under `b/src//`; one + `diff --git` line per file, then `diff -u --label a/src/... --label b/src/...` (no timestamps in the labels, or + `occt_patches` reads a wrong file name); update the file's before/after hashes in `manifest.json`. +3. **Rebuild the prefix incrementally**: restore the pristine versions of patched files in the source tree first (the + new after-hash makes `apply()` reject the old patched state); `occt_patches.install_overlay()`; in the build + directory `cmake --build . --target install` (only the changed toolkits recompile); write `occt_patches.recipe()` + into the prefix's `occt-recipe.sha256`. Install a new kernel into a new prefix (e.g. `C:/OCCT-modified/static-ypatch`) + and keep the previous one as the control. +4. **Rebuild the SDK**: a separate build directory (e.g. `out/ypatch-build`) configured with + `-DSCAD_OCCT_PREFIX= -DOpenCASCADE_DIR=/lib/cmake/opencascade`. The `.pyd` lands in + `src/simplecadapi/_cpp/`; rename the module loaded in `.venv` first, then copy the new one (a loaded DLL cannot be + overwritten but can be renamed). +5. **Test**: + - kernel: `cases.exe` over the whole family must print `failures 0`, strict history included; + - SDK: `ctest`; `pytest src/cpp/tests/python` and `pytest test tests` as two runs (one run collides on test module + names); + - continuity: zebra pictures with `tools/render/zebra.py`, looked at one by one; + - ground truth: the same cases in Plasticity driven by desktop automation (scripts under + `out/plasticity-gt/tools/` on the development machine), comparing deviations and P*. +6. **Commit**: one decision per commit, the message as a decision record (DECISION / PROBLEM / WHY / REJECTED / + EVIDENCE / NOT DONE), written to a file and committed with `git commit -F`. + +## 6. Pitfalls already met + +- **Line endings**: the repository stores bytes exactly (`* -text` in `.gitattributes`). Python's `write_text` on + Windows writes CRLF; use `write_bytes` or `newline='\n'` and check with `file` before committing. +- **English only under `src/`**: `test/test_library_is_english.py` rejects Chinese text there; decision records and + reports in Chinese belong in `design-docs/`. +- **`BRepFilletAPI_MakeFillet::IsDeleted` answers for faces only**: for edges and vertices it says "deleted". Test their + survival by presence in the result. +- **`BRepBuilderAPI_Sewing::IsModified/Modified` only know whole shapes added with `Add`**: for sub-shapes use + `IsModifiedSubShape/ModifiedSubShape`, or the supports are reported deleted. +- **`BRepTools_History::Merge` loses mappings**: a shape generated in the second history from a modified image is not + carried back to the original. Compose multi-stage histories explicitly. +- **The standard fillet depends on the order of `Add`**: the same edges added in another order can turn "not done" + into "done". Tests add edges in a fixed order. +- **Periodic seams**: with a cylinder's seam vertex on a chain to be filleted, the standard algorithm built a band twice. + Move the parametric origin away from the selected edges first, then merge the old seam's vertex (edges only). +- **Dangling temporaries**: `TopTools_ListOfShape::Iterator it(f())` with `f()` returning a list by value iterates a + destroyed temporary. Store the list in a local first. +- **History checks must be strict**: "kept, modified or deleted" lets a wrong "deleted" pass. Require: no input face + reported deleted, junction edges generating enough faces, every result face traced to an input face or edge. +- **Keep experiment outputs apart from final outputs**: experiment runs overwrote result files and a later comparison + silently used the wrong ones. Use a fresh output folder for every final run. +- **Check nobody is editing the overlay before syncing**: a prefix rebuild copies the overlay folder as it is, a + half-edited file included; such a build is provisional. +- **A text BREP round trip is not a fix**: when writing a shape as text and reading it back makes a case pass, the case + is numerically marginal there; fix the geometry. +- **Do not fit degenerate surfaces in 2D**: the pinch bands collapse to a point (section radius like x²/4R); fitting + sampled positions with a tensor spline folded them. Build such surfaces exactly (exact sections, 1D laws along the + rail, a degenerated edge at the apex). + +## 7. Acceptance checklist for a new strategy + +- [ ] detect / construct / gate / history; off means bit-identical results +- [ ] a whole family, not one sample: tangent and near-tangent, several sizes, arbitrary placement, every position of a + periodic seam, one and several occurrences, one case that must be refused +- [ ] strict history through the public entry point (e.g. `MakeFillet`) +- [ ] zebra pictures, comparison with Plasticity ground truth +- [ ] patch regenerated, manifest updated, prefix rebuilt incrementally, SDK rebuilt, C++ and Python suites green +- [ ] SDK parameter, operation-graph record and replay, capability query, docs, CHANGELOG +- [ ] decision record in `design-docs/` and decision-record commit messages diff --git a/src/cpp/patches/occt/README.md b/src/cpp/patches/occt/README.md index a8b1be17..36be7b39 100644 --- a/src/cpp/patches/occt/README.md +++ b/src/cpp/patches/occt/README.md @@ -1,4 +1,6 @@ -# OCCT fillet-robustness-3 (candidate) +# OCCT fillet-robustness-4 + +How to modify the kernel systematically (layout, strategy branches, SDK exposure, workflow, pitfalls): [GUIDE.md](GUIDE.md). Base: OCCT V7_9_3, commit `a016080bf6738d6aeae020badee4e888ad1540a5`. @@ -25,6 +27,22 @@ numerical diagnostics, not a proof that every possible self-intersection is excluded. The same-radius nonfolding construction, material semantics, general inset handling and production release remain unfinished. +`0004-fillet-y-patch.patch` adds the strategy entry points to `BRepFilletAPI_MakeFillet`: `SetYPatch` (Y transition +first), a default fallback (standard algorithm first; at a detected concave/convex tangent junction whose standard +result fails, is invalid or self-intersects, the junction strategy replaces it), `NbYPatches`, `YPatchJunction`, +`YPatchFallback`, and history (`Generated`/`Modified`/`IsDeleted`) answered from the strategy's own history. + +Overlay classes (compiled into their toolkits by `occt_patches.install_overlay`): + +| Class | Toolkit | Role | +| --- | --- | --- | +| `BRepFilletAPI_YPatch` (+ `YPatchGeom`, `YPatchBuild`) | TKFillet | junction detection, Y transition and pinch corner, gates, history | +| `BRepOffsetAPI_GraphPatch` | TKOffset | degree-8 graph patch over an ordered C0/G1/G2 loop, continuing curved supports | +| `BRepFilletAPI_RibbonFit` | TKFillet | four-sided fairing on callbacks (research API) | +| `BRepFilletAPI_TangentY` | TKFillet | canonical plate/post Y (research sample; superseded by `BRepFilletAPI_YPatch`) | + +Kernel-level checks: `tests/` (see `tests/CMakeLists.txt`). + `manifest.json` locks every input and output file. `tools/occt_patches.py` checks those digests, validates all hunks, and only then writes. Reapplying is harmless; applying to another release or a locally modified target refuses explicitly. Build the full kernel into a fresh prefix: diff --git a/src/cpp/patches/occt/manifest.json b/src/cpp/patches/occt/manifest.json index 33fd0ffa..2e835a6e 100644 --- a/src/cpp/patches/occt/manifest.json +++ b/src/cpp/patches/occt/manifest.json @@ -2,8 +2,13 @@ "tag": "V7_9_3", "commit": "a016080bf6738d6aeae020badee4e888ad1540a5", "archive_sha256": "5ecf094ec6b12d5413dfb851d8c3590c354058aee556e32e408bdfbf8c357d57", - "patchset": "fillet-robustness-3", - "patches": ["0001-tangent-end.patch", "0002-root-solid-orientation.patch", "0003-tangent-corner-boundaries.patch"], + "patchset": "fillet-robustness-4", + "patches": [ + "0001-tangent-end.patch", + "0002-root-solid-orientation.patch", + "0003-tangent-corner-boundaries.patch", + "0004-fillet-y-patch.patch" + ], "files": { "src/ChFi3d/ChFi3d_Builder_0.cxx": { "before": "e33baec19d427c2967a427a5a9f0872be23840e4a3a3697039f15b20001203d1", @@ -20,6 +25,14 @@ "src/ChFi3d/ChFi3d_Builder_1.cxx": { "before": "99fd57fe50475f21ee13d298742ce48585829bf4b9624377a78795795db46335", "after": "8fc97dcf851901e68728d756d387a98a8c94b1e4f8449698fe8057fc9f7a4e50" + }, + "src/BRepFilletAPI/BRepFilletAPI_MakeFillet.hxx": { + "before": "74bd7a1218cae8511c83bbbf666a57b793215af6f05fed2407340233f6ffabe7", + "after": "e876b2fef89b84807551f47588a1b826ed92063ddd23fc9ee0e93168d054bb01" + }, + "src/BRepFilletAPI/BRepFilletAPI_MakeFillet.cxx": { + "before": "a2d4c91fb233859eaafa9c80a652c1a6ea66578da931966b14cb0c7f48892a8f", + "after": "06e4c04f185f8a665f4a0e87b61d0ff94137fbe8dbf7a8e12717d62fa7efa402" } } } diff --git a/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatch.cxx b/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatch.cxx new file mode 100644 index 00000000..ac62f9f6 --- /dev/null +++ b/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatch.cxx @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: LGPL-2.1-only WITH OCCT-exception-1.0 +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace YPatch +{ + +Support::Support(const TopoDS_Face& f) + : face(f), + s(f, Standard_False), + sign(f.Orientation() == TopAbs_REVERSED ? -1. : 1.), + proj(new ShapeAnalysis_Surface(BRep_Tool::Surface(f))) +{ +} + +gp_Pnt Support::P(const gp_Pnt2d& uv) const +{ + return s.Value(uv.X(), uv.Y()); +} + +gp_Vec Support::N(const gp_Pnt2d& uv) const +{ + gp_Pnt p; + gp_Vec du, dv; + s.D1(uv.X(), uv.Y(), p, du, dv); + gp_Vec n = du.Crossed(dv); + const double m = n.Magnitude(); + if (m < 1e-14) + throw Standard_Failure("YPatch: singular support normal"); + return n * (sign / m); +} + +gp_Pnt2d Support::UV(const gp_Pnt& p) const +{ + return proj->ValueOfUV(p, 1e-9); +} + +gp_Pnt2d Support::UVNear(const gp_Pnt& p, const gp_Pnt2d& seed) const +{ + return proj->NextValueOfUV(seed, p, 1e-9); +} + +Rail::Rail(const TopoDS_Edge& e, const TopoDS_Vertex& v) + : edge(e), + c(e) +{ + TopoDS_Vertex v1, v2; + TopExp::Vertices(e, v1, v2); + first = c.FirstParameter(); + last = c.LastParameter(); + if (v.IsSame(v2) && !v.IsSame(v1)) + std::swap(first, last); +} + +double Rail::Param(double lambda) const +{ + return first + lambda * (last - first); +} + +gp_Pnt Rail::P(double lambda) const +{ + return c.Value(Param(lambda)); +} + +gp_Vec Rail::T(double lambda) const +{ + gp_Pnt p; + gp_Vec d; + c.D1(Param(lambda), p, d); + if (last < first) + d.Reverse(); + return d.Normalized(); +} + +gp_Pnt2d Rail::UV(const TopoDS_Face& f, double lambda) const +{ + double f1, l1; + auto pc = BRep_Tool::CurveOnSurface(edge, f, f1, l1); + if (pc.IsNull()) + throw Standard_Failure("YPatch: edge without pcurve"); + return pc->Value(Param(lambda)); +} + +// The rolling ball of radius r between T and X whose centre lies in the normal plane of +// the rail at lambda. sigma = +1: concave (ball outside), -1: convex (ball inside). +bool Band::Solve(double lambda, Ball& b, const Ball* seed) const +{ + const gp_Pnt e = rail.P(lambda); + const gp_Vec t = rail.T(lambda); + math_Vector x(1, 4); + if (seed != nullptr) + { + x(1) = seed->uvT.X(); + x(2) = seed->uvT.Y(); + x(3) = seed->uvX.X(); + x(4) = seed->uvX.Y(); + } + else + { + const gp_Pnt2d a = rail.UV(T.face, lambda), c = rail.UV(X.face, lambda); + gp_Vec nT = T.N(a), nX = X.N(c); + gp_Vec dT = nX - nT * nX.Dot(nT), dX = nT - nX * nT.Dot(nX); + if (dT.Magnitude() < 1e-9 || dX.Magnitude() < 1e-9) + return false; + const gp_Pnt2d a2 = T.UVNear(e.Translated(dT.Normalized() * (sigma * r)), a); + const gp_Pnt2d c2 = X.UVNear(e.Translated(dX.Normalized() * (sigma * r)), c); + x(1) = a2.X(); + x(2) = a2.Y(); + x(3) = c2.X(); + x(4) = c2.Y(); + } + auto residual = [&](const math_Vector& y, math_Vector& f) { + const gp_Pnt2d a(y(1), y(2)), c(y(3), y(4)); + const gp_XYZ cT = T.P(a).XYZ() + T.N(a).XYZ() * (sigma * r); + const gp_XYZ cX = X.P(c).XYZ() + X.N(c).XYZ() * (sigma * r); + const gp_XYZ d = cT - cX; + f(1) = d.X(); + f(2) = d.Y(); + f(3) = d.Z(); + f(4) = (cT - e.XYZ()).Dot(t.XYZ()); + }; + math_Vector f(1, 4), g(1, 4); + for (int it = 0; it < 60; ++it) + { + residual(x, f); + if (f.Norm() < 1e-11 * (1 + r)) + { + const gp_Pnt2d a(x(1), x(2)), c(x(3), x(4)); + b.lambda = lambda; + b.uvT = a; + b.uvX = c; + b.pT = T.P(a); + b.pX = X.P(c); + b.c = gp_Pnt(b.pT.XYZ() + T.N(a).XYZ() * (sigma * r)); + return true; + } + math_Matrix j(1, 4, 1, 4); + for (int k = 1; k <= 4; ++k) + { + math_Vector y = x; + const double h = 1e-7 * (1 + std::abs(x(k))); + y(k) += h; + residual(y, g); + for (int i = 1; i <= 4; ++i) + j(i, k) = (g(i) - f(i)) / h; + } + math_Gauss lu(j); + if (!lu.IsDone()) + return false; + math_Vector dx(1, 4); + lu.Solve(-f, dx); + double step = 1.; + const double cap = 0.5 * r; + // limit the 3D displacement of either contact to half a radius per iteration + for (int k = 0; k < 2; ++k) + { + const Support& s = k ? X : T; + const gp_Pnt2d p0(x(1 + 2 * k), x(2 + 2 * k)); + const gp_Pnt2d p1(x(1 + 2 * k) + dx(1 + 2 * k), x(2 + 2 * k) + dx(2 + 2 * k)); + const double m = s.P(p0).Distance(s.P(p1)); + if (m > cap) + step = std::min(step, cap / m); + } + x += dx * step; + } + return false; +} + +double angle(const gp_Vec& a, const gp_Vec& b) +{ + return a.Angle(b); +} + +} // namespace YPatch + +using namespace YPatch; + +NCollection_Vector BRepFilletAPI_YPatch::Detect( + const TopoDS_Shape& theShape, + const TopTools_DataMapOfShapeReal& theRadii) +{ + NCollection_Vector out; + TopTools_IndexedDataMapOfShapeListOfShape ef, ve; + TopExp::MapShapesAndAncestors(theShape, TopAbs_EDGE, TopAbs_FACE, ef); + TopExp::MapShapesAndAncestors(theShape, TopAbs_VERTEX, TopAbs_EDGE, ve); + auto faces = [&](const TopoDS_Edge& e, TopoDS_Face& f1, TopoDS_Face& f2) { + if (!ef.Contains(e)) + return false; + const TopTools_ListOfShape& l = ef.FindFromKey(e); + if (l.Extent() != 2) + return false; + f1 = TopoDS::Face(l.First()); + f2 = TopoDS::Face(l.Last()); + return !f1.IsSame(f2); + }; + for (int iv = 1; iv <= ve.Extent(); ++iv) + { + const TopoDS_Vertex v = TopoDS::Vertex(ve.FindKey(iv)); + std::vector concave, convex; + for (TopTools_ListOfShape::Iterator it(ve(iv)); it.More(); it.Next()) + { + const TopoDS_Edge e = TopoDS::Edge(it.Value()); + if (!theRadii.IsBound(e) || BRep_Tool::Degenerated(e)) + continue; + TopoDS_Face f1, f2; + if (!faces(e, f1, f2)) + continue; + const ChFiDS_TypeOfConcavity k = ChFi3d::DefineConnectType(e, f1, f2, 1.e-5, Standard_True); + auto& bucket = k == ChFiDS_Concave ? concave : convex; + if (k != ChFiDS_Concave && k != ChFiDS_Convex) + continue; + if (std::none_of(bucket.begin(), bucket.end(), [&](const TopoDS_Edge& x) { return x.IsSame(e); })) + bucket.push_back(e); + } + for (const auto& ein : concave) + for (const auto& eout : convex) + { + if (ein.IsSame(eout)) + continue; + TopoDS_Face a1, a2, b1, b2; + faces(ein, a1, a2); + faces(eout, b1, b2); + TopoDS_Face T, A, B; + if (a1.IsSame(b1) || a1.IsSame(b2)) + { + T = a1; + A = a2; + } + else if (a2.IsSame(b1) || a2.IsSame(b2)) + { + T = a2; + A = a1; + } + else + continue; + B = b1.IsSame(T) ? b2 : b1; + if (A.IsSame(B)) + continue; + // A and B must meet at V along an unselected edge. + bool adjacent = false; + for (TopTools_ListOfShape::Iterator it(ve(iv)); it.More() && !adjacent; it.Next()) + { + const TopoDS_Edge es = TopoDS::Edge(it.Value()); + TopoDS_Face f1, f2; + if (es.IsSame(ein) || es.IsSame(eout) || theRadii.IsBound(es) || !faces(es, f1, f2)) + continue; + adjacent = (f1.IsSame(A) && f2.IsSame(B)) || (f1.IsSame(B) && f2.IsSame(A)); + } + if (!adjacent) + continue; + Support sa(A), sb(B); + Rail ra(ein, v), rb(eout, v); + const double ang = angle(sa.N(ra.UV(A, 0)), sb.N(rb.UV(B, 0))); + if (ang > MaxSupportAngle()) + continue; + Junction j; + j.Vertex = v; + j.Concave = ein; + j.Convex = eout; + j.Common = T; + j.Concave2 = A; + j.Convex2 = B; + j.RConcave = theRadii.Find(ein); + j.RConvex = theRadii.Find(eout); + j.SupportAngle = ang; + out.Append(j); + } + } + return out; +} diff --git a/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatch.hxx b/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatch.hxx new file mode 100644 index 00000000..28bfe32d --- /dev/null +++ b/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatch.hxx @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: LGPL-2.1-only WITH OCCT-exception-1.0 +#ifndef _BRepFilletAPI_YPatch_HeaderFile +#define _BRepFilletAPI_YPatch_HeaderFile + +#include +#include +#include +#include +#include +#include +#include +#include + +//! Y transition between a concave and a convex constant-radius fillet whose edges meet, +//! tangentially or nearly so, at a vertex where their two non-shared support faces are +//! tangent or nearly tangent. +//! +//! Situation (the "Y junction"): edges Ein = T^A (concave) and Eout = T^B (convex) share the +//! face T and the vertex V; A and B meet at V along an unselected edge with a dihedral angle +//! close to 180 degrees. Two rolling-ball bands cannot meet there: one ball centre lies +//! outside the material, the other inside, and both claim the same wedge of T. +//! +//! Strategy: both bands stop at the cross-sections whose contacts on T coincide (P*); the +//! wedge between V and P* is covered by two G1 ribbons, each tangent to its own support +//! and band, tangent to each other along a seam from V to P*. Every other fillet, +//! including the far ends of these two bands, is computed by the standard algorithm. +class BRepFilletAPI_YPatch +{ +public: + //! One detected junction and, after Perform, its measured result. + struct Junction + { + TopoDS_Vertex Vertex; + TopoDS_Edge Concave, Convex; //!< Ein (T^A) and Eout (T^B) + TopoDS_Face Common, Concave2, Convex2; //!< T, A, B + Standard_Real RConcave = 0., RConvex = 0.; + Standard_Real SupportAngle = 0.; //!< angle between the A and B normals at V (radians) + gp_Pnt Split; //!< P*, where both bands touch T + Standard_Boolean Pinch = Standard_False; //!< built as a pinch, not a Y + Standard_Real SeamAngle = -1.; //!< max normal angle across the ribbon seam (radians) + Standard_Real BandAngle = -1.; //!< max normal angle ribbon/band and ribbon/support + Standard_Real EndAngle[2] = {-1., -1.}; //!< max normal angle at the band end: convex, concave + Standard_Real ContactAngle = -1.; //!< max normal angle ribbon/support along the contacts + }; + + //! Largest A/B support angle (radians) still treated as a junction (near tangency). + static constexpr Standard_Real MaxSupportAngle() { return 0.35; } // ~20 degrees + + //! Finds every junction among the constant-radius fillet edges in theRadii. + Standard_EXPORT static NCollection_Vector Detect(const TopoDS_Shape& theShape, + const TopTools_DataMapOfShapeReal& theRadii); + + //! Pinch instead of Y (thePinch): between V and P* both bands become rolling balls whose + //! radius shrinks to zero at V and whose contacts on T coincide, so they touch T and each + //! other along one curve (G1) and end together in V; no ribbon of their own. + //! Builds the filleted solid: theRadii holds every requested edge (each constant radius). + //! Returns false, leaving theResult untouched, when no junction exists or any step fails + //! (construction, sewing, validity, self-interference, continuity gate). theHistory maps + //! input sub-shapes to the result (Modified / Generated / Removed). + Standard_EXPORT static Standard_Boolean Perform(const TopoDS_Shape& theShape, + const TopTools_DataMapOfShapeReal& theRadii, + TopoDS_Shape& theResult, + Handle(BRepTools_History)& theHistory, + NCollection_Vector& theReport, + const Standard_Boolean thePinch = Standard_False); +}; + +#endif diff --git a/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatchBuild.cxx b/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatchBuild.cxx new file mode 100644 index 00000000..537585be --- /dev/null +++ b/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatchBuild.cxx @@ -0,0 +1,2277 @@ +// SPDX-License-Identifier: LGPL-2.1-only WITH OCCT-exception-1.0 +// Construction of the Y transition (see BRepFilletAPI_YPatch.hxx). +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace +{ +using namespace YPatch; +using V = gp_XYZ; +using Row = std::vector; +using Net = std::vector; + +constexpr int n = 23; // collocation nodes per direction +constexpr double pi = 3.14159265358979323846; + +void require(bool ok, const char* what) +{ + if (!ok) + throw Standard_Failure(what); +} + +// Cubic collocation: not-a-knot for the preliminary jets, clamped Hermite for the final +// tensor product (the construction validated by BRepFilletAPI_TangentY). +struct Spline +{ + std::vector t, k; + bool clamped; + math_Gauss lu; + + Spline(const std::vector& nodes, bool clamp) + : t(nodes), + k(4, 0.), + clamped(clamp), + lu(matrix()) + { + require(lu.IsDone(), "YPatch: singular collocation"); + } + + math_Matrix matrix() + { + for (int j = clamped ? 1 : 2; j < n - (clamped ? 1 : 2); ++j) + k.push_back(t[j]); + k.insert(k.end(), 4, 1.); + int m = int(k.size()) - 4; + math_Matrix a(1, m, 1, m, 0.); + for (int j = 0; j < n; ++j) + { + std::vector b(k.size(), 0.); + if (j == n - 1) + b[m - 1] = 1.; + else + { + for (int i = 0; i < m + 3; ++i) + b[i] = t[j] >= k[i] && t[j] < k[i + 1]; + for (int d = 1; d <= 3; ++d) + for (int i = 0; i < m + 3 - d; ++i) + { + double l = k[i + d] - k[i], r = k[i + d + 1] - k[i + 1]; + b[i] = (l ? (t[j] - k[i]) / l * b[i] : 0) + (r ? (k[i + d + 1] - t[j]) / r * b[i + 1] : 0); + } + } + for (int i = 0; i < m; ++i) + a(j + 1, i + 1) = b[i]; + } + if (clamped) + { + a(n + 1, 1) = -3 / k[4]; + a(n + 1, 2) = -a(n + 1, 1); + a(n + 2, m) = 3 / (1 - k[m - 1]); + a(n + 2, m - 1) = -a(n + 2, m); + } + return a; + } + + Row fit(const Row& values, const V& a = {}, const V& b = {}) const + { + int m = int(k.size()) - 4; + Row p(m); + for (int c = 1; c <= 3; ++c) + { + math_Vector x(1, m); + for (int i = 0; i < n; ++i) + x(i + 1) = values[i].Coord(c); + if (clamped) + { + x(n + 1) = a.Coord(c); + x(n + 2) = b.Coord(c); + } + lu.Solve(x); + for (int i = 0; i < m; ++i) + p[i].SetCoord(c, x(i + 1)); + } + return p; + } + + V jet(const Row& p, int end) const + { + int m = int(p.size()); + return end ? (p[m - 1] - p[m - 2]) * (3 / (1 - k[m - 1])) : (p[1] - p[0]) * (3 / k[4]); + } +}; + +std::vector nodes() +{ + std::vector t(n); + for (int i = 0; i < n; ++i) + t[i] = (1 - std::cos(pi * i / (n - 1))) / 2; + return t; +} + +//! Four-sided G1 ribbon: reference positions ref[i][j] at (t[i], t[j]) and the target normal +//! of each side (u=0, u=1 along v; v=0, v=1 along u). Cross-boundary derivatives are +//! projected into the target tangent planes; corner twists are averaged. +Handle(Geom_BSplineSurface) ribbon(const std::vector& t, + const Net& ref, + const std::array& normal, + const V& seam0, + const V& seam1) +{ + Spline basic(t, false), herm(t, true); + Net der(4, Row(n)), along(n, Row(n + 2)), dv(2); + for (int j = 0; j < n; ++j) + { + Row col(n); + for (int i = 0; i < n; ++i) + col[i] = ref[i][j]; + auto p = basic.fit(col), q = basic.fit(ref[j]); + for (int s = 0; s < 4; ++s) + { + V v = basic.jet(s < 2 ? p : q, s % 2), N = normal[s][j]; + der[s][j] = v - N * v.Dot(N); + } + } + // the v = 1 side is shared with the other ribbon: use the seam's exact end derivatives so + // that both ribbons interpolate the same seam curve + der[0][n - 1] = seam0; + der[1][n - 1] = seam1; + for (int j = 0; j < n; ++j) + { + Row col(n); + for (int i = 0; i < n; ++i) + col[i] = ref[i][j]; + along[j] = herm.fit(col, der[0][j], der[1][j]); + } + for (int end = 0; end < 2; ++end) + { + auto d = basic.fit(der[2 + end]); + V tw[2]; + for (int j = 0; j < 2; ++j) + tw[j] = (basic.jet(basic.fit(der[j]), end) + basic.jet(d, j)) * .5; + dv[end] = herm.fit(der[2 + end], tw[0], tw[1]); + } + TColgp_Array2OfPnt poles(1, n + 2, 1, n + 2); + for (int i = 0; i < n + 2; ++i) + { + Row col(n); + for (int j = 0; j < n; ++j) + col[j] = along[j][i]; + auto p = herm.fit(col, dv[0][i], dv[1][i]); + for (int j = 0; j < n + 2; ++j) + poles(i + 1, j + 1) = gp_Pnt(p[j]); + } + TColStd_Array1OfReal knots(1, n); + TColStd_Array1OfInteger mult(1, n); + for (int i = 0; i < n; ++i) + { + knots(i + 1) = t[i]; + mult(i + 1) = i == 0 || i == n - 1 ? 4 : 1; + } + return new Geom_BSplineSurface(poles, knots, knots, mult, mult, 3, 3); +} + +gp_Vec unit(const gp_Vec& v) +{ + const double m = v.Magnitude(); + require(m > 1e-14, "YPatch: degenerate direction"); + return v / m; +} + +// 3D vector a expressed in the uv tangent basis of S at uv (least squares). +gp_Vec2d toUV(const Support& S, const gp_Pnt2d& uv, const gp_Vec& a) +{ + gp_Pnt p; + gp_Vec du, dv; + S.s.D1(uv.X(), uv.Y(), p, du, dv); + const double g11 = du.Dot(du), g12 = du.Dot(dv), g22 = dv.Dot(dv); + const double b1 = a.Dot(du), b2 = a.Dot(dv), det = g11 * g22 - g12 * g12; + require(std::abs(det) > 1e-20, "YPatch: singular surface metric"); + return gp_Vec2d((g22 * b1 - g12 * b2) / det, (g11 * b2 - g12 * b1) / det); +} + +double cross2(const gp_XY& a, const gp_XY& b) +{ + return a.X() * b.Y() - a.Y() * b.X(); +} + +//! Everything computed for one junction. +struct Work +{ + const BRepFilletAPI_YPatch::Junction& j; + Support T, A, B; + Rail ri, ro; + Band bi, bo; + double l1 = 0, l2 = 0; + std::vector t; + std::vector in, out; // at the u nodes + Handle(Geom_BSplineSurface) rib[2]; // 0: convex side (B), 1: concave side (A) + Net refs[2]; // their collocation data + std::array nrms[2]; + V seam0, seam1; + Handle(Geom_Surface) bandSurf[2]; // the band each ribbon was fitted to (if refitted) + double endGap = 0; // pinch: canal end section vs the band end built + gp_Pnt2d keepOutT, keepOutA, keepOutB; + std::vector cuts; + std::vector fillers, fillerOf; // margin mode: strip faces and their supports + bool pinch = false; // pinch instead of Y (see PinchSections) + // margin mode, per side (0 convex, 1 concave): the offset points and the offset cut edge, + // and the filler's index, so that a pinch can rebuild its filler after refitting its end + std::vector marginOffset[2]; + TopoDS_Edge marginCut[2]; + int fillerIndex[2] = {-1, -1}; + + explicit Work(const BRepFilletAPI_YPatch::Junction& jj) + : j(jj), + T(jj.Common), + A(jj.Concave2), + B(jj.Convex2), + ri(jj.Concave, jj.Vertex), + ro(jj.Convex, jj.Vertex), + bi{ri, T, A, jj.RConcave, +1.}, + bo{ro, T, B, jj.RConvex, -1.}, + t(nodes()) + { + } + + // P*: the first crossing, from V, of the two contact curves on T. + void Split() + { + const int N = 128; + std::vector I(N + 1), O(N + 1); + for (int k = 0; k <= N; ++k) + { + require(bi.Solve(double(k) / N, I[k], k ? &I[k - 1] : nullptr), "YPatch: concave ball"); + require(bo.Solve(double(k) / N, O[k], k ? &O[k - 1] : nullptr), "YPatch: convex ball"); + } + double best = 1e300; + for (int a = 0; a < N; ++a) + for (int b = 0; b < N; ++b) + { + const gp_XY p = I[a].uvT.XY(), r = I[a + 1].uvT.XY() - p; + const gp_XY q = O[b].uvT.XY(), s = O[b + 1].uvT.XY() - q; + const double d = cross2(r, s); + if (std::abs(d) < 1e-300) + continue; + const double x = cross2(q - p, s) / d, y = cross2(q - p, r) / d; + if (x < 0 || x > 1 || y < 0 || y > 1) + continue; + const double key = a + x + b + y; + if (key < best) + { + best = key; + l1 = (a + x) / N; + l2 = (b + y) / N; + } + } + require(best < 1e299, "YPatch: the bands do not cross within the edges"); + // Newton on (l1, l2): equal contacts on T. + Ball a = I[std::min(N, int(l1 * N))], b = O[std::min(N, int(l2 * N))]; + for (int it = 0; it < 40; ++it) + { + Ball a0, b0; + require(bi.Solve(l1, a0, &a) && bo.Solve(l2, b0, &b), "YPatch: split balls"); + a = a0; + b = b0; + const gp_XY g = a.uvT.XY() - b.uvT.XY(); + if (a.pT.Distance(b.pT) < 1e-10 * (1 + bi.r)) + break; + const double h = 1e-7; + Ball a1, b1; + require(bi.Solve(l1 + h, a1, &a) && bo.Solve(l2 + h, b1, &b), "YPatch: split jacobian"); + const gp_XY ja = (a1.uvT.XY() - a.uvT.XY()) / h, jb = (b1.uvT.XY() - b.uvT.XY()) / -h; + const double det = cross2(ja, jb); + require(std::abs(det) > 1e-300, "YPatch: tangent contact curves at P*"); + l1 -= cross2(g, jb) / det; + l2 -= cross2(ja, g) / det; + require(l1 > 0 && l1 <= 1 && l2 > 0 && l2 <= 1, "YPatch: P* outside the edges"); + } + require(a.pT.Distance(b.pT) < 1e-8 * (1 + bi.r), "YPatch: P* did not converge"); + } + + // Sections at the u nodes (u=0: V, u=1: P*). + // The convex ball tangent to T at uvq (centre inside the material) and to B: its radius + // and its contact on B. + bool ConvexAt(const gp_Pnt2d& uvq, double& rho, gp_Pnt2d& uvB) const + { + const gp_Pnt q = T.P(uvq); + const gp_Vec nT = T.N(uvq); + for (int it = 0; it < 80; ++it) + { + const gp_Pnt c = q.Translated(nT * -rho); + uvB = B.UVNear(c, uvB); + const gp_Vec nB = B.N(uvB); + const double f = gp_Vec(B.P(uvB), c).Dot(nB) + rho, df = 1 - nT.Dot(nB); + if (std::abs(f) < 1e-12 * (1 + rho)) + return rho > 0; + if (std::abs(df) < 1e-9) + return false; + rho = std::max(0.5 * rho, rho - f / df); + } + return false; + } + + // The concave ball tangent to T at uvq (centre outside the material) and to A. + bool ConcaveAt(const gp_Pnt2d& uvq, double& rho, gp_Pnt2d& uvA) const + { + const gp_Pnt q = T.P(uvq); + const gp_Vec nT = T.N(uvq); + for (int it = 0; it < 80; ++it) + { + const gp_Pnt c = q.Translated(nT * rho); + uvA = A.UVNear(c, uvA); + const gp_Vec nA = A.N(uvA); + const double f = gp_Vec(A.P(uvA), c).Dot(nA) - rho, df = nT.Dot(nA) - 1; + if (std::abs(f) < 1e-12 * (1 + rho)) + return rho > 0; + if (std::abs(df) < 1e-9) + return false; + rho = std::max(0.5 * rho, rho - f / df); + } + return false; + } + + // Pinch: between V and P* the two bands are rolling balls of variable radius whose contacts + // on T coincide along one shared curve. The curve is defined by the radius laws + // rho_in = r_in h(s), rho_out = r_out g(s), s in [0, 1] from V to P*, + // each point being the one on T whose concave ball (tangent to T there and to A) and convex + // ball (tangent to T there and to B) have these radii. Both radii positive keeps it inside + // T's wedge; h, g ~ s^2 at V make it leave V regularly between the two edges. At P* a + // law with zero slope makes that band G1 to its constant-radius band (a ball tangent to T at + // q has a radius fixed by q and the two contact lines cross at P*, so not both can be): + // pinchDir 0 (default, the owner's choice, as in Plasticity's Y-off): the convex band is G1, the + // crease goes to the concave side; 1: balanced slopes (smallest largest crease); 2: concave G1. + int pinchDir = 0; + + static void law(int kind, double s, double& f) + { + // kind 0: zero slope at 1; kind 1: slope 1 at 1. Both ~ s^2 at 0 (the two radii add up + // to the wedge's width, ~ x^2 / 2R at a tangent junction), f(1) = 1, increasing. + f = kind == 0 ? s * s * (1 + 2 * s - 2 * s * s) : s * s * (1 + s - s * s); + } + + void PinchSections() + { + in.assign(n, Ball()); + out.assign(n, Ball()); + Ball a, b; + require(bi.Solve(l1, a) && bo.Solve(l2, b), "YPatch: pinch end balls"); + const int kIn = pinchDir == 2 ? 0 : 1; + const int kOut = pinchDir == 0 ? 0 : 1; + gp_Pnt2d uv = a.uvT, uvA = a.uvX, uvB = b.uvX; + double rIn = bi.r, rOut = bo.r; + for (int i = n - 2; i >= 1; --i) // from P* back to V, warm-started + { + double h, g; + law(kIn, t[i], h); + law(kOut, t[i], g); + const double wantIn = bi.r * h, wantOut = bo.r * g; + // Newton on uv: (rho_in / wantIn - 1, rho_out / wantOut - 1) = 0 + auto F = [&](const gp_Pnt2d& x, double& ri, double& ro, gp_Pnt2d& ua, gp_Pnt2d& ub, gp_XY& f) { + const double ri0 = ri, ro0 = ro; + const bool okA = ConcaveAt(x, ri, ua), okB = okA && ConvexAt(x, ro, ub); +#ifdef YPATCH_TRACE + if (!okB) + std::printf("YPatch: pinch node %d uv (%g %g) concave %d (%g -> %g) convex (%g -> %g)\n", i, x.X(), x.Y(), + (int)okA, ri0, ri, ro0, ro); +#endif + if (!okB) + return false; + f = gp_XY(ri / wantIn - 1, ro / wantOut - 1); + return true; + }; + // first guess: the previous point drawn towards V by the square root of the radius ratio + // (exact at a tangent junction; elsewhere it errs away from V, where the wedge is wider) + const gp_Pnt2d uvV = ri.UV(T.face, 0); + if (i < n - 2) + { + double h1, g1; + law(kIn, t[i + 1], h1); + law(kOut, t[i + 1], g1); + const double ratio = std::sqrt((h + g) / (h1 + g1)); + // along the bisector of the edges linearly, across it quadratically: the wedge of a + // tangent junction narrows like x^2, so a straight scaling would leave it + gp_XY along = toUV(T, uvV, unit(ri.T(0) + ro.T(0))).XY(); + along /= along.Modulus(); + const gp_XY across(-along.Y(), along.X()); + const gp_XY d = in[i + 1].uvT.XY() - uvV.XY(); + uv = gp_Pnt2d(uvV.XY() + along * (d * along * ratio) + across * (d * across * ratio * ratio)); + } + rIn = wantIn; + rOut = wantOut; + gp_XY f; + bool done = false; + for (int it = 0; it < 60 && !done; ++it) + { + double ri = rIn, ro = rOut; + gp_Pnt2d ua = uvA, ub = uvB; + require(F(uv, ri, ro, ua, ub, f), "YPatch: pinch balls"); + rIn = ri; + rOut = ro; + uvA = ua; + uvB = ub; +#ifdef YPATCH_TRACE + if (std::getenv("YPATCH_PINCH_TRACE")) + std::printf("YPatch: node %d it %d |f| %.3e uv (%.9g %.9g) r %.4g %.4g\n", i, it, f.Modulus(), uv.X(), uv.Y(), rIn, rOut); +#endif + if (f.Modulus() < 1e-8) // (relative to radii: 1e-11 mm near V) + { + done = true; + break; + } + // finite-difference jacobian in uv, step at the scale of the radii + gp_Pnt p; + gp_Vec du, dv; + T.s.D1(uv.X(), uv.Y(), p, du, dv); + const double hs = 1e-4 * std::max(1e-9, std::min(wantIn, wantOut)); + const double hu = hs / std::max(du.Magnitude(), 1e-12), hv = hs / std::max(dv.Magnitude(), 1e-12); + gp_XY fu, fv; + double r1 = rIn, r2 = rOut; + gp_Pnt2d a1 = uvA, b1 = uvB; + require(F(gp_Pnt2d(uv.X() + hu, uv.Y()), r1, r2, a1, b1, fu), "YPatch: pinch jacobian"); + r1 = rIn, r2 = rOut, a1 = uvA, b1 = uvB; + require(F(gp_Pnt2d(uv.X(), uv.Y() + hv), r1, r2, a1, b1, fv), "YPatch: pinch jacobian"); + const gp_XY ju = (fu - f) / hu, jv = (fv - f) / hv; + const double det = ju.X() * jv.Y() - ju.Y() * jv.X(); + require(std::abs(det) > 1e-300, "YPatch: pinch jacobian singular"); + double dx = -(f.X() * jv.Y() - f.Y() * jv.X()) / det, dy = -(ju.X() * f.Y() - ju.Y() * f.X()) / det; + // stay at the scale of the radii per step + const double step = (du * dx + dv * dy).Magnitude(), + cap = std::max(0.5 * (wantIn + wantOut), 0.25 * p.Distance(this->ri.P(0))); + if (step > cap) + { + dx *= cap / step; + dy *= cap / step; + } + // backtrack until both balls exist (the wedge is narrow near V) + bool moved = false; + for (int bt = 0; bt < 40 && !moved; ++bt, dx *= 0.5, dy *= 0.5) + { + double r1 = rIn, r2 = rOut; + gp_Pnt2d a1 = uvA, b1 = uvB; + gp_XY ft; + const gp_Pnt2d next(uv.X() + dx, uv.Y() + dy); + if (ConcaveAt(next, r1, a1) && ConvexAt(next, r2, b1)) + { + uv = next; + moved = true; + } + } + require(moved, "YPatch: pinch step"); + } + require(done, "YPatch: pinch curve did not converge"); + const gp_Pnt q = T.P(uv); + const gp_Vec nT = T.N(uv); + in[i].lambda = out[i].lambda = t[i]; + in[i].uvT = out[i].uvT = uv; + in[i].pT = out[i].pT = q; + in[i].uvX = uvA; + in[i].pX = A.P(uvA); + in[i].c = q.Translated(nT * rIn); + out[i].uvX = uvB; + out[i].pX = B.P(uvB); + out[i].c = q.Translated(nT * -rOut); + } + in[n - 1] = a; // (the same balls: keep the band ends bit-exact) + out[n - 1] = b; + out[n - 1].pT = a.pT; + out[n - 1].uvT = a.uvT; + // V: both sections are the point V + const gp_Pnt v = ri.P(0); + in[0].uvT = out[0].uvT = ri.UV(T.face, 0); + in[0].uvX = ri.UV(A.face, 0); + out[0].uvX = ro.UV(B.face, 0); + in[0].pT = in[0].pX = in[0].c = out[0].pT = out[0].pX = out[0].c = v; + } + + // Exact canal surface of one pinch band: every u-section is the circular arc of its ball + // from the contact on the support (v = 0) to the shared point on T (v = 1), a rational + // quadratic. Only 1D data are interpolated along u (the homogeneous rows: both contacts, + // and weight * middle pole with the weight), so nothing folds where the radius vanishes; + // the side u = 0 is the apex V. + Handle(Geom_BSplineSurface) Canal(int k) const + { + const std::vector& bs = k ? in : out; + const Support& X = k ? A : B; + const double sg = k ? 1. : -1.; // centre side of T + Row P0(n), WP1(n), P2(n), W(n); + for (int i = 0; i < n; ++i) + { + gp_Vec eq, ex; + double rho; + if (i == 0) + { + eq = T.N(bs[0].uvT) * -sg; + ex = X.N(bs[0].uvX) * -sg; + rho = 0; + } + else + { + rho = bs[i].c.Distance(bs[i].pT); + eq = gp_Vec(bs[i].c, bs[i].pT) / rho; + ex = gp_Vec(bs[i].c, bs[i].pX) / rho; + } + const double th = eq.Angle(ex), w = std::cos(th / 2); + require(w > 1e-3, "YPatch: pinch section too open"); + const gp_Vec mid = unit(eq + ex); + const gp_XYZ m = bs[i].c.XYZ() + mid.XYZ() * (rho / w); + P0[i] = bs[i].pX.XYZ(); + P2[i] = bs[i].pT.XYZ(); + WP1[i] = m * w; + W[i] = V(w, 0, 0); + } + Spline basic(t, false); + const Row c0 = basic.fit(P0), c1 = basic.fit(WP1), c2 = basic.fit(P2), cw = basic.fit(W); + const int m = int(c0.size()); + TColgp_Array2OfPnt poles(1, m, 1, 3); + TColStd_Array2OfReal weights(1, m, 1, 3); + for (int i = 0; i < m; ++i) + { + const double w = cw[i].X(); + require(w > 1e-6, "YPatch: pinch weight"); + poles(i + 1, 1) = gp_Pnt(c0[i]); + poles(i + 1, 2) = gp_Pnt(c1[i] / w); + poles(i + 1, 3) = gp_Pnt(c2[i]); + weights(i + 1, 1) = 1; + weights(i + 1, 2) = w; + weights(i + 1, 3) = 1; + } + // the not-a-knot knots of Spline (clamped = false) + std::vector ku{0.}; + std::vector mu{4}; + for (int j = 2; j < n - 2; ++j) + { + ku.push_back(t[j]); + mu.push_back(1); + } + ku.push_back(1.); + mu.push_back(4); + TColStd_Array1OfReal uk(1, int(ku.size())), vk(1, 2); + TColStd_Array1OfInteger um(1, int(mu.size())), vm(1, 2); + for (int j = 0; j < int(ku.size()); ++j) + { + uk(j + 1) = ku[j]; + um(j + 1) = mu[j]; + } + vk(1) = 0; + vk(2) = 1; + vm(1) = vm(2) = 3; + return new Geom_BSplineSurface(poles, weights, uk, vk, um, vm, 3, 2); + } + + void Sections() + { + if (pinch) + { + PinchSections(); + return; + } + in.resize(n); + out.resize(n); + for (int i = 0; i < n; ++i) + { + require(bi.Solve(t[i] * l1, in[i], i ? &in[i - 1] : nullptr), "YPatch: ribbon ball (concave)"); + require(bo.Solve(t[i] * l2, out[i], i ? &out[i - 1] : nullptr), "YPatch: ribbon ball (convex)"); + } + } + + void Ribbons() + { + if (pinch) + { + rib[0] = Canal(0); + rib[1] = Canal(1); + return; + } + const gp_Pnt v = ri.P(0); + const gp_Pnt2d uvV = ri.UV(T.face, 0), uvS = in[n - 1].uvT; + const gp_Pnt pS = T.P(uvS); + const double L = v.Distance(pS); + // seam on T: cubic Hermite in uv, leaving V along the bisector of the two edges and + // reaching P* along the bisector of the two contact curves. + auto contactTangent = [&](const Band& band, double l, const Ball& seed) { + Ball a, b; + require(band.Solve(l - 1e-6, a, &seed) && band.Solve(l, b, &seed), "YPatch: contact tangent"); + return unit(gp_Vec(a.pT, b.pT)); + }; + const gp_Vec t0 = unit(ri.T(0) + ro.T(0)) * L; + const gp_Vec t1 = unit(contactTangent(bi, l1, in[n - 1]) + contactTangent(bo, l2, out[n - 1])) * L; + const gp_Vec2d d0 = toUV(T, uvV, t0), d1 = toUV(T, uvS, t1); + auto seam = [&](double u, gp_Vec* der) { + const double h00 = 2 * u * u * u - 3 * u * u + 1, h10 = u * u * u - 2 * u * u + u; + const double h01 = -2 * u * u * u + 3 * u * u, h11 = u * u * u - u * u; + const gp_XY uv = uvV.XY() * h00 + d0.XY() * h10 + uvS.XY() * h01 + d1.XY() * h11; + if (der) + { + const double g00 = 6 * u * u - 6 * u, g10 = 3 * u * u - 4 * u + 1, g01 = -6 * u * u + 6 * u, + g11 = 3 * u * u - 2 * u; + const gp_XY d = uvV.XY() * g00 + d0.XY() * g10 + uvS.XY() * g01 + d1.XY() * g11; + gp_Pnt p; + gp_Vec du, dv; + T.s.D1(uv.X(), uv.Y(), p, du, dv); + *der = du * d.X() + dv * d.Y(); + } + return gp_Pnt2d(uv); + }; + const gp_Vec nV = unit(A.N(ri.UV(A.face, 0)) + B.N(ro.UV(B.face, 0))); + const double rr = 0.5 * (bi.r + bo.r); + std::vector q(n); + std::vector N(n), Qd(n); + gp_Vec qd0, qd1; + seam(0., &qd0); + seam(1., &qd1); + for (int i = 0; i < n; ++i) + { + gp_Vec d; + const gp_Pnt2d uv = seam(t[i], &d); + q[i] = T.P(uv); + const double u = t[i], dz = rr * (1 - u * u) / 2; + gp_Vec w = nV * dz + T.N(uv) * (rr * u * u); + const gp_Vec e = unit(d); + N[i] = unit(w - e * w.Dot(e)); + Qd[i] = d; + } + q[0] = v; + q[n - 1] = pS; + if (pinch) + { + // the seam is the common contact curve on T, and the ribbons are tangent to T along it + Spline basic(t, false); + Row qs(n); + for (int i = 0; i < n; ++i) + { + q[i] = in[i].pT; + qs[i] = q[i].XYZ(); + N[i] = T.N(in[i].uvT); + } + const Row c = basic.fit(qs); + qd0 = gp_Vec(basic.jet(c, 0)); + qd1 = gp_Vec(basic.jet(c, 1)); + for (int i = 0; i < n; ++i) + Qd[i] = i == 0 ? qd0 : i == n - 1 ? qd1 : gp_Vec(q[i - 1], q[i + 1]) / (t[i + 1] - t[i - 1]); + } + for (int k = 0; k < 2; ++k) + { + const Support& X = k ? A : B; + const std::vector& bs = k ? in : out; + const gp_Pnt c1 = bs[n - 1].c; + Net ref(n, Row(n)); + std::array nrm{Row(n), Row(n), Row(n), Row(n)}; + for (int i = 0; i < n; ++i) + { + const gp_Pnt p = bs[i].pX; + const gp_Vec ns = X.N(bs[i].uvX); + const gp_Vec D(p, q[i]); + if (pinch && D.Magnitude() < 1e-12) // V: the section is a point + { + for (int jj = 0; jj < n; ++jj) + ref[i][jj] = p.XYZ(); + nrm[2][i] = ns.XYZ(); + nrm[3][i] = N[i].XYZ(); + continue; + } + gp_Pnt m = gp_Pnt((p.XYZ() + q[i].XYZ()) / 2); + double w = std::sqrt(.5); + bool exact = false; // the circular section exists (tangent lines meet ahead) + if (D.Magnitude() > 1e-12 && ns.Crossed(D).Magnitude() > 1e-9 * D.Magnitude()) + { + const gp_Vec pl = unit(ns.Crossed(D)); + gp_Vec tp = unit(pl.Crossed(ns)); + if (tp.Dot(D) < 0) + tp.Reverse(); + gp_Vec nq = N[i] - pl * N[i].Dot(pl); + if (nq.Magnitude() > 1e-9) + { + gp_Vec tq = unit(pl.Crossed(nq)); + if (tq.Dot(D) > 0) + tq.Reverse(); + // p + a tp = q + b tq + const double c = tp.Dot(tq), det = c * c - 1; + if (std::abs(det) > 1e-8) + { + const double a = (D.Dot(tq) * c - D.Dot(tp)) / det, b = (D.Dot(tq) - c * D.Dot(tp)) / det; + if (a > 0 && b > 0) + { + m = p.Translated(tp * a); + const gp_Vec e1(m, p), e2(m, q[i]); + if (e1.Magnitude() > 1e-12 && e2.Magnitude() > 1e-12) + { + w = std::sin(e1.Angle(e2) / 2); + exact = true; + } + } + } + } + } + // Cubic section: leaves p inside the support, arrives at q straight across the seam + // (the two ribbons arrive from opposite sides). Near the bands it blends into the + // exact circular section, which the band end requires. + gp_Vec tp = D - ns * D.Dot(ns), tq = N[i].Crossed(Qd[i]); + const bool cubic = tp.Magnitude() > 1e-12 && tq.Magnitude() > 1e-12; + if (cubic) + { + tp.Normalize(); + tq.Normalize(); + if (tq.Dot(D) < 0) + tq.Reverse(); + } + const double th = cubic ? std::min(tp.Angle(tq), 2.5) : 0.; + const double alpha = th > 1e-4 ? 4. / 3. * std::tan(th / 4) * D.Magnitude() / (2 * std::sin(th / 2)) + : D.Magnitude() / 3; + // (pinch sections are exact circles all along) + const double u = t[i], s = !exact ? 0. : pinch || u >= 1. ? 1. : u <= .6 ? 0. : [](double x) { + return x * x * (3 - 2 * x); + }((u - .6) / .4); + require(!pinch || exact, "YPatch: pinch section is not circular"); + require(cubic || exact, "YPatch: degenerate ribbon section"); + for (int jj = 0; jj < n; ++jj) + { + const double vv = t[jj], a = (1 - vv) * (1 - vv), b = 2 * w * vv * (1 - vv), c = vv * vv; + const V con = (p.XYZ() * a + m.XYZ() * b + q[i].XYZ() * c) / (a + b + c); + V cub = con; + if (cubic) + { + const double o = 1 - vv; + cub = p.XYZ() * (o * o * o) + (p.XYZ() + tp.XYZ() * alpha) * (3 * o * o * vv) + + (q[i].XYZ() - tq.XYZ() * alpha) * (3 * o * vv * vv) + q[i].XYZ() * (vv * vv * vv); + } + ref[i][jj] = cub * (1 - s) + con * s; + } + require(i < n - 1 || exact, "YPatch: no circular section at the band end"); + nrm[2][i] = ns.XYZ(); + nrm[3][i] = N[i].XYZ(); + } + // u = 0 lies on the support, u = 1 on the band. + for (int jj = 0; jj < n; ++jj) + { + const gp_Pnt2d uv = X.UVNear(gp_Pnt(ref[0][jj]), bs[0].uvX); + ref[0][jj] = X.P(uv).XYZ(); + nrm[0][jj] = pinch ? V() : X.N(uv).XYZ(); // (pinch: the foot is the point V) + nrm[1][jj] = unit(gp_Vec(c1, gp_Pnt(ref[n - 1][jj]))).XYZ(); + } + rib[k] = ribbon(t, ref, nrm, qd0.XYZ(), qd1.XYZ()); + refs[k] = ref; + nrms[k] = nrm; + seam0 = qd0.XYZ(); + seam1 = qd1.XYZ(); + } + } + + // Edges that cut V's wedge out of T, A and B; interior points of the removed pieces. + + // The standard algorithm ends each band on its own (possibly approximated) spine: refit the + // ribbons' band-side row (u = 1) to the band end it actually built. The other three sides, + // which the cuts already use, keep their data. + void FitBandEnds(const TopoDS_Shape& filleted) + { + if (pinch) + { + // On a non-analytic support the standard algorithm builds an approximated band whose end + // misses the exact section (its foot by ~1e-3 r): end the canals on the band ends built + // (circle through their ends and middle; one common point on T), and rebuild the fillers + // along the new contact lines. + { + TopTools_IndexedDataMapOfShapeListOfShape ef; + TopExp::MapShapesAndAncestors(filleted, TopAbs_EDGE, TopAbs_FACE, ef); + gp_Pnt foot[2], top[2], middle[2]; + bool found[2] = {false, false}; + for (int k = 0; k < 2; ++k) + { + const Ball& b = (k ? in : out)[n - 1]; + const double tol = 1e-2 * (k ? bi.r : bo.r); + double bulge = 0; + for (int i = 1; i <= ef.Extent(); ++i) + { + if (ef(i).Extent() != 1) + continue; + BRepAdaptor_Curve c(TopoDS::Edge(ef.FindKey(i))); + const gp_Pnt a = c.Value(c.FirstParameter()), z = c.Value(c.LastParameter()); + const gp_Pnt mm = c.Value((c.FirstParameter() + c.LastParameter()) / 2); + const double bl = mm.Distance(gp_Pnt((a.XYZ() + z.XYZ()) / 2)); + for (int flip = 0; flip < 2; ++flip) + { + const gp_Pnt& f = flip ? z : a; + const gp_Pnt& q = flip ? a : z; + if (f.Distance(b.pX) < tol && q.Distance(b.pT) < tol && bl > bulge) + { + bulge = bl; + foot[k] = f; + top[k] = q; + middle[k] = mm; + found[k] = true; + } + } + } + } + bool moved = false; + for (int k = 0; k < 2; ++k) + moved = moved || (found[k] && (foot[k].Distance((k ? in : out)[n - 1].pX) > 1e-7 + || top[k].Distance((k ? in : out)[n - 1].pT) > 1e-7)); + if (moved && found[0] && found[1]) + { + const gp_Pnt q((top[0].XYZ() + top[1].XYZ()) / 2); + for (int k = 0; k < 2; ++k) + { + Ball& b = (k ? in : out)[n - 1]; + // circumcentre of foot, middle, q + const gp_Vec ab(foot[k], middle[k]), ac(foot[k], q); + const gp_Vec nn = ab.Crossed(ac); + require(nn.SquareMagnitude() > 1e-20, "YPatch: pinch end circle"); + const gp_XYZ cc = foot[k].XYZ() + + (nn.Crossed(ab) * ac.SquareMagnitude() + ac.Crossed(nn) * ab.SquareMagnitude()).XYZ() + / (2 * nn.SquareMagnitude()); + b.pX = foot[k]; + b.pT = q; + b.c = gp_Pnt(cc); + } + rib[0] = Canal(0); + rib[1] = Canal(1); + // fillers along the new contact lines (margin mode) + for (int k = 0; k < 2; ++k) + { + if (fillerIndex[k] < 0) + continue; + const Support& X = k ? A : B; + const std::vector& bs = k ? in : out; + Handle(Geom_Curve) C = rib[k]->VIso(0.); + const auto& o = marginOffset[k]; + const int m = int(o.size()); + std::vector c(m); + for (int i = 0; i < m; ++i) + c[i] = X.UVNear(C->Value(double(i) / (m - 1)), bs[std::min(n - 1, int(double(i) / (m - 1) * (n - 1)))].uvX); + auto onX = [&](const Handle(Geom2d_Curve)& cv) { + TopoDS_Edge e = BRepBuilderAPI_MakeEdge(cv, BRep_Tool::Surface(X.face)).Edge(); + BRepLib::BuildCurves3d(e); + return e; + }; + Handle(TColgp_HArray1OfPnt2d) h = new TColgp_HArray1OfPnt2d(1, m); + for (int i = 0; i < m; ++i) + h->SetValue(i + 1, c[i]); + Geom2dAPI_Interpolate ip(h, Standard_False, 1e-12); + ip.Perform(); + require(ip.IsDone(), "YPatch: pinch filler curve"); + BRepBuilderAPI_MakeWire mw; + mw.Add(onX(ip.Curve())); + mw.Add(onX(GCE2d_MakeSegment(c[m - 1], o[m - 1]).Value())); + mw.Add(marginCut[k]); + mw.Add(onX(GCE2d_MakeSegment(o[0], c[0]).Value())); + require(mw.IsDone(), "YPatch: pinch filler wire"); + TopoDS_Face f = BRepBuilderAPI_MakeFace(BRep_Tool::Surface(X.face), mw.Wire(), Standard_True).Face(); + ShapeFix_Face fix(f); + fix.Perform(); + fillers[fillerIndex[k]] = fix.Face(); + } + } + } + // the canals end on the exact end sections: measure how far the band ends the standard + // algorithm built (approximated on non-analytic supports) are from them + endGap = 0; + for (int k = 0; k < 2; ++k) + { + // distance of the canal's end section to the shell built: the band end is on it + Handle(Geom_Curve) end = rib[k]->UIso(1.); + for (int j = 0; j <= 16; ++j) + { + BRepExtrema_DistShapeShape d(BRepBuilderAPI_MakeVertex(end->Value(j / 16.)).Vertex(), filleted); + require(d.IsDone(), "YPatch: pinch end gap"); + endGap = std::max(endGap, d.Value()); + } + } +#ifdef YPATCH_TRACE + std::printf("YPatch: pinch end gap %.3e\n", endGap); +#endif + return; + } + TopTools_IndexedDataMapOfShapeListOfShape ef; + TopExp::MapShapesAndAncestors(filleted, TopAbs_EDGE, TopAbs_FACE, ef); + const gp_Pnt split = in[n - 1].pT; + for (int k = 0; k < 2; ++k) + { + const gp_Pnt foot = (k ? in : out)[n - 1].pX; + TopoDS_Edge best; + TopoDS_Face band; + double bulge = 0; + for (int i = 1; i <= ef.Extent(); ++i) + { + if (ef(i).Extent() != 1) + continue; + const TopoDS_Edge e = TopoDS::Edge(ef.FindKey(i)); + BRepAdaptor_Curve c(e); + const gp_Pnt a = c.Value(c.FirstParameter()), z = c.Value(c.LastParameter()); + const bool fits = (a.Distance(foot) < 1e-3 && z.Distance(split) < 1e-3) + || (z.Distance(foot) < 1e-3 && a.Distance(split) < 1e-3); + const gp_Pnt m = c.Value((c.FirstParameter() + c.LastParameter()) / 2); + const double b = m.Distance(gp_Pnt((a.XYZ() + z.XYZ()) / 2)); + if (fits && b > bulge) + { + bulge = b; + best = e; + band = TopoDS::Face(ef(i).First()); + } + } + if (best.IsNull()) + continue; + // node positions by arc length, from the support (v = 0) to the seam (v = 1) + Net& ref = refs[k]; + std::vector s(n, 0.); + for (int j = 1; j < n; ++j) + s[j] = s[j - 1] + (ref[n - 1][j] - ref[n - 1][j - 1]).Modulus(); + BRepAdaptor_Curve c(best); + const bool forward = c.Value(c.FirstParameter()).Distance(foot) < c.Value(c.LastParameter()).Distance(foot); + const double length = GCPnts_AbscissaPoint::Length(c); + Handle(Geom_Surface) surf = BRep_Tool::Surface(band); + for (int j = 1; j < n - 1; ++j) + { + const double d = length * s[j] / s[n - 1]; + GCPnts_AbscissaPoint ap(c, forward ? d : -d, forward ? c.FirstParameter() : c.LastParameter()); + require(ap.IsDone(), "YPatch: band end abscissa"); + const gp_Pnt p = c.Value(ap.Parameter()); + GeomAPI_ProjectPointOnSurf pr(p, surf); + require(pr.NbPoints() > 0, "YPatch: band end normal"); + double u, v; + pr.LowerDistanceParameters(u, v); + GeomLProp_SLProps lp(surf, u, v, 1, 1e-12); + require(lp.IsNormalDefined(), "YPatch: band end normal"); + ref[n - 1][j] = p.XYZ(); + nrms[k][1][j] = lp.Normal().XYZ(); + } + rib[k] = ribbon(t, ref, nrms[k], seam0, seam1); + bandSurf[k] = surf; + } + } + + // margin = false: A and B are cut along the ribbons' support boundaries. That free edge + // continues the band's own contact line, tangentially: when the standard algorithm ends + // the band on an approximated spine, its end can slide along it. margin = true: A and B + // are cut a little further from the edge, so the band end meets its free boundary + // transversally; the strip between the contact line and the cut is given back as a + // `filler` face on the support's own surface. + void Cuts(bool margin) + { + cuts.clear(); + fillers.clear(); + fillerOf.clear(); + auto onFace = [](const Support& S, const Handle(Geom2d_Curve)& c) { + TopoDS_Edge e = BRepBuilderAPI_MakeEdge(c, BRep_Tool::Surface(S.face)).Edge(); + BRepLib::BuildCurves3d(e); + return e; + }; + auto segment = [&](const Support& S, const gp_Pnt2d& a, const gp_Pnt2d& b) { + return onFace(S, GCE2d_MakeSegment(a, b).Value()); + }; + auto through = [&](const Support& S, const std::vector& pts) { + Handle(TColgp_HArray1OfPnt2d) h = new TColgp_HArray1OfPnt2d(1, int(pts.size())); + for (std::size_t i = 0; i < pts.size(); ++i) + h->SetValue(int(i) + 1, pts[i]); + Geom2dAPI_Interpolate ip(h, Standard_False, 1e-12); + ip.Perform(); + require(ip.IsDone(), "YPatch: margin curve"); + Handle(Geom2d_Curve) c = ip.Curve(); + return onFace(S, c); + }; + auto iso = [](const Handle(Geom_Curve)& c) { + return BRepBuilderAPI_MakeEdge(c).Edge(); + }; + const Ball& a = in[n - 1]; + const Ball& b = out[n - 1]; + // Each band ends at a free-boundary vertex whose two free edges hold its end section: + // the standard algorithm cuts the supports there. + cuts.push_back(segment(T, ri.UV(T.face, l1), a.uvT)); + cuts.push_back(segment(T, ro.UV(T.face, l2), b.uvT)); + if (!margin) + { + cuts.push_back(segment(A, ri.UV(A.face, l1), a.uvX)); + cuts.push_back(segment(B, ro.UV(B.face, l2), b.uvX)); + // ribbon boundaries on the supports: v = 0 (contact curve) and u = 0 (back to V) + if (pinch) + { + // the contact curves leave V tangentially to the edges: start them on V itself, so + // that the cut need not be found by intersection there + for (int k = 1; k >= 0; --k) + { + Handle(Geom_Curve) C = rib[k]->VIso(0.); + cuts.push_back(BRepBuilderAPI_MakeEdge(C, j.Vertex, BRepBuilderAPI_MakeVertex(C->Value(1.)).Vertex()).Edge()); + } + } + else + { + cuts.push_back(iso(rib[1]->VIso(0.))); + cuts.push_back(iso(rib[0]->VIso(0.))); + } + if (!pinch) // (a pinch has no foot: its ribbons end in the point V) + { + cuts.push_back(iso(rib[1]->UIso(0.))); + cuts.push_back(iso(rib[0]->UIso(0.))); + } + } + else + for (int k = 0; k < 2; ++k) + { + const Support& X = k ? A : B; + const Rail& rail = k ? ri : ro; + const double l = k ? l1 : l2, d = 0.1 * (k ? bi.r : bo.r); + const std::vector& bs = k ? in : out; + Handle(Geom_Curve) C = rib[k]->VIso(0.); + const int m = 33; + std::vector c(m), o(m); + gp_XY lastAway; // (a pinch's contact meets its edge at V) + for (int i = m - 1; i >= 0; --i) + { + const double u = double(i) / (m - 1); + c[i] = X.UVNear(C->Value(u), bs[std::min(n - 1, int(u * (n - 1)))].uvX); + // away from the edge: from its nearest point (a pinch's contacts are not indexed + // by the convex rail's own parameter) + double lam = u * l; + if (pinch) + { + Extrema_ExtPC ext(C->Value(u), rail.c); + double best = 1e300; + for (int e = 1; ext.IsDone() && e <= ext.NbExt(); ++e) + if (ext.SquareDistance(e) < best) + { + best = ext.SquareDistance(e); + lam = (ext.Point(e).Parameter() - rail.first) / (rail.last - rail.first); + } + } + gp_XY away = c[i].XY() - rail.UV(X.face, lam).XY(); + gp_Pnt p; + gp_Vec du, dv; + X.s.D1(c[i].X(), c[i].Y(), p, du, dv); + double s = (du * away.X() + dv * away.Y()).Magnitude(); + if (pinch && s < 1e-6 * d && lastAway.Modulus() > 0) + { + away = lastAway; + s = (du * away.X() + dv * away.Y()).Magnitude(); + } + require(s > 1e-12, "YPatch: margin direction"); + away /= s; + lastAway = away; + o[i] = gp_Pnt2d(c[i].XY() + away * d); + } + // the cuts: section line beyond the band end, the offset of the contact line, the + // line from V beyond the ribbon's foot + cuts.push_back(segment(X, rail.UV(X.face, l), o[m - 1])); + cuts.push_back(through(X, o)); + marginOffset[k] = o; + marginCut[k] = cuts.back(); + if (!pinch) // (a pinch's foot is the point V) + cuts.push_back(iso(rib[k]->UIso(0.))); // the ribbon's foot, V to the contact line + cuts.push_back(segment(X, c[0], o[0])); + // the strip between the contact line and the cut, on X's surface + BRepBuilderAPI_MakeWire mw; + mw.Add(through(X, c)); + mw.Add(segment(X, c[m - 1], o[m - 1])); + mw.Add(cuts[cuts.size() - (pinch ? 2 : 3)]); + mw.Add(segment(X, o[0], c[0])); + require(mw.IsDone(), "YPatch: margin wire"); + TopoDS_Face f = BRepBuilderAPI_MakeFace(BRep_Tool::Surface(X.face), mw.Wire(), Standard_True).Face(); + ShapeFix_Face fix(f); + fix.Perform(); + fillerIndex[k] = int(fillers.size()); + fillers.push_back(fix.Face()); + fillerOf.push_back(X.face); + } + keepOutT = gp_Pnt2d((ri.UV(T.face, l1 / 2).XY() + ro.UV(T.face, l2 / 2).XY()) / 2); + if (pinch) // the strips narrow towards V: probe at a node, between edge and contact + { + const int i = n / 2; + keepOutA = gp_Pnt2d((ri.UV(A.face, t[i] * l1).XY() + in[i].uvX.XY()) / 2); + keepOutB = gp_Pnt2d((B.UVNear(out[i].pT, out[i].uvX).XY() + out[i].uvX.XY()) / 2); + return; + } + Ball m1, m2; + require(bi.Solve(l1 / 2, m1, &in[n / 2]) && bo.Solve(l2 / 2, m2, &out[n / 2]), "YPatch: probe"); + keepOutA = gp_Pnt2d((ri.UV(A.face, l1 / 2).XY() + m1.uvX.XY()) / 2); + keepOutB = gp_Pnt2d((ro.UV(B.face, l2 / 2).XY() + m2.uvX.XY()) / 2); + } +}; + +// Largest angle between the unit normals of s1 at (u1, v1) and s2 at (u2, v2) on sampled +// matching boundary parameters, ignoring orientation. +double boundaryAngle(const Handle(Geom_Surface)& s, + bool alongU, + double fixed, + const std::function& target, + bool skipApex = false) +{ + double worst = 0; + for (int i = skipApex && alongU ? 1 : 0; i <= 100; ++i) // (a pinch's u = 0 side is a point) + { + const double x = i / 100., u = alongU ? x : fixed, v = alongU ? fixed : x; + GeomLProp_SLProps pr(s, u, v, 1, 1e-12); + if (!pr.IsNormalDefined()) + continue; + const gp_Vec a(pr.Normal()), b = target(pr.Value()); + if (b.Magnitude() < 1e-12) + continue; + const double ang = std::min(a.Angle(b), pi - a.Angle(b)); +#ifdef YPATCH_TRACE + if (ang > 1e-3) + std::printf(" angle %.4f deg at %s=%.3f\n", ang * 180 / pi, alongU ? "u" : "v", x); +#endif + worst = std::max(worst, ang); + } + return worst; +} + +gp_Pnt midPoint(const TopoDS_Edge& e) +{ + BRepAdaptor_Curve c(e); + return c.Value((c.FirstParameter() + c.LastParameter()) / 2); +} + +bool inFace(const TopoDS_Face& f, const gp_Pnt2d& uv) +{ + BRepClass_FaceClassifier c(f, uv, 1e-7); + return c.State() == TopAbs_IN; +} + +} // namespace + +// The Y patch on a shape whose periodic supports have their seams clear of the bands. +static Standard_Boolean performOn(const TopoDS_Shape& theShape, + const TopTools_DataMapOfShapeReal& theRadii, + TopoDS_Shape& theResult, + Handle(BRepTools_History)& theHistory, + NCollection_Vector& theReport, + const Standard_Boolean thePinch, + const int thePinchDir) +{ + using Junction = BRepFilletAPI_YPatch::Junction; + try + { + NCollection_Vector js = BRepFilletAPI_YPatch::Detect(theShape, theRadii); + if (js.IsEmpty()) + return Standard_False; + std::vector> works; + for (const Junction& j : js) + { + works.push_back(std::make_unique(j)); + Work& w = *works.back(); + w.pinch = thePinch; + w.pinchDir = thePinchDir; +#ifdef YPATCH_TRACE + if (const char* d = std::getenv("YPATCH_PINCH_DIR")) + w.pinchDir = std::atoi(d); +#endif + w.Split(); + w.Sections(); + w.Ribbons(); + } + auto attempt = [&](const bool margin) -> bool { + try + { + // 1. Cut each wedge out of the boundary. + BRepAlgoAPI_Splitter split; + TopTools_ListOfShape args, tools; + args.Append(theShape); + for (auto& w : works) + w->Cuts(margin); + for (auto& w : works) + for (auto& e : w->cuts) + tools.Append(e); + split.SetArguments(args); + split.SetTools(tools); + split.SetFuzzyValue(1e-6); + split.Build(); + require(split.IsDone() && !split.HasErrors(), "YPatch: splitting the supports failed"); + auto image = [&](const TopoDS_Shape& s) { + TopTools_ListOfShape l = split.Modified(s); + if (l.IsEmpty() && !split.IsDeleted(s)) + l.Append(s); + return l; + }; + TopTools_MapOfShape drop; + for (auto& w : works) + { + const std::pair probes[] = {{&w->T, w->keepOutT}, {&w->A, w->keepOutA}, {&w->B, w->keepOutB}}; + for (const auto& pr : probes) + { + int hits = 0; + const TopTools_ListOfShape pieces = image(pr.first->face); + for (TopTools_ListOfShape::Iterator it(pieces); it.More(); it.Next()) + if (inFace(TopoDS::Face(it.Value()), pr.second)) + { + drop.Add(it.Value()); + ++hits; + } +#ifdef YPATCH_TRACE + std::printf("YPatch: support pieces %d, wedge hits %d\n", pieces.Extent(), hits); +#endif + require(hits == 1, "YPatch: the wedge was not cut out of a support"); + } + } + BRep_Builder b; + TopoDS_Shell shell; + b.MakeShell(shell); + for (TopExp_Explorer ex(split.Shape(), TopAbs_FACE); ex.More(); ex.Next()) + if (!drop.Contains(ex.Current())) + b.Add(shell, ex.Current()); + // 2. Standard fillet of everything else on the open shell, in two passes: the convex band + // ends of the junctions go second. A single run that ends two bands at the same + // free-boundary vertex (P*) is numerically marginal for the standard algorithm. +#ifdef YPATCH_TRACE + BRepTools::Write(shell, "trace-shell.brep"); +#endif + TopTools_MapOfShape late; // pieces of the junctions' convex edges + for (auto& w : works) + { + const TopTools_ListOfShape pieces = image(w->j.Convex); + for (TopTools_ListOfShape::Iterator p(pieces); p.More(); p.Next()) + late.Add(p.Value()); + } + // the requested pieces still bounding two faces, as instances of `of` + struct Seed + { + TopoDS_Shape input; // requested edge + TopoDS_Edge piece; // its piece in the open shell + double r; + }; + std::vector seeds[2]; + { + TopTools_IndexedDataMapOfShapeListOfShape ef; + TopExp::MapShapesAndAncestors(shell, TopAbs_EDGE, TopAbs_FACE, ef); + for (TopTools_DataMapOfShapeReal::Iterator it(theRadii); it.More(); it.Next()) + { + const TopTools_ListOfShape pieces = image(it.Key()); + for (TopTools_ListOfShape::Iterator p(pieces); p.More(); p.Next()) + { + const int index = ef.FindIndex(p.Value()); + if (index == 0 || ef(index).Extent() != 2) + continue; + const TopoDS_Edge piece = TopoDS::Edge(ef.FindKey(index)); // the shell's own instance + // late when its tangent chain holds a convex junction edge (the chain moves as one) + bool isLate = late.Contains(piece); + if (!isLate) + { + BRepFilletAPI_MakeFillet probe(shell); + probe.Add(it.Value(), piece); + for (int ie = 1; probe.NbContours() > 0 && ie <= probe.NbEdges(1) && !isLate; ++ie) + isLate = late.Contains(probe.Edge(1, ie)); + } + seeds[isLate ? 1 : 0].push_back({it.Key(), piece, it.Value()}); + } + } + } + std::unique_ptr pass[2]; + TopTools_IndexedMapOfShape kept[2]; // sub-shapes of each pass's result + TopoDS_Shape current = shell; + // the images of s (a sub-shape of the input of pass k) in its result + auto passImage = [&](int k, const TopoDS_Shape& s) { + if (!pass[k]) + { + TopTools_ListOfShape l; + l.Append(s); + return l; + } + TopTools_ListOfShape l = pass[k]->Modified(s); // IsDeleted answers for faces only + if (l.IsEmpty() && kept[k].Contains(s)) + l.Append(s); + return l; + }; + for (int k = 0; k < 2; ++k) + { + if (seeds[k].empty()) + continue; + pass[k] = std::make_unique(current); + TopTools_IndexedDataMapOfShapeListOfShape ef; + TopExp::MapShapesAndAncestors(current, TopAbs_EDGE, TopAbs_FACE, ef); + for (Seed& s : seeds[k]) + { + TopoDS_Edge e = s.piece; + if (k == 1 && pass[0]) + { + const TopTools_ListOfShape now = passImage(0, e); + require(now.Extent() == 1, "YPatch: a convex band edge was changed by the first pass"); + e = TopoDS::Edge(now.First()); + } + const int index = ef.FindIndex(e); + require(index != 0 && ef(index).Extent() == 2, "YPatch: a fillet edge is not between two faces"); + s.piece = TopoDS::Edge(ef.FindKey(index)); + } + // Tangent propagation is not symmetric on a cut shell (from one piece the chain may stop + // at a vertex it crosses from the other side), and an edge in two contours gets two + // bands. Seed the longest chains first and skip seeds already covered. + std::vector> order; // (chain length, seed) + for (std::size_t i = 0; i < seeds[k].size(); ++i) + { + BRepFilletAPI_MakeFillet probe(current); + probe.Add(seeds[k][i].r, seeds[k][i].piece); + order.emplace_back(probe.NbContours() ? probe.NbEdges(1) : 0, i); + } + std::stable_sort(order.begin(), order.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); + for (const auto& o : order) + { + const Seed& s = seeds[k][o.second]; + if (pass[k]->Contour(s.piece) == 0) + pass[k]->Add(s.r, s.piece); + } +#ifdef YPATCH_TRACE + for (int ic = 1; ic <= pass[k]->NbContours(); ++ic) + for (int ie = 1; ie <= pass[k]->NbEdges(ic); ++ie) + { + const gp_Pnt m = midPoint(pass[k]->Edge(ic, ie)); + std::printf("YPatch: pass %d contour %d edge (%.3f %.3f %.3f)\n", k, ic, m.X(), m.Y(), m.Z()); + } +#endif + pass[k]->Build(); +#ifdef YPATCH_TRACE + if (!pass[k]->IsDone()) + std::printf("YPatch: pass %d: contours %d faulty contours %d faulty vertices %d\n", k, pass[k]->NbContours(), + pass[k]->NbFaultyContours(), pass[k]->NbFaultyVertices()); +#endif + require(pass[k]->IsDone(), "YPatch: the standard fillet of the remaining edges failed"); + current = pass[k]->Shape(); + TopExp::MapShapes(current, kept[k]); + } + for (auto& w : works) + { + w->bandSurf[0].Nullify(); + w->bandSurf[1].Nullify(); + w->FitBandEnds(current); + } + // 3. The free boundary must be exactly the ribbons' outline. A free edge away from every + // ribbon is a remnant of a cut the standard algorithm left in a support's wire (seen for + // small radii): drop it from its wire; validity is checked on the final solid. + std::vector ribbons; + for (auto& w : works) + for (int k = 0; k < 2; ++k) + ribbons.push_back(BRepBuilderAPI_MakeFace(w->rib[k], 1e-7).Face()); + Handle(BRepTools_ReShape) reshape = new BRepTools_ReShape(); + TopoDS_Shape filleted = current; + { + TopTools_IndexedDataMapOfShapeListOfShape fe; + TopExp::MapShapesAndAncestors(filleted, TopAbs_EDGE, TopAbs_FACE, fe); + TopTools_MapOfShape stray; + for (int i = 1; i <= fe.Extent(); ++i) + { + if (fe(i).Extent() != 1) + continue; + const gp_Pnt p = midPoint(TopoDS::Edge(fe.FindKey(i))); + bool onRib = false; + for (auto& w : works) + for (int k = 0; k < 2 && !onRib; ++k) + { + GeomAPI_ProjectPointOnSurf pr(p, w->rib[k]); + onRib = pr.NbPoints() > 0 && pr.LowerDistance() < 1e-4; + } + for (auto& w : works) + for (std::size_t k = 0; k < w->fillers.size() && !onRib; ++k) + { + BRepExtrema_DistShapeShape dist(BRepBuilderAPI_MakeVertex(p).Vertex(), w->fillers[k]); + onRib = dist.IsDone() && dist.Value() < 1e-4; + } + if (!onRib) + { +#ifdef YPATCH_TRACE + std::printf("YPatch: stray free edge at (%.4f %.4f %.4f)\n", p.X(), p.Y(), p.Z()); +#endif + stray.Add(fe.FindKey(i)); + } + } + // Also seen on a periodic support cut by the wedge: a wire holding the same edge twice + // with the same orientation (only a seam may appear twice, and then reversed). + TopTools_IndexedMapOfShape faces; + for (TopTools_MapOfShape::Iterator it(stray); it.More(); it.Next()) + faces.Add(fe.FindFromKey(it.Value()).First()); + for (TopExp_Explorer fx(filleted, TopAbs_FACE); fx.More(); fx.Next()) + for (TopoDS_Iterator wi(fx.Current()); wi.More(); wi.Next()) + { + TopTools_MapOfOrientedShape seen; + for (TopoDS_Iterator ei(wi.Value()); ei.More(); ei.Next()) + if (!seen.Add(ei.Value())) + faces.Add(fx.Current()); + } + BRep_Builder bb; + for (int i = 1; i <= faces.Extent(); ++i) + { + const TopoDS_Face f = TopoDS::Face(faces(i)); + TopoDS_Face f2 = TopoDS::Face(f.EmptyCopied()); + for (TopoDS_Iterator wi(f); wi.More(); wi.Next()) + { + TopoDS_Wire w2 = TopoDS::Wire(wi.Value().EmptyCopied()); + TopTools_MapOfOrientedShape seen; + for (TopoDS_Iterator ei(wi.Value()); ei.More(); ei.Next()) + if (!stray.Contains(ei.Value()) && seen.Add(ei.Value())) + bb.Add(w2, ei.Value()); + w2.Closed(BRep_Tool::IsClosed(w2)); + bb.Add(f2, w2); + } +#ifdef YPATCH_TRACE + std::printf("YPatch: rebuilt the wires of a support face\n"); +#endif + reshape->Replace(f, f2); + } + if (!faces.IsEmpty()) + filleted = reshape->Apply(filleted); + } + // 4. Close with the ribbons. The standard algorithm ends a band on an approximated spine + // (e.g. an ellipse on an inclined face): its end section may then differ from the exact + // one by a few 1e-4 r. Sew tight first, then once with a tolerance bounded by the radii. + double rmax = 0; + for (auto& w : works) + rmax = std::max({rmax, w->bi.r, w->bo.r}); + std::unique_ptr sewing; + double gap = 0; // pinch: the measured end gap, bounded + for (auto& w : works) + if (w->pinch) + gap = std::max(gap, w->endGap); + require(gap < 1e-3 * std::max(1., rmax), "YPatch: pinch end too far from the band end built"); + double sewTol = 0; + for (const double tol : {1e-5, 1e-4 * std::max(1., rmax), 2 * gap}) + { + sewTol = tol; + sewing = std::make_unique(tol); + sewing->Add(filleted); + for (const TopoDS_Face& f : ribbons) + sewing->Add(f); + for (auto& w : works) + for (const TopoDS_Face& f : w->fillers) + sewing->Add(f); + sewing->Perform(); + if (sewing->NbFreeEdges() == 0 && sewing->NbMultipleEdges() == 0) + break; + } + BRepBuilderAPI_Sewing& sew = *sewing; + TopoDS_Shape sewn = sew.SewedShape(); +#ifdef YPATCH_TRACE + BRepTools::Write(current, "trace-fillet.brep"); + for (std::size_t i = 0; i < works.size(); ++i) + for (int k = 0; k < 2; ++k) + BRepTools::Write(BRepBuilderAPI_MakeFace(works[i]->rib[k], 1e-7).Face(), ("trace-rib" + std::to_string(k) + ".brep").c_str()); + for (int i = 1; i <= sew.NbFreeEdges(); ++i) + { + BRepAdaptor_Curve c(sew.FreeEdge(i)); + gp_Pnt a = c.Value(c.FirstParameter()), m = c.Value((c.FirstParameter() + c.LastParameter()) / 2), z = c.Value(c.LastParameter()); + std::printf("free (%.4f %.4f %.4f) (%.4f %.4f %.4f) (%.4f %.4f %.4f)\n", a.X(), a.Y(), a.Z(), m.X(), m.Y(), m.Z(), z.X(), z.Y(), z.Z()); + } +#endif + require(sew.NbFreeEdges() == 0 && sew.NbMultipleEdges() == 0, "YPatch: ribbons do not close the shell"); + TopExp_Explorer sh(sewn, TopAbs_SHELL); + require(sh.More(), "YPatch: no shell"); + TopoDS_Shell closed = TopoDS::Shell(sh.Current()); + sh.Next(); + require(!sh.More(), "YPatch: several shells"); + TopoDS_Solid solid = BRepBuilderAPI_MakeSolid(closed).Solid(); + require(BRepLib::OrientClosedSolid(solid), "YPatch: cannot orient the solid"); + // A pinch sewn at the looser tolerance (approximated band ends) can leave an edge shorter + // than that tolerance where a band end meets the shared point: merge it. + Handle(ShapeBuild_ReShape) fixContext = new ShapeBuild_ReShape(); + TopTools_DataMapOfShapeShape fixedFace; // faces the fix rebuilt (it records edges only) + auto interferes = [](const TopoDS_Shape& x) { + BOPAlgo_CheckerSI c; + c.SetLevelOfCheck(5); + c.AddArgument(x); + c.Perform(); + return c.HasErrors() || !c.DS().Interferences().IsEmpty(); + }; + if (sewTol > 1e-5 && std::any_of(works.begin(), works.end(), [](const auto& w) { return w->pinch; }) + && interferes(solid)) + { + const TopoDS_Solid before = solid; + ShapeFix_Wireframe fix(solid); + fix.SetContext(fixContext); + fix.SetPrecision(sewTol); + fix.SetMaxTolerance(sewTol); + fix.ModeDropSmallEdges() = Standard_True; + fix.FixSmallEdges(); + TopExp_Explorer one(fix.Shape(), TopAbs_SOLID); + require(one.More(), "YPatch: small-edge fix lost the solid"); + solid = TopoDS::Solid(one.Current()); + // a face before -> the face after with the same surface sharing an untouched edge + TopTools_IndexedDataMapOfShapeListOfShape edgeFaces; + TopExp::MapShapesAndAncestors(solid, TopAbs_EDGE, TopAbs_FACE, edgeFaces); + TopTools_IndexedMapOfShape afterFaces; + TopExp::MapShapes(solid, TopAbs_FACE, afterFaces); + for (TopExp_Explorer f(before, TopAbs_FACE); f.More(); f.Next()) + { + const Handle(Geom_Surface) sf = BRep_Tool::Surface(TopoDS::Face(f.Current())); + if (afterFaces.Contains(f.Current())) + continue; // untouched + for (TopExp_Explorer e(f.Current(), TopAbs_EDGE); e.More() && !fixedFace.IsBound(f.Current()); e.Next()) + { + if (!edgeFaces.Contains(e.Current())) + continue; + for (TopTools_ListOfShape::Iterator g(edgeFaces.FindFromKey(e.Current())); g.More(); g.Next()) + if (BRep_Tool::Surface(TopoDS::Face(g.Value())) == sf) + { + fixedFace.Bind(f.Current(), g.Value()); + break; + } + } + if (fixedFace.IsBound(f.Current())) + continue; + // no untouched edge left: the face on the same surface nearest to its edges' middles + double best = 1e300; + TopoDS_Shape pick; + for (int i = 1; i <= afterFaces.Extent(); ++i) + { + if (BRep_Tool::Surface(TopoDS::Face(afterFaces(i))) != sf) + continue; + double worst = 0; + for (TopExp_Explorer e(f.Current(), TopAbs_EDGE); e.More(); e.Next()) + { + BRepExtrema_DistShapeShape d(BRepBuilderAPI_MakeVertex(midPoint(TopoDS::Edge(e.Current()))).Vertex(), afterFaces(i)); + worst = std::max(worst, d.IsDone() ? d.Value() : 1e300); + } + if (worst < best) + { + best = worst; + pick = afterFaces(i); + } + } + if (!pick.IsNull() && best < 10 * sewTol) + fixedFace.Bind(f.Current(), pick); + } + } +#ifdef YPATCH_TRACE + BRepTools::Write(solid, "trace-solid.brep"); +#endif + require(BRepCheck_Analyzer(solid).IsValid(), "YPatch: invalid result"); + BOPAlgo_CheckerSI si; + si.SetLevelOfCheck(5); + si.AddArgument(solid); + si.Perform(); + require(!si.HasErrors() && si.DS().Interferences().IsEmpty(), "YPatch: self-interference"); + // 4. Continuity gate and report. + theReport.Clear(); + for (auto& w : works) + { + Junction j = w->j; + j.Pinch = w->pinch; + j.Split = w->in[n - 1].pT; + const auto& R0 = w->rib[0]; + const auto& R1 = w->rib[1]; + j.SeamAngle = boundaryAngle(R0, true, 1., [&](const gp_Pnt& p) { + GeomAPI_ProjectPointOnSurf pr(p, R1); + double u, v; + pr.LowerDistanceParameters(u, v); + GeomLProp_SLProps lp(R1, u, v, 1, 1e-12); + return lp.IsNormalDefined() ? gp_Vec(lp.Normal()) : gp_Vec(); + }, w->pinch); + double band = 0, contact = 0; + for (int k = 0; k < 2; ++k) + { + const Support& X = k ? w->A : w->B; + const gp_Pnt c1 = (k ? w->in : w->out)[n - 1].c; + const Handle(Geom_Surface)& bs = w->bandSurf[k]; + j.EndAngle[k] = boundaryAngle(w->rib[k], false, 1., [&](const gp_Pnt& p) { + if (bs.IsNull()) + return gp_Vec(c1, p); + GeomAPI_ProjectPointOnSurf pr(p, bs); + double u, v; + pr.LowerDistanceParameters(u, v); + GeomLProp_SLProps lp(bs, u, v, 1, 1e-12); + return lp.IsNormalDefined() ? gp_Vec(lp.Normal()) : gp_Vec(); + }); + band = std::max(band, j.EndAngle[k]); + contact = std::max(contact, boundaryAngle(w->rib[k], true, 0., [&](const gp_Pnt& p) { return X.N(X.UV(p)); }, w->pinch)); + } + j.BandAngle = std::max(band, contact); + j.ContactAngle = contact; + theReport.Append(j); + } + // 5. History: splitter, then fillet, then sewing. + Handle(BRepTools_History) h = new BRepTools_History(); + TopTools_IndexedMapOfShape inputs; + TopExp::MapShapes(theShape, TopAbs_FACE, inputs); + TopExp::MapShapes(theShape, TopAbs_EDGE, inputs); + TopExp::MapShapes(theShape, TopAbs_VERTEX, inputs); + TopTools_IndexedMapOfShape outputs; + TopExp::MapShapes(solid, outputs); + auto after = [&](const TopoDS_Shape& x) { + const TopoDS_Shape y = reshape->Value(x); + const TopoDS_Shape z = sew.IsModifiedSubShape(y) ? sew.ModifiedSubShape(y) : y; // (IsModified knows added shapes only) + if (z.ShapeType() == TopAbs_FACE) + return fixedFace.IsBound(z) ? fixedFace.Find(z) : z; + const TopoDS_Shape f = fixContext->Value(z); + return f.IsNull() ? z : f; + }; + // through both passes, the stray-edge cleanup and the sewing, into the solid + auto finalOf = [&](const TopoDS_Shape& s, int from, TopTools_ListOfShape& to) { + TopTools_ListOfShape mids; + mids.Append(s); + for (int k = from; k < 2; ++k) + { + TopTools_ListOfShape next; + for (TopTools_ListOfShape::Iterator it(mids); it.More(); it.Next()) + { + TopTools_ListOfShape l = passImage(k, it.Value()); + next.Append(l); + } + mids = next; + } + for (TopTools_ListOfShape::Iterator it(mids); it.More(); it.Next()) + { + TopoDS_Shape r = after(it.Value()); + if (outputs.Contains(r)) + to.Append(r); + } + }; + for (int i = 1; i <= inputs.Extent(); ++i) + { + const TopoDS_Shape& s = inputs(i); + TopTools_ListOfShape result; + const TopTools_ListOfShape pieces = image(s); + for (TopTools_ListOfShape::Iterator it(pieces); it.More(); it.Next()) + finalOf(it.Value(), 0, result); + if (result.IsEmpty()) + h->Remove(s); + else if (!(result.Extent() == 1 && result.First().IsSame(s))) + for (TopTools_ListOfShape::Iterator it(result); it.More(); it.Next()) + h->AddModified(s, it.Value()); + } + // Bands: every edge of every contour (a seed drags its tangent chain along), credited to + // the input edge it comes from. + for (int k = 0; k < 2; ++k) + { + if (!pass[k]) + continue; + // the input edge of each edge of this pass's input + NCollection_DataMap origin; + TopTools_IndexedMapOfShape inputEdges; + TopExp::MapShapes(theShape, TopAbs_EDGE, inputEdges); + for (int i = 1; i <= inputEdges.Extent(); ++i) + { + TopTools_ListOfShape mids; + const TopTools_ListOfShape pieces = image(inputEdges(i)); + for (TopTools_ListOfShape::Iterator it(pieces); it.More(); it.Next()) + { + if (k == 0) + mids.Append(it.Value()); + else + { + TopTools_ListOfShape l = passImage(0, it.Value()); + mids.Append(l); + } + } + for (TopTools_ListOfShape::Iterator it(mids); it.More(); it.Next()) + origin.Bind(it.Value().Oriented(TopAbs_FORWARD), inputEdges(i)); + } + for (int ic = 1; ic <= pass[k]->NbContours(); ++ic) + for (int ie = 1; ie <= pass[k]->NbEdges(ic); ++ie) + { + const TopoDS_Edge& e = pass[k]->Edge(ic, ie); + const TopoDS_Shape key = e.Oriented(TopAbs_FORWARD); + if (!origin.IsBound(key)) + continue; + for (TopTools_ListOfShape::Iterator g(pass[k]->Generated(e)); g.More(); g.Next()) + { + TopTools_ListOfShape result; + finalOf(g.Value(), k + 1, result); + for (TopTools_ListOfShape::Iterator it(result); it.More(); it.Next()) + h->AddGenerated(origin(key), it.Value()); + } + } + } + for (std::size_t w = 0; w < works.size(); ++w) + for (int k = 0; k < 2; ++k) + { + TopoDS_Shape r = ribbons[2 * w + k]; + r = sew.IsModifiedSubShape(r) ? sew.ModifiedSubShape(r) : r; + r = fixedFace.IsBound(r) ? fixedFace.Find(r) : r; + h->AddGenerated(k ? works[w]->j.Concave : works[w]->j.Convex, r); + } + for (auto& w : works) + for (std::size_t k = 0; k < w->fillers.size(); ++k) + { + TopoDS_Shape r = w->fillers[k]; + r = sew.IsModifiedSubShape(r) ? sew.ModifiedSubShape(r) : r; + r = fixedFace.IsBound(r) ? fixedFace.Find(r) : r; + h->AddModified(w->fillerOf[k], r); + } + theResult = solid; + theHistory = h; + return true; + } + catch (const Standard_Failure& ex) + { +#ifdef YPATCH_TRACE + std::printf("YPatch (margin %d): %s\n", int(margin), ex.GetMessageString()); +#endif + (void)ex; + return false; + } + }; + // the direct cut first, then the cut with a margin on the supports + return attempt(false) || attempt(true); + } + catch (const Standard_Failure& ex) + { +#ifdef YPATCH_TRACE + std::printf("YPatch: %s\n", ex.GetMessageString()); +#endif + (void)ex; + return Standard_False; + } +} + +namespace +{ +// The standard algorithm mishandles a band that starts on a free boundary (as the Y cut makes +// it) and runs across, or ends on, the seam of a periodic support: it builds a piece of the +// band twice. Such supports are first re-seated: the face is rebuilt on its surface turned +// about its own axis, so that the seam lies where no selected edge passes. The point set of +// every face is unchanged. +struct Reseated +{ + TopoDS_Shape shape; + TopTools_DataMapOfShapeReal radii; + Handle(BRepTools_History) history; +}; + +// S turned by phi about its axis such that S'(u, v) = S(u + phi, v); null when S is not a +// surface of revolution about a fixed axis. +Handle(Geom_Surface) turned(const Handle(Geom_Surface)& S, const double phi) +{ + gp_Ax1 axis; + if (Handle(Geom_ElementarySurface) e = Handle(Geom_ElementarySurface)::DownCast(S)) + axis = e->Position().Axis(); + else if (Handle(Geom_SurfaceOfRevolution) r = Handle(Geom_SurfaceOfRevolution)::DownCast(S)) + axis = r->Axis(); + else + return Handle(Geom_Surface)(); + for (const double sign : {1., -1.}) + { + Handle(Geom_Surface) T = Handle(Geom_Surface)::DownCast(S->Rotated(axis, sign * phi)); + if (T->Value(0.3, 0.37).Distance(S->Value(0.3 + phi, 0.37)) < 1e-9 + && T->Value(1.7, 0.37).Distance(S->Value(1.7 + phi, 0.37)) < 1e-9) + return T; + } + return Handle(Geom_Surface)(); +} + +// One edge of a re-seated face, in its wire orientation. +struct Use +{ + TopoDS_Edge edge; + Handle(Geom2d_Curve) pc; // on the turned surface + double f = 0, l = 0; + + gp_Pnt2d Start() const { return pc->Value(edge.Orientation() == TopAbs_REVERSED ? l : f); } + + gp_Pnt2d End() const { return pc->Value(edge.Orientation() == TopAbs_REVERSED ? f : l); } +}; + +bool reseat(const TopoDS_Shape& input, const TopTools_DataMapOfShapeReal& radii, Reseated& out) +{ + TopTools_IndexedMapOfShape selectedVertices; + for (TopTools_DataMapOfShapeReal::Iterator it(radii); it.More(); it.Next()) + TopExp::MapShapes(it.Key(), TopAbs_VERTEX, selectedVertices); + // the faces to re-seat and the parameter of their new seam + std::vector> todo; + TopTools_IndexedMapOfShape faces; + TopExp::MapShapes(input, TopAbs_FACE, faces); + for (int i = 1; i <= faces.Extent(); ++i) + { + const TopoDS_Face F = TopoDS::Face(faces(i)); + const Handle(Geom_Surface) S = BRep_Tool::Surface(F); + if (S.IsNull() || !S->IsUPeriodic()) + continue; + bool touched = false; + for (TopExp_Explorer ex(F, TopAbs_EDGE); ex.More() && !touched; ex.Next()) + if (BRep_Tool::IsClosed(TopoDS::Edge(ex.Current()), F)) + for (TopExp_Explorer vx(ex.Current(), TopAbs_VERTEX); vx.More(); vx.Next()) + touched = touched || selectedVertices.Contains(vx.Current()); + if (!touched) + continue; + // the parameters covered by the selected edges on F, in bins of the period + const double P = S->UPeriod(); + const int nb = 720; + std::vector covered(nb, false); + auto bin = [&](double u) { + double x = std::fmod(u, P); + if (x < 0) + x += P; + return std::min(nb - 1, int(x / P * nb)); + }; + for (TopExp_Explorer ex(F, TopAbs_EDGE); ex.More(); ex.Next()) + { + if (!radii.IsBound(ex.Current())) + continue; + double f, l; + Handle(Geom2d_Curve) pc = BRep_Tool::CurveOnSurface(TopoDS::Edge(ex.Current()), F, f, l); + if (pc.IsNull()) + continue; + for (int k = 0; k < 64; ++k) + { + const double a = pc->Value(f + (l - f) * k / 64).X(), b = pc->Value(f + (l - f) * (k + 1) / 64).X(); + const int steps = 1 + int(std::abs(b - a) / P * nb); + for (int s = 0; s <= steps; ++s) + covered[bin(a + (b - a) * s / steps)] = true; + } + } + // the middle of the largest free run (circular) + int bestStart = -1, bestLen = 0; + for (int s = 0; s < nb; ++s) + { + if (covered[s] || !covered[(s + nb - 1) % nb]) + continue; + int len = 0; + while (len < nb && !covered[(s + len) % nb]) + ++len; + if (len > bestLen) + { + bestLen = len; + bestStart = s; + } + } + if (bestStart < 0 || bestLen < 4) + continue; + todo.emplace_back(F, (bestStart + bestLen / 2. + 0.5) / nb * P); + } + if (todo.empty()) + return false; + // 1. split each face along its new seam line + BRepAlgoAPI_Splitter split; + TopTools_ListOfShape args, tools; + std::vector rulings; + args.Append(input); + for (auto& item : todo) + { + const TopoDS_Face& F = item.first; + const double phi = item.second; + double umin, umax, vmin, vmax; + BRepTools::UVBounds(F, umin, umax, vmin, vmax); + const double P = BRep_Tool::Surface(F)->UPeriod(); + double u = phi + P * std::floor((umin - phi) / P); + if (u < umin) + u += P; + Handle(Geom2d_Curve) line = new Geom2d_Line(gp_Pnt2d(u, 0.), gp_Dir2d(0., 1.)); + TopoDS_Edge e = BRepBuilderAPI_MakeEdge(line, BRep_Tool::Surface(F), vmin, vmax).Edge(); + BRepLib::BuildCurves3d(e); + rulings.push_back(e); + tools.Append(e); + } + split.SetArguments(args); + split.SetTools(tools); + split.Build(); + if (!split.IsDone() || split.HasErrors()) + return false; + // 2. a copy: re-binding pcurves must not touch the input's edges + BRepBuilderAPI_Copy copy(split.Shape(), Standard_True, Standard_False); + TopTools_ListOfShape copied; + copied.Append(split.Shape()); + Handle(BRepTools_History) hc = new BRepTools_History(copied, copy); + auto copyOf = [&](const TopoDS_Shape& s) { // (Copy::Modified throws for a foreign shape) + const TopTools_ListOfShape& l = hc->Modified(s); + return l.IsEmpty() ? s : l.First(); + }; + auto image = [&](const TopoDS_Shape& s) { // input -> split -> copy + TopTools_ListOfShape l; + if (split.IsDeleted(s)) + return l; + TopTools_ListOfShape pieces = split.Modified(s); + if (pieces.IsEmpty()) + pieces.Append(s); + for (TopTools_ListOfShape::Iterator it(pieces); it.More(); it.Next()) + l.Append(copyOf(it.Value())); + return l; + }; + Handle(BRepTools_ReShape) rs = new BRepTools_ReShape(); + BRep_Builder bb; + TopTools_MapOfShape seamVertices; // the old seams' vertices, in the copy + for (std::size_t t = 0; t < todo.size(); ++t) + { + const TopoDS_Face& F = todo[t].first; + const double phi = todo[t].second; + const Handle(Geom_Surface) S = BRep_Tool::Surface(F); + const Handle(Geom_Surface) S2 = turned(S, phi); + if (S2.IsNull()) + return false; + const double P = S->UPeriod(); + TopTools_MapOfShape oldSeams, newSeams; + for (TopExp_Explorer ex(F, TopAbs_EDGE); ex.More(); ex.Next()) + if (BRep_Tool::IsClosed(TopoDS::Edge(ex.Current()), F)) + { + const TopTools_ListOfShape l = image(ex.Current()); + for (TopTools_ListOfShape::Iterator it(l); it.More(); it.Next()) + { + oldSeams.Add(it.Value()); + for (TopExp_Explorer vx(it.Value(), TopAbs_VERTEX); vx.More(); vx.Next()) + seamVertices.Add(vx.Current()); + } + } + { + const TopTools_ListOfShape l = split.Modified(rulings[t]); + for (TopTools_ListOfShape::Iterator it(l); it.More(); it.Next()) + newSeams.Add(copyOf(it.Value())); + } + const TopTools_ListOfShape pieces = image(F); + if (pieces.Extent() < 2) + return false; + // an old seam piece becomes interior only where the pieces meet across it (it is used + // twice); used once, it is a boundary that merely lay on the old seam line + NCollection_DataMap seamUses; + for (TopTools_ListOfShape::Iterator pit(pieces); pit.More(); pit.Next()) + for (TopExp_Explorer ex(pit.Value(), TopAbs_EDGE); ex.More(); ex.Next()) + if (oldSeams.Contains(ex.Current())) + { + const TopoDS_Shape key = ex.Current().Oriented(TopAbs_FORWARD); + if (!seamUses.IsBound(key)) + seamUses.Bind(key, 0); + seamUses(key) += 1; + } + std::vector uses; + NCollection_DataMap seamF, seamR; + for (TopTools_ListOfShape::Iterator pit(pieces); pit.More(); pit.Next()) + { + const TopoDS_Face p = TopoDS::Face(pit.Value().Oriented(TopAbs_FORWARD)); + double umin, umax, vmin, vmax; + BRepTools::UVBounds(p, umin, umax, vmin, vmax); + double side = std::fmod((umin + umax) / 2 - phi, P); // the piece's place on the turned surface + if (side < 0) + side += P; + for (TopExp_Explorer ex(p, TopAbs_EDGE); ex.More(); ex.Next()) + { + const TopoDS_Edge e = TopoDS::Edge(ex.Current()); + if (oldSeams.Contains(e) && seamUses(e.Oriented(TopAbs_FORWARD)) > 1) + continue; + Use use; + use.edge = e; + Handle(Geom2d_Curve) pc = BRep_Tool::CurveOnSurface(e, p, use.f, use.l); + if (pc.IsNull()) + return false; + double shift = -phi; + if (newSeams.Contains(e)) // u' = 0 next to the piece at the start of the period, else u' = P + shift += (side < P / 2 ? 0. : P) - P * std::round((pc->Value(use.f).X() - phi) / P); + else + shift -= P * std::floor((pc->Value((use.f + use.l) / 2).X() - phi) / P); + use.pc = Handle(Geom2d_Curve)::DownCast(pc->Translated(gp_Vec2d(shift, 0.))); + if (newSeams.Contains(e)) + (e.Orientation() == TopAbs_REVERSED ? seamR : seamF).Bind(e.Oriented(TopAbs_FORWARD), use.pc); + uses.push_back(use); + } + } + // re-bind the pcurves on the turned surface + for (const Use& use : uses) + { + const TopoDS_Shape key = use.edge.Oriented(TopAbs_FORWARD); + if (newSeams.Contains(use.edge)) + { + if (!seamF.IsBound(key) || !seamR.IsBound(key)) + return false; + bb.UpdateEdge(TopoDS::Edge(key), seamF(key), seamR(key), S2, TopLoc_Location(), + BRep_Tool::Tolerance(use.edge)); + } + else + bb.UpdateEdge(use.edge, use.pc, S2, TopLoc_Location(), BRep_Tool::Tolerance(use.edge)); + } + // chain the uses into closed wires by their uv ends + TopoDS_Face F2; + bb.MakeFace(F2, S2, BRep_Tool::Tolerance(F)); + const double tol = 1e-6 * (1 + P); + std::vector used(uses.size(), false); + for (std::size_t start = 0; start < uses.size(); ++start) + { + if (used[start]) + continue; + TopoDS_Wire w; + bb.MakeWire(w); + std::size_t cur = start; + while (true) + { + used[cur] = true; + bb.Add(w, uses[cur].edge); + const gp_Pnt2d end = uses[cur].End(); + std::size_t next = uses.size(); + double best = tol; + for (std::size_t k = 0; k < uses.size(); ++k) + if (!used[k] && uses[k].Start().Distance(end) < best) + { + best = uses[k].Start().Distance(end); + next = k; + } + if (next == uses.size()) + { + if (uses[start].Start().Distance(end) > tol) + { +#ifdef YPATCH_TRACE + std::printf("YPatch: re-seat open loop at (%g %g)\n", end.X(), end.Y()); +#endif + return false; // an open loop + } + break; + } + cur = next; + } + w.Closed(Standard_True); + bb.Add(F2, w); + } + if (!BRepCheck_Analyzer(F2).IsValid()) + { +#ifdef YPATCH_TRACE + std::printf("YPatch: re-seated face invalid\n"); +#endif + return false; + } + bool first = true; + for (TopTools_ListOfShape::Iterator pit(pieces); pit.More(); pit.Next()) + { + if (first) + rs->Replace(pit.Value(), F2.Oriented(pit.Value().Orientation())); + else + rs->Remove(pit.Value()); + first = false; + } + } + // With the old seam gone, its vertices split curves for nothing (a band then starts on a + // free boundary and crosses one, which the standard algorithm handles badly for small + // radii): merge the edges through them, and only through them. + const TopoDS_Shape reshaped = rs->Apply(copy.Shape()); + ShapeUpgrade_UnifySameDomain usd(reshaped, Standard_True, Standard_False, Standard_False); + { + TopTools_IndexedMapOfShape verts; + TopExp::MapShapes(reshaped, TopAbs_VERTEX, verts); + for (int i = 1; i <= verts.Extent(); ++i) + if (!seamVertices.Contains(verts(i))) + usd.KeepShape(verts(i)); + } + usd.Build(); + out.shape = usd.Shape(); + Handle(BRepTools_History) hu = usd.History(); + if (!BRepCheck_Analyzer(out.shape).IsValid()) + return false; + // The history, sub-shape by sub-shape: split, copy, replacement, edge merging. (Chained Merge calls + // drop the copy of every shape the splitter left alone.) + TopTools_IndexedMapOfShape outs; + for (const TopAbs_ShapeEnum t : {TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX}) + TopExp::MapShapes(out.shape, t, outs); + auto through = [&](const TopoDS_Shape& s) { + TopTools_ListOfShape result; + if (split.IsDeleted(s)) + return result; + TopTools_ListOfShape pieces = split.Modified(s); + if (pieces.IsEmpty()) + pieces.Append(s); + TopTools_MapOfShape seen; + for (TopTools_ListOfShape::Iterator it(pieces); it.More(); it.Next()) + { + const TopoDS_Shape z = rs->Value(copyOf(it.Value())); + if (z.IsNull() || hu->IsRemoved(z)) + continue; + TopTools_ListOfShape merged = hu->Modified(z); + if (merged.IsEmpty()) + merged.Append(z); + for (TopTools_ListOfShape::Iterator m(merged); m.More(); m.Next()) + if (outs.Contains(m.Value()) && seen.Add(m.Value())) + result.Append(m.Value()); + } + return result; + }; + TopTools_IndexedMapOfShape inputs; + for (const TopAbs_ShapeEnum t : {TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX}) + TopExp::MapShapes(input, t, inputs); + out.history = new BRepTools_History(); + for (int i = 1; i <= inputs.Extent(); ++i) + { + const TopTools_ListOfShape images = through(inputs(i)); + if (images.IsEmpty()) + out.history->Remove(inputs(i)); + else if (!(images.Extent() == 1 && images.First().IsSame(inputs(i)))) + for (TopTools_ListOfShape::Iterator it(images); it.More(); it.Next()) + out.history->AddModified(inputs(i), it.Value()); + } + out.radii.Clear(); + for (TopTools_DataMapOfShapeReal::Iterator it(radii); it.More(); it.Next()) + { + const TopTools_ListOfShape images = through(it.Key()); + if (images.IsEmpty()) + return false; + for (TopTools_ListOfShape::Iterator e(images); e.More(); e.Next()) + out.radii.Bind(e.Value(), it.Value()); + } + return true; +} +} // namespace + +// input -> h1 -> h2, for the faces, edges and vertices of `input`. (BRepTools_History::Merge +// does not carry a shape generated, in h2, from a modified image of an input shape.) +static Handle(BRepTools_History) compose(const TopoDS_Shape& input, + const Handle(BRepTools_History)& h1, + const Handle(BRepTools_History)& h2, + const TopoDS_Shape& result) +{ + TopTools_IndexedMapOfShape inputs, outputs; + for (const TopAbs_ShapeEnum t : {TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX}) + { + TopExp::MapShapes(input, t, inputs); + TopExp::MapShapes(result, t, outputs); + } + auto images = [](const Handle(BRepTools_History)& h, const TopoDS_Shape& s) { + TopTools_ListOfShape l; + if (h->IsRemoved(s)) + return l; + l = h->Modified(s); + if (l.IsEmpty()) + l.Append(s); + return l; + }; + Handle(BRepTools_History) out = new BRepTools_History(); + for (int i = 1; i <= inputs.Extent(); ++i) + { + const TopoDS_Shape& s = inputs(i); + TopTools_ListOfShape modified, generated; + const TopTools_ListOfShape mids = images(h1, s); + for (TopTools_ListOfShape::Iterator m(mids); m.More(); m.Next()) + { + const TopTools_ListOfShape fin = images(h2, m.Value()); + for (TopTools_ListOfShape::Iterator f(fin); f.More(); f.Next()) + if (outputs.Contains(f.Value())) + modified.Append(f.Value()); + for (TopTools_ListOfShape::Iterator g(h2->Generated(m.Value())); g.More(); g.Next()) + if (outputs.Contains(g.Value())) + generated.Append(g.Value()); + } + if (modified.IsEmpty()) + out->Remove(s); + else if (!(modified.Extent() == 1 && modified.First().IsSame(s))) + for (TopTools_ListOfShape::Iterator f(modified); f.More(); f.Next()) + out->AddModified(s, f.Value()); + for (TopTools_ListOfShape::Iterator g(generated); g.More(); g.Next()) + out->AddGenerated(s, g.Value()); + } + return out; +} + +// One attempt with a given pinch law: periodic supports re-seated first, then the shape as it is. +static Standard_Boolean attempt(const TopoDS_Shape& theShape, + const TopTools_DataMapOfShapeReal& theRadii, + TopoDS_Shape& theResult, + Handle(BRepTools_History)& theHistory, + NCollection_Vector& theReport, + const Standard_Boolean thePinch, + const int thePinchDir) +{ + try + { + Reseated r; + if (!BRepFilletAPI_YPatch::Detect(theShape, theRadii).IsEmpty() && reseat(theShape, theRadii, r)) + { + TopoDS_Shape result; + Handle(BRepTools_History) h; + NCollection_Vector report; +#ifdef YPATCH_TRACE + std::printf("YPatch: periodic supports re-seated\n"); +#endif + if (performOn(r.shape, r.radii, result, h, report, thePinch, thePinchDir)) + { + theResult = result; + theHistory = compose(theShape, r.history, h, result); + theReport = report; + return Standard_True; + } + } + } + catch (const Standard_Failure& ex) + { +#ifdef YPATCH_TRACE + std::printf("YPatch: re-seat: %s\n", ex.GetMessageString()); +#endif + (void)ex; + } + return performOn(theShape, theRadii, theResult, theHistory, theReport, thePinch, thePinchDir); +} + +Standard_Boolean BRepFilletAPI_YPatch::Perform(const TopoDS_Shape& theShape, + const TopTools_DataMapOfShapeReal& theRadii, + TopoDS_Shape& theResult, + Handle(BRepTools_History)& theHistory, + NCollection_Vector& theReport, + const Standard_Boolean thePinch) +{ + if (!thePinch) + return attempt(theShape, theRadii, theResult, theHistory, theReport, Standard_False, 0); + // The pinch: the convex band G1 at P*'s section first (Plasticity's layout); where the cusp is too + // narrow for that law (r = 1 on a flush post, a curved side) or the crease it leaves on the other + // side is unacceptable (an inclined common face measured 90 degrees), the balanced law. + constexpr double kMaxCrease = 30. * 3.14159265358979323846 / 180.; + for (const int dir : {0, 1}) + { + TopoDS_Shape result; + Handle(BRepTools_History) history; + NCollection_Vector report; + if (!attempt(theShape, theRadii, result, history, report, Standard_True, dir)) + continue; + bool creased = false; + for (const Junction& j : report) + creased = creased || j.EndAngle[0] > kMaxCrease || j.EndAngle[1] > kMaxCrease; +#ifdef YPATCH_TRACE + if (creased) + std::printf("YPatch: pinch law %d rejected: crease above 30 degrees\n", dir); +#endif + if (creased) + continue; + theResult = result; + theHistory = history; + theReport = report; + return Standard_True; + } + return Standard_False; +} diff --git a/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatchGeom.hxx b/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatchGeom.hxx new file mode 100644 index 00000000..7da0f2a7 --- /dev/null +++ b/src/cpp/patches/occt/overlay/BRepFilletAPI_YPatchGeom.hxx @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: LGPL-2.1-only WITH OCCT-exception-1.0 +// Internal geometry of BRepFilletAPI_YPatch (not part of the public API). +#ifndef _BRepFilletAPI_YPatchGeom_HeaderFile +#define _BRepFilletAPI_YPatchGeom_HeaderFile + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace YPatch +{ +//! A support face: point, outward normal and inverse by uv. +struct Support +{ + TopoDS_Face face; + BRepAdaptor_Surface s; + double sign; + Handle(ShapeAnalysis_Surface) proj; + + explicit Support(const TopoDS_Face& f); + gp_Pnt P(const gp_Pnt2d& uv) const; + gp_Vec N(const gp_Pnt2d& uv) const; //!< outward unit normal + gp_Pnt2d UV(const gp_Pnt& p) const; + gp_Pnt2d UVNear(const gp_Pnt& p, const gp_Pnt2d& seed) const; +}; + +//! A selected edge parametrised by lambda in [0,1] from the junction vertex. +struct Rail +{ + TopoDS_Edge edge; + BRepAdaptor_Curve c; + double first, last; + + Rail(const TopoDS_Edge& e, const TopoDS_Vertex& v); + double Param(double lambda) const; + gp_Pnt P(double lambda) const; + gp_Vec T(double lambda) const; //!< unit tangent pointing away from the vertex + gp_Pnt2d UV(const TopoDS_Face& f, double lambda) const; +}; + +//! A rolling-ball section: contacts on T and on X, and the centre. +struct Ball +{ + double lambda = 0; + gp_Pnt2d uvT, uvX; + gp_Pnt pT, pX, c; +}; + +//! The constant-radius band of one rail between the common face T and its own support X. +struct Band +{ + const Rail& rail; + const Support& T; + const Support& X; + double r; + double sigma; //!< +1 concave (centre outside the material), -1 convex + + bool Solve(double lambda, Ball& b, const Ball* seed = nullptr) const; +}; + +double angle(const gp_Vec& a, const gp_Vec& b); +} // namespace YPatch + +#endif diff --git a/src/cpp/patches/occt/overlay/BRepOffsetAPI_GraphPatch.cxx b/src/cpp/patches/occt/overlay/BRepOffsetAPI_GraphPatch.cxx index 7ef0d698..dfd9c388 100644 --- a/src/cpp/patches/occt/overlay/BRepOffsetAPI_GraphPatch.cxx +++ b/src/cpp/patches/occt/overlay/BRepOffsetAPI_GraphPatch.cxx @@ -8,10 +8,18 @@ #include #include #include +#include +#include +#include #include #include +#include +#include +#include #include +#include #include +#include #include #include #include @@ -21,6 +29,7 @@ #include #include #include +#include namespace { @@ -28,11 +37,27 @@ constexpr int N = 8, n = N + 1, samples = 2 * N + 1, dim = n * n; using Basis = std::array; using Row = std::array; -void require(bool b) +// Acceptance of a patch whose boundary data are not exactly polynomial (curved supports): the +// largest distance to a support edge (model units), the largest normal angle to a G1/G2 support +// (radians) and the cross-boundary normal curvature difference to a G2 support, relative to +// max(|curvature|, 1 / patch size). Measured on the built face, densely along every edge. +constexpr double TolGap = 1e-3, TolAngle = 1e-3, TolCurvature = 0.05; +// Best fit of inexact data: position rows weigh this much more than derivative rows (which are +// scaled to lengths by the patch size); the prior enters with this weight relative to the data. +constexpr double PositionWeight = 10, PriorWeight = 0.1; + +void check(bool b, int line) { if (!b) + { +#ifdef GRAPHPATCH_TRACE + printf("[graphpatch] check at line %d refused\n", line); +#endif + (void)line; throw Standard_ConstructionError("GraphPatch: outside graph or fit domain"); + } } +#define require(b) check(b, __LINE__) double binom(int a, int b) { @@ -70,8 +95,9 @@ Row row(double u, double v, int du, int dv) struct Jet { - gp_Pnt p; - double z[6]; + gp_Pnt p; + double z[6]; + gp_Pnt2d uv; // on the support }; Jet jet(const BRepAdaptor_Curve2d& c, @@ -83,6 +109,7 @@ Jet jet(const BRepAdaptor_Curve2d& c, auto uv = c.Value(c.FirstParameter() * (1 - t) + c.LastParameter() * t); gp_Vec u, v, uu, vv, uvv; Jet s{}; + s.uv = uv; if (order == 0) s.p = surf.Value(uv.X(), uv.Y()); else if (order == 1) @@ -164,69 +191,166 @@ gp_Trsf plane(int count, const TopoDS_Edge* edges) return f; } -math_Vector solve(const std::vector& rows, const std::vector& values) +double dot(const Row& r, const math_Vector& x) +{ + double s = 0; + for (int j = 0; j < dim; ++j) + s += r[j] * x(j + 1); + return s; +} + +double norm(const std::vector& rows) { - int m = std::max(dim, int(rows.size())); - math_Matrix A(1, m, 1, dim, 0.), V(1, dim, 1, dim); - math_Vector W(1, dim), b(1, m, 0.), x(1, dim); - for (size_t i = 0; i < rows.size(); ++i) + double s = 0; + for (auto& r : rows) + for (double v : r) + s += v * v; + return sqrt(s); +} + +// What decides the freedom the boundary data leave: least-squares rows with target values. +// Rows that are height targets carry the factor turning their residual into model units. +struct Prior +{ + std::vector rows; + std::vector values, units; + + void add(const std::vector& r, + const std::vector& v, + double scale, + const std::vector* u = nullptr) { - b(1 + i) = values[i]; - for (int j = 0; j < dim; ++j) - A(i + 1, j + 1) = rows[i][j]; - } - require(SVD_Decompose(A, W, V) == 0); - double eps = W(W.Max()) * 1e-11; - std::vector null; - for (int i = 1; i <= dim; ++i) - if (W(i) <= eps) + for (size_t i = 0; i < r.size(); ++i) { - W(i) = 0.; - null.push_back(i); + Row s = r[i]; + for (double& c : s) + c *= scale; + rows.push_back(s); + values.push_back(v[i] * scale); + units.push_back(u ? (*u)[i] / scale : 0.); } - SVD_Solve(A, W, V, b, x); - // Remaining freedom minimizes the integrated squared Hessian in the exact - // null space, so fairing cannot trade away any accepted boundary constraint. - if (!null.empty()) + } + + // The largest distance of the graph x from the height targets. + double stray(const math_Vector& x) const { - int q = int(null.size()); - math_Matrix D(1, 3 * n * n, 1, q); - math_Vector rhs(1, 3 * n * n), delta(1, q), t(1, n), w(1, n); - math::GaussPoints(n, t); - math::GaussWeights(n, w); - int i = 0; - for (int a = 1; a <= n; ++a) - for (int b_ = 1; b_ <= n; ++b_) - for (int k = 0; k <= 2; ++k) + double d = 0; + for (size_t i = 0; i < rows.size(); ++i) + d = std::max(d, std::abs(dot(rows[i], x) - values[i]) * units[i]); + return d; + } +}; + +// The integrated squared Hessian of the graph over the domain square. +Prior hessian() +{ + Prior p; + math_Vector t(1, n), w(1, n); + math::GaussPoints(n, t); + math::GaussWeights(n, w); + for (int a = 1; a <= n; ++a) + for (int b = 1; b <= n; ++b) + for (int k = 0; k <= 2; ++k) + { + auto r = row((t(a) + 1) / 2, (t(b) + 1) / 2, 2 - k, k); + double weight = sqrt(w(a) * w(b) * (k == 1 ? 2. : 1.)); + for (double& c : r) + c *= weight; + p.rows.push_back(r); + p.values.push_back(0.); + p.units.push_back(0.); + } + return p; +} + +// The boundary rows (kind = derivative order) and a prior for what they leave free. Interpolating +// (the research solver), the data are met exactly when they allow it and the prior only decides +// the exact null space, so it cannot trade away an accepted constraint. Data no degree-eight +// graph meets (curved supports) are instead fitted together with the prior, positions weighted +// and the prior weak. When the prior is the supports' continuation, a target in itself, that fit +// also decides the directions the data barely determine (which an interpolant fills with +// whatever meets the data); an exact interpolant is then kept only if it strays from the +// continuation at most twice as far as the fit. `exact` reports whether the data were met. +math_Vector solve(const std::vector& rows, + const std::vector& values, + const std::vector& kinds, + const Prior& prior, + bool continued, + bool& exact) +{ + math_Vector x(1, dim); + auto met = [&](const math_Vector& y) { + bool ok = true; + for (size_t i = 0; i < rows.size(); ++i) + ok = ok && std::abs(dot(rows[i], y) - values[i]) <= 1e-5; + return ok; + }; + { + int m = std::max(dim, int(rows.size())); + math_Matrix A(1, m, 1, dim, 0.), V(1, dim, 1, dim); + math_Vector W(1, dim), b(1, m, 0.); + for (size_t i = 0; i < rows.size(); ++i) + { + b(1 + i) = values[i]; + for (int j = 0; j < dim; ++j) + A(i + 1, j + 1) = rows[i][j]; + } + require(SVD_Decompose(A, W, V) == 0); + double eps = W(W.Max()) * 1e-11; + std::vector null; + for (int i = 1; i <= dim; ++i) + if (W(i) <= eps) + { + W(i) = 0.; + null.push_back(i); + } + SVD_Solve(A, W, V, b, x); + if (!null.empty()) + { + int q = int(null.size()), p = int(prior.rows.size()); + math_Matrix D(1, p, 1, q); + math_Vector rhs(1, p), delta(1, q); + for (int i = 0; i < p; ++i) + { + rhs(i + 1) = prior.values[i] - dot(prior.rows[i], x); + for (int c = 0; c < q; ++c) { - auto r = row((t(a) + 1) / 2, (t(b_) + 1) / 2, 2 - k, k); - ++i; - double weight = sqrt(w(a) * w(b_) * (k == 1 ? 2. : 1.)); - rhs(i) = 0; + double sum = 0; for (int j = 0; j < dim; ++j) - rhs(i) -= weight * r[j] * x(j + 1); - for (int c = 0; c < q; ++c) - { - double sum = 0; - for (int j = 0; j < dim; ++j) - sum += r[j] * V(j + 1, null[c]); - D(i, c + 1) = sum * weight; - } + sum += prior.rows[i][j] * V(j + 1, null[c]); + D(i + 1, c + 1) = sum; } - math_SVD svd(D); - require(svd.IsDone()); - svd.Solve(rhs, delta, 1e-11); - for (int j = 1; j <= dim; ++j) - for (int c = 0; c < q; ++c) - x(j) += V(j, null[c]) * delta(c + 1); + } + math_SVD svd(D); + require(svd.IsDone()); + svd.Solve(rhs, delta, 1e-11); + for (int j = 1; j <= dim; ++j) + for (int c = 0; c < q; ++c) + x(j) += V(j, null[c]) * delta(c + 1); + } + if ((exact = met(x)) && !continued) + return x; } - for (size_t i = 0; i < rows.size(); ++i) + const math_Vector interpolant = x; + const double scale = PriorWeight * norm(rows) / norm(prior.rows); + const int total = int(rows.size() + prior.rows.size()); + math_Matrix M(1, std::max(dim, total), 1, dim, 0.); + math_Vector r(1, std::max(dim, total), 0.); + for (int i = 0; i < total; ++i) { - double err = -values[i]; + bool data = i < int(rows.size()); + const Row& row_ = data ? rows[i] : prior.rows[i - rows.size()]; + double w = data ? (kinds[i] ? 1. : PositionWeight) : scale; + r(i + 1) = w * (data ? values[i] : prior.values[i - rows.size()]); for (int j = 0; j < dim; ++j) - err += rows[i][j] * x(j + 1); - require(std::abs(err) <= 1e-5); + M(i + 1, j + 1) = w * row_[j]; } + math_SVD fit(M); + require(fit.IsDone()); + fit.Solve(r, x, 1e-13); + if (exact && prior.stray(interpolant) <= 2 * prior.stray(x) + Precision::Confusion()) + return interpolant; + exact = met(x); return x; } @@ -400,7 +524,8 @@ bool rectangle(const std::vector>& ss, double err = -s.z[k] * pow(w, du[k]) * pow(h, dv[k]); for (int j = 0; j < dim; ++j) err += r[j] * x(j + 1); - require(std::abs(err) <= 1e-6); + if (std::abs(err) > 1e-6) + return false; // not a polynomial trace: the general fit decides } } TColgp_Array2OfPnt p(1, n, 1, n); @@ -409,10 +534,156 @@ bool rectangle(const std::vector>& ss, p(a + 1, b_ + 1) = gp_Pnt(xmin + w * a / N, ymin + h * b_ / N, x(1 + n * a + b_)).Transformed(f); auto face = BRepBuilderAPI_MakeFace(new Geom_BezierSurface(p), 1e-7).Face(); - require(BRepCheck_Analyzer(face).IsValid()); + if (!BRepCheck_Analyzer(face).IsValid()) + return false; out = face; return true; } + +// Height over the frame point (x, y) of the surface carrying a support, continued by Newton from +// uv; false where that surface is no graph over the frame plane. +bool height(const BRepAdaptor_Surface& s, + const gp_Trsf& inv, + double x, + double y, + gp_Pnt2d uv, + double tol, + double& z) +{ + for (int it = 0; it < 30; ++it) + { + gp_Pnt p; + gp_Vec du, dv; + s.D1(uv.X(), uv.Y(), p, du, dv); + p.Transform(inv); + du.Transform(inv); + dv.Transform(inv); + const double ex = p.X() - x, ey = p.Y() - y; + if (std::hypot(ex, ey) <= tol) + { + z = p.Z(); + return true; + } + const double det = du.X() * dv.Y() - du.Y() * dv.X(); + if (std::abs(det) <= 1e-9 * du.Magnitude() * dv.Magnitude()) + return false; + uv.SetCoord(uv.X() - (dv.Y() * ex - dv.X() * ey) / det, + uv.Y() - (du.X() * ey - du.Y() * ex) / det); + } + return false; +} + +bool inside(const std::vector& polygon, double x, double y) +{ + bool in = false; + for (size_t i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++) + { + const gp_Pnt2d &a = polygon[i], &b = polygon[j]; + if ((a.Y() > y) != (b.Y() > y) && x < b.X() + (a.X() - b.X()) * (y - b.Y()) / (a.Y() - b.Y())) + in = !in; + } + return in; +} + +// The supports continued over the loop: the height of each support's surface, from the nearest +// sample of its edges, blended by inverse distance to those edges. A hole cut in one surface +// is so filled by (the best degree-eight graph of) that surface. Empty when some interior point +// has no such height (supports that are no graphs over the frame, as walls under a lid). +Prior reference(int count, + const TopoDS_Face* fs, + const std::vector>& ss, + const std::vector& polygon, + const gp_Trsf& inv, + double xmin, + double ymin, + double L) +{ + std::vector group(count); + std::vector> surfaces(count); + for (int i = 0; i < count; ++i) + { + group[i] = i; + for (int j = 0; j < i && group[i] == i; ++j) + if (fs[j].IsSame(fs[i])) + group[i] = group[j]; + if (group[i] == i) + surfaces[i] = std::make_unique(fs[i]); + } + constexpr int G = 2 * N; + math_Vector t(1, G), w(1, G); + std::vector rows; + std::vector values, units; + math::GaussPoints(G, t); + math::GaussWeights(G, w); + for (int a = 1; a <= G; ++a) + for (int b = 1; b <= G; ++b) + { + const double u = (t(a) + 1) / 2, v = (t(b) + 1) / 2, x = xmin + L * u, y = ymin + L * v; + if (!inside(polygon, u, v)) + continue; + double sum = 0, weights = 0; + for (int g = 0; g < count; ++g) + { + if (group[g] != g) + continue; + double d = 1e100, z; + gp_Pnt2d start; + for (int i = 0; i < count; ++i) + for (const auto& s : ss[i]) + if (group[i] == g && std::hypot(s.p.X() - x, s.p.Y() - y) < d) + { + d = std::hypot(s.p.X() - x, s.p.Y() - y); + start = s.uv; + } + if (height(*surfaces[g], inv, x, y, start, 1e-10 * L, z)) + { + const double weight = 1 / pow(d / L + 1e-6, 4); + sum += weight * z; + weights += weight; + } + } + if (weights == 0) + return {}; + auto r = row(u, v, 0, 0); + const double scale = sqrt(w(a) * w(b)); + for (double& c : r) + c *= scale; + rows.push_back(r); + values.push_back(scale * sum / weights); + units.push_back(1 / scale); + } + Prior p; + if (rows.empty()) + return p; + p.add(rows, values, 1 / norm(rows), &units); + // keeps the part of the square outside the loop determined + Prior h = hessian(); + p.add(h.rows, h.values, 1e-6 / norm(h.rows)); + return p; +} + +void setPole(const Handle(Geom2d_BoundedCurve)& c, bool first, const gp_Pnt2d& p) +{ + if (auto b = Handle(Geom2d_BezierCurve)::DownCast(c)) + b->SetPole(first ? 1 : b->NbPoles(), p); + else if (auto s = Handle(Geom2d_BSplineCurve)::DownCast(c)) + s->SetPole(first ? 1 : s->NbPoles(), p); +} + +// Normal curvature along the tangent d of a surface with derivatives su .. suv and unit normal nn. +double curvature(const gp_Vec& su, + const gp_Vec& sv, + const gp_Vec& suu, + const gp_Vec& svv, + const gp_Vec& suv, + const gp_Vec& d, + const gp_Vec& nn) +{ + const double E = su.Dot(su), F = su.Dot(sv), G = sv.Dot(sv), det = E * G - F * F; + const double a = (G * d.Dot(su) - F * d.Dot(sv)) / det, b = (E * d.Dot(sv) - F * d.Dot(su)) / det; + return (suu.Dot(nn) * a * a + 2 * suv.Dot(nn) * a * b + svv.Dot(nn) * b * b) + / (E * a * a + 2 * F * a * b + G * b * b); +} } // namespace bool BRepOffsetAPI_GraphPatch::TryBuild(int count, @@ -469,11 +740,13 @@ bool BRepOffsetAPI_GraphPatch::TryBuild(int count, } math_SVD trim(B); require(trim.IsDone()); - std::vector A; - std::vector rhs; - std::vector curves; - gp_Pnt2d start, last; - const int du[] = {0, 1, 0, 2, 1, 0}, dv[] = {0, 0, 1, 0, 1, 2}; + std::vector A; + std::vector rhs; + std::vector kinds; + std::vector curves; + std::vector reversed; + gp_Pnt2d start, last; + const int du[] = {0, 1, 0, 2, 1, 0}, dv[] = {0, 0, 1, 0, 1, 2}; for (int i = 0; i < count; ++i) { TColgp_Array1OfPnt2d p(1, n); @@ -489,15 +762,41 @@ bool BRepOffsetAPI_GraphPatch::TryBuild(int count, { A.push_back(row(u, v, du[k], dv[k])); rhs.push_back(s.z[k] * pow(L, du[k] + dv[k])); + kinds.push_back(du[k] + dv[k]); } } trim.Solve(bx, x); trim.Solve(by, y); for (int k = 1; k <= n; ++k) p(k) = {x(k), y(k)}; - Handle(Geom2d_BezierCurve) c = new Geom2d_BezierCurve(p); + Handle(Geom2d_BoundedCurve) c = new Geom2d_BezierCurve(p); + bool polynomial = true; for (int j = 0; j < samples; ++j) - require(c->Value(double(j) / (samples - 1)).Distance({bx(j + 1), by(j + 1)}) * L <= 1e-7); + polynomial = polynomial + && c->Value(double(j) / (samples - 1)).Distance({bx(j + 1), by(j + 1)}) * L <= 1e-7; + if (!polynomial) + { + // The projected edge is no degree-eight polynomial in its parameter (an intersection + // curve, an oblique arc): interpolate it densely on the same parameter instead. + BRepAdaptor_Curve2d pc(es[i], fs[i]); + BRepAdaptor_Surface surf(fs[i]); + const int m = 8 * N + 1; + Handle(TColgp_HArray1OfPnt2d) pts = new TColgp_HArray1OfPnt2d(1, m); + Handle(TColStd_HArray1OfReal) prm = new TColStd_HArray1OfReal(1, m); + for (int j = 0; j < m; ++j) + { + const double t = double(j) / (m - 1); + const auto uv = pc.Value(pc.FirstParameter() * (1 - t) + pc.LastParameter() * t); + const gp_Pnt q = surf.Value(uv.X(), uv.Y()).Transformed(inv); + pts->SetValue(j + 1, gp_Pnt2d((q.X() - xmin) / L, (q.Y() - ymin) / L)); + prm->SetValue(j + 1, t); + } + Geom2dAPI_Interpolate interpolate(pts, prm, false, Precision::Confusion() / L); + interpolate.Perform(); + require(interpolate.IsDone()); + c = interpolate.Curve(); + } + bool flip = false; if (!i) { auto nextDist = [&](gp_Pnt2d pt) { @@ -505,32 +804,108 @@ bool BRepOffsetAPI_GraphPatch::TryBuild(int count, pt.Distance({(ss[1][0].p.X() - xmin) / L, (ss[1][0].p.Y() - ymin) / L}), pt.Distance({(ss[1].back().p.X() - xmin) / L, (ss[1].back().p.Y() - ymin) / L})); }; - if (nextDist(c->StartPoint()) < nextDist(c->EndPoint())) - c->Reverse(); - start = c->StartPoint(); + flip = nextDist(c->StartPoint()) < nextDist(c->EndPoint()); } else - { - if (last.Distance(c->EndPoint()) < last.Distance(c->StartPoint())) - c->Reverse(); + flip = last.Distance(c->EndPoint()) < last.Distance(c->StartPoint()); + if (flip) + c->Reverse(); + if (!i) + start = c->StartPoint(); + else require(last.Distance(c->StartPoint()) * L <= 1e-6); - } last = c->EndPoint(); curves.push_back(c); + reversed.push_back(flip); } require(start.Distance(last) * L <= 1e-6); - auto z = solve(A, rhs); + // Consecutive trims end exactly where the next starts, so the wire closes on their vertices. + for (int i = 0; i < count; ++i) + { + const auto& a = curves[i]; + const auto& b = curves[(i + 1) % count]; + gp_Pnt2d p((a->EndPoint().XY() + b->StartPoint().XY()) / 2); + setPole(a, false, p); + setPole(b, true, p); + } + std::vector polygon; + for (auto& c : curves) + for (int j = 0; j < 4 * N; ++j) + polygon.push_back(c->Value(c->FirstParameter() + (c->LastParameter() - c->FirstParameter()) * j / (4. * N))); + // Without supports to continue, the freedom left is faired by the squared Hessian. + Prior prior = reference(count, fs, ss, polygon, inv, xmin, ymin, L); + bool continued = !prior.rows.empty(), exact; + if (!continued) + prior = hessian(); + auto z = solve(A, rhs, kinds, prior, continued, exact); TColgp_Array2OfPnt poles(1, n, 1, n); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) poles(i + 1, j + 1) = gp_Pnt(xmin + L * i / N, ymin + L * j / N, z(1 + i * n + j)).Transformed(f); Handle(Geom_BezierSurface) base = new Geom_BezierSurface(poles); - BRepBuilderAPI_MakeWire wire; + // Validate the built patch against its supports, densely along every edge. + double gap = 0, angle = 0, bend = 0; + for (int i = 0; i < count; ++i) + { + BRepAdaptor_Curve2d pc(es[i], fs[i]); + BRepAdaptor_Surface s(fs[i]); + for (int j = 0; j <= 4 * N; ++j) + { + const double t = j / (4. * N), te = reversed[i] ? 1 - t : t; + gp_Pnt2d uv; + gp_Vec2d duv; + pc.D1(pc.FirstParameter() * (1 - te) + pc.LastParameter() * te, uv, duv); + gp_Pnt P, Q; + gp_Vec su, sv, suu, svv, suv, bu, bv, buu, bvv, buv; + gp_Pnt2d q = curves[i]->Value(curves[i]->FirstParameter() * (1 - t) + curves[i]->LastParameter() * t); + s.D2(uv.X(), uv.Y(), P, su, sv, suu, svv, suv); + base->D2(q.X(), q.Y(), Q, bu, bv, buu, bvv, buv); + gap = std::max(gap, P.Distance(Q)); + if (orders[i] == 0) + continue; + gp_Vec ns = su.Crossed(sv).Normalized(), nb = bu.Crossed(bv).Normalized(); + if (ns.Dot(nb) < 0) + nb.Reverse(); + angle = std::max(angle, ns.Angle(nb)); + if (orders[i] == 1) + continue; + const gp_Vec d = ns.Crossed(su * duv.X() + sv * duv.Y()).Normalized(); + const double ks = curvature(su, sv, suu, svv, suv, d, ns); + const double kb = curvature(bu, bv, buu, bvv, buv, d, nb); + bend = std::max(bend, std::abs(ks - kb) / std::max(std::abs(ks), 1 / L)); + } + } +#ifdef GRAPHPATCH_TRACE + printf("[graphpatch] %s fit, %s; gap %.3g angle %.3g curvature %.3g\n", + exact ? "exact" : "best", + continued ? "supports continued" : "Hessian faired", + gap, + angle, + bend); +#endif + require(gap <= TolGap && angle <= TolAngle && bend <= TolCurvature); + BRepBuilderAPI_MakeWire wire; for (auto& c : curves) wire.Add(BRepBuilderAPI_MakeEdge(c, base).Edge()); auto face = BRepBuilderAPI_MakeFace(base, wire.Wire(), true).Face(); - require(BRepLib::BuildCurves3d(face, 1e-8) && BRepCheck_Analyzer(face).IsValid()); + require(BRepLib::BuildCurves3d(face, 1e-8)); + // The edges are on the patch; their tolerance covers the gap to the supports' edges. + if (gap > Precision::Confusion()) + { + BRep_Builder builder; + for (TopExp_Explorer ex(face, TopAbs_EDGE); ex.More(); ex.Next()) + { + const auto& e = TopoDS::Edge(ex.Current()); + builder.UpdateEdge(e, std::max(gap, BRep_Tool::Tolerance(e))); + } + for (TopExp_Explorer ex(face, TopAbs_VERTEX); ex.More(); ex.Next()) + { + const auto& v = TopoDS::Vertex(ex.Current()); + builder.UpdateVertex(v, std::max(gap, BRep_Tool::Tolerance(v))); + } + } + require(BRepCheck_Analyzer(face).IsValid()); out = face; return true; } diff --git a/src/cpp/patches/occt/overlay/BRepOffsetAPI_GraphPatch.hxx b/src/cpp/patches/occt/overlay/BRepOffsetAPI_GraphPatch.hxx index 40868966..3563061e 100644 --- a/src/cpp/patches/occt/overlay/BRepOffsetAPI_GraphPatch.hxx +++ b/src/cpp/patches/occt/overlay/BRepOffsetAPI_GraphPatch.hxx @@ -5,10 +5,29 @@ #include #include -//! Degree-eight variational graph patch. The arrays contain Count ordered seam -//! edges, their incident support faces and geometric continuity orders 0/1/2. -//! Frame maps the local graph to world coordinates; null fits a PCA plane. -//! On a failed domain, fit or topology check return false, leaving Result alone. +//! Degree-eight variational graph patch filling one loop of Count edges. +//! +//! Input contract: Edges[i] is an edge of Supports[i], the patch meets that support with +//! geometric continuity Orders[i] (0, 1 or 2: C0, G1, G2); consecutive edges (and the last with +//! the first) share an end point, each edge in either orientation, so the loop is closed and +//! ordered. Frame maps the local graph to world coordinates (no scaling, no mirror); null fits +//! a PCA plane to the boundary. The loop must project one-to-one onto the frame plane, and a +//! G1/G2 support must be a graph over it along its edge. +//! +//! The patch is a degree-eight Bezier graph over the frame plane, trimmed by the projected loop. +//! Boundary data a degree-eight graph can meet (planar supports, polynomial ones) are met +//! exactly (to ~1e-10). Others (curved supports: cylinder, sphere, B-spline) are fitted as +//! a whole; the patch is then accepted if, densely along every edge, it is within 1e-3 of the +//! support edge, its normal within 1e-3 rad of the support's (G1, G2) and its cross-boundary +//! normal curvature within 5% of the support's (G2), and the edges of the result carry that +//! gap as their tolerance. The freedom the boundary leaves follows the supports' own surfaces +//! continued over the loop, where they are graphs over the frame (a hole cut in one surface is +//! filled by that surface, to the accuracy of a degree-eight graph); otherwise the patch +//! minimises its squared Hessian. +//! +//! Returns false, leaving Result alone, on a broken contract, a loop that is no graph over the +//! frame, a fit outside those limits or an invalid face. With GRAPHPATCH_TRACE defined at the +//! compilation of the implementation, the refusing check and the fit's measures are printed. class BRepOffsetAPI_GraphPatch { public: diff --git a/src/cpp/patches/occt/tests/CMakeLists.txt b/src/cpp/patches/occt/tests/CMakeLists.txt new file mode 100644 index 00000000..73c190f1 --- /dev/null +++ b/src/cpp/patches/occt/tests/CMakeLists.txt @@ -0,0 +1,47 @@ +# Kernel-level checks of the OCCT patch set, built against an installed patched prefix: +# cmake -S src/cpp/patches/occt/tests -B -G Ninja -DOpenCASCADE_DIR=/lib/cmake/opencascade +# With -DYPATCH_DEV=ON the overlay sources of this checkout are compiled in, so kernel edits +# can be tried without rebuilding the prefix (the prefix's own copies are then shadowed). +cmake_minimum_required(VERSION 3.20) +project(occt_patch_tests LANGUAGES CXX) +find_package(OpenCASCADE CONFIG REQUIRED) +option(YPATCH_DEV "compile the checkout's Y-patch overlay sources into the tools" OFF) +# with YPATCH_DEV: a directory holding the patched BRepFilletAPI_MakeFillet.hxx/.cxx (patch 0004 +# applied), compiled in as well so that the tools exercise it +set(YPATCH_MAKEFILLET "" CACHE PATH "patched BRepFilletAPI_MakeFillet sources") +set(overlay ${CMAKE_CURRENT_SOURCE_DIR}/../overlay) +set(dev_sources) +if(YPATCH_DEV) + set(dev_sources ${overlay}/BRepFilletAPI_YPatch.cxx ${overlay}/BRepFilletAPI_YPatchBuild.cxx) + if(YPATCH_MAKEFILLET) + list(APPEND dev_sources ${YPATCH_MAKEFILLET}/BRepFilletAPI_MakeFillet.cxx) + endif() +endif() +foreach(name cases inspect check shellfillet wires sidetail fixsmall) + add_executable(${name} ${name}.cxx ${dev_sources}) + target_compile_features(${name} PRIVATE cxx_std_17) + if(YPATCH_DEV) + target_include_directories(${name} BEFORE PRIVATE ${overlay} ${YPATCH_MAKEFILLET}) + target_compile_definitions(${name} PRIVATE YPATCH_TRACE) + endif() + target_include_directories(${name} PRIVATE ${OpenCASCADE_INCLUDE_DIR}) + if(NOT OpenCASCADE_BUILD_SHARED_LIBS) + target_compile_definitions(${name} PRIVATE OCCT_STATIC_BUILD _USE_MATH_DEFINES) + endif() + target_link_libraries(${name} PRIVATE TKOffset TKFillet TKDESTEP TKBool TKBO) +endforeach() +# graphpatch: BRepOffsetAPI_GraphPatch on planar and curved supports (cylinder and sphere windows, +# 3..6-sided holes in a B-spline sheet, plane holes, wall loops); exit status 1 on a refusal or a +# patch off its limits. With YPATCH_DEV the checkout's graph patch is compiled in, tracing its fit. +add_executable(graphpatch graphpatch.cxx) +if(YPATCH_DEV) + target_sources(graphpatch PRIVATE ${overlay}/BRepOffsetAPI_GraphPatch.cxx) + target_include_directories(graphpatch BEFORE PRIVATE ${overlay}) + target_compile_definitions(graphpatch PRIVATE GRAPHPATCH_TRACE) +endif() +target_compile_features(graphpatch PRIVATE cxx_std_17) +target_include_directories(graphpatch PRIVATE ${OpenCASCADE_INCLUDE_DIR}) +if(NOT OpenCASCADE_BUILD_SHARED_LIBS) + target_compile_definitions(graphpatch PRIVATE OCCT_STATIC_BUILD _USE_MATH_DEFINES) +endif() +target_link_libraries(graphpatch PRIVATE TKOffset TKFillet TKBool TKBO TKMesh) diff --git a/src/cpp/patches/occt/tests/cases.cxx b/src/cpp/patches/occt/tests/cases.cxx new file mode 100644 index 00000000..70b658ac --- /dev/null +++ b/src/cpp/patches/occt/tests/cases.cxx @@ -0,0 +1,267 @@ +// Runs the Y-junction case family: the standard algorithm, a plain MakeFillet (the default +// Y fallback), then the Y patch. +// cases [name-filter | =exact-name] +// Environment: YPATCH_SRC_ROUNDTRIP reads each input +// back from BREP first. Writes src-.brep and, on success, case-.brep. +#include "cases.hxx" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static TopoDS_Shape roundtrip(const TopoDS_Shape& s) +{ + std::stringstream ss; + BRepTools::Write(s, ss); + TopoDS_Shape back; + BRep_Builder b; + BRepTools::Read(back, ss, b); + return back; +} + +int main(int argc, char** argv) +{ + int failures = 0; + std::vector all = family(); + if (const char* path = std::getenv("YPATCH_SDK_FIXTURE")) // the SDK's plate/post (binary BREP) + { + TopoDS_Shape s; + BinTools::Read(s, path); + for (const double r : {1., 2.5, 5., 8., 12.}) + { + all.push_back({"sdk-plate-post-" + radiusTag(r), s, + {{gp_Pnt(35.3553, -35.3553, 40), r}, {gp_Pnt(35.3553, 35.3553, 40), r}, {gp_Pnt(75, -50, 40), r}}}); + all.push_back({"sdk-plate-post-both-sides-" + radiusTag(r), s, + {{gp_Pnt(35.3553, -35.3553, 40), r}, {gp_Pnt(35.3553, 35.3553, 40), r}, {gp_Pnt(75, -50, 40), r}, + {gp_Pnt(75, 50, 40), r}}}); + } + } + for (auto& c : all) + { + const std::string want = argc > 1 ? argv[1] : ""; + if (!want.empty() && (want[0] == '=' ? c.name != want.substr(1) : c.name.find(want) == std::string::npos)) + continue; + std::printf("== %s\n", c.name.c_str()); + if (std::getenv("YPATCH_SRC_ROUNDTRIP")) + c.shape = roundtrip(c.shape); + std::vector> picked; // in pick order: runs are reproducible + TopTools_DataMapOfShapeReal radii; + for (auto& [p, r] : c.picks) + { + picked.emplace_back(edge_at(c.shape, p), r); + radii.Bind(picked.back().first, r); + } + // the standard algorithm alone (ChFi3d, as MakeFillet runs it, without any Y strategy) + bool standardSound = false; + { + ChFi3d_FilBuilder f(c.shape); + for (auto& [e, r] : picked) + f.Add(r, e); + try + { + f.Compute(); + if (f.IsDone()) + { + const int si = si_count(f.Shape()); + standardSound = valid(f.Shape()) && si == 0; + std::printf(" standard: done valid %d si %d\n", valid(f.Shape()), si); + } + else + std::printf(" standard: not done\n"); + } + catch (Standard_Failure& e) + { + std::printf(" standard: throws %s\n", e.GetMessageString()); + } + } + // a plain MakeFillet (no SetYPatch): with a junction it must succeed; where the standard + // result is sound it must be that result + const bool hasJunction = !BRepFilletAPI_YPatch::Detect(c.shape, radii).IsEmpty(); + bool pinchOk = false; + if (hasJunction) + { + TopoDS_Shape o; + Handle(BRepTools_History) hh; + NCollection_Vector rr; + pinchOk = BRepFilletAPI_YPatch::Perform(c.shape, radii, o, hh, rr, Standard_True); + } + { + BRepFilletAPI_MakeFillet plain(c.shape); + for (auto& [e, r] : picked) + if (plain.Contour(e) == 0) + plain.Add(r, e); + bool ok = false, sound = false; + try + { + plain.Build(); + ok = plain.IsDone(); + sound = ok && valid(plain.Shape()) && si_count(plain.Shape()) == 0; + } + catch (Standard_Failure&) + { + } + const bool pinched = ok && plain.NbYPatches() > 0 && plain.YPatchJunction(1).Pinch; + const char* path = !ok ? "-" + : plain.YPatchFallback() ? (pinched ? "pinch fallback" : "Y fallback") + : plain.NbYPatches() ? "Y" + : "standard"; + bool pass = true; + if (hasJunction && !c.expect_refusal) + pass = sound; + // where the standard result fails and a pinch can be built, the fallback is the pinch + if (hasJunction && !standardSound && pinchOk) + pass = pass && plain.YPatchFallback() && pinched; + if (standardSound) + pass = pass && ok && !plain.YPatchFallback() && plain.NbYPatches() == 0; + std::printf(" plain: done %d sound %d path %s%s\n", (int)ok, (int)sound, path, pass ? "" : " FAILED"); + failures += pass ? 0 : 1; + } + auto js = BRepFilletAPI_YPatch::Detect(c.shape, radii); + std::printf(" junctions %d", js.Length()); + for (auto& j : js) + std::printf(" [support angle %.3f deg]", j.SupportAngle * 180 / M_PI); + std::printf("\n"); + for (const bool pinchMode : {false, true}) + { + TopoDS_Shape out; + Handle(BRepTools_History) h; + NCollection_Vector rep; + auto t0 = std::chrono::steady_clock::now(); + bool ok = BRepFilletAPI_YPatch::Perform(c.shape, radii, out, h, rep, pinchMode); + double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + std::printf(" %s: ok %d %.0f ms", pinchMode ? "pinch" : "ypatch", ok, ms); + if (ok == c.expect_refusal) + ++failures; + if (!ok && c.expect_refusal) + std::printf(" (refused, as expected)"); + if (ok) + { + std::printf(" valid %d si %d faces %d", valid(out), si_count(out), count(out, TopAbs_FACE)); + // Strict history, from Perform and from the entry point the SDK uses (MakeFillet with + // SetYPatch): no input face is deleted (none lies wholly inside a removed wedge in + // this family), its images are result faces; a junction edge generates its band and + // its ribbon (>= 2 faces), every selected edge generates >= 1; every result face is an + // image of an input face or generated by a selected edge. + TopTools_IndexedMapOfShape junctionEdges; + for (auto& j : BRepFilletAPI_YPatch::Detect(c.shape, radii)) + { + junctionEdges.Add(j.Concave); + junctionEdges.Add(j.Convex); + } + // (SetYPatch(true) is the Y transition: checked in the Y run only) + BRepFilletAPI_MakeFillet mf(c.shape); + mf.SetYPatch(Standard_True); + for (auto& [e, r] : picked) + if (mf.Contour(e) == 0) + mf.Add(r, e); + bool viaMakeFillet = false; + if (!pinchMode) + { + mf.Build(); + viaMakeFillet = mf.IsDone() && mf.NbYPatches() == rep.Length(); + std::printf(" makefillet %s", viaMakeFillet ? "ok" : "FAILED"); + if (!viaMakeFillet) + std::printf(" [done %d y-patches %d, expected %d]", (int)mf.IsDone(), mf.NbYPatches(), rep.Length()); + failures += viaMakeFillet ? 0 : 1; + } + using List = TopTools_ListOfShape; + auto strict = [&](const char* tag, const TopoDS_Shape& result, const std::function& deleted, + const std::function& modified, + const std::function& generated) { + TopTools_IndexedMapOfShape outFaces, inFaces, covered; + TopExp::MapShapes(result, TopAbs_FACE, outFaces); + TopExp::MapShapes(c.shape, TopAbs_FACE, inFaces); + bool good = true; + for (int i = 1; i <= inFaces.Extent(); ++i) + { + const TopoDS_Shape& f = inFaces(i); + List m = modified(f); + if (m.IsEmpty() && !deleted(f)) + m.Append(f); + bool ok = !deleted(f) && !m.IsEmpty(); + for (List::Iterator it(m); it.More(); it.Next()) + { + ok = ok && outFaces.Contains(it.Value()); + covered.Add(it.Value()); + } + if (!ok) + std::printf(" [%s: face %d deleted %d images %d]", tag, i, (int)deleted(f), m.Extent()); + good = good && ok; + } + for (auto& [e, r] : picked) + { + int n = 0; + const List g = generated(e); + for (List::Iterator it(g); it.More(); it.Next()) + if (outFaces.Contains(it.Value())) + { + ++n; + covered.Add(it.Value()); + } + const int need = junctionEdges.Contains(e) ? 2 : 1; + if (n < need) + std::printf(" [%s: edge at (%.1f %.1f %.1f) generates %d < %d]", tag, mid(e).X(), mid(e).Y(), mid(e).Z(), n, need); + good = good && n >= need; + } + // faces generated by any input edge are tracked (a seed drags its tangent chain along) + TopTools_IndexedMapOfShape inEdges; + TopExp::MapShapes(c.shape, TopAbs_EDGE, inEdges); + for (int i = 1; i <= inEdges.Extent(); ++i) + { + const List g = generated(inEdges(i)); + for (List::Iterator it(g); it.More(); it.Next()) + covered.Add(it.Value()); + } + for (int i = 1; i <= outFaces.Extent(); ++i) + if (!covered.Contains(outFaces(i))) + { + std::printf(" [%s: result face %d untracked]", tag, i); + good = false; + } + return good; + }; + bool historyOk = + strict("perform", out, [&](const TopoDS_Shape& s) { return h->IsRemoved(s); }, + [&](const TopoDS_Shape& s) { return h->Modified(s); }, [&](const TopoDS_Shape& s) { return h->Generated(s); }) + && (!viaMakeFillet + || strict("makefillet", mf.Shape(), [&](const TopoDS_Shape& s) { return mf.IsDeleted(s); }, + [&](const TopoDS_Shape& s) { return mf.Modified(s); }, + [&](const TopoDS_Shape& s) { return mf.Generated(s); })); + // the default fallback (no SetYPatch) answers the same history when it takes the Y path + BRepFilletAPI_MakeFillet plain(c.shape); + for (auto& [e, r] : picked) + if (plain.Contour(e) == 0) + plain.Add(r, e); + if (!pinchMode) + plain.Build(); + const bool fallbackOk = + pinchMode || !plain.IsDone() || !plain.YPatchFallback() + || strict("fallback", plain.Shape(), [&](const TopoDS_Shape& s) { return plain.IsDeleted(s); }, + [&](const TopoDS_Shape& s) { return plain.Modified(s); }, + [&](const TopoDS_Shape& s) { return plain.Generated(s); }); + historyOk = historyOk && fallbackOk; + std::printf(" history %s\n", historyOk ? "ok" : "BROKEN"); + failures += historyOk ? 0 : 1; + for (auto& j : rep) + std::printf(" P*(%.4f %.4f %.4f) seam %.2e deg band %.2e deg [%s end convex %.3g concave %.3g contact %.2e]\n", + j.Split.X(), j.Split.Y(), j.Split.Z(), j.SeamAngle * 180 / M_PI, j.BandAngle * 180 / M_PI, + j.Pinch ? "pinch" : "Y", j.EndAngle[0] * 180 / M_PI, j.EndAngle[1] * 180 / M_PI, + j.ContactAngle * 180 / M_PI); + BRepTools::Write(out, ((pinchMode ? "pinch-" : "case-") + c.name + ".brep").c_str()); + } + else + std::printf("\n"); + } + BRepTools::Write(c.shape, ("src-" + c.name + ".brep").c_str()); + } + std::printf("failures %d\n", failures); + return failures; +} diff --git a/src/cpp/patches/occt/tests/cases.hxx b/src/cpp/patches/occt/tests/cases.hxx new file mode 100644 index 00000000..d9688c96 --- /dev/null +++ b/src/cpp/patches/occt/tests/cases.hxx @@ -0,0 +1,194 @@ +#pragma once +// The Y-junction case family: a concave and a convex fillet edge meeting, tangentially or +// nearly so, on a common face, with their other supports tangent or nearly tangent. +#include "fixtures.hxx" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct Case +{ + std::string name; + TopoDS_Shape shape; + std::vector> picks; // a point on each selected edge, radius + bool expect_refusal = false; // outside the domain: Perform must say no +}; + +inline TopoDS_Edge edge_at(const TopoDS_Shape& s, const gp_Pnt& p) +{ + TopTools_IndexedMapOfShape m; + TopExp::MapShapes(s, TopAbs_EDGE, m); + TopoDS_Vertex v = BRepBuilderAPI_MakeVertex(p); + double best = 1e100; + TopoDS_Edge out; + for (int i = 1; i <= m.Extent(); ++i) + { + BRepExtrema_DistShapeShape d(v, m(i)); + if (d.IsDone() && d.Value() < best) + { + best = d.Value(); + out = TopoDS::Edge(m(i)); + } + } + if (best > 1e-6) + std::printf(" warning: no edge at (%g %g %g), nearest %g\n", p.X(), p.Y(), p.Z(), best); + return out; +} + +inline TopoDS_Shape prism_xy(const std::vector& poly, double z0, double z1) +{ + BRepBuilderAPI_MakePolygon mp; + for (auto& p : poly) + mp.Add(gp_Pnt(p.X(), p.Y(), z0)); + mp.Close(); + auto f = BRepBuilderAPI_MakeFace(mp.Wire(), true).Face(); + return BRepPrimAPI_MakePrism(f, gp_Vec(0, 0, z1 - z0)).Shape(); +} + +inline TopoDS_Shape post(double R, double H) +{ + return BRepPrimAPI_MakeCylinder(gp_Ax2(gp_Pnt(), gp_Dir(0, 0, 1), gp_Dir(-1, 0, 0)), R, H).Shape(); +} + +inline TopoDS_Shape moved(const TopoDS_Shape& s, const gp_Trsf& t) +{ + return BRepBuilderAPI_Transform(s, t, true).Shape(); +} + +// r1, r2.5, r12: a radius in a case name +inline std::string radiusTag(double r) +{ + char buf[32]; + std::snprintf(buf, sizeof buf, "r%g", r); + return buf; +} + +inline std::vector family() +{ + std::vector cs; + const double R = 50, h = 40, L = 150; + // 1. post flush with the plate side (the reference sample), several radii + for (double r : {1., 2.5, 5., 8., 12.}) + cs.push_back({"flush-" + radiusTag(r), plate_post(R, h), {{gp_Pnt(R, 0, h), r}, {gp_Pnt(75, -R, h), r}}}); + // 1b. the cylinder's default seam (+X) lies on the root, which is then two quarter arcs + // (what make_cylinder_rsolid gives every SDK user) + { + auto c = BRepPrimAPI_MakeCylinder(gp_Ax2(gp_Pnt(), gp_Dir(0, 0, 1)), R, 2 * h).Shape(); + auto b = BRepPrimAPI_MakeBox(gp_Pnt(0, -R, 0), 3 * R, 2 * R, h).Shape(); + const double q = R / std::sqrt(2.); + const TopoDS_Shape s = fuse(c, b); + for (const double r : {1., 2.5, 5., 8., 12.}) + { + const std::string tag = radiusTag(r); + cs.push_back({"flush-seam-on-root-" + tag, s, {{gp_Pnt(q, -q, h), r}, {gp_Pnt(q, q, h), r}, {gp_Pnt(75, -R, h), r}}}); + cs.push_back({"flush-seam-on-root-both-sides-" + tag, s, + {{gp_Pnt(q, -q, h), r}, {gp_Pnt(q, q, h), r}, {gp_Pnt(75, -R, h), r}, {gp_Pnt(75, R, h), r}}}); + } + } + // 1c. the seam at every eighth of a turn (angle of the cylinder's X direction) + for (int deg = 0; deg < 360; deg += 45) + { + const double a = deg * M_PI / 180; + auto c = BRepPrimAPI_MakeCylinder(gp_Ax2(gp_Pnt(), gp_Dir(0, 0, 1), gp_Dir(std::cos(a), std::sin(a), 0)), R, 2 * h).Shape(); + auto b = BRepPrimAPI_MakeBox(gp_Pnt(0, -R, 0), 3 * R, 2 * R, h).Shape(); + Case sc{"seam-at-" + std::to_string(deg), fuse(c, b), {{gp_Pnt(75, -R, h), 5}}}; + for (double t : {-85., -60., -35., -10., 10., 35., 60., 85.}) // root points clear of every seam angle + sc.picks.push_back({gp_Pnt(R * std::cos(t * M_PI / 180), R * std::sin(t * M_PI / 180), h), 5}); + cs.push_back(sc); + } + // 2. both plate sides flush: two junctions on one concave edge + cs.push_back({"flush-both-sides", plate_post(R, h), {{gp_Pnt(R, 0, h), 5}, {gp_Pnt(75, -R, h), 5}, {gp_Pnt(75, R, h), 5}}}); + // 3. unequal radii + cs.push_back({"flush-r3-r7", plate_post(R, h), {{gp_Pnt(R, 0, h), 3}, {gp_Pnt(75, -R, h), 7}}}); + cs.push_back({"flush-r7-r3", plate_post(R, h), {{gp_Pnt(R, 0, h), 7}, {gp_Pnt(75, -R, h), 3}}}); + // 4. arbitrary placement + { + gp_Trsf t; + t.SetRotation(gp_Ax1(gp_Pnt(3, -7, 11), gp_Dir(1, 2, 3)), 0.7); + gp_Trsf m; + m.SetTranslation(gp_Vec(10, -20, 5)); + t = m * t; + Case c{"flush-moved", moved(plate_post(R, h), t), {}}; + c.picks = {{gp_Pnt(R, 0, h).Transformed(t), 5}, {gp_Pnt(75, -R, h).Transformed(t), 5}}; + cs.push_back(c); + } + // 5. near tangency: the plate side turned outward by d degrees about the junction line + for (double d : {2., 5., 10.}) + { + const double a = d * M_PI / 180; + auto plate = prism_xy({{0, -R}, {L, -R - L * std::tan(a)}, {L, R}, {0, R}}, 0, h); + cs.push_back({"side-out-" + std::to_string(int(d)) + "deg", fuse(post(R, 2 * h), plate), + {{gp_Pnt(R, 0, h), 5}, {gp_Pnt(75, -R - 75 * std::tan(a), h), 5}}}); + } + // 6. near tangency: the plate side turned inward (it enters the post; the junction moves to + // where it leaves the post). The plate starts at x = 1 and its other side is y = R/2, so + // that its end face lies wholly inside the post (no sliver faces). + for (double d : {2., 5.}) + { + const double a = d * M_PI / 180; + auto plate = prism_xy({{-R, -R - R * std::tan(a)}, {L, -R + L * std::tan(a)}, {L, R / 2}, {-R, R / 2}}, 0, h); + auto cut = fuse(post(R, 2 * h), + BRepAlgoAPI_Common(plate, BRepPrimAPI_MakeBox(gp_Pnt(1, -2 * R, 0), L, 4 * R, h).Shape()).Shape()); + cs.push_back({"side-in-" + std::to_string(int(d)) + "deg", cut, + {{gp_Pnt(R * std::cos(0.2), R * std::sin(0.2), h), 5}, {gp_Pnt(120, -R + 120 * std::tan(a), h), 5}}}); + } + // 7. planar wedge: a block whose face makes d degrees with the plate side; the Y spans about + // (r_in + r_out) / tan(d) along the edges, so the block is long enough for it. The short + // variant ends the concave edge before the bands separate: it must be refused. + struct Wedge + { + double d, e; + bool refuse; + const char* suffix; + }; + for (const Wedge& wg : {Wedge{5., 140., false, ""}, Wedge{5., 60., true, "-short"}, Wedge{10., 60., false, ""}, + Wedge{15., 60., false, ""}}) + { + const double a = wg.d * M_PI / 180, w = 40, e = wg.e; + auto plate = BRepPrimAPI_MakeBox(gp_Pnt(0, -R, 0), L, 2 * R, h).Shape(); + auto block = prism_xy({{-w, -R - w * std::tan(a)}, {e, -R + e * std::tan(a)}, {e, R}, {-w, R}}, 0, 2 * h); + Case c{"wedge-" + std::to_string(int(wg.d)) + "deg" + wg.suffix, fuse(plate, block), + {{gp_Pnt(e / 2, -R + e / 2 * std::tan(a), h), 4}, {gp_Pnt(e + (L - e) / 2, -R, h), 4}}}; + c.expect_refusal = wg.refuse; + cs.push_back(c); + } + // 8. curved plate side: a large arc tangent to the post at the junction + { + // The rim (radius R2) leaves the junction, then continues tangentially as a straight side + // that meets the square plate end: each band's far end is a standard one. + const double R2 = 140, a0 = 0.5, top = 0.5 * R; + auto rp = [&](double a) { return gp_Pnt(R2 * std::sin(a), -R + R2 - R2 * std::cos(a), 0); }; + const gp_Pnt p0 = rp(0), p1 = rp(a0), p2(L, p1.Y() + (L - p1.X()) * std::tan(a0), 0); + BRepBuilderAPI_MakeWire w; + w.Add(BRepBuilderAPI_MakeEdge(GC_MakeArcOfCircle(p0, rp(a0 / 2), p1).Value()).Edge()); + w.Add(BRepBuilderAPI_MakeEdge(p1, p2).Edge()); + w.Add(BRepBuilderAPI_MakeEdge(p2, gp_Pnt(L, top, 0)).Edge()); + w.Add(BRepBuilderAPI_MakeEdge(gp_Pnt(L, top, 0), gp_Pnt(0, top, 0)).Edge()); + w.Add(BRepBuilderAPI_MakeEdge(gp_Pnt(0, top, 0), p0).Edge()); + auto plate = BRepPrimAPI_MakePrism(BRepBuilderAPI_MakeFace(w.Wire(), true).Face(), gp_Vec(0, 0, h)).Shape(); + gp_Pnt rim = rp(a0 / 2).Translated(gp_Vec(0, 0, h)); + cs.push_back({"curved-side", fuse(post(R, 2 * h), plate), {{gp_Pnt(R, 0, h), 5}, {rim, 5}}}); + } + // 9. inclined common face: the plate top rises along x + { + const double s = 0.15; + BRepBuilderAPI_MakePolygon mp; + for (auto p : {gp_Pnt(0, -R, 0), gp_Pnt(L, -R, 0), gp_Pnt(L, -R, h + s * L), gp_Pnt(0, -R, h)}) + mp.Add(p); + mp.Close(); + auto plate = BRepPrimAPI_MakePrism(BRepBuilderAPI_MakeFace(mp.Wire(), true).Face(), gp_Vec(0, 1.5 * R, 0)).Shape(); + const double x = R * std::cos(0.3); + cs.push_back({"inclined-top", fuse(post(R, 3 * h), plate), + {{gp_Pnt(x, R * std::sin(0.3), h + s * x), 5}, {gp_Pnt(75, -R, h + s * 75), 5}}}); + } + return cs; +} diff --git a/src/cpp/patches/occt/tests/check.cxx b/src/cpp/patches/occt/tests/check.cxx new file mode 100644 index 00000000..ae0daf94 --- /dev/null +++ b/src/cpp/patches/occt/tests/check.cxx @@ -0,0 +1,28 @@ +#include "fixtures.hxx" +#include +#include +#include +#include +#include +#include +int main(int argc, char** argv) { + BRep_Builder b; TopoDS_Shape s; BRepTools::Read(s, argv[1], b); + BRepCheck_Analyzer an(s); + std::printf("valid %d\n", an.IsValid()); + for (auto t : {TopAbs_VERTEX, TopAbs_EDGE, TopAbs_WIRE, TopAbs_FACE, TopAbs_SHELL, TopAbs_SOLID}) { + TopTools_IndexedMapOfShape m; TopExp::MapShapes(s, t, m); + for (int i = 1; i <= m.Extent(); ++i) { + auto r = an.Result(m(i)); if (r.IsNull()) continue; + for (BRepCheck_ListIteratorOfListOfStatus it(r->Status()); it.More(); it.Next()) + if (it.Value() != BRepCheck_NoError) { + gp_Pnt p; if (t == TopAbs_EDGE) p = mid(TopoDS::Edge(m(i))); else if (t == TopAbs_VERTEX) p = BRep_Tool::Pnt(TopoDS::Vertex(m(i))); else { GProp_GProps g; BRepGProp::LinearProperties(m(i), g); p = g.CentreOfMass(); } + std::printf("type %d #%d status %d at (%.3f %.3f %.3f)\n", (int)t, i, (int)it.Value(), p.X(), p.Y(), p.Z()); } + // context statuses (edge in face etc.) + if (t == TopAbs_EDGE || t == TopAbs_WIRE) { + TopTools_IndexedMapOfShape fm; TopExp::MapShapes(s, TopAbs_FACE, fm); + for (int k = 1; k <= fm.Extent(); ++k) { r->InitContextIterator(); for (; r->MoreShapeInContext(); r->NextShapeInContext()) { + for (BRepCheck_ListIteratorOfListOfStatus it(r->StatusOnShape()); it.More(); it.Next()) if (it.Value() != BRepCheck_NoError) { gp_Pnt p = t == TopAbs_EDGE ? mid(TopoDS::Edge(m(i))) : gp_Pnt(); std::printf("type %d #%d context status %d at (%.3f %.3f %.3f)\n", (int)t, i, (int)it.Value(), p.X(), p.Y(), p.Z()); } } break; } + } + } + } +} diff --git a/src/cpp/patches/occt/tests/fixsmall.cxx b/src/cpp/patches/occt/tests/fixsmall.cxx new file mode 100644 index 00000000..58bec9a2 --- /dev/null +++ b/src/cpp/patches/occt/tests/fixsmall.cxx @@ -0,0 +1,18 @@ +// fixsmall : merge edges shorter than tol (ShapeFix_Wireframe), then validity and SI. +#include "fixtures.hxx" +#include +#include +int main(int, char** argv) +{ + BRep_Builder b; + TopoDS_Shape s; + BRepTools::Read(s, argv[1], b); + std::printf("before: valid %d si %d edges %d\n", valid(s), si_count(s), count(s, TopAbs_EDGE)); + ShapeFix_Wireframe fix(s); + fix.SetPrecision(atof(argv[2])); + fix.SetMaxTolerance(atof(argv[2])); + fix.ModeDropSmallEdges() = Standard_True; + fix.FixSmallEdges(); + const TopoDS_Shape r = fix.Shape(); + std::printf("after: valid %d si %d edges %d\n", valid(r), si_count(r), count(r, TopAbs_EDGE)); +} diff --git a/src/cpp/patches/occt/tests/fixtures.hxx b/src/cpp/patches/occt/tests/fixtures.hxx new file mode 100644 index 00000000..24d338d8 --- /dev/null +++ b/src/cpp/patches/occt/tests/fixtures.hxx @@ -0,0 +1,43 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +inline TopoDS_Shape fuse(const TopoDS_Shape& a, const TopoDS_Shape& b) { + BRepAlgoAPI_Fuse f(a, b); f.SimplifyResult(); return f.Shape(); +} +// The research sample: post radius R (height 2h) flush with the plate side, plate 3R x 2R x h. +inline TopoDS_Shape plate_post(double R = 50, double h = 40) { + auto c = BRepPrimAPI_MakeCylinder(gp_Ax2(gp_Pnt(), gp_Dir(0, 0, 1), gp_Dir(-1, 0, 0)), R, 2 * h).Shape(); + auto b = BRepPrimAPI_MakeBox(gp_Pnt(0, -R, 0), 3 * R, 2 * R, h).Shape(); + return fuse(c, b); +} +inline gp_Pnt mid(const TopoDS_Edge& e) { + BRepAdaptor_Curve c(e); return c.Value((c.FirstParameter() + c.LastParameter()) / 2); +} +inline std::vector edges_where(const TopoDS_Shape& s, std::function f) { + TopTools_IndexedMapOfShape m; TopExp::MapShapes(s, TopAbs_EDGE, m); std::vector out; + for (int i = 1; i <= m.Extent(); ++i) if (f(TopoDS::Edge(m(i)))) out.push_back(TopoDS::Edge(m(i))); + return out; +} +inline int si_count(const TopoDS_Shape& s) { + BOPAlgo_CheckerSI c; c.SetLevelOfCheck(5); c.AddArgument(s); c.Perform(); + if (c.HasErrors()) return -1; + return c.DS().Interferences().Extent(); +} +inline bool valid(const TopoDS_Shape& s) { return !s.IsNull() && BRepCheck_Analyzer(s).IsValid(); } +inline int count(const TopoDS_Shape& s, TopAbs_ShapeEnum t) { TopTools_IndexedMapOfShape m; TopExp::MapShapes(s, t, m); return m.Extent(); } diff --git a/src/cpp/patches/occt/tests/graphpatch.cxx b/src/cpp/patches/occt/tests/graphpatch.cxx new file mode 100644 index 00000000..55a3c241 --- /dev/null +++ b/src/cpp/patches/occt/tests/graphpatch.cxx @@ -0,0 +1,394 @@ +// graphpatch: BRepOffsetAPI_GraphPatch on planar and curved supports. For each loop it prints +// the boundary gap to the supports (mm), the normal angle to the supports (rad, orders >= 1), +// the cross-boundary normal curvature difference (1/mm, order 2) and the deviation of the patch +// from the surface the loop was cut from (mm, sampled on a mesh of the patch); a refused or +// out-of-tolerance case makes the exit status non-zero. +#include "fixtures.hxx" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +struct Loop +{ + std::vector edges; + std::vector supports; +}; + +struct Metrics +{ + double gap = 0, angle = 0, curvature = 0, deviation = 0, area = 0; +}; + +double area(const TopoDS_Shape& s) +{ + GProp_GProps g; + BRepGProp::SurfaceProperties(s, g); + return g.Mass(); +} + +TopoDS_Face largest(const TopoDS_Shape& s, std::function keep) +{ + TopoDS_Face best; + double a = 0; + for (TopExp_Explorer ex(s, TopAbs_FACE); ex.More(); ex.Next()) + { + auto f = TopoDS::Face(ex.Current()); + if (keep(f) && area(f) > a) + { + a = area(f); + best = f; + } + } + return best; +} + +// The edges of one support passing `pick`, ordered by angle around their centroid in the plane +// spanned by (a, b): the ordered loop the graph patch takes. +Loop loop_on(const TopoDS_Face& support, + std::function pick, + const gp_Vec& a, + const gp_Vec& b) +{ + Loop l; + l.edges = edges_where(support, [&](const TopoDS_Edge& e) { return pick(mid(e)); }); + gp_XYZ c; + for (auto& e : l.edges) + c += mid(e).XYZ() / double(l.edges.size()); + auto angle = [&](const TopoDS_Edge& e) { + gp_Vec d(mid(e).XYZ() - c); + return std::atan2(d.Dot(b), d.Dot(a)); + }; + std::sort(l.edges.begin(), l.edges.end(), [&](auto& x, auto& y) { return angle(x) < angle(y); }); + l.supports.assign(l.edges.size(), support); + return l; +} + +TopoDS_Shape prism(const std::vector& polygon, const gp_Vec& along) +{ + BRepBuilderAPI_MakePolygon p; + for (auto& q : polygon) + p.Add(q); + p.Close(); + return BRepPrimAPI_MakePrism(BRepBuilderAPI_MakeFace(p.Wire()).Face(), along).Shape(); +} + +std::vector regular(int sides, double r, double z) +{ + std::vector v; + for (int i = 0; i < sides; ++i) + v.emplace_back(r * cos(2 * M_PI * i / sides + .3), r * sin(2 * M_PI * i / sides + .3), z); + return v; +} + +TopoDS_Shape tube_minus(const TopoDS_Shape& tool) +{ + auto tube = BRepAlgoAPI_Cut(BRepPrimAPI_MakeCylinder(30, 60).Shape(), + BRepPrimAPI_MakeCylinder(26, 60).Shape()) + .Shape(); + return BRepAlgoAPI_Cut(tube, tool).Shape(); +} + +TopoDS_Face outer_cylinder(const TopoDS_Shape& s) +{ + return largest(s, [](const TopoDS_Face& f) { + BRepAdaptor_Surface a(f); + return a.GetType() == GeomAbs_Cylinder && a.Cylinder().Radius() > 29; + }); +} + +// Normal curvature of s at (u, v) along the tangent direction d, the normal oriented along ref. +double normal_curvature(const Adaptor3d_Surface& s, double u, double v, const gp_Vec& d, const gp_Vec& ref) +{ + gp_Pnt p; + gp_Vec su, sv, suu, svv, suv; + s.D2(u, v, p, su, sv, suu, svv, suv); + gp_Vec nn = su.Crossed(sv).Normalized(); + if (nn.Dot(ref) < 0) + nn.Reverse(); + double E = su.Dot(su), F = su.Dot(sv), G = sv.Dot(sv), det = E * G - F * F; + double du = (G * d.Dot(su) - F * d.Dot(sv)) / det, dv = (E * d.Dot(sv) - F * d.Dot(su)) / det; + return (suu.Dot(nn) * du * du + 2 * suv.Dot(nn) * du * dv + svv.Dot(nn) * dv * dv) + / (E * du * du + 2 * F * du * dv + G * dv * dv); +} + +Metrics measure(const Loop& l, + const std::vector& orders, + const TopoDS_Face& patch, + std::function deviation) +{ + Metrics m; + Handle(Geom_Surface) g = BRep_Tool::Surface(patch); + GeomAdaptor_Surface ga(g); + for (size_t i = 0; i < l.edges.size(); ++i) + { + BRepAdaptor_Curve2d c(l.edges[i], l.supports[i]); + BRepAdaptor_Surface s(l.supports[i]); + for (int j = 0; j <= 64; ++j) + { + double t = c.FirstParameter() + (c.LastParameter() - c.FirstParameter()) * j / 64; + gp_Pnt2d uv; + gp_Vec2d duv; + c.D1(t, uv, duv); + gp_Pnt p; + gp_Vec su, sv; + s.D1(uv.X(), uv.Y(), p, su, sv); + GeomAPI_ProjectPointOnSurf proj(p, g); + if (!proj.NbPoints()) + { + m.gap = 1e100; + continue; + } + m.gap = std::max(m.gap, proj.LowerDistance()); + if (orders[i] < 1) + continue; + double pu, pv; + proj.LowerDistanceParameters(pu, pv); + gp_Pnt q; + gp_Vec qu, qv; + ga.D1(pu, pv, q, qu, qv); + gp_Vec ns = su.Crossed(sv).Normalized(), np = qu.Crossed(qv).Normalized(); + m.angle = std::max(m.angle, std::acos(std::min(1., std::abs(ns.Dot(np))))); + if (orders[i] < 2) + continue; + gp_Vec tangent = su * duv.X() + sv * duv.Y(), cross = ns.Crossed(tangent).Normalized(); + m.curvature = std::max(m.curvature, + std::abs(normal_curvature(s, uv.X(), uv.Y(), cross, ns) + - normal_curvature(ga, pu, pv, cross, ns))); + } + } + BRepMesh_IncrementalMesh(patch, 0.01, false, 0.05); + TopLoc_Location loc; + auto tri = BRep_Tool::Triangulation(patch, loc); + for (int i = 1; tri && i <= tri->NbNodes(); ++i) + m.deviation = std::max(m.deviation, deviation(tri->Node(i).Transformed(loc.Transformation()))); + m.area = area(patch); + return m; +} + +int failures = 0; + +// Runs one loop with one order everywhere; the patch must be valid and within the limits. +void run(const char* name, + const Loop& l, + int order, + std::function deviation, + double maxDeviation) +{ + std::vector orders(l.edges.size(), order); + TopoDS_Face patch; + bool ok = !l.edges.empty() + && BRepOffsetAPI_GraphPatch::TryBuild(int(l.edges.size()), + l.edges.data(), + l.supports.data(), + orders.data(), + patch); + if (!ok) + { + std::printf("%-22s %zu sides order %d: REFUSED\n", name, l.edges.size(), order); + ++failures; + return; + } + auto m = measure(l, orders, patch, deviation); + // the gap is bounded like the deviation: 1e-3 on curved supports, model precision on planar ones + bool pass = valid(patch) && m.gap <= std::min(1e-3, maxDeviation) && m.angle <= 1e-3 + && m.deviation <= maxDeviation; + std::printf("%-22s %zu sides order %d: gap %.2e angle %.2e dcurv %.2e deviation %.2e area %.4f %s\n", + name, + l.edges.size(), + order, + m.gap, + m.angle, + m.curvature, + m.deviation, + m.area, + pass ? "ok" : "FAIL"); + failures += !pass; +} +} // namespace + +int main() +{ + auto radial = [](double r) { + return [r](const gp_Pnt& p) { return std::abs(std::hypot(p.X(), p.Y()) - r); }; + }; + // A window through the wall of a tube (radius 30), around +y and away from the seam. + { + auto holed = tube_minus(BRepPrimAPI_MakeBox(gp_Pnt(-20, 15, 18), 40, 30, 24).Shape()); + auto loop = loop_on(outer_cylinder(holed), + [](const gp_Pnt& p) { return p.Y() > 20 && p.Z() > 17 && p.Z() < 43; }, + gp_Vec(1, 0, 0), + gp_Vec(0, 0, 1)); + for (int order : {0, 1, 2}) + run("cylinder window", loop, order, radial(30), 1e-3); + // the plate filling of the same loop, for reference + BRepOffsetAPI_MakeFilling filling; + for (auto& e : loop.edges) + filling.Add(e, loop.supports[0], GeomAbs_G1); + filling.Build(); + if (filling.IsDone()) + { + auto f = largest(filling.Shape(), [](const TopoDS_Face&) { return true; }); + std::vector orders(loop.edges.size(), 1); + auto m = measure(loop, orders, f, radial(30)); + std::printf("%-22s %zu sides order 1: gap %.2e angle %.2e deviation %.2e (plate filling)\n", + "cylinder window", + loop.edges.size(), + m.gap, + m.angle, + m.deviation); + } + // the same edges out of order are no loop: refused + Loop shuffled = loop; + std::swap(shuffled.edges[1], shuffled.edges[2]); + std::vector orders(shuffled.edges.size(), 1); + TopoDS_Face patch; + bool refused = !BRepOffsetAPI_GraphPatch::TryBuild(int(shuffled.edges.size()), + shuffled.edges.data(), + shuffled.supports.data(), + orders.data(), + patch); + std::printf("%-22s %zu sides order 1: out of order %s\n", + "cylinder window", + shuffled.edges.size(), + refused ? "refused, ok" : "ACCEPTED"); + failures += !refused; + } + // A triangle through the tube wall: two of its sides are ellipse arcs. + { + auto holed = tube_minus(prism({{-15, 10, 20}, {15, 10, 20}, {0, 10, 44}}, gp_Vec(0, 40, 0))); + auto loop = loop_on(outer_cylinder(holed), + [](const gp_Pnt& p) { return p.Y() > 20 && p.Z() > 19 && p.Z() < 45; }, + gp_Vec(1, 0, 0), + gp_Vec(0, 0, 1)); + for (int order : {1, 2}) + run("cylinder triangle", loop, order, radial(30), 1e-3); + } + // A window on a sphere (radius 30), centred on +y at the equator. + { + auto holed = BRepAlgoAPI_Cut(BRepPrimAPI_MakeSphere(30).Shape(), + BRepPrimAPI_MakeBox(gp_Pnt(-10, 15, -10), 20, 30, 20).Shape()) + .Shape(); + auto sphere = largest(holed, [](const TopoDS_Face&) { return true; }); + auto loop = loop_on(sphere, + [](const gp_Pnt& p) { return p.Y() > 15; }, + gp_Vec(1, 0, 0), + gp_Vec(0, 0, 1)); + auto dev = [](const gp_Pnt& p) { return std::abs(p.Distance(gp::Origin()) - 30); }; + for (int order : {1, 2}) + run("sphere window", loop, order, dev, 1e-3); + // a pentagonal cap around the pole: the seam crosses the hole, the pole is inside it + auto capped = BRepAlgoAPI_Cut(BRepPrimAPI_MakeSphere(30).Shape(), + prism(regular(5, 11, 15), gp_Vec(0, 0, 30))) + .Shape(); + auto cap = largest(capped, [](const TopoDS_Face&) { return true; }); + auto rim = loop_on(cap, + [](const gp_Pnt& p) { return p.Z() > 20; }, + gp_Vec(1, 0, 0), + gp_Vec(0, 1, 0)); + for (int order : {1, 2}) + run("sphere cap", rim, order, dev, 1e-3); + } + // A bumpy B-spline sheet with 3-, 5- and 6-sided vertical prisms cut through it. + { + TColgp_Array2OfPnt grid(1, 9, 1, 9); + for (int i = 1; i <= 9; ++i) + for (int j = 1; j <= 9; ++j) + { + double x = -40 + 10 * (i - 1), y = -40 + 10 * (j - 1); + grid(i, j) = gp_Pnt(x, y, 6 * sin(x / 25) * cos(y / 30) + 0.004 * x * y); + } + Handle(Geom_Surface) sheet = GeomAPI_PointsToBSplineSurface(grid).Surface(); + auto face = BRepBuilderAPI_MakeFace(sheet, 1e-7).Face(); + auto dev = [sheet](const gp_Pnt& p) { + GeomAPI_ProjectPointOnSurf proj(p, sheet); + return proj.NbPoints() ? proj.LowerDistance() : 1e100; + }; + for (int sides : {3, 5, 6}) + { + auto holed = BRepAlgoAPI_Cut(face, prism(regular(sides, 15, -30), gp_Vec(0, 0, 60))).Shape(); + auto sheetFace = largest(holed, [](const TopoDS_Face&) { return true; }); + auto loop = + loop_on(sheetFace, + [](const gp_Pnt& p) { return std::hypot(p.X(), p.Y()) < 16; }, + gp_Vec(1, 0, 0), + gp_Vec(0, 1, 0)); + for (int order : {1, 2}) + run("b-spline polygon", loop, order, dev, 1e-3); + } + } + // Holes in a plate and open prisms (the walls hold the loop): planar-representable, exact. + // The square ones take the rectangular branch, the others the general loop. + { + auto plateTop = [](const TopoDS_Shape& tool) { + auto plate = BRepAlgoAPI_Cut(BRepPrimAPI_MakeBox(gp_Pnt(-20, -20, 0), 40, 40, 5).Shape(), tool).Shape(); + auto top = largest(plate, [](const TopoDS_Face& f) { + BRepAdaptor_Surface a(f); + return a.GetType() == GeomAbs_Plane && a.Plane().Location().Z() > 4.9 + && std::abs(a.Plane().Axis().Direction().Z()) > 0.99; + }); + return loop_on(top, + [](const gp_Pnt& p) { return std::max(std::abs(p.X()), std::abs(p.Y())) < 8; }, + gp_Vec(1, 0, 0), + gp_Vec(0, 1, 0)); + }; + auto flat = [](double z) { return [z](const gp_Pnt& p) { return std::abs(p.Z() - z); }; }; + auto square = plateTop(BRepPrimAPI_MakeBox(gp_Pnt(-5, -5, -2), 10, 10, 9).Shape()); + auto penta = plateTop(prism(regular(5, 7, -2), gp_Vec(0, 0, 9))); + for (int order : {1, 2}) + { + run("plane hole", square, order, flat(5), 1e-9); + run("plane polygon hole", penta, order, flat(5), 1e-9); + } + // the top edges of a prism, each with its wall, ordered around the axis + auto walls = [](const TopoDS_Shape& solid, double z) { + std::vector> found; + for (TopExp_Explorer ex(solid, TopAbs_FACE); ex.More(); ex.Next()) + { + auto f = TopoDS::Face(ex.Current()); + if (std::abs(BRepAdaptor_Surface(f).Plane().Axis().Direction().Z()) > 1e-9) + continue; + for (auto& e : edges_where(f, [z](const TopoDS_Edge& e) { return std::abs(mid(e).Z() - z) < 1e-9; })) + found.emplace_back(e, f); + } + gp_XYZ c; + for (auto& w : found) + c += mid(w.first).XYZ() / double(found.size()); + auto at = [c](const std::pair& w) { + auto p = mid(w.first); + return std::atan2(p.Y() - c.Y(), p.X() - c.X()); + }; + std::sort(found.begin(), found.end(), [&](auto& a, auto& b) { return at(a) < at(b); }); + Loop l; + for (auto& w : found) + { + l.edges.push_back(w.first); + l.supports.push_back(w.second); + } + return l; + }; + run("open box", walls(BRepPrimAPI_MakeBox(20, 20, 10).Shape(), 10), 0, flat(10), 1e-9); + run("open hexagonal prism", walls(prism(regular(6, 12, 0), gp_Vec(0, 0, 10)), 10), 0, flat(10), 1e-9); + } + std::printf("%d failure(s)\n", failures); + return failures ? 1 : 0; +} diff --git a/src/cpp/patches/occt/tests/inspect.cxx b/src/cpp/patches/occt/tests/inspect.cxx new file mode 100644 index 00000000..c542d1c1 --- /dev/null +++ b/src/cpp/patches/occt/tests/inspect.cxx @@ -0,0 +1,45 @@ +#include "fixtures.hxx" +#include +#include +#include +#include +void dump(const char* tag, int nf, const TopoDS_Edge& e) +{ + BRepAdaptor_Curve c(e); + double f = c.FirstParameter(), l = c.LastParameter(); + gp_Pnt a = c.Value(f), m = c.Value((f + l) / 2), z = c.Value(l); + std::printf("%s n%d type %d (%.4f %.4f %.4f) (%.4f %.4f %.4f) (%.4f %.4f %.4f)\n", tag, nf, (int)c.GetType(), + a.X(), a.Y(), a.Z(), m.X(), m.Y(), m.Z(), z.X(), z.Y(), z.Z()); +} +int main(int argc, char** argv) +{ + BRep_Builder b; + TopoDS_Shape s; + BRepTools::Read(s, argv[1], b); + TopTools_IndexedDataMapOfShapeListOfShape ef; + TopExp::MapShapesAndAncestors(s, TopAbs_EDGE, TopAbs_FACE, ef); + std::printf("faces %d\n", count(s, TopAbs_FACE)); + int k = 0; + for (TopExp_Explorer ex(s, TopAbs_FACE); ex.More(); ex.Next()) + { + BRepAdaptor_Surface su(TopoDS::Face(ex.Current())); + std::printf(" face %d type %d edges %d\n", ++k, (int)su.GetType(), count(ex.Current(), TopAbs_EDGE)); + if (argc > 3 && std::atoi(argv[3]) == k) // inspect x : the edges of face k + for (TopExp_Explorer e(ex.Current(), TopAbs_EDGE); e.More(); e.Next()) + { + const TopoDS_Edge edge = TopoDS::Edge(e.Current()); + dump(" in-face", ef.FindFromKey(edge).Extent(), edge); + double f, l; // the pcurve in this face, in wire orientation + Handle(Geom2d_Curve) pc = BRep_Tool::CurveOnSurface(edge, TopoDS::Face(ex.Current()), f, l); + if (!pc.IsNull()) + { + gp_Pnt2d a = pc->Value(edge.Orientation() == TopAbs_REVERSED ? l : f); + gp_Pnt2d z = pc->Value(edge.Orientation() == TopAbs_REVERSED ? f : l); + std::printf(" uv (%.4f %.4f) -> (%.4f %.4f) orient %d\n", a.X(), a.Y(), z.X(), z.Y(), (int)edge.Orientation()); + } + } + } + for (int i = 1; i <= ef.Extent(); ++i) + if (ef(i).Extent() == 1 || argc > 2) + dump(ef(i).Extent() == 1 ? "free" : "edge", ef(i).Extent(), TopoDS::Edge(ef.FindKey(i))); +} diff --git a/src/cpp/patches/occt/tests/shellfillet.cxx b/src/cpp/patches/occt/tests/shellfillet.cxx new file mode 100644 index 00000000..84bb6b37 --- /dev/null +++ b/src/cpp/patches/occt/tests/shellfillet.cxx @@ -0,0 +1,111 @@ +// Standard fillet of chosen edges of a BREP shape (solid or open shell): +// shellfillet x y z r [x y z r ...] +// Each edge is the two-face edge whose midpoint is nearest to (x y z). Writes +// shellfillet-out.brep. YP_PARAMS="tang tesp t2d tapp3d tolapp2d fleche" sets SetParams; +// YP_FIX=1 runs ShapeFix_Face on every invalid face of the result first. +#include "fixtures.hxx" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) +{ + BRep_Builder b; + TopoDS_Shape s; + BRepTools::Read(s, argv[1], b); + TopTools_IndexedDataMapOfShapeListOfShape ef; + TopExp::MapShapesAndAncestors(s, TopAbs_EDGE, TopAbs_FACE, ef); + BRepFilletAPI_MakeFillet f(s); + if (const char* p = std::getenv("YP_PARAMS")) + { + double a[6]; + std::sscanf(p, "%lf %lf %lf %lf %lf %lf", a, a + 1, a + 2, a + 3, a + 4, a + 5); + f.SetParams(a[0], a[1], a[2], a[3], a[4], a[5]); + } + for (int a = 2; a + 3 < argc; a += 4) + { + gp_Pnt p(std::atof(argv[a]), std::atof(argv[a + 1]), std::atof(argv[a + 2])); + double best = 1e9; + int bi = 0; + for (int i = 1; i <= ef.Extent(); ++i) + { + if (ef(i).Extent() != 2) + continue; + double d = mid(TopoDS::Edge(ef.FindKey(i))).Distance(p); + if (d < best) + { + best = d; + bi = i; + } + } + auto e = TopoDS::Edge(ef.FindKey(bi)); + auto m = mid(e); + std::printf("edge %d mid (%.3f %.3f %.3f) d %.3g conc %d\n", bi, m.X(), m.Y(), m.Z(), best, + (int)ChFi3d::DefineConnectType(e, TopoDS::Face(ef(bi).First()), TopoDS::Face(ef(bi).Last()), 1e-5, true)); + f.Add(std::atof(argv[a + 3]), e); + } + try + { + f.Build(); + std::printf("done %d\n", f.IsDone()); + if (!f.IsDone()) + { + std::printf("faulty contours %d vertices %d\n", f.NbFaultyContours(), f.NbFaultyVertices()); + for (int i = 1; i <= f.NbFaultyVertices(); ++i) + { + auto p = BRep_Tool::Pnt(f.FaultyVertex(i)); + std::printf(" faulty vertex (%.3f %.3f %.3f)\n", p.X(), p.Y(), p.Z()); + } + return 1; + } + TopoDS_Shape out = f.Shape(); + if (std::getenv("YP_FIX")) + { + Handle(ShapeBuild_ReShape) rs = new ShapeBuild_ReShape(); + for (TopExp_Explorer ex(out, TopAbs_FACE); ex.More(); ex.Next()) + if (!BRepCheck_Analyzer(ex.Current()).IsValid()) + { + const TopoDS_Face face = TopoDS::Face(ex.Current()); + for (TopoDS_Iterator wi(face); wi.More(); wi.Next()) + { + ShapeFix_Wire fw(TopoDS::Wire(wi.Value()), face, 1e-7); + fw.SetContext(rs); + const bool shifted = fw.FixShifted(); + std::printf("FixShifted %d\n", (int)shifted); + if (shifted) + rs->Replace(wi.Value(), fw.Wire()); + } + } + out = rs->Apply(out); + } + BRepTools::Write(out, "shellfillet-out.brep"); + // the standard algorithm's history on this input + TopTools_IndexedMapOfShape outFaces; + TopExp::MapShapes(f.Shape(), TopAbs_FACE, outFaces); + int k = 0; + for (TopExp_Explorer ex(s, TopAbs_FACE); ex.More(); ex.Next()) + { + int in = 0; + for (TopTools_ListOfShape::Iterator it(f.Modified(ex.Current())); it.More(); it.Next()) + in += outFaces.Contains(it.Value()); + std::printf("face %d: modified %d (in result %d) deleted %d kept %d\n", ++k, f.Modified(ex.Current()).Extent(), in, + (int)f.IsDeleted(ex.Current()), (int)outFaces.Contains(ex.Current())); + } + for (int c = 1; c <= f.NbContours(); ++c) + for (int i = 1; i <= f.NbEdges(c); ++i) + std::printf("contour %d edge %d: generated %d\n", c, i, f.Generated(f.Edge(c, i)).Extent()); + } + catch (Standard_Failure& e) + { + std::printf("throw %s\n", e.GetMessageString()); + return 1; + } + return 0; +} diff --git a/src/cpp/patches/occt/tests/sidetail.cxx b/src/cpp/patches/occt/tests/sidetail.cxx new file mode 100644 index 00000000..e91f890e --- /dev/null +++ b/src/cpp/patches/occt/tests/sidetail.cxx @@ -0,0 +1,41 @@ +// sidetail : the self-interferences (level 5), with where they are. +#include "fixtures.hxx" +#include +#include +#include +#include +#include +static gp_Pnt where(const TopoDS_Shape& s) +{ + GProp_GProps g; + if (s.ShapeType() == TopAbs_FACE) + BRepGProp::SurfaceProperties(s, g); + else if (s.ShapeType() == TopAbs_EDGE) + BRepGProp::LinearProperties(s, g); + else + return BRep_Tool::Pnt(TopoDS::Vertex(s)); + return g.CentreOfMass(); +} +int main(int, char** argv) +{ + BRep_Builder b; + TopoDS_Shape s; + BRepTools::Read(s, argv[1], b); + BOPAlgo_CheckerSI c; + c.SetLevelOfCheck(5); + c.AddArgument(s); + c.Perform(); + const BOPDS_DS& ds = c.DS(); + for (BOPDS_MapIteratorOfMapOfPair it(ds.Interferences()); it.More(); it.Next()) + { + int i1, i2; + it.Value().Indices(i1, i2); + const TopoDS_Shape &a = ds.Shape(i1), &z = ds.Shape(i2); + gp_Pnt pa = where(a), pz = where(z); + std::printf("%d/%d types %d %d at (%.3f %.3f %.3f) / (%.3f %.3f %.3f)\n", i1, i2, (int)a.ShapeType(), (int)z.ShapeType(), + pa.X(), pa.Y(), pa.Z(), pz.X(), pz.Y(), pz.Z()); + if (a.ShapeType() == TopAbs_FACE) + std::printf(" face types %d %d\n", (int)BRepAdaptor_Surface(TopoDS::Face(a)).GetType(), + z.ShapeType() == TopAbs_FACE ? (int)BRepAdaptor_Surface(TopoDS::Face(z)).GetType() : -1); + } +} diff --git a/src/cpp/patches/occt/tests/wires.cxx b/src/cpp/patches/occt/tests/wires.cxx new file mode 100644 index 00000000..75f1f6dd --- /dev/null +++ b/src/cpp/patches/occt/tests/wires.cxx @@ -0,0 +1,29 @@ +// wires : the wires of a face, edge by edge (3D ends, orientation). +#include "fixtures.hxx" +#include +#include +#include +int main(int argc, char** argv) +{ + BRep_Builder b; + TopoDS_Shape s; + BRepTools::Read(s, argv[1], b); + int k = 0; + for (TopExp_Explorer ex(s, TopAbs_FACE); ex.More(); ex.Next()) + { + if (++k != std::atoi(argv[2])) + continue; + int w = 0; + for (TopoDS_Iterator wi(ex.Current()); wi.More(); wi.Next()) + { + std::printf("wire %d closed %d\n", ++w, (int)BRep_Tool::IsClosed(wi.Value())); + for (TopoDS_Iterator ei(wi.Value()); ei.More(); ei.Next()) + { + BRepAdaptor_Curve c(TopoDS::Edge(ei.Value())); + const bool rev = ei.Value().Orientation() == TopAbs_REVERSED; + gp_Pnt a = c.Value(rev ? c.LastParameter() : c.FirstParameter()), z = c.Value(rev ? c.FirstParameter() : c.LastParameter()); + std::printf(" %p o%d (%.3f %.3f %.3f)->(%.3f %.3f %.3f)\n", (void*)ei.Value().TShape().get(), (int)ei.Value().Orientation(), a.X(), a.Y(), a.Z(), z.X(), z.Y(), z.Z()); + } + } + } +} diff --git a/src/cpp/patches/occt/tests/yfillet.cxx b/src/cpp/patches/occt/tests/yfillet.cxx new file mode 100644 index 00000000..60bb02ae --- /dev/null +++ b/src/cpp/patches/occt/tests/yfillet.cxx @@ -0,0 +1,53 @@ +// yfillet IN.brep x y z r [x y z r ...]: BRepFilletAPI_MakeFillet with SetYPatch on the edges +// nearest to the given points; reports the Y junctions and writes yfillet-out.brep. +#include "cases.hxx" +#include +#include +#include +int main(int argc, char** argv) +{ + BRep_Builder b; + TopoDS_Shape s; + if (argc < 6 || !(BRepTools::Read(s, argv[1], b) || BinTools::Read(s, argv[1]))) // text or binary + return 2; + BRepFilletAPI_MakeFillet f(s); + f.SetYPatch(Standard_True); + for (int a = 2; a + 3 < argc; a += 4) + f.Add(atof(argv[a + 3]), edge_at(s, gp_Pnt(atof(argv[a]), atof(argv[a + 1]), atof(argv[a + 2])))); + f.Build(); + std::printf("done %d y-patches %d\n", f.IsDone(), f.IsDone() ? f.NbYPatches() : 0); + for (int i = 1; f.IsDone() && i <= f.NbYPatches(); ++i) + { + const auto& j = f.YPatchJunction(i); + std::printf(" P*(%.4f %.4f %.4f) seam %.2e deg band %.2e deg\n", j.Split.X(), j.Split.Y(), j.Split.Z(), + j.SeamAngle * 180 / M_PI, j.BandAngle * 180 / M_PI); + } + if (f.IsDone()) + { + std::printf("valid %d si %d faces %d\n", valid(f.Shape()), si_count(f.Shape()), count(f.Shape(), TopAbs_FACE)); + BRepTools::Write(f.Shape(), "yfillet-out.brep"); + // history as a caller sees it: every input face is kept, modified or deleted; every selected edge generates + TopTools_IndexedMapOfShape out; + TopExp::MapShapes(f.Shape(), out); + int k = 0; + for (TopExp_Explorer ex(s, TopAbs_FACE); ex.More(); ex.Next(), ++k) + { + const TopTools_ListOfShape& m = f.Modified(ex.Current()); + int inside = 0; + for (TopTools_ListOfShape::Iterator it(m); it.More(); it.Next()) + inside += out.Contains(it.Value()); + std::printf(" face %d: modified %d (in result %d) deleted %d kept %d\n", k, m.Extent(), inside, + (int)f.IsDeleted(ex.Current()), (int)out.Contains(ex.Current())); + } + for (int a = 2; a + 3 < argc; a += 4) + { + const TopoDS_Edge e = edge_at(s, gp_Pnt(atof(argv[a]), atof(argv[a + 1]), atof(argv[a + 2]))); + const TopTools_ListOfShape& g = f.Generated(e); + int inside = 0; + for (TopTools_ListOfShape::Iterator it(g); it.More(); it.Next()) + inside += out.Contains(it.Value()); + std::printf(" edge %d: generated %d (in result %d)\n", a / 4, g.Extent(), inside); + } + } + return f.IsDone() ? 0 : 1; +} diff --git a/src/cpp/src/ops/features/blends.cpp b/src/cpp/src/ops/features/blends.cpp index 276bae4c..936b73d9 100644 --- a/src/cpp/src/ops/features/blends.cpp +++ b/src/cpp/src/ops/features/blends.cpp @@ -113,7 +113,8 @@ Solid finish_blend(const Solid& solid, TrackedResult tracked, const BlendAttempt } // namespace -Solid fillet_rsolid(const Solid& solid, const EdgeSelection& edges, const Scalar& radius, const BlendTags& tags) { +Solid fillet_rsolid(const Solid& solid, const EdgeSelection& edges, const Scalar& radius, const BlendTags& tags, + const FilletOptions& options) { static const ErrorSpec spec{"fillet_rsolid", "Failed to apply the fillet operation.", {"The radius is not a positive finite scalar.", "No valid edges were selected.", @@ -140,7 +141,10 @@ Solid fillet_rsolid(const Solid& solid, const EdgeSelection& edges, const Scalar if (attempt.edges.empty()) throw ValueError("At least one edge should be selected as the target for fillet"); - TrackedResult tracked = tracked_fillet(solid, attempt.edges, radius_value); + // Recorded only when on, so records of the standard algorithm stay as they were. + if (options.strategy_auto_y_patch) + rec.param("strategy_auto_y_patch", Value(true)); + TrackedResult tracked = tracked_fillet(solid, attempt.edges, radius_value, options.strategy_auto_y_patch); return finish_blend(solid, std::move(tracked), attempt, "fillet", radius_value, rec, tags, "fillet.patch"); }); } catch (const std::exception& error) { diff --git a/src/cpp/src/ops/features/executors.cpp b/src/cpp/src/ops/features/executors.cpp index 555fe075..235b4c39 100644 --- a/src/cpp/src/ops/features/executors.cpp +++ b/src/cpp/src/ops/features/executors.cpp @@ -117,7 +117,10 @@ void register_sweeps(reactive::ExecutorRegistry& registry) { void register_blends(reactive::ExecutorRegistry& registry) { registry.add("make_fillet_rsolid", [](Params p, Inputs in, const ScalarValues&) { - return one(fillet_rsolid(Solid(input(in, 0)), rest(in, 1, in.size()), number(p, "radius"))); + FilletOptions options; + if (const Value* y = p.find("strategy_auto_y_patch"); y != nullptr && y->is_bool()) + options.strategy_auto_y_patch = y->as_bool(); + return one(fillet_rsolid(Solid(input(in, 0)), rest(in, 1, in.size()), number(p, "radius"), {}, options)); }); registry.add("make_chamfer_rsolid", [](Params p, Inputs in, const ScalarValues&) { ChamferOptions options; diff --git a/src/cpp/src/semantic/tracking_blends.cpp b/src/cpp/src/semantic/tracking_blends.cpp index 182ca4ea..f0566770 100644 --- a/src/cpp/src/semantic/tracking_blends.cpp +++ b/src/cpp/src/semantic/tracking_blends.cpp @@ -15,6 +15,13 @@ #include #include +// The patched kernel installs BRepFilletAPI_YPatch.hxx together with MakeFillet::SetYPatch. +#if __has_include() +#define SCAD_KERNEL_Y_PATCH 1 +#else +#define SCAD_KERNEL_Y_PATCH 0 +#endif + #include "scad/core/error.hpp" #include "scad/kernel/cast.hpp" #include "scad/kernel/membership.hpp" @@ -76,9 +83,22 @@ TrackedResult track_blend(BRepFilletAPI_LocalOperation& op, const Solid& solid, } // namespace -TrackedResult tracked_fillet(const Solid& solid, const std::vector& edges, double radius) { +bool kernel_has_y_patch() { + return SCAD_KERNEL_Y_PATCH != 0; +} + +TrackedResult tracked_fillet(const Solid& solid, const std::vector& edges, double radius, bool auto_y_patch) { return occt_guard([&] { BRepFilletAPI_MakeFillet fillet(solid.wrapped()); + if (auto_y_patch) { +#if SCAD_KERNEL_Y_PATCH + fillet.SetYPatch(Standard_True); +#else + throw ValueError( + "strategy_auto_y_patch needs an OpenCASCADE kernel built with the SimpleCADAPI patch set " + "fillet-robustness-4 (src/cpp/patches/occt); this build links one without it"); +#endif + } for (const Edge& edge : edges) fillet.Add(radius, TopoDS::Edge(edge.wrapped())); fillet.Build(); diff --git a/src/cpp/src/surface/faces_from_edges.cpp b/src/cpp/src/surface/faces_from_edges.cpp index 5868319e..c37dffde 100644 --- a/src/cpp/src/surface/faces_from_edges.cpp +++ b/src/cpp/src/surface/faces_from_edges.cpp @@ -106,10 +106,13 @@ Face make_surface_patch_rface(const std::vector& boundaries, co throw ValueError("boundaries must be a non-empty SurfaceBoundary sequence"); const SurfaceFillingSettings settings = options.settings.value_or(SurfaceFillingSettings{}); settings.validate(); + if (options.strategy_graph_patch && (!options.holes.empty() || options.settings)) + throw ValueError("strategy_graph_patch takes no holes and no filling settings"); OperationRecord record{.op = "make_surface_patch_rface"}; FillingProblem problem; problem.settings = settings; + problem.graph_patch = options.strategy_graph_patch; std::int64_t support_count = 0; Value boundary_dicts = Value::array(); for (const SurfaceBoundary& boundary : boundaries) { @@ -140,6 +143,8 @@ Face make_surface_patch_rface(const std::vector& boundaries, co record.params.set("points", to_value(options.points)); record.params.set("settings", settings.as_dict()); record.params.set("tag_prefix", to_value(options.tag_prefix)); + if (options.strategy_graph_patch) // only when on: records of the plate filling stay as they were + record.params.set("strategy_graph_patch", Value(true)); return finalize_surface_output(Face(face), FaceOutput{.record = std::move(record), .tag_prefix = options.tag_prefix}); }); diff --git a/src/cpp/src/surface/fitter.cpp b/src/cpp/src/surface/fitter.cpp index bfe34d63..8e573658 100644 --- a/src/cpp/src/surface/fitter.cpp +++ b/src/cpp/src/surface/fitter.cpp @@ -10,9 +10,20 @@ #include #include +#include + +// The patched kernel (src/cpp/patches/occt) installs the graph patch as a separate entry point. +#if __has_include() +#include +#define SCAD_KERNEL_GRAPH_PATCH 1 +#else +#define SCAD_KERNEL_GRAPH_PATCH 0 +#endif + #include "gordon.hpp" #include "internal.hpp" #include "scad/kernel/convert.hpp" +#include "scad/kernel/membership.hpp" #include "scad/kernel/topology.hpp" namespace scad::surface { @@ -55,6 +66,8 @@ class OcctSurfaceFitter final : public SurfaceFitter { // occt_guard: the caller fill_face is only called from operator_scope bodies (faces_from_edges.cpp, shell_ops.cpp), // which are guarded. TopoDS_Face fill(const FillingProblem& problem) const override { + if (problem.graph_patch) + return graph_patch(problem); const SurfaceFillingSettings& s = problem.settings; BRepOffsetAPI_MakeFilling builder(s.degree, s.points_per_curve, s.iterations, s.anisotropic, s.tolerance_2d, s.tolerance_3d, s.angular_tolerance, s.curvature_tolerance, s.max_degree, @@ -74,6 +87,49 @@ class OcctSurfaceFitter final : public SurfaceFitter { return detail::single_face(builder.Shape(), "filling"); } + // The ordered loop as BRepOffsetAPI_GraphPatch takes it: each edge from its support face, with + // its continuity as the numeric order 0/1/2 (GeomAbs_G2 is not the integer 2). + static TopoDS_Face graph_patch(const FillingProblem& problem) { +#if SCAD_KERNEL_GRAPH_PATCH + const std::size_t count = problem.boundaries.size(); + if (count < 3 || count > 64) + throw ValueError("strategy_graph_patch takes one ordered loop of 3 to 64 boundaries, got " + + std::to_string(count)); + if (!problem.points.empty()) + throw ValueError("strategy_graph_patch takes no interior points"); + std::vector edges; + std::vector supports; + std::vector orders; + for (std::size_t i = 0; i < count; ++i) { + const FillingBoundary& b = problem.boundaries[i]; + if (b.support.IsNull()) + throw ValueError("strategy_graph_patch needs a support face on every boundary (boundary " + std::to_string(i) + + " has none)"); + if (!kernel::SubShapeIndex(b.support).contains(b.edge)) + throw ValueError( + "strategy_graph_patch needs each boundary edge to be an edge of its support face " + "(boundary " + + std::to_string(i) + ")"); + edges.push_back(b.edge); + supports.push_back(b.support); + orders.push_back(b.continuity == "G2" ? 2 : b.continuity == "G1" ? 1 : 0); + } + TopoDS_Face face; + if (!BRepOffsetAPI_GraphPatch::TryBuild(static_cast(count), edges.data(), supports.data(), orders.data(), + face)) + throw ValueError( + "the graph patch was refused: the loop is not ordered and closed, cannot be represented " + "over one plane, or no degree-8 graph meets its supports within 1e-3 mm, 1e-3 rad (G1) " + "and 5% of their curvature (G2)"); + return face; +#else + (void)problem; + throw ValueError( + "strategy_graph_patch needs an OpenCASCADE kernel built with the SimpleCADAPI patch set " + "fillet-robustness-4 (src/cpp/patches/occt); this build links one without it"); +#endif + } + Handle(Geom_BSplineSurface) gordon(const std::vector& profiles, const std::vector& guides, double tolerance) const override { return detail::interpolate_curve_network(profiles, guides, tolerance); @@ -97,6 +153,10 @@ std::shared_ptr occt_surface_fitter() { return registry().occt; } +bool kernel_has_graph_patch() { + return SCAD_KERNEL_GRAPH_PATCH != 0; +} + std::shared_ptr surface_fitter() { Registry& r = registry(); const std::lock_guard lock(r.mutex); diff --git a/src/cpp/tests/python/test_ops_features_blends.py b/src/cpp/tests/python/test_ops_features_blends.py index 6652b635..151aacd9 100644 --- a/src/cpp/tests/python/test_ops_features_blends.py +++ b/src/cpp/tests/python/test_ops_features_blends.py @@ -107,7 +107,7 @@ def raises(call): def test_signatures_match_python(): expected = { - "fillet_rsolid": ["solid", "edges", "radius", "result_tag", "generated_faces_tag"], + "fillet_rsolid": ["solid", "edges", "radius", "result_tag", "generated_faces_tag", "strategy_auto_y_patch"], "chamfer_rsolid": ["solid", "edges", "distance", "angle", "reference_direction", "result_tag", "generated_faces_tag"], "shell_rsolid": ["solid", "faces_to_remove", "thickness", "result_tag", "body_faces_tag", "offset_faces_tag", "closing_faces_tag", "wall_edges_tag"], diff --git a/src/simplecadapi/_cpp/__init__.py b/src/simplecadapi/_cpp/__init__.py index 30eedf85..b31706a5 100644 --- a/src/simplecadapi/_cpp/__init__.py +++ b/src/simplecadapi/_cpp/__init__.py @@ -18,5 +18,6 @@ from ._native import _testing # noqa: F401 (underscore names are not star-exported) from ._native import _brep_region, _internal_mesh # noqa: F401 (underscore names are not star-exported) from ._native import _constrain_rsketch # noqa: F401 (graph replay's generic constraint) +from ._native import _kernel_capabilities # noqa: F401 (strategies the linked OCCT carries) from ._native import _brep_region_path # noqa: F401 (graph replay's locator check) from ._native import _from_occt, _occt # noqa: F401 (the OCCT classes of the kept Python layers; see occt/) diff --git a/src/simplecadapi/_cpp/_native/__init__.pyi b/src/simplecadapi/_cpp/_native/__init__.pyi index ff6cc140..d2d8d4d2 100644 --- a/src/simplecadapi/_cpp/_native/__init__.pyi +++ b/src/simplecadapi/_cpp/_native/__init__.pyi @@ -781,6 +781,10 @@ def _interpolated_bspline_edge(points: collections.abc.Sequence[typing.Annotated """ An interpolating B-spline edge through the points (GeomAPI_Interpolate). """ +def _kernel_capabilities() -> dict: + """ + Kernel strategies the linked OpenCASCADE carries: y_patch (fillet_rsolid strategy_auto_y_patch), graph_patch (make_surface_patch_rface strategy_graph_patch). + """ def _locate_anchor(within: OperationNode, stable: typing.Any) -> typing.Any: """ The anchor {node_id, output_slot, kind, topo_id} a stable anchor names upstream of `within`, or None. diff --git a/src/simplecadapi/_glue/docstrings.json b/src/simplecadapi/_glue/docstrings.json index 8cbf5358..039c56ce 100644 --- a/src/simplecadapi/_glue/docstrings.json +++ b/src/simplecadapi/_glue/docstrings.json @@ -159,7 +159,7 @@ "extrude_until_rsolid": "Extrude a planar face until a target surface, including curved surfaces.\n\nThe direction is interpreted in the current coordinate system and\nnormalized before construction. ``until`` selects the termination:\n``NEXT`` (forward, nearest intersecting target surface), ``LAST`` (forward,\nfarthest), ``PREVIOUS`` (reverse, nearest) and ``FIRST`` (reverse,\nfarthest). The temporary prism is intersected with the target, the target's\nboundary faces are taken from kernel history and sewn into surfaces, and\nthe prism is split on the selected one. Bounding boxes only size the\ntemporary prism; they do not define the termination surface, and side\nwalls parallel to the direction do not join separate near and far limits.\n\nTargets must cover the profile at the requested contact: an uncovered,\nopen or disconnected output is rejected, as are a missing contact, an\ninvalid mode, a zero or nonfinite direction and an empty target sequence.\nInputs are preserved. The operation is recorded as\n``make_extrude_until_rsolid``; its ordered inputs are the profile followed\nby every target solid and its parameters keep ``direction``, ``until`` and\n``target_count``, so a changed target is recomputed on replay (no final\nBRep is embedded).\n\nArgs:\n profile: The planar face to extrude.\n target: A solid, or a sequence of solids, that bounds the extrusion.\n direction: Extrusion direction in current coordinate-system\n coordinates.\n until: ``\"NEXT\"``, ``\"LAST\"``, ``\"PREVIOUS\"`` or ``\"FIRST\"``.\n\nReturns:\n One valid solid.\n\nRaises:\n TypeError: ``profile`` is not a Face, or ``target`` is not a Solid or\n a sequence of Solid.\n ValueError: No target, no contact, insufficient coverage, a bad mode\n or direction, or an invalid kernel result.\n\nExamples:\n import simplecadapi as scad\n profile = scad.make_rectangle_rface(2, 2)\n ceiling = scad.make_box_rsolid(10, 10, 2, bottom_face_center=(0, 0, 5))\n near = scad.extrude_until_rsolid(profile, ceiling, until=\"NEXT\") # volume 20\n far = scad.extrude_until_rsolid(profile, ceiling, until=\"LAST\") # volume 28\n sphere = scad.make_sphere_rsolid(5, center=(0, 0, 10))\n curved = scad.extrude_until_rsolid(profile, sphere)", "fill_holes_rshell": "Fill selected closed free boundaries and return a sewn Shell.", "fillet_corner_rsketch": "Round the corner where lines ``a`` and ``b`` meet with an arc of ``radius``.\n\nThe lines must share an end point (the corner). The sketch is solved first; both lines are shortened to the\ntangent points and the arc (counter-clockwise from its start to its end around its centre) is tied to each line\nwith a tangent constraint and to ``radius`` with a driving radius dimension, so the result survives a re-solve.\nThe corner point goes away unless a constraint or another entity uses it (then it stays as the sharp corner and\nthe cut-off parts of the lines stay as construction lines). horizontal/vertical and the other constraints that\nhold for a shorter line stay; lengths and other dimensions of the lines are dropped (see\ndiff_sketch_rsketchdiff). Refused: parallel lines, lines that share no point, a radius too large for the\nshorter line (the message names the largest radius). New ids: points ``p``, arc ``a``, legs ``l``,\nconstraints ``c__``.", - "fillet_rsolid": "Apply fillets, with optional tagging of kernel-proven patch faces.\n\n``solid`` may also be the list of pieces a cut that split a body returns: each piece gets the picked edges that lie on it, a piece with none is kept as it is, and the result is the list of pieces in the same order. A selector is resolved on every piece and its cardinality (``exactly``/``at_least``/``at_most``) is checked on the edges of all of them.", + "fillet_rsolid": "Apply fillets, with optional tagging of kernel-proven patch faces.\n\n``solid`` may also be the list of pieces a cut that split a body returns: each piece gets the picked edges that lie on it, a piece with none is kept as it is, and the result is the list of pieces in the same order. A selector is resolved on every piece and its cardinality (``exactly``/``at_least``/``at_most``) is checked on the edges of all of them.\n\nWhere a concave and a convex selected edge meet tangentially or nearly so (a post flush with a plate side, a wall a few degrees off it), two rolling-ball bands cannot meet: one ball lies outside the material, the other inside. By default the kernel runs its standard algorithm first and, only at such a junction and only when the standard result fails or is invalid or self-intersecting, closes the junction with the pinch corner: both bands taper along one shared curve on the common face to a single point at the junction vertex (each band an exact variable-radius rolling-ball surface, G1 to its supports and along the shared curve; at the section where the taper starts the convex band continues G1, as in Plasticity, and the concave band meets its constant-radius band with a crease, about 17 degrees at r = 5 on a post flush with a plate side; where that layout does not fit or would crease more than 30 degrees, the crease is shared between both sides). If the pinch fails its checks, the Y transition is tried: both bands stop where they touch the shared face and two G1 ribbons join them. A valid standard result is kept. ``strategy_auto_y_patch=True`` takes the Y transition first wherever there is such a junction. Every other edge, and both bands away from the junction, use the standard algorithm; the ribbons are tagged like the bands (``fillet.patch``). Needs a kernel built with the SDK's OCCT patch set (``fillet-robustness-4``); otherwise the flag raises ``ValueError``.", "fit_cubic_bspline_control_points": "Fit a minimal cubic B-spline control polygon to sampled curve points.\n\nUses chord-length parameterization, cubic clamped B-spline least squares,\nsecond-difference fairing regularization, and adaptive simple knot insertion\nuntil the maximum sample error is within `tolerance`. Only simple interior\nknots are inserted, so a cubic result remains C2-continuous at every interior\nknot.\n\nArgs:\n sample_points: Ordered 2D or 3D points sampled along the intended curve.\n Consecutive duplicate points within `duplicate_tolerance` are ignored.\n tolerance: Maximum allowed Euclidean fitting error at the input samples.\n max_control_points: Upper bound for fitted control points. Defaults to the\n cleaned sample count, with a cubic minimum of four controls.\n fairing: Non-negative second-difference regularization weight. Larger\n values prefer smoother control polygons while still respecting the\n error tolerance when possible.\n duplicate_tolerance: Distance threshold for removing consecutive duplicate\n sample points before chord-length parameterization.\n knot_tolerance: Normalized parameter spacing threshold used to avoid\n duplicate or near-boundary interior knots.\n raise_on_failure: Raise `ValueError` when the tolerance cannot be reached\n within `max_control_points`. If false, return the best non-converged\n result instead.\n\nReturns:\n `BSplineFitResult` containing cubic degree, control points, a full clamped\n knot vector, knot multiplicities, sample parameters, and fitting error.\n\nRaises:\n ValueError: If inputs are invalid, or if the tolerance cannot be met and\n `raise_on_failure=True`.\n\nExamples:\n ```python\n from simplecadapi.math import fit_cubic_bspline_control_points\n\n samples = [(0.0, 0.0, 0.0), (1.0, 0.4, 0.0), (2.0, 0.0, 0.0)]\n fit = fit_cubic_bspline_control_points(samples, tolerance=0.01)\n print(fit.control_points)\n print(fit.knots, fit.multiplicities)\n ```", "fit_point_grid_rface": "Fit a B-spline Face through a rectangular 3D point grid.", "free_boundaries_rwirelist": "Return unique closed and open free boundary wires of a Shell.", @@ -255,7 +255,7 @@ "make_spur_rack_rsolid": "Create a straight-tooth rack.\n\nParameters\n----------\nmodule : float\n Gear module in mm (tooth pitch = pi * module).\nn_teeth : int, default 10\n Number of teeth along the rack.\npressure_angle : float, default 20\n Pressure angle in degrees.\nrack_height : float, default 6.0\n Rack thickness along Z in mm.", "make_spur_ring_gear_rsolid": "Create an internal spur ring gear.\n\nParameters\n----------\nn_teeth : int\n Number of internal teeth (>= 3).\nmodule : float\n Gear module in mm.\npressure_angle : float, default 20\n Pressure angle in degrees.\ngear_height : float, default 6.0\n Ring gear thickness along Z in mm.\nrim_thickness : float, default 3.0\n Thickness of the rim beyond the tooth tips in mm.\nbacklash : float, default 0.0\n Circumferential tooth-space clearance at the pitch circle in mm.\naddendum_factor : float, default 1.0\n Internal tooth addendum as a multiple of module.\nclearance_factor : float, default 0.25\n Internal tooth root clearance beyond the addendum, as a multiple of module.", "make_straight_bevel_gear_rsolid": "Create a straight bevel gear with standard metric tooth proportions.\n\nThe large-end transverse section uses the same analytic involute profile as\n:func:`make_spur_gear_rsolid`. A similar small-end section is located on the\nrequested pitch cone and joined with ruled straight tooth surfaces.\n\n``face_width`` is measured along the pitch-cone generator. This factory\nsupplies nominal tooth geometry; a released pair still requires mating-gear,\nmounting-distance, contact-pattern, backlash, material, heat-treatment, and\nstrength checks.", - "make_surface_patch_rface": "Fill a constrained boundary network into one Face, optionally with holes.\n\nThe filling kernel re-fits each boundary edge, so adjacent patches built\nwith this operation do not keep identical shared boundary curves. When\nseveral patches must share exact boundary edges and sew into one closed\nshell, build each patch with ``make_gordon_surface_rface`` from a shared\nprofile/guide edge network instead.", + "make_surface_patch_rface": "Fill a constrained boundary network into one Face, optionally with holes.\n\nThe filling kernel re-fits each boundary edge, so adjacent patches built\nwith this operation do not keep identical shared boundary curves. When\nseveral patches must share exact boundary edges and sew into one closed\nshell, build each patch with ``make_gordon_surface_rface`` from a shared\nprofile/guide edge network instead.\n\n``strategy_graph_patch=True`` fills with the kernel's graph patch instead: ``boundaries`` must be one ordered closed loop of 3 to 64 edges, each an edge of its ``support`` face, with continuity C0, G1 or G2 per edge; ``points``, ``holes`` and ``settings`` are not accepted. The patch is a degree-8 variational surface trimmed by the projected boundary. It meets its supports exactly where a degree-8 graph can (planar supports); on curved supports (cylinder, sphere, B-spline) it continues the supports' own surfaces over the hole and is accepted within 1e-3 mm of the support edges, 1e-3 rad of their normals (G1) and 5% of their curvature (G2), its edge tolerances covering that gap, so the face can be sewn to its supports. Loops that cannot be represented over one plane (seen along the fitted normal) are refused with ``ValueError``. Needs a kernel built with the SDK's OCCT patch set (``fillet-robustness-4``).", "make_three_point_arc_redge": "Create an arc edge from three points.", "make_three_point_arc_rwire": "Create a wire containing an arc defined by three points.", "make_vertex_connector_rconnector": "Create a connector anchored to a Vertex.\n\nOrigin is the vertex point; axes are identity.\nflip has no effect on vertex connectors (no direction).", @@ -379,4 +379,4 @@ "make_workplane_offset_rworkplane": "Create a workplane moved and turned relative to a workplane or a named plane.\n\nThe editor's move and turn handles write this operation: a plane placed by hand on a base, without any model geometry.\n\nArgs:\n base: The plane it is placed on: a workplane value (made by a ``make_workplane_*_rworkplane`` operation, recorded\n as this node's input so the new plane follows it when it moves) or a named plane ``\"XY\"`` / ``\"XZ\"`` / ``\"YZ\"``\n (axes as sketches read them).\n offset: How far the origin moves, ``(dx, dy, dz)`` along the base's own x, y and normal.\n rx, ry, rz: Turns in degrees about the base's own axes, applied in that order, each about the axis as the previous\n turn left it (R = Rx(rx) Ry(ry) Rz(rz) in the base's frame).\n\nReturns:\n SimpleWorkplane: The new frame. Use it as a sketch plane (``plane=wp``) or as a context (``with wp:``).\n\nExamples:\n >>> wp = scad.make_workplane_offset_rworkplane(\"XY\", offset=(0, 0, 20), rx=30)\n >>> lid = scad.make_workplane_offset_rworkplane(wp, offset=(0, 0, 5)) # follows wp", "inset_face_rsolid": "Imprint the loops of one planar face moved a distance inside it.\n\nThe outline of the face (and the outline of each of its holes) is offset in\nthe face's plane by ``distance`` towards the inside, and the offset loops are\nimprinted on the solid: the face becomes an inner face and the ring around it\n(a ring around each hole too). The solid keeps its shape and volume; it only\nhas one face more, which the next operation can pull out, push in or open, so\nsteps, bosses and walls are built by insetting and pulling again.\n\nThe operation is recorded as ``make_inset_face_rsolid``; the body and the face\nare ordered inputs and the distance is a parameter, so model JSON replay is\nstrict. The split pieces are fragments of the face (element references and\ntags follow them as a split) and carry the kernel roles ``inset.inner`` and\n``inset.ring``, so ``scad.ref.face(..., role=\"inset.inner\")`` names the inner\nface whatever the face was.\n\nArgs:\n solid: The body whose face is inset.\n face: One planar face of ``solid``, or a QL selector that picks exactly one.\n distance: How far inside the face the loops run, in mm; positive.\n\nReturns:\n The same solid with the face split in its inner face and ring.\n\nRaises:\n TypeError: ``solid`` is not a Solid.\n ValueError: Not exactly one face, a face of another solid, a curved\n face, a non-positive distance, or a distance at which nothing of the\n face is left inside the loops.\n\nExamples:\n import simplecadapi as scad\n ql = scad.ql\n box = scad.make_box_rsolid(40, 30, 20)\n top = ql.faces().where(ql.prop(\"geom.center.z\", \">=\", 19.9)).exactly(1)\n inset = scad.inset_face_rsolid(box, top, 3)\n inner = scad.ref.face(\"\", \"make_inset_face_rsolid\", role=\"inset.inner\").one(inset)\n", "press_pull_rsolid": "Pull one planar face out along its normal, or press it in.\n\nA positive ``distance`` pulls the face out: the prism of the face along its\noutward normal is joined to the solid (a boss, a step). A negative one presses\nit in: the prism into the solid is cut (a pocket, a recess; through the solid it\ncuts a hole). Zero leaves the solid as it is. One signed number covers both, so\na parameter can be tuned across zero without changing the code.\n\nPair it with ``inset_face_rsolid``: inset a face, then press or pull its inner\nface, to build steps, bosses and walls without a sketch.\n\nThe operation is recorded as its steps: ``make_extrude_rsolid`` of the face,\nthen ``make_union_rsolid`` (pull) or ``make_cut_rsolid`` (press), so the new\nfaces carry the extrusion's roles (``extrusion.end`` is the moved face,\n``extrusion.side`` its walls) and element references follow them.\n\nArgs:\n solid: The body whose face is pressed or pulled.\n face: One planar face of ``solid``, or a QL selector that picks exactly one.\n distance: How far, in mm, along the face's outward normal: positive pulls,\n negative presses.\n\nReturns:\n The solid with the face pulled out or pressed in.\n\nRaises:\n TypeError: ``solid`` is not a Solid.\n ValueError: Not exactly one face, a face of another solid, a curved face,\n a non-finite distance, or a press that removes the whole solid.\n\nExamples:\n import simplecadapi as scad\n ql = scad.ql\n box = scad.make_box_rsolid(40, 30, 20)\n top = ql.faces().where(ql.prop(\"geom.center.z\", \">=\", 19.9)).exactly(1)\n stepped = scad.inset_face_rsolid(box, top, 3)\n inner = scad.ref.faces(scad.ref.face(\"\", \"make_inset_face_rsolid\", role=\"inset.inner\"))\n boss = scad.press_pull_rsolid(stepped, inner, 10)\n pocket = scad.press_pull_rsolid(stepped, inner, -4)\n" -} \ No newline at end of file +} diff --git a/src/simplecadapi/recording/serializer.py b/src/simplecadapi/recording/serializer.py index 4898733f..7c0d1918 100644 --- a/src/simplecadapi/recording/serializer.py +++ b/src/simplecadapi/recording/serializer.py @@ -4119,6 +4119,7 @@ def _vector(value: Any) -> Any: settings=ops.SurfaceFillingSettings(**settings_payload), holes=cast(Sequence[Wire], holes), tag_prefix=cast(Optional[str], params.get("tag_prefix")), + strategy_graph_patch=bool(params.get("strategy_graph_patch", False)), ) _store_outputs(node, result) continue @@ -4782,7 +4783,12 @@ def _vector(value: Any) -> Any: ctx.fail( f"Graph node '{node.node_id}' ({op_name}) expected {expected} selected edge(s), got {len(edges)}" ) - result = ops.fillet_rsolid(solid, edges, params["radius"]) + result = ops.fillet_rsolid( + solid, + edges, + params["radius"], + strategy_auto_y_patch=bool(params.get("strategy_auto_y_patch", False)), + ) _store_outputs(node, result) continue diff --git a/test/test_kernel_strategies.py b/test/test_kernel_strategies.py new file mode 100644 index 00000000..3c259445 --- /dev/null +++ b/test/test_kernel_strategies.py @@ -0,0 +1,206 @@ +"""Kernel strategies behind explicit flags: the Y-transition fillet (``strategy_auto_y_patch``) and the graph patch +(``strategy_graph_patch``). Both need the SDK's OCCT patch set (src/cpp/patches/occt, fillet-robustness-4); on another +kernel they must refuse with a ValueError, never fall back silently.""" + +import math + +import pytest + +import simplecadapi as s +from simplecadapi import _cpp +from simplecadapi._cpp import _kernel_capabilities +from simplecadapi.recording.graph import GraphSession + +CAPS = _kernel_capabilities() +needs_y = pytest.mark.skipif(not CAPS["y_patch"], reason="kernel without the Y-transition strategy") +needs_graph = pytest.mark.skipif(not CAPS["graph_patch"], reason="kernel without the graph patch") + +R, H = 50.0, 40.0 + + +def plate_post(): + """A post of radius R flush with the side y = -R of a plate 3R x 2R x H (the reference Y junction).""" + post = s.make_cylinder_rsolid(R, 2 * H) + plate = s.make_box_rsolid(3 * R, 2 * R, H, bottom_face_center=(1.5 * R, 0, 0)) + return s.union_rsolid(post, plate) + + +def _at(edge): + c = edge.get_center() + return c.x, c.y, c.z + + +def junction_edges(body): + """The concave root of the post on the plate top and the convex top edge of the flush side y = -R.""" + circles = s.ql.edges().where(s.ql.prop("geom.type", "==", "CIRCLE")).resolve(body) + lines = s.ql.edges().where(s.ql.prop("geom.type", "==", "LINE")).resolve(body) + root = [e for e in circles if abs(_at(e)[2] - H) < 1e-6] # get_center() is the arc's centroid + side = [e for e in lines if abs(_at(e)[1] + R) < 1e-6 and abs(_at(e)[2] - H) < 1e-6] + assert root and len(side) == 1 + return root + side + + +def test_capabilities_are_reported(): + assert set(CAPS) == {"y_patch", "graph_patch"} + assert all(isinstance(v, bool) for v in CAPS.values()) + + +@pytest.mark.skipif(CAPS["y_patch"], reason="the refusal is for kernels without the strategy") +def test_without_the_kernel_strategy_the_flag_refuses(): + body = plate_post() + with pytest.raises(s.SimpleCADError, match="fillet-robustness-4"): + s.fillet_rsolid(body, junction_edges(body), 5.0, strategy_auto_y_patch=True) + + +@needs_y +@pytest.mark.parametrize("radius", [2.5, 5.0, 8.0]) +def test_y_patch_closes_the_flush_post_junction(radius): + body = plate_post() + out = s.fillet_rsolid(body, junction_edges(body), radius, strategy_auto_y_patch=True, generated_faces_tag="round") + # (fillet_rsolid itself rejects an invalid or volume-inconsistent blend result) + # bands and the two ribbons are all generated by the selected edges + rounds = s.ql.faces().where(s.ql.tag("round")).resolve(out) + assert len(rounds) >= 4 + # the concave band adds material, the convex one removes some; both are small next to the body + assert abs(out.get_volume() - body.get_volume()) < 0.01 * body.get_volume() + + +@needs_y +def test_y_patch_off_is_the_standard_algorithm(): + body = plate_post() + edges = s.ql.edges().where(s.ql.prop("geom.center.z", ">", 2 * H - 1e-6)).resolve(body) + plain = s.fillet_rsolid(body, edges, 3.0) + flagged = s.fillet_rsolid(body, edges, 3.0, strategy_auto_y_patch=True) # no junction among these edges + assert flagged.get_volume() == pytest.approx(plain.get_volume(), rel=1e-12) + assert len(s.ql.faces().resolve(flagged)) == len(s.ql.faces().resolve(plain)) + + +@needs_y +@pytest.mark.parametrize("radius", [2.5, 5.0]) +def test_a_plain_fillet_of_the_tangent_junction_falls_back_to_the_pinch_corner(radius): + # Without the flag the kernel runs its standard algorithm first; it fails on this junction, so the kernel closes + # it with the pinch corner: both bands taper to one point at the junction vertex, no ribbons. The flag asks for + # the Y transition instead: same bands far from the junction, a different corner. + body = plate_post() + plain = s.fillet_rsolid(body, junction_edges(body), radius, generated_faces_tag="round") + flagged = s.fillet_rsolid(body, junction_edges(body), radius, strategy_auto_y_patch=True, generated_faces_tag="round") + assert len(s.ql.faces().where(s.ql.tag("round")).resolve(plain)) >= 3 + assert plain.get_volume() != pytest.approx(flagged.get_volume(), rel=1e-9) + assert plain.get_volume() == pytest.approx(flagged.get_volume(), rel=1e-3) # differ only near the junction + + +@needs_y +def test_y_patch_is_recorded_and_replayed(): + with GraphSession() as session: + body = plate_post() + out = s.fillet_rsolid(body, junction_edges(body), 5.0, strategy_auto_y_patch=True) + session.capture_result(value=out) + model = s.export_model_json(session) + assert '"strategy_auto_y_patch": true' in model.replace("'", '"') or "strategy_auto_y_patch" in str(model) + replayed = s.replay_model_json(model)[0] + assert replayed.get_volume() == pytest.approx(out.get_volume(), rel=1e-9) + + +def open_box(): + """A 20 x 20 x 10 box without its top: four walls hold the loop the patch must close.""" + box = s.make_box_rsolid(20, 20, 10) + walls = [f for f in s.ql.faces().resolve(box) if abs(f.get_normal_at().z) < 1e-9] + loop = [] + for wall in walls: + top = [e for e in s.ql.edges().resolve(wall) if abs(_at(e)[2] - 10) < 1e-9] + loop.append((top[0], wall)) + # order the loop by the angle of each edge's centre around the box axis + loop.sort(key=lambda item: math.atan2(_at(item[0])[1], _at(item[0])[0])) + return box, loop + + +def plate_with_hole(): + """A 40 x 40 x 5 plate with a 10 x 10 through hole: the top face holds the hole's loop.""" + plate = s.cut_rsolid(s.make_box_rsolid(40, 40, 5), s.make_box_rsolid(10, 10, 9, bottom_face_center=(0, 0, -2))) + top = max(s.ql.faces().resolve(plate), key=lambda f: f.get_center().z) + hole = [e for e in s.ql.edges().resolve(top) if max(abs(_at(e)[0]), abs(_at(e)[1])) < 6] + hole.sort(key=lambda e: math.atan2(_at(e)[1], _at(e)[0])) + assert len(hole) == 4 + return top, hole + + +@needs_graph +def test_graph_patch_meets_its_walls_in_position(): + box, loop = open_box() + patch = s.make_surface_patch_rface([s.SurfaceBoundary(edge, "C0", wall) for edge, wall in loop], strategy_graph_patch=True) + assert patch.get_area() == pytest.approx(400.0, rel=1e-6) + + +@needs_graph +@pytest.mark.parametrize("continuity", ["G1", "G2"]) +def test_graph_patch_continues_its_support(continuity): + top, hole = plate_with_hole() + patch = s.make_surface_patch_rface([s.SurfaceBoundary(edge, continuity, top) for edge in hole], strategy_graph_patch=True) + # tangent (and curvature) continuous with a plane: the lid is that plane, the size of the hole + assert patch.get_area() == pytest.approx(100.0, rel=1e-6) + assert abs(patch.get_normal_at().z) == pytest.approx(1.0, abs=1e-9) + assert patch.get_center().z == pytest.approx(5.0, abs=1e-9) + + +def tube_window(): + """A tube (radius 30 outside, 26 inside, height 60) with a 40 x 24 window cut through its wall at +y, away from the + seam: the outer cylinder face and the four edges of the window on it, ordered around the window.""" + tube = s.cut_rsolid(s.make_cylinder_rsolid(30, 60), s.make_cylinder_rsolid(26, 60)) + holed = s.cut_rsolid(tube, s.make_box_rsolid(40, 30, 24, bottom_face_center=(0, 30, 18))) + cylinders = s.ql.faces().where(s.ql.prop("geom.type", "==", "CYLINDER")).resolve(holed) + outer = max(cylinders, key=lambda f: f.get_area()) + window = [e for e in s.ql.edges().resolve(outer) if _at(e)[1] > 20 and 17 < _at(e)[2] < 43] + window.sort(key=lambda e: math.atan2(_at(e)[2] - 30, _at(e)[0])) + assert len(window) == 4 + return outer, window + + +def off_cylinder(face, radius=30.0): + """How far a face is from the cylinder r = radius about z, over the nodes of a fine mesh: the largest distance and + the largest angle (rad) between the face normal and the radial direction.""" + mesh = _cpp.mesh(face, 0.01, 0.05) + distance = angle = 0.0 + for p, n in zip(mesh.vertices, mesh.normals): + r = math.hypot(p[0], p[1]) + distance = max(distance, abs(r - radius)) + cos = abs(n[0] * p[0] + n[1] * p[1]) / r / math.sqrt(n[0] ** 2 + n[1] ** 2 + n[2] ** 2) + angle = max(angle, math.acos(min(1.0, cos))) + return distance, angle + + +@needs_graph +@pytest.mark.parametrize("continuity", ["C0", "G1", "G2"]) +def test_graph_patch_fills_a_window_in_a_cylinder(continuity): + outer, window = tube_window() + patch = s.make_surface_patch_rface( + [s.SurfaceBoundary(edge, continuity, outer) for edge in window], strategy_graph_patch=True + ) + # the patch continues the cylinder it was cut from, to what a degree-8 graph represents (~1e-4 mm here) + distance, angle = off_cylinder(patch) + assert distance < 1e-3 + assert angle < 2e-3 + # the piece of the cylinder: radius x opening angle x height + assert patch.get_area() == pytest.approx(30 * 2 * math.asin(2 / 3) * 24, rel=1e-4) + + +@needs_graph +def test_graph_patch_is_far_closer_to_a_cylinder_than_the_plate_filling(): + outer, window = tube_window() + boundaries = [s.SurfaceBoundary(edge, "G1", outer) for edge in window] + plate, _ = off_cylinder(s.make_surface_patch_rface(boundaries)) # about 0.39 mm off + graph, _ = off_cylinder(s.make_surface_patch_rface(boundaries, strategy_graph_patch=True)) + assert graph < 1e-3 < plate + assert graph < plate / 100 + + +@needs_graph +def test_graph_patch_refuses_what_it_cannot_represent(): + box, loop = open_box() + with pytest.raises(s.SimpleCADError, match="support face"): + s.make_surface_patch_rface([s.SurfaceBoundary(edge, "G1") for edge, _ in loop], strategy_graph_patch=True) + with pytest.raises(s.SimpleCADError, match="no holes"): + s.make_surface_patch_rface( + [s.SurfaceBoundary(edge, "G1", wall) for edge, wall in loop], + strategy_graph_patch=True, + settings=s.SurfaceFillingSettings(), + ) diff --git a/tools/render/zebra.py b/tools/render/zebra.py new file mode 100644 index 00000000..301dc70a --- /dev/null +++ b/tools/render/zebra.py @@ -0,0 +1,459 @@ +"""Zebra-stripe (reflection-line) renderer for B-rep files. + +Judges surface continuity visually: across a G0-only junction the stripes break, +across a G1 junction they stay connected but kink, across a G2 junction they flow +smoothly. Pure numpy software rasterizer (z-buffer, perspective camera, +per-pixel interpolated surface normals, 2x2 supersampling); OCCT, through the +SimpleCAD native module, only reads and tessellates the shapes. + + python tools/render/zebra.py a.brep [b.brep ...] --out out.png + [--view x,y,z] [--up x,y,z] [--target x,y,z] [--fov deg] [--fit] + [--focus x,y,z --radius r] [--stripes N] [--stripe-angle deg] + [--size WxH] [--titles A B ...] [--mode zebra|shaded|both] + +--view is the direction from the target toward the eye. Without --focus the +camera frames all inputs (one shared camera, so panels are comparable); with +--focus/--radius it frames the sphere (focus, radius) for a close-up. +""" + +from __future__ import annotations + +import argparse +import math +import sys +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +SS = 2 # supersampling factor per axis +BACKGROUND = np.array([0.965, 0.968, 0.975]) +EDGE_COLOR = np.array([0.10, 0.12, 0.16]) +SILHOUETTE_COLOR = np.array([0.25, 0.27, 0.30]) +ZEBRA_EDGE_COLOR = np.array([0.90, 0.30, 0.12]) # readable on both stripe colours + + +# --------------------------------------------------------------------------- loading + + +@dataclass +class Model: + name: str + vertices: np.ndarray # (n, 3) float64 + normals: np.ndarray # (n, 3) float64, unit, from the surface + triangles: np.ndarray # (m, 3) int64 + edges: list[np.ndarray] # B-rep edge polylines, each (k, 3) + + +def load_model(path: str, deflection: float, angular: float) -> Model: + from simplecadapi import _cpp + + shape = _cpp.import_brep(path) + # Faces keep their own vertices and the normals are evaluated on the + # surface, so normals are never averaged across B-rep face boundaries. + mesh = _cpp.mesh(shape, deflection, angular, relative=False) + vertices = np.asarray(mesh.vertices, dtype=np.float64) + normals = np.asarray(mesh.normals, dtype=np.float64) + triangles = np.asarray(mesh.triangles, dtype=np.int64) + points, starts = _cpp.render_edge_polylines(shape, deflection=deflection) + points = np.asarray(points, dtype=np.float64) + starts = np.asarray(starts, dtype=np.int64) + edges = [points[starts[i] : starts[i + 1]] for i in range(len(starts) - 1)] + edges = [e for e in edges if len(e) >= 2] + return Model(Path(path).stem, vertices, normals, triangles, edges) + + +# --------------------------------------------------------------------------- camera + + +@dataclass +class Camera: + eye: np.ndarray + forward: np.ndarray + right: np.ndarray + up: np.ndarray + focal: float # pixels (at render resolution) + width: int + height: int + + def to_view(self, p: np.ndarray) -> np.ndarray: + d = p - self.eye + return np.stack([d @ self.right, d @ self.up, d @ self.forward], axis=-1) + + def project(self, v: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """View coords -> (screen x, screen y) in pixels (pixel centres at i+0.5).""" + z = v[..., 2] + sx = self.width * 0.5 + self.focal * v[..., 0] / z + sy = self.height * 0.5 - self.focal * v[..., 1] / z + return sx, sy + + +def _unit(v) -> np.ndarray: + v = np.asarray(v, dtype=np.float64) + n = np.linalg.norm(v) + if n == 0: + raise SystemExit("zero-length vector") + return v / n + + +def _basis(view_dir, up): + forward = -_unit(view_dir) + up = _unit(up) + right = np.cross(forward, up) + if np.linalg.norm(right) < 1e-6: # view parallel to up: pick any up + right = np.cross(forward, [0.0, 1.0, 0.0] if abs(forward[1]) < 0.9 else [1.0, 0.0, 0.0]) + right = _unit(right) + return forward, right, np.cross(right, forward) + + +def make_camera(models, args, width, height) -> Camera: + fov = math.radians(args.fov) + focal = (height * 0.5) / math.tan(fov * 0.5) + forward, right, up = _basis(args.view, args.up) + if args.focus is not None: + target = np.asarray(args.focus, dtype=np.float64) + dist = args.radius / math.sin(fov * 0.5) + return Camera(target - forward * dist, forward, right, up, focal, width, height) + + pts = np.concatenate([m.vertices for m in models]) + lo, hi = pts.min(0), pts.max(0) + target = np.asarray(args.target, dtype=np.float64) if args.target is not None else (lo + hi) * 0.5 + if args.target is None: + # centre the projected extents in the image plane + rel = pts - target + x, y = rel @ right, rel @ up + target = target + right * (x.max() + x.min()) * 0.5 + up * (y.max() + y.min()) * 0.5 + rel = pts - target + x, y, z = rel @ right, rel @ up, rel @ (-forward) + margin = 1.0 + args.margin + ty = math.tan(fov * 0.5) / margin + tx = ty * width / height + dist = float(np.max(np.maximum(z + np.abs(x) / tx, z + np.abs(y) / ty))) + return Camera(target - forward * dist, forward, right, up, focal, width, height) + + +# --------------------------------------------------------------------------- raster + + +def rasterize(cam: Camera, verts: np.ndarray, tris: np.ndarray): + """Z-buffer. Returns (inverse depth buffer, triangle id buffer), flat arrays.""" + W, H = cam.width, cam.height + zbuf = np.zeros(W * H, dtype=np.float64) # 1/z, 0 = background + tid = np.full(W * H, -1, dtype=np.int64) + + v = cam.to_view(verts) + near = 1e-6 * max(1.0, float(np.abs(v[:, 2]).max())) + sx, sy = cam.project(v) + tz = v[tris, 2] + keep = np.all(tz > near, axis=1) + ids = np.nonzero(keep)[0] + X, Y, IZ = sx[tris[ids]], sy[tris[ids]], 1.0 / tz[ids] + + area = (X[:, 1] - X[:, 0]) * (Y[:, 2] - Y[:, 0]) - (X[:, 2] - X[:, 0]) * (Y[:, 1] - Y[:, 0]) + x0 = np.clip(np.ceil(X.min(1) - 0.5), 0, W).astype(np.int64) + x1 = np.clip(np.floor(X.max(1) - 0.5), -1, W - 1).astype(np.int64) + y0 = np.clip(np.ceil(Y.min(1) - 0.5), 0, H).astype(np.int64) + y1 = np.clip(np.floor(Y.max(1) - 0.5), -1, H - 1).astype(np.int64) + bw, bh = x1 - x0 + 1, y1 - y0 + 1 + ok = (bw > 0) & (bh > 0) & (np.abs(area) > 1e-12) + ids, X, Y, IZ, area = ids[ok], X[ok], Y[ok], IZ[ok], area[ok] + x0, y0, bw, bh = x0[ok], y0[ok], bw[ok], bh[ok] + + # bucket by power-of-two bbox so each batch is a dense (n, sy, sx) grid + kx = np.ceil(np.log2(bw)).astype(np.int64) + ky = np.ceil(np.log2(bh)).astype(np.int64) + key = kx * 64 + ky + budget = 1 << 22 + for k in np.unique(key): + sel = np.nonzero(key == k)[0] + gx, gy = 1 << int(k // 64), 1 << int(k % 64) + step = max(1, budget // (gx * gy)) + ax, ay = np.arange(gx), np.arange(gy) + for c in range(0, len(sel), step): + s = sel[c : c + step] + px = x0[s, None, None] + ax[None, None, :] # (n,1,gx) + py = y0[s, None, None] + ay[None, :, None] # (n,gy,1) + inside_box = (px < (x0[s] + bw[s])[:, None, None]) & (py < (y0[s] + bh[s])[:, None, None]) + cx, cy = px + 0.5, py + 0.5 + Xs, Ys = X[s], Y[s] + sign = np.sign(area[s])[:, None, None] + inv_area = 1.0 / np.abs(area[s])[:, None, None] + + def edge(a, b): + return sign * ( + (Xs[:, b, None, None] - Xs[:, a, None, None]) * (cy - Ys[:, a, None, None]) + - (Ys[:, b, None, None] - Ys[:, a, None, None]) * (cx - Xs[:, a, None, None]) + ) + + w0, w1, w2 = edge(1, 2), edge(2, 0), edge(0, 1) + inside = inside_box & (w0 >= 0) & (w1 >= 0) & (w2 >= 0) + n_idx, iy, ix = np.nonzero(inside) + if n_idx.size == 0: + continue + b0 = w0[n_idx, iy, ix] * inv_area[n_idx, 0, 0] + b1 = w1[n_idx, iy, ix] * inv_area[n_idx, 0, 0] + b2 = 1.0 - b0 - b1 + iz = IZ[s][n_idx] + depth = b0 * iz[:, 0] + b1 * iz[:, 1] + b2 * iz[:, 2] + pix = (y0[s][n_idx] + iy) * W + (x0[s][n_idx] + ix) + order = np.lexsort((-depth, pix)) + pix, depth, tri = pix[order], depth[order], ids[s][n_idx][order] + first = np.ones(pix.size, dtype=bool) + first[1:] = pix[1:] != pix[:-1] + pix, depth, tri = pix[first], depth[first], tri[first] + better = depth > zbuf[pix] + zbuf[pix[better]] = depth[better] + tid[pix[better]] = tri[better] + return zbuf, tid + + +def surface_attributes(cam: Camera, verts, norms, tris, tid): + """Per covered pixel: exact ray/triangle barycentrics -> interpolated normal.""" + W, H = cam.width, cam.height + pix = np.nonzero(tid >= 0)[0] + N = np.zeros((pix.size, 3)) + D = np.zeros((pix.size, 3)) + chunk = 1 << 20 + for c in range(0, pix.size, chunk): + p = pix[c : c + chunk] + t = tris[tid[p]] + px, py = p % W + 0.5, p // W + 0.5 + d = ( + cam.forward[None] + + ((px - W * 0.5) / cam.focal)[:, None] * cam.right[None] + - ((py - H * 0.5) / cam.focal)[:, None] * cam.up[None] + ) + d /= np.linalg.norm(d, axis=1, keepdims=True) + a, b, cc = verts[t[:, 0]], verts[t[:, 1]], verts[t[:, 2]] + e1, e2 = b - a, cc - a + pv = np.cross(d, e2) + det = np.einsum("ij,ij->i", e1, pv) + det = np.where(np.abs(det) < 1e-30, 1e-30, det) + tv = cam.eye[None] - a + u = np.einsum("ij,ij->i", tv, pv) / det + qv = np.cross(tv, e1) + v = np.einsum("ij,ij->i", d, qv) / det + u, v = np.clip(u, 0, 1), np.clip(v, 0, 1) + s = u + v + over = s > 1 + u[over] /= s[over] + v[over] /= s[over] + n = (1 - u - v)[:, None] * norms[t[:, 0]] + u[:, None] * norms[t[:, 1]] + v[:, None] * norms[t[:, 2]] + n /= np.maximum(np.linalg.norm(n, axis=1, keepdims=True), 1e-12) + # show back sides (open shells, inner walls) as if facing the viewer + back = np.einsum("ij,ij->i", n, d) > 0 + n[back] = -n[back] + N[c : c + chunk], D[c : c + chunk] = n, d + return pix, N, D + + +def _box_square_wave(f, w): + """Box-filtered square wave of period 2 (light on [0,1), dark on [1,2)).""" + + def integral(x): + return np.floor(x * 0.5) + np.clip(2.0 * (x * 0.5 - np.floor(x * 0.5)), 0.0, 1.0) + + return (integral(f + w * 0.5) - integral(f - w * 0.5)) / w + + +def _footprint(img, mask, period=None): + """Screen-space footprint |df/dx|+|df/dy| of a scalar image, ignoring background.""" + out = np.zeros_like(img) + for axis in (0, 1): + d = np.diff(img, axis=axis) + if period is not None: + d -= np.round(d / period) * period + m = np.logical_and(np.take(mask, range(0, mask.shape[axis] - 1), axis), np.take(mask, range(1, mask.shape[axis]), axis)) + d = np.where(m, np.abs(d), 0.0) + pad_lo = [(0, 0), (0, 0)] + pad_hi = [(0, 0), (0, 0)] + pad_lo[axis] = (1, 0) + pad_hi[axis] = (0, 1) + out += np.maximum(np.pad(d, pad_lo), np.pad(d, pad_hi)) + return out + + +def shade(cam: Camera, model: Model, mode: str, stripes: int, stripe_angle: float): + W, H = cam.width, cam.height + zbuf, tid = rasterize(cam, model.vertices, model.triangles) + pix, N, D = surface_attributes(cam, model.vertices, model.normals, model.triangles, tid) + mask = (tid >= 0).reshape(H, W) + img = np.broadcast_to(BACKGROUND, (H * W, 3)).copy() + + light = _unit(-cam.forward + 0.55 * cam.up - 0.35 * cam.right) + ndl = np.clip(N @ light, 0.0, 1.0) + ndv = np.clip(-np.einsum("ij,ij->i", N, D), 0.0, 1.0) + + if mode == "zebra": + R = D - 2.0 * np.einsum("ij,ij->i", D, N)[:, None] * N + ang = math.radians(stripe_angle) + axis_b = math.cos(ang) * cam.up - math.sin(ang) * cam.right # perpendicular to the light tubes + phi = np.arctan2(R @ axis_b, R @ (-cam.forward)) + f = np.zeros(H * W) + f[pix] = phi * (stripes / math.pi) # `stripes` bands per 180 deg of reflection + f2 = f.reshape(H, W) + fw = _footprint(f2, mask, period=2.0 * stripes).reshape(-1)[pix] + fw = np.maximum(fw, 1e-3) + light_amt = _box_square_wave(f[pix], fw) + light_amt = np.where(fw > 1.0, 0.5, light_amt) + dark, bright = np.array([0.10, 0.11, 0.13]), np.array([0.99, 0.99, 0.99]) + k = 0.72 + 0.28 * ndl + col = (dark[None] + (bright - dark)[None] * light_amt[:, None]) * k[:, None] + else: + albedo = np.array([0.62, 0.70, 0.80]) + fill = _unit(-cam.forward - 0.4 * cam.up + 0.6 * cam.right) + h = _unit(light - cam.forward) + spec = np.clip(N @ h, 0.0, 1.0) ** 60 + diffuse = 0.28 + 0.60 * ndl + 0.18 * np.clip(N @ fill, 0.0, 1.0) + col = albedo[None] * diffuse[:, None] + 0.35 * spec[:, None] + col = col * (0.85 + 0.15 * ndv)[:, None] + img[pix] = np.clip(col, 0.0, 1.0) + img = img.reshape(H, W, 3) + + # silhouette against the background + sil = np.zeros_like(mask) + sil[:-1] |= mask[:-1] != mask[1:] + sil[1:] |= mask[:-1] != mask[1:] + sil[:, :-1] |= mask[:, :-1] != mask[:, 1:] + sil[:, 1:] |= mask[:, :-1] != mask[:, 1:] + img[sil] = img[sil] * 0.3 + SILHOUETTE_COLOR * 0.7 + + cover = edge_coverage(cam, model.edges, zbuf.reshape(H, W)) + ink = ZEBRA_EDGE_COLOR if mode == "zebra" else EDGE_COLOR + img = img * (1 - cover[..., None]) + ink[None, None] * cover[..., None] + return img + + +def edge_coverage(cam: Camera, edges, zbuf, width_px: float = 1.5 * SS): + """Anti-aliased coverage of the visible B-rep edges (depth-tested).""" + W, H = cam.width, cam.height + cover = np.zeros((H, W)) + if not edges: + return cover + a = np.concatenate([e[:-1] for e in edges]) + b = np.concatenate([e[1:] for e in edges]) + va, vb = cam.to_view(a), cam.to_view(b) + ok = (va[:, 2] > 1e-9) & (vb[:, 2] > 1e-9) + va, vb = va[ok], vb[ok] + ax, ay = cam.project(va) + bx, by = cam.project(vb) + n = np.maximum(1, np.ceil(np.hypot(bx - ax, by - ay) / 0.5)).astype(np.int64) + n = np.minimum(n, 4 * (W + H)) + seg = np.repeat(np.arange(n.size), n + 1) + t = np.arange(seg.size) - np.repeat(np.cumsum(n + 1) - (n + 1), n + 1) + t = t / n[seg] + sx = ax[seg] + (bx - ax)[seg] * t + sy = ay[seg] + (by - ay)[seg] * t + iz = (1 - t) / va[seg, 2] + t / vb[seg, 2] + inb = (sx >= 0) & (sx < W) & (sy >= 0) & (sy < H) + sx, sy, iz = sx[inb], sy[inb], iz[inb] + + # depth test against the farthest surface in a 3x3 neighbourhood + depth = np.where(zbuf > 0, 1.0 / np.maximum(zbuf, 1e-300), np.inf) + pad = np.pad(depth, 1, constant_values=np.inf) + far = np.max([pad[dy : dy + H, dx : dx + W] for dy in range(3) for dx in range(3)], axis=0) + ix, iy = sx.astype(np.int64), sy.astype(np.int64) + zs = 1.0 / iz + vis = zs <= far[iy, ix] * (1.0 + 2e-3) + sx, sy = sx[vis], sy[vis] + + r = width_px * 0.5 + R = int(math.ceil(r + 1)) + cx, cy = np.floor(sx).astype(np.int64), np.floor(sy).astype(np.int64) + for dy in range(-R, R + 1): + for dx in range(-R, R + 1): + px, py = cx + dx, cy + dy + ok = (px >= 0) & (px < W) & (py >= 0) & (py < H) + d = np.hypot(px + 0.5 - sx, py + 0.5 - sy) + c = np.clip(r + 0.5 - d, 0.0, 1.0) + ok &= c > 0 + np.maximum.at(cover, (py[ok], px[ok]), c[ok]) + return cover * 0.9 + + +# --------------------------------------------------------------------------- compose + + +def _font(size): + for name in ("segoeui.ttf", "arial.ttf", "DejaVuSans.ttf"): + try: + return ImageFont.truetype(name, size) + except OSError: + continue + return ImageFont.load_default() + + +def render(args) -> Image.Image: + width, height = args.size + models = [load_model(p, args.deflection, args.angular) for p in args.inputs] + cam = make_camera(models, args, width * SS, height * SS) + modes = ["shaded", "zebra"] if args.mode == "both" else [args.mode] + titles = list(args.titles or []) + title_h = int(height * 0.06) if titles else 0 + gap = 8 + cols, rows = len(models), len(modes) + canvas = Image.new( + "RGB", + (cols * width + (cols - 1) * gap, rows * (height + title_h) + (rows - 1) * gap), + (255, 255, 255), + ) + font = _font(max(14, int(height * 0.035))) + draw = ImageDraw.Draw(canvas) + for r, mode in enumerate(modes): + for c, model in enumerate(models): + img = shade(cam, model, mode, args.stripes, args.stripe_angle) + img = img.reshape(height, SS, width, SS, 3).mean(axis=(1, 3)) + tile = Image.fromarray((np.clip(img, 0, 1) ** (1 / 1.0) * 255 + 0.5).astype(np.uint8)) + x, y = c * (width + gap), r * (height + title_h + gap) + canvas.paste(tile, (x, y + title_h)) + if c < len(titles) and titles[c]: + draw.rectangle([x, y, x + width - 1, y + title_h - 1], fill=(255, 255, 255)) + draw.text((x + width // 2, y + title_h // 2), titles[c], fill=(30, 34, 40), font=font, anchor="mm") + print(f"rendered {model.name} [{mode}] ({len(model.triangles)} triangles)", file=sys.stderr) + return canvas + + +def _vec(text): + parts = [float(t) for t in text.replace(" ", "").split(",")] + if len(parts) != 3: + raise argparse.ArgumentTypeError("expected x,y,z") + return np.array(parts) + + +def _size(text): + w, h = text.lower().split("x") + return int(w), int(h) + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("inputs", nargs="+", help="BREP files (one panel each)") + ap.add_argument("--out", required=True) + ap.add_argument("--view", type=_vec, default=np.array([1.0, -1.4, 1.0]), help="direction target->eye") + ap.add_argument("--up", type=_vec, default=np.array([0.0, 0.0, 1.0])) + ap.add_argument("--target", type=_vec, default=None, help="look-at point (default: model centre)") + ap.add_argument("--fov", type=float, default=30.0, help="vertical field of view, degrees") + ap.add_argument("--fit", action="store_true", help="frame all inputs (default unless --focus)") + ap.add_argument("--margin", type=float, default=0.06, help="fit margin fraction") + ap.add_argument("--focus", type=_vec, default=None, help="close-up centre") + ap.add_argument("--radius", type=float, default=25.0, help="close-up radius") + ap.add_argument("--stripes", type=int, default=16, help="stripe count (light+dark) per 180 deg of reflection") + ap.add_argument("--stripe-angle", type=float, default=0.0, help="rotate light tubes about the view axis, degrees") + ap.add_argument("--size", type=_size, default=(1200, 900), help="panel size WxH") + ap.add_argument("--titles", nargs="*", default=None) + ap.add_argument("--mode", choices=("zebra", "shaded", "both"), default="zebra") + ap.add_argument("--deflection", type=float, default=0.01, help="linear tessellation deflection, mm") + ap.add_argument("--angular", type=float, default=0.05, help="angular tessellation deflection, rad") + args = ap.parse_args(argv) + if args.fit: + args.focus = None + canvas = render(args) + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + canvas.save(out) + print(out) + + +if __name__ == "__main__": + main()