Files
makeCAD/crates/kernel/src/fair.rs
T
jyviko ea772a0438 Merge develop into main: SolidCraft on the SMLib kernel (v1.1.0-alpha) (#11351)
* UI: rim and wall picking tests for a circle of arcs that is one wall

A circle drawn as two half arcs now extrudes to one full-turn wall with its
seam edge, and each rim is one closed edge (tangency-labs/smlib#67). The tests
keep their intent on that body: a rim clicked once is one item, measured and
highlighted whole and picked from either side; a wall picked either side of
its seam is the same surface, lit whole, and toggles off from the other side;
every face is its own patch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillets: a later round at a corner where earlier rounds meet blends them again with it

The owner's ruling of 2026-10-30: a later fillet on an edge at a vertex where earlier
rounds already meet in a mitre makes the corner rounding all of them at once makes, one
smooth patch, the mitre gone. A body made by constant-radius rounds keeps what they were
made on and which edges they rounded at which radius; a later round reaching such a corner
blends the earlier rounds' edges (from the earliest of those meeting there on) with the new
edges in one SMLib blend of the body before them. The result's history is put over the body
the later round was given: an earlier round's face is that face trimmed anew (its name
kept), the corner patch and the new rounds are the later fillet's. A picked mitre seam has
no round of its own: it is refused unless a new edge of its radius meets it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a later r3 round at an r2 mitre, through the Fillet feature, makes the all-at-once corner

Two box edges rounded r2 in one fillet, then the upright edge at their mitre r3 in a second
fillet (tangent chain on, so the seam comes with it): 10 faces, 7928.743041 mm³ as
fillet_radii of the box gives, the r2 rounds' names kept, the r3 round and the corner patch
the second fillet's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel: a body's record of rounds goes with its history, and can be read back

The rounds that made a body are over the body its history is over: a new history (an
operation carrying a step's result back to its own operands) leaves the record out, so a
later round never reads one history against another body. Body::rounds gives the record and
Body::with_rounds_of takes one back, checked (edges of the body before them, a fillet's
radii, the body's history over that body), for a saved model to keep it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Model cache: a body made by rounds keeps them, so a later round blends them the same after opening

A design gave another body when opened from its model cache: the rounds a body was made of
lived only in memory, so a later round at their mitre was built sequentially (or refused, as
too large) after opening and blended with them when evaluated anew. The saved model now
records, per kernel body made by rounds, the body they were made on (a place in the bodies,
stored once though no state holds it) and the edges with their radii; reading it attaches
them back down each chain, and a thinned model keeps those bodies with the bodies made from
them. Model cache format 7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a corner patch of rounds 2/3/4 takes no more than the strips leave in its block

three_rounds_at_a_corner bounded the patch's extra cut at 3 mm³ beyond the strips, a figure
with no derivation; SMLib's all-at-once body at radii 2, 3, 4 takes 3.099 (V 7878.579574
against strips 7881.678). That body is the strips' outside the block its patch lies in: its
rounds are the strips' cylinders ending at a's section y = rc, b's x = 20 − rc and c's rails
where they meet a's and b's (the patch's four corners, now asserted), so the patch takes at
most what the strips leave in that block (11.86 at 2/2/3, 32.69 at 2/3/4). The lower bound is
that block; the upper one, at most the strips' volume, stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: the io crate's hand-built saved models list their rounds, as format 7 records do

Model cache format 7 (f3cf0c4f3) records a `rounds` list in every saved model, and reading one
without it is refused ("saved model: rounds"), as is a model without any of its other lists:
the states, the preview and the thinned model all came back empty. The io tests' saved_model
and timeline_model wrote format-6 records, so six tests (the round trip, the repeated part
stored once, and the four too-big-for-the-file cases) read nothing. Their bodies are none made
by rounds: the list is empty, and every expectation stays as it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib: pin eaa998a (tangency-labs/smlib#68, #69, #70)

Batch 4: drafts and loops, mitre corners, rim chamfers, rulings, tight box, stitch, point
classification, eased corners. Batch 5: a face's tight box divides its cells at the surface's
knots (thread boxes exact); a cylinder, cone, sphere or torus is extended along its own circles.
Batch 6: a revolution's extension closes its turn; a dropped point's foot is the converged one.
The C API is ABI 5 (smlib_blend_dropping and smlib_brep_classify_point are new; nothing existing
changed), so the binding expects 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a strip's tangent and curvature run-offs are the distance long across the surface

SMLib measures an extension's distance across the surface (smlib_extend_sheet corrects
CreateExtendedSurface until the parameter line through the side's middle is that long), so each
run-off of the cylinder strip, swept 20 along z, adds 5 x 20: 10 pi/2 20 + 100 = 414.159 for
both. The parabola-length formula (418.18) was truck's.

Ruling d2 (2026-10-30).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: one smooth angle, and a round too small to change the part is refused

The blend's tangent angle is the shaded view's half degree (smooth_edges::ANGLE), one value
for smooth. A constant round lies r (sec(d/2) - 1) inside the crease it replaces (about
r d^2/8); below the edge's tolerance it changes nothing and is refused before SMLib (which
answered SM_ERR_INVALID_INPUT), naming the smallest radius that rounds,
tolerance / (sec(d/2) - 1). d is the least turn along the edge
(tangent_edge::least_angle_along, at tangent_all_along's stations).

Ruling d3 (2026-10-30). The block's tolerance is 2e-5 mm, not 0.1 um: at 1 deg the smallest
radius is 0.526 mm, so R2 and R20 reach SMLib, which still calls an edge within 2 deg smooth
(SmEdge::GetBlendEdgeuse); that test is ignored until SMLib uses 0.5 deg.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: the knife-edge chamfers name SMLib's cause, a cusp's ball radius of 0

smlib_chamfer turns the distance into a ball radius d sqrt((1 - c)/(1 + c)), c the faces'
binormals' dot (capi chamfer_radius); at #851's cusp the binormals agree, the radius is 0 and
the call is SM_ERR_INVALID_INPUT before the fillet executive runs (gdb: chamfer_edges sees
radius 0; the dump's why is empty). SolidCraft hands every chamfer to SMLib, so the
ball-contact chord (the ball of radius d: 3.822 wide at d = 2, 159.2365 removed) is SMLib's to
build.

Ruling d4 (2026-10-30).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel tests: a corner round wider than its faces overflows and takes the corner's other edges

R21 on a 20 mm cube's edge builds (6107.529370, closed form, to 2e-12). With R5 on the
corner's other edges the R21 takes the faces they lie on, so the body is R21's alone; SMLib
fails that blend (status 1001, fillet error 4, Unable to Trim Rail Curve) and the test is
ignored until it builds. It replaces the refusal test that expected TooLarge.

Ruling d8 (2026-10-30).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a 1 degree crease rounds, and the knife edge's chamfers build, on SMLib smlib-batch-4-rulings

With SMLib's smooth limit at half a degree (422e6f1) the 1 degree crease rounds R2 and R20
(the test is no longer ignored), and with a cusp's chamfer the ball of radius d (d231547) the
The 0.5 one stays, for its own cause (the chamfer face left apart from the body). Two corner
cases the same SMLib (replay/1.0.1 and those commits) builds come off too.

Needs SMLIB_REV at that SMLib once it is pushed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel, doc: an overflowing round goes first; an edge it removes is gone, and the fillet says so

SMLib (smlib-batch-4-rulings 0e83cca, SMLIB_ABI_VERSION 5) rounds the edges whose rounds overflow
their faces first and then what is left of the others; smlib_blend_dropping says which picks'
edges the overflow removed whole. The smlib crate binds it (Brep::blend_dropping), the kernel
returns those picks (fillet_removing), and a fillet notes them as its warning: "the edge at
(0, 0, 10) was removed by the larger round, so it is not rounded" (a 50 x 50 x 20 block, R21 on
its bottom front edge with the front left upright: the block is R21's alone, in closed form).

Ruling d8: [21, 5, 5] on a 20 cube builds as R21 alone (6107.529370); the test is no longer
ignored. R25 with R2 at a corner (blend_corner) builds the same way, R25's alone in closed form,
where it was refused. The rig's 1080 notched block outline at R8 builds now and comes off the
known-failing list.

Needs SMLIB_REV at that SMLib once it is pushed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: the knife edge's 0.5 chamfer builds

SMLib's trim took a fillet meeting its face at more than 78 degrees for one with no side
(smlib-batch-4-rulings 971e567); the chord of the knife edge's 0.5 chamfer meets the flat face at
81 degrees. The case comes off the known-failing list.

Needs SMLIB_REV at that SMLib once it is pushed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a 15° tapered text builds, every letter grown, exact where its outline gives it

Owner ruling d6: the letter t of "tres long" was drafted inward by SMLib (its
loop's normal, summed from the cross products of its chords, pointed down;
fixed in SMLib). With the fix every letter grows, and the join builds at 3°
and 15° by the Round rule and by the default rule (tangent for spline
outlines), where before 15° was expected to be refused.

Exact where the outline derives it: a letter's section at height z is its
outline offset by e = z tan a, by the Round rule of area A + P e + C e² while
the offset trims nothing (Steiner; C half each loop's turning less
tan(t/2) - t/2 at each reflex corner), so the letter is
A h + P k h²/2 + C k² h³/3. Each extruded alone, the t at 3° and s, l and o
at 3° and 15° are checked to 1e-6 (SMLib measures them within 1.3e-9; its
mass properties integrate to 1e-8). The concave joins of r, n, g and e are
tighter than e already at 3° (their swallowtails trimmed: r 1.1e-3 under the
formula), the t's by 15° (9.9e-5 over), and on the block the letters grow
into each other, so the whole word is checked for what holds exactly: one
closed body with the block, and half-way up every point of each straight
letter's outline inside the solid (the t drafted inward failed that).

With SMLib's fix (smlib-batch-4-text-loops 82133b2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: a sloped basin's mitred rim rounds are checked tangent along their contact lines

1080-fillet-sloped-basin-1-mm-rim-r0-5-4-edges asked G1 at every blend seam. Its front wall
leans 19 over 20 and the others 10 over 20, so at each rim corner the two mitred rounds meet the
sloped corner edge at different heights (0.155625 and 0.276393 below the top): the deeper round
runs on past the corner edge and is cut by the plane of the other's wall, a crease by
construction, the gap below the shallower round filled on that plane. The check now measures
the rounds' contact seams, on the top and on each wall, where the rounds are tangent. The
volume is unchanged.

With SMLib smlib-batch-4-mitre (1c15364): the case passes (V 144530.427946 against
144530.427909, 15 faces, sound); before it, only the four corner creases failed the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* smlib: Brep::classify_point says exactly where a point lies against a body

Binds the fork's smlib_brep_classify_point (SmBrep::Point3DClassify at the body's own zone
tolerance): inside, outside, or on the boundary within that tolerance of a face, an edge or a
vertex. A box and a cylinder just off its curved wall in measure's tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* kernel: Body::classify_point decides inside, outside or on the boundary exactly

SMLib's point classification at the body's own tolerance, on the exact faces and edges, in
place of a mesh at a chord of 2e-3 of the body's size (about 0.4 mm on a 200 mm part). A point
within the tolerance of a face, edge or vertex is OnBoundary, never decided by a ray. A mesh
body's triangles are its exact shape: on them within the record's tolerance, else by ray
crossings. The kernel's own probes move to it; Body::contains goes once its last callers have.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* doc: a hole decides whether it exits at its drill point's shoulder exactly

Material past the depth needs a body with the point inside, air before it needs every body to
have it outside; a point within a body's tolerance of the exit face is neither.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* engine tests: probes ask for the exact point class

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* ui, cli tests: probes ask for the exact point class

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* kernel: Body::contains, the mesh test, is gone

Every caller asks Body::classify_point now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NvoxKQ2rEZvcXNQnhE3Sgs

* kernel tests: the rim chamfers running off their rims build, on SMLib 737c392

chamfer_wider_than_sloped_basin_rim_builds and a_rim_loop_chamfer_running_off_its_rim_builds
waited for SMLib to build the cliff overflow (CloseRemovalRegion refused it,
SM_FILERR_NO_ROOM). The pinned SMLib builds it (eddf0ede4, bba9914b6): both pass on aarch64
Linux and are no longer ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: the cases SMLib 737c392 builds come off the known-failing list

The gate on aarch64 Linux reports 16 fillet cases FIXED with the pinned SMLib: the sloped and
equal-slope basin rim chamfers and rounds past their rims (1080-*, 5835-*), the pocket rim
chamfer past the floor, and the three pocket rim rounds now mitred at the pocket's corners
(every-pocket-*). No other area's gate reports a case fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: the re-blend's removed picks formatted as rustfmt lays them out

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: blend_smlib laid out by the 2024 edition's rustfmt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Skills: the tests skill's unit-test example stays under the 3600-character limit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet: the radius-too-large choice in plain nouns

"If too large: Stop and say so / Largest that fits / Narrow where needed"
becomes "Face limits: Exact radius / Largest radius / Narrowed radius", in
every language of the catalog, with the error and the tip that name them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: a round that would cut through its wall into a hollow is refused

The owner's rule of 2026-10-30: a round running past a rim of its faces
into open air builds; one whose section would remove material through to
a hollow behind its edge (a slit into the hollow, a cut through the part)
is refused as too large, so the fillet names the largest radius that fits.

Decided exactly in the section of a straight convex edge between planar
faces: the round's centre is at depth r below both planes, and it opens
where its arc uncovers a boundary point strictly inside the wedge with no
material beyond it toward the centre (the body's exact point
classification). Looked at: straight edges parallel to the round's (a
hollow's corner), cylinders about parallel axes (a rounded corner), and a
picked concave parallel edge's own round, which fills the corner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: 1668's R7 past the inside corner is refused at 4 + 2 sqrt2

The round's centre (32 - r, 42 - r) leaves the hollow's corner (30, 40)
outside its circle, opening the wall, where sqrt2 (r - 2) = r: the case
expects the refusal naming 6.828. 2852's R30, refused naming 25.24, now
passes too: both come off the known-failing list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* xtask: known-failing grades a nextest junit report against tests/KNOWN_FAILING_TESTS

`cargo xtask known-failing --junit PATH` reads nextest's junit (a file, or every .xml under a
directory, so all of a run's junit artifacts at once) and fails on a test that failed and the
list does not name, and on a listed test that passed (FIXED: take its line off, as the kernel
rig's gate does). A listed test that did not run is neither, since a pull request tests only the
packages it touches. The list has the rig's KNOWN_FAILING format (`<test> <cause>`, sorted, the
rig's own parser), with `<test>` nextest's `<binary id>::<test name>`; `cargo xtask lists`
checks it is sorted. The list starts empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* CI: the test jobs grade their junit against tests/KNOWN_FAILING_TESTS

Native Linux tests and the GPU path test shards no longer fail on any failed test: nextest's
"tests failed" exit (100) goes to `cargo xtask known-failing --junit`, which fails on a failure
the list does not name and on a listed test that passes. Any other nextest exit (a build error,
a bad filter) still fails the step at once. The tests skill says to list a failing test with its
cause, in place of ignoring it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: the known-failing list takes develop's 10 failing tests

Develop 38fd4a4f6 (CI run 41157648345, after the SMLib eaa998a pin) fails 10 cargo tests; each
is listed with the cause its failure message gives. Seven are SMLib refusals or results off
their derived volumes (fillet, chamfer and shell), the cli action matrix and naming corpus
among them; the two corner_g2 tests are the fitted G2 corner patch bulging past the box, which
the explicit G2 corner fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Reference tests: the eight cases that fail on SMLib eaa998a name their cause as known failures

Develop 38fd4a4f6's Reference tests fail 34, 35, 77, 78 and 81 (STEP export finds fillet edges
4.6e-5 to 6.1e-5 off their surfaces against 2e-5), 37 (the apex blend 0.193 off), 80 (the
taper-to-fit area) and 83 (thicken status 1001). Each expected.json names its cause in
known_failure, which the oracle already reads: a known failure that passes fails the job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sweep path: a curve of several pieces is turned round whole

The path chain oriented its first piece, not its first curve: a first curve
of several exact pieces (a fit spline, an ellipse, a projected free-form
edge) was never turned round, so a path whose next curve meets it at its
start was refused as "not connected end to end". The chain now orients
curve by curve: the first runs toward the second where they meet at one
end only (else from the end nearest the profile), each next one starts
where the previous ended, with one joint tolerance for both questions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib: pin 2fc375f (tangency-labs/smlib#71, #72, #73)

A sheet's side is extended exactly the distance asked, or the call says it cannot (#71);
NVIDIA's -Werror build passes again (#72); a body splits by a sheet of several faces as it
is, smlib_split_body_by_sheet (#73). The C API is ABI 6 (the new entry), so the binding
expects 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: Extend grows a surface of several faces face by face

A surface body of more than one face (a fit-point spline's spans extruded, #3830) was refused.
Each face with a picked edge is now extended alone by SMLib's extension of its surface, and the
faces are sewn back together, each the face it was. A side that lengthens onto a face meeting it
tangent takes that face along, past its edge continuing the picked one; across a crease the
neighbour grows only when its edge is picked too, otherwise the extension is refused. Faces whose
lengthened sides no longer meet are refused. Up to a target keeps the pieces every grown face
lies in.

3830's extensions now build; its split still fails (the tool point picks one span, and a face
tool cuts with that face's surface alone), so it stays on the list with that reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: Split Body by a face of a smooth sheet cuts with the whole sheet

A face tool cut with that face's surface alone, so a face of a surface body made of spans joined
tangent (a fit-point spline extruded, #3830) cut nothing where its span ends inside the body.
Split Body by a face of a surface body now takes the faces joined to it tangentially (the exact
check Extend uses, within the one angle for smooth) and slices with them as they are, through
SMLib's slice by a sheet (smlib_split_body_by_sheet, tangency-labs/smlib 7a01f1b), its sides those
of the picked face. A sheet that only nicks the body cuts nothing, as before; a lone face, or a
face of a solid, still cuts with its surface extended.

3830 comes off the booleans list. Its answer counted the two halves of the cup and not the surface
that cut it, which stays as a body of its own (4879 removes its surface for that reason): three
bodies, the volume unchanged.

Needs SMLib 7a01f1b pinned (SMLIB_REV, prebuilt; its SMLIB_ABI_VERSION 6, which crates/smlib now expects) to link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: a cylinder strip's run-offs are 100 pi + 100 to 1e-6, SMLib's exact area

The tangent and curvature run-offs of the quarter cylinder r 10 strip, 5 across the surface,
are its section swept 20 along z: exactly 10 pi/2 20 + 5 x 20 = 414.159265. measure is SMLib's
integration on the exact surface (1e-8), not a mesh, so the run-off check is 1e-6 relative and
the 'measured on meshes' notes go. Red until SMLib's extension is solved to its distance
(smlib-extend-converges 590d8a1): eaa998a's curvature run-off is 4.986 long, area 413.882.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: an extension SMLib cannot make exact says so, naming the length asked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sketch: a control spline can carry its own knots and weights

A sketch spline over control points was always the clamped uniform B-spline
over them, so a free-form edge whose knots are not evenly spaced (or whose
weights are not 1) could only come into a sketch as one curve per Bezier
span. A control spline now may save `nurbs`: its clamped knots and its
weights. Its points, polyline, exact pieces (one a knot span; conics for a
rational quadratic), the solver's distance and curvature, links, parallel
re-projection and inspect.sketch all read them; a loaded design's are
checked. One pending format file (spline-knots).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sketch projection: a free-form edge comes in as the one exact spline it is

A projected spline edge of several Bezier spans came into the sketch as one
curve per span (#1508), so a G2 round's bottom edge was 16 curves and a path
naming the corner named one span of it (#3604). The kernel now reads such an
edge (a spline, or an elliptical arc of several spans) as the one clamped
B-spline it is over the edge's interval, its knots and weights its own, and
the sketch takes it as one control spline whose ends sit on the edge's
vertices. Planar regions still read edges span by span. The 3604 case builds
with its original path and leaves KNOWN_FAILING.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: blends past an outer rim of their faces build, on SMLib smlib-blends-past-rims

The owner's ruling: a round or chamfer that runs past an outer edge of its face into open air
builds, tangent where it has room and cut by the face beyond where it runs out. SMLib's branch
smlib-blends-past-rims builds them by the rig's analytic answers. Off the known-failing list:
the disc's rim past its 2 mm wall (190), the hole's top rim R12 past the plate's bottom, the
chamfer past the cylinder's bottom (2893), each closing on the wall continued as itself, and
926's chamfer ending on the boss's wall, which now builds to its answer too.

The sloped basins' R4 rim rounds (1080, mitred rounds built together where one overflows) build
to their analytic volumes (to 6e-9), and stay listed with that reason: their continuity check
(g1 at every blend seam) takes in the mitres' creases, G0 by the mitre ruling.
2893-chamfer-two-distances-elliptical-rim is graded as a solid (the owner: it builds) and stays
listed, waiting on the ruling on unequal chamfers along a rim whose angle varies.
5158-fillet-round-just-past-a-10mm-face stays listed with its cause found: the round passes
5e-6 under the box's top back edge, inside the body's tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Naming: test that a round of a round's end has no seam with that round's faces

The r1 round of a block's top edge, chained onto the end curve of the r2
round of its arc at a cylinder (rig fillets/every-block-cylinder-crease-
top-edge-after-arc-round-r1), ends where it runs into the cylinder. That
edge is no seam of the r1 round: the cylinder is a face of the r2 round,
not of the r1. blend_seams takes it for one today (the r2 round's name
F3:blend:F1:+z|F2:side holds a | of its own), and the rig reads it as a
contact seam at 60 degrees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Naming: a blend's seams split its edge's name at the | between its two faces

A blend face's name holds the edge it replaced, <face>|<face>, and a side
of that edge can be a blend face whose own name holds a |. Whether a face
is a contact of the blend was read as the edge's name starting or ending
with the face's name next to a |, so the r2 round's own face F2:side read
as a contact of the r1 round F4:blend:F1:+y|F3:blend:F1:+z|F2:side. The
edge's name is now split into its two faces, a blend side read whole as
the two faces of its own edge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fillet rig: five refused blends build, off the known-failing list

926 (the chamfer ending on the boss's wall), the oblique cut's r0.1
round, the every-block r1 round (its seam with the cylinder is no
contact seam, after the blend_seams fix), the up-down squares' concave
chamfers and the shelled box's lip chamfer build with SMLib branch
smlib-blend-refusals (f8650b8 and later). 1207 r0.5 passes SMLib's check
on its rails now and stays listed for the next cause: its end rib on the
boss, which starts where the round and the boss are tangent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the trough and the pocket whose floors fall to a drain build

SMLib now offsets a vertex where four faces meet (two walls and two facets at the floor's
corners, four facets at the drain) to two vertices joined by a new edge (tangency-labs/smlib
branch smlib-shells). Both volumes match their closed forms. The pocket's lining, hanging from
the top's rim round the pocket, stands apart from the slab's outer walls with the cavity rising
between them to the open top: the case says two shells in the one body.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the plate with a hole through its arc side shells open at its far end

SMLib's merge now intersects the offsets of an edge's faces where they could not be mated along
it (the hole's offset poking out through the half-round side's; tangency-labs/solidcore#1795):
one closed valid solid with the one face open, as the owner ruled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the ring cut frame and the up-down join shell

SMLib's inset now keeps only the regions that are cavity, not the one the offsets close where
they overlap (between the two faces of #545's 0.5 floor, round the up-down join's two empty
octants). The frame's core under the recess is hollowed to a sealed void, so the case says two
shells and its closed form, 21044 mm³.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: #616's lid shells open at a rib's side, with the 0.15 lip

SMLib keeps the skirt top's offset where its loops wind the other way under the opening, the
cavity's floor (the owner's ruling of 2026-10-31: build it; a lip thinner than the wall is no
break-through).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Known failing tests: the action matrix's shells and chamfers as they fail with SMLib batch 7

The ring cut frame's and the up-down join's shells build now, and so do the up-down join's and
modern-plastic's chamfers (SMLib smlib-blend-refusals). #616's lid in the corpus still fails
SMLib's loop check, the shelled box shelled again at an inner wall is unchanged, and the
oblique cut of a cylinder's fillet still fails SmSurfOfRevolution's Test #7: 3 actions of 7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib: pin 26cc451 (batch 7: rounds past a rim, blend refusals that build, shells)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Known failing tests: the shell after a cut whose end touches an arc side builds on SMLib batch 7

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Surface fair test: the energy falls strictly, the face moves, and the edges are read after the fair

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sketch scaling test: the first dimension sets l1 to 40 and scales both joined rectangles about the origin

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Frames tests: a pick on a moved component or an instance removes the exact round and bore volumes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Issue 1080 tests: the rib's rounds and the mitred corner chamfers and rounds have their exact volumes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Engine tests: lip_after_boss checks each lip's and groove's exact band, hole_as_deep_as_the_plate each hole's exact bore

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Robustness tests: lip_after_boss and hole_as_deep_as_the_plate live once, in the engine's tests.rs with exact volumes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Engine tests: loft_cut goes; loft_spacing's hollow elbow covers its section counts and more

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel loft test: the square-to-circle loft has the oracle's exact ruled volume, without printing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tessellation lens test: the lens's triangles fill exactly the rhombus through its arcs' midpoints

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pattern test: six chamfered holes take exactly five more holes' bore and chamfer rings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel pocket floor fillet test: the corner rounds and the floor loop round add their exact volumes, by Pappus at the corners

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Shell regression: the saddle-corner shell opened on the top box's side has its exact volume

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib history test: every operand's order is the identity on its record's faces and edges

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Boolean history tests: the SMLib module's box-minus-sphere, box-minus-cylinder and box-union-box copies go; the top-level ones check more

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Modify history tests: shell, offset and thicken are one test each through the public API, with the volumes, refusals and history the SMLib copies checked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chamfer history test: the chamfer after each box cut is exactly one face on the painted block too

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Grid test: a pole side's face is the five triangles fanned from its one grid node, none degenerate

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel tests: the twelve ignored print-only debug tests and surveys go; coplanar_curved_booleans checks the flush-capped cylinder cuts and unions they printed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel: the #883 board fixture generator is an example, not an ignored test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STEP import test: a seam sphere whose meridian stops short of the pole imports as the whole 2 mm ball

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Material tests: the nine copies in material_properties go; the persistence file checks the library copy's card and formats 20 and 21 in one loop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sample test: one loop checks every sample builds cleanly and without a panic; the robustness copy goes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Known failing: the non-antipodal seam sphere import, refused for a loop of no (u, v) area

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: rustfmt the board fixture example and the coplanar asserts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the two 3871 cone cases were byte-for-byte the 258 cases; the 258 cases carry their sources

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: a volume or area can be graded as a hand-derived range where analysis only bounds it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: fillets keeps one case per regime; 17 replications of a case in the same regime go

The sloped-basin chamfers and rounds at 0.5 mm rims repeat the 1 mm rim's regimes; two of the
three knife-edge chamfer tips, the r1 and box r3 curvature corners, the r1 tangent corner, the
1 mm pocket-rim and hole-rim chamfers short of the floor and the r1 together-round each repeat a kept case's regime
and grades. #854 moves to 851-chamfer-arc-top-edge-9-5, and the cases that cited a dropped one
cite the kept one or state its formula.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: five cases outside fillets repeat a kept case's regime and go

A square cut is the slanted plane's ordinary crossing; the cam's half turn is the quarter turn's
contact at a symmetric angle; the r15 slab stands inside the same coincidence tolerance as the r10;
the 90 degree unfold and the 40 degree flange repeat the 72 degree and 20 degree cases' formulas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 3243 rim and tooth join graded on its volume (rim plus the trimmed tooth less their 0.01 mm overlap)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 3782 emboss on a cylinder graded on its volume, area, faces and box (the wrapped 4 x 5 badge raised 1 mm)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 3604 G2 swept-tool cut graded on a volume range (filleted box minus the swept corner section)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4505 coil joined through a cylinder wall graded on its volume, area and box (cylinder plus the wire's screw-swept segment outside r 76)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4879 window cut through a thickened spline revolve graded on a volume range and its faces

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4623 join of crossing pleated loft skins graded on its volume and box (both skins less their overlap)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 831 tapered glyph extrude graded on a volume range and box (the font's S drafted in by 10 deg)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 2357 ring of 90 cylinder segments graded on its volume and box (the segments less their 90 joint overlaps)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4542 fluted wall joined on a revolved base graded on its volume and box (the base by Pappus plus the fit-spline ring)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 1985 and 2243 STEP-export enclosures graded on their volume and box (the outline less the cavity, plus gusset and standoffs)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: both 4092 loft, ribs and pad unions graded on their volume and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 1525 graded on its volume (the convex body's exact 2 mm inward offset), faces and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 1494 graded on its volume (box and cylinder less the 1 mm-offset cavity, sharp to rounded concave edges) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4492 graded on its box and a volume range (the face's 19 mm sweep added, within the block's sides)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 745 graded on its volume (the end moved 1 mm plus the spline boss's exact area), faces and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 4567 graded on its volume (the revolved spline less its revolved 2 mm offset), faces and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the up-down squares shell graded on its volume (the columns less the 0.346 mm-offset cavity, sharp to rounded concave edges) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 545 graded on its volume (the frame less its 0.5 mm-offset cavity, sharp to rounded concave edges), its sealed pillar void and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the shell-again case graded on its volume (the shelled box less the 0.5 mm-offset cavity in its walls) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the arc-sided plate shell graded on its volume (sharp to rounded at the hole's bottom), faces and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 616 graded on its volume (the lid less its 0.5 mm-offset cavity, sharp to rounded concave edges) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 391 graded on its volume (the shelled housing, sharp to rounded at the flange, less the letters' 0.6 mm deboss) and box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: shell/3576 was the ladder's drafted box with rounds shelled, recipe for recipe; the ladder case grades it and carries #3576 and #3573

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the two 851 chamfers of 2 graded on their volume (the cone's sweep, and its union with the front edge's prism)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the chamfered corner of the lipped shell graded on its volume (the chamfer's triangle through the wall)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the concave round into the peg's cylinder graded on a volume range (the torus it must add, the band it can't leave)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the two folded 72 degree trays graded on their volume (flat area x thickness) and the walls' reach

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the flanged rhombus graded on its volume (flat area x thickness, all four reliefs cut) and its walls' ends

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the base with two adjacent flanges and a hole graded on its volume (base, bends and panels folded)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the flange beside the ledge graded on a volume range (the flange's two readings of its length)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the two G0 window patches graded on the box the part they close keeps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the hub's six swept grooves graded on its volume (the revolved hub less each tube's part inside it)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the cut mirrored loft graded on the box its sections pin

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the three modelled-thread joins and the fine M48 graded on their volume (the basic profile's groove, Pappus)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the oblique-cut round graded by its seams (tangent, not curvature-continuous); the flanged rhombus says what it tests (its reliefs stay apart at 60 mm)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 3841 is 168's rim touching its coin along a circle, and 4092's reduced recipe is its report less a flange clear of the failing join; the kept cases carry their sources

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the oblique-cut round keeps its old grade until the new blend algorithm lands

Its seams grade needs the continuity check to skip the body the round is not on. Fillet cases
wait for the new algorithm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: 1985's enclosure is 78 x 77 (74 and 73 inside, 2 mm walls); its volume 38063.827 by hand

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the three spline walls' face counts wait for the one-wall decision; their volumes grade them

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STEP import: a face bounded by seams alone runs its loop the other way, never turns over

A loop that uses each of its edges once each way (a whole torus within its tube and ring seams)
is the same set of uses run backwards, so it says nothing of the face's side. One written
clockwise in (u, v) turned the face over, against its same_sense: the torus came in inside out
with a warning. Such a loop is now reversed and the face keeps its side.

Test: seam_only_torus_imports_as_a_whole_ring, both orders of the two seams, volume 2π²Rr².

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STEP import: a face bounded by a slit alone is the whole of its closed surface

A loop that runs out along a chain of edges and straight back (a meridian from a sphere's pole
stopping short of the other, out and back) encloses no (u, v) area, yet on a closed surface it
bounds all of it less a cut of none. The reader only read such a face when the slit already ran
pole to pole (and moved the sphere's frame onto it only then), so the 2 mm ball whose meridian
stops at 2.5 rad was refused for its empty loop.

The slit is now made the face's seams, so its loop bounds the surface's whole domain: on a
sphere, a revolution whose profile ends on its axis, or a spline closed round u that collapses
at both ends, the slit's meridian is run on to both poles, out and back (a sphere's frame put
on the slit first, whichever two points it joins); on a torus, the circle the slit lies along is
closed and the other circle through its start is the second seam. The seams on a sphere are its
own meridians (angle 0 on the equator), so their pcurves are exact lines on its form.

Tests: non_antipodal_seam_sphere_imports_as_a_whole_ball passes (its known-failing line goes);
seam_only_torus_imports_as_a_whole_ring adds a torus bounded by a slit along its tube.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the test-peg's concave arc and front top edge rounded together stay within the body's box

A new fillet case, report-fillet-concave-arc-and-front-top-edge-together-solver-residues:
the reported part's bar (with the sketch solver's residues) whose sides run tangent into the
cylinder, its concave arc and front top edge rounded r2 together. The plane of the front face
bounds the whole body, so every blend lies within the unblended body's exact box (SMLib's tight
box); graded to 4e-5, the corner patch's own tolerance. On SMLib 2fc375f the corner patch
stands 0.0374 out of the front face (box y min 0.0205): listed in KNOWN_FAILING.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the test-peg corner at r5 and r7

Two more fillet cases, the reported part's concave arc and front top edge rounded together at
r5 and r7, with the same exact-box containment check (graded to 4e-5, the corner patch's
tolerance). On SMLib 2fc375f the corner patch stands 0.128 (r5) and 0.230 (r7) out of the
bar's front face (box y min -0.0699 and -0.1723): listed in KNOWN_FAILING.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: blends that end where their face runs tangent into another

Fifteen fillet cases on the test-peg's shape with clean numbers: a bar 40 x 16 x 10 whose far
end is a half disc R8, a disc R8 standing 10 on its top, joined, so the front face runs tangent
into the cylinder along x = 40 and the front top edge (convex) meets the concave arc of the top
tangentially there. Each blend ends on a face tangent to the one it rolls on.

- Rounds: both edges together at r2 and r5; one after the other in either order at r2, and at
  r1.5 and r3; the front edge alone as a curvature round, whose end on the cylinder is a
  semicubical cusp. The containment invariant (the unblended body's exact box, to 4e-5) and
  G1 seams, or the analytic volume where the blend has a closed section.
- Chamfers: the front edge alone and the concave arc alone (analytic volumes: the section along
  x up to the wall, the cone's spandrel ring clipped by the sides), both together, and one after
  the other (1 then 2).
- STEP: the peg written to STEP and read back, its front edge rounded (analytic) and both edges
  rounded together.
- A cone: the peg drafted 5 deg, whose front face runs tangent into a cone along a generator,
  its front edge alone and both edges together.

The quadratures are tanh-sinh, converged to 1e-13; SMLib's own volumes of the passing analytic
cases agree to 4e-9. A sphere is left out: a plane meets a sphere tangentially at a point, not
along a seam, so it is not this ending.

On SMLib 2fc375f eight fail, listed in KNOWN_FAILING: every chamfer that ends tangent (status
1001, SmFilletNx1Corner), the two rounds together (the corner patch 0.0374 at r2 and 0.128 at r5
out of the front face, and the rounds meeting with normals 180 degrees apart where their
contact lines on the top cross), the same on the STEP-read peg (status 1001) and on the drafted
peg (its corner refused as unsupported).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: fillet corners graded curvature-continuous, the default to be

Six fillet cases that pick their edges with no type, so they take the fillet's default, which the
owner has ruled is to be curvature-continuous (G2) at every corner, with circular rounds kept as
an option. Each grades every seam of the rounds and of the corner patch G2, on one valid body:

- an oblique convex corner (a block drafted 15 deg);
- a four-edge and a five-edge apex corner (pyramids lofted to a point);
- a pocket's concave corner;
- a mixed corner (a step: one concave edge, two convex);
- a corner beside a cylinder (the top corner of a half cylinder).

All six fail on SMLib 2fc375f, listed in KNOWN_FAILING: today's default is the circular round,
whose seams jump in curvature by 1/r. On the five-edge apex the corner patch also meets two
rounds at 8.45 degrees (G0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the test-peg's front chamfer builds

With the SMLib fork's smlib-tangent-ends (a rail's end on its side edge is the rail/edge
crossing), report-peg-front-chamfer-d2 passes. Its line leaves KNOWN_FAILING, for the pin that
carries that fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the curvature-continuous corner cases pick the curvature fillet

The six corner cases added in 3a854104a took the fillet's default type, on the premise that the
default would become curvature-continuous. The default stays the circular round, so each case
now asks for the curvature fillet itself (type curvature: curvature-continuous sections and
corner patches) and keeps its grading: every seam of the rounds and of the corner patch G2, one
valid body. They are renamed from cov-fillet-g2-default-* to cov-fillet-g2-*.

The oblique three-edge corner (a block drafted 15 deg) and the pocket corner pass. Four fail, as
KNOWN_FAILING now says:

- the corner beside a cylinder: the curvature fillet builds its sections only between planar
  faces;
- the four- and five-edge apex corners: refused because the default setback is shorter than
  where the rounds' contact lines meet (3.90 and 3.51 mm from the apex);
- the mixed corner: SMLib sets back a corner only where its edges are all convex or all
  concave.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rig: the test-peg's concave chamfer, alone and after the front chamfer, builds

With SMLib's tangent end as an event of the fillet's trace (blend-end-event 6d73e4f), the
concave chamfer's rail on the cylinder ends where it crosses the seam along which the front
face runs tangent into the cylinder, continued past the vertex, and its end rib on the front
face is built from there. report-peg-concave-chamfer-d2 and
report-peg-front-chamfer-d1-then-concave-chamfer-d2 pass and leave KNOWN_FAILING. The two
chamfers together still fail, now at the mixed-convexity corner where they meet: its line says
so. Rig against SMLib 0cc48bd: no area regresses (963/993 pass, 961 on a87c502), ladder 168/168,
kernel lib only its listed failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: constant rounds of the exact classes, and a tee's round

A plane cutting a cylinder or a cone at an angle, a sphere or a cone coaxial with the other face, a
cone and a cylinder touching one ball, two pipes touching at a point: their rounds' centre lines
are rational, so the rounds are rational surfaces of degrees fixed by the construction ((4, 2),
(2, 2) revolved, (6, 2), (12, 2)). The tee's centre line is not rational; its round is graded on
its volume. Volumes from the divergence theorem over the exact pieces, at rel 1e-6. The six that
SMLib 0cc48bd traces are listed in KNOWN_FAILING with what they come out as.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the exact-class rounds pass on SMLib's classified exact rounds

The rounds now come as the rational surfaces their classes give, closed ones as two faces split
at their seams, the touching pipes' as four: one splines entry a face, each of the class's degrees.
Their KNOWN_FAILING lines go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SMLib: pin 7ac037e (the new blend's tangent-end event, zero-speed G2 ends, and its exact-class rounds)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the fillets known-failing list is the 22 cases that fail on SMLib 7ac037e

Twelve listed cases build on the new blend's end event and exact classes, or were already
built on develop: they come off the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: #316's bottom rounds as large as the wall, or larger, shell with a step wall at the opening, not refused

Where the round meets the open bottom the cavity's wall steps down along the bottom's normal, so the
round meets it at 90 degrees and the opening is exactly the picked face. The cases are renamed and
graded on the exact volumes, and come off the shell known-failing list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Merge fixes: every crate and test target compiles on the merged tree, but for crates/geom's hlr

world_state, view::bounds, home_camera and scene return Result on develop; new
main code takes that with ? or session_world. New fixtures carry the spline's
nurbs. ForeignCopy::of returns Result. occurrence_placement_with walks the path
with its moves, since the placement index holds pending_moves only.

The hlr port is separate and still to come: this commit does not compile as it
stands in crates/geom/src/hlr.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Drawings hidden lines: read develop's B-rep records

Edges come from the record's edge list, cut to their interval (C3::of_edge), and
faces from its face list; a cylinder, cone, sphere or torus chart takes its bounds
from where its NURBS form lies on its label (S3::of_face). A rigidly placed
revolution has main's revolution chart; other placements stay refused. Moving a body
to its centre goes through Brep::moved. Loops are read against the natural normal of
the face's parameters where a chart wraps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Hidden-line fixtures: build develop's records from the fixtures' data

Fixtures keep their bounded curves and surfaces and their own edge numbers; a private
builder makes the canonical record, and the local prepare puts the edges back in the
fixture's numbering. Assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Hidden lines: tests of the bounded edges, face charts and placed revolutions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* drawing-hlr doc: what is drawn and refused on develop's records

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* hlr tests: a placed revolution is refused when its placement is not rigid

The new model has one record for main's Revolution, which was drawn, and its
PlacedRevolution, which was refused. An identity placement is now the former, so
this test's fixture takes a non-rigid one. The refusal it asserts is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Hidden lines: a traced intersection is drawn only where its spline lies on both surfaces

A leader off either surface is refused like a curve with no spline to follow. Tests: a traced rim
drawn on the circle and plane within tolerance, the same leader 1 mm off refused, and kernel bodies
with arcs through the production prepare against closed forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Hidden lines: kernel bodies through the production prepare against closed forms

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Tests from main: the world state is a Result here

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* A blend's pick measures close edges on their curves, not their polylines

A polyline can be a chord off its edge, more than two edges are apart near a
tangent point. A pick exactly on a ball's rim took the straight edge the rim is
tangent to, and solidcore built a chamfer of that edge with a clean check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk
(cherry picked from commit c786db6bf49804fb83a02f0eb7f83bd9f82fa643)

* Merge fixes from the first SMLib test pass

Model cache key covers the crates develop's kernel adds under doc (profile, smlib, step).
A piece taking a name also takes the feature that made it: SMLib lists a cut's pieces in another
order, and the swap left the name on a piece of the wrong feature.
A replaced analysis keeps its status slot. A command with no world picks does not place the model
first, so assembly.mass_properties answers for a flattening placement. FeatureCommon loses the
touching key the merge added; only the contracts that read it take it.
Two of main's tests listed as failing on SMLib, with why.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Merge fixes from the ui test pass and the gates

Main's thread.direction keys go with develop's thread hand, which replaced them. Vietnamese for the
messages develop added while main made vi a complete catalog. CGA and 1-bit themes set develop's
comb and section hatch colours. A ribbon button with a persistent effect is pressed only while its
tool runs, so persistent_ribbon_pressed alone decides how its effect is shown; other analyses stay
pressed while on. Two of main's ui tests listed as failing on SMLib, with why.
Gates: fixed thread tables become slices, one collapsed if, rustfmt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* A silhouette takes its facing from the surface's normals

A flat triangle beside the outline can tip the other way from the surface it approximates, and its
edges joined the outline. On SMLib's sphere that made 192 segments instead of the equator's 64, 100
curves and 95 profiles from the tight fit of #7989. Each corner's normal is used where it is close
to the triangle's own; a mesh without such normals (none, zero, not numbers, or averaged across
creases) keeps the triangle's normal, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Clippy and rustfmt on the merged tree

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk

* Stepwise open checks every feature under the session's mode

OpenSteps::start evaluated under the default check mode, and finish kept those results under the session's mode: an each_step or off session opened in steps recomputed nothing. start now takes the mode (the app passes its session's), and a mode that changed before finish evaluates the design again under the new one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Clippy without SMLib: the planar-sheet edge reader is built only with it

Its one caller is in the smlib-only sheets module, so without the feature it was dead code and
clippy -D warnings refused the kernel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* SMLib: pin d01d7b0 (the new blend's one Gⁿ section generator: the chord, circle and curvature sections, and the variable rounds as the union of their balls)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the section orders, chord, circle and curvature section, on planes and against a cylinder

Eight fillet cases for the blend's cross-section by its order of contact with the faces, each
graded on its analytic volume at rel 1e-7 and its exact continuity (the order, and not the next):

- a box's top back edge chamfered 3 (G0), rounded r3 (G1) and curvature-rounded 3 (G2): the
  areas cut off the corner s^2/2, (1 - pi/4) s^2 and 113/756 s^2, the last by the default
  thumbweight's definition;
- a pipe R10 dipping into a plate, its concave edge chamfered 2 (the chord between the contacts of
  the ball SMLib rolls for that setback, radius 1), rounded r2 and curvature-rounded 2, each
  section's added area by Green's theorem along the plate, the section and the pipe's arc; the
  order-2 section is built from the faces' feet of the point at distance d from both, which on
  the pipe are not linear in d;
- a boss root curvature-rounded 2, the square corner's section revolved (Pappus);
- a variable round r1 to r5 along a box edge (rel 1e-5): the balls' envelope is a circular cone,
  and the volume is the cone's sections integrated along the edge.

Three fail today and are listed: the two curvature rounds whose faces are not a square corner of
planes (SMLib's quintic blend curve, not the order-2 section: rel 6.5e-7 and 1.2e-5) and the
variable round (great circles, not the envelope's: rel 4.8e-5). The other five pass on SMLib
7ac037e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the curvature fillets' expected bodies from the order-2 section at thumbweight 0

SMLIB_BLEND_CURVATURE's section is now the order-2 G^n section at thumbweight 0. Between two
planes square to each other it cuts A = 0.154192655384275 s^2 off the corner, its first moment
about either face 0.0291753295725360 s^3 (Green's theorem on the section): the curvature cases
built on that corner (862, 2708, every-box-edge, every-hole-top-rim, every-l-bracket,
every-block-cylinder-crease, the three-edges-at-bar-corner reports, 3604's fillet) take their
volumes from it by their own methods, the peg's front blend 23.3237146876 (its section along x
up to the wall). Between planes the section's t^3 term vanishes (their feet are linear in the
distance): the box edge case is exactly G3. The boss root is a certified fit, G3 to the plate and
G2 to the wall at Continuity Analysis's tolerances: at least G2. The boss root and the pipe on
the plate pass on SMLib's section and leave the known-failing list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Curvature fillets: the section's default thumbweight is equal area, so the round's volumes are the circle's

On the round's rails the order-2 section takes off what the ball's circle does: (1 - pi/4) s^2 at a
square corner, first moment 0.0474559669443 s^3 (w = -0.5252123889). The kernel and engine tests
and the curvature rig cases take their volumes from it by their own methods; the pipe on the plate
from its own wedge (70.52878 degrees, w = -0.8544103493). The G2 corner patch's seam test is listed
until the corner step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: four G2 corners wait for the corner step: their patch meets the new section's rounds G1 at one face seam

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the turn at a corner of two rounds, Mitre (the default) and Swept, at a pocket's floor and a boss's base, by exact volumes

A round's spandrel A = (1 - pi/4) r^2 and its first moment about its wall M = r^3 (5/6 - pi/4):
Mitre adds L A -+ 2 M per edge (cut at, or run on to, the corners' bisector planes), Swept turns
the section about a convex corner's edge, (pi/2) M a corner, and refuses a concave corner rounded
less than the ball. The pocket's tangent chain round its R3 corners is a torus each. Graded to
1e-7, where Mitre and Swept differ by 6.6e-6. The Swept cases are listed until solid.fillet
takes a turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: a junction family: oblique wedges 30 to 150 degrees rounded and chamfered (exact), bosses upright and tilted, pipe tees and a Y junction

Four are listed with their causes: the equal-pipe tee (its exact conic-pair rounds meet at the
ellipses' crossings in a corner the old corner code cannot join), the tilted bosses (1001, before the
blend rework too) and the Y junction (refused for room at its triple points).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Variable rounds: graded by the union of their balls (their envelope), not the balls' great circles

The smlib crate's laws and ladder 005, 006, 007 and 012 take the volumes the balls' envelope
removes; the law with a corner is its own test, listed as failing until the corner step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel tests: variable rounds graded by the union of their balls, the removed volume to 1e-4 of itself

removed_by_balls integrates, in each plane square to a right-angled edge, the corner the union
of the balls leaves (by rays from the edge, the least entry over the balls), cut to the body's
section. The law with a corner through a middle point is its own test, listed as failing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel tests: a spline radius whose balls fold over one another at its peak is refused

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: the variable round on its cone passes (the round is the balls' envelope)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: three rounds of different radii at a corner listed: the corner's transition kinks with the balls' touch circles

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Ladder: the variable rounds graded to 1e-6 by the union of their balls; 012 by its law going on past the edge

At the default 1e-3 the great circles' volumes (4e-6 off) passed too. SMLib builds each within
1.6e-7. The golden takes the new volumes and areas; counts unchanged. The G2 corner test listed
as failing passes on SMLib's step 3 and leaves the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Reference tests: the variable rounds 77, 78 and 81 pass on SMLib d01d7b0; their known-failure marks come off

The new section builds their edges on the surfaces, so STEP export no longer finds them 4.6e-5
to 6.1e-5 off. develop's Reference tests (60393a718) report all three as passing while marked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STEP import: a ball's halves whose seams are off each other's quarter lines each form within one turn

A sphere split into two halves along a circle about its axis, each half covering a pole with no
seam, gets a seam per half from the first vertex of its loop to the pole. The circles between the
halves group their frames so they turn together, and when the two seams are not a whole number of
quarters apart no one turn fits both: the group kept its frames, a half's form ran past one turn,
SMLib's trim (SMLib and solidcore alike) across the form's end crossed the face, and the mesh
folded over the ball (a rotor's ball showed torn; its half had 196 times its area in triangles).

When no one turn fits the group, each spilling face is now turned on its own to start on a quarter
line. On the rotor file this also clears three other faces that were filled leniently and a
0.076 mm edge gap; regression test in step_in/tests.rs with the area and volume of each half.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz
(cherry picked from commit b3188e005d427043b918267449c2336a1777e54f)

* SMLib: pin 5e8c9c1 (the new blend's corners: Ball and End/Join; exact fold and room checks with fit sizes; overflow in place; the round as its definition)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: a law's dip shows its corner ball's sphere, a peak's two rounds cross (the reasons had them swapped)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Reference tests: the variable rounds 77, 78, 80 and 81 expect the union of their balls

A variable round is the envelope of the balls rolled along the edge, which takes less than a
quarter round in each section. The expectations are now that union, the law continued past the
edge's ends along its end slopes, integrated by Gauss-Legendre panels in x and t; 2, 4 and 8
panels agree to 1e-9 of the body's values, and 77's removed volume matches a brute-force union of
balls to 2.5e-10. The nearest-ball search now scans the balls the ray meets around ball x
(|x - s| < r(s) sqrt(sin 2t)) on their own, which near the faces and where 78's radius closes to 0
are narrower than the global scan's step. Regenerating keeps each case's known_failure. 79, a
constant radius, is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Known failing: the law corners' kernel and crate tests and rig 1207 pass on SMLib 48ea616

SMLib builds a variable round's law corners as its balls' union (the corner
ball's zone at a dip, the sides' crossing at a peak): the kernel's corner
through a middle point (39.5410) and the crate's 4 -> 2 -> 4 law (39.5421) pass.
Rig 1207 (the bar's top edge rounded after the boss's arc, r0.5) builds and
grades on the same SMLib; it failed on c820346.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Kernel rig: every fillet and chamfer case rounds its tangent chain

The owner's ruling of 2026-11-01: the rig and the ladder round with tangent_chain true, how a
user's default pick behaves. The 38 fillets-area recipes and the ladder's 07-fillets/016 and 018
that passed false now pass true. The shell recipes keep theirs: a shell's tangent_chain is its
open-face chain, a different feature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the partial-selection cases kept as -partial-chain copies, tangent chain off

Where a case's point is one edge of a tangent chain rounded alone, a copy keeps tangent_chain
false as its own case (SMLib rounds exactly the picked edges, ending at the smooth vertex); their
expectations stay as they were, to be re-derived:
- fillets/1207-fillet-box-end-edge-into-unblended-round-partial-chain;
- fillets/every-fillet-after-fillet-curvature-front-then-side-r3-partial-chain;
- fillets/1207-fillet-bar-top-edge-after-boss-arc-round-partial-chain, renamed from
  ...-no-tangent-chain: with the chain on it is exactly 1207-fillet-bar-top-edge-after-boss-arc-round,
  which the rig already has;
- ladder/07-fillets/020 and 021, the r5/r3/r7 and r5/r3/r2 corners (016 and 018) with the r3 on
  its edge alone: with the chain on, the r3 runs on along the r5 round's end arc and down the
  vertical edge the third round was to take.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the concave arc between the block's tangent sides kept with tangent chain off

fillets/every-block-cylinder-tangent-concave-arc-r2-partial-chain: the pick takes one piece of the
concave half circle, which SMLib splits; with the chain off its other pieces are left out, and the
blend is refused at the piece's end (the base gate's outcome). With the chain on the case rounds
the whole half circle. The copy keeps its expectation, to be re-derived.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: two chains that now build graded by their exact volumes

With the tangent chain on, two cases round more than the edge they pick, and their old
expectations were the single edge's:
- 1207-fillet-box-end-edge-into-unblended-round: the r1 chain is the end face's top edge, the r3
  round's end arc and the back upright; 34 A + (pi/2) A (3 - c) by Pappus on the arc:
  V = 7953.139216 (it built 7953.139216, the old 7957.505 passed only inside 1e-3), 10 faces.
- 851-fillet-top-front-then-front-left-upright: the upright's chain runs up the first round's
  end arc on x = 0 and along the left top edge, so the corner becomes the R2 ball's eighth:
  V0 less the first round's spandrel to the wall (35.344727) less 27 (4 - pi) + 2 pi/3:
  V = 9530.777979 (built 9530.777987), 10 faces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: a curvature chain round a round's end refused for its size; the concave half circle builds

- every-fillet-after-fillet-curvature-front-then-side-r3: the side edge's chain runs round the
  first curvature round's end curve, whose radius of curvature has a weighted mean of 3 (its
  setback) and is unbounded at the ends, so somewhere below 3: the size-3 blend's contact line
  folds back on itself. Refused, "larger than the faces beside its edges allow", as ladder
  07-fillets/016's r7 on the r5 arc. (It was solid or refused for running on tangentially.)
- every-block-cylinder-tangent-concave-arc-r2-no-tangent-chain: the chain takes every piece of
  the half circle and ends at the convex edges it runs on into; it builds the analytic 19091.9620,
  so the outcome is solid (the refusal alternative was the chain-off one's).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known failing: two 851 chains whose corner piece is a ball of tube-centre radius 0

851-fillet-arc-then-top-front and 851-fillet-top-front-then-upright: with the tangent chain on,
each R2 chain runs along the end curve of an R2 round on a curved face (the arc round's end on the
front face; the first round's end on the wall), where the rolling ball sits on that round's own
centre line, so the piece is the ball about (39.2538, -19, 8): the three-edge rolling-ball corner.
SMLib fails with status 1001; the same piece on a plane end arc builds (front-left upright).
Expectations unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Ladder: 016 and 018 refused, their r3 chain takes the vertical edge; 020 and 021 recorded

With the tangent chain on, 016's and 018's r3 runs on along the r5 round's end arc and down the
vertical edge, so the third pick (60, 40, 8) is 3 from both of that round's contact lines and
names no edge: refused, asking for a point along one edge. The corners they were made for are
020 and 021 (the r3 alone), whose golden entries are 016's and 018's (021 measured on f12a101).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: three rounds at a box corner end on one rational patch on the ball's sphere, not an analytic sphere

SMLib's Ball corner is always the rational patch exactly on the sphere (owner ruling, blend
design §23), so the corner counts as an 'other' face beside the three cylinders and six planes.
The removed volume still checks the corner against r³ − πr³/6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the curvature round on a pipe on a plate is listed: a seam grades G3 where exactly G2 is wanted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: the box-and-fillet wire fixture records the round's cylinder frame as SMLib now keeps it

The round's cylinder keeps the frame it was made on when it is turned (SMLib's SwapUV no longer
re-derives it): its origin sits at x = −20 on the same axis line, (x, 2, 8) along x, radius 2.
Same cylinder; one number in the record moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known failing: two kernel tests' reasons as they fail on SMLib 5e8c9c1 (a partial selection running into an unblended tangent edge)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: two curvature rounds get 600 s, past the 180 s default, while G2 certification is slow (tangency-labs/smlib#96)

On the CI runners the boss root and the hole rim, both size-2/size-1 curvature rounds, build
correctly but take more than 180 s: the order-2 section's span certificate and the round's
definition are evaluated station by station. The per-case limit is the one the thread cases use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Lid ring sketch test: find the ring under the pick, not by main's kernel's name

On SMLib the lip join's exact history names the lid underside's ring a piece
of the lid's own start (F14:start#[...]), as the naming rule says for a face
that came from the feature's input; main's kernel named it after the case's
top it rests on (F2:top). The test looked the ring up by that name and so
stopped before the attachment it guards. It now takes the underside piece
under the pick point, which the cap certificate attaches on either kernel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Viewport culling test: each box's triangles from its mesh, not 12

SMLib meshes a 10 mm box in 108 triangles, so the hard-coded 12 a box stopped
the test before it reached the culling. The expected counts are now each
body's span in the scene.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Timeline chip test: a fillet that really reduces

The R20 fillet with fit reduce on one top edge of a 10 mm box builds on SMLib
without a reduced-radius warning, so the fixture had no warned feature. It
now rounds the four vertical edges at R6, reduced to the full round (5), as
the copy-warning test beside it does, and checks the warning says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Oracle: 34-chamfer-then-fillet and 35-fillet-curved-curved pass on SMLib 5e8c9c1 (their STEP edges are on their surfaces)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known-failing: the shell of a fully rounded box opened at one face fails on SMLib 5e8c9c1 (tangency-labs/smlib#102)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known-failing: the action matrix's oblique cylinder cut fillet passes on SMLib 5e8c9c1; two shells still fail

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the boss root's curvature round gets the rig's 1800 s cap: on the CI runners, 8 cases at a time, its G2 certification passed 600 s (tangency-labs/smlib#96)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: a case's continuity can ask for an order per seam (seams: [{order, edges, exact}])

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the pipe on a plate's curvature round meets the plate G2 and the pipe G3, 40307.8856312 (option B's order-2 jets, tangency-labs/solidcraft#10845)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Edge names: a seam names its one face once; the curve-id test reads every edge kernel-neutrally

A seam's two sides are the same face, and edge names list each face an edge
bounds once, so SMLib's extruded circle names its side's seam F2:side:c1, with
no separator. The name grammar now says one face also means a seam. The #5858
test no longer counts one '|' an edge: every part of every edge name is a
whole face name of the edge, one per face it bounds, two for the rims and one
only for the side's seam (checked to run bottom to top on the circle).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* rustfmt on the merged tree

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Known failing on SMLib: two of main's new tests assume truck's box mesh and fillet torus

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* SMLib: pin f916a8d (a round on a definition face is its definition; the G1 setback fill certified convex, setbacks too short refused naming the least; the G2 certificate halves a span no level can certify at once)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Fillet: a setback too short for its corner is refused naming the least that builds (smlib_blend_fit_size)

SMLib's setback corner takes a G1 fill only once certified convex, and refuses a setback too
short for that as SMLIB_ERR_NO_ROOM with SMLIB_FIT_SETBACK_AT_LEAST, the smallest setback that
builds. The kernel reads it (solidcraft-smlib binds smlib_blend_fit_size) and names it; the
Fillet dialog says it in plain words. Other room refusals keep their words. The r5 box corner
set back 5.5 is refused naming 5.962, which builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: three rounds of different radii at a corner meet in SMLib's setback corner

Each round runs whole to its section square to its edge at its setback (the owner's rule, at
least 1.5 r, scaled to the least at which the G1 fill is certified convex), and the hole is the
setback split: one patch per round and the triangle in three quadrilaterals, 15 faces, G1.
Outside the box the sections span the body is the three strips', so its volume is theirs within
that box's. A later r3 round at the mitred corner makes the body all three at once make
(7928.142563938, 15 faces), as the engine and the model-cache tests have it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel tests: SMLib's own corner between curvature rounds is curvature continuous, as the G2 patch is

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the boss root's and the hole rim's curvature rounds take the default timeout again (37 s and 34 s on the box under the rig's parallel load, tangency-labs/smlib#96)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Agents: model decisions use exact geometry; a mesh is for display, export, previews and mesh bodies

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* xtask: mesh-decisions, model decisions use exact geometry; today's 176 mesh decision sites are listed and the list only shrinks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Sheet metal: cuts and holes pass over sheets and bends by their exact boxes, never a mesh's

A primitive cut skips the sheets kernel::apart (exact bounds grown by the record tolerance)
finds clear of its tool; the bend check leaves the clear case to kernel::boolean, which answers
it from the same exact boxes with no intersection work. The mesh-box helpers are gone, and their
four lines leave xtask/mesh-decisions.txt (172 sites left).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Agents: AGENTS.md loses a stray merge-conflict marker line at its end

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Locales: Vietnamese for the setback-too-short refusal, now that vi is a complete catalog

Main made vi a complete catalog; develop's new message (ui.fillet_error_setback_short) had no vi
entry, so every_complete_catalog_carries_every_english_message failed on the merged tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: exact volumes for 1213's bent-tube round and 4782's bar round, rel 1e-6

1213: the loft is a cubic skin through the five sections (ellipses between
them), not a torus; its volume 131601.597487935 by quadrature less the exact
rolling-ball removal 233.662461919 gives 131367.935026 (was a Pappus estimate
on a torus, 131360.148, at rel 5e-4).

4782: the section's area in closed form, 25 pi/3 - 5 sqrt(75) + 25, so
V = 630.2934873 (was a grid estimate, 630.293125).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Kernel rig: the boss root's and the hole rim's curvature rounds take 600 s again: under CI's parallel load they pass the 180 s default (develop 820b7b6)

They take 37 s and 34 s alone on the box, but CI runs 8 cases at once on slower runners. Their
G2 certificate cost is the open item (tangency-labs/smlib#106, moved to solidcore#2344).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* After the merge: clippy's auto-deref, and the mesh-decisions list for the merged tree

Develop's list was taken on develop alone. Main's code (tap-marking reach, cut and hole box
checks, join pieces, print faces, placed measuring, selection items, imported mesh payloads) and
the branch's own exact_edges and named_vertex use meshes too; three listed functions were renamed
by main (face_outline and plate_recesses into FaceSlice, paste into build).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* After the merge: main's new tests on the SMLib kernel

- Cut To the far side of a curved wall (#8634): the tool stops past the first crossing of the
  face ahead of the profile; SMLib's whole bore is one face that a line crosses twice, so the
  single-crossing rule found none and the cut took nothing.
- Clearing view analyses goes through refresh_display, as main's #10687 made the others, so an
  open feature editor keeps OK and Cancel after Zebra.
- vi, a complete catalog on main, gets the setback-too-short message.
- fillets/KNOWN_FAILING: 4782's cause is now its continuity check (SMLib f916a8d builds the
  expected volume).
- Known failing, as main's tests assume truck: the spline wall's spans as one mesh patch, a
  hole touching an edge at a point leaving one body, and a copy of a copy's triangles matching
  a fresh mesh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz

* Twisted sweep: circles about a straight path are exact cylinders (solidcore#2184)

A twist about a straight path maps a profile circle centred on the path's
line onto itself, so its swept wall is exactly the cylinder. The skin
through the stations stayed within 3.9e-9 of it (6.6e-9 on the outer wall),
and a boolean with another body on that cylinder failed with status 1001
(solidcore#2184; the kernel's handling of a B-spline face lying on a
cylinder stays open there).

sweep_controlled now builds those walls exactly when the path is lines
along the profile's normal and there is no end scale or rails: a profile
whose every loop is such a circle is swept untwisted, and such holes in
another outer loop are cut as exact cylinders from the skinned sweep of
the rest. Other loops, and an axis-centred arc inside a loop of other
curves, are skinned as before; a failed cut falls back to skinning all.

Regression test in smlib_sweeps_tests.rs: #2184's tubes joined at 10, 16,
18, 20 and 30 degrees give one closed body of 11.5625 pi with cylinder
walls; a twisted hexagon with the bore keeps a cylinder bore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEtwSrdwZxqTQp5MfnU

* After the merge: a hole that misses is found by exact boxes; a face is a one-face patch; main's mesh-box helpers gone

- `hole_misses` (main's #10701, through brett's branch) decided from the targets' mesh boxes. It now uses their exact boxes (`Body::exact_bounds`). An unknown box still leaves the hole not known to miss.
- With #10303's two shortcuts and `hole_misses` off the mesh, `body_box`, `mesh_box` and `padded_box` have no caller left, and are deleted.
- `project`'s intersection link passes its one face to `meeting_edges` as a one-element patch. This branch picks one face, not #9009's mesh patch.
- xtask/mesh-decisions.txt drops the six sites that no longer use a mesh here: `apply_traced_with`, `cut_end_past_face`, `beyond_cylinder_reach`, `hole_misses`, `body_box`/`mesh_box`/`padded_box`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* After the merge: split_move's Result reaches its callers; to_local's duplicated move check goes

`frames::split_move` returns a Result on this branch: an unplaceable model is an error, not a silent no-split.
- Move/Copy of a component (main's #9914) propagates it, as its other calls do.
- `to_local` had the solid.move check twice after the merge (brett's Option one and ours). Ours stays, after the no-picks/not-placed return.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* After the merge: main's two new tests take world_state's Result, as the rest of their files do

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Native B-rep: a ball patch is its own surface kind, read from and written to SMLib's flat kind 6

SMLib's flat arrays now carry the corner of three equal rounds as `SURFACE_BALL_PATCH` (kind 6): its net as a NURBS face's block, with its sphere's centre and radius as its definition (ids 36 and 166). The record reads it as `ball_patch {center, radius}`, a label like the analytic kinds, with the net as its `nurbs`. A plain sphere with a form won't do: the net is not a piece of SMLib's sphere NURBS, so SMLib's `IsNurbSurfaceSphere` would refuse it.

Written back, a ball patch is kind 6 with the same definition, which SMLib takes once its net is certified on that sphere. Elsewhere:
- Offsets classify it as its sphere, so its offsets stay exact and collapse at the centre.
- Face kinds count it as a sphere: fillet_three_edges_at_a_corner's corner is now `sphere`, no longer `other`.
- STEP, which has no ball-patch entity, gets the net as the face's B-spline surface, pcurves included.
- Iso curves and SSI of the label are refused; the face's form is what evaluates.

Test: a_rounded_cubes_ball_patches_go_round_with_their_spheres. The cube's eight corners are ball patches about the corners pulled in by r. Points of each patch lie on its sphere to 1e-12. The patches are kind 6 again after import, with the same definitions bit for bit, and the closed-form volume holds.

Format: pending/ball-patch-faces.rs. Docs: docs/native-brep.md and the rig README's `surface_types` (`ball_patch`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* SMLib: pin v1.1.0-alpha (a18bbe5): the generic blend's step-4 corners, the Ball's sphere patch through the flat arrays, all-target CI

Since f916a8d:
- #120: every target again, plus the warnings fix;
- #121: the Ball's patch as flat kind 6 with its sphere, read by the previous commit;
- #122: tests gated on counts;
- #123: the Mixed corner;
- #124: the End at a smooth vertex;
- #125: four or more rounds, and open setbacks;
- #126: the equal-area thumbweight guard;
- #127: the trunk merge.

The SMLIB_PREBUILT checksums are from the release prebuilt-a18bbe5…, written by `scripts/fetch-smlib.sh --pin`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* smlib export tests: rustfmt's line for the rounded cube's edge midpoints

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: the fillet and ladder results on SMLib v1.1.0-alpha, the new failures recorded with their reasons

Fixed (off the known-failing list): the Mixed corner's peg cases and the concave arc with the front top edge (smlib #123), and the 40° boss junction (smlib #124). Eight cases in all.

New failures, recorded as they are, each with its reason. They passed on f916a8d.
- **Six cases grade a blend seam G0 where G1 (or G2) is wanted,** at the end of the round's contact seam, after smlib #124's End at a smooth vertex. Two of them also shift in volume.
- **Four cases come back unsupported** after smlib #125, which leaves setbacks to the Setback's corners only.
- **Ladder 07/012** makes 9 faces, 20 edges and 13 vertices, where its golden had 8, 18 and 12. Its golden entry is the new result, with the reason added.

Whether each change is by design or a defect is being established. A defect is fixed in solidcore, where the End and the Setback are being brought over (#2364, #2365), not in the frozen SMLib.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel ladder: 07/021 and 06/018 recorded as they are on SMLib v1.1.0-alpha, each with its reason

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel ladder: a golden case marked unstable is gated on its status, and 06/018 is marked

On SMLib v1.1.0-alpha, 06/018 makes 597 or 594 edges from the same input:
the union's post-process keeps pointers to edges it has deleted. A golden
entry's `unstable` reason makes the gate compare that case's status only
and name it in its output; recording keeps the reason, and only an edit of
the golden removes it. v1.1.0-alpha.1 fixes the cause and removes the mark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* After the merge with main: its new code on develop's exact bounds, types and thread fields

- The sheet cut's cull (#10301) and the tapped wall's (#10227) use each
  body's exact box (`exact_box`), not its display mesh.
- model.threads replies with develop's thread fields: form, hand (right,
  left or both) and starts.
- surface.boundary's schema checks a network curve's continuity as the
  handler does, and words a list entry's error as it does.
- Main's new tests take develop's Hole fields and world_state's Result.
- mesh-decisions: contact_sweep's triangle check is now `depth` (main
  split `hits`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Known failing: the 14 cargo tests SMLib v1.1.0-alpha fails, with what each sees; two cases that pass now

Develop's CI after the a18bbe5 pin (run 41522001173) fails 14 tests that
passed on f916a8d, and passes two listed ones. Each new line says what the
test sees on v1.1.0-alpha; v1.1.0-alpha.1 fixes the setback hole's cause.
shell_tangent_chain_that_opens_every_face_explains_how_to_keep_walls and
oracle 37-pyramid-apex-blend pass and leave their lists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Cargo.lock: develop's profile, smlib and step crates at main's 0.30.1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: main's six new sketch-only commands are exempt from a kernel case

sketch.construction_line (and its horizontal and vertical forms) and
sketch.spline.insert_point, remove_point and reverse change only the 2D
sketch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Cuts leave the bodies their tools can't reach, by exact boxes (#10225 on exact geometry)

- The per-target cut loop skips a body whose exact box lies clear of
  every tool's, as main's version did with mesh boxes. The sheet culls
  (#10226, #10301) and this one now leave the far sheets and bodies alone:
  a_cut_leaves_bodies_it_cannot_reach_as_they_were passes and leaves the
  known-failing list.
- a_cut_still_runs_where_its_tool_touches_grazes_or_meets_a_curved_face:
  a tool 0.5 µm clear of the block is now left out (exact boxes; 0.5 µm is
  far past the bodies' tolerances); touching and 0.1 mm in still cut.
- Known failing, with reasons: main's edge lookup by a stored point
  (#11286, on the display mesh) is not taken; SMLib refuses the
  wrong-way chamfer for its tangent chain first.
- EXEMPT: main's eight new sketch-only commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: main's new view, rendering, appearance and settings commands are exempt from a case

62 of the commands main added change no geometry: the view and render
panes, rendering lights and results, appearance tools, settings profiles,
point clouds (drawn as points, never a body), the selection, two sketch
edits, component links and History bar visibility, edit.repeat,
timeline.play, inspect.compare_picture (a picture against the outline),
and component.paste_from_design, which pastes the app's cross-window
clipboard that no command fills. Each joins EXEMPT's first section under
its family's reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: construct.plane.axis_point gets construction cases

The plane through a box edge and its far corner, graded against its
closed-form normal (0,-2,3)/sqrt(13) through the origin, and the refusal
of a point on the axis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: assembly cases for mass properties, align, find limits and moving items between parts

- assembly.mass_properties: two boxes (2 g/cm3) in a rigid group: mass
  0.006 kg, centre (18.333,5,5), inertia diag(0.1, 1.0333, 1.0333) kg mm2
  by the parallel-axis theorem.
- occurrence.align: a block's end face onto a base's top face: a quarter
  turn about y, centre (70,20,20), box (65,15,10)-(75,25,30).
- joint.find_limits: a slider between two stops: min -20, max 10 mm.
- component.move_features, browser.reparent and
  component.move_sketches.to_parts: items moved into a turned and moved
  part keep their world place (volumes, centres and boxes by hand).

The mass case assigns a material it creates, so material.create and
material.assign leave EXEMPT. PATHS names the new command modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

* Kernel rig: export and print face cases in the import area

- file.export_step, export_stl, export_3mf, export_obj: a 30x20x10 box
  written and read back (the meshes converted to a solid): V 6000,
  A 2200, 6 faces, box (5,-10,0)-(35,10,10).
- file.export_urdf: a hinged arm on a grounded base: 3 links, 2 joints,
  and the base's mesh, written in metres, reads back as the
  1 x 0.5 x 0.2 box (V 0.1, A 1.6).
- body.print_face: a cylinder's flat end is accepted, its side refused.

PATHS adds the URDF writer and the print face modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ

---------

Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: brett19 <brett19@gmail.com>
2026-11-02 22:53:32 +00:00

1607 lines
84 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Fairing the control points of a B-spline curve or surface: moving the interior control
//! vertices to the least-bending shape while the ends, or the boundary rows, stay exactly where
//! the design put them.
//!
//! The fairness energy is the thin-plate (curvature-variation) energy of the *geometry* the
//! control net describes, in the net's own parameter directions:
//!
//! - a curve: `E = ∫‖C″(t)‖² dt`,
//! - a surface: `E = ∫∫ ‖S_uu‖² + 2‖S_uv‖² + ‖S_vv‖² du dv`.
//!
//! A plane has energy zero and anything else pays for how much it bends, which is what a
//! designer means by "fair". Both energies are quadratic in the control points, `E(P) = Pᵀ·G·P`,
//! with `G` the Gram matrix of the basis functions' derivatives (`Gᵢⱼ = ∫Nᵢ″Nⱼ″ dt`, and the
//! tensor products of the one-direction Gram matrices for a surface). Each one-direction Gram is
//! integrated span by span with four-point Gauss–Legendre, exact to degree 7 — a cubic's second
//! derivative products are quadratic, so the cubic curves and bicubic faces fairing meets in
//! practice are integrated exactly.
//!
//! One fairing step is then a constrained least-squares solve: hold the boundary control points,
//! take the exact minimiser of `E` over the interior (for a quadratic that is one Newton step,
//! `G_ff·d = −(G·P)_f`), and apply a fraction `strength` of it, so `strength = 1` is the full
//! solution and a smaller value walks towards it. With the exact step the energy falls by
//! `q·s·(1 − s)` for `q ≥ 0`, so a run at any strength decreases it strictly until it converges.
//! `G_ff` does not change as the control points move, so it is factorised once, by banded
//! Cholesky, and every further step is a matrix–vector product and a triangular solve.
//!
//! Two guarantees are built in rather than checked afterwards:
//!
//! - **The boundary never moves.** The result starts as a copy of the input and only interior
//! entries are written, so a held control point is bit-identical to the one the design gave.
//! - **The geometry cannot jump.** A B-spline lies in the convex hull of its control points
//! (NURBS Book §3.1; with the weights unchanged the rational basis functions are still
//! non-negative and sum to one), so the geometry moves at most as far as the farthest control
//! point. Every step is clamped so that no control point leaves the ball of radius
//! `tolerance` about where it started: the faired curve or surface is then within `tolerance`
//! of the input at the same parameters, by a bound rather than by measurement. A step that
//! would not lower the energy is halved and, if it still would not, the run stops — it never
//! loops for ever and never moves the design further than the caller allowed.
//!
//! Everything is checked before it is used: degrees, knot vectors and counts must be consistent,
//! the control points finite, `strength ∈ (0, 1]`, `iterations` in `1…`[`MAX_FAIR_ITERATIONS`] and
//! `tolerance > 0`. A singular system — fewer than two interior control points, or an interior
//! control point that does not change the geometry at all — is reported as an error and the
//! geometry is left alone.
use solidcraft_geom::brep as b;
use solidcraft_geom::bspline::{HPoint, MAX_SPLINE_DEGREE, NurbsSurface, Side, SplineError, check_knots, local_basis};
use solidcraft_geom::{Grid, Vec3};
use crate::body::Body;
use crate::history::Change;
use crate::{KernelError, Result};
/// Most steps one fairing run takes (see [`FairOptions::iterations`]).
pub const MAX_FAIR_ITERATIONS: usize = 1000;
/// Most control points one fairing run accepts (a 128 × 128 net). `MAX_FAIR_BAND` is what
/// bounds the solver's memory and its factorisation; this bounds the rest of a step, the energy
/// sweep over every control point (`(2p_u + 1)(2p_v + 1)` neighbours each, three terms) and the
/// copies of the net: for a bicubic net a few million multiply-adds and under a megabyte. It is
/// set above the band's own limit for square bicubic nets (about 90 × 90), so a face's net is
/// refused for the system it needs rather than for its size: SMLib's thickenings make faces of
/// 72 × 78 control points, which the band takes at about 1.1 M entries.
pub const MAX_FAIR_POINTS: usize = 1 << 14;
/// Most entries of the banded system (2²¹ doubles, 16 MB). The factorisation's work is at most
/// `n · min(n, bw)²` for `n` unknowns `bw` apart with `n · (bw + 1)` within this, a few 10⁹
/// multiply-adds at the very worst (`n ≈ bw ≈ 1450`), and each solve's at most twice the band.
const MAX_FAIR_BAND: usize = 1 << 21;
/// The fairness energy of a curve, as a one-direction net: the `(order in u, order in v, weight)`
/// term list of `∫∫ (∂S)²`.
const CURVE_ENERGY: [(usize, usize, f64); 1] = [(2, 0, 1.0)];
/// The thin-plate energy of a surface: `‖S_uu‖² + 2‖S_uv‖² + ‖S_vv‖²` — the classic
/// curvature-variation energy, zero on a plane and the same if u and v are swapped.
const SURFACE_ENERGY: [(usize, usize, f64); 3] = [(2, 0, 1.0), (1, 1, 2.0), (0, 2, 1.0)];
/// Four-point Gauss–Legendre nodes and weights on `[−1, 1]` (exact to degree 7).
const GAUSS4: [(f64, f64); 4] = [
(-0.861_136_311_594_052_6, 0.347_854_845_137_453_8),
(-0.339_981_043_584_856_3, 0.652_145_154_862_546_2),
(0.339_981_043_584_856_3, 0.652_145_154_862_546_2),
(0.861_136_311_594_052_6, 0.347_854_845_137_453_8),
];
/// The second direction of a curve seen as a control net: one basis function of degree 0 over
/// `[0, 1]`, whose Gram entry is exactly `∫1 dt = 1`, so the net's energy is the curve's own
/// energy unchanged.
const TRIVIAL_KNOTS: [f64; 2] = [0.0, 1.0];
/// How often a step is halved before the run calls the point converged.
const MAX_HALVINGS: u32 = 40;
/// A step smaller than this fraction of the full Newton step is not worth taking.
const MIN_STEP: f64 = 1e-12;
/// Steps are clamped this far inside the tolerance, so rounding cannot push a control point
/// past it.
const TOLERANCE_SLACK: f64 = 1.0 - 1e-12;
/// How a fairing run is asked to behave.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FairOptions {
/// The fraction of each energy step to apply, `0 < strength ≤ 1`: `1` is the full least
/// squares solution (the exact minimiser of the energy at the held boundary), a smaller
/// value takes that fraction of the way there. The energy falls at every step either way.
pub strength: f64,
/// How many steps at most, one to [`MAX_FAIR_ITERATIONS`].
pub iterations: usize,
/// Hold the layer of control points next to the boundary as well as the boundary itself (two
/// layers held at each end). For a clamped knot vector the boundary row fixes the position
/// along the edge and the row next to it fixes the derivative across the edge, so with this
/// set the boundary keeps the position and the tangent the design gave it.
pub keep_edges: bool,
/// The farthest a control point may move from where the design put it, in mm. The geometry
/// then stays within this distance of the input at the same parameters (see the module
/// docs), so a fairing run can never make a design jump.
pub tolerance: f64,
}
impl FairOptions {
/// Checked options for one fairing run: an error, never a panic, for a strength outside
/// `(0, 1]`, zero iterations, more than [`MAX_FAIR_ITERATIONS`] of them, or a tolerance that
/// is not a positive finite number.
pub fn new(strength: f64, iterations: usize, keep_edges: bool, tolerance: f64) -> Result<FairOptions> {
FairOptions { strength, iterations, keep_edges, tolerance }.checked()
}
/// The same checks as [`FairOptions::new`], for options built field by field.
pub fn checked(self) -> Result<FairOptions> {
if !(self.strength.is_finite() && self.strength > 0.0 && self.strength <= 1.0) {
return Err(KernelError::Invalid(format!("the fairing strength {} must be greater than 0 and at most 1", self.strength)));
}
if self.iterations == 0 || self.iterations > MAX_FAIR_ITERATIONS {
return Err(KernelError::Invalid(format!("{} fairing iterations (1 to {MAX_FAIR_ITERATIONS})", self.iterations)));
}
if !(self.tolerance.is_finite() && self.tolerance > 0.0) {
return Err(KernelError::Invalid(format!("the fairing tolerance {} must be a positive number of mm", self.tolerance)));
}
Ok(self)
}
}
impl Default for FairOptions {
/// One full step with the boundary held, at most 1 mm of movement: the defaults a command can
/// start from before a user picks their own.
fn default() -> Self {
FairOptions { strength: 1.0, iterations: 1, keep_edges: false, tolerance: 1.0 }
}
}
/// What a fairing run did: the energy before and after, how many steps were applied, how far the
/// control points moved and the energy after every applied step. The energy is a sum of squares,
/// so where rounding leaves it a hair below zero the true value is zero: it is reported as zero.
#[derive(Clone, Debug, PartialEq)]
pub struct FairReport {
/// The fairness energy of the input, in the parameter units of the net's own knots.
pub energy_before: f64,
/// The fairness energy of the result: never more than `energy_before`, and equal to it only
/// when no step could lower it.
pub energy_after: f64,
/// How many steps were applied (at most the requested `iterations`).
pub steps: usize,
/// The farthest any control point moved from where the design put it, in mm. It bounds how
/// far the geometry moved from the input (see the module docs) and never exceeds the
/// requested tolerance.
pub movement: f64,
/// The energy after each applied step, the last equal to `energy_after`: it never rises, and
/// falls strictly at every step until the run reaches the rounding of its own arithmetic.
pub energy_trace: Vec<f64>,
}
/// A faired B-spline curve: the input's degree and knots, the moved control points and the run's
/// report.
#[derive(Clone, Debug, PartialEq)]
pub struct FairCurve<const N: usize> {
pub degree: usize,
pub knots: Vec<f64>,
/// The faired control points; the ends (and, with `keep_edges`, the points next to them) are
/// bit-identical to the input.
pub ctrl: Vec<[f64; N]>,
pub report: FairReport,
}
/// A faired B-spline control net: the input's degrees and knots, the moved control points and the
/// run's report.
#[derive(Clone, Debug, PartialEq)]
pub struct FairNet<const N: usize> {
pub degree: [usize; 2],
pub knots: [Vec<f64>; 2],
/// The faired control points, as many as the input's; the held boundary layers are
/// bit-identical to the input.
pub ctrl: Grid<[f64; N]>,
pub report: FairReport,
}
/// A geom spline error as the kernel's.
fn spline_error(what: &str, e: SplineError) -> KernelError {
match e {
SplineError::TooLarge(m) => KernelError::TooLarge(format!("{what}: {m}")),
other => KernelError::Invalid(format!("{what}: {other}")),
}
}
/// The dot product of two control points' coordinate vectors.
fn dot<const N: usize>(a: &[f64; N], b: &[f64; N]) -> f64 {
a.iter().zip(b).map(|(x, y)| x * y).sum()
}
/// The distance between two control points.
fn dist<const N: usize>(a: &[f64; N], b: &[f64; N]) -> f64 {
let d: [f64; N] = std::array::from_fn(|c| a[c] - b[c]);
dot(&d, &d).sqrt()
}
/// The Gram matrices of one parameter direction, stored banded: entry `r` is
/// `∫ Nᵢ^{(r)}(t)·Nₖ^{(r)}(t) dt` over the direction's domain, and since a basis function
/// overlaps only its `degree` neighbours an entry is non-zero only for `|i − k| ≤ degree`, so
/// the whole thing is `count·(degree + 1)` numbers per order.
struct Gram {
count: usize,
bw: usize,
g: [Vec<f64>; 3],
}
impl Gram {
/// The Gram matrices of `count` basis functions of `degree` over `knots`, for orders 0, 1 and
/// 2 — the derivatives a thin-plate energy is built from.
fn new(degree: usize, knots: &[f64], count: usize) -> Result<Gram> {
let bw = degree;
let mut g: [Vec<f64>; 3] = std::array::from_fn(|_| vec![0.0; count * (bw + 1)]);
// On the span `[knots[s], knots[s + 1])` only the basis functions `i ∈ [s − degree, s]`
// are non-zero. The quadrature nodes lie strictly inside the span, so either one-sided
// limit gives the same value there.
let mut ders = [[0.0f64; 3]; MAX_SPLINE_DEGREE + 1];
for s in degree..count {
let (Some(&a), Some(&b)) = (knots.get(s), knots.get(s + 1)) else { continue };
if !(b > a) {
continue;
}
for &(x, w) in GAUSS4.iter() {
let t = 0.5 * (a + b) + 0.5 * (b - a) * x;
let first = s - degree;
let mut live = 0usize;
for i in first..=s {
let Some(local) = knots.get(i..=i + degree + 1) else { break };
let d = local_basis(local, t, Side::Right, 2);
if let Some(slot) = ders.get_mut(live) {
for (o, v) in slot.iter_mut().zip(d.iter()) {
*o = *v;
}
}
live += 1;
}
let weight = 0.5 * (b - a) * w;
let value = |rel: usize, r: usize| ders.get(rel).and_then(|d| d.get(r)).copied().unwrap_or(0.0);
// The upper triangle only — the band holds one copy of a symmetric entry — and at
// the basis functions' own indices, not their places in this span.
for i in 0..live {
for k in i..live {
let (row, off) = (first + i, k - i);
for (r, gg) in g.iter_mut().enumerate() {
if let Some(slot) = gg.get_mut(row * (bw + 1) + off) {
*slot += weight * value(i, r) * value(k, r);
}
}
}
}
}
}
if g.iter().flatten().any(|v| !v.is_finite()) {
return Err(KernelError::Invalid("the fairness energy of this net is not a finite number".into()));
}
Ok(Gram { count, bw, g })
}
/// `∫ Nᵢ^{(r)} Nₖ^{(r)} dt`, zero outside the band or off the end of the basis.
fn at(&self, r: usize, i: usize, k: usize) -> f64 {
let Some(m) = self.g.get(r) else { return 0.0 };
let (row, off) = if i <= k { (i, k - i) } else { (k, i - k) };
if off > self.bw || row >= self.count {
return 0.0;
}
m.get(row * (self.bw + 1) + off).copied().unwrap_or(0.0)
}
}
/// A control net to fair: a tensor-product B-spline with the terms of its fairness energy. A
/// direction of one control point (degree 0, knots `[0, 1]`) makes the net a curve, whose energy
/// is the one-direction [`CURVE_ENERGY`].
struct Net<'a, const N: usize> {
degree: [usize; 2],
/// The control points as the design has them; the run moves copies.
ctrl: &'a Grid<[f64; N]>,
gram: [Gram; 2],
/// The energy's terms that the net's degrees can carry (see [`Net::new`]).
terms: Vec<(usize, usize, f64)>,
}
impl<'a, const N: usize> Net<'a, N> {
/// Check the degrees, knots and counts and build the Gram matrices: an error, never a panic,
/// for a degree above [`MAX_SPLINE_DEGREE`], too few control points for the degree, a knot
/// vector of the wrong length, unusable knots or an empty parameter range.
///
/// A term that differentiates a direction more often than its degree is dropped: on every
/// span the basis functions are polynomials of that degree, so the derivative is zero and so
/// is the term, exactly. A face of degree 1 one way (an extruded curve) has no `S_vv` that
/// way: its energy is the bending along the curve and the twist, and the straight direction
/// pays nothing.
fn new(degree: [usize; 2], knots: [Vec<f64>; 2], ctrl: &'a Grid<[f64; N]>, terms: &'static [(usize, usize, f64)]) -> Result<Net<'a, N>> {
let count = ctrl.count();
if ctrl.cells().len() > MAX_FAIR_POINTS {
return Err(KernelError::TooLarge(format!("fairing {} × {} control points (at most {MAX_FAIR_POINTS} in all)", count[0], count[1])));
}
for d in 0..2 {
let (p, c, kn) = (degree[d], count[d], &knots[d]);
if p > MAX_SPLINE_DEGREE {
return Err(KernelError::TooLarge(format!("fairing a spline of degree {p} (at most {MAX_SPLINE_DEGREE})")));
}
if c <= p {
return Err(KernelError::Invalid(format!("{c} control points is too few across one direction of a spline of degree {p}")));
}
if kn.len() != c + p + 1 {
return Err(KernelError::Invalid(format!(
"{} knots across one direction, expected {} for {c} control points of degree {p}",
kn.len(),
c + p + 1
)));
}
check_knots(kn).map_err(|e| spline_error("fairing", e))?;
let (lo, hi) = (kn.get(p).copied().unwrap_or(f64::NAN), kn.get(c).copied().unwrap_or(f64::NAN));
if !(lo < hi) {
return Err(KernelError::Invalid("the fairing's parameter range is empty".into()));
}
}
if terms.iter().any(|&(_, _, w)| !(w.is_finite() && w >= 0.0)) {
return Err(KernelError::Invalid("a fairness term's weight is not a non-negative number".into()));
}
let terms: Vec<(usize, usize, f64)> = terms.iter().copied().filter(|&(ru, rv, _)| ru <= degree[0] && rv <= degree[1]).collect();
if terms.is_empty() {
return Err(KernelError::Invalid(format!("a net of degree {} × {} does not bend: there is nothing to fair", degree[0], degree[1])));
}
let gram = [Gram::new(degree[0], &knots[0], count[0])?, Gram::new(degree[1], &knots[1], count[1])?];
Ok(Net { degree, ctrl, gram, terms })
}
/// Control points along u and along v.
fn count(&self) -> [usize; 2] {
self.ctrl.count()
}
/// The number of control points, `count[0] · count[1]`.
fn total(&self) -> usize {
self.ctrl.cells().len()
}
/// The index of control point `(i, j)` in the flattened net (u fastest).
fn index(&self, i: usize, j: usize) -> usize {
j * self.count()[0] + i
}
/// The fairness energy `Pᵀ·G·P` of the net `ctrl` (u fastest) and, in `grad`, `G·P`. One
/// banded sweep gives both, since `E = Σ Pₚ·(G·P)ₚ`.
fn energy_gradient(&self, ctrl: &[[f64; N]], grad: &mut [[f64; N]]) -> f64 {
let [cu, cv] = self.count();
let (pu, pv) = (self.degree[0], self.degree[1]);
let mut energy = 0.0;
for j in 0..cv {
for i in 0..cu {
let mut acc = [0.0f64; N];
for &(ru, rv, w) in &self.terms {
for l in j.saturating_sub(pv)..=(j + pv).min(cv - 1) {
for k in i.saturating_sub(pu)..=(i + pu).min(cu - 1) {
let a = w * self.gram[0].at(ru, i, k) * self.gram[1].at(rv, j, l);
if a == 0.0 {
continue;
}
if let Some(p) = ctrl.get(self.index(k, l)) {
for (x, v) in acc.iter_mut().zip(p) {
*x += a * v;
}
}
}
}
}
let at = self.index(i, j);
if let Some(c) = ctrl.get(at) {
energy += dot(c, &acc);
}
if let Some(g) = grad.get_mut(at) {
*g = acc;
}
}
}
energy
}
/// The energy matrix `G` over the interior control points, banded and already factorised (the
/// matrix does not change as the control points move, so one factorisation serves every
/// step). In the u-fastest order two unknowns couple within `degree_u + degree_v · cols`:
/// `degree_u` along a row, `degree_v` rows apart.
fn system(&self, interior: &Interior) -> Result<Band> {
let [cu, cv] = self.count();
let (pu, pv) = (self.degree[0], self.degree[1]);
let rows = if cv > 1 { interior.rows.saturating_sub(1).min(pv) } else { 0 };
let mut band = Band::new(interior.points.len(), pu + rows * interior.cols)?;
for (r, &at) in interior.points.iter().enumerate() {
let (i, j) = (at % cu, at / cu);
for &(ru, rv, w) in &self.terms {
for l in j.saturating_sub(pv)..=(j + pv).min(cv - 1) {
for k in i.saturating_sub(pu)..=(i + pu).min(cu - 1) {
let Some(s) = interior.slot.get(self.index(k, l)).copied().flatten() else { continue };
band.add(r, s, w * self.gram[0].at(ru, i, k) * self.gram[1].at(rv, j, l));
}
}
}
}
band.factorised()
}
/// Whether holding `keep` layers at each end of each direction holds every control point: a
/// direction of more than one control point and no more than `2 · keep` of them.
fn all_held(&self, keep: usize) -> bool {
self.count().iter().any(|&c| c > 1 && c <= 2 * keep)
}
/// The report of a run that moved nothing: the net's energy before and after, no steps.
fn unmoved(&self) -> Result<FairReport> {
let mut grad = vec![[0.0; N]; self.total()];
let energy = self.energy_gradient(self.ctrl.cells(), &mut grad);
if !energy.is_finite() {
return Err(KernelError::Invalid("the fairness energy of this net is not a finite number".into()));
}
let energy = energy.max(0.0);
Ok(FairReport { energy_before: energy, energy_after: energy, steps: 0, movement: 0.0, energy_trace: Vec::new() })
}
/// Fair the net with checked `opts`: see the module docs. The result is the input with the
/// interior control points moved; the held ones are bit-identical.
fn fair(&self, opts: &FairOptions) -> Result<(Grid<[f64; N]>, FairReport)> {
let ctrl = self.ctrl.cells();
if ctrl.iter().flatten().any(|x| !x.is_finite()) {
return Err(KernelError::Invalid("a control point is not a finite number".into()));
}
let interior = Interior::new(self, if opts.keep_edges { 2 } else { 1 })?;
let system = self.system(&interior)?;
let mut current = self.ctrl.clone();
let mut grad = vec![[0.0; N]; self.total()];
let energy_before = self.energy_gradient(ctrl, &mut grad);
if !energy_before.is_finite() {
return Err(KernelError::Invalid("the fairness energy of this net is not a finite number".into()));
}
// The energy is a sum of squares, so where rounding leaves it a hair below zero the true
// value is zero: report it that way rather than as a negative number.
let energy_before = energy_before.max(0.0);
// How big the net itself is, for telling a fairing step from rounding (see below).
let size = interior.size(ctrl);
let mut step = vec![[0.0; N]; interior.points.len()];
let mut b = vec![0.0; interior.points.len()];
let mut report = FairReport { energy_before, energy_after: energy_before, steps: 0, movement: 0.0, energy_trace: Vec::new() };
for _ in 0..opts.iterations {
let e_now = self.energy_gradient(current.cells(), &mut grad);
if !e_now.is_finite() {
break;
}
// The exact minimiser over the interior is the Newton step `G_ff·d = −(G·P)_f`; the
// system is per coordinate, all three sharing the one factorisation.
for c in 0..N {
for (slot, &at) in interior.points.iter().enumerate() {
b[slot] = -grad.get(at).and_then(|g| g.get(c)).copied().unwrap_or(0.0);
}
system.solve(&mut b)?;
for (slot, v) in b.iter().enumerate() {
if let Some(d) = step.get_mut(slot).and_then(|d| d.get_mut(c)) {
*d = *v;
}
}
}
if step.iter().flatten().all(|&x| x == 0.0) {
break;
}
// The largest fraction of the step that keeps every control point within the
// tolerance of where the design put it, and never more than the whole step.
let mut s = opts.strength.min(interior.limit(ctrl, current.cells(), &step, opts.tolerance));
if !(s > 0.0) {
break;
}
// A step this much shorter than the net's own size cannot be told from the rounding
// of the arithmetic that found it: the net is as fair as it gets.
let longest = step.iter().flatten().fold(0.0f64, |m, x| m.max(x.abs()));
if s * longest <= MIN_STEP * size {
break;
}
let mut taken = false;
for _ in 0..MAX_HALVINGS {
let candidate = interior.apply(&current, &step, s);
let e = self.energy_gradient(candidate.cells(), &mut grad);
if e < e_now {
current = candidate;
report.steps += 1;
report.energy_trace.push(e.max(0.0));
taken = true;
break;
}
// The step did not lower the energy: halve it and try again, and when even a hair
// of a step will not, this is as fair as the net gets.
s *= 0.5;
if s <= MIN_STEP {
break;
}
}
if !taken {
break;
}
}
report.energy_after = report.energy_trace.last().copied().unwrap_or(energy_before);
report.movement = interior.movement(ctrl, current.cells());
Ok((current, report))
}
}
/// Which control points a fairing run may move, and where each sits in the banded system.
struct Interior {
/// The flattened index (u fastest) of interior point number `k`.
points: Vec<usize>,
/// The interior number of each flattened index, `None` where the point is held.
slot: Vec<Option<usize>>,
/// How many control points across u (`cols`) and across v (`rows`) are interior.
cols: usize,
rows: usize,
}
impl Interior {
/// The interior of `net` with `keep` layers held at each end of each direction (1 without
/// [`FairOptions::keep_edges`], 2 with it).
fn new<const N: usize>(net: &Net<N>, keep: usize) -> Result<Interior> {
let [cu, cv] = net.count();
let (i0, i1) = free_span(cu, keep)?;
let (j0, j1) = free_span(cv, keep)?;
let (cols, rows) = (i1 - i0, j1 - j0);
let mut points = Vec::with_capacity(cols * rows);
let mut slot = vec![None; net.total()];
for j in j0..j1 {
for i in i0..i1 {
if let Some(s) = slot.get_mut(net.index(i, j)) {
*s = Some(points.len());
}
points.push(net.index(i, j));
}
}
if points.len() < 2 {
return Err(KernelError::Invalid(format!(
"fairing needs at least two interior control points; this {cu} × {cv} net has {}",
points.len()
)));
}
Ok(Interior { points, slot, cols, rows })
}
/// `current` with `s` times the step `d` added to the interior control points; the held ones
/// are copied as they are, bit for bit.
fn apply<const N: usize>(&self, current: &Grid<[f64; N]>, d: &[[f64; N]], s: f64) -> Grid<[f64; N]> {
let mut out = current.clone();
for (slot, &at) in self.points.iter().enumerate() {
let (Some(p), Some(v)) = (out.cells_mut().get_mut(at), d.get(slot)) else { continue };
for (x, dx) in p.iter_mut().zip(v) {
*x += s * dx;
}
}
out
}
/// How big the interior is: the farthest interior control point from the first one, in mm.
/// A fairing step far below this belongs to the rounding of the arithmetic, not the design.
fn size<const N: usize>(&self, ctrl: &[[f64; N]]) -> f64 {
let Some(first) = self.points.first().and_then(|&at| ctrl.get(at)) else { return 0.0 };
self.points.iter().fold(0.0f64, |m, &at| ctrl.get(at).map_or(m, |p| m.max(dist(first, p))))
}
/// The largest fraction `s ≤ 1` of the step `d` that keeps every interior control point
/// within `tolerance` of where the design put it (`input`). The movement is `‖Δ + s·d‖ ≤ tol`
/// per point — a quadratic in `s` opening upwards, with the accumulated movement
/// `Δ = current − input` already inside the ball, so the bound is its positive root.
fn limit<const N: usize>(&self, input: &[[f64; N]], current: &[[f64; N]], d: &[[f64; N]], tolerance: f64) -> f64 {
let mut s = 1.0f64;
for (slot, &at) in self.points.iter().enumerate() {
let (Some(dv), Some(cv), Some(iv)) = (d.get(slot), current.get(at), input.get(at)) else { continue };
let a = dot(dv, dv);
if a <= 0.0 {
continue;
}
let delta: [f64; N] = std::array::from_fn(|c| cv[c] - iv[c]);
let b = 2.0 * dot(&delta, dv);
let c = dot(&delta, &delta) - tolerance * tolerance;
let disc = b * b - 4.0 * a * c;
let root = if disc >= 0.0 { (-b + disc.sqrt()) / (2.0 * a) } else { 0.0 };
// `f64::max` ignores a NaN, so a step whose arithmetic overflows stops the run
// instead of leaking a not-a-number into a control point.
s = s.min(root.max(0.0));
}
(s * TOLERANCE_SLACK).clamp(0.0, 1.0)
}
/// The farthest any interior control point moved from the design's own position, in mm.
fn movement<const N: usize>(&self, input: &[[f64; N]], current: &[[f64; N]]) -> f64 {
self.points.iter().fold(0.0f64, |m, &at| match (input.get(at), current.get(at)) {
(Some(a), Some(b)) => m.max(dist(a, b)),
_ => m,
})
}
}
/// The control points of one direction a fairing run may move, as `[lo, hi)`. A direction of one
/// control point — a curve seen as a net one row deep — is all interior; otherwise `keep` layers
/// are held at each end: the boundary, and with `keep = 2` the layer next to it.
fn free_span(count: usize, keep: usize) -> Result<(usize, usize)> {
if count == 1 {
return Ok((0, 1));
}
if count <= 2 * keep {
return Err(KernelError::Invalid(format!(
"fairing a net {count} control points across one direction and holding {keep} at each edge leaves nothing to move"
)));
}
Ok((keep, count - keep))
}
/// A symmetric banded matrix in upper-triangular form: row `r` holds columns `r ..= r + bw`.
struct Band {
n: usize,
bw: usize,
/// The upper band, `n · (bw + 1)` numbers; the scaling by the largest diagonal is folded in
/// when the matrix is factorised.
a: Vec<f64>,
scale: f64,
}
impl Band {
fn new(n: usize, bw: usize) -> Result<Band> {
let Some(len) = (bw + 1).checked_mul(n).filter(|&l| l <= MAX_FAIR_BAND) else {
return Err(KernelError::TooLarge(format!("a fairing system of {n} unknowns {bw} apart")));
};
Ok(Band { n, bw, a: vec![0.0; len], scale: 1.0 })
}
fn index(&self, r: usize, s: usize) -> Option<usize> {
let (r, s) = if r <= s { (r, s) } else { (s, r) };
(s - r <= self.bw && s < self.n).then_some(r * (self.bw + 1) + (s - r))
}
fn get(&self, r: usize, s: usize) -> f64 {
self.index(r, s).and_then(|i| self.a.get(i)).copied().unwrap_or(0.0)
}
fn set(&mut self, r: usize, s: usize, v: f64) {
if let Some(x) = self.index(r, s).and_then(|i| self.a.get_mut(i)) {
*x = v;
}
}
/// Add `v` at `(r, s)`. Only `r ≤ s` is stored (the matrix is symmetric, so callers adding a
/// whole symmetric neighbourhood reach each stored entry once).
fn add(&mut self, r: usize, s: usize, v: f64) {
if r <= s
&& let Some(x) = self.index(r, s).and_then(|i| self.a.get_mut(i))
{
*x += v;
}
}
/// `A = Uᵀ·U` in place, the entries scaled by the largest diagonal first (the scaling does
/// not change the solution, only the size of the pivots, so a net whose knots span microns or
/// kilometres factorises just as well). An error, never a panic, when a pivot is not
/// positive: the system is singular there and the geometry must not move.
fn factorised(mut self) -> Result<Band> {
let (n, bw) = (self.n, self.bw);
let scale = (0..n).fold(0.0f64, |m, r| m.max(self.get(r, r).abs()));
if !(scale > 0.0) || !scale.is_finite() {
return Err(KernelError::Invalid("the fairness energy does not depend on any interior control point: nothing to fair".into()));
}
self.scale = scale;
for v in self.a.iter_mut() {
*v /= scale;
}
for r in 0..n {
let mut d = self.get(r, r);
for k in r.saturating_sub(bw)..r {
let u = self.get(k, r);
d -= u * u;
}
if !(d > 0.0) {
return Err(KernelError::Invalid(
"the fairing equations are singular (an interior control point that does not move the geometry)".into(),
));
}
let d = d.sqrt();
self.set(r, r, d);
for s in r + 1..(r + bw + 1).min(n) {
let mut v = self.get(r, s);
for k in s.saturating_sub(bw)..r {
v -= self.get(k, r) * self.get(k, s);
}
self.set(r, s, v / d);
}
}
Ok(self)
}
/// Solve `A·x = b` with the stored factorisation, in place.
fn solve(&self, b: &mut [f64]) -> Result<()> {
let (n, bw) = (self.n, self.bw);
if b.len() != n {
return Err(KernelError::Invalid(format!("{} fairing unknowns for a system of {n}", b.len())));
}
for x in b.iter_mut() {
*x /= self.scale;
}
// Uᵀ·y = b, then U·x = y.
for r in 0..n {
let mut v = b.get(r).copied().unwrap_or(0.0);
for k in r.saturating_sub(bw)..r {
v -= self.get(k, r) * b.get(k).copied().unwrap_or(0.0);
}
if let Some(x) = b.get_mut(r) {
*x = v / self.get(r, r);
}
}
for r in (0..n).rev() {
let mut v = b.get(r).copied().unwrap_or(0.0);
for s in r + 1..(r + bw + 1).min(n) {
v -= self.get(r, s) * b.get(s).copied().unwrap_or(0.0);
}
if let Some(x) = b.get_mut(r) {
*x = v / self.get(r, r);
}
}
if b.iter().any(|x| !x.is_finite()) {
return Err(KernelError::Invalid("the fairing step is not a finite number".into()));
}
Ok(())
}
}
/// Fair a B-spline curve's control points of any dimension: hold control points `0` and `n − 1`
/// and (with [`FairOptions::keep_edges`]) those next to them, and move the rest to lower the
/// bending energy `∫‖C″‖² dt` in the curve's own parameter (see the module docs). `N` is 3 for a
/// wire in space, 2 for a sketch curve.
pub fn fair_curve<const N: usize>(degree: usize, knots: &[f64], ctrl: &[[f64; N]], opts: &FairOptions) -> Result<FairCurve<N>> {
let opts = opts.checked()?;
let row = Grid::row(ctrl.to_vec());
let (faired, report) = Net::new([degree, 0], [knots.to_vec(), TRIVIAL_KNOTS.to_vec()], &row, &CURVE_ENERGY)?.fair(&opts)?;
Ok(FairCurve { degree, knots: knots.to_vec(), ctrl: faired.into_cells(), report })
}
/// Fair the interior of a B-spline control net with the thin-plate energy
/// `∫∫ ‖S_uu‖² + 2‖S_uv‖² + ‖S_vv‖² du dv` in the net's own parameters (see the module docs).
/// The boundary layers (see [`FairOptions::keep_edges`]) are held. The generic core behind
/// [`fair_surface`], [`fair_bspline_surface`] and their rational counterparts, for a caller with
/// its own control net.
pub fn fair_net<const N: usize>(degree: [usize; 2], knots: [&[f64]; 2], ctrl: &Grid<[f64; N]>, opts: &FairOptions) -> Result<FairNet<N>> {
let opts = opts.checked()?;
let (faired, report) = Net::new(degree, [knots[0].to_vec(), knots[1].to_vec()], ctrl, &SURFACE_ENERGY)?.fair(&opts)?;
Ok(FairNet { degree, knots: [knots[0].to_vec(), knots[1].to_vec()], ctrl: faired, report })
}
/// The degree of a spline record of `count` control points on `knots`.
fn degree_of(knots: &[f64], count: usize) -> Result<usize> {
knots.len().checked_sub(count + 1).ok_or_else(|| KernelError::Invalid(format!("{} knots are too few for {count} control points", knots.len())))
}
/// Fair a B-spline curve record's control points (a `Curve::Spline`): [`fair_curve`] on its
/// points, the same knots.
pub fn fair_bspline_curve(curve: &b::Curve, opts: &FairOptions) -> Result<(b::Curve, FairReport)> {
let b::Curve::Spline { knots, points } = curve else { return Err(KernelError::Invalid("not a B-spline curve".into())) };
let faired = fair_curve(degree_of(knots, points.len())?, knots, points, opts)?;
Ok((b::Curve::Spline { knots: faired.knots, points: faired.ctrl }, faired.report))
}
/// Fair a rational curve record's control points (a `Curve::RationalSpline`): its Cartesian
/// control points are faired like any other curve and its weights are kept, so the result is the
/// same rational curve with moved control points. The convex-hull bound that keeps the geometry
/// within the tolerance still holds, because with the weights unchanged the rational basis
/// functions are non-negative and sum to one.
pub fn fair_nurbs_curve(curve: &b::Curve, opts: &FairOptions) -> Result<(b::Curve, FairReport)> {
let b::Curve::RationalSpline { knots, homogeneous } = curve else { return Err(KernelError::Invalid("not a rational B-spline curve".into())) };
let hpoints: Vec<HPoint> = homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect();
let ctrl = positions(&Grid::row(hpoints.clone()))?;
let faired = fair_curve(degree_of(knots, homogeneous.len())?, knots, ctrl.cells(), opts)?;
let net = reweighted(Grid::row(hpoints), &Grid::row(faired.ctrl));
let homogeneous = net.into_cells().into_iter().map(|h| [h.x, h.y, h.z, h.w]).collect();
Ok((b::Curve::RationalSpline { knots: faired.knots, homogeneous }, faired.report))
}
/// Fair a B-spline surface record's control net (a `Surface::Spline`): [`fair_net`] on its
/// points, the same knots, the boundary rows held.
pub fn fair_bspline_surface(surface: &b::Surface, opts: &FairOptions) -> Result<(b::Surface, FairReport)> {
let b::Surface::Spline { u_knots, v_knots, points } = surface else { return Err(KernelError::Invalid("not a B-spline surface".into())) };
let net = record_net(points)?;
let [cu, cv] = net.count();
let degree = [degree_of(u_knots, cu)?, degree_of(v_knots, cv)?];
let faired = fair_net(degree, [u_knots, v_knots], &net, opts)?;
Ok((b::Surface::Spline { u_knots: u_knots.clone(), v_knots: v_knots.clone(), points: faired.ctrl.into_u_rows() }, faired.report))
}
/// Fair a rational surface record's control net (a `Surface::RationalSpline`), like
/// [`fair_surface`]: the Cartesian control points are faired, the weights kept.
pub fn fair_nurbs_surface(surface: &b::Surface, opts: &FairOptions) -> Result<(b::Surface, FairReport)> {
let b::Surface::RationalSpline { u_knots, v_knots, homogeneous } = surface else {
return Err(KernelError::Invalid("not a rational B-spline surface".into()));
};
let net = record_net(homogeneous)?.map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] });
let [cu, cv] = net.count();
let degree = [degree_of(u_knots, cu)?, degree_of(v_knots, cv)?];
let faired = fair_net(degree, [u_knots, v_knots], &positions(&net)?, opts)?;
let homogeneous = reweighted(net, &faired.ctrl).map(|h| [h.x, h.y, h.z, h.w]).into_u_rows();
Ok((b::Surface::RationalSpline { u_knots: u_knots.clone(), v_knots: v_knots.clone(), homogeneous }, faired.report))
}
/// A surface record's control net (`rows[i][j]`, i along u) as a grid: refused when it is empty
/// or not rectangular.
fn record_net<P: Clone>(rows: &[Vec<P>]) -> Result<Grid<P>> {
let net = Grid::from_u_rows(rows).ok_or_else(|| KernelError::Invalid("the surface's control net is not rectangular".into()))?;
if net.is_empty() {
return Err(KernelError::Invalid("the surface has no control points".into()));
}
Ok(net)
}
/// A homogeneous control net's Cartesian points; refused when a weight is zero (the point has no
/// position).
fn positions(net: &Grid<HPoint>) -> Result<Grid<[f64; 3]>> {
net.clone().try_map(|h| {
let p = h.project().ok_or_else(|| KernelError::Invalid("a control point has no position: its weight is zero".into()))?;
Ok([p.x, p.y, p.z])
})
}
/// `net` moved to the faired `points`, each keeping its weight.
fn reweighted(mut net: Grid<HPoint>, points: &Grid<[f64; 3]>) -> Grid<HPoint> {
for (h, &[x, y, z]) in net.cells_mut().iter_mut().zip(points.cells()) {
*h = HPoint::weighted(Vec3::new(x, y, z), h.w);
}
net
}
/// Fair a geom NURBS surface's control net: [`fair_net`] on its Cartesian control points, with
/// the weights kept as they are (a fairing moves points, not weights) and the boundary rows held.
/// A rational surface's geometry then stays within the tolerance too, by the same convex-hull
/// bound as the non-rational case.
pub fn fair_surface(surface: &NurbsSurface, opts: &FairOptions) -> Result<(NurbsSurface, FairReport)> {
let net = surface.net();
let [ku, kv] = surface.knots();
let degree = surface.degree();
let faired = fair_net(degree, [ku, kv], &positions(&net)?, opts)?;
let net = reweighted(net, &faired.ctrl);
let out =
NurbsSurface::from_homogeneous(degree, surface.knots().clone(), net.into_cells()).map_err(|e| spline_error("fairing the surface", e))?;
Ok((out, faired.report))
}
/// Fair the B-spline faces at `faces` (indices in `body`'s face order) of `body`: each face's
/// interior control vertices move to flatten the thin-plate energy of the face while its boundary
/// rows stay put, so the face keeps meeting its neighbours as it did.
///
/// Every picked face keeps the very loops, edges and vertices it had and the way it pointed: only
/// its surface changes in the body's record, so the body is as closed (or as open) as it was,
/// holes and all, and SMLib builds it from that record. A face that is not a B-spline (a plane,
/// cylinder, cone, sphere, torus or revolution) has no control points to fair and is refused by
/// name; a mesh body has no faces to fair at all. A face whose held layers are its whole net (see
/// [`held_face`]) has no interior control vertex to move and is left exactly as it is, its energy
/// reported unchanged.
///
/// The report is over the picked faces together: the energies summed, the largest movement of any
/// control point, and the energy trace as the sum at each step (a face that stops early keeps its
/// last energy for the steps the others still take).
pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(Body, FairReport)> {
let opts = opts.checked()?;
body.require_brep("fair")?;
let mut record = crate::native::brep_record(body)?;
let count = record.faces.len();
if count == 0 {
return Err(KernelError::Invalid("the body has no faces".into()));
}
let mut picked: Vec<usize> = Vec::new();
for &i in faces {
if i >= count {
return Err(KernelError::Invalid(format!("no face {i}: the body has {count}")));
}
if !picked.contains(&i) {
picked.push(i);
}
}
if picked.is_empty() {
return Err(KernelError::Invalid("pick the faces to fair".into()));
}
let mut reports: Vec<FairReport> = Vec::with_capacity(picked.len());
let mut changed: Vec<usize> = Vec::with_capacity(picked.len());
for &i in &picked {
let Some(face) = record.faces.get_mut(i) else { continue };
if let Some(report) = held_face(&face.surface, &opts)? {
reports.push(report);
continue;
}
let (surface, report) = match &face.surface {
b::Surface::Spline { .. } => fair_bspline_surface(&face.surface, &opts)?,
b::Surface::RationalSpline { .. } => fair_nurbs_surface(&face.surface, &opts)?,
_ => {
return Err(KernelError::Invalid(format!(
"face {i} is not a B-spline face: a plane, cylinder, cone, sphere, torus or revolution has no control points to fair"
)));
}
};
face.surface = surface;
reports.push(report);
changed.push(i);
}
let report = FairReport {
energy_before: reports.iter().map(|r| r.energy_before).sum(),
energy_after: reports.iter().map(|r| r.energy_after).sum(),
steps: reports.iter().map(|r| r.steps).max().unwrap_or(0),
movement: reports.iter().fold(0.0f64, |m, r| m.max(r.movement)),
energy_trace: {
let longest = reports.iter().map(|r| r.energy_trace.len()).max().unwrap_or(0);
(0..longest).map(|k| reports.iter().map(|r| r.energy_trace.get(k).copied().unwrap_or(r.energy_after)).sum()).collect()
},
};
if changed.is_empty() {
return Ok((body.clone(), report));
}
let smlib = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| KernelError::Failed(format!("fair: SMLib: {e}")))?;
let (result, order) = crate::native::body_from_smlib_ordered(&smlib)?;
// The topology is the body's own, so SMLib's order is the body's: each face kept or
// modified, each edge kept. Where SMLib's order is not the record's the history is not known.
let kept = order.is_some_and(|o| o.faces.iter().enumerate().all(|(i, f)| i == *f) && o.edges.iter().enumerate().all(|(i, e)| i == *e));
if !kept || result.face_count() != body.face_count() || result.edge_count() != body.edge_count() {
return Ok((result, report));
}
let mut history = <crate::history::History as crate::history::BodyHistory>::identity(body);
for &i in &changed {
if let Some(f) = history.faces.get_mut(i) {
f.change = Change::Modified;
}
}
Ok((result.with_history(history, &[body])?, report))
}
/// The report for a B-spline face whose every control point `opts` holds, which the run leaves
/// exactly as it is: a direction of no more control points than the held layers (a single-span
/// cubic with its edges kept, an extruded curve's two rows) holds the whole net, since every row
/// is a boundary row or one next to it. `None` when some control point is free to move, and for a
/// face that is not a B-spline.
fn held_face(surface: &b::Surface, opts: &FairOptions) -> Result<Option<FairReport>> {
let (u_knots, v_knots, ctrl) = match surface {
b::Surface::Spline { u_knots, v_knots, points } => (u_knots, v_knots, record_net(points)?),
b::Surface::RationalSpline { u_knots, v_knots, homogeneous } => {
(u_knots, v_knots, positions(&record_net(homogeneous)?.map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }))?)
}
_ => return Ok(None),
};
let [cu, cv] = ctrl.count();
let degree = [degree_of(u_knots, cu)?, degree_of(v_knots, cv)?];
let net = Net::new(degree, [u_knots.clone(), v_knots.clone()], &ctrl, &SURFACE_ENERGY)?;
if !net.all_held(if opts.keep_edges { 2 } else { 1 }) {
return Ok(None);
}
net.unmoved().map(Some)
}
#[cfg(test)]
mod tests {
use super::*;
use solidcraft_geom::brep::eval::CurveEval;
/// A clamped uniform knot vector over `[0, spans]` of degree `degree`: `spans + degree`
/// control points.
fn clamped(spans: usize, degree: usize) -> Vec<f64> {
let mut k = vec![0.0; degree + 1];
k.extend((1..spans).map(|i| i as f64));
k.extend(std::iter::repeat_n(spans as f64, degree + 1));
k
}
/// The knot average `(kᵢ₊₁ + … + kᵢ₊ₚ)/p` of control point `i`: `Σ Nᵢ(t)·ξᵢ = t` (NURBS Book
/// eq. 3.4), so control points at `a + b·ξᵢ` describe the affine curve `a + b·t` exactly.
fn average(knots: &[f64], degree: usize, i: usize) -> f64 {
(1..=degree).map(|r| knots.get(i + r).copied().unwrap_or(0.0)).sum::<f64>() / degree as f64
}
/// The control points of the affine curve `ξ ↦ a + b·ξ` at the knot averages of `knots`: a
/// curve of exactly zero bending energy.
fn affine_curve(knots: &[f64], degree: usize, a: [f64; 3], b: [f64; 3]) -> Vec<[f64; 3]> {
(0..knots.len() - degree - 1).map(|i| std::array::from_fn(|c| a[c] + b[c] * average(knots, degree, i))).collect()
}
/// The control net (u fastest) of the plane `(ξ, η) ↦ a + b·ξ + c·η` at the knot averages of
/// `ku` and `kv`: a net of exactly zero thin-plate energy.
fn planar_net(ku: &[f64], kv: &[f64], degree: [usize; 2], a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> Vec<[f64; 3]> {
let (cu, cv) = (ku.len() - degree[0] - 1, kv.len() - degree[1] - 1);
let mut net = Vec::with_capacity(cu * cv);
for j in 0..cv {
for i in 0..cu {
let (xi, eta) = (average(ku, degree[0], i), average(kv, degree[1], j));
net.push(std::array::from_fn(|d| a[d] + b[d] * xi + c[d] * eta));
}
}
net
}
/// The point of the curve `(degree, knots, ctrl)` at `t`, through the same basis geom uses: a
/// basis function `i` owns the `degree + 2` knots `knots[i..=i + degree + 1]`.
fn curve_at<const N: usize>(degree: usize, knots: &[f64], ctrl: &[[f64; N]], t: f64) -> [f64; N] {
let n = ctrl.len();
let side = if t >= knots.get(n).copied().unwrap_or(f64::INFINITY) { Side::Left } else { Side::Right };
let mut out = [0.0; N];
for (i, c) in ctrl.iter().enumerate() {
let b = knots.get(i..=i + degree + 1).and_then(|l| local_basis(l, t, side, 0).first().copied()).unwrap_or(0.0);
for (o, x) in out.iter_mut().zip(c) {
*o += b * x;
}
}
out
}
/// The greatest distance between two points of space, in mm.
fn apart(a: Vec3, b: Vec3) -> f64 {
a.dist(b)
}
/// A geom point as a coordinate triple.
fn triple(p: Vec3) -> [f64; 3] {
[p.x, p.y, p.z]
}
#[test]
fn a_perturbed_curve_is_faired_back_to_its_smooth_shape_and_its_ends_stay_put() {
// A cubic curve whose control points sit at the knot averages of an affine curve: zero
// bending energy, so a fairing run must return to the same control polygon. The knots are
// deliberately uneven, so a fairing that ignored the curve's own parameter would not.
let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 5.0, 9.0, 9.0, 9.0, 9.0];
let (a, b) = ([-20.0, 5.0, 1.5], [4.0, -2.5, 3.0]);
let smooth = affine_curve(&knots, 3, a, b);
let mut rough = smooth.clone();
rough[2] = [rough[2][0] + 1.5, rough[2][1] - 2.0, rough[2][2] + 3.0];
rough[3][2] += 2.5;
rough[4][0] -= 1.25;
rough[5][1] += 1.75;
let far = (0..smooth.len()).map(|i| dist(&rough[i], &smooth[i])).fold(0.0, f64::max);
let opts = FairOptions::new(1.0, 8, false, 100.0).unwrap();
let faired = fair_curve(3, &knots, &rough, &opts).unwrap();
// The ends did not move at all, bit for bit.
assert_eq!(faired.ctrl[0], rough[0]);
assert_eq!(faired.ctrl[6], rough[6]);
// Every interior control point came back to the smooth shape.
let near = (1..6).map(|i| dist(&faired.ctrl[i], &smooth[i])).fold(0.0, f64::max);
eprintln!(
"curve: perturbation {far} mm, faired to {near:e} mm, energy {:e} → {:e} in {} steps, movement {:e} mm",
faired.report.energy_before, faired.report.energy_after, faired.report.steps, faired.report.movement
);
assert!(near < 1e-6 && near < far * 1e-6, "faired to {near:e}, was {far} mm out");
// The energy is a real number before, fell to nothing, and never rose on the way.
assert!(faired.report.energy_before > 1e-3, "{:e}", faired.report.energy_before);
assert!(faired.report.energy_after >= 0.0 && faired.report.energy_after < 1e-9 * faired.report.energy_before);
assert!(faired.report.steps >= 1 && faired.report.energy_trace.len() == faired.report.steps);
assert_eq!(faired.report.energy_trace.last().copied(), Some(faired.report.energy_after));
assert!(faired.report.energy_trace.windows(2).all(|w| w[1] < w[0]), "{:?}", faired.report.energy_trace);
// A step never moves a control point further than the tolerance, and here it moved the
// whole way back to the smooth shape.
assert!(faired.report.movement <= 100.0 && (faired.report.movement - far).abs() < 1e-9, "{:e}", faired.report.movement);
// The faired curve is the affine line it was meant to be.
let mut off = 0.0f64;
for k in 0..=32 {
let t = 9.0 * f64::from(k) / 32.0;
let want: [f64; 3] = std::array::from_fn(|c| a[c] + b[c] * t);
off = off.max(dist(&curve_at(3, &knots, &faired.ctrl, t), &want));
}
eprintln!("curve: the faired curve is {off:e} mm off the affine line it describes");
assert!(off < 1e-6, "{off:e}");
}
#[test]
fn a_half_strength_run_walks_to_the_same_shape_over_its_iterations() {
// The same perturbation, walked a half step at a time: the energy must fall at every step
// (monotone, strictly) and still arrive at the smooth shape.
let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 5.0, 9.0, 9.0, 9.0, 9.0];
let smooth = affine_curve(&knots, 3, [-20.0, 5.0, 1.5], [4.0, -2.5, 3.0]);
let mut rough = smooth.clone();
rough[2][2] += 4.0;
rough[3][0] += 2.0;
let opts = FairOptions::new(0.5, 40, false, 100.0).unwrap();
let faired = fair_curve(3, &knots, &rough, &opts).unwrap();
eprintln!("half strength: energy {:e} → {:e} in {} steps", faired.report.energy_before, faired.report.energy_after, faired.report.steps);
assert!(faired.report.energy_trace.len() > 4, "one step is not a walk");
assert!(faired.report.energy_trace.windows(2).all(|w| w[1] < w[0]), "the energy must fall at every step");
assert!(faired.report.energy_after < 1e-9 * faired.report.energy_before);
assert_eq!(faired.ctrl[0], rough[0]);
assert_eq!(faired.ctrl[6], rough[6]);
assert!(dist(&faired.ctrl[3], &smooth[3]) < 1e-6);
}
#[test]
fn the_faired_curve_stays_within_the_tolerance_of_the_design() {
// A heavily perturbed curve with a 0.75 mm tolerance: the design may be smoothed, but
// never by more than the caller allowed, and the bound is on the geometry itself.
let knots = clamped(3, 3);
let smooth = affine_curve(&knots, 3, [0.0, 0.0, 0.0], [30.0, 8.0, 0.0]);
let mut rough = smooth.clone();
for (i, d) in [(1, [1.0, -2.0, 4.0]), (2, [-3.0, 2.0, -6.0]), (3, [2.0, -1.0, 5.0]), (4, [-2.0, 3.0, -4.0])] {
for c in 0..3 {
rough[i][c] += d[c];
}
}
let tolerance = 0.75;
let opts = FairOptions::new(1.0, 12, false, tolerance).unwrap();
let faired = fair_curve(3, &knots, &rough, &opts).unwrap();
let mut off = 0.0f64;
for k in 0..=64 {
let t = 3.0 * f64::from(k) / 64.0;
off = off.max(dist(&curve_at(3, &knots, &faired.ctrl, t), &curve_at(3, &knots, &rough, t)));
}
eprintln!(
"tolerance {tolerance}: the curve moved {off:e} mm at worst ({:e} mm of control points), energy {:e} → {:e}",
faired.report.movement, faired.report.energy_before, faired.report.energy_after
);
assert!(faired.report.movement <= tolerance, "{:e}", faired.report.movement);
assert!(off <= tolerance * (1.0 + 1e-9), "{off:e} over {tolerance}");
assert!(faired.report.energy_after < faired.report.energy_before);
// The tolerance did not stop the run from heading for the smooth shape.
let before = (0..6).map(|i| dist(&rough[i], &smooth[i])).fold(0.0, f64::max);
let after = (0..6).map(|i| dist(&faired.ctrl[i], &smooth[i])).fold(0.0, f64::max);
assert!(after < before, "{after} vs {before}");
assert_eq!(faired.ctrl[0], rough[0]);
assert_eq!(faired.ctrl[5], rough[5]);
}
#[test]
fn a_sketch_curve_of_two_dimensions_fairs_the_same_way() {
// The generic core takes `[f64; 2]` just as well: a quadratic sketch curve, its middle
// pulled 2 mm out of the smooth polyline.
let knots = clamped(4, 2);
let smooth: Vec<[f64; 2]> = (0..knots.len() - 3).map(|i| [average(&knots, 2, i) * 10.0, average(&knots, 2, i) * 2.0]).collect();
let mut rough = smooth.clone();
rough[2] = [rough[2][0] + 1.0, rough[2][1] - 2.0];
rough[3][1] += 1.5;
let opts = FairOptions::new(1.0, 10, false, 50.0).unwrap();
let faired = fair_curve(2, &knots, &rough, &opts).unwrap();
eprintln!("2D sketch curve: energy {:e} → {:e} in {} steps", faired.report.energy_before, faired.report.energy_after, faired.report.steps);
assert_eq!(faired.ctrl[0], rough[0]);
assert_eq!(faired.ctrl[5], rough[5]);
assert!(faired.report.energy_after >= 0.0 && faired.report.energy_after < 1e-9 * faired.report.energy_before);
for (i, want) in smooth.iter().enumerate().take(5).skip(1) {
assert!(dist(&faired.ctrl[i], want) < 1e-6, "point {i}");
}
}
#[test]
fn a_perturbed_net_is_faired_back_to_its_plane_with_its_boundary_rows_held() {
// A bicubic net of a plane (zero thin-plate energy), its middle pushed out; the boundary
// rows must not move at all and the interior must come back to the plane.
let (ku, kv) = (clamped(3, 3), clamped(4, 3));
let degree = [3, 3];
let (cu, cv) = (ku.len() - 4, kv.len() - 4);
let (a, b, c) = ([1.0, -2.0, 4.0], [2.0, 0.5, -0.25], [-0.5, 1.5, 0.75]);
let smooth = planar_net(&ku, &kv, degree, a, b, c);
let mut rough = smooth.clone();
for &(i, j, d) in &[(2usize, 2usize, 3.0), (3, 3, -2.5), (1, 4, 1.5), (4, 5, -1.0)] {
rough[j * cu + i][2] += d;
}
let opts = FairOptions::new(1.0, 6, false, 100.0).unwrap();
let faired = fair_net(degree, [&ku, &kv], &Grid::from_fn([cu, cv], |i, j| rough[j * cu + i]).unwrap(), &opts).unwrap();
for j in 0..cv {
for i in [0, cu - 1] {
assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "column {i}, row {j} moved");
}
}
for i in 0..cu {
for j in [0, cv - 1] {
assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "row {j}, column {i} moved");
}
}
let near = faired.ctrl.cells().iter().zip(&smooth).map(|(a, b)| dist(a, b)).fold(0.0, f64::max);
let far = (0..cu * cv).map(|k| dist(&rough[k], &smooth[k])).fold(0.0, f64::max);
eprintln!("net: perturbation {far} mm, faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after);
assert!(near < 1e-6, "{near:e}");
assert!(faired.report.energy_after < 1e-9 * faired.report.energy_before);
assert!(faired.report.energy_trace.windows(2).all(|w| w[1] < w[0]));
// With keep_edges the two outer layers at each side stay exactly as designed — so the
// bump goes into the middle of the net — and the rest still comes back to the plane.
let mut inner = smooth.clone();
for &(i, j, d) in &[(2usize, 2usize, 3.0), (3, 3, -2.5), (2, 3, 1.5), (3, 2, -1.0)] {
inner[j * cu + i][2] += d;
}
let kept = FairOptions::new(1.0, 6, true, 100.0).unwrap();
let faired = fair_net(degree, [&ku, &kv], &Grid::from_fn([cu, cv], |i, j| inner[j * cu + i]).unwrap(), &kept).unwrap();
let shell = |i: usize, j: usize| i < 2 || i + 2 >= cu || j < 2 || j + 2 >= cv;
for j in 0..cv {
for i in 0..cu {
if shell(i, j) {
assert_eq!(faired.ctrl.get(i, j), Some(&inner[j * cu + i]), "({i}, {j}) is a boundary layer and moved");
}
}
}
let near = (0..cu * cv).filter(|&k| !shell(k % cu, k / cu)).map(|k| dist(&faired.ctrl.cells()[k], &smooth[k])).fold(0.0, f64::max);
eprintln!("net with keep_edges: interior faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after);
assert!(near < 1e-6 && faired.report.energy_after < faired.report.energy_before);
}
#[test]
fn a_faired_geom_surface_stays_within_the_tolerance_of_the_design_and_keeps_its_weights() {
// A rational surface (weights off one) whose middle is pushed out: fair it with a 0.5 mm
// tolerance. The weights must be untouched, the boundary rows must not move, and the
// surface must stay within the tolerance of the one the design asked for.
let (ku, kv) = (clamped(3, 3), clamped(3, 3));
let degree = [3, 3];
let (cu, cv) = (ku.len() - 4, kv.len() - 4);
let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]);
let weights: Vec<f64> = (0..cu * cv).map(|k| 0.5 + (k % 5) as f64 * 0.25).collect();
let mut rough = smooth.clone();
for &(i, j, d) in &[(2usize, 2usize, 4.0), (3, 3, -3.0), (1, 2, 2.0)] {
rough[j * cu + i][2] += d;
}
let surface =
NurbsSurface::new(degree, [ku.clone(), kv.clone()], &rough.iter().map(|c| Vec3::new(c[0], c[1], c[2])).collect::<Vec<_>>(), &weights)
.unwrap();
let tolerance = 0.5;
let opts = FairOptions::new(1.0, 8, false, tolerance).unwrap();
let (faired, report) = fair_surface(&surface, &opts).unwrap();
for k in 0..cu * cv {
let (i, j) = (k % cu, k / cu);
assert_eq!(faired.point(i, j).w, surface.point(i, j).w, "the weight of ({i}, {j}) changed");
}
for j in 0..cv {
for i in [0, cu - 1] {
assert_eq!(faired.point(i, j), surface.point(i, j), "column {i} moved");
}
}
let dom = surface.domain();
let mut off = 0.0f64;
for k in 0..=24 {
for l in 0..=24 {
let (u, v) = (dom[0][0] + (dom[0][1] - dom[0][0]) * f64::from(k) / 24.0, dom[1][0] + (dom[1][1] - dom[1][0]) * f64::from(l) / 24.0);
off = off.max(surface.eval(u, v).unwrap().dist(faired.eval(u, v).unwrap()));
}
}
eprintln!(
"surface: moved {off:e} mm at worst ({:e} mm of control points), energy {:e} → {:e}",
report.movement, report.energy_before, report.energy_after
);
assert!(report.movement <= tolerance, "{:e}", report.movement);
assert!(off <= tolerance * (1.0 + 1e-9), "{off:e} over {tolerance}");
assert!(report.energy_after < report.energy_before);
// Every interior control point is nearer the plane than it was.
let before = (0..cu * cv).map(|k| dist(&rough[k], &smooth[k])).fold(0.0, f64::max);
let after = (0..cu * cv).map(|k| dist(&triple(faired.point(k % cu, k / cu).project().unwrap()), &smooth[k])).fold(0.0, f64::max);
assert!(after < before, "{after} vs {before}");
}
#[test]
fn the_record_wrappers_fair_a_spline_curve_and_surface_with_their_ends_held() {
let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 5.0, 9.0, 9.0, 9.0, 9.0];
let smooth = affine_curve(&knots, 3, [-20.0, 5.0, 1.5], [4.0, -2.5, 3.0]);
let mut rough = smooth.clone();
rough[2][2] += 3.0;
rough[4][1] -= 2.0;
let curve = b::Curve::Spline { knots: knots.to_vec(), points: rough.clone() };
let tolerance = 5.0;
let opts = FairOptions::new(1.0, 8, false, tolerance).unwrap();
let (faired, report) = fair_bspline_curve(&curve, &opts).unwrap();
let (fe, ce) = (CurveEval::new(&faired).unwrap(), CurveEval::new(&curve).unwrap());
let mut off = 0.0f64;
for k in 0..=64 {
let t = 9.0 * f64::from(k) / 64.0;
off = off.max(apart(fe.point(t).unwrap(), ce.point(t).unwrap()));
}
eprintln!(
"record curve: energy {:e} → {:e} in {} steps, moved {off:e} mm ({:e} mm of control points)",
report.energy_before, report.energy_after, report.steps, report.movement
);
let b::Curve::Spline { points: moved, .. } = &faired else { panic!("a B-spline curve") };
assert_eq!(moved.first(), rough.first());
assert_eq!(moved.last(), rough.last());
assert!(off <= tolerance * (1.0 + 1e-9), "{off:e}");
assert!(report.energy_after < 1e-9 * report.energy_before);
// The same on a B-spline surface: boundary rows bit-identical, the bump in the middle
// comes down, the energy falls.
let (ku, kv) = (clamped(3, 3), clamped(3, 3));
let degree = [3, 3];
let (cu, cv) = (ku.len() - 4, kv.len() - 4);
let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]);
let mut rough = smooth.clone();
rough[2 * cu + 2][2] += 5.0;
let rows: Vec<Vec<[f64; 3]>> = (0..cu).map(|i| (0..cv).map(|j| rough[j * cu + i]).collect()).collect();
let surface = b::Surface::Spline { u_knots: ku.clone(), v_knots: kv.clone(), points: rows.clone() };
let (faired, report) = fair_bspline_surface(&surface, &FairOptions::new(1.0, 6, true, 8.0).unwrap()).unwrap();
let b::Surface::Spline { points: moved, .. } = &faired else { panic!("a B-spline surface") };
eprintln!("record surface: energy {:e} → {:e}, {} steps", report.energy_before, report.energy_after, report.steps);
for i in 0..cu {
for j in 0..cv {
if i < 2 || i + 2 >= cu || j < 2 || j + 2 >= cv {
assert_eq!(moved[i][j], rows[i][j], "({i}, {j}) is a boundary layer and moved");
}
}
}
assert!(report.energy_after < report.energy_before);
assert!(moved[2][2][2] < rows[2][2][2], "the bump should come down");
}
#[test]
fn a_rational_surface_fairs_with_its_boundary_and_tolerance_intact() {
// The rational record wrapper, on weights away from one: fairing moves the Cartesian control
// points and keeps the weights, so the surface still cannot move more than the tolerance.
let (ku, kv) = (clamped(3, 3), clamped(3, 3));
let degree = [3, 3];
let (cu, cv) = (ku.len() - 4, kv.len() - 4);
let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]);
let mut rough = smooth.clone();
rough[2 * cu + 3][2] += 6.0;
let weights: Vec<f64> = (0..cu * cv).map(|k| 0.75 + (k % 3) as f64 * 0.5).collect();
let rows: Vec<Vec<[f64; 4]>> = (0..cu)
.map(|i| {
(0..cv)
.map(|j| {
let (c, w) = (rough[j * cu + i], weights[j * cu + i]);
[c[0] * w, c[1] * w, c[2] * w, w]
})
.collect()
})
.collect();
let surface = b::Surface::RationalSpline { u_knots: ku.clone(), v_knots: kv.clone(), homogeneous: rows.clone() };
let (faired, report) = fair_nurbs_surface(&surface, &FairOptions::new(1.0, 6, false, 0.5).unwrap()).unwrap();
eprintln!("rational surface: energy {:e} → {:e}, movement {:e} mm", report.energy_before, report.energy_after, report.movement);
assert!(report.movement <= 0.5 && report.energy_after < report.energy_before);
let b::Surface::RationalSpline { homogeneous: moved, .. } = &faired else { panic!("a rational surface") };
for i in 0..cu {
for j in 0..cv {
let (before, after) = (rows[i][j], moved[i][j]);
assert_eq!(after[3], before[3], "the weight of ({i}, {j}) changed");
if i == 0 || i + 1 == cu || j == 0 || j + 1 == cv {
assert_eq!(after, before, "({i}, {j}) is on the boundary and moved");
}
}
}
}
#[test]
fn hostile_fairing_inputs_are_refused() {
let knots = clamped(3, 3);
let ctrl = affine_curve(&knots, 3, [0.0, 0.0, 0.0], [10.0, 4.0, 2.0]);
let ok = FairOptions::new(1.0, 4, false, 10.0).unwrap();
// Out-of-range parameters: strength, iterations and tolerance are all input-derived.
for strength in [0.0, -0.25, 1.000_001, f64::NAN, f64::INFINITY] {
assert!(FairOptions::new(strength, 4, false, 10.0).is_err(), "strength {strength}");
}
for iterations in [0, MAX_FAIR_ITERATIONS + 1, usize::MAX] {
assert!(FairOptions::new(1.0, iterations, false, 10.0).is_err(), "iterations {iterations}");
}
for tolerance in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert!(FairOptions::new(1.0, 4, false, tolerance).is_err(), "tolerance {tolerance}");
}
// A control point that is not a finite number.
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let mut nan = ctrl.clone();
nan[2][1] = bad;
assert!(fair_curve(3, &knots, &nan, &ok).is_err(), "a control point of {bad} was faired");
}
// Knot vectors that do not fit the control points or the degree.
assert!(fair_curve(3, &knots[..9], &ctrl, &ok).is_err(), "nine knots for six control points of degree three");
assert!(fair_curve(3, &[0.0, 0.0, 0.0, 0.0, 2.0, 1.0, 3.0, 4.0, 4.0, 4.0], &ctrl, &ok).is_err(), "knots that decrease");
assert!(fair_curve(3, &vec![f64::NAN; knots.len()], &ctrl, &ok).is_err(), "a knot that is not a number");
assert!(fair_curve(9, &knots, &ctrl, &ok).is_err(), "a degree above the supported maximum");
// Fewer than two interior control points: one free point (a triangle of a quadratic), and
// a 3 × 3 net whose two edge layers leave nothing at all.
let triangle = [[0.0, 0.0, 0.0], [5.0, 2.0, 0.0], [10.0, 0.0, 1.0]];
let one = fair_curve(2, &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], &triangle, &ok).unwrap_err();
assert!(one.to_string().contains("at least two interior"), "{one}");
let flat = [0.0, 0.0, 1.0, 2.0, 2.0];
let grid = [[0.0, 0.0, 0.0]; 9];
let kept = FairOptions::new(1.0, 4, true, 1.0).unwrap();
assert!(
fair_net([1, 1], [&flat, &flat], &Grid::from_fn([3, 3], |i, j| grid[j * 3 + i]).unwrap(), &kept).is_err(),
"keep_edges on a 3 × 3 net"
);
// A net too large to fair, refused before anything is allocated for it.
let line = [0.0, 0.0, 1.0, 1.0];
let huge = fair_net([1, 1], [&line, &line], &Grid::from_fn([129, 129], |_, _| [0.0; 3]).unwrap(), &ok).unwrap_err();
assert!(matches!(huge, KernelError::TooLarge(_)), "16641 control points: {huge}");
// A singular system: a cubic whose last control points lie past the end of its domain
// (0.5), where they do not move the curve at all, so the interior equations have no
// unique solution and the run must refuse rather than move anything.
let odd = [0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0];
let six: Vec<[f64; 3]> = (0..6).map(|i| [i as f64, 0.0, 1.0]).collect();
let singular = fair_curve(3, &odd, &six, &ok).unwrap_err();
eprintln!("hostile inputs: refused with {singular}");
assert!(singular.to_string().contains("singular"), "{singular}");
}
#[test]
fn a_small_quadratic_net_and_a_quintic_curve_fair_the_same_way() {
// Degrees and band shapes away from the bicubic case. A 5 × 5 quadratic net has fewer
// rows than the degree, so the solver's band is narrower than `degree_u + degree_v · cols`
// (the coupling cannot reach that far in v); a quintic curve carries six basis functions
// per span instead of four. Both must reproduce a zero-energy shape exactly.
let (ku, kv) = (clamped(3, 2), clamped(3, 2));
let degree = [2, 2];
let (cu, cv) = (ku.len() - 3, kv.len() - 3);
assert_eq!((cu, cv), (5, 5));
let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [12.0, 1.0, 0.0], [-2.0, 9.0, 0.0]);
let mut rough = smooth.clone();
for &(i, j, d) in &[(1usize, 2usize, 2.5), (2, 2, -1.5), (3, 3, 3.0), (2, 1, -2.0)] {
rough[j * cu + i][2] += d;
}
let faired = fair_net(
degree,
[&ku, &kv],
&Grid::from_fn([cu, cv], |i, j| rough[j * cu + i]).unwrap(),
&FairOptions::new(1.0, 8, false, 100.0).unwrap(),
)
.unwrap();
let near = faired.ctrl.cells().iter().zip(&smooth).map(|(a, b)| dist(a, b)).fold(0.0, f64::max);
eprintln!("5 × 5 quadratic net: faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after);
assert!(near < 1e-6 && faired.report.energy_after < 1e-9 * faired.report.energy_before);
for j in 0..cv {
for i in 0..cu {
if i == 0 || i + 1 == cu || j == 0 || j + 1 == cv {
assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "({i}, {j}) is on the boundary and moved");
}
}
}
// A quintic curve, its middle pulled out.
let knots = clamped(3, 5);
let smooth = affine_curve(&knots, 5, [-10.0, 0.0, 2.0], [6.0, 4.0, -1.0]);
let mut rough = smooth.clone();
rough[3][1] += 3.0;
rough[4][2] -= 2.0;
let faired = fair_curve(5, &knots, &rough, &FairOptions::new(1.0, 8, false, 100.0).unwrap()).unwrap();
let near = (1..smooth.len() - 1).map(|i| dist(&faired.ctrl[i], &smooth[i])).fold(0.0, f64::max);
eprintln!("quintic curve: faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after);
assert!(near < 1e-6 && faired.report.energy_after < 1e-9 * faired.report.energy_before);
assert_eq!(faired.ctrl[0], rough[0]);
assert_eq!(faired.ctrl[rough.len() - 1], rough[rough.len() - 1]);
}
#[test]
fn a_net_of_degree_one_across_fairs_along_its_curved_direction_only() {
// Cubic along u, linear across v over two spans (three rows): `S_vv` is zero on every
// span, so only the bending along u and the twist count. A plane's net bumped at its
// middle row fairs back to the plane, the boundary rows bit-identical.
let (ku, kv) = (clamped(3, 3), vec![0.0, 0.0, 1.0, 2.0, 2.0]);
let degree = [3, 1];
let (cu, cv) = (ku.len() - 4, kv.len() - 2);
assert_eq!((cu, cv), (6, 3));
let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [30.0, 0.0, 0.0], [0.0, 20.0, 4.0]);
let mut rough = smooth.clone();
rough[cu + 2][2] += 2.0;
rough[cu + 3][2] -= 1.0;
let faired = fair_net(
degree,
[&ku, &kv],
&Grid::from_fn([cu, cv], |i, j| rough[j * cu + i]).unwrap(),
&FairOptions::new(1.0, 8, false, 100.0).unwrap(),
)
.unwrap();
let near = faired.ctrl.cells().iter().zip(&smooth).map(|(a, b)| dist(a, b)).fold(0.0, f64::max);
eprintln!("degree 3 × 1 net: faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after);
assert!(near < 1e-6 && faired.report.energy_after < 1e-9 * faired.report.energy_before);
for i in 0..cu {
for j in [0, cv - 1] {
assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "({i}, {j}) is on the boundary and moved");
}
}
}
#[test]
fn a_face_whose_edges_hold_its_whole_net_is_left_as_it_is() {
// A single-span bicubic with its edges kept: every row is a boundary row or the one next
// to it, so there is nothing to move. The run succeeds, the body is the one it was and
// the report says no step was taken.
let (ku, kv) = (clamped(1, 3), clamped(1, 3));
let mut net = planar_net(&ku, &kv, [3, 3], [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]);
net[5][2] += 2.0;
let body = sheet(&ku, &kv, &net);
let (faired, report) = fair_faces(&body, &[0], &FairOptions::new(1.0, 10, true, 1.0).unwrap()).unwrap();
eprintln!("held face: energy {:e} → {:e}, {} steps", report.energy_before, report.energy_after, report.steps);
assert_eq!(face_surface(&faired, 0), face_surface(&body, 0));
assert_eq!(edge_records(&faired), edge_records(&body));
assert_eq!((report.steps, report.movement), (0, 0.0));
assert!(report.energy_before > 0.0 && report.energy_after == report.energy_before);
}
/// A one-face sheet body of the bicubic surface `net` (u fastest) over the clamped knots `ku`
/// and `kv`, its sides the straight lines between the surface's corners — true while the
/// net's boundary rows describe lines, which is how a plane's control net is built here.
fn sheet(ku: &[f64], kv: &[f64], net: &[[f64; 3]]) -> Body {
use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble};
let (cu, cv) = (ku.len() - 4, kv.len() - 4);
assert_eq!(net.len(), cu * cv, "the net does not fit the knots");
let points: Vec<Vec<[f64; 3]>> = (0..cu).map(|i| (0..cv).map(|j| net[j * cu + i]).collect()).collect();
let surface = b::Surface::Spline { u_knots: ku.to_vec(), v_knots: kv.to_vec(), points };
let corners = [(0, 0), (cu - 1, 0), (cu - 1, cv - 1), (0, cv - 1)];
let (u, v) = ([ku[3], ku[cu]], [kv[3], kv[cv]]);
let uv = [[u[0], v[0]], [u[1], v[0]], [u[1], v[1]], [u[0], v[1]]];
let vertices: Vec<[f64; 3]> = corners.iter().map(|&(i, j)| net[j * cu + i]).collect();
let edges = (0..4)
.map(|k| PartEdge {
nurbs: None,
curve: b::Curve::Line { start: vertices[k], end: vertices[(k + 1) % 4] },
interval: [0.0, 1.0],
vertices: [k as u32, ((k + 1) % 4) as u32],
})
.collect();
let loops = vec![
(0..4)
.map(|k| PartUse {
edge: k as u32,
forward: true,
given: Some(b::Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![uv[k], uv[(k + 1) % 4]] }),
})
.collect(),
];
let made = assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops }], tolerance: 1e-6 }, false).unwrap();
crate::native::body_from_smlib(&solidcraft_smlib::Brep::from_record(&made.brep, true).unwrap()).unwrap()
}
/// Each edge of the body's record: its curve, interval and vertices.
fn edge_records(body: &Body) -> Vec<(b::Curve, [f64; 2], [u32; 2])> {
crate::native::brep_record(body).unwrap().edges.into_iter().map(|e| (e.curve, e.interval, e.vertices)).collect()
}
/// The surface of face `i` of the body's record.
fn face_surface(body: &Body, i: usize) -> b::Surface {
crate::native::brep_record(body).unwrap().faces[i].surface.clone()
}
#[test]
fn a_body_face_is_faired_with_its_edges_untouched_and_its_history_kept() {
// A sheet whose middle is bumped: fairing the face must smooth it without moving a single
// edge, vertex or neighbouring face of the body, and must leave a history saying so.
let (ku, kv) = (clamped(3, 3), clamped(3, 3));
let (cu, cv) = (ku.len() - 4, kv.len() - 4);
let smooth = planar_net(&ku, &kv, [3, 3], [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]);
let mut rough = smooth.clone();
for &(i, j, d) in &[(2usize, 2usize, 3.0), (3, 3, -2.0), (2, 3, 1.5)] {
rough[j * cu + i][2] += d;
}
let body = sheet(&ku, &kv, &rough);
let before = edge_records(&body);
assert!(!before.is_empty());
let (faired, report) = fair_faces(&body, &[0], &FairOptions::new(1.0, 6, false, 50.0).unwrap()).unwrap();
let after = edge_records(&faired);
eprintln!(
"face: energy {:e} → {:e} in {} steps, movement {:e} mm, {} faces, history {}",
report.energy_before,
report.energy_after,
report.steps,
report.movement,
faired.face_count(),
faired.history().is_some()
);
assert_eq!(before, after, "the body's edges must be the very ones it had");
assert_eq!(faired.face_count(), 1);
assert!(faired.history().is_some(), "the face came from the one it was faired from");
assert!(report.energy_after < 1e-9 * report.energy_before);
// The face's own surface is back on the plane, boundary rows bit for bit as they were.
let b::Surface::Spline { points, .. } = face_surface(&faired, 0) else { panic!("a B-spline face") };
for j in 0..cv {
for i in 0..cu {
let p = points[i][j];
let want = if i == 0 || i + 1 == cu || j == 0 || j + 1 == cv { rough[j * cu + i] } else { smooth[j * cu + i] };
assert!(dist(&p, &want) < 1e-6, "({i}, {j})");
}
}
// A solid keeps its shells, its faces and its edges: thickening the sheet gives a closed
// body whose top face is still the B-spline one, and fairing that face leaves the body a
// solid of the same shape.
let solid = crate::thicken(&body, 2.0, false).unwrap();
assert!(!solid.is_surface());
let top = (0..solid.face_count()).find(|&i| matches!(face_surface(&solid, i), b::Surface::Spline { .. }));
let Some(top) = top else { panic!("the thickened sheet keeps its B-spline face") };
let edges = edge_records(&solid);
let (faired, report) = fair_faces(&solid, &[top], &FairOptions::new(1.0, 6, false, 0.5).unwrap()).unwrap();
eprintln!("thickened solid: energy {:e} → {:e}, movement {:e} mm", report.energy_before, report.energy_after, report.movement);
assert!(!faired.is_surface() && faired.face_count() == solid.face_count() && faired.shell_count() == solid.shell_count());
assert_eq!(edge_records(&faired), edges);
assert!(report.energy_after < report.energy_before);
// A face with no control points to fair is refused, by name.
let cube = crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap();
let refused = fair_faces(&cube, &[0], &FairOptions::new(1.0, 1, false, 1.0).unwrap()).unwrap_err();
eprintln!("cube face: {refused}");
assert!(refused.to_string().contains("not a B-spline face"), "{refused}");
assert!(fair_faces(&body, &[7], &FairOptions::new(1.0, 1, false, 1.0).unwrap()).is_err(), "no such face");
assert!(fair_faces(&body, &[], &FairOptions::new(1.0, 1, false, 1.0).unwrap()).is_err(), "no face picked");
}
#[test]
fn an_already_fair_curve_is_left_where_it_is() {
// Zero bending energy, no reason to move: nothing churns, and an input at the minimum
// cannot be faired into a worse shape.
let knots = clamped(4, 3);
let smooth = affine_curve(&knots, 3, [1.0, 2.0, 3.0], [5.0, -1.0, 0.5]);
let opts = FairOptions::new(1.0, 20, false, 10.0).unwrap();
let faired = fair_curve(3, &knots, &smooth, &opts).unwrap();
eprintln!(
"already fair: energy {:e} → {:e}, {} steps, {:e} mm",
faired.report.energy_before, faired.report.energy_after, faired.report.steps, faired.report.movement
);
assert!(faired.report.energy_after <= faired.report.energy_before);
assert!(faired.report.energy_after >= 0.0);
assert!(faired.report.movement < 1e-9, "{:e}", faired.report.movement);
for (i, want) in smooth.iter().enumerate() {
assert!(dist(&faired.ctrl[i], want) < 1e-9, "control point {i}");
}
}
}