Files
solidcraft/docs/drawing-hlr.md
T
Mateusz SychandMateuszSychXpl e81a201ff8 Drawing W06a: parallel hidden lines and shared work limits (#2455) (#3013)
* geom/hlr: per-curve work on worker threads, shared work limits

Silhouette tracing, screen sampling, shadow cuts, classification, coverage and
the crossing search (by grid rows) with crossing refinement run on worker
threads through one ordered map: results go back in item order, so drawings
are the same bit for bit on any number of threads. Options::threads picks the
workers (0 = one per core, small views stay on the calling thread); the
browser build stays serial. Placements sharing a body and a turn share one
silhouette tracing.

Cancellation is polled before every item and inside long ones from every
worker; the first error stops the others; a panicking worker becomes
HlrError::Internal instead of escaping. Ray, curve, crossing, shadow and
coverage budgets are totals over all threads (shared counters; crossing pairs
are counted before the search).

Limits: placements and the default max_tracks are hlr::MAX_ITEMS, which is
section::MAX_ITEMS (also the brep record limit); trim_samples must be 1..=4096.

* docs/drawing-hlr: link the parallel-work PR

* geom/hlr: clearer limits and parallel-work docs, faster thread tests

docs/drawing-hlr.md now separates input limits (with the error each returns:
body records fail with Invalid, not Budget) from the work budgets, names every
budget's error, and states how errors and panics behave on worker threads.
Code comments say the same in plainer terms. The budget and cancellation
tests drop the oblique torus, and the freeform pass of the identity test
compares one parallel run, which keeps the HLR suite under 4 s.

* geom/hlr: poll cancellation inside long items, find spline spans by bisection

Review found two items a worker could run for seconds without seeing a
cancellation: tracing a body with many curved surfaces, and sampling one long
spline (up to 4096 control points). Silhouette tracing now asks before each
surface, screen sampling at every refinement pass, the cuts at left-out faces
every 4096 chords and coverage every 65536 checks.

The long spline was slow because every point and every part hull scanned all
of its knot spans. de Boor evaluation now finds its span by bisection over the
ordered knots, and a part's hull starts at its first piece and stops after
its last: the same spans, so the same bits (checked on the fixture scenes),
and a 4096-point spline edge prepares in 0.9 s instead of 2.2 s and samples
in 0.23 s instead of 1.47 s.

* geom/hlr: poll cancellation while forming and trimming silhouette sets

Review found that forming a body's silhouette sets scanned each face's whole
surface group before the first poll, quadratic in the faces on one surface
(about 4e8 steps for 20 000 faces). The group scan now stops at its first
supported face (groups list faces in order, so that is the same face), the
loop polls every 256 faces, and trimming a traced curve asks before each
face. A cancellation seen while trimming drops the partial curves, even if
the callback answers false later. Output unchanged on the fixture scenes.

* geom/hlr: poll cancellation per boxes met when cutting at left-out faces

Review found that one chord crossing the screen boxes of very many left-out
faces bisects every side without a poll (polls came only every 4096 chords).
It now also polls every 1024 boxes met. The docs state the cancellation
contract precisely: polls are where listed, and the work between two polls is
bounded by the input limits rather than by a time.

* docs/drawing-hlr: say where coverage polls cancellation

* geom/hlr: body records have brep's own, larger limit now

Main raised brep::MAX_ITEMS to 1 000 000 (#3093, which stores whole evaluated
models), so it no longer equals section::MAX_ITEMS. hlr::MAX_ITEMS stays
section's 100 000 for placements and the default curve budget; the docs and
the limits test now say that a body's records are bounded separately, by
brep's limit.

* geom/hlr: a panicking worker stops the others; the ray budget is HLR's own

A worker that panics now sets the shared stop flag while it unwinds, so the
other workers end the phase early instead of finishing work the call throws
away. The docs no longer compare the ray budget with the occlusion work
budget of file.export_view_dxf: the two count different work.

* geom/hlr: an ignored timing test, prepare and drawing timed apart

hlr_timing prepares four bodies, then draws 100 differently turned placements
on one thread, two workers and one worker per core, printing the total, the
phase timings and the ray count. SOLIDCRAFT_BENCH_HLR sets the placement count.

* geom/hlr: timing scenes for sharing and crossings; placements keep their lines when permuted

hlr_timing now starts its prepare clock after the fixtures are built, adds the
same grid at one turn (shared definitions against one per placement) and
sixteen thin bars crossing 8x8 from above, rotates the thread order over three
rounds and checks the drawings match across thread counts outside the timed
part. A new test permutes three placements of one prepared box and removes one:
each line keeps its own placement index, and the boxes' lines stay exact.

* docs/drawing-hlr: the review's limits and fixtures in the parallel tables

* geom/hlr: follow the B-rep record into solidcore-record

The record, its version and its item limit now come from solidcore-record
(#11496): the new tests build their bodies at `solidcore_record::brep::VERSION`
and make a spline's curve with `C3::bounded`, as the other fixtures do, and
the limits table gives the record's own limit, 4 000 000 items, checked by
`brep::check::validate`.

---------

Co-authored-by: MateuszSychXpl <151755914+MateuszSychXpl@users.noreply.github.com>
2026-11-04 16:56:07 -05:00

19 KiB

Hidden lines (W06a)

This is the geometry core of Drawing package W06 from the published plan in #860: #2455 / PR #2457, with its parallel work and shared limits in PR #3013. It turns the subset that the W05a investigation (#2105, draft #2106, findings) showed to be ready into code: exact orthographic hidden lines for placed bodies whose faces are planes, cylinders, cones, spheres or tori.

The code is crates/geom/src/hlr (layer L0). It reads the neutral geom::brep records, uses no kernel or UI types, returns errors instead of panicking and builds for wasm32-unknown-unknown. It does not register commands, create views, extract bodies from the kernel or draw sections. The read-only kernel adapter follows the W02 extraction contract; until then callers build Brep records themselves.

Using it

prepare(&Brep, &Options) -> Result<Prepared, HlrError>            once per body
hidden_lines(&[Prepared], &[Placement], &View, &Options, &cancel) -> Result<Drawing, HlrError>
  • prepare checks the body (Brep::validate), recognises each face's surface, builds its trim and classifies each edge as sharp, tangent or seam. Prepared::report says what it found: surfaces and curves by kind, tangent and seam edges, faces whose trim is unsupported, freeform faces and the largest boundary chord error.
  • A Placement puts a prepared body in the scene: world = rotation * local + translation, the rotation given by its columns. Several placements may share one prepared body. A placement that is not a proper rotation (a mirror, a scale) is refused with HlrError::Invalid.
  • View::new(direction_of_sight, up) is an orthographic view. Screen coordinates are (p . x, p . y) in millimetres, with x = direction x up normalised and y = x x direction.
  • cancel is polled during the work, from every worker thread, so it must be Sync; when it returns true the call ends with HlrError::Cancelled. prepare_cancellable(&Brep, &Options, &cancel) is prepare with such a callback, polled between edges, faces and surface comparisons.
  • Options::threads sets the number of worker threads (0, the default, means one per core); see Parallel work.

The Drawing holds one Line per drawable edge and per silhouette curve of each placement, in order of placement. A line names its placement and source (Edge { edge, tangent } or Silhouette { face }) and is split into pieces. Each Piece has:

Field Meaning
t Parameter interval on the source curve.
visibility Visible, Hidden or Uncertain.
covered Another piece already draws the same projected curve here; draw only uncovered pieces.
geometry The piece in screen coordinates as Seg2 segments.
accuracy CurveAccuracy of geometry (the W01a vocabulary).

Drawing::unsupported lists the faces whose silhouettes were not drawn and why; Drawing::stats counts curves, crossings, pieces, rays and uncertain pieces, with phase timings where the platform has a clock (zero on wasm32-unknown-unknown).

What is exact

Source Geometry Accuracy
Line edges; cylinder and cone silhouette rulings one Seg2::Line Analytic
Circle and ellipse edges; sphere silhouettes; torus silhouettes seen along the axis Seg2::Conic arcs of at most 90 degrees Analytic
Spline and intersection edges chords between exact points, halved until each piece's control hull is within the sag target Sampled (a bound from that hull)
Torus silhouettes in other views chords between traced points, halved to 1e-7 of the torus's size Sampled (measured deviation)

An orthographic projection is affine, so a circle projects to an ellipse, which a rational quadratic arc represents exactly. Chords are refined until their sag on screen is at most 1e-7 of the scene size. A fitted edge record also carries its own bound, and the visibility work allows for it.

Surfaces are recognised whether they are stored as analytic records, as rigidly placed revolutions of lines and circles or as spline patches (to 1e-9 relative; a patch whose control points lie in one plane is that plane). A spline curve or patch is taken for a circle, quadric or torus only when it lies on it at enough points of every knot span to make the check exact for its degree, with its largest distance there, scaled by how far apart its weights are, within the tolerance: weights near zero cannot hide a swerve, and widely spread weights mean chords. A recognised patch is trimmed and intersected in its own analytic chart. Faces that lie on one surface (a sphere stored as two hemispheres, a cylinder split in two) share their silhouettes: the edges between them are seams and are not drawn, and a silhouette running along such a seam is one curve. A face joins such a set only when the first face's surface passes through its own points to rounding (1e-13 of its size); recognition alone groups surfaces more loosely, and such faces keep silhouettes of their own.

Visibility

Projected curves are split where they cross or touch, found on a screen grid and refined on the exact curves. Each piece is classified by rays toward the viewer against every trimmed face: closed forms for planes and quadrics, a sampled quartic for tori. A ray that grazes a face, meets one within its boundary tolerance or meets another body right at its start makes the piece Uncertain; nothing is guessed.

Coincident curves (an edge and a silhouette on top of each other, two touching bodies) follow the W05a policy: visible wins and duplicates are marked covered. The tolerance comes from the curves' own accuracy (chord sag and fit bounds) plus a rounding allowance of 1e-7 mm and 1e-9 of the scene size, never from the scene size alone, so small parts in large scenes keep their detail.

prepare moves each body to its own centre, and the work is done in a frame centred on the scene and shifted back at the end, so coordinates stay small: a part 1e7 mm from the origin, whether placed there or modelled there, is classified as at the origin.

Parallel work

hidden_lines spreads its per-curve work over worker threads: silhouette tracing, screen sampling, the cuts at the boxes of left-out faces, the classification of pieces, coverage, and the crossing search (by rows of its screen grid) with the refinement of each crossing. Each phase hands its items to the workers one at a time and stores every result at its item's index, so the drawing is identical, bit for bit, for any number of threads: the same pieces in the same order and the same statistics apart from the phase timings.

  • Thread count. With Options::threads at 0 (the default) a phase uses up to one worker per core, but at most one per distinct silhouette tracing, 16 curves, 4 grid rows or 256 crossings, so the per-curve phases of a small view stay on the calling thread. 1 runs everything on the calling thread; a larger number caps the workers. The browser build always runs on the calling thread.
  • Shared silhouettes. Silhouettes depend on the body and the direction of sight in its own frame, not on its position, so placements that share both (repeated parts turned alike) share one tracing. This speeds up the browser build too.
  • Cancellation. cancel is polled before every item, on whichever thread runs it, and inside long items: every 256 faces and before every face a silhouette is trimmed to, at every sampling pass, every 4096 chords and every 1024 boxes met when cutting at left-out faces, every 1024 rays, every 65 536 crossing candidates, and between the chords of a piece once 65 536 coverage checks have passed since the last poll. The work between two polls is bounded by the input limits, not by a time: in ordinary scenes the longest step is tracing one surface's silhouette curves, a few tenths of a second for a torus, but a scene built at the limits can make one step take longer.
  • Errors. The first error, cancellation included, stops the other workers and is the one returned. When two different failures coincide on different threads (a cancellation while a budget is exceeded), the error returned may differ from a run on one thread; a successful result never does.
  • Panics. Every parallel item runs on a spawned worker that the calling thread joins. A worker that panics loses its item and stops the other workers: the call returns HlrError::Internal and no drawing, and the panic does not reach the caller. Work on the calling thread (one thread, or the browser build) lets a panic propagate to the caller as before.

Measured on a 32-thread desktop (release build, isometric view of boxes, cylinders, spheres and tori): 100 placements, each turned differently, take 0.8 s, against 9.9 s on one thread; 300 placements turned alike take 0.8 s, against 33 to 55 s before silhouettes were shared.

Freeform faces

Faces that are not planes, cylinders, cones, spheres or tori are freeform. By default they are listed in Drawing::unsupported with the reason freeform face, their silhouettes are not drawn, and a piece whose ray meets one is Uncertain, never Hidden. Without its silhouettes nothing marks where such a face's outline crosses a curve, so curves are cut at the face's screen box and every piece inside the box that can reach behind its nearest point (bounded by the curve's control points, not by samples) is Uncertain too, the face's own edges included (faces left out for an unsupported trim likewise). With Options::freeform set their silhouettes are contoured and their ray tests use seeded Newton iterations: slower, Sampled, and subject to the misses listed in the W05a findings.

Limits

Inputs are checked before any work:

Input Limit Otherwise
Records of one body solidcore_record::brep::MAX_ITEMS (4 000 000), checked by brep::check::validate in prepare Invalid("portable B-rep")
Placements in one scene hlr::MAX_ITEMS (100 000) Budget("placement")
Options::trim_samples 1 to MAX_TRIM_SAMPLES (4096) Invalid("trim samples")
Coordinates of a placed body's box at most MAX_COORDINATE (1e12 mm, the bound geom::section and geom::brep put on stored numbers) Invalid("scene extent")
Options::threads at most MAX_THREADS (64) capped

Work budgets are totals over the whole call and all worker threads. Whether one is exceeded does not depend on the number of threads or on their scheduling:

Work Budget Error
Surface comparisons grouping a body's faces, in prepare 50 million Budget("surface group")
Curves: drawable edges and silhouette pieces Options::max_tracks, default hlr::MAX_ITEMS Budget("curve")
Visibility rays Options::max_rays, default 20 000 000 Budget("ray")
Crossing grid entries 50 million Budget("crossing grid")
Crossing candidate pairs, counted before the search 500 million Budget("crossing pair")
Crossings 50 million Budget("crossing")
Left-out face grid entries 50 million Budget("shadow grid")
Left-out face box checks 500 million Budget("shadow")
Coverage point checks 200 million Budget("coverage")

hlr::MAX_ITEMS is section::MAX_ITEMS, the aggregate item limit that geom::section applies, and the body limit of file.export_view_dxf. It bounds the placements a caller supplies and, by default, the number of curves, which is the number of lines in the drawing; a caller drawing a large assembly may raise max_tracks. A body's own records have the larger limit of the B-rep record (solidcore_record::brep), which stores whole evaluated models. The ray budget is HLR's own: it counts visibility classifications, one per ray. The 200 million work steps of file.export_view_dxf count other work (placements, tree nodes and triangles of its occlusion test), so the two numbers are not comparable. Every piece costs at least one ray, so the ray budget also bounds the pieces. The remaining caps bound the steps in between.

Other limits:

  • Options::tangent_edges (default on) draws edges between tangent faces, flagged tangent: true; drafting policy for them is W17.
  • Tolerances are relative to the faces and the scene. They are meant for faces up to about 10 m across and features down to about 1e-3 mm. A spline patch only a sliver wide next to its radii (a few millionths of them) cannot be told from its neighbours' surfaces reliably and is reported as freeform. Distinct surfaces that recognition takes for one (closer than 1e-9 of their size or position, a nearly flat cone's far apex included) share the own-face margin of 1e-6 of the face's size when a ray leaves one of them.
  • Not in this slice: the kernel adapter (after W02), perspective, section regions (W03), views and commands (W07), and mirrored placements. Of the records the kernel now saves, planes through three points (PlaneThrough) are drawn as planes; a procedural SurfaceIntersection curve is drawn as its leader, within its tolerance, when the leader is a spline; one with a polyline leader, or a PlacedRevolution surface whose placement is not rigid (it may scale it unevenly), is refused by prepare with HlrError::Unsupported until the adapter handles them. A single surface's silhouette is traced on one thread, so one torus seen obliquely still takes about 0.3 s whatever the thread count.

Fixtures

crates/geom/src/hlr_tests.rs builds bodies from records and checks analytic positions and intervals:

  • a cube in an isometric view hides its three back edges; a box in front hides the middle of an edge over exactly the covered interval;
  • a cylinder's silhouette rulings are exact lines, including one along the seam; a cone frustum seen from the front has exact rulings and draws each edge-on circle once;
  • a sphere's outline is exact conic arcs at its radius in three views;
  • a disc bounded by a rational circle with unevenly spaced knots, with a knot span narrower than rounding, or with a parameterisation that races through its first turn is drawn as arcs turning the full 360 degrees; splines off their circle between evenly spaced samples or inside such a narrow span are drawn as chords; exact arcs that turn almost all of their 358 degrees in the first hundredth of their parameter, or several radians in a knot span of 1e-6 or 1e-11, keep the turn of every piece;
  • a torus stored as two halves, seen face on, is drawn at both equators, one silhouette each; an edge under it is hidden over exactly the intervals the tube covers; seen obliquely its outline spans R + r on both sides with a deviation under 1e-3 mm;
  • cone frusta and narrow cone sectors a hair off one axis or with axes 3e-7 rad apart, and spherical caps through one circle with centres 5e-7 mm apart, keep their own outlines;
  • a cylinder 1e5 and 1e7 mm from the origin draws as at the origin; a cone trimmed to its tip 1 mm below the apex hides nothing above it;
  • a freeform patch is reported and makes the edges it covers uncertain, or hidden when freeform faces are enabled; a flat spline patch hides them for certain; a long edge behind a freeform tube is uncertain where the tube may cover it and visible elsewhere, and so is a sloping edge that only dips behind a freeform patch near its end, while one that leaves the patch's box below its level but crosses the box above it stays visible;
  • a curve that swerves 2.9 mm off its circle where its weight is 1e-12, and a nearly straight cubic 0.002 mm off a circle of radius 1e7, are drawn as chords; an edge whose depth dips behind a freeform patch between its samples is uncertain there, and so is an arc seen along its plane whose projection folds back under a freeform patch between two samples, and the edge of a freeform sheet that curls back over it 0.005 mm above;
  • a torus patch stored as a rational spline is recognised and draws its outer equator as an exact arc, and one with a bump in a knot span 0.002 of its parameters wide is not taken for a torus; a big circle passing under a thin freeform tube in a coarse scene is uncertain there;
  • two strips of a torus 0.0003 rad wide keep their 0.006 mm of outline;
  • two touching boxes draw each shared edge once;
  • a box whose top plane record stands one rounding (or 1e-11 of 100 mm) off its edges still hides its back edges, and so does a 0.001 mm cube 1e7 mm out whose top plane is one step above its edges; a plate's sixteen holes each hide the same part of their bottom circle; eight coaxial cylinders seen along their axis show one circle; 300 boxes apart on screen are each drawn as the first one; an arc that bulges across a line 1 mm off its chord still crosses it twice; the trim's chord grid agrees with a scan of every chord; surface groups agree with comparing every pair of faces, and preparing can be cancelled;
  • mirrored placements, bad body indices and bad views are refused; cancellation and budgets return errors;
  • a box stored with planes through three points draws the same bits as one with axis-stored planes; rigidly placed revolutions draw as what they are, others are refused as not supported yet, as are intersection curves with no spline to follow;
  • a mixed scene (touching boxes, cylinders, a sphere, an oblique torus and a left-out patch, with and without freeform faces) draws the same bits on 1, 2, 3, 8 and automatic threads; placements sharing a body and a turn draw as if each had its own copy of the body; the ray and curve budgets pass at the serial run's counts and fail one below them on 1 and 4 threads; cancellation asked only from worker threads ends a parallel run, and a failing or panicking item ends the work with its error; scenes over MAX_ITEMS placements and trim sample counts out of range are refused; sampling one long spline and tracing a body's silhouettes ask for cancellation inside the item; spline points and part hulls come from their own knot spans;
  • torus ray roots for thin, large and nearly tangent cases, and torus silhouettes near the axis direction.