Skip to main content

brep_render/
metadata.rs

1//! The Properties-panel DATA layer (UI comes later): a name-keyed metadata
2//! store, per-entity measurements, and object provenance — all engine-native,
3//! all crossing the R3 boundary as plain JSON/scalars.
4//!
5//! # Metadata store ([`MetadataStore`])
6//!
7//! `object name → { attribute → value }`, keyed by the KERNEL OBJECT NAME (a
8//! solid / face / edge name), **not** a feature id. This loose coupling is the
9//! whole point: a record survives feature edits, rollback and re-tessellation as
10//! long as the object's name persists (edge/face names ARE propagated through
11//! booleans, splits and welds by the kernel). Values are strings; the well-known
12//! `density` attribute (mass units per mm³) drives a solid's weight. The store is
13//! persisted WITH the model — [`crate::engine_state::EngineState::history_request_json`]
14//! folds it in as a top-level `metadata` field and
15//! [`crate::engine_state::EngineState::set_history_json`] lifts it back out, so it
16//! round-trips through save/open.
17//!
18//! # Measurements + provenance
19//!
20//! The [`EngineState`] methods below resolve an object NAME to its kind (solid /
21//! face / edge, via the scene) and return the right measurements from the
22//! kernel's exact integrators (volume, surface area, arc length), plus the
23//! feature that produced the object (provenance, via the history's per-feature
24//! output solids). Units are millimetres (the kernel length convention).
25
26use crate::engine_state::EngineState;
27use brep_kernel::COLOR_METADATA_KEY;
28use crate::runner::{MeasureKind, MeasureQuery};
29use serde_json::Value;
30use std::collections::BTreeMap;
31
32/// The metadata key a solid's or face's transparency is stored under: a number
33/// from 0 (opaque) to 1 (clear), or the same as a percentage (`35%`).
34pub const TRANSPARENCY_METADATA_KEY: &str = "transparency";
35
36/// A `transparency` attribute's value as the OPACITY the display draws at
37/// (0 clear .. 1 opaque). `None` for anything that is not a number.
38pub fn transparency_opacity(value: &str) -> Option<f32> {
39    let text = value.trim();
40    let fraction = match text.strip_suffix('%') {
41        Some(percent) => percent.trim().parse::<f64>().ok()? / 100.0,
42        None => text.parse::<f64>().ok()?,
43    };
44    fraction.is_finite().then(|| (1.0 - fraction.clamp(0.0, 1.0)) as f32)
45}
46
47/// The default density (mass per unit volume) when an object carries no
48/// `density` metadata: unit density, so `weight == volume`.
49pub const DEFAULT_DENSITY: f64 = 1.0;
50
51/// The name-keyed metadata store: `object name → { attribute → value }`, string
52/// values, deterministic iteration (a `BTreeMap` so the persisted JSON is
53/// stable). Empty records are never retained (removing the last attribute drops
54/// the whole record).
55#[derive(Debug, Clone, Default)]
56pub struct MetadataStore {
57    entries: BTreeMap<String, BTreeMap<String, String>>,
58    /// Names the content: every mutation takes a fresh process-wide number, and
59    /// a clone (an undo snapshot) carries its content's number with it, so two
60    /// equal stamps always hold equal records.
61    stamp: u64,
62}
63
64static STAMPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
65
66impl MetadataStore {
67    pub fn new() -> Self {
68        Self::default()
69    }
70
71    /// Whether the store holds no records at all.
72    pub fn is_empty(&self) -> bool {
73        self.entries.is_empty()
74    }
75
76    /// The content stamp: unmoved means unchanged (see the field).
77    pub fn stamp(&self) -> u64 {
78        self.stamp
79    }
80
81    fn touch(&mut self) {
82        self.stamp = STAMPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
83    }
84
85    /// Set (or overwrite) one attribute of `name`'s record. An empty object name
86    /// or key is ignored (no phantom records).
87    pub fn set_attribute(&mut self, name: &str, key: &str, value: &str) {
88        if name.is_empty() || key.is_empty() {
89            return;
90        }
91        self.touch();
92        self.entries
93            .entry(name.to_string())
94            .or_default()
95            .insert(key.to_string(), value.to_string());
96    }
97
98    /// Remove one attribute of `name`'s record, dropping the record if it becomes
99    /// empty. Returns whether the attribute existed.
100    pub fn remove_attribute(&mut self, name: &str, key: &str) -> bool {
101        let Some(record) = self.entries.get_mut(name) else {
102            return false;
103        };
104        let existed = record.remove(key).is_some();
105        if record.is_empty() {
106            self.entries.remove(name);
107        }
108        if existed {
109            self.touch();
110        }
111        existed
112    }
113
114    /// One attribute's value (`None` if the object or key is unknown).
115    pub fn attribute(&self, name: &str, key: &str) -> Option<&str> {
116        self.entries.get(name)?.get(key).map(String::as_str)
117    }
118
119    /// One object's whole record (empty map if the object has no metadata).
120    pub fn record(&self, name: &str) -> BTreeMap<String, String> {
121        self.entries.get(name).cloned().unwrap_or_default()
122    }
123
124    /// The whole store (all records), read-only.
125    pub fn all(&self) -> &BTreeMap<String, BTreeMap<String, String>> {
126        &self.entries
127    }
128
129    /// The resolved density (mass per mm³) for `name`: its `density` attribute
130    /// parsed as a positive finite number, else [`DEFAULT_DENSITY`].
131    pub fn density(&self, name: &str) -> f64 {
132        self.attribute(name, "density")
133            .and_then(|value| value.trim().parse::<f64>().ok())
134            .filter(|density| density.is_finite() && *density > 0.0)
135            .unwrap_or(DEFAULT_DENSITY)
136    }
137
138    /// Drop every record (a part load replaces the store wholesale).
139    pub fn clear(&mut self) {
140        self.entries.clear();
141        self.touch();
142    }
143
144    /// One object's record as a JSON object `{ key: value, ... }` (`{}` when the
145    /// object has no metadata).
146    pub fn record_json(&self, name: &str) -> String {
147        Value::Object(
148            self.record(name)
149                .into_iter()
150                .map(|(key, value)| (key, Value::String(value)))
151                .collect(),
152        )
153        .to_string()
154    }
155
156    /// The whole store as a JSON value `{ name: { key: value, ... }, ... }` — the
157    /// persisted shape and the whole-store getter.
158    pub fn to_json(&self) -> Value {
159        Value::Object(
160            self.entries
161                .iter()
162                .map(|(name, record)| {
163                    let object = record
164                        .iter()
165                        .map(|(key, value)| (key.clone(), Value::String(value.clone())))
166                        .collect();
167                    (name.clone(), Value::Object(object))
168                })
169                .collect(),
170        )
171    }
172
173    /// The whole store as a JSON string (the whole-store getter's string form).
174    pub fn to_json_string(&self) -> String {
175        self.to_json().to_string()
176    }
177
178    /// Replace the whole store from a persisted `metadata` value (or `None`, which
179    /// clears it — loading a part with no metadata). Non-string leaf values are
180    /// coerced to their JSON text so a legacy document never fails the load.
181    pub fn load_json(&mut self, value: Option<&Value>) {
182        self.entries.clear();
183        self.touch();
184        let Some(Value::Object(objects)) = value else {
185            return;
186        };
187        for (name, record) in objects {
188            let Value::Object(attributes) = record else {
189                continue;
190            };
191            let map: BTreeMap<String, String> = attributes
192                .iter()
193                .map(|(key, value)| (key.clone(), value_to_string(value)))
194                .collect();
195            if !map.is_empty() {
196                self.entries.insert(name.clone(), map);
197            }
198        }
199    }
200}
201
202/// Coerce a persisted metadata leaf to a string value (strings verbatim, `null`
203/// to empty, everything else to its JSON text).
204fn value_to_string(value: &Value) -> String {
205    match value {
206        Value::String(text) => text.clone(),
207        Value::Null => String::new(),
208        other => other.to_string(),
209    }
210}
211
212/// The kind an object NAME resolves to in the current scene.
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214enum ObjectKind {
215    Solid,
216    Face,
217    Edge,
218}
219
220// --- EngineState: metadata store API (a SEPARATE impl block, appended, so
221//     concurrent edits to the primary block don't conflict) -------------------
222impl EngineState {
223    /// One object's metadata record as JSON `{ key: value, ... }` (`{}` if none).
224    pub fn object_metadata_json(&self, name: &str) -> String {
225        self.metadata.record_json(name)
226    }
227
228    /// Set (or overwrite) one metadata attribute of an object by NAME. String
229    /// value; the well-known `density` key drives the object's weight and the
230    /// well-known `color` key drives its shaded colour, and the well-known
231    /// `transparency` key (0 opaque .. 1 clear) how see-through it is.
232    pub fn set_metadata_attribute(&mut self, name: &str, key: &str, value: &str) {
233        self.metadata.set_attribute(name, key, value);
234        // A metadata edit (notably `density`) feeds the object-info output but does
235        // NOT trigger a history rerun, so drop this object's cached info so a
236        // re-selection re-measures with the new attribute.
237        self.info_cache.remove(name);
238        // `color` is the one attribute the VIEWPORT reads, and there is no rerun
239        // to carry it through — push it to the display right here so recolouring
240        // a body is immediate.
241        if key == COLOR_METADATA_KEY || key == TRANSPARENCY_METADATA_KEY {
242            self.sync_colors_from_metadata();
243        }
244    }
245
246    /// [`Self::set_metadata_attribute`] for many `(name, value)` pairs under one
247    /// `key`, re-deriving the display colours once at the end rather than once
248    /// per object (an import colouring many bodies would otherwise walk the
249    /// whole scene for each).
250    pub fn set_metadata_attributes(&mut self, key: &str, pairs: &[(String, String)]) {
251        for (name, value) in pairs {
252            self.metadata.set_attribute(name, key, value);
253            self.info_cache.remove(name.as_str());
254        }
255        if !pairs.is_empty() && (key == COLOR_METADATA_KEY || key == TRANSPARENCY_METADATA_KEY) {
256            self.sync_colors_from_metadata();
257        }
258    }
259
260    /// Remove one metadata attribute of an object. Returns whether it existed.
261    pub fn remove_metadata_attribute(&mut self, name: &str, key: &str) -> bool {
262        let existed = self.metadata.remove_attribute(name, key);
263        // Same rerun-less invalidation as `set_metadata_attribute`.
264        self.info_cache.remove(name);
265        if existed && (key == COLOR_METADATA_KEY || key == TRANSPARENCY_METADATA_KEY) {
266            self.sync_colors_from_metadata();
267        }
268        existed
269    }
270
271    /// Re-derive the display scene's colours from the metadata store — the ONE
272    /// call that connects the durable `color` attribute to the renderer (and,
273    /// the same way, the `transparency` attribute).
274    ///
275    /// Every colour the viewport shows comes from here: a STEP import's stamped
276    /// body/face colours, a colour typed or picked in the Info window, a colour
277    /// restored from a saved document. The store is the authority; the display's
278    /// `color_override` fields are a derived cache of it, rebuilt after every
279    /// history apply (`EngineState::finish_apply`), on every document load, on
280    /// a metadata edit, and whenever the display setting flips.
281    ///
282    /// [`crate::style::RenderSettings::override_model_colors`] is honoured HERE
283    /// rather than in the renderer, and it is deliberately a READ of the store,
284    /// never a write: ticking the box resolves every colour to `None` so the
285    /// viewport falls back to `faceColorMode`, while the stored attributes stay
286    /// exactly as they were. Unticking restores them from the same records.
287    ///
288    /// Returns whether anything changed, and marks the engine dirty only then —
289    /// the no-op case must stay free, since this runs after every single run.
290    pub fn sync_colors_from_metadata(&mut self) -> bool {
291        // Disjoint field borrows: the closure reads `self.metadata` while
292        // `self.scene` is borrowed mutably.
293        let ignore = self.settings.override_model_colors;
294        let metadata = &self.metadata;
295        let changed = self.scene.apply_metadata_colors(|name| {
296            if ignore {
297                return None;
298            }
299            metadata
300                .attribute(name, COLOR_METADATA_KEY)
301                .and_then(crate::style::parse_css_hex)
302                // A derived BOARD body has a colour of its own and no producing
303                // feature to have coloured it, so without this fallback the
304                // pass would resolve it to `None` and the board would draw in
305                // the name-hashed default — green substrate and copper traces
306                // are the whole point of drawing it. A stored attribute still
307                // wins, so a user may recolour the board like anything else.
308                .or_else(|| crate::engine_state::board_default_color(name))
309        });
310        // `transparency` rides the same seam. It is not a colour, so the
311        // "override model colors" setting leaves it alone: a see-through body
312        // stays see-through in whatever colour the display gives it.
313        let changed = self.scene.apply_metadata_opacity(|name| {
314            metadata.attribute(name, TRANSPARENCY_METADATA_KEY).and_then(transparency_opacity)
315        }) || changed;
316        // An edge's own `color` and `transparency`: the stored attributes
317        // only (no board default), the colour hidden by the override.
318        let changed = self.scene.apply_metadata_edge_looks(
319            |name| if ignore { None } else { metadata.attribute(name, COLOR_METADATA_KEY).and_then(crate::style::parse_css_hex) },
320            |name| metadata.attribute(name, TRANSPARENCY_METADATA_KEY).and_then(transparency_opacity),
321        ) || changed;
322        if changed {
323            self.dirty = true;
324        }
325        changed
326    }
327
328    /// The whole metadata store as JSON `{ name: { key: value } }`.
329    pub fn metadata_json(&self) -> String {
330        self.metadata.to_json_string()
331    }
332
333    /// [`Self::metadata_json`] as a JSON value.
334    pub fn metadata_value(&self) -> Value {
335        self.metadata.to_json()
336    }
337}
338
339// --- EngineState: measurements + provenance (SEPARATE impl block) ------------
340impl EngineState {
341    /// Resolve an object NAME to `(kind, owning solid name)` via the display
342    /// scene: a solid resolves to itself; a face/edge resolves to its owning
343    /// solid. `None` for an empty or unknown name (vertices carry no kernel name).
344    fn resolve_object(&self, name: &str) -> Option<(ObjectKind, String)> {
345        if name.is_empty() {
346            return None;
347        }
348        if self.scene.solid(name).is_some() {
349            return Some((ObjectKind::Solid, name.to_string()));
350        }
351        for solid in self.scene.solids() {
352            if solid.faces.iter().any(|face| face.name == name) {
353                return Some((ObjectKind::Face, solid.name.clone()));
354            }
355        }
356        for solid in self.scene.solids() {
357            if solid.edges.iter().any(|edge| edge.name == name) {
358                return Some((ObjectKind::Edge, solid.name.clone()));
359            }
360        }
361        None
362    }
363
364    /// The feature that an object ORIGINATES from, as `(feature id, feature type)`.
365    /// For a FACE/EDGE this is the feature that first gave it its name (its true
366    /// origin, from the eager `entity_origin` first-writer map) — NOT the owning
367    /// solid's last producer — so "Edit owning feature" rolls back to where the
368    /// entity was born. For a SOLID it's the solid's producer (last writer, the
369    /// eager `provenance` map). `None` if the name is unknown or has no known
370    /// producer. Reads only the eager maps the last run shipped, so it never re-runs
371    /// the history — the freeze side-door `context_bar` hit every selected frame is
372    /// now O(1).
373    pub fn creating_feature(&self, name: &str) -> Option<(String, String)> {
374        let Some((kind, owner)) = self.resolve_object(name) else {
375            // A datum / construction PLANE (or one plane of a datum) is not a
376            // resident solid/face/edge — it's a named frame. Its producer is the
377            // D/P feature that emitted the frame (same fallback object_info_json
378            // uses), so "Edit owning feature" resolves for a lone plane pick too.
379            return self.datum_feature_for_name(name);
380        };
381        let id = match kind {
382            // A face/edge resolves to its ORIGIN. Fall back to the owning solid's
383            // producer when the name is somehow absent from `entity_origin` (keeps
384            // the "Edit owning feature" button from vanishing).
385            ObjectKind::Face | ObjectKind::Edge => self
386                .entity_origin
387                .get(name)
388                .cloned()
389                .or_else(|| self.provenance.get(&owner).cloned())?,
390            // A solid keeps its existing last-writer producer semantics.
391            ObjectKind::Solid => self.provenance.get(&owner)?.clone(),
392        };
393        Some((id.clone(), self.feature_type_of(&id)))
394    }
395
396    /// Whether the object `name` (a solid, or a face/edge owned by a solid) sits
397    /// on a SHEET-METAL body — its owning display solid carries the sheet-metal
398    /// marker the pipeline stamped from the resident handle's `SheetTree`. Reads
399    /// only the display scene, so it is O(1) and thread-safe (no `SheetTree`
400    /// thread-local touched on the UI thread — [`crate::scene::SolidDisplay::
401    /// is_sheet_metal`]). The gate for the sheet-metal edit features (SM Flange /
402    /// Fillet / Chamfer). `false` for an unknown name or a synthesized sketch
403    /// sheet (no resident handle, no tree).
404    pub fn is_sheet_metal_object(&self, name: &str) -> bool {
405        self.resolve_object(name)
406            .and_then(|(_, owner)| self.scene.solid(&owner))
407            .is_some_and(|solid| solid.is_sheet_metal)
408    }
409
410    /// A feature's type token by id (empty string if the id is not in the history).
411    fn feature_type_of(&self, id: &str) -> String {
412        self.history
413            .index_of(id)
414            .and_then(|index| self.history.feature_type(index))
415            .unwrap_or_default()
416    }
417
418    /// The `{ id, type }` provenance JSON for an object by NAME (or `null` if it has
419    /// no known producer). Delegates to [`creating_feature`](Self::creating_feature)
420    /// so a face/edge reports its ORIGIN (first-writer) and a solid its producer
421    /// (last-writer) — one resolver, so the Info tab and the context bar agree.
422    fn creating_feature_value(&self, name: &str) -> Value {
423        match self.creating_feature(name) {
424            Some((id, ty)) => serde_json::json!({ "id": id, "type": ty }),
425            None => Value::Null,
426        }
427    }
428
429    /// The full Properties-panel info for an object by NAME: its resolved kind,
430    /// the right measurements, and provenance. Units are millimetres.
431    ///
432    /// - **Solid** — `{ ok, name, kind:"solid", volume, surfaceArea,
433    ///   edgeLengthTotal, density, weight, creatingFeature }`, where
434    ///   `weight = density · volume` and `density` comes from the object's
435    ///   metadata (default [`DEFAULT_DENSITY`]).
436    /// - **Face** — `{ ok, name, kind:"face", solid, surfaceType, area,
437    ///   edgeLengthTotal, creatingFeature }` (`edgeLengthTotal` = its boundary
438    ///   edges; `surfaceType` = the carrier-surface classification, e.g.
439    ///   `"Plane"`/`"Cylinder"`/`"Cone"`/`"Sphere"`/`"Torus"`/`"NURBS"`), plus
440    ///   the carrier's dimensions when it has them: `radius` + `diameter`
441    ///   (cylinder, sphere), `halfAngleDeg` (cone), `majorRadius` +
442    ///   `minorRadius` (torus).
443    /// - **Edge** — `{ ok, name, kind:"edge", solid, length, creatingFeature }`,
444    ///   plus `curveType` (`"Circle"`/`"Arc"`), `radius`, `diameter` and an
445    ///   arc's `sweepDeg` when the edge lies on a circle.
446    ///
447    /// `{ ok:false, name, message }` for an empty/unknown name, a non-resident
448    /// solid, or a kernel measurement failure.
449    ///
450    /// The real solid/face/edge MEASUREMENT is routed to the [`HistoryRunner`] (so
451    /// the warm-registry runner answers it, never the potentially-cold main side)
452    /// and CACHED here keyed by name — fired once per selection, served from the
453    /// cache every subsequent frame. For the synchronous
454    /// [`InlineRunner`](crate::runner::InlineRunner) the submit → `pump_queries`
455    /// resolves same-call, so this returns the merged JSON immediately and stays
456    /// byte-identical to the pre-seam in-process result; a background
457    /// [`ThreadRunner`](crate::runner::ThreadRunner) returns a `pending` placeholder
458    /// for the frame(s) until its reply lands (drained by `pump_queries`). The cache
459    /// is invalidated on any geometry change (`apply_run_output`) or metadata edit
460    /// (`set_metadata_attribute`).
461    ///
462    /// [`HistoryRunner`]: crate::runner::HistoryRunner
463    pub fn object_info_json(&mut self, name: &str) -> String {
464        let raw = self.object_info_raw_json(name);
465        self.with_part_mass(name, raw)
466    }
467
468    /// A SOLID's info carries the mass the part's density gives it (see
469    /// `engine_state::part_mass`): `density` (g/cm³, `null` when none
470    /// resolves), `densitySource` (`solid` | `part` | `material`), `mass` (kg)
471    /// and, with no number, `massNote` saying why. The runner's unit-density
472    /// `weight` is not reported: the BOM and this window read ONE density.
473    fn with_part_mass(&self, name: &str, raw: String) -> String {
474        let Ok(mut info) = serde_json::from_str::<Value>(&raw) else {
475            return raw;
476        };
477        if info.get("ok").and_then(Value::as_bool) != Some(true)
478            || info.get("kind").and_then(Value::as_str) != Some("solid")
479        {
480            return raw;
481        }
482        let volume = info.get("volume").and_then(Value::as_f64);
483        let resolved = self.solid_density(name);
484        if let Some(object) = info.as_object_mut() {
485            object.remove("weight");
486            object.insert(
487                "density".into(),
488                resolved.map(|(density, _)| Value::from(density)).unwrap_or(Value::Null),
489            );
490            object.insert(
491                "densitySource".into(),
492                resolved
493                    .map(|(_, source)| Value::from(source.as_str()))
494                    .unwrap_or(Value::Null),
495            );
496            let mass = volume.zip(resolved).map(|(v, (d, _))| v * d * 1e-6);
497            object.insert("mass".into(), mass.map(Value::from).unwrap_or(Value::Null));
498            if mass.is_none() {
499                object.insert(
500                    "massNote".into(),
501                    Value::from("no density: set the part's Material or Density"),
502                );
503            }
504        }
505        info.to_string()
506    }
507
508    /// [`Self::object_info_json`] without the part-density fold: the runner's
509    /// measurement as cached.
510    pub(crate) fn object_info_raw_json(&mut self, name: &str) -> String {
511        let Some((kind, owner)) = self.resolve_object(name) else {
512            // A construction datum/plane carries no resident geometry (no volume /
513            // area / length), so it never resolves as a solid/face/edge. Return a
514            // graceful minimal record — name + kind + creating feature — rather than
515            // erroring, so the Properties Info tab renders for a selected datum and
516            // its name flows into the (name-keyed) Metadata tab.
517            if let Some((feature_id, feature_type)) = self.datum_feature_for_name(name) {
518                let kind_label = if feature_type == "P" { "plane" } else { "datum" };
519                return serde_json::json!({
520                    "ok": true,
521                    "name": name,
522                    "kind": kind_label,
523                    "creatingFeature": { "id": feature_id, "type": feature_type },
524                })
525                .to_string();
526            }
527            return serde_json::json!({
528                "ok": false, "name": name, "message": "unknown object",
529            })
530            .to_string();
531        };
532        // A committed-sketch SHEET is a scene solid with NO kernel handle, so the
533        // handle-based measurement path can't serve it. Measure straight off its
534        // synthesized display (planar-mesh triangle areas / edge polylines) and
535        // report `kind:"sketch"` — no volume. Handle-less ⇒ synchronous, no query.
536        if let Some(solid) = self.scene.solid(&owner) {
537            if solid.is_sketch {
538                return self.sketch_info_json(name, kind, solid);
539            }
540        }
541
542        // Real geometry: serve from the info cache, else fire a measurement query at
543        // the runner (deduped: never submit a second query for a name already in
544        // flight), pump, and return the resolved JSON — or a pending placeholder.
545        if let Some(cached) = self.info_cache.get(name) {
546            return cached.clone();
547        }
548        if !self.pending_query.values().any(|pending| pending == name) {
549            self.next_query_id += 1;
550            let id = self.next_query_id;
551            let measure_kind = match kind {
552                ObjectKind::Solid => MeasureKind::Solid,
553                ObjectKind::Face => MeasureKind::Face,
554                ObjectKind::Edge => MeasureKind::Edge,
555            };
556            let density = self.metadata.density(name);
557            self.pending_query.insert(id, name.to_string());
558            self.runner.submit_query(MeasureQuery {
559                id,
560                kind: measure_kind,
561                owner,
562                entity: name.to_string(),
563                density,
564            });
565        }
566        self.pump_queries();
567        match self.info_cache.get(name) {
568            Some(resolved) => resolved.clone(),
569            None => serde_json::json!({ "ok": false, "name": name, "pending": true }).to_string(),
570        }
571    }
572
573    /// Drain every completed measurement reply from the runner and fold it into the
574    /// name-keyed info cache — the query counterpart of [`EngineState::pump`]. Called
575    /// once per frame from `pump` AND synchronously from
576    /// [`Self::object_info_json`] (so the Inline runner resolves same-call). Each
577    /// reply is MERGED with the main-injected `name` + `creatingFeature` (from the
578    /// eager provenance) into the final object-info JSON.
579    pub fn pump_queries(&mut self) {
580        while let Some(reply) = self.runner.poll_query() {
581            let Some(name) = self.pending_query.remove(&reply.id) else {
582                // A reply whose request was invalidated (a rerun cleared the pending
583                // set) — drop it; the re-selection re-queries against fresh geometry.
584                continue;
585            };
586            let fragment: Value = serde_json::from_str(&reply.result).unwrap_or(Value::Null);
587            let merged = self.merge_info(&name, &fragment);
588            self.info_cache.insert(name, merged);
589        }
590    }
591
592    /// Merge a runner measurement FRAGMENT with the main-side `name` +
593    /// `creatingFeature` into the final object-info JSON, preserving the exact field
594    /// ORDER the pre-seam `object_info_json` emitted (so the output is
595    /// byte-identical): `ok`, then `name`, then the fragment's remaining fields in
596    /// order (`kind`, the measurements — or `message` on error), then
597    /// `creatingFeature` (only when `ok`, since an error record carries none).
598    fn merge_info(&self, name: &str, fragment: &Value) -> String {
599        let object = fragment.as_object();
600        let ok = object
601            .and_then(|map| map.get("ok"))
602            .and_then(Value::as_bool)
603            .unwrap_or(false);
604        let mut merged = serde_json::Map::new();
605        merged.insert("ok".to_string(), Value::Bool(ok));
606        merged.insert("name".to_string(), Value::String(name.to_string()));
607        if let Some(map) = object {
608            for (key, value) in map {
609                if key == "ok" {
610                    continue;
611                }
612                merged.insert(key.clone(), value.clone());
613            }
614        }
615        if ok {
616            merged.insert(
617                "creatingFeature".to_string(),
618                // Resolve by ENTITY NAME (not `owner`): a face/edge reports its
619                // ORIGIN, a solid its producer — the same correction the context bar
620                // gets, so the Info tab's `creatingFeature` agrees.
621                self.creating_feature_value(name),
622            );
623        }
624        Value::Object(merged).to_string()
625    }
626
627    /// Properties info for a committed-sketch SHEET object (the sheet solid, its
628    /// planar face, or a boundary edge), measured off the synthesized display — a
629    /// sketch carries no resident kernel geometry. `kind:"sketch"` for the whole
630    /// sheet (area + total edge length, NO volume); `"face"` for its planar face;
631    /// `"edge"` for a boundary edge. Provenance is the sketch feature itself.
632    fn sketch_info_json(
633        &self,
634        name: &str,
635        kind: ObjectKind,
636        solid: &crate::scene::SolidDisplay,
637    ) -> String {
638        let creating = serde_json::json!({
639            "id": solid.name,
640            "type": self.feature_type_of(&solid.name),
641        });
642        let edge_total: f64 = solid.edges.iter().map(|e| polyline_length(&e.polyline)).sum();
643        match kind {
644            ObjectKind::Solid => serde_json::json!({
645                "ok": true,
646                "name": name,
647                "kind": "sketch",
648                "area": sheet_mesh_area(solid),
649                "edgeLengthTotal": edge_total,
650                "creatingFeature": creating,
651            })
652            .to_string(),
653            ObjectKind::Face => serde_json::json!({
654                "ok": true,
655                "name": name,
656                "kind": "face",
657                "solid": solid.name,
658                // A committed sketch's sheet face is planar by construction.
659                "surfaceType": "Plane",
660                "area": sheet_mesh_area(solid),
661                "edgeLengthTotal": edge_total,
662                "creatingFeature": creating,
663            })
664            .to_string(),
665            ObjectKind::Edge => {
666                let length = solid
667                    .edges
668                    .iter()
669                    .find(|e| e.name == name)
670                    .map(|e| polyline_length(&e.polyline))
671                    .unwrap_or(0.0);
672                serde_json::json!({
673                    "ok": true,
674                    "name": name,
675                    "kind": "edge",
676                    "solid": solid.name,
677                    "length": length,
678                    "creatingFeature": creating,
679                })
680                .to_string()
681            }
682        }
683    }
684}
685
686/// Total surface area (mm²) of a synthesized sheet's planar display mesh — the
687/// sum of its triangle areas.
688fn sheet_mesh_area(solid: &crate::scene::SolidDisplay) -> f64 {
689    let p = &solid.mesh.positions;
690    solid
691        .mesh
692        .indices
693        .chunks_exact(3)
694        .map(|t| {
695            let a = p[t[0] as usize];
696            let b = p[t[1] as usize];
697            let c = p[t[2] as usize];
698            let ab = [
699                (b[0] - a[0]) as f64,
700                (b[1] - a[1]) as f64,
701                (b[2] - a[2]) as f64,
702            ];
703            let ac = [
704                (c[0] - a[0]) as f64,
705                (c[1] - a[1]) as f64,
706                (c[2] - a[2]) as f64,
707            ];
708            let cross = [
709                ab[1] * ac[2] - ab[2] * ac[1],
710                ab[2] * ac[0] - ab[0] * ac[2],
711                ab[0] * ac[1] - ab[1] * ac[0],
712            ];
713            (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5
714        })
715        .sum()
716}
717
718/// Arc length (mm) of a sampled edge polyline — the sum of its segment lengths.
719fn polyline_length(polyline: &[[f32; 3]]) -> f64 {
720    polyline
721        .windows(2)
722        .map(|w| {
723            let d = [
724                (w[1][0] - w[0][0]) as f64,
725                (w[1][1] - w[0][1]) as f64,
726                (w[1][2] - w[0][2]) as f64,
727            ];
728            (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt()
729        })
730        .sum()
731}
732