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