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