Skip to main content

brep_render/
scene.rs

1//! Renderer-independent display objects keyed by kernel feature names.
2//! Rendering, picking, and feature-reference display share this scene map.
3
4use crate::camera::Aabb;
5use std::cell::RefCell;
6use std::collections::HashMap;
7
8/// The kind of a display face (surface classification rides along when known —
9/// typed replacement for the previous app's untyped `faceKind` tag).
10#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
11pub enum FaceKind {
12    Unknown,
13    /// The cap a PMI section view draws over a cut (`pmi_section`): display
14    /// only, no kernel face — it carries the section colour and is picked as
15    /// its solid.
16    SectionCap,
17}
18
19/// One face of a solid: a contiguous triangle range of the solid mesh plus the
20/// kernel face identity.
21#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
22pub struct FaceDisplay {
23    /// Kernel face name (byte-exact pipeline name); empty when unnamed.
24    pub name: String,
25    /// Kernel topology face id.
26    pub topo_id: u64,
27    /// First triangle (not index) of this face in the mesh.
28    pub tri_start: u32,
29    /// Triangle count.
30    pub tri_count: u32,
31    pub kind: FaceKind,
32    /// Per-FACE base colour, resolved from this face's `color` metadata
33    /// attribute by [`RenderScene::apply_metadata_colors`]. Takes precedence
34    /// over the owning solid's colour (and over `faceColorMode`), but selection
35    /// / hover emphasis still wins over it. `None` = inherit the solid.
36    #[serde(default)]
37    pub color_override: Option<[f32; 3]>,
38    /// Per-FACE opacity (0 clear .. 1 opaque), resolved from this face's
39    /// `transparency` metadata attribute by
40    /// [`RenderScene::apply_metadata_opacity`]. `None` = inherit the solid.
41    #[serde(default)]
42    pub opacity: Option<f32>,
43}
44
45/// One display edge: a world-space polyline plus the kernel edge identity and
46/// the typed flags the previous display layer kept per object.
47#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
48pub struct EdgeDisplay {
49    /// Kernel edge name (`faceA|faceB[n]` convention); empty when unnamed.
50    pub name: String,
51    /// Kernel topology edge id.
52    pub topo_id: u64,
53    /// World-space polyline (chord-tolerance sampled, ≥ 2 points).
54    pub polyline: Vec<[f32; 3]>,
55    /// Auxiliary display edge (not a real BREP boundary): drawn, but never
56    /// picked, listed or named — a board's copper outline is one.
57    pub aux: bool,
58    /// Centerline flag (hole/revolve axis display).
59    pub centerline: bool,
60    /// This edge's own colour (linear sRGB), from its `color` metadata
61    /// attribute; `None` draws it in the theme's edge colour.
62    #[serde(default)]
63    pub color_override: Option<[f32; 3]>,
64    /// This edge's own opacity (0 clear .. 1 opaque), from its `transparency`
65    /// metadata attribute; `None` draws it opaque.
66    #[serde(default)]
67    pub opacity: Option<f32>,
68}
69
70impl EdgeDisplay {
71    /// Whether this edge draws in a style of its own rather than the theme's.
72    pub fn is_styled(&self) -> bool {
73        self.color_override.is_some() || self.opacity.is_some_and(|o| o < 1.0)
74    }
75}
76
77/// One display vertex (kernel topology vertex).
78#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
79pub struct VertexDisplay {
80    pub topo_id: u64,
81    pub position: [f64; 3],
82}
83
84/// The triangle mesh of one solid, ready for GPU upload (f32; the kernel's f64
85/// buffers are narrowed exactly once, here).
86#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
87pub struct DisplayMesh {
88    /// Interleaved-ready parallel arrays: xyz per vertex.
89    pub positions: Vec<[f32; 3]>,
90    pub normals: Vec<[f32; 3]>,
91    /// Triangle indices (3 per triangle).
92    pub indices: Vec<u32>,
93    /// Per-TRIANGLE face index into `SolidDisplay::faces`.
94    pub face_ids: Vec<u32>,
95}
96
97/// A displayed solid: mesh + named faces/edges/vertices + visibility.
98#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
99pub struct SolidDisplay {
100    /// Kernel solid name — the scene key.
101    pub name: String,
102    /// The resident kernel handle this display was tessellated from (0 = none,
103    /// e.g. a synthesized sheet with no kernel solid). Handles are monotonic and
104    /// never recycled, so this is a stable identity for the geometry: the R10
105    /// display-reuse fast path keeps an existing display across a history rerun
106    /// ONLY when the name's resident handle still equals this — a name re-bound to
107    /// a DIFFERENT handle (a SUBTRACT result inherits its target's name; a
108    /// roll-back replays that name's ORIGINAL producer) must re-tessellate.
109    pub source_handle: u32,
110    pub visible: bool,
111    /// Optional per-solid base color override (R14 — user-set solid color),
112    /// else the name-hashed stable color is used.
113    pub color_override: Option<[f32; 3]>,
114    /// Display-only opacity (0 clear .. 1 opaque; `None` = opaque): a motion
115    /// study's transparency clip. A translucent solid draws after every opaque
116    /// one through the blended pass, with its base colour's alpha set to this.
117    pub opacity: Option<f32>,
118    /// The solid's own opacity (0 clear .. 1 opaque; `None` = opaque),
119    /// resolved from its `transparency` metadata attribute by
120    /// [`RenderScene::apply_metadata_opacity`]. Kept apart from
121    /// [`Self::opacity`] so a motion study's clip, which writes that field and
122    /// gives it back afterwards, never has to know about it; the clip wins
123    /// while it is set.
124    #[serde(default)]
125    pub model_opacity: Option<f32>,
126    /// Monotonic content revision (R10). Every freshly built display gets a
127    /// unique value, so the renderer's GPU-buffer cache re-uploads on any
128    /// rebuild — correct-by-default (equivalent to teardown-rebuild). The
129    /// reused-buffer fast path (keep a revision stable across a `reused`
130    /// pipeline result) is a follow-up optimization.
131    pub revision: u64,
132    /// Nonzero: this display is the solid of revision `shape_revision`, MOVED
133    /// rigidly (the same mesh topology, faces, edges, vertices and styles; only
134    /// positions and normals differ). The renderer may then rewrite those in the
135    /// buffers it already holds instead of rebuilding them. Every other change
136    /// resets it to 0, so a stale value can never skip a rebuild.
137    #[serde(default)]
138    pub shape_revision: u64,
139    /// The affine (column-major 4×4) that takes the geometry of shape
140    /// `shape_revision` to this display's positions, when that is all that
141    /// moved it (an explode pose): the renderer then draws the buffers it holds
142    /// for the shape through it, writing a matrix instead of every vertex.
143    /// `None` for an unposed display, and for one moved any other way; every
144    /// change that resets `shape_revision` resets this.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub pose: Option<[f32; 16]>,
147    pub mesh: DisplayMesh,
148    pub faces: Vec<FaceDisplay>,
149    pub edges: Vec<EdgeDisplay>,
150    pub vertices: Vec<VertexDisplay>,
151    /// Per-entity + group hide state (individual faces/edges/vertices, or a
152    /// whole group). Default = everything visible; see [`crate::visibility`].
153    /// Reused solids keep it across history reruns (this whole struct is cloned
154    /// forward); a re-tessellated solid resets to all-visible.
155    pub visibility: crate::visibility::EntityVisibility,
156    /// World bbox over mesh positions (edges lie on the mesh by construction).
157    pub bbox: Aabb,
158    /// This display is a SYNTHESIZED committed-sketch SHEET (planar face + named
159    /// boundary edges + corner vertices), not a kernel solid — it carries no
160    /// resident handle (`source_handle == 0`). The marker lets the UI treat a
161    /// sketch as a sketch: it is listed under "Sketches" (not among solids) yet is
162    /// pickable / selectable / measurable like any scene solid.
163    pub is_sketch: bool,
164    /// This body is SHEET METAL — its resident handle carried a `SheetTree` when
165    /// the display was built. Stamped by the pipeline from
166    /// [`brep_kernel::is_sheet_metal_handle`] on the RUNNER thread (where the
167    /// tree's thread-local is warm), so the UI thread can answer "is this a
168    /// sheet-metal body?" straight off the scene — the gate for the sheet-metal
169    /// edit features (SM Flange / Fillet / Chamfer). Immutable-correct: a tree is
170    /// attached at solid creation and dropped exactly when the handle is freed,
171    /// handles never recycle, and the display-reuse fast path clones this struct
172    /// forward only while the handle is unchanged.
173    pub is_sheet_metal: bool,
174    /// The colour this display's edges take when the metadata store names none
175    /// for them (`None`: the theme's edge colour). Set on a synthesized display
176    /// whose edges ARE the message — a refused Sew to Solid's open edges — so
177    /// [`RenderScene::apply_metadata_edge_looks`] keeps them highlighted.
178    #[serde(default)]
179    pub edge_color_base: Option<[f32; 3]>,
180}
181
182/// Source of monotonic [`SolidDisplay::revision`] values.
183pub(crate) fn next_revision() -> u64 {
184    use std::sync::atomic::{AtomicU64, Ordering};
185    static COUNTER: AtomicU64 = AtomicU64::new(1);
186    COUNTER.fetch_add(1, Ordering::Relaxed)
187}
188
189/// The scene: insertion-ordered solids + an exact name index (R8 — the
190/// `getObjectByName` heuristic-scoring lookup is replaced by this map).
191#[derive(Debug, Default)]
192pub struct RenderScene {
193    solids: Vec<SolidDisplay>,
194    index: HashMap<String, usize>,
195    /// Triangle BVHs for dense displays, built once on first pick. Scene
196    /// mutations invalidate these independently of camera and visibility.
197    pick_trees: RefCell<HashMap<String, brep_kernel::Bvh>>,
198    /// The B-rep of the kernel displays a drawing sheet has ASKED for, keyed by
199    /// solid name with the resident handle it came from: `name -> (handle,
200    /// fingerprint, solid)`. Only a sheet reads topology, and the runner sends
201    /// it only when asked (`EngineState::request_exact_solids`), so a document
202    /// with no sheet holds none. Beside the displays rather than inside them,
203    /// because a display is cloned (the PMI explode keeps originals) and
204    /// rebuilt on the UI thread (committed sketches), and neither wants a copy
205    /// of the topology. Read through [`Self::exact_solid`], which answers only
206    /// while the handle still matches the display's. The `u64` is the solid's
207    /// [`brep_fingerprint`], taken once here rather than per projection.
208    exact: HashMap<String, (u32, u64, brep_kernel::BrepSolid)>,
209    /// Bumped whenever [`Self::exact`] gains or loses a solid, so a projection
210    /// cached without a topology is redrawn when it arrives.
211    exact_revision: u64,
212    /// Bumped whenever [`Self::set_visible`] actually CHANGES a solid's
213    /// visibility — see [`Self::visibility_revision`].
214    visibility_revision: u64,
215    /// A Work part's CONTEXT scene only: the context faces drawn emphasised,
216    /// `(solid, face, selected)` (else hovered). Set by
217    /// `EngineState::sync_context_highlight`; the context render pass reads it.
218    pub highlight: Vec<(String, String, bool)>,
219    /// A Work part's CONTEXT scene only: its colour and opacity (`None`: the
220    /// default [`crate::render::WORK_PART_CONTEXT_RGBA`]). Set by
221    /// `EngineState::set_context_display`; the context render pass reads it.
222    pub tint: Option<[f32; 4]>,
223    /// Draw the scene as a Line art instructions step (set by the engine
224    /// while such a step is shown): a light grey ground, flat unlit fills,
225    /// the parts in `placed` white with grey lines, every other part flat
226    /// blue with black lines, and each part outlined.
227    pub line_art: Option<LineArtLook>,
228}
229
230/// What [`RenderScene::line_art`] needs: which solids earlier steps placed.
231#[derive(Debug, Clone, Default, PartialEq)]
232pub struct LineArtLook {
233    pub placed: std::collections::HashSet<String>,
234}
235
236impl SolidDisplay {
237    /// The opacity the solid's own faces draw at (0 clear .. 1 opaque): a
238    /// motion study's clip while one is set, else the `transparency`
239    /// attribute, else opaque.
240    pub fn base_opacity(&self) -> f32 {
241        self.opacity.or(self.model_opacity).unwrap_or(1.0).clamp(0.0, 1.0)
242    }
243
244    /// The opacity `face` draws at: a clip fades the whole solid, else the
245    /// face's own `transparency` attribute, else the solid's.
246    pub fn face_opacity(&self, face: &FaceDisplay) -> f32 {
247        match self.opacity {
248            Some(clip) => clip,
249            None => face.opacity.or(self.model_opacity).unwrap_or(1.0),
250        }
251        .clamp(0.0, 1.0)
252    }
253}
254
255impl RenderScene {
256    pub fn new() -> Self {
257        Self::default()
258    }
259
260    /// Insert or replace a solid by name (replacement keeps insertion order —
261    /// a boolean result reusing its target's name stays in place).
262    pub fn insert_solid(&mut self, solid: SolidDisplay) {
263        self.pick_trees.get_mut().remove(&solid.name);
264        match self.index.get(&solid.name) {
265            Some(&slot) => self.solids[slot] = solid,
266            None => {
267                self.index.insert(solid.name.clone(), self.solids.len());
268                self.solids.push(solid);
269            }
270        }
271    }
272
273    /// Drop every solid (the scene rebuild path clears then repopulates).
274    pub fn clear(&mut self) {
275        self.pick_trees.get_mut().clear();
276        self.solids.clear();
277        self.index.clear();
278        self.highlight.clear();
279    }
280
281    /// Empty the scene, RETURNING every solid by value (the name index is cleared
282    /// and the vec is `mem::take`-n out). The history-apply seam MOVES existing
283    /// displays out this way to reinsert the reused ones without cloning their
284    /// meshes — a scene-free [`crate::pipeline::SceneRunner`] delta is applied by
285    /// draining then reinserting in snapshot order.
286    pub fn drain(&mut self) -> Vec<SolidDisplay> {
287        self.pick_trees.get_mut().clear();
288        self.index.clear();
289        std::mem::take(&mut self.solids)
290    }
291
292    /// Set (or clear) a solid's metadata color override, bumping its revision
293    /// so the renderer re-derives the base style. Returns false if unknown.
294    pub fn set_color_override(&mut self, name: &str, color: Option<[f32; 3]>) -> bool {
295        let Some(slot) = self.index.get(name).copied() else {
296            return false;
297        };
298        let solid = &mut self.solids[slot];
299        if solid.color_override != color {
300            solid.color_override = color;
301            solid.revision = next_revision();
302            solid.shape_revision = 0;
303            solid.pose = None;
304        }
305        true
306    }
307
308    /// Set the per-FACE colour overrides of solid `name`, face `i` taking
309    /// `colors[i]` (faces past the slice are left alone), bumping the solid's
310    /// revision only when one changed. Returns false if the solid is unknown.
311    /// A display-only body (the mesh import's region view) colours its faces
312    /// through this.
313    pub fn set_face_colors(&mut self, name: &str, colors: &[Option<[f32; 3]>]) -> bool {
314        let Some(slot) = self.index.get(name).copied() else {
315            return false;
316        };
317        let solid = &mut self.solids[slot];
318        let mut changed = false;
319        for (face, &color) in solid.faces.iter_mut().zip(colors) {
320            if face.color_override != color {
321                face.color_override = color;
322                changed = true;
323            }
324        }
325        if changed {
326            solid.revision = next_revision();
327            solid.shape_revision = 0;
328            solid.pose = None;
329        }
330        true
331    }
332
333    /// Re-derive every solid's and face's opacity from the name-keyed
334    /// metadata store: the seam through which the durable `transparency`
335    /// attribute reaches the display, as [`Self::apply_metadata_colors`] is
336    /// for `color`.
337    ///
338    /// `lookup` maps an object NAME (a solid's or a face's) to its opacity
339    /// (0 clear .. 1 opaque), `None` for "nothing recorded". A solid that
340    /// resolves fully opaque stores `None`; a face keeps an explicit 1, which
341    /// is how one face of a see-through body is made opaque again. A section
342    /// cap inherits its solid.
343    ///
344    /// A changed solid's `revision` is bumped, and only then: the same no-op
345    /// guarantee the colour pass gives, for the same reason.
346    pub fn apply_metadata_opacity(&mut self, lookup: impl Fn(&str) -> Option<f32>) -> bool {
347        let mut any = false;
348        for solid in &mut self.solids {
349            let mut changed = false;
350            let want = lookup(&solid.name).map(|o| o.clamp(0.0, 1.0)).filter(|o| *o < 1.0);
351            if solid.model_opacity != want {
352                solid.model_opacity = want;
353                changed = true;
354            }
355            for face in &mut solid.faces {
356                let want = if face.name.is_empty() || face.kind == FaceKind::SectionCap {
357                    None
358                } else {
359                    lookup(&face.name).map(|o| o.clamp(0.0, 1.0))
360                };
361                if face.opacity != want {
362                    face.opacity = want;
363                    changed = true;
364                }
365            }
366            if changed {
367                solid.revision = next_revision();
368                solid.shape_revision = 0;
369                solid.pose = None;
370                any = true;
371            }
372        }
373        any
374    }
375
376    /// Re-derive every EDGE's own colour and opacity from the metadata store,
377    /// by the edge's own name. Its own lookups, not the solids' and faces':
378    /// an edge never inherits its solid's or its faces' look, and no derived
379    /// default (a board body's colour) may read an edge name as a face's.
380    /// Unnamed and display-only (aux) edges carry none. Returns whether
381    /// anything changed; bumps a changed solid's revision.
382    pub fn apply_metadata_edge_looks(
383        &mut self,
384        color: impl Fn(&str) -> Option<[f32; 3]>,
385        opacity: impl Fn(&str) -> Option<f32>,
386    ) -> bool {
387        let mut any = false;
388        for solid in &mut self.solids {
389            let mut changed = false;
390            let base = solid.edge_color_base;
391            for edge in &mut solid.edges {
392                let (want_color, want_opacity) = if edge.name.is_empty() || edge.aux {
393                    (base, None)
394                } else {
395                    (color(&edge.name).or(base), opacity(&edge.name).map(|o| o.clamp(0.0, 1.0)).filter(|o| *o < 1.0))
396                };
397                if edge.color_override != want_color || edge.opacity != want_opacity {
398                    edge.color_override = want_color;
399                    edge.opacity = want_opacity;
400                    changed = true;
401                }
402            }
403            if changed {
404                solid.revision = next_revision();
405                solid.shape_revision = 0;
406                solid.pose = None;
407                any = true;
408            }
409        }
410        any
411    }
412
413    /// Re-derive every solid's and face's base colour from the name-keyed
414    /// metadata store — the ONE seam through which the durable `color`
415    /// attribute reaches the display.
416    ///
417    /// `lookup` maps an object NAME (a solid's or a face's) to its resolved
418    /// colour. It returns `None` both for "no colour recorded" and for "the
419    /// display setting is overriding model colours", so this method needs to
420    /// know about neither.
421    ///
422    /// A SKETCH sheet's own `color_override` is the synthesized
423    /// `crate::engine_state::SKETCH_SHEET_COLOR`, not a metadata colour, and
424    /// re-deriving it from a store that has no record for the sheet would blank
425    /// it back to the global face colour — so it is left alone. The sketch's
426    /// `color` attribute (keyed by the sketch id, which is the sheet's name)
427    /// lands on the sheet's FACES instead: a face override wins over the
428    /// solid's colour, and clearing the attribute clears the face overrides,
429    /// which restores the synthesized sheet colour underneath.
430    ///
431    /// A changed solid's `revision` is bumped so the renderer re-uploads it —
432    /// and ONLY when something actually changed. That no-op guarantee is
433    /// load-bearing, not a nicety: this runs after EVERY history apply, and the
434    /// R10 GPU-buffer reuse fast path keys off a stable revision.
435    pub fn apply_metadata_colors(&mut self, lookup: impl Fn(&str) -> Option<[f32; 3]>) -> bool {
436        let mut any = false;
437        for solid in &mut self.solids {
438            let mut changed = false;
439            // A sketch sheet keeps its synthesized base colour; its metadata
440            // colour reaches the display through the faces below.
441            let sheet_color = if solid.is_sketch {
442                lookup(&solid.name)
443            } else {
444                let want = lookup(&solid.name);
445                if solid.color_override != want {
446                    solid.color_override = want;
447                    changed = true;
448                }
449                None
450            };
451            for face in &mut solid.faces {
452                // A section cap keeps the section colour its view gave it.
453                if face.kind == FaceKind::SectionCap {
454                    continue;
455                }
456                // An unnamed face can carry no metadata record, so it always
457                // inherits the solid rather than costing a store lookup.
458                let want = if face.name.is_empty() {
459                    None
460                } else {
461                    lookup(&face.name)
462                }
463                .or(sheet_color);
464                if face.color_override != want {
465                    face.color_override = want;
466                    changed = true;
467                }
468            }
469            if changed {
470                solid.revision = next_revision();
471                solid.shape_revision = 0;
472                solid.pose = None;
473                any = true;
474            }
475        }
476        any
477    }
478
479    /// Set a solid's visibility (R11). Returns false if unknown.
480    pub fn set_visible(&mut self, name: &str, visible: bool) -> bool {
481        let Some(solid) = self.solid_mut(name) else {
482            return false;
483        };
484        let changed = solid.visible != visible;
485        solid.visible = visible;
486        if changed {
487            self.visibility_revision = self.visibility_revision.wrapping_add(1);
488        }
489        true
490    }
491
492    /// Monotonic counter of VISIBILITY changes — the cache key for anything
493    /// derived from which bodies are shown.
494    ///
495    /// Hiding a body is SESSION state: it writes no history, runs nothing, and
496    /// lands no exact solid, so it moves none of the counters a derived
497    /// drawing would otherwise key on. A drawing sheet draws "the solids
498    /// visible in the scene" (`sheets::project::sheet_solid_names`), so its
499    /// cached projection depends on this and nothing else could tell it.
500    ///
501    /// Only a REAL change counts. `EngineState::apply_view_display` sets every
502    /// solid's visibility from the active PMI view's hidden set on every
503    /// activation, and almost all of those calls are no-ops; counting them
504    /// would re-project the open sheet for nothing.
505    pub fn visibility_revision(&self) -> u64 {
506        self.visibility_revision
507    }
508
509    /// Scene enumeration for the host scene-tree panel (R11): names, kind,
510    /// visibility, child face/edge/vertex counts — as JSON.
511    pub fn listing_json(&self) -> String {
512        let solids: Vec<serde_json::Value> = self
513            .solids
514            .iter()
515            .map(|solid| {
516                serde_json::json!({
517                    "name": solid.name,
518                    "kind": "SOLID",
519                    "visible": solid.visible,
520                    "faces": solid.faces.len(),
521                    "edges": solid.edges.iter().filter(|e| !e.aux).count(),
522                    "vertices": solid.vertices.len(),
523                })
524            })
525            .collect();
526        serde_json::Value::Array(solids).to_string()
527    }
528
529    /// Remove a solid by exact name.
530    pub fn remove_solid(&mut self, name: &str) -> bool {
531        let Some(slot) = self.index.remove(name) else {
532            return false;
533        };
534        self.solids.remove(slot);
535        self.pick_trees.get_mut().remove(name);
536        for value in self.index.values_mut() {
537            if *value > slot {
538                *value -= 1;
539            }
540        }
541        true
542    }
543
544    pub fn solid(&self, name: &str) -> Option<&SolidDisplay> {
545        self.index.get(name).map(|&slot| &self.solids[slot])
546    }
547
548    /// Drop every kept B-rep whose display is gone or now comes from a
549    /// different handle. Called after a run's displays are reconciled, so "the
550    /// display's handle" is that run's.
551    pub fn prune_exact_solids(&mut self) {
552        let (solids, index) = (&self.solids, &self.index);
553        let before = self.exact.len();
554        self.exact.retain(|name, (handle, _, _)| {
555            index.get(name).is_some_and(|&slot| solids[slot].source_handle == *handle)
556        });
557        if self.exact.len() != before {
558            self.exact_revision += 1;
559        }
560    }
561
562    /// Record the B-rep the runner sent for `name`, when `handle` is still the
563    /// one its display was tessellated from; `false` (and nothing kept) when
564    /// the display has moved on since the request went out.
565    pub fn set_exact_solid(&mut self, name: &str, handle: u32, solid: brep_kernel::BrepSolid) -> bool {
566        if handle == 0 || self.solid(name).map(|display| display.source_handle) != Some(handle) {
567            return false;
568        }
569        self.exact.insert(name.to_string(), (handle, brep_fingerprint(&solid), solid));
570        self.exact_revision += 1;
571        true
572    }
573
574    /// Forget the B-rep of `name`: its geometry changed under the SAME handle
575    /// (an assembly solve re-poses a resident solid in place), so the next
576    /// projection must ask again.
577    pub fn drop_exact_solid(&mut self, name: &str) {
578        if self.exact.remove(name).is_some() {
579            self.exact_revision += 1;
580        }
581    }
582
583    /// Forget every B-rep: the handles they were keyed by belong to a runner
584    /// that is gone (a cancel restarts its registry, which counts from one
585    /// again) or to a document that was replaced.
586    pub fn clear_exact_solids(&mut self) {
587        if !self.exact.is_empty() {
588            self.exact.clear();
589            self.exact_revision += 1;
590        }
591    }
592
593    /// See `Self::exact`'s revision counter.
594    pub fn exact_revision(&self) -> u64 {
595        self.exact_revision
596    }
597
598    /// The B-rep the displayed solid `name` was tessellated from, or `None`
599    /// when the scene holds none for its CURRENT handle — a synthesized sketch
600    /// sheet, or a solid whose topology did not reach this thread.
601    pub fn exact_solid(&self, name: &str) -> Option<&brep_kernel::BrepSolid> {
602        self.exact_solid_fingerprinted(name).map(|(solid, _)| solid)
603    }
604
605    /// [`Self::exact_solid`] with its content fingerprint.
606    pub fn exact_solid_fingerprinted(&self, name: &str) -> Option<(&brep_kernel::BrepSolid, u64)> {
607        let display = self.solid(name)?;
608        self.exact
609            .get(name)
610            .filter(|(handle, _, _)| *handle == display.source_handle && *handle != 0)
611            .map(|(_, fingerprint, solid)| (solid, *fingerprint))
612    }
613
614    pub fn solid_mut(&mut self, name: &str) -> Option<&mut SolidDisplay> {
615        let slot = *self.index.get(name)?;
616        // A caller can edit positions, indices or face ranges through this
617        // reference without changing the display revision.
618        self.pick_trees.get_mut().remove(name);
619        Some(&mut self.solids[slot])
620    }
621
622    pub(crate) fn pick_triangles(&self, solid: &SolidDisplay, ray: &crate::view::Ray, out: &mut Vec<usize>) {
623        let mut trees = self.pick_trees.borrow_mut();
624        let tree = trees.entry(solid.name.clone()).or_insert_with(|| {
625            let boxes: Vec<_> = solid.mesh.indices.chunks_exact(3).map(|indices| {
626                let mut bounds = brep_kernel::Aabb::empty();
627                for &index in indices {
628                    let p = solid.mesh.positions[index as usize];
629                    bounds.include_point(brep_kernel::Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64));
630                }
631                bounds
632            }).collect();
633            brep_kernel::Bvh::build(&boxes)
634        });
635        let v = |p: [f64; 3]| brep_kernel::Vec3::new(p[0], p[1], p[2]);
636        tree.intersecting_ray(v(ray.origin), v(ray.dir), 1e-9, out);
637        // Preserve face/triangle traversal order, including tied hits.
638        out.sort_unstable();
639    }
640
641    /// Insertion-ordered iteration (deterministic — drives draw order).
642    pub fn solids(&self) -> &[SolidDisplay] {
643        &self.solids
644    }
645
646    /// The world-space polyline of the first display edge named `name` across all
647    /// solids (widened to `f64`), or `None` when no edge carries that exact name.
648    /// The engine-native sketch pickEdges tool (S6b-2) uses this to fetch a picked
649    /// scene edge's geometry for projection into the sketch plane. There is no name
650    /// index for edges (only solids), so this is a linear scan — fine for the
651    /// interactive per-click use.
652    pub fn edge_polyline_world(&self, name: &str) -> Option<Vec<[f64; 3]>> {
653        for solid in &self.solids {
654            for edge in &solid.edges {
655                if edge.name == name {
656                    return Some(
657                        edge.polyline
658                            .iter()
659                            .map(|p| [p[0] as f64, p[1] as f64, p[2] as f64])
660                            .collect(),
661                    );
662                }
663            }
664        }
665        None
666    }
667
668    /// The name of the solid owning the first display edge named `name`, or `None`
669    /// (the companion of [`edge_polyline_world`](Self::edge_polyline_world) — the
670    /// pickEdges tool stores it as external-ref metadata).
671    pub fn edge_solid_name(&self, name: &str) -> Option<&str> {
672        for solid in &self.solids {
673            if solid.edges.iter().any(|edge| edge.name == name) {
674                return Some(&solid.name);
675            }
676        }
677        None
678    }
679
680    /// The world plane of the first display face named `name` across all solids,
681    /// as `(centroid, unit outward normal)`: the area-weighted centroid of the
682    /// face's mesh triangles and the normalized sum of their cross products. The
683    /// watertight tessellation winds every face's triangles by `same_sense`, so
684    /// the cross-product sum IS the outward normal (the stored per-vertex normals
685    /// are shading normals and can be blended at shared boundary vertices). This
686    /// is what lets an extrude/revolve whose `profile` is a resident solid FACE
687    /// (not a sketch) anchor its dimension gizmo — the engine's dimension refs
688    /// fall back to it (`EngineState::lookup_profile_plane`). Hidden solids count
689    /// too: a hidden source solid still anchors the gizmo. `None` when no face
690    /// carries that exact name, it has no triangles, or the triangles are
691    /// degenerate (zero area). Linear scan like [`edge_polyline_world`](Self::edge_polyline_world).
692    pub fn face_plane_world(&self, name: &str) -> Option<([f64; 3], [f64; 3])> {
693        for solid in &self.solids {
694            let Some(face) = solid.faces.iter().find(|face| face.name == name) else {
695                continue;
696            };
697            let positions = &solid.mesh.positions;
698            let indices = &solid.mesh.indices;
699            let start = face.tri_start as usize;
700            let end = (start + face.tri_count as usize).min(indices.len() / 3);
701            let mut weighted = [0.0f64; 3];
702            let mut normal = [0.0f64; 3];
703            let mut total_area = 0.0f64;
704            for tri in start..end {
705                let a = f64_point(positions[indices[tri * 3] as usize]);
706                let b = f64_point(positions[indices[tri * 3 + 1] as usize]);
707                let c = f64_point(positions[indices[tri * 3 + 2] as usize]);
708                let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
709                let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
710                // Twice the signed-area vector; its length is 2·area.
711                let cross = [
712                    ab[1] * ac[2] - ab[2] * ac[1],
713                    ab[2] * ac[0] - ab[0] * ac[2],
714                    ab[0] * ac[1] - ab[1] * ac[0],
715                ];
716                let area =
717                    0.5 * (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt();
718                for k in 0..3 {
719                    weighted[k] += area * (a[k] + b[k] + c[k]) / 3.0;
720                    normal[k] += cross[k];
721                }
722                total_area += area;
723            }
724            let normal_len =
725                (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]).sqrt();
726            if total_area <= 1e-18 || normal_len <= 1e-18 {
727                return None;
728            }
729            return Some((
730                [
731                    weighted[0] / total_area,
732                    weighted[1] / total_area,
733                    weighted[2] / total_area,
734                ],
735                [normal[0] / normal_len, normal[1] / normal_len, normal[2] / normal_len],
736            ));
737        }
738        None
739    }
740
741    /// Whether the display face named `name` is PLANAR: every one of its mesh
742    /// triangles' normals is parallel to the face's summed normal (within
743    /// `1e-4` in the sine). A cylinder, cone or freeform face fails this; a
744    /// face with no triangles is not planar either. Linear scan like
745    /// [`face_plane_world`](Self::face_plane_world) — the 3D sketch editor asks
746    /// this once per reference pick, never per frame.
747    pub fn face_is_planar(&self, name: &str) -> bool {
748        for solid in &self.solids {
749            let Some(face) = solid.faces.iter().find(|face| face.name == name) else {
750                continue;
751            };
752            let positions = &solid.mesh.positions;
753            let indices = &solid.mesh.indices;
754            let start = face.tri_start as usize;
755            let end = (start + face.tri_count as usize).min(indices.len() / 3);
756            if start >= end {
757                return false;
758            }
759            let cross_of = |tri: usize| -> [f64; 3] {
760                let a = f64_point(positions[indices[tri * 3] as usize]);
761                let b = f64_point(positions[indices[tri * 3 + 1] as usize]);
762                let c = f64_point(positions[indices[tri * 3 + 2] as usize]);
763                let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
764                let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
765                [
766                    ab[1] * ac[2] - ab[2] * ac[1],
767                    ab[2] * ac[0] - ab[0] * ac[2],
768                    ab[0] * ac[1] - ab[1] * ac[0],
769                ]
770            };
771            let mut sum = [0.0f64; 3];
772            for tri in start..end {
773                let n = cross_of(tri);
774                for k in 0..3 {
775                    sum[k] += n[k];
776                }
777            }
778            let sum_len = (sum[0] * sum[0] + sum[1] * sum[1] + sum[2] * sum[2]).sqrt();
779            if sum_len <= 1e-18 {
780                return false;
781            }
782            let unit = [sum[0] / sum_len, sum[1] / sum_len, sum[2] / sum_len];
783            for tri in start..end {
784                let n = cross_of(tri);
785                let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
786                if len <= 1e-18 {
787                    continue; // A sliver triangle says nothing about the plane.
788                }
789                let cross = [
790                    n[1] * unit[2] - n[2] * unit[1],
791                    n[2] * unit[0] - n[0] * unit[2],
792                    n[0] * unit[1] - n[1] * unit[0],
793                ];
794                let sine = (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() / len;
795                if sine > 1e-4 {
796                    return false;
797                }
798            }
799            return true;
800        }
801        false
802    }
803
804    pub fn is_empty(&self) -> bool {
805        self.solids.is_empty()
806    }
807
808    /// World bbox over every VISIBLE solid.
809    pub fn bbox(&self) -> Aabb {
810        let mut bbox = Aabb::empty();
811        for solid in &self.solids {
812            if solid.visible {
813                bbox.union(&solid.bbox);
814            }
815        }
816        bbox
817    }
818}
819
820/// A hash of everything in a B-rep the drawing sheet's hidden-line pass reads: every vertex,
821/// curve, carrier and pcurve number to the bit, and the topology that ties
822/// them together.
823pub fn brep_fingerprint(solid: &brep_kernel::BrepSolid) -> u64 {
824    use std::hash::{Hash, Hasher};
825    let mut hasher = std::collections::hash_map::DefaultHasher::new();
826    let mut numbers = |values: &mut dyn Iterator<Item = f64>| {
827        for value in values {
828            value.to_bits().hash(&mut hasher);
829        }
830    };
831    let curve = |curve: &brep_kernel::NurbsCurve| -> Vec<f64> {
832        let mut out = vec![curve.degree as f64];
833        out.extend(curve.knots.iter().copied());
834        out.extend(curve.control_points.iter().flat_map(|cp| [cp.x, cp.y, cp.z, cp.w]));
835        out
836    };
837    for vertex in &solid.vertices {
838        numbers(&mut [vertex.id as f64, vertex.point.x, vertex.point.y, vertex.point.z].into_iter());
839    }
840    for edge in &solid.edges {
841        numbers(&mut [edge.id as f64, edge.t0, edge.t1, edge.start_vertex_id as f64, edge.end_vertex_id as f64].into_iter());
842        numbers(&mut [edge.degenerate as u8 as f64].into_iter());
843        numbers(&mut curve(&edge.curve).into_iter());
844    }
845    for shell in &solid.shells {
846        for face in &shell.faces {
847            let surface = &face.surface;
848            numbers(&mut [face.same_sense as u8 as f64, surface.degree_u as f64, surface.degree_v as f64].into_iter());
849            numbers(&mut surface.knots_u.iter().chain(&surface.knots_v).copied());
850            numbers(&mut surface.control_points.iter().flatten().flat_map(|cp| [cp.x, cp.y, cp.z, cp.w]));
851            for lp in &face.loops {
852                numbers(&mut [f64::NAN].into_iter());
853                for coedge in &lp.coedges {
854                    numbers(&mut [coedge.edge_id as f64, coedge.forward as u8 as f64].into_iter());
855                    numbers(&mut curve(&coedge.pcurve).into_iter());
856                }
857            }
858        }
859    }
860    hasher.finish()
861}
862
863/// Widen a display-mesh vertex to `f64` (the mesh stores `f32`).
864fn f64_point(p: [f32; 3]) -> [f64; 3] {
865    [p[0] as f64, p[1] as f64, p[2] as f64]
866}
867
868/// Build a [`SolidDisplay`] from the kernel's native display payload.
869pub fn solid_display_from_payload(
870    name: &str,
871    payload: brep_kernel::DisplaySolidPayload,
872) -> SolidDisplay {
873    let mesh_in = payload.mesh;
874    let vertex_count = mesh_in.positions.len() / 3;
875    let mut positions = Vec::with_capacity(vertex_count);
876    let mut normals = Vec::with_capacity(vertex_count);
877    let mut bbox = Aabb::empty();
878    for i in 0..vertex_count {
879        let p = [
880            mesh_in.positions[i * 3],
881            mesh_in.positions[i * 3 + 1],
882            mesh_in.positions[i * 3 + 2],
883        ];
884        bbox.expand(p);
885        positions.push([p[0] as f32, p[1] as f32, p[2] as f32]);
886        normals.push([
887            mesh_in.normals[i * 3] as f32,
888            mesh_in.normals[i * 3 + 1] as f32,
889            mesh_in.normals[i * 3 + 2] as f32,
890        ]);
891    }
892
893    // Face ranges: the watertight mesh emits each face's triangles as one
894    // contiguous run of `face_ids`. Group runs; a face with no triangles gets
895    // an empty range.
896    let mut faces: Vec<FaceDisplay> = payload
897        .faces
898        .iter()
899        .map(|(topo_id, name)| FaceDisplay {
900            name: name.clone().unwrap_or_default(),
901            topo_id: *topo_id,
902            tri_start: 0,
903            tri_count: 0,
904            kind: FaceKind::Unknown,
905            color_override: None,
906            opacity: None,
907        })
908        .collect();
909    let mut run_start = 0u32;
910    let mut run_face: Option<u32> = None;
911    for (tri, &face_id) in mesh_in.face_ids.iter().enumerate() {
912        if run_face != Some(face_id) {
913            run_face = Some(face_id);
914            run_start = tri as u32;
915        }
916        if let Some(face) = faces.get_mut(face_id as usize) {
917            if face.tri_count == 0 {
918                face.tri_start = run_start;
919            }
920            face.tri_count += 1;
921        }
922    }
923
924    // Edges and vertices expand the bbox too. For a real solid they lie ON the
925    // meshed boundary, so this changes nothing; for a synthesized OPEN-sketch
926    // display (edges + endpoints, no face) they are the ONLY extent there is, and
927    // an empty bbox would leave the sketch out of zoom-to-fit and out of every
928    // bbox-gated traversal.
929    for (_, _, points) in &payload.edges {
930        for point in points {
931            bbox.expand([point.x, point.y, point.z]);
932        }
933    }
934    for (_, point) in &payload.vertices {
935        bbox.expand([point.x, point.y, point.z]);
936    }
937
938    let edges = payload
939        .edges
940        .into_iter()
941        .map(|(topo_id, name, points)| EdgeDisplay {
942            name: name.unwrap_or_default(),
943            topo_id,
944            polyline: points
945                .iter()
946                .map(|p| [p.x as f32, p.y as f32, p.z as f32])
947                .collect(),
948            aux: false,
949            centerline: false,
950            color_override: None,
951            opacity: None,
952        })
953        .collect();
954
955    let vertices = payload
956        .vertices
957        .into_iter()
958        .map(|(topo_id, p)| VertexDisplay {
959            topo_id,
960            position: [p.x, p.y, p.z],
961        })
962        .collect();
963
964    SolidDisplay {
965        name: name.to_string(),
966        source_handle: 0, // set by the caller that knows the resident handle
967        visible: true,
968        color_override: None,
969        opacity: None,
970        model_opacity: None,
971        revision: next_revision(),
972        shape_revision: 0,
973        pose: None,
974        mesh: DisplayMesh {
975            positions,
976            normals,
977            indices: mesh_in.indices,
978            face_ids: mesh_in.face_ids,
979        },
980        faces,
981        edges,
982        vertices,
983        visibility: crate::visibility::EntityVisibility::default(),
984        bbox,
985        is_sketch: false, // set by the sketch-sheet synthesizer for a committed sketch
986        edge_color_base: None,
987        is_sheet_metal: false, // stamped by the pipeline from the resident handle's SheetTree
988    }
989}