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