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