Files
solvecraft/docs/native-brep.md
T
Irakli Kourtis 93a2922c5e Display plans and the model cache for large STEP assemblies (#2814) (#4021)
* STEP import: mesh band faces that wrap around a closed surface correctly

Fixes two related bugs that caused SolidCraft to fail to mesh a face wrapping
all the way around a closed, non-periodic surface (a revolved ridge band, or a
tube-shaped B-spline surface): a missing face, a folded/self-overlapping
triangulation, or a hole in the rendered body.

1. Ring edges that run slightly off their surface. STEP files write a surface
   and the curves bounding it to the file's own declared uncertainty, so a
   ring edge can legitimately sit a few micrometres off the surface it
   bounds. The code finding where a ring edge crosses the planned split line
   compared against the edge's raw (off-surface) point using a hardcoded
   tolerance far stricter than the file's own precision, rejecting a valid
   cut. Now matches against the point on the surface directly below the ring
   crossing, respecting the file's declared tolerance.

2. Closed B-spline surfaces, their slits and their slivers. truck only treats
   the rotation of a revolved surface as periodic; a face on a B-spline
   surface whose control net closes on itself (a tube) wasn't recognized as
   wrapping around at all. This produced a folded face, a hole (a boundary
   loop landing a full period away from where it should cut), and one
   near-zero-width sliver face costing the entire body its tessellation
   plan. Adds periodicity detection for closed B-spline surfaces, period-
   aware hole-loop alignment, dropping of zero-width slit boundaries, and
   isolating a too-thin-to-triangulate face so it no longer takes the rest
   of the body down with it. The GPU shader's periodic wrap mirrors the CPU
   math so the two don't drift apart.

Regression tests: band_faces_split_when_ring_edges_run_off_their_surface,
band_face_with_a_zero_width_slit_is_still_meshed,
a_sliver_face_too_thin_to_triangulate_does_not_cost_the_body_its_plan.
Ablation-tested: disabling either mechanism in (2) reproduces its target
test's original failure message while leaving the other test unaffected.

* STEP import: mesh the band's split faces, not just split them

jyviko asked whether a band wall missing from the interactive app's render
was a shading issue or a genuinely missing face. It was missing: the ring-
edge split fix made the band's topology correct, but plan_face still
produced zero triangles for the two new sub-faces.

Two causes, both in plan_face (crates/kernel/src/tess/mod.rs):

1. The tolerance for how far an imported boundary may lie off its surface
   was tied to the requested mesh's chord tolerance instead of to the
   body's own size. A finer display tolerance could then reject a boundary
   a coarser one had just accepted, so the face would drop out exactly when
   zooming in on it.

2. Near a sharp corner of this flat-panelled band, several boundary points
   that are legitimately a few micrometres apart (within the STEP file's
   own declared precision) all projected onto the same surface point. The
   boundary loop then repeated a point in (u, v), which a triangulator
   can't follow, so the face's plan failed outright. One face without a
   plan costs the whole body its plan, and the fallback mesher can't
   handle a closed B-spline surface either, leaving both halves of the
   split band with no triangles at all: present in the topology, invisible
   in every renderer, and absent from the body's volume.

Fix: scale the off-surface tolerance to the body's own extent (new
Rules::extent), and collapse a run of boundary nodes that land on the same
surface point to one (drop_collapsed) before triangulating.

Regression test additions to band_faces_split_when_ring_edges_run_off_their_surface:
the body's volume now matches the analytic pentagon prism (was a third of
it - only the top cap - before this fix); display_plan leaves no face
without triangles from coarse to fine tolerance; and the actual tolerance
and facet angle the viewport draws with gives the split band its full
lateral area on both halves.

Confirmed on review_band_big.step, the fixture behind the review screenshots:
volume's relative error against the analytic pentagon prism drops from
1.4e-4 to 4.1e-6, and the band wall now occludes the floor grid behind it
in a snapshot the same way the top and bottom caps always did.

