Files
makeCAD/crates/doc/src/eval.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

8742 lines
434 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.
//! Timeline evaluation.
#[path = "placed_mesh.rs"]
mod placed_mesh;
#[path = "placement_reuse.rs"]
mod placement_reuse;
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock};
use serde::{Deserialize, Serialize};
use solidcraft_geom::brep::part::Contact;
use solidcraft_geom::tess::TessPlan;
use solidcraft_geom::{Mesh, Plane, Region2, UnitVec3, Vec2, Vec3, regions_apart};
use solidcraft_kernel::{self as kernel, Body, BoolOp};
use solidcraft_sketch::{CurveKind, Profile, SolveReport, find_profiles};
use crate::expr::{self, Kind, Value};
use crate::lineage::Traced;
use crate::{AxisRef, DocError, Document, Feature, FeatureId, FeatureKind, HoleKind, Operation, PlaneRef, ProfileSel, Result};
type JointFaces = (Body, kernel::Result<Arc<[kernel::FaceInfo]>>);
/// A body's isoparametric curves worked out so far ([`ModelBody::iso_lines`]), with the body they
/// were worked out on: by face, count each way and display quality.
type IsoLines = (Option<Body>, std::collections::HashMap<(usize, usize, usize), Arc<[kernel::IsoLine]>>);
/// A body in the evaluated model.
#[derive(Clone, Debug)]
pub struct ModelBody {
pub name: String,
/// Definition identity for a computed placement; never parsed from its display name.
pub source_name: Option<String>,
/// Definition geometry coordinates to this computed body's frame.
pub source_transform: crate::Mat,
pub body: Body,
/// Feature that created it.
pub feature: u64,
// Timeline snapshots are cloned before meshes are requested. Share the cell itself so
// meshing any snapshot also warms every unchanged copy of this body.
mesh: Arc<OnceLock<Arc<Mesh>>>,
/// Joint face measurements use their own tolerance, independent of display quality.
/// Shared by snapshots of this geometry; the body identity guards direct replacement.
joint_faces: Arc<OnceLock<JointFaces>>,
/// Lazy canonical reference triangles for a proper rigid occurrence placement.
mesh_placement: Option<Arc<placed_mesh::PlacedMesh>>,
/// For a mirrored copy: its faces as a world state shows them, a rigid move of the source's
/// [`placed_mesh::OppositeHand`]. Display only: the model reads the copy's own triangles.
mirrored_mesh: Option<Arc<placed_mesh::PlacedMesh>>,
/// The first mirrored copy made of this body, shared by its clones.
opposite_hand: Arc<OnceLock<placed_mesh::OppositeHand>>,
/// The display plan (none when the body has no plan: a mesh body, or one the planner
/// refuses), shared like the mesh. A GPU viewport draws it.
plan: Arc<[OnceLock<Option<Arc<TessPlan>>>; 4]>,
/// The plan evaluated on the CPU (none without a plan), shared like the mesh: the triangles a
/// GPU viewport draws, so a highlight over a face lies exactly on it.
plan_mesh: Arc<[OnceLock<Option<Arc<Mesh>>>; 4]>,
/// Identity of this body's content for the evaluation cache: the key of the evaluation
/// that produced it (kept while later features pass it through unchanged).
key: u64,
/// Persistent face names (worked out on first use).
pub(crate) names: crate::naming::NameCell,
/// How the feature being evaluated made or changed it (read when its names are set up).
pub(crate) made: crate::lineage::Made,
/// The component the body belongs to (set after each feature).
pub component: u64,
/// A timeline transfer has converted this body into its evaluated owner's frame.
pub transferred: bool,
/// The look it was imported with, carried through later features.
pub imported: Option<Arc<crate::appearance::ImportedLook>>,
/// [`Body::retained_bytes`] of `body`, measured when a feature made or changed it (0: not
/// measured), so the evaluation cache's budget does not walk every body after every feature.
bytes: usize,
/// In a world state: the [`ModelBody::geometry_key`] of the model body this one places (0: none).
source_key: u64,
/// [`Body::outline_bounds`] of `body` (with the body it was measured on), worked out once
/// and shared by clones.
outline: Arc<OnceLock<(Body, solidcraft_geom::Aabb3)>>,
/// [`kernel::measure`] of `body` (with the body it was measured on), worked out once and
/// shared by clones: inspecting a design again measures only the bodies that changed.
measured: Arc<OnceLock<(Body, kernel::Result<kernel::BodyMeasure>)>>,
/// Whether `body` is open (with the body it was measured on): a B-rep one a surface body
/// ([`Body::is_surface`]), a mesh one with a side only one triangle has
/// ([`Body::is_closed_mesh`]); worked out once and shared by clones.
surface: Arc<OnceLock<(Body, bool)>>,
/// [`ModelBody::iso_lines`] worked out so far, shared by clones.
iso: Arc<std::sync::Mutex<IsoLines>>,
}
impl ModelBody {
pub fn new(name: String, body: Body, feature: u64) -> Self {
ModelBody {
name,
source_name: None,
source_transform: crate::IDENTITY,
body,
feature,
mesh: Arc::new(OnceLock::new()),
joint_faces: Arc::new(OnceLock::new()),
mesh_placement: None,
mirrored_mesh: None,
opposite_hand: Arc::new(OnceLock::new()),
plan: Arc::new(Default::default()),
plan_mesh: Arc::new(Default::default()),
key: 0,
names: Default::default(),
made: Default::default(),
component: 0,
transferred: false,
imported: None,
bytes: 0,
source_key: 0,
outline: Arc::new(OnceLock::new()),
measured: Arc::new(OnceLock::new()),
surface: Arc::new(OnceLock::new()),
iso: Default::default(),
}
}
/// A surface body: some shell does not close ([`Body::is_surface`]), worked out once.
pub fn is_surface(&self) -> bool {
!self.body.is_mesh() && self.is_open()
}
/// The body encloses a volume: a solid whose shells all close ([`ModelBody::is_surface`]),
/// or a mesh body every side of which two triangles share ([`Body::is_closed_mesh`]).
/// Worked out once.
pub fn is_closed(&self) -> bool {
!self.is_open()
}
fn is_open(&self) -> bool {
let open = |b: &Body| if b.is_mesh() { !b.is_closed_mesh() } else { b.is_surface() };
match self.surface.get_or_init(|| (self.body.clone(), open(&self.body))) {
(measured, s) if measured.same(&self.body) => *s,
// The body was replaced in this cell's holder since: look again.
_ => open(&self.body),
}
}
/// Face measurements for joint origins, at their original chord tolerance. Pose changes
/// and scratch copies share them; a geometry edit makes a new body and cache.
pub(crate) fn joint_faces(&self) -> Result<Arc<[kernel::FaceInfo]>> {
let measure = || {
#[cfg(test)]
cost_tests::count(|c| c.joint_faces += 1);
let tol = (self.body.size() * 2e-3).max(1e-3);
self.body.faces(tol).map(Arc::from)
};
let (body, faces) = self.joint_faces.get_or_init(|| (self.body.clone(), measure()));
if body.same(&self.body) { faces.clone().map_err(Into::into) } else { measure().map_err(Into::into) }
}
/// A box around the body without meshing it ([`Body::outline_bounds`]), worked out once.
pub fn outline_bounds(&self) -> solidcraft_geom::Aabb3 {
match self.outline.get_or_init(|| (self.body.clone(), self.body.outline_bounds())) {
(measured, b) if measured.same(&self.body) => *b,
// The body was replaced in this cell's holder since: measure it again.
_ => self.body.outline_bounds(),
}
}
/// [`kernel::measure`] of the body (volume, area, centre of mass, box and topology), worked
/// out once: snapshots and passed-through copies of this geometry share it.
pub fn measure(&self) -> kernel::Result<kernel::BodyMeasure> {
let measure = || {
#[cfg(test)]
cost_tests::count(|c| c.measures += 1);
kernel::measure(&self.body)
};
let (body, m) = self.measured.get_or_init(|| (self.body.clone(), measure()));
// The body was replaced in this cell's holder since: measure it again.
if body.same(&self.body) { m.clone() } else { measure() }
}
/// Identity of this body's geometry where it stands: the same for a body evaluated or
/// placed again from the same inputs at the same place, so work measured on it can be
/// reused (none for a body the evaluation cache does not key).
pub fn geometry_key(&self) -> Option<u64> {
use std::hash::{Hash, Hasher};
let key = if self.key != 0 { self.key } else { self.source_key };
if key == 0 {
return None;
}
let mut h = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut h);
self.source_transform.iter().flatten().for_each(|v| v.to_bits().hash(&mut h));
Some(h.finish())
}
pub fn definition_name(&self) -> &str {
self.source_name.as_deref().unwrap_or(&self.name)
}
/// Display mesh, computed once: chord tolerance 1/1000 of the body size, and no facet of a
/// curved face or edge turning more than [`kernel::DISPLAY_ANGLE`], so that a bend or a
/// hole that is small beside the body is still drawn round.
pub fn mesh(&self) -> Arc<Mesh> {
// From the reference mesher, not the display plan: the model reads this mesh (holes
// finding their surface, picks naming their face, sketch planes), and a different
// triangulation moved those and changed what designs build. A GPU viewport draws the
// plan ([`ModelBody::display_plan`]).
if let Some(mesh) = self.mesh.get() {
return mesh.clone();
}
match self.mesh_placement.as_deref() {
Some(placed) => self.mesh.get_or_init(|| placed.mesh()).clone(),
None => placed_mesh::reference_mesh(&self.body, &self.mesh, self.display_tol()),
}
}
/// The display plan of this body at the viewport's display quality
/// ([`crate::display_quality::current`]; at Normal, the same tolerance and angle as
/// [`ModelBody::mesh`]), made once per level; `None` when the body has no plan (a mesh body,
/// or one the planner refuses).
pub fn display_plan(&self) -> Option<Arc<TessPlan>> {
self.display_plan_at(crate::display_quality::current())
}
/// The display plan at a given display quality, made once per level.
pub fn display_plan_at(&self, q: crate::display_quality::DisplayQuality) -> Option<Arc<TessPlan>> {
let cell = self.plan.get(q.index())?;
match self.mesh_placement.as_deref() {
// A placed part shows its definition's plan, moved (planned once for every placement).
Some(placed) => cell.get_or_init(|| placed.plan(q, &self.name)).clone(),
None => placed_mesh::definition_plan(&self.body, cell, q, &self.name),
}
}
/// The display plan's mesh, evaluated on the CPU once per level: the same triangles a GPU
/// viewport evaluates and draws for this body. Highlights over a face drawn from the plan use
/// it, since the reference mesh ([`ModelBody::mesh`]) triangulates the face differently and
/// the two would fight at equal depth. `None` when the body has no plan.
pub fn plan_mesh(&self) -> Option<Arc<Mesh>> {
self.plan_mesh_at(crate::display_quality::current())
}
/// The display plan's mesh at a given display quality.
pub fn plan_mesh_at(&self, q: crate::display_quality::DisplayQuality) -> Option<Arc<Mesh>> {
self.plan_mesh
.get(q.index())?
.get_or_init(|| match self.mesh_placement.as_deref() {
Some(placed) => placed.plan_mesh(q, &self.name),
None => self.display_plan_at(q).and_then(|plan| self.body.mesh_of(&plan).ok()).map(Arc::new),
})
.clone()
}
/// Identity of this body's display geometry, without meshing it: the cell its mesh is kept
/// in, shared by every clone of the body (timeline snapshots, world states that place it
/// unchanged) and, while it is held, by no other body.
pub fn display_identity(&self) -> Arc<dyn std::any::Any + Send + Sync> {
self.mesh.clone()
}
/// [`ModelBody::mesh`] as a shared mesh and the move that places it: for a rigid placement
/// of a definition, the definition's own mesh (the same one for every placement of it) and
/// the placement; for any other body its own mesh, unmoved. The mesh moved by the matrix is
/// `mesh()`, so a viewport can draw every placement of a part from one copy of its
/// triangles, without making the moved copies.
pub fn mesh_in_place(&self) -> (Arc<Mesh>, crate::Mat) {
match self.mesh_placement.as_deref() {
Some(placed) => placed.source_mesh(),
None => (self.mesh(), crate::IDENTITY),
}
}
/// The box of [`ModelBody::mesh`] without making a placement's moved copy: the shared mesh's
/// points, moved.
pub fn mesh_bounds(&self) -> solidcraft_geom::Aabb3 {
if let Some(mesh) = self.cached_mesh() {
return mesh.bounds();
}
let (mesh, m) = self.mesh_in_place();
if crate::is_identity(&m) {
return mesh.bounds();
}
mesh.positions.iter().fold(solidcraft_geom::Aabb3::EMPTY, |mut b, p| {
b.add(crate::apply_point(&m, *p));
b
})
}
/// [`ModelBody::plan_mesh_at`] as a shared mesh and the move that places it, as
/// [`ModelBody::mesh_in_place`] does for the reference mesh.
pub fn plan_mesh_in_place_at(&self, q: crate::display_quality::DisplayQuality) -> Option<(Arc<Mesh>, crate::Mat)> {
match self.mesh_placement.as_deref() {
Some(placed) => placed.source_plan_mesh(q, &self.name),
None => Some((self.plan_mesh_at(q)?, crate::IDENTITY)),
}
}
/// [`ModelBody::plan_mesh`] if it is made already; otherwise it is made on a worker thread
/// (once, however often this is asked) and `None` comes back meanwhile, so a caller drawing a
/// frame (a face highlighted under the pointer) is not held up by a large body's plan
/// (#3745): the plan mesh of a long modelled thread takes most of a second. The browser
/// build has no threads: there it is made now.
pub fn plan_mesh_soon(&self) -> Option<Arc<Mesh>> {
let q = crate::display_quality::current();
let cell = self.plan_mesh.get(q.index())?;
if let Some(mesh) = cell.get() {
return mesh.clone();
}
#[cfg(not(target_arch = "wasm32"))]
{
static WARMING: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
let key = Arc::as_ptr(&self.plan_mesh) as usize + q.index();
let Ok(mut warming) = WARMING.lock() else { return None };
if warming.contains(&key) {
return None;
}
let body = self.clone();
let started = std::thread::Builder::new().name("plan-mesh".into()).spawn(move || {
let _ = body.plan_mesh_at(q);
if let Ok(mut warming) = WARMING.lock() {
warming.retain(|k| *k != key);
}
});
if started.is_ok() {
warming.push(key);
return None;
}
}
self.plan_mesh_at(q)
}
/// The display plan and its mesh `k` steps finer than `q` (view-dependent refinement, #1320;
/// see [`crate::display_quality::refinement_for`]). Step 0 is the cached plan at `q`; finer
/// steps are made on each call and kept by the viewport, which evicts them when it runs over
/// its budget. `None` when the body has no plan at that step.
pub fn refined_display(&self, q: crate::display_quality::DisplayQuality, k: u8) -> Option<(Arc<TessPlan>, Arc<Mesh>)> {
if k == 0 {
return Some((self.display_plan_at(q)?, self.plan_mesh_at(q)?));
}
let plan = match self
.body
.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: q.refined_chord(self.body.size(), k), angle: Some(q.refined_angle(k)) })
{
Ok(plan) => plan,
Err(e) => {
log::debug!("{}: no display plan refined {k} steps ({e})", self.name);
return None;
}
};
let mesh = self.body.mesh_of(&plan).ok()?;
Some((Arc::new(plan), Arc::new(mesh)))
}
/// The chord tolerance of [`ModelBody::mesh`] (mm): 1/1000 of the definition's size, at least
/// 1 µm. Proper rigid placements retain that tolerance along with the reference triangles.
pub fn display_tol(&self) -> f64 {
self.mesh_placement.as_ref().map(|placed| placed.tolerance).unwrap_or_else(|| (self.body.size() * 1e-3).max(1e-3))
}
/// Already computed display geometry; saving must not trigger cold tessellation.
pub fn cached_mesh(&self) -> Option<Arc<Mesh>> {
self.mesh.get().cloned()
}
/// The isoparametric curves of face `face` for Isocurve Analysis: `count` each way, evenly
/// spaced across the face (faces on one surface spaced together, so they share them), exact
/// and cut to its trims ([`kernel::iso_grid`]), their points at the chord
/// tolerance of the viewport's display quality. Worked out once per face, count and display
/// quality, and shared by every clone of this body (timeline snapshots, world states). A mesh
/// body has no surfaces, so none.
pub fn iso_lines(&self, face: usize, count: usize) -> Result<Arc<[kernel::IsoLine]>> {
if self.body.is_mesh() {
return Err(DocError::Invalid(format!("{} is a mesh body: its faces have no surface parameters, so no isoparametric curves", self.name)));
}
let quality = crate::display_quality::current();
let key = (face, count, quality.index());
let make = || kernel::iso_grid(&self.body, face, count, quality.chord(self.body.size())).map(Arc::from);
let Ok(mut cache) = self.iso.lock() else { return Ok(make()?) };
if !cache.0.as_ref().is_some_and(|b| b.same(&self.body)) {
// A body replaced in this cell's holder since: what was worked out was on another.
*cache = (Some(self.body.clone()), Default::default());
}
if let Some(lines) = cache.1.get(&key) {
return Ok(lines.clone());
}
let lines = make()?;
cache.1.insert(key, lines.clone());
Ok(lines)
}
}
/// A solved sketch in the evaluated model.
#[derive(Clone, Debug)]
pub struct SolvedSketch {
pub feature: u64,
pub name: String,
pub plane: Plane,
pub sketch: solidcraft_sketch::Sketch,
pub report: SolveReport,
pub profiles: Vec<Profile>,
/// Open and untied ends of its profile curves (where a profile can fail).
pub ends: solidcraft_sketch::EndReport,
}
/// A constant fillet of `edges`; with [`FilletFit::Reduce`](crate::FilletFit::Reduce), a radius too
/// large for the geometry around them is reduced where it doesn't fit, to the largest that works
/// for each group of edges sharing a face; the radius per edge is returned. With
/// [`FilletFit::Taper`](crate::FilletFit::Taper) it tapers along each edge it doesn't fit. With
/// the exact fit a radius too large is refused, naming the largest that fits ([`with_largest_fit`]).
/// Also the picks whose edges a round overflowing its faces removed whole ([`kernel::fillet_removing`]).
fn fillet_fitted(
body: &kernel::Body,
edges: &[Vec3],
r: f64,
fit: crate::FilletFit,
) -> std::result::Result<(kernel::Body, Option<Vec<f64>>, Vec<Vec3>), kernel::KernelError> {
match kernel::fillet_removing(body, edges, r) {
Ok((b, gone)) => Ok((b, None, gone)),
Err(kernel::KernelError::TooLarge(why)) if fit == crate::FilletFit::Exact => {
Err(with_largest_fit(why, "radius", || kernel::fillet_max(body, edges, r)))
}
Err(kernel::KernelError::TooLarge(why)) if fit == crate::FilletFit::Reduce => match kernel::fillet_max_each(body, edges, r)? {
// Built at the radius asked for after all (the groups apart): nothing reduced.
Some((used, b)) => Ok((b, used.iter().any(|u| *u < r).then_some(used), Vec::new())),
None => Err(kernel::KernelError::TooLarge(why)),
},
Err(kernel::KernelError::TooLarge(_)) if fit == crate::FilletFit::Taper => {
kernel::fillet_tapered(body, edges, r).map(|(b, _)| (b, None, Vec::new()))
}
Err(e) => Err(e),
}
}
/// The warning of a fillet some of whose edges a larger round, overflowing its faces, removed
/// whole: they are gone, so they are not rounded.
fn removed_note(gone: &[Vec3]) -> String {
let at = |p: &Vec3| format!("({}, {}, {})", show_mm(p.x), show_mm(p.y), show_mm(p.z));
match gone {
[one] => format!("the edge at {} was removed by the larger round, so it is not rounded", at(one)),
_ => format!("the edges at {} were removed by the larger round, so they are not rounded", gone.iter().map(at).collect::<Vec<_>>().join(", ")),
}
}
/// A blend's refusal as too large (`why`) with the largest `size` (radius, distance) that fits,
/// as `search` finds it by building candidates ([`kernel::fillet_max`]): the refusal as it is
/// when none fits or the search itself fails (a candidate failing for another reason says
/// nothing about the size).
fn with_largest_fit(
why: String,
size: &str,
search: impl FnOnce() -> std::result::Result<Option<(f64, kernel::Body)>, kernel::KernelError>,
) -> kernel::KernelError {
match search() {
Ok(Some((largest, _))) => kernel::KernelError::TooLarge(format!("{why}; the largest {size} that fits is {} mm", show_mm(largest))),
Ok(None) => kernel::KernelError::TooLarge(why),
Err(e) => {
log::debug!("the largest {size} that fits: {e}");
kernel::KernelError::TooLarge(why)
}
}
}
/// The warning of a fillet whose radius `asked` was reduced to `used` (per edge).
fn reduced_note(used: &[f64], asked: f64) -> String {
let mut values: Vec<f64> = used.iter().copied().filter(|r| *r < asked).collect();
values.sort_by(f64::total_cmp);
values.dedup();
let shown = values.iter().map(|v| show_mm(*v)).collect::<Vec<_>>().join(", ");
let n = used.iter().filter(|r| **r < asked).count();
if n == used.len() && values.len() == 1 {
format!("the radius is reduced to {shown} mm, the largest that fits these edges")
} else {
format!("the radius is reduced to {shown} mm on {n} of {} edges, the largest that fits them", used.len())
}
}
/// The warning of a fillet that tapered on some of its edges (a taper per edge, None where the
/// radius is constant), naming the smallest radius a taper ends at.
fn tapered_note(tapers: &[Option<kernel::Taper>]) -> Option<String> {
let ends: Vec<f64> = tapers.iter().flatten().flat_map(|t| [t.spline.radii.first(), t.spline.radii.last()]).flatten().copied().collect();
let low = ends.into_iter().reduce(f64::min)?;
let n = tapers.iter().flatten().count();
Some(format!("the radius tapers to the room on {n} of {} edges, down to {} mm", tapers.len(), show_mm(low)))
}
/// Blend `edges` one at a time with `blend`, each blend's lineage over the one before: the
/// result and the lineage of what the last blend started from.
fn one_by_one(input: Traced, edges: &[Vec3], blend: impl Fn(&kernel::Body, Vec3) -> kernel::Result<kernel::Body>) -> Result<(kernel::Body, Traced)> {
let mut b = input;
let mut from = None;
for p in edges {
let next = Traced::step(blend(&b.body, *p)?, &[&b]);
from = Some(std::mem::replace(&mut b, next));
}
match from {
Some(prev) => Ok((b.body, prev)),
None => Err(DocError::Invalid("no edges to fillet".into())),
}
}
/// `Posts` for `Posts (1)`: the body a split piece was numbered after.
fn split_piece_of(name: &str) -> Option<&str> {
let (base, n) = name.strip_suffix(')')?.rsplit_once(" (")?;
(!n.starts_with('0') && n.parse::<u32>().is_ok()).then_some(base)
}
/// The warning of a sketch whose profile search was cut short (#6896).
fn profiles_cut_short_note() -> String {
format!("some profiles may be missing: a group of touching curves is cut into more than {} pieces", solidcraft_sketch::MAX_PROFILE_EDGES)
}
/// Add `note` to a feature's warning.
fn append_warning(warning: &mut Option<String>, note: String) {
*warning = Some(match warning.take() {
Some(w) => format!("{w}; {note}"),
None => note,
});
}
/// A length in mm, without trailing zeros.
fn show_mm(v: f64) -> String {
let s = format!("{v:.6}");
s.trim_end_matches('0').trim_end_matches('.').to_string()
}
impl ModelState {
/// The smallest radius fillet `feature` used when it reduced a radius too large for its edges.
pub fn fitted_radius(&self, feature: u64) -> Option<f64> {
self.fitted_range(feature).map(|(lo, _)| lo)
}
/// The smallest and largest radius fillet `feature` used when it reduced a radius too large
/// for some of its edges.
pub fn fitted_range(&self, feature: u64) -> Option<(f64, f64)> {
self.fitted.get(&feature)?.iter().fold(None, |acc, r| Some(acc.map_or((*r, *r), |(lo, hi): (f64, f64)| (lo.min(*r), hi.max(*r)))))
}
/// How the pieces join `feature` split off into bodies of their own touched the others, when
/// it split any off.
pub fn kept_separate(&self, feature: u64) -> Option<KeptSeparate> {
self.kept_separate.get(&feature).copied()
}
/// Each edge fillet `feature` tapered (a point on it) with the radius spline it was given.
pub fn tapered(&self, feature: u64) -> Option<&[(Vec3, kernel::Taper)]> {
self.tapered.get(&feature).map(Vec::as_slice)
}
/// Each edge fillet `feature` blended (a point on it) with the radius it used, when it
/// reduced a radius too large for some of its edges.
pub fn fitted_edges(&self, feature: u64) -> Option<Vec<(Vec3, f64)>> {
let radii = self.fitted.get(&feature)?;
let edges = self.blend_edges.get(&feature)?;
Some(edges.iter().copied().zip(radii.iter().copied()).collect())
}
}
/// Model after some prefix of the timeline.
#[derive(Clone, Debug, Default)]
pub struct ModelState {
/// Frame placements belong to the evaluator. A weak reference avoids a cycle through
/// cached bodies' naming origins, which retain earlier model states.
frame_bodies: std::sync::Weak<std::sync::Mutex<FrameBodies>>,
/// Cosmetic threads (from Thread features and threaded holes).
pub threads: Vec<ThreadInfo>,
pub bodies: Vec<ModelBody>,
/// Shared between states: a feature that does not change a sketch keeps it as it was.
pub sketches: Vec<Arc<SolvedSketch>>,
pub body_counter: usize,
/// Body names the design used and must not use again (a name a `body.rename` freed, #4957),
/// and the names stored on the suppressed features so far, so a body made while a feature is
/// suppressed keeps its name once it is back (#4302). The counter starts over at every
/// evaluation, so without these a design that is evaluated again hands such a name to the next
/// body.
pub reserved_body_names: std::collections::BTreeSet<String>,
/// Sheet metal bodies (by body name) and their flat patterns.
pub sheets: Vec<crate::sheet::SheetBody>,
/// Construction planes, axes and points as evaluated (by feature).
pub construct: Vec<crate::construct::Construct>,
/// Evaluation-cache keys of the sketches (by sketch feature id).
sketch_keys: BTreeMap<u64, u64>,
/// The edges each fillet or chamfer blended, as found in this evaluation (by feature id):
/// a pattern of the feature repeats these, not the points picked when it was made, which a
/// parameter change may have moved off the edges.
blend_edges: BTreeMap<u64, Vec<Vec3>>,
/// The radius per edge a fillet used when it reduced a radius too large for some of its edges
/// (by feature id, see `FilletFit::Reduce`).
fitted: BTreeMap<u64, Vec<f64>>,
/// The radius spline of each edge a fillet tapered (a point on the edge with it, by feature
/// id, see `FilletFit::Taper`).
tapered: BTreeMap<u64, Vec<(Vec3, kernel::Taper)>>,
/// How the pieces a join split off into bodies of their own touched the others (by feature
/// id), for its notice.
kept_separate: BTreeMap<u64, KeptSeparate>,
/// For a feature saved before format 14 that split a body, a digest of the later features'
/// picks its pieces were named by (by feature id, see [`crate::lineage::order_legacy_lumps`]):
/// the state stands for the feature only while those picks are the same.
legacy_picks: BTreeMap<u64, u64>,
}
/// How a piece a join split off into a body of its own (`Touching::Separate`) touched the
/// pieces it was joined with: the most any such piece shared with another, least first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum KeptSeparate {
/// A point.
AtPoint,
/// A line or a point their boundaries don't hold (a face tangent to another): found on the
/// exact geometry, which doesn't say which.
Touching,
/// A curve: an edge of both.
AlongEdge,
}
impl KeptSeparate {
/// Its id in a feature's result: `at_point`, `touching` or `along_edge`.
pub fn id(self) -> &'static str {
match self {
KeptSeparate::AtPoint => "at_point",
KeptSeparate::Touching => "touching",
KeptSeparate::AlongEdge => "along_edge",
}
}
/// What a feature's result says about it.
pub fn notice(self) -> &'static str {
match self {
KeptSeparate::AtPoint => "These bodies only touch at a point, so they were kept as separate bodies.",
KeptSeparate::Touching => "These bodies only touch along a line or at a point, so they were kept as separate bodies.",
KeptSeparate::AlongEdge => "These bodies only touch along an edge, so they were kept as separate bodies.",
}
}
}
impl ModelState {
/// `body` moved by `matrix` into a feature's frame. The evaluator that made this state keeps
/// the moved body, so an unchanged body under an unchanged placement is moved (and meshed)
/// once rather than on every evaluation.
pub(crate) fn body_in_frame(&self, body: &ModelBody, matrix: &Mat) -> Result<ModelBody> {
if crate::is_identity(matrix) {
return Ok(body.clone());
}
let cache = self.frame_bodies.upgrade();
// Not held while the body is moved: copies of the evaluator may share the cache.
let reused = cache.as_ref().and_then(|c| c.lock().unwrap_or_else(|e| e.into_inner()).reused(body, matrix));
let placed = match reused {
Some(placed) => placed,
None => {
let placed = ModelBody::new(body.name.clone(), kernel::transform_matrix(&body.body, *matrix)?, body.feature);
#[cfg(test)]
cost_tests::count(|c| c.moved += 1);
if let Some(c) = &cache {
c.lock().unwrap_or_else(|e| e.into_inner()).keep(body, matrix, &placed);
}
placed
}
};
Ok(in_frame(body, matrix, &placed))
}
/// A digest of everything later features can read: bodies (by content identity), sketches,
/// the body counter, threads and sheet bodies.
fn digest(&self) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
for b in &self.bodies {
b.name.hash(&mut h);
b.key.hash(&mut h);
b.feature.hash(&mut h);
b.component.hash(&mut h);
b.transferred.hash(&mut h);
}
for s in &self.sketches {
s.feature.hash(&mut h);
self.sketch_keys.get(&s.feature).hash(&mut h);
}
self.body_counter.hash(&mut h);
for n in &self.reserved_body_names {
n.hash(&mut h);
}
for (feature, points) in &self.blend_edges {
feature.hash(&mut h);
for p in points {
[p.x, p.y, p.z].map(f64::to_bits).hash(&mut h);
}
}
for (feature, radii) in &self.fitted {
feature.hash(&mut h);
for r in radii {
r.to_bits().hash(&mut h);
}
}
for (feature, tapers) in &self.tapered {
feature.hash(&mut h);
for (p, t) in tapers {
let s = &t.spline;
for x in [p.x, p.y, p.z, t.start.x, t.start.y, t.start.z].iter().chain(&s.knots).chain(&s.radii) {
x.to_bits().hash(&mut h);
}
s.degree.hash(&mut h);
}
}
serde_json::to_string(&self.threads).unwrap_or_default().hash(&mut h);
serde_json::to_string(&self.sheets).unwrap_or_default().hash(&mut h);
h.finish()
}
/// After a feature evaluated to this state from `before` with cache key `key`: bodies it
/// made or changed take that key, sketches it made a digest of their solved geometry (see
/// [`quantize`]); the rest keep theirs.
fn stamp(&mut self, doc: &Document, before: &Arc<ModelState>, f: &Feature, key: u64, mats: Vec<Mat>) {
let feature = f.id;
let depth = before.bodies.iter().filter_map(|b| b.names.depth()).max().unwrap_or(0) + 1;
let sheets = if f.kind.is_sheet() { self.sheets.clone() } else { Vec::new() };
let origin = Arc::new(crate::naming::NamingOrigin { feature: f.clone(), before: before.clone(), depth, mats, sheets });
// Pieces a cut left are named after their faces, not the kernel's shell order (unless
// the feature was saved when they were named in that order).
if !f.shell_piece_order {
crate::lineage::order_lumps(&mut self.bodies, &origin);
} else {
crate::lineage::order_legacy_lumps(&mut self.bodies, before, doc, f);
}
match crate::lineage::legacy_picks_digest(&self.bodies, before, doc, f) {
0 => self.legacy_picks.remove(&f.id),
d => self.legacy_picks.insert(f.id, d),
};
// The bodies before the feature by name, in their order (names repeat only in damaged
// states): every lookup below is the first match of a linear search, without walking
// every earlier body for every body, after every feature.
let mut by_name: std::collections::HashMap<&str, Vec<&ModelBody>> = std::collections::HashMap::with_capacity(before.bodies.len());
for old in &before.bodies {
by_name.entry(old.name.as_str()).or_default().push(old);
}
for b in &mut self.bodies {
let olds: &[&ModelBody] = by_name.get(b.name.as_str()).map(Vec::as_slice).unwrap_or_default();
if !matches!(f.kind, FeatureKind::BodyTransfer { .. })
&& let Some(old) = olds.iter().find(|old| old.transferred)
{
b.transferred = true;
b.component = old.component;
b.source_transform = old.source_transform;
}
let kept = olds.iter().find(|x| x.body.same(&b.body));
match kept {
Some(x) => {
b.key = x.key;
b.names = x.names.clone();
b.bytes = if x.bytes > 0 { x.bytes } else { b.body.retained_bytes() };
}
None => {
let mut h = std::collections::hash_map::DefaultHasher::new();
(key, &b.name).hash(&mut h);
b.key = h.finish();
if !matches!(f.kind, FeatureKind::BodyTransfer { .. }) {
b.names = crate::naming::NameCell::traced(Some(origin.clone()), b.lineage());
}
// Faces split on purpose stay split through later features (for export).
if b.body.split_lines().is_none()
&& let Some(lines) = olds.first().and_then(|x| x.body.split_lines())
{
b.body = b.body.clone().with_split_lines(Some(lines.clone()));
b.mirrored_mesh = None;
}
// An imported look outlives the operations on the body.
if b.body.paint().is_none()
&& b.body.color().is_none()
&& let Some(old) = olds.first()
{
b.imported = crate::appearance::ImportedLook::of(old);
}
b.bytes = b.body.retained_bytes();
}
}
}
// Later features read a sketch's solved geometry: they are keyed by it (to the
// quantum), so a value set back that solves to the same geometry reuses their results.
if let Some(s) = self.sketches.iter().find(|s| s.feature == feature) {
let mut h = std::collections::hash_map::DefaultHasher::new();
serde_json::to_string(&s.plane).unwrap_or_default().hash(&mut h);
let mut sketch = s.sketch.clone();
quantize(&mut sketch);
serde_json::to_string(&sketch).unwrap_or_default().hash(&mut h);
s.report.ok().hash(&mut h);
self.sketch_keys.insert(feature, h.finish());
}
}
}
/// Evaluation results by cache key, shared by a model and its copies (previews, scratch
/// sessions), so a result computed once is reused wherever the same inputs come back.
#[derive(Debug, Default)]
pub struct EvalCache {
map: std::collections::HashMap<u64, CachedEval>,
order: std::collections::VecDeque<u64>,
/// What the stored results cost together.
bytes: usize,
/// The byte budget (0: [`CACHE_BYTES`]).
pub(crate) budget: usize,
pub hits: usize,
}
#[derive(Clone, Debug)]
struct CachedEval {
error: Option<String>,
warning: Option<String>,
import_report: Option<Arc<kernel::ImportReport>>,
repair: Option<Arc<kernel::RepairReport>>,
ms: f64,
state: Arc<ModelState>,
/// What the state costs, worked out once when it was stored (see
/// [`ModelState::retained_bytes`]).
bytes: usize,
}
/// Results kept (oldest dropped first).
const CACHE_ENTRIES: usize = 4096;
/// Bytes of results kept (oldest dropped first). A cached result is as big as the model it
/// holds, so bounding the cache by entry count alone let a long editing session keep every
/// superseded state: the entries nothing else refers to any more are exactly the ones a byte
/// budget drops.
const CACHE_BYTES: usize = 64 << 20;
impl EvalCache {
/// A cache that keeps `bytes` of results (always at least the last one): a small budget
/// stands in for a design whose states are large.
pub fn with_budget(bytes: usize) -> Self {
EvalCache { budget: bytes, ..EvalCache::default() }
}
/// Results stored.
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
fn get(&mut self, key: u64) -> Option<CachedEval> {
let r = self.map.get(&key).cloned();
if r.is_some() {
self.hits += 1;
}
r
}
fn put(&mut self, key: u64, e: CachedEval) {
let bytes = e.bytes;
match self.map.insert(key, e) {
Some(old) => self.bytes = self.bytes.saturating_sub(old.bytes),
None => self.order.push_back(key),
}
self.bytes = self.bytes.saturating_add(bytes);
// One result is always kept, so a single state larger than the budget cannot empty the
// cache and force a full recompute on every undo.
let budget = if self.budget == 0 { CACHE_BYTES } else { self.budget };
while self.order.len() > CACHE_ENTRIES || (self.bytes > budget && self.order.len() > 1) {
if let Some(k) = self.order.pop_front()
&& let Some(old) = self.map.remove(&k)
{
self.bytes = self.bytes.saturating_sub(old.bytes);
}
}
}
}
/// The results an evaluation ahead on a copy of a model computed or took from the cache, kept for
/// the run that follows on the model itself (#1989). The evaluation cache is bounded by bytes and
/// charges every entry its whole model, so on a design with large bodies it holds only the last
/// few states: by the time the run came, the cache had dropped most of what was computed ahead,
/// and the run computed it all again, on the window thread.
#[derive(Debug, Default)]
pub struct KeptResults(std::sync::Mutex<std::collections::HashMap<u64, CachedEval>>);
impl KeptResults {
/// Results kept.
pub fn len(&self) -> usize {
self.0.lock().map_or(0, |m| m.len())
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn get(&self, key: u64) -> Option<CachedEval> {
self.0.lock().ok().and_then(|m| m.get(&key).cloned())
}
fn put(&self, key: u64, e: &CachedEval) {
if let Ok(mut m) = self.0.lock()
&& (m.len() < CACHE_ENTRIES || m.contains_key(&key))
{
m.insert(key, e.clone());
}
}
}
/// Where a model keeps its results besides the cache ([`Model::keep`]). A copy of the model
/// starts without: it keeps nothing it computes for someone else's run.
#[derive(Debug, Default)]
struct KeptSlot(Option<Arc<KeptResults>>);
impl Clone for KeptSlot {
fn clone(&self) -> Self {
KeptSlot(None)
}
}
impl SolvedSketch {
/// The curves `ids` in order along the open chain they make, from one free end to the other,
/// whatever order they were given in. Refused unless they join end to end into one open chain.
pub fn chain_order(&self, ids: &[String]) -> Result<Vec<String>> {
let tol = 1e-5;
let mut ends = Vec::with_capacity(ids.len());
for id in ids {
let ci = self.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("curve `{id}`")))?;
let segs = self.sketch.segs(ci);
let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Err(DocError::Invalid(format!("curve `{id}` has no length"))) };
ends.push((id.clone(), first.start(), last.end()));
}
let joined = |p: Vec2, skip: usize| ends.iter().enumerate().any(|(k, e)| k != skip && (e.1.dist(p) < tol || e.2.dist(p) < tol));
// Start at a curve with a free end, walking away from it.
let Some((start, at)) = ends.iter().enumerate().find_map(|(k, e)| match (joined(e.1, k), joined(e.2, k)) {
(false, _) => Some((k, e.2)),
(_, false) => Some((k, e.1)),
_ => None,
}) else {
return Err(DocError::Invalid("the curves close into a loop: an open chain is needed".into()));
};
let (mut order, mut at) = (vec![start], at);
while order.len() < ends.len() {
let Some((k, e)) = ends.iter().enumerate().find(|(k, e)| !order.contains(k) && (e.1.dist(at) < tol || e.2.dist(at) < tol)) else {
return Err(DocError::Invalid("the curves are not joined end to end into one chain".into()));
};
at = if e.1.dist(at) < tol { e.2 } else { e.1 };
order.push(k);
}
Ok(order.iter().filter_map(|k| ends.get(*k).map(|e| e.0.clone())).collect())
}
/// Rough heap footprint (see [`ModelState::retained_bytes`]).
pub fn retained_bytes(&self) -> usize {
let entities = self.sketch.points.len() + self.sketch.curves.len() + self.sketch.constraints.len() + self.sketch.links.len();
let loops: usize = self.profiles.iter().map(|p| p.region.outer.segs.len() + p.region.holes.iter().map(|h| h.segs.len()).sum::<usize>()).sum();
entities * 192 + loops * 64 + 512
}
}
impl ModelState {
/// Rough heap footprint, for the evaluation cache's byte budget. The bodies' B-rep
/// topology is what makes a kept timeline snapshot expensive, so it dominates; sketches
/// and the rest are counted from their entity counts.
pub fn retained_bytes(&self) -> usize {
let bodies: usize = self.bodies.iter().map(|b| if b.bytes > 0 { b.bytes } else { b.body.retained_bytes() }).sum();
let sketches: usize = self.sketches.iter().map(|s| s.retained_bytes()).sum();
bodies + sketches + self.sheets.len() * 4096 + self.threads.len() * 192 + self.construct.len() * 192
}
/// [`ModelState::retained_bytes`] of what this state holds that `before` does not: bodies
/// and sketches it shares with `before` are already paid for by the cached state that made
/// them. Charging every cached state its whole model let a design whose model is large next
/// to the budget keep only its last few states, so setting a parameter back recomputed what
/// had dropped out.
fn added_bytes(&self, before: &ModelState) -> usize {
// `before`'s bodies by solid, and its sketches by address: looked up per body and sketch,
// not searched (every feature's result is charged, so searching was bodies² per feature).
// Bodies sharing a solid are still told apart by `same_shape` (the mesh as well).
let mut solids: std::collections::HashMap<usize, Vec<&Body>> = std::collections::HashMap::with_capacity(before.bodies.len());
for o in &before.bodies {
solids.entry(o.body.solid_id()).or_default().push(&o.body);
}
let bodies: usize = self
.bodies
.iter()
.filter(|b| !solids.get(&b.body.solid_id()).is_some_and(|os| os.iter().any(|o| o.same_shape(&b.body))))
.map(|b| if b.bytes > 0 { b.bytes } else { b.body.retained_bytes() })
.sum();
let kept: std::collections::HashSet<*const SolvedSketch> = before.sketches.iter().map(Arc::as_ptr).collect();
let sketches: usize = self.sketches.iter().filter(|s| !kept.contains(&Arc::as_ptr(s))).map(|s| s.retained_bytes()).sum();
bodies + sketches + self.sheets.len() * 4096 + self.threads.len() * 192 + self.construct.len() * 192
}
pub fn body(&self, name: &str) -> Option<&ModelBody> {
#[cfg(test)]
cost_tests::count(|c| c.body_searches += 1);
self.bodies.iter().find(|b| b.name == name)
}
/// Make every body's display mesh now, on all cores (bodies are meshed independently and
/// each keeps its own mesh, so the meshes are those `ModelBody::mesh` makes one by one).
/// Stops starting bodies once `go_on` says no.
pub fn warm_meshes(&self, go_on: impl Fn() -> bool + Sync) {
// Only bodies without a mesh: starting threads just to find every mesh made costs more
// than looking (most bodies are unchanged from one command to the next).
let cold: Vec<_> = self.bodies.iter().filter(|b| b.mesh.get().is_none()).collect();
kernel::for_each_on_threads(&cold, 16, |b| {
if go_on() {
let _ = b.mesh();
}
});
}
/// Prepare reference meshes and display plans at the current quality for ahead jobs.
pub fn warm_display(&self) {
let q = crate::display_quality::current();
let planned = |b: &ModelBody| b.plan.get(q.index()).is_none_or(|cell| cell.get().is_some());
let cold: Vec<_> = self.bodies.iter().filter(|b| b.mesh.get().is_none() || !planned(b)).collect();
kernel::for_each_on_threads(&cold, 16, |b| {
let _ = b.mesh();
let _ = b.display_plan();
});
}
/// Prepare reference picking geometry and the GPU plan/highlight mesh at exactly the
/// requested quality. The first viewport frame then consumes initialized caches only.
pub fn warm_display_at(&self, quality: crate::display_quality::DisplayQuality, go_on: impl Fn() -> bool + Sync) {
kernel::for_each_on_threads(&self.bodies, 16, |body| {
if go_on() {
let _ = body.mesh();
}
if go_on() {
let _ = body.plan_mesh_at(quality);
}
});
}
pub fn sketch(&self, feature: u64) -> Option<&SolvedSketch> {
self.sketches.iter().find(|s| s.feature == feature).map(|s| &**s)
}
}
/// Evaluation result of one feature.
#[derive(Clone, Debug, Serialize)]
pub struct FeatureResult {
pub id: u64,
pub name: String,
pub error: Option<String>,
pub warning: Option<String>,
/// An Import feature's warnings by kind and part, with what came in of the file's parts
/// (`warning` is the first of them as the kernel words them).
#[serde(skip_serializing_if = "Option::is_none")]
pub import_report: Option<Arc<kernel::ImportReport>>,
/// What a Repair Part feature changed, face by face (the command's reply says it).
#[serde(skip)]
pub repair: Option<Arc<kernel::RepairReport>>,
pub ms: f64,
pub skipped: bool,
/// Not evaluated on the document's current inputs: a feature at or after a sketch shown live
/// ([`Model::show_live_sketch`]). It keeps its last result until the next `evaluate`, which
/// never reuses it.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub stale: bool,
#[serde(skip)]
fingerprint: u64,
/// Taken from a saved model that did not keep this feature's state (#3220): `state` only
/// stands in for it until [`Model::evaluate`] evaluates the feature again, which
/// [`Model::adopt`] does before the model is used.
#[serde(skip)]
unkept: bool,
#[serde(skip)]
pub state: Arc<ModelState>,
}
/// Incremental evaluator: holds the state after every feature.
#[derive(Clone, Debug, Default)]
pub struct Model {
pub results: Vec<FeatureResult>,
pub param_errors: BTreeMap<String, String>,
empty: Arc<ModelState>,
/// Features recomputed by the last `evaluate`.
pub last_recomputed: usize,
/// Features recomputed by every `evaluate` of this model (and of the model it was copied
/// from) so far.
pub recomputed: usize,
/// Features whose result the last `evaluate` took from the cache instead of recomputing: the
/// same feature on the same inputs was evaluated before (an edit set back, undo, redo, a
/// configuration row). Their geometry did change since the previous evaluation.
pub last_restored: usize,
/// Results by inputs, shared with this model's copies.
pub cache: Arc<std::sync::Mutex<EvalCache>>,
/// Evaluate everything from scratch (no reuse; tests compare the two).
pub no_cache: bool,
/// Results kept besides the cache ([`Model::keep`]).
kept: KeptSlot,
/// The imported texts' digests the last `evaluate` fingerprinted the features with.
step_digests: StepDigests,
/// The address of the shared document whose fingerprints the results were last given in
/// full, with [`fingerprints_digest`] of them then ([`Model::pinned_prefix`]). Only an
/// address: a reference to the document would make every in-place edit of it a copy.
fingerprinted: Option<(usize, u64)>,
/// The document context the last `evaluate` ran in ([`context_digest`]).
context: u64,
/// The last active result of each feature hidden by the history marker, with its document
/// context. These share the existing states, so rolling back does not surrender them to
/// the bounded cache. A result leaves this map when its feature is active again or removed.
rolled_results: std::collections::HashMap<u64, (u64, FeatureResult)>,
/// Results another copy of this model evaluated (ahead, off the window thread) that
/// `evaluate` takes for features they match ([`Model::prime`]), with that copy's context.
primed: Option<(u64, Arc<std::collections::HashMap<u64, FeatureResult>>)>,
/// Shared with copies of this evaluator; states hold only a weak reference.
frame_bodies: Arc<std::sync::Mutex<FrameBodies>>,
/// When SMLib's check runs on the features this model evaluates ([`Model::set_validation`]).
validation: kernel::Validation,
/// Inputs proven to describe placement-independent geometry, and the state they produced.
placement_inputs: Option<placement_reuse::Inputs>,
/// All evaluated features use supported local inputs; computed with the existing owner index.
placement_local: bool,
}
/// Parameters a feature uses directly (inputs, sketch dimensions and the expressions of a
/// sketch's texts, the text parameters of their words included), sorted.
fn param_names(f: &Feature) -> Vec<String> {
let mut names: Vec<String> = f.kind.expressions().iter().flat_map(|e| expr::references(e)).collect();
if let FeatureKind::Sketch { sketch, .. } = &f.kind {
names.extend(sketch.constraints.iter().filter_map(|c| c.param.clone()));
names.extend(sketch.patterns.iter().flat_map(|p| p.expressions.values()).flat_map(|e| expr::references(e)));
names.extend(sketch.text_exprs().into_iter().flat_map(|(_, e)| expr::references(e)));
names.extend(sketch.text_word_exprs().into_iter().flat_map(|e| crate::text_params::references(e)));
}
names.sort();
names.dedup();
names
}
fn fingerprint(doc: &Document, prev: u64, f: &Feature, vals: &BTreeMap<String, Value>, rolled_back: bool, steps: &StepDigests) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
prev.hash(&mut h);
rolled_back.hash(&mut h);
vals.get(DESIGN_LEN).map(|v| v.v.to_bits()).hash(&mut h);
hash_feature_json(f, steps, &mut h);
for n in param_names(f) {
n.hash(&mut h);
match (vals.get(&n), doc.text_param(&n)) {
(Some(v), _) => {
v.v.to_bits().hash(&mut h);
v.len.hash(&mut h);
v.ang.hash(&mut h);
}
(None, Some(p)) => p.text.hash(&mut h),
(None, None) => 0u8.hash(&mut h),
}
}
h.finish()
}
/// The digests of the Import features' STEP texts, by feature id, with the text each was taken
/// from. Every evaluation fingerprints every feature, and writing out a design's imported files
/// each time made every command as slow as the files are large: a text is shared (`Arc`), so
/// its digest is taken once and kept while the feature holds that same text.
#[derive(Clone, Debug, Default)]
struct StepDigests(std::collections::HashMap<u64, (Arc<str>, u64)>);
impl StepDigests {
/// The digests of `doc`'s imported texts, reusing `known` for texts it has seen.
fn of(doc: &Document, known: &StepDigests) -> StepDigests {
let texts = doc.features.iter().filter_map(|f| match &f.kind {
FeatureKind::Import { step, .. } => Some((f.id, step)),
_ => None,
});
StepDigests(
texts
.map(|(id, step)| {
let digest = known.get(id, step).unwrap_or_else(|| step_text_digest(step));
(id, (step.clone(), digest))
})
.collect(),
)
}
/// The digest of `step`, when it is the text feature `id` was last seen with.
fn get(&self, id: u64, step: &Arc<str>) -> Option<u64> {
self.0.get(&id).filter(|(text, _)| Arc::ptr_eq(text, step)).map(|(_, digest)| *digest)
}
}
fn step_text_digest(text: &str) -> u64 {
#[cfg(test)]
cost_tests::count(|c| c.digested += 1);
let mut h = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut h);
h.finish()
}
/// Positions and radii are fingerprinted to this quantum (mm): far below anything a design
/// can show, far above the solver's rounding, so a sketch solved again to the same geometry
/// reads as the same input.
const QUANTUM: f64 = 1e-6;
/// Put what a solve writes into a sketch on the [`QUANTUM`] grid: positions, radii and the
/// measured values of driven dimensions.
fn quantize(sk: &mut solidcraft_sketch::Sketch) {
let q = |v: f64| (v / QUANTUM).round() * QUANTUM;
for p in &mut sk.points {
p.pos = Vec2::new(q(p.pos.x), q(p.pos.y));
}
for c in &mut sk.curves {
if let CurveKind::Circle { r, .. } | CurveKind::Ellipse { r, .. } = &mut c.kind {
*r = q(*r);
}
}
for c in sk.constraints.iter_mut().filter(|c| c.driven) {
if let Some(v) = c.kind.value() {
c.kind.set_value(q(v));
}
}
}
/// A feature as fingerprinted: its definition, a sketch's stored solve quantized, an imported
/// file's text by its digest.
/// Hash [`feature_json`] of `f` into `h`. Every evaluation fingerprints every feature, and in a
/// design built command by command almost all of them are the same as last time: the text of a
/// feature is kept (by id) with the feature it was written from, and written again only when the
/// feature differs. An Import's text also depends on its STEP digest, so it is written each time
/// as before.
///
/// The texts are shared by every thread: a command evaluated ahead runs on a new worker thread
/// each time (the desktop's deferred commands and delete checks, the control channel's ahead
/// jobs), and a per-thread store started empty there, so every ahead run wrote out every
/// feature again. The lock is held only to look up or store an entry, never while a feature is
/// compared or written; an entry is the same whichever thread wrote it, since the text is a
/// function of the feature alone.
fn hash_feature_json(f: &Feature, steps: &StepDigests, h: &mut impl Hasher) {
type Written = std::collections::HashMap<u64, Arc<(Feature, String)>>;
static WRITTEN: std::sync::LazyLock<std::sync::Mutex<Written>> = std::sync::LazyLock::new(Default::default);
if matches!(f.kind, FeatureKind::Import { .. }) {
feature_json(f, steps).hash(h);
return;
}
let seen = WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).get(&f.id).cloned();
if let Some(seen) = seen
&& seen.0 == *f
{
seen.1.hash(h);
return;
}
#[cfg(test)]
cost_tests::count_written();
let json = feature_json(f, steps);
json.hash(h);
let entry = Arc::new((f.clone(), json));
let mut written = WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
if written.len() >= 1 << 15 {
written.clear();
}
written.insert(f.id, entry);
}
fn feature_json(f: &Feature, steps: &StepDigests) -> String {
if let FeatureKind::Import { step, .. } = &f.kind {
let mut g = f.clone();
if let FeatureKind::Import { step: text, .. } = &mut g.kind {
let digest = steps.get(f.id, step).unwrap_or_else(|| step_text_digest(step));
*text = Arc::from(format!("{digest:016x}:{}", step.len()));
}
return serde_json::to_string(&g).unwrap_or_default();
}
if let FeatureKind::Sketch { .. } = &f.kind {
let mut g = f.clone();
if let FeatureKind::Sketch { sketch, .. } = &mut g.kind {
quantize(sketch);
}
return serde_json::to_string(&g).unwrap_or_default();
}
serde_json::to_string(f).unwrap_or_default()
}
/// Store in `stored` the solution `solved` holds for it: the positions, the circle and ellipse
/// radii, the arcs' end order and orientation (a signed sweep can swap them) and the
/// constraints' values. Nothing else: what evaluation derives for its own copy (an offset's
/// upgraded topology, refreshed links) stays out of the stored sketch. A `solved` that does not
/// match `stored` entity for entity is not adopted.
fn adopt_solution(stored: &mut solidcraft_sketch::Sketch, solved: &solidcraft_sketch::Sketch) -> bool {
if stored.patterns != solved.patterns {
// Rebuild authored copies without storing topology derived from links or offsets.
let mut updated = stored.clone();
for pattern in &solved.patterns {
let Some(index) = updated.patterns.iter().position(|p| p.id == pattern.id) else { return false };
if updated.update_pattern(index, pattern.kind.clone()).is_err() {
return false;
}
}
if updated.patterns != solved.patterns || !adopt_solution(&mut updated, solved) {
return false;
}
*stored = updated;
return true;
}
if stored.points.len() != solved.points.len()
|| stored.curves.len() != solved.curves.len()
|| stored.constraints.len() != solved.constraints.len()
|| stored.constraints.iter().zip(&solved.constraints).any(|(a, b)| a.id != b.id)
{
return false;
}
for (p, q) in stored.points.iter_mut().zip(&solved.points) {
p.pos = q.pos;
}
for (c, d) in stored.curves.iter_mut().zip(&solved.curves) {
match (&mut c.kind, &d.kind) {
(CurveKind::Circle { r, .. }, CurveKind::Circle { r: s, .. }) | (CurveKind::Ellipse { r, .. }, CurveKind::Ellipse { r: s, .. }) => {
*r = *s
}
(CurveKind::Arc { a, b, .. }, CurveKind::Arc { a: sa, b: sb, .. }) => {
(*a, *b) = (*sa, *sb);
c.reversed = d.reversed;
}
_ => {}
}
}
for (c, d) in stored.constraints.iter_mut().zip(&solved.constraints) {
if let Some(v) = d.kind.value() {
c.kind.set_value(v);
}
}
true
}
impl Document {
/// The values features are evaluated with: the parameters, and the design's length unit.
pub fn evaluation_values(&self) -> BTreeMap<String, Value> {
evaluation_values(self).0
}
}
/// The values features are evaluated with: the parameters, and the design's length unit.
fn evaluation_values(doc: &Document) -> (BTreeMap<String, Value>, BTreeMap<String, String>) {
let (mut vals, perr) = doc.param_values();
if let Some((Kind::Length, scale)) = expr::unit_info(doc.units.trim())
&& scale != 1.0
{
vals.insert(DESIGN_LEN.into(), Value { v: scale, len: 0, ang: 0 });
}
(vals, perr)
}
/// A feature's fingerprint in the chain after `prev`: its own inputs, where it is placed, and
/// the sheet metal or plastic rules it takes defaults from.
#[allow(clippy::too_many_arguments)]
fn chain_fingerprint(
doc: &Document,
vals: &BTreeMap<String, Value>,
f: &Feature,
prev: u64,
rolled_back: bool,
steps: &StepDigests,
st: Option<&ModelState>,
) -> u64 {
let mut fp = fingerprint(doc, prev, f, vals, rolled_back, steps) ^ placement_digest(doc, f, st);
// Sheet metal features also depend on the rules (and the parameters they use).
if f.kind.is_sheet() {
let mut h = std::collections::hash_map::DefaultHasher::new();
fp.hash(&mut h);
serde_json::to_string(&doc.sheet).unwrap_or_default().hash(&mut h);
for r in &doc.sheet.rules {
for (_, e, _) in r.fields() {
for n in expr::references(e) {
vals.get(&n).map(|v| v.v.to_bits()).hash(&mut h);
}
}
}
fp = h.finish();
}
// Plastic features take defaults from the plastic rules.
if f.kind.is_plastic() && !doc.plastic.is_empty() {
let mut h = std::collections::hash_map::DefaultHasher::new();
fp.hash(&mut h);
serde_json::to_string(&doc.plastic).unwrap_or_default().hash(&mut h);
for r in &doc.plastic.rules {
for (_, e, _) in r.fields() {
for n in expr::references(e) {
vals.get(&n).map(|v| v.v.to_bits()).hash(&mut h);
}
}
}
fp = h.finish();
}
// A pattern or mirror of features replays its sources' definitions wherever they are in the
// timeline. One made with the timeline rolled back comes before them, where the chain doesn't
// cover them: its copies kept the size the sources had when they were made.
if let FeatureKind::Pattern { features, bodies, .. } | FeatureKind::Mirror { features, bodies, .. } = &f.kind
&& bodies.is_empty()
&& !features.is_empty()
{
let mut h = std::collections::hash_map::DefaultHasher::new();
fp.hash(&mut h);
for g in replayed_sources(doc, features) {
fingerprint(doc, 0, g, vals, false, steps).hash(&mut h);
}
fp = h.finish();
}
fp
}
/// The features a pattern or mirror of `features` replays: each source, and the sources of one
/// that is itself a pattern or mirror of features (see `copy_plan`), each once.
fn replayed_sources<'a>(doc: &'a Document, features: &[crate::FeatureId]) -> Vec<&'a Feature> {
let mut out: Vec<&Feature> = Vec::new();
let mut todo: Vec<crate::FeatureId> = features.to_vec();
// A bound on the walk, as on the copy plan's nesting: a design can't make it run on.
for _ in 0..1024 {
let Some(id) = todo.pop() else { break };
let Ok(g) = source_feature(doc, id) else { continue };
if out.iter().any(|x| x.id == g.id) {
continue;
}
if let FeatureKind::Pattern { features, bodies, .. } | FeatureKind::Mirror { features, bodies, .. } = &g.kind
&& bodies.is_empty()
{
todo.extend(features.iter().copied());
}
out.push(g);
}
out
}
/// Document-level inputs any feature may read: construction planes (resolved by name), sheet
/// metal and plastic rules (and the parameters they use), components and body placement.
fn context_digest(doc: &Document, vals: &BTreeMap<String, Value>) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
for f in doc.features.iter().filter(|f| {
matches!(f.kind, FeatureKind::ConstructionPlane { .. } | FeatureKind::ConstructionAxis { .. } | FeatureKind::ConstructionPoint { .. })
}) {
fingerprint(doc, 0, f, vals, false, &StepDigests::default()).hash(&mut h);
}
doc.units.hash(&mut h);
serde_json::to_string(&doc.sheet).unwrap_or_default().hash(&mut h);
serde_json::to_string(&doc.plastic).unwrap_or_default().hash(&mut h);
serde_json::to_string(&doc.components).unwrap_or_default().hash(&mut h);
serde_json::to_string(&doc.body_components).unwrap_or_default().hash(&mut h);
for e in doc.sheet.rules.iter().flat_map(|r| r.fields().map(|(_, e, _)| e)) {
for n in expr::references(e) {
vals.get(&n).map(|v| v.v.to_bits()).hash(&mut h);
}
}
for r in &doc.plastic.rules {
for (_, e, _) in r.fields() {
for n in expr::references(e) {
vals.get(&n).map(|v| v.v.to_bits()).hash(&mut h);
}
}
}
h.finish()
}
/// What the validation mode adds to the context digest: nothing for checking every step (how
/// every evaluation before the mode checked, so its results and saved caches stand), so a result
/// is taken from the cache only under the mode it was evaluated in.
fn validation_digest(validation: kernel::Validation) -> u64 {
match validation {
kernel::Validation::EachStep => 0,
v => {
let mut h = std::collections::hash_map::DefaultHasher::new();
("validation", v.id()).hash(&mut h);
h.finish()
}
}
}
/// SMLib's check of every body a feature made or changed (in `after`, not in `before`, the
/// state it started from), once its steps left their checks to its end: the first that fails is
/// the feature's error, naming the body.
fn check_kept(before: &ModelState, after: &ModelState) -> kernel::Result<()> {
for b in &after.bodies {
if before.bodies.iter().any(|old| old.body.same_shape(&b.body)) {
continue;
}
kernel::check_kept(&b.body).map_err(|e| kernel::KernelError::Failed(format!("body `{}`: {e}", b.name)))?;
}
Ok(())
}
/// Whether `after`, a state feature `f` evaluated to from `before` in an earlier evaluation, is
/// still its result in `doc`: a feature saved before format 14 names the pieces it splits a body
/// into as the later features pick them ([`crate::lineage::order_legacy_lumps`]), which neither
/// its fingerprint nor its cache key cover. (A script replays those features after it: the state
/// made before they were there named the pieces otherwise.)
fn legacy_current(doc: &Document, f: &Feature, before: &ModelState, after: &ModelState) -> bool {
!f.shell_piece_order || after.legacy_picks.get(&f.id).copied().unwrap_or(0) == crate::lineage::legacy_picks_digest(&after.bodies, before, doc, f)
}
/// The cache key of a feature evaluation: its own inputs, the document context and the state it
/// starts from. Features that replay other features' definitions (patterns and mirrors of
/// features) also take the chain fingerprint, which covers every earlier definition.
fn cache_key(f: &Feature, chain_fp: u64, local: u64, ctx: u64, state: &ModelState) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
local.hash(&mut h);
ctx.hash(&mut h);
state.digest().hash(&mut h);
f.id.hash(&mut h);
let replays = match &f.kind {
FeatureKind::Pattern { features, .. } | FeatureKind::Mirror { features, .. } => !features.is_empty(),
_ => false,
};
if replays {
chain_fp.hash(&mut h);
}
h.finish()
}
/// What a feature reads of placements: components (their first placement), occurrence paths
/// and bodies in its timeline input, whose geometry it finds in its evaluating frame, or all.
#[derive(Default)]
struct PlacementReads {
all: bool,
components: std::collections::BTreeSet<u64>,
paths: Vec<Vec<u64>>,
bodies: std::collections::BTreeSet<String>,
}
impl PlacementReads {
fn is_empty(&self) -> bool {
!self.all && self.components.is_empty() && self.paths.is_empty() && self.bodies.is_empty()
}
/// A body's complete placement in the feature's input state, including its offset. Later
/// transfers do not change where an earlier feature read it.
fn placed_body(&mut self, st: Option<&ModelState>, name: &str) {
if st.is_some_and(|st| st.body(name).is_some()) {
self.bodies.insert(name.to_owned());
} else {
self.all = true;
}
}
/// The same target selection as `apply_traced`, expanded only over the timeline input.
fn drawn_targets(&mut self, st: Option<&ModelState>, f: &Feature) {
let Some(st) = st else {
self.all = true;
return;
};
let (_, targets) = feature_op(f);
let names = if targets.is_empty() { &f.participants } else { &targets };
let all = names.len() == 1 && names.first().is_some_and(|n| n == "*");
if all || names.is_empty() {
self.bodies.extend(st.bodies.iter().filter(|b| all || b.component == f.component || b.feature == f.id).map(|b| b.name.clone()));
} else {
for name in names {
self.placed_body(Some(st), name);
}
}
}
/// The component of body `name` in `st`; every component when the body is not there (a
/// projection then takes the body nearest its point, wherever that is).
fn body(&mut self, doc: &Document, st: Option<&ModelState>, name: &str) {
match st.and_then(|st| st.body(name)) {
Some(b) => {
self.components.insert(doc.model_body_component(b));
}
None => self.all = true,
}
}
/// The component of sketch `id`, and the root when it holds wires fixed in the world (they
/// are read through the reader's whole placement).
fn sketch(&mut self, doc: &Document, id: u64) {
self.components.insert(doc.feature(id).map(|f| f.component).unwrap_or(0));
if doc.sketch(id).is_ok_and(|sk| sk.wires.iter().any(|w| w.space == solidcraft_sketch::WireSpace::World)) {
self.components.insert(0);
}
}
fn link(&mut self, doc: &Document, st: Option<&ModelState>, source: &solidcraft_sketch::LinkSource) {
use solidcraft_sketch::LinkSource as L;
match source {
L::Edge { body, .. } | L::Face { body, .. } | L::Body { body } | L::Vertex { body, .. } | L::Iso { body, .. } | L::Spun { body, .. } => {
self.body(doc, st, body)
}
L::SketchCurve { sketch, .. } | L::SketchPoint { sketch, .. } => self.sketch(doc, *sketch),
L::OnSurface { sketch, body, .. } => {
self.sketch(doc, *sketch);
self.body(doc, st, body);
}
L::Intersection { a, b } => {
self.link(doc, st, a);
self.link(doc, st, b);
}
// In the sketch's own frame: the component's origin, axes and planes, its own axes, text.
L::Origin | L::Axis { .. } | L::SketchAxis { .. } | L::Plane { .. } | L::Text { .. } => {}
}
}
}
/// The frame of an occurrence path from the root (its occurrences' transforms in turn); `None`
/// when the path no longer leads anywhere.
fn path_frame(doc: &Document, path: &[u64]) -> Option<Mat> {
if path.len() > crate::MAX_PLACEMENT_DEPTH + 1 {
return None;
}
let (mut m, mut c) = (crate::IDENTITY, 0);
for id in path {
let o = doc.occurrences.iter().find(|o| o.id == *id && o.parent == c)?;
m = crate::mat_mul(&m, &o.transform);
c = o.component;
}
Some(m)
}
/// Hash a placement on a grid far finer than anything a design shows ([`QUANTUM`] mm, a
/// thousandth of that for the rotation), so the same relative placement reached through
/// different whole-assembly motions (each rounding a little differently) reads the same.
fn hash_placement(m: &Mat, h: &mut impl Hasher) {
for (col, column) in m.iter().enumerate() {
let q = if col == 3 { QUANTUM } else { QUANTUM * 1e-3 };
for v in column {
let r = (v / q).round();
// -0 and 0 are the same place.
(if r == 0.0 { 0.0f64 } else { r }).to_bits().hash(h);
}
}
}
/// Where the geometry a feature reads from other components is placed, as its own component
/// sees it: the placement of each component (or occurrence path) it reads relative to its own
/// frame. A feature that reads nothing outside its own frame gives 0, so moving parts around
/// (a joint driven, an occurrence moved) leaves it as it was; one that reads a part moved
/// relative to it (a sketch projecting a face of another part, To Object, a mirror of a placed
/// body) is evaluated again. `st` is the model the feature starts from, which says what
/// component a body it names belongs to (without it, every component is taken as read).
/// [`placement_digest`] of a mirror of placed bodies: its own component's frame, each placement it
/// was picked at (the copy's component, frame and the frame it was picked in) and the offsets of
/// the bodies it mirrors (#1938).
fn mirror_placements_digest(doc: &Document, f: &Feature, placements: &[Vec<u64>], bodies: &[crate::BodyName]) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
doc.component_transform(f.component).iter().flatten().for_each(|x| x.to_bits().hash(&mut h));
// A feature added after the mirror that builds on its copies needs them made for that.
placement_reuse::copies_only_shown(doc, f).hash(&mut h);
for placed in placements.iter().map(|path| mirror_copy_frame(doc, path)) {
placed.is_some().hash(&mut h);
if let Some((component, frame, picked)) = placed {
component.hash(&mut h);
frame.iter().chain(&picked).flatten().for_each(|x| x.to_bits().hash(&mut h));
}
}
for b in bodies {
serde_json::to_string(&doc.body_offsets.get(&b.0)).unwrap_or_default().hash(&mut h);
}
h.finish()
}
fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64 {
// No shortcut for a design without placements: its first component (placed where the
// design is) must not change what its features read, or creating it evaluates them all.
let mut reads = PlacementReads::default();
let mut frame = None;
let mut h = std::collections::hash_map::DefaultHasher::new();
// A sketch, profile or path of another component is moved through both placements.
for (sketch, _) in f.kind.profile_sels() {
if doc.feature(sketch).is_some_and(|s| s.component != f.component) {
reads.sketch(doc, sketch);
}
}
let path = match &f.kind {
FeatureKind::Sweep { path_sketch, .. }
| FeatureKind::SurfaceSweep { path_sketch, .. }
| FeatureKind::Pipe { path_sketch, .. }
| FeatureKind::FrameMember { path_sketch, .. }
| FeatureKind::Pattern { pattern: crate::PatternKind::Path { path_sketch, .. }, .. } => Some(*path_sketch),
_ => None,
};
let wired = |id: &crate::SketchId| doc.sketch(id.0).is_ok_and(|sketch| !sketch.wires.is_empty());
let rails: &[crate::SweepRail] = match &f.kind {
FeatureKind::Sweep { rails, .. }
| FeatureKind::SurfaceSweep { rails, .. }
| FeatureKind::Loft { rails, .. }
| FeatureKind::SurfaceLoft { rails, .. } => rails,
_ => &[],
};
// Members map their frame sketch into their own component's frame, 2D lines included.
let member = matches!(f.kind, FeatureKind::FrameMember { .. });
if path.as_ref().is_some_and(|p| member || wired(p)) || rails.iter().any(|r| wired(&r.sketch)) {
if let Some(path) = path {
reads.sketch(doc, path.0);
}
// A sweep's profile and the rails' components place them too.
let profile = match &f.kind {
FeatureKind::Sweep { sketch, .. } | FeatureKind::SurfaceSweep { sketch, .. } => Some(sketch),
_ => None,
};
for sketch in profile.into_iter().chain(rails.iter().map(|r| &r.sketch)) {
reads.sketch(doc, sketch.0);
}
}
// A network through 3D sketch curves reads their points through the components the
// feature and those sketches are placed in, as a sweep's wired path does.
if let FeatureKind::SurfaceNetwork { u, v, .. } = &f.kind {
let sketches: Vec<crate::SketchId> = u.iter().chain(v).filter_map(|c| c.sketch).collect();
if sketches.iter().any(wired) {
for sketch in &sketches {
reads.sketch(doc, sketch.0);
}
}
}
match &f.kind {
// To / From Object finds its target where that target's component is placed (#928),
// over every body.
FeatureKind::Extrude { extent, .. } if extent.to.is_some() || extent.from.is_some() => reads.all = true,
FeatureKind::Revolve { to: Some(_), .. } => reads.all = true,
// A mirror of placed bodies follows the placements it was picked at and its own component's
// frame, not every occurrence: moving an unrelated one leaves it (and its cache) alone.
FeatureKind::Mirror { placements, bodies, .. } if !placements.is_empty() => return mirror_placements_digest(doc, f, placements, bodies),
// A combine moves tools placed differently from its target into the target's frame (#3383).
FeatureKind::Combine { target, tools, .. } => {
frame = st.and_then(|st| st.body(target)).map(|b| body_world(doc, b));
reads.placed_body(st, target);
for tool in tools {
reads.placed_body(st, tool);
}
}
// A pattern of bodies copies them along its directions or about its axis in its own
// component's frame, so it follows where each body it copies is placed relative to that
// frame: copies of a root block, patterned in a component, move with the component.
FeatureKind::Pattern { bodies, .. } if !bodies.is_empty() => {
for b in bodies {
reads.placed_body(st, &b.0);
}
}
// Joins, cuts and intersects meet their targets where those are placed (#3383).
kind if drawn_tools_change_bodies(kind) => reads.drawn_targets(st, f),
FeatureKind::Sketch { plane, sketch } => {
match crate::face_anchor::plane_face_anchor(plane) {
// Read in the frame of the placement it was drawn in, its face through the
// placement it was picked at.
Some(anchor) => {
match anchor.author_frame(doc, f.component) {
Ok(m) => frame = Some(m),
Err(e) => e.to_string().hash(&mut h),
}
if anchor.path.is_empty() {
reads.components.insert(anchor.component);
} else {
reads.paths.push(anchor.path.clone());
}
}
// A face or edges picked on whatever body lies there.
None if plane_reads_geometry(plane) => reads.all = true,
None => {}
}
for link in &sketch.links {
reads.link(doc, st, &link.source);
}
}
_ => {}
}
if reads.is_empty() {
return 0;
}
let frame = frame.unwrap_or_else(|| doc.component_transform(f.component));
let Some(inverse) = crate::mat_inverse(&frame) else { return placements_hash(doc) };
if reads.all {
reads.components.insert(0);
match st {
// The components holding what the feature can reach: a component made later, or one
// that holds nothing yet (just created), changes nothing it reads.
Some(st) => {
reads.components.extend(doc.body_owners(st));
let owner = |id: u64| doc.feature(id).map(|g| g.component);
reads.components.extend(st.sketches.iter().filter_map(|s| owner(s.feature)));
reads.components.extend(st.construct.iter().filter_map(|c| owner(c.feature)));
}
None => reads.components.extend(doc.components.iter().map(|c| c.id)),
}
}
for c in &reads.components {
c.hash(&mut h);
// Its own component is read in its own frame.
if *c != f.component {
hash_placement(&crate::mat_mul(&inverse, &doc.component_transform(*c)), &mut h);
}
}
for path in &reads.paths {
path.hash(&mut h);
match path_frame(doc, path) {
Some(m) => hash_placement(&crate::mat_mul(&inverse, &m), &mut h),
None => u8::MAX.hash(&mut h),
}
}
hash_placed_bodies(doc, st, &reads.bodies, &inverse, &mut h);
// Legacy and component-wide reads still need the conservative offset dependency. Body
// reads above already include just their own offsets, in the frame that evaluates them.
if reads.all || !reads.components.is_empty() || !reads.paths.is_empty() {
serde_json::to_string(&doc.body_offsets).unwrap_or_default().hash(&mut h);
}
// Never 0: the feature reads placements.
h.finish() | 1
}
/// The bodies part of [`placement_digest`]: each body read, in name order, and where it is placed
/// relative to the reading frame `inverse` (`u8::MAX` for one not in `st`), as [`body_world`]
/// places it. The bodies, their components and the components' frames are looked up once: a
/// join or cut without targets reads every body of its component, and searching the model, the
/// timeline and the placements again for each of them made every evaluation, even one served
/// from the cache, quadratic in the bodies.
fn hash_placed_bodies(doc: &Document, st: Option<&ModelState>, names: &std::collections::BTreeSet<String>, inverse: &Mat, h: &mut impl Hasher) {
let (Some(st), false) = (st, names.is_empty()) else {
names.iter().for_each(|name| (name, u8::MAX).hash(h));
return;
};
// The first body of a name, as `ModelState::body` finds it.
let mut index: std::collections::HashMap<&str, usize> = std::collections::HashMap::with_capacity(st.bodies.len());
for (i, b) in st.bodies.iter().enumerate() {
index.entry(b.name.as_str()).or_insert(i);
}
let components = doc.model_body_components(st);
let mut frames: std::collections::HashMap<u64, Mat> = std::collections::HashMap::new();
for name in names {
name.hash(h);
let found = index.get(name.as_str()).and_then(|&i| Some((st.bodies.get(i)?, *components.get(i)?)));
match found {
Some((b, component)) => {
let m = *frames.entry(component).or_insert_with(|| doc.component_transform(component));
let world = doc.model_body_offset(b).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m);
hash_placement(&crate::mat_mul(inverse, &world), h);
}
None => u8::MAX.hash(h),
}
}
}
/// Every occurrence's placement and every body offset (a feature read from a frame that cannot
/// be inverted).
fn placements_hash(doc: &Document) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
for o in &doc.occurrences {
o.id.hash(&mut h);
o.transform.iter().flatten().for_each(|x| x.to_bits().hash(&mut h));
}
serde_json::to_string(&doc.body_offsets).unwrap_or_default().hash(&mut h);
h.finish()
}
fn now() -> web_time::Instant {
web_time::Instant::now()
}
impl Model {
pub fn new() -> Self {
Model::default()
}
/// The final model state.
pub fn state(&self) -> Arc<ModelState> {
self.results.iter().rev().find(|r| !r.skipped).map(|r| r.state.clone()).unwrap_or_else(|| self.empty.clone())
}
/// State just before the feature with this id (for editing a sketch in context).
pub fn state_before(&self, id: u64) -> Arc<ModelState> {
let Some(i) = self.results.iter().position(|r| r.id == id) else { return self.state() };
self.results.get(..i).and_then(|s| s.iter().rev().find(|r| !r.skipped)).map(|r| r.state.clone()).unwrap_or_else(|| self.empty.clone())
}
pub fn result(&self, id: u64) -> Option<&FeatureResult> {
self.results.iter().find(|r| r.id == id)
}
/// Show a sketch's new solution before the model is evaluated again (the frames of an
/// interactive drag): `sketch`, already solved with `report`, on the plane it was last
/// evaluated on. The sketch's own result and the final state show it, and the sketch and
/// every feature after it are marked stale, keeping their last geometry. Nothing else is
/// recomputed; the next [`Model::evaluate`] recomputes from the sketch on. Returns `false`,
/// changing nothing, when the sketch has no evaluated result or a feature before it is
/// already stale (only a full evaluation brings that up to date).
pub fn show_live_sketch(&mut self, feature: u64, sketch: solidcraft_sketch::Sketch, report: SolveReport) -> bool {
let Some(i) = self.results.iter().position(|r| r.id == feature) else { return false };
if self.results.iter().take(i).any(|r| r.stale) {
return false;
}
let Some(last) = self.results.get(i).filter(|r| !r.skipped && r.error.is_none()).and_then(|r| r.state.sketch(feature)) else {
return false;
};
let solved = Arc::new(SolvedSketch {
feature,
name: last.name.clone(),
plane: last.plane,
profiles: find_profiles(&sketch),
ends: solidcraft_sketch::loose_ends(&sketch),
sketch,
report,
});
let shown = self.results.iter().rposition(|r| !r.skipped);
for (k, r) in self.results.iter_mut().enumerate().skip(i) {
r.stale = true;
// The sketch's own state and the final one show it: only that entry changes (the
// states are copied on the first frame; later frames own them and swap in place).
if (k == i || Some(k) == shown)
&& let Some(s) = Arc::make_mut(&mut r.state).sketches.iter_mut().find(|s| s.feature == feature)
{
*s = solved.clone();
}
}
true
}
/// Some results are stale ([`Model::show_live_sketch`]): the model needs an `evaluate`.
pub fn is_stale(&self) -> bool {
self.results.iter().any(|r| r.stale)
}
/// Store in `doc` the sketches whose last evaluation solved them for new driving values
/// (see `Document::solve_sketch`), so the stored sketch is the solved state the next value
/// edit continues from (edits depend on their history, as a user editing dimensions one
/// after another expects) and later evaluations repeat no continuation. Their results
/// stand for the updated document: the solved sketch is what evaluating it gives.
/// Returns how many sketches were stored.
pub fn adopt_solved_sketches(&mut self, doc: &mut Document) -> usize {
let solved: Vec<SolvedSketch> = self.edited_sketches(doc).cloned().collect();
let Some(first) = solved.iter().filter_map(|s| doc.features.iter().position(|f| f.id == s.feature)).min() else { return 0 };
self.placement_inputs = None;
for s in &solved {
if let Ok(stored) = doc.sketch_mut(s.feature) {
adopt_solution(stored, &s.sketch);
}
}
// The fingerprints from the first stored sketch on.
let vals = evaluation_values(doc).0;
let steps = StepDigests::of(doc, &self.step_digests);
let marker = doc.marker.unwrap_or(usize::MAX);
let mut prev_fp = first.checked_sub(1).and_then(|i| self.results.get(i)).map_or(0, |r| r.fingerprint);
for (i, f) in doc.features.iter().enumerate().skip(first) {
let before = self.state_before(f.id);
prev_fp = chain_fingerprint(doc, &vals, f, prev_fp, i >= marker, &steps, Some(&before));
if let Some(r) = self.results.get_mut(i).filter(|r| r.id == f.id) {
r.fingerprint = prev_fp;
}
}
solved.len()
}
/// The sketches the last evaluation solved for driving values other than the ones `doc`
/// stores them with (a value edit since they were stored), or with their linked points
/// elsewhere (a value edit upstream moved what they project: stored, the next evaluation
/// starts where this one ended instead of walking the links there again).
pub fn edited_sketches<'a>(&'a self, doc: &'a Document) -> impl Iterator<Item = &'a SolvedSketch> + 'a {
self.results.iter().filter(|r| !r.skipped && r.error.is_none()).filter_map(|r| r.state.sketch(r.id)).filter(|s| {
s.report.keeps_orientation()
&& doc.sketch(s.feature).is_ok_and(|stored| {
stored.driving_values() != s.sketch.driving_values()
|| stored.patterns != s.sketch.patterns
|| s.sketch.points.iter().zip(&stored.points).any(|(p, q)| p.link.is_some() && p.id == q.id && p.pos != q.pos)
})
})
}
/// While `kept` is set, every result this model evaluates or takes from the cache is also
/// kept there, and a result the cache no longer has is taken from there (#1989): an
/// evaluation ahead on a copy keeps what it computes, and the run that follows on the model
/// itself finds it all, whatever the cache dropped meanwhile. Copies of the model keep
/// nothing.
pub fn keep(&mut self, kept: Option<Arc<KeptResults>>) {
self.kept = KeptSlot(kept);
}
/// Where this model keeps its results besides the cache, if it does ([`Model::keep`]).
pub fn kept(&self) -> Option<Arc<KeptResults>> {
self.kept.0.clone()
}
/// Whether the results are `doc`'s evaluation: one per feature, each on the inputs `doc`
/// gives it, none stale, so [`Model::evaluate`] would keep every one of them. A document
/// changed without an evaluation since is not.
pub fn is_current(&self, doc: &Document) -> bool {
if self.results.len() != doc.features.len() || self.is_stale() {
return false;
}
let vals = evaluation_values(doc).0;
let steps = StepDigests::of(doc, &self.step_digests);
let marker = doc.marker.unwrap_or(usize::MAX);
let mut prev = 0;
// The model each feature starts from (which components the bodies it names are in).
let mut state = self.empty.clone();
doc.features.iter().zip(&self.results).enumerate().all(|(i, (f, r))| {
prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &steps, Some(&state));
if !r.skipped {
state = r.state.clone();
}
r.id == f.id && r.fingerprint == prev
})
}
/// Take the results `ahead` (a copy of this model, evaluated off this thread for the same
/// commands) computed: until [`Model::unprime`], `evaluate` reuses each one whose feature
/// has the same inputs here, instead of evaluating it again. Results that don't match are
/// ignored, so a design changed meanwhile is evaluated as usual.
pub fn prime(&mut self, ahead: &Model) {
let results = ahead.results.iter().filter(|r| !r.skipped && !r.stale).map(|r| (r.id, r.clone())).collect();
self.primed = Some((ahead.context, Arc::new(results)));
}
/// Stop offering the results [`Model::prime`] took.
pub fn unprime(&mut self) {
self.primed = None;
}
/// When SMLib's check runs on the features this model evaluates.
pub fn validation(&self) -> kernel::Validation {
self.validation
}
/// Check the features evaluated from now on under `validation` ([`kernel::Validation`]):
/// after every sweep, boolean and blend, once on the bodies each feature keeps, or not at
/// all. The results already there stand until their features are evaluated again; the cache
/// keeps results apart by mode, so one evaluated under another mode is not taken up.
pub fn set_validation(&mut self, validation: kernel::Validation) {
self.validation = validation;
}
/// Re-evaluate the document, reusing results up to the first changed feature.
pub fn evaluate(&mut self, doc: &Document) {
let _span = solidcraft_profile::span("doc", "evaluate");
self.placement_inputs = None;
self.fingerprinted = None;
self.placement_local = true;
let (vals, perr) = evaluation_values(doc);
self.param_errors = perr;
self.frame_bodies.lock().unwrap_or_else(|e| e.into_inner()).next_generation();
let mut prev_fp = 0u64;
// The names the design must not use again travel with the state (#4957).
let mut state = std::sync::Arc::new(ModelState { reserved_body_names: doc.reserved_body_names.clone(), ..(*self.empty).clone() });
// Those and the names stored on the suppressed features so far (#4302).
let mut reserved = doc.reserved_body_names.clone();
let mut out: Vec<FeatureResult> = Vec::with_capacity(doc.features.len());
let mut reuse = !self.no_cache;
let mut recomputed = 0;
let mut restored = 0;
let marker = doc.marker.unwrap_or(usize::MAX);
let validation = self.validation;
let ctx = context_digest(doc, &vals) ^ validation_digest(validation);
let previous_context = self.context;
let mut rolled_results = std::mem::take(&mut self.rolled_results);
self.context = ctx;
self.step_digests = StepDigests::of(doc, &self.step_digests);
let primed = self.primed.as_ref().filter(|(context, _)| !self.no_cache && *context == ctx).map(|(_, results)| results.clone());
// Each feature's component, for `Document::legacy_body_component` on every body after
// every feature without searching the timeline for each (the first feature with an id).
let mut feature_component: std::collections::HashMap<u64, u64> = std::collections::HashMap::with_capacity(doc.features.len());
for f in &doc.features {
feature_component.entry(f.id).or_insert(f.component);
}
let watched = crate::progress::begin(doc.features.len());
// The features that failed so far in this pass, by id: their names and errors (#9075).
let mut failed: std::collections::HashMap<u64, (String, String)> = std::collections::HashMap::new();
for (i, f) in doc.features.iter().enumerate() {
if let Some(r) = out.last()
&& let Some(e) = &r.error
{
failed.insert(r.id, (r.name.clone(), e.clone()));
}
self.placement_local = self.placement_local && placement_reuse::local_geometry(f, &feature_component);
let rolled_back = i >= marker;
// Retain at most one active result per rolled-back feature, even across several
// marker moves. Build the map anew so deleted features release their states too.
let rolled = rolled_results.remove(&f.id);
let rolled = if self.no_cache {
None
} else if rolled_back {
let active = self.results.get(i).filter(|r| r.id == f.id && !r.skipped && !r.stale && !r.unkept);
if let Some(saved) = active.map(|r| (previous_context, r.clone())).or(rolled) {
self.rolled_results.insert(f.id, saved);
}
None
} else {
rolled.filter(|(context, _)| *context == ctx).map(|(_, r)| r)
};
// Opening was cancelled: the rest is skipped and the result discarded.
let cancelled = watched.step(i);
let fp = chain_fingerprint(doc, &vals, f, prev_fp, rolled_back, &self.step_digests, Some(&state));
prev_fp = fp;
let current = |old: &&FeatureResult| old.id == f.id && old.fingerprint == fp && !old.stale;
// A state the saved model did not keep is evaluated again from the one before it; the
// results after it that the model did keep still stand (#3220).
let unkept = reuse && self.results.get(i).filter(current).is_some_and(|old| old.unkept);
if f.suppressed && !rolled_back {
reserved.extend(f.body_names.iter().map(|n| n.trim()).filter(|n| !n.is_empty()).map(str::to_string));
}
// A feature that names its pieces as later features pick them (saved before format 14)
// has a result only while those picks are what they were.
if reuse
&& !unkept
&& let Some(old) = self.results.get(i).filter(current).filter(|old| old.skipped || legacy_current(doc, f, &state, &old.state))
{
if !old.skipped {
state = old.state.clone();
}
out.push(old.clone());
continue;
}
reuse = unkept && !cancelled;
if f.suppressed || rolled_back || cancelled {
out.push(FeatureResult {
id: f.id,
name: f.name.clone(),
error: None,
warning: None,
import_report: None,
repair: None,
ms: 0.0,
skipped: true,
stale: false,
fingerprint: fp,
unkept: false,
state: state.clone(),
});
continue;
}
// Taken from the design each time: a state taken from an earlier evaluation may have
// been made before a rename freed a name or a feature was suppressed.
if state.reserved_body_names != reserved {
Arc::make_mut(&mut state).reserved_body_names.clone_from(&reserved);
}
// A sketch the feature is built from failed earlier in this pass: the feature fails naming
// that sketch, with its error, as one using a failed parameter does (#9075), not as a
// sketch that must come earlier in the timeline. Never cached: the cache key holds
// neither the sketch's name nor its error (a rename, another failing value).
let failed_sketch = if failed.is_empty() {
None
} else {
f.kind.input_sketches().into_iter().find_map(|id| failed.get(&id)).map(|(name, e)| format!("sketch `{name}` failed: {e}"))
};
if let Some(e) = failed_sketch {
recomputed += 1;
reuse = false;
out.push(FeatureResult {
id: f.id,
name: f.name.clone(),
error: Some(e),
warning: None,
import_report: None,
repair: None,
ms: 0.0,
skipped: false,
stale: false,
fingerprint: fp,
unkept: false,
state: state.clone(),
});
continue;
}
// The same feature on the same inputs: its earlier result.
let key =
cache_key(f, fp, fingerprint(doc, 0, f, &vals, false, &self.step_digests) ^ placement_digest(doc, f, Some(&state)), ctx, &state);
let kept = self.kept.0.as_ref().filter(|_| !self.no_cache);
if !self.no_cache
&& let Some(c) = self
.cache
.lock()
.ok()
.and_then(|mut m| m.get(key))
.or_else(|| kept.and_then(|k| k.get(key)))
.filter(|c| c.error.is_some() || legacy_current(doc, f, &state, &c.state))
{
if let Some(k) = kept {
k.put(key, &c);
}
restored += 1;
if c.error.is_none() {
state = c.state.clone();
}
// A kept result after a failed one would not be this evaluation's.
reuse &= c.error.is_none();
out.push(FeatureResult {
id: f.id,
name: f.name.clone(),
error: c.error,
warning: c.warning,
import_report: c.import_report,
repair: c.repair,
ms: c.ms,
skipped: false,
stale: false,
fingerprint: fp,
unkept: false,
state: state.clone(),
});
continue;
}
// An active result hidden by the marker, or evaluated ahead on these same inputs
// (the same chain of definitions from the start). Changed inputs never reuse it.
if let Some(r) = rolled
.as_ref()
.filter(current)
.or_else(|| primed.as_ref().and_then(|p| p.get(&f.id)).filter(current))
.filter(|r| r.error.is_some() || legacy_current(doc, f, &state, &r.state))
{
restored += 1;
if r.error.is_none() {
state = r.state.clone();
}
reuse &= r.error.is_none();
out.push(FeatureResult { state: state.clone(), unkept: false, ..r.clone() });
continue;
}
recomputed += 1;
// Each feature computed is a profiler span named after its kind.
let _feature_span = solidcraft_profile::span("feature", f.kind.type_name());
let before = state.clone();
let t0 = now();
let mut next = (*state).clone();
// The names the design must not use again travel with the state (#4957, #4302).
next.reserved_body_names.clone_from(&reserved);
next.frame_bodies = Arc::downgrade(&self.frame_bodies);
for b in &mut next.bodies {
b.made = crate::lineage::Made::Before;
}
let mut warning = None;
let mut import_report = None;
let mut repair = None;
// Face references by name: move each face point onto its named face (on the body the
// feature names, when it names one and the face is there).
let renamed;
let mut frame_error: Option<String> = None;
let f = match with_named_face_points(doc, &state, f) {
Ok(Some((g, notes))) => {
if !notes.is_empty() {
warning = Some(notes.join("; "));
}
renamed = g;
&renamed
}
Ok(None) => f,
Err(e) => {
frame_error = Some(e.in_feature(&f.name).to_string());
f
}
};
// A parameter with an error fails the features using it, with that error.
let bad_param = param_names(f).into_iter().find_map(|n| self.param_errors.get(&n).map(|e| format!("parameter `{n}`: {e}")));
let r = match frame_error.or(bad_param) {
Some(e) => Err(kernel::KernelError::Failed(e)),
None => kernel::guard(&f.name, || {
let (r, deferred) =
kernel::validating(validation, || eval_feature(doc, &vals, f, &mut next, &mut warning, &mut import_report, &mut repair));
r.map_err(|e| kernel::KernelError::Failed(e.in_feature(&f.name).to_string()))?;
// The checks the feature's steps left to its end: the bodies it keeps.
if deferred { check_kept(&state, &next) } else { Ok(()) }
}),
};
if r.is_ok() {
// Profiles picked by curves that no longer bound a profile exactly were found
// by their best match: say which.
let thin = matches!(&f.kind, FeatureKind::Extrude { thin: Some(_), .. });
for (sketch, sel) in f.kind.profile_sels() {
if let (false, Some(ss)) = (thin, state.sketch(sketch)) {
for note in crate::profile_fallback_notes(ss, sel) {
append_warning(&mut warning, note);
}
}
}
track_altered_sheets(&state, &mut next, f, &mut warning);
note_join_apart(&state, &next, f, &mut warning);
}
let ms = t0.elapsed().as_secs_f64() * 1000.0;
let error = match r {
Ok(()) => {
// Copies are named after their sources through the instance transforms.
let mats = match &f.kind {
FeatureKind::Pattern { pattern, .. } => pattern_transforms(doc, &vals, &state, f.component, pattern).unwrap_or_default(),
FeatureKind::Mirror { plane, .. } => {
doc.resolve_plane_in(&vals, plane, 0, Some(&state)).map(|pl| vec![mirror_matrix(&pl)]).unwrap_or_default()
}
_ => Vec::new(),
};
// Copies made through a pattern or mirror among the sources come after (#395).
let mats = match &f.kind {
FeatureKind::Pattern { features, bodies, .. } | FeatureKind::Mirror { features, bodies, .. } if bodies.is_empty() => {
copy_instances(doc, &vals, &state, features, &mats).unwrap_or(mats)
}
_ => mats,
};
next.stamp(doc, &state, f, key, mats);
// Evaluated again only for what came before it (a mirror moved by a drag).
if let Some(old) = self.results.get(i).filter(|old| old.id == f.id) {
let made = old.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| (b.name.as_str(), b));
let made: std::collections::HashMap<&str, &ModelBody> = made.collect();
for b in next.bodies.iter_mut().filter(|b| b.feature == f.id) {
if let Some(old) = made.get(b.name.as_str()) {
b.keep_meshes_of(old);
}
}
}
for b in &mut next.bodies {
if !b.transferred {
b.component = match doc.body_components.get(&b.name) {
Some(c) => *c,
None => feature_component.get(&b.feature).copied().unwrap_or(0),
};
}
}
state = Arc::new(next);
// A window opening the design can show what is built so far.
watched.offer(i + 1, doc, &state);
None
}
Err(e) => Some(e.to_string().trim_start_matches("the operation failed: ").to_string()),
};
if !self.no_cache && !watched.cancelled() {
let e = CachedEval {
error: error.clone(),
warning: warning.clone(),
import_report: import_report.clone(),
repair: repair.clone(),
ms,
bytes: state.added_bytes(&before),
state: state.clone(),
};
if let Some(k) = &self.kept.0 {
k.put(key, &e);
}
if let Ok(mut m) = self.cache.lock() {
m.put(key, e);
}
}
reuse &= error.is_none();
out.push(FeatureResult {
id: f.id,
name: f.name.clone(),
error,
warning,
import_report,
repair,
ms,
skipped: false,
stale: false,
fingerprint: fp,
unkept: false,
state: state.clone(),
});
}
self.placement_local = self.placement_local && out.iter().all(|r| !r.skipped && !r.stale && !r.unkept && r.error.is_none());
self.results = out;
self.last_recomputed = recomputed;
self.recomputed += recomputed;
self.last_restored = restored;
}
}
impl Model {
/// Follow a rename of body `old` to `new` without evaluating anything (#3044): `doc` is the
/// design after the rename, which changed nothing but names, so every result keeps its
/// geometry and meshes and only the body's name (and the names worked out from it) changes.
/// Later features that change the body (a pattern, a chamfer, a join) keep their results
/// too (#2467): a feature's geometry doesn't depend on its bodies' names. A body no later
/// feature changes is followed even when other bodies are numbered after it (`X (2)`, the
/// solids of a STEP file that share a label): `body.rename` keeps their names.
/// False, leaving the model as it was, when the rename can't be followed that way and the
/// design must be evaluated: the model isn't the design's, a body of that name comes and goes
/// or isn't the same body throughout, a later body's name is worked out from a body later
/// features change, a message quotes it, or it is sheet metal, threaded, or named in a later
/// feature's face references.
pub fn rename_body(&mut self, doc: &Document, old: &str, new: &str) -> bool {
if self.results.len() != doc.features.len() || self.results.iter().zip(&doc.features).any(|(r, f)| r.id != f.id || r.stale) {
return false;
}
let Some(at) = self.results.iter().position(|r| r.state.body(old).is_some()) else { return false };
let Some((feature, made)) = self.results.get(at).and_then(|r| r.state.body(old)).map(|b| (b.feature, Arc::as_ptr(&b.mesh))) else {
return false;
};
// Untouched from the feature that made it to the end: `body.rename` keeps the names of
// its siblings and of later bodies named after it (`X (2)`, the solids of a STEP file
// with one label), so evaluating the renamed design gives the same names.
let untouched = self.results.iter().skip(at).all(|r| r.state.body(old).is_some_and(|b| Arc::as_ptr(&b.mesh) == made));
// Or one body from the feature that made it until it is gone (joined into another), and
// no other body's name comes from its name.
let held: Vec<bool> = self.results.iter().skip(at).map(|r| r.state.body(old).is_some()).collect();
let one_run = held.iter().skip_while(|h| **h).all(|h| !*h);
let derived = format!("{old} (");
let same_body = || {
self.results
.iter()
.skip(at)
.all(|r| r.state.bodies.iter().all(|b| if b.name == old { b.feature == feature } else { !b.name.starts_with(&derived) }))
};
let quoted = self.results.iter().skip(at).any(|r| [&r.error, &r.warning].into_iter().flatten().any(|m| m.contains(old)));
let named_elsewhere = self
.results
.iter()
.any(|r| r.state.body(new).is_some() || r.state.sheets.iter().any(|x| x.body == old) || r.state.threads.iter().any(|t| t.body == old));
let faces_named = doc.features.iter().skip(at + 1).any(|f| f.face_names.iter().any(|n| n.contains(old)));
if !(untouched || (one_run && same_body())) || quoted || named_elsewhere || faces_named {
return false;
}
// States shared between results stay shared.
let mut renamed: std::collections::HashMap<*const ModelState, Arc<ModelState>> = std::collections::HashMap::new();
for r in self.results.iter_mut().skip(at) {
let state = renamed
.entry(Arc::as_ptr(&r.state))
.or_insert_with(|| {
let mut st = (*r.state).clone();
for b in st.bodies.iter_mut().filter(|b| b.name == old) {
b.name = new.to_string();
b.names = b.names.renamed();
}
// The names the design must not use again travel with the state (#4957).
st.reserved_body_names = doc.reserved_body_names.clone();
Arc::new(st)
})
.clone();
r.state = state;
}
self.refingerprint(doc);
true
}
/// Follow a rename of feature `id` to `doc`'s name for it without evaluating anything: a
/// feature's name labels it (its result, its sketch, its construction geometry) but builds
/// nothing. False, leaving the model as it was, when the model isn't the design's, the
/// feature failed, or a later failed feature's error quotes its old name: evaluate then.
pub fn rename_feature(&mut self, doc: &Document, id: u64) -> bool {
if self.results.len() != doc.features.len() || self.results.iter().zip(&doc.features).any(|(r, f)| r.id != f.id || r.stale) {
return false;
}
let Some(name) = doc.feature(id).map(|f| f.name.clone()) else { return false };
let Some(at) = self.results.iter().position(|r| r.id == id) else { return false };
// An error may quote the old name: the feature's own, or a later one's that refers to it
// by id (a pattern of it: "{name} cannot be patterned or mirrored yet").
let old = self.results.get(at).map(|r| r.name.clone()).unwrap_or_default();
if self.results.iter().skip(at).any(|r| r.error.as_deref().is_some_and(|e| r.id == id || e.contains(&old))) {
return false;
}
if let Some(r) = self.results.get_mut(at) {
r.name.clone_from(&name);
}
let mut renamed: std::collections::HashMap<*const ModelState, Arc<ModelState>> = std::collections::HashMap::new();
for r in self.results.iter_mut().skip(at) {
let labels = r.state.sketches.iter().any(|k| k.feature == id) || r.state.construct.iter().any(|c| c.feature == id);
if !labels {
continue;
}
let state = renamed
.entry(Arc::as_ptr(&r.state))
.or_insert_with(|| {
let mut st = (*r.state).clone();
for k in st.sketches.iter_mut().filter(|k| k.feature == id) {
Arc::make_mut(k).name.clone_from(&name);
}
for c in st.construct.iter_mut().filter(|c| c.feature == id) {
c.name.clone_from(&name);
}
Arc::new(st)
})
.clone();
r.state = state;
}
self.refingerprint(doc);
true
}
/// Set every result's fingerprint to `doc`'s, so the next evaluation reuses every result
/// (after a change that builds nothing differently).
pub fn refingerprint(&mut self, doc: &Document) {
self.refingerprint_from(doc, 0);
}
/// How many leading results keep their fingerprints when `doc` has the body names of the
/// features `renamed` pinned, and nothing else changed (see [`Model::refingerprint_shared`]).
/// Every command pins, and fingerprinting the whole timeline again for it cost as much as
/// the fingerprinting of the evaluation itself. When the results hold `doc`'s fingerprints
/// (the address and digest kept when they were given prove it), those before the first
/// renamed feature stand, since nothing they read changes, unless a pattern or mirror of
/// features among them replays a renamed one (it fingerprints its sources' definitions
/// wherever they are). Without that proof: none.
pub fn pinned_prefix(&self, doc: &Arc<Document>, renamed: &[u64]) -> usize {
let proven = self.fingerprinted.is_some_and(|(of, digest)| of == Arc::as_ptr(doc) as usize && digest == fingerprints_digest(&self.results));
if !proven {
return 0;
}
let Some(first) = doc.features.iter().position(|f| renamed.contains(&f.id)) else { return doc.features.len() };
let replays_renamed = |f: &Feature| match &f.kind {
FeatureKind::Pattern { features, bodies, .. } | FeatureKind::Mirror { features, bodies, .. } => {
bodies.is_empty() && !features.is_empty() && replayed_sources(doc, features).iter().any(|g| renamed.contains(&g.id))
}
_ => false,
};
doc.features.iter().take(first).position(replays_renamed).unwrap_or(first)
}
/// Drop the proof [`Model::pinned_prefix`] reads: the document at that address is about to
/// change in place.
pub fn forget_fingerprints(&mut self) {
self.fingerprinted = None;
}
/// Fingerprint the results from `start` on for `doc`, chained onto the fingerprint before.
pub(crate) fn refingerprint_from(&mut self, doc: &Document, start: usize) {
self.placement_inputs = None;
self.fingerprinted = None;
self.step_digests = StepDigests::of(doc, &self.step_digests);
let start = start.min(self.results.len()).min(doc.features.len());
if start == self.results.len().min(doc.features.len()) {
return;
}
let (vals, _) = evaluation_values(doc);
let marker = doc.marker.unwrap_or(usize::MAX);
let last = start.checked_sub(1).and_then(|i| self.results.get(i));
let mut prev = last.map_or(0, |r| r.fingerprint);
// Each feature's fingerprint reads the model it starts from, as evaluating does.
let mut before = last.map_or_else(|| Arc::new(ModelState::default()), |r| r.state.clone());
for (i, (r, f)) in self.results.iter_mut().zip(&doc.features).enumerate().skip(start) {
prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.step_digests, Some(&before));
r.fingerprint = prev;
before = r.state.clone();
}
}
/// Note that the results now hold `doc`'s fingerprints (for [`Model::pinned_prefix`]).
pub(crate) fn mark_fingerprinted(&mut self, doc: &Arc<Document>) {
self.fingerprinted = Some((Arc::as_ptr(doc) as usize, fingerprints_digest(&self.results)));
}
}
/// A digest of the results' features and fingerprints, which proves they are still the ones
/// [`Model::mark_fingerprinted`] saw (whatever changed them since).
fn fingerprints_digest(results: &[FeatureResult]) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
results.len().hash(&mut h);
for r in results {
r.id.hash(&mut h);
r.fingerprint.hash(&mut h);
}
h.finish()
}
/// Key of the design's length unit (mm per unit) among the values (no parameter can be named
/// so).
pub(crate) const DESIGN_LEN: &str = "\u{1}design_len";
/// An expression's value. A length that comes out unit-less without being a bare number (a
/// unit-less parameter used as a length) is in the design's units.
/// A point given as length expressions.
fn point(vals: &BTreeMap<String, Value>, p: &crate::PointExpr) -> Result<Vec3> {
let [x, y, z] = p;
let v = Vec3::new(val(vals, x, Kind::Length)?, val(vals, y, Kind::Length)?, val(vals, z, Kind::Length)?);
if [v.x, v.y, v.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) { Ok(v) } else { Err(DocError::Invalid("the position is out of range".into())) }
}
pub(crate) fn val(vals: &BTreeMap<String, Value>, e: &str, k: Kind) -> Result<f64> {
let scale = vals.get(DESIGN_LEN).map(|x| x.v).unwrap_or(1.0);
// Non-literal lengths (a parameter ± a bare number) must read that bare number in the design's
// units during the expression, not only when the whole result is unit-less (#9015).
if k == Kind::Length && scale != 1.0 && !expr::is_literal(e) {
let defaults = expr::Defaults { len: scale, ..expr::Defaults::default() };
let look = |n: &str| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`")));
return expr::eval_with_defaults(e, &look, defaults)?.to_kind_in(k, defaults);
}
Document::eval_in(vals, e, k)
}
#[cfg(test)]
mod design_unit_val_tests {
use super::*;
use expr::Value;
/// #9015: with inches as the design unit, `baseLength - 1` subtracts one inch (not one mm).
#[test]
fn bare_offsets_beside_a_length_follow_the_design_units() {
let mut vals = BTreeMap::new();
vals.insert(DESIGN_LEN.into(), Value::num(25.4));
vals.insert("baseLength".into(), Value::length(76.0 * 25.4));
let got = val(&vals, "baseLength - 1", Kind::Length).unwrap();
assert!((got - 75.0 * 25.4).abs() < 1e-9, "got {got} mm, want 75 in");
let got = val(&vals, "baseLength - 1.5", Kind::Length).unwrap();
assert!((got - 74.5 * 25.4).abs() < 1e-9, "got {got} mm, want 74.5 in");
// An explicit millimetre still wins.
let got = val(&vals, "baseLength - 1 mm", Kind::Length).unwrap();
assert!((got - (76.0 * 25.4 - 1.0)).abs() < 1e-9, "got {got}");
// A bare literal stays millimetres (feature inputs write the design unit in when typed).
let got = val(&vals, "2", Kind::Length).unwrap();
assert!((got - 2.0).abs() < 1e-12, "got {got}");
}
}
/// Collapsing the outline and its holes onto one apex cannot make a manifold solid.
fn refuse_loft_holes(r: &Region2) -> Result<()> {
if r.holes.is_empty() {
return Ok(());
}
Err(DocError::Invalid("not supported yet: lofting a section with holes to a point".into()))
}
/// What each way of closing a taper's corners ([`kernel::DraftCorner`]) gives at each sharp
/// corner of the profiles `sel` picks in `ss`, extruded `distance` with a taper of `taper` radians
/// (positive grows the profile), the profiles merged as an extrude merges them: per corner, how
/// far each offset curve runs on (or is trimmed), whether the corner cuts in, or why the rule
/// refuses it. A dialog offers the other rules where the chosen one is a poor fit.
pub fn draft_corner_options(ss: &SolvedSketch, sel: &ProfileSel, distance: f64, taper: f64) -> Result<Vec<kernel::CornerReport>> {
let regions = solidcraft_sketch::merge_regions(&select_profiles(ss, sel)?);
let mut out = Vec::new();
for r in &regions {
out.extend(kernel::draft_corners(r, distance, taper)?);
}
Ok(out)
}
/// The corner rule a taper takes for profile `r` of `ss` when the user chose none: preserve
/// curvature, unless a corner of the profile cannot keep it exactly (a curve that is neither a
/// line nor an arc), then the tangent rule, with a note in `notes` saying where and why.
fn draft_corner_for(ss: &SolvedSketch, r: &Region2, distance: f64, taper: f64, notes: &mut Vec<String>) -> Result<kernel::DraftCorner> {
let reports = kernel::draft_corners(r, distance, taper)?;
let inexact = reports
.iter()
.find(|c| c.options.iter().any(|o| o.rule == kernel::DraftCorner::PreserveCurvature && o.fill == Err(kernel::CornerRefusal::NotExact)));
Ok(match inexact {
Some(c) => {
notes.push(format!(
"the taper's corners of profile at ({}, {}) in {} use the tangent rule: a curve of it is neither a line nor an arc, so its walls cannot continue as themselves exactly; corner: round also builds",
show_mm(c.at.x),
show_mm(c.at.y),
ss.name
));
kernel::DraftCorner::Tangent
}
None => kernel::DraftCorner::PreserveCurvature,
})
}
pub fn select_profiles(ss: &SolvedSketch, sel: &ProfileSel) -> Result<Vec<Region2>> {
let ps = &ss.profiles;
if ps.is_empty() {
return Err(DocError::Invalid(format!("{} has no closed profiles", ss.name)));
}
let out: Vec<Region2> = match sel {
// "All" means what was drawn: projected reference geometry (a face's auto-projected
// edges) only counts when the drawn curves alone make no profile. Text is drawn, and
// its letters keep their counters as holes (the counters are not filled in).
ProfileSel::All => {
let drawn = solidcraft_sketch::find_drawn_profiles(&ss.sketch);
let chosen = if drawn.is_empty() { ps.clone() } else { drawn };
solidcraft_sketch::without_text_counters(&ss.sketch, chosen).into_iter().map(|p| p.region).collect()
}
ProfileSel::Indices { indices } => {
// A design file may list a profile more than once; it is still one profile.
let mut seen = std::collections::BTreeSet::new();
let mut v = Vec::new();
for i in indices.iter().filter(|i| seen.insert(**i)) {
v.push(ps.get(*i).ok_or_else(|| DocError::Unknown(format!("profile {i} of {}", ss.name)))?.region.clone());
}
v
}
// A curve loop that no longer bounds a profile exactly falls back to the best match; the
// feature's warning says so (`profile_fallback_notes`).
ProfileSel::Curves { .. } | ProfileSel::OffsetBoundaries { .. } | ProfileSel::WholeBoundaries { .. } => {
crate::profile_selection_indices_lenient(ss, sel)?
.0
.into_iter()
.map(|index| {
ps.get(index)
.map(|profile| profile.region.clone())
.ok_or_else(|| DocError::Invalid("profile index changed during resolution".into()))
})
.collect::<Result<Vec<_>>>()?
}
ProfileSel::Points { points } => {
let mut v = Vec::new();
for p in points {
// Innermost profile containing the point.
let found = solidcraft_sketch::profile_at_point(ps, *p).and_then(|i| ps.get(i));
v.push(found.ok_or_else(|| DocError::Unknown(format!("profile at {:?} in {}", [p.x, p.y], ss.name)))?.region.clone());
}
v
}
};
if out.is_empty() {
return Err(DocError::Invalid("no profile selected".into()));
}
Ok(out)
}
/// The error for a profile picked by curves that no longer names exactly one profile.
pub fn curve_pick_error(e: solidcraft_sketch::CurvePick, ids: &[String], sketch: &str) -> DocError {
match e {
solidcraft_sketch::CurvePick::Missing => DocError::Invalid(format!(
"no profile of {sketch} is bounded by exactly the curves {ids:?} (a curve was deleted, or another curve now cuts the region)"
)),
solidcraft_sketch::CurvePick::Ambiguous(n) => DocError::Invalid(format!(
"{n} profiles of {sketch} are bounded by exactly the curves {ids:?}; add a curve that tells them apart, or pick by index or point"
)),
}
}
fn new_name(state: &mut ModelState, f: &Feature, k: usize) -> String {
if let Some(n) = f.body_names.get(k)
&& !n.is_empty()
&& state.body(n).is_none()
{
// A pinned `BodyN` counts as handed out, so a design evaluated again from its stored
// names ends with the counter it had when the counter numbered them.
if let Some(number) = n.strip_prefix("Body").filter(|_| crate::is_counted_body_name(n)).and_then(|d| d.parse::<usize>().ok()) {
state.body_counter = state.body_counter.max(number);
}
return n.clone();
}
// Bodies past the stored names (a profile added after the feature was made) are numbered
// after the first name: `Ribs (4)` (#373). Features saved before format 14 keep `BodyN`,
// which later features of those designs may name.
if !f.shell_piece_order
&& k >= f.body_names.len()
&& let Some(base) = f.body_names.first().map(|n| n.trim()).filter(|n| !n.is_empty())
{
let n = format!("{base} ({})", k.saturating_add(1));
return if state.body(&n).is_none() { n } else { unique_body_name(state, base) };
}
loop {
state.body_counter += 1;
let n = format!("Body{}", state.body_counter);
// A name a rename freed is not handed out again (#4957).
if state.body(&n).is_none() && !state.reserved_body_names.contains(&n) {
return n;
}
}
}
/// The k-th body of a body pattern: its stored name, else a copy of `source`. Once `body.rename`
/// has stored this feature's names, a copy beyond them (the count was raised) is numbered after
/// the highest stored `source (n)`, so it never takes a number freed by a rename (#372).
/// Features without stored names keep the first free `source (n)`.
fn pattern_copy_name(state: &ModelState, f: &Feature, k: usize, source: &str) -> String {
if f.body_names.get(k).is_some_and(|name| !name.trim().is_empty()) {
return copy_body_name(state, f, k, source);
}
let base = if source.trim().is_empty() { "Body" } else { source.trim() };
let prefix = format!("{base} (");
let highest = f.body_names.iter().filter_map(|n| n.trim().strip_prefix(prefix.as_str())?.strip_suffix(')')?.parse::<u32>().ok()).max();
match highest {
Some(h) => {
(u64::from(h) + 1..).map(|i| format!("{base} ({i})")).find(|n| state.body(n).is_none()).unwrap_or_else(|| unique_body_name(state, base))
}
None => unique_body_name(state, base),
}
}
fn copy_body_name(state: &ModelState, f: &Feature, k: usize, source: &str) -> String {
let base = f.body_names.get(k).filter(|name| !name.trim().is_empty()).map(String::as_str).unwrap_or(source);
unique_body_name(state, base)
}
/// Keeps each sheet metal body's flat pattern true to the body (see `SheetBody::altered_by`).
/// A feature that changes a sheet body's material but not its sheet model (a fillet, a join, a
/// mirror combined into it) marks the sheet with its name, and says so. A feature that rebuilds
/// the body from the model (a sheet metal feature, or machining the model keeps as cut-outs,
/// which changes the model) clears the mark, and says that the change it drops is not kept.
/// Features that move whole bodies or only mark their faces (a cosmetic thread, not a modelled
/// one, which cuts material) leave the flat pattern as it was.
fn track_altered_sheets(before: &ModelState, after: &mut ModelState, f: &Feature, warning: &mut Option<String>) {
if matches!(
f.kind,
FeatureKind::Move { .. }
| FeatureKind::Align { .. }
| FeatureKind::Rest { .. }
| FeatureKind::BodyTransfer { .. }
| FeatureKind::SplitFace { .. }
| FeatureKind::Thread { modeled: false, .. }
) {
return;
}
let ModelState { sheets, bodies, .. } = after;
for sh in sheets.iter_mut() {
let Some(old) = before.sheets.iter().find(|s| s.body == sh.body) else { continue };
let (Some(was), Some(now)) = (before.body(&sh.body), bodies.iter().find(|b| b.name == sh.body)) else { continue };
if was.body.same_shape(&now.body) {
continue;
}
if f.kind.is_sheet() || sh != old {
if let Some(lost) = sh.altered_by.take() {
append_warning(
warning,
format!("`{}` is rebuilt from its sheet metal features: what {lost} changed is not kept (not supported yet)", sh.body),
);
}
} else if sh.altered_by.is_none() {
sh.altered_by = Some(f.name.clone());
append_warning(
warning,
format!(
"`{}` is sheet metal: its flat pattern, DXF and bend table can't include this change yet and are refused; a later sheet metal feature rebuilds the body without it",
sh.body
),
);
}
}
}
/// A Join whose material meets none of its targets still joins it, to the first target as a
/// separate piece (see `apply_traced`): a valid body in several pieces, but rarely what was meant
/// when Join was left on by mistake. Says so when a feature's Join leaves the bodies it changed
/// in more pieces than they had (#4434). Combine joins the bodies it is given, apart or not.
fn note_join_apart(before: &ModelState, after: &ModelState, f: &Feature, warning: &mut Option<String>) {
let operation = match &f.kind {
FeatureKind::Extrude { operation, .. }
| FeatureKind::Revolve { operation, .. }
| FeatureKind::Box { operation, .. }
| FeatureKind::Cylinder { operation, .. }
| FeatureKind::Sphere { operation, .. }
| FeatureKind::Torus { operation, .. }
| FeatureKind::Cone { operation, .. }
| FeatureKind::Loft { operation, .. }
| FeatureKind::Sweep { operation, .. }
| FeatureKind::Pipe { operation, .. }
| FeatureKind::Coil { operation, .. }
| FeatureKind::BoundaryFill { operation, .. }
| FeatureKind::Thicken { operation, .. }
| FeatureKind::SurfaceNetwork { operation, .. } => *operation,
_ => return,
};
if operation != Operation::Join {
return;
}
for (name, n) in join_pieces_added(before, after) {
append_warning(
warning,
format!("the joined piece doesn't touch `{name}`, so `{name}` is now in {n} separate pieces (New Body makes it a body of its own)"),
);
}
}
/// The bodies a Join from `before` to `after` left in more separate pieces than it found, with
/// their piece counts now: empty when the joined material made one body with what it touched
/// (or bridged pieces). A lid closing a cavity adds a void, not a piece.
pub fn join_pieces_added(before: &ModelState, after: &ModelState) -> Vec<(String, usize)> {
let pieces = |b: &Body| b.lumps().map_or(1, |l| l.len());
// Pieces of the bodies the join changed or absorbed before it, and of those it kept after.
let (mut had, mut have) = (0usize, 0usize);
let mut grown: Vec<(String, usize)> = Vec::new();
for was in &before.bodies {
match after.body(&was.name) {
Some(now) if now.body.same_shape(&was.body) => {}
Some(now) => {
let (old, new) = (pieces(&was.body), pieces(&now.body));
had += old;
have += new;
if new > old {
grown.push((now.name.clone(), new));
}
}
None => had += pieces(&was.body),
}
}
if have <= had { Vec::new() } else { grown }
}
/// Add tool bodies to the model according to the operation.
fn sheet_boolean_unchanged(body: &Body, tools: &[Body], op: Operation) -> Result<()> {
if sheet_boolean_changes(body, tools, op)? {
return Err(DocError::Invalid("this sheet machining cannot be preserved in its flat material: use a parallel, untapered extrude pocket/cut, or unfold before intersecting; unsupported 3D sheet machining is refused to prevent material restoration".into()));
}
Ok(())
}
fn sheet_boolean_changes(body: &Body, tools: &[Body], op: Operation) -> Result<bool> {
let united;
let tools: &[Body] = if op == Operation::Intersect {
united = intersection_tool_union(tools.iter().cloned().map(Traced::unnamed).collect())?.into_iter().map(|t| t.body).collect::<Vec<_>>();
&united
} else {
tools
};
for tool in tools {
let test = if op == Operation::Cut { BoolOp::Intersect } else { BoolOp::Cut };
if kernel::boolean(body, tool, test)?.is_some() {
return Ok(true);
}
}
Ok(false)
}
/// Selected profiles form one machining tool, including disconnected tool material: their
/// union in one kernel call.
fn intersection_tool_union(tools: Vec<Traced>) -> Result<Vec<Traced>> {
if tools.len() > 1000 || tools.iter().fold(0usize, |n, t| n.saturating_add(t.body.face_count())) > 16_384 {
return Err(DocError::Invalid("intersection tools exceed the bounded geometry budget".into()));
}
if tools.len() < 2 {
return Ok(tools);
}
Ok(vec![union_all(&tools.iter().collect::<Vec<_>>())?])
}
/// The union of `operands` (traced bodies) in one kernel call, keeping their lineage.
fn union_all(operands: &[&Traced]) -> Result<Traced> {
let bodies: Vec<&Body> = operands.iter().map(|t| &t.body).collect();
Ok(Traced::step(kernel::union_all(&bodies)?, operands))
}
/// After a cut handled some sheet bodies as flat machining, apply it to the other targets.
fn apply_beside_sheet_cut(
doc: &Document,
st: &mut ModelState,
f: &Feature,
tools: Vec<Traced>,
op: Operation,
targets: &[String],
handled: &[String],
) -> Result<()> {
let effective = if targets.is_empty() { &f.participants } else { targets };
let all = effective.len() == 1 && effective.first().is_some_and(|t| t == "*");
let rest: Vec<String> = st
.bodies
.iter()
.filter(|b| {
!handled.contains(&b.name)
&& (all || if effective.is_empty() { b.component == f.component || b.feature == f.id } else { effective.contains(&b.name) })
})
.map(|b| b.name.clone())
.collect();
if rest.is_empty() {
return Ok(());
}
apply_traced(doc, st, f, tools, op, &rest)
}
fn apply_op(doc: &Document, state: &mut ModelState, f: &Feature, tools: Vec<Body>, op: Operation, targets: &[String]) -> Result<()> {
apply_traced(doc, state, f, tools.into_iter().map(Traced::unnamed).collect(), op, targets)
}
/// Many cut tools clear of each other (a pattern's copies, the circles of a vent field in one
/// sketch) as one tool of many pieces, so the target is cut once instead of rebuilding an ever
/// more complex body for every tool (#261, #368). Tools that may meet are left as they are.
fn clear_tools_as_one(tools: Vec<Traced>) -> Result<Vec<Traced>> {
if tools.len() < 8 {
return Ok(tools);
}
let bodies: Vec<Body> = tools.iter().map(|t| t.body.clone()).collect();
Ok(match kernel::union_apart(&bodies)? {
// Each piece's faces keep the names of the tool it is.
Some(one) => vec![Traced::step(one, &tools.iter().collect::<Vec<_>>())],
None => tools,
})
}
/// An intersect never deletes a body by accident (#5295): it is refused when nothing of a named
/// target would remain, when nothing of any target would remain, or when the tools meet a target
/// and the boolean still came out empty. Only an unnamed target the tools miss altogether is
/// removed, as an intersect with every body does (#5160).
pub(crate) fn empty_intersection(bodies: &[&str]) -> DocError {
let body = match bodies {
[one] => format!("`{one}`"),
[first, rest @ ..] => format!("`{first}` and {} more", rest.len()),
[] => "the target body".to_string(),
};
DocError::Invalid(format!("the intersection is empty: nothing of {body} would remain; check that the profile overlaps the body"))
}
/// The bodies a feature's boolean takes part in, and whether they were named rather than taken
/// by default (every body, or the feature's component).
pub(crate) fn boolean_scope(state: &ModelState, f: &Feature, targets: &[String]) -> (bool, Vec<String>) {
let effective = if targets.is_empty() { &f.participants } else { targets };
let all = effective.len() == 1 && effective.first().is_some_and(|t| t == "*");
let names = state
.bodies
.iter()
.filter(|b| all || if effective.is_empty() { b.component == f.component || b.feature == f.id } else { effective.contains(&b.name) })
.map(|b| b.name.clone())
.collect();
(!all && !effective.is_empty(), names)
}
/// Suggest one nearby body without changing the default component scope or running a boolean.
fn empty_boolean_targets(doc: &Document, state: &ModelState, f: &Feature, tools: &[Traced], default_targets: bool) -> DocError {
let plain = "there is no body to cut or intersect";
if !default_targets {
return DocError::Invalid(plain.into());
}
let component_name = |id| {
if id == 0 {
doc.name.clone()
} else {
doc.components.iter().take(10_000).find(|c| c.id == id).map(|c| c.name.clone()).unwrap_or_else(|| format!("Component{id}"))
}
};
let tool_bounds: Vec<_> = tools.iter().take(64).map(|t| t.body.outline_bounds()).collect();
let frame = doc.component_transform(f.component);
let Some(inverse) = crate::mat_inverse(&frame) else { return DocError::Invalid(plain.into()) };
// Named by the component the Browser shows the body in; one shown in the feature's own
// component has no other component to point at.
let others = state
.bodies
.iter()
.take(256)
.map(|b| (b, doc.model_body_component(b)))
.filter(|(b, owner)| b.component != f.component && *owner != f.component);
for (body, owner) in others {
// Compare in the feature's frame, including component placements and body offsets.
let world = body_world(doc, body);
let relative = crate::mat_mul(&inverse, &world);
let bounds = body.outline_bounds();
if bounds.is_empty() || !bounds.min.is_finite() || !bounds.max.is_finite() {
continue;
}
let mut placed = solidcraft_geom::Aabb3::EMPTY;
for x in [bounds.min.x, bounds.max.x] {
for y in [bounds.min.y, bounds.max.y] {
for z in [bounds.min.z, bounds.max.z] {
placed.add(crate::apply_point(&relative, Vec3::new(x, y, z)));
}
}
}
if tool_bounds.iter().any(|b| !b.is_empty() && b.min.is_finite() && b.max.is_finite() && b.meets(&placed)) {
let own = component_name(f.component);
let other = component_name(owner);
let name = &body.name;
return DocError::Invalid(format!(
"{plain} in component '{own}'; the tool may overlap '{name}' in component '{other}' — activate that component or pick the body as a target"
));
}
}
DocError::Invalid(plain.into())
}
/// [`apply_op`] with tools whose lineage is known: the bodies it makes or changes keep theirs.
fn apply_traced(doc: &Document, state: &mut ModelState, f: &Feature, tools: Vec<Traced>, op: Operation, targets: &[String]) -> Result<()> {
apply_traced_with(doc, state, f, tools, op, targets, &[])
}
/// [`apply_traced`] with bodies that take part in the boolean besides the feature's targets:
/// the body a Join extrude runs to (#6424), which joins with the tool.
fn apply_traced_with(
doc: &Document,
state: &mut ModelState,
f: &Feature,
tools: Vec<Traced>,
op: Operation,
targets: &[String],
extra: &[String],
) -> Result<()> {
let tools = if op == Operation::Intersect { intersection_tool_union(tools)? } else { tools };
// Participants: the feature's own targets, else its explicit participants, else the bodies
// of its component (and what it made itself): other components are left alone.
let targets: &[String] = if targets.is_empty() { &f.participants } else { targets };
let all = targets.len() == 1 && targets.first().is_some_and(|t| t == "*");
let named = !all && !targets.is_empty();
let mut target_idx: Vec<usize> = if all {
(0..state.bodies.len()).collect()
} else if targets.is_empty() {
(0..state.bodies.len()).filter(|i| state.bodies.get(*i).is_some_and(|b| b.component == f.component || b.feature == f.id)).collect()
} else {
let mut v = Vec::new();
for t in targets {
v.push(state.bodies.iter().position(|b| &b.name == t).ok_or_else(|| DocError::Unknown(format!("body `{t}`")))?);
}
v
};
// Bodies that take part besides the feature's own targets: the body a Join extrude runs to
// joins with the tool (#6424), when it is in the feature's own component. A body of another
// component (the shell a connector's boss runs up to) joins only when the feature names it:
// an extent's end face never pulls a part across a component boundary.
for name in extra {
if let Some(i) = state.bodies.iter().position(|b| &b.name == name && b.component == f.component)
&& !target_idx.contains(&i)
{
target_idx.push(i);
}
}
if op == Operation::NewBody || target_idx.is_empty() {
if op == Operation::Cut || op == Operation::Intersect {
return Err(empty_boolean_targets(doc, state, f, &tools, targets.is_empty()));
}
for (k, t) in tools.into_iter().enumerate() {
let name = new_name(state, f, k);
state.bodies.push(ModelBody::traced_new(name, t, f.id));
}
return Ok(());
}
if matches!(op, Operation::Cut | Operation::Intersect) {
// A cut that cannot reach a sheet leaves it as it is (#10226): a sheet whose box lies
// clear of every tool's, in its own frame, needs no boolean to show it. An intersect
// removes the sheets it misses, and checks each one as before.
let mut reach: Option<Vec<Option<solidcraft_geom::Aabb3>>> = None;
for &i in &target_idx {
if let Some(mb) = state.bodies.get(i).filter(|b| state.sheets.iter().any(|s| s.body == b.name)) {
let m = tool_frame(&mb.name);
if op == Operation::Cut && m.is_none() && !mb.body.is_mesh() && !tools.iter().any(|t| t.body.is_mesh()) {
let reach = reach.get_or_insert_with(|| tools.iter().map(|t| more::exact_box(&t.body)).collect());
if !reach.is_empty()
&& let Some(target) = more::exact_box(&mb.body)
&& reach.iter().all(|tool| more::boxes_apart(&Some(target), tool))
{
continue;
}
}
let bodies: Vec<Body> = tools.iter().map(|t| tool_in(t, m).map(|t| t.body)).collect::<Result<_>>()?;
#[cfg(test)]
cost_tests::count(|c| c.cut += 1);
sheet_boolean_unchanged(&mb.body, &bodies, op)?;
}
}
}
match op {
Operation::Join => {
let joined = join(state, tools, &target_idx)?;
if f.touching == crate::Touching::Separate {
let mut kept = None;
for name in joined {
kept = kept.max(separate_touching(state, &name)?);
}
if let Some(k) = kept {
let most = state.kept_separate.entry(f.id).or_insert(k);
*most = (*most).max(k);
}
}
}
Operation::Cut | Operation::Intersect => {
let bop = if op == Operation::Cut { BoolOp::Cut } else { BoolOp::Intersect };
let tools = if op == Operation::Cut { clear_tools_as_one(tools)? } else { tools };
// Each target's pieces before the cut: a body joined from separate pieces stays one.
let affected: std::collections::BTreeMap<String, usize> =
target_idx.iter().filter_map(|i| state.bodies.get(*i)).map(|b| (b.name.clone(), b.body.lumps().map_or(1, |l| l.len()))).collect();
let mut remove = Vec::new();
// A cut hands a body its tools cannot reach back as it was, but only after a whole
// boolean: in a design of many bodies that was most of a hole's time (#10225). A body
// whose exact box lies clear of every tool's is left as it is. A body shown in another
// frame, and a mesh body, are cut as before; an intersect removes the bodies it misses.
let reach: Option<Vec<Option<solidcraft_geom::Aabb3>>> =
(op == Operation::Cut && !tools.iter().any(|t| t.body.is_mesh())).then(|| tools.iter().map(|t| more::exact_box(&t.body)).collect());
for &ti in &target_idx {
let Some(mut acc) = state.bodies.get(ti).map(|b| Some(b.traced())) else { continue };
// The tools meet the target where it is shown: in its frame (#3383).
let into = state.bodies.get(ti).and_then(|b| tool_frame(&b.name));
if let (Some(reach), None, Some(mb)) = (&reach, into, state.bodies.get(ti))
&& !reach.is_empty()
&& !mb.body.is_mesh()
&& let Some(target) = more::exact_box(&mb.body)
&& reach.iter().all(|tool| more::boxes_apart(&Some(target), tool))
{
continue;
}
#[cfg(test)]
cost_tests::count(|c| c.cut += 1);
for t in &tools {
let t = &tool_in(t, into)?;
acc = match acc {
Some(a) => kernel::boolean(&a.body, &t.body, bop)?.map(|r| Traced::step(r, &[&a, t])),
None => None,
};
}
if op == Operation::Intersect && acc.as_ref().is_none_or(|b| b.body.face_count() == 0) {
let Some(mb) = state.bodies.get(ti) else { continue };
// A tool that meets the body yet leaves nothing is a failed boolean, not an empty result.
let mut met = false;
if !named && !mb.body.is_mesh() {
for t in &tools {
if mb.body.meets(&tool_in(t, into)?.body)? {
met = true;
break;
}
}
}
if named || met {
return Err(empty_intersection(&[mb.name.as_str()]));
}
remove.push(ti);
continue;
}
match acc {
Some(b) => {
if let Some(mb) = state.bodies.get_mut(ti) {
*mb = ModelBody::traced_new(mb.name.clone(), b, mb.feature);
}
}
None => remove.push(ti),
}
}
if op == Operation::Intersect && target_idx.iter().all(|i| remove.contains(i)) {
let names: Vec<&str> = target_idx.iter().filter_map(|i| state.bodies.get(*i)).map(|b| b.name.as_str()).collect();
return Err(empty_intersection(&names));
}
let mut i = 0;
state.bodies.retain(|_| {
let keep = !remove.contains(&i);
i += 1;
keep
});
let live: std::collections::BTreeSet<&str> = state.bodies.iter().map(|b| b.name.as_str()).collect();
state.threads.retain(|t| live.contains(t.body.as_str()));
// A cut can leave a body in pieces: each piece becomes its own body ("Bar", "Bar (1)"),
// numbered on past names already taken (a body cut in pieces before). Only a cut that
// made more pieces than the body had splits it: the pieces of a join stay together.
// Not yet: a cut that splits one piece of such a body still splits all of them; keeping
// the untouched ones together needs each new piece traced to the piece it came from.
let mut taken: std::collections::BTreeSet<String> = state.bodies.iter().map(|b| b.name.clone()).collect();
// The pieces past the first belong to this feature, like a split's pieces (#10123):
// `body.rename` stores their names in this feature's `body_names`, in this order, so a
// renamed piece keeps its own name through a rebuild instead of landing on a sibling
// of the body it was cut from.
let mut extra = 0usize;
let mut split: Vec<ModelBody> = Vec::new();
for mb in std::mem::take(&mut state.bodies) {
let Some(&had) = affected.get(&mb.name).filter(|_| !state.sheets.iter().any(|s| s.body == mb.name)) else {
split.push(mb);
continue;
};
let pieces = mb.body.lumps().unwrap_or_else(|_| vec![mb.body.clone()]);
if pieces.len() <= had {
split.push(mb);
continue;
}
split.extend(named_pieces_of(&mb, pieces, &mut taken, f.id, &f.body_names, &mut extra));
}
state.bodies = split;
}
Operation::NewBody => {}
}
Ok(())
}
/// Join `tools` into the bodies at `target_idx`: each tool joins every target it meets into one
/// body, kept under the first one's name; a tool that meets none joins the first target as a
/// separate piece. A sheet metal body keeps its own identity: only the first body met may be
/// one. The names of the bodies the tools went into.
fn join(state: &mut ModelState, tools: Vec<Traced>, target_idx: &[usize]) -> Result<Vec<String>> {
let mut live: Vec<String> = target_idx.iter().filter_map(|i| state.bodies.get(*i).map(|b| b.name.clone())).collect();
// Each union keeps the lineage of what it joins, so the joined body's faces keep
// their names (the tool's new faces are named by their roles).
let union = |a: &Traced, b: &Traced| -> Result<Traced> {
let u = kernel::boolean(&a.body, &b.body, BoolOp::Union)?.ok_or_else(|| DocError::Invalid("join produced nothing".into()))?;
Ok(Traced::step(u, &[a, b]))
};
// One target takes every tool, whichever it meets: the result is the union of all of
// them in one kernel call, checked once.
if let [keep] = live.as_slice()
&& tools.len() > 1
{
let Some(base) = state.body(keep).map(ModelBody::traced) else { return Ok(Vec::new()) };
// The tools go into the kept body's frame, where it is shown (#3383).
let into_keep = tool_frame(keep);
let tools = tools.iter().map(|tool| tool_in(tool, into_keep)).collect::<Result<Vec<_>>>()?;
let operands: Vec<&Traced> = std::iter::once(&base).chain(&tools).collect();
let acc = union_all(&operands)?;
if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == *keep) {
*mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature);
}
return Ok(vec![keep.clone()]);
}
let mut joined = Vec::new();
for tool in &tools {
let mut met: Vec<String> = Vec::new();
for name in &live {
let Some(mb) = state.body(name) else { continue };
let sheet = state.sheets.iter().any(|s| &s.body == name);
if mb.body.is_mesh() || (!met.is_empty() && sheet) {
continue;
}
// Each body is met where it is shown: the tool goes into its frame (#3383).
if mb.body.meets(&tool_in(tool, tool_frame(name))?.body)? {
met.push(name.clone());
}
}
let Some(keep) = met.first().or(live.first()).cloned() else { return Ok(joined) };
let Some(base) = state.body(&keep).map(ModelBody::traced) else { continue };
let into_keep = tool_frame(&keep);
let mut acc = union(&base, &tool_in(tool, into_keep)?)?;
for name in met.iter().skip(1) {
if let Some(b) = state.body(name) {
// A body placed differently from the one kept joins it where it is shown.
let from = match tool_frame(name) {
Some(m) => crate::mat_inverse(&m),
None => Some(crate::IDENTITY),
};
let m = from.map(|from| crate::mat_mul(&into_keep.unwrap_or(crate::IDENTITY), &from)).filter(|m| !crate::is_identity(m));
acc = union(&acc, &tool_in(&b.traced(), m)?)?;
}
}
let absorbed: std::collections::BTreeSet<String> = met.into_iter().skip(1).collect();
if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == keep) {
*mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature);
}
state.bodies.retain(|b| !absorbed.contains(&b.name));
for t in state.threads.iter_mut().filter(|t| absorbed.contains(&t.body)) {
t.body = keep.clone();
}
live.retain(|n| !absorbed.contains(n));
if !joined.contains(&keep) {
joined.push(keep);
}
}
Ok(joined)
}
/// With `Touching::Separate`: the joined body `name` never keeps two pieces that touch only
/// along an edge or at a point, since they cannot be one solid. Its pieces that share a face are
/// one group. The groups that hold the material of the body before the feature (the first group
/// where that is not known) stay in it, each unless it touches one already kept; every other
/// group that touches another along an edge or at a point (as the record says, or on the exact
/// geometry where SMLib left the contact out) becomes a body of its own, named as a cut's pieces
/// are; groups that touch nothing stay in the joined body, which keeps its name. How
/// the pieces split off touched, when any were (a sheet metal or mesh body keeps its pieces).
fn separate_touching(state: &mut ModelState, name: &str) -> Result<Option<KeptSeparate>> {
let Some(i) = state.bodies.iter().position(|b| b.name == name) else { return Ok(None) };
let Some(mb) = state.bodies.get(i).filter(|b| !b.body.is_mesh() && !state.sheets.iter().any(|s| s.body == name)) else { return Ok(None) };
let n = mb.body.record().material_regions().len();
if n < 2 {
return Ok(None);
}
// Pieces sharing a face are one solid: each group is listed under its least piece.
let contacts = mb.body.region_contacts()?;
let mut root: Vec<usize> = (0..n).collect();
let find = |root: &[usize], mut k: usize| {
while let Some(&r) = root.get(k).filter(|&&r| r != k) {
k = r;
}
k
};
for c in contacts.iter().filter(|c| c.contact == Contact::Face) {
let [a, b] = c.regions.map(|k| find(&root, k));
if let Some(slot) = root.get_mut(a.max(b)) {
*slot = a.min(b);
}
}
let mut groups: Vec<Vec<usize>> = Vec::new();
let mut group_of: Vec<usize> = Vec::with_capacity(n);
let mut by_root: BTreeMap<usize, usize> = BTreeMap::new();
for k in 0..n {
let g = *by_root.entry(find(&root, k)).or_insert_with(|| {
groups.push(Vec::new());
groups.len() - 1
});
if let Some(list) = groups.get_mut(g) {
list.push(k);
}
group_of.push(g);
}
// The groups each group touches along an edge or at a point (groups never share a face), and
// the most any two of them share.
let mut touches: Vec<Vec<usize>> = vec![Vec::new(); groups.len()];
let mut most: Option<KeptSeparate> = None;
for c in &contacts {
let (Some(&a), Some(&b)) = (group_of.get(c.regions[0]), group_of.get(c.regions[1])) else { continue };
if a == b {
continue;
}
for (g, h) in [(a, b), (b, a)] {
if let Some(list) = touches.get_mut(g).filter(|l| !l.contains(&h)) {
list.push(h);
}
}
most = most.max(Some(if c.contact == Contact::Vertex { KeptSeparate::AtPoint } else { KeptSeparate::AlongEdge }));
}
// Groups the record has apart may still touch where SMLib left the contact out of the
// topology (a face tangent to another along a line).
if groups.len() > 1 {
for [a, b] in unrecorded_touches(&mb.body.parts(&groups)?, &touches)? {
for (g, h) in [(a, b), (b, a)] {
if let Some(list) = touches.get_mut(g) {
list.push(h);
}
}
most = most.max(Some(KeptSeparate::Touching));
}
}
let Some(most) = most else { return Ok(None) };
// What stays in the joined body: the groups that touch nothing, and those of the body before
// the feature, each unless it touches one already kept.
let mut anchor = groups_from_body(mb, &groups).filter(|a| a.contains(&true)).unwrap_or_default();
if anchor.is_empty() {
anchor = (0..groups.len()).map(|g| g == 0).collect();
}
let mut stays: Vec<bool> = touches.iter().map(Vec::is_empty).collect();
for g in 0..groups.len() {
let free = touches.get(g).is_some_and(|t| !t.iter().any(|h| stays.get(*h) == Some(&true)));
if free
&& anchor.get(g) == Some(&true)
&& let Some(slot) = stays.get_mut(g)
{
*slot = true;
}
}
let mut kept: Vec<usize> = groups.iter().zip(&stays).filter(|(_, s)| **s).flat_map(|(g, _)| g.iter().copied()).collect();
kept.sort_unstable();
let parts: Vec<Vec<usize>> = std::iter::once(kept).chain(groups.into_iter().zip(&stays).filter(|(_, s)| !**s).map(|(g, _)| g)).collect();
let pieces = mb.body.parts(&parts)?;
let mut taken: std::collections::BTreeSet<String> = state.bodies.iter().map(|b| b.name.clone()).collect();
let named = named_pieces(mb, pieces, &mut taken);
state.bodies.splice(i..=i, named);
Ok(Some(most))
}
/// The pairs of `pieces` (positions) that touch though `touches` (the pieces each touches, as
/// the record says) doesn't list them: their least distance on the exact faces and edges is
/// within the larger of their record tolerances. A distance only the meshes give is not trusted
/// to say they touch.
fn unrecorded_touches(pieces: &[Body], touches: &[Vec<usize>]) -> Result<Vec<[usize; 2]>> {
let meshes = pieces
.iter()
.map(|p| {
let chord = (p.size() * 1e-4).max(1e-6);
Ok((p.mesh(&kernel::MeshTolerance::chord(chord))?, chord))
})
.collect::<Result<Vec<_>>>()?;
let shapes: Vec<kernel::DistanceShape> = pieces.iter().zip(&meshes).map(|(p, (m, chord))| kernel::DistanceShape::new(p, m, *chord)).collect();
let mut out = Vec::new();
for (a, (sa, pa)) in shapes.iter().zip(pieces).enumerate() {
for (b, (sb, pb)) in shapes.iter().zip(pieces).enumerate().skip(a + 1) {
if touches.get(a).is_some_and(|t| t.contains(&b)) || !sa.bounds().meets(&sb.bounds()) {
continue;
}
let tol = pa.record().tolerance.max(pb.record().tolerance);
if kernel::body_distance(sa, sb, tol)?.is_some_and(|d| d.exact && d.distance <= tol) {
out.push([a, b]);
}
}
}
Ok(out)
}
/// Which of `groups` (of positions in `mb`'s material regions) hold material of the body named
/// as `mb` before the feature: a face of theirs came from one of its faces. `None` where the
/// body's lineage is not known.
fn groups_from_body(mb: &ModelBody, groups: &[Vec<usize>]) -> Option<Vec<bool>> {
let from = mb.lineage()?.faces_from_body(&mb.name);
let record = mb.body.record();
let regions = record.material_regions();
let holds = |k: usize| {
let shells = regions.get(k).and_then(|&r| record.regions.get(r)).map(|r| r.shells.as_slice()).unwrap_or_default();
shells.iter().any(|&s| match record.shells.get(s as usize) {
Some(solidcraft_geom::brep::Shell::Faces { faces, .. }) => faces.iter().any(|f| from.get(f.face as usize) == Some(&true)),
_ => false,
})
};
Some(groups.iter().map(|g| g.iter().any(|&k| holds(k))).collect())
}
/// The bodies the pieces of `mb` become: the first keeps its name, the others are numbered after
/// it ("Bar (1)") on past the names already `taken`. Each piece's faces are named after the
/// whole's, worked out once for the whole (so pieces of one face in different bodies are told
/// apart).
fn named_pieces(mb: &ModelBody, pieces: Vec<Body>, taken: &mut std::collections::BTreeSet<String>) -> Vec<ModelBody> {
named_pieces_of(mb, pieces, taken, mb.feature, &[], &mut 0)
}
/// [`named_pieces`] for a feature that made the pieces past the first: they are `feature`'s, and
/// take the names stored for it from `stored`, from the place `extra` keeps (#10123), where one
/// is set and free.
fn named_pieces_of(
mb: &ModelBody,
pieces: Vec<Body>,
taken: &mut std::collections::BTreeSet<String>,
feature: u64,
stored: &[String],
extra: &mut usize,
) -> Vec<ModelBody> {
let lineages = crate::lineage::Lineage::lumps(&mb.body, mb.lineage().as_deref(), &pieces);
let mut out = Vec::with_capacity(pieces.len());
for (k, (p, lineage)) in pieces.into_iter().zip(lineages).enumerate() {
let (name, made_by) = if k == 0 {
(mb.name.clone(), mb.feature)
} else {
let kept = stored.get(*extra).filter(|n| !n.trim().is_empty() && !taken.contains(*n)).cloned();
*extra += 1;
let name =
kept.unwrap_or_else(|| (k..=k + taken.len()).map(|j| format!("{} ({j})", mb.name)).find(|n| !taken.contains(n)).unwrap_or_default());
(name, feature)
};
taken.insert(name.clone());
out.push(ModelBody::new(name, p, made_by).with_lineage(lineage));
}
out
}
/// Distance that reaches through every target body from the sketch plane (either side).
pub fn through_all_distance(st: &ModelState, plane: &Plane, targets: &[String]) -> Result<f64> {
let mut far: f64 = 0.0;
let mut any = false;
for b in st.bodies.iter().filter(|b| targets.is_empty() || targets.contains(&b.name)) {
let bb = b.mesh().bounds();
if bb.is_empty() {
continue;
}
any = true;
for i in 0..8 {
let p = Vec3::new(
if i & 1 == 0 { bb.min.x } else { bb.max.x },
if i & 2 == 0 { bb.min.y } else { bb.max.y },
if i & 4 == 0 { bb.min.z } else { bb.max.z },
);
far = far.max(plane.height(p).abs());
}
}
if !any {
return Err(DocError::Invalid("through all needs a body to cut".into()));
}
Ok(far * 1.02 + 1.0)
}
/// The body a face-based feature applies to: by name, or the one whose surface is nearest the
/// first point.
fn body_at(st: &ModelState, body: &Option<crate::BodyName>, points: &[Vec3]) -> Result<usize> {
if let Some(n) = body {
return st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")));
}
let p = points.first().ok_or_else(|| DocError::Invalid("no faces selected".into()))?;
st.bodies
.iter()
.enumerate()
.map(|(i, b)| {
let bb = b.mesh().bounds();
let q = Vec3::new(p.x.clamp(bb.min.x, bb.max.x), p.y.clamp(bb.min.y, bb.max.y), p.z.clamp(bb.min.z, bb.max.z));
(i, q.dist(*p))
})
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i)
.ok_or_else(|| DocError::Invalid("there is no body".into()))
}
/// A hole stays on its face when the model changes: a position now inside a body moves back
/// against the drilling direction to the surface, one now above it moves down onto it. Only the
/// bodies in `scope` count (every body when it is empty, see [`hole_scope`]). Edit Hole seeds from
/// this point so the dialog's face pick matches where evaluation drills (#10689).
pub fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) -> Vec3 {
let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max);
let eps = size * 1e-6;
let mut best: Option<Vec3> = None;
for b in st.bodies.iter().filter(|b| in_hole_scope(scope, b)) {
let m = b.mesh();
// Already on the surface: the drill enters right here.
if let Some((t, _)) = m.raycast(p - dir * eps, dir)
&& t < eps * 4.0
{
return p;
}
let q = if m.contains(p) { m.raycast(p, -dir).map(|(t, _)| p - dir * t) } else { m.raycast(p, dir).map(|(t, _)| p + dir * t) };
if let Some(q) = q
&& best.is_none_or(|bq| q.dist(p) < bq.dist(p))
{
best = Some(q);
}
}
best.unwrap_or(p)
}
/// The faces of the model near `p`: for each, how far `p` is from it, the outward normal there
/// (the surface's own normal for planes, cylinders and spheres, turned the way the face looks out
/// of its body; the nearest mesh facet's otherwise) and, for a plane, how far `p` is from the
/// plane itself. Only faces within `reach` of `p`, nearest first.
fn faces_through(st: &ModelState, p: Vec3, reach: f64) -> Vec<(f64, Vec3, Option<f64>)> {
let mut out: Vec<(f64, Vec3, Option<f64>)> = Vec::new();
for b in st.bodies.iter().filter(|b| !b.body.is_mesh()) {
let m = b.mesh();
// The nearest facet of each face of this body.
let mut near: BTreeMap<u32, (f64, Vec3)> = BTreeMap::new();
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
let Some([a, bb, c]) = m.tri(t) else { continue };
let d = crate::appearance::closest_on_triangle(p, a, bb, c).dist(p);
let Some(n) = (bb - a).cross(c - a).normalized() else { continue };
if d <= reach && near.get(f).is_none_or(|(x, _)| d < *x) {
near.insert(*f, (d, n));
}
}
for (f, (d, facet)) in near {
let (exact, off) = match kernel::face_surface(&b.body, f as usize) {
Some(kernel::FaceSurface::Plane { normal, point }) => (Some(*normal), Some((p - point).dot(normal).abs())),
Some(kernel::FaceSurface::Cylinder { origin, axis, .. }) => {
let v = p - origin;
((v - axis * v.dot(axis)).normalized(), None)
}
Some(kernel::FaceSurface::Sphere { center, .. }) => ((p - center).normalized(), None),
// Square to the line through the apex, not the nearest facet's normal (#10698).
Some(kernel::FaceSurface::Cone { apex, axis, half_angle }) => {
let v = p - apex;
let out = (v - axis * v.dot(axis)).normalized();
(out.and_then(|u| (u * half_angle.cos() - axis * half_angle.sin()).normalized()), None)
}
// Away from the nearest point of the ring the tube goes round.
Some(kernel::FaceSurface::Torus { center, axis, major, .. }) => {
let v = p - center;
let ring = (v - axis * v.dot(axis)).normalized().map(|u| center + u * major);
(ring.and_then(|q| (p - q).normalized()), None)
}
_ => (None, None),
};
let n = match exact {
Some(n) if n.dot(facet) < 0.0 => -n,
Some(n) => n,
None => facet,
};
out.push((d, n, off));
}
}
out.sort_by(|a, b| a.0.total_cmp(&b.0));
out
}
/// The way a hole placed at `p` drills: into the material, against the outward normal of the
/// face `p` lies on. A point on no face (a planar face's centroid outside it, say) takes the
/// nearest planar face whose plane it lies in, else the face nearest it within its body's pick
/// tolerance. None when no face is near.
pub fn hole_direction_at(st: &ModelState, p: Vec3) -> Option<Vec3> {
let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max);
let faces = faces_through(st, p, f64::INFINITY);
if let Some((d, n, _)) = faces.first()
&& *d <= size * 1e-4
{
return Some(-*n);
}
if let Some((_, n, _)) = faces.iter().find(|(_, _, off)| off.is_some_and(|o| o <= size * 1e-4)) {
return Some(-*n);
}
let reach = st.bodies.iter().map(crate::appearance::pick_tolerance).fold(0.0, f64::max);
faces.first().filter(|(d, _, _)| *d <= reach).map(|(_, n, _)| -*n)
}
/// A hole placed on a face drills into the material: when its direction leaves every face it
/// starts on (as designs saved before format 18 can say: their direction was taken from any face
/// whose plane passed near the point, such as the other side of a thin plate or a face of another
/// body at the same height), it is mirrored in the face it starts on, so it goes in at the same
/// angle. A direction that enters a face there, or a spot on no face, is kept.
fn hole_dir_into_face(st: &ModelState, p: Vec3, dir: Vec3) -> Vec3 {
let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max);
let faces = faces_through(st, p, size * 1e-5);
if faces.is_empty() || faces.iter().any(|(_, n, _)| n.dot(dir) < -1e-9) {
return dir;
}
match faces.iter().map(|(_, n, _)| *n).max_by(|a, b| a.dot(dir).total_cmp(&b.dot(dir))) {
Some(n) if n.dot(dir) > 1e-9 => (dir - n * (2.0 * n.dot(dir))).normalized().unwrap_or(dir),
_ => dir,
}
}
/// Where a picked edge sat in its body: its direction (zero for curved edges) and the body's
/// bounding box at the time.
#[derive(Clone, Debug, PartialEq, Serialize, serde::Deserialize)]
pub struct EdgeRef {
pub dir: Vec3,
pub min: Vec3,
pub max: Vec3,
}
fn edge_dir(e: &kernel::EdgeInfo) -> Vec3 {
let (Some(a), Some(b)) = (e.points.first(), e.points.last()) else { return Vec3::ZERO };
let straight = e.points.iter().all(|p| p.dist_to_segment(*a, *b) < 1e-6 * (1.0 + e.length));
if straight && a.dist(*b) > 1e-9 { (*b - *a).normalized().unwrap_or(Vec3::ZERO) } else { Vec3::ZERO }
}
/// The body each edge picked at `pts` lies on (the state before a blend): the named body, else,
/// for each point on its own, the body with an edge nearest it. A blend over the edges of
/// several bodies remembers every edge on the body it was picked on, never on the first edge's.
fn picked_bodies(st: &ModelState, body: &Option<crate::BodyName>, pts: &[Vec3]) -> Option<Vec<usize>> {
if body.is_some() || st.bodies.iter().filter(|b| !b.body.is_mesh()).count() < 2 {
blend_target(st, body, pts).ok().map(|ti| vec![ti; pts.len()])
} else {
pts.iter().map(|p| blend_target(st, &None, std::slice::from_ref(p)).ok()).collect()
}
}
/// References for edges picked at `pts` on the bodies a blend would go on (the state before it).
pub fn edge_refs(st: &ModelState, body: &Option<crate::BodyName>, pts: &[Vec3]) -> Vec<EdgeRef> {
let Some(on) = picked_bodies(st, body, pts) else { return Vec::new() };
let mut seen: BTreeMap<usize, Option<(Vec<kernel::EdgeInfo>, solidcraft_geom::Aabb3)>> = BTreeMap::new();
let mut out = Vec::with_capacity(pts.len());
for (p, ti) in pts.iter().zip(on) {
let found = seen.entry(ti).or_insert_with(|| {
let mb = st.bodies.get(ti)?;
let size = mb.body.size();
Some((mb.body.edges((size * 1e-3).max(1e-3)).ok()?, mb.mesh().bounds()))
});
let Some((edges, bb)) = found else { return Vec::new() };
let e = edges.iter().min_by(|x, y| {
let d = |e: &kernel::EdgeInfo| e.points.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min);
d(x).total_cmp(&d(y))
});
out.push(EdgeRef { dir: e.map(edge_dir).unwrap_or(Vec3::ZERO), min: bb.min, max: bb.max });
}
out
}
/// Persistent names of the edges picked at `pts`, each on the body it lies on (see
/// [`picked_bodies`]): of the edge a blend takes at each pick (at a vertex where a seam meets a
/// rim, the rim), else of the nearest edge.
pub fn edge_names_for(st: &ModelState, body: &Option<crate::BodyName>, pts: &[Vec3]) -> Vec<String> {
let Some(on) = picked_bodies(st, body, pts) else { return Vec::new() };
let mut out = vec![String::new(); pts.len()];
let mut done: Vec<usize> = Vec::new();
for &ti in &on {
if done.contains(&ti) {
continue;
}
done.push(ti);
let Some(b) = st.bodies.get(ti) else { continue };
// The body's names are worked out once for all its picks.
let idx: Vec<usize> = on.iter().enumerate().filter(|(_, t)| **t == ti).map(|(i, _)| i).collect();
let at: Vec<Vec3> = idx.iter().filter_map(|i| pts.get(*i).copied()).collect();
let names = match kernel::blend_edges(&b.body, &at) {
Ok(edges) => {
let all = crate::naming::edge_names(b);
edges.iter().map(|e| all.get(*e).cloned().unwrap_or_default()).collect()
}
Err(_) => crate::naming::edge_names_at(b, &at),
};
for (i, n) in idx.into_iter().zip(names) {
if let Some(slot) = out.get_mut(i) {
*slot = n;
}
}
}
out
}
/// The stored pick sits on the axis of a round, not on an edge. The nearest edge within a
/// quarter of the body is that round's tangency seam, which is a different edge (#775).
fn pick_lies_on_a_round_axis(body: &Body, p: Vec3) -> bool {
let Some(cyl) = kernel::cylinder_face_at(body, p) else { return false };
let Some(axis) = cyl.axis.normalized() else { return false };
let radial = p - cyl.axis_point;
let dist = (radial - axis * radial.dot(axis)).len();
if !(cyl.radius > 1e-6 && dist < cyl.radius * 0.35) {
return false;
}
let tight = (body.size() * 2e-3).max(1e-3);
// A pick on the wall itself is the seam. Only an axial pick is the vanished corner.
match body.nearest_edge(p, cyl.radius * 2.0) {
Ok(Some((_, d))) => d > tight,
_ => true,
}
}
/// Edge reference points re-found on the body: points on an edge stay; a point that moved off
/// (an upstream edit) is carried with the body (its place in the body's bounding box then and
/// now) to an edge running the same way; failing that it goes to the nearest edge with a
/// warning; points with no edge near are dropped with a warning.
fn resolve_edges(b: &Body, pts: &[Vec3], refs: &[EdgeRef], warning: &mut Option<String>) -> Result<Vec<Vec3>> {
let size = b.size();
let edges = b.edges((size * 1e-3).max(1e-3))?;
let tight = (size * 2e-3).max(1e-3);
let dist = |p: Vec3, e: &kernel::EdgeInfo| e.points.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min);
let now = b.mesh(&solidcraft_kernel::MeshTolerance::chord((size * 1e-2).max(1e-2))).map(|m| m.bounds()).ok();
let (mut out, mut moved, mut lost) = (Vec::new(), 0, 0);
for (i, p) in pts.iter().enumerate() {
let on = edges.iter().any(|e| dist(*p, e) <= tight);
if !on && let (Some(r), Some(nb)) = (refs.get(i), now.as_ref()) {
// The same place in the body as it is now.
let map = |v: f64, a0: f64, a1: f64, b0: f64, b1: f64| {
if (a1 - a0).abs() > 1e-9 { b0 + (v - a0) * (b1 - b0) / (a1 - a0) } else { v + (b0 - a0) }
};
let q = Vec3::new(
map(p.x, r.min.x, r.max.x, nb.min.x, nb.max.x),
map(p.y, r.min.y, r.max.y, nb.min.y, nb.max.y),
map(p.z, r.min.z, r.max.z, nb.min.z, nb.max.z),
);
let fits = |e: &kernel::EdgeInfo| {
let d = edge_dir(e);
dist(q, e) <= tight && (r.dir.len() < 0.5 || d.cross(r.dir).len() < 1e-3)
};
if edges.iter().any(fits) {
out.push(q);
continue;
}
}
let best = edges
.iter()
.map(|e| (e.points.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min), e.mid))
.min_by(|a, b| a.0.total_cmp(&b.0));
match best {
Some((d, _)) if d <= tight => out.push(*p),
Some((d, mid)) if d <= size * 0.25 => {
out.push(mid);
moved += 1;
}
_ => lost += 1,
}
}
if out.is_empty() {
return Err(DocError::Invalid("none of the selected edges exist any more".into()));
}
if moved + lost > 0 {
let mut w = Vec::new();
if moved > 0 {
w.push(format!("{moved} edge reference(s) re-found on the nearest edge"));
}
if lost > 0 {
w.push(format!("{lost} edge reference(s) no longer found and skipped"));
}
*warning = Some(w.join("; "));
}
Ok(out)
}
/// The body a fillet/chamfer applies to: by name, or the one closest to the first edge point.
pub fn blend_target(state: &ModelState, body: &Option<crate::BodyName>, edges: &[Vec3]) -> Result<usize> {
if let Some(n) = body {
return state.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")));
}
let p = edges.first().ok_or_else(|| DocError::Invalid("no edges selected".into()))?;
let mut best: Option<(usize, f64)> = None;
for (i, b) in state.bodies.iter().enumerate() {
let tol = (b.body.size() * 2e-3).max(1e-3);
if let Ok(Some((_, d))) = b.body.nearest_edge(*p, tol)
&& best.is_none_or(|(_, bd)| d < bd)
{
best = Some((i, d));
}
}
best.map(|(i, _)| i).ok_or_else(|| {
if state.bodies.iter().any(|b| b.body.is_mesh()) {
DocError::Invalid("there is no solid body to modify (mesh bodies have no edges)".into())
} else {
DocError::Invalid("there is no body to modify".into())
}
})
}
/// Whether `p` lies in the bounding box a reference recorded (with a little slack): an edge
/// picked on a body lies in that body's box.
fn in_ref_box(r: &EdgeRef, p: Vec3) -> bool {
let slack = ((r.max - r.min).len() * 1e-2).max(1e-3);
(r.min.x - slack..=r.max.x + slack).contains(&p.x)
&& (r.min.y - slack..=r.max.y + slack).contains(&p.y)
&& (r.min.z - slack..=r.max.z + slack).contains(&p.z)
}
/// The stored name of a blend's edge `i` (picked at `p`), when it can be trusted. Builds before
/// blends over several bodies were split by body named every edge on the first edge's body: the
/// name of a pick on another body is that body's nearest edge, and the reference's box (that
/// body's) does not hold the pick. Such a name (and its reference) is not used.
fn trusted_edge_name(f: &Feature, i: usize, p: Vec3) -> Option<&str> {
let n = f.edge_names.get(i).filter(|n| !n.is_empty())?;
match f.edge_refs.get(i) {
Some(r) if !in_ref_box(r, p) => None,
_ => Some(n.as_str()),
}
}
/// The body (index) an edge name finds an edge on, when one does: the one where the edge still
/// runs through the pick `p`, else the nearest.
fn named_body(st: &ModelState, name: &str, p: Vec3) -> Option<usize> {
// Names start with the feature that made the face: only bodies with such a face can hold it.
let bare = crate::naming::legacy_name(name).unwrap_or(name);
let token = bare.find(':').map(|k| &bare[..=k]);
let mut best: Option<(usize, (bool, f64))> = None;
for (i, b) in st.bodies.iter().enumerate() {
if b.body.is_mesh() || token.is_some_and(|t| !crate::naming::face_names(b).iter().any(|n| n.contains(t))) {
continue;
}
let Ok(hit) = crate::naming::locate_edge(b, name, p) else { continue };
let score = (hit.on_point, -hit.point.dist(p));
if best.as_ref().is_none_or(|(_, s)| score.partial_cmp(s).is_some_and(|o| o.is_gt())) {
best = Some((i, score));
}
}
best.map(|(i, _)| i)
}
/// The body (index) an edge picked at `p` lies on: the body with an edge through it.
fn body_on_edge(st: &ModelState, p: Vec3) -> Option<usize> {
let mut best: Option<(usize, f64)> = None;
for (i, b) in st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh()) {
let size = b.body.size();
let tight = (size * 2e-3).max(1e-3);
if let Ok(Some((_, d))) = b.body.nearest_edge(p, (size * 1e-3).max(1e-3))
&& d <= tight
&& best.is_none_or(|(_, bd)| d < bd)
{
best = Some((i, d));
}
}
best.map(|(i, _)| i)
}
/// The body (index) each edge of a blend is on: the named body; else, for each edge, the body
/// its stored name finds it on. A named edge that is gone stays on the bodies the feature's other
/// edges were found on; an unnamed one goes to the body the pick lies on an edge of; failing
/// both, the body nearest the first pick (as before blends were split by body). A named edge is
/// never moved onto another body because that body's edge is nearer.
fn blend_bodies(st: &ModelState, f: &Feature, body: &Option<crate::BodyName>, pts: &[Vec3]) -> Result<Vec<usize>> {
// Named, or only one body to blend: no lookup.
if body.is_some() || st.bodies.iter().filter(|b| !b.body.is_mesh()).count() < 2 {
let ti = blend_target(st, body, pts)?;
return Ok(vec![ti; pts.len()]);
}
let names: Vec<Option<&str>> = pts.iter().enumerate().map(|(i, p)| trusted_edge_name(f, i, *p)).collect();
let by_name: Vec<Option<usize>> = names.iter().zip(pts).map(|(n, p)| n.and_then(|n| named_body(st, n, *p))).collect();
let mut named: Vec<usize> = by_name.iter().flatten().copied().collect();
named.sort_unstable();
named.dedup();
// Of the bodies the feature's other edges were found on, the one with an edge nearest `p`.
let nearest_named = |p: Vec3| {
named
.iter()
.filter_map(|i| {
let b = st.bodies.get(*i)?;
let tol = (b.body.size() * 2e-3).max(1e-3);
Some((*i, b.body.nearest_edge(p, tol).ok()??.1))
})
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i)
};
let mut fallback = None;
let mut out = Vec::with_capacity(pts.len());
for ((b, n), p) in by_name.into_iter().zip(&names).zip(pts) {
let found = match (b, n) {
(Some(ti), _) => Some(ti),
// A named edge that is gone stays with the feature's other bodies: another body's
// edge where it was picked is not it.
(None, Some(_)) => nearest_named(*p).or_else(|| body_on_edge(st, *p)),
(None, None) => body_on_edge(st, *p).or_else(|| nearest_named(*p)),
};
let ti = match (found, fallback) {
(Some(ti), _) => ti,
(None, Some(ti)) => ti,
(None, None) => *fallback.insert(blend_target(st, &None, pts)?),
};
out.push(ti);
}
Ok(out)
}
/// The edges `idx` of blend `f` found on body `mb`: by name, where the edge was stored with one.
/// A name that no longer finds exactly its edge fails the blend, asking for the edge to be picked
/// again; so does a name a build stored for the wrong body (see `trusted_edge_name`).
fn blend_edges_on(mb: &ModelBody, f: &Feature, edges: &[crate::Position], idx: &[usize], warning: &mut Option<String>) -> Result<Vec<Vec3>> {
let pick = |i: usize| edges.get(i).map(|p| p.0).unwrap_or(Vec3::ZERO);
if !f.edge_names.iter().any(|n| !n.is_empty()) {
let pts: Vec<Vec3> = idx.iter().map(|i| pick(*i)).collect();
let refs: Vec<EdgeRef> = idx.iter().map_while(|i| f.edge_refs.get(*i).cloned()).collect();
return resolve_edges(&mb.body, &pts, &refs, warning);
}
let (mut out, mut notes) = (Vec::new(), Vec::new());
for &i in idx {
let p = pick(i);
let Some(stored) = f.edge_names.get(i).filter(|n| !n.is_empty()) else {
// An edge picked without a name: by its point. A pick on the axis of a round must not
// fall through to the tangency seam (#775).
let mut w = None;
let refs: Vec<EdgeRef> = f.edge_refs.get(i).cloned().into_iter().collect();
let skipped = "edge `?` no longer exists and was skipped";
if pick_lies_on_a_round_axis(&mb.body, p) {
notes.push(skipped.into());
} else if let Ok(q) = resolve_edges(&mb.body, &[p], &refs, &mut w) {
out.extend(q);
notes.push("an edge reference without a name was found by its point".into());
} else {
notes.push(skipped.into());
}
continue;
};
let hit =
trusted_edge_name(f, i, p).and_then(|n| crate::naming::locate_edge(mb, n, p).ok()).ok_or_else(|| DocError::reselect(stored.as_str()))?;
if let Some(note) = hit.note(stored) {
notes.push(note);
}
// The body changed since the pick: the pick may now sit at an end of the edge.
let moved = f.edge_refs.get(i).is_some_and(|r| {
let now = mb.mesh().bounds();
let tight = (mb.body.size() * 2e-3).max(1e-3);
now.min.dist(r.min) > tight || now.max.dist(r.max) > tight
});
out.push(if moved { off_the_ends(mb, hit.edge, hit.point) } else { hit.point });
}
if out.is_empty() {
let why = if notes.is_empty() { String::new() } else { format!(" ({})", notes.join("; ")) };
return Err(DocError::Invalid(format!("none of the selected edges exist any more{why}")));
}
if !notes.is_empty() {
*warning = Some(notes.join("; "));
}
Ok(out)
}
/// A point on edge `edge` of a body for the kernel to find it by: `p`, unless it lies at an end
/// of the edge (an upstream edit moved the edge along it), where the edges meeting there are as
/// near: then the edge's middle.
fn off_the_ends(mb: &ModelBody, edge: usize, p: Vec3) -> Vec3 {
let m = mb.mesh();
let Some(e) = m.edges.get(edge) else { return p };
let tight = (mb.body.size() * 2e-3).max(1e-3);
let (Some(a), Some(b)) = (e.first(), e.last()) else { return p };
if p.dist(*a) > tight && p.dist(*b) > tight {
return p;
}
let total: f64 = e.windows(2).map(|w| w[0].dist(w[1])).sum();
let mut acc = 0.0;
for w in e.windows(2) {
let l = w[0].dist(w[1]);
if acc + l >= total / 2.0 {
let t = if l > 0.0 { (total / 2.0 - acc) / l } else { 0.0 };
return w[0] + (w[1] - w[0]) * t;
}
acc += l;
}
p
}
/// The edges a tapered fillet tapered (a point on each, with its taper).
type Tapered = Vec<(Vec3, kernel::Taper)>;
/// A blend's refusal when the feature blended the picked edges' tangent chains too (tangent
/// propagation, the default), saying so and how to blend the picked edges alone.
fn with_propagation_hint(e: DocError) -> DocError {
const HINT: &str = " (tangent propagation blended the picked edges' tangent chain with them; with it off, tangent_chain: false, only the picked edges are blended)";
match e {
DocError::Kernel(kernel::KernelError::TooLarge(m)) => DocError::Kernel(kernel::KernelError::TooLarge(m + HINT)),
DocError::Kernel(kernel::KernelError::Invalid(m)) => DocError::Kernel(kernel::KernelError::Invalid(m + HINT)),
DocError::Kernel(kernel::KernelError::Failed(m)) => DocError::Kernel(kernel::KernelError::Failed(m + HINT)),
DocError::Invalid(m) => DocError::Invalid(m + HINT),
e => e,
}
}
/// Body `mb` with blend `f` applied at `edges` (radius or distance `r`), the radii a fitted fillet
/// used (when it reduced any) and the edges it tapered.
fn blend_body(
vals: &BTreeMap<String, Value>,
f: &Feature,
mb: &ModelBody,
edges: &[Vec3],
r: f64,
warning: &mut Option<String>,
) -> Result<(Traced, Option<Vec<f64>>, Tapered)> {
let input = mb.traced();
let (mut used, mut tapered) = (None, Vec::new());
// The blended body, and the lineage of what the last blend started from.
let (nb, from) = match &f.kind {
// A curvature-continuous fillet's corners are G2 patches, whatever `corner` says: SMLib's
// own corner patch is only tangent to its rounds.
FeatureKind::Fillet { style: crate::FilletStyle::Curvature, setbacks, .. } => {
let mut corners = Vec::with_capacity(setbacks.len());
for c in setbacks {
corners.push((c.vertex.0, val(vals, &c.distance, Kind::Length)?));
}
(kernel::fillet_g2_with_g2_corners(&mb.body, edges, r, &corners)?, input)
}
FeatureKind::Fillet { corner, setbacks, .. } if matches!(corner, crate::FilletCorner::G2) || !setbacks.is_empty() => {
// Each setback: its corner's vertex and its distance.
let mut corners = Vec::with_capacity(setbacks.len());
for c in setbacks {
corners.push((c.vertex.0, val(vals, &c.distance, Kind::Length)?));
}
match corner {
crate::FilletCorner::G2 => (kernel::fillet_g2_corners(&mb.body, edges, r, &corners)?, input),
crate::FilletCorner::Rolling => (kernel::fillet_setback(&mb.body, edges, r, &corners)?, input),
}
}
FeatureKind::Fillet { style: crate::FilletStyle::Chord, .. } => (kernel::fillet_chord(&mb.body, edges, r)?, input),
FeatureKind::Fillet { style: crate::FilletStyle::Variable { radius2, start, mid, smooth }, .. } => {
let r2 = val(vals, radius2, Kind::Length)?;
let mut pts = vec![(0.0, r), (1.0, r2)];
for (t, e) in mid {
pts.push((*t, val(vals, e, Kind::Length)?));
}
one_by_one(input, edges, |b, p| kernel::fillet_variable_points(b, p, start.0, &pts, *smooth))?
}
FeatureKind::Fillet { style: crate::FilletStyle::Spline { start, knots, radii }, .. } => {
let mut values = vec![r];
for e in radii {
values.push(val(vals, e, Kind::Length)?);
}
let law = crate::FilletStyle::spline(knots, values);
one_by_one(input, edges, |b, p| kernel::fillet_variable_spline(b, p, start.0, &law))?
}
FeatureKind::Fillet { fit: crate::FilletFit::Taper, .. } => {
let (b, tapers) = kernel::fillet_tapered(&mb.body, edges, r)?;
if let Some(note) = tapered_note(&tapers) {
append_warning(warning, note);
}
tapered = edges.iter().copied().zip(tapers).filter_map(|(p, t)| Some((p, t?))).collect();
(b, input)
}
FeatureKind::Fillet { fit, .. } => {
let (b, u, gone) = fillet_fitted(&mb.body, edges, r, *fit)?;
if let Some(u) = &u {
append_warning(warning, reduced_note(u, r));
}
if !gone.is_empty() {
append_warning(warning, removed_note(&gone));
}
used = u;
(b, input)
}
FeatureKind::Chamfer { distance2, angle, flip, .. } => (chamfer_with(vals, &mb.body, edges, r, distance2, angle, *flip)?, input),
_ => return Err(DocError::Invalid("blend".into())),
};
// Keeping the input's planar certificates may join faces; their history stays over the same
// operand.
Ok((Traced::step(nb.with_preserved_planar_sources(&mb.body)?, &[&from]), used, tapered))
}
/// The revolve axis in the sketch's plane coordinates (a point and a direction). `st` is the model
/// an axis on an edge or face of it is found in; `construct` gives a construction axis, by name, in
/// the sketch's 3D frame.
pub(crate) fn revolve_axis(
ss: &SolvedSketch,
axis: &AxisRef,
st: &ModelState,
construct: &dyn Fn(&str) -> Result<(Vec3, Vec3)>,
) -> Result<(Vec2, Vec2)> {
match axis {
AxisRef::SketchLine { curve } => {
let ci = ss.sketch.curve_index(curve).ok_or_else(|| DocError::Unknown(format!("sketch line `{curve}`")))?;
match ss.sketch.curves.get(ci).map(|c| &c.kind) {
Some(CurveKind::Line { a, b }) => {
let (pa, pb) = (ss.sketch.point(*a).unwrap_or_default(), ss.sketch.point(*b).unwrap_or_default());
Ok((pa, pb - pa))
}
_ => Err(DocError::Invalid(format!("`{curve}` is not a line"))),
}
}
AxisRef::SketchAxis { axis } => match axis.to_ascii_lowercase().as_str() {
"x" => Ok((Vec2::ZERO, Vec2::X)),
"y" => Ok((Vec2::ZERO, Vec2::Y)),
other => Err(DocError::Unknown(format!("sketch axis `{other}`"))),
},
AxisRef::World { axis } => {
let d = match axis.to_ascii_uppercase().as_str() {
"X" => Vec3::X,
"Y" => Vec3::Y,
"Z" => Vec3::Z,
other => return Err(DocError::Unknown(format!("axis `{other}`"))),
};
let pl = &ss.plane;
if d.dot(pl.normal()).abs() > 1e-9 || pl.height(Vec3::ZERO).abs() > 1e-9 {
return Err(DocError::Invalid(format!("the {axis} axis does not lie in the sketch plane")));
}
Ok((pl.to_local(Vec3::ZERO), Vec2::new(d.dot(pl.x), d.dot(pl.y))))
}
AxisRef::Line { origin, dir } => line_in_sketch_plane(ss, origin.0, dir.0),
AxisRef::Model { geo } => {
let (o, d) = crate::construct::model_axis(st, geo)?;
line_in_sketch_plane(ss, o, d)
}
AxisRef::Construction { name } => {
let (o, d) = construct(name)?;
line_in_sketch_plane(ss, o, d)
}
}
}
/// The model a revolve axis is found in: what construction geometry of component `comp` is built
/// on when the axis is an edge or face of it (only then is it worth placing); a model that cannot
/// be placed is the error.
pub(super) fn axis_state<'a>(doc: &Document, st: &'a ModelState, comp: u64, axis: &AxisRef) -> Result<std::borrow::Cow<'a, ModelState>> {
match axis {
AxisRef::Model { .. } => construction_state(doc, st, comp),
_ => Ok(std::borrow::Cow::Borrowed(st)),
}
}
/// A world line through `origin` along `dir` in the sketch's plane coordinates, or an error when it
/// does not lie in the sketch plane.
fn line_in_sketch_plane(ss: &SolvedSketch, origin: Vec3, dir: Vec3) -> Result<(Vec2, Vec2)> {
let pl = &ss.plane;
let d = dir.normalized().ok_or_else(|| DocError::Invalid("revolve axis has no direction".into()))?;
if d.dot(pl.normal()).abs() > 1e-9 || pl.height(origin).abs() > 1e-6 {
return Err(DocError::Invalid("the revolve axis does not lie in the sketch plane".into()));
}
Ok((pl.to_local(origin), Vec2::new(d.dot(pl.x), d.dot(pl.y))))
}
/// A construction axis `name` of the timeline so far, as evaluated, in the frame of component
/// `comp`: a point on it and its direction. Without a document (`doc` None) it is taken in its
/// own component's frame.
pub(crate) fn construction_axis_in(doc: Option<&Document>, st: &ModelState, name: &str, comp: u64) -> Result<(Vec3, Vec3)> {
let c = st
.construct
.iter()
.find(|c| c.name == name)
.ok_or_else(|| DocError::Unknown(format!("construction axis `{name}` (it must come earlier in the timeline)")))?;
let crate::construct::ConstructGeom::Axis { origin, dir } = &c.geom else {
return Err(DocError::Invalid(format!("`{name}` is not a construction axis")));
};
let Some(doc) = doc else { return Ok((*origin, *dir)) };
let owner = doc.feature(c.feature).map_or(0, |f| f.component);
if owner == comp || doc.occurrences.is_empty() {
return Ok((*origin, *dir));
}
let inverse =
crate::mat_inverse(&doc.component_transform(comp)).ok_or_else(|| DocError::Invalid("the feature's component frame is invalid".into()))?;
let relative = crate::mat_mul(&inverse, &doc.component_transform(owner));
Ok((crate::apply_point(&relative, *origin), crate::apply_vector(&relative, *dir)))
}
/// Whether a drill from `p` along `d` reaches material: it starts into a body (`touches`), or,
/// when `ahead` is set, a body lies further along `d`. A spot exactly on a surface counts only
/// when the drill enters there, not when it leaves. Only the bodies in `scope` count.
fn hole_reaches(st: &ModelState, p: Vec3, d: Vec3, ahead: bool, scope: &[String]) -> bool {
let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max);
let eps = size * 1e-6;
let q = p + d * eps;
st.bodies.iter().filter(|b| in_hole_scope(scope, b)).any(|b| {
let m = b.mesh();
m.contains(q) || (ahead && m.raycast(q, d).is_some())
})
}
/// The side hole centres on a sketch drill to: into the material, whichever way the sketch plane
/// faces. Material that touches a spot (the drill starts in it) wins over material further away,
/// so a sketch on a plate's face drills that plate rather than one across an air gap: `-n` (away
/// from the plane's normal) if any spot touches material that way, else `+n` if any spot touches
/// material that way. With no touching on either side it goes by the nearest body ahead: `-n` if
/// any spot has a body ahead that way, else `+n` if any has, else `-n`.
/// The way holes at these points of a sketch drill (see [`sketch_hole_dir`]), flipped or not.
/// None when the sketch or a point is not there.
pub fn sketch_hole_direction(st: &ModelState, sketch: u64, ids: &[String], flip: bool) -> Option<Vec3> {
let ss = st.sketch(sketch)?;
let spots: Vec<Vec3> =
ids.iter().map(|id| ss.sketch.points.iter().find(|p| &p.id == id).map(|p| ss.plane.to_world(p.pos))).collect::<Option<_>>()?;
let dir = sketch_hole_dir(st, &spots, ss.plane.normal(), &[]);
Some(if flip { -dir } else { dir })
}
fn sketch_hole_dir(st: &ModelState, spots: &[Vec3], n: Vec3, scope: &[String]) -> Vec3 {
let down = -n;
let any = |d: Vec3, ahead: bool| spots.iter().any(|p| hole_reaches(st, *p, d, ahead, scope));
if any(down, false) {
down
} else if any(n, false) {
n
} else if any(down, true) || !any(n, true) {
down
} else {
n
}
}
/// The bodies a hole at sketch points finds its side and its faces on: the bodies it cuts when it
/// names them (a hole from a sketch on a body's face cuts that body, #2882), so a body further
/// along can't take the holes meant for it. Empty (every body) otherwise.
fn hole_scope(f: &Feature) -> &[String] {
match &f.kind {
FeatureKind::Hole { points: Some(sp), .. } if !sp.single && !f.participants.iter().any(|b| b == "*") => &f.participants,
_ => &[],
}
}
fn in_hole_scope(scope: &[String], b: &ModelBody) -> bool {
scope.is_empty() || scope.contains(&b.name)
}
/// Where a hole feature drills (each on the surface) and in which direction: at its sketch
/// points perpendicular to the sketch (into the material), else at its position.
fn hole_spots(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
let FeatureKind::Hole { position, at, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
let (spots, dir) = match points {
Some(sp) if !sp.single => {
let ss =
st.sketch(sp.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", sp.sketch)))?;
let mut v = Vec::new();
for id in &sp.ids {
let p = ss.sketch.points.iter().find(|p| &p.id == id).ok_or_else(|| DocError::Unknown(format!("sketch point `{id}`")))?;
v.push(ss.plane.to_world(p.pos));
}
let dir = sketch_hole_dir(st, &v, ss.plane.normal(), hole_scope(f));
let dir = if sp.flip { -dir } else { dir };
(v, dir)
}
_ => {
let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;
let at = hole_on_surface(st, single_hole_position(vals, st, position, at, points)?, dir, &[]);
let at = with_references(vals, st, f, at, dir, true)?;
let dir = hole_dir_into_face(st, at, dir);
return Ok((vec![hole_on_surface(st, at, dir, &[])], dir));
}
};
if spots.is_empty() || spots.len() > 10_000 {
return Err(DocError::Invalid("a hole needs 1…10000 points".into()));
}
Ok((spots.into_iter().map(|p| hole_on_surface(st, p, dir, hole_scope(f))).collect(), dir))
}
/// A hole's depth: down to the To Object (where the hole's axis meets the face there, else the
/// point's depth along the axis), else as given.
fn hole_depth_to(st: &ModelState, at: &Vec3, dir: Vec3, to: &Option<Vec3>, depth: &Option<crate::Expr>) -> Result<Option<crate::Expr>> {
let Some(t) = to else { return Ok(depth.clone()) };
let mut d = (*t - *at).dot(dir);
// The face at the To point, met along the axis.
for b in st.bodies.iter().filter(|b| !b.body.is_mesh()) {
let Some(fi) = crate::appearance::face_index_at(b, *t) else { continue };
let m = b.mesh();
if let Some((h, tri)) = m.raycast(*at + dir * 1e-6, dir)
&& m.tri_face.get(tri).is_some_and(|x| *x as usize == fi)
{
d = h + 1e-6;
}
break;
}
if !(d > 1e-6) {
return Err(DocError::Invalid("the hole's To object is not ahead of the hole".into()));
}
Ok(Some(format!("{d} mm").into()))
}
/// A hole's spots as given (not yet moved onto the surface) and its direction.
fn hole_spots_raw(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
let FeatureKind::Hole { position, at, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
match points {
Some(sp) if !sp.single => {
let ss = st.sketch(sp.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", sp.sketch)))?;
let v: Vec<Vec3> =
sp.ids.iter().filter_map(|id| ss.sketch.points.iter().find(|p| &p.id == id)).map(|p| ss.plane.to_world(p.pos)).take(10_000).collect();
let dir = sketch_hole_dir(st, &v, ss.plane.normal(), hole_scope(f));
let dir = if sp.flip { -dir } else { dir };
Ok((v, dir))
}
_ => {
let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;
let p = single_hole_position(vals, st, position, at, points)?;
let p = if hole_references(f).is_empty() { p } else { with_references(vals, st, f, hole_on_surface(st, p, dir, &[]), dir, false)? };
Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir, &[]), dir)))
}
}
}
/// Where a hole placed by position is drilled: at its sketch point where the sketch has it now,
/// for a Single hole snapped to one (#2110), else as [`hole_position`].
fn single_hole_position(
vals: &BTreeMap<String, Value>,
st: &ModelState,
position: &crate::FacePick,
at: &Option<crate::PointExpr>,
points: &Option<crate::SketchPoints>,
) -> Result<Vec3> {
let Some(sp) = points else { return hole_position(vals, position, at) };
let ss = st.sketch(sp.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", sp.sketch)))?;
let id = sp.ids.first().ok_or_else(|| DocError::Invalid("a Single hole needs its sketch point".into()))?;
let p = ss.sketch.points.iter().find(|p| &p.id == id).ok_or_else(|| DocError::Unknown(format!("sketch point `{id}`")))?;
Ok(ss.plane.to_world(p.pos))
}
/// A hole's (#37) or a cylinder's (#6380) reference edges; none for any other feature.
fn hole_references(f: &Feature) -> &[crate::HoleReference] {
match &f.kind {
FeatureKind::Hole { references, .. } | FeatureKind::Cylinder { references, .. } => references,
_ => &[],
}
}
/// Where a cylinder stands: its base, or with reference edges (#6380) at their distances in the
/// plane of the flat face at its base, square to its axis.
fn cylinder_base(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature, base: &crate::PointExpr, axis: Vec3) -> Result<Vec3> {
let at = point(vals, base)?;
with_references(vals, st, f, at, -axis, true)
}
/// Where a Single hole (or a cylinder) with reference edges (#37) is placed: at its distances
/// from the edges' lines, in the plane of the face at `at` (on the surface), the edges found by
/// their names, else their points. A feature without reference edges stays at `at`. With
/// `on_face` the centre must lie on that face; a pattern or mirror replaying a hole that is
/// already drilled finds its centre in the opening and doesn't ask (#8055).
fn with_references(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature, at: Vec3, dir: Vec3, on_face: bool) -> Result<Vec3> {
let references = hole_references(f);
if references.is_empty() {
return Ok(at);
}
let mut distances = Vec::with_capacity(references.len());
for r in references {
distances.push(Document::eval_in(vals, &r.distance, Kind::Length)?);
}
let edges: Vec<(Vec3, Option<&str>)> = references.iter().enumerate().map(|(i, r)| (r.edge.0, f.edge_names.get(i).map(String::as_str))).collect();
let frame = crate::hole_reference::reference_frame(st, at, dir, &edges, false)?;
let centre = frame.place(at, &distances)?;
if on_face && !crate::hole_reference::on_reference_face(st, &frame, centre) {
return Err(DocError::Invalid("the reference distances put the hole's centre off its face".into()));
}
Ok(centre)
}
/// Where a hole placed by position is drilled: its `at` expressions evaluated, so it follows the
/// parameters (#1678), else the point it was given.
fn hole_position(vals: &BTreeMap<String, Value>, position: &crate::FacePick, at: &Option<crate::PointExpr>) -> Result<Vec3> {
let Some([x, y, z]) = at else { return Ok(position.0) };
let p =
Vec3::new(Document::eval_in(vals, x, Kind::Length)?, Document::eval_in(vals, y, Kind::Length)?, Document::eval_in(vals, z, Kind::Length)?);
if ![p.x, p.y, p.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) {
return Err(DocError::Invalid("the hole's position is out of range".into()));
}
Ok(p)
}
// Pick an actual cylindrical wall, not a depth derived from its radius: a large pipe bore can
// be shallow or pass through a thin plate. Sampling its finite face also skips a wider entry
// pocket and keeps metadata attached to the narrow cylindrical bore.
fn parallel_tapped_wall(st: &ModelState, entry: Vec3, inward: Vec3, radius: f64) -> Option<Vec3> {
let tol = (radius * 1e-6).max(1e-6);
let mut best: Option<(f64, Vec3)> = None;
for body in &st.bodies {
// A wall found lies on the line through `entry` along `inward`, give or take its radius
// (and the slant its axis may have off `inward` over the body's distance), and its
// faces lie in the body's exact box: a body whose box that line misses by more holds
// none, and its faces are not read one by one (#10227).
let far = more::exact_box(&body.body).map_or(f64::INFINITY, |b| (b.min - entry).len().max((b.max - entry).len()) + b.diagonal());
if far.is_finite() && more::line_beyond_reach(body, entry, inward, radius * 1.01 + tol + 1e-3 + 2e-4 * far) {
continue;
}
#[cfg(test)]
cost_tests::count(|c| c.tapped_wall += 1);
let mesh = body.mesh();
for face in 0..body.body.face_count() {
let Some(c) = kernel::cylinder_face(&body.body, &mesh, face) else { continue };
let offset = entry - c.axis_point;
if !c.internal
|| (c.radius - radius).abs() > tol
|| c.axis.dot(inward).abs() < 1.0 - 1e-8
|| (offset - c.axis * offset.dot(c.axis)).len() > tol
{
continue;
}
let a = (c.axis_point + c.axis * c.start - entry).dot(inward);
let b = (c.axis_point + c.axis * c.end - entry).dot(inward);
let lo = a.min(b).max(0.0);
let hi = a.max(b);
if hi > lo + 1e-9 && best.as_ref().is_none_or(|(old, _)| lo < *old) {
best = Some((lo, entry + inward * ((lo + hi) * 0.5) + inward.any_perp() * radius));
}
}
}
best.map(|(_, wall)| wall)
}
/// The cutting tools of a hole feature at every spot, each with its exact geometry when it is a
/// straight cylinder (see [`hole_tools_and_prisms`]).
fn hole_feature_tools(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<Vec<(Traced, Option<more::PrimitivePrism>)>> {
let FeatureKind::Hole { diameter, depth, hole, to, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
let (spots, dir) = hole_spots(vals, st, f)?;
if spots.is_empty() || spots.len() > 10_000 {
return Err(DocError::Invalid("a hole needs 1…10000 points".into()));
}
let mut tools = Vec::new();
for at in spots {
let depth = hole_depth_to(st, &at, dir, &to.map(Vec3::from), depth)?;
tools.extend(hole_tools_and_prisms(vals, st, &at, dir, diameter, &depth, hole)?);
}
Ok(tools)
}
/// A hole drilled square into sheet metal whose tools are straight cylinders (a plain hole, a
/// counterbore) is machined like the equivalent extrude cut, so the sheet keeps it as a cut-out
/// or pocket of its flat pattern (#560). Returns the sheet bodies it machined; none, with the
/// model as it was, when a tool that meets a sheet can't be kept that way (the ordinary cut then
/// refuses it). Pieces the hole parts from a sheet's base are named in `warning`.
fn sheet_hole_cut(
st: &mut ModelState,
f: &Feature,
tools: &[(Traced, Option<more::PrimitivePrism>)],
warning: &mut Option<String>,
) -> Result<Vec<String>> {
if st.sheets.is_empty() {
return Ok(Vec::new());
}
let saved = (st.sheets.clone(), st.bodies.clone());
let mut handled: Vec<String> = Vec::new();
// Noted only when every tool was machined here.
let mut parted = None;
// Many plain drills along one axis (a hole on each of a pattern's points): all in one pass.
let prisms: Option<Vec<more::PrimitivePrism>> = tools.iter().map(|(_, prism)| *prism).collect();
if let Some(prisms) = prisms {
match more::sheet_drill_cuts(f, st, &prisms, &mut parted)? {
Some(done) => {
if let Some(note) = parted {
append_warning(warning, note);
}
return Ok(done);
}
// Not all of them that way: one by one, from the model as it was.
None => {
(st.sheets, st.bodies) = saved.clone();
parted = None;
}
}
}
for (tool, prism) in tools {
let tool = &tool.body;
// Square across the panels it meets, a flat cut-out; along them into a rim, a bore.
let done = match prism {
Some(prism) => match more::sheet_drill(f, st, *prism)? {
Some(more::Drill::Across) => more::sheet_primitive_cut(f, st, tool, *prism, Operation::Cut, true, &mut parted)?,
Some(more::Drill::Along) => more::sheet_bore_cut(f, st, *prism)?.unwrap_or_default(),
None => Vec::new(),
},
None => Vec::new(),
};
if done.is_empty() {
// A sheet whose box lies clear of the tool's cannot meet it (#10226).
let reach = more::exact_box(tool);
let mut meets = false;
for sheet in &st.sheets {
let Some(mb) = st.body(&sheet.body) else { continue };
if more::boxes_apart(&more::exact_box(&mb.body), &reach) {
continue;
}
#[cfg(test)]
cost_tests::count(|c| c.cut += 1);
if kernel::boolean(&mb.body, tool, BoolOp::Intersect)?.is_some() {
meets = true;
break;
}
}
if meets {
(st.sheets, st.bodies) = saved;
return Ok(Vec::new());
}
}
for name in done {
if !handled.contains(&name) {
handled.push(name);
}
}
}
if let Some(note) = parted {
append_warning(warning, note);
}
Ok(handled)
}
/// The cutting tools of one hole at `position`, drilling along `dir`.
#[allow(clippy::too_many_arguments)]
fn hole_tools(
vals: &BTreeMap<String, Value>,
st: &ModelState,
position: &Vec3,
dir: Vec3,
diameter: &str,
depth: &Option<crate::Expr>,
hole: &HoleKind,
) -> Result<Vec<Traced>> {
Ok(hole_tools_and_prisms(vals, st, position, dir, diameter, depth, hole)?.into_iter().map(|(tool, _)| tool).collect())
}
/// The scale a hole's tools are sized by: the largest body the hole's axis meets (#2904), so a
/// large body elsewhere in the model changes neither the tool's reach above the face nor its
/// depth. A hole whose axis meets no body is sized by the
/// largest body of the model, as before.
fn hole_axis_size(st: &ModelState, position: &Vec3, dir: Vec3) -> f64 {
let along = |b: &ModelBody| {
// The axis (an unbounded line) against the body's box, grown by the display tolerance.
let bb = b.mesh().bounds();
if bb.is_empty() {
return false;
}
let pad = 2.0 * b.display_tol();
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
for (o, d, min, max) in
[(position.x, dir.x, bb.min.x, bb.max.x), (position.y, dir.y, bb.min.y, bb.max.y), (position.z, dir.z, bb.min.z, bb.max.z)]
{
if d.abs() < 1e-12 {
if o < min - pad || o > max + pad {
return false;
}
} else {
let (a, c) = ((min - pad - o) / d, (max + pad - o) / d);
lo = lo.max(a.min(c));
hi = hi.min(a.max(c));
}
}
lo <= hi
};
let met = st.bodies.iter().filter(|b| along(b)).map(|b| b.body.size()).fold(0.0, f64::max);
if met > 0.0 { met } else { st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max) }
}
/// [`hole_tools`], each with its exact geometry when it is a straight cylinder along the axis
/// (a plain hole, a counterbore, a drill point left in the air past a through hole), so sheet
/// metal can keep it as a flat cut-out or pocket. Each tool's faces are named by the part of the
/// hole it cuts (`bore`, `cbore`, `csink`: `F7:cbore:base` is a counterbore's floor).
#[allow(clippy::too_many_arguments)]
fn hole_tools_and_prisms(
vals: &BTreeMap<String, Value>,
st: &ModelState,
position: &Vec3,
dir: Vec3,
diameter: &str,
depth: &Option<crate::Expr>,
hole: &HoleKind,
) -> Result<Vec<(Traced, Option<more::PrimitivePrism>)>> {
let r = val(vals, diameter, Kind::Length)? / 2.0;
if !(r > 1e-6) {
return Err(DocError::Invalid("hole diameter must be positive".into()));
}
let size = hole_axis_size(st, position, dir);
let top = (size * 0.01).max(0.1);
let bottom = match depth {
Some(d) => -val(vals, d, Kind::Length)?,
None => -(size * 2.0 + 1.0),
};
if bottom >= 0.0 {
return Err(DocError::Invalid("hole depth must be positive".into()));
}
// Tools are cylinders and cones made by (tapered) extrudes along the axis, cut one
// after another, widest first.
let plane = Plane::from_normal(*position, -dir).ok_or_else(|| DocError::Invalid("hole axis".into()))?;
// Each tool's circle seam at its own angle, so seams don't line up between tools.
let seam = std::cell::Cell::new(0.0);
let disc = |rad: f64| {
seam.set(seam.get() + 0.613);
Region2 { outer: solidcraft_geom::Loop2::circle_from(Vec2::ZERO, rad, seam.get()), holes: vec![] }
};
let cyl = |rad: f64, lo: f64, hi: f64, part: &str| -> Result<(Traced, Option<more::PrimitivePrism>)> {
let tool = kernel::extrude(&plane, &[disc(rad)], lo, hi)?.pop().ok_or_else(|| DocError::Invalid("hole tool".into()))?;
let axis = plane.normal();
let prism = more::PrimitivePrism::Cylinder { base: *position + axis * lo, axis, radius: rad, height: hi - lo };
Ok((crate::lineage::part_tool(tool, part), Some(prism)))
};
// Reuse the existing drill-point tool for the narrow bore, independently of its entry.
let bore = |tip_angle: Option<&crate::Expr>| -> Result<Vec<(Traced, Option<more::PrimitivePrism>)>> {
if let Some(tip_angle) = tip_angle {
let half = val(vals, tip_angle, Kind::Angle)? / 2.0;
// A hole exactly as deep as the material: the point is in the air past the exit
// face, which would lie on the drill point's shoulder (a through hole, as drilled).
let at = |h: f64| *position + dir * (-h);
let eps = size * 1e-6;
// Exact classification against every body: material where one has the point inside,
// air where all have it outside; a point within a body's tolerance of its boundary is
// neither, and the hole is then not taken to exit at its shoulder.
let classes = |h: f64| st.bodies.iter().map(|b| b.body.classify_point(at(h))).collect::<std::result::Result<Vec<_>, _>>();
let solid = classes(bottom + eps)?.contains(&kernel::PointClass::Inside);
let air = classes(bottom - eps)?.iter().all(|c| *c == kernel::PointClass::Outside);
let exits_at_shoulder = solid && air;
if depth.is_some() && half > 1e-3 && half < std::f64::consts::FRAC_PI_2 && !exits_at_shoulder {
// One revolved tool (cylinder with a drill point).
let tip = r / half.tan();
let up = -dir;
let side = up.any_perp();
let rp = Plane::new(*position, side, up).ok_or_else(|| DocError::Invalid("hole axis".into()))?;
let pts = [Vec2::new(0.0, top), Vec2::new(r, top), Vec2::new(r, bottom), Vec2::new(0.0, bottom - tip)];
let region = Region2 { outer: solidcraft_geom::Loop2::polygon(&pts), holes: vec![] };
return Ok(kernel::revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU)?
.into_iter()
.map(|tool| (crate::lineage::part_tool(tool, "bore"), None))
.collect());
}
}
Ok(vec![cyl(r, bottom, top, "bore")?])
};
let mut tools = Vec::new();
match hole {
HoleKind::Simple => tools.extend(bore(None)?),
HoleKind::Drilled { tip_angle } => tools.extend(bore(Some(tip_angle))?),
HoleKind::Counterbore { cb_diameter, cb_depth, tip_angle } => {
let (rc, dc) = (val(vals, cb_diameter, Kind::Length)? / 2.0, val(vals, cb_depth, Kind::Length)?);
if !(rc > r && dc > 0.0 && -dc > bottom) {
return Err(DocError::Invalid("the counterbore must be wider than the hole and shallower than it".into()));
}
// Wide and shallow first: the narrow hole then crosses the pocket floor.
tools.push(cyl(rc, -dc, top, "cbore")?);
tools.extend(bore(tip_angle.as_ref())?);
}
HoleKind::Countersink { cs_diameter, cs_angle, tip_angle } => {
let (rc, half) = (val(vals, cs_diameter, Kind::Length)? / 2.0, val(vals, cs_angle, Kind::Angle)? / 2.0);
if !(rc > r && half > 1e-3 && half < std::f64::consts::FRAC_PI_2) {
return Err(DocError::Invalid("the countersink must be wider than the hole".into()));
}
// One revolved tool: the cone from its rim on the face to just inside the hole
// radius, and above the face the rim's cylinder, as the bore's own cylinder runs on
// above it. The cone widening on above the face would cut what stands beside the rim
// (#5041). The cone is the profile's first segment (`csink:side:0`).
let r_end = r * 0.9;
let len = (rc - r_end) / half.tan();
let up = -dir;
let rp = Plane::new(*position, up.any_perp(), up).ok_or_else(|| DocError::Invalid("hole axis".into()))?;
let pts = [Vec2::new(rc, 0.0), Vec2::new(r_end, -len), Vec2::new(0.0, -len), Vec2::new(0.0, top), Vec2::new(rc, top)];
let region = Region2 { outer: solidcraft_geom::Loop2::polygon(&pts), holes: vec![] };
tools.extend(
kernel::revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU)?
.into_iter()
.map(|tool| (crate::lineage::part_tool(tool, "csink"), None)),
);
tools.extend(bore(tip_angle.as_ref())?);
}
}
Ok(tools)
}
/// The angular interval used by both the solid and its interactive extent handles.
#[derive(Clone, Copy, Debug)]
pub struct RevolveExtent {
pub start: f64,
pub sweep: f64,
pub rotation_axis: Vec3,
pub display_start: f64,
/// A curved target trims the swept solid and has no single angular boundary.
pub curved_to: bool,
}
pub fn revolve_extent(
st: &ModelState,
plane: &Plane,
regions: &[Region2],
(origin, axis): (Vec3, Vec3),
(angle, angle2): (f64, Option<f64>),
symmetric: bool,
to: Option<Vec3>,
) -> Result<RevolveExtent> {
revolve_extent_with_convention(st, plane, regions, (origin, axis), (angle, angle2), symmetric, to, crate::RevolveConvention::LegacyAxisStart)
}
#[allow(clippy::too_many_arguments)]
pub fn revolve_extent_with_convention(
st: &ModelState,
plane: &Plane,
regions: &[Region2],
(origin, axis): (Vec3, Vec3),
(angle, angle2): (f64, Option<f64>),
symmetric: bool,
to: Option<Vec3>,
convention: crate::RevolveConvention,
) -> Result<RevolveExtent> {
let extent = revolve_extent_for_handle(st, plane, regions, (origin, axis), (angle, angle2), symmetric, to, convention)?;
// A solid needs an open sweep inside one full turn. Zero and a turn past 360° keep a
// handle frame (`revolve_extent_for_handle`) and still fail here, with the same message.
if !(extent.sweep.abs() > 1e-9 && extent.sweep.abs() <= std::f64::consts::TAU + 1e-9) {
return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into()));
}
Ok(extent)
}
/// Where the angle handle sits. A sweep of zero, or past a full turn, builds no solid and
/// [`revolve_extent_with_convention`] refuses it. The boundary is still a point on the circle,
/// and the grab point stays there so the angle can be dragged back into range.
#[allow(clippy::too_many_arguments)]
pub fn revolve_extent_for_handle(
st: &ModelState,
plane: &Plane,
regions: &[Region2],
(origin, axis): (Vec3, Vec3),
(angle, angle2): (f64, Option<f64>),
symmetric: bool,
to: Option<Vec3>,
convention: crate::RevolveConvention,
) -> Result<RevolveExtent> {
let (start, sweep) = match (to, angle2, symmetric) {
(Some(point), _, _) => {
let points: Vec<Vec2> = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect();
let centre = if convention == crate::RevolveConvention::SketchNormal {
regions.first().map(|r| plane.to_world(r.centroid())).ok_or_else(|| DocError::Invalid("no profile selected".into()))?
} else {
plane.to_world(points.iter().fold(Vec2::default(), |sum, point| sum + *point) * (1.0 / points.len().max(1) as f64))
};
let projection_axis = if convention == crate::RevolveConvention::SketchNormal {
axis.normalized().ok_or_else(|| DocError::Invalid("revolve axis has no direction".into()))?
} else {
axis
};
let flat = |point: Vec3| {
let v = point - origin;
v - projection_axis * v.dot(projection_axis)
};
let (u, v) = (flat(centre), flat(point));
let angle_axis = if convention == crate::RevolveConvention::SketchNormal {
if v.len() < 1e-9 {
return Err(DocError::Invalid("the revolve target lies on the axis; pick a point away from the axis".into()));
}
kernel::canonical_revolve_axis(
plane,
regions.first().ok_or_else(|| DocError::Invalid("no profile selected".into()))?,
plane.to_local(origin),
Vec2::new(projection_axis.dot(plane.x), projection_axis.dot(plane.y)),
)?
} else {
-axis
};
let sweep = angle_axis.dot(u.cross(v)).atan2(u.dot(v));
(0.0, if sweep <= 1e-9 { sweep + std::f64::consts::TAU } else { sweep })
}
(None, Some(other), _) => (-other, angle + other),
(None, None, true) => (-angle / 2.0, angle),
(None, None, false) => (0.0, angle),
};
if !(sweep.is_finite() && start.is_finite()) {
return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into()));
}
let points: Vec<Vec2> = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect();
let centre = plane.to_world(points.iter().fold(Vec2::default(), |sum, point| sum + *point) * (1.0 / points.len().max(1) as f64));
let unit_axis = axis.normalized().ok_or_else(|| DocError::Invalid("revolve axis has no direction".into()))?;
let radial_centre = regions.first().map(|region| plane.to_world(region.centroid())).unwrap_or(centre);
let radial = radial_centre - origin - unit_axis * (radial_centre - origin).dot(unit_axis);
let rotation_axis = match (convention, regions.first()) {
(crate::RevolveConvention::SketchNormal, Some(region)) => {
kernel::canonical_revolve_axis(plane, region, plane.to_local(origin), Vec2::new(unit_axis.dot(plane.x), unit_axis.dot(plane.y)))?
}
_ => {
if unit_axis.cross(radial).dot(plane.normal()) < 0.0 {
-unit_axis
} else {
unit_axis
}
}
};
let display_start = match convention {
crate::RevolveConvention::LegacyAxisStart => start * -unit_axis.dot(rotation_axis),
crate::RevolveConvention::SketchNormal => start,
};
Ok(RevolveExtent { start, sweep, rotation_axis, display_start, curved_to: to.is_some_and(|point| curved_target_any(st, point).is_some()) })
}
/// The exact input frame and scalar interval of a current, untrimmed constructor.
struct ExtrudeConstructor {
plane: Plane,
interval: (f64, f64),
}
/// Construct planar caps locally before placing the completed tool.
fn centered_extrude(
plane: &Plane,
region: &Region2,
start: f64,
end: f64,
sketch: Option<&SolvedSketch>,
thin: Option<&crate::lineage::ThinWallRoles>,
) -> Result<Vec<Traced>> {
if !plane.origin.is_finite()
|| !plane.x.is_finite()
|| !plane.y.is_finite()
|| (plane.x.len2() - 1.0).abs() > 1e-8
|| (plane.y.len2() - 1.0).abs() > 1e-8
|| plane.x.dot(plane.y).abs() > 1e-8
{
return Err(DocError::Invalid("extrude frame is not finite and orthonormal".into()));
}
// The faces' roles: the sketch curve under each side, the caps by where they lie.
let (lo, hi) = if start <= end { (start, end) } else { (end, start) };
let roles = crate::lineage::ProfileRoles {
sketch,
region: Some(region),
caps: [Some(crate::lineage::extrude_cap_role(lo)), Some(crate::lineage::extrude_cap_role(hi))],
thin,
};
// Fit cap surfaces in their own coordinates. Fitting a distant world-space
// wire can tilt an otherwise exact planar cap through numeric cancellation.
// A side drawn in collinear pieces is one face (#1788).
let bodies = kernel::extrude_whole_sides(&Plane::XY, std::slice::from_ref(region), start, end)?;
if *plane == Plane::XY {
return Ok(bodies.into_iter().map(|body| roles.tool(body, None)).collect());
}
let n = plane.normal();
let m = [
[plane.x.x, plane.x.y, plane.x.z, 0.0],
[plane.y.x, plane.y.y, plane.y.z, 0.0],
[n.x, n.y, n.z, 0.0],
[plane.origin.x, plane.origin.y, plane.origin.z, 1.0],
];
bodies
.into_iter()
.map(|body| {
let moved = kernel::transform_matrix(&body, m)?;
Ok(roles.tool(moved, Some(&body)))
})
.collect()
}
/// How far a thin extrude's wall reaches either side of its curves: (inside, outside).
fn thin_distances(vals: &BTreeMap<String, Value>, thin: &crate::ThinWall) -> Result<(f64, f64)> {
let t = val(vals, &thin.thickness, Kind::Length)?;
let (inside, outside) = match thin.side {
crate::ThinSide::Center => (t / 2.0, t / 2.0),
crate::ThinSide::Inside => (t, 0.0),
crate::ThinSide::Outside => (0.0, t),
crate::ThinSide::TwoSides => {
let e = thin.thickness2.as_deref().ok_or_else(|| DocError::Invalid("a two-sided thin wall needs `thickness2`".into()))?;
(t, val(vals, e, Kind::Length)?)
}
};
if !(inside >= 0.0 && outside >= 0.0 && inside + outside > 0.0) {
return Err(DocError::Invalid("the wall thickness must be positive".into()));
}
Ok((inside, outside))
}
/// The regions a thin extrude's wall covers in its sketch.
pub(crate) fn thin_regions(vals: &BTreeMap<String, Value>, ss: &SolvedSketch, thin: &crate::ThinWall) -> Result<Vec<Region2>> {
if thin.curves.is_empty() || thin.curves.len() > 1000 {
return Err(DocError::Invalid("a thin extrude needs 1…1000 sketch curves".into()));
}
let (inside, outside) = thin_distances(vals, thin)?;
let curves = thin
.curves
.iter()
.map(|id| {
let ci = ss.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("curve `{id}` of {}", ss.name)))?;
Ok(ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci)))
})
.collect::<Result<Vec<_>>>()?;
solidcraft_sketch::thin_wall_regions(&curves, inside, outside).map_err(|e| DocError::Invalid(format!("thin wall: {e}")))
}
/// How far apart (mm) profiles must stay for their extruded tools to be cut as one.
const APART_GAP: f64 = 1e-3;
/// The tool bodies a feature adds or removes (extrude, revolve, primitives), in the current state.
/// `to_body` is the body a To Object extent runs to (an extrude), when it found one.
fn feature_tools_with_constructor(
doc: &Document,
vals: &BTreeMap<String, Value>,
f: &Feature,
st: &ModelState,
constructor: &mut Option<ExtrudeConstructor>,
to_body: &mut Option<String>,
warning: &mut Option<String>,
) -> Result<Vec<Traced>> {
*to_body = None;
let unnamed = |bodies: Vec<Body>| -> Vec<Traced> { bodies.into_iter().map(Traced::unnamed).collect() };
match &f.kind {
FeatureKind::Extrude { sketch, profiles, extent, operation, targets, thin } => {
let ss = sketch_in_feature_frame(
doc,
st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?,
f.component,
)?;
let regions = match thin {
Some(thin) => thin_regions(vals, &ss, thin)?,
None => solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?),
};
// A thin wall's sides are named by the curves they run beside.
let thin_roles = match thin {
Some(thin) => {
let (inside, outside) = thin_distances(vals, thin)?;
Some(crate::lineage::ThinWallRoles { curves: thin.curves.clone(), distances: [inside, outside] })
}
None => None,
};
// From / To Object: where the face or point lies along the normal, measured over the
// middle of the profiles. The points are in this feature's component frame, so the
// model is seen from there: a target in another, moved component where it is shown.
let n = ss.plane.normal();
let tst =
if extent.to.is_some() || extent.from.is_some() { state_in_frame(doc, st, f.component)? } else { std::borrow::Cow::Borrowed(st) };
// Through all, and where the tool meets its targets, is measured where they are shown.
let shown = targets_as_shown(st, f, &crate::plain(targets))?;
let st: &ModelState = &shown;
// The face names follow `face_points`: To, then From.
let name = |k: usize| f.face_names.get(k).map(String::as_str);
let (to_name, from_name) = if extent.to.is_some() { (name(0), name(1)) } else { (None, name(0)) };
let to_face = extent.to.and_then(|p| object_face(&tst, to_name, p.0, Some(n)));
// The body the extent runs to: a Join to it joins that body too (#6424), unless the
// design was built before it did (#8151).
*to_body = to_face.filter(|_| !extent.to_body_apart).and_then(|(bi, _)| tst.bodies.get(bi)).map(|b| b.name.clone());
let centre = {
let pts: Vec<Vec2> = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect();
let c = pts.iter().fold(Vec2::default(), |a, p| a + *p) * (1.0 / pts.len().max(1) as f64);
ss.plane.to_world(c)
};
let from = match extent.from {
Some(p) => height_at(&tst, object_face(&tst, from_name, p.0, Some(n)), &ss.plane, centre, p.0),
None => 0.0,
};
let d = match extent.to {
Some(p) => {
let off = match &extent.to_offset {
Some(e) => val(vals, e, Kind::Length)?,
None => 0.0,
};
let h = height_at(&tst, to_face, &ss.plane, centre, p.0);
let start = from + extent.start_offset.as_deref().map(|e| val(vals, e, Kind::Length)).transpose()?.unwrap_or(0.0);
// Past the face by the offset, in the direction travelled.
let to = h + if h >= start { off } else { -off };
if (to - start).abs() < 1e-9 {
return Err(DocError::Invalid("the To object is where the extrude starts".into()));
}
to - start
}
None if extent.through_all => through_all_distance(st, &ss.plane, &crate::plain(targets))?,
None => val(vals, &extent.distance, Kind::Length)?,
};
if let Some(tp) = &extent.taper {
let taper = val(vals, tp, Kind::Angle)?;
if extent.distance2.is_some() || extent.direction == crate::Direction::Symmetric {
return Err(DocError::Invalid("not supported yet: taper with two-sided or symmetric extents".into()));
}
let sign = if extent.to.is_none() && extent.direction == crate::Direction::Negative { -1.0 } else { 1.0 };
let (len, sign) = if d < 0.0 { (-d, -sign) } else { (d, sign) };
// Where the extrude starts: the From Object's level and a start offset along the
// normal from it. The offset moves the profile that far and the sides are drafted
// from there, so the profile stays the section at the start whatever the offset
// (`d` is measured from the start already, To Object included).
let base = from
+ match &extent.start_offset {
Some(e) => val(vals, e, Kind::Length)?,
None => 0.0,
};
let start_plane = ss.plane.offset(base);
let caps = [
Some(crate::lineage::extrude_cap_role(base)),
Some(crate::lineage::extrude_cap_role(if sign < 0.0 { base - len } else { base + len })),
];
// How far a tool grows past its profile, at most: its sides' run over its length.
let growth = len * taper.tan().abs();
let mut notes = Vec::new();
let tools: Vec<Traced> = regions
.iter()
.map(|r| {
let roles =
crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone(), thin: thin_roles.as_ref() };
let corner = match extent.corner {
Some(c) => c,
None => draft_corner_for(&ss, r, len, taper, &mut notes)?,
};
let body = kernel::extrude_tapered_between(&start_plane, r, 0.0, len, 0.0, sign, taper, corner)?;
Ok(roles.tool(body, None))
})
.collect::<Result<_>>()?;
for note in notes {
append_warning(warning, note);
}
// Profiles apart by more than the tools grow (the letters of a text): the tools
// are apart too, and go into the body as one, in one boolean rather than one per
// profile, each on a body grown or cut by the ones before. (A join meeting several
// bodies keeps joining them tool by tool; sheet metal keeps cutting tool by tool.)
let sheet =
if targets.is_empty() { !st.sheets.is_empty() } else { targets.iter().any(|t| st.sheets.iter().any(|sheet| &sheet.body == t)) };
let one_target = if targets.is_empty() { st.bodies.len() == 1 } else { targets.len() == 1 };
let at_once = match operation {
Operation::Cut => !sheet,
Operation::Join => one_target && !sheet,
_ => false,
};
if at_once && tools.len() > 1 && regions_apart(&regions, APART_GAP + 2.0 * growth) {
let bodies: Vec<Body> = tools.iter().map(|t| t.body.clone()).collect();
if let Some(one) = kernel::join_apart(&bodies)? {
return Ok(vec![Traced::step(one, &tools.iter().collect::<Vec<_>>())]);
}
}
return Ok(tools);
}
let off = from
+ match &extent.start_offset {
Some(e) => val(vals, e, Kind::Length)?,
None => 0.0,
};
// To Object gives a signed distance from the start: one side only.
let direction = if extent.to.is_some() { crate::Direction::Positive } else { extent.direction };
let (a, b) = extent_sides(vals, extent, d, direction)?;
// A negative distance flips the side.
let (mut lo, mut hi) = if a <= b { (a, b) } else { (b, a) };
// To a curved (or slanted) face: run right through the target body, then keep what
// lies before its surface (the tool less the body, the piece at the start).
let curved = curved_face(&tst, to_face, Some(n));
if let Some(bi) = curved
&& let Some(tb) = tst.bodies.get(bi)
{
let m = tb.mesh();
let hs: Vec<f64> = m.positions.iter().map(|q| (*q - ss.plane.origin).dot(n) - off).collect();
let margin = tb.body.size() * 0.05 + 1.0;
if hi > 0.0 {
hi = hs.iter().cloned().fold(hi, f64::max) + margin;
} else {
lo = hs.iter().cloned().fold(lo, f64::min) - margin;
}
}
let untrimmed = extent.to.is_none() && extent.from.is_none() && !extent.through_all;
let mut tools = Vec::new();
for r in &regions {
tools.extend(centered_extrude(&ss.plane, r, lo + off, hi + off, Some(&ss), thin_roles.as_ref())?);
}
// A cut or a join by profiles apart in the sketch (the letters of a text): each tool
// lies in the prism over its profile, so the tools are apart too. The body is then cut once by all of them, or joined to
// all of them at once, rather than once per profile, each on a body grown or cut by
// the ones before. (A join meeting several bodies keeps joining them tool by tool;
// sheet metal keeps its own way of cutting, tool by tool, to keep its flat pattern.)
let sheet =
if targets.is_empty() { !st.sheets.is_empty() } else { targets.iter().any(|t| st.sheets.iter().any(|sheet| &sheet.body == t)) };
let one_target = if targets.is_empty() { st.bodies.len() == 1 } else { targets.len() == 1 };
let at_once = match operation {
Operation::Cut => !sheet,
Operation::Join => one_target && !sheet,
_ => false,
};
if at_once && tools.len() > 1 && regions_apart(&regions, APART_GAP) {
let bodies: Vec<Body> = tools.iter().map(|t| t.body.clone()).collect();
if let Some(one) = kernel::join_apart(&bodies)? {
tools = vec![Traced::step(one, &tools.iter().collect::<Vec<_>>())];
}
}
if let Some(tb) = curved.and_then(|bi| tst.bodies.get(bi)) {
let start = if hi > 0.0 { lo + off } else { hi + off };
tools = trim_to_body(tools, tb, |q: Vec3| ((q - ss.plane.origin).dot(n) - start).abs())?;
}
// A join's profile grows into the material it joins; its sketch plane and depth as drawn
// still serve a join into sheet metal (`sheet_join`), which takes the sketch's regions.
if untrimmed || (*operation == Operation::Join && curved.is_none()) {
*constructor = Some(ExtrudeConstructor { plane: ss.plane, interval: (lo + off, hi + off) });
}
// A Join tool's faces outlive the boolean where they stay on the result, so they are
// certified as a new body's are (see `Body::with_preserved_union_planar_sources`).
if matches!(operation, Operation::NewBody | Operation::Join) && extent.taper.is_none() {
let bodies: Vec<Body> = tools.iter().map(|t| t.body.clone()).collect();
let cap_bindings = match thin {
Some(thin) => Some(crate::config::thin_extrude_cap_bindings(&thin.curves, regions.len(), &bodies)),
None => crate::config::extrude_cap_bindings(&ss, &bodies, 10_000_000),
};
let source_curves = cap_bindings.as_ref().map(|_| crate::config::ExactSketchCurves::new(&ss));
tools = tools
.into_iter()
.enumerate()
.map(|(body_index, Traced { body, lineage })| {
let curves: Vec<_> = body
.face_sources()
.into_iter()
.flatten()
.map(|source| match source {
Some(kernel::FaceSource::ExtrudeSide { segment, .. }) if cap_bindings.is_some() => {
source_curves.as_ref().and_then(|curves| curves.find(segment))
}
_ => None,
})
.collect();
let mut caps =
cap_bindings.as_ref().and_then(|bindings| bindings.get(body_index)).cloned().unwrap_or_else(|| vec![None; curves.len()]);
// A cap moved off its designed height (into a Join target, or past a
// curved To face) is not the feature's start or end face.
let nominal = |plane: &solidcraft_geom::Plane| {
let height = (plane.origin - ss.plane.origin).dot(n);
let tolerance = 1e-9 * (1.0 + height.abs() + (lo + off).abs() + (hi + off).abs());
(height - (lo + off)).abs() <= tolerance || (height - (hi + off)).abs() <= tolerance
};
for (cap, source) in caps.iter_mut().zip(body.face_sources().into_iter().flatten()) {
if matches!(source, Some(kernel::FaceSource::ExtrudeCap { plane, .. }) if !nominal(plane)) {
*cap = None;
}
}
// Certificates set face sources only: the faces, and their lineage, stay.
let body = body.with_extrude_certificates(f.id, sketch.0, &curves)?.with_extrude_cap_certificates(f.id, sketch.0, &caps)?;
Ok(Traced { body, lineage })
})
.collect::<Result<Vec<_>>>()?;
}
Ok(tools)
}
FeatureKind::Revolve { sketch, profiles, axis, angle, angle2, symmetric, convention, to, .. } => {
let ss = sketch_in_feature_frame(
doc,
st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?,
f.component,
)?;
let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?);
let (o, d) =
revolve_axis(&ss, axis, &*axis_state(doc, st, f.component, axis)?, &|name| construction_axis_in(Some(doc), st, name, f.component))?;
// To Object is in this feature's component frame: the model as seen from there.
let tst = if to.is_some() { state_in_frame(doc, st, f.component)? } else { std::borrow::Cow::Borrowed(st) };
let angles = if to.is_some() {
(0.0, None)
} else {
(val(vals, angle, Kind::Angle)?, angle2.as_ref().map(|a| val(vals, a, Kind::Angle)).transpose()?)
};
let extent = revolve_extent_with_convention(
&tst,
&ss.plane,
&regions,
(ss.plane.to_world(o), ss.plane.dir_to_world(d)),
angles,
*symmetric,
to.map(Vec3::from),
*convention,
)?;
let (start, ang) = (extent.start, extent.sweep);
let region_extents = regions
.iter()
.map(|r| {
if *convention == crate::RevolveConvention::SketchNormal && to.is_some() {
revolve_extent_with_convention(
&tst,
&ss.plane,
std::slice::from_ref(r),
(ss.plane.to_world(o), ss.plane.dir_to_world(d)),
angles,
*symmetric,
to.map(Vec3::from),
*convention,
)
} else {
Ok(extent)
}
})
.collect::<Result<Vec<_>>>()?;
let (operation, _) = feature_op(f);
let axis_w = ss.plane.dir_to_world(d);
let origin_w = ss.plane.to_world(o);
// To a curved face: turn past the whole target body, then cut back to its surface
// (the piece that starts at the profile).
let curved = curved_face(&tst, to.and_then(|p| object_face(&tst, f.face_names.first().map(String::as_str), p.0, None)), None);
let curved_body = curved.and_then(|bi| tst.bodies.get(bi));
// Each region's body: its sides named by the sketch curves, its caps start and end.
let tool = |r: &Region2, body: Body, built: Option<&Body>| crate::lineage::ProfileRoles::swept(Some(&ss), Some(r)).tool(body, built);
let build_curved = |regions: &[Region2], angle_axis: Vec3, tb: &ModelBody| -> Result<Vec<Traced>> {
let pts: Vec<Vec2> = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect();
let c = ss.plane.to_world(pts.iter().fold(Vec2::default(), |a, q| a + *q) * (1.0 / pts.len().max(1) as f64));
let flat = |q: Vec3| {
let v = q - origin_w;
v - axis_w * v.dot(axis_w)
};
let u0 = flat(c);
let angle_of = |q: Vec3| {
let v = flat(q);
let a = angle_axis.dot(u0.cross(v)).atan2(u0.dot(v));
if a < 0.0 { a + std::f64::consts::TAU } else { a }
};
let far = tb.mesh().positions.iter().map(|q| angle_of(*q)).fold(0.0, f64::max);
let sweep = (far + 0.05).min(std::f64::consts::TAU - 1e-3);
let bodies = kernel::revolve(&ss.plane, regions, o, d, sweep)?;
let tools = regions.iter().zip(bodies).map(|(r, body)| tool(r, body, None)).collect();
let n = ss.plane.normal();
let tol_side = |q: Vec3| if flat(q).dot(u0) > 0.0 { ((q - ss.plane.origin).dot(n)).abs() } else { f64::MAX };
trim_to_body(tools, tb, tol_side)
};
if *convention == crate::RevolveConvention::LegacyAxisStart
&& let Some(tb) = curved_body
{
return build_curved(&regions, -axis_w, tb);
}
// A new body is final: its planar faces come out whole. A boolean's tool is not
// healed (the boolean heals its result).
let revolve = if operation == Operation::NewBody { kernel::revolve_whole } else { kernel::revolve };
if *convention == crate::RevolveConvention::SketchNormal {
let mut out = Vec::new();
for (region, region_extent) in regions.iter().zip(&region_extents) {
let rotation_axis = kernel::canonical_revolve_axis(&ss.plane, region, o, d)?;
if let Some(tb) = curved_body {
out.extend(build_curved(std::slice::from_ref(region), rotation_axis, tb)?);
continue;
}
let bodies = revolve(&ss.plane, std::slice::from_ref(region), o, d, region_extent.sweep)?;
let m = crate::rigid(Vec3::ZERO, origin_w, rotation_axis, region_extent.start);
for body in bodies {
out.push(if region_extent.start.abs() < 1e-12 {
tool(region, body, None)
} else {
tool(region, kernel::transform_matrix(&body, m)?, Some(&body))
});
}
}
return Ok(out);
}
let bodies = revolve(&ss.plane, &regions, o, d, ang)?;
if start.abs() < 1e-12 {
return Ok(regions.iter().zip(bodies).map(|(r, body)| tool(r, body, None)).collect());
}
// Turned back to start before the profile.
let m = crate::rigid(Vec3::ZERO, origin_w, axis_w, -start);
regions.iter().zip(bodies).map(|(r, body)| Ok(tool(r, kernel::transform_matrix(&body, m)?, Some(&body)))).collect()
}
FeatureKind::Loft { sections, rails, .. } if sections.iter().any(|s| s.point.is_some()) => {
// A profile lofted to a sketch point (an apex).
if !rails.is_empty() {
return Err(DocError::Invalid("not supported yet: guide rails on a loft to a point".into()));
}
let [a, b] = &sections[..] else { return Err(DocError::Invalid("not supported yet: a point section in a loft of more than two".into())) };
let (prof, pt) = if a.point.is_some() { (b, a) } else { (a, b) };
let ss = st.sketch(prof.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", prof.sketch)))?;
let regions = solidcraft_sketch::merge_regions(&select_profiles(ss, &prof.profiles)?);
let [r] = &regions[..] else { return Err(DocError::Invalid("each loft section must be one profile".into())) };
refuse_loft_holes(r)?;
let ps = st.sketch(pt.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", pt.sketch)))?;
let id = pt.point.as_deref().unwrap_or_default();
let q = ps.sketch.points.iter().find(|p| p.id == id).ok_or_else(|| DocError::Unknown(format!("point `{id}` in {}", ps.name)))?;
let body = kernel::loft_to_point(&ss.plane, &r.outer, ps.plane.to_world(q.pos))?;
// Its sides are named by the profile's curves, its base `start`.
Ok(vec![crate::lineage::ProfileRoles::swept(Some(ss), Some(r)).tool(body, None)])
}
FeatureKind::Coil {
base, axis, diameter, pitch, turns, section_size, section, position, start_angle, clockwise, sketch, profiles, ..
} => {
let base = &point(vals, base)?;
let k = axis.normalized().ok_or_else(|| DocError::Invalid("coil axis".into()))?;
let p = val(vals, pitch, Kind::Length)?;
let n = val(vals, turns, Kind::Unitless)?;
if sketch.is_some()
&& (diameter.is_some()
|| section_size.is_some()
|| start_angle.is_some()
|| !matches!(section, crate::CoilSection::Circular)
|| *position != 0)
{
return Err(DocError::Invalid(
"a coil with a `sketch` cannot also set `diameter`, `section_size`, `section`, `section_position` or `start_angle`".into(),
));
}
if sketch.is_none() && !matches!(profiles, ProfileSel::All) {
return Err(DocError::Invalid("a coil's `profiles` need a `sketch`".into()));
}
if let Some(sk) = sketch {
let ss = st.sketch(sk.0).ok_or_else(|| DocError::Unknown(format!("sketch {sk} (it must come earlier in the timeline)")))?;
let regions = select_profiles(ss, profiles)?;
if regions.iter().any(|r| !r.holes.is_empty()) {
return Err(DocError::Invalid("a coil from a sketch takes a profile without holes".into()));
}
let [region] = &regions[..] else {
return Err(DocError::Invalid(format!("a coil from a sketch takes one closed profile (the sketch has {})", regions.len())));
};
let axis = if *clockwise { k * -1.0 } else { k };
// A left-handed coil turns about −axis and climbs along +axis: mirror the pitch.
let pitch = if *clockwise { -p } else { p };
return Ok(unnamed(vec![kernel::sweep_helix(&ss.plane, region, *base, axis, pitch, n)?]));
}
let diameter = diameter.as_ref().ok_or_else(|| DocError::Invalid("a coil needs a `sketch` or a `diameter`".into()))?;
let section_size = section_size.as_ref().ok_or_else(|| DocError::Invalid("a coil needs a `sketch` or a `section_size`".into()))?;
let (d, s) = (val(vals, diameter, Kind::Length)?, val(vals, section_size, Kind::Length)?);
if !(d > 0.0 && s > 0.0 && n > 0.0) {
return Err(DocError::Invalid("the coil diameter, section size and revolutions must be positive".into()));
}
let r = d / 2.0 + f64::from(*position) * s / 2.0;
if r <= s / 2.0 {
return Err(DocError::Invalid("the section reaches the coil's axis".into()));
}
let a0 = match start_angle {
Some(e) => val(vals, e, Kind::Angle)?,
None => 0.0,
};
// Radial direction at the start; the section lies in the plane of the axis.
let x0 = if k.cross(Vec3::X).len() > 1e-6 { (Vec3::X - k * k.dot(Vec3::X)).normalized() } else { Some(k.any_perp()) };
let x0 = x0.ok_or_else(|| DocError::Invalid("coil axis".into()))?;
let x = x0 * a0.cos() + k.cross(x0) * a0.sin();
let plane = Plane { origin: *base, x, y: k };
let c = Vec2::new(r, 0.0);
let outer = match section {
crate::CoilSection::Circular => solidcraft_geom::Loop2::circle(c, s / 2.0),
crate::CoilSection::Square => {
let h = s / 2.0;
solidcraft_geom::Loop2::polygon(&[c + Vec2::new(-h, -h), c + Vec2::new(h, -h), c + Vec2::new(h, h), c + Vec2::new(-h, h)])
}
};
let region = Region2 { outer, holes: Vec::new() };
let axis = if *clockwise { k * -1.0 } else { k };
// A left-handed coil turns about −axis and climbs along +axis: mirror the pitch.
let pitch = if *clockwise { -p } else { p };
Ok(unnamed(vec![kernel::sweep_helix(&plane, &region, *base, axis, pitch, n)?]))
}
FeatureKind::Loft { sections, rails, rail_fit, .. } => {
let mut secs = Vec::new();
let mut sketches = Vec::new();
for sec in sections {
let ss = st
.sketch(sec.sketch.0)
.ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", sec.sketch)))?;
let regions = solidcraft_sketch::merge_regions(&select_profiles(ss, &sec.profiles)?);
let [r] = &regions[..] else { return Err(DocError::Invalid("each loft section must be one profile".into())) };
secs.push((ss.plane, r.clone()));
sketches.push(ss);
}
// Its caps are the first and last sections, its sides named by the curves they run
// between.
let body = if rails.is_empty() {
kernel::loft_regions(&secs)?
} else {
// Rails shape the sections' outlines; sections with holes wait for rails that
// carry the holes too.
if secs.iter().any(|(_, r)| !r.holes.is_empty()) {
return Err(DocError::Invalid("not supported yet: guide rails on a loft whose sections have holes".into()));
}
let outlines: Vec<_> = secs.iter().map(|(p, r)| (*p, r.outer.clone())).collect();
// The rails run from the end at the first section.
let start = outlines.first().and_then(|(p, lp)| lp.segs.first().map(|seg| p.to_world(seg.start()))).unwrap_or_default();
kernel::loft_with_rails(&outlines, &rail_polylines(doc, st, rails, f.component, start)?, kernel_rail_fit(*rail_fit))?
};
let roles = crate::lineage::SectionRoles {
sections: sketches.into_iter().zip(secs.iter().map(|(_, r)| std::iter::once(&r.outer).chain(&r.holes).collect())).collect(),
};
Ok(vec![roles.tool(body)])
}
FeatureKind::Sweep { sketch, profiles, path_sketch, path, orientation, twist, scale, rails, rail_fit, .. } => {
let ss = st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?;
let ps =
st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?;
let profile;
let ss = if !ps.sketch.wires.is_empty() {
profile = profile_in_frame(doc, ss, f.component)?;
&profile
} else {
ss
};
let mapped = path_in_frame(doc, ps, f.component)?;
let ps = mapped.as_ref();
let regions = solidcraft_sketch::merge_regions(&select_profiles(ss, profiles)?);
let start = regions.first().map(|r| ss.plane.to_world(r.centroid())).unwrap_or_default();
let tool = |r: &Region2, body: Body| crate::lineage::ProfileRoles::swept(Some(ss), Some(r)).tool(body, None);
let points = path_points(ps, path, start)?;
let segs = match points {
Some(_) => Vec::new(),
None => path_segments_at(ps, path, start, Some(&ss.plane))?,
};
let path_start =
points.as_ref().and_then(|p| p.points().first().copied()).or_else(|| segs.first().map(kernel::PathSeg::start)).unwrap_or(start);
let rails = rail_polylines(doc, st, rails, f.component, path_start)?;
let ctl = sweep_control(vals, orientation, twist, scale, rails, *rail_fit)?;
// A path through 3D sketch curves: its drawn splines exactly, the rest as points.
if let Some(path) = points {
return regions.iter().map(|r| Ok(tool(r, kernel::sweep_point_path_with(&ss.plane, r, &path, &ctl)?))).collect();
}
regions.iter().map(|r| Ok(tool(r, kernel::sweep_with(&ss.plane, r, &segs, &ctl)?))).collect()
}
FeatureKind::Pipe { path_sketch, path, diameter, wall, .. } => {
let ps =
st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?;
let mapped = path_in_frame(doc, ps, f.component)?;
let ps = mapped.as_ref();
let r = val(vals, diameter, Kind::Length)? / 2.0;
if !(r > 1e-6) {
return Err(DocError::Invalid("pipe diameter must be positive".into()));
}
if let Some(along) = path_points(ps, path, Vec3::new(f64::NAN, f64::NAN, f64::NAN))? {
let pts = along.points();
let (Some(a), Some(b)) = (pts.first().copied(), pts.get(1).copied()) else { return Err(DocError::Invalid("empty path".into())) };
let t = (b - a).normalized().ok_or_else(|| DocError::Invalid("path direction".into()))?;
let plane = Plane::from_normal(a, t).ok_or_else(|| DocError::Invalid("pipe profile plane".into()))?;
return Ok(unnamed(vec![kernel::sweep_point_path_with(
&plane,
&pipe_region(vals, r, wall)?,
&along,
&kernel::SweepControl::default(),
)?]));
}
let segs = path_segments(ps, path, Vec3::new(f64::NAN, f64::NAN, f64::NAN))?;
let first = segs.first().ok_or_else(|| DocError::Invalid("empty path".into()))?;
let start = first.start();
let (t, _) = first.tangents().ok_or_else(|| DocError::Invalid("path direction".into()))?;
let plane = Plane::from_normal(start, t).ok_or_else(|| DocError::Invalid("pipe profile plane".into()))?;
Ok(unnamed(vec![kernel::sweep(&plane, &pipe_region(vals, r, wall)?, &segs)?]))
}
FeatureKind::Box { corner, length, width, height, .. } => {
let s = Vec3::new(val(vals, length, Kind::Length)?, val(vals, width, Kind::Length)?, val(vals, height, Kind::Length)?);
let corner = point(vals, corner)?;
Ok(vec![crate::lineage::box_tool(kernel::box_solid(corner, corner + s)?)])
}
FeatureKind::Cylinder { base, axis, radius, height, .. } => Ok(vec![crate::lineage::cylinder_tool(kernel::cylinder(
cylinder_base(vals, st, f, base, axis.0)?,
axis.0,
val(vals, radius, Kind::Length)?,
val(vals, height, Kind::Length)?,
)?)]),
FeatureKind::Sphere { center, radius, .. } => Ok(unnamed(vec![kernel::sphere(point(vals, center)?, val(vals, radius, Kind::Length)?)?])),
FeatureKind::Torus { center, major, minor, .. } => {
Ok(unnamed(vec![kernel::torus(point(vals, center)?, val(vals, major, Kind::Length)?, val(vals, minor, Kind::Length)?)?]))
}
FeatureKind::Cone { base, axis, radius, top_radius, height, .. } => Ok(unnamed(vec![more::cone(
point(vals, base)?,
axis.0,
val(vals, radius, Kind::Length)?,
val(vals, top_radius, Kind::Length)?,
val(vals, height, Kind::Length)?,
)?])),
FeatureKind::Hole { .. } => Ok(hole_feature_tools(vals, st, f)?.into_iter().map(|(tool, _)| tool).collect()),
_ => Err(DocError::Invalid(format!("{} cannot be patterned or mirrored yet", f.name))),
}
}
/// A chain of sketch curves as 3D path segments, starting at the end nearest `start`.
/// A sweep's options from its stored orientation, its twist and end scale expressions (none: no
/// twist, scale 1) and its guide rails as polylines (see [`rail_polylines`]). Out-of-range values
/// are refused by the kernel.
pub(crate) fn sweep_control(
vals: &BTreeMap<String, Value>,
orientation: &crate::SweepOrientation,
twist: &Option<crate::Expr>,
scale: &Option<crate::Expr>,
rails: Vec<Vec<Vec3>>,
rail_fit: crate::RailFit,
) -> Result<kernel::SweepControl> {
let orientation = match *orientation {
crate::SweepOrientation::Perpendicular => kernel::SweepOrientation::Perpendicular,
crate::SweepOrientation::Parallel => kernel::SweepOrientation::Parallel,
crate::SweepOrientation::Direction(d) => kernel::SweepOrientation::Direction(d.0),
};
let twist = match twist {
Some(t) => val(vals, t, Kind::Angle)?,
None => 0.0,
};
let scale = match scale {
Some(k) => val(vals, k, Kind::Unitless)?,
None => 1.0,
};
let ctl = kernel::SweepControl { orientation, twist, scale, rails, rail_fit: kernel_rail_fit(rail_fit) };
ctl.check()?;
Ok(ctl)
}
/// How guide rails reshape a sweep's profile or a loft's sections, for the kernel.
pub(crate) fn kernel_rail_fit(fit: crate::RailFit) -> kernel::RailFit {
match fit {
crate::RailFit::Scale => kernel::RailFit::Scale,
crate::RailFit::Stretch => kernel::RailFit::Stretch,
}
}
/// A sweep's or a loft's guide rails as polylines in the feature's frame, each a chain of its sketch's curves
/// (planar or 3D) from the end nearest `start` (the start of the path, the loft's first section).
pub(crate) fn rail_polylines(doc: &Document, st: &ModelState, rails: &[crate::SweepRail], consumer: u64, start: Vec3) -> Result<Vec<Vec<Vec3>>> {
if rails.len() > 2 {
return Err(DocError::Invalid("a sweep or a loft takes one or two guide rails".into()));
}
rails
.iter()
.map(|rail| {
if rail.curves.is_empty() {
return Err(DocError::Invalid("a guide rail needs its curves".into()));
}
let rs = st
.sketch(rail.sketch.0)
.ok_or_else(|| DocError::Unknown(format!("rail sketch {} (it must come earlier in the timeline)", rail.sketch)))?;
let mapped = path_in_frame(doc, rs, consumer)?;
let rs = mapped.as_ref();
match path_points(rs, &rail.curves, start)? {
Some(path) => Ok(path.points()),
None => Ok(kernel::path_polyline(&path_segments(rs, &rail.curves, start)?)?),
}
})
.collect()
}
/// A pipe's section: a circle of radius `r`, hollow when it has a wall.
fn pipe_region(vals: &BTreeMap<String, Value>, r: f64, wall: &Option<crate::Expr>) -> Result<Region2> {
let holes = match wall {
Some(w) => {
let wt = val(vals, w, Kind::Length)?;
if !(wt > 0.0 && wt < r) {
return Err(DocError::Invalid("the wall must be thinner than the radius".into()));
}
vec![solidcraft_geom::Loop2::circle(Vec2::ZERO, r - wt).reversed()]
}
None => Vec::new(),
};
Ok(Region2 { outer: solidcraft_geom::Loop2::circle(Vec2::ZERO, r), holes })
}
pub fn map_wire(wire: &mut solidcraft_sketch::Wire, matrix: &Mat) {
wire.map(|p| crate::apply_point(matrix, p), |v| crate::apply_vector(matrix, v));
}
/// A feature's sketch as its component sees it: a sketch of another component that is placed
/// differently is moved through both placements (as `state_in_frame` does for sketches on faces),
/// so the tool is built where the sketch is shown. The sketch itself when they share a frame.
fn sketch_in_feature_frame(doc: &Document, sketch: &SolvedSketch, consumer: u64) -> Result<SolvedSketch> {
let owner = doc.feature(sketch.feature).map(|feature| feature.component).unwrap_or(0);
if owner == consumer || doc.occurrences.is_empty() {
return Ok(sketch.clone());
}
profile_in_frame(doc, sketch, consumer)
}
fn profile_in_frame(doc: &Document, sketch: &SolvedSketch, consumer: u64) -> Result<SolvedSketch> {
let owner = doc.feature(sketch.feature).map(|feature| feature.component).unwrap_or(0);
let inverse =
crate::mat_inverse(&doc.component_transform(consumer)).ok_or_else(|| DocError::Invalid("profile consumer frame is invalid".into()))?;
let relative = crate::mat_mul(&inverse, &doc.component_transform(owner));
let mut mapped = sketch.clone();
mapped.plane = Plane::new(
crate::apply_point(&relative, sketch.plane.origin),
crate::apply_vector(&relative, sketch.plane.x),
crate::apply_vector(&relative, sketch.plane.y),
)
.ok_or_else(|| DocError::Invalid("profile sketch frame is invalid".into()))?;
Ok(mapped)
}
/// Stored wire coordinates are converted once into the feature consumer frame.
fn path_in_frame<'a>(doc: &Document, sketch: &'a SolvedSketch, consumer: u64) -> Result<std::borrow::Cow<'a, SolvedSketch>> {
use std::borrow::Cow;
if sketch.sketch.wires.is_empty() {
return Ok(Cow::Borrowed(sketch));
}
let owner = doc.feature(sketch.feature).map(|f| f.component).unwrap_or(0);
let inverse =
crate::mat_inverse(&doc.component_transform(consumer)).ok_or_else(|| DocError::Invalid("path consumer frame is not invertible".into()))?;
let relative = crate::mat_mul(&inverse, &doc.component_transform(owner));
let mut mapped = sketch.clone();
mapped.plane = Plane::new(
crate::apply_point(&relative, sketch.plane.origin),
crate::apply_vector(&relative, sketch.plane.x),
crate::apply_vector(&relative, sketch.plane.y),
)
.ok_or_else(|| DocError::Invalid("path sketch frame is invalid".into()))?;
for wire in &mut mapped.sketch.wires {
let matrix = if wire.space == solidcraft_sketch::WireSpace::Component { &relative } else { &inverse };
map_wire(wire, matrix);
}
Ok(Cow::Owned(mapped))
}
/// A path that uses 3D sketch curves (wires), as one chain of pieces from the end nearest
/// `start` (no start: the first curve runs toward the second): each drawn 3D spline as its fit
/// points (the kernel has its exact curve), each curve held exactly (a planar sketch curve, a
/// linked curve with [`solidcraft_sketch::Wire::exact`]) as its path segments, and a linked
/// curve known only as points as those points. `None` when the path is all planar curves.
fn path_points(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result<Option<kernel::PointPath>> {
if !ids.iter().any(|id| ps.sketch.wire_index(id).is_some()) {
return Ok(None);
}
if ids.len() > 1000 {
return Err(DocError::Invalid("the path needs 1…1000 curves".into()));
}
let mut pieces: Vec<kernel::PathPiece> = Vec::with_capacity(ids.len());
for id in ids {
if let Some(wi) = ps.sketch.wire_index(id) {
pieces.push(match ps.sketch.wires.get(wi) {
// A drawn 3D arc is its circle, from its start counter-clockwise about its normal
// (its three fit points define it; a spline through them is not the arc).
Some(solidcraft_sketch::Wire { arc: Some(arc), .. }) => {
let x = (arc.start - arc.center).normalized().ok_or_else(|| DocError::Invalid("a 3D arc of no radius".into()))?;
let y = arc.normal.cross(x);
let frame = solidcraft_geom::brep::Frame { origin: arc.center.into(), x_axis: x.into(), y_axis: y.into() };
let circle = solidcraft_geom::brep::Curve::Circle { frame, radius: arc.radius };
kernel::PathPiece::Segs(kernel::curve_path(&circle, [0.0, solidcraft_sketch::arc_sweep(arc)])?)
}
Some(w) if w.fit.len() >= 3 => kernel::PathPiece::Spline { fit: w.fit.clone(), reversed: false },
Some(w) if !w.exact.is_empty() => {
let mut segs = Vec::new();
for c in &w.exact {
segs.extend(kernel::curve_path(&c.curve, c.interval)?);
}
kernel::PathPiece::Segs(segs)
}
w => kernel::PathPiece::Polyline(w.map(|w| w.pts.clone()).unwrap_or_default()),
});
} else {
let ci = ps.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("path curve `{id}`")))?;
let segs = ps.sketch.exact_segs(ci).unwrap_or_else(|| ps.sketch.segs(ci));
pieces.push(kernel::PathPiece::Segs(segs.iter().map(|s| kernel::PathSeg::of_sketch(&ps.plane, s)).collect()));
}
}
// Pieces meet within the sketch's tolerance (projected curves are only that close).
let tol = 1e-3;
let ends = |p: &kernel::PathPiece| {
let pts = p.points();
(pts.first().copied().unwrap_or_default(), pts.last().copied().unwrap_or_default())
};
let mut pieces = pieces.into_iter();
let Some(first) = pieces.next() else { return Ok(None) };
let rest: Vec<kernel::PathPiece> = pieces.collect();
let (a, b) = ends(&first);
let flip = if start.is_finite() {
b.dist(start) < a.dist(start)
} else {
rest.first().is_some_and(|n| {
let (na, nb) = ends(n);
na.dist(a).min(nb.dist(a)) < na.dist(b).min(nb.dist(b))
})
};
let first = if flip { first.reversed() } else { first };
let mut last = ends(&first).1;
let mut chain = vec![first];
for p in rest {
let (a, b) = ends(&p);
let (p, a, b) = if b.dist(last) < a.dist(last) { (p.reversed(), b, a) } else { (p, a, b) };
if a.dist(last) > tol {
return Err(DocError::Invalid("the path curves are not connected end to end".into()));
}
chain.push(p);
last = b;
}
Ok(Some(kernel::PointPath { pieces: chain }))
}
fn path_segments(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result<Vec<kernel::PathSeg>> {
path_segments_at(ps, ids, start, None)
}
/// [`path_segments`] for a profile in `profile`: a closed path is followed from where the
/// profile's plane crosses it nearest `start`, the curve there split in two, when that is not
/// already where the chain starts (#3345). Swept from anywhere else, the profile would stand
/// off the path by the distance between the two.
pub(crate) fn path_segments_at(ps: &SolvedSketch, ids: &[String], start: Vec3, profile: Option<&Plane>) -> Result<Vec<kernel::PathSeg>> {
if ids.is_empty() || ids.len() > 1000 {
return Err(DocError::Invalid("the path needs 1…1000 curves".into()));
}
// A path through 3D sketch curves is followed as a 3D polyline.
if let Some(path) = path_points(ps, ids, start)? {
return Ok(path.points().windows(2).map(|w| kernel::PathSeg::Line { a: w[0], b: w[1] }).collect());
}
// Each curve as its exact pieces (Béziers, conics) where it has them, in its own direction
// of travel. A curve is turned round whole: its pieces stay one run.
let mut curves: Vec<Vec<solidcraft_geom::Seg2>> = Vec::with_capacity(ids.len());
for id in ids {
let ci = ps.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("path curve `{id}`")))?;
curves.push(ps.sketch.exact_segs(ci).unwrap_or_else(|| ps.sketch.segs(ci)));
}
curves.retain(|c| !c.is_empty());
let ends = |c: &[solidcraft_geom::Seg2]| c.first().zip(c.last()).map(|(f, l)| (f.start(), l.end()));
let reversed = |c: Vec<solidcraft_geom::Seg2>| c.into_iter().rev().map(|s| s.reversed()).collect::<Vec<_>>();
// Where two curves meet: one tolerance for telling which ends touch and for the joint.
const JOINT: f64 = 1e-5;
// Orient the first curve: it runs toward the second where it meets it at one end only;
// otherwise (one curve, or a second meeting it at both ends) from the end nearest `start`
// (no start given, a pipe: as drawn).
let w = |p: Vec2| ps.plane.to_world(p);
if let Some((a, b)) = curves.first().and_then(|c| ends(c)) {
let touches = |p: Vec2| curves.get(1).and_then(|n| ends(n)).is_some_and(|(na, nb)| na.dist(p) <= JOINT || nb.dist(p) <= JOINT);
let flip = match (touches(a), touches(b)) {
(true, false) => true,
(false, true) => false,
_ => start.is_finite() && w(b).dist(start) < w(a).dist(start),
};
if flip && let Some(first) = curves.first_mut() {
*first = reversed(std::mem::take(first));
}
}
// Each next curve starts where the previous one ended.
let mut segs: Vec<solidcraft_geom::Seg2> = Vec::new();
for curve in curves {
let (Some(prev_end), Some((a, b))) = (segs.last().map(solidcraft_geom::Seg2::end), ends(&curve)) else {
segs.extend(curve);
continue;
};
let curve = if b.dist(prev_end) < a.dist(prev_end) { reversed(curve) } else { curve };
segs.extend(curve);
}
if segs.windows(2).any(|pair| pair[1].start().dist(pair[0].end()) > JOINT) {
return Err(DocError::Invalid("the path curves are not connected end to end".into()));
}
if let Some(profile) = profile {
segs = from_profile_on_closed_path(segs, &ps.plane, profile, start);
}
Ok(segs.iter().map(|s| kernel::PathSeg::of_sketch(&ps.plane, s)).collect())
}
/// A closed chain `segs` (in the plane `path`) begun where `profile`'s plane crosses it nearest
/// `start`: the curve there split in two, its second part first and its first part last (or the
/// chain begun at the joint there). Unchanged when the chain is open, already starts on the
/// profile's plane, or its point nearest `start` is off that plane.
fn from_profile_on_closed_path(segs: Vec<solidcraft_geom::Seg2>, path: &Plane, profile: &Plane, start: Vec3) -> Vec<solidcraft_geom::Seg2> {
let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return segs };
let size: f64 = segs.iter().map(solidcraft_geom::Seg2::length).sum();
let on_plane = |p: Vec2| profile.height(path.to_world(p)).abs() <= (size * 1e-9).max(1e-9);
if !start.is_finite() || !(size > 0.0 && size.is_finite()) || last.end().dist(first.start()) > 1e-5 || on_plane(first.start()) {
return segs;
}
let local = path.to_local(start);
let Some((k, t, q)) = segs
.iter()
.enumerate()
.map(|(k, s)| {
let t = s.closest_param(local);
(k, t, path.to_world(s.point_at(t)))
})
.min_by(|a, b| a.2.dist(start).total_cmp(&b.2.dist(start)))
else {
return segs;
};
if profile.height(q).abs() > (size * 1e-6).max(1e-6) {
return segs;
}
let Some(seg) = segs.get(k).copied() else { return segs };
let n = segs.len();
let from = |k: usize| segs.iter().cycle().skip(k % n).take(n).copied().collect::<Vec<_>>();
let at = |p: Vec2| path.to_world(p).dist(q) <= 1e-6;
if at(seg.start()) {
return from(k);
}
if at(seg.end()) {
return from(k + 1);
}
let (before, after) = seg.split_at(t);
let mut out = Vec::with_capacity(n + 1);
out.push(after);
out.extend(from(k + 1).into_iter().take(n - 1));
out.push(before);
out
}
/// Where an extrude of distance `d` starts and ends along the sketch normal, before any start
/// offset: one side, the other, both (symmetric), or a second distance on the other side.
///
/// A second distance (`distance2`) goes the other way from the first side, wherever that went:
/// against the normal for `direction: negative` (#2700), and back along it when a negative
/// distance or a To Object below the sketch sends the first side down.
pub(crate) fn extent_sides(vals: &BTreeMap<String, Value>, extent: &crate::Extent, d: f64, direction: crate::Direction) -> Result<(f64, f64)> {
Ok(match (&extent.distance2, direction) {
(Some(d2), _) => {
let first = if direction == crate::Direction::Negative { -d } else { d };
let d2 = val(vals, d2, Kind::Length)?;
(if first < 0.0 { d2 } else { -d2 }, first)
}
(None, crate::Direction::Positive) => (0.0, d),
(None, crate::Direction::Negative) => (-d, 0.0),
(None, crate::Direction::Symmetric) => {
// Through All is a reach computed from target bodies, not an entered total.
let half = if extent.through_all { d } else { extent.convention.symmetric_half_distance(d) };
(-half, half)
}
})
}
/// Operation and targets of a feature that makes tools.
fn feature_op(f: &Feature) -> (Operation, Vec<String>) {
match &f.kind {
FeatureKind::Extrude { operation, targets, .. } | FeatureKind::Revolve { operation, targets, .. } => (*operation, crate::plain(targets)),
FeatureKind::Box { operation, .. }
| FeatureKind::Cylinder { operation, .. }
| FeatureKind::Sphere { operation, .. }
| FeatureKind::Torus { operation, .. }
| FeatureKind::Cone { operation, .. } => (*operation, Vec::new()),
FeatureKind::Hole { .. } => (Operation::Cut, Vec::new()),
FeatureKind::Pipe { operation, targets, .. } => (*operation, crate::plain(targets)),
FeatureKind::Loft { operation, targets, .. } | FeatureKind::Sweep { operation, targets, .. } => (*operation, crate::plain(targets)),
FeatureKind::Coil { operation, targets, .. } => (*operation, crate::plain(targets)),
FeatureKind::Rib { .. } => (Operation::Join, Vec::new()),
_ => (Operation::NewBody, Vec::new()),
}
}
type Mat = [[f64; 4]; 4];
fn translation(t: Vec3) -> Mat {
[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [t.x, t.y, t.z, 1.0]]
}
/// Rotation by `ang` about the line through `o` with direction `a` (column-major).
fn rotation(o: Vec3, a: Vec3, ang: f64) -> Mat {
let a = a.normalized().unwrap_or(Vec3::Z);
let (c, s) = (ang.cos(), ang.sin());
let t = 1.0 - c;
let r = [
[t * a.x * a.x + c, t * a.x * a.y + s * a.z, t * a.x * a.z - s * a.y],
[t * a.x * a.y - s * a.z, t * a.y * a.y + c, t * a.y * a.z + s * a.x],
[t * a.x * a.z + s * a.y, t * a.y * a.z - s * a.x, t * a.z * a.z + c],
];
// p' = R (p - o) + o
let ro = Vec3::new(
r[0][0] * o.x + r[1][0] * o.y + r[2][0] * o.z,
r[0][1] * o.x + r[1][1] * o.y + r[2][1] * o.z,
r[0][2] * o.x + r[1][2] * o.y + r[2][2] * o.z,
);
let tr = o - ro;
[[r[0][0], r[0][1], r[0][2], 0.0], [r[1][0], r[1][1], r[1][2], 0.0], [r[2][0], r[2][1], r[2][2], 0.0], [tr.x, tr.y, tr.z, 1.0]]
}
/// A copy of a sheet metal body is sheet metal too: its sheet model goes with it, moved, or
/// mirrored into the opposite hand ([`crate::sheet::SheetBody::copied`]), so the copy has its
/// own flat pattern, DXF and bend table. A copy by any other transform stays a plain solid.
fn copy_sheet(st: &mut ModelState, from: &str, to: &str, m: &crate::Mat) {
let Some(sheet) = st.sheets.iter().find(|s| s.body == from).and_then(|s| s.copied(to, m)) else { return };
st.sheets.retain(|s| s.body != to);
st.sheets.push(sheet);
}
/// Reflection in a plane (column-major).
fn mirror_matrix(pl: &Plane) -> Mat {
let n = pl.normal();
let d = pl.origin.dot(n);
let m = |i: usize, j: usize| {
let (ni, nj) = ([n.x, n.y, n.z][i], [n.x, n.y, n.z][j]);
(if i == j { 1.0 } else { 0.0 }) - 2.0 * ni * nj
};
// p' = p - 2 (p·n - d) n
[
[m(0, 0), m(0, 1), m(0, 2), 0.0],
[m(1, 0), m(1, 1), m(1, 2), 0.0],
[m(2, 0), m(2, 1), m(2, 2), 0.0],
[2.0 * d * n.x, 2.0 * d * n.y, 2.0 * d * n.z, 1.0],
]
}
const MAX_INSTANCES: usize = 1000;
/// Where a mirrored body was picked and where its copy goes: the component the copy joins and
/// that component's world frame, and the frame the body's own geometry is in where it was picked
/// (its placement `path`, with its offset). `None` in older designs, which saved no placement and
/// mirror the body's own geometry.
fn mirrored_placement(doc: &Document, mb: &ModelBody, path: Option<&[u64]>) -> Result<Option<(u64, Mat, Mat)>> {
let Some(path) = path else { return Ok(None) };
let lost = || DocError::Invalid(format!("the placement `{}` was mirrored at no longer exists", mb.name));
// A stale or edited path that leads to another component no longer shows the body.
let (at, _) = doc.path_placement(path).ok_or_else(lost)?;
if !placement_shows(doc, mb, at) {
return Err(lost());
}
let (component, frame, picked) = mirror_copy_frame(doc, path).ok_or_else(lost)?;
let source = doc.model_body_offset(mb).map(|offset| crate::mat_mul(&picked, offset)).unwrap_or(picked);
Ok(Some((component, frame, source)))
}
/// Whether a placement of component `at` shows body `mb`: `at` is the body's component. That is
/// the evaluated body's own where a transfer recorded it, else the component its name is recorded
/// in (an import's bodies) or its feature's. Inserting the same file again reuses the body names
/// and points them at the new insert's components: when the recorded component lies outside the
/// components the body's own feature made, the name is another body's, and the placement only has
/// to lie inside the components the body's feature made.
fn placement_shows(doc: &Document, mb: &ModelBody, at: u64) -> bool {
let owner = doc.model_body_component(mb);
if owner == at {
return true;
}
if mb.transferred || mb.source_name.is_some() {
return false;
}
let made_in = doc.feature(mb.feature).map(|f| f.component).unwrap_or(0);
!component_within(doc, owner, made_in) && component_within(doc, at, made_in)
}
/// Whether component `c` is `ancestor` or lies inside it (every component lies in the root).
fn component_within(doc: &Document, mut c: u64, ancestor: u64) -> bool {
for _ in 0..=doc.components.len() {
if c == ancestor || ancestor == 0 {
return true;
}
match doc.components.iter().find(|x| x.id == c) {
Some(x) if c != 0 => c = x.parent,
_ => return false,
}
}
false
}
/// For a body mirrored at placement `path` (which, not the body's name, says where it is: a later
/// insert can reuse the name): the component its copy joins, that component's world frame, and
/// the placement's world frame. The copy joins the body's component, or, when that component is
/// placed more than once (a copy there would show at every placement), the innermost component
/// around it that is placed once.
fn mirror_copy_frame(doc: &Document, path: &[u64]) -> Option<(u64, Mat, Mat)> {
let (_, picked) = doc.path_placement(path)?;
let placed_once = |id: &u64| {
let component = doc.occurrences.iter().find(|o| o.id == *id).map(|o| o.component);
doc.occurrences.iter().filter(|o| Some(o.component) == component).count() == 1
};
let once = path.iter().take_while(|id| placed_once(id)).count();
let (component, frame) = doc.path_placement(path.get(..once)?)?;
Some((component, frame, picked))
}
/// The placements (column-major matrices) of a pattern's copies, the original excluded.
pub fn pattern_matrices(doc: &Document, st: &ModelState, p: &crate::PatternKind) -> Result<Vec<[[f64; 4]; 4]>> {
let (vals, _) = doc.param_values();
pattern_transforms(doc, &vals, st, 0, p)
}
fn pattern_transforms(doc: &Document, vals: &BTreeMap<String, Value>, st: &ModelState, component: u64, p: &crate::PatternKind) -> Result<Vec<Mat>> {
let count = |e: &str| -> Result<usize> {
let n = expr::eval_count(e, vals)?;
if !(1.0..=MAX_INSTANCES as f64).contains(&n) {
return Err(DocError::Invalid(format!("pattern count must be 1…{MAX_INSTANCES}")));
}
Ok(n as usize)
};
let mut out = Vec::new();
match p {
crate::PatternKind::Rectangular { dir1, count1, spacing1, dir2, count2, spacing2, alignment, alignment2, reversed, reversed2 } => {
let (n1, s1) = (count(count1)?, val(vals, spacing1, Kind::Length)?);
let d1 = dir1.normalized().ok_or_else(|| DocError::Invalid("pattern direction".into()))?;
let (n2, s2, d2) = match (dir2, count2, spacing2) {
(Some(d), Some(c), Some(sp)) => {
(count(c)?, val(vals, sp, Kind::Length)?, d.normalized().ok_or_else(|| DocError::Invalid("pattern direction".into()))?)
}
_ => (1, 0.0, Vec3::Y),
};
if n1 * n2 > MAX_INSTANCES {
return Err(DocError::Invalid("too many pattern instances".into()));
}
for i in 0..n1 {
for j in 0..n2 {
if i == 0 && j == 0 {
continue;
}
out.push(translation(d1 * (s1 * alignment.multiplier(i, *reversed)) + d2 * (s2 * alignment2.multiplier(j, *reversed2))));
}
}
}
crate::PatternKind::Path { path_sketch, path, count: c, spacing, extent, flip, orient } => {
let n = count(c)?;
let d = val(vals, spacing, Kind::Length)?;
let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("path sketch {path_sketch}")))?;
let mapped = path_in_frame(doc, ps, component)?;
let ps = mapped.as_ref();
// Free-form curves measured along their polylines.
let mut segs = kernel::PathSeg::flattened(&path_segments(ps, path, Vec3::new(f64::NAN, f64::NAN, f64::NAN))?);
if *flip {
segs = segs.iter().rev().map(reverse_seg).collect();
}
let total: f64 = segs.iter().map(seg_len).sum();
let step = if *extent { if n > 1 { d / (n - 1) as f64 } else { 0.0 } } else { d };
if (step * (n - 1) as f64).abs() > total * (1.0 + 1e-5) + 1e-6 {
return Err(DocError::Invalid(format!("the instances run past the end of the path ({total:.3} mm long)")));
}
let normal = ps.plane.normal();
let (p0, t0) = path_at(&segs, 0.0);
for i in 1..n {
let (pk, tk) = path_at(&segs, step * i as f64);
let mut m = if *orient {
// Signed turn of the tangent about the sketch normal.
let ang = t0.cross(tk).dot(normal).atan2(t0.dot(tk));
rotation(p0, normal, ang)
} else {
translation(Vec3::ZERO)
};
let dv = pk - p0;
m[3][0] += dv.x;
m[3][1] += dv.y;
m[3][2] += dv.z;
out.push(m);
}
}
crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed, axis_ref, axis_feature } => {
// On an edge or round face: about it as it is now; on a construction axis: where it is;
// else through its origin, whose expressions follow the parameters (#10852).
let (origin, axis) = match (axis_ref, axis_feature) {
(Some(g), _) => crate::construct::model_axis(&*construction_state(doc, st, component)?, g)?,
(None, Some(name)) => construction_axis_in(Some(doc), st, name, component)?,
(None, None) => {
let [x, y, z] = origin;
let o = Vec3::new(val(vals, x, Kind::Length)?, val(vals, y, Kind::Length)?, val(vals, z, Kind::Length)?);
if ![o.x, o.y, o.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) {
return Err(DocError::Invalid("the pattern's axis origin is out of range".into()));
}
(o, axis.0)
}
};
let n = count(c)?;
let total = val(vals, angle, Kind::Angle)?;
let full = (total.abs() - std::f64::consts::TAU).abs() < 1e-9;
let step = if full {
total / n as f64
} else if n > 1 {
total / (n - 1) as f64
} else {
0.0
};
for i in 1..n {
out.push(rotation(origin, axis, step * alignment.multiplier(i, *reversed)));
}
}
}
Ok(out)
}
fn seg_len(s: &kernel::PathSeg) -> f64 {
match *s {
kernel::PathSeg::Line { a, b } => (b - a).len(),
kernel::PathSeg::Arc { a, center, angle, .. } => (a - center).len() * angle.abs(),
// Patterns flatten their paths; a curve left is measured along its chord.
kernel::PathSeg::Curve { .. } | kernel::PathSeg::Bezier(_) => s.start().dist(s.end()),
}
}
/// Rotate `v` about the unit axis `k` by `ang` (Rodrigues).
fn rotate_vec(v: Vec3, k: Vec3, ang: f64) -> Vec3 {
v * ang.cos() + k.cross(v) * ang.sin() + k * (k.dot(v) * (1.0 - ang.cos()))
}
/// Point and unit tangent `t` mm along a segment.
fn seg_at(s: &kernel::PathSeg, t: f64) -> (Vec3, Vec3) {
match *s {
kernel::PathSeg::Line { a, b } => {
let d = (b - a).normalized().unwrap_or(Vec3::X);
(a + d * t, d)
}
kernel::PathSeg::Arc { a, center, axis, angle } => {
let k = axis.normalized().unwrap_or(Vec3::Z);
let r = (a - center).len().max(1e-12);
// Sweeps turn right-handed about `axis` (angles are positive).
let s = if angle < 0.0 { -1.0 } else { 1.0 };
let v = rotate_vec(a - center, k, s * t / r);
(center + v, k.cross(v).normalized().unwrap_or(Vec3::X) * s)
}
kernel::PathSeg::Curve { .. } | kernel::PathSeg::Bezier(_) => {
let (a, b) = (s.start(), s.end());
let d = (b - a).normalized().unwrap_or(Vec3::X);
(a + d * t, d)
}
}
}
fn reverse_seg(s: &kernel::PathSeg) -> kernel::PathSeg {
s.reversed()
}
/// Point and tangent at arc length `d` along a chain (clamped to its ends).
fn path_at(segs: &[kernel::PathSeg], d: f64) -> (Vec3, Vec3) {
let mut left = d.max(0.0);
for (i, s) in segs.iter().enumerate() {
let l = seg_len(s);
if left <= l + 1e-9 || i + 1 == segs.len() {
return seg_at(s, left.min(l));
}
left -= l;
}
(Vec3::ZERO, Vec3::X)
}
/// Whether a copy has no material to cut in any of its eligible targets.
/// The bodies a hole cuts: those its feature names, else its component's and its own (as
/// `apply_traced` picks a cut's targets).
fn hole_targets<'a>(st: &'a ModelState, f: &Feature) -> Vec<&'a ModelBody> {
let all = f.participants.len() == 1 && f.participants.first().is_some_and(|t| t == "*");
st.bodies
.iter()
.filter(|b| all || if f.participants.is_empty() { b.component == f.component || b.feature == f.id } else { f.participants.contains(&b.name) })
.collect()
}
/// Whether hole tool `tool` is clear of every body the hole cuts, by their exact boxes (#10701).
/// Boxes only: a probe boolean for every hole of a large hole pattern would double its work. A
/// body whose exact box is unknown, or one of another component (in another frame), leaves the
/// hole not known to miss.
fn hole_misses(st: &ModelState, f: &Feature, tool: &Body) -> bool {
let targets = hole_targets(st, f);
let bounds = tool.outline_bounds();
if targets.is_empty()
|| targets.iter().any(|b| b.component != f.component)
|| bounds.is_empty()
|| !bounds.min.is_finite()
|| !bounds.max.is_finite()
{
return false;
}
let tool_box = Some(bounds.inflated(1e-6));
targets.iter().all(|b| more::boxes_apart(&tool_box, &b.body.exact_bounds().ok()))
}
fn copy_misses(st: &ModelState, f: &Feature, targets: &[String], tools: &[Traced]) -> bool {
let targets = if targets.is_empty() { &f.participants } else { targets };
let all = targets.len() == 1 && targets.first().is_some_and(|t| t == "*");
st.bodies
.iter()
.filter(|b| all || if targets.is_empty() { b.component == f.component || b.feature == f.id } else { targets.contains(&b.name) })
.all(|b| {
tools.iter().all(|t| {
// An inconclusive probe is not a miss: it must not reject an otherwise valid cut.
matches!(kernel::boolean(&b.body, &t.body, BoolOp::Intersect), Ok(None))
})
})
}
/// The deepest a pattern or mirror reaches through patterns and mirrors of features (#395).
const MAX_NESTING: usize = 8;
/// The feature a pattern or mirror names as a source. Seeds are keyed by id (#1134): a
/// reference that names no feature dangles, as a missing name did before.
fn source_feature(doc: &Document, id: FeatureId) -> Result<&Feature> {
doc.feature(id.0).ok_or_else(|| DocError::Unknown(format!("feature `{id}`")))
}
/// How a source feature shows in a warning: its name, or its id when it names no feature.
fn source_label(doc: &Document, id: FeatureId) -> String {
doc.feature(id.0).map(|f| f.name.clone()).unwrap_or_else(|| id.to_string())
}
/// What a pattern or mirror of features copies, when it is the source of another one (#395): its
/// own sources, and the transforms of its copies. `None` for any other feature, and for a pattern
/// or mirror of bodies (its copies are bodies, which a pattern or mirror of features can't take).
fn copied_features(doc: &Document, vals: &BTreeMap<String, Value>, st: &ModelState, src: &Feature) -> Result<Option<(Vec<FeatureId>, Vec<Mat>)>> {
match &src.kind {
FeatureKind::Pattern { features, pattern, bodies } if bodies.is_empty() => {
Ok(Some((features.clone(), pattern_transforms(doc, vals, st, src.component, pattern)?)))
}
FeatureKind::Mirror { features, plane, bodies, .. } if bodies.is_empty() => {
let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?;
Ok(Some((features.clone(), vec![mirror_matrix(&pl)])))
}
_ => Ok(None),
}
}
/// The copies a pattern or mirror of `features` at `mats` makes, source by source: the source
/// feature, the transforms of its copies, and the instance number of its first copy less one.
/// A source that is itself a pattern or mirror of features (#395) stands for what it copied: its
/// own sources, at each of its transforms moved by each of ours. Those copies are numbered after
/// `mats`' own (which keep the numbers they always had), each nested source in a block of its
/// own, so no two copies of one feature share an instance. Suppressed sources copy nothing.
/// `f` with each face point moved onto its named face (on the body the feature names, when it
/// names one and the face is there) in `state`, and notes on how the faces were found. `None`
/// when `f` names no face; an error when a name no longer finds its face (the feature asks for
/// it to be picked again), or when the frame the faces are looked up in cannot be made.
fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Result<Option<(Feature, Vec<String>)>> {
// Cylindrical emboss resolves its named face in the selected body's frame
// and certifies an analytic anchor; mesh projection here would undo that.
let explicit_emboss = matches!(&f.kind, FeatureKind::Emboss { face: Some(_), .. });
if explicit_emboss || !f.face_names.iter().any(|n| !n.is_empty()) {
return Ok(None);
}
let mut g = f.clone();
let mut notes = Vec::new();
// A hole's position is a place on its face, not a pick of the face: it follows
// the face along the hole's axis and never slides sideways to the face's nearest
// point when the face no longer reaches it.
let hole_axis = match &f.kind {
FeatureKind::Hole { direction, points: None | Some(crate::SketchPoints { single: true, .. }), .. } => direction.normalized(),
_ => None,
};
let fst = face_point_state(doc, state, &f.kind, f.component)?;
for (k, (p, n)) in g.kind.face_points_mut().into_iter().zip(&f.face_names).enumerate() {
if n.is_empty() {
continue;
}
match crate::name_lookup::locate_face_on_body(&fst, f.kind.face_body(), n, *p) {
Some(hit) => {
if let Some(note) = hit.note(n) {
notes.push(note);
}
match (k, hole_axis) {
(0, Some(axis)) => match hit.along(&fst, *p, axis) {
Some(q) => *p = q,
// The place still lies on the face (the axis may run along it).
None if hit.on_point => {}
None => notes.push(format!(
"the hole's position [{}, {}, {}] is no longer on face `{n}`: it stays where it was placed",
p.x, p.y, p.z
)),
},
_ => *p = hit.pick_point(&fst, *p),
}
}
None => return Err(DocError::reselect(n.as_str())),
}
}
Ok(Some((g, notes)))
}
fn copy_plan<'a>(
doc: &'a Document,
vals: &BTreeMap<String, Value>,
st: &ModelState,
features: &[FeatureId],
mats: &[Mat],
) -> Result<Vec<(&'a Feature, Vec<Mat>, usize)>> {
#[allow(clippy::too_many_arguments)]
fn walk<'a>(
doc: &'a Document,
vals: &BTreeMap<String, Value>,
st: &ModelState,
features: &[FeatureId],
mats: &[Mat],
first: usize,
next: &mut usize,
depth: usize,
out: &mut Vec<(&'a Feature, Vec<Mat>, usize)>,
) -> Result<()> {
for id in features {
if doc.feature(id.0).is_some_and(|x| x.suppressed) {
continue;
}
let src = source_feature(doc, *id)?;
let Some((inner, inner_mats)) = copied_features(doc, vals, st, src)? else {
out.push((src, mats.to_vec(), first));
continue;
};
if depth >= MAX_NESTING {
return Err(DocError::Invalid(format!("patterns and mirrors of patterns and mirrors nest at most {MAX_NESTING} deep")));
}
let moved: Vec<Mat> = mats.iter().flat_map(|m| inner_mats.iter().map(move |mi| crate::mat_mul(m, mi))).collect();
if moved.len() > MAX_INSTANCES || next.saturating_add(moved.len()) > MAX_INSTANCES * MAX_NESTING {
return Err(DocError::Invalid("too many pattern instances".into()));
}
let block = *next;
*next += moved.len();
walk(doc, vals, st, &inner, &moved, block, next, depth + 1, out)?;
}
Ok(())
}
let mut next = mats.len();
let mut out = Vec::new();
walk(doc, vals, st, features, mats, 0, &mut next, 0, &mut out)?;
Ok(out)
}
/// The transforms of a pattern's or mirror's copies in their instance order (instance `k + 1`
/// is the `k`-th): `mats`, then those of the copies made through patterns and mirrors among
/// `features` ([`copy_plan`]). Naming finds a copy's faces through them.
fn copy_instances(doc: &Document, vals: &BTreeMap<String, Value>, st: &ModelState, features: &[FeatureId], mats: &[Mat]) -> Result<Vec<Mat>> {
let plan = copy_plan(doc, vals, st, features, mats)?;
let len = plan.iter().map(|(_, ms, first)| first + ms.len()).max().unwrap_or(0).max(mats.len());
let mut all = vec![crate::IDENTITY; len];
for (slot, m) in all.iter_mut().zip(mats) {
*slot = *m;
}
for (_, ms, first) in &plan {
for (k, m) in ms.iter().enumerate() {
if let Some(slot) = all.get_mut(first + k) {
*slot = *m;
}
}
}
Ok(all)
}
/// Apply transformed copies of the tools of `features` (patterns, mirrors).
fn replay(
doc: &Document,
vals: &BTreeMap<String, Value>,
f: &Feature,
st: &mut ModelState,
features: &[FeatureId],
mats: &[Mat],
warning: &mut Option<String>,
) -> Result<()> {
if features.is_empty() {
return Err(DocError::Invalid("no features selected".into()));
}
// A suppressed feature has nothing to copy: its copies go with it.
let suppressed: Vec<FeatureId> = features.iter().copied().filter(|n| doc.feature(n.0).is_some_and(|x| x.suppressed)).collect();
if !suppressed.is_empty() {
let list = suppressed.iter().map(|n| format!("`{}`", source_label(doc, *n))).collect::<Vec<_>>().join(", ");
*warning = Some(if suppressed.len() == features.len() {
format!("nothing to copy: {list} suppressed")
} else {
format!("{list} suppressed and not copied")
});
}
// The copies are made in timeline order, whatever order the features were picked in: a
// chamfer picked before the hole it blends would otherwise find no edge to copy.
let mut kept: Vec<FeatureId> = features.iter().copied().filter(|n| !suppressed.contains(n)).collect();
let at = |id: &FeatureId| doc.features.iter().position(|x| x.id == id.0).unwrap_or(usize::MAX);
kept.sort_by_key(at);
kept.dedup();
let (mut missed, mut total) = (0usize, 0usize);
let plan = copy_plan(doc, vals, st, &kept, mats)?;
for (src, mats, first) in &plan {
// A fillet or chamfer repeats at the copied edges.
if let FeatureKind::Fillet { edges, radius, .. } | FeatureKind::Chamfer { edges, distance: radius, .. } = &src.kind {
let r = val(vals, radius, Kind::Length)?;
// The edges the feature blended in this evaluation (found by name), falling back to
// its picked points.
let found = st.blend_edges.get(&src.id).cloned().unwrap_or_else(|| crate::plain(edges));
for m in mats {
let moved_all: Vec<Vec3> = found.iter().map(|p| crate::apply_point(m, *p)).collect();
// The copies of a blend over several bodies blend each body's own edges.
let mut groups: Vec<(usize, Vec<usize>)> = Vec::new();
for (i, p) in moved_all.iter().enumerate() {
let ti = match body_on_edge(st, *p) {
Some(ti) => ti,
None => blend_target(st, &None, &moved_all)?,
};
match groups.iter_mut().find(|(b, _)| *b == ti) {
Some((_, idx)) => idx.push(i),
None => groups.push((ti, vec![i])),
}
}
for (ti, idx) in groups {
let moved: Vec<Vec3> = idx.iter().filter_map(|i| moved_all.get(*i).copied()).collect();
let Some(mb) = st.bodies.get(ti).cloned() else { continue };
let nb = match &src.kind {
FeatureKind::Chamfer { distance2, angle, flip, .. } => chamfer_with(vals, &mb.body, &moved, r, distance2, angle, *flip)?,
// A copy is congruent to the original: the radius it was reduced to first.
FeatureKind::Fillet { fit, .. } => match st.fitted.get(&src.id) {
Some(used) => {
let used: Vec<f64> = idx.iter().map(|i| used.get(*i).copied().unwrap_or(r)).collect();
kernel::fillet_each(&mb.body, &moved, &used)?
}
None => fillet_fitted(&mb.body, &moved, r, *fit)?.0,
},
_ => kernel::fillet(&mb.body, &moved, r)?,
};
// A copy blends edges the pattern's own copies made: named after the body so far.
let nb = mb.traced().then(nb);
if let Some(slot) = st.bodies.get_mut(ti) {
*slot = ModelBody::traced_new(mb.name, nb, mb.feature);
}
}
}
continue;
}
let (op, targets) = feature_op(src);
// A primitive's or a hole's targets are its participants (#1108): the copies change
// those bodies only, like the feature itself (#2755).
let targets = if targets.is_empty() { src.participants.clone() } else { targets };
// A join that merged its targets left only the first of them (the others now live in
// it): the copies change the bodies still there (#3378). When none is, the names stay
// and say which body is missing.
let present: Vec<String> = targets.iter().filter(|t| st.bodies.iter().any(|b| &b.name == *t)).cloned().collect();
let targets = if present.is_empty() { targets } else { present };
let mut copies = Vec::new();
let mut instances = Vec::with_capacity(mats.len());
if let FeatureKind::Hole { diameter, depth, hole, to, .. } = &src.kind {
// A hole is drilled again at each copy of its spot (found on the surface there), so
// a blind hole's depth counts from the face at the copy, not from the bottom of the
// original hole under the original spot.
let (spots, dir) = hole_spots_raw(vals, st, src)?;
for (k, m) in mats.iter().enumerate() {
let d = crate::apply_vector(m, dir).normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;
let start = copies.len();
for p in &spots {
let at = hole_on_surface(st, crate::apply_point(m, *p), d, hole_scope(src));
let to = to.map(|t| crate::apply_point(m, t.0));
let depth = hole_depth_to(st, &at, d, &to, depth)?;
// Each copy's faces are named as the hole's, with the instance.
copies.extend(
hole_tools(vals, st, &at, d, diameter, &depth, hole)?
.into_iter()
.map(|t| Traced { lineage: t.lineage.map(|l| l.copied(src.id, first + k + 1)), body: t.body }),
);
}
instances.push(start..copies.len());
}
} else if let FeatureKind::Rib { .. } = &src.kind {
// A rib is built again at each copy of its sketch, against the bodies there (#4593):
// its walls run until they meet the body, which may not lie the same way there.
for (k, m) in mats.iter().enumerate() {
for body in more::rib_tools(vals, st, src, Some(m))? {
// Each copy's faces are named as the rib's, with the instance.
let t = Traced::unnamed(body);
copies.push(Traced { lineage: t.lineage.map(|l| l.copied(src.id, first + k + 1)), body: t.body });
}
}
} else {
// Each copy's faces are named as the source feature's, with the instance. Its face
// points follow their named faces, as the feature's own did (#2121): a To Object
// extrude's copies reach the face where it is now, not where it was picked.
let moved = with_named_face_points(doc, st, src)?.map(|(g, _)| g);
let tools = feature_tools_with_constructor(doc, vals, moved.as_ref().unwrap_or(src), st, &mut None, &mut None, &mut None)?;
for (k, m) in mats.iter().enumerate() {
let start = copies.len();
for t in &tools {
copies.push(t.copied(kernel::transform_matrix(&t.body, *m)?, src.id, first + k + 1));
}
instances.push(start..copies.len());
}
}
if op == Operation::Cut {
for instance in &instances {
if let Some(tools) = copies.get(instance.clone()) {
total += 1;
missed += usize::from(copy_misses(st, f, &targets, tools));
}
}
}
// Copies of a cut through sheet metal are cut-outs of its flat pattern, as the cut is
// (#6841): each machined into the sheets in turn, then cut from the other targets.
if op == Operation::Cut && matches!(src.kind, FeatureKind::Extrude { .. }) && !st.sheets.is_empty() && instances.len() == mats.len() {
let mut handled = Vec::with_capacity(mats.len());
for (m, instance) in mats.iter().zip(&instances) {
let bodies: Vec<Body> = copies.get(instance.clone()).unwrap_or_default().iter().map(|t| t.body.clone()).collect();
handled.push(more::sheet_cut_copy(f, src, m, st, &bodies, &targets, warning)?);
}
if handled.iter().any(|h| !h.is_empty()) {
// Copies the same sheets took are cut from the rest at once.
let mut groups: Vec<(Vec<String>, Vec<Traced>)> = Vec::new();
let mut rest = copies.into_iter();
for (done, instance) in handled.into_iter().zip(&instances) {
let tools: Vec<Traced> = rest.by_ref().take(instance.len()).collect();
match groups.iter_mut().find(|(d, _)| *d == done) {
Some((_, all)) => all.extend(tools),
None => groups.push((done, tools)),
}
}
for (done, tools) in groups {
apply_beside_sheet_cut(doc, st, f, tools, op, &targets, &done)?;
}
continue;
}
}
// New bodies from a pattern join their source when they touch it (as one feature would).
if f.body_names.is_empty() {
apply_traced(doc, st, f, copies, op, &targets)?;
} else {
let start = st.bodies.iter().filter(|b| b.feature == f.id).count();
let mut named = f.clone();
named.body_names = f.body_names.iter().skip(start).cloned().collect();
apply_traced(doc, st, &named, copies, op, &targets)?;
}
}
if missed > 0 {
append_warning(warning, format!("{missed} of {total} cut copies remove no material"));
}
Ok(())
}
#[path = "model_cache.rs"]
mod model_cache;
#[path = "eval_more.rs"]
mod more;
pub use model_cache::SavedModel;
#[path = "eval_frame.rs"]
pub(crate) mod frame_member;
#[path = "eval_surface.rs"]
mod surface;
#[path = "eval_thread.rs"]
mod thread;
use thread::thread_on;
pub use thread::{ThreadInfo, metric_thread_sizes, parse_metric_thread, suggested_thread, suggested_thread_in};
/// Height above `plane` (along its normal) of the object at `p` as seen from `centre`: the face
/// there if it is planar and parallel (its plane), else where a ray from `centre` along the
/// normal meets the body there, else the point itself.
pub fn object_height(st: &ModelState, plane: &Plane, centre: Vec3, p: Vec3) -> f64 {
height_at(st, face_at(st, p, Some(plane.normal())), plane, centre, p)
}
/// [`object_height`] of the point `p` on `face` (`(body index, face index)`, see [`object_face`]).
fn height_at(st: &ModelState, face: Option<(usize, usize)>, plane: &Plane, centre: Vec3, p: Vec3) -> f64 {
let n = plane.normal();
let h = |q: Vec3| (q - plane.origin).dot(n);
let Some((bi, fi)) = face else { return h(p) };
let Some(b) = st.bodies.get(bi) else { return h(p) };
let tol = (b.body.size() * 1e-3).max(1e-3);
let Ok(faces) = b.body.faces(tol) else { return h(p) };
if let Some(f) = faces.iter().find(|f| f.index == fi)
&& f.plane_normal.is_some_and(|fnrm| fnrm.cross(n).len() < 1e-6)
{
return h(f.centroid);
}
// A curved or slanted face: where the profile's middle meets it.
let m = b.mesh();
for dir in [n, n * -1.0] {
if let Some((t, tri)) = m.raycast(centre, dir)
&& m.tri_face.get(tri).is_some_and(|x| *x as usize == fi)
{
return h(centre + dir * t);
}
}
h(p)
}
/// The face a To Object pick is on: the nearest face over every solid body, `(body index,
/// face index)`, within that body's pick tolerance. Not the first body with any face within
/// its tolerance: that is 5 % of the body's size, so a large body beside a small target (a
/// plate under a post, a frame around a pin) would otherwise take a pick made on the target.
fn face_at(st: &ModelState, p: Vec3, normal: Option<Vec3>) -> Option<(usize, usize)> {
st.bodies
.iter()
.enumerate()
.filter(|(_, b)| !b.body.is_mesh())
.filter_map(|(bi, b)| {
let (d, fi) = nearest_object_face(b, p, normal)?;
(d <= crate::appearance::pick_tolerance(b)).then_some((d, bi, fi))
})
.min_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, bi, fi)| (bi, fi))
}
/// At a shared edge or corner an extrusion's end plane and side wall can be equally near.
/// Prefer the plane square to the extrusion: choosing the wall would instead extend the tool
/// past the whole body and try to trim it, even when the tool never intersects that body.
/// Only settle a distance tie; a nearby plane must not steal a pick on another face.
fn nearest_object_face(b: &ModelBody, p: Vec3, normal: Option<Vec3>) -> Option<(f64, usize)> {
let nearest = crate::appearance::nearest_face(b, p)?;
let Some(n) = normal else { return Some(nearest) };
if nearest.0 > crate::appearance::pick_tolerance(b) {
return Some(nearest);
}
let tol = (b.body.size() * 1e-3).max(1e-3);
let Ok(faces) = b.body.faces(tol) else { return Some(nearest) };
let caps: std::collections::BTreeSet<usize> =
faces.iter().filter(|f| f.plane_normal.is_some_and(|fnrm| fnrm.cross(n).len() < 1e-6)).map(|f| f.index).collect();
if caps.is_empty() || caps.contains(&nearest.1) {
return Some(nearest);
}
let tie = (b.body.size() * 1e-9).max(1e-7);
let mesh = b.mesh();
mesh.triangles
.iter()
.zip(&mesh.tri_face)
.filter(|(_, fi)| caps.contains(&(**fi as usize)))
.filter_map(|(tri, fi)| {
let [a, b, c] = mesh.tri(tri)?;
let d = crate::appearance::closest_on_triangle(p, a, b, c).dist(p);
(d <= nearest.0 + tie).then_some((d, *fi as usize))
})
.min_by(|a, b| a.0.total_cmp(&b.0))
.or(Some(nearest))
}
/// The face a To / From Object point stands for, `(body index, face index)`: the face its
/// stored `name` finds when the point lies on it (evaluation has moved the point onto its named
/// face), else the nearest face at the point. The name settles a tie: in an assembly a part of
/// another component may rest on the target and touch it at the point.
fn object_face(st: &ModelState, name: Option<&str>, p: Vec3, normal: Option<Vec3>) -> Option<(usize, usize)> {
if let Some(n) = name.filter(|n| !n.is_empty())
&& let Some(hit) = crate::naming::locate_face(st, n, p)
&& hit.on_point
{
return Some((hit.body, hit.face));
}
face_at(st, p, normal)
}
/// The body of `face` when that face is not a plane (with `n`: not a plane square to `n`), so To
/// Object must follow its shape.
fn curved_face(st: &ModelState, face: Option<(usize, usize)>, n: Option<Vec3>) -> Option<usize> {
let (bi, fi) = face?;
let b = st.bodies.get(bi)?;
let tol = (b.body.size() * 1e-3).max(1e-3);
let normal = b.body.faces(tol).ok()?.into_iter().find(|f| f.index == fi).map(|f| f.plane_normal);
let planar = match n {
Some(n) => normal.flatten().is_some_and(|fnrm| fnrm.cross(n).len() < 1e-6),
None => normal.is_some_and(|fnrm| fnrm.is_some()),
};
(!planar).then_some(bi)
}
/// The body at `p` when the face there is not planar.
fn curved_target_any(st: &ModelState, p: Vec3) -> Option<usize> {
curved_face(st, face_at(st, p, None), None)
}
/// Tools run through `target`, cut back to its surface: each tool less the body, keeping the
/// piece(s) that touch the start (`dist_to_start` 0 there).
fn trim_to_body(tools: Vec<Traced>, target: &ModelBody, dist_to_start: impl Fn(Vec3) -> f64) -> Result<Vec<Traced>> {
let mut out = Vec::new();
let target_traced = target.traced();
for t in tools {
let Some(cut) = kernel::boolean(&t.body, &target.body, BoolOp::Cut)? else { continue };
let cut = Traced::step(cut, &[&t, &target_traced]);
let lumps = cut.body.lumps()?;
let lineages = crate::lineage::Lineage::lumps(&cut.body, cut.lineage.as_ref(), &lumps);
for (lump, lineage) in lumps.into_iter().zip(lineages) {
let tol = (lump.size() * 1e-4).max(1e-6);
let touches = lump
.mesh(&solidcraft_kernel::MeshTolerance::chord((lump.size() * 1e-2).max(1e-2)))
.map(|m| m.positions.iter().any(|q| dist_to_start(*q) < tol))
.unwrap_or(false);
if touches {
out.push(Traced { body: lump, lineage });
}
}
}
if out.is_empty() {
return Err(DocError::Invalid("nothing lies between the profile and the To object".into()));
}
Ok(out)
}
/// One point on each face of a body (a triangle centre, so it lies on the face).
fn face_samples(b: &ModelBody) -> Vec<Vec3> {
let m = b.mesh();
let mut out: Vec<Option<Vec3>> = Vec::new();
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
let f = *f as usize;
if out.len() <= f {
out.resize(f + 1, None);
}
if let (Some(slot @ None), Some([a, bb, c])) = (out.get_mut(f), m.tri(t)) {
*slot = Some((a + bb + c) * (1.0 / 3.0));
}
}
out.into_iter().flatten().collect()
}
/// The picked faces and every face joined to them smoothly (across tangent edges).
/// Each face appears once, with a point on it. Shell evaluation and selection feedback use
/// the same expansion; callers keep the original picks when saving the feature.
pub fn tangent_face_chain(b: &ModelBody, picks: &[Vec3]) -> Vec<(usize, Vec3)> {
let m = b.mesh();
let samples = face_samples(b);
let face_of = |p: Vec3| crate::appearance::face_index_at(b, p);
// The surface normal of face f at its mesh vertex nearest q (vertex normals are the
// surface's, so a tangent edge reads the same from both sides).
let normal_near = |f: u32, q: Vec3| -> Option<Vec3> {
m.triangles
.iter()
.zip(&m.tri_face)
.filter(|(_, tf)| **tf == f)
.flat_map(|(t, _)| t.iter().copied())
.filter_map(|i| Some((m.positions.get(i as usize)?.dist(q), *m.normals.get(i as usize)?)))
.min_by(|a, b| a.0.total_cmp(&b.0))
.and_then(|(_, n)| n.normalized())
};
let mut chosen: Vec<u32> = picks.iter().filter_map(|p| face_of(*p).map(|f| f as u32)).collect();
chosen.sort_unstable();
chosen.dedup();
let mut k = 0;
while k < chosen.len() && chosen.len() < 10_000 {
let f = chosen[k];
k += 1;
for (e, fs) in m.edges.iter().zip(&m.edge_faces) {
let (Some(&a), Some(&bb)) = (fs.first(), fs.get(1)) else { continue };
let other = if a == f {
bb
} else if bb == f {
a
} else {
continue;
};
if chosen.contains(&other) {
continue;
}
let Some(mid) = e.get(e.len() / 2).copied() else { continue };
if let (Some(n1), Some(n2)) = (normal_near(f, mid), normal_near(other, mid))
&& n1.dot(n2) > 2f64.to_radians().cos()
{
chosen.push(other);
}
}
}
let mut out = Vec::new();
for f in chosen {
if let Some(p) = picks.iter().chain(&samples).find(|p| face_of(**p) == Some(f as usize)) {
out.push((f as usize, *p));
}
}
out
}
fn smooth_chain(b: &ModelBody, picks: &[Vec3]) -> Vec<Vec3> {
let mut out = picks.to_vec();
out.extend(tangent_face_chain(b, picks).into_iter().map(|(_, point)| point));
out
}
/// `plane` with the sheet face it names (see `sheet::plane_sheet_face`) replaced by that face's current
/// plane in the frame of component `comp`, or an error when the face is gone: a lost
/// attachment is reported, never moved to the nearest face.
pub(crate) fn sheet_face_plane_in_frame(doc: &Document, st: &ModelState, comp: u64, plane: &PlaneRef) -> Result<PlaneRef> {
Ok(match plane {
PlaneRef::Face { name: Some(name), anchor: None, .. } if crate::sheet::plane_sheet_face(plane).is_some() => {
let lost = || DocError::Invalid(format!("lost face attachment: the sheet face `{name}` no longer exists; reattach the sketch to a face"));
let (body, face) = crate::sheet::sheet_face_plane(st, name).ok_or_else(lost)?;
if doc.occurrences.is_empty() && doc.body_offsets.is_empty() {
return Ok(PlaneRef::Custom { plane: face });
}
// The body's own coordinates into the component's frame, as `state_in_frame` places its bodies.
let source = st.body(&body).ok_or_else(lost)?;
let inverse = crate::mat_inverse(&doc.component_transform(comp)).ok_or_else(lost)?;
let m = crate::mat_mul(&inverse, &doc.component_transform(doc.model_body_component(source)));
let m = doc.model_body_offset(source).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m);
let placed = Plane::new(crate::apply_point(&m, face.origin), crate::apply_vector(&m, face.x), crate::apply_vector(&m, face.y));
PlaneRef::Custom { plane: placed.ok_or_else(lost)? }
}
PlaneRef::Offset { base, distance } => {
PlaneRef::Offset { base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?), distance: distance.clone() }
}
PlaneRef::AtAngle { base, axis_origin, axis_dir, angle, line } => PlaneRef::AtAngle {
base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?),
axis_origin: *axis_origin,
axis_dir: *axis_dir,
angle: angle.clone(),
line: line.clone(),
},
PlaneRef::Flipped { base, about_y } => {
PlaneRef::Flipped { base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?), about_y: *about_y }
}
PlaneRef::ThroughPoint { base, point } => {
PlaneRef::ThroughPoint { base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?), point: point.clone() }
}
other => other.clone(),
})
}
/// The plane of the body face a sketch sits on, found again: the face its stored `name` finds,
/// which must still be planar and face the picked plane's way (else the sketch fails, asking for
/// its face to be picked again); without a name, among planar faces with the picked plane's
/// normal, the one nearest `at`. The picked frame moves along its normal onto it.
fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) -> Result<(Plane, Option<String>)> {
let n = picked.normal();
if let Some(name) = name {
let hit = crate::naming::locate_face(st, name, at).ok_or_else(|| DocError::reselect(name))?;
let b = st.bodies.get(hit.body).ok_or_else(|| DocError::reselect(name))?;
let tol = (b.body.size() * 1e-3).max(1e-3);
let face = b.body.faces(tol)?.into_iter().find(|f| f.index == hit.face).ok_or_else(|| DocError::reselect(name))?;
if !face.plane_normal.is_some_and(|fnrm| fnrm.dot(n) > 1.0 - 1e-6) {
return Err(DocError::reselect(name));
}
let note = if !crate::naming::face_name_exact(b, hit.face) && (face.centroid - at).dot(n).abs() > tol {
// Named from geometry and moved off the picked plane: geometry alone decided.
Some(format!("face `{}` was found by geometry, not exact history; check it", crate::name_lookup::quoted(name)))
} else {
None
};
return Ok((picked.offset(face.centroid.dot(n) - picked.origin.dot(n)), note));
}
let mut best: Option<(f64, f64)> = None; // (distance from `at`, plane offset along n)
for b in &st.bodies {
let tol = (b.body.size() * 1e-3).max(1e-3);
let (Ok(faces), Ok(mesh)) = (b.body.faces(tol), b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol))) else { continue };
for f in faces {
let Some(fnrm) = f.plane_normal else { continue };
if fnrm.dot(n) < 1.0 - 1e-6 {
continue;
}
let d = mesh
.triangles
.iter()
.zip(&mesh.tri_face)
.filter(|(_, tf)| **tf as usize == f.index)
.filter_map(|(t, _)| mesh.tri(t))
.map(|[a, bb, c]| crate::project::closest_on_triangle(at, a, bb, c).dist(at))
.fold(f64::INFINITY, f64::min);
if best.is_none_or(|x| d < x.0) {
best = Some((d, f.centroid.dot(n)));
}
}
}
Ok(match best {
Some((_, off)) => {
let shift = off - picked.origin.dot(n);
(picked.offset(shift), None)
}
None => (*picked, Some("the face the sketch was on is gone; the sketch stays where it was".into())),
})
}
/// A chamfer, equal or by its second distance or angle.
fn chamfer_with(
vals: &BTreeMap<String, Value>,
b: &kernel::Body,
edges: &[Vec3],
d: f64,
distance2: &Option<crate::Expr>,
angle: &Option<crate::Expr>,
flip: bool,
) -> Result<kernel::Body> {
let side = match (distance2, angle) {
(Some(e), _) => Some(kernel::ChamferSide::Distance(val(vals, e, Kind::Length)?)),
(None, Some(e)) => Some(kernel::ChamferSide::Angle(val(vals, e, Kind::Angle)?)),
(None, None) => None,
};
Ok(match side {
Some(s) => kernel::chamfer_sides(b, edges, d, s, flip)?,
None => match kernel::chamfer(b, edges, d) {
Err(kernel::KernelError::TooLarge(why)) => return Err(with_largest_fit(why, "distance", || kernel::chamfer_max(b, edges, d)).into()),
other => other?,
},
})
}
fn eval_feature(
doc: &Document,
vals: &BTreeMap<String, Value>,
f: &Feature,
st: &mut ModelState,
warning: &mut Option<String>,
import_report: &mut Option<Arc<kernel::ImportReport>>,
repair: &mut Option<Arc<kernel::RepairReport>>,
) -> Result<()> {
// Its tools meet bodies in other placements where those are shown (#3383).
let _frames = ToolFrames::install(doc, f, st);
match &f.kind {
FeatureKind::BodyTransfer { bodies, from, to, transform } => {
crate::body_transfer::evaluate(doc, st, &crate::plain(bodies), *from, *to, *transform)
}
FeatureKind::SheetBase { .. }
| FeatureKind::SheetContour { .. }
| FeatureKind::SheetFlange { .. }
| FeatureKind::SheetHem { .. }
| FeatureKind::SheetPerforate { .. }
| FeatureKind::SheetFold { .. }
| FeatureKind::SheetPath { .. }
| FeatureKind::SheetUnfold { .. }
| FeatureKind::SheetConvert { .. } => more::sheet_eval(doc, vals, f, st, warning),
FeatureKind::Boss { .. } | FeatureKind::Lip { .. } | FeatureKind::SnapFit { .. } | FeatureKind::Rest { .. } => {
more::plastic_eval(doc, vals, f, st)
}
FeatureKind::Patch { .. }
| FeatureKind::Stitch { .. }
| FeatureKind::Thicken { .. }
| FeatureKind::SurfaceTrim { .. }
| FeatureKind::SurfaceExtend { .. }
| FeatureKind::SurfaceExtrude { .. }
| FeatureKind::Unstitch { .. }
| FeatureKind::ReverseNormal { .. }
| FeatureKind::SurfaceRevolve { .. }
| FeatureKind::SurfaceSweep { .. }
| FeatureKind::SurfaceLoft { .. }
| FeatureKind::SurfaceBlend { .. }
| FeatureKind::SurfaceBoundary { .. }
| FeatureKind::SurfaceNetwork { .. }
| FeatureKind::SurfaceMatch { .. }
| FeatureKind::SurfaceFair { .. }
| FeatureKind::SurfaceOffset { .. }
| FeatureKind::SurfaceRuled { .. }
| FeatureKind::SurfaceUntrim { .. } => surface::eval(doc, vals, f, st, warning),
FeatureKind::Emboss { .. }
| FeatureKind::Rib { .. }
| FeatureKind::ReplaceFace { .. }
| FeatureKind::Align { .. }
| FeatureKind::Remove { .. } => more::eval(doc, vals, f, st),
FeatureKind::Sketch { plane, sketch } => {
let anchor = crate::face_anchor::plane_face_anchor(plane);
let fst = match anchor {
Some(anchor) => crate::state_in_face_anchor_frame(doc, st, anchor, f.component)?,
// A sketch that reads no geometry (a fixed plane, no projections) needs no other
// component's bodies moved into its frame: placing every body of a large
// assembly again is what made each sketch edit as slow as the design is big.
None if !plane_reads_geometry(plane) && sketch.links.is_empty() => std::borrow::Cow::Borrowed(st),
None => state_in_frame(doc, st, f.component)?,
};
let (plane, face_warning) = match (anchor, plane) {
(Some(_), plane) => doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?,
// A flat face of a sheet: the panel's exact plane, from its flat region and fold.
(None, plane) if crate::sheet::plane_sheet_face(plane).is_some() => {
(doc.resolve_plane_in(vals, &sheet_face_plane_in_frame(doc, st, f.component, plane)?, 0, Some(&fst))?, None)
}
(None, PlaneRef::Face { plane: picked, at, name, anchor: None }) => face_plane(&fst, picked, *at, name.as_deref())?,
(None, other) => (doc.resolve_plane_in(vals, other, 0, Some(&fst))?, None),
};
let mut sk = sketch.clone();
// A text's outlines are rebuilt from its numbers when the links are refreshed: the
// ones its expressions give come first.
doc.apply_text_values(vals, &mut sk)?;
let mut warns = match anchor {
Some(anchor) => crate::project::refresh_face_anchor_links(doc, vals, &fst, &plane, &mut sk, anchor)?,
None => crate::project::refresh_links(doc, vals, &fst, &plane, &mut sk)?,
};
drop(fst);
sk.refresh_offsets()?;
if let Some(w) = face_warning {
warns.insert(0, w);
}
// The stored sketch is solved for its stored values, with its links where they
// were stored: a link that moved must not change the side a dimension from it is on.
let stored = sk.driving_values();
let report = doc.solve_sketch(vals, &mut sk, &stored, Some(sketch))?;
if !report.keeps_orientation() {
warns.insert(0, report.failure(|f| format!("the sketch constraints conflict ({f})")));
} else {
// The solve may have moved the curve a text runs along.
warns.extend(crate::project::relay_path_texts(&mut sk));
}
if !warns.is_empty() {
*warning = Some(warns.join("; "));
}
sk.validate_periodic_splines()?;
// A group of touching curves too large to search whole says so, rather than
// leaving profiles out silently (#6896).
let search = solidcraft_sketch::find_profiles_checked(&sk);
if search.incomplete {
append_warning(warning, profiles_cut_short_note());
}
let profiles = search.profiles;
let ends = solidcraft_sketch::loose_ends(&sk);
st.sketches.retain(|s| s.feature != f.id);
st.sketches.push(Arc::new(SolvedSketch { feature: f.id, name: f.name.clone(), plane, sketch: sk, report, profiles, ends }));
Ok(())
}
FeatureKind::Extrude { operation, targets, .. }
| FeatureKind::Pipe { operation, targets, .. }
| FeatureKind::Revolve { operation, targets, .. }
| FeatureKind::Loft { operation, targets, .. }
| FeatureKind::Coil { operation, targets, .. }
| FeatureKind::Sweep { operation, targets, .. } => {
let mut constructor = None;
let mut to_body = None;
let tools = feature_tools_with_constructor(doc, vals, f, st, &mut constructor, &mut to_body, warning)?;
// Cuts through sheet metal become cut-outs of its flat pattern.
if matches!(operation, Operation::Cut | Operation::Intersect) && matches!(f.kind, FeatureKind::Extrude { .. }) && !st.sheets.is_empty() {
let bodies: Vec<Body> = tools.iter().map(|t| t.body.clone()).collect();
let handled = more::sheet_cut(f, st, &bodies, &crate::plain(targets), constructor.as_ref(), warning)?;
if !handled.is_empty() {
return apply_beside_sheet_cut(doc, st, f, tools, *operation, &crate::plain(targets), &handled);
}
}
// A join one sheet thick in the plane of a panel becomes part of that panel. A Join to an
// object (#6424) is left to the generic path below, which joins the object as well.
if *operation == Operation::Join && to_body.is_none() && matches!(f.kind, FeatureKind::Extrude { .. }) && !st.sheets.is_empty() {
let bodies: Vec<Body> = tools.iter().map(|t| t.body.clone()).collect();
if !more::sheet_join(f, st, &bodies, &crate::plain(targets), constructor.as_ref())?.is_empty() {
return Ok(());
}
}
// A Join extrude to an object joins that object too (#6424): the tool and the body
// it runs to are one body, not only the body the profile was sketched on.
let extra: Vec<String> = if *operation == Operation::Join { to_body.into_iter().collect() } else { Vec::new() };
apply_traced_with(doc, st, f, tools, *operation, &crate::plain(targets), &extra)
}
FeatureKind::Hole { thread, thread_depth, diameter, hand, modeled, ease_out, .. } => {
let thread_depth = thread_depth.as_ref().map(|d| val(vals, d, Kind::Length)).transpose()?;
if thread_depth.is_some() && thread.is_none() {
return Err(DocError::Invalid("thread depth requires a tapped hole".into()));
}
if *modeled && thread.is_none() {
return Err(DocError::Invalid("a modelled thread needs a tapped hole".into()));
}
if ease_out.is_some() && !*modeled {
return Err(DocError::Invalid("a runout is cut only on a modelled thread".into()));
}
if thread_depth.is_some_and(|d| !d.is_finite() || d <= 0.0) {
return Err(DocError::Invalid("thread depth must be finite and positive".into()));
}
let (spots, dir) = hole_spots(vals, st, f)?;
let tools = hole_feature_tools(vals, st, f)?;
let handled = sheet_hole_cut(st, f, &tools, warning)?;
let tools: Vec<Traced> = tools.into_iter().map(|(tool, _)| tool).collect();
if handled.is_empty() {
// A hole moved off the material (a changed position, parameter or sketch point)
// cuts nothing: it says so, as a pattern does of its copies (#10701).
let missed = tools.iter().filter(|tool| hole_misses(st, f, &tool.body)).count();
let total = tools.len();
let targets: Vec<String> = hole_targets(st, f).iter().map(|b| b.name.clone()).collect();
apply_traced(doc, st, f, tools, Operation::Cut, &[])?;
match (missed, total) {
(0, _) => {}
(_, 1) => append_warning(warning, "the hole removes no material".into()),
_ => append_warning(warning, format!("{missed} of {total} holes remove no material")),
}
// A hole wider than the part takes all of it away (#10702): almost never what a
// hole means, so it says which bodies are gone.
let gone: Vec<&str> = targets.iter().map(String::as_str).filter(|n| st.body(n).is_none()).collect();
if !gone.is_empty() {
append_warning(warning, format!("the hole removes all of {}", gone.join(", ")));
}
} else {
apply_beside_sheet_cut(doc, st, f, tools, Operation::Cut, &[], &handled)?;
}
if let Some(d) = thread {
// Find the bore beyond any entry recess, including shallow and through holes.
let r = val(vals, diameter, Kind::Length)? / 2.0;
// A pipe thread's wall must be found: no fallback place on a guessed wall.
let pipe = crate::parse_tapped_thread(d).is_some_and(|t| {
matches!(
t.family,
crate::TappedThreadFamily::G | crate::TappedThreadFamily::Rp | crate::TappedThreadFamily::Rc | crate::TappedThreadFamily::Npt
)
});
let ease = thread::runout(vals, ease_out)?;
for p in spots {
let wall = if pipe {
parallel_tapped_wall(st, p, dir, r).ok_or_else(|| DocError::Invalid("no cylindrical pipe-thread wall remains".into()))?
} else {
parallel_tapped_wall(st, p, dir, r).unwrap_or(p + dir.any_perp() * r + dir * (r * 0.5))
};
let ask = thread::ThreadAsk { designation: Some(d), tapped: true, hand: *hand, ..Default::default() };
if *modeled {
// Cut from the entry, as deep as `thread_depth` or along the whole wall:
// at a blind hole's bottom the groove stops clear of it, or fades out
// before it with a runout.
let extent = thread_depth.map_or(thread::Extent::Full, thread::Extent::Length);
let ask = thread::ThreadAsk { modeled: true, extent, from: Some(p), ease_out: ease, ..ask };
let on = thread_on(st, f.id, wall, &ask)?;
thread::cut(st, on, (crate::thread_forms::ThreadTip::None, None, None))?;
continue;
}
let mut t = thread_on(st, f.id, wall, &ask)?.info;
if let Some(depth) = thread_depth {
let available = t.end - t.start;
if depth > available {
return Err(DocError::Invalid(format!(
"thread depth {} mm exceeds the cylindrical wall's useful length of {} mm; reduce the thread depth or use full thread depth",
show_mm(depth),
show_mm(available)
)));
}
// Start at the entry in the drilling direction, independently of the
// wall probe's position and the cylinder surface's axis orientation.
if dir.dot(t.axis) > 0.0 {
t.end = t.start + depth;
} else {
t.start = t.end - depth;
}
}
st.threads.push(t);
}
}
Ok(())
}
FeatureKind::Thread { .. } => thread::eval(doc, vals, f, st),
FeatureKind::Shell { faces, thickness, body, direction, tangent_chain } => {
let t = val(vals, thickness, Kind::Length)?;
// No face opened (a closed hollow body) picks no body: the one there is, or the named one.
let i = match (faces.is_empty(), body, st.bodies.len()) {
(true, None, 1) => 0,
(true, None, _) => return Err(DocError::Invalid("a shell that opens no face needs the body named".into())),
_ => body_at(st, body, &crate::plain(faces))?,
};
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) };
let picks = crate::plain(faces);
let open = if *tangent_chain {
let chain = tangent_face_chain(&mb, &picks);
if !chain.is_empty() && chain.len() == mb.body.face_count() {
return Err(DocError::Invalid(
"Tangent Chain opens every face of this body, leaving no walls; turn off Tangent Chain to remove only the picked faces"
.into(),
));
}
// Keep every authored pick, including any the kernel must reject, as before
// chain expansion. The derived samples must not silently drop a bad input.
let mut open = picks;
open.extend(chain.into_iter().map(|(_, point)| point));
open
} else {
picks
};
let input = mb.traced();
// The shell, and the operands of the operation that made it.
let (nb, operands) = match direction.as_str() {
"" | "inside" => (kernel::shell(&mb.body, &open, t)?, vec![input]),
"outside" | "both" => {
// Walls grown out of the faces (or half out, half in): an offset body less a
// cavity, the open faces pushed out of the way.
if !(t > 1e-6) {
return Err(DocError::Invalid("shell thickness must be positive".into()));
}
let (out, inn) = if direction == "outside" { (t, 0.0) } else { (t / 2.0, t / 2.0) };
let samples = face_samples(&mb);
let opened =
|p: &Vec3| open.iter().any(|q| crate::appearance::face_index_at(&mb, *q) == crate::appearance::face_index_at(&mb, *p));
let walls: Vec<Vec3> = samples.iter().filter(|p| !opened(p)).copied().collect();
let outer = Traced::step(kernel::offset_faces(&mb.body, &walls, out)?, &[&input]);
// The cavity's faces are the shell's inner walls, named after the faces they offset.
let inner = mb.before_as(crate::lineage::Operand::Inner(mb.name.clone()));
let cavity = if inn > 0.0 { Traced::step(kernel::offset_faces(&mb.body, &walls, -inn)?, &[&inner]) } else { inner };
// The open faces pushed out of the way (none: the cavity stays sealed inside).
let cavity =
if open.is_empty() { cavity } else { Traced::step(kernel::offset_faces(&cavity.body, &open, 2.0 * t + 1.0)?, &[&cavity]) };
let cut = kernel::boolean(&outer.body, &cavity.body, BoolOp::Cut)?
.ok_or_else(|| DocError::Invalid("the shell removed everything".into()))?;
(cut, vec![outer, cavity])
}
o => return Err(DocError::Invalid(format!("unknown shell direction `{o}` (inside, outside or both)"))),
};
// Certifying may join faces; their history stays over the same operands.
let nb = Traced::step(nb.with_shell_certificate(f.id)?, &operands.iter().collect::<Vec<_>>());
if let Some(slot) = st.bodies.get_mut(i) {
*slot = ModelBody::traced_new(mb.name, nb, mb.feature);
}
Ok(())
}
FeatureKind::Draft { faces, angle, neutral, pull, body } => {
let a = val(vals, angle, Kind::Angle)?;
let pl = doc.resolve_plane_in(vals, neutral, 0, Some(st))?;
let i = body_at(st, body, &crate::plain(faces))?;
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) };
let nb = Traced::step(kernel::draft(&mb.body, &crate::plain(faces), &pl, pull.0, a)?, &[&mb.traced()]);
if let Some(slot) = st.bodies.get_mut(i) {
*slot = ModelBody::traced_new(mb.name, nb, mb.feature);
}
Ok(())
}
FeatureKind::ConstructionPlane { plane } => {
// On a body face: follow the face as it is now, as a sketch on that face does.
let pl = match crate::face_anchor::plane_face_anchor(plane) {
Some(anchor) => {
let fst = crate::state_in_face_anchor_frame(doc, st, anchor, f.component)?;
let (pl, note) = doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?;
if let Some(note) = note {
append_warning(warning, note);
}
pl
}
// On a flat face of a sheet: that panel's plane as it is now, as a sketch on the
// face finds it (the stored plane is only where the face was picked).
None if crate::sheet::plane_sheet_face(plane).is_some() => {
doc.resolve_plane_in(vals, &sheet_face_plane_in_frame(doc, st, f.component, plane)?, 0, Some(st))?
}
// A plane of numbers alone reads no body: placing them all is the design's size.
None if plane_is_fixed(plane) => doc.resolve_plane_in(vals, plane, 0, Some(st))?,
// Picks on bodies of other (moved) components are where those bodies are shown.
None => doc.resolve_plane_in(vals, plane, 0, Some(&*construction_state(doc, st, f.component)?))?,
};
st.construct.push(crate::construct::Construct {
feature: f.id,
name: f.name.clone(),
geom: crate::construct::ConstructGeom::Plane(pl),
bodies: Vec::new(),
});
Ok(())
}
FeatureKind::ConstructionAxis { def } => {
let cst = construction_state(doc, st, f.component)?;
let ctx = crate::construct::Ctx { doc, vals, st: &cst, depth: 0 };
let (origin, dir) = crate::construct::resolve_axis(&ctx, def)?;
let bodies = crate::construct::source_bodies(&ctx, &def.refs());
st.construct.push(crate::construct::Construct {
feature: f.id,
name: f.name.clone(),
geom: crate::construct::ConstructGeom::Axis { origin, dir },
bodies,
});
Ok(())
}
FeatureKind::ConstructionPoint { def } => {
let cst = construction_state(doc, st, f.component)?;
let ctx = crate::construct::Ctx { doc, vals, st: &cst, depth: 0 };
let p = crate::construct::resolve_point(&ctx, def)?;
let bodies = crate::construct::source_bodies(&ctx, &def.refs());
st.construct.push(crate::construct::Construct {
feature: f.id,
name: f.name.clone(),
geom: crate::construct::ConstructGeom::Point(p),
bodies,
});
Ok(())
}
FeatureKind::BoundaryFill { tools, cells, operation, remove_tools } => {
if tools.is_empty() || tools.len() > 64 || cells.is_empty() || cells.len() > 1000 {
return Err(DocError::Invalid("Boundary Fill needs 1…64 tool bodies and 1…1000 cells".into()));
}
let tb: Vec<ModelBody> =
tools.iter().map(|t| st.body(t).cloned().ok_or_else(|| DocError::Unknown(format!("body `{t}`")))).collect::<Result<_>>()?;
let mut made = Vec::new();
for p in cells {
// The cell: inside the tools that hold the point, outside the others.
let inside: Vec<bool> = tb.iter().map(|b| b.mesh().contains(p.0)).collect();
let mut acc: Option<Traced> = None;
for (b, _) in tb.iter().zip(&inside).filter(|(_, i)| **i) {
acc = match acc {
None => Some(b.traced()),
Some(a) => kernel::boolean(&a.body, &b.body, BoolOp::Intersect)?.map(|r| Traced::step(r, &[&a, &b.traced()])),
};
}
let Some(mut cell) = acc else {
return Err(DocError::Invalid(format!("the point {p:?} is outside every tool: no enclosed cell there")));
};
for (b, _) in tb.iter().zip(&inside).filter(|(_, i)| !**i) {
let cut = kernel::boolean(&cell.body, &b.body, BoolOp::Cut)?.ok_or_else(|| DocError::Invalid("a cell came out empty".into()))?;
cell = Traced::step(cut, &[&cell, &b.traced()]);
}
made.push(cell);
}
if *remove_tools {
st.bodies.retain(|b| !tools.iter().any(|t| *t == b.name));
}
apply_traced(doc, st, f, made, *operation, &[])
}
FeatureKind::SplitFace { faces, body, plane, tool, sketch } => {
let i = body_at(st, body, &crate::plain(faces))?;
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) };
let mut picked: Vec<usize> = Vec::new();
for p in faces {
let fi = crate::appearance::face_index_at(&mb, p.0)
.ok_or_else(|| DocError::Invalid(format!("Split Face: no face of {} at {p:?}", mb.name)))?;
if !picked.contains(&fi) {
picked.push(fi);
}
}
let nb = match (tool, sketch) {
(Some(t), _) => {
let tb = st.body(&t.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", t.body)))?;
let face = crate::appearance::face_index_at(tb, t.point.0)
.ok_or_else(|| DocError::Invalid(format!("no face of `{}` at the tool point", t.body)))?;
kernel::split_faces(&mb.body, &picked, &kernel::SplitTool::Face { body: &tb.body, face })?
}
(None, Some(sid)) => {
let ss = st.sketch(sid.0).ok_or_else(|| DocError::Unknown(format!("sketch {sid}")))?;
// Each curve's exact segments (lines and arcs split by their own plane and cylinder).
let curves: Vec<Vec<solidcraft_geom::Seg2>> = (0..ss.sketch.curves.len())
.filter(|ci| ss.sketch.curves.get(*ci).is_some_and(|c| !c.construction))
.map(|ci| ss.sketch.segs(ci))
.filter(|segs| !segs.is_empty())
.collect();
if curves.is_empty() {
return Err(DocError::Invalid(format!("sketch `{}` has no curves to split with", ss.name)));
}
kernel::split_faces(&mb.body, &picked, &kernel::SplitTool::Curves { plane: ss.plane, curves, along: None })?
}
(None, None) => {
let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?;
kernel::split_faces(&mb.body, &picked, &kernel::SplitTool::Plane(pl))?
}
};
let nb = Traced::step(nb, &[&mb.traced()]);
if let Some(slot) = st.bodies.get_mut(i) {
*slot = ModelBody::traced_new(mb.name, nb, mb.feature);
}
Ok(())
}
FeatureKind::Split { body, plane, tool, sketch, line } => {
let i = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Unknown(format!("body `{body}`"))) };
let input = mb.traced();
let parts = match tool {
// A sketch line: the plane through it along the sketch's normal.
_ if sketch.is_some() || line.is_some() => {
let (Some(sketch), Some(line)) = (sketch, line) else {
return Err(DocError::Invalid("a sketch line tool needs both its sketch and its line".into()));
};
split_by_plane_traced(&input, &sketch_line_plane(st, sketch.0, line)?)?
}
// A face of a body (its surface extended).
Some(t) => {
let tb = st.body(&t.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", t.body)))?;
let face = crate::appearance::face_index_at(tb, t.point.0)
.ok_or_else(|| DocError::Invalid(format!("no face of `{}` at the tool point", t.body)))?;
// The pieces keep the planar roles of the faces they share with the body (#565).
kernel::split_body(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face })?
.into_iter()
.map(|part| Ok(Traced::step(part.with_preserved_planar_sources(&mb.body)?, &[&input])))
.collect::<Result<Vec<_>>>()?
}
None => {
let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?;
split_by_plane_traced(&input, &pl)?
}
};
if parts.len() < 2 {
return Err(DocError::Invalid("the tool does not split the body".into()));
}
let mut it = parts.into_iter();
if let (Some(first), Some(slot)) = (it.next(), st.bodies.get_mut(i)) {
*slot = ModelBody::traced_new(mb.name.clone(), first, mb.feature);
}
for (k, b) in it.enumerate() {
// A piece renamed with `body.rename` keeps its own name (#3510).
let mut name = match f.body_names.get(k).filter(|n| !n.trim().is_empty() && st.body(n).is_none()) {
Some(n) => n.clone(),
None => format!("{} ({})", mb.name, k + 1),
};
while st.body(&name).is_some() {
name.push('\'');
}
st.bodies.push(ModelBody::traced_new(name, b, f.id));
}
Ok(())
}
FeatureKind::Pattern { features, pattern, bodies } => {
let mats = pattern_transforms(doc, vals, st, f.component, pattern)?;
if bodies.is_empty() {
return replay(doc, vals, f, st, features, &mats, warning);
}
// Bodies: each copy is a new body named after its source.
let here = doc.component_transform(f.component);
let mut output = 0;
for n in bodies {
let mb = st.body(n).cloned().ok_or_else(|| DocError::Unknown(format!("body `{n}`")))?;
// A body of another component is held in that component's frame, the pattern's
// transforms in this feature's: each copy is moved as the pattern moves it in the
// world and kept beside its source, in its component (#4763). Taken as they were,
// the copies landed where the source sits before its component is placed.
let owner = (mb.component != f.component).then(|| {
let frame = doc.component_transform(mb.component);
let singular = || DocError::Invalid(format!("the component holding `{n}` has a singular placement"));
Ok::<_, DocError>((frame, crate::mat_inverse(&frame).ok_or_else(singular)?, crate::mat_inverse(&here).ok_or_else(singular)?))
});
let owner = owner.transpose()?;
for (k, m) in mats.iter().enumerate() {
let local = match &owner {
Some((frame, frame_inv, here_inv)) => {
crate::mat_mul(&crate::mat_mul(frame_inv, &here), &crate::mat_mul(&crate::mat_mul(m, here_inv), frame))
}
None => *m,
};
let copy = moved_copy(&mb, kernel::transform_matrix(&mb.body, local)?, k + 1);
let name = pattern_copy_name(st, f, output, &mb.name);
copy_sheet(st, &mb.name, &name, &local);
let mut body = ModelBody::traced_new(name, copy, f.id);
if owner.is_some() {
// Kept in that component as a moved body is (and through later features).
body.component = mb.component;
body.transferred = true;
}
st.bodies.push(body);
output += 1;
}
}
Ok(())
}
FeatureKind::Mirror { features, plane, bodies, combine, placements } => {
let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?;
if bodies.is_empty() {
return replay(doc, vals, f, st, features, &[mirror_matrix(&pl)], warning);
}
let m = mirror_matrix(&pl);
let mut output = 0;
// Copies evaluated on each frame a placement is dragged, which nothing cuts or joins:
// searching their revolved faces again was nearly all that took.
let shown_only = !*combine && !placements.is_empty() && placement_reuse::copies_only_shown(doc, f);
for (k, n) in bodies.iter().enumerate() {
let i = st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")))?;
let Some(mb) = st.bodies.get(i).cloned() else { continue };
// A body picked where a placement shows it is mirrored there: the copy goes beside
// it into the component that placement shows, a joined body stays in its own frame.
let (component, copy, own) = match mirrored_placement(doc, &mb, placements.get(k).map(Vec::as_slice))? {
Some((component, frame, source)) => {
let singular = || DocError::Invalid(format!("the placement `{n}` was mirrored at is singular"));
let inverse = |m: &Mat| crate::mat_inverse(m).ok_or_else(singular);
// The plane is in this feature's component: the body mirrored in the world.
let here = doc.component_transform(f.component);
let world = crate::mat_mul(&crate::mat_mul(&here, &m), &crate::mat_mul(&inverse(&here)?, &source));
(Some(component), crate::mat_mul(&inverse(&frame)?, &world), crate::mat_mul(&inverse(&source)?, &world))
}
None => (None, m, m),
};
let copied = if shown_only {
kernel::place_matrix(&mb.body, copy)
} else {
kernel::transform_matrix(&mb.body, if *combine { own } else { copy })
};
let mirrored = moved_copy(&mb, copied?, 1);
if *combine {
let joined = kernel::boolean(&mb.body, &mirrored.body, BoolOp::Union)?
.ok_or_else(|| DocError::Invalid("the mirror join produced nothing".into()))?;
let joined = Traced::step(joined, &[&mb.traced(), &mirrored]);
let pieces = joined.body.lumps()?;
let lineages = crate::lineage::Lineage::lumps(&joined.body, joined.lineage.as_ref(), &pieces);
for (k, (p, lineage)) in pieces.into_iter().zip(lineages).enumerate() {
if k == 0 {
if let Some(slot) = st.bodies.get_mut(i) {
*slot = ModelBody::new(mb.name.clone(), p, mb.feature).with_lineage(lineage);
}
} else {
let name = copy_body_name(st, f, output, &mb.name);
st.bodies.push(ModelBody::new(name, p, f.id).with_lineage(lineage));
output += 1;
}
}
} else {
let name = copy_body_name(st, f, output, &mb.name);
copy_sheet(st, &mb.name, &name, &copy);
let mut body = ModelBody::traced_new(name, mirrored, f.id);
if !placements.is_empty() {
body.mirrored_mesh = placed_mesh::PlacedMesh::mirrored(&mb, &body.body, &copy).map(Arc::new);
}
if let Some(c) = component.filter(|c| *c != f.component) {
// Kept in that component as a moved body is (and through later features).
body.component = c;
body.transferred = true;
}
st.bodies.push(body);
output += 1;
}
}
Ok(())
}
FeatureKind::Fillet { edges, radius, body, .. } | FeatureKind::Chamfer { edges, distance: radius, body, .. } => {
let r = val(vals, radius, Kind::Length)?;
// A G2 corner is built by the corner construction alone, for a constant radius: any
// other style (or a fitted radius) has no corner patch to repeat.
if let FeatureKind::Fillet { corner: crate::FilletCorner::G2, style, fit, .. } = &f.kind
&& (!matches!(style, crate::FilletStyle::Constant) || !matches!(fit, crate::FilletFit::Exact))
{
return Err(DocError::Invalid("a G2 corner is built for a constant-radius fillet (type: constant, fit: exact) only".into()));
}
// Each edge is found on its own body (picked over several bodies, the edges of each
// are blended on it), all against the bodies as they were before this feature.
// Corner setbacks likewise: SMLib sets back the corners of constant-radius rounds.
if let FeatureKind::Fillet { setbacks, style, fit, .. } = &f.kind
&& !setbacks.is_empty()
&& (!matches!(style, crate::FilletStyle::Constant) || !matches!(fit, crate::FilletFit::Exact))
{
return Err(DocError::Invalid("corner setbacks are built for a constant-radius fillet (type: constant, fit: exact) only".into()));
}
let on = blend_bodies(st, f, body, &crate::plain(edges))?;
let mut groups: Vec<(usize, Vec<usize>)> = Vec::new();
for (i, ti) in on.iter().enumerate() {
match groups.iter_mut().find(|(b, _)| b == ti) {
Some((_, idx)) => idx.push(i),
None => groups.push((*ti, vec![i])),
}
}
let (mut found, mut notes, mut fitted, mut tapered_all) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
let mut reduced = false;
// The kernel blends exactly the edges given: the feature adds each one's tangent
// chain when it asks for it. A radius law runs along one edge, so a variable or
// spline round takes its edge alone.
let chain = match &f.kind {
FeatureKind::Fillet { tangent_chain, style, .. } => {
*tangent_chain && !matches!(style, crate::FilletStyle::Variable { .. } | crate::FilletStyle::Spline { .. })
}
FeatureKind::Chamfer { tangent_chain, .. } => *tangent_chain,
_ => false,
};
let mut blended = Vec::new();
for (ti, idx) in &groups {
let Some(mb) = st.bodies.get(*ti) else { return Err(DocError::Invalid("body".into())) };
let mut w = None;
let edges = blend_edges_on(mb, f, edges, idx, &mut w)?;
let picked = edges.len();
let edges = if chain { kernel::tangent_chain(&mb.body, &edges)? } else { edges };
if let Some(w) = w {
notes.push(w);
}
let mut note = None;
let propagated = edges.len() > picked;
let (nb, used, tapered) =
blend_body(vals, f, mb, &edges, r, &mut note).map_err(|e| if propagated { with_propagation_hint(e) } else { e })?;
if let Some(n) = note {
notes.push(n);
}
reduced |= used.is_some();
fitted.extend(used.unwrap_or_else(|| vec![r; edges.len()]));
tapered_all.extend(tapered);
found.extend(edges);
blended.push((*ti, nb));
}
if !notes.is_empty() {
*warning = Some(notes.join("; "));
}
st.blend_edges.insert(f.id, found);
if reduced {
st.fitted.insert(f.id, fitted);
}
if !tapered_all.is_empty() {
st.tapered.insert(f.id, tapered_all);
}
for (ti, nb) in blended {
if let Some(slot) = st.bodies.get_mut(ti) {
let (name, feat) = (slot.name.clone(), slot.feature);
*slot = ModelBody::traced_new(name, nb, feat);
}
}
Ok(())
}
FeatureKind::Box { corner, length, width, height, operation } => {
let s = Vec3::new(val(vals, length, Kind::Length)?, val(vals, width, Kind::Length)?, val(vals, height, Kind::Length)?);
let corner = point(vals, corner)?;
let b = kernel::box_solid(corner, corner + s)?;
let b = if matches!(operation, Operation::NewBody | Operation::Join) { b.with_box_certificate(f.id)? } else { b };
let handled = more::sheet_primitive_cut(f, st, &b, more::PrimitivePrism::Box { lo: corner, hi: corner + s }, *operation, false, warning)?;
let tools = vec![crate::lineage::box_tool(b)];
if !handled.is_empty() {
return apply_beside_sheet_cut(doc, st, f, tools, *operation, &[], &handled);
}
apply_traced(doc, st, f, tools, *operation, &[])
}
FeatureKind::Cylinder { base, axis, radius, height, operation, .. } => {
let base = cylinder_base(vals, st, f, base, axis.0)?;
let (radius, height) = (val(vals, radius, Kind::Length)?, val(vals, height, Kind::Length)?);
let b = kernel::cylinder(base, axis.0, radius, height)?;
let b = if matches!(operation, Operation::NewBody | Operation::Join) { b.with_cylinder_certificate(f.id)? } else { b };
let prism = more::PrimitivePrism::Cylinder { base, axis: axis.0, radius, height };
let handled = more::sheet_primitive_cut(f, st, &b, prism, *operation, false, warning)?;
let tools = vec![crate::lineage::cylinder_tool(b)];
if !handled.is_empty() {
return apply_beside_sheet_cut(doc, st, f, tools, *operation, &[], &handled);
}
apply_traced(doc, st, f, tools, *operation, &[])
}
FeatureKind::Sphere { center, radius, operation } => {
let b = kernel::sphere(point(vals, center)?, val(vals, radius, Kind::Length)?)?;
apply_op(doc, st, f, vec![b], *operation, &[])
}
FeatureKind::Torus { center, major, minor, operation } => {
let b = kernel::torus(point(vals, center)?, val(vals, major, Kind::Length)?, val(vals, minor, Kind::Length)?)?;
apply_op(doc, st, f, vec![b], *operation, &[])
}
FeatureKind::Cone { base, axis, radius, top_radius, height, operation } => {
let (radius, top_radius, height) =
(val(vals, radius, Kind::Length)?, val(vals, top_radius, Kind::Length)?, val(vals, height, Kind::Length)?);
let b = more::cone(point(vals, base)?, axis.0, radius, top_radius, height)?;
apply_op(doc, st, f, vec![b], *operation, &[])
}
FeatureKind::Combine { target, tools, operation, keep_tools } => {
if tools.iter().any(|t| t == target) {
return Err(DocError::Invalid("a body cannot be combined with itself".into()));
}
// Each body is kept in its own component's frame: a tool placed differently from the
// target is moved into the target's frame, so it is combined where it is shown (#3383).
// A tool placed exactly as the target is left as it is.
let target_world = st.body(target).map(|b| body_world(doc, b));
let mut tb = Vec::new();
for t in tools {
match st.body(t) {
Some(b) => {
let traced = b.traced();
let world = body_world(doc, b);
match target_world.filter(|w| *w != world) {
Some(w) => {
let into_target = crate::mat_inverse(&w)
.ok_or_else(|| DocError::Invalid(format!("`{target}` is placed where it cannot be combined")))?;
let rel = crate::mat_mul(&into_target, &world);
tb.push(Traced::step(kernel::transform_matrix(&b.body, rel)?, &[&traced]));
}
None => tb.push(traced),
}
}
// Designs saved before #2247 combined the pieces a cut split off a body that
// was already several pieces (`Posts`, `Posts (1)`). A cut keeps them in one
// body now: the piece is in `Posts`, which is a tool too or the body joined to.
None => match split_piece_of(t) {
Some(base)
if st.body(base).is_some()
&& (tools.iter().any(|o| **o == *base)
|| (**target == *base && matches!(operation, Operation::Join | Operation::NewBody))) =>
{
append_warning(warning, format!("`{t}` is part of `{base}` now"));
}
_ => return Err(DocError::Unknown(format!("body `{t}`"))),
},
}
}
if st.body(target).is_none() {
return Err(DocError::Unknown(format!("body `{target}`")));
}
if tb.is_empty() && !tools.is_empty() {
return Ok(()); // the pieces were all joined back into the body they are part of
}
let op = if *operation == Operation::NewBody { Operation::Join } else { *operation };
apply_traced(doc, st, f, tb, op, std::slice::from_ref(&target.0))?;
if !keep_tools {
st.bodies.retain(|b| !tools.iter().any(|t| *t == b.name));
}
Ok(())
}
FeatureKind::Scale { bodies, origin, factor, factors } => {
let k = match factors {
Some(fs) => [val(vals, &fs[0], Kind::Unitless)?, val(vals, &fs[1], Kind::Unitless)?, val(vals, &fs[2], Kind::Unitless)?],
None => {
let x = val(vals, factor, Kind::Unitless)?;
[x, x, x]
}
};
if k.iter().any(|x| !(x.is_finite() && *x > 1e-9 && *x < 1e6)) {
return Err(DocError::Invalid("scale factors must be positive".into()));
}
let o = *origin;
// Column-major: scale about the origin.
let m = [
[k[0], 0.0, 0.0, 0.0],
[0.0, k[1], 0.0, 0.0],
[0.0, 0.0, k[2], 0.0],
[o.x * (1.0 - k[0]), o.y * (1.0 - k[1]), o.z * (1.0 - k[2]), 1.0],
];
for n in bodies {
let i = st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")))?;
if let Some(mb) = st.bodies.get_mut(i) {
let nb = Traced::step(kernel::transform_matrix(&mb.body, m)?, &[&mb.traced()]);
*mb = ModelBody::traced_new(mb.name.clone(), nb, mb.feature);
}
}
Ok(())
}
FeatureKind::OffsetFace { faces, distance, body } => {
let d = val(vals, distance, Kind::Length)?;
let i = body_at(st, body, &crate::plain(faces))?;
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) };
let nb = Traced::step(kernel::offset_faces(&mb.body, &crate::plain(faces), d)?, &[&mb.traced()]);
if let Some(slot) = st.bodies.get_mut(i) {
*slot = ModelBody::traced_new(mb.name, nb, mb.feature);
}
Ok(())
}
FeatureKind::DeleteFace { faces, body, heal } => {
let i = body_at(st, body, &crate::plain(faces))?;
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) };
let mut picked: Vec<usize> = Vec::new();
for p in faces {
let fi = crate::appearance::face_index_at(&mb, p.0)
.ok_or_else(|| DocError::Invalid(format!("Delete Face: no face of {} at {p:?}", mb.name)))?;
if !picked.contains(&fi) {
picked.push(fi);
}
}
let all = kernel::with_same_surface(&mb.body, &picked);
let left = if *heal { kernel::delete_faces(&mb.body, &all)? } else { kernel::remove_faces(&mb.body, &all)? };
let nb = Traced::step(left, &[&mb.traced()]);
if let Some(slot) = st.bodies.get_mut(i) {
*slot = ModelBody::traced_new(mb.name, nb, mb.feature);
}
Ok(())
}
FeatureKind::FrameMember { .. } => frame_member::evaluate(doc, vals, f, st),
FeatureKind::BoundingSolid { bodies, margin } => {
let m = val(vals, margin, Kind::Length)?;
let mut bb = solidcraft_geom::Aabb3::EMPTY;
for b in st.bodies.iter().filter(|b| bodies.is_empty() || bodies.iter().any(|t| *t == b.name)) {
bb = bb.union(&b.mesh().bounds());
}
if bb.is_empty() {
return Err(DocError::Invalid("no bodies to bound".into()));
}
let pad = Vec3::new(m, m, m);
let b = crate::lineage::numbered_tool(kernel::box_solid(bb.min - pad, bb.max + pad)?);
let name = unique_body_name(st, f.body_names.first().map(String::as_str).unwrap_or("Bounding"));
st.bodies.push(ModelBody::traced_new(name, b, f.id));
Ok(())
}
FeatureKind::Move { bodies, translate, rotate_axis, angle, copy } => {
let t =
Vec3::new(val(vals, &translate[0], Kind::Length)?, val(vals, &translate[1], Kind::Length)?, val(vals, &translate[2], Kind::Length)?);
let ang = match angle {
Some(a) => val(vals, a, Kind::Angle)?,
None => 0.0,
};
let axis = rotate_axis.map(Vec3::from).unwrap_or(Vec3::Z);
// With `copy` set, the source body is kept in place and the transform lands on a new
// body pushed beside it instead of replacing it.
let mut output = 0;
for n in bodies {
let i = st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")))?;
let Some(mb) = st.bodies.get(i).cloned() else { continue };
let nb = kernel::transform(&mb.body, t, Vec3::ZERO, axis, ang)?;
if *copy {
let traced = moved_copy(&mb, nb, 1);
let name = copy_body_name(st, f, output, &mb.name);
copy_sheet(st, &mb.name, &name, &crate::rigid(t, Vec3::ZERO, axis, ang));
st.bodies.push(ModelBody::traced_new(name, traced, f.id));
output += 1;
} else if let Some(slot) = st.bodies.get_mut(i) {
*slot = ModelBody::traced_new(mb.name.clone(), Traced::step(nb, &[&mb.traced()]), mb.feature);
}
}
if !*copy {
move_constructions_with(doc, st, bodies, &crate::rigid(t, Vec3::ZERO, axis, ang));
}
Ok(())
}
FeatureKind::MeshConvert { body, tolerance } => {
let tolerance = val(vals, tolerance, Kind::Length)?;
let index = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
let source = st.bodies.get(index).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
if doc.model_body_component(source) != f.component {
return Err(DocError::Invalid("activate the mesh body's component before converting it".into()));
}
let converted = kernel::convert_prismatic_mesh(&source.body, tolerance)?;
let converted = converted.with_color(source.body.color());
let result = ModelBody::new(source.name.clone(), converted, f.id);
let target = st.bodies.get_mut(index).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
*target = result;
Ok(())
}
FeatureKind::Repair { body, gap, patch_holes } => {
let gap = val(vals, gap, Kind::Length)?;
let index = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
let source = st.bodies.get(index).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
let (repaired, report) = kernel::repair(&source.body, &kernel::RepairOptions { gap, patch_holes: *patch_holes })?;
let repaired = repaired.with_color(source.body.color());
let result = ModelBody::new(source.name.clone(), repaired, source.feature);
let mut left: Vec<String> =
report.refused.iter().map(|r| format!("SMLib still refuses face {} ({:?}): {}", r.face + 1, r.surface, r.why)).collect();
left.extend(
report
.holes
.iter()
.filter(|h| !h.patched)
.map(|h| h.why.clone().unwrap_or_else(|| format!("a hole of {} edges is left open", h.edges.len()))),
);
if !left.is_empty() {
*warning = Some(left.join("; "));
}
let target = st.bodies.get_mut(index).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
*target = result;
*repair = Some(Arc::new(report));
Ok(())
}
FeatureKind::MeshImport { meshes, .. } => {
for (k, (name, b)) in mesh_bodies(meshes)?.into_iter().enumerate() {
let name = copy_body_name(st, f, k, &name);
st.bodies.push(ModelBody::new(name, b, f.id));
}
Ok(())
}
FeatureKind::Import { step, skip, .. } => {
let imp = kernel::step_import_shared(step)?;
let digest = crate::config::payload_digest(step);
let names = import_body_names(st, &f.body_names, &imp, skip);
for (k, (b, name)) in imp.bodies.iter().zip(names).enumerate() {
let Some(name) = name else { continue };
let carried = f.link_faces.get(k).map_or(&[][..], Vec::as_slice);
let b = crate::lineage::linked_tool(b.body.clone().with_import_certificate(&digest, f.id)?, f.id, carried);
st.bodies.push(ModelBody::traced_new(name, b, f.id));
}
if !imp.warnings.is_empty() {
let n = imp.warnings.len();
let shown: Vec<&str> = imp.warnings.iter().take(3).map(String::as_str).collect();
let more = if n > 3 { format!(" (+{} more)", n - 3) } else { String::new() };
*warning = Some(format!("{}{more}", shown.join("; ")));
*import_report = Some(Arc::new(imp.report.clone()));
}
Ok(())
}
}
}
/// `copy`, a moved copy of `source` (instance `instance` of a pattern or mirror): its faces are
/// named after the source's.
fn moved_copy(source: &ModelBody, copy: Body, instance: usize) -> Traced {
Traced::step(copy, &[&source.before_as(crate::lineage::Operand::Copy { body: source.name.clone(), instance })])
}
/// Mesh bodies of a MeshImport feature.
fn mesh_bodies(meshes: &[crate::MeshData]) -> Result<Vec<(String, Body)>> {
let mut out = Vec::with_capacity(meshes.len());
for m in meshes {
let positions: Vec<Vec3> = m.positions.as_chunks::<3>().0.iter().map(|c| Vec3::new(c[0], c[1], c[2])).collect();
let triangles: Vec<[u32; 3]> = m.triangles.as_chunks::<3>().0.to_vec();
let b = kernel::mesh_body(&positions, &triangles).map_err(|e| DocError::Invalid(format!("mesh `{}`: {e}", m.name)))?;
out.push((m.name.clone(), b.with_color(m.color)));
}
Ok(out)
}
/// The names an Import feature gives the file's bodies, added after the bodies of `st`, in the
/// file's order: `None` for a body it skips (a later instance of a repeated part). `body_names`
/// are the feature's stored names (by index), else the file's own.
pub fn import_body_names(st: &ModelState, body_names: &[String], imp: &kernel::StepImport, skip: &[u64]) -> Vec<Option<String>> {
let skip: std::collections::HashSet<u64> = skip.iter().copied().collect();
// Files from board and assembly tools give thousands of bodies the same name: name them
// from a set, not by searching the bodies for every candidate (cubic).
let mut names = BodyNames::new(st);
imp.bodies
.iter()
.enumerate()
.map(|(k, b)| {
if skip.contains(&(k as u64)) {
return None;
}
let base = body_names.get(k).filter(|n| !n.trim().is_empty()).unwrap_or(&b.name);
Some(names.unique(base))
})
.collect()
}
/// [`unique_body_name`] for many bodies in a row: the same names, in time linear in the bodies.
struct BodyNames {
taken: std::collections::HashSet<String>,
/// The next suffix worth trying for each base (smaller ones are all taken).
next: std::collections::HashMap<String, usize>,
}
impl BodyNames {
fn new(st: &ModelState) -> Self {
BodyNames { taken: st.bodies.iter().map(|b| b.name.clone()).collect(), next: std::collections::HashMap::new() }
}
fn unique(&mut self, base: &str) -> String {
let base = if base.trim().is_empty() { "Body" } else { base.trim() };
if self.taken.insert(base.to_string()) {
return base.to_string();
}
let mut i = self.next.get(base).copied().unwrap_or(2);
let name = loop {
let candidate = format!("{base} ({i})");
i += 1;
if self.taken.insert(candidate.clone()) {
break candidate;
}
};
self.next.insert(base.to_string(), i);
name
}
}
/// `base`, or `base (2)`, `base (3)`… if a body already has that name.
fn unique_body_name(st: &ModelState, base: &str) -> String {
let base = if base.trim().is_empty() { "Body" } else { base.trim() };
if st.body(base).is_none() {
return base.to_string();
}
(2..).map(|i| format!("{base} ({i})")).find(|n| st.body(n).is_none()).unwrap_or_else(|| base.to_string())
}
/// The model as a component sees it: bodies and sketches of components placed differently from
/// it are moved into its frame (through both placements), so a sketch on another component's
/// face finds the face where it is shown and projects its edges there. The model itself when
/// every placement agrees (the usual case).
/// What construction geometry of component `comp` is built on: the model as that component sees
/// it, other components' bodies where they are placed. In the root, every placement of a
/// component (its pasted instances too) is there, as the viewport shows it.
fn construction_state<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> Result<std::borrow::Cow<'a, ModelState>> {
if comp == 0 && !doc.occurrences.is_empty() {
return Ok(std::borrow::Cow::Owned(world_state(doc, st)?));
}
state_in_frame(doc, st, comp)
}
/// Construction axes and points built on bodies a Move moves go with them (#10127): an axis
/// through a cylinder turns with the cylinder, as its faces do. Only those built from the moved
/// bodies alone (`Construct::bodies`) follow; one also held by a fixed point, a plane or another
/// body stays. `m` is the move in the bodies' own frame; each construction is kept in its
/// component's frame (`construction_state`), so the move is carried over into that frame.
fn move_constructions_with(doc: &Document, st: &mut ModelState, moved: &[crate::BodyName], m: &Mat) {
let frame_of = |feature: u64| {
let comp = doc.feature(feature).map(|f| f.component).unwrap_or(0);
if comp == 0 && !doc.occurrences.is_empty() { crate::IDENTITY } else { doc.component_transform(comp) }
};
let world: BTreeMap<&str, Mat> =
st.bodies.iter().filter(|b| moved.iter().any(|n| *n == b.name)).map(|b| (b.name.as_str(), body_world(doc, b))).collect();
let mut placed = Vec::new();
for (k, c) in st.construct.iter().enumerate() {
let Some(body) = c.bodies.first().and_then(|b| world.get(b.as_str())) else { continue };
if !c.bodies.iter().all(|b| world.contains_key(b.as_str())) {
continue;
}
let frame = frame_of(c.feature);
let (Some(body_inv), Some(frame_inv)) = (crate::mat_inverse(body), crate::mat_inverse(&frame)) else { continue };
let in_frame = crate::mat_mul(&crate::mat_mul(&frame_inv, body), &crate::mat_mul(m, &crate::mat_mul(&body_inv, &frame)));
placed.push((k, c.geom.placed(&in_frame)));
}
for (k, geom) in placed {
if let Some(c) = st.construct.get_mut(k) {
c.geom = geom;
}
}
}
/// Whether `plane` is given by the origin planes and numbers alone.
fn plane_is_fixed(plane: &PlaneRef) -> bool {
match plane {
PlaneRef::Origin { .. } | PlaneRef::Custom { .. } | PlaneRef::Placed { .. } => true,
PlaneRef::AtAngle { line: Some(_), .. } => false,
PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane_is_fixed(base),
_ => false,
}
}
/// Whether resolving `plane` reads the model's bodies or sketches (a face, edges, points),
/// rather than only the origin planes, numbers and construction planes.
fn plane_reads_geometry(plane: &PlaneRef) -> bool {
match plane {
PlaneRef::Origin { .. } | PlaneRef::Custom { .. } | PlaneRef::Placed { .. } | PlaneRef::Construction { .. } => false,
PlaneRef::AtAngle { line: Some(_), .. } => true,
PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane_reads_geometry(base),
PlaneRef::ThroughPoint { .. }
| PlaneRef::Midplane { .. }
| PlaneRef::TwoEdges { .. }
| PlaneRef::AxisPoint { .. }
| PlaneRef::ThreePoints { .. }
| PlaneRef::Tangent { .. }
| PlaneRef::AlongPath { .. }
| PlaneRef::Perpendicular { .. }
| PlaneRef::Face { .. } => true,
}
}
/// Where a body's geometry is placed in the world: through its component's placement and any
/// offset it was moved into that component with (as [`state_in_frame_at`] places it).
fn body_world(doc: &Document, mb: &ModelBody) -> Mat {
let m = doc.component_transform(doc.model_body_component(mb));
doc.model_body_offset(mb).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m)
}
thread_local! {
/// While a feature whose tools are drawn in its own component's frame is evaluated: each body
/// placed differently, with the matrix from that frame into the body's own (#3383).
static TOOL_FRAMES: std::cell::RefCell<Vec<(String, Mat)>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Whether a feature joins, cuts or intersects with tools drawn in its own component's frame: a
/// primitive, or a solid built from its sketches. (A combine's tools are bodies, each in its own
/// frame; it moves them itself.)
fn drawn_tools_change_bodies(kind: &FeatureKind) -> bool {
match kind {
FeatureKind::Box { operation, .. }
| FeatureKind::Cylinder { operation, .. }
| FeatureKind::Sphere { operation, .. }
| FeatureKind::Torus { operation, .. }
| FeatureKind::Cone { operation, .. }
| FeatureKind::Extrude { operation, .. }
| FeatureKind::Revolve { operation, .. }
| FeatureKind::Loft { operation, .. }
| FeatureKind::Sweep { operation, .. }
| FeatureKind::Pipe { operation, .. }
| FeatureKind::Coil { operation, .. } => *operation != Operation::NewBody,
_ => false,
}
}
/// The frames of [`TOOL_FRAMES`] for the feature being evaluated; what was there before is put
/// back when it is dropped.
struct ToolFrames(Vec<(String, Mat)>);
impl ToolFrames {
/// For a feature with drawn tools (see [`drawn_tools_change_bodies`]): the bodies placed
/// differently from its component, so its tools meet them where they are shown (#3383).
fn install(doc: &Document, f: &Feature, st: &ModelState) -> Option<ToolFrames> {
if !drawn_tools_change_bodies(&f.kind) || (doc.occurrences.is_empty() && doc.body_offsets.is_empty()) {
return None;
}
let frame = doc.component_transform(f.component);
let frames: Vec<(String, Mat)> = st
.bodies
.iter()
.filter_map(|b| {
let world = body_world(doc, b);
(world != frame).then(|| crate::mat_inverse(&world).map(|inv| (b.name.clone(), crate::mat_mul(&inv, &frame)))).flatten()
})
.collect();
if frames.is_empty() {
return None;
}
Some(ToolFrames(TOOL_FRAMES.with(|t| std::mem::replace(&mut *t.borrow_mut(), frames))))
}
}
impl Drop for ToolFrames {
fn drop(&mut self) {
let before = std::mem::take(&mut self.0);
TOOL_FRAMES.with(|t| *t.borrow_mut() = before);
}
}
/// The matrix taking the evaluated feature's drawn tools into body `name`'s frame (`None`: the
/// same frame).
fn tool_frame(name: &str) -> Option<Mat> {
TOOL_FRAMES.with(|t| t.borrow().iter().find(|(n, _)| n == name).map(|(_, m)| *m))
}
/// The model as the evaluated feature's drawn tools meet it: the bodies it changes (`targets`,
/// else the feature's participants; `*` for all) that are placed differently, moved into its
/// component's frame. A through-all extent, and every test of where a tool meets its targets, is
/// measured on it, so a target in another, moved component is met where it is shown (#3383).
/// The model itself when no such body is placed differently.
fn targets_as_shown<'a>(st: &'a ModelState, f: &Feature, targets: &[String]) -> Result<std::borrow::Cow<'a, ModelState>> {
let names: &[String] = if targets.is_empty() { &f.participants } else { targets };
let all = names.iter().any(|n| n == "*");
let mut out: Option<ModelState> = None;
for (i, b) in st.bodies.iter().enumerate() {
if !(all || names.contains(&b.name)) {
continue;
}
let Some(back) = tool_frame(&b.name).and_then(|m| crate::mat_inverse(&m)) else { continue };
let shown = out.get_or_insert_with(|| st.clone());
let mut moved = ModelBody::new(b.name.clone(), kernel::transform_matrix(&b.body, back)?, b.feature);
moved.component = b.component;
moved.transferred = b.transferred;
moved.names = crate::naming::NameCell::same(b);
if let Some(slot) = shown.bodies.get_mut(i) {
*slot = moved;
}
}
Ok(match out {
Some(shown) => std::borrow::Cow::Owned(shown),
None => std::borrow::Cow::Borrowed(st),
})
}
/// `tool` moved by `m` (unchanged for `None`).
fn tool_in(tool: &Traced, m: Option<Mat>) -> Result<Traced> {
match m {
Some(m) => Ok(Traced::step(kernel::transform_matrix(&tool.body, m)?, &[tool])),
None => Ok(tool.clone()),
}
}
pub fn state_in_frame<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> Result<std::borrow::Cow<'a, ModelState>> {
state_in_frame_at(doc, st, comp, doc.component_transform(comp))
}
/// The model a feature's face points (`FeatureKind::face_points`) are found in. Extrude's To /
/// From and Revolve's To place geometry, so they are kept in the feature's own component frame
/// (`comp`): the model as that component sees it, a target in another, moved component where it
/// is shown (#928). Other face points are picks, kept in the frame of the body they lie on: the
/// model itself.
pub fn face_point_state<'a>(doc: &Document, st: &'a ModelState, kind: &FeatureKind, comp: u64) -> Result<std::borrow::Cow<'a, ModelState>> {
match kind {
FeatureKind::Extrude { .. } | FeatureKind::Revolve { .. } => state_in_frame(doc, st, comp),
_ => Ok(std::borrow::Cow::Borrowed(st)),
}
}
/// The names of the faces a feature's face points lie on (empty where none), found in
/// [`face_point_state`]. A To / From point is named after the nearest face over every body, the
/// one `object_height` resolves it to, not the first body with a face within tolerance: a part
/// resting a hair from the picked face would otherwise take its name. Another feature's point is
/// named on the bodies of the feature's own component first: each component's bodies lie in its
/// own coordinates there, where a part inserted twice has a face at the same point in each.
pub fn face_point_names(doc: &Document, st: &ModelState, kind: &FeatureKind, comp: u64) -> Result<Vec<String>> {
let pts = kind.face_points();
if !matches!(kind, FeatureKind::Extrude { .. } | FeatureKind::Revolve { .. }) {
let own = ModelState { bodies: st.bodies.iter().filter(|b| doc.model_body_component(b) == comp).cloned().collect(), ..ModelState::default() };
let names = crate::naming::face_names_at(&own, &pts);
return Ok(names
.into_iter()
.zip(&pts)
.map(|(name, p)| if name.is_empty() { crate::naming::face_names_at(st, std::slice::from_ref(p)).pop().unwrap_or_default() } else { name })
.collect());
}
let fst = face_point_state(doc, st, kind, comp)?;
let normal = match kind {
FeatureKind::Extrude { sketch, .. } => {
st.sketch(sketch.0).and_then(|ss| sketch_in_feature_frame(doc, ss, comp).ok()).map(|ss| ss.plane.normal())
}
_ => None,
};
Ok(pts
.iter()
.map(|p| {
fst.bodies
.iter()
.filter(|b| !b.body.is_mesh())
.filter_map(|b| {
let (d, fi) = nearest_object_face(b, *p, normal)?;
(d <= (b.body.size() * 1e-3).max(1e-3)).then_some((d, b, fi))
})
.min_by(|a, b| a.0.total_cmp(&b.0))
.and_then(|(_, b, fi)| crate::naming::face_names(b).get(fi).cloned())
.unwrap_or_default()
})
.collect())
}
/// As `state_in_frame`, using the exact active placement for its shared source geometry.
pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, frame: Mat) -> Result<std::borrow::Cow<'a, ModelState>> {
use std::borrow::Cow;
if doc.occurrences.is_empty() && doc.body_offsets.is_empty() {
return Ok(Cow::Borrowed(st));
}
let inv = crate::mat_inverse(&frame).ok_or_else(|| DocError::Invalid(format!("component {comp}'s frame cannot be inverted")))?;
let comp_of_feature = |id: u64| doc.feature(id).map(|f| f.component).unwrap_or(0);
let rel = |c: u64, body: Option<&str>| {
let m = crate::mat_mul(&inv, &if c == comp { frame } else { doc.component_transform(c) });
match body.and_then(|b| doc.body_offsets.get(b)) {
Some(o) => crate::mat_mul(&m, o),
None => m,
}
};
let body_m: Vec<Mat> = st
.bodies
.iter()
.map(|b| {
let m = rel(doc.model_body_component(b), None);
doc.model_body_offset(b).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m)
})
.collect();
let sketch_m: Vec<Mat> = st.sketches.iter().map(|s| rel(comp_of_feature(s.feature), None)).collect();
let world_wires_need_mapping = !crate::is_identity(&inv)
&& st.sketches.iter().any(|sketch| sketch.sketch.wires.iter().any(|wire| wire.space == solidcraft_sketch::WireSpace::World));
if body_m.iter().chain(&sketch_m).all(crate::is_identity) && !world_wires_need_mapping {
return Ok(Cow::Borrowed(st));
}
let mut out = st.clone();
for (b, m) in out.bodies.iter_mut().zip(&body_m) {
if !crate::is_identity(m) {
let moved = st.body_in_frame(b, m).map_err(|e| DocError::Invalid(format!("body `{}` cannot be moved into the frame: {e}", b.name)))?;
*b = moved;
}
}
for (s, m) in out.sketches.iter_mut().zip(&sketch_m) {
// Only a sketch the frame moves is copied.
let maps_wire = |w: &solidcraft_sketch::Wire| !crate::is_identity(if w.space == solidcraft_sketch::WireSpace::Component { m } else { &inv });
if crate::is_identity(m) && !s.sketch.wires.iter().any(maps_wire) {
continue;
}
let s = Arc::make_mut(s);
if !crate::is_identity(m) {
s.plane = placed_plane(m, &s.plane)?;
}
for wire in &mut s.sketch.wires {
let matrix = if wire.space == solidcraft_sketch::WireSpace::Component { m } else { &inv };
map_wire(wire, matrix);
}
}
Ok(Cow::Owned(out))
}
/// The model placed in the world: each component's bodies, sketches, threads and construction
/// geometry through every occurrence of it (bodies of the first placement keep their names;
/// further instances get the occurrence path in brackets). Without components this is the model
/// itself.
pub fn world_state(doc: &Document, st: &ModelState) -> Result<ModelState> {
world_state_reusing(doc, st, &mut PlacedBodies::default())
}
/// Bodies a [`world_state_reusing`] call placed away from their definition (a moved
/// component's bodies), by their definition and placement: the next call reuses each one whose
/// definition and placement are unchanged instead of transforming it again, and so keeps its
/// display mesh. Without this every change anywhere in a design transformed and meshed every
/// body of every moved component again.
#[derive(Debug, Default)]
pub struct PlacedBodies {
by_source: std::collections::HashMap<(usize, [u64; 16]), (ModelBody, ModelBody)>,
}
impl PlacedBodies {
fn reused(&self, b: &ModelBody, m: &crate::Mat) -> Option<&ModelBody> {
self.by_source
.get(&placed_key(b, m))
.filter(|(source, _)| {
Arc::ptr_eq(&source.mesh, &b.mesh)
&& source.body.same(&b.body)
&& source.body.color() == b.body.color()
&& source.body.paint() == b.body.paint()
&& match (source.body.split_lines(), b.body.split_lines()) {
(Some(x), Some(y)) => Arc::ptr_eq(x, y),
(None, None) => true,
_ => false,
}
})
.map(|(_, placed)| placed)
}
/// The body `b` placed by `m`, from an earlier call when `b` is the same body as then; an
/// error when it cannot be placed.
fn placed(&self, b: &ModelBody, m: &crate::Mat, name: String) -> Result<ModelBody> {
if let Some(placed) = self.taken(b, m, &name) {
return Ok(placed);
}
// The identity places the body as it is, without a copy through the kernel.
let body = if crate::is_identity(m) {
b.body.clone()
} else {
kernel::place_matrix(&b.body, *m).map_err(|e| DocError::Invalid(format!("body `{}` cannot be placed: {e}", b.name)))?
};
let mut fresh = ModelBody::new(name, body, b.feature);
fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new);
Ok(fresh)
}
/// The body `b` placed by `m` as an earlier call placed it, when `b` is the same body as then.
fn taken(&self, b: &ModelBody, m: &crate::Mat, name: &str) -> Option<ModelBody> {
self.reused(b, m).map(|placed| {
let mut fresh = ModelBody::new(name.to_string(), placed.body.clone(), b.feature);
fresh.mesh = placed.mesh.clone();
fresh.measured = placed.measured.clone();
fresh.mesh_placement = placed.mesh_placement.clone();
fresh.plan = placed.plan.clone();
fresh.plan_mesh = placed.plan_mesh.clone();
fresh
})
}
}
/// Bodies [`state_in_frame_at`] moved into a feature's frame, by source body and matrix: a
/// sketch on a face of a turned component is evaluated in that component's frame, and without
/// this every edit of it moved (and so meshed again) every body placed differently from it.
/// Held by the [`Model`] across evaluations; each `evaluate` that moves a body starts a new
/// generation, and an entry neither it nor the last such evaluation before it used is dropped,
/// so the cache holds only the placements in use. An evaluation that moves nothing (every
/// result reused, or taken from the cache: an undo, the refreshes a command makes after its
/// edit) leaves the generations alone: counting it, two of them in a row dropped every moved
/// body, and the next edit of the sketch moved and meshed them all again.
#[derive(Debug, Default)]
pub(crate) struct FrameBodies {
now: PlacedBodies,
before: PlacedBodies,
/// An evaluation began and has not used the cache yet: its first use starts the generation.
pending: bool,
}
impl FrameBodies {
/// At most this many bodies are kept per generation.
const CAP: usize = 4096;
/// An evaluation begins; its generation starts when it first moves a body.
pub(crate) fn next_generation(&mut self) {
self.pending = true;
}
fn begin(&mut self) {
if std::mem::take(&mut self.pending) {
self.before = std::mem::take(&mut self.now);
}
}
/// The moved body for `b` under `m`, when a call in this or the previous generation moved
/// the same body by the same matrix.
fn reused(&mut self, b: &ModelBody, m: &crate::Mat) -> Option<ModelBody> {
self.begin();
if let Some(placed) = self.now.reused(b, m) {
return Some(placed.clone());
}
let placed = self.before.reused(b, m)?.clone();
let key = placed_key(b, m);
if let Some(entry) = self.before.by_source.remove(&key)
&& self.now.by_source.len() < Self::CAP
{
self.now.by_source.insert(key, entry);
}
Some(placed)
}
fn keep(&mut self, b: &ModelBody, m: &crate::Mat, moved: &ModelBody) {
self.begin();
if self.now.by_source.len() < Self::CAP {
self.now.by_source.insert(placed_key(b, m), (b.clone(), moved.clone()));
}
}
}
/// `b` in a feature's frame: `placed` (its geometry moved by `m`, sharing the moved body's
/// mesh and display plan), carrying `b`'s ownership and naming.
fn in_frame(b: &ModelBody, m: &crate::Mat, placed: &ModelBody) -> ModelBody {
let mut moved = ModelBody::new(b.name.clone(), placed.body.clone(), b.feature);
moved.mesh = placed.mesh.clone();
moved.plan = placed.plan.clone();
moved.plan_mesh = placed.plan_mesh.clone();
moved.component = b.component;
moved.transferred = b.transferred;
moved.source_name = b.source_name.clone();
moved.source_transform = crate::mat_mul(m, &b.source_transform);
moved.imported = b.imported.clone();
// Moving a body keeps its faces (and their order): it keeps their names.
moved.names = crate::naming::NameCell::same(b);
moved
}
fn placed_key(b: &ModelBody, m: &crate::Mat) -> (usize, [u64; 16]) {
let mut bits = [0u64; 16];
for (slot, v) in bits.iter_mut().zip(m.iter().flatten()) {
*slot = v.to_bits();
}
(Arc::as_ptr(&b.mesh) as usize, bits)
}
/// Whether a world state shows `b`, placed by `m`, apart from the model's body. A mirrored copy
/// always is: it is drawn from its source's opposite hand, and the model keeps its own triangles.
fn placed_apart(b: &ModelBody, m: &crate::Mat) -> bool {
!crate::is_identity(m) || b.mirrored_mesh.is_some()
}
/// [`world_state`], reusing the bodies `placed` holds from an earlier call and leaving it holding
/// this call's.
pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut PlacedBodies) -> Result<ModelState> {
if doc.occurrences.is_empty() {
return Ok(st.clone());
}
let mut placed_now = PlacedBodies::default();
// Looked up once: every sketch, construction and tap asked the timeline, and every placement
// went through all bodies, each time searching (a large assembly paid this every command).
let feature_components: std::collections::HashMap<u64, u64> = doc.features.iter().rev().map(|f| (f.id, f.component)).collect();
let comp_of_feature = |id: u64| feature_components.get(&id).copied().unwrap_or(0);
let first_path = |comp: u64| -> Vec<u64> {
let mut path = Vec::new();
let mut c = comp;
for _ in 0..1000 {
if c == 0 {
break;
}
let Some(o) = doc.occurrence_of(c) else { break };
path.insert(0, o.id);
c = o.parent;
}
path
};
let mut out = ModelState { body_counter: st.body_counter, ..Default::default() };
let placements = doc.placements();
// A body moved in from another component keeps its place (its offset).
let body_matrix = |b: &ModelBody, m: &crate::Mat| doc.model_body_offset(b).map(|o| crate::mat_mul(m, o)).unwrap_or(*m);
// Every body placed elsewhere than its definition, placed on all cores: a large assembly
// places hundreds of parts, each a B-rep transform.
let mut jobs = Vec::new();
let owners = doc.model_body_components(st);
let names = crate::WorldNames::new(doc, st);
let mut by_component: std::collections::HashMap<u64, Vec<&ModelBody>> = std::collections::HashMap::new();
for (b, owner) in st.bodies.iter().zip(&owners) {
by_component.entry(*owner).or_default().push(b);
}
let bodies_of = |comp: u64| by_component.get(&comp).into_iter().flatten().copied();
// Each tap's component and the offset of the body it is on (the first body of that name).
let mut first_body: std::collections::HashMap<&str, (&ModelBody, u64)> = std::collections::HashMap::new();
for (b, owner) in st.bodies.iter().zip(&owners).rev() {
first_body.insert(b.name.as_str(), (b, *owner));
}
let tap_frames: Vec<(u64, Option<&crate::Mat>)> = st
.threads
.iter()
.map(|t| match first_body.get(t.body.as_str()) {
Some((body, owner)) => (*owner, doc.model_body_offset(body)),
None => (comp_of_feature(t.feature), None),
})
.collect();
for (comp, path, m) in &placements {
for b in bodies_of(*comp) {
let bm = body_matrix(b, m);
if placed_apart(b, &bm) {
jobs.push((b, bm, names.name(&b.name, *comp, path)));
}
}
}
// Bodies placed as before are taken here: starting threads only to copy them cost every
// command in a design with placed components more than the copies.
let reused: Vec<_> = jobs.iter().map(|(b, bm, name)| placed_before.taken(b, bm, name)).collect();
let fresh: Vec<_> = jobs.iter().zip(&reused).filter(|(_, r)| r.is_none()).map(|(job, _)| job).collect();
let mut placed_fresh = kernel::map_on_threads(&fresh, 16, |(b, bm, name)| placed_before.placed(b, bm, name.clone())).into_iter();
let mut moved = reused.into_iter().map(|r| match r {
Some(placed) => Some(Ok(placed)),
None => placed_fresh.next().flatten(),
});
for (comp, path, m) in placements {
let primary = path == first_path(comp);
let ident = crate::is_identity(&m);
for b in bodies_of(comp) {
let bm = body_matrix(b, &m);
// Identical geometry also shares its display mesh cell with the definition.
// A changed placement keeps a distinct mesh, at that placement's coordinates.
let mut placed = if !placed_apart(b, &bm) {
let mut placed = b.clone();
placed.name = names.name(&b.name, comp, &path);
placed
} else {
// The same order as the jobs: this body's, made above.
let placed = match moved.next() {
Some(Some(placed)) => placed?,
Some(None) => return Err(DocError::Invalid(format!("body `{}` could not be placed (its worker failed)", b.name))),
None => return Err(DocError::Invalid(format!("body `{}` has no placement", b.name))),
};
placed_now.by_source.insert(placed_key(b, &bm), (b.clone(), placed.clone()));
placed
};
// World states keep their previous display-only evaluation-key semantics.
placed.key = 0;
// With the model body's own frame, so its place is told apart from the placement's.
placed.source_key = b.geometry_key().unwrap_or(0);
placed.source_name = Some(b.definition_name().to_string());
placed.source_transform = crate::mat_mul(&bm, &b.source_transform);
placed.component = comp;
placed.transferred = b.transferred;
placed.imported = b.imported.clone();
// Placement preserves topology: face ownership remains that of the
// source model, including modifiers on component instances.
placed.names = crate::naming::NameCell::same(b);
out.bodies.push(placed);
}
if primary {
for s in st.sketches.iter().filter(|s| comp_of_feature(s.feature) == comp) {
if ident {
// In place: shared as it is.
out.sketches.push(s.clone());
continue;
}
let mut s2 = SolvedSketch::clone(s);
s2.plane = placed_plane(&m, &s.plane)?;
for wire in &mut s2.sketch.wires {
if wire.space == solidcraft_sketch::WireSpace::Component {
map_wire(wire, &m);
}
}
out.sketches.push(Arc::new(s2));
}
// The component's construction planes, axes and points where it is placed: once the
// design has a component the root's constructions are built in this state
// (`construction_state`), and one built on another finds it here by name.
for c in st.construct.iter().filter(|c| comp_of_feature(c.feature) == comp) {
let geom = if ident { c.geom.clone() } else { c.geom.placed(&m) };
out.construct.push(crate::construct::Construct { geom, ..c.clone() });
}
}
// Unlike editable sketch guides, cosmetic surfaces belong to every occurrence.
for (t, (_, offset)) in st.threads.iter().zip(&tap_frames).filter(|(_, (owner, _))| *owner == comp) {
let mut t2 = t.clone();
t2.body = names.name(&t.body, comp, &path);
let frame = offset.map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m);
t2.axis_point = crate::apply_point(&frame, t.axis_point);
t2.axis = crate::apply_vector(&frame, *t.axis).unit().ok_or_else(|| DocError::Invalid("a thread's axis cannot be placed".into()))?;
out.threads.push(t2);
}
}
*placed_before = placed_now;
Ok(out)
}
/// `plane` moved by the placement `m`; an error when `m` does not keep it a plane (a placement
/// that is not a rigid motion, which [`Document`] does not take).
fn placed_plane(m: &crate::Mat, plane: &Plane) -> Result<Plane> {
Plane::new(crate::apply_point(m, plane.origin), crate::apply_vector(m, plane.x), crate::apply_vector(m, plane.y))
.ok_or_else(|| DocError::Invalid("a sketch plane cannot be placed: the placement is not a rigid motion".into()))
}
#[cfg(test)]
mod display_preparation_tests {
use super::*;
fn state() -> ModelState {
let body = kernel::box_solid(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0)).unwrap();
ModelState { bodies: vec![ModelBody::new("Box".into(), body, 1)], ..Default::default() }
}
#[test]
fn prepared_display_reads_all_three_caches_without_cold_geometry_or_quality_changes() {
use crate::display_quality::{DisplayQuality, current};
let state = state();
let body = &state.bodies[0];
let quality = DisplayQuality::Fine;
let index = quality.index();
let current = current();
let tolerance = body.display_tol();
assert!(body.mesh.get().is_none() && body.plan[index].get().is_none() && body.plan_mesh[index].get().is_none());
state.warm_display_at(quality, || true);
// Inspect the caches before invoking any consumer that could initialize them.
let reference = body.mesh.get().unwrap();
let plan = body.plan[index].get().unwrap().as_ref().unwrap();
let display = body.plan_mesh[index].get().unwrap().as_ref().unwrap();
assert!(Arc::ptr_eq(reference, &body.mesh()));
assert!(Arc::ptr_eq(plan, &body.display_plan_at(quality).unwrap()));
assert!(Arc::ptr_eq(display, &body.plan_mesh_at(quality).unwrap()));
assert_eq!(crate::display_quality::current(), current);
assert_eq!(body.display_tol(), tolerance);
for other in DisplayQuality::ALL.into_iter().filter(|other| *other != quality) {
assert!(body.plan[other.index()].get().is_none() && body.plan_mesh[other.index()].get().is_none());
}
}
#[test]
fn cancelled_display_preparation_leaves_cold_caches_untouched() {
let state = state();
state.warm_display_at(crate::display_quality::DisplayQuality::Normal, || false);
let body = &state.bodies[0];
assert!(body.mesh.get().is_none());
assert!(body.plan.iter().all(|slot| slot.get().is_none()));
assert!(body.plan_mesh.iter().all(|slot| slot.get().is_none()));
}
}
#[cfg(test)]
mod world_placement_cache_tests {
use super::*;
#[test]
fn placed_real_feature_retains_names_from_its_original_feature_context() {
let mut doc = Document::new("authored names");
let component = doc.add_component(Some("Part"), 0).unwrap();
let feature = doc
.add_feature(
FeatureKind::Box {
corner: crate::point_expr(Vec3::ZERO),
length: "2 mm".into(),
width: "3 mm".into(),
height: "4 mm".into(),
operation: crate::Operation::NewBody,
},
Some("AuthoredBox"),
)
.unwrap();
doc.feature_mut(feature).unwrap().component = component;
let matrix = crate::rigid(Vec3::new(15., -2., 8.), Vec3::ZERO, Vec3::X, 0.7);
doc.occurrences.iter_mut().find(|o| o.component == component).unwrap().transform = matrix;
let mut model = Model::default();
model.evaluate(&doc);
let state = model.state();
let source = &state.bodies[0];
assert!(source.names.origin.is_some());
assert!(source.mesh.get().is_none());
let world = world_state(&doc, &state).unwrap();
let names = crate::naming::face_names(&world.bodies[0]);
assert!(Arc::ptr_eq(&names, &crate::naming::face_names(source)));
assert!(names.iter().all(|name| name.starts_with(&format!("F{feature}:"))));
let local = source.mesh();
let placed = world.bodies[0].mesh();
assert_eq!(local.tri_face, placed.tri_face);
let mapped: Vec<_> = local.positions.iter().map(|p| crate::apply_point(&matrix, *p)).collect();
assert!(mapped.iter().all(|p| placed.positions.iter().any(|q| p.dist(*q) < 1e-8)));
assert!(placed.positions.iter().all(|p| mapped.iter().any(|q| p.dist(*q) < 1e-8)));
}
#[test]
fn identity_shares_mesh_but_rotated_instances_keep_distinct_physical_coordinates_and_source_names() {
let mut doc = Document::new("placements");
let component = doc.add_component(Some("Part"), 0).unwrap();
doc.body_components.insert("Block".into(), component);
let matrix = crate::rigid(Vec3::new(10., 20., 0.), Vec3::ZERO, Vec3::Z, std::f64::consts::FRAC_PI_2);
let second = doc.add_occurrence(component, 0, matrix).unwrap();
let mut state = ModelState::default();
state.bodies.push(ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(), 1));
state.bodies[0].key = 1234;
let source = &state.bodies[0];
let world = world_state(&doc, &state).unwrap();
assert_eq!(world.bodies.len(), 2);
let first = world.body("Block").unwrap();
let second_name = doc.world_body_name(&state, "Block", component, &[second]);
let placed = world.body(&second_name).unwrap();
assert!(Arc::ptr_eq(&source.mesh, &first.mesh), "unchanged geometry must retain the shared display mesh cell");
assert_eq!(first.key, 0);
assert_eq!(placed.key, 0);
// Each placement has its own geometry identity, for work measured on it.
assert!(first.geometry_key().is_some() && first.geometry_key() != placed.geometry_key());
assert!(!Arc::ptr_eq(&source.mesh, &placed.mesh), "a transformed mesh cannot be reused without mapping coordinates");
assert_eq!(first.source_name.as_deref(), Some("Block"));
assert_eq!(placed.source_name.as_deref(), Some("Block"));
assert_eq!(placed.source_transform, matrix);
assert_eq!(doc.model_body_component(placed), component);
let bounds = placed.mesh().bounds();
assert!(bounds.min.dist(Vec3::new(7., 20., 0.)) < 1e-9);
assert!(bounds.max.dist(Vec3::new(10., 22., 4.)) < 1e-9);
let names = crate::naming::face_names(source);
assert!(Arc::ptr_eq(&names, &crate::naming::face_names(first)));
assert!(Arc::ptr_eq(&names, &crate::naming::face_names(placed)));
let original_mesh = source.mesh();
assert!(Arc::ptr_eq(&original_mesh, &first.mesh()));
let again = world_state(&doc, &state).unwrap();
assert!(Arc::ptr_eq(&original_mesh, &again.body("Block").unwrap().mesh()));
assert!(Arc::ptr_eq(&names, &crate::naming::face_names(again.body(&second_name).unwrap())));
}
}
#[cfg(test)]
mod chain_tests {
use super::*;
/// The top face of a box with one rounded top edge chains to the round and on to the side
/// it rolls into; the other sides meet at sharp edges and stay out.
#[test]
fn tangent_chain_follows_smooth_edges() {
let mut doc = Document::new("T");
doc.add_feature(
FeatureKind::Box {
corner: crate::point_expr(Vec3::ZERO),
length: "40".into(),
width: "30".into(),
height: "20".into(),
operation: Operation::NewBody,
},
None,
)
.unwrap();
doc.add_feature(
FeatureKind::Fillet {
edges: vec![crate::Position(Vec3::new(20.0, 0.0, 20.0))],
radius: "4".into(),
body: None,
style: crate::FilletStyle::Constant,
fit: Default::default(),
corner: Default::default(),
setbacks: Vec::new(),
tangent_chain: true,
},
None,
)
.unwrap();
let mut m = Model::new();
m.evaluate(&doc);
let st = m.state();
let b = &st.bodies[0];
let pts = tangent_face_chain(b, &[Vec3::new(20.0, 15.0, 20.0)]);
let faces: std::collections::BTreeSet<usize> = pts.iter().map(|(index, _)| *index).collect();
assert_eq!(faces.len(), 3, "{faces:?}");
assert_eq!(pts.len(), faces.len());
for (index, point) in &pts {
assert_eq!(crate::appearance::face_index_at(b, *point), Some(*index));
}
assert_eq!(tangent_face_chain(b, &[Vec3::new(20.0, 15.0, 20.0); 2]), pts);
}
fn fillet(at: Vec3, radius: &str, tangent_chain: bool) -> FeatureKind {
FeatureKind::Fillet {
edges: vec![crate::Position(at)],
radius: radius.into(),
body: None,
style: crate::FilletStyle::Constant,
fit: Default::default(),
corner: Default::default(),
setbacks: Vec::new(),
tangent_chain,
}
}
/// A 20 box's top edge along y rounded r2, then the top front edge (along x) rounded r3: that
/// edge runs on tangentially into the round's end arc, so by default (tangent propagation)
/// the arc is rounded with it, which an r3 round on an r2 arc cannot be: refused, saying that
/// propagation blended the chain and how to blend the edge alone. With propagation off the
/// edge is rounded alone, ending on the r2 round.
#[test]
fn a_propagated_chain_that_cannot_build_says_how_to_blend_the_edge_alone() {
let build = |chain: bool| {
let mut doc = Document::new("T");
let solid = FeatureKind::Box {
corner: crate::point_expr(Vec3::ZERO),
length: "20".into(),
width: "20".into(),
height: "20".into(),
operation: Operation::NewBody,
};
doc.add_feature(solid, None).unwrap();
doc.add_feature(fillet(Vec3::new(20.0, 10.0, 20.0), "2", true), None).unwrap();
let last = doc.add_feature(fillet(Vec3::new(10.0, 0.0, 20.0), "3", chain), None).unwrap();
let mut m = Model::new();
m.evaluate(&doc);
(m.result(last).and_then(|r| r.error.clone()), m.state().bodies.first().map(|b| b.body.face_count()))
};
let (on, _) = build(true);
let on = on.expect("the propagated chain is refused");
assert!(on.contains("with it off, tangent_chain: false, only the picked edges are blended"), "{on}");
let (off, faces) = build(false);
assert_eq!(off, None);
assert_eq!(faces, Some(8));
}
}
#[cfg(test)]
#[path = "eval_cost_tests.rs"]
pub(crate) mod cost_tests;
#[cfg(test)]
mod body_name_tests {
use super::*;
/// Imported bodies get the names one-at-a-time naming gives them, in time linear in the
/// bodies: a board file with thousands of same-named parts once took minutes (#883).
#[test]
fn many_same_named_bodies_are_named_in_linear_time() {
let mut st = ModelState::default();
let body = kernel::box_solid(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0)).unwrap();
for name in ["R", "R (3)", "C"] {
st.bodies.push(ModelBody::new(name.into(), body.clone(), 1));
}
// The same names as asking the bodies one at a time.
let mut names = BodyNames::new(&st);
let mut slow = st.clone();
for base in ["R", "R", "C", " ", "Body", "R", "R (2)", "X"] {
let expected = unique_body_name(&slow, base);
assert_eq!(names.unique(base), expected);
slow.bodies.push(ModelBody::new(expected, body.clone(), 2));
}
// 50,000 parts named alike: milliseconds (one-at-a-time naming would take hours).
let began = std::time::Instant::now();
let mut names = BodyNames::new(&ModelState::default());
let last = (0..50_000).map(|_| names.unique("R_0603")).last().unwrap();
assert_eq!(last, "R_0603 (50000)");
assert!(began.elapsed() < std::time::Duration::from_secs(5), "{:?}", began.elapsed());
}
}
/// The parts of a body split by a plane, on its positive side first (only the non-empty ones).
/// Each part's cut face is named `section` after the half-space box that cut it, so it takes an
/// attachment that follows the plane (#565); the box's other faces never reach the part.
fn split_by_plane_traced(input: &Traced, plane: &Plane) -> Result<Vec<Traced>> {
let mut parts = Vec::new();
for positive in [true, false] {
let (part, tool) = kernel::half_space(&input.body, plane, positive)?;
let Some(part) = part else { continue };
// The box's cap in the plane: its start cap on the positive side, its end cap on the other.
let section = Some("section".to_string());
let caps = if positive { [section, None] } else { [None, section] };
let tool = crate::lineage::ProfileRoles { sketch: None, region: None, caps, thin: None }.tool(tool, None);
parts.push(Traced::step(part, &[input, &tool]));
}
Ok(parts)
}
/// The plane a straight sketch line sweeps along its sketch's normal: through the line, its x
/// along the line and its y along the normal (a Split Body tool, #1552).
pub fn sketch_line_plane(st: &ModelState, sketch: u64, line: &str) -> Result<Plane> {
let ss = st.sketch(sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?;
let ci = ss.sketch.curve_index(line).ok_or_else(|| DocError::Unknown(format!("curve `{line}`")))?;
let (a, b) = match ss.sketch.segs(ci).as_slice() {
[solidcraft_geom::Seg2::Line { a, b }] => (*a, *b),
_ => return Err(DocError::Invalid(format!("`{line}` is not a straight line: split by a sketch line"))),
};
let (wa, wb) = (ss.plane.to_world(a), ss.plane.to_world(b));
let x = (wb - wa).normalized().ok_or_else(|| DocError::Invalid(format!("`{line}` has no length")))?;
Ok(Plane { origin: wa, x, y: ss.plane.normal() })
}
#[cfg(test)]
mod named_face_lookup_tests {
use super::*;
use crate::naming::FaceHit;
/// A row of `n` 10 mm cubes `Part0`, `Part1`… 20 mm apart along x, without history: their
/// faces are named from geometry, which meshes them.
fn parts(n: usize) -> ModelState {
let mut st = ModelState::default();
for i in 0..n {
let x = 20.0 * i as f64;
let cube = kernel::box_solid(Vec3::new(x, 0.0, 0.0), Vec3::new(x + 10.0, 10.0, 10.0)).unwrap();
st.bodies.push(ModelBody::new(format!("Part{i}"), cube, 1));
}
st
}
/// The name of the face of `body` at `p`.
fn name_at(st: &ModelState, body: &str, p: Vec3) -> String {
let b = st.body(body).unwrap();
let face = crate::appearance::face_index_at(b, p).unwrap();
crate::naming::face_names(b)[face].clone()
}
/// Everything a lookup found, to compare two lookups.
fn found(hit: Option<FaceHit>) -> String {
format!("{hit:?}")
}
/// A shell late in a long timeline spent seconds meshing every body of the model to find its
/// face by name (#287). A feature that names its body finds the face there without naming
/// the other bodies, and finds what looking over every body finds.
#[test]
fn a_face_is_found_on_the_body_the_feature_names_without_meshing_the_others() {
let st = parts(12);
let top = Vec3::new(145.0, 5.0, 10.0);
let name = name_at(&st, "Part7", top);
let hit = crate::name_lookup::locate_face_on_body(&st, Some("Part7"), &name, top);
for b in st.bodies.iter().filter(|b| b.name != "Part7") {
assert!(b.mesh.get().is_none(), "{} was meshed", b.name);
}
let h = hit.unwrap();
assert_eq!(h.body, 7);
assert_eq!(found(hit), found(crate::naming::locate_face(&st, &name, top)));
// Looking over every body names (and so meshes) them all.
assert!(st.bodies.iter().all(|b| b.mesh.get().is_some()));
}
/// A name the named body has no face of (it moved to another body: a combine took the face),
/// a body that is not there, no body, a name saved before format 14 or a name no face has:
/// looked for over every body, as without a body.
#[test]
fn a_name_not_on_the_named_body_is_looked_for_over_every_body() {
let st = parts(4);
let top = Vec3::new(45.0, 5.0, 10.0);
let name = name_at(&st, "Part2", top);
for name in [name.clone(), format!("{}{name}", crate::naming::LEGACY_MARK), "Part2:face:99".into()] {
let everywhere = found(crate::naming::locate_face(&st, &name, top));
for body in [Some("Part1"), Some("Part2"), Some("Nope"), None] {
assert_eq!(found(crate::name_lookup::locate_face_on_body(&st, body, &name, top)), everywhere, "{name} on {body:?}");
}
}
let moved = crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, top).unwrap();
assert_eq!(moved.body, 2);
}
/// A copy of a body has its source's face names. Over every body the name finds the face on
/// both, and takes the one the point lies on; a point on neither finds no face (it is never
/// told apart by the nearest). A feature on the copy takes the copy's face.
#[test]
fn the_same_face_on_a_copy_is_not_a_piece_of_the_named_bodys_face() {
let mut st = parts(2);
let source = st.bodies[0].clone();
st.bodies[1].names = crate::naming::NameCell::same(&source);
let top = Vec3::new(25.0, 5.0, 10.0);
let name = name_at(&st, "Part1", top);
assert_eq!(name, name_at(&st, "Part0", Vec3::new(5.0, 5.0, 10.0)));
let on_copy = crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, top).unwrap();
let everywhere = crate::naming::locate_face(&st, &name, top).unwrap();
assert_eq!((on_copy.body, on_copy.face, on_copy.point), (everywhere.body, everywhere.face, everywhere.point));
assert_eq!(on_copy.note(&name), None);
assert!(crate::naming::locate_face(&st, &name, Vec3::new(15.0, 5.0, 30.0)).is_none());
assert_eq!(crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, Vec3::new(15.0, 5.0, 30.0)).map(|hit| hit.body), Some(1));
}
}