diff --git a/crates/smlib/src/core.rs b/crates/smlib/src/core.rs index 149968c46..7571971d6 100644 --- a/crates/smlib/src/core.rs +++ b/crates/smlib/src/core.rs @@ -25,6 +25,7 @@ mod boolean_tests; mod convert; #[cfg(test)] mod convert_tests; +pub(crate) mod history; mod measure; #[cfg(test)] mod measure_tests; diff --git a/crates/smlib/src/core/blend_tests.rs b/crates/smlib/src/core/blend_tests.rs index e3d72feda..d36d10ad2 100644 --- a/crates/smlib/src/core/blend_tests.rs +++ b/crates/smlib/src/core/blend_tests.rs @@ -504,3 +504,25 @@ fn the_first_distance_goes_on_the_face_along_first() { assert!((m.centroid[1] - y).abs() < 1e-7 && (m.centroid[2] - z).abs() < 1e-7, "{first:?}: centroid {:?} vs ({y}, {z})", m.centroid); } } + +/// Face and edge tags (`Brep::tagged`) through blends routed to solidcore, as on C++: the box is +/// tagged on the C++ kernel, its solidcore body converted from that and tagged the same way, and +/// the two results' histories must be the same. +#[cfg(feature = "native")] +mod history { + use crate::{Blend, Brep, ffi}; + + /// A 2 mm round on the top front edge of a box: the top and front are trimmed, the round is + /// new. + #[test] + #[ignore = "solidcore#1594: the fillet does not carry the body's attributes onto the faces it rebuilds (the top, front and sides come out Generated)"] + fn tags_cross_a_fillet() { + crate::init().unwrap(); + let a = Brep::made(ffi::make_box(&[0.0; 3], &[20.0, 30.0, 10.0]).unwrap()).tagged(0).unwrap(); + let edge = [[10.0, 0.0, 10.0]]; + let cpp = ffi::ops::blend(ffi::ops::BLEND_ROUND, a.cpp().unwrap(), &edge, &[2.0], super::TOL).unwrap(); + let cpp = Brep::made(cpp).history().unwrap(); + let core = super::blend(a.core().unwrap(), Blend::Round, &edge, &[2.0], super::TOL, &[], &[], super::Corners::Filled).unwrap(); + assert_eq!(Brep::made_core(core).history().unwrap().canonical(), cpp.canonical()); + } +} diff --git a/crates/smlib/src/core/boolean_tests.rs b/crates/smlib/src/core/boolean_tests.rs index 7f3534900..baad6b47a 100644 --- a/crates/smlib/src/core/boolean_tests.rs +++ b/crates/smlib/src/core/boolean_tests.rs @@ -338,15 +338,18 @@ fn operands_stay_as_they_were() { assert!(rel(v, 1000.0) < 1e-9, "A ∪ A: {v}"); } -/// Face and edge tags (`Brep::tagged`) through a boolean routed to solidcore, as on C++. +/// Face and edge tags (`Brep::tagged`) through operations routed to solidcore, as on C++: each +/// operand is tagged on the C++ kernel, its solidcore body converted from that and tagged the same +/// way there, and the two results' histories ([`Raw`], each in its own kernel's face and edge +/// order) must be the same. #[cfg(feature = "native")] mod history { use crate::history::Raw; use crate::{BooleanOp, Brep, ffi}; - fn tagged_box(origin: [f64; 3], operand: usize) -> Brep { + fn tagged_box(origin: [f64; 3], size: [f64; 3], operand: usize) -> Brep { crate::init().unwrap(); - Brep::made(ffi::make_box(&origin, &[10.0; 3]).unwrap()).tagged(operand).unwrap() + Brep::made(ffi::make_box(&origin, &size).unwrap()).tagged(operand).unwrap() } /// Two 10 mm cubes overlapping in a 5 mm one (the capi's `overlapping_boxes_union`): 12 @@ -361,16 +364,82 @@ mod history { #[test] fn tags_cross_a_cpp_boolean() { - let (a, b) = (tagged_box([0.0; 3], 0), tagged_box([5.0; 3], 1)); + let (a, b) = (tagged_box([0.0; 3], [10.0; 3], 0), tagged_box([5.0; 3], [10.0; 3], 1)); let r = Brep::made(ffi::ops::boolean(a.cpp().unwrap(), b.cpp().unwrap(), ffi::ops::BOOLEAN_UNION).unwrap()); check(&r.history().unwrap()); } #[test] - #[ignore = "the tags do not cross the flat arrays (smlib_flat.cpp carries no attributes), so the operands reach solidcore untagged; solidcore#1568 carries attributes through the boolean itself"] fn tags_cross_a_solidcore_boolean() { - let (a, b) = (tagged_box([0.0; 3], 0), tagged_box([5.0; 3], 1)); + let (a, b) = (tagged_box([0.0; 3], [10.0; 3], 0), tagged_box([5.0; 3], [10.0; 3], 1)); let r = super::boolean(a.core().unwrap(), b.core().unwrap(), BooleanOp::Union).unwrap().unwrap(); check(&Brep::made_core(r).history().unwrap()); } + + /// `a` op `b` on both kernels: the same history. + fn parity(a: &Brep, b: &Brep, op: BooleanOp) { + let code = match op { + BooleanOp::Union => ffi::ops::BOOLEAN_UNION, + BooleanOp::Subtract => ffi::ops::BOOLEAN_SUBTRACT, + BooleanOp::Intersect => ffi::ops::BOOLEAN_INTERSECT, + }; + let cpp = Brep::made(ffi::ops::boolean(a.cpp().unwrap(), b.cpp().unwrap(), code).unwrap()).history().unwrap(); + let core = Brep::made_core(super::boolean(a.core().unwrap(), b.core().unwrap(), op).unwrap().unwrap()).history().unwrap(); + assert_eq!(core.canonical(), cpp.canonical()); + } + + #[test] + fn an_overlapping_union_has_the_cpp_history() { + parity(&tagged_box([0.0; 3], [10.0; 3], 0), &tagged_box([5.0; 3], [10.0; 3], 1), BooleanOp::Union); + } + + /// A slot across the top of a 20 mm cube: the top is cut in two, the slot's walls and floor + /// come from the tool. + #[test] + fn a_slot_has_the_cpp_history() { + let (a, b) = (tagged_box([0.0; 3], [20.0; 3], 0), tagged_box([5.0, -1.0, 10.0], [10.0, 22.0, 15.0], 1)); + parity(&a, &b, BooleanOp::Subtract); + } + + /// Two boxes side by side, sharing the face x = 10 and their top and bottom planes: faces + /// found lying on each other's (SMLib's coincidences and merges) stand for both. + #[test] + fn boxes_side_by_side_have_the_cpp_history() { + let (a, b) = (tagged_box([0.0; 3], [10.0; 3], 0), tagged_box([10.0, 0.0, 0.0], [10.0; 3], 1)); + parity(&a, &b, BooleanOp::Union); + } + + /// A box sharing one corner region with another: the intersection keeps three faces of each. + #[test] + fn an_intersection_has_the_cpp_history() { + parity(&tagged_box([0.0; 3], [10.0; 3], 0), &tagged_box([5.0; 3], [10.0; 3], 1), BooleanOp::Intersect); + } + + /// `SmApiBrepCopy` (the copy every solidcore operation starts from) keeps every tag: the + /// copy's history is the operand's own, every face Kept, as on C++. + #[test] + fn tags_cross_a_copy() { + let a = tagged_box([0.0; 3], [10.0, 20.0, 30.0], 0); + // Converted (and tagged) before the kernel's lock is taken: the conversion takes it too. + let body = a.core().unwrap(); + let copy = super::run("copy", |k| { + let g = body.0.lock().unwrap(); + super::super::boolean::copy_of(k, &g, 7) + }) + .unwrap(); + let core = Brep::made_core(super::Body::new(copy)).history().unwrap(); + let cpp = Brep::made(ffi::copy(a.cpp().unwrap()).unwrap()).history().unwrap(); + assert_eq!(core.canonical(), cpp.canonical()); + assert!(core.faces.iter().all(|f| f.change == solidcraft_geom::brep::history::Change::Kept), "{core:?}"); + } + + /// A post standing on the top of a cube, imprinted on it: the top is split along the + /// post's foot, the other faces are as they were. + #[test] + fn an_imprint_has_the_cpp_history() { + let (a, b) = (tagged_box([0.0; 3], [20.0; 3], 0), tagged_box([5.0, 5.0, 10.0], [10.0, 10.0, 20.0], 1)); + let cpp = Brep::made(ffi::ops::imprint(a.cpp().unwrap(), b.cpp().unwrap()).unwrap()).history().unwrap(); + let core = Brep::made_core(super::imprint(a.core().unwrap(), b.core().unwrap()).unwrap().unwrap()).history().unwrap(); + assert_eq!(core.canonical(), cpp.canonical()); + } } diff --git a/crates/smlib/src/core/history.rs b/crates/smlib/src/core/history.rs new file mode 100644 index 000000000..b4a5c1eb8 --- /dev/null +++ b/crates/smlib/src/core/history.rs @@ -0,0 +1,259 @@ +//! Face and edge history on solidcore: a port of the fork's `capi/src/smlib_history.cpp` +//! (`smlib_history_tag`, `smlib_history_read`) onto solidcore's B-rep-owned attribute store +//! ([`Brep::add_attribute`]), which solidcore's operations carry through their edits with SMLib's +//! handlers: Split when a face or edge is cut in two (both children get it), Merge when two become +//! one (the survivor gets it), Copy when an object is copied (a boolean copies the second operand +//! into the first), Coincident where a boolean finds one operand's entity lying on the other's. +//! New topology (a boolean's intersection edges) is made without any. +//! +//! The capi's Tag is one attribute holding a set of (operand, index) origins, with its own Split, +//! Merge and Coincident handlers joining the sets where SMLib's defaults keep only one. solidcore +//! runs SMLib's default handlers alone (no application attribute class can override them), so each +//! origin here is an attribute of its own, its id naming the origin ([`id`]): the default +//! handlers give an object every attribute it has no attribute of that id for, which on a set of +//! distinct ids is the union the capi's handlers make. The face's boundary edges then (`edges`) +//! and the edge's points then (`at`) ride on the origin's attribute. +//! +//! Deviations from the capi, each where its own handlers differ from the default ones: +//! - An object that already stands for something and is copied onto (`SmAttribute::Copy`, not +//! overridden there) keeps only its own origins in the capi, here takes the copy's too. No +//! operation copies onto an object it did not just make. +//! - A split child, or an untagged object a coincidence or merge lands on, gets the capi's Tag +//! without `at` (so it never counts as moved); here the origin's attribute carries its `at` +//! along. `at` is read only for an edge with one origin no other edge shares, which a split +//! edge is not unless its sibling is gone, and then the faces beside it have changed anyway. +//! +//! The rest is as there: the same origins, boundary records, samples and classification. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use solidcore::geom::attribute::{Attribute, AttributeValue, Behavior}; +use solidcore::kernel::Kernel; +use solidcore::query::api_queries::edge_closest_point; +use solidcore::topology::face::p4 as face4; +use solidcore::topology::{Brep, EdgeId, edge}; +use solidcore::{EntityRef, Point3, SolidError}; +use solidcraft_geom::brep::history::Change; + +use super::boolean::copy_of; +use super::{Body, answer, with_body}; +use crate::history::{Raw, RawEdge, RawFace}; +use crate::{Error, Result}; + +/// Operand numbers and indices a tag accepts (`TAG_MAX`: keeps every value inside 30 bits). +const TAG_MAX: usize = 1 << 30; + +/// The first id of a tag's attributes: above SMLib's own ids and the applications' (all below +/// `SM_AI_USER_3 + 10000`), so a tag is told apart by its id alone. +const TAG_BASE: u64 = 1 << 62; + +/// An edge's tag ids set this bit; a face's don't. +const EDGE_BIT: u64 = 1 << 60; + +/// One (operand, index) pair a face or edge stands for. +type Origin = (usize, usize); + +/// The attribute id of origin `o` on a face or (`edge`) an edge. +fn id(o: Origin, edge: bool) -> u64 { + TAG_BASE | if edge { EDGE_BIT } else { 0 } | ((o.0 as u64) << 30) | o.1 as u64 +} + +/// The origin an attribute id names on a face or (`edge`) an edge, if it is a tag's. +fn origin_of(id: u64, edge: bool) -> Option { + if id & !(EDGE_BIT | ((1 << 60) - 1)) != TAG_BASE || (id & EDGE_BIT != 0) != edge { + return None; + } + let mask = (1u64 << 30) - 1; + Some((usize::try_from((id >> 30) & mask).ok()?, usize::try_from(id & mask).ok()?)) +} + +/// What one of a face's or edge's tag attributes says: its origin, for a face the boundary edges +/// that origin had, for an edge the points it ran through then. +struct Said { + origin: Origin, + edges: Vec, + at: Vec, +} + +/// The tag attributes on `e` (`Tag::on`), each read; none where it has no tag. +fn tags(b: &Brep, e: EntityRef) -> Vec { + let edge = matches!(e, EntityRef::Edge(_)); + b.entity_attributes(e) + .into_iter() + .filter_map(|(_, a)| { + let origin = origin_of(a.attribute_id(), edge)?; + let AttributeValue::Generic { longs, doubles, .. } = a.value() else { return None }; + let edges = longs.iter().filter_map(|x| usize::try_from(*x).ok()).collect(); + let at = doubles.as_chunks::<3>().0.iter().map(|[x, y, z]| Point3::new(*x, *y, *z)).collect(); + Some(Said { origin, edges, at }) + }) + .collect() +} + +/// `Tag::set`: replaces whatever tag `e` has with exactly origin `o`, the boundary edges `edges` +/// (a face's) and the points `at` (an edge's). +fn set(b: &mut Brep, e: EntityRef, o: Origin, edges: &[usize], at: &[Point3]) -> std::result::Result<(), SolidError> { + let edge = matches!(e, EntityRef::Edge(_)); + let old: Vec<_> = b.entity_attributes(e).into_iter().filter(|(_, a)| origin_of(a.attribute_id(), edge).is_some()).map(|(h, _)| h).collect(); + for h in old { + b.remove_attribute(e, h)?; + } + let longs: Vec = edges.iter().filter_map(|x| i64::try_from(*x).ok()).collect(); + let doubles: Vec = at.iter().flat_map(|p| [p.x, p.y, p.z]).collect(); + b.add_attribute(e, Attribute::generic(id(o, edge), Behavior::Copy, &longs, &doubles, &[]))?; + Ok(()) +} + +/// `samples`: points along `e`, its two ends, then three between, evenly in its parameter. Empty +/// where it can't be evaluated. +fn samples(k: &Kernel, b: &Brep, e: EdgeId) -> std::result::Result, SolidError> { + let edge = b.edge(e)?; + let Some(curve) = edge.curve.as_ref() else { return Ok(Vec::new()) }; + let (lo, hi) = (edge.interval.min(), edge.interval.max()); + let mut p = Vec::with_capacity(5); + for t in [0.0, 1.0, 0.25, 0.5, 0.75] { + let Some(v) = answer(curve.evaluate(k, lo + t * (hi - lo), 0, true, false))? else { return Ok(Vec::new()) }; + let Some(v) = v.first() else { return Ok(Vec::new()) }; + p.push(Point3::new(v.x, v.y, v.z)); + } + Ok(p) +} + +/// `moved`: has `e` moved from where its tag says it lay (`at`: its ends elsewhere, or a point +/// it ran through off it, by more than `tol`)? An edge with no record of where it lay has not. +fn moved(k: &Kernel, b: &Brep, e: EdgeId, at: &[Point3], tol: f64) -> std::result::Result { + let ([a0, a1, ..], true) = (at, at.len() >= 2) else { return Ok(false) }; + let now = samples(k, b, e)?; + let [n0, n1, ..] = now.as_slice() else { return Ok(true) }; + let near = |p: &Point3, q: &Point3| p.distance(*q) <= tol; + let ends = (near(n0, a0) && near(n1, a1)) || (near(n0, a1) && near(n1, a0)); + if !ends { + return Ok(true); + } + for q in at.iter().skip(2) { + // `SmApiEdgeClosestPoint` failing counts as off it, as a distance above `tol` does. + match answer(edge_closest_point(k, b, e, *q))? { + Some(c) if c.closest.distance <= tol => {} + _ => return Ok(true), + } + } + Ok(false) +} + +/// `smlib_history_tag`: a copy of `body` (`SmApiBrepCopy`) whose face i and edge i stand for face +/// i and edge i of operand `operand` (in its face and edge order, which the copy keeps), a face +/// also recording its boundary edges then, an edge the points it ran through. +pub(crate) fn tag(body: &Body, operand: usize) -> Result { + if operand >= TAG_MAX { + return Err(Error::Argument); + } + with_body("smlib_history_tag", body, |k, b| { + let mut r = copy_of(k, b, 1)?; + let faces = r.face_list().to_vec(); + let edges = r.edge_list().to_vec(); + if faces.len() >= TAG_MAX || edges.len() >= TAG_MAX { + return Ok(Err(Error::Argument)); + } + let edge_at: HashMap = edges.iter().enumerate().map(|(i, e)| (*e, i)).collect(); + for (i, f) in faces.iter().enumerate() { + let own: BTreeSet = face4::edges(&r, *f, None, false, None)?.iter().filter_map(|e| edge_at.get(e).copied()).collect(); + set(&mut r, EntityRef::Face(*f), (operand, i), &own.into_iter().collect::>(), &[])?; + } + for (i, e) in edges.iter().enumerate() { + let at = samples(k, &r, *e)?; + set(&mut r, EntityRef::Edge(*e), (operand, i), &[], &at)?; + } + Ok(Ok(r)) + })? + .map(Body::new) +} + +/// `smlib_history_read`: each face's and edge's origins in `result`, a face's change from how +/// many origins it has, how many result faces share them and whether its boundary is still +/// exactly its origin's edges; each edge's faces. In the body's own face and edge order. +pub(crate) fn read(result: &Body) -> Result { + with_body("smlib_history_read", result, |k, b| { + let faces = b.face_list().to_vec(); + let edges = b.edge_list().to_vec(); + let face_at: HashMap<_, usize> = faces.iter().enumerate().map(|(i, f)| (*f, i)).collect(); + let edge_at: HashMap = edges.iter().enumerate().map(|(i, e)| (*e, i)).collect(); + let tol = b.tolerance(); + + // Each face's origins and the boundary edges they had; each edge's origins and points. + let mut fo: Vec> = Vec::with_capacity(faces.len()); + let mut fe: Vec> = Vec::with_capacity(faces.len()); + let mut eo: Vec> = Vec::with_capacity(edges.len()); + let mut at: Vec> = Vec::with_capacity(edges.len()); + let mut face_uses: BTreeMap = BTreeMap::new(); + let mut edge_uses: BTreeMap = BTreeMap::new(); + for f in &faces { + let said = tags(b, EntityRef::Face(*f)); + let o: BTreeSet = said.iter().map(|s| s.origin).collect(); + for x in &o { + *face_uses.entry(*x).or_default() += 1; + } + fe.push(said.iter().flat_map(|s| s.edges.iter().copied()).collect()); + fo.push(o); + } + for e in &edges { + let said = tags(b, EntityRef::Edge(*e)); + let o: BTreeSet = said.iter().map(|s| s.origin).collect(); + for x in &o { + *edge_uses.entry(*x).or_default() += 1; + } + // The capi's Tag has one `at`; an edge with one origin has one attribute. + at.push(said.into_iter().next().map(|s| s.at).unwrap_or_default()); + eo.push(o); + } + + let mut out_faces = Vec::with_capacity(faces.len()); + for (i, f) in faces.iter().enumerate() { + let (Some(o), Some(own)) = (fo.get(i), fe.get(i)) else { continue }; + let change = match o.iter().next() { + None => Change::Generated, + Some(_) if o.len() > 1 => Change::Merged, + Some(first) if face_uses.get(first).copied().unwrap_or(0) > 1 => Change::Split, + Some(first) => { + // Kept when its boundary is still exactly the edges it had, each whole (one + // origin, under no other result edge), its own operand's and where it was (an + // edge an operation moved, as a draft moves a tilted face's neighbours' edges, + // leaves those faces trimmed differently). + let mut now = BTreeSet::new(); + let mut whole = true; + for e in face4::edges(b, *f, None, false, None)? { + let Some(j) = edge_at.get(&e).copied() else { + whole = false; + break; + }; + let (Some(origins), Some(points)) = (eo.get(j), at.get(j)) else { + whole = false; + break; + }; + let only = match origins.iter().next() { + Some(x) if origins.len() == 1 => *x, + _ => { + whole = false; + break; + } + }; + whole = only.0 == first.0 && edge_uses.get(&only).copied().unwrap_or(0) == 1 && !moved(k, b, e, points, tol)?; + if !whole { + break; + } + now.insert(only.1); + } + if whole && now == *own { Change::Kept } else { Change::Modified } + } + }; + out_faces.push(RawFace { change, origins: o.iter().copied().collect() }); + } + + let mut out_edges = Vec::with_capacity(edges.len()); + for (i, e) in edges.iter().enumerate() { + let bounds: BTreeSet = edge::faces(b, *e, None)?.iter().filter_map(|f| face_at.get(f).copied()).collect(); + let origins = eo.get(i).map(|o| o.iter().copied().collect()).unwrap_or_default(); + out_edges.push(RawEdge { faces: bounds.into_iter().collect(), origins }); + } + Ok(Raw { faces: out_faces, edges: out_edges }) + }) +} diff --git a/crates/smlib/src/core/offset_tests.rs b/crates/smlib/src/core/offset_tests.rs index 1e80515f0..9110aff54 100644 --- a/crates/smlib/src/core/offset_tests.rs +++ b/crates/smlib/src/core/offset_tests.rs @@ -574,3 +574,52 @@ fn a_solidcore_error_in_a_pick_is_an_error() { let unported = pick(&all, &points, 1.0, 1e-6, |i, _| answer(if i == 0 { Err(SolidError::unported("Sm::X", "u")) } else { Ok(0.5) })); assert!(matches!(unported, Err(SolidError::Unported { .. })), "{unported:?}"); } + +/// Face and edge tags (`Brep::tagged`) through offsets routed to solidcore, as on C++: the box is +/// tagged on the C++ kernel, its solidcore body converted from that and tagged the same way, and +/// the two results' histories must be the same. +#[cfg(feature = "native")] +mod history { + use crate::{Brep, ffi}; + + fn tagged_box() -> Brep { + crate::init().unwrap(); + Brep::made(ffi::make_box(&[0.0; 3], &[20.0, 30.0, 10.0]).unwrap()).tagged(0).unwrap() + } + + /// The box hollowed to 2 mm walls, its top open: the five walls offset inward stand for the + /// faces they offset. + #[test] + fn tags_cross_a_shell() { + let a = tagged_box(); + let top = [[10.0, 15.0, 10.0]]; + let cpp = Brep::made(ffi::ops::pick_op(ffi::ops::Pick::Shell, a.cpp().unwrap(), &top, super::TOL, -2.0).unwrap()).history().unwrap(); + let core = Brep::made_core(super::shell(a.core().unwrap(), &top, super::TOL, -2.0).unwrap()).history().unwrap(); + assert_eq!(core.canonical(), cpp.canonical()); + } + + /// The top moved down 2 mm: it stands for itself, its four neighbours are trimmed to meet it. + #[test] + #[ignore = "no SmOffsetFacesExecutive, fork a96ce9f (solidcore#1060): solidcore cannot offset the face yet"] + fn tags_cross_a_face_offset() { + let a = tagged_box(); + let top = [[10.0, 15.0, 10.0]]; + let cpp = Brep::made(ffi::ops::pick_op(ffi::ops::Pick::OffsetFaces, a.cpp().unwrap(), &top, super::TOL, -2.0).unwrap()).history().unwrap(); + let core = Brep::made_core(super::offset_faces(a.core().unwrap(), &top, super::TOL, -2.0).unwrap()).history().unwrap(); + assert_eq!(core.canonical(), cpp.canonical()); + } + + /// A 5 degree draft of the front about the bottom plane: the front tilts, its neighbours' + /// edges move with it. + #[test] + #[ignore = "solidcore's draft (its local operation) does not carry the body's attributes yet: every face comes out untagged"] + fn tags_cross_a_draft() { + let a = tagged_box(); + let front = [[10.0, 0.0, 5.0]]; + let (origin, normal, pull, angle) = ([0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], 5f64.to_radians()); + let cpp = ffi::ops::draft(a.cpp().unwrap(), &front, super::TOL, &origin, &normal, &pull, angle).unwrap(); + let cpp = Brep::made(cpp).history().unwrap(); + let core = Brep::made_core(super::draft(a.core().unwrap(), &front, super::TOL, origin, normal, pull, angle).unwrap()).history().unwrap(); + assert_eq!(core.canonical(), cpp.canonical()); + } +} diff --git a/crates/smlib/src/history.rs b/crates/smlib/src/history.rs index 547b0d7ed..dafd1cf17 100644 --- a/crates/smlib/src/history.rs +++ b/crates/smlib/src/history.rs @@ -14,7 +14,7 @@ use std::collections::BTreeSet; use solidcraft_geom::brep::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, Failed, History, Side}; -use crate::{Brep, Error, Result, error, ffi}; +use crate::{Brep, Error, Result, core, error, ffi, route}; /// A result face as SMLib reports it: how it relates to its origins, and the (operand, face) /// pairs it came from, sorted. @@ -67,20 +67,65 @@ impl Brep { /// A copy whose face i and edge i are tagged as face i and edge i of operand `operand` (in /// SMLib's order, which the copy keeps). Run an operation on tagged copies, then read its /// result's [`Brep::history`]. + /// + /// The tags are made in the kernel the body is in (solidcore's when it has its body, + /// [`crate::core::history`]); converted for the other, the body is tagged there the same way. pub fn tagged(&self, operand: usize) -> Result { - let operand = i32::try_from(operand).map_err(|_| Error::Argument)?; - ffi::history::tag(self.cpp()?, operand).map(Brep::made).map_err(error) + let mut t = match self.core.get() { + Some(Ok(b)) => Brep::made_core(core::history::tag(b, operand)?), + _ => { + let k = i32::try_from(operand).map_err(|_| Error::Argument)?; + Brep::made(ffi::history::tag(self.cpp()?, k).map_err(error)?) + } + }; + t.operand = Some(operand); + Ok(t) } /// The history of this body, made by an operation from tagged operands: each face's and - /// edge's origins among them. Faces and edges no tag reached have none. + /// edge's origins among them. Faces and edges no tag reached have none. Read in the kernel + /// that made the body: the tags never cross between them. pub fn history(&self) -> Result { + if self.maker == route::Backend::Solidcore { + if let Some(what) = self.untracked { + return Err(Error::Solidcore(format!("smlib_history_read: not supported yet: {what}"))); + } + return core::history::read(self.core()?); + } let v = ffi::history::read(self.cpp()?).map_err(error)?; Raw::decode(&v).ok_or(Error::Exception) } } impl Raw { + /// This history with its faces in a canonical order (by origins, then change) and each edge + /// naming its faces by that order, the edges sorted: two kernels' histories of one result + /// compare equal whatever order each lists its faces and edges in. + #[cfg(test)] + pub(crate) fn canonical(&self) -> Raw { + let mut order: Vec = (0..self.faces.len()).collect(); + order.sort_by(|a, b| { + let (fa, fb) = (&self.faces[*a], &self.faces[*b]); + (&fa.origins, fa.change as u8).cmp(&(&fb.origins, fb.change as u8)) + }); + let mut at = vec![0; order.len()]; + for (new, old) in order.iter().enumerate() { + at[*old] = new; + } + let faces = order.iter().map(|i| self.faces[*i].clone()).collect(); + let mut edges: Vec = self + .edges + .iter() + .map(|e| { + let mut f: Vec = e.faces.iter().map(|i| at[*i]).collect(); + f.sort(); + RawEdge { faces: f, origins: e.origins.clone() } + }) + .collect(); + edges.sort_by(|a, b| (&a.origins, &a.faces).cmp(&(&b.origins, &b.faces))); + Raw { faces, edges } + } + /// Decodes `smlib_history_read`'s records; `None` where they don't read as its layout. fn decode(v: &[i64]) -> Option { let mut r = Reader(v.iter()); diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs index 76fdc5f7a..34fe70bde 100644 --- a/crates/smlib/src/lib.rs +++ b/crates/smlib/src/lib.rs @@ -231,6 +231,14 @@ pub fn current_call() -> Option { pub struct Brep { cpp: OnceLock>, core: OnceLock>, + /// The kernel that made it, whose tags [`Brep::history`] reads (the arrays carry none). + maker: route::Backend, + /// `Some(k)` for [`Brep::tagged`]`(k)`: its faces and edges stand for their own positions in + /// operand `k`, so the body converted for the other kernel is tagged the same way there. + operand: Option, + /// Why [`Brep::history`] cannot be read, for a body made by a solidcore operation that does + /// not carry the attributes yet. + untracked: Option<&'static str>, } impl std::fmt::Debug for Brep { @@ -242,29 +250,51 @@ impl std::fmt::Debug for Brep { impl Brep { /// A body the C++ kernel made. fn made(h: ffi::Handle) -> Brep { - Brep { cpp: OnceLock::from(Ok(h)), core: OnceLock::new() } + Brep { cpp: OnceLock::from(Ok(h)), core: OnceLock::new(), maker: route::Backend::Smlib, operand: None, untracked: None } } /// A body solidcore made. fn made_core(b: core::Body) -> Brep { - Brep { cpp: OnceLock::new(), core: OnceLock::from(Ok(b)) } + Brep { cpp: OnceLock::new(), core: OnceLock::from(Ok(b)), maker: route::Backend::Solidcore, operand: None, untracked: None } } - /// The C++ kernel's body: converted from solidcore's the first time it is asked for. + /// A body a solidcore blend made: solidcore's fillets do not carry the body's attributes onto + /// the faces they rebuild yet (solidcore#1594), so its history is not read. + fn made_core_blend(b: core::Body) -> Brep { + Brep { untracked: Some("the history of a blend on solidcore (solidcore#1594)"), ..Brep::made_core(b) } + } + + /// A body a solidcore draft made: its local operation does not carry the body's attributes + /// yet (every face comes out with none), so its history is not read. + fn made_core_draft(b: core::Body) -> Brep { + Brep { untracked: Some("the history of a draft on solidcore, whose local operation does not carry attributes yet"), ..Brep::made_core(b) } + } + + /// The C++ kernel's body: converted from solidcore's the first time it is asked for (and + /// tagged as solidcore's is, for a [`Brep::tagged`] body). fn cpp(&self) -> Result<&ffi::Handle> { let made = self.cpp.get_or_init(|| { let core = self.core.get().ok_or(Error::Empty)?.as_ref().map_err(Clone::clone)?; let a = core::to_arrays(core)?; - flat::Flat::from_arrays(&a)?.import()?.cpp.into_inner().unwrap_or(Err(Error::Empty)) + let h = flat::Flat::from_arrays(&a)?.import()?.cpp.into_inner().unwrap_or(Err(Error::Empty))?; + match self.operand { + Some(k) => ffi::history::tag(&h, i32::try_from(k).map_err(|_| Error::Argument)?).map_err(error), + None => Ok(h), + } }); made.as_ref().map_err(Clone::clone) } - /// solidcore's body: converted from the C++ kernel's the first time it is asked for. + /// solidcore's body: converted from the C++ kernel's the first time it is asked for (and + /// tagged as the C++ kernel's is, for a [`Brep::tagged`] body). fn core(&self) -> Result<&core::Body> { let made = self.core.get_or_init(|| { self.cpp.get().ok_or(Error::Empty)?.as_ref().map_err(Clone::clone)?; - core::from_arrays(&self.cpp_arrays()?) + let b = core::from_arrays(&self.cpp_arrays()?)?; + match self.operand { + Some(k) => core::history::tag(&b, k), + None => Ok(b), + } }); made.as_ref().map_err(Clone::clone) } diff --git a/crates/smlib/src/ops.rs b/crates/smlib/src/ops.rs index ef0cc37b9..1d0d4c9bb 100644 --- a/crates/smlib/src/ops.rs +++ b/crates/smlib/src/ops.rs @@ -280,7 +280,7 @@ impl Brep { } if route::Op::Blend.backend() == route::Backend::Solidcore { return core::blend::blend_holes(self.core()?, kind, edges, sizes, tolerance, corners, setbacks, core::blend::Corners::Open) - .map(|(b, holes)| (Brep::made_core(b), holes)); + .map(|(b, holes)| (Brep::made_core_blend(b), holes)); } init()?; let kind = match kind { @@ -301,7 +301,7 @@ impl Brep { /// (the edge curve's parameter scaled to 0..1). pub fn fillet_variable(&self, edge: [f64; 3], tolerance: f64, start: [f64; 3], degree: usize, knots: &[f64], radii: &[f64]) -> Result { if route::Op::Blend.backend() == route::Backend::Solidcore { - return core::blend::fillet_variable(self.core()?, edge, tolerance, start, degree, knots, radii).map(Brep::made_core); + return core::blend::fillet_variable(self.core()?, edge, tolerance, start, degree, knots, radii).map(Brep::made_core_blend); } init()?; let degree = i32::try_from(degree).map_err(|_| Error::Argument)?; @@ -321,7 +321,7 @@ impl Brep { return Err(Error::Argument); } if route::Op::Blend.backend() == route::Backend::Solidcore { - return core::blend::chamfer_sides(self.core()?, edges, tolerance, distance, second, first).map(Brep::made_core); + return core::blend::chamfer_sides(self.core()?, edges, tolerance, distance, second, first).map(Brep::made_core_blend); } init()?; let (value, angle) = match second { @@ -396,7 +396,7 @@ impl Brep { return Err(Error::Argument); } if route::Op::Split.backend() == route::Backend::Solidcore { - return core::offset::draft(self.core()?, faces, tolerance, neutral_origin, neutral_normal, pull, angle).map(Brep::made_core); + return core::offset::draft(self.core()?, faces, tolerance, neutral_origin, neutral_normal, pull, angle).map(Brep::made_core_draft); } init()?; ffi::ops::draft(self.cpp()?, faces, tolerance, &neutral_origin, &neutral_normal, &pull, angle).map(Brep::made).map_err(pick_error) @@ -417,7 +417,7 @@ impl Brep { if edges.len() > MAX_POINTS || edges.is_empty() { return Err(Error::Argument); } - core::blend::blend(self.core()?, kind, edges, sizes, tolerance, corners, setbacks, open).map(Brep::made_core) + core::blend::blend(self.core()?, kind, edges, sizes, tolerance, corners, setbacks, open).map(Brep::made_core_blend) } fn pick_op(&self, kind: ffi::ops::Pick, points: &[[f64; 3]], tolerance: f64, size: f64, allow_none: bool) -> Result {