Skip to main content

brep_render/engine_state/
scene_query.rs

1use super::*;
2
3impl EngineState {
4    /// Ranked candidate list under CSS-pixel `(x, y)`, kernel names, priority
5    /// VERTEX > EDGE > FACE > … > SOLID.
6    ///
7    /// SCENE ONLY, deliberately: this R3-boundary accessor (and its
8    /// [`hover_json`](Self::hover_json) sibling) reports kernel-named GEOMETRY, and
9    /// its in-tree consumer is the sketch's external-edge picker, which wants
10    /// edges. The construction PLANE cards join the pick list one level up, in
11    /// [`pick_candidates_at`](Self::pick_candidates_at) — that is what the
12    /// selection paths and the app's pick-list popup consume.
13    pub fn pick_json(&self, x: f64, y: f64) -> String {
14        let candidates = pick::pick(&self.scene, &self.camera, x, y, &self.pick_options());
15        pick::candidates_to_json(&candidates)
16    }
17
18    /// The single best candidate under `(x, y)` (hover), or `null`.
19    pub fn hover_json(&self, x: f64, y: f64) -> String {
20        let candidates = pick::pick(&self.scene, &self.camera, x, y, &self.pick_options());
21        match candidates.first() {
22            Some(best) => pick::candidates_to_json(std::slice::from_ref(best))
23                .strip_prefix('[')
24                .and_then(|s| s.strip_suffix(']'))
25                .map(str::to_string)
26                .unwrap_or_else(|| "null".to_string()),
27            None => "null".to_string(),
28        }
29    }
30
31    // --- Settings / emphasis / visibility (R11/R14/R17) -------------------
32
33    pub fn apply_settings_json(&mut self, json: &str) -> Result<(), String> {
34        let prev_lod = self.settings.lod_factor;
35        let prev_override_model_colors = self.settings.override_model_colors;
36        self.settings.apply_json(json)?;
37        self.settings_generation = self.settings_generation.wrapping_add(1);
38        self.dirty = true;
39        // "Override model colors" is resolved when colours are derived, not when
40        // they are drawn, so flipping it has to re-derive. Guarded on an actual
41        // change: this apply path also runs on every unrelated settings edit.
42        if self.settings.override_model_colors != prev_override_model_colors {
43            self.sync_colors_from_metadata();
44        }
45        // Push the (possibly changed) ViewCube size into the widget so the rendered
46        // cube AND its hit-test rect track the setting. Always re-pushed (idempotent
47        // for an unchanged value) so this ONE choke point covers panel edits, boot
48        // restore, and Reset-to-defaults alike.
49        self.widgets.set_viewcube_size(self.settings.viewcube_size_px);
50        // Projection rides in the settings JSON as `orthographic` (see `settings_json`)
51        // so the toolbar toggle AND a reload both go through this ONE apply path — the
52        // same way wireframe does. It is NOT a `RenderSettings` field: read it straight
53        // off the JSON and drive the camera. A PARTIAL apply (the wireframe toggle's
54        // `{"wireframe":true}`) omits the key and leaves the projection untouched, and
55        // the panel's full-buffer apply carries the live value (so it's a no-op).
56        if let Some(want_ortho) = serde_json::from_str::<serde_json::Value>(json)
57            .ok()
58            .and_then(|v| v.get("orthographic").and_then(|o| o.as_bool()))
59        {
60            let is_ortho = matches!(
61                self.camera.projection,
62                crate::view::Projection::Orthographic { .. }
63            );
64            if want_ortho != is_ortho {
65                self.set_projection(if want_ortho { "orthographic" } else { "perspective" });
66            }
67        }
68        // The LOD factor scales DISPLAY tessellation, so a change must re-run so the
69        // resident meshes re-tessellate at the new chord tolerance (the runner drops
70        // its reuse baseline when the lod differs). Every OTHER setting is pure
71        // render state and needs no re-run. Skip the re-run when there are no
72        // features (e.g. boot restores a saved `lodFactor` before any document is
73        // loaded): the run would be empty, and the real doc load re-runs with the
74        // lod already injected.
75        if self.settings.lod_factor != prev_lod && !self.history.is_empty() {
76            self.rerun_history();
77        }
78        // Sketch colors live in the settings too: when a sketch is being edited, push
79        // the (possibly) new palette into the live session and re-push the overlay so
80        // an edited color takes effect immediately (mirrors how a wireframe/lod change
81        // refreshes the view). Compute the palette first to avoid a split borrow.
82        if self.sketch_edit.is_some() {
83            let colors = self.settings.sketch_colors();
84            if let Some(edit) = self.sketch_edit.as_mut() {
85                edit.session.colors = colors;
86            }
87            self.refresh_sketch_overlay();
88        }
89        Ok(())
90    }
91
92    /// The FULL current settings as JSON (the round-trip counterpart of
93    /// [`apply_settings_json`]): the schema-driven form seeds its widgets from
94    /// this and the storage seam persists it.
95    pub fn settings_json(&self) -> String {
96        // Projection is live CAMERA state surfaced to the settings layer as a boolean
97        // (`orthographic`) so the toolbar toggle persists and the settings panel can
98        // round-trip it without clobbering. DERIVE it from the camera here — it is
99        // never a stored `RenderSettings` field — so it can NEVER drift from the
100        // actual projection no matter which code path last changed it.
101        let mut value: serde_json::Value =
102            serde_json::from_str(&self.settings.to_json()).unwrap_or(serde_json::Value::Null);
103        if let Some(obj) = value.as_object_mut() {
104            obj.insert(
105                "orthographic".into(),
106                serde_json::Value::Bool(matches!(
107                    self.camera.projection,
108                    crate::view::Projection::Orthographic { .. }
109                )),
110            );
111        }
112        value.to_string()
113    }
114
115    /// The current per-solid metadata color overrides as JSON —
116    /// `[{"name": "...", "override": "#rrggbb" | null}, …]`. Lets a UI list the
117    /// scene's solids with their current override so the picker reflects state.
118    pub fn solid_color_overrides_json(&self) -> String {
119        let solids: Vec<serde_json::Value> = self
120            .scene
121            .solids()
122            .iter()
123            .map(|solid| {
124                let over = solid.color_override.map(|rgb| {
125                    let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
126                    format!("#{:02x}{:02x}{:02x}", q(rgb[0]), q(rgb[1]), q(rgb[2]))
127                });
128                serde_json::json!({ "name": solid.name, "override": over })
129            })
130            .collect();
131        serde_json::Value::Array(solids).to_string()
132    }
133
134    pub fn apply_emphasis_json(&mut self, json: &str) -> Result<(), String> {
135        self.emphasis.apply_json(json)?;
136        self.dirty = true;
137        Ok(())
138    }
139
140    pub fn set_visible(&mut self, name: &str, visible: bool) -> bool {
141        let ok = self.scene.set_visible(name, visible);
142        if ok {
143            // A derived BOARD body is dropped by every run's scene reconcile
144            // and re-seated from the KEPT display, so the hide has to reach
145            // that copy or it lasts only until the next feature edit.
146            self.remember_board_visibility(name, visible);
147            self.dirty = true;
148        }
149        ok
150    }
151
152    pub fn scene_listing_json(&self) -> String {
153        self.scene.listing_json()
154    }
155
156    // --- Overlay widgets --------------------------------------------------
157
158    /// The BASE bbox the camera depth-range fit starts from: the visible SOLIDS
159    /// unioned with the pushed OVERLAY groups (sketch curves/points, dimension
160    /// leaders, constraint glyphs — the `set_overlay` channel). Folding in the
161    /// groups stops orbiting an editing sketch from clipping it against the
162    /// solids-only bounds (the reported clipping when "Lock to sketch" is off).
163    /// The render path ([`Self::fit_camera_and_overlay`]) unions the FULL widget
164    /// overlay's world bounds (datum planes, world axes, frames, transform
165    /// gizmo — NOT in this bbox's channels) and the world origin on top of this
166    /// before fitting, so construction geometry never clips. Callers must bind
167    /// this to a local before `camera.fit_depth_range` (which needs
168    /// `&mut self.camera`).
169    pub fn depth_range_bbox(&self) -> crate::camera::Aabb {
170        let mut bbox = self.scene.bbox();
171        bbox.union(&self.widgets.overlay_groups_bbox());
172        bbox
173    }
174
175}
176
177impl EngineState {
178    /// A RICHER scene listing than [`scene_listing_json`](Self::scene_listing_json)
179    /// (which is counts only): per solid the individual face + edge kernel NAMES
180    /// and vertex refs (topo id + world position), plus visibility — the shape the
181    /// engine-native Scene tree lists entities from and the headed verifier asserts
182    /// against. Vertices carry no kernel name, so they are keyed by topo id + world
183    /// position (the same shape the emphasis vertex-ref selection uses).
184    pub fn scene_entities_json(&self) -> String {
185        let solids: Vec<serde_json::Value> = self
186            .scene
187            .solids()
188            .iter()
189            // Committed-sketch SHEETS are scene solids (pickable/measurable) but list
190            // under "Sketches" (`committed_sketches`), not among the real solids.
191            .filter(|solid| !solid.is_sketch)
192            .map(|solid| {
193                let faces: Vec<&str> = solid.faces.iter().map(|f| f.name.as_str()).collect();
194                // Display-only (aux) edges are not entities: a board's copper
195                // outline would list thousands of unnamed ones.
196                let edges: Vec<&str> = solid.edges.iter().filter(|e| !e.aux).map(|e| e.name.as_str()).collect();
197                let vertices: Vec<serde_json::Value> = solid
198                    .vertices
199                    .iter()
200                    .map(|v| serde_json::json!({ "topoId": v.topo_id, "position": v.position }))
201                    .collect();
202                serde_json::json!({
203                    "name": solid.name,
204                    "visible": solid.visible,
205                    "faces": faces,
206                    "edges": edges,
207                    "vertices": vertices,
208                })
209            })
210            .collect();
211        serde_json::Value::Array(solids).to_string()
212    }
213
214    /// Drive the engine SELECTION by kernel NAME from a UI tree (the name-based
215    /// analogue of [`select_top_at`](Self::select_top_at), which picks under the
216    /// cursor). Replaces the current selection with the single named `solid` /
217    /// `face` / `edge` so clicking a Scene-tree row highlights that entity in the
218    /// viewport (the render pass reads `emphasis`). Vertices have no kernel name —
219    /// use [`select_vertex_by_position`](Self::select_vertex_by_position). Returns
220    /// false for an unknown `kind` or an empty `name`.
221    pub fn select_by_name(&mut self, kind: &str, name: &str) -> bool {
222        // A construction datum/plane routes to its own name-keyed selection.
223        if kind == "datum" {
224            return self.select_datum(name);
225        }
226        if name.is_empty() || !matches!(kind, "solid" | "face" | "edge") {
227            return false;
228        }
229        let had_datum = !self.emphasis.selected_datums.is_empty();
230        self.emphasis.selected_solids.clear();
231        self.emphasis.selected_faces.clear();
232        self.emphasis.selected_edges.clear();
233        self.emphasis.selected_vertices.clear();
234        self.emphasis.selected_datums.clear();
235        match kind {
236            "solid" => {
237                self.emphasis.selected_solids.insert(name.to_string());
238            }
239            "face" => {
240                self.emphasis.selected_faces.insert(name.to_string());
241            }
242            "edge" => {
243                self.emphasis.selected_edges.insert(name.to_string());
244            }
245            _ => unreachable!(),
246        }
247        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
248        self.dirty = true;
249        if had_datum {
250            self.refresh_construction_datums();
251        }
252        true
253    }
254
255    /// Select a single vertex by its owning solid + world position — vertices have
256    /// no kernel name, so emphasis keys them by solid + position (matched with a
257    /// tolerance in the render pass). Replaces the current selection. Returns false
258    /// for an empty solid name.
259    pub fn select_vertex_by_position(&mut self, solid: &str, position: [f64; 3]) -> bool {
260        if solid.is_empty() {
261            return false;
262        }
263        let had_datum = !self.emphasis.selected_datums.is_empty();
264        self.emphasis.selected_solids.clear();
265        self.emphasis.selected_faces.clear();
266        self.emphasis.selected_edges.clear();
267        self.emphasis.selected_vertices.clear();
268        self.emphasis.selected_datums.clear();
269        self.emphasis.selected_vertices.push(crate::style::VertexRef {
270            solid: solid.to_string(),
271            position,
272        });
273        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
274        self.dirty = true;
275        if had_datum {
276            self.refresh_construction_datums();
277        }
278        true
279    }
280
281    // -----------------------------------------------------------------------
282    // Scene-tree row HOVER → the viewport hover highlight
283    //
284    // The hover twin of the name-based selection above: mousing over a Scene-tree
285    // row lights the entity EXACTLY as mousing over it in the 3D view does,
286    // because it feeds the SAME `emphasis` hover buckets through the SAME
287    // `hover_candidate` bucketing the viewport's `hover_at` uses (so a hovered
288    // datum plane gets its accent re-feed, a solid lights whole, and the render
289    // pass needs no new concept). The pointer is off the viewport while it is over
290    // a row, so the viewport's pointer-left-the-viewport `clear_hover` would
291    // otherwise wipe it every frame — hence the one-frame yield flag, the twin of
292    // `take_sketch_list_hover` / `take_constraint_label_hover`.
293    // -----------------------------------------------------------------------
294
295    /// Hover-highlight by kernel NAME from a UI tree — the hover twin of
296    /// [`select_by_name`](Self::select_by_name) (`kind` is `"solid"` / `"face"` /
297    /// `"edge"` / `"datum"`; vertices carry no kernel name, so they use
298    /// [`hover_vertex_by_position`](Self::hover_vertex_by_position)).
299    ///
300    /// Deliberately does NOT consult the selection filter, matching the row's
301    /// CLICK: a row selects whatever kind it is, so its hover previews the same
302    /// entity. An unknown `kind`, an empty `name` or an unresolved datum frame is
303    /// refused without touching the current hover.
304    ///
305    /// Call it EVERY frame the row is hovered: it re-arms the one-frame
306    /// [`take_scene_tree_hover`](Self::take_scene_tree_hover) yield flag and
307    /// re-lights nothing when the hover is already this entity. Returns whether
308    /// the hover CHANGED (the [`hover_at`](Self::hover_at) convention) so the
309    /// caller can request a repaint.
310    pub fn hover_by_name(&mut self, kind: &str, name: &str) -> bool {
311        if name.is_empty() {
312            return false;
313        }
314        let pick_kind = match kind {
315            "solid" => pick::PickKind::Solid,
316            "face" => pick::PickKind::Face,
317            "edge" => pick::PickKind::Edge,
318            // A construction datum/plane hovers by FRAME name — the bucket
319            // `select_datum` and the viewport's plane picks fill.
320            "datum" => pick::PickKind::Plane,
321            _ => return false,
322        };
323        let candidate = pick::PickCandidate {
324            kind: pick_kind,
325            name: name.to_string(),
326            // A SOLID candidate resolves through `candidate_solid_name`, which
327            // prefers `solid` — and this row IS the solid.
328            solid: match pick_kind {
329                pick::PickKind::Solid => name.to_string(),
330                _ => String::new(),
331            },
332            depth: 0.0,
333            screen_dist: 0.0,
334            position: [0.0; 3],
335        };
336        self.set_scene_tree_hover(candidate)
337    }
338
339    /// Hover a single vertex by its owning solid + world position — the hover twin
340    /// of [`select_vertex_by_position`](Self::select_vertex_by_position) (vertices
341    /// have no kernel name, so emphasis keys them by solid + position). Same
342    /// per-frame contract and return as [`hover_by_name`](Self::hover_by_name).
343    pub fn hover_vertex_by_position(&mut self, solid: &str, position: [f64; 3]) -> bool {
344        if solid.is_empty() {
345            return false;
346        }
347        self.set_scene_tree_hover(pick::PickCandidate {
348            kind: pick::PickKind::Vertex,
349            // Vertices are unnamed: `solid` + `position` is the identity.
350            name: String::new(),
351            solid: solid.to_string(),
352            depth: 0.0,
353            screen_dist: 0.0,
354            position,
355        })
356    }
357
358    /// The pointer left the Scene tree's rows: drop the row-driven highlight.
359    /// Clears ONLY a hover the tree itself lit and that is STILL lit — if the
360    /// viewport has since hovered something else (it may draw before the panel in
361    /// the dock), that hover is left alone. Safe to call every frame no row is
362    /// hovered: the target is taken, so it is a no-op from the second call on.
363    /// Returns whether the hover changed.
364    pub fn scene_tree_hover_end(&mut self) -> bool {
365        match self.scene_tree_hovered.take() {
366            Some(candidate) if self.hover_is(&candidate) => self.clear_hover(),
367            _ => false,
368        }
369    }
370
371    /// Consume the one-frame "a Scene-tree row is hovering an entity" flag — the
372    /// viewport's modeling hover branch skips its pointer-off-viewport
373    /// `clear_hover` while it is set (mirrors
374    /// [`take_sketch_list_hover`](Self::take_sketch_list_hover)) so the row-driven
375    /// highlight survives the frame instead of being cleared and re-applied.
376    pub fn take_scene_tree_hover(&mut self) -> bool {
377        std::mem::take(&mut self.scene_tree_hover_active)
378    }
379
380    /// Light one Scene-tree row's candidate: arm the yield flag (every frame — the
381    /// viewport consumes it every frame), record the target so
382    /// [`scene_tree_hover_end`](Self::scene_tree_hover_end) knows what the tree
383    /// lit, and re-emphasize only when the hover actually changed (a held row must
384    /// not re-bump the emphasis generation / re-feed the datums every frame).
385    fn set_scene_tree_hover(&mut self, candidate: pick::PickCandidate) -> bool {
386        self.scene_tree_hover_active = true;
387        match self.apply_ui_hover(&candidate) {
388            // Refused (an unresolved datum frame): nothing lit, so the tree records
389            // no target and has nothing to end.
390            None => false,
391            Some(changed) => {
392                // Recorded even when unchanged: the viewport may have lit the
393                // identical entity, and the tree still owns ending it.
394                self.scene_tree_hovered = Some(candidate);
395                changed
396            }
397        }
398    }
399
400    /// Apply ONE UI-driven hover candidate to the emphasis — the shared body
401    /// behind every list→viewport highlight (the Scene tree's rows, the dialog
402    /// rows below). `None` = REFUSED, `Some(changed)` = applied, and `changed`
403    /// says whether the hover actually moved (a held row must not re-bump the
404    /// emphasis generation / re-feed the datums every frame).
405    ///
406    /// Each caller records its OWN target: that is what keeps two panes' `_end`
407    /// calls from ending each other's highlight.
408    fn apply_ui_hover(&mut self, candidate: &pick::PickCandidate) -> Option<bool> {
409        if self.hover_is(candidate) {
410            return Some(false);
411        }
412        // Only a RESOLVED datum frame hovers (the `select_datum` guard); an
413        // unresolved name would light nothing and churn the datum feed. Checked on
414        // the change path only — the dedupe above carries the held frames.
415        if candidate.kind == pick::PickKind::Plane
416            && !self.construction_frames.iter().any(|(n, _)| *n == candidate.name)
417        {
418            return None;
419        }
420        self.hover_candidate(candidate);
421        Some(true)
422    }
423}
424
425// ---------------------------------------------------------------------------
426// DIALOG row HOVER → the viewport hover highlight
427//
428// The Scene tree knows the KIND of every row it draws; a dialog does not. A
429// feature form's reference line, its read-only `Outputs` line and the picker
430// card's picked-name line all carry a bare kernel NAME, so this lane resolves the
431// kind from the scene itself and then feeds the SAME hover buckets the tree and
432// the viewport's `hover_at` fill.
433// ---------------------------------------------------------------------------
434impl EngineState {
435    /// Hover-highlight the entity a DIALOG row names — the kind-less twin of
436    /// [`hover_by_name`](Self::hover_by_name), for the lists that show a bare
437    /// kernel name (a reference line, an `Outputs` line, the picker card).
438    ///
439    /// `owner` is the pane that is hovering (`"history"`, `"constraints"`,
440    /// `"pmi"`, `"refsel"`): [`dialog_hover_end`](Self::dialog_hover_end) acts
441    /// only for the owner that set the hover, so panes that are on screen together
442    /// in a split dock cannot end each other's highlight.
443    ///
444    /// The name is resolved by [`resolve_entity_name`](Self::resolve_entity_name),
445    /// which also covers the row whose entity the feature CONSUMED — an open
446    /// fillet form is rolled to the fillet, so its `Edges` rows name edges that no
447    /// longer exist and the blend faces the kernel built from them are lit
448    /// instead. Call it EVERY frame the row is hovered: the resolution is memoized
449    /// on the row text and the emphasis re-feed is deduped, so a held hover costs
450    /// nothing. Returns whether the hover CHANGED (the
451    /// [`hover_at`](Self::hover_at) convention), so the caller can repaint.
452    pub fn hover_entity_by_name(&mut self, owner: &'static str, name: &str) -> bool {
453        if name.is_empty() {
454            return false;
455        }
456        // Armed even for a row that resolves to nothing: the pointer is over the
457        // dialog, so the viewport's pointer-left-the-viewport `clear_hover` must
458        // still yield — otherwise moving along a list of rows would strobe the
459        // highlight off on every unresolvable one.
460        self.dialog_hover_active = true;
461        let memo = match &self.dialog_hovered {
462            Some(held) if held.owner == owner && held.row == name => Some(held.candidate.clone()),
463            _ => None,
464        };
465        let candidate = match memo {
466            Some(cached) => cached,
467            None => self.resolve_entity_name(name),
468        };
469        let applied = match &candidate {
470            Some(c) => self.apply_ui_hover(c),
471            None => None,
472        };
473        let changed = match applied {
474            Some(changed) => changed,
475            // Nothing to light (the scene carries no such name, or the candidate
476            // was refused): end whatever the slot holds — WHOEVER set it. Leaving
477            // the previous row's entity standing while the pointer sits on a
478            // different row reads as "this row is that entity", and the previous
479            // row is not always this owner's: moving from a History line straight
480            // onto an unresolvable Constraints one (a component-local vertex ref)
481            // would otherwise strand the History highlight with nobody left
482            // holding the record that could end it.
483            None => self.take_dialog_hover_slot(),
484        };
485        self.dialog_hovered = Some(super::DialogHover {
486            owner,
487            row: name.to_string(),
488            candidate,
489        });
490        changed
491    }
492
493    /// The pointer left `owner`'s dialog rows: drop the row-driven highlight.
494    /// Clears ONLY a hover THIS owner lit and that is STILL lit — a pane that
495    /// never hovered a row (or whose hover the viewport has since replaced) is a
496    /// no-op, which is what lets every consumer call it unconditionally every
497    /// frame. Returns whether the hover changed.
498    pub fn dialog_hover_end(&mut self, owner: &'static str) -> bool {
499        let mine = matches!(&self.dialog_hovered, Some(held) if held.owner == owner);
500        if mine {
501            self.take_dialog_hover_slot()
502        } else {
503            false
504        }
505    }
506
507    /// Take the dialog-hover slot and drop the highlight it recorded, when that
508    /// highlight is still the live one (the viewport may have replaced it since).
509    /// Owner-AGNOSTIC: [`dialog_hover_end`](Self::dialog_hover_end) checks the
510    /// owner before calling this, while a row that lights nothing calls it
511    /// directly — the pointer is on THAT row now, so whatever the slot still
512    /// records is stale whoever set it.
513    fn take_dialog_hover_slot(&mut self) -> bool {
514        match self.dialog_hovered.take() {
515            Some(held) => match held.candidate {
516                Some(candidate) if self.hover_is(&candidate) => self.clear_hover(),
517                _ => false,
518            },
519            None => false,
520        }
521    }
522
523    /// Consume the one-frame "a dialog row is hovering an entity" flag — the
524    /// viewport's modeling hover branch skips its pointer-off-viewport
525    /// `clear_hover` while it is set (the twin of
526    /// [`take_scene_tree_hover`](Self::take_scene_tree_hover)).
527    pub fn take_dialog_hover(&mut self) -> bool {
528        std::mem::take(&mut self.dialog_hover_active)
529    }
530
531    /// Resolve one bare kernel NAME to the entity it addresses, or `None` when the
532    /// scene carries nothing by that name.
533    ///
534    /// Order — most specific identity first: a SOLID (a shown committed sketch is
535    /// a scene solid keyed by its sketch id — `refresh_committed_sketches` inserts
536    /// the sheet under the feature id an extrude's `profile` stores — so a
537    /// `SKETCH` reference lands here whenever that sheet is shown), a
538    /// construction datum FRAME, a FACE, an EDGE, then a `{solid}@x,y,z` VERTEX
539    /// ref (the position-keyed form assembly constraints and PMI store, accepted
540    /// only when it really is a vertex of that solid — a component-LOCAL ref lights
541    /// nothing rather than lighting the wrong vertex).
542    ///
543    /// # The consumed row
544    ///
545    /// A feature's form is drawn with the model rolled TO that feature, so the
546    /// feature has RUN and the entities its references name are gone: a fillet's
547    /// `Edges` rows name edges the blend replaced. The kernel names what it builds
548    /// after what it consumed — `{featureId}:BLEND:{originatingEdgeName}`, asserted
549    /// by the kernel's own `fillet_by_face_ref_rounds_the_top_ring` /
550    /// `chamfer` naming tests — so a row that resolves to nothing falls back to the
551    /// FACE whose name ends with `:{row}`: the thing the feature made from it.
552    /// Only when EXACTLY ONE face matches, so an ambiguous mapping lights nothing
553    /// rather than an arbitrary half of it. Ends-with, never `contains`: the edges
554    /// bounding that blend are named `BOX_NZ|F1:BLEND:BOX_NX|BOX_NZ[0][0]`, which
555    /// CONTAINS the row but is not what it became.
556    fn resolve_entity_name(&self, name: &str) -> Option<pick::PickCandidate> {
557        let at = |kind: pick::PickKind, entity: &str, solid: &str| pick::PickCandidate {
558            kind,
559            name: entity.to_string(),
560            solid: solid.to_string(),
561            depth: 0.0,
562            screen_dist: 0.0,
563            position: [0.0; 3],
564        };
565        let solids = self.scene.solids();
566        if solids.iter().any(|s| s.name == name) {
567            // A SOLID candidate resolves through `candidate_solid_name`, which
568            // prefers `solid` — and this row IS the solid.
569            return Some(at(pick::PickKind::Solid, name, name));
570        }
571        if self.construction_frames.iter().any(|(n, _)| n.as_str() == name) {
572            return Some(at(pick::PickKind::Plane, name, ""));
573        }
574        for solid in solids {
575            if solid.faces.iter().any(|f| f.name == name) {
576                return Some(at(pick::PickKind::Face, name, &solid.name));
577            }
578        }
579        for solid in solids {
580            if solid.edges.iter().any(|e| e.name == name) {
581                return Some(at(pick::PickKind::Edge, name, &solid.name));
582            }
583        }
584        if let Some(candidate) = self.resolve_vertex_ref(name) {
585            return Some(candidate);
586        }
587        let suffix = format!(":{name}");
588        let mut derived = solids
589            .iter()
590            .flat_map(|solid| solid.faces.iter().map(move |face| (solid, face)))
591            .filter(|(_, face)| face.name.ends_with(&suffix));
592        match (derived.next(), derived.next()) {
593            (Some((solid, face)), None) => {
594                Some(at(pick::PickKind::Face, &face.name, &solid.name))
595            }
596            _ => None,
597        }
598    }
599
600    /// A `{solid}@x,y,z` VERTEX reference → its candidate, when the position
601    /// really is a vertex of that solid within the emphasis match tolerance.
602    /// Vertices carry no kernel name, so this is the only form a dialog can list
603    /// one under; PMI stores WORLD coordinates (which resolve here), assembly
604    /// constraints store component-LOCAL ones (which do not, and so light nothing
605    /// rather than the wrong vertex).
606    fn resolve_vertex_ref(&self, name: &str) -> Option<pick::PickCandidate> {
607        /// The tolerance the render pass matches an emphasis vertex ref at.
608        const TOL: f64 = 1e-4;
609        let (solid_name, coords) = name.rsplit_once('@')?;
610        let mut parts = coords.split(',').map(|p| p.trim().parse::<f64>().ok());
611        let position = [parts.next()??, parts.next()??, parts.next()??];
612        if parts.next().is_some() {
613            return None;
614        }
615        let solid = self.scene.solids().iter().find(|s| s.name == solid_name)?;
616        solid.vertices.iter().find(|v| {
617            (v.position[0] - position[0]).abs() <= TOL
618                && (v.position[1] - position[1]).abs() <= TOL
619                && (v.position[2] - position[2]).abs() <= TOL
620        })?;
621        Some(pick::PickCandidate {
622            kind: pick::PickKind::Vertex,
623            name: String::new(),
624            solid: solid_name.to_string(),
625            depth: 0.0,
626            screen_dist: 0.0,
627            position,
628        })
629    }
630}
631
632
633impl EngineState {
634    /// The resident kernel handle of every solid currently displayed, keyed by
635    /// name. Obtained by replaying the CURRENT rolled-to history prefix through
636    /// [`brep_kernel::execute_history`]: after a build the incremental cache
637    /// holds exactly this prefix, so the replay is a clean cache hit — it
638    /// re-tessellates nothing and hands back the SAME handles the scene was built
639    /// from (mirrors the pipeline's `fold_history`: removals then additions).
640    /// `pub(super)`: the interference check (`engine_state::interference`) reads
641    /// the same warm main-side handle map for its non-destructive booleans.
642    pub(super) fn resident_solid_handles(&self) -> HashMap<String, u32> {
643        let request: HistoryRequest = match serde_json::from_value(self.run_request_value()) {
644            Ok(request) => request,
645            Err(_) => return HashMap::new(),
646        };
647        let _trace = crate::run_trace::span("resident_solid_handles");
648        let result = brep_kernel::execute_history(&request);
649        let mut handles: HashMap<String, u32> = HashMap::new();
650        for feature in &result.results {
651            for removed in &feature.removed {
652                handles.remove(removed);
653            }
654            for added in &feature.added {
655                handles.insert(added.name.clone(), added.handle);
656            }
657        }
658        handles
659    }
660
661    /// Mass properties for the Inspector panel, from the kernel's exact
662    /// (divergence-theorem) integrator. `name = Some(solid)` reports that resident
663    /// solid; `None` reports the whole model. `density` (mass units per mm³; the
664    /// kernel length convention is millimetres) scales `mass` and the inertia
665    /// tensor — the centroid and principal axes are density-independent.
666    ///
667    /// Returns JSON:
668    /// ```json
669    /// { "ok": true, "target": "Box", "solidCount": 1, "density": 1.0,
670    ///   "volume": 5738.05, "surfaceArea": 2927.79, "mass": 5738.05,
671    ///   "centroid": [10.0, 10.0, 10.0],
672    ///   "inertia": [[..],[..],[..]] | null,
673    ///   "principalMoments": [a,b,c] | null,
674    ///   "principalAxes": [[..],[..],[..]] | null }
675    /// ```
676    /// A single resolved solid carries the full centroidal inertia tensor +
677    /// principal axes/moments; a multi-solid aggregate reports summed volume /
678    /// area / mass and the volume-weighted centroid, with the tensor fields
679    /// `null` (select one solid for its inertia). `ok:false` with a `message` on
680    /// no solids / an unknown name / an integrator failure.
681    pub fn mass_properties_json(&self, name: Option<&str>, density: f64) -> String {
682        let handles = self.resident_solid_handles();
683
684        // Resolve the target solids: a named solid (must be resident) or, for the
685        // whole model, every scene solid that has resident geometry (draw order).
686        let targets: Vec<String> = match name {
687            Some(name) if handles.contains_key(name) => vec![name.to_string()],
688            Some(name) => {
689                return serde_json::json!({
690                    "ok": false,
691                    "message": format!("solid '{name}' has no resident geometry"),
692                })
693                .to_string();
694            }
695            None => self
696                .scene
697                .solids()
698                .iter()
699                .map(|solid| solid.name.clone())
700                .filter(|name| handles.contains_key(name))
701                .collect(),
702        };
703        if targets.is_empty() {
704            return serde_json::json!({ "ok": false, "message": "no solids" }).to_string();
705        }
706
707        // Per-solid density mass properties straight from the kernel.
708        let mut props = Vec::with_capacity(targets.len());
709        for target in &targets {
710            match brep_kernel::mass_properties_handle_native(handles[target], density) {
711                Ok(properties) => props.push(properties),
712                Err(error) => {
713                    return serde_json::json!({
714                        "ok": false,
715                        "message": format!("{target}: {error}"),
716                    })
717                    .to_string();
718                }
719            }
720        }
721
722        let target_label = if targets.len() == 1 {
723            targets[0].clone()
724        } else {
725            "(whole model)".to_string()
726        };
727
728        if props.len() == 1 {
729            // Single solid: the full tensor + principal frame are meaningful.
730            let p = &props[0];
731            serde_json::json!({
732                "ok": true,
733                "target": target_label,
734                "solidCount": 1,
735                "density": p.density,
736                "volume": p.volume,
737                "surfaceArea": p.surface_area,
738                "mass": p.mass,
739                "centroid": [p.centroid.x, p.centroid.y, p.centroid.z],
740                "inertia": p.inertia,
741                "principalMoments": p.principal_moments,
742                "principalAxes": p.principal_axes,
743            })
744            .to_string()
745        } else {
746            // Aggregate: additive scalars + volume-weighted centroid. Combining
747            // the tensors needs a parallel-axis shift per solid; left to the
748            // single-solid view rather than approximated here.
749            let volume: f64 = props.iter().map(|p| p.volume).sum();
750            let surface_area: f64 = props.iter().map(|p| p.surface_area).sum();
751            let mass: f64 = props.iter().map(|p| p.mass).sum();
752            let centroid = if volume.abs() > f64::EPSILON {
753                let mut acc = [0.0f64; 3];
754                for p in &props {
755                    acc[0] += p.volume * p.centroid.x;
756                    acc[1] += p.volume * p.centroid.y;
757                    acc[2] += p.volume * p.centroid.z;
758                }
759                [acc[0] / volume, acc[1] / volume, acc[2] / volume]
760            } else {
761                [0.0, 0.0, 0.0]
762            };
763            serde_json::json!({
764                "ok": true,
765                "target": target_label,
766                "solidCount": props.len(),
767                "density": density,
768                "volume": volume,
769                "surfaceArea": surface_area,
770                "mass": mass,
771                "centroid": centroid,
772                "inertia": serde_json::Value::Null,
773                "principalMoments": serde_json::Value::Null,
774                "principalAxes": serde_json::Value::Null,
775            })
776            .to_string()
777        }
778    }
779}
780
781