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 shown_color(metadata, name)
300 .and_then(crate::style::parse_css_hex)
301 // A derived BOARD body has a colour of its own and no producing
302 // feature to have coloured it, so without this fallback the
303 // pass would resolve it to `None` and the board would draw in
304 // the name-hashed default — green substrate and copper traces
305 // are the whole point of drawing it. A stored attribute still
306 // wins, so a user may recolour the board like anything else.
307 .or_else(|| crate::engine_state::board_default_color(name))
308 });
309 // `transparency` rides the same seam. It is not a colour, so the
310 // "override model colors" setting leaves it alone: a see-through body
311 // stays see-through in whatever colour the display gives it.
312 let changed = self.scene.apply_metadata_opacity(|name| {
313 metadata.attribute(name, TRANSPARENCY_METADATA_KEY).and_then(transparency_opacity)
314 }) || changed;
315 // An edge's own `color` and `transparency`: the stored attributes
316 // only (no board default), the colour hidden by the override.
317 let changed = self.scene.apply_metadata_edge_looks(
318 |name| if ignore { None } else { shown_color(metadata, name).and_then(crate::style::parse_css_hex) },
319 |name| metadata.attribute(name, TRANSPARENCY_METADATA_KEY).and_then(transparency_opacity),
320 ) || changed;
321 if changed {
322 self.dirty = true;
323 }
324 changed
325 }
326
327 /// The whole metadata store as JSON `{ name: { key: value } }`.
328 pub fn metadata_json(&self) -> String {
329 self.metadata.to_json_string()
330 }
331
332 /// [`Self::metadata_json`] as a JSON value.
333 pub fn metadata_value(&self) -> Value {
334 self.metadata.to_json()
335 }
336}
337
338/// The colour an entity shows: its own `color`, except that a Pattern
339/// Component instance's entity whose colour was not set on the instance itself
340/// (none, or still the `partColor` it took from its part) shows its SEED
341/// entity's colour, so a colour set on the seed in the assembly reaches every
342/// copy, and a copy of a copy through its own seed. A colour set on the
343/// instance wins.
344fn shown_color<'a>(metadata: &'a MetadataStore, name: &str) -> Option<&'a str> {
345 let own = metadata.attribute(name, COLOR_METADATA_KEY);
346 let set_on_instance = own.is_some() && own != metadata.attribute(name, PART_COLOR_METADATA_KEY);
347 if !set_on_instance {
348 if let Some(color) = pattern_seed_entity(name).and_then(|seed| shown_color(metadata, &seed)) {
349 return Some(color);
350 }
351 }
352 own
353}
354
355/// The marker the kernel stamps on a component entity's colour taken from
356/// its part (`assembly_component::PART_COLOR_KEY`).
357const PART_COLOR_METADATA_KEY: &str = "partColor";
358
359/// The seed entity a Pattern Component instance's entity copies:
360/// `APAT5.ACOMP3.i2:F9` → `ACOMP3:F9`; `None` for anything else.
361fn pattern_seed_entity(name: &str) -> Option<String> {
362 let (head, rest) = name.split_once(':')?;
363 let (_, seed, _) = brep_kernel::pattern_component_instance(head)?;
364 Some(format!("{seed}:{rest}"))
365}
366
367// --- EngineState: measurements + provenance (SEPARATE impl block) ------------
368impl EngineState {
369 /// Resolve an object NAME to `(kind, owning solid name)` via the display
370 /// scene: a solid resolves to itself; a face/edge resolves to its owning
371 /// solid. `None` for an empty or unknown name (vertices carry no kernel name).
372 fn resolve_object(&self, name: &str) -> Option<(ObjectKind, String)> {
373 if name.is_empty() {
374 return None;
375 }
376 if self.scene.solid(name).is_some() {
377 return Some((ObjectKind::Solid, name.to_string()));
378 }
379 for solid in self.scene.solids() {
380 if solid.faces.iter().any(|face| face.name == name) {
381 return Some((ObjectKind::Face, solid.name.clone()));
382 }
383 }
384 for solid in self.scene.solids() {
385 if solid.edges.iter().any(|edge| edge.name == name) {
386 return Some((ObjectKind::Edge, solid.name.clone()));
387 }
388 }
389 None
390 }
391
392 /// The feature that an object ORIGINATES from, as `(feature id, feature type)`.
393 /// For a FACE/EDGE this is the feature that first gave it its name (its true
394 /// origin, from the eager `entity_origin` first-writer map) — NOT the owning
395 /// solid's last producer — so "Edit owning feature" rolls back to where the
396 /// entity was born. For a SOLID it's the solid's producer (last writer, the
397 /// eager `provenance` map). `None` if the name is unknown or has no known
398 /// producer. Reads only the eager maps the last run shipped, so it never re-runs
399 /// the history — the freeze side-door `context_bar` hit every selected frame is
400 /// now O(1).
401 pub fn creating_feature(&self, name: &str) -> Option<(String, String)> {
402 let Some((kind, owner)) = self.resolve_object(name) else {
403 // A datum / construction PLANE (or one plane of a datum) is not a
404 // resident solid/face/edge — it's a named frame. Its producer is the
405 // D/P feature that emitted the frame (same fallback object_info_json
406 // uses), so "Edit owning feature" resolves for a lone plane pick too.
407 return self.datum_feature_for_name(name);
408 };
409 let id = match kind {
410 // A face/edge resolves to its ORIGIN. Fall back to the owning solid's
411 // producer when the name is somehow absent from `entity_origin` (keeps
412 // the "Edit owning feature" button from vanishing).
413 ObjectKind::Face | ObjectKind::Edge => self
414 .entity_origin
415 .get(name)
416 .cloned()
417 .or_else(|| self.provenance.get(&owner).cloned())?,
418 // A solid keeps its existing last-writer producer semantics.
419 ObjectKind::Solid => self.provenance.get(&owner)?.clone(),
420 };
421 Some((id.clone(), self.feature_type_of(&id)))
422 }
423
424 /// Whether the object `name` (a solid, or a face/edge owned by a solid) sits
425 /// on a SHEET-METAL body — its owning display solid carries the sheet-metal
426 /// marker the pipeline stamped from the resident handle's `SheetTree`. Reads
427 /// only the display scene, so it is O(1) and thread-safe (no `SheetTree`
428 /// thread-local touched on the UI thread — [`crate::scene::SolidDisplay::
429 /// is_sheet_metal`]). The gate for the sheet-metal edit features (SM Flange /
430 /// Fillet / Chamfer). `false` for an unknown name or a synthesized sketch
431 /// sheet (no resident handle, no tree).
432 pub fn is_sheet_metal_object(&self, name: &str) -> bool {
433 self.resolve_object(name)
434 .and_then(|(_, owner)| self.scene.solid(&owner))
435 .is_some_and(|solid| solid.is_sheet_metal)
436 }
437
438 /// A feature's type token by id (empty string if the id is not in the history).
439 fn feature_type_of(&self, id: &str) -> String {
440 self.history
441 .index_of(id)
442 .and_then(|index| self.history.feature_type(index))
443 .unwrap_or_default()
444 }
445
446 /// The `{ id, type }` provenance JSON for an object by NAME (or `null` if it has
447 /// no known producer). Delegates to [`creating_feature`](Self::creating_feature)
448 /// so a face/edge reports its ORIGIN (first-writer) and a solid its producer
449 /// (last-writer) — one resolver, so the Info tab and the context bar agree.
450 fn creating_feature_value(&self, name: &str) -> Value {
451 match self.creating_feature(name) {
452 Some((id, ty)) => serde_json::json!({ "id": id, "type": ty }),
453 None => Value::Null,
454 }
455 }
456
457 /// The full Properties-panel info for an object by NAME: its resolved kind,
458 /// the right measurements, and provenance. Units are millimetres.
459 ///
460 /// - **Solid** — `{ ok, name, kind:"solid", volume, surfaceArea,
461 /// edgeLengthTotal, density, weight, creatingFeature }`, where
462 /// `weight = density · volume` and `density` comes from the object's
463 /// metadata (default [`DEFAULT_DENSITY`]).
464 /// - **Face** — `{ ok, name, kind:"face", solid, surfaceType, area,
465 /// edgeLengthTotal, creatingFeature }` (`edgeLengthTotal` = its boundary
466 /// edges; `surfaceType` = the carrier-surface classification, e.g.
467 /// `"Plane"`/`"Cylinder"`/`"Cone"`/`"Sphere"`/`"Torus"`/`"NURBS"`), plus
468 /// the carrier's dimensions when it has them: `radius` + `diameter`
469 /// (cylinder, sphere), `halfAngleDeg` (cone), `majorRadius` +
470 /// `minorRadius` (torus).
471 /// - **Edge** — `{ ok, name, kind:"edge", solid, length, creatingFeature }`,
472 /// plus `curveType` (`"Circle"`/`"Arc"`), `radius`, `diameter` and an
473 /// arc's `sweepDeg` when the edge lies on a circle.
474 ///
475 /// `{ ok:false, name, message }` for an empty/unknown name, a non-resident
476 /// solid, or a kernel measurement failure.
477 ///
478 /// The real solid/face/edge MEASUREMENT is routed to the [`HistoryRunner`] (so
479 /// the warm-registry runner answers it, never the potentially-cold main side)
480 /// and CACHED here keyed by name — fired once per selection, served from the
481 /// cache every subsequent frame. For the synchronous
482 /// [`InlineRunner`](crate::runner::InlineRunner) the submit → `pump_queries`
483 /// resolves same-call, so this returns the merged JSON immediately and stays
484 /// byte-identical to the pre-seam in-process result; a background
485 /// [`ThreadRunner`](crate::runner::ThreadRunner) returns a `pending` placeholder
486 /// for the frame(s) until its reply lands (drained by `pump_queries`). The cache
487 /// is invalidated on any geometry change (`apply_run_output`) or metadata edit
488 /// (`set_metadata_attribute`).
489 ///
490 /// [`HistoryRunner`]: crate::runner::HistoryRunner
491 pub fn object_info_json(&mut self, name: &str) -> String {
492 let raw = self.object_info_raw_json(name);
493 self.with_part_mass(name, raw)
494 }
495
496 /// A SOLID's info carries the mass the part's density gives it (see
497 /// `engine_state::part_mass`): `density` (g/cm³, `null` when none
498 /// resolves), `densitySource` (`solid` | `part` | `material`), `mass` (kg)
499 /// and, with no number, `massNote` saying why. The runner's unit-density
500 /// `weight` is not reported: the BOM and this window read ONE density.
501 fn with_part_mass(&self, name: &str, raw: String) -> String {
502 let Ok(mut info) = serde_json::from_str::<Value>(&raw) else {
503 return raw;
504 };
505 if info.get("ok").and_then(Value::as_bool) != Some(true)
506 || info.get("kind").and_then(Value::as_str) != Some("solid")
507 {
508 return raw;
509 }
510 let volume = info.get("volume").and_then(Value::as_f64);
511 let resolved = self.solid_density(name);
512 if let Some(object) = info.as_object_mut() {
513 object.remove("weight");
514 object.insert(
515 "density".into(),
516 resolved.map(|(density, _)| Value::from(density)).unwrap_or(Value::Null),
517 );
518 object.insert(
519 "densitySource".into(),
520 resolved
521 .map(|(_, source)| Value::from(source.as_str()))
522 .unwrap_or(Value::Null),
523 );
524 let mass = volume.zip(resolved).map(|(v, (d, _))| v * d * 1e-6);
525 object.insert("mass".into(), mass.map(Value::from).unwrap_or(Value::Null));
526 if mass.is_none() {
527 object.insert(
528 "massNote".into(),
529 Value::from("no density: set the part's Material or Density"),
530 );
531 }
532 }
533 info.to_string()
534 }
535
536 /// [`Self::object_info_json`] without the part-density fold: the runner's
537 /// measurement as cached.
538 pub(crate) fn object_info_raw_json(&mut self, name: &str) -> String {
539 let Some((kind, owner)) = self.resolve_object(name) else {
540 // A construction datum/plane carries no resident geometry (no volume /
541 // area / length), so it never resolves as a solid/face/edge. Return a
542 // graceful minimal record — name + kind + creating feature — rather than
543 // erroring, so the Properties Info tab renders for a selected datum and
544 // its name flows into the (name-keyed) Metadata tab.
545 if let Some((feature_id, feature_type)) = self.datum_feature_for_name(name) {
546 let kind_label = if feature_type == "P" { "plane" } else { "datum" };
547 return serde_json::json!({
548 "ok": true,
549 "name": name,
550 "kind": kind_label,
551 "creatingFeature": { "id": feature_id, "type": feature_type },
552 })
553 .to_string();
554 }
555 return serde_json::json!({
556 "ok": false, "name": name, "message": "unknown object",
557 })
558 .to_string();
559 };
560 // A committed-sketch SHEET is a scene solid with NO kernel handle, so the
561 // handle-based measurement path can't serve it. Measure straight off its
562 // synthesized display (planar-mesh triangle areas / edge polylines) and
563 // report `kind:"sketch"` — no volume. Handle-less ⇒ synchronous, no query.
564 if let Some(solid) = self.scene.solid(&owner) {
565 if solid.is_sketch {
566 return self.sketch_info_json(name, kind, solid);
567 }
568 }
569
570 // Real geometry: serve from the info cache, else fire a measurement query at
571 // the runner (deduped: never submit a second query for a name already in
572 // flight), pump, and return the resolved JSON — or a pending placeholder.
573 if let Some(cached) = self.info_cache.get(name) {
574 return cached.clone();
575 }
576 if !self.pending_query.values().any(|pending| pending == name) {
577 self.next_query_id += 1;
578 let id = self.next_query_id;
579 let measure_kind = match kind {
580 ObjectKind::Solid => MeasureKind::Solid,
581 ObjectKind::Face => MeasureKind::Face,
582 ObjectKind::Edge => MeasureKind::Edge,
583 };
584 let density = self.metadata.density(name);
585 self.pending_query.insert(id, name.to_string());
586 self.runner.submit_query(MeasureQuery {
587 id,
588 kind: measure_kind,
589 owner,
590 entity: name.to_string(),
591 density,
592 });
593 }
594 self.pump_queries();
595 match self.info_cache.get(name) {
596 Some(resolved) => resolved.clone(),
597 None => serde_json::json!({ "ok": false, "name": name, "pending": true }).to_string(),
598 }
599 }
600
601 /// Drain every completed measurement reply from the runner and fold it into the
602 /// name-keyed info cache — the query counterpart of [`EngineState::pump`]. Called
603 /// once per frame from `pump` AND synchronously from
604 /// [`Self::object_info_json`] (so the Inline runner resolves same-call). Each
605 /// reply is MERGED with the main-injected `name` + `creatingFeature` (from the
606 /// eager provenance) into the final object-info JSON.
607 pub fn pump_queries(&mut self) {
608 while let Some(reply) = self.runner.poll_query() {
609 let Some(name) = self.pending_query.remove(&reply.id) else {
610 // A reply whose request was invalidated (a rerun cleared the pending
611 // set) — drop it; the re-selection re-queries against fresh geometry.
612 continue;
613 };
614 let fragment: Value = serde_json::from_str(&reply.result).unwrap_or(Value::Null);
615 let merged = self.merge_info(&name, &fragment);
616 self.info_cache.insert(name, merged);
617 }
618 }
619
620 /// Merge a runner measurement FRAGMENT with the main-side `name` +
621 /// `creatingFeature` into the final object-info JSON, preserving the exact field
622 /// ORDER the pre-seam `object_info_json` emitted (so the output is
623 /// byte-identical): `ok`, then `name`, then the fragment's remaining fields in
624 /// order (`kind`, the measurements — or `message` on error), then
625 /// `creatingFeature` (only when `ok`, since an error record carries none).
626 fn merge_info(&self, name: &str, fragment: &Value) -> String {
627 let object = fragment.as_object();
628 let ok = object
629 .and_then(|map| map.get("ok"))
630 .and_then(Value::as_bool)
631 .unwrap_or(false);
632 let mut merged = serde_json::Map::new();
633 merged.insert("ok".to_string(), Value::Bool(ok));
634 merged.insert("name".to_string(), Value::String(name.to_string()));
635 if let Some(map) = object {
636 for (key, value) in map {
637 if key == "ok" {
638 continue;
639 }
640 merged.insert(key.clone(), value.clone());
641 }
642 }
643 if ok {
644 merged.insert(
645 "creatingFeature".to_string(),
646 // Resolve by ENTITY NAME (not `owner`): a face/edge reports its
647 // ORIGIN, a solid its producer — the same correction the context bar
648 // gets, so the Info tab's `creatingFeature` agrees.
649 self.creating_feature_value(name),
650 );
651 }
652 Value::Object(merged).to_string()
653 }
654
655 /// Properties info for a committed-sketch SHEET object (the sheet solid, its
656 /// planar face, or a boundary edge), measured off the synthesized display — a
657 /// sketch carries no resident kernel geometry. `kind:"sketch"` for the whole
658 /// sheet (area + total edge length, NO volume); `"face"` for its planar face;
659 /// `"edge"` for a boundary edge. Provenance is the sketch feature itself.
660 fn sketch_info_json(
661 &self,
662 name: &str,
663 kind: ObjectKind,
664 solid: &crate::scene::SolidDisplay,
665 ) -> String {
666 let creating = serde_json::json!({
667 "id": solid.name,
668 "type": self.feature_type_of(&solid.name),
669 });
670 let edge_total: f64 = solid.edges.iter().map(|e| polyline_length(&e.polyline)).sum();
671 match kind {
672 ObjectKind::Solid => serde_json::json!({
673 "ok": true,
674 "name": name,
675 "kind": "sketch",
676 "area": sheet_mesh_area(solid),
677 "edgeLengthTotal": edge_total,
678 "creatingFeature": creating,
679 })
680 .to_string(),
681 ObjectKind::Face => serde_json::json!({
682 "ok": true,
683 "name": name,
684 "kind": "face",
685 "solid": solid.name,
686 // A committed sketch's sheet face is planar by construction.
687 "surfaceType": "Plane",
688 "area": sheet_mesh_area(solid),
689 "edgeLengthTotal": edge_total,
690 "creatingFeature": creating,
691 })
692 .to_string(),
693 ObjectKind::Edge => {
694 let length = solid
695 .edges
696 .iter()
697 .find(|e| e.name == name)
698 .map(|e| polyline_length(&e.polyline))
699 .unwrap_or(0.0);
700 serde_json::json!({
701 "ok": true,
702 "name": name,
703 "kind": "edge",
704 "solid": solid.name,
705 "length": length,
706 "creatingFeature": creating,
707 })
708 .to_string()
709 }
710 }
711 }
712}
713
714/// Total surface area (mm²) of a synthesized sheet's planar display mesh — the
715/// sum of its triangle areas.
716fn sheet_mesh_area(solid: &crate::scene::SolidDisplay) -> f64 {
717 let p = &solid.mesh.positions;
718 solid
719 .mesh
720 .indices
721 .chunks_exact(3)
722 .map(|t| {
723 let a = p[t[0] as usize];
724 let b = p[t[1] as usize];
725 let c = p[t[2] as usize];
726 let ab = [
727 (b[0] - a[0]) as f64,
728 (b[1] - a[1]) as f64,
729 (b[2] - a[2]) as f64,
730 ];
731 let ac = [
732 (c[0] - a[0]) as f64,
733 (c[1] - a[1]) as f64,
734 (c[2] - a[2]) as f64,
735 ];
736 let cross = [
737 ab[1] * ac[2] - ab[2] * ac[1],
738 ab[2] * ac[0] - ab[0] * ac[2],
739 ab[0] * ac[1] - ab[1] * ac[0],
740 ];
741 (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5
742 })
743 .sum()
744}
745
746/// Arc length (mm) of a sampled edge polyline — the sum of its segment lengths.
747fn polyline_length(polyline: &[[f32; 3]]) -> f64 {
748 polyline
749 .windows(2)
750 .map(|w| {
751 let d = [
752 (w[1][0] - w[0][0]) as f64,
753 (w[1][1] - w[0][1]) as f64,
754 (w[1][2] - w[0][2]) as f64,
755 ];
756 (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt()
757 })
758 .sum()
759}
760