* Iterate instead of indexing in nine loops Replace index loops that look up neighbours by position with enumerate, zip(cycle().skip(1)) for wrap-around pairs and zip(skip(1)) for consecutive pairs. No behaviour change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * geom: ring_edges for the edges of a closed ring Every walk over a polygon's edges, the last back to the first, spelled x.iter().zip(x.iter().cycle().skip(1)); eighteen of them now call geom::ring_edges. Three redundant take(len) calls go with them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * geom: Ring, a closed ring that knows it is closed A Ring holds items in order around a closed polygon, loop or fan; edges() walks each with the next and the last with the first, corners() each with both neighbours. Ring<Vec2> has signed_area and even-odd contains. Loop2::polyline returns a Ring, as do doc's face_loops and boundary_loops, kernel's coplanar wire samples, CapLoop's segments, tess pieces' rings, the gizmo's plane quads and the navigation cube's facets. Their walks take edges() or corners() instead of wrapping an index; sketch's text-hole test and doc's poly_area become contains and signed_area. Loop2::joints pairs each segment with the next. Replaces the ring_edges free function. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * geom: Chain, Ring and Path; bounds for a chain of points Ring becomes Chain<T, Closed> beside Path = Chain<T, Open>: edges() closes a ring and stops at a path's end, Path::close makes the ring, and bounds() (the empty box for no points) serves both. Eight hand-rolled min/max folds over a loop's polyline call bounds(); doc's flat_polyline returns a Ring. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * geom: area and inside on Ring for any planar point Ring's signed_area and contains take any Planar point (Vec2 or [f64; 2]). The cam profile in joints_cam is a Ring: its own even-odd test goes, and its edge walks, gap and area take edges(). face_params' loop area, the text path's winding, tess pieces' ring area and the copies in three tests call signed_area or contains; the formulas are the same term for term. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * doc: sheet's closed outlines go through Ring dedup takes and returns a Ring (dropping a last point back on the first is what makes it a ring's), near_outline walks a Ring's edges, and the copy of it beside fold checks calls it. point_in goes: its callers ask the Ring. Its formula anchored each crossing on the other end of the edge, so the two can differ only for a point on an edge to the last digit; one caller sets such points aside first, the others test a region's interior point, a cut's midpoint or another outline's corners. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * doc: cam tests build their outlines with Ring::from Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * geom: area_vector on Ring<Vec3>; three Newell sums use it Ring<Vec3>::area_vector is half the sum of a × b round the ring. heal's loop_area, lip's outer-loop turning and the revolve's loop orientation summed it by hand with a wrapped index; they take it from the Ring (the half is exact, and two of them only read its sign). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * geom: Aabb3 from points; boxes built and asked through it Aabb3 collects from points (skipping non-finite ones, as add does) and gains inflated, contains and meets. Fifteen hand-rolled min/max folds over points or boxes in kernel, doc and engine become collect or union, and their "within tol of the box" tests become inflated(tol).contains. blend's refused-edge boxes and naming's face index hold an Aabb3. A NaN point is now outside every box, where the old negated comparisons let it in; an infinite point no longer stretches a box. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * geom: Aabb2, the plane's box; 2D folds and box tuples use it Aabb2 mirrors Aabb3 (collect, add, union, inflated, contains, meets) and adds relative, a point's place in the box. sketch's link and link_loops each had that formula; link_loops' boundaries, prism's segment and loop boxes, profiles' shape boxes and grid, and ends' segment box hold an Aabb2 instead of a (low, high) pair. Folds in the cam, sketch bounds, sheet's perforation grid and the sketch clipboard collect one. Boxes are built from the same terms (a round's box keeps c - r - tol). As with Aabb3, a NaN point is outside every box and an infinite point no longer stretches one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * kernel: prism's segment boxes are plain Aabb2s The SegBox alias named a (low, high) pair; Aabb2 says it itself. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * geom: Chain::bounds is an Aabb2; the boxes #2382 left as pairs follow Chain::bounds returns an Aabb2. Its callers keep it: sheet's hole and cut boxes (loop_box), letter boxes, island outlines and line-near-cut test use meets, contains and inflated; profile's outline overlap and max_clearance, profiles' box tests and the cam test read its corners. flat_size and the flat pattern's JSON size are the union of the loops' boxes (0 × 0 for no loop, where the pair fold gave -∞). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * geom: Aabb3::intersection; hand-grown and hand-met boxes use the box Aabb3::intersection is the box both hold. ops' four overlap boxes of a boolean's operands take it, and seven boxes grown by hand (ops' body boxes, the distance set's bounds, coplanar's face box, eval_more's padded mesh box, compare's group and region boxes) call inflated with the same amount on every side. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
156 lines
7.4 KiB
Rust
156 lines
7.4 KiB
Rust
//! Physical properties of an assembly placement, with original body material assignments.
|
|
use serde_json::{Value, json};
|
|
use solidcraft_doc::{Document, Mat};
|
|
use solidcraft_geom::{Aabb3, Vec3};
|
|
|
|
use crate::params::bad;
|
|
use crate::{Result, Session};
|
|
|
|
fn descendants(p: &Value, cmd: &str) -> Result<bool> {
|
|
match p.get("descendants") {
|
|
None => Ok(true),
|
|
Some(Value::Bool(v)) => Ok(*v),
|
|
Some(_) => Err(bad(cmd, "`descendants` must be a boolean")),
|
|
}
|
|
}
|
|
|
|
fn placed_doc(s: &Session) -> Document {
|
|
let mut doc = (*s.doc).clone();
|
|
for occurrence in &mut doc.occurrences {
|
|
if let Some(transform) = s.pending_moves.get(&occurrence.id) {
|
|
occurrence.transform = *transform;
|
|
}
|
|
}
|
|
doc
|
|
}
|
|
|
|
/// A property total must cover the entire assembly. The display traversal intentionally
|
|
/// truncates hostile designs, so use an explicit error instead of accepting its prefix.
|
|
pub(in crate::cmd) fn placements(doc: &Document, cmd: &str) -> Result<Vec<(u64, Vec<u64>, Mat)>> {
|
|
let mut out = vec![(0, Vec::new(), solidcraft_doc::IDENTITY)];
|
|
let mut stack = vec![(0, Vec::<u64>::new(), solidcraft_doc::IDENTITY)];
|
|
let mut children: std::collections::BTreeMap<u64, Vec<_>> = std::collections::BTreeMap::new();
|
|
for occurrence in &doc.occurrences {
|
|
children.entry(occurrence.parent).or_default().push(occurrence);
|
|
}
|
|
while let Some((component, path, transform)) = stack.pop() {
|
|
for occurrence in children.get(&component).into_iter().flatten() {
|
|
if path.len() >= 64 || out.len() >= 100_000 {
|
|
return Err(bad(cmd, "assembly exceeds physical-properties traversal limits (64 levels or 100000 placements)"));
|
|
}
|
|
let mut child_path = path.clone();
|
|
child_path.push(occurrence.id);
|
|
let world = solidcraft_doc::mat_mul(&transform, &occurrence.transform);
|
|
out.push((occurrence.component, child_path.clone(), world));
|
|
stack.push((occurrence.component, child_path, world));
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
pub(super) fn component(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let cmd = "component.properties";
|
|
let id = if p.get("component").is_some() { super::component(s, p, "component", cmd)? } else { s.active_component };
|
|
let doc = placed_doc(s);
|
|
let path = doc.first_path(id);
|
|
let name = if id == 0 {
|
|
doc.name.clone()
|
|
} 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)?;
|
|
out["component"] = json!(id);
|
|
out["name"] = json!(name);
|
|
Ok(out)
|
|
}
|
|
|
|
pub(super) fn occurrence(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let cmd = "occurrence.properties";
|
|
let id = super::occurrence(s, p, cmd)?;
|
|
let doc = placed_doc(s);
|
|
let path = if p.get("path").is_some() {
|
|
super::occurrence_path(s, p, id, cmd)?
|
|
} else {
|
|
let paths: Vec<Vec<u64>> =
|
|
placements(&doc, cmd)?.into_iter().filter(|(_, path, _)| path.last() == Some(&id)).map(|(_, path, _)| path).collect();
|
|
match paths.as_slice() {
|
|
[path] => path.clone(),
|
|
[] => return Err(bad(cmd, "occurrence has no placement")),
|
|
_ => return Err(bad(cmd, "occurrence has multiple placements; supply its `path`")),
|
|
}
|
|
};
|
|
let mut out = properties(s, &doc, &path, descendants(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> {
|
|
let state = s.model.state();
|
|
let mut bodies = Vec::new();
|
|
let (mut volume, mut area, mut mass) = (0.0, 0.0, 0.0);
|
|
let mut moment = Vec3::ZERO;
|
|
let mut bounds = Aabb3::EMPTY;
|
|
let (mut faces, mut edges, mut vertices) = (0, 0, 0);
|
|
let mut placement_count = 0;
|
|
let selected_placements = if selected.is_empty() {
|
|
if descendants { placements(doc, cmd)? } else { vec![(0, Vec::new(), solidcraft_doc::IDENTITY)] }
|
|
} else {
|
|
let placement = s.occurrence_placement(selected).map_err(|e| bad(cmd, e.to_string()))?;
|
|
let mut out = vec![(placement.component, selected.to_vec(), placement.world)];
|
|
let mut stack = if descendants { out.clone() } else { Vec::new() };
|
|
while let Some((component, path, transform)) = stack.pop() {
|
|
for occurrence in doc.occurrences.iter().filter(|o| o.parent == component) {
|
|
if path.len() >= 64 || out.len() >= 100_000 {
|
|
return Err(bad(cmd, "assembly exceeds physical-properties traversal limits (64 levels or 100000 placements)"));
|
|
}
|
|
let mut child = path.clone();
|
|
child.push(occurrence.id);
|
|
let world = solidcraft_doc::mat_mul(&transform, &occurrence.transform);
|
|
out.push((occurrence.component, child.clone(), world));
|
|
stack.push((occurrence.component, child, world));
|
|
}
|
|
}
|
|
out
|
|
};
|
|
for (component, path, transform) in selected_placements {
|
|
placement_count += 1;
|
|
for body in state.bodies.iter().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;
|
|
volume += measured.volume;
|
|
area += measured.area;
|
|
mass += body_mass;
|
|
moment += measured.centroid * body_mass;
|
|
bounds = bounds.union(&measured.bbox);
|
|
faces += measured.merged.faces;
|
|
edges += measured.merged.edges;
|
|
vertices += measured.merged.vertices;
|
|
bodies.push(json!({"name": body.name, "component": component, "path": path,
|
|
"material": doc.materials.get(&body.name).map(String::as_str).unwrap_or("Default"),
|
|
"density_g_cm3": density, "mass_g": body_mass, "volume_mm3": measured.volume,
|
|
"area_mm2": measured.area, "center_of_mass": measured.centroid,
|
|
"bbox": {"min": measured.bbox.min, "max": measured.bbox.max}}));
|
|
}
|
|
}
|
|
if !(volume.is_finite() && area.is_finite() && mass.is_finite() && moment.is_finite()) {
|
|
return Err(bad(cmd, "physical properties exceed supported numeric range"));
|
|
}
|
|
let centroid = if mass > 0.0 { Some(moment / mass) } else { None };
|
|
if centroid.is_some_and(|point| !point.is_finite()) {
|
|
return Err(bad(cmd, "center of mass exceeds supported numeric range"));
|
|
}
|
|
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,
|
|
"placement_count": placement_count, "body_count": bodies.len(), "bodies": bodies,
|
|
"total": {"volume_mm3": volume, "area_mm2": area, "mass_g": mass,
|
|
"center_of_mass": centroid, "bbox": bbox, "faces": faces, "edges": edges, "vertices": vertices}}))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "component_properties_tests.rs"]
|
|
mod tests;
|