Properties: moment of inertia, principal axes and first moments of a part or assembly (#8095) (#8103)

* claim: #8095

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Properties: moment of inertia, principal axes and first moments of a part or assembly (#8095)

component.properties and occurrence.properties report each closed body's
inertia tensor about its centre of mass, and in total the tensor about the
total centre of mass (world axes, g·mm²), its principal moments and axes,
the first moments, and with `about: [x, y, z]` the tensor about any point.
The tensor comes from each body's welded export mesh, tessellated once per
body, scaled to the measured mass and turned by each placement; bodies add
by parallel axes. The maths is a new crates/geom inertia module.

The Properties window shows the first moments, the tensor, the principal
moments and axes, and the view marks the centre of mass with the principal
axes while it is open. Inspect → Measure → Properties now opens that window
(it ran the command and showed nothing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Properties: Copy matrix, and the whole design's card titled just Properties (#8095)

Copy matrix, under the tensor, puts it on the clipboard as three lines of
tab-separated values at full precision, in the units shown. The card for
the whole design is titled Properties; one opened on a component,
placement or bodies keeps its name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Properties: measure beside the window, so a large assembly doesn't freeze it (#8095)

Properties ran on the window thread: 18 s on a 144-body design, with the
window answering nothing meanwhile (#5203). In the desktop app the card now
measures on a copy of the session on a worker, the way #4614 made agents'
measures work, says "Measuring…" until the reply is in, and Close drops it.
A quick measure still shows at once; headless, tests and the web measure in
place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ryan
2026-10-29 13:47:44 +00:00
committed by GitHub
parent be8bd43a18
commit 5e0e168ae9
18 changed files with 991 additions and 33 deletions
+2 -2
View File
@@ -78,10 +78,10 @@ pub static COMMANDS: &[CommandSpec] = &[
),
CommandSpec::new("component.properties", "Component Physical Properties", properties::component)
.icon("measure").noundo()
.params("component?: id or name (default active); descendants?: bool (default true). Measures the first placement, or all placements for root, including pending moves; material-aware mass and center of mass in world coordinates; volume, density, mass and center of mass only for closed, consistently oriented bodies; total.open_bodies_skipped counts open bodies excluded from volume/mass totals"),
.params("component?: id or name (default active); descendants?: bool (default true); about?: [x, y, z] (mm). Measures the first placement, or all placements for root, including pending moves; material-aware mass and center of mass in world coordinates; volume, density, mass, center of mass and inertia_g_mm2 (the inertia tensor about the body's center of mass, world axes, from its tessellation) only for closed, consistently oriented bodies; total.open_bodies_skipped counts open bodies excluded from volume/mass totals; total.first_moment_g_mm (mass × center of mass), inertia_g_mm2 about the total center of mass, principal_moments_g_mm2 (smallest first) and principal_axes (unit, right-handed); with about, total.inertia_about {point, inertia_g_mm2}"),
CommandSpec::new("occurrence.properties", "Occurrence Physical Properties", properties::occurrence)
.icon("measure").noundo()
.params("occurrence: id or name; path?: [occurrence ids] (required if nested under multiple instances); descendants?: bool (default true). Physical properties of this placement in world coordinates, including pending moves; volume, density, mass and center of mass only for closed, consistently oriented bodies; total.open_bodies_skipped counts open bodies excluded from volume/mass totals"),
.params("occurrence: id or name; path?: [occurrence ids] (required if nested under multiple instances); descendants?: bool (default true); about?: [x, y, z] (mm). Physical properties of this placement in world coordinates, including pending moves; volume, density, mass, center of mass and inertia_g_mm2 only for closed, consistently oriented bodies; total.open_bodies_skipped counts open bodies excluded from volume/mass totals; total inertia as in component.properties"),
CommandSpec::new("component.rename", "Rename Component", rename).icon("rename").params("component, name"),
CommandSpec::new("component.delete", "Delete Component", delete).icon("delete").params("component: deletes it, its subcomponents, occurrences and features"),
CommandSpec::new("component.unlock", "Unlock Contents", unlock).icon("rigid_group").params(
+66 -6
View File
@@ -1,6 +1,9 @@
//! Physical properties of an assembly placement, with original body material assignments.
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Value, json};
use solidcraft_doc::{Document, Mat};
use solidcraft_geom::inertia::{self, Tensor3};
use solidcraft_geom::{Aabb3, Vec3};
use crate::params::bad;
@@ -14,6 +17,23 @@ fn descendants(p: &Value, cmd: &str) -> Result<bool> {
}
}
/// Principal moments this close (a share of the largest) count as equal: a round body's
/// tessellation tells its two equal moments apart by about 1e-4, which turns their axes at random.
const EQUAL_MOMENTS: f64 = 1e-3;
/// The point `about` asks for the inertia tensor about, if any.
fn about(p: &Value, cmd: &str) -> Result<Option<Vec3>> {
match p.get("about") {
None | Some(Value::Null) => Ok(None),
Some(v) => crate::params::vec3(v).map(Some).ok_or_else(|| bad(cmd, "`about` must be a point [x, y, z] in mm")),
}
}
/// The 3 × 3 linear part of a placement, row by row: its turn, and any scale or mirror.
fn linear(m: &Mat) -> Tensor3 {
[0, 1, 2].map(|i| [0, 1, 2].map(|j| m[j][i]))
}
fn placed_doc(s: &Session) -> Document {
let mut doc = (*s.doc).clone();
for occurrence in &mut doc.occurrences {
@@ -58,7 +78,7 @@ pub(super) fn component(s: &mut Session, p: &Value) -> Result<Value> {
} else {
doc.components.iter().find(|c| c.id == id).map(|c| c.name.clone()).ok_or_else(|| bad(cmd, "no active component"))?
};
let mut out = properties(s, &doc, &path, descendants(p, cmd)?, cmd)?;
let mut out = properties(s, &doc, &path, descendants(p, cmd)?, about(p, cmd)?, cmd)?;
out["component"] = json!(id);
out["name"] = json!(name);
Ok(out)
@@ -79,13 +99,13 @@ pub(super) fn occurrence(s: &mut Session, p: &Value) -> Result<Value> {
_ => return Err(bad(cmd, "occurrence has multiple placements; supply its `path`")),
}
};
let mut out = properties(s, &doc, &path, descendants(p, cmd)?, cmd)?;
let mut out = properties(s, &doc, &path, descendants(p, cmd)?, about(p, cmd)?, cmd)?;
out["occurrence"] = json!(id);
out["name"] = json!(doc.occurrences.iter().find(|o| o.id == id).map(|o| o.name.as_str()));
Ok(out)
}
fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, cmd: &str) -> Result<Value> {
fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, about: Option<Vec3>, cmd: &str) -> Result<Value> {
let state = s.model.state();
let mut bodies = Vec::new();
let (mut volume, mut area, mut mass) = (0.0, 0.0, 0.0);
@@ -114,19 +134,40 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
}
out
};
// How each closed body's volume spreads about its centre of mass (#8095): one tessellation
// however often it is placed, which each placement then turns.
let components: BTreeSet<u64> = selected_placements.iter().map(|(component, _, _)| *component).collect();
let spread_bodies: Vec<usize> = (0..state.bodies.len())
.filter(|&i| {
state.bodies.get(i).is_some_and(|b| components.contains(&doc.model_body_component(b)) && crate::cmd::inspect::encloses_volume(&b.body))
})
.collect();
let spreads = solidcraft_kernel::map_on_threads(&spread_bodies, 16, |&i| {
state.bodies.get(i).and_then(|b| solidcraft_io::mass_properties(&b.body).ok().flatten()).and_then(|m| m.gyration())
});
let spread: BTreeMap<usize, Tensor3> = spread_bodies.into_iter().zip(spreads).filter_map(|(i, g)| Some((i, g.flatten()?))).collect();
// Closed bodies' (mass, centre of mass, inertia about it), all in world axes.
let mut parts: Vec<(f64, Vec3, Option<Tensor3>)> = Vec::new();
for (component, path, transform) in selected_placements {
placement_count += 1;
for body in state.bodies.iter().filter(|b| doc.model_body_component(b) == component) {
for (index, body) in state.bodies.iter().enumerate().filter(|(_, b)| doc.model_body_component(b) == component) {
let transform: Mat = doc.model_body_offset(body).map(|offset| solidcraft_doc::mat_mul(&transform, offset)).unwrap_or(transform);
let placed = solidcraft_kernel::transform_matrix(&body.body, transform)?;
let measured = solidcraft_kernel::measure(&placed)?;
let density = doc.density(&body.name);
let body_mass = measured.volume * density / 1000.0;
let closed = crate::cmd::inspect::encloses_volume(&placed);
// The mesh's spread with the exact mass, so the tensor agrees with the mass shown.
let body_inertia = spread
.get(&index)
.filter(|_| closed)
.map(|g| inertia::from_gyration(&inertia::transformed(g, &linear(&transform)), body_mass))
.filter(|i| i.iter().flatten().all(|x| x.is_finite()));
if closed {
volume += measured.volume;
mass += body_mass;
moment += measured.centroid * body_mass;
parts.push((body_mass, measured.centroid, body_inertia));
} else {
skipped += 1;
}
@@ -140,6 +181,7 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
"closed": closed, "density_g_cm3": closed.then_some(density),
"mass_g": closed.then_some(body_mass), "volume_mm3": closed.then_some(measured.volume),
"area_mm2": measured.area, "center_of_mass": closed.then_some(measured.centroid),
"inertia_g_mm2": body_inertia,
"bbox": {"min": measured.bbox.min, "max": measured.bbox.max}}));
}
}
@@ -150,11 +192,29 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
if centroid.is_some_and(|point| !point.is_finite()) {
return Err(bad(cmd, "center of mass exceeds supported numeric range"));
}
// About the centre of mass: each body's own tensor, plus its mass at its distance from that
// centre (parallel axes). Unknown when any closed body's mesh did not close.
let at_centre = centroid.and_then(|c| {
parts.iter().try_fold([[0.0f64; 3]; 3], |sum, (m, at, i)| {
let i = inertia::shifted(&(*i)?, *m, *at - c);
Some([0, 1, 2].map(|r| [0, 1, 2].map(|k| sum[r][k] + i[r][k])))
})
});
let at_centre = at_centre.filter(|i| i.iter().flatten().all(|x| x.is_finite()));
let principal = at_centre.and_then(|i| inertia::principal(&i, EQUAL_MOMENTS));
let bbox = if bodies.is_empty() { Value::Null } else { json!({"min": bounds.min, "max": bounds.max}) };
Ok(json!({"path": selected, "coordinate_frame": "world", "descendants": descendants,
let mut out = json!({"path": selected, "coordinate_frame": "world", "descendants": descendants,
"placement_count": placement_count, "body_count": bodies.len(), "bodies": bodies,
"total": {"open_bodies_skipped": skipped, "volume_mm3": volume, "area_mm2": area, "mass_g": mass,
"center_of_mass": centroid, "bbox": bbox, "faces": faces, "edges": edges, "vertices": vertices}}))
"center_of_mass": centroid, "first_moment_g_mm": moment, "inertia_g_mm2": at_centre,
"principal_moments_g_mm2": principal.map(|(moments, _)| moments), "principal_axes": principal.map(|(_, axes)| axes),
"bbox": bbox, "faces": faces, "edges": edges, "vertices": vertices}});
if let Some(point) = about {
let shifted =
centroid.zip(at_centre).map(|(c, i)| inertia::shifted(&i, mass, point - c)).filter(|i| i.iter().flatten().all(|x| x.is_finite()));
out["total"]["inertia_about"] = json!({"point": point, "inertia_g_mm2": shifted});
}
Ok(out)
}
#[cfg(test)]
@@ -98,6 +98,114 @@ fn properties_reject_hostile_identifiers_and_options() {
for path in [json!([]), json!(["bad"]), json!([0]), json!(vec![occurrence; 65])] {
assert!(s.execute("occurrence.properties", &json!({"occurrence": occurrence, "path": path})).is_err());
}
for about in [json!("origin"), json!([1, 2]), json!([1, 2, "z"]), json!([f64::MAX, 0, 0]), json!({"x": 1})] {
assert!(s.execute("component.properties", &json!({"about": about})).is_err(), "{about}");
}
}
fn tensor(v: &Value) -> [[f64; 3]; 3] {
[0, 1, 2].map(|r| [0, 1, 2].map(|c| v[r][c].as_f64().unwrap_or_else(|| panic!("no [{r}][{c}] in {v}"))))
}
fn tensor_close(actual: &Value, want: [[f64; 3]; 3], rel: f64) {
let got = tensor(actual);
let scale = want.iter().flatten().fold(0.0f64, |m, x| m.max(x.abs()));
for (g, w) in got.iter().flatten().zip(want.iter().flatten()) {
assert!((g - w).abs() <= rel * scale, "{got:?} != {want:?}");
}
}
/// #8095: a 10 × 20 × 30 mm steel box's inertia tensor about its centre of mass is
/// m (b² + c²) / 12 … on the diagonal, its principal axes are its edges, and turning its
/// placement turns the tensor with it.
#[test]
fn box_inertia_matches_the_closed_form_and_turns_with_its_placement() {
let mut s = Session::default();
let c = run(&mut s, "component.create", json!({"name": "Block", "grounded": false}));
run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"}));
run(&mut s, "material.assign", json!({"bodies": ["Block"], "material": "Steel"}));
let r = run(&mut s, "component.properties", json!({"component": c["component"]}));
let total = &r["total"];
close(&total["bbox"]["max"][1], 20.0);
let m = total["mass_g"].as_f64().unwrap();
close(&total["mass_g"], 6000.0 * s.doc.density("Block") / 1000.0);
let (a, b, h) = (10.0, 20.0, 30.0);
let (ixx, iyy, izz) = (m * (b * b + h * h) / 12.0, m * (a * a + h * h) / 12.0, m * (a * a + b * b) / 12.0);
tensor_close(&total["inertia_g_mm2"], [[ixx, 0.0, 0.0], [0.0, iyy, 0.0], [0.0, 0.0, izz]], 1e-9);
tensor_close(&r["bodies"][0]["inertia_g_mm2"], [[ixx, 0.0, 0.0], [0.0, iyy, 0.0], [0.0, 0.0, izz]], 1e-9);
// Smallest first: about the longest edge (z), largest about the shortest (x).
for (k, want) in [izz, iyy, ixx].into_iter().enumerate() {
assert!((total["principal_moments_g_mm2"][k].as_f64().unwrap() - want).abs() < 1e-9 * ixx, "{total}");
}
// Right-handed: z × y is −x.
assert_eq!(total["principal_axes"], json!([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]]));
for (k, want) in [5.0, 10.0, 15.0].iter().enumerate() {
close(&total["first_moment_g_mm"][k], m * want);
}
// A quarter turn about z swaps the x and y moments; the principal moments stay.
run(&mut s, "occurrence.move", json!({"occurrence": c["occurrence"], "axis": [0, 0, 1], "angle": "90 deg", "capture": false}));
let turned = run(&mut s, "component.properties", json!({"component": c["component"]}));
tensor_close(&turned["total"]["inertia_g_mm2"], [[iyy, 0.0, 0.0], [0.0, ixx, 0.0], [0.0, 0.0, izz]], 1e-9);
assert_eq!(turned["total"]["principal_moments_g_mm2"], total["principal_moments_g_mm2"]);
let x_axis = &turned["total"]["principal_axes"][2];
assert!(x_axis[0].as_f64().unwrap().abs() < 1e-9 && (x_axis[1].as_f64().unwrap().abs() - 1.0).abs() < 1e-9, "{turned}");
}
/// #8095: an assembly's tensor adds each placement's own about the shared centre of mass by
/// parallel axes, and `about` takes it about any point; a cylinder's comes from its
/// tessellation, close to m r² / 2 about its axis.
#[test]
fn assembly_inertia_adds_placements_by_parallel_axes_and_about_any_point() {
let mut s = Session::default();
let (component, _, body) = box_in(&mut s, "Block");
run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20, 0, 0]}));
let root = run(&mut s, "component.properties", json!({"component": "root", "about": [0, 0, 0]}));
let total = &root["total"];
let m = s.doc.density(&body);
close(&total["mass_g"], 2.0 * m);
// Each 10 mm cube: m (10² + 10²) / 12 on its diagonal; each sits 10 mm along x from (15, 5, 5).
let own = m * 200.0 / 12.0;
let at_centre = [[2.0 * own, 0.0, 0.0], [0.0, 2.0 * own + 2.0 * m * 100.0, 0.0], [0.0, 0.0, 2.0 * own + 2.0 * m * 100.0]];
tensor_close(&total["inertia_g_mm2"], at_centre, 1e-9);
// About the origin: the parallel-axis term of the whole mass at (15, 5, 5).
let (mm, cv) = (2.0 * m, [15.0, 5.0, 5.0]);
let c2: f64 = cv.iter().map(|x| x * x).sum();
let at_origin = [0, 1, 2].map(|r| [0, 1, 2].map(|k| at_centre[r][k] + mm * (if r == k { c2 } else { 0.0 } - cv[r] * cv[k])));
assert_eq!(total["inertia_about"]["point"], json!([0.0, 0.0, 0.0]));
tensor_close(&total["inertia_about"]["inertia_g_mm2"], at_origin, 1e-9);
assert!(total.get("inertia_about").is_some() && run(&mut s, "component.properties", json!({}))["total"].get("inertia_about").is_none());
let mut s = Session::default();
run(&mut s, "solid.cylinder", json!({"radius": 8, "height": 10, "body_name": "Pin"}));
let r = run(&mut s, "component.properties", json!({}));
let (m, r2) = (r["total"]["mass_g"].as_f64().unwrap(), 64.0);
let i = tensor(&r["total"]["inertia_g_mm2"]);
assert!((i[2][2] - m * r2 / 2.0).abs() < 1e-3 * m * r2 / 2.0, "{i:?}");
assert!((i[0][0] - m * (3.0 * r2 + 100.0) / 12.0).abs() < 1e-3 * i[0][0], "{i:?}");
}
/// #8095: an open surface has no volume, so no tensor; the closed bodies beside it keep theirs.
#[test]
fn open_bodies_have_no_inertia_and_leave_the_closed_ones_alone() {
let mut s = Session::default();
for (command, params) in [
("sketch.create", json!({"plane": "XY", "name": "Profile"})),
("sketch.line", json!({"points": [[30, 0], [30, 40]], "ids": ["side"]})),
("sketch.finish", json!({})),
("surface.revolve", json!({"sketch": "Profile", "curves": ["side"], "axis": "y", "angle": "270 deg", "body_name": "Tube"})),
] {
run(&mut s, command, params);
}
let open = run(&mut s, "component.properties", json!({"about": [1, 2, 3]}));
assert_eq!(open["bodies"][0]["inertia_g_mm2"], Value::Null);
for key in ["inertia_g_mm2", "principal_moments_g_mm2", "principal_axes"] {
assert_eq!(open["total"][key], Value::Null, "{key}");
}
assert_eq!(open["total"]["inertia_about"]["inertia_g_mm2"], Value::Null);
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [100, 0, 0], "body_name": "Box"}));
let both = run(&mut s, "component.properties", json!({}));
let m = both["total"]["mass_g"].as_f64().unwrap();
tensor_close(&both["total"]["inertia_g_mm2"], [[m * 200.0 / 12.0, 0.0, 0.0], [0.0, m * 200.0 / 12.0, 0.0], [0.0, 0.0, m * 200.0 / 12.0]], 1e-9);
}
#[test]