Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Wave 341/509: Designs before format 14: a split's pieces take the names its later features use them by (and 3 more)

jyviko8ac38056c1c1
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 1c5b63cbab..0ea2388411 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -535,6 +535,10 @@ pub struct ModelState {
/// How the pieces a join split off into bodies of their own touched the others (by feature
/// id), for its notice.
kept_separate: BTreeMap<u64, KeptSeparate>,
+ /// For a feature saved before format 14 that split a body, a digest of the later features'
+ /// picks its pieces were named by (by feature id, see [`crate::lineage::order_legacy_lumps`]):
+ /// the state stands for the feature only while those picks are the same.
+ legacy_picks: BTreeMap<u64, u64>,
}
/// How a piece a join split off into a body of its own (`Touching::Separate`) touched the
@@ -645,7 +649,7 @@ impl ModelState {
/// After a feature evaluated to this state from `before` with cache key `key`: bodies it
/// made or changed take that key, sketches it made a digest of their solved geometry (see
/// [`quantize`]); the rest keep theirs.
- fn stamp(&mut self, before: &Arc<ModelState>, f: &Feature, key: u64, mats: Vec<Mat>) {
+ fn stamp(&mut self, doc: &Document, before: &Arc<ModelState>, f: &Feature, key: u64, mats: Vec<Mat>) {
let feature = f.id;
let depth = before.bodies.iter().filter_map(|b| b.names.depth()).max().unwrap_or(0) + 1;
let sheets = if f.kind.is_sheet() { self.sheets.clone() } else { Vec::new() };
@@ -654,7 +658,13 @@ impl ModelState {
// the feature was saved when they were named in that order).
if !f.shell_piece_order {
crate::lineage::order_lumps(&mut self.bodies, &origin);
+ } else {
+ crate::lineage::order_legacy_lumps(&mut self.bodies, before, doc, f);
}
+ match crate::lineage::legacy_picks_digest(&self.bodies, before, doc, f) {
+ 0 => self.legacy_picks.remove(&f.id),
+ d => self.legacy_picks.insert(f.id, d),
+ };
// The bodies before the feature by name, in their order (names repeat only in damaged
// states): every lookup below is the first match of a linear search, without walking
// every earlier body for every body, after every feature.
@@ -1328,6 +1338,15 @@ fn context_digest(doc: &Document, vals: &BTreeMap<String, Value>) -> u64 {
h.finish()
}
+/// Whether `after`, a state feature `f` evaluated to from `before` in an earlier evaluation, is
+/// still its result in `doc`: a feature saved before format 14 names the pieces it splits a body
+/// into as the later features pick them ([`crate::lineage::order_legacy_lumps`]), which neither
+/// its fingerprint nor its cache key cover. (A script replays those features after it: the state
+/// made before they were there named the pieces otherwise.)
+fn legacy_current(doc: &Document, f: &Feature, before: &ModelState, after: &ModelState) -> bool {
+ !f.shell_piece_order || after.legacy_picks.get(&f.id).copied().unwrap_or(0) == crate::lineage::legacy_picks_digest(&after.bodies, before, doc, f)
+}
+
/// The cache key of a feature evaluation: its own inputs, the document context and the state it
/// starts from. Features that replay other features' definitions (patterns and mirrors of
/// features) also take the chain fingerprint, which covers every earlier definition.
@@ -1860,9 +1879,11 @@ impl Model {
if f.suppressed && !rolled_back {
reserved.extend(f.body_names.iter().map(|n| n.trim()).filter(|n| !n.is_empty()).map(str::to_string));
}
+ // A feature that names its pieces as later features pick them (saved before format 14)
+ // has a result only while those picks are what they were.
if reuse
&& !unkept
- && let Some(old) = self.results.get(i).filter(current)
+ && let Some(old) = self.results.get(i).filter(current).filter(|old| old.skipped || legacy_current(doc, f, &state, &old.state))
{
if !old.skipped {
state = old.state.clone();
@@ -1898,7 +1919,13 @@ impl Model {
cache_key(f, fp, fingerprint(doc, 0, f, &vals, false, &self.step_digests) ^ placement_digest(doc, f, Some(&state)), ctx, &state);
let kept = self.kept.0.as_ref().filter(|_| !self.no_cache);
if !self.no_cache
- && let Some(c) = self.cache.lock().ok().and_then(|mut m| m.get(key)).or_else(|| kept.and_then(|k| k.get(key)))
+ && let Some(c) = self
+ .cache
+ .lock()
+ .ok()
+ .and_then(|mut m| m.get(key))
+ .or_else(|| kept.and_then(|k| k.get(key)))
+ .filter(|c| c.error.is_some() || legacy_current(doc, f, &state, &c.state))
{
if let Some(k) = kept {
k.put(key, &c);
@@ -1927,7 +1954,12 @@ impl Model {
}
// An active result hidden by the marker, or evaluated ahead on these same inputs
// (the same chain of definitions from the start). Changed inputs never reuse it.
- if let Some(r) = rolled.as_ref().filter(current).or_else(|| primed.as_ref().and_then(|p| p.get(&f.id)).filter(current)) {
+ if let Some(r) = rolled
+ .as_ref()
+ .filter(current)
+ .or_else(|| primed.as_ref().and_then(|p| p.get(&f.id)).filter(current))
+ .filter(|r| r.error.is_some() || legacy_current(doc, f, &state, &r.state))
+ {
restored += 1;
if r.error.is_none() {
state = r.state.clone();
@@ -2010,7 +2042,7 @@ impl Model {
}
_ => mats,
};
- next.stamp(&state, f, key, mats);
+ next.stamp(doc, &state, f, key, mats);
for b in &mut next.bodies {
if !b.transferred {
b.component = match doc.body_components.get(&b.name) {
diff --git a/crates/doc/src/lineage.rs b/crates/doc/src/lineage.rs
index 5264e8982e..60f34d6445 100644
--- a/crates/doc/src/lineage.rs
+++ b/crates/doc/src/lineage.rs
@@ -11,7 +11,7 @@
use std::sync::{Arc, OnceLock};
-use solidcraft_geom::Region2;
+use solidcraft_geom::{Region2, Vec3};
use solidcraft_kernel::Body;
use solidcraft_kernel::history::{BodyHistory, Change, FaceOrigin, FaceProv, History};
@@ -568,6 +568,150 @@ impl crate::ModelBody {
}
}
+/// The pieces feature `f` (saved before format 14) split a body into, named so the later
+/// features of the design find them. Those builds named the pieces in truck's shell order, which
+/// SMLib's need not follow, and a later feature names the piece it works on (`body`) and keeps
+/// the points it picked on it: each name goes to the piece nearest the points the features
+/// naming it picked. Pieces no later feature names keep the order they came in; so do all of
+/// them where the picks do not tell the pieces apart.
+pub(crate) fn order_legacy_lumps(bodies: &mut [crate::ModelBody], before: &crate::ModelState, doc: &crate::Document, f: &crate::Feature) {
+ for members in made_families(bodies, before) {
+ order_legacy_family(bodies, &members, doc, f);
+ }
+}
+
+/// The families of [`lump_families`] the feature that left `bodies` after `before` made: a family
+/// it left as it was keeps its names.
+fn made_families(bodies: &[crate::ModelBody], before: &crate::ModelState) -> Vec<Vec<usize>> {
+ lump_families(bodies)
+ .into_iter()
+ .filter(|members| members.iter().filter_map(|i| bodies.get(*i)).any(|b| !before.bodies.iter().any(|o| o.body.same(&b.body))))
+ .collect()
+}
+
+/// What [`order_legacy_lumps`] named the pieces of `bodies` (the state feature `f` left after
+/// `before`) by: a digest of each piece name with the points the later features of `doc` naming
+/// it picked, 0 where `f` was saved since format 14 or split nothing. Those features come after
+/// `f`, so the state is `f`'s only while this is the same: a script replays them after it, and
+/// an edit may change what they pick or name.
+pub(crate) fn legacy_picks_digest(bodies: &[crate::ModelBody], before: &crate::ModelState, doc: &crate::Document, f: &crate::Feature) -> u64 {
+ use std::hash::{Hash, Hasher};
+ if !f.shell_piece_order {
+ return 0;
+ }
+ let families = made_families(bodies, before);
+ if families.is_empty() {
+ return 0;
+ }
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ for members in families {
+ let mut names: Vec<String> = members.iter().filter_map(|i| bodies.get(*i).map(|b| b.name.clone())).collect();
+ names.sort();
+ for (name, points) in names.iter().zip(later_picks(doc, f, &names)) {
+ name.hash(&mut h);
+ for p in points {
+ [p.x, p.y, p.z].map(f64::to_bits).hash(&mut h);
+ }
+ }
+ }
+ // 0 means "nothing named so"; a digest that happens to be 0 must not read as that.
+ h.finish().max(1)
+}
+
+/// The pieces each body a feature cut in two or more came out as (the bodies whose lineage is
+/// that one operand), as [`order_lumps`] finds them.
+fn lump_families(bodies: &[crate::ModelBody]) -> Vec<Vec<usize>> {
+ let mut families: Vec<(*const Operand, Vec<usize>)> = Vec::new();
+ for (i, b) in bodies.iter().enumerate() {
+ let Made::Traced(l) = &b.made else { continue };
+ let [op] = l.operands.as_slice() else { continue };
+ if !matches!(op.as_ref(), Operand::Stage(_)) {
+ continue;
+ }
+ let key = Arc::as_ptr(op);
+ match families.iter_mut().find(|(k, _)| *k == key) {
+ Some((_, members)) => members.push(i),
+ None => families.push((key, vec![i])),
+ }
+ }
+ families.into_iter().map(|(_, m)| m).filter(|m| m.len() > 1).collect()
+}
+
+/// Per name of `names`: the points the features after `f` in `doc` that name that body picked
+/// on it.
+fn later_picks(doc: &crate::Document, f: &crate::Feature, names: &[String]) -> Vec<Vec<Vec3>> {
+ let later = doc.features.iter().skip_while(|g| g.id != f.id).skip(1);
+ let mut picks: Vec<Vec<Vec3>> = vec![Vec::new(); names.len()];
+ for g in later {
+ let Ok(kind) = serde_json::to_value(&g.kind) else { continue };
+ let Some(k) = kind.get("body").and_then(|b| b.as_str()).and_then(|b| names.iter().position(|n| n == b)) else { continue };
+ for key in ["edges", "faces", "face", "position"] {
+ let point = |v: &serde_json::Value| -> Option<Vec3> {
+ let a = v.as_array().filter(|a| a.len() == 3)?;
+ Some(Vec3::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?))
+ };
+ let found: Vec<Vec3> = match kind.get(key) {
+ Some(v) => {
+ point(v).map(|p| vec![p]).unwrap_or_else(|| v.as_array().map(|a| a.iter().filter_map(point).collect()).unwrap_or_default())
+ }
+ None => Vec::new(),
+ };
+ if let Some(slot) = picks.get_mut(k) {
+ slot.extend(found);
+ }
+ }
+ }
+ picks
+}
+
+fn order_legacy_family(bodies: &mut [crate::ModelBody], members: &[usize], doc: &crate::Document, f: &crate::Feature) {
+ if members.len() > 64 {
+ return;
+ }
+ let names: Vec<String> = members.iter().filter_map(|i| bodies.get(*i).map(|b| b.name.clone())).collect();
+ let picks = later_picks(doc, f, &names);
+ // How far piece `i` is from the points of name `k` (the mesh's nearest triangle).
+ let far = |piece: usize, pts: &[Vec3]| -> f64 {
+ let Some(b) = members.get(piece).and_then(|i| bodies.get(*i)) else { return f64::INFINITY };
+ let m = b.mesh();
+ pts.iter()
+ .map(|p| {
+ m.triangles
+ .iter()
+ .filter_map(|t| m.tri(t))
+ .map(|[a, b, c]| solidcraft_geom::compare::closest_on_triangle(*p, a, b, c).dist(*p))
+ .fold(f64::INFINITY, f64::min)
+ })
+ .fold(0.0, f64::max)
+ };
+ let mut order: Vec<Option<usize>> = vec![None; names.len()];
+ let mut taken = vec![false; members.len()];
+ for (k, pts) in picks.iter().enumerate().filter(|(_, p)| !p.is_empty()) {
+ let best =
+ (0..members.len()).filter(|i| !taken.get(*i).copied().unwrap_or(true)).map(|i| (far(i, pts), i)).min_by(|a, b| a.0.total_cmp(&b.0));
+ let Some((d, i)) = best else { return };
+ // Only a piece the points lie on: a pick off every piece tells nothing.
+ let size = members.get(i).and_then(|m| bodies.get(*m)).map_or(1.0, |b| b.body.size().max(1.0));
+ if d > size * 1e-3 {
+ return;
+ }
+ if let (Some(o), Some(t)) = (order.get_mut(k), taken.get_mut(i)) {
+ *o = Some(i);
+ *t = true;
+ }
+ }
+ let mut free = (0..members.len()).filter(|i| !taken.get(*i).copied().unwrap_or(true));
+ let order: Vec<usize> = order.into_iter().map(|o| o.or_else(|| free.next())).collect::<Option<_>>().unwrap_or_default();
+ if order.len() != names.len() {
+ return;
+ }
+ for (name, piece) in names.into_iter().zip(order) {
+ if let Some(b) = members.get(piece).and_then(|i| bodies.get_mut(*i)) {
+ b.name = name;
+ }
+ }
+}
+
/// Name the pieces a body fell into after their faces: of the bodies in `bodies` that are lumps
/// of one body (made in the same step, from one stage), the one whose least face name sorts first
/// takes the first of their body names, and so on. The kernel's shell order, which named them
diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs
index 045670cdc8..35f9b33295 100644
--- a/crates/doc/src/model_cache.rs
+++ b/crates/doc/src/model_cache.rs
@@ -364,6 +364,10 @@ impl SavedModel {
tapered: serde_json::from_value(field("tapered")?).map_err(invalid)?,
// A join's notice is for the evaluation that made it, not kept with the cache.
kept_separate: BTreeMap::new(),
+ // Not kept either: a saved model's states carry no lineage, so the check of a
+ // legacy split's picks (`lineage::legacy_picks_digest`) finds no pieces in them
+ // and takes them as the design's evaluation they were saved as.
+ legacy_picks: BTreeMap::new(),
};
held = held.saturating_add(st.bodies.len()).saturating_add(st.sketches.len()).saturating_add(st.sheets.len());
if held > MAX_HELD {
diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs
index be65121947..7b65f1d863 100644
--- a/crates/kernel/src/build.rs
+++ b/crates/kernel/src/build.rs
@@ -799,24 +799,61 @@ pub fn extrude_tapered_between(
smlib_tapered(plane, region, from, to, foot, dir_sign.signum(), taper, corner)
}
-/// [`extrude_tapered_between`] through SMLib's draft extrusion: one loop (SMLib's takes no
-/// holes), its section at `from` the profile offset by the taper, after any straight foot.
+/// [`extrude_tapered_between`] through SMLib's draft extrusion, its section at `from` the
+/// profile offset by the taper, after any straight foot. SMLib's draft extrusion takes one loop:
+/// a region with holes is its outer loop drafted, less each hole drafted the other way (every
+/// wall leaning by the taper on the material's side), refused only where the taper would make a
+/// hole meet the outer wall or another hole within the extrusion.
#[allow(clippy::too_many_arguments)]
fn smlib_tapered(plane: &Plane, region: &Region2, from: f64, to: f64, foot: f64, sign: f64, taper: f64, corner: DraftCorner) -> Result<Body> {
- if !region.holes.is_empty() {
- return Err(crate::smlib_sweeps::refuse("draft extrusion of a profile with holes (SMLib's takes one loop)"));
- }
- let outer = oriented(region)?.map_loops(|l| l.merged_lines(continues_straight)).outer;
- let bottom = if from == 0.0 || taper == 0.0 {
- outer
- } else {
- let moved = offset_loop(&outer.lp, from * taper.tan())?;
- let segs: Option<Vec<Seg2>> = moved.into_iter().collect();
+ let joined = oriented(region)?.map_loops(|l| l.merged_lines(continues_straight));
+ // A loop's section `at` along the extrusion: counter-clockwise, grown by `taper` (a hole's
+ // the other way, as the wall of the material round it leans).
+ let section = |l: &NumberedLoop, at: f64, taper: f64| -> Result<NumberedLoop> {
+ let ccw = l.oriented(false);
+ if at == 0.0 || taper == 0.0 {
+ return Ok(ccw);
+ }
+ let segs: Option<Vec<Seg2>> = offset_loop(&ccw.lp, at * taper.tan())?.into_iter().collect();
let segs = segs.ok_or_else(|| crate::smlib_sweeps::refuse("draft extrusion that starts before its profile where the taper closes a side"))?;
- NumberedLoop { lp: Loop2 { segs }, from: outer.from }
+ Ok(NumberedLoop { lp: Loop2 { segs }, from: ccw.from })
};
+ let outer = section(&joined.outer, from, taper)?;
let draft = (taper != 0.0).then_some(crate::smlib_sweeps::Draft { taper, foot, corner });
- crate::smlib_sweeps::extrude(plane, &crate::smlib_sweeps::pieces([&bottom]), Some(region), from * sign, to - from, sign, draft)
+ if joined.holes.is_empty() {
+ return crate::smlib_sweeps::extrude(plane, &crate::smlib_sweeps::pieces([&outer]), Some(region), from * sign, to - from, sign, draft);
+ }
+ let Some(draft) = draft else {
+ return Err(KernelError::Invalid("a tapered extrusion needs a taper".into()));
+ };
+ let holes: Vec<NumberedLoop> = joined.holes.iter().map(|h| section(h, from, -taper)).collect::<Result<_>>()?;
+ // The sections where the walls are farthest moved, the two ends: each hole stays inside the
+ // outer loop and clear of the other holes there (the walls are planes, cones and their like,
+ // which move monotonically in between).
+ for at in [from, to] {
+ let o = section(&joined.outer, at, taper)?;
+ let hs: Vec<NumberedLoop> = joined.holes.iter().map(|h| section(h, at, -taper)).collect::<Result<_>>()?;
+ let pts = |l: &NumberedLoop| l.lp.segs.iter().flat_map(|s| s.polyline(1e-3)).collect::<Vec<Vec2>>();
+ // Apart: no point of either inside the other.
+ let apart = |a: &NumberedLoop, b: &NumberedLoop| !pts(a).iter().any(|p| b.lp.contains(*p)) && !pts(b).iter().any(|p| a.lp.contains(*p));
+ for (i, h) in hs.iter().enumerate() {
+ let inside = pts(h).iter().all(|p| o.lp.contains(*p)) && !pts(&o).iter().any(|p| h.lp.contains(*p));
+ if !inside || hs.iter().skip(i + 1).any(|k| !apart(h, k)) {
+ return Err(KernelError::Invalid("the draft makes a hole meet the outer wall or another hole".into()));
+ }
+ }
+ }
+ let all: Vec<NumberedLoop> = std::iter::once(outer.clone()).chain(holes.iter().map(|h| h.oriented(true))).collect();
+ crate::smlib_sweeps::extrude_drafted_with_holes(
+ plane,
+ &crate::smlib_sweeps::pieces([&outer]),
+ &holes.iter().map(|h| crate::smlib_sweeps::pieces([h])).collect::<Vec<_>>(),
+ &crate::smlib_sweeps::pieces(all.iter()),
+ from * sign,
+ to - from,
+ sign,
+ draft,
+ )
}
/// A planar region on `plane` as the schema 4 record of one face (an open sheet): the plane's
diff --git a/crates/kernel/src/smlib_sweeps.rs b/crates/kernel/src/smlib_sweeps.rs
index 62386961f3..008b981ac3 100644
--- a/crates/kernel/src/smlib_sweeps.rs
+++ b/crates/kernel/src/smlib_sweeps.rs
@@ -71,8 +71,8 @@ pub(crate) struct Draft {
}
pub(crate) use imp::{
- body_from_record, curve, extrude, face_section, loft, loft_rails, loft_to_point, path_curve, project_onto_face, revolve, screw, screw_radial,
- sphere, sweep, sweep_controlled,
+ body_from_record, curve, extrude, extrude_drafted_with_holes, face_section, loft, loft_rails, loft_to_point, path_curve, project_onto_face,
+ revolve, screw, screw_radial, sphere, sweep, sweep_controlled,
};
/// Refuses what no SMLib sweep does, before any work.
@@ -447,6 +447,79 @@ mod imp {
with_history(body, &roles, pieces)
}
+ /// The solid `pieces` (one closed loop) on `plane` sweep, moved `from` along its normal and
+ /// drafted `d` over `distance` along `sign` × the normal, as [`extrude`] builds it, without
+ /// its roles.
+ fn drafted_loop(plane: &Plane, pieces: &[Piece], from: f64, distance: f64, sign: f64, d: Draft) -> Result<Brep> {
+ let base = plane.offset(from);
+ let n = plane.x.cross(plane.y).normalized().ok_or_else(|| KernelError::Invalid("profile plane".into()))?;
+ let dir = n * sign.signum();
+ if d.foot > 0.0 {
+ if !(d.foot < distance) {
+ return Err(KernelError::Invalid(format!("taper foot = {}", d.foot)));
+ }
+ let knee = plane.offset(from + sign.signum() * d.foot);
+ let lean = -(distance * d.taper.tan() / (distance - d.foot)).atan();
+ let prism =
+ Brep::extrude(&curves(&base, pieces)?, p(dir), d.foot, 0.0, DraftCorner::default(), true).map_err(|e| failed("extrude", e))?;
+ let slope =
+ Brep::extrude(&curves(&knee, pieces)?, p(dir), distance - d.foot, lean, corner(d.corner), true).map_err(|e| failed("extrude", e))?;
+ let brep = prism.boolean(&slope, solidcraft_smlib::BooleanOp::Union).map_err(|e| failed("extrude", e))?;
+ return brep.ok_or_else(|| failed("extrude", "nothing is left"));
+ }
+ Brep::extrude(&curves(&base, pieces)?, p(dir), distance, -d.taper, corner(d.corner), true).map_err(|e| failed("extrude", e))
+ }
+
+ /// A drafted extrusion of a region with holes: SMLib's draft extrusion takes one loop, so the
+ /// outer loop is drafted and each hole, turned counter-clockwise, is drafted the other way
+ /// and cut from it. Every wall leans by the taper on the material's side, as a single
+ /// drafted sweep would: a taper that narrows the outer boundary widens the holes. `outer` and
+ /// `holes` are the loops' pieces at `from` as [`extrude`] takes them, `all` the region's
+ /// pieces in their numbering (outer, then the holes as they bound the material), which the
+ /// walls' roles name.
+ pub(crate) fn extrude_drafted_with_holes(
+ plane: &Plane,
+ outer: &[Piece],
+ holes: &[Vec<Piece>],
+ all: &[Piece],
+ from: f64,
+ distance: f64,
+ sign: f64,
+ draft: Draft,
+ ) -> Result<Body> {
+ let mut brep = drafted_loop(plane, outer, from, distance, sign, draft)?;
+ for h in holes {
+ let cutter = drafted_loop(plane, h, from, distance, sign, Draft { taper: -draft.taper, ..draft })?;
+ brep = brep
+ .boolean(&cutter, solidcraft_smlib::BooleanOp::Subtract)
+ .map_err(|e| failed("extrude", e))?
+ .ok_or_else(|| KernelError::Invalid("the draft leaves nothing of the profile".into()))?;
+ }
+ let body = body_of(&brep, "extrude")?;
+ let base = plane.offset(from);
+ let top = plane.offset(from + sign.signum() * distance);
+ let low = roles(&body, &base, Some(&top), &seeds(&base, all, |q| q), &[], false)?;
+ let roles: Vec<Role> = if draft.foot > 0.0 {
+ // The sloping walls stand on their edges at the knee, as in [`extrude`].
+ let knee = plane.offset(from + sign.signum() * draft.foot);
+ let high = roles(&body, &knee, Some(&top), &seeds(&knee, all, |q| q), &[], false)?;
+ low.into_iter()
+ .zip(high)
+ .map(|(a, b)| match (a, b) {
+ (Role::Wall(mut x), Role::Wall(y)) => {
+ x.extend(y);
+ Role::Wall(x)
+ }
+ (Role::Unknown, w @ Role::Wall(_)) => w,
+ (a, _) => a,
+ })
+ .collect()
+ } else {
+ low
+ };
+ with_history(body, &roles, all)
+ }
+
/// The construction sources of a straight extrusion's faces along the normal of `sketch`, as
/// [`crate::extrude`] gives them: each cap the region at its end (both caps found once
/// each), each wall swept from one piece that piece as drawn, a line's with the wall's plane.
diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs
index a632470d1f..21abd4d90b 100644
--- a/crates/kernel/src/tests.rs
+++ b/crates/kernel/src/tests.rs
@@ -463,6 +463,21 @@ fn tapered_extrudes() {
assert!(rel(m.volume, v) < 5e-4, "{} vs {v}", m.volume);
assert!(m.bbox.max.z < 1e-6 && m.bbox.min.z > -10.0 - 1e-6, "{:?}", m.bbox);
assert!(extrude_tapered(&Plane::XY, &c, 10.0, 1.0, -60f64.to_radians(), crate::DraftCorner::default()).is_err(), "closes the profile");
+ // The square with a 10 × 10 square hole, 30 up, 5° inward: every wall leans in toward the
+ // material's outside, so the outer frustum narrows and the hole's widens; the solid is the
+ // one frustum less the other, with each wall a face of its own (four out, four in, two caps).
+ let t = 5f64.to_radians().tan();
+ let hole = Loop2::polygon(&[Vec2::new(-5.0, -5.0), Vec2::new(-5.0, 5.0), Vec2::new(5.0, 5.0), Vec2::new(5.0, -5.0)]);
+ let ring = Region2 { outer: sq.outer.clone(), holes: vec![hole] };
+ let b = extrude_tapered(&Plane::XY, &ring, 30.0, 1.0, -5f64.to_radians(), crate::DraftCorner::default()).unwrap();
+ let frustum = |a0: f64, a1: f64| 30.0 / 3.0 * (a0 * a0 + a1 * a1 + a0 * a1);
+ let v = frustum(40.0, 40.0 - 60.0 * t) - frustum(10.0, 10.0 + 60.0 * t);
+ let m = measure(&b).unwrap();
+ assert!(rel(m.volume, v) < 1e-6, "{} vs {v}", m.volume);
+ assert_eq!(m.merged.faces, 10);
+ // At 30° the hole would grow past the outer wall: refused, saying why.
+ let e = extrude_tapered(&Plane::XY, &ring, 30.0, 1.0, -30f64.to_radians(), crate::DraftCorner::default()).unwrap_err();
+ assert!(e.to_string().contains("hole"), "{e}");
}
/// A slot (two lines and two half-circles, tangent) tapered inward: every edge moves in by
diff --git a/crates/kernel/tests/chamfer_curved_holder.rs b/crates/kernel/tests/chamfer_curved_holder.rs
index 7006535f0d..f45ab14a60 100644
--- a/crates/kernel/tests/chamfer_curved_holder.rs
+++ b/crates/kernel/tests/chamfer_curved_holder.rs
@@ -59,7 +59,12 @@ fn chamfer_the_top_lip_at_a_tangent_wall_junction() {
assert_eq!(made.crossed_face_loops().unwrap(), 0);
let history = made.history().expect("the chamfer retains exact face provenance");
assert!(history.faces.iter().any(|f| f.origins.iter().any(|o| matches!(o, solidcraft_kernel::history::FaceOrigin::Edge { operand: 0, .. }))));
- let mesh = |body: &Body| body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.0005)).unwrap();
+ // Fine enough that the meshes' chord error is below the tolerance: the removed volume
+ // measured on meshes is 37.404 at chord 0.002, 37.672 at 0.0005, 37.761 at 0.0001 and 37.759
+ // at 0.00003, converged on the expected 37.762 (the chamfer as the chord between the contacts
+ // of a 2 mm ball). The planner's meshes of the two bodies differ, so their chord errors no
+ // longer cancel as truck's did.
+ let mesh = |body: &Body| body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.0001)).unwrap();
let before = mesh(&body).measure().volume;
let after = mesh(&made);
let removed = before - after.measure().volume;
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 9ecc3a6f0e..099cbdb4d4 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -170,3 +170,12 @@ The #303 draft used `solvecraft-container/1`. `crates/io/src/design.rs` accepts
marker alongside `solidcraft-container/1`, and writes only the new marker. Optional
old previews are discarded; required document/blob validation is unchanged. The
`draft_container_marker_remains_readable` regression covers this shim.
+
+## Split pieces in designs saved before format 14
+
+Builds before format 14 named the pieces a cut splits a body into in the old kernel's shell
+order, and the design's later features name the piece they work on by that name (`Body1`,
+`Body1 (1)`). SMLib orders pieces otherwise. Such a feature (`shell_piece_order` in the file)
+names its pieces so its later features find them: each name goes to the piece the points those
+features picked lie on. A name no later feature uses keeps SMLib's order. Designs saved since
+format 14 name pieces after their faces and are not affected.
diff --git a/tests/oracle/17-loft/expected.json b/tests/oracle/17-loft/expected.json
index 790fe3b19a..58fa78d83e 100644
--- a/tests/oracle/17-loft/expected.json
+++ b/tests/oracle/17-loft/expected.json
@@ -1,24 +1,34 @@
{
- "source": "freecad 1.1.4",
- "method": "FreeCAD (OpenCASCADE) build of recipe.json by tools/freecad-oracle/build.py: Part.makeLoft",
+ "source": "analytic",
+ "method": "ruled loft, square 40 at z 0 to circle r 10 at z 40, each side on one rational quarter of the circle (corner (20, -20) at -45 deg): A(t) = (1-t)^2 A_S + t^2 A_C + t(1-t) M, M = 1/2 int (S x C' + C x S') du (Gauss-Legendre on the exact rational arcs), V = h (A_S/3 + A_C/3 + M/6), z_c = h (A_S/12 + A_C/4 + M/12) / (V/h), wall area = int |P_u x P_t| du dt",
"body_count": 1,
- "volume_mm3": 35125.49757633739,
- "area_mm2": 6495.0000512370025,
+ "volume_mm3": 35080.725116114816,
+ "area_mm2": 6493.984396260195,
"center_of_mass": [
- 4.902280481153527e-11,
- 9.800242527565077e-16,
- 15.119060422795876
+ 0.0,
+ 0.0,
+ 15.112831028492234
],
"bbox": {
"min": [
- -20.0000001,
- -20.0000001,
- -1e-07
+ -20.0,
+ -20.0,
+ 0.0
],
"max": [
- 20.0000001,
- 20.0000001,
- 40.000000100000015
+ 20.0,
+ 20.0,
+ 40.0
]
- }
+ },
+ "faces": 6,
+ "note": "a difference of definition with the FreeCAD (OpenCASCADE) loft, which runs each side to the quarter at uniform angle (arc length): that correspondence has no exact rational B-spline form, and SolidCraft keeps its surfaces exact; OpenCASCADE's volume is 35125.50 mm^3 (0.13% more). The reference.stl is OpenCASCADE's, so the surface comparison is left out",
+ "compare": [
+ "body_count",
+ "volume_mm3",
+ "area_mm2",
+ "center_of_mass",
+ "bbox",
+ "faces"
+ ]
}
diff --git a/tools/oracle-analytic/cases_basic.py b/tools/oracle-analytic/cases_basic.py
index 23d343263d..08241bd23e 100644
--- a/tools/oracle-analytic/cases_basic.py
+++ b/tools/oracle-analytic/cases_basic.py
@@ -371,6 +371,74 @@ def c16_sweep():
"from the bend axis along the bisector) + 2 end disks", 1, mp.v, A, mp.com(), [-r, -r, 0], [50, r, 50 + r], 5)
+def c17_loft():
+ """A ruled loft from the 40 x 40 square at z = 0 to the circle r 10 at z = 40. Each side of the
+ square runs to one quarter of the circle, the corner (20, -20) to angle -45 deg, and both by
+ their own parameters: the side linearly, the quarter as the exact rational quadratic arc
+ (middle weight sqrt(2) / 2) that is the circle's B-spline form. Point (u, t) of a wall is
+ (1 - t) S(u) + t C(u) at height 40 t, so the section at t is the blend of the two loops and
+ its area A(t) = (1 - t)^2 A_S + t^2 A_C + t (1 - t) M with M the mixed area
+ 1/2 int (S x C' + C x S') du."""
+ h, half, r = 40.0, 20.0, 10.0
+ w = math.sqrt(2.0) / 2.0
+ corners = [(half, -half), (half, half), (-half, half), (-half, -half)]
+
+ def side(k, t):
+ (ax, ay), (bx, by) = corners[k], corners[(k + 1) % 4]
+ return (ax + (bx - ax) * t, ay + (by - ay) * t), (bx - ax, by - ay)
+
+ def quarter(k, t):
+ a0 = -PI / 4 + k * PI / 2
+ p0 = (r * math.cos(a0), r * math.sin(a0))
+ p2 = (r * math.cos(a0 + PI / 2), r * math.sin(a0 + PI / 2))
+ p1 = (p0[0] + p2[0], p0[1] + p2[1]) # the control polygon's corner, sqrt(2) r out
+ b = [(1 - t) ** 2, 2 * t * (1 - t) * w, t * t]
+ db = [-2 * (1 - t), 2 * (1 - 2 * t) * w, 2 * t]
+ d = sum(b)
+ dd = sum(db)
+ n = [sum(bi * q[i] for bi, q in zip(b, (p0, p1, p2))) for i in range(2)]
+ dn = [sum(bi * q[i] for bi, q in zip(db, (p0, p1, p2))) for i in range(2)]
+ return (n[0] / d, n[1] / d), ((dn[0] * d - n[0] * dd) / (d * d), (dn[1] * d - n[1] * dd) / (d * d))
+
+ xs, ws = GL
+ a_s, a_c = (2 * half) ** 2, PI * r * r
+ mixed = 0.0
+ area_walls = 0.0
+ for k in range(4):
+ for x, wu in zip(xs, ws):
+ u = 0.5 * (x + 1)
+ (s, ds), (c, dc) = side(k, u), quarter(k, u)
+ mixed += 0.5 * wu * 0.5 * ((s[0] * dc[1] - s[1] * dc[0]) + (c[0] * ds[1] - c[1] * ds[0]))
+ for y, wt in zip(xs, ws):
+ t = 0.5 * (y + 1)
+ pu = ((1 - t) * ds[0] + t * dc[0], (1 - t) * ds[1] + t * dc[1], 0.0)
+ pt = (c[0] - s[0], c[1] - s[1], h)
+ n = (pu[1] * pt[2] - pu[2] * pt[1], pu[2] * pt[0] - pu[0] * pt[2], pu[0] * pt[1] - pu[1] * pt[0])
+ area_walls += 0.25 * wu * wt * math.sqrt(sum(v * v for v in n))
+ int_a = a_s / 3 + a_c / 3 + mixed / 6
+ int_ta = a_s / 12 + a_c / 4 + mixed / 12
+ V = h * int_a
+ zc = h * int_ta / int_a
+ return result(
+ "ruled loft, square 40 at z 0 to circle r 10 at z 40, each side on one rational quarter of the circle "
+ "(corner (20, -20) at -45 deg): A(t) = (1-t)^2 A_S + t^2 A_C + t(1-t) M, M = 1/2 int (S x C' + C x S') du "
+ "(Gauss-Legendre on the exact rational arcs), V = h (A_S/3 + A_C/3 + M/6), z_c = h (A_S/12 + A_C/4 + M/12) / (V/h), "
+ "wall area = int |P_u x P_t| du dt",
+ 1,
+ V,
+ area_walls + a_s + a_c,
+ (0.0, 0.0, zc),
+ (-half, -half, 0.0),
+ (half, half, h),
+ faces=6,
+ note="a difference of definition with the FreeCAD (OpenCASCADE) loft, which runs each side to the quarter at "
+ "uniform angle (arc length): that correspondence has no exact rational B-spline form, and SolidCraft keeps its "
+ "surfaces exact; OpenCASCADE's volume is 35125.50 mm^3 (0.13% more). The reference.stl is OpenCASCADE's, so "
+ "the surface comparison is left out",
+ compare=["body_count", "volume_mm3", "area_mm2", "center_of_mass", "bbox", "faces"],
+ )
+
+
def c18_hole_features():
T = 15.0
mp = MP().add(*box_mp([0, 0, 0], [60, 40, T]))
@@ -542,6 +610,7 @@ CASES = {
"14-combine-cut": c14_combine_cut,
"15-combine-intersect": c15_combine_intersect,
"16-sweep": c16_sweep,
+ "17-loft": c17_loft,
"18-hole-features": c18_hole_features,
"19-l-bracket-constrained": c19_l_bracket,
"20-slot-constrained": c20_slot,