ea772a0438
* 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>
3563 lines
192 KiB
Rust
3563 lines
192 KiB
Rust
//! Solid feature commands: extrude, revolve, fillet, chamfer, primitives, combine, move.
|
||
|
||
use serde_json::{Value, json};
|
||
use solidcraft_doc::{
|
||
AxisRef, Direction, Expr, Extent, FeatureKind, Operation, PointExpr, ProfileSel, RailFit, SweepOrientation, SweepRail, ThinSide, ThinWall,
|
||
Touching, expr::Kind, point_expr,
|
||
};
|
||
use solidcraft_doc::{BodyName, FeatureName, SketchId};
|
||
use solidcraft_doc::{Dir, FacePick, Position};
|
||
use solidcraft_geom::Vec3;
|
||
|
||
use super::{CommandSpec, not_in_sketch};
|
||
use crate::params::{UNKNOWN_COMMAND, bad, bool_, expr, expr_problem, req_expr, str_, string_list, string_list_or_default, vec2, vec3};
|
||
use crate::schema::features::{
|
||
BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureNotice, FeatureResult, NoticeAction, OffsetPlaneParams,
|
||
PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams, TorusParams,
|
||
};
|
||
use crate::schema::{TypedContract, output_schema_for};
|
||
use crate::{EngineError, Result, Session};
|
||
|
||
const BOX_CONTRACT: TypedContract<BoxParams> = TypedContract::new();
|
||
const EXTRUDE_CONTRACT: TypedContract<ExtrudeParams> = TypedContract::new();
|
||
const CYLINDER_CONTRACT: TypedContract<CylinderParams> = TypedContract::new();
|
||
const SPHERE_CONTRACT: TypedContract<SphereParams> = TypedContract::new();
|
||
const TORUS_CONTRACT: TypedContract<TorusParams> = TypedContract::new();
|
||
const CONE_CONTRACT: TypedContract<ConeParams> = TypedContract::new();
|
||
const PIPE_CONTRACT: TypedContract<PipeParams> = TypedContract::new();
|
||
const BOUNDING_SOLID_CONTRACT: TypedContract<BoundingSolidParams> = TypedContract::new();
|
||
const SCALE_CONTRACT: TypedContract<ScaleParams> = TypedContract::new();
|
||
const OFFSET_PLANE_CONTRACT: TypedContract<OffsetPlaneParams> = TypedContract::new();
|
||
const PLANE_AT_ANGLE_CONTRACT: TypedContract<PlaneAtAngleParams> = TypedContract::new();
|
||
|
||
pub static COMMANDS: &[CommandSpec] = &[
|
||
CommandSpec::new("solid.extrude", "Extrude", crate::checked!("solid.extrude", extrude))
|
||
.at("SOLID", "CREATE")
|
||
.icon("extrude")
|
||
.key("E")
|
||
.contract(&EXTRUDE_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (how a symmetric distance is read; default total_distance, split evenly around the start plane; legacy_per_side: the distance on each side, as older symmetric extrudes keep); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
|
||
CommandSpec::new("solid.revolve", "Revolve", revolve)
|
||
.at("SOLID", "CREATE")
|
||
.icon("revolve")
|
||
.params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | {type: world, axis: X|Y|Z} (as returned by timeline.inspect) | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, touching?, targets?, name?, body_name?"),
|
||
CommandSpec::new("solid.sweep", "Sweep", sweep)
|
||
.at("SOLID", "CREATE")
|
||
.icon("sweep")
|
||
.params("sketch: profile sketch; profiles?; path_sketch: sketch; path: [curve ids in order]; orientation?: perpendicular (default: square to the path, turning with it) | parallel (as drawn: the profile moves without turning; the path must keep crossing its plane) | [x,y,z] (square to the path, its turn about the path fixed by this direction); twist?: angle expr (the profile turns this much about the path over its length; within 4 turns); scale?: expr (the profile's scale at the end, linear along the path; 0.01…100); rails?: [{sketch?: sketch (default path_sketch), curves: [curve ids in order]}] (guide rails, one or two, each meeting every plane square to the path once along it, from the end nearest the path's start: one rail turns the profile so its point where the rail starts stays on the rail and scales it with the rail's distance from the path; two rails carry it between them, its points where they start staying on both; rails take the default orientation, no twist and no scale, and a path without sharp corners); rail_fit?: scale (default: the profile grows and shrinks evenly) | stretch (only across to the rail, between the rails); operation?, touching?, targets?, name?, body_name?"),
|
||
CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); rails?: [{sketch, curves: [ids in order]}] (one or two guide rails from the first section to the last, through every section's outline: the loft follows them between the sections; not with sections that have holes); rail_fit?: scale|stretch (default scale: with one rail the sections grow evenly with the rail's distance from their middle, with two with the distance between the rails; stretch: only that way); operation?, touching?, targets? (Join excludes hidden bodies from automatic targets; explicit targets or participants may include them), name?, body_name?"),
|
||
CommandSpec::new("solid.box", "Box", crate::checked!("solid.box", prim_box))
|
||
.at("SOLID", "CREATE")
|
||
.icon("box")
|
||
.contract(&BOX_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, touching?, targets?: [body], name?, body_name?"),
|
||
CommandSpec::new("solid.cylinder", "Cylinder", crate::checked!("solid.cylinder", prim_cylinder))
|
||
.at("SOLID", "CREATE")
|
||
.icon("cylinder")
|
||
.contract(&CYLINDER_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); references?: [{edge: [x,y,z] on a straight edge of the face it stands on, distance: expr}] (at most two, as solid.hole's: the base centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric base only); operation?, touching?, targets?: [body], name?, body_name?"),
|
||
CommandSpec::new("solid.sphere", "Sphere", crate::checked!("solid.sphere", prim_sphere))
|
||
.at("SOLID", "CREATE")
|
||
.icon("sphere")
|
||
.contract(&SPHERE_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, touching?, targets?: [body], name?, body_name?"),
|
||
CommandSpec::new("solid.torus", "Torus", crate::checked!("solid.torus", prim_torus))
|
||
.at("SOLID", "CREATE")
|
||
.icon("torus")
|
||
.contract(&TORUS_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("major, minor: expr (radii); center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, touching?, targets?: [body], name?, body_name?"),
|
||
CommandSpec::new("solid.cone", "Cone", crate::checked!("solid.cone", prim_cone))
|
||
.at("SOLID", "CREATE")
|
||
.icon("cone")
|
||
.contract(&CONE_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("radius | diameter, height: expr (the base circle, and the top's distance along the axis; a negative height goes the other way); top_radius? | top_diameter?: expr (the top circle; default 0: a full cone ending in an apex); base?: [x,y,z] (centre of the base circle: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, touching?, targets?: [body], name?, body_name?"),
|
||
CommandSpec::new("solid.fillet", "Fillet", fillet)
|
||
.at("SOLID", "MODIFY")
|
||
.icon("fillet")
|
||
.key("F")
|
||
.params("edges: [[x,y,z] point on edge | {body, index}] ; radius: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is rounded with it; false: exactly the picked edges); body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; a curvature round's corners are always g2 patches, between its own sections; g2: each corner where three or more rounded edges meet, and every edge there is rounded, is set back (1.5 × the radius along each edge unless `setbacks` names it) and filled with a patch meeting the rounds and the faces round it to the second order (curvature-continuous seams, clear of the points where a round's section ends on a face), constant-radius exact fillets only, refused where it cannot be built); setbacks?: [{vertex: [x,y,z], distance: expr}, …] (corner setbacks: the corner at the vertex nearest `vertex`, where every edge meeting it is rounded, starts its patch `distance` along each of those edges from the vertex, past where the rounds would meet (past the radius at a square corner), so the rounds blend through a larger patch; one distance for all of a corner's edges; constant-radius exact fillets only; with `corner: g2`, the G2 patch's corners); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused, naming the largest that fits; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"),
|
||
CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}] ; distance: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is cut with it; false: exactly the picked edges); distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"),
|
||
CommandSpec::new("solid.combine", "Combine", combine).at("SOLID", "MODIFY").icon("combine").params("target: body; tools: [body]; operation?: join|cut|intersect; touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"),
|
||
CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect)
|
||
.at("SOLID", "CREATE")
|
||
.icon("pattern_rect")
|
||
.params("features: [names] | bodies: [names] | components: [names]; dir1: [x,y,z]; count1; spacing1; dir2?, count2?, spacing2?; alignment?, alignment2?: left|center|right (default right; counts include the original); reversed?, reversed2?: bool (Flip)"),
|
||
CommandSpec::new("solid.pattern.circular", "Circular Pattern", pattern_circ)
|
||
.at("SOLID", "CREATE")
|
||
.icon("pattern_circ")
|
||
.params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir} (origin coordinates may be length expressions; the pattern follows them) | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"),
|
||
CommandSpec::new("solid.pattern.path", "Pattern on Path", pattern_path)
|
||
.at("SOLID", "CREATE")
|
||
.icon("pattern_path")
|
||
.params("features: [names] | bodies: [names]; path_sketch: sketch; path: [curve ids in order]; count; spacing (between instances) | distance (first to last); orientation?: identical|path; flip?: bool"),
|
||
CommandSpec::new("solid.mirror", "Mirror", mirror).at("SOLID", "CREATE").icon("mirror").params("features: [names] | bodies: [names] (combine?: join with the original); plane: XY|XZ|YZ|construction plane name or id|{origin, normal}|{origin, x_dir, y_dir} (origin coordinates may be length expressions; the mirror follows them, or a construction plane)"),
|
||
CommandSpec::new("solid.hole", "Hole", hole)
|
||
.at("SOLID", "CREATE")
|
||
.icon("hole")
|
||
.key("H")
|
||
.params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole, drilled with the tap maker's tabulated drill: ISO metric (a custom metric size: major minus pitch), UNC/UNF, G, Rp, Rc 1/16 to 4, NPT 1/16 to 3; a `diameter` given with it chooses another drill, from the thread's minor diameter to 5% over the tap maker's) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); references?: [{edge: [x,y,z] on a straight edge of the face, distance: expr}] (at most two; the centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric position only); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\", \"1/4-20 UNC\", \"G 1/4\", \"Rp 1/4\", \"Rc 1/4\" or \"1/4-18 NPT\" (cosmetic unless modeled); hand?: right|left (the tapped thread's hand; default right; needs thread); thread_depth?: positive length independent of drill depth (default: full useful cylindrical wall; must fit that wall); modeled?: bool (needs thread: the tapped thread cut into the wall, the groove between its teeth, as solid.thread's modelled one; default false: listed only); ease_out?: expr|standard|short (modelled tapped threads: the inner end, towards the bottom, fades out over this length, ISO 3508's runout, standard 2.5 P, short 1.25 P; without it the groove stops square at thread_depth, or clear of a blind hole's bottom); targets?: [body] (the bodies to drill; holes at the points of a sketch on a body's face default to that body, found along the holes' direction on it alone; explicit targets or participants override, [\"*\"] every body)"),
|
||
CommandSpec::new("solid.pipe", "Pipe", crate::checked!("solid.pipe", pipe))
|
||
.at("SOLID", "CREATE")
|
||
.icon("pipe")
|
||
.contract(&PIPE_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("path_sketch: sketch; path: [curve ids in order]; diameter: expr; wall?: expr (hollow); operation?, targets?, name?, body_name?"),
|
||
CommandSpec::new("solid.bounding_solid", "Bounding Solid", crate::checked!("solid.bounding_solid", bounding_solid))
|
||
.at("SOLID", "CREATE")
|
||
.icon("bounding_solid")
|
||
.contract(&BOUNDING_SOLID_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("bodies?: [names] (default: all); margin?: expr; name?, body_name?"),
|
||
CommandSpec::new("solid.scale", "Scale", crate::checked!("solid.scale", scale))
|
||
.at("SOLID", "MODIFY")
|
||
.icon("scale")
|
||
.contract(&SCALE_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("bodies: [names]; factor: expr | factors: [x, y, z] exprs; origin?: [x,y,z]"),
|
||
CommandSpec::new("face.delete", "Delete Face", delete_face)
|
||
.at("SOLID", "MODIFY")
|
||
.icon("delete_face")
|
||
.params("faces: [[x,y,z] points on the faces, or face names from model.faces]; body?; heal?: bool (default true: the neighbouring planes close the gap, as when a rounded edge, hole or boss is taken off; false: the gap stays open and the faces left are a surface body)"),
|
||
CommandSpec::new("solid.offset_face", "Offset Face", offset_face)
|
||
.at("SOLID", "MODIFY")
|
||
.icon("offset_face")
|
||
.params("faces: [[x,y,z] points on faces (planar or curved), or face names from model.faces]; distance: expr (positive: outward); body?"),
|
||
CommandSpec::new("solid.thread", "Thread", thread)
|
||
.at("SOLID", "CREATE")
|
||
.icon("thread")
|
||
.params("face: [x,y,z] on a cylindrical face; form?: metric|trapezoidal|acme|buttress|buttress_asme|bspp|rp|bspt|npt (default: the one `designation` names, else metric; square is refused: no current standard defines it); designation?: the size, as its standard writes it: metric \"M8\", \"M8x1\", \"M16xPh3P1.5\" (ISO 68-1, ISO 261, ISO 965-1); trapezoidal \"Tr20x4\", \"Tr40x14(P7)\" (ISO 2904, ISO 2903); buttress \"S20x4\", \"S40x14(P7)\" (DIN 513, 3°/30°); acme \"1/2-10 ACME\" (ASME B1.5); buttress_asme \"2.5-8 BUTT\" (ASME B1.9, 7°/45°, basic profile; no size table); bspp \"G 1/2\" (ISO 228-1, 55° parallel); rp \"Rp 1/2\" (ISO 7-1's parallel internal thread, 55°, an R screws into it; internal only); bspt \"R 1/2\" external, \"Rc 1/2\" internal (ISO 7-1, 55°, taper 1 in 16); npt \"1/2-14 NPT\" (ASME B1.20.1, 60°, taper 1 in 16) — a taper thread starts at a free end (the pipe end or the hole mouth) with its standard diameter there, and an external one runs its standard length unless `length` or `up_to` says otherwise (default: the standard size that fits the face, a shaft its major diameter, a hole its drill); hand?: right|left|both (default right; both: a right- and a left-handed groove crossing); steep_flank?: start|end (buttress only, default end: the steep flank of the screw's teeth faces the thread's end, the way its axis points); starts?: 1..8 (lead = starts x pitch: that many grooves, each a turn's starts-th further round; a designation that gives the lead gives the starts); ease_out?: expr|standard|short (modelled threads: the inner end, away from where the thread starts, fades out over this length (shorter than a turn too), its section moving out of the material as it turns; standard 2.5 P, short 1.25 P per ISO 3508; it lies past the full-form length, up to a shoulder's clearance; at a free end, inside the face; without it the groove stops square there, ending in its own profile; the start never fades: it runs off its free end, plain or chamfered (`tip`)); tip?: none|start|both (modelled external threads: start chamfers the end the thread starts from, which must be free, both each free end the thread reaches, after the groove is cut, ISO 4753's chamfered end, the last teeth tapering into the cone; chamfer_angle?: angle expr to the axis, default 45 deg; chamfer_depth?: expr, radial from the major diameter, default for a metric thread down to the external minor diameter d3 = d - 1.226869 P (ISO 724), the largest ISO 4753 allows; other forms give it); extent?: full|length|up_to (default: length when `length` is given, up_to when `up_to` is, else full: the whole face); length?: expr (from the end the thread starts at); up_to?: [x,y,z] (a point, such as on a shoulder face: the thread runs to its place along the axis) | plane name or {origin, normal} (to where the plane crosses the axis); from?: [x,y,z] near the end of the face the thread starts at (default: the face's only free end, the one with no material past it; else the end the `face` point lies within a third of the face of; a pick in the middle of a face whose ends are alike is refused); modeled?: bool (default false). Cosmetic: the model is unchanged, model.threads lists it. Modeled: cuts the thread profile into the body: past a free end the groove runs out a pitch into the air (or through a chamfer); at a shoulder, a head or a blind hole's bottom it stops with its section clear of it, never cutting into it; a shaft thicker than the thread is refused with the size to make it, never turned down"),
|
||
CommandSpec::new("solid.shell", "Shell", shell)
|
||
.at("SOLID", "MODIFY")
|
||
.icon("shell")
|
||
.params("faces: [[x,y,z] points on the faces to remove, or face names from model.faces; none: a closed hollow body]; thickness: expr; direction?: inside|outside|both; tangent_chain?: bool (also open faces joined smoothly to the picked ones); body? (needed with no faces when there are several bodies)"),
|
||
CommandSpec::new("solid.draft", "Draft", draft)
|
||
.at("SOLID", "MODIFY")
|
||
.icon("draft")
|
||
.params("faces: [[x,y,z] points, or face names from model.faces]; angle: expr; neutral: XY|XZ|YZ|plane name|{origin, normal}; pull?: [x,y,z] (default: neutral plane normal); body?"),
|
||
CommandSpec::new("construct.plane.offset", "Offset Plane", crate::checked!("construct.plane.offset", plane_offset))
|
||
.at("SOLID", "CONSTRUCT")
|
||
.icon("plane")
|
||
.contract(&OFFSET_PLANE_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("base: XY|XZ|YZ|plane name, or a planar face {face: [x,y,z], body?, index?, path?}; offset: expr, or through: a point ref (vertex, sketch point, construction point) the plane goes through, parallel to base; name?"),
|
||
CommandSpec::new("construct.plane.at_angle", "Plane at Angle", crate::checked!("construct.plane.at_angle", plane_angle))
|
||
.at("SOLID", "CONSTRUCT")
|
||
.icon("plane_angle")
|
||
.contract(&PLANE_AT_ANGLE_CONTRACT)
|
||
.output(output_schema_for::<FeatureResult>)
|
||
.params("base: XY|XZ|YZ|plane name, or a planar face {face: [x,y,z], body?, index?, path?}; axis: X|Y|Z|construction axis name (where it is now)|{origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle: expr; name?"),
|
||
CommandSpec::new("solid.split_face", "Split Face", split_face)
|
||
.at("SOLID", "MODIFY")
|
||
.icon("split_face")
|
||
.params(
|
||
"faces: [[x,y,z] points on the faces to split, or face names from model.faces]; body?; and the splitting tool: plane: XY|XZ|YZ|plane name|{origin, normal} — or tool: {body, point} (a face of a body, its surface extended) — or sketch: id or name (its curves, along the sketch's normal)",
|
||
),
|
||
CommandSpec::new("solid.split_body", "Split Body", split_body)
|
||
.at("SOLID", "MODIFY")
|
||
.icon("split_body")
|
||
.params("body: name; plane: XY|XZ|YZ|plane name|{origin, normal} — or tool: {body, point} (a face of a body, its surface extended) — or sketch: id, line: curve id (a straight sketch line, along the sketch's normal)"),
|
||
CommandSpec::new("solid.press_pull", "Press Pull", press_pull)
|
||
.at("SOLID", "MODIFY")
|
||
.icon("presspull")
|
||
.key("Q")
|
||
.params("face: [x,y,z] and distance: expr (positive adds material, negative cuts), or edges: [[x,y,z]…] and distance (a fillet)"),
|
||
CommandSpec::new("solid.move", "Move/Copy", move_bodies).at("SOLID", "MODIFY").icon("move").key("M").enabled(not_in_sketch).params("bodies: [names]; translate?: [x,y,z] (exprs or numbers); axis?: [x,y,z]; angle?: expr; copy?: bool (default false: keeps the original bodies and transforms a new copy instead of moving them in place); occurrences?: [occurrence paths, root first] (only with copy: each component is copied as an independent component, as Paste New copies it, and the copy moves by the same translate, axis and angle in the world; the reply lists the copies in occurrences)"),
|
||
];
|
||
|
||
/// Where an extrude starts and which way is positive: a point inside the (first) profile or
|
||
/// face, and the unit normal.
|
||
fn extrude_base(s: &Session, p: &Value) -> Option<(Vec3, Vec3)> {
|
||
if let Some(fp) = p.get("face").or_else(|| p.get("faces").and_then(Value::as_array).and_then(|faces| faces.first())).and_then(vec3) {
|
||
return Some((fp, super::face::face_normal_in(s, fp, str_(p, "face_body"))?));
|
||
}
|
||
let sid = feature_sketch(s, p, "Extrude").ok()?;
|
||
let st = s.model.state();
|
||
let ss = st.sketch(sid)?;
|
||
if bool_(p, "thin").unwrap_or(false) {
|
||
let thin = thin_param(s, p, sid, "solid.extrude").ok()?;
|
||
let q = thin_regions(s, ss, &thin).ok()?.first()?.interior_point();
|
||
return Some((ss.plane.to_world(q), ss.plane.normal()));
|
||
}
|
||
let ps = &ss.profiles;
|
||
let q = match profiles(p, "Extrude").ok()? {
|
||
ProfileSel::All => ps.first()?.region.interior_point(),
|
||
ProfileSel::Indices { indices } => ps.get(*indices.first()?)?.region.interior_point(),
|
||
ProfileSel::Points { points } => *points.first()?,
|
||
selection @ (ProfileSel::Curves { .. } | ProfileSel::OffsetBoundaries { .. } | ProfileSel::WholeBoundaries { .. }) => {
|
||
let indices = solidcraft_doc::profile_selection_indices(ss, &selection).ok()?;
|
||
ps.get(*indices.first()?)?.region.interior_point()
|
||
}
|
||
};
|
||
Some((ss.plane.to_world(q), ss.plane.normal()))
|
||
}
|
||
|
||
/// How far an extrude with these parameters goes from its profile along the profile's normal
|
||
/// (negative: the other way). To an object, the target's height, on whichever side it is: the
|
||
/// extrude goes there and its `direction` does not count (#1633). Otherwise its distance, turned
|
||
/// round for the negative direction.
|
||
pub fn extrude_reach(s: &Session, p: &Value) -> Option<f64> {
|
||
if let Some(t) = p.get("to").and_then(vec3) {
|
||
let (base, n) = extrude_base(s, p)?;
|
||
return Some((t - base).dot(n)).filter(|h| h.is_finite());
|
||
}
|
||
let d = s.doc.eval(&expr(p, "distance")?, Kind::Length).ok()?;
|
||
let dir = str_(p, "direction").map(str::to_ascii_lowercase);
|
||
Some(if matches!(dir.as_deref(), Some("negative" | "reverse" | "flip")) { -d } else { d })
|
||
}
|
||
|
||
/// How far past the profile [`auto_operation`] looks for material it starts in.
|
||
const START_PROBE_MM: f64 = 0.1;
|
||
|
||
/// What `operation: "auto"` means for an extrude with these parameters: `cut` when it goes
|
||
/// into a body, otherwise `join` when the active component has a solid. Keeping an
|
||
/// addition separate requires an explicit `new` operation.
|
||
///
|
||
/// "Goes into a body" is decided where the extrude starts: just past the profile in the
|
||
/// direction it grows, or halfway along it. With the halfway point alone, a cut dragged far
|
||
/// past a body's far side read as a Join (#1257).
|
||
///
|
||
/// Faces picked in the world are probed in the placed model; one that cannot be placed is the
|
||
/// error.
|
||
pub fn auto_operation(s: &Session, p: &Value) -> Result<Option<&'static str>> {
|
||
let st = if grouped_face(p).is_some() { s.world_state()? } else { s.model.state() };
|
||
Ok(auto_operation_in(s, p, &st))
|
||
}
|
||
|
||
impl Session {
|
||
/// Whether a cut or intersect that names no bodies takes part in every body of `st`: the
|
||
/// active component has no body of its own while the model has some (a sketch in the
|
||
/// assembly's root cutting through its parts, #1234). The command and its preview both ask
|
||
/// this, so the preview never refuses a cut the command makes (#3085).
|
||
pub fn cut_takes_every_body(&self, st: &solidcraft_doc::ModelState) -> bool {
|
||
!st.bodies.is_empty() && !st.bodies.iter().any(|b| self.doc.model_body_component(b) == self.active_component)
|
||
}
|
||
}
|
||
|
||
/// The first of an extrude's grouped face picks.
|
||
fn grouped_face(p: &Value) -> Option<Vec3> {
|
||
p.get("faces").and_then(Value::as_array).and_then(|faces| faces.first()).and_then(vec3)
|
||
}
|
||
|
||
/// [`auto_operation`] probing the model `st`.
|
||
fn auto_operation_in(s: &Session, p: &Value, st: &solidcraft_doc::ModelState) -> Option<&'static str> {
|
||
let symmetric = p.get("to").is_none() && str_(p, "direction").is_some_and(|d| d.eq_ignore_ascii_case("symmetric"));
|
||
// Imported face groups can belong to a child of an empty active component.
|
||
// Probe in the same coordinate frame as the face picks.
|
||
let grouped = grouped_face(p);
|
||
// The body the extrude starts on, when it is in a component inside the active one: it takes
|
||
// part as the active component's own bodies do (#5679).
|
||
let mut started_on = None;
|
||
let (base, n) = if let Some(point) = grouped {
|
||
let (mesh, index, distance, name) = super::face::face_at_state(st, point, str_(p, "face_body")).ok().flatten()?;
|
||
if distance > (mesh.bounds().diagonal() * 1e-3).max(1e-3) * 10.0 {
|
||
return None;
|
||
}
|
||
let normal = st.body(&name)?.body.planar_face(index as usize)?.normal();
|
||
started_on = Some(name);
|
||
(point, normal)
|
||
} else {
|
||
if p.get("face").is_none() {
|
||
started_on = feature_sketch(s, p, "Extrude").ok().and_then(|sketch| face_body_reached(s, sketch).ok().flatten());
|
||
}
|
||
extrude_base(s, p)?
|
||
};
|
||
// The extrude starts at its From Object or start offset, not at the profile: probe from
|
||
// there (#467). To an object it then reaches only from that start.
|
||
let start = match p.get("from").and_then(vec3) {
|
||
Some(from) if grouped.is_none() => (from - base).dot(n),
|
||
_ => expr(p, "start_offset").and_then(|e| s.doc.eval(&e, Kind::Length).ok()).unwrap_or(0.0),
|
||
};
|
||
let start = if start.is_finite() { start } else { 0.0 };
|
||
let base = base + n * start;
|
||
let d = if grouped.is_some() && p.get("to").is_some() {
|
||
(p.get("to").and_then(vec3)? - base).dot(n)
|
||
} else if let Some(d) = extrude_reach(s, p) {
|
||
if p.get("to").is_some() { d - start } else { d }
|
||
} else {
|
||
through_all_reach(st, p, base)?
|
||
};
|
||
if st.bodies.is_empty() || !d.is_finite() {
|
||
return Some("new");
|
||
}
|
||
// Match the evaluator's implicit participants: a grouped cut from an empty
|
||
// assembly component considers every body; otherwise keep the active scope.
|
||
// Explicit participants override either default.
|
||
// A component with no body of its own works on those of the components inside it (#3223).
|
||
// The participants only pick the scope here; the feature itself refuses a list of the
|
||
// wrong type (`add_feature`), so a wrong type cannot make this cut anything. This preview
|
||
// cannot fail, so it reads the list leniently.
|
||
let parts = string_list_or_default(p, "participants");
|
||
let implicit_all = grouped.is_some() && !st.bodies.iter().any(|body| s.doc.model_body_component(body) == s.active_component);
|
||
let mut bodies: Vec<_> = if !parts.is_empty() {
|
||
st.bodies.iter().filter(|b| parts.contains(&b.name)).collect()
|
||
} else if implicit_all {
|
||
st.bodies.iter().collect()
|
||
} else {
|
||
active_scope(s, st)
|
||
};
|
||
if parts.is_empty()
|
||
&& let Some(body) = started_on.as_deref().and_then(|name| st.body(name))
|
||
&& !bodies.iter().any(|b| b.name == body.name)
|
||
&& s.doc.component_within(s.doc.model_body_component(body), s.active_component)
|
||
{
|
||
bodies.push(body);
|
||
}
|
||
if bodies.is_empty() {
|
||
return Some("new");
|
||
}
|
||
// A profile's points are in the active component's frame; a body placed differently (in a
|
||
// moved or turned component) is probed where it is shown. Face picks are in `st`'s frame.
|
||
let frames: Vec<Option<solidcraft_doc::Mat>> = bodies.iter().map(|b| if grouped.is_some() { None } else { into_body_frame(s, b) }).collect();
|
||
let inside = |q: Vec3| bodies.iter().zip(&frames).any(|(b, m)| b.mesh().contains(m.as_ref().map_or(q, |m| solidcraft_doc::apply_point(m, q))));
|
||
// A step into whatever is right in front of the profile, short of the far end.
|
||
let near = |d: f64| d.signum() * (d.abs() * 0.5).min(START_PROBE_MM);
|
||
let into = |d: f64| inside(base + n * near(d)) || inside(base + n * (d * 0.5));
|
||
if symmetric {
|
||
return Some(if into(d.abs()) || into(-d.abs()) { "cut" } else { "join" });
|
||
}
|
||
if into(d) {
|
||
Some("cut")
|
||
} else {
|
||
// A profile can meet material along its side, or only around part of a
|
||
// screw boss. A single point behind its centre cannot establish contact.
|
||
// Default additions to Join and let the boolean merge the actual geometry.
|
||
Some("join")
|
||
}
|
||
}
|
||
|
||
/// How far a Through All extrude with no distance reaches from `base`, signed by its
|
||
/// direction: past every body of the model. Without it `auto` could not tell a cut through
|
||
/// a part from an addition and made a separate body.
|
||
fn through_all_reach(st: &solidcraft_doc::ModelState, p: &Value, base: Vec3) -> Option<f64> {
|
||
let through_all = bool_(p, "through_all").unwrap_or(false) || str_(p, "extent").is_some_and(|e| e.eq_ignore_ascii_case("through_all"));
|
||
if !through_all {
|
||
return None;
|
||
}
|
||
let reach =
|
||
st.bodies.iter().map(|b| b.mesh().bounds()).map(|bb| bb.center().dist(base) + bb.diagonal()).filter(|r| r.is_finite()).fold(1.0, f64::max);
|
||
let dir = str_(p, "direction").map(str::to_ascii_lowercase);
|
||
Some(if matches!(dir.as_deref(), Some("negative" | "reverse" | "flip")) { -reach } else { reach })
|
||
}
|
||
|
||
pub(super) fn operation(p: &Value, cmd: &str) -> Result<Operation> {
|
||
match str_(p, "operation") {
|
||
None => Ok(Operation::NewBody),
|
||
Some(o) => Operation::parse(o).ok_or_else(|| bad(cmd, format!("unknown operation `{o}` (new, join, cut, intersect)"))),
|
||
}
|
||
}
|
||
|
||
/// The sketch a feature uses: `sketch` param, the active sketch, or the last sketch.
|
||
pub(super) fn feature_sketch(s: &Session, p: &Value, cmd: &str) -> Result<u64> {
|
||
if let Some(v) = p.get("sketch") {
|
||
let key = sketch_key(Some(v)).ok_or_else(|| bad(cmd, "`sketch` must be an id or name"))?;
|
||
let f = s.doc.find_feature(&key).ok_or_else(|| bad(cmd, format!("no sketch `{key}`")))?;
|
||
return match f.kind {
|
||
FeatureKind::Sketch { .. } => Ok(f.id),
|
||
_ => Err(bad(cmd, format!("`{key}` is not a sketch"))),
|
||
};
|
||
}
|
||
if let Some(a) = super::sketch_store::active(s) {
|
||
return Ok(a);
|
||
}
|
||
let limit = s.doc.marker.unwrap_or(usize::MAX);
|
||
s.doc
|
||
.features
|
||
.iter()
|
||
.take(limit)
|
||
.rev()
|
||
.find(|f| matches!(f.kind, FeatureKind::Sketch { .. }))
|
||
.map(|f| f.id)
|
||
.ok_or_else(|| bad(cmd, "there is no sketch to use (create one first)"))
|
||
}
|
||
|
||
/// Profiles picked by index or point are stored by the curve ids of each profile's outer loop
|
||
/// as the sketch is now solved, so they follow the geometry when parameters move it. A pick
|
||
/// whose curves would not find that same profile again (two profiles bounded by the same
|
||
/// curves) stays as given. Curve picks are checked: one that names no profile, or several, is
|
||
/// refused now rather than failing later.
|
||
///
|
||
/// `exact` keeps each index or point pick to the region it names. Otherwise a pick on a drawn
|
||
/// profile that reference geometry cuts into regions takes the whole drawn profile
|
||
/// ([`drawn_profile_regions`], #5302).
|
||
pub(super) fn stable_profiles(s: &Session, kind: &mut FeatureKind, exact: bool) -> Result<()> {
|
||
use solidcraft_doc::sketch::profile_at_point;
|
||
let st = s.model.state();
|
||
for (sketch, sel) in kind.profile_sels_mut() {
|
||
let Some(ss) = st.sketch(sketch) else { continue };
|
||
let indices = match sel {
|
||
ProfileSel::Indices { indices } => {
|
||
let have = ss.profiles.len();
|
||
if indices.len() > have {
|
||
return Err(EngineError::Other(format!("{} profiles are listed, but {} has {have}", indices.len(), ss.name)));
|
||
}
|
||
if let Some(i) = indices.iter().find(|i| **i >= have) {
|
||
return Err(EngineError::Other(format!("there is no profile {i} in {} (it has {have})", ss.name)));
|
||
}
|
||
solidcraft_doc::profile_selection_indices(ss, sel)?
|
||
}
|
||
ProfileSel::Points { points } => {
|
||
if points.len() > ss.profiles.len() {
|
||
return Err(EngineError::Other(format!(
|
||
"{} profile points are given, but {} has {} profiles",
|
||
points.len(),
|
||
ss.name,
|
||
ss.profiles.len()
|
||
)));
|
||
}
|
||
let Some(indices) = points.iter().map(|point| profile_at_point(&ss.profiles, *point)).collect::<Option<Vec<_>>>() else { continue };
|
||
let mut seen = std::collections::BTreeSet::new();
|
||
if let Some(i) = indices.iter().find(|i| !seen.insert(**i)) {
|
||
return Err(EngineError::Other(format!("two profile points pick the same profile ({i}) in {}", ss.name)));
|
||
}
|
||
indices
|
||
}
|
||
ProfileSel::Curves { loops } => {
|
||
// The command's ordinary curve lists are sets, including repeated
|
||
// caller IDs. Saved graph-span multisets retain their legacy meaning.
|
||
// Reserved offset roles never use this ordinary normalization.
|
||
let mut normalized = loops.clone();
|
||
let reserved = ss
|
||
.sketch
|
||
.offsets
|
||
.iter()
|
||
.filter_map(|offset| offset.topology.as_ref())
|
||
.flat_map(|topology| topology.roles.iter().map(|role| role.output.as_str()))
|
||
.collect::<std::collections::BTreeSet<_>>();
|
||
for curves in &mut normalized {
|
||
let dynamic = curves.iter().any(|curve| reserved.contains(curve.as_str()));
|
||
if !dynamic {
|
||
let mut seen = std::collections::BTreeSet::new();
|
||
curves.retain(|curve| seen.insert(curve.clone()));
|
||
}
|
||
}
|
||
let selection = ProfileSel::Curves { loops: normalized };
|
||
solidcraft_doc::profile_selection_indices(ss, &selection)?;
|
||
*sel = selection;
|
||
continue;
|
||
}
|
||
ProfileSel::OffsetBoundaries { .. } | ProfileSel::WholeBoundaries { .. } => {
|
||
// Explicit identities retain the caller's semantics. Validate through the
|
||
// same resolver as recomputation, including reserved-role precedence.
|
||
solidcraft_doc::profile_selection_indices(ss, sel)?;
|
||
continue;
|
||
}
|
||
ProfileSel::All => continue,
|
||
};
|
||
let picked = if exact { indices } else { drawn_profile_regions(ss, &indices) };
|
||
let captured = solidcraft_doc::capture_profile_selection(ss, &picked)?;
|
||
*sel = match captured {
|
||
ProfileSel::OffsetBoundaries { associations }
|
||
if associations.iter().any(|id| {
|
||
s.doc
|
||
.sketch(sketch)
|
||
.is_ok_and(|raw| !raw.offsets.iter().filter_map(|offset| offset.topology.as_ref()).any(|topology| topology.id == *id))
|
||
}) =>
|
||
{
|
||
// Legacy upgrade descriptors belong to the solved copy. Persist the
|
||
// complete original role IDs instead of an unsaved association ID.
|
||
let loops = associations
|
||
.iter()
|
||
.map(|id| {
|
||
ss.sketch
|
||
.offsets
|
||
.iter()
|
||
.filter_map(|offset| offset.topology.as_ref())
|
||
.find(|topology| topology.id == *id)
|
||
.map(|topology| topology.roles.iter().map(|role| role.output.clone()).collect())
|
||
.ok_or_else(|| EngineError::Other(format!("offset association `{id}` changed during profile capture")))
|
||
})
|
||
.collect::<Result<Vec<_>>>()?;
|
||
ProfileSel::Curves { loops }
|
||
}
|
||
captured => captured,
|
||
};
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// The regions a picked profile stands for.
|
||
///
|
||
/// A drawn profile cut by reference geometry that crosses it (the projected outline of the face
|
||
/// a sketch is on) is several regions of the sketch's graph, and picking one of them takes the
|
||
/// whole drawn profile (#5302): the regions that share a drawn curve with the picked one are
|
||
/// the parts of that outline, split by the reference geometry crossing it. Reference geometry
|
||
/// that stays inside the drawn profile (the rim of a counterbored hole) bounds an inner region
|
||
/// of it, a real boundary of the material, so the pick keeps its own region. The drawn profiles
|
||
/// are the disjoint faces of the drawn graph, so a drawn hole keeps filling only itself
|
||
/// (#5176).
|
||
fn drawn_profile_regions(ss: &solidcraft_doc::SolvedSketch, indices: &[usize]) -> Vec<usize> {
|
||
const MAX_PROFILES: usize = 10_000;
|
||
if indices.is_empty() || indices.len() > MAX_PROFILES || ss.profiles.len() > MAX_PROFILES {
|
||
return indices.to_vec();
|
||
}
|
||
let drawn = solidcraft_sketch::find_drawn_profiles(&ss.sketch);
|
||
if drawn.is_empty() || drawn.len() >= ss.profiles.len() {
|
||
return indices.to_vec();
|
||
}
|
||
// The curves the user drew: the drawn profiles are made of them, the reference geometry is
|
||
// not part of them.
|
||
let drawn_curves: std::collections::BTreeSet<&str> = ss
|
||
.sketch
|
||
.curves
|
||
.iter()
|
||
.enumerate()
|
||
.filter(|(index, curve)| {
|
||
!curve.construction && !curve.centerline && !curve.infinite && (!ss.sketch.is_linked_curve(*index) || ss.sketch.is_text_curve(*index))
|
||
})
|
||
.map(|(_, curve)| curve.id.as_str())
|
||
.collect();
|
||
let mut out: Vec<usize> = Vec::with_capacity(indices.len());
|
||
for index in indices {
|
||
let Some(picked) = ss.profiles.get(*index) else { continue };
|
||
// The drawn profile the picked region belongs to: the region around it that the drawn
|
||
// geometry alone bounds.
|
||
let probe = picked.region.interior_point();
|
||
let Some(owner) = drawn.iter().find(|profile| profile.region.contains(probe)) else {
|
||
out.push(*index);
|
||
continue;
|
||
};
|
||
// The drawn curves the picked region is bounded by.
|
||
let picked_curves: std::collections::BTreeSet<&str> = picked
|
||
.outer_curves
|
||
.iter()
|
||
.chain(picked.hole_curves.iter().flatten())
|
||
.map(String::as_str)
|
||
.filter(|id| drawn_curves.contains(id))
|
||
.collect();
|
||
if picked_curves.is_empty() {
|
||
out.push(*index);
|
||
continue;
|
||
}
|
||
// The regions of the drawn profile that share a drawn curve with the picked one: the
|
||
// parts of the same outline, cut apart by reference geometry crossing it.
|
||
let pieces: Vec<usize> = ss
|
||
.profiles
|
||
.iter()
|
||
.enumerate()
|
||
.filter(|(_, profile)| owner.region.contains(profile.region.interior_point()))
|
||
.filter(|(_, profile)| {
|
||
profile.outer_curves.iter().chain(profile.hole_curves.iter().flatten()).any(|id| picked_curves.contains(id.as_str()))
|
||
})
|
||
.map(|(index, _)| index)
|
||
.collect();
|
||
if pieces.is_empty() {
|
||
out.push(*index);
|
||
} else {
|
||
out.extend(pieces);
|
||
}
|
||
}
|
||
out.sort_unstable();
|
||
out.dedup();
|
||
out
|
||
}
|
||
|
||
/// `exact_regions: true`: each index or point pick is the region it names, never grown to the
|
||
/// whole drawn profile. The dialogs send it: they highlight exactly the regions picked, and OK
|
||
/// must build those (#6724).
|
||
pub(super) fn exact_regions(p: &Value) -> bool {
|
||
bool_(p, "exact_regions").unwrap_or(false)
|
||
}
|
||
|
||
pub(crate) fn profiles(p: &Value, cmd: &str) -> Result<ProfileSel> {
|
||
let Some(v) = p.get("profiles") else { return Ok(ProfileSel::All) };
|
||
match v {
|
||
Value::Object(fields) => {
|
||
if fields.get("type").and_then(Value::as_str) == Some("whole_boundaries") {
|
||
return solidcraft_doc::whole_profile_selection_from_value(v).map_err(|error| bad(cmd, error.to_string()));
|
||
}
|
||
if !fields.contains_key("offset_boundaries") && fields.get("type").and_then(Value::as_str) != Some("offset_boundaries") {
|
||
return Err(bad(
|
||
cmd,
|
||
r#"`profiles` must be `"all"`, an index such as `0`, indices such as `[0]`, point picks such as `[{"point": [0, 0]}]` or curve-id picks such as `[{"curves": ["c1"]}]`"#,
|
||
));
|
||
}
|
||
let associations = fields
|
||
.get("offset_boundaries")
|
||
.or_else(|| (fields.get("type").and_then(Value::as_str) == Some("offset_boundaries")).then(|| fields.get("associations")).flatten())
|
||
.and_then(Value::as_array)
|
||
.ok_or_else(|| bad(cmd, "profile object must provide `offset_boundaries: [association ids]`"))?;
|
||
if associations.is_empty() || associations.len() > 128 {
|
||
return Err(bad(cmd, "offset profile selection needs 1 to 128 association ids"));
|
||
}
|
||
let associations = associations
|
||
.iter()
|
||
.map(|id| {
|
||
id.as_str()
|
||
.filter(|id| !id.is_empty() && id.len() <= 512)
|
||
.map(str::to_string)
|
||
.ok_or_else(|| bad(cmd, "offset association ids must be nonempty strings of at most 512 bytes"))
|
||
})
|
||
.collect::<Result<Vec<_>>>()?;
|
||
if associations.iter().collect::<std::collections::BTreeSet<_>>().len() != associations.len() {
|
||
return Err(bad(cmd, "offset association ids must be unique"));
|
||
}
|
||
Ok(ProfileSel::OffsetBoundaries { associations })
|
||
}
|
||
Value::String(s) if s.eq_ignore_ascii_case("all") => Ok(ProfileSel::All),
|
||
Value::Number(n) => Ok(ProfileSel::Indices { indices: vec![n.as_u64().ok_or_else(|| bad(cmd, "profile index"))? as usize] }),
|
||
Value::Array(a) if a.is_empty() => Err(bad(cmd, "`profiles` is empty")),
|
||
Value::Array(a) if a.len() > 10_000 => Err(bad(cmd, "too many profiles")),
|
||
Value::Array(a) => {
|
||
if a.iter().all(Value::is_u64) {
|
||
// Each profile once: a repeat would build the same body again.
|
||
let mut seen = std::collections::BTreeSet::new();
|
||
let mut indices = Vec::with_capacity(a.len());
|
||
for i in a.iter().filter_map(Value::as_u64) {
|
||
let i = usize::try_from(i).map_err(|_| bad(cmd, format!("there is no profile {i}")))?;
|
||
if !seen.insert(i) {
|
||
return Err(bad(cmd, format!("profile {i} is listed twice")));
|
||
}
|
||
indices.push(i);
|
||
}
|
||
return Ok(ProfileSel::Indices { indices });
|
||
}
|
||
if a.iter().all(|x| x.get("point").is_some()) {
|
||
let pts =
|
||
a.iter().map(|x| x.get("point").and_then(vec2).ok_or_else(|| bad(cmd, "profile point must be [x, y]"))).collect::<Result<_>>()?;
|
||
return Ok(ProfileSel::Points { points: pts });
|
||
}
|
||
// [[ids]], [{curves: [...]}] or recipe-style [{loops: [{outer: true, curves: [...]}]}].
|
||
let mut loops = Vec::new();
|
||
for x in a {
|
||
let ids: Vec<String> = match x {
|
||
Value::Array(ids) => ids.iter().filter_map(|i| i.as_str().map(str::to_string)).collect(),
|
||
Value::Object(_) => {
|
||
if x.get("curves").is_some() {
|
||
string_list(cmd, x, "curves")?
|
||
} else if let Some(ls) = x.get("loops").and_then(Value::as_array) {
|
||
let outer = ls.iter().find(|l| l.get("outer").and_then(Value::as_bool).unwrap_or(true)).or(ls.first());
|
||
match outer {
|
||
Some(l) => string_list(cmd, l, "curves")?,
|
||
None => Vec::new(),
|
||
}
|
||
} else {
|
||
Vec::new()
|
||
}
|
||
}
|
||
_ => Vec::new(),
|
||
};
|
||
if ids.is_empty() {
|
||
return Err(bad(cmd, "each profile must be an index, a list of curve ids, {curves}, {loops} or {point}"));
|
||
}
|
||
loops.push(ids);
|
||
}
|
||
Ok(ProfileSel::Curves { loops })
|
||
}
|
||
_ => Err(bad(cmd, "`profiles` must be \"all\" or a list")),
|
||
}
|
||
}
|
||
|
||
pub(super) fn check_expr(s: &Session, e: &str, kind: Kind, cmd: &str, what: &str) -> Result<()> {
|
||
s.doc.eval(e, kind).map(|_| ()).map_err(|err| bad(cmd, format!("{what}: {err}")))
|
||
}
|
||
|
||
/// A pattern count: a whole, unit-less number (see `expr::eval_count`).
|
||
pub(super) fn check_count(s: &Session, e: &str, cmd: &str, what: &str) -> Result<()> {
|
||
let (vals, _) = s.doc.param_values();
|
||
solidcraft_doc::expr::eval_count(e, &vals).map(|_| ()).map_err(|err| bad(cmd, format!("{what}: {err}")))
|
||
}
|
||
|
||
/// Add a feature, evaluate, and report its result (an evaluation error fails the command).
|
||
pub(super) fn add_feature(s: &mut Session, p: &Value, kind: FeatureKind) -> Result<Value> {
|
||
add_feature_in(s, p, kind, true)
|
||
}
|
||
|
||
/// `add_feature`; `world` is false when `kind` is already in the active component's frame.
|
||
fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> Result<Value> {
|
||
let name = str_(p, "name");
|
||
// What a join makes of pieces that share no face (`Touching`): separate unless asked.
|
||
let touching = match p.get("touching") {
|
||
None | Some(Value::Null) => Touching::Separate,
|
||
Some(v) => v.as_str().and_then(Touching::parse).ok_or_else(|| EngineError::Other("`touching` must be separate or one_body".into()))?,
|
||
};
|
||
// The bodies before the feature, to say which ones it changed or removed.
|
||
let before = s.model.state();
|
||
// Commands speak world coordinates; the feature is authored in the active component.
|
||
let mut kind = kind;
|
||
if world {
|
||
super::component::to_active_frame(s, &mut kind);
|
||
}
|
||
// Bare lengths typed in an inch (or cm…) design mean that unit.
|
||
if s.doc.units.trim() != "mm" {
|
||
let doc = s.doc.clone();
|
||
for (_, e, k) in kind.inputs_mut() {
|
||
*e = doc.with_design_unit(e, k).into();
|
||
}
|
||
}
|
||
// Profiles picked by index are kept by the curves around them: a recompute can renumber a
|
||
// sketch's profiles (a face sketch's projected outline rebuilt), never the curves.
|
||
stable_profiles(s, &mut kind, exact_regions(p))?;
|
||
// Blends remember where their edges sat, to find them again after upstream edits.
|
||
let (refs, names) = match &kind {
|
||
FeatureKind::Fillet { edges, body, .. } | FeatureKind::Chamfer { edges, body, .. } => {
|
||
let st = s.model.state();
|
||
(
|
||
solidcraft_doc::edge_refs(&st, body, &solidcraft_doc::plain(edges)),
|
||
solidcraft_doc::edge_names_for(&st, body, &solidcraft_doc::plain(edges)),
|
||
)
|
||
}
|
||
// Sheet metal edges are named by the sheet model.
|
||
FeatureKind::SheetFlange { edges, .. } => {
|
||
let points: Vec<_> = edges.iter().map(|e| e.point).collect();
|
||
(Vec::new(), solidcraft_doc::sheet::sheet_edge_names(&s.model.state(), &solidcraft_doc::plain(&points)))
|
||
}
|
||
FeatureKind::SheetHem { edges, .. } => (Vec::new(), solidcraft_doc::sheet::sheet_edge_names(&s.model.state(), &solidcraft_doc::plain(edges))),
|
||
// A hole's reference edges (#37) are edges of the body it is drilled into.
|
||
FeatureKind::Hole { position, references, .. } if !references.is_empty() => {
|
||
let edges: Vec<Vec3> = references.iter().map(|r| r.edge.0).collect();
|
||
(Vec::new(), solidcraft_doc::hole_reference::reference_edge_names(&s.model.state(), position.0, &edges))
|
||
}
|
||
// A cylinder's reference edges (#6380) are edges of the body it stands on.
|
||
FeatureKind::Cylinder { base, references, .. } if !references.is_empty() => {
|
||
(Vec::new(), solidcraft_doc::hole_reference::cylinder_edge_names(&s.model.state(), base, references))
|
||
}
|
||
// A conversion's bend edges are edges of the body it converts.
|
||
FeatureKind::SheetConvert { body, bends, .. } if !bends.is_empty() => {
|
||
(Vec::new(), solidcraft_doc::sheet::bend_edge_names(&s.model.state(), body, &solidcraft_doc::plain(bends)))
|
||
}
|
||
_ => (Vec::new(), Vec::new()),
|
||
};
|
||
let face_names = {
|
||
let pts = kind.face_points();
|
||
if let FeatureKind::Emboss { face: Some(face), .. } = &kind {
|
||
let state = s.model.state();
|
||
let body = state.body(&face.body).ok_or_else(|| EngineError::Other("selected cylinder body no longer exists".into()))?;
|
||
let frame = face.body_frame(&s.doc, body).map_err(|e| EngineError::Other(e.to_string()))?;
|
||
let inverse = solidcraft_doc::mat_inverse(&frame).ok_or_else(|| EngineError::Other("invalid cylinder placement".into()))?;
|
||
let at = solidcraft_doc::apply_point(&solidcraft_doc::mat_mul(&inverse, &s.active_component_frame()), face.at.0);
|
||
let mut scoped = solidcraft_doc::ModelState::default();
|
||
scoped.bodies.push(body.clone());
|
||
let names = solidcraft_doc::naming::face_names_at(&scoped, &[at]);
|
||
if names.len() != 1 || names.first().is_none_or(|name| name.is_empty()) {
|
||
return Err(EngineError::Other("selected cylinder face has no persistent identity".into()));
|
||
}
|
||
names
|
||
} else if pts.is_empty() {
|
||
Vec::new()
|
||
} else {
|
||
solidcraft_doc::face_point_names(&s.doc, &s.model.state(), &kind, s.active_component)?
|
||
}
|
||
};
|
||
// Primitives have no `targets` of their own: their `targets` are the bodies taking part (#259).
|
||
let primitive = matches!(
|
||
kind,
|
||
FeatureKind::Box { .. } | FeatureKind::Cylinder { .. } | FeatureKind::Sphere { .. } | FeatureKind::Torus { .. } | FeatureKind::Cone { .. }
|
||
);
|
||
let (participants, key) = match string_list(UNKNOWN_COMMAND, p, "participants")? {
|
||
v if v.is_empty() && primitive => (string_list(UNKNOWN_COMMAND, p, "targets")?, "targets"),
|
||
v => (v, "participants"),
|
||
};
|
||
if participants.len() > 10_000 || participants.iter().any(|b| b != "*" && s.model.state().body(b).is_none()) {
|
||
return Err(EngineError::Other(format!("`{key}` must list existing bodies")));
|
||
}
|
||
// A cut or intersect made where the active component has no body of its own (a sketch in
|
||
// the assembly's root, cutting through the parts, #1234) would have nothing to work on: it
|
||
// takes part in every body instead, which it changes only where it meets them. An extrude's
|
||
// own operation counts too: an automatic one that came out as a cut (#3223); and so does a
|
||
// hole, which is always a cut (one at the points of a sketch on a nested part's face).
|
||
let participants = if participants.is_empty()
|
||
&& !primitive
|
||
&& (matches!(str_(p, "operation").and_then(Operation::parse), Some(Operation::Cut | Operation::Intersect))
|
||
|| matches!(&kind, FeatureKind::Extrude { operation: Operation::Cut | Operation::Intersect, .. } | FeatureKind::Hole { .. }))
|
||
&& s.cut_takes_every_body(&s.model.state())
|
||
{
|
||
vec!["*".to_string()]
|
||
} else {
|
||
participants
|
||
};
|
||
// An extrude's Join, Cut or Intersect with no bodies picked changes the bodies of the active
|
||
// component that are shown, never a hidden one (#2464). The shown ones are kept as its
|
||
// participants, so showing or hiding bodies later doesn't change the model.
|
||
let participants = match &kind {
|
||
FeatureKind::Extrude { operation: Operation::Join | Operation::Cut | Operation::Intersect, targets, .. }
|
||
if participants.is_empty() && targets.is_empty() =>
|
||
{
|
||
shown_scope(s).unwrap_or_default()
|
||
}
|
||
_ => participants,
|
||
};
|
||
if matches!(kind, FeatureKind::ConstructionPlane { .. })
|
||
&& let Some(n) = name
|
||
{
|
||
check_plane_name(n, "construct.plane")?;
|
||
}
|
||
let id = s.doc_mut().add_feature(kind, name)?;
|
||
if let Some(f) = s.doc_mut().feature_mut(id) {
|
||
f.participants = participants;
|
||
f.touching = touching;
|
||
f.edge_refs = refs;
|
||
f.edge_names = names;
|
||
f.face_names = face_names;
|
||
}
|
||
s.doc_mut().name_feature_inputs(id);
|
||
let comp = s.active_component;
|
||
if comp != 0
|
||
&& let Some(f) = s.doc_mut().feature_mut(id)
|
||
{
|
||
f.component = comp;
|
||
}
|
||
let mut names = string_list(UNKNOWN_COMMAND, p, "body_names")?;
|
||
if let Some(b) = str_(p, "body_name") {
|
||
names.insert(0, b.to_string());
|
||
}
|
||
if !names.is_empty()
|
||
&& let Some(f) = s.doc_mut().feature_mut(id)
|
||
{
|
||
f.body_names = names.clone();
|
||
}
|
||
s.active_sketch = None;
|
||
s.refresh();
|
||
// A feature that makes more bodies than it was given names (a multi-profile extrude with one
|
||
// `body_name`) has the rest numbered after the first by the evaluator: `Ribs`, `Ribs (2)`,
|
||
// `Ribs (3)`… (#266, #373). They are stored on the feature, so recomputes and saved designs
|
||
// keep them even when the profiles are later picked in another order.
|
||
if names.first().is_some_and(|n| !n.trim().is_empty()) {
|
||
let made: Vec<String> = s.model.state().bodies.iter().filter(|b| b.feature == id).map(|b| b.name.clone()).collect();
|
||
if made.len() > names.len()
|
||
&& let Some(f) = s.doc_mut().feature_mut(id)
|
||
{
|
||
f.body_names = made;
|
||
}
|
||
}
|
||
let r = s.model.result(id).cloned();
|
||
if let Some(e) = r.as_ref().and_then(|r| r.error.clone()) {
|
||
return Err(EngineError::Other(e));
|
||
}
|
||
let st = s.model.state();
|
||
let bodies: Vec<&str> = st.bodies.iter().map(|b| b.name.as_str()).collect();
|
||
// Bodies that were there before and now have other geometry, and bodies that are gone.
|
||
let old: std::collections::HashMap<&str, &solidcraft_doc::kernel::Body> = before.bodies.iter().map(|b| (b.name.as_str(), &b.body)).collect();
|
||
// The bodies this feature made, apart from the ones it changed or that were there (#374),
|
||
// and the pieces a cut left of a body made earlier, which keep that body's feature.
|
||
let created: Vec<&str> = st.bodies.iter().filter(|b| b.feature == id || !old.contains_key(b.name.as_str())).map(|b| b.name.as_str()).collect();
|
||
let now: std::collections::HashSet<&str> = st.bodies.iter().map(|b| b.name.as_str()).collect();
|
||
let changed: Vec<&str> =
|
||
st.bodies.iter().filter(|b| b.feature != id && old.get(b.name.as_str()).is_some_and(|o| !o.same(&b.body))).map(|b| b.name.as_str()).collect();
|
||
let removed: Vec<&str> = before.bodies.iter().map(|b| b.name.as_str()).filter(|n| !now.contains(n)).collect();
|
||
let fname = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
|
||
// A warning (a reference found again elsewhere, a reduced radius) is part of
|
||
// the reply: a script or an agent sees it without asking the timeline (#616).
|
||
let warning = r.as_ref().and_then(|r| r.warning.clone());
|
||
// A join that split pieces touching along an edge or at a point into bodies of their own says
|
||
// so, with the edit that makes them one body instead.
|
||
let notice = r.as_ref().and_then(|r| r.state.kept_separate(id)).map(|kept| FeatureNotice {
|
||
message: kept.notice().to_string(),
|
||
contact: kept.id().to_string(),
|
||
action: NoticeAction {
|
||
label: "Make one body".into(),
|
||
command: "timeline.edit".into(),
|
||
params: json!({"feature": id, "set": {"touching": "one_body"}}),
|
||
},
|
||
});
|
||
let owned = |names: Vec<&str>| names.into_iter().map(str::to_string).collect();
|
||
let reply = FeatureResult {
|
||
feature: id,
|
||
name: fname,
|
||
bodies: owned(bodies),
|
||
created_bodies: owned(created),
|
||
changed_bodies: owned(changed),
|
||
removed_bodies: owned(removed),
|
||
warning,
|
||
notice,
|
||
ms: r.map(|r| r.ms),
|
||
param_warnings: Vec::new(),
|
||
};
|
||
serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
|
||
}
|
||
|
||
fn extrude(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.extrude";
|
||
let grouped = if let Some(value) = p.get("faces") {
|
||
if p.get("face").is_some() || p.get("sketch").is_some() || p.get("profiles").is_some() {
|
||
return Err(bad(cmd, "faces cannot be combined with face, sketch or profiles"));
|
||
}
|
||
let faces = value
|
||
.as_array()
|
||
.filter(|faces| !faces.is_empty() && faces.len() <= 1024)
|
||
.ok_or_else(|| bad(cmd, "faces must contain between 1 and 1024 points"))?;
|
||
let points = faces.iter().map(|point| vec3(point).ok_or_else(|| bad(cmd, "faces must be points [x,y,z]"))).collect::<Result<Vec<_>>>()?;
|
||
let (id, points, body) = super::face::sketch_of_faces(s, &points, cmd, str_(p, "face_body"))?;
|
||
Some((id, Some(ProfileSel::Points { points }), Some(body)))
|
||
} else {
|
||
None
|
||
};
|
||
// A planar body face extrudes like a profile: its boundary is copied into a sketch on it.
|
||
let (sketch, face_profile, face_body) = if let Some(grouped) = grouped {
|
||
grouped
|
||
} else {
|
||
match p.get("face").and_then(vec3) {
|
||
Some(fp) => {
|
||
let (id, inside, body) = super::face::sketch_of_face(s, fp, cmd, str_(p, "face_body"))?;
|
||
(id, Some(ProfileSel::Points { points: vec![inside] }), Some(body))
|
||
}
|
||
None => (feature_sketch(s, p, cmd)?, None, None),
|
||
}
|
||
};
|
||
let extent = extent_param(s, p, cmd)?;
|
||
let thin = match bool_(p, "thin") {
|
||
Some(true) => {
|
||
if face_profile.is_some() || p.get("profiles").is_some() {
|
||
return Err(bad(cmd, "a thin extrude follows `curves`; it takes no `profiles` or `face`"));
|
||
}
|
||
Some(thin_param(s, p, sketch, cmd)?)
|
||
}
|
||
_ if p.get("thin").is_some_and(|v| !v.is_boolean()) => return Err(bad(cmd, "`thin` must be true or false")),
|
||
_ => None,
|
||
};
|
||
let operation = match str_(p, "operation") {
|
||
Some(o) if o.eq_ignore_ascii_case("auto") => {
|
||
Operation::parse(auto_operation_in(s, p, &s.model.state()).unwrap_or("new")).unwrap_or(Operation::NewBody)
|
||
}
|
||
_ => operation(p, cmd)?,
|
||
};
|
||
let mut targets = string_list(cmd, p, "targets")?;
|
||
let mut p = std::borrow::Cow::Borrowed(p);
|
||
if operation == Operation::Join && targets.is_empty() && string_list(cmd, &p, "participants")?.is_empty() {
|
||
// A face's outward extension joins that body, and so does a profile sketched on a body's
|
||
// face. Assembly neighbours can touch only an edge of the tool: trying to join them
|
||
// first fails, or absorbs unrelated parts (#226). A profile drawn past the face can lie
|
||
// on a neighbour's face too: a rib on a bracket's side welded in the motor the bracket
|
||
// holds, a join that ran for minutes and failed (#1349).
|
||
// Store the resolved target so recomputes and reopening keep the same scope.
|
||
targets.extend(match face_body {
|
||
Some(body) => Some(body),
|
||
None => face_body_reached(s, sketch)?,
|
||
});
|
||
} else if let Some(parts) = cut_scope(s, &p, operation, sketch, face_body, cmd)? {
|
||
p.to_mut()["participants"] = json!(parts);
|
||
}
|
||
let kind = FeatureKind::Extrude {
|
||
sketch: SketchId(sketch),
|
||
profiles: match face_profile {
|
||
Some(f) => f,
|
||
None if thin.is_some() => ProfileSel::All,
|
||
None if p.get("profiles").is_none() => default_extrude_profiles(s, sketch),
|
||
None => profiles(&p, cmd)?,
|
||
},
|
||
extent,
|
||
operation,
|
||
targets: targets.into_iter().map(BodyName).collect(),
|
||
thin,
|
||
};
|
||
add_feature(s, &p, kind)
|
||
}
|
||
|
||
/// The bodies a cut or intersect from a profile on a body's face takes part in when it names
|
||
/// none and that body is in a component inside the active one (#5679): the active component's
|
||
/// own bodies, as by default, and that body. `None` when the default already reaches it: it is
|
||
/// one of the active component's, or a component with no body of its own cuts every body.
|
||
fn cut_scope(s: &Session, p: &Value, operation: Operation, sketch: u64, face_body: Option<String>, cmd: &str) -> Result<Option<Vec<String>>> {
|
||
if !matches!(operation, Operation::Cut | Operation::Intersect)
|
||
|| !string_list(cmd, p, "targets")?.is_empty()
|
||
|| !string_list(cmd, p, "participants")?.is_empty()
|
||
{
|
||
return Ok(None);
|
||
}
|
||
let Some(body) = face_body_reached(s, sketch)?.or(face_body) else { return Ok(None) };
|
||
let st = s.model.state();
|
||
if s.cut_takes_every_body(&st) {
|
||
return Ok(None);
|
||
}
|
||
let mut parts: Vec<String> = active_scope(s, &st).into_iter().map(|b| b.name.clone()).collect();
|
||
let within = st.body(&body).is_some_and(|b| s.doc.component_within(s.doc.model_body_component(b), s.active_component));
|
||
if parts.contains(&body) || !within {
|
||
return Ok(None);
|
||
}
|
||
parts.push(body);
|
||
Ok(Some(parts))
|
||
}
|
||
|
||
/// The profiles an extrude takes when `profiles` is omitted: even-odd nesting over what was drawn,
|
||
/// so a loop inside an outline is its hole and a loop inside that hole is material again (#5172).
|
||
/// Without nesting this is `All`, as before. When the pick cannot be stored so that it finds the
|
||
/// same profiles again (the sketch is not solved, or two profiles share their curves), it stays
|
||
/// `All` too.
|
||
fn default_extrude_profiles(s: &Session, sketch: u64) -> ProfileSel {
|
||
let st = s.model.state();
|
||
let Some(ss) = st.sketch(sketch) else { return ProfileSel::All };
|
||
let drawn = solidcraft_sketch::find_drawn_profiles(&ss.sketch);
|
||
let ps = if drawn.is_empty() { ss.profiles.clone() } else { drawn };
|
||
if ps.len() > 10_000 || ps.iter().all(|p| p.region.holes.is_empty()) {
|
||
return ProfileSel::All;
|
||
}
|
||
// Each profile has the profiles directly inside it as holes, so the number of holes around a
|
||
// point of a profile's material is its nesting depth.
|
||
let material: Vec<_> = ps
|
||
.iter()
|
||
.filter(|p| {
|
||
let probe = p.region.interior_point();
|
||
ps.iter().filter(|other| other.region.holes.iter().any(|hole| hole.contains(probe))).count() % 2 == 0
|
||
})
|
||
.collect();
|
||
let all = solidcraft_sketch::without_text_counters(&ss.sketch, ps.clone());
|
||
if material.iter().map(|p| &p.outer_curves).eq(all.iter().map(|p| &p.outer_curves)) {
|
||
return ProfileSel::All;
|
||
}
|
||
// Profiles of the solved sketch itself are stored by index, which `stable_profiles` turns
|
||
// into curves; drawn profiles of a sketch with projected references are named by curves.
|
||
let same = ps.len() == ss.profiles.len() && ps.iter().zip(&ss.profiles).all(|(a, b)| a.outer_curves == b.outer_curves);
|
||
let sel = if same {
|
||
let indices = ps.iter().enumerate().filter(|(_, p)| material.iter().any(|m| std::ptr::eq(*m, *p))).map(|(i, _)| i).collect();
|
||
ProfileSel::Indices { indices }
|
||
} else {
|
||
ProfileSel::Curves { loops: material.iter().map(|p| p.outer_curves.clone()).collect() }
|
||
};
|
||
match solidcraft_doc::profile_selection_indices(ss, &sel) {
|
||
Ok(found) if found.len() == material.len() && material.iter().all(|p| !p.outer_curves.is_empty()) => sel,
|
||
_ => ProfileSel::All,
|
||
}
|
||
}
|
||
|
||
/// The matrix taking a point of the active component's frame into the frame `b`'s geometry is
|
||
/// kept in, as the evaluator moves a tool into it; `None` when the two are the same.
|
||
fn into_body_frame(s: &Session, b: &solidcraft_doc::ModelBody) -> Option<solidcraft_doc::Mat> {
|
||
let frame = s.doc.component_transform(s.doc.model_body_component(b));
|
||
let world = s.doc.model_body_offset(b).map_or(frame, |offset| solidcraft_doc::mat_mul(&frame, offset));
|
||
let active = s.doc.component_transform(s.active_component);
|
||
if world == active {
|
||
return None;
|
||
}
|
||
solidcraft_doc::mat_inverse(&world).map(|into| solidcraft_doc::mat_mul(&into, &active))
|
||
}
|
||
|
||
/// The body whose face `sketch` is attached to, when a join or cut made in the active component
|
||
/// can change it: one of the active component's own ([`active_scope`]), or one in a component
|
||
/// inside it, moved or turned, which is changed in its own component, so every placement of that
|
||
/// component shows the change (#5679). `Ok(None)` when the sketch is not on a face, or the body is
|
||
/// outside the active component. Refused where the change can't be made in the body's component:
|
||
/// its bodies come from a linked design file, or the face was picked on a further placement of a
|
||
/// component placed more than once (the change is drawn at the first).
|
||
fn face_body_reached(s: &Session, sketch: u64) -> Result<Option<String>> {
|
||
let Some(FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor: Some(anchor), .. }, .. }) = s.doc.feature(sketch).map(|f| &f.kind)
|
||
else {
|
||
return Ok(None);
|
||
};
|
||
let st = s.model.state();
|
||
if let Some(own) = active_scope(s, &st).into_iter().find(|b| b.name == anchor.target.body) {
|
||
return Ok(Some(own.name.clone()));
|
||
}
|
||
let Some(body) = st.body(&anchor.target.body) else { return Ok(None) };
|
||
let component = s.doc.model_body_component(body);
|
||
if !s.doc.component_within(component, s.active_component) {
|
||
return Ok(None);
|
||
}
|
||
let name = |c: u64| s.doc.components.iter().find(|x| x.id == c).map_or_else(|| format!("component {c}"), |x| x.name.clone());
|
||
let mut c = component;
|
||
for _ in 0..1000 {
|
||
if c == s.active_component || c == 0 {
|
||
break;
|
||
}
|
||
if s.doc.links.contains_key(&c) {
|
||
return Err(EngineError::Other(format!(
|
||
"`{}` is in {}, which is linked to a design file: open that design to change it, or break the link first",
|
||
body.name,
|
||
name(c)
|
||
)));
|
||
}
|
||
match s.doc.components.iter().find(|x| x.id == c) {
|
||
Some(x) => c = x.parent,
|
||
None => break,
|
||
}
|
||
}
|
||
if !anchor.path.is_empty() && anchor.path != s.doc.first_path(component) {
|
||
return Err(EngineError::Other(format!(
|
||
"`{}` is in {}, which is placed more than once, and the sketch is on another placement than the first: activate that placement of {} to cut or join it there",
|
||
body.name,
|
||
name(component),
|
||
name(component)
|
||
)));
|
||
}
|
||
Ok(Some(body.name.clone()))
|
||
}
|
||
|
||
/// The body whose face `sketch` is attached to (on the face itself, not offset from it), when
|
||
/// it is one the active component works on ([`active_scope`]).
|
||
fn sketch_face_body(s: &Session, sketch: u64) -> Option<String> {
|
||
let FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor: Some(anchor), .. }, .. } = &s.doc.feature(sketch)?.kind else {
|
||
return None;
|
||
};
|
||
let st = s.model.state();
|
||
active_scope(s, &st).into_iter().find(|b| b.name == anchor.target.body).map(|b| b.name.clone())
|
||
}
|
||
|
||
/// The bodies a Join named none for: the body whose face a profile sketch is on (the first
|
||
/// sketch that is on one), as for an extrude, also in a component inside the active one, moved
|
||
/// or turned (#5679; refused as [`face_body_reached`] says). Explicit `targets` or
|
||
/// `participants` keep theirs.
|
||
fn face_join_targets(s: &Session, p: &Value, operation: Operation, sketches: &[u64], cmd: &str) -> Result<Vec<BodyName>> {
|
||
let mut targets = string_list(cmd, p, "targets")?;
|
||
if operation == Operation::Join && targets.is_empty() && string_list(cmd, p, "participants")?.is_empty() {
|
||
for sketch in sketches {
|
||
if let Some(body) = face_body_reached(s, *sketch)? {
|
||
targets.push(body);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
Ok(targets.into_iter().map(BodyName).collect())
|
||
}
|
||
|
||
/// The bodies a Join, Cut or Intersect that names none may change, less the hidden ones, when
|
||
/// some of them are hidden: stored as the feature's `targets`, so a hidden body is left alone
|
||
/// (#3961, #6901) and showing it again later doesn't change the model. None when every one is
|
||
/// shown; empty when none is.
|
||
pub fn shown_scope(s: &Session) -> Option<Vec<String>> {
|
||
let st = s.model.state();
|
||
let scope = active_scope(s, &st);
|
||
if scope.iter().all(|b| s.body_visible(&b.name)) {
|
||
return None;
|
||
}
|
||
Some(scope.into_iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect())
|
||
}
|
||
|
||
/// The bodies a feature of the active component works on when it names none: the component's
|
||
/// own. A component with no body of its own (the root of an opened STEP assembly, whose parts
|
||
/// are components inside it) works on the bodies of the components inside it whose geometry is
|
||
/// in its own frame, as an import places it: a profile sketched on such a part's face meets the
|
||
/// part where it is shown (#3223).
|
||
fn active_scope<'a>(s: &Session, st: &'a solidcraft_doc::ModelState) -> Vec<&'a solidcraft_doc::ModelBody> {
|
||
let active = s.active_component;
|
||
let own: Vec<_> = st.bodies.iter().filter(|b| s.doc.model_body_component(b) == active).collect();
|
||
if !own.is_empty() {
|
||
return own;
|
||
}
|
||
let Some(into_active) = solidcraft_doc::mat_inverse(&s.doc.component_transform(active)) else { return own };
|
||
st.bodies
|
||
.iter()
|
||
.filter(|b| {
|
||
let comp = s.doc.model_body_component(b);
|
||
if !s.doc.component_within(comp, active) {
|
||
return false;
|
||
}
|
||
let frame = s.doc.component_transform(comp);
|
||
let world = s.doc.model_body_offset(b).map_or(frame, |offset| solidcraft_doc::mat_mul(&frame, offset));
|
||
let rel = solidcraft_doc::mat_mul(&into_active, &world);
|
||
rel.iter().flatten().zip(solidcraft_doc::IDENTITY.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-9)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// A thin extrude's wall from its parameters: the sketch's curves it follows (every drawn
|
||
/// curve when none are given), its thickness and which side of them it lies on.
|
||
fn thin_param(s: &Session, p: &Value, sketch: u64, cmd: &str) -> Result<ThinWall> {
|
||
let st = s.model.state();
|
||
let ss = st.sketch(sketch).ok_or_else(|| bad(cmd, "the sketch is not evaluated"))?;
|
||
let mut curves = string_list(cmd, p, "curves")?;
|
||
if curves.is_empty() {
|
||
curves =
|
||
ss.sketch.curves.iter().filter(|c| !c.construction && !c.centerline && !c.infinite && c.link.is_none()).map(|c| c.id.clone()).collect();
|
||
}
|
||
if curves.is_empty() || curves.len() > 1000 {
|
||
return Err(bad(cmd, "a thin extrude needs 1…1000 sketch curves (`curves`)"));
|
||
}
|
||
if let Some(c) = curves.iter().find(|c| ss.sketch.curve_index(c).is_none()) {
|
||
return Err(bad(cmd, format!("no curve `{c}` in the sketch")));
|
||
}
|
||
let thickness = req_expr(cmd, p, "thickness")?;
|
||
check_expr(s, &thickness, Kind::Length, cmd, "thickness")?;
|
||
let side = match str_(p, "side") {
|
||
None => ThinSide::Center,
|
||
Some(o) => ThinSide::parse(o).ok_or_else(|| bad(cmd, format!("unknown side `{o}` (center, inside, outside or two_sides)")))?,
|
||
};
|
||
let thickness2 = expr(p, "thickness2");
|
||
match (&thickness2, side) {
|
||
(Some(t), ThinSide::TwoSides) => check_expr(s, t, Kind::Length, cmd, "thickness2")?,
|
||
(None, ThinSide::TwoSides) => return Err(bad(cmd, "`side: two_sides` needs `thickness2` (the thickness outside)")),
|
||
(Some(_), _) => return Err(bad(cmd, "`thickness2` goes with `side: two_sides`")),
|
||
(None, _) => {}
|
||
}
|
||
let thin = ThinWall { curves, thickness, side, thickness2 };
|
||
// Refuse a wall that can't be built now, with the reason, rather than a failed feature.
|
||
thin_regions(s, ss, &thin).map_err(|e| bad(cmd, e))?;
|
||
Ok(thin)
|
||
}
|
||
|
||
/// The regions of a thin wall in its (solved) sketch, with the current parameter values.
|
||
fn thin_regions(s: &Session, ss: &solidcraft_doc::SolvedSketch, thin: &ThinWall) -> std::result::Result<Vec<solidcraft_geom::Region2>, String> {
|
||
let length = |e: &str| s.doc.eval(&s.doc.with_design_unit(e, Kind::Length), Kind::Length).map_err(|e| e.to_string());
|
||
let t = length(&thin.thickness)?;
|
||
let (inside, outside) = match thin.side {
|
||
ThinSide::Center => (t / 2.0, t / 2.0),
|
||
ThinSide::Inside => (t, 0.0),
|
||
ThinSide::Outside => (0.0, t),
|
||
ThinSide::TwoSides => (t, length(thin.thickness2.as_deref().unwrap_or("0"))?),
|
||
};
|
||
let curves: Vec<Vec<solidcraft_geom::Seg2>> = thin
|
||
.curves
|
||
.iter()
|
||
.filter_map(|id| ss.sketch.curve_index(id))
|
||
.map(|ci| ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci)))
|
||
.collect();
|
||
solidcraft_sketch::thin_wall_regions(&curves, inside, outside).map_err(|e| format!("thin wall: {e}"))
|
||
}
|
||
|
||
/// An extrude's extent from its parameters: distance (or through all, or to an object), the
|
||
/// side(s), a second distance, a start offset, a taper, and from an object.
|
||
pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result<Extent> {
|
||
let through_all = bool_(p, "through_all").unwrap_or(false) || str_(p, "extent").is_some_and(|e| e.eq_ignore_ascii_case("through_all"));
|
||
let to_object = p.get("to").is_some();
|
||
if to_object && p.get("to").and_then(vec3).is_none() {
|
||
return Err(bad(cmd, "`to` must be a point [x, y, z] on the face, vertex or point to extrude to"));
|
||
}
|
||
if p.get("from").is_some() && p.get("from").and_then(vec3).is_none() {
|
||
return Err(bad(cmd, "`from` must be a point [x, y, z] on the face or point to start from"));
|
||
}
|
||
let distance = if through_all || to_object { expr(p, "distance").unwrap_or_else(|| "0".into()) } else { req_expr(cmd, p, "distance")? };
|
||
check_expr(s, &distance, Kind::Length, cmd, "distance")?;
|
||
let taper = expr(p, "taper");
|
||
if let Some(t) = &taper {
|
||
check_expr(s, t, Kind::Angle, cmd, "taper")?;
|
||
}
|
||
let corner = match p.get("corner") {
|
||
None => None,
|
||
Some(value) => Some(serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`corner` must be preserve_curvature, tangent or round"))?),
|
||
};
|
||
let direction = match str_(p, "direction").map(str::to_ascii_lowercase).as_deref() {
|
||
None | Some("positive") | Some("one_side") => Direction::Positive,
|
||
Some("negative") | Some("reverse") | Some("flip") => Direction::Negative,
|
||
Some("symmetric") => Direction::Symmetric,
|
||
Some(o) => return Err(bad(cmd, format!("unknown direction `{o}`"))),
|
||
};
|
||
let distance2 = expr(p, "distance2");
|
||
if let Some(d) = &distance2 {
|
||
check_expr(s, d, Kind::Length, cmd, "distance2")?;
|
||
}
|
||
let start_offset = expr(p, "start_offset");
|
||
if let Some(d) = &start_offset {
|
||
check_expr(s, d, Kind::Length, cmd, "start_offset")?;
|
||
}
|
||
// A symmetric distance the call doesn't qualify is the total, split evenly around the start
|
||
// plane, for solid and surface extrudes alike.
|
||
let convention = match p.get("convention") {
|
||
None => solidcraft_doc::ExtrudeConvention::TotalDistance,
|
||
Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`convention` must be total_distance or legacy_per_side"))?,
|
||
};
|
||
Ok(Extent {
|
||
distance,
|
||
convention,
|
||
direction,
|
||
distance2,
|
||
start_offset,
|
||
through_all,
|
||
taper,
|
||
corner,
|
||
to: p.get("to").and_then(vec3).map(FacePick),
|
||
to_offset: expr(p, "to_offset"),
|
||
from: p.get("from").and_then(vec3).map(FacePick),
|
||
to_body_apart: false,
|
||
})
|
||
}
|
||
|
||
fn revolve(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.revolve";
|
||
// A planar body face revolves like a profile (its edges projected into a sketch on it).
|
||
let (sketch, face_profile) = match p.get("face").and_then(vec3) {
|
||
Some(fp) => {
|
||
let (id, inside, _) = super::face::sketch_of_face(s, fp, cmd, str_(p, "face_body"))?;
|
||
s.active_sketch = None;
|
||
(id, Some(ProfileSel::Points { points: vec![inside] }))
|
||
}
|
||
None => (feature_sketch(s, p, cmd)?, None),
|
||
};
|
||
let axis = axis_param(s, sketch, p, cmd)?;
|
||
let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into());
|
||
check_expr(s, &angle, Kind::Angle, cmd, "angle")?;
|
||
let profiles = match face_profile {
|
||
Some(f) => f,
|
||
None => profiles(p, cmd)?,
|
||
};
|
||
let angle2 = expr(p, "angle2");
|
||
if let Some(a) = &angle2 {
|
||
check_expr(s, a, Kind::Angle, cmd, "angle2")?;
|
||
}
|
||
let to = match p.get("to") {
|
||
Some(v) => Some(vec3(v).ok_or_else(|| bad(cmd, "`to` must be a point [x, y, z] to turn to"))?),
|
||
None => None,
|
||
};
|
||
let symmetric =
|
||
matches!(str_(p, "direction").map(str::to_ascii_lowercase).as_deref(), Some("symmetric")) || bool_(p, "symmetric").unwrap_or(false);
|
||
let convention = match p.get("convention") {
|
||
None => solidcraft_doc::RevolveConvention::SketchNormal,
|
||
Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`convention` must be sketch_normal or legacy_axis_start"))?,
|
||
};
|
||
let operation = operation(p, cmd)?;
|
||
let targets = face_join_targets(s, p, operation, &[sketch], cmd)?;
|
||
// From a profile on a body's face in a component inside the active one, a cut changes that
|
||
// body too, as an extrude's does (#5679).
|
||
let mut p = std::borrow::Cow::Borrowed(p);
|
||
if let Some(parts) = cut_scope(s, &p, operation, sketch, None, cmd)? {
|
||
p.to_mut()["participants"] = json!(parts);
|
||
}
|
||
let kind = FeatureKind::Revolve {
|
||
sketch: SketchId(sketch),
|
||
profiles,
|
||
axis,
|
||
angle,
|
||
operation,
|
||
targets,
|
||
angle2,
|
||
symmetric,
|
||
convention,
|
||
to: to.map(FacePick),
|
||
};
|
||
add_feature(s, &p, kind)
|
||
}
|
||
|
||
/// A revolve axis of `sketch` from its parameter: a sketch line id, the sketch's x or y axis, a
|
||
/// world axis (also as saved: {type: world, axis: X|Y|Z}), a construction axis by name
|
||
/// (followed when it is edited), {origin, dir}, or an edge
|
||
/// or round face of the model ({edge|face: [x,y,z]}), which the revolve follows as the model
|
||
/// changes. A line of the sketch wins over a construction axis of the same name.
|
||
pub(super) fn axis_param(s: &Session, sketch: u64, p: &Value, cmd: &str) -> Result<AxisRef> {
|
||
if let Some((geo, ..)) = super::construct::model_axis_param(s, p.get("axis"), cmd)? {
|
||
return Ok(AxisRef::Model { geo });
|
||
}
|
||
if let Some(o) = p.get("axis").filter(|v| v.is_object()) {
|
||
if str_(o, "type") == Some("world") {
|
||
let axis =
|
||
str_(o, "axis").filter(|a| matches!(*a, "X" | "Y" | "Z")).ok_or_else(|| bad(cmd, "world axis requires `axis` to be X, Y or Z"))?;
|
||
return Ok(AxisRef::World { axis: axis.into() });
|
||
}
|
||
let origin = o.get("origin").and_then(vec3).unwrap_or(Vec3::ZERO);
|
||
let dir = o.get("dir").and_then(vec3).ok_or_else(|| bad(cmd, "axis needs `dir`"))?;
|
||
return Ok(AxisRef::Line { origin: Position(origin), dir: Dir(dir) });
|
||
}
|
||
match str_(p, "axis") {
|
||
Some(a @ ("X" | "Y" | "Z")) => Ok(AxisRef::World { axis: a.into() }),
|
||
Some(a @ ("x" | "y")) => Ok(AxisRef::SketchAxis { axis: a.into() }),
|
||
Some(name) if !is_sketch_line(s, sketch, name) && is_construction_axis(s, name) => Ok(AxisRef::Construction { name: name.into() }),
|
||
Some(id) => Ok(AxisRef::SketchLine { curve: id.into() }),
|
||
None => {
|
||
Err(bad(cmd, "`axis` must be a sketch line id, x, y (sketch axes), X, Y, Z, a construction axis, {origin, dir} or {edge|face: [x,y,z]}"))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Whether `curve` is a curve of the sketch feature `sketch`.
|
||
fn is_sketch_line(s: &Session, sketch: u64, curve: &str) -> bool {
|
||
matches!(s.doc.feature(sketch).map(|f| &f.kind), Some(FeatureKind::Sketch { sketch, .. }) if sketch.curve_index(curve).is_some())
|
||
}
|
||
|
||
/// Whether `name` is a construction axis feature of the design.
|
||
fn is_construction_axis(s: &Session, name: &str) -> bool {
|
||
s.doc.find_feature(name).is_some_and(|f| matches!(f.kind, FeatureKind::ConstructionAxis { .. }))
|
||
}
|
||
|
||
fn radius_expr(s: &Session, p: &Value, cmd: &str) -> Result<Expr> {
|
||
match (expr(p, "radius"), expr(p, "diameter")) {
|
||
(Some(r), _) => Ok(r),
|
||
(None, Some(d)) => {
|
||
let [d] = length_operands(s, [(&d, &typed_length_unit(s))]);
|
||
Ok(format!("({d}) / 2").into())
|
||
}
|
||
_ => Err(bad(cmd, "needs `radius` or `diameter`")),
|
||
}
|
||
}
|
||
|
||
/// The unit a bare length typed into a command means: the design's units. (A point's bare
|
||
/// coordinates, and a bare number already stored in a feature, are millimetres.)
|
||
pub(super) fn typed_length_unit(s: &Session) -> String {
|
||
solidcraft_doc::expr::length_unit_or_mm(&s.doc.units).to_string()
|
||
}
|
||
|
||
/// The lengths a command works one expression out from (a radius from a diameter, a pitch from
|
||
/// a height), each with the unit a bare number means where it came from. Bare numbers get that
|
||
/// unit written in, so the expression keeps the meaning they had: inside a larger expression a
|
||
/// bare number is read in the design's units of the moment, and changing them would resize the
|
||
/// part (#716). Next to a unit-less expression that is not a bare number (`2 * 5`, a unit-less
|
||
/// parameter), which is read in the design's units itself, they stay bare and are read with it,
|
||
/// as before.
|
||
pub(super) fn length_operands<const N: usize>(s: &Session, operands: [(&str, &str); N]) -> [String; N] {
|
||
use solidcraft_doc::expr::is_bare_number;
|
||
let follows = operands.iter().any(|(e, _)| !is_bare_number(e) && s.doc.eval(e, Kind::Unitless).is_ok());
|
||
operands.map(|(e, unit)| if !follows && is_bare_number(e) { format!("{} {unit}", e.trim()) } else { e.to_string() })
|
||
}
|
||
|
||
/// A placement point: `[x, y, z]` (or `{x, y, z}`) of numbers (mm) or length expressions;
|
||
/// the origin when it is not given. Anything else is refused (never read as the origin).
|
||
pub(super) fn point_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<PointExpr>> {
|
||
let Some(v) = p.get(key) else { return Ok(None) };
|
||
let want = || bad(cmd, format!("`{key}` must be a point [x, y, z] of numbers or length expressions"));
|
||
let coords: Vec<&Value> = match v {
|
||
Value::Array(a) if a.len() == 3 => a.iter().collect(),
|
||
Value::Object(o) => ["x", "y", "z"].iter().map(|k| o.get(*k)).collect::<Option<Vec<_>>>().ok_or_else(want)?,
|
||
_ => return Err(want()),
|
||
};
|
||
let mut out = PointExpr::default();
|
||
for (slot, (c, axis)) in out.iter_mut().zip(coords.into_iter().zip(["x", "y", "z"])) {
|
||
let e = expr(&json!({ "v": c }), "v").ok_or_else(want)?;
|
||
let x = s.doc.eval(&e, Kind::Length).map_err(|err| bad(cmd, format!("{key} {axis}: {err}")))?;
|
||
if !(x.is_finite() && x.abs() < 1e9) {
|
||
return Err(bad(cmd, format!("{key} {axis} is out of range")));
|
||
}
|
||
*slot = e;
|
||
}
|
||
Ok(Some(out))
|
||
}
|
||
|
||
/// An axis direction: X|Y|Z or a non-zero `[x, y, z]`; `Z` when it is not given.
|
||
pub(super) fn axis_dir_param(p: &Value, cmd: &str) -> Result<Vec3> {
|
||
match p.get("axis") {
|
||
None => Ok(Vec3::Z),
|
||
Some(v) => axis_dir_form(v).map_err(|why| bad(cmd, why)),
|
||
}
|
||
}
|
||
|
||
/// What [`axis_dir_param`] reads a given `axis` as, without the design: X, Y or Z (trimmed, any
|
||
/// case), else a non-zero `[x, y, z]`, normalized.
|
||
pub(crate) fn axis_dir_form(v: &Value) -> std::result::Result<Vec3, &'static str> {
|
||
match v {
|
||
Value::String(a) => match a.trim().to_ascii_uppercase().as_str() {
|
||
"X" => Ok(Vec3::X),
|
||
"Y" => Ok(Vec3::Y),
|
||
"Z" => Ok(Vec3::Z),
|
||
_ => Err("`axis` must be X, Y, Z or [x, y, z]"),
|
||
},
|
||
v => vec3(v).and_then(|a| a.normalized()).ok_or("`axis` must be X, Y, Z or a non-zero [x, y, z]"),
|
||
}
|
||
}
|
||
|
||
fn prim_box(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.box";
|
||
let (l, w, h) = (req_expr(cmd, p, "length")?, req_expr(cmd, p, "width")?, req_expr(cmd, p, "height")?);
|
||
for (e, n) in [(&l, "length"), (&w, "width"), (&h, "height")] {
|
||
check_expr(s, e, Kind::Length, cmd, n)?;
|
||
}
|
||
let corner = match (point_param(s, p, "corner", cmd)?, point_param(s, p, "center", cmd)?) {
|
||
(Some(c), _) => c,
|
||
// The corner half a size back from the centre (numbers stay numbers, in mm). The centre's
|
||
// bare numbers are millimetres, the sizes' the design's units.
|
||
(None, Some([cx, cy, cz])) => {
|
||
let unit = typed_length_unit(s);
|
||
let mm_per_unit = solidcraft_doc::expr::unit_info(&unit).map_or(1.0, |(_, k)| k);
|
||
let back = |c: Expr, size: &Expr| -> Expr {
|
||
match (c.parse::<f64>(), size.parse::<f64>()) {
|
||
(Ok(a), Ok(b)) => format!("{}", a - b * mm_per_unit / 2.0).into(),
|
||
_ => {
|
||
let [c, size] = length_operands(s, [(&c, "mm"), (size, &unit)]);
|
||
format!("({c}) - ({size}) / 2").into()
|
||
}
|
||
}
|
||
};
|
||
[back(cx, &l), back(cy, &w), back(cz, &h)]
|
||
}
|
||
_ => point_expr(Vec3::ZERO),
|
||
};
|
||
add_feature(s, p, FeatureKind::Box { corner, length: l, width: w, height: h, operation: operation(p, cmd)? })
|
||
}
|
||
|
||
fn prim_cylinder(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.cylinder";
|
||
let radius = radius_expr(s, p, cmd)?;
|
||
let height = req_expr(cmd, p, "height")?;
|
||
check_expr(s, &radius, Kind::Length, cmd, "radius")?;
|
||
check_expr(s, &height, Kind::Length, cmd, "height")?;
|
||
let base = point_param(s, p, "base", cmd)?.unwrap_or_else(|| point_expr(Vec3::ZERO));
|
||
let axis = axis_dir_param(p, cmd)?;
|
||
// Reference edges (#6380), as a Single hole's: the base centre sits at these distances from
|
||
// straight edges of the face it stands on, and `base` keeps where those put it.
|
||
let references = hole_reference_params(s, p, cmd)?;
|
||
let base = if references.is_empty() {
|
||
base
|
||
} else {
|
||
let at = p
|
||
.get("base")
|
||
.and_then(vec3)
|
||
.ok_or_else(|| bad(cmd, "`references` place a cylinder by its `base` given as numbers, not length expressions"))?;
|
||
point_expr(referenced_centre(s, cmd, &references, at, -axis)?)
|
||
};
|
||
add_feature(s, p, FeatureKind::Cylinder { base, axis: Dir(axis), radius, height, operation: operation(p, cmd)?, references })
|
||
}
|
||
|
||
fn prim_sphere(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.sphere";
|
||
let radius = radius_expr(s, p, cmd)?;
|
||
check_expr(s, &radius, Kind::Length, cmd, "radius")?;
|
||
let center = point_param(s, p, "center", cmd)?.unwrap_or_else(|| point_expr(Vec3::ZERO));
|
||
add_feature(s, p, FeatureKind::Sphere { center, radius, operation: operation(p, cmd)? })
|
||
}
|
||
|
||
fn prim_torus(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.torus";
|
||
let (major, minor) = (req_expr(cmd, p, "major")?, req_expr(cmd, p, "minor")?);
|
||
check_expr(s, &major, Kind::Length, cmd, "major")?;
|
||
check_expr(s, &minor, Kind::Length, cmd, "minor")?;
|
||
let center = point_param(s, p, "center", cmd)?.unwrap_or_else(|| point_expr(Vec3::ZERO));
|
||
add_feature(s, p, FeatureKind::Torus { center, major, minor, operation: operation(p, cmd)? })
|
||
}
|
||
|
||
/// A cone or truncated cone (#5641), placed and sized like a cylinder, with the top circle's
|
||
/// radius (or diameter) besides; none is a full cone.
|
||
fn prim_cone(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.cone";
|
||
let radius = radius_expr(s, p, cmd)?;
|
||
let top_radius = match (expr(p, "top_radius"), expr(p, "top_diameter")) {
|
||
(Some(r), _) => r,
|
||
(None, Some(d)) => {
|
||
let [d] = length_operands(s, [(&d, &typed_length_unit(s))]);
|
||
format!("({d}) / 2").into()
|
||
}
|
||
// Given but unreadable (a huge number, a list): refused, never a full cone instead.
|
||
(None, None) if p.get("top_radius").is_some() || p.get("top_diameter").is_some() => {
|
||
return Err(bad(cmd, "`top_radius` (or `top_diameter`) must be a length expression"));
|
||
}
|
||
(None, None) => "0".into(),
|
||
};
|
||
let height = req_expr(cmd, p, "height")?;
|
||
for (e, n) in [(&radius, "radius"), (&top_radius, "top_radius"), (&height, "height")] {
|
||
check_expr(s, e, Kind::Length, cmd, n)?;
|
||
}
|
||
let base = point_param(s, p, "base", cmd)?.unwrap_or_else(|| point_expr(Vec3::ZERO));
|
||
let axis = axis_dir_param(p, cmd)?;
|
||
add_feature(s, p, FeatureKind::Cone { base, axis: Dir(axis), radius, top_radius, height, operation: operation(p, cmd)? })
|
||
}
|
||
|
||
/// Edge references → points on the edges.
|
||
fn edge_points(s: &Session, p: &Value, cmd: &str) -> Result<Vec<Vec3>> {
|
||
let a = p.get("edges").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`edges` must be a list"))?;
|
||
if a.is_empty() || a.len() > 1000 {
|
||
return Err(bad(cmd, "select 1…1000 edges"));
|
||
}
|
||
let st = s.model.state();
|
||
// A picked point must lie on an edge (within the distance the kernel re-finds an edge from)
|
||
// of the body the feature names, or of any body: a pick far from every edge would round
|
||
// whichever edge is nearest (#783). Each body's edges are worked out once.
|
||
let named = str_(p, "body").filter(|n| st.body(n).is_some());
|
||
// Per body: its size, its edges' polylines and which of them are seams.
|
||
let mut candidates: Option<Vec<(f64, Vec<Vec<Vec3>>, Vec<bool>)>> = None;
|
||
let mut out = Vec::new();
|
||
for e in a {
|
||
let pt = match edge_ref_form(e).map_err(|why| bad(cmd, why))? {
|
||
EdgeRefForm::Point(pt) => pt,
|
||
EdgeRefForm::Index { body, index } => {
|
||
let idx = index as usize;
|
||
let b = st.body(body).ok_or_else(|| bad(cmd, format!("no body `{body}`")))?;
|
||
let tol = (b.body.size() * 2e-3).max(1e-3);
|
||
let edges = b.body.edges(tol)?;
|
||
out.push(edges.get(idx).ok_or_else(|| bad(cmd, format!("{body} has no edge {idx}")))?.mid);
|
||
continue;
|
||
}
|
||
};
|
||
let bodies = candidates.get_or_insert_with(|| {
|
||
// Mesh bodies have no edges to pick: rounding one is refused later, saying why.
|
||
st.bodies
|
||
.iter()
|
||
.filter(|b| named.is_none_or(|n| b.name == n) && !b.body.is_mesh())
|
||
.filter_map(|b| {
|
||
let size = b.body.size();
|
||
let tol = (size * 2e-3).max(1e-3);
|
||
// The display mesh flags seams (a smooth surface meeting itself, as down the side
|
||
// of a cylinder), which nobody means by a pick where they end.
|
||
match b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol)) {
|
||
// An edge where the faces meet tangentially (the spans of a spline wall
|
||
// meeting) can't be blended either: nobody means it by a pick.
|
||
Ok(m) => Some((
|
||
size,
|
||
m.edges,
|
||
m.seams
|
||
.iter()
|
||
.zip(&m.smooth_edges)
|
||
.map(|(s, t)| *s || *t)
|
||
.chain(m.seams.iter().skip(m.smooth_edges.len()).copied())
|
||
.collect(),
|
||
)),
|
||
Err(_) => b.body.edges(tol).ok().map(|edges| (size, edges.into_iter().map(|e| e.points).collect(), Vec::new())),
|
||
}
|
||
})
|
||
.collect()
|
||
});
|
||
// A point where several edges meet (a corner) is ambiguous: the kernel would round one of
|
||
// them, picked silently (#5173). Edges that carry straight on through the point (the two
|
||
// halves of a circle) are one edge to whoever picked it, and seams and tangent joins don't
|
||
// count. Directions
|
||
// come from the polylines' end chords, which lean off a curve's tangent: within about 45°
|
||
// of opposite counts as carrying on (edges at a real corner are far from opposite).
|
||
let mut nearest = f64::INFINITY;
|
||
let mut near = Vec::new();
|
||
for (size, edges, seams) in bodies.iter() {
|
||
for (i, points) in edges.iter().enumerate() {
|
||
let d = points.windows(2).filter_map(|w| Some(pt.dist_to_segment(*w.first()?, *w.get(1)?))).fold(f64::INFINITY, f64::min);
|
||
nearest = nearest.min(d);
|
||
if d <= size * 0.05 + 1e-3 {
|
||
near.push((d, seams.get(i).copied().unwrap_or(false), leaving(points, pt)));
|
||
}
|
||
}
|
||
}
|
||
let matches = near.len();
|
||
let mut meeting: Vec<Option<Vec3>> = near.iter().filter(|(d, seam, _)| !seam && *d <= nearest + 1e-3).map(|(_, _, dir)| *dir).collect();
|
||
let mut chains = 0usize;
|
||
while let Some(dir) = meeting.pop() {
|
||
chains += 1;
|
||
if let Some(dir) = dir
|
||
&& let Some(j) = meeting.iter().position(|o| o.is_some_and(|other| other.dot(dir) < -0.7))
|
||
{
|
||
meeting.swap_remove(j);
|
||
}
|
||
}
|
||
if chains > 1 {
|
||
return Err(bad(
|
||
cmd,
|
||
format!("[{}, {}, {}] is where {chains} edges meet: give a point along one edge, such as its midpoint", pt.x, pt.y, pt.z),
|
||
));
|
||
}
|
||
if matches == 0 && !bodies.is_empty() {
|
||
let far = if nearest.is_finite() { format!("the nearest edge is {nearest:.3} mm away") } else { "there is no edge".to_string() };
|
||
return Err(bad(cmd, format!("no edge at [{}, {}, {}]: {far}", pt.x, pt.y, pt.z)));
|
||
}
|
||
out.push(pt);
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
/// The direction an edge's polyline leaves `pt` in, when `pt` is one of its ends; `None` when
|
||
/// the edge runs on through `pt`.
|
||
fn leaving(points: &[Vec3], pt: Vec3) -> Option<Vec3> {
|
||
let (first, last) = (points.first()?, points.last()?);
|
||
if first.dist(pt) <= 1e-3 {
|
||
(*points.get(1)? - *first).normalized()
|
||
} else if last.dist(pt) <= 1e-3 {
|
||
(*points.get(points.len().checked_sub(2)?)? - *last).normalized()
|
||
} else {
|
||
None
|
||
}
|
||
}
|
||
|
||
/// An edge reference as given, before it is looked up: see [`edge_points`].
|
||
pub(crate) enum EdgeRefForm<'a> {
|
||
Point(Vec3),
|
||
Index { body: &'a str, index: u64 },
|
||
}
|
||
|
||
/// What [`edge_points`] reads one edge as, without the design: a point on it (`[x, y, z]` or
|
||
/// `{point}`), else `{body, index}`.
|
||
pub(crate) fn edge_ref_form(e: &Value) -> std::result::Result<EdgeRefForm<'_>, &'static str> {
|
||
if let Some(pt) = vec3(e).or_else(|| e.get("point").and_then(vec3)) {
|
||
return Ok(EdgeRefForm::Point(pt));
|
||
}
|
||
let body = e.get("body").and_then(Value::as_str).ok_or("an edge is a point [x,y,z], {point} or {body, index}")?;
|
||
let index = e.get("index").and_then(Value::as_u64).ok_or("edge `index` must be a number")?;
|
||
Ok(EdgeRefForm::Index { body, index })
|
||
}
|
||
|
||
/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); a
|
||
/// fillet's or chamfer's face changes that feature's size; an edge is rounded (a fillet).
|
||
fn press_pull(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.press_pull";
|
||
let distance = req_expr(cmd, p, "distance")?;
|
||
if p.get("edges").is_some() {
|
||
return fillet(s, &json!({"edges": p.get("edges"), "radius": distance}));
|
||
}
|
||
let face = p.get("face").ok_or_else(|| bad(cmd, "needs `face` or `edges`"))?;
|
||
let d = s.doc.eval(&distance, Kind::Length).map_err(|e| bad(cmd, format!("distance: {e}")))?;
|
||
if d.abs() < 1e-9 {
|
||
return Err(bad(cmd, "the distance must not be zero"));
|
||
}
|
||
// A fillet's or chamfer's face: its size changes by the distance (the feature is edited). A
|
||
// chamfer's face is flat, so this is asked before whether the face is planar (#4986).
|
||
if let Some(fp) = vec3(face) {
|
||
let name = solidcraft_doc::naming::face_names_at(&s.model.state(), &[fp]).into_iter().next().unwrap_or_default();
|
||
let fid = solidcraft_doc::persistent_name::made_by(&name);
|
||
if solidcraft_doc::persistent_name::is_blend(&name) {
|
||
let f = fid.and_then(|id| s.doc.feature(id)).cloned().ok_or_else(|| bad(cmd, "the blend's feature is gone"))?;
|
||
let (key, old) = match &f.kind {
|
||
FeatureKind::Fillet { radius, .. } => ("radius", radius.clone()),
|
||
FeatureKind::Chamfer { distance, .. } => ("distance", distance.clone()),
|
||
_ => return Err(bad(cmd, "that face is not a fillet's or a chamfer's")),
|
||
};
|
||
// A bare number stored in the feature is millimetres; the distance's, the design's units.
|
||
let [old, more] = length_operands(s, [(&old, "mm"), (&distance, &typed_length_unit(s))]);
|
||
let new = format!("({old}) + ({more})");
|
||
let r = super::find_command("timeline.edit").ok_or_else(|| bad(cmd, "timeline.edit"))?;
|
||
let out = (r.run)(s, &json!({"feature": f.id, "set": {key: new}}))?;
|
||
return Ok(json!({"feature": f.id, "edited": f.name, key: new, "recomputed": out.get("recomputed"), "restored": out.get("restored")}));
|
||
}
|
||
// Another curved face moves along its normal.
|
||
if super::face::face_is_planar(s, fp) == Some(false) {
|
||
let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?;
|
||
return (r.run)(s, &json!({"faces": [face], "distance": distance}));
|
||
}
|
||
}
|
||
// Pushed in: the extrude cuts the other way by as much (a bare number stays one, so it keeps
|
||
// being read as a bare number typed into the extrude).
|
||
let flipped = match distance.trim().parse::<f64>() {
|
||
Ok(v) if solidcraft_doc::expr::is_bare_number(&distance) => Expr::new(format!("{}", -v)),
|
||
_ => Expr::new(format!("-({distance})")),
|
||
};
|
||
let (dist, dir, op) = if d > 0.0 { (distance, "positive", "join") } else { (flipped, "negative", "cut") };
|
||
extrude(s, &json!({"face": face, "distance": dist, "direction": dir, "operation": op}))
|
||
}
|
||
|
||
fn fillet(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.fillet";
|
||
let edges = edge_points(s, p, cmd)?;
|
||
let radius = req_expr(cmd, p, "radius")?;
|
||
check_expr(s, &radius, Kind::Length, cmd, "radius")?;
|
||
let style = match str_(p, "type").map(str::to_ascii_lowercase).as_deref() {
|
||
None | Some("constant") | Some("rolling_ball") => solidcraft_doc::FilletStyle::Constant,
|
||
Some("chord") | Some("chord_length") => solidcraft_doc::FilletStyle::Chord,
|
||
Some("curvature") | Some("g2") => solidcraft_doc::FilletStyle::Curvature,
|
||
Some("variable") => {
|
||
let radius2 = req_expr(cmd, p, "radius2")?;
|
||
check_expr(s, &radius2, Kind::Length, cmd, "radius2")?;
|
||
let start =
|
||
p.get("start").and_then(vec3).ok_or_else(|| bad(cmd, "a variable fillet needs `start`: [x,y,z] near the end that takes `radius`"))?;
|
||
let mut mid = Vec::new();
|
||
for m in p.get("mid").and_then(Value::as_array).into_iter().flatten().take(100) {
|
||
let (Some(t), Some(r)) = (m.get(0).and_then(Value::as_f64), m.get(1)) else {
|
||
return Err(bad(cmd, "`mid` entries are [position, radius]"));
|
||
};
|
||
if !(t.is_finite() && t > 0.0 && t < 1.0) {
|
||
return Err(bad(cmd, "`mid` positions lie between 0 and 1 (from the start end)"));
|
||
}
|
||
let r = match r {
|
||
Value::String(x) => x.clone(),
|
||
Value::Number(n) => n.to_string(),
|
||
_ => return Err(bad(cmd, "a `mid` radius is a number or an expression")),
|
||
};
|
||
check_expr(s, &r, Kind::Length, cmd, "mid radius")?;
|
||
mid.push((t, r.into()));
|
||
}
|
||
let smooth = p.get("smooth").and_then(Value::as_bool).unwrap_or(false);
|
||
solidcraft_doc::FilletStyle::Variable { radius2, start: Position(start), mid, smooth }
|
||
}
|
||
Some("spline") => {
|
||
let start = p
|
||
.get("start")
|
||
.and_then(vec3)
|
||
.ok_or_else(|| bad(cmd, "a spline fillet needs `start`: [x,y,z] near the end its positions start from"))?;
|
||
let knots: Vec<f64> = p.get("knots").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_f64).collect();
|
||
let mut radii = Vec::new();
|
||
for r in p.get("radii").and_then(Value::as_array).into_iter().flatten().take(100) {
|
||
let r = match r {
|
||
Value::String(x) => x.clone(),
|
||
Value::Number(n) => n.to_string(),
|
||
_ => return Err(bad(cmd, "a control radius is a number or an expression")),
|
||
};
|
||
check_expr(s, &r, Kind::Length, cmd, "control radius")?;
|
||
radii.push(Expr::from(r));
|
||
}
|
||
// All control radii (`radius` and `radii`) plus the degree (1…3) plus one.
|
||
if radii.is_empty() || !(radii.len() + 3..=radii.len() + 5).contains(&knots.len()) {
|
||
return Err(bad(
|
||
cmd,
|
||
"a spline fillet needs `radii` (the control radii after `radius`) and `knots` (as many as all control radii, the degree 1…3 and one more)",
|
||
));
|
||
}
|
||
solidcraft_doc::FilletStyle::Spline { start: Position(start), knots, radii }
|
||
}
|
||
Some(o) => return Err(bad(cmd, format!("unknown fillet type `{o}` (constant, chord, variable, spline or curvature)"))),
|
||
};
|
||
let fit = match str_(p, "fit").map(str::to_ascii_lowercase).as_deref() {
|
||
None | Some("exact") => solidcraft_doc::FilletFit::Exact,
|
||
Some("reduce") => solidcraft_doc::FilletFit::Reduce,
|
||
Some("taper") => solidcraft_doc::FilletFit::Taper,
|
||
Some(o) => return Err(bad(cmd, format!("unknown fit `{o}` (exact, reduce or taper)"))),
|
||
};
|
||
if !fit.is_exact() && !style.is_constant() {
|
||
return Err(bad(cmd, "`fit: reduce` and `fit: taper` take a constant radius"));
|
||
}
|
||
// What fills the corners where three blended edges meet.
|
||
let corner = match str_(p, "corner").map(str::to_ascii_lowercase).as_deref() {
|
||
None | Some("rolling") => solidcraft_doc::FilletCorner::Rolling,
|
||
Some("g2") => solidcraft_doc::FilletCorner::G2,
|
||
Some(o) => return Err(bad(cmd, format!("unknown corner `{o}` (rolling or g2)"))),
|
||
};
|
||
if !corner.is_rolling() && (!style.is_constant() || !fit.is_exact()) {
|
||
return Err(bad(cmd, "`corner: g2` is built for a constant-radius fillet (`type: constant`, `fit: exact`) only"));
|
||
}
|
||
// Corner setbacks: each a vertex and the distance its patch starts along the edges there.
|
||
let mut setbacks = Vec::new();
|
||
if let Some(list) = p.get("setbacks") {
|
||
let list = list.as_array().ok_or_else(|| bad(cmd, "`setbacks` is a list of {vertex: [x,y,z], distance: expr}"))?;
|
||
for item in list {
|
||
let vertex = item.get("vertex").and_then(vec3).ok_or_else(|| bad(cmd, "each setback needs `vertex`: [x,y,z] at the corner"))?;
|
||
let distance = expr(item, "distance").ok_or_else(|| bad(cmd, "each setback needs `distance`: a length"))?;
|
||
check_expr(s, &distance, Kind::Length, cmd, "setback distance")?;
|
||
setbacks.push(solidcraft_doc::CornerSetback { vertex: Position(vertex), distance });
|
||
}
|
||
if !setbacks.is_empty() && (!style.is_constant() || !fit.is_exact()) {
|
||
return Err(bad(cmd, "`setbacks` are built for a constant-radius fillet (`type: constant`, `fit: exact`) only"));
|
||
}
|
||
}
|
||
let mut out = add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Fillet {
|
||
edges: edges.into_iter().map(Position).collect(),
|
||
radius,
|
||
body: str_(p, "body").map(BodyName::from),
|
||
style,
|
||
fit,
|
||
corner,
|
||
setbacks,
|
||
tangent_chain: bool_(p, "tangent_chain").unwrap_or(true),
|
||
},
|
||
)?;
|
||
// The radii the fillet used, when `fit: reduce` reduced it.
|
||
if let Some(id) = out.get("feature").and_then(Value::as_u64)
|
||
&& let Some(state) = s.model.result(id).map(|res| &res.state)
|
||
&& let Some(r) = state.fitted_radius(id)
|
||
{
|
||
out["radius_applied"] = serde_json::json!(r);
|
||
let each: Vec<Value> =
|
||
state.fitted_edges(id).unwrap_or_default().into_iter().map(|(p, r)| serde_json::json!({"edge": [p.x, p.y, p.z], "radius": r})).collect();
|
||
out["radii_applied"] = Value::Array(each);
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
fn chamfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.chamfer";
|
||
let edges = edge_points(s, p, cmd)?;
|
||
let distance = req_expr(cmd, p, "distance")?;
|
||
check_expr(s, &distance, Kind::Length, cmd, "distance")?;
|
||
let (distance2, angle) = (expr(p, "distance2"), expr(p, "angle"));
|
||
if let Some(d) = &distance2 {
|
||
check_expr(s, d, Kind::Length, cmd, "distance2")?;
|
||
}
|
||
if let Some(a) = &angle {
|
||
check_expr(s, a, Kind::Angle, cmd, "angle")?;
|
||
}
|
||
if distance2.is_some() && angle.is_some() {
|
||
return Err(bad(cmd, "give `distance2` or `angle`, not both"));
|
||
}
|
||
let flip = bool_(p, "flip").unwrap_or(false);
|
||
add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Chamfer {
|
||
edges: edges.into_iter().map(Position).collect(),
|
||
distance,
|
||
distance2,
|
||
angle,
|
||
flip,
|
||
body: str_(p, "body").map(BodyName::from),
|
||
tangent_chain: bool_(p, "tangent_chain").unwrap_or(true),
|
||
},
|
||
)
|
||
}
|
||
|
||
fn combine(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.combine";
|
||
let target = str_(p, "target").ok_or_else(|| bad(cmd, "`target` must be a body name"))?.to_string();
|
||
let tools = string_list(cmd, p, "tools")?;
|
||
if tools.is_empty() {
|
||
return Err(bad(cmd, "`tools` must list bodies"));
|
||
}
|
||
let op = match str_(p, "operation") {
|
||
None => Operation::Join,
|
||
Some(o) => Operation::parse(o).filter(|o| *o != Operation::NewBody).ok_or_else(|| bad(cmd, "operation must be join, cut or intersect"))?,
|
||
};
|
||
let mut out = add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Combine {
|
||
target: target.clone().into(),
|
||
tools: tools.into_iter().map(BodyName).collect(),
|
||
operation: op,
|
||
keep_tools: bool_(p, "keep_tools").unwrap_or(false),
|
||
},
|
||
)?;
|
||
// New Component: the result goes into a component of its own.
|
||
if bool_(p, "new_component").unwrap_or(false) {
|
||
let name = str_(p, "component_name").map(str::to_string).unwrap_or_else(|| format!("{target} Combined"));
|
||
let c = s.execute("component.create", &json!({"name": name, "activate": false}))?;
|
||
super::component::transfer_constructor_result(s, &json!({"bodies": [target], "component": c["component"]}))?;
|
||
out["component"] = c["component"].clone();
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
fn move_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||
if let Some(paths) = copied_components(p)? {
|
||
return copy_components(s, p, paths);
|
||
}
|
||
if let Some(plan) = crate::frames::placements_moved(s, p) {
|
||
return move_placements(s, p, plan);
|
||
}
|
||
// Bodies in differently placed frames: one Move feature per frame, each moving its bodies
|
||
// by the world vector and turn mapped into that frame (#9660).
|
||
if let Some(moves) = crate::frames::split_move(s, p)? {
|
||
return move_split(s, &moves);
|
||
}
|
||
move_body_feature(s, p)
|
||
}
|
||
|
||
/// The moves of `frames::split_move`, in one step, with one reply: the features made, and the
|
||
/// bodies made, changed and removed by any of them.
|
||
fn move_split(s: &mut Session, moves: &[Value]) -> Result<Value> {
|
||
let mut features = Vec::new();
|
||
let mut lists: [(&str, Vec<Value>); 3] = [("created_bodies", Vec::new()), ("changed_bodies", Vec::new()), ("removed_bodies", Vec::new())];
|
||
let mut last = Value::Null;
|
||
for p in moves {
|
||
let reply = move_body_feature(s, p)?;
|
||
features.push(reply.get("feature").cloned().unwrap_or(Value::Null));
|
||
for (key, list) in &mut lists {
|
||
for name in reply.get(*key).and_then(Value::as_array).into_iter().flatten() {
|
||
if !list.contains(name) {
|
||
list.push(name.clone());
|
||
}
|
||
}
|
||
}
|
||
last = reply;
|
||
}
|
||
if let Some(out) = last.as_object_mut() {
|
||
if let Some(first) = features.first() {
|
||
out.insert("feature".into(), first.clone());
|
||
}
|
||
out.insert("features".into(), Value::Array(features));
|
||
for (key, list) in lists {
|
||
out.insert(key.into(), Value::Array(list));
|
||
}
|
||
}
|
||
Ok(last)
|
||
}
|
||
|
||
/// The occurrence paths a copying move copies (`occurrences`, root first), `None` when it names
|
||
/// none. A component is only ever copied, so the move must set `copy`.
|
||
fn copied_components(p: &Value) -> Result<Option<Vec<Vec<u64>>>> {
|
||
let cmd = "solid.move";
|
||
let Some(list) = p.get("occurrences") else { return Ok(None) };
|
||
let paths: Vec<Vec<u64>> = list
|
||
.as_array()
|
||
.into_iter()
|
||
.flatten()
|
||
.map(|path| path.as_array().and_then(|ids| ids.iter().map(Value::as_u64).collect::<Option<Vec<u64>>>()).filter(|ids| !ids.is_empty()))
|
||
.collect::<Option<_>>()
|
||
.ok_or_else(|| bad(cmd, "`occurrences` must list occurrence paths, each a list of occurrence ids"))?;
|
||
if paths.is_empty() || paths.len() > 1000 {
|
||
return Err(bad(cmd, "`occurrences` must list 1…1000 occurrence paths"));
|
||
}
|
||
if p.get("copy").and_then(Value::as_bool) != Some(true) {
|
||
return Err(bad(cmd, "`occurrences` are copied: set `copy` to true"));
|
||
}
|
||
Ok(Some(paths))
|
||
}
|
||
|
||
/// The translation (mm) and turn (radians, if any) of a move in the world.
|
||
fn world_move(s: &Session, p: &Value) -> Result<(Vec<f64>, Option<f64>)> {
|
||
let cmd = "solid.move";
|
||
let length = |v: &Value| -> Result<f64> {
|
||
match v {
|
||
Value::Number(n) => n.as_f64().ok_or_else(|| bad(cmd, "translate entries must be numbers or expressions")),
|
||
Value::String(e) => s.doc.eval(e, Kind::Length).map_err(|e| bad(cmd, format!("translate: {e}"))),
|
||
_ => Err(bad(cmd, "translate entries must be numbers or expressions")),
|
||
}
|
||
};
|
||
let translate = match p.get("translate") {
|
||
Some(Value::Array(a)) if a.len() == 3 => a.iter().map(length).collect::<Result<Vec<f64>>>()?,
|
||
None => vec![0.0; 3],
|
||
_ => return Err(bad(cmd, "`translate` must be [x, y, z]")),
|
||
};
|
||
let angle = match expr(p, "angle") {
|
||
Some(a) => Some(s.doc.eval(&a, Kind::Angle).map_err(|e| bad(cmd, format!("angle: {e}")))?),
|
||
None => None,
|
||
};
|
||
Ok((translate, angle))
|
||
}
|
||
|
||
/// A copying move of components (`occurrences`, with `copy`): each picked placement's component is
|
||
/// copied as an independent component, as Paste New copies it (`component.paste_new`), placed where
|
||
/// the placement is; the copy then moves by the move's translation and turn in the world, as
|
||
/// `occurrence.move` moves a placement. The bodies listed are copied as bodies (see
|
||
/// `move_body_feature`) in the same command, so the whole move is one undo step.
|
||
fn copy_components(s: &mut Session, p: &Value, paths: Vec<Vec<u64>>) -> Result<Value> {
|
||
let cmd = "solid.move";
|
||
let (translate, angle) = world_move(s, p)?;
|
||
let paste = super::find_command("component.paste_new").ok_or_else(|| EngineError::UnknownCommand("component.paste_new".into()))?;
|
||
let mover = super::find_command("occurrence.move").ok_or_else(|| EngineError::UnknownCommand("occurrence.move".into()))?;
|
||
// A component inside another one copied here comes with its parent's copy.
|
||
let mut paths: Vec<Vec<u64>> = paths.into_iter().fold(Vec::new(), |mut out, path| {
|
||
if !out.contains(&path) {
|
||
out.push(path);
|
||
}
|
||
out
|
||
});
|
||
let all = paths.clone();
|
||
paths.retain(|p| !all.iter().any(|q| q.len() < p.len() && p.starts_with(q)));
|
||
// The bodies are given in the world; their own component's frame turns them, as a move of bodies
|
||
// alone is turned, so they are mapped the same way, before any copy is made.
|
||
let has_bodies = match p.get("bodies") {
|
||
None => false,
|
||
Some(Value::Array(bodies)) => !bodies.is_empty(),
|
||
Some(_) => return Err(bad(cmd, "`bodies` must list bodies")),
|
||
};
|
||
let mut rest = p.clone();
|
||
if let Some(object) = rest.as_object_mut() {
|
||
object.remove("occurrences");
|
||
}
|
||
// Bodies in differently placed frames split by frame (`frames::split_move`, #9660), as a move of them alone does.
|
||
let split = crate::frames::split_move(s, &rest)?;
|
||
let bodies = if has_bodies && split.is_none() { Some(crate::frames::to_local(s, cmd, &rest)?.unwrap_or_else(|| rest.clone())) } else { None };
|
||
let mut copies = Vec::new();
|
||
for path in &paths {
|
||
let Some(&source) = path.last() else { continue };
|
||
let component =
|
||
s.doc.occurrences.iter().find(|o| o.id == source).map(|o| o.component).ok_or_else(|| bad(cmd, "`occurrences` names no occurrence"))?;
|
||
let made = paste.run_nested(s, &json!({"component": component, "occurrence": source, "path": path}))?;
|
||
let copy = made.get("occurrence").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "the copy has no occurrence"))?;
|
||
// The copy is placed by the same parent placement as its source.
|
||
let mut at = path[..path.len() - 1].to_vec();
|
||
at.push(copy);
|
||
let mut q = json!({"occurrence": copy, "path": at, "space": "world", "translate": translate});
|
||
if let Some(axis) = p.get("axis") {
|
||
q["axis"] = axis.clone();
|
||
}
|
||
if let Some(angle) = angle {
|
||
q["angle"] = json!(angle);
|
||
}
|
||
mover.run_nested(s, &q)?;
|
||
copies.push(copy);
|
||
}
|
||
// The reply is a solid.move reply: the bodies' feature reply, with the copies made alongside.
|
||
let mut out = match (split, bodies) {
|
||
(Some(moves), _) => move_split(s, &moves)?,
|
||
(None, Some(local)) => move_body_feature(s, &local)?,
|
||
(None, None) => json!({}),
|
||
};
|
||
if let Some(object) = out.as_object_mut() {
|
||
object.insert("occurrences".into(), json!(copies));
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
/// A move of several placements of one part (`frames::placements_moved`, #4768): each placement
|
||
/// moved in the world by the move's translation and turn (about the world origin, as the Move
|
||
/// feature turns bodies), and the root component's bodies listed moved as bodies, in one step.
|
||
fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMove) -> Result<Value> {
|
||
let (translate, angle) = world_move(s, p)?;
|
||
let spec = super::find_command("occurrence.move").ok_or_else(|| EngineError::UnknownCommand("occurrence.move".into()))?;
|
||
let mut moved = Vec::new();
|
||
for path in &plan.paths {
|
||
let Some(&occurrence) = path.last() else { continue };
|
||
let mut q = json!({"occurrence": occurrence, "path": path, "space": "world", "translate": translate});
|
||
if let Some(axis) = p.get("axis") {
|
||
q["axis"] = axis.clone();
|
||
}
|
||
if let Some(angle) = angle {
|
||
q["angle"] = json!(angle);
|
||
}
|
||
spec.run_nested(s, &q)?;
|
||
moved.push(occurrence);
|
||
}
|
||
let mut out = json!({"placements": moved});
|
||
if !plan.bodies.is_empty() {
|
||
let mut rest = p.clone();
|
||
rest["bodies"] = json!(plan.bodies);
|
||
out["bodies"] = move_body_feature(s, &rest)?;
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
fn move_body_feature(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.move";
|
||
let bodies = string_list(cmd, p, "bodies")?;
|
||
if bodies.is_empty() {
|
||
return Err(bad(cmd, "`bodies` must list bodies"));
|
||
}
|
||
let t = match p.get("translate") {
|
||
Some(Value::Array(a)) if a.len() == 3 => {
|
||
let mut out: [Expr; 3] = Default::default();
|
||
for (i, v) in a.iter().enumerate() {
|
||
let e = expr(&json!({"v": v}), "v").ok_or_else(|| bad(cmd, "translate entries must be numbers or expressions"))?;
|
||
check_expr(s, &e, Kind::Length, cmd, "translate")?;
|
||
if let Some(slot) = out.get_mut(i) {
|
||
*slot = e;
|
||
}
|
||
}
|
||
out
|
||
}
|
||
None => ["0".into(), "0".into(), "0".into()],
|
||
_ => return Err(bad(cmd, "`translate` must be [x, y, z]")),
|
||
};
|
||
let angle = expr(p, "angle");
|
||
if let Some(a) = &angle {
|
||
check_expr(s, a, Kind::Angle, cmd, "angle")?;
|
||
}
|
||
let copy = bool_(p, "copy").unwrap_or(false);
|
||
let reply = add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Move {
|
||
bodies: bodies.iter().cloned().map(BodyName).collect(),
|
||
translate: t,
|
||
rotate_axis: p.get("axis").and_then(vec3).map(Dir),
|
||
angle,
|
||
copy,
|
||
},
|
||
)?;
|
||
if copy {
|
||
copy_keeps_appearance(s, &reply, &bodies, cmd)?;
|
||
super::print_face::copies_keep_print_faces(s, &reply, &bodies);
|
||
}
|
||
Ok(reply)
|
||
}
|
||
|
||
/// A copy keeps the look and the material of the body it came from (#6423): the copy is the same
|
||
/// part in another place, so it looks the same.
|
||
fn copy_keeps_appearance(s: &mut Session, reply: &Value, sources: &[String], cmd: &str) -> Result<()> {
|
||
let id = reply.get("feature").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "the copy has no feature id"))?;
|
||
let copies: Vec<String> = s.model.state().bodies.iter().filter(|b| b.feature == id).map(|b| b.name.clone()).collect();
|
||
if copies.len() != sources.len() {
|
||
return Err(bad(cmd, "the copy did not make one body per body it copied"));
|
||
}
|
||
for (source, copy) in sources.iter().zip(copies.iter()) {
|
||
if let Some(look) = s.doc.appearances.bodies.get(source).cloned() {
|
||
s.doc_mut().appearances.bodies.insert(copy.clone(), look);
|
||
}
|
||
if let Some(material) = s.doc.materials.get(source).cloned() {
|
||
s.doc_mut().materials.insert(copy.clone(), material);
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
fn source_features(s: &Session, p: &Value, cmd: &str) -> Result<Vec<solidcraft_doc::FeatureId>> {
|
||
let names = string_list(cmd, p, "features")?;
|
||
if names.is_empty() {
|
||
return Err(bad(cmd, "`features` must list features to copy"));
|
||
}
|
||
// Names stay input only: the feature stores its seeds by id (#1134), resolved the way
|
||
// evaluation used to resolve them (a shared sketch name does not win over the geometry).
|
||
names.iter().map(|n| s.doc.seed_feature(n).map(|f| f.id.into()).ok_or_else(|| bad(cmd, format!("no feature `{n}`")))).collect()
|
||
}
|
||
|
||
/// An axis line from its parameter, with what it follows: an edge or round face of the model
|
||
/// ({edge|face: [x,y,z]}) or a construction axis by name ([`named_axis_line`]).
|
||
fn axis_line(s: &Session, p: &Value, cmd: &str) -> Result<(Vec3, Vec3, Option<solidcraft_doc::construct::GeoRef>, Option<FeatureName>)> {
|
||
if let Some((geo, o, d)) = super::construct::model_axis_param(s, p.get("axis"), cmd)? {
|
||
return Ok((o, d, Some(geo), None));
|
||
}
|
||
let (o, d, name) = named_axis_line(s, p, cmd)?;
|
||
Ok((o, d, None, name))
|
||
}
|
||
|
||
/// An axis line from `axis`: X, Y, Z, a construction axis by name or {origin, dir}. A construction
|
||
/// axis comes back where it is now, with its name.
|
||
fn named_axis_line(s: &Session, p: &Value, cmd: &str) -> Result<(Vec3, Vec3, Option<FeatureName>)> {
|
||
match p.get("axis") {
|
||
Some(Value::String(a)) => match a.to_ascii_uppercase().as_str() {
|
||
"X" => Ok((Vec3::ZERO, Vec3::X, None)),
|
||
"Y" => Ok((Vec3::ZERO, Vec3::Y, None)),
|
||
"Z" => Ok((Vec3::ZERO, Vec3::Z, None)),
|
||
_ if is_construction_axis(s, a) => {
|
||
let (_, _, origin, dir) = crate::view::construction_axes(s)
|
||
.into_iter()
|
||
.find(|(_, name, _, _)| name == a)
|
||
.ok_or_else(|| bad(cmd, format!("construction axis `{a}` has no geometry: fix its definition first")))?;
|
||
Ok((origin, dir, Some(a.as_str().into())))
|
||
}
|
||
_ => Err(bad(cmd, "axis must be X, Y, Z, a construction axis, {origin, dir} or {edge|face: [x,y,z]}")),
|
||
},
|
||
Some(o @ Value::Object(_)) => {
|
||
let (origin, dir) = axis_line_object(o).map_err(|why| bad(cmd, why))?;
|
||
Ok((origin, dir, None))
|
||
}
|
||
_ => Err(bad(cmd, "`axis` is required")),
|
||
}
|
||
}
|
||
|
||
/// An axis line `{origin?, dir}` as [`named_axis_line`] reads it: the origin (default: the
|
||
/// origin) and the unit direction.
|
||
pub(crate) fn axis_line_object(o: &Value) -> std::result::Result<(Vec3, Vec3), &'static str> {
|
||
let origin = match o.get("origin") {
|
||
None => Vec3::ZERO,
|
||
Some(v) => vec3(v).ok_or("axis.origin must contain three finite numeric coordinates in millimetres; expressions are not supported")?,
|
||
};
|
||
let dir = o.get("dir").and_then(vec3).and_then(|d| d.normalized()).ok_or("axis needs a non-zero `dir`")?;
|
||
Ok((origin, dir))
|
||
}
|
||
|
||
/// A pattern feature, or for `components`, new occurrences of them at each placement.
|
||
fn finish_pattern(
|
||
s: &mut Session,
|
||
p: &Value,
|
||
features: Vec<solidcraft_doc::FeatureId>,
|
||
pattern: solidcraft_doc::PatternKind,
|
||
bodies: Vec<String>,
|
||
) -> Result<Value> {
|
||
let comps = string_list(UNKNOWN_COMMAND, p, "components")?;
|
||
if comps.is_empty() {
|
||
return add_feature(s, p, FeatureKind::Pattern { features, pattern, bodies: bodies.into_iter().map(BodyName).collect() });
|
||
}
|
||
let cmd = "pattern (components)";
|
||
let mats = solidcraft_doc::pattern_matrices(&s.doc, &s.model.state(), &pattern)?;
|
||
let mut made = Vec::new();
|
||
for c in &comps {
|
||
let id = s.doc.find_component(c).filter(|id| *id != 0).ok_or_else(|| bad(cmd, format!("no component `{c}`")))?;
|
||
let src = s.doc.occurrence_of(id).cloned().ok_or_else(|| bad(cmd, format!("component `{c}` has no occurrence")))?;
|
||
for m in &mats {
|
||
made.push(s.doc_mut().add_occurrence(id, src.parent, solidcraft_doc::mat_mul(m, &src.transform))?);
|
||
}
|
||
}
|
||
Ok(json!({"occurrences": made}))
|
||
}
|
||
|
||
/// What a pattern copies: features (replayed), bodies (`bodies: [names]`), or components
|
||
/// (`components: [names]`, placed again as occurrences).
|
||
fn pattern_sources(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<solidcraft_doc::FeatureId>, Vec<String>)> {
|
||
if !string_list(cmd, p, "components")?.is_empty() {
|
||
return Ok((Vec::new(), Vec::new()));
|
||
}
|
||
let bodies = string_list(cmd, p, "bodies")?;
|
||
if bodies.is_empty() {
|
||
return Ok((source_features(s, p, cmd)?, Vec::new()));
|
||
}
|
||
let st = s.model.state();
|
||
if let Some(b) = bodies.iter().find(|b| st.body(b).is_none()) {
|
||
return Err(bad(cmd, format!("no body `{b}`")));
|
||
}
|
||
Ok((Vec::new(), bodies))
|
||
}
|
||
|
||
fn pattern_rect(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.pattern.rectangular";
|
||
let (features, bodies) = pattern_sources(s, p, cmd)?;
|
||
let dir1 = p.get("dir1").and_then(vec3).ok_or_else(|| bad(cmd, "`dir1` must be [x, y, z]"))?;
|
||
let count1 = req_expr(cmd, p, "count1")?;
|
||
let spacing1 = req_expr(cmd, p, "spacing1")?;
|
||
check_count(s, &count1, cmd, "count1")?;
|
||
check_expr(s, &spacing1, Kind::Length, cmd, "spacing1")?;
|
||
let dir2 = p.get("dir2").and_then(vec3);
|
||
let (count2, spacing2) = (expr(p, "count2"), expr(p, "spacing2"));
|
||
if let Some(c) = &count2 {
|
||
check_count(s, c, cmd, "count2")?;
|
||
}
|
||
if let Some(c) = &spacing2 {
|
||
check_expr(s, c, Kind::Length, cmd, "spacing2")?;
|
||
}
|
||
let pattern = solidcraft_doc::PatternKind::Rectangular {
|
||
dir1: Dir(dir1),
|
||
count1,
|
||
spacing1,
|
||
dir2: dir2.map(Dir),
|
||
count2,
|
||
spacing2,
|
||
alignment: super::alignment_param(p, "alignment", cmd)?,
|
||
alignment2: super::alignment_param(p, "alignment2", cmd)?,
|
||
reversed: super::reversed_param(p, "reversed", cmd)?,
|
||
reversed2: super::reversed_param(p, "reversed2", cmd)?,
|
||
};
|
||
finish_pattern(s, p, features, pattern, bodies)
|
||
}
|
||
|
||
/// The line a circular pattern turns about, as [`axis_line`] reads it, except that the origin of
|
||
/// `{origin, dir}` may be length expressions, kept so the pattern follows them (#10852).
|
||
fn pattern_axis(s: &Session, p: &Value, cmd: &str) -> Result<(PointExpr, Vec3, Option<solidcraft_doc::construct::GeoRef>, Option<FeatureName>)> {
|
||
if let Some(a @ Value::Object(o)) = p.get("axis")
|
||
&& o.contains_key("origin")
|
||
&& !super::is_model_axis(a)
|
||
{
|
||
// Read under its full name, so a refusal says which origin it means.
|
||
let origin = point_param(s, &json!({ "axis.origin": o.get("origin") }), "axis.origin", cmd)?;
|
||
let dir = a.get("dir").and_then(vec3).and_then(|d| d.normalized()).ok_or_else(|| bad(cmd, "axis needs a non-zero `dir`"))?;
|
||
return Ok((origin.unwrap_or_else(|| solidcraft_doc::point_expr(Vec3::ZERO)), dir, None, None));
|
||
}
|
||
let (origin, dir, axis_ref, axis_feature) = axis_line(s, p, cmd)?;
|
||
Ok((solidcraft_doc::point_expr(origin), dir, axis_ref, axis_feature))
|
||
}
|
||
|
||
fn pattern_circ(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.pattern.circular";
|
||
let (features, bodies) = pattern_sources(s, p, cmd)?;
|
||
let (origin, axis, axis_ref, axis_feature) = pattern_axis(s, p, cmd)?;
|
||
let count = req_expr(cmd, p, "count")?;
|
||
check_count(s, &count, cmd, "count")?;
|
||
let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into());
|
||
check_expr(s, &angle, Kind::Angle, cmd, "angle")?;
|
||
let pattern = solidcraft_doc::PatternKind::Circular {
|
||
origin,
|
||
axis: Dir(axis),
|
||
count,
|
||
angle,
|
||
alignment: super::alignment_param(p, "alignment", cmd)?,
|
||
reversed: super::reversed_param(p, "reversed", cmd)?,
|
||
axis_ref,
|
||
axis_feature,
|
||
};
|
||
finish_pattern(s, p, features, pattern, bodies)
|
||
}
|
||
|
||
fn pattern_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.pattern.path";
|
||
let (features, bodies) = pattern_sources(s, p, cmd)?;
|
||
let path_sketch = sketch_id(s, p.get("path_sketch").or_else(|| p.get("sketch")), cmd, "path_sketch")?;
|
||
let path = string_list(cmd, p, "path")?;
|
||
if path.is_empty() || path.len() > 1000 {
|
||
return Err(bad(cmd, "`path` must list 1…1000 curve ids"));
|
||
}
|
||
let count = req_expr(cmd, p, "count")?;
|
||
check_count(s, &count, cmd, "count")?;
|
||
let (spacing, extent) = match (expr(p, "spacing"), expr(p, "distance")) {
|
||
(Some(x), _) => (x, false),
|
||
(None, Some(x)) => (x, true),
|
||
(None, None) => return Err(bad(cmd, "give `spacing` (between instances) or `distance` (first to last)")),
|
||
};
|
||
check_expr(s, &spacing, Kind::Length, cmd, "spacing")?;
|
||
let orient = match str_(p, "orientation") {
|
||
None | Some("identical") => false,
|
||
Some("path" | "path_direction" | "along_path") => true,
|
||
Some(o) => return Err(bad(cmd, format!("unknown orientation `{o}` (identical or path)"))),
|
||
};
|
||
let flip = bool_(p, "flip").unwrap_or(false);
|
||
let pattern = solidcraft_doc::PatternKind::Path { path_sketch: SketchId(path_sketch), path, count, spacing, extent, flip, orient };
|
||
finish_pattern(s, p, features, pattern, bodies)
|
||
}
|
||
|
||
fn mirror(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.mirror";
|
||
let bodies = string_list(cmd, p, "bodies")?;
|
||
let features = if bodies.is_empty() { source_features(s, p, cmd)? } else { Vec::new() };
|
||
let plane = plane_param(s, p.get("plane"), cmd)?;
|
||
let combine = bool_(p, "combine").unwrap_or(false);
|
||
let (bodies, placements) = placed_bodies(s, bodies, cmd)?;
|
||
let reply =
|
||
add_feature(s, p, FeatureKind::Mirror { features, plane, bodies: bodies.iter().cloned().map(BodyName).collect(), combine, placements })?;
|
||
if !combine {
|
||
super::print_face::copies_keep_print_faces(s, &reply, &bodies);
|
||
}
|
||
Ok(reply)
|
||
}
|
||
|
||
/// Bodies picked where the viewport shows them: each world name ("Body1", or "Body1 (Occ:2)"
|
||
/// for a further instance) becomes its component's body name, with the occurrence path of the
|
||
/// placement it was picked at (where the copy goes). Names stay as they are, and no placement is
|
||
/// kept, while every body is in the active component and every component in place, or when one
|
||
/// of them is not a body.
|
||
fn placed_bodies(s: &Session, names: Vec<String>, cmd: &str) -> Result<(Vec<String>, Vec<Vec<u64>>)> {
|
||
if names.is_empty() || s.doc.occurrences.is_empty() {
|
||
return Ok((names, Vec::new()));
|
||
}
|
||
let frames = s.doc.body_frames_with_source(&s.model.state());
|
||
let mut picked = Vec::with_capacity(names.len());
|
||
for name in &names {
|
||
let Some((_, own, component, path, _)) = frames.iter().find(|(world, ..)| world == name) else { return Ok((names, Vec::new())) };
|
||
picked.push((own.clone(), *component, path.clone()));
|
||
}
|
||
if !crate::frames::placed(s) && picked.iter().all(|(_, component, _)| *component == s.active_component) {
|
||
return Ok((names, Vec::new()));
|
||
}
|
||
let uncaptured = s.uncaptured_moves();
|
||
if let Some((name, ..)) = picked.iter().find(|(_, _, path)| path.iter().any(|id| uncaptured.contains_key(id))) {
|
||
return Err(bad(cmd, format!("`{name}` has a position that is not captured yet: Capture Position (component.capture_position) first")));
|
||
}
|
||
if let Some((name, ..)) = picked.iter().find(|(_, _, path)| path.iter().any(|id| s.pending_moves.contains_key(id))) {
|
||
return Err(bad(cmd, format!("`{name}` is shown in an exploded view: show it assembled (explode.show with no view) first")));
|
||
}
|
||
Ok(picked.into_iter().map(|(own, _, path)| (own, path)).unzip())
|
||
}
|
||
|
||
/// The other name of an origin plane (`Top` for `XY`, `XY` for `Top`...), if `name` is one.
|
||
pub(super) fn origin_plane_alias(name: &str) -> Option<&'static str> {
|
||
match name.trim().to_ascii_uppercase().as_str() {
|
||
"XY" => Some("Top"),
|
||
"TOP" => Some("XY"),
|
||
"XZ" => Some("Front"),
|
||
"FRONT" => Some("XZ"),
|
||
"YZ" => Some("Right"),
|
||
"RIGHT" => Some("YZ"),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// A construction plane may not take an origin plane's name (`XY`, `Top`...): a plane
|
||
/// parameter could then mean either.
|
||
pub(super) fn check_plane_name(name: &str, cmd: &str) -> Result<()> {
|
||
match plane_name_problem(name) {
|
||
Some(why) => Err(bad(cmd, why)),
|
||
None => Ok(()),
|
||
}
|
||
}
|
||
|
||
/// What [`check_plane_name`] says about `name`, or `None` when a construction plane may take it.
|
||
pub(crate) fn plane_name_problem(name: &str) -> Option<String> {
|
||
solidcraft_geom::Plane::named(name.trim()).map(|_| {
|
||
format!("`{}` is reserved for an origin plane (XY, XZ, YZ, Top, Front, Right); give the construction plane another name", name.trim())
|
||
})
|
||
}
|
||
|
||
/// The forms [`plane_param`] takes, for its messages.
|
||
pub(crate) const PLANE_FORMS: &str =
|
||
"XY, XZ, YZ, a construction plane name or id, or {origin, normal} (origin coordinates may be length expressions)";
|
||
|
||
/// The plane an explicit plane object gives through `origin`, as [`plane_param`] reads it: from
|
||
/// `x_dir` and `y_dir` when both are points, else from `normal`; `None` when they don't make one.
|
||
pub(crate) fn explicit_plane(o: &Value, origin: Vec3) -> Option<solidcraft_geom::Plane> {
|
||
match (o.get("x_dir").and_then(vec3), o.get("y_dir").and_then(vec3), o.get("normal").and_then(vec3)) {
|
||
(Some(x), Some(y), _) => solidcraft_geom::Plane::new(origin, x, y),
|
||
(_, _, Some(n)) => solidcraft_geom::Plane::from_normal(origin, n),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// A plane reference from a parameter: an origin plane, a construction plane (by name or
|
||
/// feature id; kept by name, so the feature follows the plane when it changes), or an
|
||
/// explicit plane `{origin, x_dir, y_dir}` / `{origin, normal}`. Every command that takes a
|
||
/// plane reads it here.
|
||
pub(super) fn plane_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<solidcraft_doc::PlaneRef> {
|
||
use solidcraft_doc::PlaneRef;
|
||
const WANT: &str = PLANE_FORMS;
|
||
let construction = |r: &str| match s.doc.find_feature(r) {
|
||
Some(f) if matches!(f.kind, FeatureKind::ConstructionPlane { .. }) => Ok(PlaneRef::Construction { feature: f.id.into() }),
|
||
Some(f) => Err(bad(cmd, format!("`{}` is not a construction plane (a plane is {WANT})", f.name))),
|
||
None => Err(bad(cmd, format!("no plane `{r}` (a plane is {WANT})"))),
|
||
};
|
||
match v {
|
||
Some(Value::String(n)) if solidcraft_geom::Plane::named(n.trim()).is_some() => {
|
||
if let Some(f) = s.doc.find_feature(n.trim())
|
||
&& matches!(f.kind, FeatureKind::ConstructionPlane { .. })
|
||
{
|
||
return Err(bad(
|
||
cmd,
|
||
format!(
|
||
"plane `{}` is ambiguous: an origin-plane alias and a construction plane; use `{}` for the origin plane, construction plane feature id {}, or an explicit {{origin, normal}} plane",
|
||
n.trim(),
|
||
origin_plane_alias(n).unwrap_or("XY"),
|
||
f.id
|
||
),
|
||
));
|
||
}
|
||
Ok(PlaneRef::Origin { name: n.trim().to_ascii_uppercase() })
|
||
}
|
||
Some(Value::String(n)) => construction(n.trim()),
|
||
Some(Value::Number(id)) => match id.as_u64() {
|
||
Some(id) => construction(&id.to_string()),
|
||
None => Err(bad(cmd, format!("`plane` must be {WANT}"))),
|
||
},
|
||
Some(o @ Value::Object(_)) => {
|
||
// The origin's coordinates are numbers or length expressions; expressions are kept,
|
||
// so the plane follows its parameters.
|
||
let origin = match o.get("origin") {
|
||
None => point_expr(Vec3::ZERO),
|
||
Some(_) => point_param(s, o, "origin", cmd)?.unwrap_or_else(|| point_expr(Vec3::ZERO)),
|
||
};
|
||
let at = |e: &str| s.doc.eval(e, Kind::Length).unwrap_or(0.0);
|
||
let here = Vec3::new(at(&origin[0]), at(&origin[1]), at(&origin[2]));
|
||
let plane = explicit_plane(o, here).ok_or_else(|| bad(cmd, "plane needs x_dir and y_dir, or normal"))?;
|
||
if origin.iter().all(|e| solidcraft_doc::expr::is_literal(e)) {
|
||
return Ok(PlaneRef::Custom { plane });
|
||
}
|
||
Ok(PlaneRef::Placed { origin, x_dir: plane.x, y_dir: plane.y })
|
||
}
|
||
_ => Err(bad(cmd, format!("`plane` must be {WANT}"))),
|
||
}
|
||
}
|
||
|
||
fn plane_offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||
use solidcraft_doc::PlaneRef;
|
||
let cmd = "construct.plane.offset";
|
||
// Through a point, or at a distance along the base's normal.
|
||
let through = match p.get("through").filter(|t| !t.is_null()) {
|
||
Some(_) if p.get("offset").is_some_and(|o| !o.is_null()) => return Err(bad(cmd, "give `offset` or `through`, not both")),
|
||
Some(t) => Some(super::construct::geo(s, Some(t), cmd, "through")?),
|
||
None => None,
|
||
};
|
||
let distance = match &through {
|
||
Some(_) => Default::default(),
|
||
None => {
|
||
let d = req_expr(cmd, p, "offset")?;
|
||
check_expr(s, &d, Kind::Length, cmd, "offset")?;
|
||
d
|
||
}
|
||
};
|
||
let offset = move |base: PlaneRef| match through {
|
||
Some(point) => PlaneRef::ThroughPoint { base: Box::new(base), point: Box::new(point) },
|
||
None => PlaneRef::Offset { base: Box::new(base), distance },
|
||
};
|
||
// A planar body face: attached exactly, as a sketch on that face is, so the plane follows it.
|
||
if let Some(face) = p.get("base").filter(|b| b.get("face").is_some()) {
|
||
let base = super::sketch::face::capture(s, face, cmd)?;
|
||
super::sketch::face::capture_positions(s, &base)?;
|
||
// The capture is already in the authoring frame.
|
||
return add_feature_in(s, p, FeatureKind::ConstructionPlane { plane: offset(base) }, false);
|
||
}
|
||
let base = plane_param(s, p.get("base"), cmd)?;
|
||
add_feature(s, p, FeatureKind::ConstructionPlane { plane: offset(base) })
|
||
}
|
||
|
||
fn plane_angle(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "construct.plane.at_angle";
|
||
// The plane follows an edge or face it is on; a construction axis is kept as it is now.
|
||
let (axis_origin, axis_dir, line, _) = axis_line(s, p, cmd)?;
|
||
let angle = req_expr(cmd, p, "angle")?;
|
||
check_expr(s, &angle, Kind::Angle, cmd, "angle")?;
|
||
let line = line.map(Box::new);
|
||
// A planar body face: attached exactly, as a sketch on that face is, so the plane follows it.
|
||
if let Some(face) = p.get("base").filter(|b| b.get("face").is_some()) {
|
||
let base = super::sketch::face::capture(s, face, cmd)?;
|
||
super::sketch::face::capture_positions(s, &base)?;
|
||
let plane = solidcraft_doc::PlaneRef::AtAngle { base: Box::new(base), axis_origin, axis_dir, angle, line };
|
||
// The capture is already in the authoring frame.
|
||
return add_feature_in(s, p, FeatureKind::ConstructionPlane { plane }, false);
|
||
}
|
||
let base = plane_param(s, p.get("base"), cmd)?;
|
||
let plane = solidcraft_doc::PlaneRef::AtAngle { base: Box::new(base), axis_origin, axis_dir, angle, line };
|
||
add_feature(s, p, FeatureKind::ConstructionPlane { plane })
|
||
}
|
||
|
||
fn split_face(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.split_face";
|
||
let faces = face_points(s, p, cmd)?;
|
||
let body = str_(p, "body").map(str::to_string);
|
||
let xy = || solidcraft_doc::PlaneRef::Origin { name: "XY".into() };
|
||
let kind = if let Some(t) = p.get("tool").filter(|t| !t.is_null()) {
|
||
let tb = t.get("body").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`tool.body` must name a body"))?.to_string();
|
||
let point = t.get("point").and_then(crate::params::vec3).ok_or_else(|| bad(cmd, "`tool.point` must be [x, y, z] on the tool face"))?;
|
||
FeatureKind::SplitFace {
|
||
faces: faces.into_iter().map(FacePick).collect(),
|
||
body: body.map(BodyName),
|
||
plane: xy(),
|
||
tool: Some(solidcraft_doc::FaceAt { body: BodyName(tb), point: Position(point) }),
|
||
sketch: None,
|
||
}
|
||
} else if p.get("sketch").is_some_and(|v| !v.is_null()) {
|
||
let sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?;
|
||
FeatureKind::SplitFace {
|
||
faces: faces.into_iter().map(FacePick).collect(),
|
||
body: body.map(BodyName),
|
||
plane: xy(),
|
||
tool: None,
|
||
sketch: Some(SketchId(sketch)),
|
||
}
|
||
} else {
|
||
let plane = plane_param(s, p.get("plane"), cmd)?;
|
||
FeatureKind::SplitFace { faces: faces.into_iter().map(FacePick).collect(), body: body.map(BodyName), plane, tool: None, sketch: None }
|
||
};
|
||
add_feature(s, p, kind)
|
||
}
|
||
|
||
fn split_body(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.split_body";
|
||
let body = str_(p, "body").ok_or_else(|| bad(cmd, "`body` is required"))?.to_string();
|
||
if s.model.state().body(&body).is_none() {
|
||
return Err(bad(cmd, format!("no body `{body}`")));
|
||
}
|
||
// A straight sketch line as the tool: `sketch` and `line` (#1552).
|
||
if p.get("sketch").is_some_and(|v| !v.is_null()) || p.get("line").is_some_and(|v| !v.is_null()) {
|
||
let sketch = p.get("sketch").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`sketch` must be a sketch feature id"))?;
|
||
let line = str_(p, "line").ok_or_else(|| bad(cmd, "`line` must name a line of the sketch"))?.to_string();
|
||
let st = s.model.state();
|
||
if st.sketch(sketch).is_none() {
|
||
return Err(bad(cmd, format!("no sketch {sketch}")));
|
||
}
|
||
solidcraft_doc::sketch_line_plane(&st, sketch, &line).map_err(|e| bad(cmd, e.to_string()))?;
|
||
return add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Split {
|
||
body: BodyName(body),
|
||
plane: solidcraft_doc::PlaneRef::Origin { name: "XY".into() },
|
||
tool: None,
|
||
sketch: Some(solidcraft_doc::SketchId(sketch)),
|
||
line: Some(line),
|
||
},
|
||
);
|
||
}
|
||
// A face as the tool: `tool: {body, point}` (its surface extended); else a plane.
|
||
if let Some(t) = p.get("tool").filter(|t| !t.is_null()) {
|
||
let tb = t.get("body").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`tool.body` must name a body"))?.to_string();
|
||
let point = t.get("point").and_then(crate::params::vec3).ok_or_else(|| bad(cmd, "`tool.point` must be [x, y, z] on the tool face"))?;
|
||
let st = s.model.state();
|
||
let tbody = st.body(&tb).ok_or_else(|| bad(cmd, format!("no body `{tb}`")))?;
|
||
if solidcraft_doc::appearance::face_index_at(tbody, point).is_none() {
|
||
return Err(bad(cmd, "`tool.point` is not on a face of the tool body"));
|
||
}
|
||
return add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Split {
|
||
body: BodyName(body),
|
||
plane: solidcraft_doc::PlaneRef::Origin { name: "XY".into() },
|
||
tool: Some(solidcraft_doc::FaceAt { body: BodyName(tb), point: Position(point) }),
|
||
sketch: None,
|
||
line: None,
|
||
},
|
||
);
|
||
}
|
||
let plane = plane_param(s, p.get("plane"), cmd)?;
|
||
add_feature(s, p, FeatureKind::Split { body: BodyName(body), plane, tool: None, sketch: None, line: None })
|
||
}
|
||
|
||
/// ISO 273 clearance hole diameters (close, normal, loose fit) for metric bolts.
|
||
fn clearance_diameter(size: &str, fit: &str) -> Option<f64> {
|
||
const TABLE: [(f64, f64, f64, f64); 21] = [
|
||
(1.6, 1.7, 1.8, 2.0),
|
||
(2.0, 2.2, 2.4, 2.6),
|
||
(2.5, 2.7, 2.9, 3.1),
|
||
(3.0, 3.2, 3.4, 3.6),
|
||
(4.0, 4.3, 4.5, 4.8),
|
||
(5.0, 5.3, 5.5, 5.8),
|
||
(6.0, 6.4, 6.6, 7.0),
|
||
(8.0, 8.4, 9.0, 10.0),
|
||
(10.0, 10.5, 11.0, 12.0),
|
||
(12.0, 13.0, 13.5, 14.5),
|
||
(14.0, 15.0, 15.5, 16.5),
|
||
(16.0, 17.0, 17.5, 18.5),
|
||
(20.0, 21.0, 22.0, 24.0),
|
||
(24.0, 25.0, 26.0, 28.0),
|
||
(30.0, 31.0, 33.0, 35.0),
|
||
(36.0, 37.0, 39.0, 42.0),
|
||
(42.0, 43.0, 45.0, 48.0),
|
||
(48.0, 50.0, 52.0, 56.0),
|
||
(56.0, 58.0, 62.0, 66.0),
|
||
(60.0, 62.0, 66.0, 70.0),
|
||
(64.0, 66.0, 70.0, 74.0),
|
||
];
|
||
let t = size.trim().trim_start_matches(['M', 'm']);
|
||
let d: f64 = t.split(['x', 'X']).next()?.trim().parse().ok()?;
|
||
let row = TABLE.iter().find(|r| (r.0 - d).abs() < 1e-9)?;
|
||
match fit {
|
||
"close" | "fine" => Some(row.1),
|
||
"normal" | "medium" => Some(row.2),
|
||
"loose" | "coarse" => Some(row.3),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// The pitches to try for a plain `M<d>` that has no ISO coarse pitch, `None` for anything else.
|
||
fn fine_only_hint(t: &str) -> Option<String> {
|
||
let diameter = t.trim().strip_prefix(['M', 'm']).and_then(|d| d.trim().parse::<f64>().ok());
|
||
diameter.and_then(solidcraft_doc::thread_forms::no_coarse_pitch)
|
||
}
|
||
|
||
/// Largest nominal diameter automatic thread sizing knows (the last ISO coarse size).
|
||
const LARGEST_COARSE: f64 = 56.0;
|
||
|
||
/// The refusal for automatic sizing on a cylinder too big for the coarse table (a Ø75 shaft):
|
||
/// `None` when sizing finds a thread, or the cylinder is not past the table's end (the feature's
|
||
/// own error then explains). It suggests sizes with a pitch to type, scaled to the diameter.
|
||
fn beyond_coarse_range(st: &solidcraft_doc::ModelState, face: Vec3) -> Option<String> {
|
||
if solidcraft_doc::suggested_thread(st, face).is_ok() {
|
||
return None;
|
||
}
|
||
let cyl = st.bodies.iter().filter_map(|b| solidcraft_doc::kernel::cylinder_face_at(&b.body, face)).min_by(|a, b| {
|
||
let dist =
|
||
|c: &solidcraft_doc::kernel::CylinderFace| ((face - c.axis_point - c.axis * (face - c.axis_point).dot(c.axis)).len() - c.radius).abs();
|
||
dist(a).total_cmp(&dist(b))
|
||
})?;
|
||
let dia = cyl.radius * 2.0;
|
||
if !dia.is_finite() || dia <= LARGEST_COARSE * 0.9 || dia > 1e4 {
|
||
return None;
|
||
}
|
||
// ISO fine pitches for large sizes: the largest up to about a 25th of the diameter, then the
|
||
// next finer one. A hole's major diameter is about its bore plus one pitch.
|
||
const PITCHES: [f64; 4] = [4.0, 3.0, 2.0, 1.5];
|
||
let first = PITCHES.iter().position(|p| *p <= dia / 25.0 + 1e-6).unwrap_or(PITCHES.len() - 1);
|
||
let sizes: Vec<String> =
|
||
PITCHES.iter().skip(first).take(2).map(|p| format!("M{}x{p}", if cyl.internal { dia + p } else { dia }.round())).collect();
|
||
let kind = if cyl.internal { "hole" } else { "cylinder" };
|
||
Some(format!(
|
||
"a {dia:.2} mm {kind} is beyond the coarse thread range (up to M{LARGEST_COARSE}): type a size with its pitch, e.g. {}",
|
||
sizes.join(" or ")
|
||
))
|
||
}
|
||
|
||
fn hole(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.hole";
|
||
// At sketch points: the holes go perpendicular to the sketch and follow its points.
|
||
let points = match (p.get("sketch"), p.get("points"), p.get("position")) {
|
||
(Some(_), Some(_), _) | (Some(_), None, None) => {
|
||
let sketch = feature_sketch(s, p, cmd)?;
|
||
// No points named: every sketch point (standalone points and circle centres, not
|
||
// line or arc ends, not the origin).
|
||
let ids = if p.get("points").is_some() { string_list(cmd, p, "points")? } else { sketch_hole_points(s, sketch) };
|
||
if ids.is_empty() || ids.len() > 10_000 {
|
||
return Err(bad(cmd, "`points` must list 1…10000 sketch point ids"));
|
||
}
|
||
let st = s.model.state();
|
||
let ss = st.sketch(sketch).ok_or_else(|| bad(cmd, "the sketch is not evaluated"))?;
|
||
for id in &ids {
|
||
if !ss.sketch.points.iter().any(|q| &q.id == id) {
|
||
return Err(bad(cmd, format!("no point `{id}` in the sketch")));
|
||
}
|
||
}
|
||
let n = ss.plane.normal();
|
||
let first =
|
||
ids.first().and_then(|id| ss.sketch.points.iter().find(|q| &q.id == id)).map(|q| ss.plane.to_world(q.pos)).unwrap_or_default();
|
||
let flip = p.get("flip").and_then(Value::as_bool).unwrap_or(false);
|
||
// A Single hole at one sketch point (#2110): it follows the point, drilled into the
|
||
// face there rather than across the sketch.
|
||
let single = p.get("single").and_then(Value::as_bool).unwrap_or(false);
|
||
if single && (ids.len() != 1 || flip) {
|
||
return Err(bad(cmd, "a `single` hole takes one sketch point and no `flip`"));
|
||
}
|
||
Some((solidcraft_doc::SketchPoints { sketch: SketchId(sketch), ids, flip, single }, first, -n))
|
||
}
|
||
_ => None,
|
||
};
|
||
let thread = str_(p, "thread").map(|t| t.trim().to_string()).filter(|t| !t.is_empty());
|
||
let hand = match str_(p, "hand") {
|
||
None | Some("right") => solidcraft_doc::thread_forms::ThreadHand::Right,
|
||
Some("left") => solidcraft_doc::thread_forms::ThreadHand::Left,
|
||
Some(h) => return Err(bad(cmd, format!("unknown hand `{h}` (right or left)"))),
|
||
};
|
||
if thread.is_none() && hand != solidcraft_doc::thread_forms::ThreadHand::Right {
|
||
return Err(bad(cmd, "`hand` needs `thread` (a tapped hole)"));
|
||
}
|
||
if let Some(t) = &thread
|
||
&& solidcraft_doc::parse_tapped_thread(t).is_none()
|
||
{
|
||
return Err(bad(
|
||
cmd,
|
||
fine_only_hint(t)
|
||
.or_else(|| solidcraft_doc::untabulated_taper_tap(t))
|
||
.unwrap_or_else(|| format!("unknown tapped thread `{t}` (ISO metric or a catalogued UNC/UNF, G, Rp, Rc or NPT size)")),
|
||
));
|
||
}
|
||
let thread_depth = match p.get("thread_depth") {
|
||
None | Some(Value::Null) => None,
|
||
Some(_) => Some(req_expr(cmd, p, "thread_depth")?),
|
||
};
|
||
let modeled = p.get("modeled").and_then(Value::as_bool).unwrap_or(false);
|
||
if modeled && thread.is_none() {
|
||
return Err(bad(cmd, "`modeled` needs `thread` (a tapped hole)"));
|
||
}
|
||
let ease_out = runout_param(s, p, cmd, "ease_out")?;
|
||
if ease_out.is_some() && !modeled {
|
||
return Err(bad(cmd, "`ease_out` is cut only on a modelled thread (`modeled: true`)"));
|
||
}
|
||
if let Some(d) = &thread_depth {
|
||
if thread.is_none() {
|
||
return Err(bad(cmd, "`thread_depth` requires `thread` (a tapped hole)"));
|
||
}
|
||
let depth = s.doc.eval(d, Kind::Length).map_err(|e| bad(cmd, format!("`thread_depth`: {e}")))?;
|
||
if !depth.is_finite() || depth <= 0.0 {
|
||
return Err(bad(cmd, "`thread_depth` must be finite and positive"));
|
||
}
|
||
}
|
||
// A position given as length expressions (#1678), say `["leg_h*0.4", "width/2", "t"]`: kept,
|
||
// so the hole follows the parameters; drilled where they evaluate now.
|
||
let at: Option<solidcraft_doc::PointExpr> = match p.get("position").and_then(Value::as_array) {
|
||
Some(a) if points.is_none() && a.len() == 3 && a.iter().any(Value::is_string) => {
|
||
let mut coords = Vec::with_capacity(3);
|
||
for v in a {
|
||
let e = match v {
|
||
Value::String(x) => x.trim().to_string(),
|
||
Value::Number(n) => n.to_string(),
|
||
_ => return Err(bad(cmd, "`position` must be [x, y, z]: numbers or length expressions")),
|
||
};
|
||
check_expr(s, &e, Kind::Length, cmd, "position")?;
|
||
coords.push(solidcraft_doc::Expr::new(e));
|
||
}
|
||
let [x, y, z]: [solidcraft_doc::Expr; 3] = coords.try_into().map_err(|_| bad(cmd, "`position` must be [x, y, z]"))?;
|
||
Some([x, y, z])
|
||
}
|
||
_ => None,
|
||
};
|
||
let at_value = match &at {
|
||
Some([x, y, z]) => {
|
||
let c = |e: &solidcraft_doc::Expr| s.doc.eval(e, Kind::Length).map_err(|e| bad(cmd, format!("`position`: {e}")));
|
||
Some(Vec3::new(c(x)?, c(y)?, c(z)?)).filter(|v| v.is_finite())
|
||
}
|
||
None => None,
|
||
};
|
||
// Reference edges (#37): the centre sits at these distances from straight edges of its face.
|
||
let references = hole_reference_params(s, p, cmd)?;
|
||
if !references.is_empty() && (points.is_some() || at.is_some()) {
|
||
return Err(bad(cmd, "`references` place a hole by its `position` given as numbers, not at sketch points or length expressions"));
|
||
}
|
||
let position = match (&points, at_value.or_else(|| p.get("position").and_then(vec3))) {
|
||
(Some((_, first, _)), None) => *first,
|
||
(_, Some(x)) => x,
|
||
(None, None) => return Err(bad(cmd, "`position` must be [x, y, z], numbers or length expressions (or give `sketch` and `points`)")),
|
||
};
|
||
// A hole starts on a face: a point off every face (past a body's edge) would drill a hole
|
||
// nobody picked, and cutting across an edge that way is slow.
|
||
if points.is_none() && !super::face::on_a_face(s, position) {
|
||
return Err(bad(
|
||
cmd,
|
||
format!("`position` [{}, {}, {}] is not on a face of a body; pick a point on the face to drill", position.x, position.y, position.z),
|
||
));
|
||
}
|
||
let direction = match (p.get("direction").and_then(vec3), &points) {
|
||
(None, Some((sp, _, d))) if !sp.single => *d,
|
||
(d, _) => match d {
|
||
Some(d) => d.normalized().ok_or_else(|| bad(cmd, "`direction` must be non-zero"))?,
|
||
None => {
|
||
// Into the face the position lies on: against the outward normal of the face
|
||
// nearest it (planar or curved), as it faces out of its own body.
|
||
let st = s.model.state();
|
||
solidcraft_doc::hole_direction_at(&st, position).ok_or_else(|| bad(cmd, "no face at `position`; give `direction`"))?
|
||
}
|
||
},
|
||
};
|
||
// Placed by its reference edges: drilled where their distances put it, which `position`
|
||
// then keeps. The edges must be straight edges at the given points, and cross.
|
||
let position = if references.is_empty() { position } else { referenced_centre(s, cmd, &references, position, direction)? };
|
||
// The diameter: given, or a metric-estimate/Unified-table tap drill, or an ISO 273
|
||
// clearance hole for a bolt size (close, normal or loose fit).
|
||
let diameter = match (expr(p, "diameter"), &thread, str_(p, "clearance")) {
|
||
(Some(d), _, _) => d,
|
||
(None, _, Some(c)) => {
|
||
let fit = str_(p, "fit").unwrap_or("normal").to_ascii_lowercase();
|
||
let d = clearance_diameter(c, &fit).ok_or_else(|| bad(cmd, format!("no clearance hole for `{c}` ({fit} fit): M1.6 to M64")))?;
|
||
Expr::new(format!("{d} mm"))
|
||
}
|
||
(None, Some(t), None) => {
|
||
let size = solidcraft_doc::parse_tapped_thread(t).ok_or_else(|| bad(cmd, "thread"))?;
|
||
Expr::new(format!("{} mm", size.tap_drill))
|
||
}
|
||
(None, None, None) => return Err(bad(cmd, "needs `diameter`, `thread` (a tapped hole) or `clearance` (a bolt size)")),
|
||
};
|
||
check_expr(s, &diameter, Kind::Length, cmd, "diameter")?;
|
||
// A tapped hole drilled to another size than the tap maker's: from the thread's minor
|
||
// diameter to 5% over that drill.
|
||
if let (Some(t), Some(_)) = (&thread, expr(p, "diameter"))
|
||
&& let Some(size) = solidcraft_doc::parse_tapped_thread(t)
|
||
{
|
||
let given = s.doc.eval(&diameter, Kind::Length).map_err(|e| bad(cmd, format!("`diameter`: {e}")))?;
|
||
size.check_drill(given).map_err(|e| bad(cmd, e))?;
|
||
}
|
||
let depth = expr(p, "depth");
|
||
if let Some(d) = &depth {
|
||
check_expr(s, d, Kind::Length, cmd, "depth")?;
|
||
}
|
||
let get = |k: &str| -> Result<Expr> {
|
||
let e = req_expr(cmd, p, k)?;
|
||
Ok(e)
|
||
};
|
||
let kind = match str_(p, "type").unwrap_or("simple") {
|
||
"simple" => match expr(p, "tip_angle") {
|
||
Some(t) if depth.is_some() => solidcraft_doc::HoleKind::Drilled { tip_angle: t },
|
||
_ => solidcraft_doc::HoleKind::Simple,
|
||
},
|
||
"drilled" => solidcraft_doc::HoleKind::Drilled { tip_angle: expr(p, "tip_angle").unwrap_or_else(|| "118 deg".into()) },
|
||
"counterbore" => {
|
||
solidcraft_doc::HoleKind::Counterbore { cb_diameter: get("cb_diameter")?, cb_depth: get("cb_depth")?, tip_angle: expr(p, "tip_angle") }
|
||
}
|
||
"countersink" => solidcraft_doc::HoleKind::Countersink {
|
||
cs_diameter: get("cs_diameter")?,
|
||
cs_angle: expr(p, "cs_angle").unwrap_or_else(|| "90 deg".into()),
|
||
tip_angle: expr(p, "tip_angle"),
|
||
},
|
||
other => return Err(bad(cmd, format!("unknown hole type `{other}`"))),
|
||
};
|
||
let to = match p.get("to") {
|
||
Some(v) => Some(vec3(v).ok_or_else(|| bad(cmd, "`to` must be a point [x, y, z] on the face to drill to"))?),
|
||
None => None,
|
||
};
|
||
let mut p = p.clone();
|
||
let targets = string_list(cmd, &p, "targets")?;
|
||
if p.get("participants").is_none() {
|
||
// The bodies to drill, as `targets` (like an extrude's): its participants.
|
||
if !targets.is_empty() {
|
||
p["participants"] = json!(targets);
|
||
} else if let Some(body) = points.as_ref().filter(|(sp, _, _)| !sp.single).and_then(|(sp, _, _)| sketch_face_body(s, sp.sketch.0)) {
|
||
// Holes at the points of a sketch on a body's face drill that body (#2882): a body
|
||
// further along, past the face, doesn't take them. Stored, so recomputes and
|
||
// reopening keep the same scope.
|
||
p["participants"] = json!([body]);
|
||
} else if points.is_none()
|
||
&& let Some(body) = body_of_other_component_at(s, position)
|
||
{
|
||
// A hole picked on a body of another component (a moved one, shown where it is
|
||
// placed) cuts that body: the pick is already in that body's frame, and the
|
||
// component's own bodies alone would leave nothing to cut.
|
||
p["participants"] = json!([body]);
|
||
}
|
||
}
|
||
add_feature(
|
||
s,
|
||
&p,
|
||
FeatureKind::Hole {
|
||
position: FacePick(position),
|
||
at,
|
||
direction: Dir(direction),
|
||
diameter,
|
||
depth,
|
||
hole: kind,
|
||
points: points.map(|x| x.0),
|
||
thread,
|
||
thread_depth,
|
||
hand,
|
||
modeled,
|
||
ease_out,
|
||
to: to.map(FacePick),
|
||
references,
|
||
},
|
||
)
|
||
}
|
||
|
||
/// A thread's runout parameter: a length, `standard` (ISO 3508's 2.5 P) or `short` (1.25 P);
|
||
/// none or 0: no runout.
|
||
fn runout_param(s: &Session, p: &Value, cmd: &str, key: &str) -> Result<Option<solidcraft_doc::ThreadRunout>> {
|
||
Ok(match p.get(key) {
|
||
None | Some(Value::Null) => None,
|
||
Some(Value::String(t)) if t == "standard" => Some(solidcraft_doc::ThreadRunout::Standard),
|
||
Some(Value::String(t)) if t == "short" => Some(solidcraft_doc::ThreadRunout::Short),
|
||
Some(Value::Number(n)) if n.as_f64() == Some(0.0) => None,
|
||
Some(_) => {
|
||
let e = expr(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a length, \"standard\" or \"short\"")))?;
|
||
check_expr(s, &e, Kind::Length, cmd, key)?;
|
||
Some(solidcraft_doc::ThreadRunout::Length { length: e })
|
||
}
|
||
})
|
||
}
|
||
|
||
/// Where reference edges (#37) put a hole's (or a cylinder's) centre picked at `at` on a flat
|
||
/// face, `dir` into it: at their distances from the edges, which must be straight edges at the
|
||
/// given points, and cross.
|
||
fn referenced_centre(s: &Session, cmd: &str, references: &[solidcraft_doc::HoleReference], at: Vec3, dir: Vec3) -> Result<Vec3> {
|
||
let st = s.model.state();
|
||
let mut distances = Vec::with_capacity(references.len());
|
||
for r in references {
|
||
distances.push(s.doc.eval(&r.distance, Kind::Length).map_err(|e| bad(cmd, format!("`references`: {e}")))?);
|
||
}
|
||
let edges: Vec<(Vec3, Option<&str>)> = references.iter().map(|r| (r.edge.0, None)).collect();
|
||
let frame = solidcraft_doc::hole_reference::reference_frame(&st, at, dir, &edges, true).map_err(|e| bad(cmd, e.to_string()))?;
|
||
let centre = frame.place(at, &distances).map_err(|e| bad(cmd, e.to_string()))?;
|
||
if !solidcraft_doc::hole_reference::on_reference_face(&st, &frame, centre) {
|
||
let what = if cmd == "solid.cylinder" { "cylinder's base" } else { "hole's centre" };
|
||
return Err(bad(cmd, format!("the reference distances put the {what} off its face")));
|
||
}
|
||
Ok(centre)
|
||
}
|
||
|
||
/// A hole's reference edges (#37): `references: [{edge: [x, y, z], distance: expr}]`, at most
|
||
/// two, each distance a length.
|
||
fn hole_reference_params(s: &Session, p: &Value, cmd: &str) -> Result<Vec<solidcraft_doc::HoleReference>> {
|
||
let Some(v) = p.get("references") else { return Ok(Vec::new()) };
|
||
let list = v.as_array().ok_or_else(|| bad(cmd, "`references` must be a list of {edge: [x, y, z], distance}"))?;
|
||
let most = solidcraft_doc::hole_reference::MAX_HOLE_REFERENCES;
|
||
if list.len() > most {
|
||
return Err(bad(cmd, format!("a hole takes at most {most} `references`")));
|
||
}
|
||
let mut out = Vec::with_capacity(list.len());
|
||
for (i, r) in list.iter().enumerate() {
|
||
let edge = r
|
||
.get("edge")
|
||
.and_then(vec3)
|
||
.ok_or_else(|| bad(cmd, format!("`references[{i}].edge` must be a point [x, y, z] on a straight edge of the face")))?;
|
||
let distance = expr(r, "distance").ok_or_else(|| bad(cmd, format!("`references[{i}].distance` {}", expr_problem(r.get("distance")))))?;
|
||
check_expr(s, &distance, Kind::Length, cmd, "references")?;
|
||
out.push(solidcraft_doc::HoleReference { edge: Position(edge), distance });
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
/// The body whose face is nearest `p` (within its pick tolerance), when it belongs to another
|
||
/// component than the active one.
|
||
fn body_of_other_component_at(s: &Session, p: Vec3) -> Option<String> {
|
||
let st = s.model.state();
|
||
let (_, body) = st
|
||
.bodies
|
||
.iter()
|
||
.filter(|b| !b.body.is_mesh())
|
||
.filter_map(|b| {
|
||
let (d, _) = solidcraft_doc::appearance::nearest_face(b, p)?;
|
||
(d <= solidcraft_doc::appearance::pick_tolerance(b)).then_some((d, b))
|
||
})
|
||
.min_by(|a, b| a.0.total_cmp(&b.0))?;
|
||
(s.doc.model_body_component(body) != s.active_component).then(|| body.name.clone())
|
||
}
|
||
|
||
/// The points of a sketch a hole drills at when only the sketch is given.
|
||
fn sketch_hole_points(s: &Session, sketch: u64) -> Vec<String> {
|
||
let st = s.model.state();
|
||
let Some(ss) = st.sketch(sketch) else { return Vec::new() };
|
||
let mut ends: Vec<usize> = Vec::new();
|
||
for c in &ss.sketch.curves {
|
||
match &c.kind {
|
||
solidcraft_sketch::CurveKind::Circle { .. } => {}
|
||
solidcraft_sketch::CurveKind::Arc { a, b, .. } | solidcraft_sketch::CurveKind::Line { a, b } => ends.extend([*a, *b]),
|
||
solidcraft_sketch::CurveKind::Ellipse { m, .. } => ends.push(*m),
|
||
solidcraft_sketch::CurveKind::Spline { pts, .. } => ends.extend(pts.iter().copied()),
|
||
solidcraft_sketch::CurveKind::Conic { a, b, apex, .. } => ends.extend([*a, *b, *apex]),
|
||
}
|
||
}
|
||
ss.sketch.points.iter().enumerate().filter(|(i, p)| p.id != "origin" && !ends.contains(i)).map(|(_, p)| p.id.clone()).collect()
|
||
}
|
||
|
||
fn face_points(s: &Session, p: &Value, cmd: &str) -> Result<Vec<Vec3>> {
|
||
let a = p.get("faces").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`faces` must be a list of points or face names"))?;
|
||
if a.is_empty() || a.len() > 1000 {
|
||
return Err(bad(cmd, "select 1…1000 faces"));
|
||
}
|
||
a.iter().map(|v| super::face::face_ref(s, v, str_(p, "body"), cmd)).collect()
|
||
}
|
||
|
||
fn shell(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.shell";
|
||
// No face opened: a closed hollow body, its void sealed inside.
|
||
let faces = match p.get("faces").and_then(Value::as_array) {
|
||
Some(a) if a.is_empty() => Vec::new(),
|
||
_ => face_points(s, p, cmd)?,
|
||
};
|
||
let thickness = req_expr(cmd, p, "thickness")?;
|
||
check_expr(s, &thickness, Kind::Length, cmd, "thickness")?;
|
||
let direction = str_(p, "direction").map(str::to_ascii_lowercase).unwrap_or_default();
|
||
if !matches!(direction.as_str(), "" | "inside" | "outside" | "both") {
|
||
return Err(bad(cmd, "`direction` must be inside, outside or both"));
|
||
}
|
||
add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Shell {
|
||
faces: faces.into_iter().map(FacePick).collect(),
|
||
thickness,
|
||
body: str_(p, "body").map(BodyName::from),
|
||
direction: if direction == "inside" { String::new() } else { direction },
|
||
tangent_chain: bool_(p, "tangent_chain").unwrap_or(false),
|
||
},
|
||
)
|
||
}
|
||
|
||
fn draft(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.draft";
|
||
let faces = face_points(s, p, cmd)?;
|
||
let angle = req_expr(cmd, p, "angle")?;
|
||
check_expr(s, &angle, Kind::Angle, cmd, "angle")?;
|
||
let neutral = plane_param(s, p.get("neutral"), cmd)?;
|
||
let (vals, _) = s.doc.param_values();
|
||
let pl = s.doc.resolve_plane_in(&vals, &neutral, 0, Some(&s.model.state()))?;
|
||
let pull = p.get("pull").and_then(vec3).unwrap_or_else(|| pl.normal());
|
||
add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Draft {
|
||
faces: faces.into_iter().map(FacePick).collect(),
|
||
angle,
|
||
neutral,
|
||
pull: Dir(pull),
|
||
body: str_(p, "body").map(BodyName::from),
|
||
},
|
||
)
|
||
}
|
||
|
||
pub(super) fn sketch_id(s: &Session, v: Option<&Value>, cmd: &str, what: &str) -> Result<u64> {
|
||
let key = sketch_key(v).ok_or_else(|| bad(cmd, format!("`{what}` must be a sketch id or name")))?;
|
||
match s.doc.find_feature(&key) {
|
||
Some(f) if matches!(f.kind, FeatureKind::Sketch { .. }) => Ok(f.id),
|
||
_ => Err(bad(cmd, format!("no sketch `{key}`"))),
|
||
}
|
||
}
|
||
|
||
/// The key [`sketch_id`] and [`feature_sketch`] look a sketch up by: an id (a number) or a name.
|
||
pub(crate) fn sketch_key(v: Option<&Value>) -> Option<String> {
|
||
match v {
|
||
Some(Value::Number(n)) => Some(n.to_string()),
|
||
Some(Value::String(x)) => Some(x.clone()),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.sweep";
|
||
let sketch = feature_sketch(s, p, cmd)?;
|
||
let path_sketch = sketch_id(s, p.get("path_sketch"), cmd, "path_sketch")?;
|
||
let path = string_list(cmd, p, "path")?;
|
||
if path.is_empty() {
|
||
return Err(bad(cmd, "`path` must list curve ids"));
|
||
}
|
||
let (orientation, twist, scale) = sweep_options(s, p, cmd)?;
|
||
let (rails, rail_fit) = sweep_rails(s, p, cmd, path_sketch)?;
|
||
let operation = operation(p, cmd)?;
|
||
let targets = face_join_targets(s, p, operation, &[sketch], cmd)?;
|
||
add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Sweep {
|
||
sketch: SketchId(sketch),
|
||
profiles: profiles(p, cmd)?,
|
||
path_sketch: SketchId(path_sketch),
|
||
path,
|
||
orientation,
|
||
twist,
|
||
scale,
|
||
rails,
|
||
rail_fit,
|
||
operation,
|
||
targets,
|
||
},
|
||
)
|
||
}
|
||
|
||
/// A sweep's `orientation`, `twist` and `scale` (solid.sweep and surface.sweep), checked: an
|
||
/// orientation the sweep knows, a twist within four turns, an end scale within 0.01…100.
|
||
pub(super) fn sweep_options(s: &Session, p: &Value, cmd: &str) -> Result<(SweepOrientation, Option<Expr>, Option<Expr>)> {
|
||
let orientation = match p.get("orientation") {
|
||
None | Some(Value::Null) => SweepOrientation::Perpendicular,
|
||
Some(Value::String(o)) if o.eq_ignore_ascii_case("perpendicular") => SweepOrientation::Perpendicular,
|
||
Some(Value::String(o)) if o.eq_ignore_ascii_case("parallel") => SweepOrientation::Parallel,
|
||
Some(v) => {
|
||
let d = vec3(v)
|
||
.or_else(|| v.get("direction").and_then(vec3))
|
||
.ok_or_else(|| bad(cmd, "`orientation` must be perpendicular, parallel or a direction [x, y, z]"))?;
|
||
if !(d.len() > 1e-9) {
|
||
return Err(bad(cmd, "the `orientation` direction must not be zero"));
|
||
}
|
||
SweepOrientation::Direction(Dir(d))
|
||
}
|
||
};
|
||
let twist = match p.get("twist") {
|
||
None | Some(Value::Null) => None,
|
||
Some(_) => {
|
||
let t = expr(p, "twist").ok_or_else(|| bad(cmd, "`twist` must be an angle or an expression"))?;
|
||
let v = s.doc.eval(&t, Kind::Angle).map_err(|e| bad(cmd, format!("twist: {e}")))?;
|
||
if !(v.is_finite() && v.abs() <= solidcraft_kernel::SweepControl::MAX_TWIST) {
|
||
return Err(bad(cmd, "`twist` must be within four turns (1440 deg)"));
|
||
}
|
||
Some(t)
|
||
}
|
||
};
|
||
let scale = match p.get("scale") {
|
||
None | Some(Value::Null) => None,
|
||
Some(_) => {
|
||
let k = req_expr(cmd, p, "scale")?;
|
||
let v = s.doc.eval(&k, Kind::Unitless).map_err(|e| bad(cmd, format!("scale: {e}")))?;
|
||
let range = solidcraft_kernel::SweepControl::MIN_SCALE..=solidcraft_kernel::SweepControl::MAX_SCALE;
|
||
if !(v.is_finite() && range.contains(&v)) {
|
||
return Err(bad(cmd, "`scale` (the end scale) must be between 0.01 and 100"));
|
||
}
|
||
Some(k)
|
||
}
|
||
};
|
||
Ok((orientation, twist, scale))
|
||
}
|
||
|
||
/// A sweep's guide `rails` and `rail_fit` (solid.sweep and surface.sweep), checked: one or two
|
||
/// rails, each a sketch (default: the path's) and 1…1000 of its curves; a fit of scale or
|
||
/// stretch; and no orientation, twist or scale besides, since the rails set those.
|
||
pub(super) fn sweep_rails(s: &Session, p: &Value, cmd: &str, path_sketch: u64) -> Result<(Vec<SweepRail>, RailFit)> {
|
||
let (rails, rail_fit) = guide_rails(s, p, cmd, "sweep", Some(path_sketch))?;
|
||
if !rails.is_empty() {
|
||
for key in ["orientation", "twist", "scale"] {
|
||
if p.get(key).is_some_and(|v| !v.is_null()) {
|
||
return Err(bad(cmd, format!("guide rails set the profile's turn and size along the path: leave out `{key}`")));
|
||
}
|
||
}
|
||
}
|
||
Ok((rails, rail_fit))
|
||
}
|
||
|
||
/// A sweep's or a loft's (`what`) `rails` (one or two `{sketch?, curves}`, each rail's sketch
|
||
/// `default_sketch` when it names none) and `rail_fit` (scale | stretch).
|
||
pub(super) fn guide_rails(s: &Session, p: &Value, cmd: &str, what: &str, default_sketch: Option<u64>) -> Result<(Vec<SweepRail>, RailFit)> {
|
||
let rail_fit = match p.get("rail_fit") {
|
||
None | Some(Value::Null) => RailFit::Scale,
|
||
Some(Value::String(f)) if f.eq_ignore_ascii_case("scale") => RailFit::Scale,
|
||
Some(Value::String(f)) if f.eq_ignore_ascii_case("stretch") => RailFit::Stretch,
|
||
Some(_) => return Err(bad(cmd, "`rail_fit` must be scale or stretch")),
|
||
};
|
||
let given = match p.get("rails") {
|
||
None | Some(Value::Null) => return Ok((Vec::new(), rail_fit)),
|
||
Some(Value::Array(a)) => a,
|
||
Some(_) => return Err(bad(cmd, "`rails` must list one or two rails: [{sketch, curves: [ids]}]")),
|
||
};
|
||
if !(1..=2).contains(&given.len()) {
|
||
return Err(bad(cmd, format!("a {what} takes one or two guide rails")));
|
||
}
|
||
let mut rails = Vec::with_capacity(given.len());
|
||
for rail in given {
|
||
let sketch = match (rail.get("sketch").filter(|v| !v.is_null()), default_sketch) {
|
||
(None, Some(sketch)) => sketch,
|
||
(None, None) => return Err(bad(cmd, "each rail needs the `sketch` its curves are in")),
|
||
(Some(_), _) => sketch_id(s, rail.get("sketch"), cmd, "rails[].sketch")?,
|
||
};
|
||
let curves = string_list(cmd, rail, "curves")?;
|
||
if curves.is_empty() || curves.len() > 1000 {
|
||
return Err(bad(cmd, "each rail's `curves` must list 1…1000 curve ids in order"));
|
||
}
|
||
rails.push(SweepRail { sketch: SketchId(sketch), curves });
|
||
}
|
||
Ok((rails, rail_fit))
|
||
}
|
||
|
||
fn loft(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.loft";
|
||
let list = p.get("sections").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`sections` must be a list"))?;
|
||
if list.len() < 2 || list.len() > 50 {
|
||
return Err(bad(cmd, "a loft needs 2…50 sections"));
|
||
}
|
||
let mut sections = Vec::new();
|
||
for sec in list {
|
||
let sketch = sketch_id(s, sec.get("sketch"), cmd, "sections[].sketch")?;
|
||
// A sketch point closes the loft to an apex.
|
||
if let Some(pt) = str_(sec, "point") {
|
||
let st = s.model.state();
|
||
if !st.sketch(sketch).is_some_and(|ss| ss.sketch.points.iter().any(|q| q.id == pt)) {
|
||
return Err(bad(cmd, format!("no point `{pt}` in the section's sketch")));
|
||
}
|
||
sections.push(solidcraft_doc::LoftSection {
|
||
sketch: SketchId(sketch),
|
||
profiles: solidcraft_doc::ProfileSel::All,
|
||
point: Some(pt.to_string()),
|
||
});
|
||
continue;
|
||
}
|
||
sections.push(solidcraft_doc::LoftSection { sketch: SketchId(sketch), profiles: profiles(sec, cmd)?, point: None });
|
||
}
|
||
let (rails, rail_fit) = guide_rails(s, p, cmd, "loft", None)?;
|
||
let operation = operation(p, cmd)?;
|
||
let sketches: Vec<u64> = sections.iter().map(|sec| sec.sketch.0).collect();
|
||
let mut targets = face_join_targets(s, p, operation, &sketches, cmd)?;
|
||
if operation == Operation::Join && string_list(cmd, p, "targets")?.is_empty() && string_list(cmd, p, "participants")?.is_empty() {
|
||
let st = s.model.state();
|
||
let candidates: Vec<_> = st
|
||
.bodies
|
||
.iter()
|
||
.filter(|b| if targets.is_empty() { s.doc.model_body_component(b) == s.active_component } else { targets.iter().any(|t| t.0 == b.name) })
|
||
.collect();
|
||
// Capture the visible subset now: showing a body later or reopening the design must
|
||
// not let an existing loft consume it (#1988). Keep the usual scope when none is hidden.
|
||
if candidates.iter().any(|b| !s.body_visible(&b.name)) {
|
||
targets = candidates.iter().filter(|b| s.body_visible(&b.name)).map(|b| BodyName(b.name.clone())).collect();
|
||
// Empty targets mean automatic scope, not "no bodies". Never fall back to that
|
||
// scope when every candidate is hidden; an explicit target can still choose one.
|
||
if targets.is_empty() {
|
||
return Err(bad(cmd, "no visible body to join; show a body, choose explicit targets, or use New Body"));
|
||
}
|
||
}
|
||
}
|
||
add_feature(s, p, FeatureKind::Loft { sections, operation, targets, rails, rail_fit })
|
||
}
|
||
|
||
fn thread(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.thread";
|
||
let face = p
|
||
.get("face")
|
||
.and_then(|v| vec3(v).or_else(|| v.get("point").and_then(vec3)))
|
||
.ok_or_else(|| bad(cmd, "`face` must be a point [x, y, z] on a cylindrical face"))?;
|
||
use solidcraft_doc::thread_forms::{SteepFlank, ThreadForm, ThreadHand, ThreadTip};
|
||
let designation = str_(p, "designation").map(|t| t.trim().to_string()).filter(|t| !t.is_empty());
|
||
let form = match str_(p, "form") {
|
||
Some(f) => ThreadForm::from_name(f).ok_or_else(|| {
|
||
bad(cmd, format!("unknown thread form `{f}` (metric, trapezoidal, acme, buttress, buttress_asme, bspp, rp, bspt, npt or square)"))
|
||
})?,
|
||
None => designation.as_deref().and_then(ThreadForm::of_designation).unwrap_or_default(),
|
||
};
|
||
if let Some(why) = form.refused() {
|
||
return Err(bad(cmd, why));
|
||
}
|
||
let starts = match p.get("starts") {
|
||
None | Some(Value::Null) => 1,
|
||
Some(v) => v.as_u64().filter(|n| (1..=8).contains(n)).ok_or_else(|| bad(cmd, "`starts` must be a whole number from 1 to 8"))? as u32,
|
||
};
|
||
if let Some(t) = &designation {
|
||
form.parse(t, starts).map_err(|e| bad(cmd, e))?;
|
||
}
|
||
let hand = match str_(p, "hand") {
|
||
None | Some("right") => ThreadHand::Right,
|
||
Some("left") => ThreadHand::Left,
|
||
Some("both") => ThreadHand::Both,
|
||
Some(h) => return Err(bad(cmd, format!("unknown hand `{h}` (right, left or both)"))),
|
||
};
|
||
let steep_flank = match str_(p, "steep_flank") {
|
||
None | Some("end") => SteepFlank::End,
|
||
Some("start") => SteepFlank::Start,
|
||
Some(h) => return Err(bad(cmd, format!("unknown steep_flank `{h}` (start or end)"))),
|
||
};
|
||
if p.get("steep_flank").is_some() && !matches!(form, ThreadForm::Buttress | ThreadForm::ButtressAsme) {
|
||
return Err(bad(cmd, "`steep_flank` is for the buttress forms"));
|
||
}
|
||
let tip = match str_(p, "tip") {
|
||
None | Some("none") => ThreadTip::None,
|
||
Some("start") => ThreadTip::Start,
|
||
Some("both") => ThreadTip::Both,
|
||
Some("chamfer") => return Err(bad(cmd, "tip `chamfer` is now `both` (every free end) or `start` (the end the thread starts from)")),
|
||
Some(t) => return Err(bad(cmd, format!("unknown tip `{t}` (none, start or both)"))),
|
||
};
|
||
let angled = |key: &str, kind: Kind| -> Result<Option<solidcraft_doc::Expr>> {
|
||
let e = expr(p, key);
|
||
if let Some(e) = &e {
|
||
check_expr(s, e, kind, cmd, key)?;
|
||
}
|
||
Ok(e)
|
||
};
|
||
let chamfer_angle = angled("chamfer_angle", Kind::Angle)?;
|
||
let chamfer_depth = angled("chamfer_depth", Kind::Length)?;
|
||
if tip == ThreadTip::None && (chamfer_angle.is_some() || chamfer_depth.is_some()) {
|
||
return Err(bad(cmd, "`chamfer_angle` and `chamfer_depth` go with a chamfered tip (`tip: start` or `both`)"));
|
||
}
|
||
if p.get("ease_in").is_some() {
|
||
return Err(bad(
|
||
cmd,
|
||
"`ease_in` is gone: a thread's start runs off its free end, plain or chamfered (`tip: start`); fade the inner end with `ease_out`",
|
||
));
|
||
}
|
||
let ease_out = runout_param(s, p, cmd, "ease_out")?;
|
||
let length = expr(p, "length");
|
||
if let Some(l) = &length {
|
||
check_expr(s, l, Kind::Length, cmd, "length")?;
|
||
}
|
||
let up_to = match p.get("up_to") {
|
||
None | Some(Value::Null) => None,
|
||
Some(v) => Some(match vec3(v) {
|
||
Some(q) => solidcraft_doc::ThreadLimit::Face(FacePick(q)),
|
||
None => solidcraft_doc::ThreadLimit::Plane(plane_param(s, Some(v), cmd)?),
|
||
}),
|
||
};
|
||
match (str_(p, "extent"), &length, &up_to) {
|
||
(None, Some(_), Some(_)) => return Err(bad(cmd, "give `length` or `up_to`, not both")),
|
||
(None, ..) | (Some("full"), None, None) | (Some("length"), Some(_), None) | (Some("up_to"), None, Some(_)) => {}
|
||
(Some("full"), ..) => return Err(bad(cmd, "`extent: full` runs the whole face: it takes no `length` or `up_to`")),
|
||
(Some("length"), ..) => return Err(bad(cmd, "`extent: length` needs `length` (and no `up_to`)")),
|
||
(Some("up_to"), ..) => return Err(bad(cmd, "`extent: up_to` needs `up_to` (and no `length`)")),
|
||
(Some(e), ..) => return Err(bad(cmd, format!("unknown extent `{e}` (full, length or up_to)"))),
|
||
}
|
||
let from = match p.get("from") {
|
||
None | Some(Value::Null) => None,
|
||
Some(v) => Some(Position(vec3(v).ok_or_else(|| bad(cmd, "`from` must be a point [x, y, z] near the end the thread starts at"))?)),
|
||
};
|
||
let modeled = p.get("modeled").and_then(Value::as_bool).unwrap_or(false);
|
||
// The coarse metric range bounds only a metric thread with no designation given.
|
||
if designation.is_none()
|
||
&& form == ThreadForm::Metric
|
||
&& let Some(msg) = beyond_coarse_range(&s.model.state(), face)
|
||
{
|
||
return Err(bad(cmd, msg));
|
||
}
|
||
let kind = FeatureKind::Thread {
|
||
face: FacePick(face),
|
||
designation,
|
||
length,
|
||
modeled,
|
||
from,
|
||
up_to,
|
||
form,
|
||
hand,
|
||
starts,
|
||
ease_out,
|
||
tip,
|
||
chamfer_angle,
|
||
chamfer_depth,
|
||
steep_flank,
|
||
};
|
||
let v = add_feature(s, p, kind)?;
|
||
let st = s.model.state();
|
||
let t = v.get("feature").and_then(Value::as_u64).and_then(|id| st.threads.iter().find(|t| t.feature == id).cloned());
|
||
Ok(json!({"feature": v.get("feature"), "name": v.get("name"), "thread": t}))
|
||
}
|
||
|
||
fn pipe(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.pipe";
|
||
let path_sketch = sketch_id(s, p.get("path_sketch"), cmd, "path_sketch")?;
|
||
let path = string_list(cmd, p, "path")?;
|
||
if path.is_empty() {
|
||
return Err(bad(cmd, "`path` must list curve ids"));
|
||
}
|
||
let diameter = req_expr(cmd, p, "diameter")?;
|
||
check_expr(s, &diameter, Kind::Length, cmd, "diameter")?;
|
||
let wall = expr(p, "wall");
|
||
if let Some(w) = &wall {
|
||
check_expr(s, w, Kind::Length, cmd, "wall")?;
|
||
}
|
||
add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::Pipe {
|
||
path_sketch: SketchId(path_sketch),
|
||
path,
|
||
diameter,
|
||
wall,
|
||
operation: operation(p, cmd)?,
|
||
targets: string_list(cmd, p, "targets")?.into_iter().map(BodyName).collect(),
|
||
},
|
||
)
|
||
}
|
||
|
||
fn bounding_solid(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.bounding_solid";
|
||
let margin = expr(p, "margin").unwrap_or_else(|| "0".into());
|
||
check_expr(s, &margin, Kind::Length, cmd, "margin")?;
|
||
add_feature(s, p, FeatureKind::BoundingSolid { bodies: string_list(cmd, p, "bodies")?.into_iter().map(BodyName).collect(), margin })
|
||
}
|
||
|
||
fn scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.scale";
|
||
let bodies = string_list(cmd, p, "bodies")?;
|
||
if bodies.is_empty() {
|
||
return Err(bad(cmd, "`bodies` must list bodies"));
|
||
}
|
||
let factors = match p.get("factors").and_then(Value::as_array) {
|
||
Some(a) if a.len() == 3 => {
|
||
let e: Vec<String> = a.iter().map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).collect();
|
||
for x in &e {
|
||
check_expr(s, x, Kind::Unitless, cmd, "factors")?;
|
||
}
|
||
Some([e[0].clone().into(), e[1].clone().into(), e[2].clone().into()])
|
||
}
|
||
Some(_) => return Err(bad(cmd, "`factors` must have three values")),
|
||
None => None,
|
||
};
|
||
let factor = match (&factors, expr(p, "factor")) {
|
||
(_, Some(f)) => f,
|
||
(Some(_), None) => "1".into(),
|
||
(None, None) => return Err(bad(cmd, "give `factor` or `factors`")),
|
||
};
|
||
check_expr(s, &factor, Kind::Unitless, cmd, "factor")?;
|
||
let origin = p.get("origin").and_then(vec3).unwrap_or(Vec3::ZERO);
|
||
add_feature(s, p, FeatureKind::Scale { bodies: bodies.into_iter().map(BodyName).collect(), origin: Position(origin), factor, factors })
|
||
}
|
||
|
||
fn delete_face(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let faces = face_points(s, p, "face.delete")?;
|
||
let heal = bool_(p, "heal").unwrap_or(true);
|
||
add_feature(s, p, FeatureKind::DeleteFace { faces: faces.into_iter().map(FacePick).collect(), body: str_(p, "body").map(BodyName::from), heal })
|
||
}
|
||
|
||
fn offset_face(s: &mut Session, p: &Value) -> Result<Value> {
|
||
let cmd = "solid.offset_face";
|
||
let faces = face_points(s, p, cmd)?;
|
||
let distance = req_expr(cmd, p, "distance")?;
|
||
check_expr(s, &distance, Kind::Length, cmd, "distance")?;
|
||
add_feature(
|
||
s,
|
||
p,
|
||
FeatureKind::OffsetFace { faces: faces.into_iter().map(FacePick).collect(), distance, body: str_(p, "body").map(BodyName::from) },
|
||
)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
#[path = "patterns_tests.rs"]
|
||
mod patterns_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "model_axis_tests.rs"]
|
||
mod model_axis_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "prism_local_tests.rs"]
|
||
mod prism_local_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "loft_rails_tests.rs"]
|
||
mod loft_rails_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "revolve_convention_tests.rs"]
|
||
mod revolve_convention_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "single_hole_tests.rs"]
|
||
mod single_hole_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "sweep_options_tests.rs"]
|
||
mod sweep_options_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "sweep_rails_tests.rs"]
|
||
mod sweep_rails_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "offset_topology_tests.rs"]
|
||
mod offset_topology_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "offset_identity_tests.rs"]
|
||
mod offset_identity_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "offset_edit_guard_tests.rs"]
|
||
mod offset_edit_guard_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "offset_ends_tests.rs"]
|
||
mod offset_ends_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "offset_plane_face_tests.rs"]
|
||
mod offset_plane_face_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "lineage_face_tests.rs"]
|
||
mod lineage_face_tests;
|
||
#[cfg(test)]
|
||
#[path = "stacked_face_tests.rs"]
|
||
mod stacked_face_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "solid_move_copy_tests.rs"]
|
||
mod solid_move_copy_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "move_in_sketch_tests.rs"]
|
||
mod move_in_sketch_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "thin_extrude_tests.rs"]
|
||
mod thin_extrude_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "extrude_convention_tests.rs"]
|
||
mod extrude_convention_tests;
|
||
/// `solid.fillet corner?: rolling|g2`: the default keeps the rolling ball's sphere corner, `g2`
|
||
/// sets the corner back and fills it with the G2 patch (`solidcraft_kernel::fillet_g2_corners`),
|
||
/// with `setbacks` naming its distance, and an unknown word is refused.
|
||
#[cfg(test)]
|
||
#[allow(clippy::unwrap_used)]
|
||
mod corner_tests {
|
||
use serde_json::{Value, json};
|
||
|
||
use crate::Session;
|
||
|
||
fn run(s: &mut Session, id: &str, p: &Value) -> Value {
|
||
s.execute(id, p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||
}
|
||
|
||
/// A 20 mm box with its three edges at one corner, filleted by 4 with `corner`.
|
||
fn cornered(corner: Option<&str>) -> (Session, Value) {
|
||
let mut s = Session::default();
|
||
run(&mut s, "solid.box", &json!({"length": 20, "width": 20, "height": 20, "body_name": "B"}));
|
||
let mut p = json!({"edges": [[10, 0, 0], [0, 10, 0], [0, 0, 10]], "radius": 4});
|
||
if let Some(c) = corner {
|
||
p["corner"] = json!(c);
|
||
}
|
||
let reply = run(&mut s, "solid.fillet", &p);
|
||
(s, reply)
|
||
}
|
||
|
||
#[test]
|
||
fn the_default_corner_is_the_rolling_ball_and_g2_sets_it_back_for_its_patch() {
|
||
let (default, reply) = cornered(None);
|
||
assert_eq!(reply["warning"], json!(null), "{reply}");
|
||
let (rolling, _) = cornered(Some("rolling"));
|
||
let ball = default.world_state().unwrap().body("B").unwrap().body.clone();
|
||
let same = rolling.world_state().unwrap().body("B").unwrap().body.clone();
|
||
// `corner: rolling` is the default: the same body, to the last bit of its area.
|
||
assert_eq!(solidcraft_kernel::measure(&ball).unwrap().area, solidcraft_kernel::measure(&same).unwrap().area);
|
||
assert!(solidcraft_kernel::measure(&ball).unwrap().volume > 7000.0);
|
||
// `corner: g2`: the corner set back (1.5 r by default, or as `setbacks` says) and filled
|
||
// with the G2 patch: one closed solid of the box's faces, the rounds and the patch, a
|
||
// little fuller than the ball's corner (its patch spans the setback, not the ball).
|
||
let ball_volume = solidcraft_kernel::measure(&ball).unwrap().volume;
|
||
for setbacks in [json!([]), json!([{"vertex": [0, 0, 0], "distance": 7}])] {
|
||
let mut s = Session::default();
|
||
run(&mut s, "solid.box", &json!({"length": 20, "width": 20, "height": 20, "body_name": "B"}));
|
||
run(&mut s, "solid.fillet", &json!({"edges": [[10, 0, 0], [0, 10, 0], [0, 0, 10]], "radius": 4, "corner": "g2", "setbacks": setbacks}));
|
||
let body = s.world_state().unwrap().body("B").unwrap().body.clone();
|
||
assert!(body.validity().is_empty(), "{:?}", body.validity());
|
||
let m = solidcraft_kernel::measure(&body).unwrap();
|
||
eprintln!("corner g2, setbacks {setbacks}: {} faces, volume {:.4} (ball {:.4})", m.faces, m.volume, ball_volume);
|
||
assert_eq!(m.faces, 10);
|
||
assert!((m.volume - ball_volume).abs() < 1e-3 * ball_volume, "{} vs {}", m.volume, ball_volume);
|
||
}
|
||
let mut s = Session::default();
|
||
run(&mut s, "solid.box", &json!({"length": 20, "width": 20, "height": 20, "body_name": "B"}));
|
||
// An unknown word, and a style the G2 corner has no patch for, are refused as parameters.
|
||
assert!(s.execute("solid.fillet", &json!({"edges": [[10, 0, 0]], "radius": 4, "corner": "round"})).is_err());
|
||
assert!(s.execute("solid.fillet", &json!({"edges": [[10, 0, 0]], "radius": 4, "corner": "g2", "type": "chord"})).is_err());
|
||
assert!(s.execute("solid.fillet", &json!({"edges": [[10, 0, 0]], "radius": 4, "corner": "g2", "fit": "reduce"})).is_err());
|
||
// A corner where convex and concave rounds meet (the top of a notch's inner edge, two
|
||
// convex rounds and the concave one) is refused, the message naming it and why.
|
||
let mut s = Session::default();
|
||
run(&mut s, "solid.box", &json!({"length": 60, "width": 40, "height": 20, "body_name": "B"}));
|
||
run(&mut s, "solid.box", &json!({"corner": [40, 20, 10], "length": 30, "width": 30, "height": 20, "body_name": "N"}));
|
||
run(&mut s, "solid.combine", &json!({"target": "B", "tools": ["N"], "operation": "cut"}));
|
||
let mixed = json!({"edges": [[40, 20, 15], [50, 20, 20], [40, 30, 20]], "radius": 3, "corner": "g2"});
|
||
let err = s.execute("solid.fillet", &mixed).unwrap_err().to_string();
|
||
eprintln!("mixed corner g2: {err}");
|
||
assert!(err.contains("not supported yet") && err.contains("(40.000, 20.000, 20.000)") && err.contains("all convex or all concave"), "{err}");
|
||
}
|
||
}
|
||
#[cfg(test)]
|
||
#[path = "fillet_connected_rounds_tests.rs"]
|
||
mod fillet_connected_rounds_tests;
|