Skip to content

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

Wave 148/509: kernel: record.rs records history on the schema 4 record, by index (and 3 more)

jyviko38ef4e83cc5e
diff --git a/crates/kernel/src/assemble.rs b/crates/kernel/src/assemble.rs
index 127c62b7a2..d0581fd058 100644
--- a/crates/kernel/src/assemble.rs
+++ b/crates/kernel/src/assemble.rs
@@ -3,8 +3,7 @@
//! neighbours) starts from the body's record, takes faces away, adds faces bounded by new or
//! existing edges, and finishes into a record in canonical order (docs/native-brep.md): pcurves
//! from the record's one routine ([`solidcraft_geom::brep::pcurve`]) for every new use, the
-//! record's own for every use kept, edge uses, regions and shells. SMLib builds the body from
-//! that record, as from any other.
+//! record's own for every use kept, edge uses, regions and shells. The body is that record.
//!
//! Faces keep the record's convention as the operation gives them: each face's loops are seen
//! from the side the material is not on (the outward side), the outer loop counter-clockwise
@@ -19,7 +18,7 @@ use solidcraft_geom::brep::{
};
use crate::body::Body;
-use crate::history::{EdgeOrigin, EdgeProv, FaceProv, History};
+use crate::history::{EdgeOrigin, FaceProv};
use crate::{KernelError, Result};
fn invalid(m: impl std::fmt::Display) -> KernelError {
@@ -426,24 +425,12 @@ fn domain_of(surface: &Surface, pcurves: &[Vec<Curve2>], kept: Option<[[f64; 2];
Some(out)
}
-/// The body SMLib builds from `record`, and whether its faces and edges are numbered as the
-/// record's (then face i of the body is face i of the record, and so for edges).
-pub(crate) fn body_of(record: &Brep) -> Result<(Body, bool)> {
- let (brep, same) = crate::native::smlib_record_ordered(record)?;
- let (body, kept) = crate::native::body_from_smlib_ordered(&brep)?;
- Ok((body, same.is_some() && kept.is_some()))
-}
-
/// The body of `finished`, built from the one operand `from`, with the history whose faces are
/// `faces` (in the assembly's face order, taken-away faces skipped): each kept edge the operand
-/// edge it is, each new one where its two faces meet. No history where SMLib renumbered the
-/// record.
-pub(crate) fn body_with_history(finished: &Finished, assembly: &Assembly, from: &Body, faces: Vec<FaceProv>) -> Result<Body> {
- let (body, same) = body_of(&finished.record)?;
- let counts = crate::record::counts(&[from]);
- if !same {
- return Ok(body.with_checked_history(None, &counts));
- }
+/// edge it is, each re-made one the operand edges it is a piece of, each new one where its two
+/// faces meet ([`crate::record::of_faces`]). The body is the finished record, so its faces and
+/// edges are numbered as the record's.
+pub(crate) fn body_with_history(finished: Finished, assembly: &Assembly, from: &Body, faces: Vec<FaceProv>) -> Result<Body> {
// The provenance of each record face, from the assembly's face order.
let mut provs: Vec<Option<FaceProv>> = vec![None; finished.record.faces.len()];
let mut given = faces.into_iter();
@@ -451,30 +438,18 @@ pub(crate) fn body_with_history(finished: &Finished, assembly: &Assembly, from:
let p = given.next().ok_or_else(|| invalid("history: fewer faces than the body"))?;
*provs.get_mut(*k).ok_or_else(|| invalid("history: face"))? = Some(p);
}
- let mut faces: Vec<FaceProv> = provs.into_iter().collect::<Option<_>>().ok_or_else(|| invalid("history: a face without provenance"))?;
- crate::record::mark_shared_split(&mut faces);
- let edges = finished
- .record
+ let faces: Option<Vec<FaceProv>> = provs.into_iter().collect();
+ let edges: Vec<Vec<EdgeOrigin>> = finished
.edges
.iter()
- .zip(&finished.edges)
- .map(|(e, a)| {
- let mut between: Vec<usize> = e.uses.iter().map(|u| u.face as usize).collect();
- between.sort_unstable();
- between.dedup();
- let origins = match assembly.edges.get(*a) {
- Some(AEdge { source: Some(edge), .. }) => vec![EdgeOrigin::Edge { operand: 0, edge: *edge }],
- Some(AEdge { of, .. }) if !of.is_empty() => {
- let mut of = of.clone();
- of.sort_unstable();
- of.into_iter().map(|edge| EdgeOrigin::Edge { operand: 0, edge }).collect()
- }
- _ => crate::record::meeting(&between, &faces),
- };
- EdgeProv { faces: between, origins }
+ .map(|a| match assembly.edges.get(*a) {
+ Some(AEdge { source: Some(edge), .. }) => crate::record::pieces_of(0, [*edge]),
+ Some(AEdge { of, .. }) => crate::record::pieces_of(0, of.iter().copied()),
+ None => Vec::new(),
})
.collect();
- Ok(body.with_checked_history(Some(History { operands: 1, faces, edges }), &counts))
+ let body = Body::from_record(finished.record)?;
+ Ok(crate::record::attach(body, &crate::record::counts(&[from]), faces, &edges))
}
/// Whether the face `face` of `b` has its natural normal out of the material.
diff --git a/crates/kernel/src/boolean_history_tests.rs b/crates/kernel/src/boolean_history_tests.rs
index 9a939f8858..d8157d13b7 100644
--- a/crates/kernel/src/boolean_history_tests.rs
+++ b/crates/kernel/src/boolean_history_tests.rs
@@ -187,11 +187,11 @@ fn faces_of(h: &History) -> Vec<(Change, Vec<FaceOrigin>)> {
h.faces.iter().map(|f| (f.change, f.origins.clone())).collect()
}
-/// Truck's boolean with a sphere (no prism, no coincident faces): a box with a corner taken
+/// A boolean with a sphere (no prism, no coincident faces): a box with a corner taken
/// off by a sphere. The three faces at the corner get a notch, the sphere's patches inside the
/// box bound it, meeting the box's faces along new edges.
#[test]
-fn box_minus_sphere_through_truck() {
+fn box_minus_sphere() {
let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0);
let b = crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap();
let r = boolean(&a, &b, BoolOp::Cut).unwrap().unwrap();
@@ -212,30 +212,6 @@ fn box_minus_sphere_through_truck() {
assert!(meets(h).iter().all(|(x, y)| matches!((x, y), (FaceOrigin::Face { operand: 0, .. }, FaceOrigin::Face { operand: 1, .. }))));
}
-/// The jitter retries move both operands and the result back: the history holds for the
-/// operands themselves, the same faces coming from the same operand faces.
-#[test]
-fn shifted_truck_attempt_keeps_the_history() {
- let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0);
- let b = crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap();
- let counts = crate::record::counts(&[&a, &b]);
- let mut compared = 0;
- for op in [BoolOp::Cut, BoolOp::Union, BoolOp::Intersect] {
- let Ok((_, Some((plain, _)))) = crate::ops::truck_boolean(&a, &b, op, None, 0.035) else { continue };
- // The shifts the retries use (a hundredth of the size along each).
- for j in [[0.1373, 0.2719, 0.3911], [-0.5127, 0.0833, 0.2291], [0.6911, -0.3337, -0.6127]] {
- let shift = truck_modeling::Vector3::new(j[0], j[1], j[2]) * 0.17;
- let Ok((s, h)) = crate::ops::truck_boolean(&a, &b, op, Some(shift), 0.035) else { continue };
- let faces = h.as_ref().map(|(f, _)| f.clone());
- assert_eq!(faces, Some(plain.clone()), "{op:?}");
- let r = crate::boolean_record::truck_result(s, h, 17.4, &[], &counts).unwrap();
- verified(&r, &[&a, &b], 0.02);
- compared += 1;
- }
- }
- assert!(compared > 0);
-}
-
/// Two prisms along x, the tool's section inside the target's, overlapping in part: sewn slab by
/// slab, then healed. The target's face at x = 10 gets the tool's outline as a hole, which the
/// tool's sides meet; the tool's sides and far end stand out of it.
@@ -399,17 +375,6 @@ fn planar_fallback() {
}
}
-/// The nudged retry: a boolean with the tool moved a hair, composed with the move.
-#[test]
-fn nudged_tool_composes() {
- let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0);
- let b = crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap();
- let nb = crate::transform(&b, Vec3::new(1e-5, 0.0, 0.0), Vec3::ZERO, Vec3::Z, 0.0).unwrap();
- let r = boolean(&a, &nb, BoolOp::Cut).unwrap().unwrap();
- let r = crate::ops::nudged(r, &nb, &crate::record::counts(&[&a, &b]));
- verified(&r, &[&a, &b], 0.02);
-}
-
/// A boolean with a triangle mesh: the mesh's faces are its triangles (and it has no edges).
#[test]
fn faceted_tool() {
@@ -593,7 +558,7 @@ mod smlib {
let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0);
for (name, b) in [("edge", boxed(10.0, 10.0, 0.0, 20.0, 20.0, 10.0)), ("vertex", boxed(10.0, 10.0, 10.0, 20.0, 20.0, 20.0))] {
let r = through_smlib(&a, &b, BoolOp::Union);
- assert_eq!(r.solid.boundaries().len(), 2, "{name}");
+ assert_eq!(r.shell_count(), 2, "{name}");
assert_eq!((r.face_count(), r.edge_count()), (12, 24), "{name}");
let v = crate::measure(&r).unwrap().volume;
assert!((v - 2000.0).abs() < 1e-6 * 2000.0, "{name}: {v}");
@@ -609,7 +574,7 @@ mod smlib {
let a = boxed(0.0, 0.0, 0.0, 20.0, 20.0, 10.0);
let once = through_smlib(&a, &boxed(10.0, -1.0, -1.0, 21.0, 10.0, 11.0), BoolOp::Cut);
let r = through_smlib(&once, &boxed(-1.0, 10.0, -1.0, 10.0, 21.0, 11.0), BoolOp::Cut);
- assert_eq!(r.solid.boundaries().len(), 2);
+ assert_eq!(r.shell_count(), 2);
let v = crate::measure(&r).unwrap().volume;
assert!((v - 2000.0).abs() < 1e-6 * 2000.0, "{v}");
}
@@ -625,7 +590,7 @@ mod smlib {
for (name, z0, depth) in [("through", -1.0, 12.0), ("blind", 2.0, 9.0)] {
let b = crate::cylinder(Vec3::new(10.0, 15.0, z0), Vec3::Z, 5.0, depth).unwrap();
let r = through_smlib(&a, &b, BoolOp::Cut);
- assert_eq!(r.solid.boundaries().len(), 1, "{name}");
+ assert_eq!(r.shell_count(), 1, "{name}");
let record = crate::brep_record(&r).unwrap();
assert!(record.edges.iter().all(|e| e.uses.len() == 2), "{name}");
let hole = std::f64::consts::PI * 25.0 * (10.0 - z0.max(0.0));
diff --git a/crates/kernel/src/boolean_record.rs b/crates/kernel/src/boolean_record.rs
index 491780bacb..bceaca9a40 100644
--- a/crates/kernel/src/boolean_record.rs
+++ b/crates/kernel/src/boolean_record.rs
@@ -1,20 +1,13 @@
-//! Recording the exact history of a boolean's result, whichever path made it (see
-//! [`crate::ops::boolean`]): for each result face, the operand faces it is a region of; for each
-//! result edge, the operand edges it lies along or the operand faces whose meeting it is. The
-//! operands are `[a, b]`: the target, then the tool. Paths compose the histories of the steps
-//! they take ([`History::over`], [`History::substitute`]); a path that cannot leaves the result
-//! without history.
-
-use std::collections::HashMap;
-
-use solidcraft_geom::Vec3;
-use truck_modeling as mt;
+//! Composing the exact history of a multi-step operation (a boolean through several steps, a
+//! local modifier on a healed body): each step's history over its own operands is placed among
+//! the operation's operands ([`placed`], [`kept`]) and substituted into the next
+//! ([`through`], [`of_pair`], [`crate::record::after`]). The operands of a boolean are `[a, b]`:
+//! the target, then the tool. A step that cannot report its history leaves the result without
+//! one.
use crate::Result;
-use crate::body::{Body, Solid, edge_order};
-use crate::history::BodyHistory;
-use crate::history::{Change, EdgeOrigin, FaceOrigin, FaceProv, History};
-use crate::record;
+use crate::body::Body;
+use crate::history::{BodyHistory, History};
/// A composition step's history, or none (logged) where the lineage can't be expressed.
pub(crate) fn composed<E: std::fmt::Display>(h: std::result::Result<History, E>) -> Option<History> {
@@ -44,19 +37,6 @@ pub(crate) fn operand(body: &Body, operand: usize, counts: &[(usize, usize)]) ->
body.clone().with_checked_history(kept(body, operand, counts.len()), counts)
}
-/// The histories of `parts`, each made of shells of `whole` (its lumps), over `[whole]`: their
-/// faces and edges are the whole's own (by identity).
-pub(crate) fn parts_of(parts: &[Body], whole: &Body) -> Vec<Option<History>> {
- let (faces, edges) = (record::face_index(&whole.solid), record::edge_origins(&whole.solid, 0));
- parts
- .iter()
- .map(|part| {
- let faces = part.solid.face_iter().map(|f| Some(record::from_face(0, *faces.get(&f.id())?, Change::Kept))).collect::<Option<Vec<_>>>()?;
- Some(History { operands: 1, faces, edges: record::edge_provs(part, &edges)? })
- })
- .collect()
-}
-
/// A body with its history over the operation's operands (`None`: not known).
pub(crate) type Traced = (Body, Option<History>);
@@ -66,169 +46,14 @@ pub(crate) fn of_pair(result: &Body, x: &Option<History>, y: &Option<History>) -
composed(result.history()?.clone().over(&[x.as_ref()?, y.as_ref()?]))
}
-/// Bodies apart from each other, each with its history over the operation's operands (with
-/// `counts` faces and edges), as one body of several pieces whose history is theirs side by side.
-pub(crate) fn join(pieces: Vec<Traced>, counts: &[(usize, usize)]) -> Result<Option<Body>> {
- if pieces.len() < 2 {
- return Ok(pieces.into_iter().next().map(|(b, h)| b.with_checked_history(h, counts)));
- }
- // The pieces' shells in order: their faces in order, their edges themselves.
- let mut faces = Some(Vec::new());
- let mut edges = HashMap::new();
- for (p, h) in &pieces {
- let (Some(h), Some(all)) = (h, faces.as_mut()) else {
- faces = None;
- break;
- };
- all.extend(h.faces.iter().cloned());
- edges.extend(record::edges_by_identity(p, h));
- }
- if let Some(faces) = faces.as_mut() {
- record::mark_shared_split(faces);
- }
- let joined = crate::ops::join_pieces(pieces.into_iter().map(|(p, _)| p).collect())?;
- Ok(joined.map(|body| record::traced(body, counts, faces, Some(&edges))))
-}
-
-/// A truck boolean's history in our terms, in the order of the solid it made: each face a
-/// region of one operand face (Kept when that very face), each edge's origins.
-pub(crate) type Shapeops = (Vec<FaceProv>, Vec<Vec<EdgeOrigin>>);
-
-/// A truck boolean's history in our terms ([`Shapeops`]). `tool` is the
-/// tool as passed (after a cut turned it inside out, which keeps its faces' order but walks each
-/// face's edges the other way, so its edge order changes) and `tool_edges` its edges by identity
-/// in its own order (before turning).
-pub(crate) fn shapeops(h: &truck_shapeops::History, tool: &Solid, tool_edges: Option<&HashMap<mt::EdgeID, Vec<EdgeOrigin>>>) -> Option<Shapeops> {
- let face = |f: truck_shapeops::FaceIndex| FaceOrigin::Face { operand: f.operand, face: f.face };
- let faces =
- h.faces.iter().map(|o| record::from_face(o.source.operand, o.source.face, if o.kept { Change::Kept } else { Change::Modified })).collect();
- let passed: Vec<mt::EdgeID> = edge_order(tool.face_iter()).0.iter().map(|e| e.id()).collect();
- let edges = h
- .edges
- .iter()
- .map(|o| match *o {
- truck_shapeops::EdgeOrigin::Edge { operand: 1, edge } if tool_edges.is_some() => {
- tool_edges.and_then(|t| t.get(passed.get(edge)?)).cloned()
- }
- truck_shapeops::EdgeOrigin::Edge { operand, edge } => Some(vec![EdgeOrigin::Edge { operand, edge }]),
- truck_shapeops::EdgeOrigin::Meet { a, b } => Some(vec![EdgeOrigin::meet(face(a), face(b))]),
- })
- .collect::<Option<Vec<_>>>()?;
- Some((faces, edges))
-}
-
-/// Samples along each edge when checking that its curve evaluates.
-const EVALUATION_SAMPLES: usize = 32;
-
-/// Whether every edge of `solid` evaluates along its whole range. An intersection curve projects
-/// its leader's point onto both surfaces, which fails to converge where a boolean made the edge
-/// from an approximation that strayed (#1252). Such a result is no solid to keep: the mesher,
-/// healing and measuring all sample the edge and stumble over the gap.
-pub(crate) fn edges_evaluate(solid: &Solid) -> bool {
- use truck_meshalgo::prelude::TrySubs;
- use truck_modeling::BoundedCurve;
- solid.boundaries().iter().flat_map(|shell| shell.edge_iter()).all(|edge| {
- let curve = edge.curve();
- let (t0, t1) = curve.range_tuple();
- (0..=EVALUATION_SAMPLES).all(|k| {
- let t = t0 + (t1 - t0) * k as f64 / EVALUATION_SAMPLES as f64;
- curve.try_subs(t).is_some_and(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite())
- })
- })
-}
-
-/// The body made of `solid` healed (keeping faces apart along `keep`), with the history whose
-/// faces and edges (in `solid`'s orders) are given before healing, carried through it.
-/// Operands with `counts` faces and edges. A result with an edge that does not evaluate is
-/// refused (see [`edges_evaluate`]).
-pub(crate) fn heal_build(
- solid: Solid,
- size: f64,
- keep: &[Vec<Vec3>],
- faces: Option<Vec<FaceProv>>,
- edges: Option<Vec<Vec<EdgeOrigin>>>,
- counts: &[(usize, usize)],
-) -> Result<Body> {
- let (healed, map) = crate::heal::heal_traced(solid, size, keep);
- if !edges_evaluate(&healed) {
- return Err(crate::KernelError::Failed("an edge of the result does not evaluate".into()));
- }
- let carried = faces.zip(edges).zip(map).and_then(|((f, e), m)| m.carry(&f, &e));
- let (faces, edges) = carried.unzip();
- record::build(healed, counts, faces, edges.as_ref())
-}
-
-/// The body truck's result `s` makes, healed (see [`heal_build`]), with its history `h`.
-pub(crate) fn truck_result(s: Solid, h: Option<Shapeops>, size: f64, keep: &[Vec<Vec3>], counts: &[(usize, usize)]) -> Result<Body> {
- let (faces, edges) = h.unzip();
- heal_build(s, size, keep, faces, edges, counts)
-}
-
-/// `body` healed (see [`heal_build`]), its history carried through: `solid` is `body`'s solid
-/// or a copy of it (`Body::deep_copy`, which keeps its order).
-pub(crate) fn heal_body(body: &Body, solid: Solid, size: f64, keep: &[Vec<Vec3>], counts: &[(usize, usize)]) -> Result<Body> {
- let (faces, edges) = body.history().map(|h| (h.faces.clone(), h.edges.iter().map(|e| e.origins.clone()).collect())).unzip();
- heal_build(solid, size, keep, faces, edges, counts)
-}
-
-/// A prism boolean's result `body` with the coplanar pieces its slabs leave merged (nothing
-/// else healed: its edges are exact as they are), its history carried through, and what else it carries kept: each face's
-/// construction source where every piece merged into it had that same one, its Split Face
-/// lines and its regularization protection.
-pub(crate) fn heal_prism_result(body: &Body, size: f64, keep: &[Vec<Vec3>], counts: &[(usize, usize)]) -> Result<Body> {
- let (faces, edges): (Option<Vec<FaceProv>>, Option<Vec<Vec<EdgeOrigin>>>) =
- body.history().map(|h| (h.faces.clone(), h.edges.iter().map(|e| e.origins.clone()).collect())).unzip();
- let (healed, map) = crate::heal::merge_faces_traced((*body.solid).clone(), size, keep);
- let sources = match (body.face_sources(), &map) {
- (Some(sources), Some(m)) => Some(
- m.faces
- .iter()
- .map(|under| {
- let mut each = under.iter().map(|i| sources.get(*i).cloned().flatten());
- let first = each.next().flatten()?;
- each.all(|s| s.as_ref() == Some(&first)).then_some(first)
- })
- .collect::<Vec<_>>(),
- ),
- _ => None,
- };
- let carried = faces.zip(edges).zip(map).and_then(|((f, e), m)| m.carry(&f, &e));
- let (faces, edges) = carried.unzip();
- let mut out = record::build(healed, counts, faces, edges.as_ref())?;
- out = out.with_face_sources(sources.map(std::sync::Arc::new)).inherit_regularization_protection(body);
- out.splits = body.splits.clone();
- Ok(out)
-}
-
-/// `body` healed as the local modifiers take it (coplanar neighbours as one face, as after a
-/// join; faces split on purpose kept apart), with its history over `[body]`.
+/// `body` healed as the local modifiers take it (faces on one surface as one face, as after a
+/// join; faces split on purpose kept apart), with its history over `[body]`
+/// ([`crate::heal::heal`]), each face keeping the construction source its faces shared and the
+/// body its regularization protection.
pub(crate) fn healed(body: &Body) -> Result<Body> {
- let counts = record::counts(&[body]);
- heal_body(&operand(body, 0, &counts), body.deep_copy(), body.size(), body.split_keep(), &counts)
-}
-
-/// `body` copied as it is, unhealed (`Body::deep_copy`, which keeps its face and edge order),
-/// with its history over `[body]`: every face and edge kept.
-pub(crate) fn copied(body: &Body) -> Result<Body> {
- let copy = Body::new(body.deep_copy())?;
- Ok(operand(&copy, 0, &record::counts(&[body])))
-}
-
-/// The faces and edges of `a`, then of the tool `b` turned inside out as a void (`inner`, a
-/// copy of `b`, with `inner_edges` its edges by identity before turning): the history of
-/// `a` with `b`'s inside taken out where `b` lies wholly within it.
-pub(crate) fn void(
- a: &Body,
- inner_edges: HashMap<mt::EdgeID, Vec<EdgeOrigin>>,
- b_faces: usize,
-) -> (Vec<FaceProv>, HashMap<mt::EdgeID, Vec<EdgeOrigin>>) {
- let faces = (0..a.face_count())
- .map(|i| record::from_face(0, i, Change::Kept))
- .chain((0..b_faces).map(|i| record::from_face(1, i, Change::Kept)))
- .collect();
- let mut edges = record::edge_origins(&a.solid, 0);
- edges.extend(inner_edges);
- (faces, edges)
+ let healed = crate::heal::heal(body, body.split_keep())?;
+ let sources = healed.history().map(|h| std::sync::Arc::new(h.face_sources(&[body])));
+ Ok(healed.with_face_sources(sources).inherit_regularization_protection(body))
}
#[cfg(test)]
diff --git a/crates/kernel/src/delete_face.rs b/crates/kernel/src/delete_face.rs
index 07a802af0c..db483895af 100644
--- a/crates/kernel/src/delete_face.rs
+++ b/crates/kernel/src/delete_face.rs
@@ -318,7 +318,7 @@ pub fn delete_faces(body: &Body, faces: &[usize]) -> Result<Body> {
}
}
let finished = asm.finish().map_err(|e| fail(format!("the neighbouring faces do not close the gap ({e})")))?;
- crate::assemble::body_with_history(&finished, &asm, body, history)
+ crate::assemble::body_with_history(finished, &asm, body, history)
})
}
diff --git a/crates/kernel/src/emboss.rs b/crates/kernel/src/emboss.rs
index 7e35b1cd38..a883c4bceb 100644
--- a/crates/kernel/src/emboss.rs
+++ b/crates/kernel/src/emboss.rs
@@ -389,7 +389,7 @@ fn emboss_impl(body: &Body, anchor: Option<Vec3>, plane: &Plane, regions: &[Regi
asm.face(f);
}
let finished = asm.finish()?;
- let result = crate::assemble::body_with_history(&finished, &asm, body, history)?;
+ let result = crate::assemble::body_with_history(finished, &asm, body, history)?;
if !result.validity().is_empty() {
return Err(fail("rebuilt cylinder is not a closed manifold"));
}
diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs
index 7a8fdcc019..9b05d8fc1d 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -169,7 +169,7 @@ pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDG
pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid};
pub use build::{
PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, extrude_whole_sides, loft, loft_regions,
- loft_with_rails, path_polyline, revolve, revolve_whole, sphere, sweep, sweep_with, torus,
+ loft_with_rails, path_polyline, planar_face_record, revolve, revolve_whole, sphere, sweep, sweep_with, torus,
};
pub use clearance::{Clearance, Occupancy};
pub use coaxial_overlap::{CoaxialOverlap, coaxial_candidate, coaxial_overlap};
@@ -202,7 +202,7 @@ pub use ops::{
BoolOp, boolean, can_join_all_touching_faces, can_join_touching_faces, compound_disjoint_extrusions, half_space, is_planar, join_apart,
place_matrix, split_by_plane, transform, transform_matrix, union_apart, with_attempt_budget,
};
-pub use point_path::{PathPiece, PointPath, sweep_point_path_with};
+pub use point_path::{PathPiece, PointPath, SpaceBezier, curve_path, edge_path, sketch_record_curve, sweep_point_path_with};
pub use polybool::faceted_boolean;
pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell};
pub use prism::{PLANAR_FIT_TOL, extrude_planar_regions, planar_regions_boolean};
diff --git a/crates/kernel/src/lip.rs b/crates/kernel/src/lip.rs
index 09dcd2dfa1..a191a9b3c1 100644
--- a/crates/kernel/src/lip.rs
+++ b/crates/kernel/src/lip.rs
@@ -355,7 +355,7 @@ pub fn raise_band(body: &Body, at: Vec3, width: f64, height: f64, outside: bool)
}
asm.face(top);
let finished = asm.finish()?;
- let b = crate::assemble::body_with_history(&finished, &asm, body, history)?;
+ let b = crate::assemble::body_with_history(finished, &asm, body, history)?;
let problems = b.validity();
if !problems.is_empty() {
return Err(fail(&problems.join("; ")));
diff --git a/crates/kernel/src/record.rs b/crates/kernel/src/record.rs
index d7dbf5d0e0..50190bd01e 100644
--- a/crates/kernel/src/record.rs
+++ b/crates/kernel/src/record.rs
@@ -1,23 +1,16 @@
-//! Recording the exact history of the bodies the creation builders make (extrude, revolve,
-//! sweeps, lofts, primitives, and the builders that rebuild a body around new faces), by
-//! topology identity inside the building call: which face a profile edge was swept into,
-//! which edges an operand still owns. Nothing is sampled.
-//!
-//! Faces our code builds are paired with their provenance as they are made (a [`Side`]); only
-//! where truck makes the faces itself (`tsweep`, `rsweep`, `cone`) are they found afterwards,
-//! by following each profile edge's column of swept faces ([`follow`]). Profile segments are
-//! numbered by [`crate::numbered`].
+//! Recording the exact history of the bodies operations build on the schema 4 record: for each
+//! result face, what it is made from (operand faces it is the whole of or a piece of, profile
+//! segments, caps, operand edges a blend replaces); for each result edge, the operand edges it is
+//! or is a piece of, and otherwise the meeting of the two faces it separates. Indices are the
+//! records' canonical ones, the result's and each operand's. Nothing is sampled: the building
+//! code says what it built from what. Profile segments are numbered by [`crate::numbered`].
-use std::collections::{BTreeSet, HashMap};
+use std::collections::BTreeSet;
-use truck_modeling as mt;
+use solidcraft_geom::brep::Brep;
-use crate::Result;
-use crate::body::{Body, Solid, edge_order};
-use crate::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History};
-
-/// A face as built, with its provenance (`None` where the construction could not be followed).
-pub(crate) type Side = (mt::Face, Option<FaceProv>);
+use crate::body::Body;
+use crate::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History, edge_faces};
/// A face made from all of profile segments `numbers` (in any order, repeats allowed).
pub(crate) fn profile<'a>(numbers: impl IntoIterator<Item = &'a usize>) -> FaceProv {
@@ -70,112 +63,47 @@ pub(crate) fn region(origins: BTreeSet<FaceOrigin>, whole: bool) -> FaceProv {
pub(crate) use solidcraft_geom::brep::history::mark_shared_split;
-/// The index of each of `solid`'s edges by identity, in its edge order.
-pub(crate) fn edge_index(solid: &crate::body::Solid) -> HashMap<mt::EdgeID, usize> {
- edge_order(solid.face_iter()).0.iter().enumerate().map(|(i, e)| (e.id(), i)).collect()
-}
-
-/// The index of each of `solid`'s faces by identity, in its face order.
-pub(crate) fn face_index(solid: &crate::body::Solid) -> HashMap<mt::FaceID, usize> {
- solid.face_iter().enumerate().map(|(i, f)| (f.id(), i)).collect()
-}
-
-/// Each of `solid`'s edges, by identity, as edge `i` (its position in the solid's edge order) of
-/// operand `operand`: the operand's own edges, or a copy's made by `Body::deep_copy` or truck's
-/// mapping builders (`translated`, `transformed`), which build the same faces, wires and edges
-/// in the same order, so position `i` of the copy is position `i` of the body it copies.
-pub(crate) fn edge_origins(solid: &crate::body::Solid, operand: usize) -> HashMap<mt::EdgeID, Vec<EdgeOrigin>> {
- edge_order(solid.face_iter()).0.iter().enumerate().map(|(edge, e)| (e.id(), vec![EdgeOrigin::Edge { operand, edge }])).collect()
+/// The origins of a result edge that is (a piece of, or the moved) edges `edges` of operand
+/// `operand`.
+pub(crate) fn pieces_of(operand: usize, edges: impl IntoIterator<Item = usize>) -> Vec<EdgeOrigin> {
+ let edges: BTreeSet<usize> = edges.into_iter().collect();
+ edges.into_iter().map(|edge| EdgeOrigin::Edge { operand, edge }).collect()
}
-/// The edge entries of the history of `body`, each edge's origins from `origins` (by identity);
-/// `None` when an edge has none there.
-pub(crate) fn edge_provs(body: &Body, origins: &HashMap<mt::EdgeID, Vec<EdgeOrigin>>) -> Option<Vec<EdgeProv>> {
- let (edges, bounds) = edge_order(body.solid.face_iter());
- edges.iter().zip(bounds).map(|(e, faces)| Some(EdgeProv { faces, origins: origins.get(&e.id())?.clone() })).collect()
+/// The history over `operands` operands of `result`, whose faces (in its face order) come from
+/// `faces` (an operand face shared by several result faces is marked Split), and whose edges come
+/// from `edges` (by result edge index) where the building code knows them: an operand edge it
+/// kept or re-made ([`pieces_of`]). Every other edge separates two faces that met nowhere before,
+/// so it comes from their meeting ([`meeting`]).
+pub(crate) fn of_faces(result: &Brep, operands: usize, mut faces: Vec<FaceProv>, edges: &[Vec<EdgeOrigin>]) -> History {
+ mark_shared_split(&mut faces);
+ let edges = edge_faces(result)
+ .into_iter()
+ .enumerate()
+ .map(|(i, between)| {
+ let origins = match edges.get(i) {
+ Some(known) if !known.is_empty() => known.clone(),
+ _ => meeting(&between, &faces),
+ };
+ EdgeProv { faces: between, origins }
+ })
+ .collect();
+ History { operands, faces, edges }
}
-/// `body` with the history whose faces are `faces` (in its face order) and whose edges'
-/// origins are `edges` (by identity), made from operands with the face and edge `counts`; with
-/// no history where either is missing, an edge has no entry, or the history does not describe
-/// the body (an operation whose history could not be recorded still gives its result).
-pub(crate) fn traced(
- body: Body,
- counts: &[(usize, usize)],
- faces: Option<Vec<FaceProv>>,
- edges: Option<&HashMap<mt::EdgeID, Vec<EdgeOrigin>>>,
-) -> Body {
- let history = faces.zip(edges).and_then(|(faces, edges)| Some(History { operands: counts.len(), faces, edges: edge_provs(&body, edges)? }));
+/// `body`, made from operands with these face and edge `counts`, with the history [`of_faces`]
+/// gives (none where the faces could not be followed, `None`, or the history does not describe
+/// the body: an operation whose history could not be recorded still gives its result).
+pub(crate) fn attach(body: Body, counts: &[(usize, usize)], faces: Option<Vec<FaceProv>>, edges: &[Vec<EdgeOrigin>]) -> Body {
+ let history = faces.map(|faces| of_faces(body.record(), counts.len(), faces, edges));
body.with_checked_history(history, counts)
}
-/// [`traced`] of the body `Body::new` makes of `solid`: faces given in `solid`'s face order
-/// and edges by identity, both of which `Body::new` keeps.
-pub(crate) fn build(
- solid: crate::body::Solid,
- counts: &[(usize, usize)],
- faces: Option<Vec<FaceProv>>,
- edges: Option<&HashMap<mt::EdgeID, Vec<EdgeOrigin>>>,
-) -> Result<Body> {
- Ok(traced(Body::new(solid)?, counts, faces, edges))
-}
-
-/// [`build`] for a solid made by placing an already-oriented copy: the orientation comes from
-/// the placement matrix instead of meshing the whole solid again (see
-/// [`crate::body::Body::new_placed`]).
-pub(crate) fn build_placed(
- solid: crate::body::Solid,
- counts: &[(usize, usize)],
- faces: Option<Vec<FaceProv>>,
- edges: Option<&HashMap<mt::EdgeID, Vec<EdgeOrigin>>>,
- flip: bool,
- coarse: Option<(f64, usize)>,
- phased: bool,
-) -> Result<Body> {
- Ok(traced(Body::new_placed(solid, flip, coarse, phased)?, counts, faces, edges))
-}
-
-/// The origins of `body`'s edges by identity, from its history `h` (edges in its edge order).
-pub(crate) fn edges_by_identity<'a>(body: &'a Body, h: &'a History) -> impl Iterator<Item = (mt::EdgeID, Vec<EdgeOrigin>)> + 'a {
- edge_order(body.solid.face_iter()).0.into_iter().zip(&h.edges).map(|(e, p)| (e.id(), p.origins.clone()))
-}
-
/// The face and edge counts of `bodies`, for [`traced`].
pub(crate) fn counts(bodies: &[&Body]) -> Vec<(usize, usize)> {
bodies.iter().map(|b| (b.face_count(), b.edge_count())).collect()
}
-/// An operation's operand, with its edges indexed by identity (in its edge order).
-pub(crate) struct Operand<'a> {
- pub body: &'a Body,
- pub edges: HashMap<mt::EdgeID, usize>,
-}
-
-impl<'a> Operand<'a> {
- pub(crate) fn new(body: &'a Body) -> Operand<'a> {
- Operand { body, edges: edge_index(&body.solid) }
- }
-}
-
-/// Attach to `body`, made from `operands`, the history whose faces are `faces` (in its face
-/// order); a body whose faces could not be followed (`None`) has no history. Each edge's
-/// origin is the operand edge it is (the very edge, kept by the building code), or what
-/// `copies` says: result edges the building code made as exact copies of operand edges.
-pub(crate) fn attach(body: Body, operands: &[Operand], faces: Option<Vec<FaceProv>>, copies: HashMap<mt::EdgeID, EdgeOrigin>) -> Result<Body> {
- let Some(faces) = faces else { return Ok(body) };
- let mut owned = copies;
- for (operand, o) in operands.iter().enumerate() {
- for (id, edge) in &o.edges {
- owned.entry(*id).or_insert(EdgeOrigin::Edge { operand, edge: *edge });
- }
- }
- let (edges, bounds) = edge_order(body.solid.face_iter());
- let edges = edges.iter().zip(bounds).map(|(e, faces)| EdgeProv { faces, origins: owned.get(&e.id()).cloned().into_iter().collect() }).collect();
- let history = History { operands: operands.len(), faces, edges };
- let counts: Vec<(usize, usize)> = operands.iter().map(|o| (o.body.face_count(), o.edges.len())).collect();
- body.with_history_counts(history, &counts)
-}
-
/// `step`, made from `prev` (the step's one operand), with its history carried back to what
/// `prev` was made from: the operation's operands, with `counts` faces and edges. A multi-step
/// operation starts from its operand with [`crate::boolean_record::operand`] (or healed, see
@@ -186,146 +114,6 @@ pub(crate) fn after(mut step: Body, prev: &Body, counts: &[(usize, usize)]) -> B
step.with_checked_history(h, counts)
}
-/// The history over `operands` operands of a body made by building `solid`, whose faces (in its
-/// face order) come from `faces`: each edge new, where its two faces meet ([`meeting`]).
-pub(crate) fn from_faces(solid: &Solid, operands: usize, faces: Vec<FaceProv>) -> History {
- let edges = edge_order(solid.face_iter()).1.into_iter().map(|between| EdgeProv { origins: meeting(&between, &faces), faces: between }).collect();
- History { operands, faces, edges }
-}
-
-/// What a result face of a local rebuild was made from, by identity: an operand face it was
-/// rebuilt from, or an operand edge it was made in place of (a blend).
-#[derive(Clone, Copy, Debug)]
-pub(crate) enum Was {
- Face(mt::FaceID),
- Edge(mt::EdgeID),
-}
-
-/// What an operation built from its operands' topology, recorded by identity while the
-/// operands and the result are both alive: the faces it made (each from what [`Was`], and
-/// whether it is the whole of the one operand face it was rebuilt from: the same region) and
-/// the edges it made as (parts of, or joins of) operand edges. A result face or edge that is an
-/// operand's own (the very same topology, kept by the building code) is that, whatever was
-/// recorded for it. Every
-/// other edge is new, and comes from the meeting of the two faces it separates
-/// ([`Rebuild::history`]). The record holds what it names, so that no identity it was given is
-/// reused by later topology while it lives.
-#[derive(Debug, Default)]
-pub(crate) struct Rebuild {
- faces: HashMap<mt::FaceID, (mt::Face, Vec<Was>, bool)>,
- edges: HashMap<mt::EdgeID, (mt::Edge, Vec<mt::EdgeID>)>,
-}
-
-impl Rebuild {
- /// `new` is `from` rebuilt (trimmed differently, moved).
- pub(crate) fn face(&mut self, new: &mt::Face, from: &mt::Face) {
- self.made(new, vec![Was::Face(from.id())]);
- }
-
- /// `new` is `from` rebuilt over the same region (its boundary edges cut or re-made).
- pub(crate) fn whole(&mut self, new: &mt::Face, from: &mt::Face) {
- self.faces.insert(new.id(), (new.clone(), vec![Was::Face(from.id())], true));
- }
-
- /// `new` is made in place of the operand edges `edges` (a blend; a corner patch lists the
- /// edges meeting at its corner).
- pub(crate) fn blend(&mut self, new: &mt::Face, edges: impl IntoIterator<Item = mt::EdgeID>) {
- self.made(new, edges.into_iter().map(Was::Edge).collect());
- }
-
- /// `new` is made from what `was` says (nothing: new to the operation).
- pub(crate) fn made(&mut self, new: &mt::Face, was: Vec<Was>) {
- self.faces.insert(new.id(), (new.clone(), was, false));
- }
-
- /// `new` is (a piece of, or the moved) edge `of`: an operand edge, or an edge recorded as
- /// made from operand edges (a piece of a piece is a piece of the operand edge).
- pub(crate) fn piece(&mut self, new: &mt::Edge, of: &mt::Edge) {
- self.piece_of(new, of.id());
- }
-
- /// Every piece in `subst` (edge → the edge made in its place).
- pub(crate) fn pieces<'a>(&mut self, subst: impl IntoIterator<Item = (&'a mt::EdgeID, &'a mt::Edge)>) {
- for (old, new) in subst {
- self.piece_of(new, *old);
- }
- }
-
- fn piece_of(&mut self, new: &mt::Edge, of: mt::EdgeID) {
- let roots = self.edges.get(&of).map_or_else(|| vec![of], |(_, roots)| roots.clone());
- let (_, slot) = self.edges.entry(new.id()).or_insert_with(|| (new.clone(), Vec::new()));
- for root in roots {
- if !slot.contains(&root) {
- slot.push(root);
- }
- }
- }
-
- /// The history of `result` (in its face order; edges by identity) made from `operands`
- /// (their solids, in the operation's operand order): faces and edges that are an operand's
- /// own by identity (several operands' when they share it), the rest as recorded; an edge
- /// recorded nowhere separates two faces that met nowhere before, so it comes from their
- /// meeting ([`meeting`]). `None` when a face is neither an operand's nor recorded, or a record
- /// names topology no operand has.
- pub(crate) fn history(&self, result: &Solid, operands: &[&Solid]) -> Option<(Vec<FaceProv>, HashMap<mt::EdgeID, Vec<EdgeOrigin>>)> {
- let mut face_at: HashMap<mt::FaceID, Vec<FaceOrigin>> = HashMap::new();
- let mut edge_at: HashMap<mt::EdgeID, Vec<(usize, usize)>> = HashMap::new();
- for (operand, s) in operands.iter().enumerate() {
- for (id, face) in face_index(s) {
- face_at.entry(id).or_default().push(FaceOrigin::Face { operand, face });
- }
- for (id, edge) in edge_index(s) {
- edge_at.entry(id).or_default().push((operand, edge));
- }
- }
- let was = |w: &Was| -> Option<Vec<FaceOrigin>> {
- Some(match *w {
- Was::Face(id) => face_at.get(&id)?.clone(),
- Was::Edge(id) => edge_at.get(&id)?.iter().map(|&(operand, edge)| FaceOrigin::Edge { operand, edge }).collect(),
- })
- };
- let mut faces = result
- .face_iter()
- .map(|f| {
- let (origins, whole): (BTreeSet<FaceOrigin>, bool) = match face_at.get(&f.id()) {
- Some(own) => (own.iter().copied().collect(), true),
- None => {
- let (_, made, whole) = self.faces.get(&f.id())?;
- (made.iter().map(was).collect::<Option<Vec<_>>>()?.into_iter().flatten().collect(), *whole)
- }
- };
- let on_faces = origins.iter().filter(|o| matches!(o, FaceOrigin::Face { .. })).count();
- let change = match on_faces {
- 0 => Change::Generated,
- 1 if origins.len() == 1 && whole => Change::Kept,
- 1 if origins.len() == 1 => Change::Modified,
- _ => Change::Merged,
- };
- Some(FaceProv { origins: origins.into_iter().collect(), change })
- })
- .collect::<Option<Vec<FaceProv>>>()?;
- mark_shared_split(&mut faces);
- let edge_origins = |id: &mt::EdgeID| edge_at.get(id).map(|at| at.iter().map(|&(operand, edge)| EdgeOrigin::Edge { operand, edge }));
- let (edges, bounds) = edge_order(result.face_iter());
- let mut origins = HashMap::with_capacity(edges.len());
- for (e, between) in edges.iter().zip(bounds) {
- let of: Vec<EdgeOrigin> = if let Some(own) = edge_origins(&e.id()) {
- own.collect()
- } else if let Some((_, roots)) = self.edges.get(&e.id()) {
- let mut set = BTreeSet::new();
- for root in roots {
- set.extend(edge_origins(root)?);
- }
- set.into_iter().collect()
- } else {
- meeting(&between, &faces)
- };
- origins.insert(e.id(), of);
- }
- Some((faces, origins))
- }
-}
-
/// The origins of a new edge between the result faces `between` (whose provenance is in
/// `faces`): the meeting of the two faces (each side all of its face's origins, one or
/// several), when each comes from something and no origin is under both; else none (a seam,
@@ -341,172 +129,6 @@ pub(crate) fn meeting(between: &[usize], faces: &[FaceProv]) -> Vec<EdgeOrigin>
}
}
-/// The face and edge counts of the solids `operands`, for [`traced`].
-pub(crate) fn solid_counts(operands: &[&Solid]) -> Vec<(usize, usize)> {
- operands.iter().map(|s| (s.face_iter().count(), edge_order(s.face_iter()).0.len())).collect()
-}
-
-/// The body `Body::new` makes of `result`, which an operation built from `operands` (their
-/// solids) as `rec` records, with that history (none where it could not be recorded).
-pub(crate) fn rebuilt(result: Solid, operands: &[&Solid], rec: &Rebuild) -> Result<Body> {
- let (faces, edges) = rec.history(&result, operands).unzip();
- build(result, &solid_counts(operands), faces, edges.as_ref())
-}
-
-/// [`rebuilt`] for a body made as it is (a surface, which `Body::new` does not take): its
-/// solid is the one the operation built.
-pub(crate) fn rebuilt_body(body: Body, operands: &[&Solid], rec: &Rebuild) -> Body {
- let (faces, edges) = rec.history(&body.solid, operands).unzip();
- let counts = solid_counts(operands);
- traced(body, &counts, faces, edges.as_ref())
-}
-
-/// Ruled faces (truck's `try_wire_homotopy` of wires `a` and `b`), each with the provenance of
-/// the edges it spans: every face holds one edge of each wire, and comes from the profile
-/// segments under both (`a_numbers`, `b_numbers`: by edge, in wire order).
-pub(crate) fn ruled(faces: &mt::Shell, a: &mt::Wire, b: &mt::Wire, a_numbers: &[Vec<usize>], b_numbers: &[Vec<usize>]) -> Vec<Side> {
- let under = |w: &mt::Wire, numbers: &[Vec<usize>]| -> HashMap<mt::EdgeID, Vec<usize>> {
- w.edge_iter().map(|e| e.id()).zip(numbers.iter().cloned()).collect()
- };
- let (ua, ub) = (under(a, a_numbers), under(b, b_numbers));
- faces
- .face_iter()
- .map(|f| {
- let held = |u: &HashMap<mt::EdgeID, Vec<usize>>| -> Option<Vec<usize>> {
- let mut found = f.absolute_boundaries().iter().flat_map(|w| w.edge_iter()).filter_map(|e| u.get(&e.id()));
- let one = found.next()?.clone();
- found.next().is_none().then_some(one)
- };
- let prov = held(&ua).zip(held(&ub)).map(|(x, y)| profile(x.iter().chain(&y)));
- (f.clone(), prov)
- })
- .collect()
-}
-
-/// How far a column of swept faces runs.
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub(crate) enum Column {
- /// Until no face lies beyond (an open sweep whose caps are not among the faces) or the
- /// column comes back to its first face (a full turn).
- ToEnd,
- /// Exactly this many faces (the sweep's caps are among the faces).
- Steps(usize),
-}
-
-/// Follow the faces truck sweeps from the profile edges (`seeds`) they start at. A face swept
-/// from an edge is bounded by one loop: the edge, its moved copy, and the paths its ends sweep
-/// (none where an end stays put: a cone's apex, `fixed`). The copy is the loop's one other edge
-/// that shares no moving vertex with the edge, and is where the next step of the sweep starts.
-/// The face at `skip` is never entered. Returns, for each face, the seed whose column it lies
-/// in; `None` when the faces don't follow that pattern (a face reached twice, a column with a
-/// fork or of the wrong length).
-pub(crate) fn follow<'a>(
- faces: impl IntoIterator<Item = &'a mt::Face>,
- seeds: &[mt::EdgeID],
- skip: Option<usize>,
- run: Column,
- fixed: &[mt::VertexID],
-) -> Option<Vec<Option<usize>>> {
- let faces: Vec<&mt::Face> = faces.into_iter().collect();
- let mut by_edge: HashMap<mt::EdgeID, Vec<usize>> = HashMap::new();
- for (i, f) in faces.iter().enumerate() {
- if skip == Some(i) {
- continue;
- }
- for e in f.absolute_boundaries().iter().flat_map(|w| w.edge_iter()) {
- let slot = by_edge.entry(e.id()).or_default();
- if !slot.contains(&i) {
- slot.push(i);
- }
- }
- }
- let mut owner: Vec<Option<usize>> = vec![None; faces.len()];
- let limit = match run {
- Column::Steps(n) => n,
- Column::ToEnd => faces.len(),
- };
- for (seed, start) in seeds.iter().enumerate() {
- let (mut edge, mut prev, mut first) = (*start, None, None);
- let mut count = 0;
- while count < limit {
- let next: Vec<usize> = by_edge.get(&edge).map(|v| v.iter().copied().filter(|f| Some(*f) != prev).collect()).unwrap_or_default();
- let next = match (next.as_slice(), first) {
- ([], _) => break,
- ([f], _) => *f,
- // A full turn: the profile edge bounds the first face and the last.
- ([f, _], None) if run == Column::ToEnd => *f,
- _ => return None,
- };
- if Some(next) == first {
- break;
- }
- let slot = owner.get_mut(next)?;
- if slot.is_some() {
- return None;
- }
- *slot = Some(seed);
- let [wire] = faces.get(next)?.absolute_boundaries().as_slice() else { return None };
- let here = wire.edge_iter().find(|e| e.id() == edge)?;
- let moving: Vec<mt::VertexID> = [here.front().id(), here.back().id()].into_iter().filter(|v| !fixed.contains(v)).collect();
- let mut copies = wire.edge_iter().filter(|e| e.id() != edge && !moving.contains(&e.front().id()) && !moving.contains(&e.back().id()));
- let (Some(copy), None) = (copies.next(), copies.next()) else { return None };
- edge = copy.id();
- prev = Some(next);
- first.get_or_insert(next);
- count += 1;
- }
- if matches!(run, Column::Steps(n) if count != n) {
- return None;
- }
- }
- Some(owner)
-}
-
-/// Each face's provenance by the column it lies in ([`follow`]), from the profile segments
-/// under each seed edge.
-pub(crate) fn columns<'a>(
- faces: impl IntoIterator<Item = &'a mt::Face>,
- seeds: &[(mt::EdgeID, Vec<usize>)],
- skip: Option<usize>,
- run: Column,
- fixed: &[mt::VertexID],
-) -> Option<Vec<Option<FaceProv>>> {
- let ids: Vec<mt::EdgeID> = seeds.iter().map(|(id, _)| *id).collect();
- Some(follow(faces, &ids, skip, run, fixed)?.into_iter().map(|o| o.and_then(|s| seeds.get(s)).map(|(_, numbers)| profile(numbers))).collect())
-}
-
-/// The history of a solid truck swept from the planar face `profile` (`rsweep` of it), whose
-/// boundary edges `seeds` come from the profile segments given with them. Open
-/// (`closed == false`): the profile face is the start cap, each edge's faces follow from it to
-/// the end cap (the one face left), the same number of faces for every edge. Closed (a full
-/// turn): no caps, each edge's faces go round.
-pub(crate) fn swept_face(solid: &crate::body::Solid, profile: &mt::Face, seeds: &[(mt::EdgeID, Vec<usize>)], closed: bool) -> Option<Vec<FaceProv>> {
- let faces: Vec<&mt::Face> = solid.face_iter().collect();
- let start = faces.iter().position(|f| f.id() == profile.id());
- let run = match (closed, start) {
- (true, None) => Column::ToEnd,
- (false, Some(_)) => {
- // Two caps, and as many faces for every edge.
- let steps = faces.len().checked_sub(2)?.checked_div(seeds.len())?;
- if steps == 0 || steps * seeds.len() + 2 != faces.len() {
- return None;
- }
- Column::Steps(steps)
- }
- _ => return None,
- };
- // Every face but the caps lies in a column, so the one face left open is the end cap.
- columns(faces, seeds, start, run, &[])?
- .into_iter()
- .enumerate()
- .map(|(i, p)| match p {
- Some(p) => Some(p),
- None if Some(i) == start => Some(cap(false)),
- None => (!closed).then(|| cap(true)),
- })
- .collect()
-}
-
#[cfg(test)]
#[path = "record_tests.rs"]
mod tests;
diff --git a/crates/kernel/src/record_tests.rs b/crates/kernel/src/record_tests.rs
index c6e7372118..c1b78c27ff 100644
--- a/crates/kernel/src/record_tests.rs
+++ b/crates/kernel/src/record_tests.rs
@@ -21,7 +21,7 @@ fn sketch_made(b: &Body) -> &History {
h.check(b, &[]).unwrap();
assert!(h.faces.iter().all(|f| f.change == Change::Generated && !f.origins.is_empty()));
assert!(h.edges.iter().all(|e| e.origins.is_empty()));
- assert_eq!(h.edges.iter().map(|e| e.faces.clone()).collect::<Vec<_>>(), crate::history::edge_faces(&b.solid));
+ assert_eq!(h.edges.iter().map(|e| e.faces.clone()).collect::<Vec<_>>(), crate::history::edge_faces(b.record()));
h
}
@@ -525,7 +525,7 @@ fn raised_band_reports_kept_trimmed_and_new_faces() {
let [FaceOrigin::Face { operand: 0, face: rim }] = rim.origins.as_slice() else { panic!() };
// The rim's inner loop: the edges the walls stand on.
let loop_edges: Vec<usize> =
- crate::history::edge_faces(&sh.solid).iter().enumerate().filter(|(_, fs)| fs.contains(rim)).map(|(i, _)| i).collect();
+ crate::history::edge_faces(sh.record()).iter().enumerate().filter(|(_, fs)| fs.contains(rim)).map(|(i, _)| i).collect();
let mut walls = 0;
for (i, f) in h.faces.iter().enumerate() {
if let [FaceOrigin::Edge { operand: 0, edge }] = f.origins.as_slice() {
diff --git a/crates/smlib/SMLIB_REV b/crates/smlib/SMLIB_REV
index 462f1a8451..c214fc77fe 100644
--- a/crates/smlib/SMLIB_REV
+++ b/crates/smlib/SMLIB_REV
@@ -1 +1 @@
-9c97a665559072ab58b2483465ad8378fc623317
+1934b5799653dd205182456943bfb29beccaae92