Skip to main content

brep_render/
pipeline.rs

1//! History → scene: run a whole feature history through the kernel's native
2//! `execute_history` (same process, same thread — the solid registry is
3//! thread-local) and populate a [`RenderScene`] from the resident handles via
4//! the kernel's native display payload accessor. No JSON, no typed-array
5//! boundary — the R1 promise.
6
7use crate::scene::{solid_display_from_payload, RenderScene, SolidDisplay};
8use brep_kernel::{display_payload_handle_native, execute_history, HistoryRequest};
9use std::collections::HashMap;
10
11/// Non-fatal diagnostics from a scene build (mirrors the previous app's run-history
12/// reporting: a failed feature halts the remaining features but the solids
13/// built so far still display — seeing what a failing history DID build is the
14/// point of the artifact).
15#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
16pub struct SceneBuildReport {
17    /// Per-feature hard errors, as `"<feature id>: <message>"`.
18    pub feature_errors: Vec<String>,
19    /// Unresolved reference-selection names, as `"<feature id>: <name>"`.
20    pub unresolved: Vec<String>,
21    /// What the kernel REPAIRED while building a feature, as
22    /// `"<feature id>: <what>"` — today, a self-crossing the soundness
23    /// acceptance split and re-trimmed rather than refused. Not an error: the
24    /// feature SUCCEEDED, with a result the kernel changed on its way out, and
25    /// a change the user cannot see is the one thing a repair must never be.
26    /// `#[serde(default)]` keeps reports serialized before this field crossing
27    /// the worker boundary.
28    #[serde(default)]
29    pub feature_notes: Vec<String>,
30    /// Solids whose display payload (tessellation) failed, as
31    /// `"<solid name>: <message>"` — the solid is skipped, not fatal.
32    pub display_errors: Vec<String>,
33    /// Per-feature wall-clock execution time `(feature id, milliseconds)` in run
34    /// order, carried through from the kernel's [`brep_kernel::HistoryResult`]
35    /// timings — the history tree's "N ms" readout.
36    pub feature_timings: Vec<(String, f64)>,
37    /// Per-feature output solid names `(feature id, [solid names])` in run order —
38    /// the history tree's read-only "Outputs" node.
39    pub feature_outputs: Vec<(String, Vec<String>)>,
40    /// Named plane FRAMES this run resolved `(frame name, frame)`, in run order —
41    /// every DATUM registers three (`{id}:XY|XZ|YZ`), every PLANE one (`{id}`), and
42    /// a SKETCH its own plane (`{id}`). Surfaced here so the engine can DISPLAY the
43    /// construction datum/plane frames (filtered to the D/P producing features) as
44    /// first-class scene citizens — the resolved frames ride
45    /// [`brep_kernel::FeatureResult::frames`] straight through, no kernel change.
46    pub frames: Vec<(String, brep_kernel::Frame)>,
47    /// Solved sketch PROFILES this run produced `(sketch id, profile)`, in run
48    /// order — every SKETCH feature publishes one under its own id. Surfaced here
49    /// (exactly like [`Self::frames`]) so the engine can display each committed
50    /// sketch as a SHEET SOLID (planar face + named boundary edges + corner
51    /// vertices) via `sketch_display_payload`, no kernel-contract change.
52    pub profiles: Vec<(String, brep_kernel::SketchProfile)>,
53    /// Named axis LINES this run produced `(axis name, line)`, in run order — a
54    /// SKETCH publishes one per line geometry (construction included). Surfaced
55    /// here (exactly like [`Self::frames`]/[`Self::profiles`]) so the engine can
56    /// resolve a revolve/sweep `axis` reference to a world line at annotation-build
57    /// time, fully headless. `#[serde(default)]` keeps older serialized reports
58    /// (pre-`axes`) deserializing cleanly across the worker boundary.
59    #[serde(default)]
60    pub axes: Vec<(String, brep_kernel::Axis)>,
61    /// Named PATH chains this run produced `(path name, curves)`, in run order — a
62    /// SKETCH publishes its whole ordered chain under `{id}` and EACH model segment
63    /// under `{id}:G{gid}`. Surfaced here (exactly like [`Self::profiles`]) so the
64    /// engine can draw a committed sketch's OPEN geometry: an open chain closes no
65    /// region, so it publishes no profile, and before this the sheet builder had
66    /// nothing to draw it from — an open sketch was invisible in 3D. `#[serde(default)]`
67    /// keeps older serialized reports (pre-`paths`) deserializing cleanly across the
68    /// worker boundary.
69    #[serde(default)]
70    pub paths: Vec<(String, Vec<brep_kernel::NurbsCurve>)>,
71    /// Named world POINTS this run produced `(point name, point)`, in run order —
72    /// a SKETCH publishes every solved point under `{id}:P{pid}` with its
73    /// construction flag. Surfaced here (exactly like [`Self::paths`]) so the
74    /// engine can draw a committed sketch's STANDALONE points: a points-only
75    /// sketch (a hole-placement sketch) has no segment and no profile, so before
76    /// this the sheet builder had nothing to draw it from — it was invisible and
77    /// unpickable in 3D. `#[serde(default)]` keeps older serialized reports
78    /// (pre-`points`) deserializing cleanly across the worker boundary.
79    #[serde(default)]
80    pub points: Vec<(String, brep_kernel::ScenePoint)>,
81    /// The wire-harness tail's routing report (endpoints, segments, one route
82    /// per connection, bundles). Read RUNNER-SIDE like everything else here —
83    /// the tail ran on the runner's thread — and shipped so the harness panel
84    /// reads it off the applied run. `#[serde(default)]` keeps older serialized
85    /// reports deserializing across the worker boundary.
86    #[serde(default)]
87    pub wire_harness: Option<brep_kernel::WireHarnessReport>,
88    /// The PMI tail's resolution of every view's annotations (`None` when the
89    /// document carries no `pmi` block).
90    #[serde(default)]
91    pub pmi: Option<brep_kernel::PmiReport>,
92    /// The PORTS tail's resolution of the declared-ports block (`None` when the
93    /// document declares none). Shipped for the same reason the two above are:
94    /// the tail is not a feature, so its refused names and unresolved
95    /// references reach no feature row — the Qualify panel reads them here.
96    #[serde(default)]
97    pub ports: Option<brep_kernel::PortsReport>,
98}
99
100/// Execute a serialized `HistoryRequest` (the `execute_history_json` request
101/// shape — a saved part file parses as one) and build the display scene from
102/// the final resident solids.
103pub fn scene_from_history_json(
104    request_json: &str,
105) -> Result<(RenderScene, SceneBuildReport), String> {
106    let request: HistoryRequest = serde_json::from_str(request_json)
107        .map_err(|error| format!("history request parse: {error}"))?;
108    scene_from_history(&request)
109}
110
111/// Typed-request variant of [`scene_from_history_json`].
112pub fn scene_from_history(
113    request: &HistoryRequest,
114) -> Result<(RenderScene, SceneBuildReport), String> {
115    let mut scene = RenderScene::new();
116    let report = update_scene_from_history(&mut scene, request)?;
117    Ok((scene, report))
118}
119
120/// The fold of a history run into an ordered scene layout: each entry is the
121/// solid's final name, its resident handle, and whether the feature that
122/// produced it REPLAYED from the incremental cache (R10 — a reused solid is the
123/// same resident geometry, so its display can be kept verbatim and its GPU
124/// buffers reused).
125struct SceneLayout {
126    order: Vec<String>,
127    handles: std::collections::HashMap<String, u32>,
128    reused: std::collections::HashSet<String>,
129    /// `name -> creating-feature id` of the FINAL resident SOLIDS (last writer
130    /// wins; a `removed` name drops its entry) — the eager provenance the runner
131    /// ships so the main thread never has to re-run the history to answer
132    /// "what feature produced this SOLID?". Matches the resident semantics of the
133    /// old `resident_handles_and_creators`.
134    creators: std::collections::HashMap<String, String>,
135    /// `face/edge NAME -> ORIGINATING feature id` — the FIRST feature (timeline
136    /// order) to emit each face/edge name, i.e. the entity's TRUE origin (the
137    /// feature that gave it its name). Unlike `creators` this is FIRST-writer-wins
138    /// and is NEVER pruned on `removed`: a boolean removes its target solid and
139    /// re-adds the same solid name carrying mostly the same face names, so pruning
140    /// then re-adding would reset those origins to the boolean feature — the same
141    /// last-writer bug one level down. Accepted edge case: a fully-deleted solid
142    /// whose name later recurs on unrelated geometry keeps its old origin — but
143    /// under this app's DETERMINISTIC naming a recurring name is the same
144    /// conceptual entity, and the whole map is rebuilt every run, so it can never
145    /// point at a feature that was deleted from the history.
146    entity_origin: std::collections::HashMap<String, String>,
147}
148
149/// Whether `request` is an ASSEMBLY document: any ACOMP-typed feature, or a
150/// present `assembly` constraint block. Mirrors
151/// `EngineState::history_has_assembly` — a componentless document ships no
152/// [`AssemblySync`] and the main side clears its projection, exactly as the
153/// main-side sync used to.
154fn request_has_assembly(request: &HistoryRequest) -> bool {
155    request.assembly.is_some()
156        || request.features.iter().any(|feature| {
157            feature.feature_type.eq_ignore_ascii_case("ACOMP")
158                || feature.feature_type.eq_ignore_ascii_case("ASSEMBLY COMPONENT")
159        })
160}
161
162fn fold_history(result: &brep_kernel::HistoryResult, report: &mut SceneBuildReport) -> SceneLayout {
163    // Removals first (a boolean result reuses a removed target's name), then
164    // additions, insertion-ordered — mirrors SceneMap::apply.
165    let mut order: Vec<String> = Vec::new();
166    let mut handles: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
167    let mut reused: std::collections::HashSet<String> = std::collections::HashSet::new();
168    let mut creators: std::collections::HashMap<String, String> = std::collections::HashMap::new();
169    let mut entity_origin: std::collections::HashMap<String, String> =
170        std::collections::HashMap::new();
171    for (index, feature) in result.results.iter().enumerate() {
172        // A feature whose `inputParams` carry no `id` still has to be nameable in
173        // the report, or its errors read as `": <message>"` and point at nothing.
174        // Its POSITION is the only handle it has, and the one `feature_delete`
175        // takes to remove it again.
176        let label = if feature.id.is_empty() { format!("feature[{index}]") } else { feature.id.clone() };
177        for removed in &feature.removed {
178            if handles.remove(removed).is_some() {
179                order.retain(|name| name != removed);
180            }
181            reused.remove(removed);
182            creators.remove(removed);
183            // NOTE: `entity_origin` is deliberately NOT pruned here — see its doc on
184            // `SceneLayout`. First-writer-with-no-pruning is the whole point.
185        }
186        for added in &feature.added {
187            if handles.insert(added.name.clone(), added.handle).is_none() {
188                order.push(added.name.clone());
189            }
190            creators.insert(added.name.clone(), feature.id.clone());
191            // The FIRST feature to emit a given face/edge name IS its origin (this
192            // loop is in timeline order). `entry(..).or_insert_with` keeps that
193            // first writer — using `insert` here would be last-writer and silently
194            // reproduce the exact bug this map exists to fix.
195            for (_, name) in &added.face_names {
196                entity_origin
197                    .entry(name.clone())
198                    .or_insert_with(|| feature.id.clone());
199            }
200            for (_, name) in &added.edge_names {
201                entity_origin
202                    .entry(name.clone())
203                    .or_insert_with(|| feature.id.clone());
204            }
205            // A solid displays as reused only when its whole producing feature
206            // replayed unchanged; a re-run feature re-tessellates.
207            if feature.reused {
208                reused.insert(added.name.clone());
209            } else {
210                reused.remove(&added.name);
211            }
212        }
213        if let Some(error) = &feature.error {
214            report.feature_errors.push(format!("{label}: {error}"));
215        }
216        for name in &feature.unresolved {
217            report.unresolved.push(format!("{label}: {name}"));
218        }
219        for note in &feature.notes {
220            report.feature_notes.push(format!("{label}: {note}"));
221        }
222        // The feature's output solid name(s) — the history tree's Outputs node.
223        report.feature_outputs.push((
224            feature.id.clone(),
225            feature.added.iter().map(|a| a.name.clone()).collect(),
226        ));
227        // The named plane frames this feature resolved (DATUM three / PLANE one /
228        // SKETCH its own). Carried straight through so the engine can display the
229        // construction datum/plane frames (it filters to the D/P producers).
230        for (name, frame) in &feature.frames {
231            report.frames.push((name.clone(), *frame));
232        }
233        // The solved sketch profile (SKETCH features publish one under `{id}`) —
234        // carried straight through so the engine can synthesize its sheet solid.
235        for (name, profile) in &feature.profiles {
236            report.profiles.push((name.clone(), profile.clone()));
237        }
238        // The named axis lines this feature published (a SKETCH emits one per line
239        // geometry) — carried through so the engine can resolve a revolve `axis`
240        // reference to a world line for the angle gizmo.
241        for (name, axis) in &feature.axes {
242            report.axes.push((name.clone(), *axis));
243        }
244        // The named path chains this feature published (a SKETCH emits its whole
245        // chain under `{id}` and every model segment under `{id}:G{gid}`) — carried
246        // through so the engine can draw the segments no closed profile covers.
247        for (name, curves) in &feature.paths {
248            report.paths.push((name.clone(), curves.clone()));
249        }
250        // The named world points this feature published (a SKETCH emits every
251        // solved point under `{id}:P{pid}`) — carried through so the engine can
252        // draw a sketch's standalone points, which no segment covers.
253        for (name, point) in &feature.points {
254            report.points.push((name.clone(), *point));
255        }
256    }
257    // Per-feature timing rides the kernel result straight through.
258    report.feature_timings = result.timings.clone();
259    // The wire-harness routing report rides through the same way; its bundle
260    // solids arrived above as the appended `WireHarness` result's `added`.
261    report.wire_harness = result.wire_harness.clone();
262    report.pmi = result.pmi.clone();
263    report.ports = result.ports.clone();
264    SceneLayout { order, handles, reused, creators, entity_origin }
265}
266
267/// Executes history without accessing the render scene and emits display deltas.
268/// Tracks resident handles so unchanged solids retain their meshes and GPU
269/// buffers when the main thread applies the resulting [`RunOutput`].
270pub struct SceneRunner {
271    /// Last emitted handle per solid name. Handles are never recycled, so a
272    /// matching handle identifies a cache replay whose display can be reused.
273    last_sent: HashMap<String, u32>,
274    /// Baseline tessellation LOD. A change clears `last_sent` so even unchanged
275    /// handles receive meshes built with the new chord tolerance.
276    last_lod: f64,
277    /// Revision installed via `Command::SetPartsLibrary`. Runs with a different
278    /// revision are refused; `reset` clears this alongside the kernel store.
279    pub(crate) parts_library_revision: Option<u64>,
280    /// Names in the last library install. A missing installed part triggers a
281    /// library reload; a name never installed proceeds to the feature's normal
282    /// unresolved-reference error, avoiding an endless reload loop.
283    pub(crate) parts_library_names: std::collections::BTreeSet<String>,
284}
285
286/// One placed component as the run left it — the engine's own projection of the
287/// kernel's `ComponentRecord`, which is a `#[serde(skip)]` side-channel and
288/// carries no serde derives of its own. Shipped in the reply so the main thread
289/// has the post-solve component set without re-running the history.
290#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
291pub struct ComponentSnapshot {
292    /// The owning ACOMP feature id — also the namespace prefix segment.
293    pub id: String,
294    /// The display / parts-library part name.
295    pub part_name: String,
296    /// The rigid instance pose (part-local snapshot space -> assembly space)
297    /// as the kernel's row-major 4x4; [`Self::affine`] wraps it back up.
298    pub transform: [f64; 16],
299    /// Grounded flag (the feature's `isFixed`).
300    pub fixed: bool,
301    /// Opaque source metadata (`sourceKey` / `sourceSignature` / …).
302    pub source: serde_json::Value,
303    /// Member solid scene names, already namespaced (`{id}:{part solid name}`).
304    pub solids: Vec<String>,
305    /// The part's harness PORT ids, namespaced (`{id}:{part port id}`).
306    pub ports: Vec<String>,
307}
308
309impl ComponentSnapshot {
310    /// The pose as the kernel's transform type (for `transform_brep` and the
311    /// structured STEP writer).
312    pub fn affine(&self) -> brep_kernel::AffineTransform {
313        brep_kernel::AffineTransform { elements: self.transform }
314    }
315}
316
317/// Bake an ACOMP `transform` param (`{translate, rotateEulerDeg}`, degrees,
318/// intrinsic `XYZ` — `R = Rx·Ry·Rz`) into the kernel's row-major 4x4. The
319/// inverse of [`brep_kernel::transform_to_pose_params`], which is the encoder
320/// the solver's write-back uses; a component's record pose and its
321/// `inputParams.transform` are the same rigid placement in the two spellings,
322/// and `component_snapshot_pose_matches_the_kernel_bake` pins this against the
323/// kernel's own bake of the same params.
324///
325/// Needed because the per-feature `components` side-channel is captured when the
326/// ACOMP EXECUTES, which is before the constraint tail solves; the solved pose
327/// arrives separately as the write-back. Missing/garbage values fall back to the
328/// identity placement, exactly like the feature's own reader.
329fn pose_params_to_transform(pose: &serde_json::Value) -> [f64; 16] {
330    let vec3 = |key: &str| -> [f64; 3] {
331        let value = &pose[key];
332        std::array::from_fn(|axis| value[axis].as_f64().unwrap_or(0.0))
333    };
334    let translate = vec3("translate");
335    let [rx, ry, rz] = vec3("rotateEulerDeg").map(f64::to_radians);
336    let (sx, cx) = rx.sin_cos();
337    let (sy, cy) = ry.sin_cos();
338    let (sz, cz) = rz.sin_cos();
339    let x = [[1.0, 0.0, 0.0], [0.0, cx, -sx], [0.0, sx, cx]];
340    let y = [[cy, 0.0, sy], [0.0, 1.0, 0.0], [-sy, 0.0, cy]];
341    let z = [[cz, -sz, 0.0], [sz, cz, 0.0], [0.0, 0.0, 1.0]];
342    let mul = |a: [[f64; 3]; 3], b: [[f64; 3]; 3]| -> [[f64; 3]; 3] {
343        std::array::from_fn(|i| {
344            std::array::from_fn(|j| (0..3).map(|k| a[i][k] * b[k][j]).sum())
345        })
346    };
347    let r = mul(x, mul(y, z));
348    [
349        r[0][0], r[0][1], r[0][2], translate[0],
350        r[1][0], r[1][1], r[1][2], translate[1],
351        r[2][0], r[2][1], r[2][2], translate[2],
352        0.0, 0.0, 0.0, 1.0,
353    ]
354}
355
356impl From<&brep_kernel::ComponentRecord> for ComponentSnapshot {
357    fn from(record: &brep_kernel::ComponentRecord) -> Self {
358        Self {
359            id: record.id.clone(),
360            part_name: record.part_name.clone(),
361            transform: record.transform.elements,
362            fixed: record.fixed,
363            source: record.source.clone(),
364            solids: record.solids.clone(),
365            ports: record.ports.clone(),
366        }
367    }
368}
369
370/// Everything the main thread needs from the run's ASSEMBLY tail, read on the
371/// runner right after the run and shipped in the reply.
372///
373/// The kernel's assembly session — the post-solve constraint state, its
374/// per-constraint statuses, the DOF summary and the overlay geometry — is
375/// thread-local to whoever ran `execute_history`. Before this the main thread
376/// obtained them by executing the whole history a SECOND time
377/// (`sync_assembly`), which on a document with a wire harness swept every
378/// bundle twice per edit. It reads them from here instead; the only main-side
379/// replay left is the one a constraint MUTATION needs, because that solve runs
380/// against resident geometry on the thread that asks (see
381/// `EngineState::ensure_assembly_session`).
382///
383/// `None` for a componentless document: nothing here is read and the reads cost
384/// nothing.
385#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
386pub struct AssemblySync {
387    /// The scene's component set in deterministic id order — the same fold
388    /// (`removed` unmaps, `components` inserts) the scene build honours.
389    pub components: Vec<ComponentSnapshot>,
390    /// The post-solve `assembly` block (`{constraints, idCounter}`), which the
391    /// applier folds back into the document — the pose-authority write-back's
392    /// state half (the pose/`isFixed` half rides
393    /// [`RunOutput::assembly_poses`]/[`RunOutput::assembly_fixed`]).
394    pub state: serde_json::Value,
395    /// Per-constraint status rows for the constraints panel.
396    pub statuses: serde_json::Value,
397    /// The solve's DOF / diagnostics summary.
398    pub dof: serde_json::Value,
399    /// Per-constraint overlay rows (world anchors/directions/status/value).
400    pub overlay: serde_json::Value,
401    /// The runner's parts-library store, shipped ONLY when the run itself moved
402    /// it — the ACOMP self-heal and the orphan GC are library mutations and the
403    /// main side has no other way to see them. Omitted (`None`) otherwise: it
404    /// carries every embedded part payload, which for an imported STEP assembly
405    /// is megabytes.
406    #[serde(default, skip_serializing_if = "Option::is_none")]
407    pub parts_library: Option<brep_kernel::PartsLibraryMap>,
408}
409
410/// The delta a [`SceneRunner::run`] produces: the displayed KERNEL solids IN
411/// ORDER plus the run's [`SceneBuildReport`]. The applier walks `snapshot` in
412/// order, reusing or replacing each entry (see the field docs).
413#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
414pub struct RunOutput {
415    /// The displayed KERNEL solids IN ORDER. `display: Some` = freshly tessellated
416    /// (new, or the handle changed since last emit); `None` = UNCHANGED — the
417    /// applier keeps its existing [`SolidDisplay`] for this name, whose
418    /// `source_handle` equals `handle`.
419    pub snapshot: Vec<(String /* name */, u32 /* handle */, Option<SolidDisplay>)>,
420    pub report: SceneBuildReport,
421    /// Eager PROVENANCE: `name -> creating-feature id` for the run's FINAL resident
422    /// SOLIDS (same last-writer-wins fold as the display snapshot). Shipped WITH the
423    /// run so the main thread can answer SOLID provenance without a cold
424    /// `execute_history` — critical once the run lives on a background thread and the
425    /// main-side registry is cold.
426    pub provenance: Vec<(String, String)>,
427    /// Eager ENTITY ORIGIN: `face/edge NAME -> ORIGINATING feature id` (FIRST writer
428    /// in timeline order, never pruned — see `SceneLayout::entity_origin`). Shipped
429    /// beside `provenance` so `creating_feature` can answer "which feature gave this
430    /// face/edge its name?" (the "Edit owning feature" context action + the Info
431    /// tab's `creatingFeature`) with no cold re-run. Crosses the background-worker
432    /// seam, so the serde round-trip test asserts it survives.
433    pub entity_origin: Vec<(String, String)>,
434    /// Assembly-solver POSE write-backs from this run's constraint tail:
435    /// `(component feature id, {translate, rotateEulerDeg})` — read RUNNER-SIDE
436    /// (the kernel assembly session is thread-local to the thread/worker that ran
437    /// `execute_history`, so only the runner can see it) and shipped here so the
438    /// engine folds them into the owning ACOMP features' `inputParams` (the
439    /// pose-authority contract, build-spec §6 step 4). Empty on a no-motion
440    /// solve — a satisfied assembly must not churn feature fingerprints.
441    /// `#[serde(default)]` keeps pre-assembly serialized replies deserializing.
442    #[serde(default)]
443    pub assembly_poses: Vec<(String, serde_json::Value)>,
444    /// `isFixed` write-backs riding the same fold (the Fixed-constraint lane
445    /// grounds a component); shape mirrors [`Self::assembly_poses`].
446    #[serde(default)]
447    pub assembly_fixed: Vec<(String, bool)>,
448    /// Names of solids the solve re-posed IN PLACE this run (the display seam:
449    /// their producing feature may have replayed `reused`, yet their geometry
450    /// moved). The runner already defeated the handle-unchanged reuse fast path
451    /// for these (their snapshot entries arrive `Some`, freshly tessellated);
452    /// shipped for observability/tests. Empty on zero-mate/no-motion runs.
453    #[serde(default)]
454    pub moved_solids: Vec<String>,
455    /// IMPORTED COLOURS: `entity name -> "#RRGGBB"` for every solid/face this run
456    /// left a `color` scene-metadata record on (STEP presentation entities, read
457    /// by `brep_kernel::io/appearance.rs` and stamped by IMPORT3D).
458    ///
459    /// Read RUNNER-SIDE for the same reason as `assembly_poses`: the kernel's
460    /// scene-metadata store is thread-local to whoever ran `execute_history`, so
461    /// a main-thread read under a background runner sees nothing. The applier
462    /// folds these into the engine's own [`crate::metadata::MetadataStore`]
463    /// WITHOUT overwriting, so the Info window shows an imported colour and a
464    /// user's edit of it still wins.
465    ///
466    /// Filtered to the names this run actually produced, so a colour left in the
467    /// (never-cleared) kernel store by a previous document cannot bleed into
468    /// this one.
469    #[serde(default)]
470    pub imported_colors: Vec<(String, String)>,
471    /// Every output name some feature of this run CONSUMED — the union of the
472    /// per-feature `removed` lists, sorted. The committed-sketch refresh hides a
473    /// sketch a downstream extrude/revolve/sheet-metal consumer absorbed, and it
474    /// used to learn that by executing the history again on the UI thread; it
475    /// reads this instead. NOT pruned the way the display fold prunes: a name
476    /// removed and later re-added is still a name this run consumed.
477    #[serde(default)]
478    pub consumed: Vec<String>,
479    /// The run's assembly tail, for a document that has one (see
480    /// [`AssemblySync`]).
481    #[serde(default)]
482    pub assembly: Option<AssemblySync>,
483}
484
485impl SceneRunner {
486    pub fn new() -> Self {
487        Self {
488            last_sent: HashMap::new(),
489            last_lod: 1.0,
490            parts_library_revision: None,
491            parts_library_names: std::collections::BTreeSet::new(),
492        }
493    }
494
495    /// Reset the delta baseline (call on a wholesale document switch so the next
496    /// run is a full rebuild — no stale reuse across unrelated models).
497    pub fn reset(&mut self) {
498        self.last_sent.clear();
499        // A reset always accompanies the `clear_history_cache` that empties
500        // this side's parts library, so forget what was installed — the next
501        // run's stamp will not match and the library is re-sent.
502        self.parts_library_revision = None;
503        self.parts_library_names.clear();
504    }
505
506    /// Execute `request` and fold it into an ordered delta snapshot (does NOT
507    /// touch any scene). For each displayed kernel solid in order: if the handle
508    /// is unchanged since the last emit, emit `(name, handle, None)` (the applier
509    /// keeps its existing display); otherwise (re-)tessellate the resident handle
510    /// and emit `(name, handle, Some(display))`. A display-payload error is
511    /// recorded in `report.display_errors` and the entry is SKIPPED — and NOT
512    /// recorded in the new baseline, so a later successful run re-tessellates it.
513    ///
514    ///
515    /// Colours are NOT applied here. A display arrives colourless and the main
516    /// side paints it from the metadata store
517    /// ([`EngineState::sync_colors_from_metadata`](crate::engine_state::EngineState::sync_colors_from_metadata)),
518    /// which is the only colour authority — a runner may be a background thread
519    /// or worker with no view of that store.
520    pub fn run(&mut self, request: &HistoryRequest) -> RunOutput {
521        self.run_observed(request, &mut |_| true)
522    }
523
524    /// [`Self::run`] with a progress observer: `observe` is called before every
525    /// feature the kernel actually executes (see
526    /// [`brep_kernel::execute_history_observed`]); returning `false` stops the
527    /// run at that boundary, and the partial result is folded like any other.
528    pub fn run_observed(
529        &mut self,
530        request: &HistoryRequest,
531        observe: &mut dyn FnMut(brep_kernel::HistoryProgress<'_>) -> bool,
532    ) -> RunOutput {
533        // The parts-library revision ACROSS the run: a run heals a dirty entry
534        // and GCs orphans, and those are the only library mutations the main
535        // side cannot see for itself. Compared below to decide whether the
536        // (potentially megabyte) store has to ride the reply.
537        let library_revision_before = brep_kernel::parts_library_revision();
538        let result = {
539            let mut trace = crate::run_trace::span("runner");
540            let result = brep_kernel::execute_history_observed(request, observe);
541            if let Some(trace) = trace.as_mut() {
542                trace.result(&result);
543            }
544            result
545        };
546        let mut report = SceneBuildReport::default();
547        let layout = fold_history(&result, &mut report);
548
549        // --- assembly pose-authority read (RUNNER-SIDE, build-spec §6/§13) ----
550        // The kernel assembly session (constraint solve tail) is THREAD-LOCAL to
551        // whoever ran `execute_history` — i.e. this thread/worker — so the pose
552        // and isFixed write-backs must be read HERE and shipped in the RunOutput;
553        // a main-thread read under a background runner would see a cold session.
554        let pose_updates: serde_json::Value =
555            serde_json::from_str(&brep_kernel::assembly_pose_updates_json())
556                .unwrap_or(serde_json::Value::Null);
557        let assembly_poses: Vec<(String, serde_json::Value)> = pose_updates["poses"]
558            .as_object()
559            .map(|map| map.iter().map(|(id, pose)| (id.clone(), pose.clone())).collect())
560            .unwrap_or_default();
561        let assembly_fixed: Vec<(String, bool)> = pose_updates["isFixed"]
562            .as_object()
563            .map(|map| {
564                map.iter()
565                    .filter_map(|(id, flag)| flag.as_bool().map(|b| (id.clone(), b)))
566                    .collect()
567            })
568            .unwrap_or_default();
569        // The display seam: solids the solve re-posed IN PLACE keep their resident
570        // handle, so the handle-unchanged reuse fast path below would wrongly skip
571        // re-tessellating them even though their geometry moved. Drop them from
572        // the baseline so they re-emit fresh displays. The `movedSolids` key is
573        // ABSENT on zero-mate reports — tolerated (empty).
574        let dof: serde_json::Value = serde_json::from_str(&brep_kernel::assembly_dof_json())
575            .unwrap_or(serde_json::Value::Null);
576        let moved_solids: Vec<String> = dof["movedSolids"]
577            .as_array()
578            .map(|items| {
579                items
580                    .iter()
581                    .filter_map(|item| item["name"].as_str().map(String::from))
582                    .collect()
583            })
584            .unwrap_or_default();
585        for name in &moved_solids {
586            self.last_sent.remove(name);
587        }
588
589        // --- the assembly session + consumed names (RUNNER-SIDE) -------------
590        // Same thread-local reason as the poses above, and the whole point of
591        // `AssemblySync`: read here, applied there, never re-executed.
592        let assembly = request_has_assembly(request).then(|| {
593            let mut components: std::collections::BTreeMap<String, ComponentSnapshot> =
594                std::collections::BTreeMap::new();
595            for feature in &result.results {
596                for removed in &feature.removed {
597                    components.remove(removed);
598                }
599                for record in &feature.components {
600                    components.insert(record.id.clone(), ComponentSnapshot::from(record));
601                }
602            }
603            // A record's pose is captured when its ACOMP EXECUTES, which is
604            // before the constraint tail solves — so a solved component's record
605            // still carries its authored placement. Re-pose from the same solver
606            // write-back the document adopts, or the projection (the structure
607            // tree, the BOM, the structured STEP writer, the component vertex
608            // ref) would lag the solve by a run.
609            for (id, pose) in &assembly_poses {
610                if let Some(component) = components.get_mut(id) {
611                    component.transform = pose_params_to_transform(pose);
612                }
613            }
614            let parse = |json: String| {
615                serde_json::from_str::<serde_json::Value>(&json).unwrap_or(serde_json::Value::Null)
616            };
617            AssemblySync {
618                components: components.into_values().collect(),
619                state: parse(brep_kernel::assembly_state_json()),
620                statuses: parse(brep_kernel::assembly_statuses_json()),
621                dof: dof.clone(),
622                overlay: parse(brep_kernel::assembly_overlay_json()),
623                parts_library: (brep_kernel::parts_library_revision() != library_revision_before)
624                    .then(brep_kernel::parts_library_map),
625            }
626        });
627        // The consumed-name union the committed-sketch refresh needs. Sorted, so
628        // the reply is byte-stable for a given run (the worker seam serializes it).
629        let consumed: Vec<String> = result
630            .results
631            .iter()
632            .flat_map(|feature| feature.removed.iter().cloned())
633            .collect::<std::collections::BTreeSet<String>>()
634            .into_iter()
635            .collect();
636
637        // Display LOD: a finite, positive factor (garbage from a hand-edited saved
638        // file → the "Normal" 1.0, since chord = extent·1.5e-3·lod and a 0/NaN lod
639        // would zero the tolerance → runaway refinement). A change since the last
640        // run means every resident mesh must re-tessellate at the new chord even
641        // though its handle is unchanged, so drop the reuse baseline.
642        let lod = if request.display_lod.is_finite() && request.display_lod > 0.0 {
643            request.display_lod
644        } else {
645            1.0
646        };
647        if lod != self.last_lod {
648            self.last_sent.clear();
649            self.last_lod = lod;
650        }
651
652        let mut snapshot: Vec<(String, u32, Option<SolidDisplay>)> =
653            Vec::with_capacity(layout.order.len());
654        let mut next_sent: HashMap<String, u32> = HashMap::with_capacity(layout.order.len());
655
656        for name in &layout.order {
657            let handle = layout.handles[name];
658            if self.last_sent.get(name) == Some(&handle) {
659                // Handle unchanged since last emit ⇒ same resident geometry ⇒ the
660                // applier keeps its existing display. This is EXACTLY the old
661                // `reused && source_handle == handle` fast path (monotonic handles):
662                // the canary below verifies the implication holds.
663                debug_assert!(
664                    layout.reused.contains(name),
665                    "handle unchanged must imply reused (monotonic handles): {name}"
666                );
667                snapshot.push((name.clone(), handle, None));
668                next_sent.insert(name.clone(), handle);
669                continue;
670            }
671            match display_payload_handle_native(handle, lod) {
672                Ok(payload) => {
673                    let mut solid = solid_display_from_payload(name, payload);
674                    solid.source_handle = handle;
675                    // Runner thread → the SheetTree thread-local is warm here; stamp
676                    // the sheet-metal marker so the UI thread reads it off the scene
677                    // (never calling the thread-local from a cold UI thread).
678                    solid.is_sheet_metal = brep_kernel::is_sheet_metal_handle(handle);
679                    snapshot.push((name.clone(), handle, Some(solid)));
680                    next_sent.insert(name.clone(), handle);
681                }
682                // A tessellation failure skips the solid (non-fatal) and does NOT
683                // poison the baseline — dropping it lets a later successful run
684                // re-tessellate from scratch.
685                Err(error) => report.display_errors.push(format!("{name}: {error}")),
686            }
687        }
688
689        self.last_sent = next_sent;
690        // Eager provenance for the run's final resident solids (the applier stores
691        // this map main-side so per-frame provenance queries never re-run history).
692        let provenance: Vec<(String, String)> = layout
693            .creators
694            .iter()
695            .map(|(name, id)| (name.clone(), id.clone()))
696            .collect();
697        // Eager entity origin (face/edge NAME -> originating feature id) rides
698        // alongside, so face/edge provenance survives the off-thread seam too.
699        let entity_origin: Vec<(String, String)> = layout
700            .entity_origin
701            .iter()
702            .map(|(name, id)| (name.clone(), id.clone()))
703            .collect();
704        // Imported colours, read HERE for the thread-local reason above and
705        // filtered to this run's own entities: the solids it displays plus the
706        // faces/edges it named. The kernel store is never cleared between
707        // documents, so an unfiltered ship could hand the applier a colour that
708        // belongs to a model the user closed.
709        let imported_colors: Vec<(String, String)> = serde_json::from_str::<serde_json::Value>(
710            &brep_kernel::scene_metadata_colors_json(),
711        )
712        .ok()
713        .and_then(|value| value.as_object().cloned())
714        .map(|map| {
715            map.into_iter()
716                .filter(|(name, _)| {
717                    layout.handles.contains_key(name) || layout.entity_origin.contains_key(name)
718                })
719                .filter_map(|(name, hex)| hex.as_str().map(|hex| (name, hex.to_string())))
720                .collect()
721        })
722        .unwrap_or_default();
723
724        RunOutput {
725            snapshot,
726            report,
727            provenance,
728            entity_origin,
729            assembly_poses,
730            assembly_fixed,
731            moved_solids,
732            imported_colors,
733            consumed,
734            assembly,
735        }
736    }
737
738    /// The resident handle last EMITTED for `name` (the delta baseline), or `None`
739    /// if the runner has not emitted a solid of that name. The measurement-query
740    /// path resolves an object's owning-solid handle through this so the query runs
741    /// against the SAME resident geometry the last run displayed (on the runner's
742    /// own thread, whose registry is warm from that run).
743    pub fn handle_of(&self, name: &str) -> Option<u32> {
744        self.last_sent.get(name).copied()
745    }
746}
747
748impl Default for SceneRunner {
749    fn default() -> Self {
750        Self::new()
751    }
752}
753
754/// Execute the history and reconcile `scene` in place (R10 incremental update):
755/// reused solids already present keep their [`SolidDisplay`] verbatim (stable
756/// `revision` ⇒ the renderer reuses their GPU buffers); everything else is
757/// (re-)tessellated from the resident handle; departed solids are dropped.
758///
759/// Implemented on the M1 seam: a throwaway [`SceneRunner`] primed from the
760/// CURRENT scene (`name → source_handle` of what is displayed) reproduces the
761/// pre-seam reuse in a single synchronous call, and its [`RunOutput`] delta is
762/// applied back to `scene` by MOVING existing displays out (via
763/// [`RenderScene::drain`]) so a reused solid's mesh is never cloned.
764pub fn update_scene_from_history(
765    scene: &mut RenderScene,
766    request: &HistoryRequest,
767) -> Result<SceneBuildReport, String> {
768    let mut runner = SceneRunner::new();
769    runner.last_sent = scene
770        .solids()
771        .iter()
772        .map(|solid| (solid.name.clone(), solid.source_handle))
773        .collect();
774    let output = runner.run(request);
775
776    // Move the current displays out, then reinsert in snapshot ORDER: a fresh
777    // entry replaces, an UNCHANGED entry reuses the moved-out display (whose
778    // `source_handle` equals the run's handle — guaranteed by the reuse
779    // invariant). Leftovers (departed names) are dropped.
780    let mut kept: HashMap<String, SolidDisplay> = scene
781        .drain()
782        .into_iter()
783        .map(|solid| (solid.name.clone(), solid))
784        .collect();
785    for (name, _handle, maybe) in output.snapshot {
786        match maybe {
787            Some(display) => scene.insert_solid(display),
788            None => scene.insert_solid(
789                kept.remove(&name).expect("keep target present"),
790            ),
791        }
792    }
793    Ok(output.report)
794}
795
796/// Execute `request` and return the FINAL resident solids as `(name, handle)` in
797/// display order — the export lane (STEP/STL) needs the current solids' resident
798/// handles, which the scene build does not itself retain. Run right after a scene
799/// build (warm incremental cache) this replays the cached features, so the
800/// handles it returns are the very ones the displayed scene was built from; run
801/// cold it re-executes and registers fresh (still-valid) handles. Either way the
802/// handles are live in the thread-local registry when this returns, ready to
803/// hand to `brep_kernel::export_step_handles`.
804pub fn resident_solid_handles(request: &HistoryRequest) -> Vec<(String, u32)> {
805    let _trace = crate::run_trace::span("export_resident_handles");
806    let result = execute_history(request);
807    let mut report = SceneBuildReport::default();
808    let layout = fold_history(&result, &mut report);
809    layout
810        .order
811        .iter()
812        .map(|name| (name.clone(), layout.handles[name]))
813        .collect()
814}
815