1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use super::*;
impl EngineState {
/// Ranked candidate list under CSS-pixel `(x, y)`, kernel names, priority
/// VERTEX > EDGE > FACE > … > SOLID. Feeds the host's multi-candidate popup.
pub fn pick_json(&self, x: f64, y: f64) -> String {
let candidates = pick::pick(&self.scene, &self.camera, x, y, &self.pick_options());
pick::candidates_to_json(&candidates)
}
/// The single best candidate under `(x, y)` (hover), or `null`.
pub fn hover_json(&self, x: f64, y: f64) -> String {
let candidates = pick::pick(&self.scene, &self.camera, x, y, &self.pick_options());
match candidates.first() {
Some(best) => pick::candidates_to_json(std::slice::from_ref(best))
.strip_prefix('[')
.and_then(|s| s.strip_suffix(']'))
.map(str::to_string)
.unwrap_or_else(|| "null".to_string()),
None => "null".to_string(),
}
}
// --- Settings / emphasis / visibility (R11/R14/R17) -------------------
pub fn apply_settings_json(&mut self, json: &str) -> Result<(), String> {
let prev_lod = self.settings.lod_factor;
self.settings.apply_json(json)?;
self.settings_generation = self.settings_generation.wrapping_add(1);
self.dirty = true;
// Projection rides in the settings JSON as `orthographic` (see `settings_json`)
// so the toolbar toggle AND a reload both go through this ONE apply path — the
// same way wireframe does. It is NOT a `RenderSettings` field: read it straight
// off the JSON and drive the camera. A PARTIAL apply (the wireframe toggle's
// `{"wireframe":true}`) omits the key and leaves the projection untouched, and
// the panel's full-buffer apply carries the live value (so it's a no-op).
if let Some(want_ortho) = serde_json::from_str::<serde_json::Value>(json)
.ok()
.and_then(|v| v.get("orthographic").and_then(|o| o.as_bool()))
{
let is_ortho = matches!(
self.camera.projection,
crate::view::Projection::Orthographic { .. }
);
if want_ortho != is_ortho {
self.set_projection(if want_ortho { "orthographic" } else { "perspective" });
}
}
// The LOD factor scales DISPLAY tessellation, so a change must re-run so the
// resident meshes re-tessellate at the new chord tolerance (the runner drops
// its reuse baseline when the lod differs). Every OTHER setting is pure
// render state and needs no re-run. Skip the re-run when there are no
// features (e.g. boot restores a saved `lodFactor` before any document is
// loaded): the run would be empty, and the real doc load re-runs with the
// lod already injected.
if self.settings.lod_factor != prev_lod && !self.history.is_empty() {
self.rerun_history();
}
// Sketch colors live in the settings too: when a sketch is being edited, push
// the (possibly) new palette into the live session and re-push the overlay so
// an edited color takes effect immediately (mirrors how a wireframe/lod change
// refreshes the view). Compute the palette first to avoid a split borrow.
if self.sketch_edit.is_some() {
let colors = self.settings.sketch_colors();
if let Some(edit) = self.sketch_edit.as_mut() {
edit.session.colors = colors;
}
self.refresh_sketch_overlay();
}
Ok(())
}
/// The FULL current settings as JSON (the round-trip counterpart of
/// [`apply_settings_json`]): the schema-driven form seeds its widgets from
/// this and the storage seam persists it.
pub fn settings_json(&self) -> String {
// Projection is live CAMERA state surfaced to the settings layer as a boolean
// (`orthographic`) so the toolbar toggle persists and the settings panel can
// round-trip it without clobbering. DERIVE it from the camera here — it is
// never a stored `RenderSettings` field — so it can NEVER drift from the
// actual projection no matter which code path last changed it.
let mut value: serde_json::Value =
serde_json::from_str(&self.settings.to_json()).unwrap_or(serde_json::Value::Null);
if let Some(obj) = value.as_object_mut() {
obj.insert(
"orthographic".into(),
serde_json::Value::Bool(matches!(
self.camera.projection,
crate::view::Projection::Orthographic { .. }
)),
);
}
value.to_string()
}
/// The current per-solid metadata color overrides as JSON —
/// `[{"name": "...", "override": "#rrggbb" | null}, …]`. Lets a UI list the
/// scene's solids with their current override so the picker reflects state.
pub fn solid_color_overrides_json(&self) -> String {
let solids: Vec<serde_json::Value> = self
.scene
.solids()
.iter()
.map(|solid| {
let over = solid.color_override.map(|rgb| {
let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
format!("#{:02x}{:02x}{:02x}", q(rgb[0]), q(rgb[1]), q(rgb[2]))
});
serde_json::json!({ "name": solid.name, "override": over })
})
.collect();
serde_json::Value::Array(solids).to_string()
}
pub fn apply_emphasis_json(&mut self, json: &str) -> Result<(), String> {
self.emphasis.apply_json(json)?;
self.dirty = true;
Ok(())
}
pub fn set_visible(&mut self, name: &str, visible: bool) -> bool {
let ok = self.scene.set_visible(name, visible);
if ok {
self.dirty = true;
}
ok
}
/// Set (or clear) a solid's LIVE per-solid color override (R14) without a
/// history rerun — the app assigning a metadata color updates the view
/// immediately. `color_hex` is a CSS hex string (`#rrggbb`); `None` or an
/// empty/unparseable string clears back to the hashed/uniform base color.
/// Marks dirty; returns false if the solid name is unknown.
pub fn set_color_override(&mut self, name: &str, color_hex: Option<&str>) -> bool {
let color = match color_hex {
Some(hex) if !hex.trim().is_empty() => crate::style::parse_css_hex(hex),
_ => None,
};
let ok = self.scene.set_color_override(name, color);
if ok {
self.dirty = true;
}
ok
}
pub fn scene_listing_json(&self) -> String {
self.scene.listing_json()
}
// --- Overlay widgets --------------------------------------------------
/// The bbox the camera depth-range fit should use: the visible SOLIDS unioned
/// with the pushed OVERLAY groups (sketch curves/points, dimension leaders,
/// constraint glyphs). Folding in the overlay stops orbiting an editing sketch
/// from clipping it against the solids-only bounds (the reported clipping when
/// "Lock to sketch" is off). Callers must bind this to a local before
/// `camera.fit_depth_range` (which needs `&mut self.camera`).
pub fn depth_range_bbox(&self) -> crate::camera::Aabb {
let mut bbox = self.scene.bbox();
bbox.union(&self.widgets.overlay_groups_bbox());
bbox
}
}
// ============================================================================
// Scene-tree accessors (appended — see the engine-native Scene panel slice).
// Kept as a SEPARATE `impl` block so concurrent panel work does not conflict
// with the primary surface above; purely additive over the existing
// scene / emphasis API (`scene_listing_json`, `set_visible`, `selection_json`,
// `clear_selection`, `apply_emphasis_json`).
// ============================================================================
impl EngineState {
/// A RICHER scene listing than [`scene_listing_json`](Self::scene_listing_json)
/// (which is counts only): per solid the individual face + edge kernel NAMES
/// and vertex refs (topo id + world position), plus visibility — the shape the
/// engine-native Scene tree lists entities from and the headed verifier asserts
/// against. Vertices carry no kernel name, so they are keyed by topo id + world
/// position (the same shape the emphasis vertex-ref selection uses).
pub fn scene_entities_json(&self) -> String {
let solids: Vec<serde_json::Value> = self
.scene
.solids()
.iter()
// Committed-sketch SHEETS are scene solids (pickable/measurable) but list
// under "Sketches" (`committed_sketches`), not among the real solids.
.filter(|solid| !solid.is_sketch)
.map(|solid| {
let faces: Vec<&str> = solid.faces.iter().map(|f| f.name.as_str()).collect();
let edges: Vec<&str> = solid.edges.iter().map(|e| e.name.as_str()).collect();
let vertices: Vec<serde_json::Value> = solid
.vertices
.iter()
.map(|v| serde_json::json!({ "topoId": v.topo_id, "position": v.position }))
.collect();
serde_json::json!({
"name": solid.name,
"visible": solid.visible,
"faces": faces,
"edges": edges,
"vertices": vertices,
})
})
.collect();
serde_json::Value::Array(solids).to_string()
}
/// Drive the engine SELECTION by kernel NAME from a UI tree (the name-based
/// analogue of [`select_top_at`](Self::select_top_at), which picks under the
/// cursor). Replaces the current selection with the single named `solid` /
/// `face` / `edge` so clicking a Scene-tree row highlights that entity in the
/// viewport (the render pass reads `emphasis`). Vertices have no kernel name —
/// use [`select_vertex_by_position`](Self::select_vertex_by_position). Returns
/// false for an unknown `kind` or an empty `name`.
pub fn select_by_name(&mut self, kind: &str, name: &str) -> bool {
// A construction datum/plane routes to its own name-keyed selection.
if kind == "datum" {
return self.select_datum(name);
}
if name.is_empty() || !matches!(kind, "solid" | "face" | "edge") {
return false;
}
let had_datum = !self.emphasis.selected_datums.is_empty();
self.emphasis.selected_solids.clear();
self.emphasis.selected_faces.clear();
self.emphasis.selected_edges.clear();
self.emphasis.selected_vertices.clear();
self.emphasis.selected_datums.clear();
match kind {
"solid" => {
self.emphasis.selected_solids.insert(name.to_string());
}
"face" => {
self.emphasis.selected_faces.insert(name.to_string());
}
"edge" => {
self.emphasis.selected_edges.insert(name.to_string());
}
_ => unreachable!(),
}
self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
self.dirty = true;
if had_datum {
self.refresh_construction_datums();
}
true
}
/// Select a single vertex by its owning solid + world position — vertices have
/// no kernel name, so emphasis keys them by solid + position (matched with a
/// tolerance in the render pass). Replaces the current selection. Returns false
/// for an empty solid name.
pub fn select_vertex_by_position(&mut self, solid: &str, position: [f64; 3]) -> bool {
if solid.is_empty() {
return false;
}
let had_datum = !self.emphasis.selected_datums.is_empty();
self.emphasis.selected_solids.clear();
self.emphasis.selected_faces.clear();
self.emphasis.selected_edges.clear();
self.emphasis.selected_vertices.clear();
self.emphasis.selected_datums.clear();
self.emphasis.selected_vertices.push(crate::style::VertexRef {
solid: solid.to_string(),
position,
});
self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
self.dirty = true;
if had_datum {
self.refresh_construction_datums();
}
true
}
}
// Scene-tree accessor tests — kept in their OWN module (appended) so they do not
// conflict with the primary `mod tests` above.
#[cfg(test)]
mod scene_tree_tests {
use super::*;
fn cube_history(name: &str) -> String {
serde_json::json!({
"expressions": "",
"configurator": {},
"features": [{
"type": "P.CU",
"inputParams": {
"id": name,
"sizeX": 10.0, "sizeY": 10.0, "sizeZ": 10.0,
"transform": {
"position": [0.0, 0.0, 0.0],
"rotationEuler": [0.0, 0.0, 0.0],
"scale": [1.0, 1.0, 1.0]
},
"boolean": { "targets": [], "operation": "NONE" }
},
"persistentData": {}
}]
})
.to_string()
}
#[test]
fn scene_entities_json_lists_solid_faces_edges_vertices() {
let mut engine = EngineState::new();
engine.set_history_json(&cube_history("Box")).unwrap();
let listing: serde_json::Value =
serde_json::from_str(&engine.scene_entities_json()).unwrap();
let arr = listing.as_array().unwrap();
assert_eq!(arr.len(), 1);
let solid = &arr[0];
assert_eq!(solid["name"], "Box");
assert_eq!(solid["visible"], true);
// A cube has 6 faces, 12 edges, 8 vertices.
assert_eq!(solid["faces"].as_array().unwrap().len(), 6);
assert_eq!(solid["edges"].as_array().unwrap().len(), 12);
assert_eq!(solid["vertices"].as_array().unwrap().len(), 8);
// Each vertex ref carries a position triple.
assert_eq!(solid["vertices"][0]["position"].as_array().unwrap().len(), 3);
}
#[test]
fn select_by_name_solid_sets_emphasis_and_replaces() {
let mut engine = EngineState::new();
engine.set_history_json(&cube_history("Box")).unwrap();
assert!(engine.select_by_name("solid", "Box"));
assert!(engine.emphasis.selected_solids.contains("Box"));
// A second solid selection REPLACES the first (single-select).
engine.emphasis.selected_faces.insert("stale".into());
assert!(engine.select_by_name("solid", "Box"));
assert!(engine.emphasis.selected_faces.is_empty());
}
#[test]
fn select_by_name_rejects_unknown_kind_or_empty_without_clearing() {
let mut engine = EngineState::new();
engine.set_history_json(&cube_history("Box")).unwrap();
engine.select_by_name("solid", "Box");
// An unknown kind / empty name is a no-op that keeps the current selection.
assert!(!engine.select_by_name("blob", "Box"));
assert!(!engine.select_by_name("solid", ""));
assert!(engine.emphasis.selected_solids.contains("Box"));
}
#[test]
fn select_vertex_by_position_records_vertex_ref() {
let mut engine = EngineState::new();
engine.set_history_json(&cube_history("Box")).unwrap();
assert!(engine.select_vertex_by_position("Box", [1.0, 2.0, 3.0]));
assert_eq!(engine.emphasis.selected_vertices.len(), 1);
let vr = &engine.emphasis.selected_vertices[0];
assert_eq!(vr.solid, "Box");
assert_eq!(vr.position, [1.0, 2.0, 3.0]);
// Empty solid name is rejected.
assert!(!engine.select_vertex_by_position("", [0.0, 0.0, 0.0]));
}
#[test]
fn set_visible_toggles_solid_and_shows_in_listing() {
let mut engine = EngineState::new();
engine.set_history_json(&cube_history("Box")).unwrap();
assert!(engine.set_visible("Box", false));
let listing: serde_json::Value =
serde_json::from_str(&engine.scene_entities_json()).unwrap();
assert_eq!(listing[0]["visible"], false);
assert!(!engine.set_visible("Nope", false));
}
}
// ============================================================================
// Inspector mass properties (appended — see the Inspector-panel slice).
// SEPARATE `impl` block so concurrent panel work appending to the primary block
// does not conflict; purely additive over the existing history/scene API.
// ============================================================================
impl EngineState {
/// The resident kernel handle of every solid currently displayed, keyed by
/// name. Obtained by replaying the CURRENT rolled-to history prefix through
/// [`brep_kernel::execute_history`]: after a build the incremental cache
/// holds exactly this prefix, so the replay is a clean cache hit — it
/// re-tessellates nothing and hands back the SAME handles the scene was built
/// from (mirrors the pipeline's `fold_history`: removals then additions).
fn resident_solid_handles(&self) -> HashMap<String, u32> {
let request: HistoryRequest = match serde_json::from_value(self.history.prefix_request()) {
Ok(request) => request,
Err(_) => return HashMap::new(),
};
let result = brep_kernel::execute_history(&request);
let mut handles: HashMap<String, u32> = HashMap::new();
for feature in &result.results {
for removed in &feature.removed {
handles.remove(removed);
}
for added in &feature.added {
handles.insert(added.name.clone(), added.handle);
}
}
handles
}
/// Mass properties for the Inspector panel, from the kernel's exact
/// (divergence-theorem) integrator. `name = Some(solid)` reports that resident
/// solid; `None` reports the whole model. `density` (mass units per mm³; the
/// kernel length convention is millimetres) scales `mass` and the inertia
/// tensor — the centroid and principal axes are density-independent.
///
/// Returns JSON:
/// ```json
/// { "ok": true, "target": "Box", "solidCount": 1, "density": 1.0,
/// "volume": 5738.05, "surfaceArea": 2927.79, "mass": 5738.05,
/// "centroid": [10.0, 10.0, 10.0],
/// "inertia": [[..],[..],[..]] | null,
/// "principalMoments": [a,b,c] | null,
/// "principalAxes": [[..],[..],[..]] | null }
/// ```
/// A single resolved solid carries the full centroidal inertia tensor +
/// principal axes/moments; a multi-solid aggregate reports summed volume /
/// area / mass and the volume-weighted centroid, with the tensor fields
/// `null` (select one solid for its inertia). `ok:false` with a `message` on
/// no solids / an unknown name / an integrator failure.
pub fn mass_properties_json(&self, name: Option<&str>, density: f64) -> String {
let handles = self.resident_solid_handles();
// Resolve the target solids: a named solid (must be resident) or, for the
// whole model, every scene solid that has resident geometry (draw order).
let targets: Vec<String> = match name {
Some(name) if handles.contains_key(name) => vec![name.to_string()],
Some(name) => {
return serde_json::json!({
"ok": false,
"message": format!("solid '{name}' has no resident geometry"),
})
.to_string();
}
None => self
.scene
.solids()
.iter()
.map(|solid| solid.name.clone())
.filter(|name| handles.contains_key(name))
.collect(),
};
if targets.is_empty() {
return serde_json::json!({ "ok": false, "message": "no solids" }).to_string();
}
// Per-solid density mass properties straight from the kernel.
let mut props = Vec::with_capacity(targets.len());
for target in &targets {
match brep_kernel::mass_properties_handle_native(handles[target], density) {
Ok(properties) => props.push(properties),
Err(error) => {
return serde_json::json!({
"ok": false,
"message": format!("{target}: {error}"),
})
.to_string();
}
}
}
let target_label = if targets.len() == 1 {
targets[0].clone()
} else {
"(whole model)".to_string()
};
if props.len() == 1 {
// Single solid: the full tensor + principal frame are meaningful.
let p = &props[0];
serde_json::json!({
"ok": true,
"target": target_label,
"solidCount": 1,
"density": p.density,
"volume": p.volume,
"surfaceArea": p.surface_area,
"mass": p.mass,
"centroid": [p.centroid.x, p.centroid.y, p.centroid.z],
"inertia": p.inertia,
"principalMoments": p.principal_moments,
"principalAxes": p.principal_axes,
})
.to_string()
} else {
// Aggregate: additive scalars + volume-weighted centroid. Combining
// the tensors needs a parallel-axis shift per solid; left to the
// single-solid view rather than approximated here.
let volume: f64 = props.iter().map(|p| p.volume).sum();
let surface_area: f64 = props.iter().map(|p| p.surface_area).sum();
let mass: f64 = props.iter().map(|p| p.mass).sum();
let centroid = if volume.abs() > f64::EPSILON {
let mut acc = [0.0f64; 3];
for p in &props {
acc[0] += p.volume * p.centroid.x;
acc[1] += p.volume * p.centroid.y;
acc[2] += p.volume * p.centroid.z;
}
[acc[0] / volume, acc[1] / volume, acc[2] / volume]
} else {
[0.0, 0.0, 0.0]
};
serde_json::json!({
"ok": true,
"target": target_label,
"solidCount": props.len(),
"density": density,
"volume": volume,
"surfaceArea": surface_area,
"mass": mass,
"centroid": centroid,
"inertia": serde_json::Value::Null,
"principalMoments": serde_json::Value::Null,
"principalAxes": serde_json::Value::Null,
})
.to_string()
}
}
}
#[cfg(test)]
mod inspector_tests {
use super::*;
/// The same 3-feature seed the app boots with: a 20 mm cube `Box`, a r=6
/// h=30 cylinder `Pin` through its centre, and `Cut` = SUBTRACT(Box, [Pin]).
/// The SUBTRACT result reuses the target's name, so the final solid is `Box`.
fn seed_history() -> String {
serde_json::json!({
"expressions": "",
"configurator": {},
"features": [
{
"type": "P.CU",
"inputParams": {
"id": "Box",
"sizeX": 20.0, "sizeY": 20.0, "sizeZ": 20.0,
"transform": {
"position": [0.0, 0.0, 0.0],
"rotationEuler": [0.0, 0.0, 0.0],
"scale": [1.0, 1.0, 1.0]
},
"boolean": { "targets": [], "operation": "NONE" }
},
"persistentData": {}
},
{
"type": "P.CY",
"inputParams": {
"id": "Pin",
"radius": 6.0, "height": 30.0,
"transform": {
"position": [10.0, -5.0, 10.0],
"rotationEuler": [0.0, 0.0, 0.0],
"scale": [1.0, 1.0, 1.0]
},
"boolean": { "targets": [], "operation": "NONE" }
},
"persistentData": {}
},
{
"type": "B",
"inputParams": {
"id": "Cut",
"targetSolid": "Box",
"boolean": { "operation": "SUBTRACT", "targets": ["Pin"] }
},
"persistentData": {}
}
]
})
.to_string()
}
#[test]
fn seed_box_mass_properties_match_analytic_cube() {
let mut engine = EngineState::new();
engine.set_history_json(&seed_history()).unwrap();
// Roll back to just the plain 20 mm cube (before the hole).
engine.roll_to(0);
assert_eq!(engine.scene.solids().len(), 1);
let value: serde_json::Value =
serde_json::from_str(&engine.mass_properties_json(Some("Box"), 1.0)).unwrap();
assert_eq!(value["ok"], true);
assert_eq!(value["solidCount"], 1);
// 20 mm cube: V = 8000, A = 6·400 = 2400, centroid at the centre (10,10,10).
assert!((value["volume"].as_f64().unwrap() - 8000.0).abs() < 1e-6);
assert!((value["surfaceArea"].as_f64().unwrap() - 2400.0).abs() < 1e-6);
for component in value["centroid"].as_array().unwrap() {
assert!((component.as_f64().unwrap() - 10.0).abs() < 1e-6);
}
// A single solid carries the inertia tensor + principal frame.
assert!(value["inertia"].is_array());
assert!(value["principalAxes"].is_array());
// Density scales mass linearly (mass = density · volume).
let scaled: serde_json::Value =
serde_json::from_str(&engine.mass_properties_json(Some("Box"), 2.5)).unwrap();
assert!((scaled["mass"].as_f64().unwrap() - 2.5 * 8000.0).abs() < 1e-6);
}
#[test]
fn seed_boolean_result_is_cube_with_through_hole() {
let mut engine = EngineState::new();
engine.set_history_json(&seed_history()).unwrap();
// The full seed leaves one solid: the cube minus the pin.
assert_eq!(engine.scene.solids().len(), 1);
// No selection → whole model; with one solid that resolves to the single
// solid's full properties.
let value: serde_json::Value =
serde_json::from_str(&engine.mass_properties_json(None, 1.0)).unwrap();
assert_eq!(value["ok"], true);
assert_eq!(value["solidCount"], 1);
// V = cube − cylinder-through-hole = 8000 − π·6²·20.
let expected = 8000.0 - std::f64::consts::PI * 36.0 * 20.0;
assert!(
(value["volume"].as_f64().unwrap() - expected).abs() < 1e-2,
"hole volume {} vs {expected}",
value["volume"]
);
// Symmetric about the cube centre in X and Z.
let centroid = value["centroid"].as_array().unwrap();
assert!((centroid[0].as_f64().unwrap() - 10.0).abs() < 1e-6);
assert!((centroid[2].as_f64().unwrap() - 10.0).abs() < 1e-6);
}
#[test]
fn unknown_solid_reports_not_ok() {
let mut engine = EngineState::new();
engine.set_history_json(&seed_history()).unwrap();
let value: serde_json::Value =
serde_json::from_str(&engine.mass_properties_json(Some("Nope"), 1.0)).unwrap();
assert_eq!(value["ok"], false);
}
}
// ============================================================================
// Selection filter (which entity KINDS a plain viewport click may select) +
// the quick selection actions (clear / hide). Appended as its OWN type + a
// SEPARATE `impl` block so concurrent edits to the primary block don't conflict;
// purely additive over the existing selection/pick API.
//
// Mirrors the earlier `SelectionFilter.allowedSelectionTypes`: the picker reports
// EVERYTHING under the cursor (priority VERTEX > EDGE > FACE > SOLID), and the
// filter narrows what a click actually grabs. `select_top_at` reuses the
// existing `pick::pick_filtered` with the enabled kinds — the SAME type-
// constrained pick the reference-selection widget uses — so a click resolves the
// top-priority candidate whose kind is enabled and selects THAT kind (a FACE-only
// filter selects a face, a SOLID-only filter the owning solid).
// ============================================================================