Full kernel suite: 739 tests, 0 failed.

* STEP import: hold an imported boundary to the file's own tolerance, not the part's size

jyviko: the off-surface acceptance added in the last commit
(rules.extent * OFF_SURFACE) scaled with the part, so a 2 m part
silently accepted a boundary 2 mm off its surface while a 20 mm copy
of the same part accepted only 0.02 mm. A STEP file's own declared
uncertainty does not grow with the part, so the bound shouldn't either.

Body gains boundary_tol: Option<f64>, Some(file's declared tolerance)
for a body read from STEP (crate::step_in::Units::tol, already used
by the ring-split fix in split.rs), None for anything this kernel
built. It's set before the import's own unmeshed-face check runs, and
carried over by the two face-split operations that re-cut an imported
surface (splitface.rs, outline.rs), since the file's uncertainty still
describes those boundaries afterward.

plan_face's accept now reads: the file's own tolerance when the body
declares one, or the old chord-tolerance/extent bound otherwise. The
old bound's tol * 10.0 term had to go too, not just the extent term:
at a 2 m part's typical display tolerance that term alone is ~20 mm,
nearly ten times the extent bound jyviko objected to, so keeping it
would have left the exact 2 m/2 mm example still silently accepted.

Two new tests in step_in/tests.rs:
- band_faces_split_when_a_scaled_copy_runs_off_its_surface: the same
  band fixture at a realistic 2 m scale with the same absolute slop
  and declared uncertainty as the small one, meshes the same way at
  every chord tolerance from coarse to fine.
- off_surface_budget_follows_the_file_not_the_part_size: the actual
  regression. The same off-surface error is accepted or refused the
  same way whether the part is 20 mm or 2 m; a 2 mm error against a
  1 µm declared uncertainty is refused at both sizes now (accepted at
  2 m under the old bound, refused at 20 mm - that asymmetry was the
  bug). Checked at both a coarse and a fine display tolerance.

Known gap, not fixed here: a STEP-imported body saved into a
.solidcraft design and reopened loses boundary_tol (native.rs's
decoder has no field to read it from) and falls back to the old
extent-based bound on reload. Today's design format has no concept of
this value at all; persisting it is a real format change, out of
scope for this fix.

Full kernel suite: 776 tests, 0 failed. clippy -D warnings clean.

* Display plans for STEP threads and pointed ends (#3847)

Three faces cost a threaded or pointed STEP part its whole display plan, so it
was drawn from the reference mesh: cracked, faceted, and never refined up close.

- A loop through a pole (a cone's apex on the boundary) seemed to wind around
  the surface: the jump at the apex, unwrapped to the nearest copy, was
  arbitrary. The loop is turned to end where it leaves the pole, so the step
  that closes it is an ordinary one (`seam::close_through_pole`).
- Projection onto a spline with hundreds of spans (a helical flank) restarted
  from a 16 x 16 grid and settled on another turn; it now starts from two
  points per span, capped.
- Sag refinement no longer inserts a point exactly on a boundary side, which
  split the side and failed the face.

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

* tess: a refused face's edges are divided finer and it is planned again (#2814)

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

* tess: sliver faces plan empty; a face no method plans is filled flat from its nodes (#2814)

A face whose boundary runs out and back along itself (two edges between the
same vertices, a rounding apart, as STEP files write slivers) encloses nothing
and is planned with no triangles. A face still refused after its edges are
divided finer (a cusp, a sliver whose sides sag across each other, a small cap
at a pole) is filled flat from its shared boundary nodes, so the rest of the
body keeps its display plan instead of falling back to the reference mesh.

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

* display mesh tests: a rim the chord tolerance leaves a line is divided again (#2814)

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

* portable B-rep: up to 8192 control points along a spline direction (#2814)

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

* solidcraft-cli: --debug logs what the engine reports to stderr

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

* STEP import: a spline written over a tiny parameter range is read over one (#2814)

Some writers parameterize splines over a few millionths (a humanoid robot's
edges span 5.4e-6). The kernel tells parameters apart only to 1e-6, so over
such a range it evaluated the curve's end wrongly, and trimming an edge to its
vertices dropped a control point: the bodies could not be stored exactly and
the whole model cache was left out of the design. The knots are now stretched
to span one; the curve is the same and edges are trimmed by their vertices, so
nothing read from the file refers to the old parameters.

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

* model cache: a body keeps its file's declared accuracy (#2814)

A body restored from the cache dropped the accuracy the file it was read from
declares, so the planner held its boundaries to the kernel's own bound and a
reopened design drew differently from the import. It is stored with the body's
runtime values, and only when there is one.

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

* tess: a boundary within a hundredth of its body lies on its surface, at every quality (#2814)

#1721 held a body read from a file to the accuracy the file declares. A writer
declares what it aims for, not a bound its edges keep: a 251-body robot
assembly declaring 0.01 µm has boundaries 10 to 30 µm off their surfaces, and
95 of its bodies lost their display plans. The bound is a hundredth of the
body again, what Normal quality always allowed, and now the same at every
quality, so zooming in still never drops a face (#1721's point). A file
declaring more raises it.

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

* STEP import: keep faces whose edge vertices sit slightly off their curves

Some exporters write an edge's vertex beside the end of its curve, further off
than the accuracy the file declares (a surface export declares
0.01 mm and puts a vertex 0.19 mm off two spline ends). The reader refused
such edges and left the face, and with single-face bodies the body, out.

A vertex may now sit up to the file's tolerance or 1/1000 of the model's size
(the diagonal around its VERTEX_POINTs), whichever is larger, never more than
the existing 1 mm ceiling. Spline and open-conic edges have the end control
point moved onto the vertex, so every such edge meets its vertices exactly.
The file's declared accuracy still governs closed-curve, seam and circle
checks.

* tess, io: review clean-ups (#2814)

- A sliver face is one whose loops are all slit: drop_slits finds it in the
  retry after a failed plan, so the pre-check on every face (folded) is gone.
- The flat fill uses cdt::triangulate (a lenient fill that leaves out sides
  crossing one already kept) and its flood-fill inside test, and the plane
  from geom::Plane.
- Refinement only builds its indexes when a face was refused, takes the
  faces to plan again from edge_faces, and re-samples edges on the pool;
  Rules::finer for the finer rules.
- One PackageWriter::fits for the model cache, the preview and the thumbnail.
- The band split's ring tolerance lives in split.rs; comments say what the
  off-surface bound is now.
- The CLI logger prints Level::as_str().

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

---------

Co-authored-by: David Lackovic <lackovicdavid1234@gmail.com>
Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com>
Co-authored-by: Ray <raykholo@users.noreply.github.com>
2026-10-21 10:37:12 +00:00

10 KiB

Native B-rep, schema 3

This is SolidCraft's geometry data model in solidcraft_geom::brep. It has no modelling-backend dependency. It is the body encoding of a design's model cache (the container format); it is not a STEP replacement for external interchange. The container reader, binary codec and kernel adapters are separate layers. The truck adapter writes it exactly: a body decoded by the producer that encoded it is that body, number for number.

Geometry and topology

Coordinates are IEEE-754 binary64, in millimetres, right-handed Z-up. Angles are radians. Integer references are unsigned 32-bit shell-local indices, never kernel addresses or runtime IDs. The schema version is an explicit unsigned 32-bit field. A body contains ordered shells; a shell contains ordered vertices, edges and faces. Order is retained for SolidCraft's face provenance and naming. Closed and open shells are representable; material containment is not inferred from shell order.

An edge references its start/end vertices in its curve's forward direction. Each face contains ordered closed loops of oriented edge uses. A reversed use swaps edge endpoints. Loops record the physical face-oriented traversal. Face forward flips only the surface normal; it never swaps surface parameters or reverses these stored loops. Adapters must convert their internal boundary conventions separately. Shared edges are stored once per shell. Closed edges may reference the same endpoint vertex; individual adapters may refuse them. The validator checks references and connected closed loops. It does not certify watertightness, geometric coincidence, absence of self-intersections or trustworthy modelling state; backend extraction has additional requirements.

Curves are tagged mathematical records:

  • line: start/end points, linear parameter from 0 to 1.
  • polyline: ordered points, segment i spans parameter i to i+1.
  • spline: full nondecreasing knot vector and Cartesian control points. Degree is knot count minus control-point count minus one.
  • rational_spline: the same basis with homogeneous [x*w,y*w,z*w,w] coefficients, retaining the original coefficients rather than normalizing/reapproximating them.
  • circle_arc and ellipse_arc: an orthonormal frame, radius/radii and an increasing angular range. Position is origin + xrxcos(t) + yrysin(t).
  • intersection: an explicit ordinary 3D polynomial spline (knots and Cartesian control points), positive fitting tolerance in millimetres, and optional two shell-local face references as hints. No supporting surfaces, leader, backend solver or parameter-search convention is required to evaluate it. (Read only; schema 3 writers store the intersection itself, below.)
  • surface_intersection: the intersection of two surface records, traced from a leader (a polyline or spline near it, its knots as the producer holds them) to within tolerance mm. The curve is the procedural one, not a fit: a different kernel must trace it again.

Surfaces include planes (origin and independent parameter axes), polynomial and rational tensor-product splines, and explicit analytic records. Analytic frames store origin and orthonormal x/y axes; z is x cross y. Angular ranges are radians:

  • cylinder: radius, angular range and axial height range;
  • cone: radius at origin, half angle, angular range and height range; radius at height h is radius_at_origin + h*tan(half_angle);
  • sphere: radius, longitude and latitude ranges;
  • torus: major/minor radii, longitude and meridian ranges;
  • revolution: profile, origin, unit axis and angular range. Rotate the profile around that axis using the right-hand rule. There is no persisted affine matrix or backend orientation/parameter-swap flag. (Read only in schema 3.)
  • placed revolution: a full revolution of a profile about an origin and unit axis, then mapped by a column-major affine matrix (non-singular), with the normal reversed unless forward. Nothing is baked into the profile.

A plane_through record is a plane given by three points: parameter (0, 0) at origin, (1, 0) at u_point and (0, 1) at v_point. Writers use it rather than the axis form, whose axes would be rounded differences of the points.

Cylinder/cone positions are origin + hz + r(h)(cos(u)x + sin(u)y). Sphere positions are origin + r(cos(v)(cos(u)*x + sin(u)y) + sin(v)z). Torus positions are origin + (R+rcos(v))(cos(u)*x + sin(u)y) + rsin(v)*z. Analytic normals point outward; face orientation can flip them. Each adapter must preserve the geometric locus and explicit face-oriented boundaries, even when its runtime uses a different parameterization.

Validation and trust

Schema 3 caps 1,024 shells, 1,000,000 combined topology/geometry items, geometry nesting at 16, spline degree at 16 and control points per spline dimension at 8,192. Numbers must be finite and bounded in magnitude by 1e12. Knot order, active spline domain, multiplicities, rectangular grids, positive rational weights, nondegenerate planes, orthonormal frames, unit revolution axes, positive radii, valid angular/height ranges and intersection face references are checked before an adapter is called. These are resource and structural guards, not a geometric validity certificate. The binary reader must additionally bound bytes, allocation and nesting before creating these structures.

Schema tests build and validate an open triangular face without constructing or linking a kernel body. Kernel-specific structures must appear only inside adapters; they must never acquire authority over persisted field names or encodings. A second backend still requires an implemented and tested adapter before claiming cross-kernel interoperability.

Face-source certificates, operation history, appearances and persistent document identities belong to a versioned SolidCraft body/state envelope around this geometry. They must be preserved by the cache codec, not reconstructed from face counts or floating-point comparisons. A decoded cache remains provisional until authoritative re-evaluation finishes. The document and original blobs remain sufficient to reopen when a cache, representation, producer or adapter is unsupported.

Body binary envelope, version 4

SCBREP04 is the eight-byte envelope signature. Geometry schema 3 is nested in solid; metadata schema 1 is nested in metadata; runtime holds what the body measured about itself that later operations read (its size, from which kernel tolerances follow, and the orientation mesh's missing-face count), so a decoded body works to the same tolerances. These are separate version numbers because each contract can evolve independently. Signatures 01 and 02 were development prototypes; 02 introduced the explicit geometry schema while 03 also separated metadata from runtime Rust types and 04 made the encoding exact. Unsupported versions are cache misses, not design-file migration failures.

The envelope uses its own explicitly versioned records for color, paint, authored boundaries, face-source certificates, operation history and boundary protection. Plane, region and segment records are also owned by the wire schema. Exhaustive manual adapter conversions separate these from runtime FaceSource, History, FaceProv, EdgeProv, Paint, Seg2, Region2 and Plane types. Their serde derives or internal refactors cannot silently redefine the saved fields. No truck serde struct, pointer, tessellation or STEP string is written. Changing field semantics requires a format version change, even if a Rust type keeps its name.

Values use tags: null=0, false=1, true=2, signed integer=3, unsigned integer=4, binary64=5, UTF-8 string=6, array=7, object=8. Numbers use eight little-endian bytes. Strings and collections use unsigned 32-bit little-endian lengths; object keys are length-prefixed UTF-8, emitted lexicographically. Readers reject duplicate keys, unknown tags, non-finite numbers and trailing bytes. Limits per body are 256 MiB, 20,000,000 values, depth 48, 1,000,000 entries per collection and 1 MiB per string; a design's cache bounds the total (see the container format).

The truck adapter writes every curve and surface as truck holds it: lines, B-spline and NURBS coefficients, the three points of a plane, a revolution's profile, axis, matrix and orientation, and an intersection's two surfaces, leader and tolerance. Decoding builds the same structures without the constructors that would round them (normalizing an axis, composing a matrix with the identity), and rebuilds each shell's topology as recorded, including closed edges on one vertex and seam edges a wire uses twice. On reading it refuses standalone polylines, unclamped spline domains and non-full angular carrier surfaces in the portable records it does not write. Circle/ellipse arcs use exact rational quadratic loci; the adapter may reparameterize them. Normal flips and backend boundary orientation are converted separately.

Hashes prove which document and payload a cache belongs to, not who wrote it: the container's key ties a cache to the producer, application build and platform that computed it, and the decoder applies the structural and resource checks above to every body. A second backend needs its own tested adapter before cross-kernel interoperability can be claimed.

The box-and-fillet golden JSON fixture pins the decoded version-4 envelope, field names, tags, topology, geometry and metadata. Integer and structural values are exact; floating coefficients allow 1e-10 relative/absolute platform rounding. The signature is asserted separately. This protects the wire contract against accidental runtime-refactor changes.

Bounded provisional display

native_preview_mesh samples at most 32 points along each curved edge, caps each face's boundary at 4,096 points, and bounds spline controls and nested surfaces before parameter searches. Searches use at most 16 refinement trials. Revolution profiles involving procedural intersections are refused in this display path. The separate mesher uses a fixed grid of at most 16 subdivisions per direction and fixed periodic-seam connections; it never invokes adaptive edge, surface or aspect-ratio refinement. Planes use a single grid cell.

Before projection, the caller reserves a conservative triangle bound covering duplicated projected boundary points, periodic seams and the grid for the complete body. Output is checked against that reservation and for finite coordinates. Missing faces or exceeded budgets cause a cache miss. This mesh is approximate, read-only display; normal modelling/export tessellation is unchanged.