Skip to content

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

Wave 407/509: Native B-rep: a body is written as it serializes, not through a JSON value (and 3 more)

jyviko27d240d58c48
diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs
index 536a9f8bba..377bb8443d 100644
--- a/crates/doc/src/eval_more.rs
+++ b/crates/doc/src/eval_more.rs
@@ -843,9 +843,21 @@ pub(super) fn sheet_eval(
}
}
-/// Current unmodified extrusion caps, including placement, certify the tool's depth.
-/// Tessellation can drift in thickness at distant coordinates and cannot certify a slab.
+/// The tool's depth along the sketch normal (from `source`), the roundoff of that depth and the
+/// tool's current footprint where it differs from the profile: from its current unmodified
+/// extrusion caps, including placement, else from its exact record proving it a uniform prism
+/// along the normal (a To Object tool trimmed by the body it runs to, whose boolean leaves no
+/// extrusion faces: its section is its footprint). Tessellation can drift in thickness at
+/// distant coordinates and cannot certify a slab.
fn sheet_tool_span(body: &Body, source: &Plane) -> Option<(f64, f64, f64, Option<(Plane, Region2)>)> {
+ extrusion_tool_span(body, source).or_else(|| {
+ let prism = kernel::certified_prism_section(body, source).ok().flatten()?;
+ (prism.tolerance <= 1e-7).then_some((prism.lo, prism.hi, prism.tolerance, Some((*source, prism.region))))
+ })
+}
+
+/// [`sheet_tool_span`] from the tool's extrusion caps.
+fn extrusion_tool_span(body: &Body, source: &Plane) -> Option<(f64, f64, f64, Option<(Plane, Region2)>)> {
use kernel::FaceSource;
#[derive(PartialEq)]
enum Signature<'a> {
diff --git a/crates/engine/src/cmd/face_tests.rs b/crates/engine/src/cmd/face_tests.rs
index e9afe13893..3a0e0d9b91 100644
--- a/crates/engine/src/cmd/face_tests.rs
+++ b/crates/engine/src/cmd/face_tests.rs
@@ -184,6 +184,27 @@ fn internal_capture_in_another_component_anchors_an_offset_face_by_its_history_n
assert_eq!(s.pending_moves, pending);
}
+/// Extrude from a face in another component whose occurrence has an uncaptured move, where the
+/// face has neither a construction certificate nor an exact history name: a half of a box's top
+/// that Split Face divided. The face profile would take the legacy path, which can't capture the
+/// source's pending position, so the extrude is refused and changes nothing.
+#[test]
+fn face_extrude_of_a_split_face_in_another_component_refuses_an_uncaptured_source() {
+ let mut s = Session::default();
+ let component = run(&mut s, "component.create", json!({"name":"Source","grounded":false}));
+ let occurrence = component["occurrence"].as_u64().unwrap();
+ run(&mut s, "solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Stock"}));
+ run(&mut s, "solid.split_face", json!({"faces":[[10,15,20]],"plane":{"origin":[20,0,0],"normal":[1,0,0]}}));
+ run(&mut s, "component.activate", json!({"component":0}));
+ run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,0,0],"capture":false}));
+ let before = s.doc.to_json();
+ let pending = s.pending_moves.clone();
+ let error = s.execute("solid.extrude", &json!({"face":[40,15,20],"distance":5,"operation":"new"})).unwrap_err();
+ assert!(error.to_string().contains("capture the source occurrence position"), "{error}");
+ assert_eq!(s.doc.to_json(), before);
+ assert_eq!(s.pending_moves, pending);
+}
+
#[test]
fn repeated_source_face_profile_requires_and_uses_the_exact_active_occurrence() {
let mut s = Session::default();
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index b1ed9117a2..8d86118c1b 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -736,6 +736,36 @@ pub(crate) fn hostile_values() -> Vec<Value> {
]
}
+/// A copy of `s` as it stands: its design and model (sharing their bodies, as undo does), its
+/// undo and redo, its open sketch and the design it was entered from, and its log.
+fn copy_with_history(s: &Session) -> Session {
+ Session { undo: s.undo.clone(), redo: s.redo.clone(), sketch_entry: s.sketch_entry.clone(), log: s.log.clone(), ..s.scratch() }
+}
+
+/// The hostile-parameter test's copy starts where a session built afresh stands: cancelling its
+/// sketch and undoing step for step give the same designs, and the copied session is untouched.
+#[test]
+fn a_copy_with_history_undoes_like_the_session_it_copies() {
+ let start = |s: &mut Session| {
+ run(s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
+ run(s, "sketch.create", json!({"plane": "XY"}));
+ run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [5, 5]}));
+ };
+ let mut fresh = Session::default();
+ start(&mut fresh);
+ let mut original = Session::default();
+ start(&mut original);
+ let before = original.doc.clone();
+ let mut copy = copy_with_history(&original);
+ for (command, params) in [("sketch.cancel", json!({})), ("edit.undo", json!({})), ("edit.undo", json!({})), ("edit.redo", json!({}))] {
+ run(&mut fresh, command, params.clone());
+ run(&mut copy, command, params);
+ assert_eq!(*fresh.doc, *copy.doc, "{command}");
+ assert_eq!(fresh.active_sketch, copy.active_sketch, "{command}");
+ }
+ assert!(std::sync::Arc::ptr_eq(&original.doc, &before) && original.active_sketch.is_some(), "the copied session is untouched");
+}
+
/// Every command, every parameter name it documents, every hostile value: no panic escapes and
/// no command panics internally.
#[test]
@@ -880,16 +910,20 @@ fn hostile_params_never_panic() {
scope.spawn(|| {
let mut internal = Vec::new();
while let Some(&id) = ids.get(next.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) {
+ // A model with a sketch, a body and an active sketch, so most commands get far.
+ // Built once per command and copied for each call: SMLib serialises every
+ // call behind one lock, so building the box for each of the ~3000 calls
+ // ran one after another on every thread (over half an hour in CI).
+ let mut start = Session::default();
+ let _ = start.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10}));
+ let _ = start.execute("sketch.create", &json!({"plane": "XY"}));
+ let _ = start.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, 5]}));
for v in hostile_values() {
for k in keys {
if k == "path" && (id.starts_with("parameters.") || id == "timeline.export_script") {
continue; // parameter and script files: covered by their own tests (no stray files)
}
- let mut s = Session::default();
- // A model with a sketch, a body and an active sketch, so most commands get far.
- let _ = s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10}));
- let _ = s.execute("sketch.create", &json!({"plane": "XY"}));
- let _ = s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, 5]}));
+ let mut s = copy_with_history(&start);
let p = json!({ k: v.clone() });
if let Err(EngineError::Internal(id, msg)) = s.execute(id, &p) {
internal.push(format!("{id} {p}: {msg}"));
diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs
index 6f394c29ed..eca49fd84d 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -207,7 +207,7 @@ pub use point_path::{
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};
-pub use prism_measure::certified_prism_equivalent;
+pub use prism_measure::{PrismSection, certified_prism_equivalent, certified_prism_section};
pub use repair::{Hole, RebuiltFace, RefusedFace, RepairOptions, RepairReport, SewnGap, repair};
pub use sew::{EdgeSpec, FaceSpec, SurfSpec, sew, sew_touching};
pub use splitface::{SplitTool, split_body, split_faces, split_faces_with_map};
diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs
index 9f166d2dba..f7d06860df 100644
--- a/crates/kernel/src/native.rs
+++ b/crates/kernel/src/native.rs
@@ -68,13 +68,8 @@ pub fn encode_native_body(body: &Body) -> Result<Vec<u8>> {
let saved = SavedBody { solid: body.record().clone(), metadata: metadata::encode(body)?, runtime };
// Structural validation does not invoke another geometric reconstruction.
validate_topology(&saved)?;
- let value = serde_json::to_value(saved).map_err(invalid)?;
- validate_value(&value, 0)?;
- if value_nodes(&value) > MAX_VALUES {
- return Err(invalid("value budget"));
- }
let mut out = MAGIC.to_vec();
- binary::write(&value, &mut out, 0)?;
+ binary::write_serialized(&saved, &mut out)?;
Ok(out)
})
}
@@ -275,6 +270,8 @@ fn validate_value(v: &Value, depth: usize) -> Result<()> {
Ok(())
}
+/// How many values `v` is (a collection and each of its items): [`MAX_VALUES`] at most.
+#[cfg(test)]
fn value_nodes(v: &Value) -> usize {
match v {
Value::Array(a) => a.iter().fold(1usize, |n, v| n.saturating_add(value_nodes(v))),
@@ -338,6 +335,63 @@ mod tests {
}
}
+ /// The encoding as it was made before the encoder wrote as it serialized: the whole record as
+ /// a JSON value, checked, then written.
+ fn encoded_through_a_value(body: &Body) -> Result<Vec<u8>> {
+ let runtime = Runtime { size: body.size, coarse_missing: None };
+ let saved = SavedBody { solid: body.record().clone(), metadata: metadata::encode(body)?, runtime };
+ validate_topology(&saved)?;
+ let value = serde_json::to_value(saved).map_err(invalid)?;
+ validate_value(&value, 0)?;
+ if value_nodes(&value) > MAX_VALUES {
+ return Err(invalid("value budget"));
+ }
+ let mut out = MAGIC.to_vec();
+ binary::write(&value, &mut out, 0)?;
+ Ok(out)
+ }
+
+ /// Written as it serializes, a body's encoding is the bytes its JSON value gave, byte for
+ /// byte: plain, blended, cut (history), extruded (face sources), coloured, painted, split
+ /// along lines, round (spline forms), open, and placed far off.
+ #[test]
+ fn the_encoding_is_the_bytes_of_the_record_as_a_json_value() {
+ use solidcraft_geom::{Loop2, Plane, Region2, Vec2};
+ let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap();
+ let rounded = crate::fillet(&cube, &[Vec3::new(20., 0., 10.)], 2.).unwrap();
+ let bore = crate::cylinder(Vec3::new(10., 10., -1.), Vec3::Z, 3., 12.).unwrap();
+ let cut = crate::boolean(&rounded, &bore, crate::BoolOp::Cut).unwrap().unwrap();
+ let region = Region2 {
+ outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(0., 20.)]),
+ holes: vec![Loop2::circle(Vec2::new(10., 10.), 4.)],
+ };
+ let extruded = crate::extrude(&Plane::XY, &[region], 0., 5.).unwrap().remove(0);
+ assert!(extruded.face_sources().is_some_and(|s| s.iter().any(Option::is_some)), "an extrusion carries its face sources");
+ assert!(cut.history().is_some(), "a cut carries its history");
+ let paint = crate::Paint { opacity: 0.5, faces: vec![crate::FacePaint { face: 1, color: [0.9, 0.1, 0.2], opacity: 0.75 }] };
+ let painted = cube.clone().with_color(Some([0.1, 0.5, 0.9])).with_paint(Some(paint));
+ let top = (0..cube.face_count()).find(|f| cube.planar_face(*f).is_some_and(|p| p.normal().z > 0.5 && p.origin.z > 9.)).unwrap();
+ let split =
+ crate::split_faces(&cube, &[top], &crate::SplitTool::Plane(Plane::from_normal(Vec3::new(20., 0., 0.), Vec3::X).unwrap())).unwrap();
+ let surface = crate::copy_faces(&cube, &[Vec3::new(20., 15., 10.)]).unwrap();
+ let far = crate::transform(&cut, Vec3::new(1.0e6, -2.5e5, 3.0e4), Vec3::ZERO, Vec3::Z, 0.7).unwrap();
+ let bodies = [
+ cube,
+ rounded,
+ cut,
+ extruded,
+ painted,
+ split,
+ surface,
+ crate::sphere(Vec3::ZERO, 12.).unwrap(),
+ crate::torus(Vec3::ZERO, 20., 4.).unwrap(),
+ far,
+ ];
+ for (i, body) in bodies.iter().enumerate() {
+ assert_eq!(encode_native_body(body).unwrap(), encoded_through_a_value(body).unwrap(), "body {i}");
+ }
+ }
+
#[test]
fn box_and_fillet_have_stable_wire_records() {
let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap();
diff --git a/crates/kernel/src/native/binary.rs b/crates/kernel/src/native/binary.rs
index a5e8559278..bedb25b1f6 100644
--- a/crates/kernel/src/native/binary.rs
+++ b/crates/kernel/src/native/binary.rs
@@ -61,15 +61,20 @@ pub(super) fn read(input: &mut &[u8], depth: usize, budget: &mut usize) -> Resul
_ => return Err(invalid("unknown binary tag")),
})
}
+#[cfg(test)]
fn count(n: usize, out: &mut Vec<u8>) -> Result<()> {
out.extend_from_slice(&u32::try_from(n).map_err(invalid)?.to_le_bytes());
Ok(())
}
+#[cfg(test)]
fn text(s: &str, out: &mut Vec<u8>) -> Result<()> {
count(s.len(), out)?;
out.extend_from_slice(s.as_bytes());
Ok(())
}
+/// `value` appended to `out`. The encoder writes a body as it serializes
+/// ([`write_serialized`]); this writes a value already built, as tests build hostile ones.
+#[cfg(test)]
pub(super) fn write(value: &Value, out: &mut Vec<u8>, depth: usize) -> Result<()> {
if depth > 48 || out.len() > MAX_BYTES {
return Err(invalid("encoding budget"));
@@ -114,3 +119,517 @@ pub(super) fn write(value: &Value, out: &mut Vec<u8>, depth: usize) -> Result<()
}
Ok(())
}
+
+/// Why a value could not be written (a serde error carries only its message).
+#[derive(Debug)]
+pub(super) struct WriteError(String);
+
+impl std::fmt::Display for WriteError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+impl std::error::Error for WriteError {}
+
+impl serde::ser::Error for WriteError {
+ fn custom<T: std::fmt::Display>(msg: T) -> Self {
+ WriteError(msg.to_string())
+ }
+}
+
+fn refuse(what: &str) -> WriteError {
+ WriteError(what.into())
+}
+
+type Written<T = ()> = std::result::Result<T, WriteError>;
+
+/// `value` appended to `out` as the tagged binary value it is as JSON: the bytes [`write`] gives
+/// for `serde_json::to_value(value)`, refused where that, the checks on its result
+/// (`validate_value`, the [`MAX_VALUES`] budget) or [`write`] refuse. Written as it is
+/// serialized, with no JSON value in between: a body's record is millions of values, and building
+/// them all first was most of the cost of encoding it.
+///
+/// As JSON: a struct or a map is an object of its entries in key order (a JSON object's), its
+/// keys strings (a map's keys may be strings, characters, booleans or integers, written as JSON
+/// writes such keys); an enum variant without data its name, one with data an object of its name
+/// and the data; an option its value or null; bytes an array of numbers. A number is an integer
+/// (unsigned from 0 up, signed below) or a finite float; a float that is not finite is null.
+///
+/// Refused: nesting past 48, a string over 1 MiB, an array of more than [`MAX_ITEMS`], a float
+/// over 1e12 in size, more than [`MAX_VALUES`] values, more than [`MAX_BYTES`] in `out`.
+pub(super) fn write_serialized<T: serde::Serialize + ?Sized>(value: &T, out: &mut Vec<u8>) -> Result<()> {
+ let mut w = Writer { out, values: 0 };
+ value.serialize(Ser { w: &mut w, depth: 0 }).map_err(invalid)
+}
+
+struct Writer<'a> {
+ out: &'a mut Vec<u8>,
+ values: usize,
+}
+
+impl Writer<'_> {
+ /// Count a value at `depth` and write its tag.
+ fn start(&mut self, depth: usize, tag: u8) -> Written {
+ if depth > 48 {
+ return Err(refuse("nesting"));
+ }
+ self.values = self.values.saturating_add(1);
+ if self.values > MAX_VALUES {
+ return Err(refuse("value budget"));
+ }
+ self.out.push(tag);
+ self.fits()
+ }
+ fn fits(&self) -> Written {
+ if self.out.len() > MAX_BYTES { Err(refuse("encoding size")) } else { Ok(()) }
+ }
+ fn number(&mut self, depth: usize, tag: u8, bits: [u8; 8]) -> Written {
+ self.start(depth, tag)?;
+ self.out.extend_from_slice(&bits);
+ self.fits()
+ }
+ fn unsigned(&mut self, depth: usize, v: u64) -> Written {
+ self.number(depth, 4, v.to_le_bytes())
+ }
+ fn signed(&mut self, depth: usize, v: i64) -> Written {
+ match u64::try_from(v) {
+ Ok(u) => self.unsigned(depth, u),
+ Err(_) => self.number(depth, 3, v.to_le_bytes()),
+ }
+ }
+ fn float(&mut self, depth: usize, v: f64) -> Written {
+ if !v.is_finite() {
+ return self.start(depth, 0);
+ }
+ if v.abs() > 1e12 {
+ return Err(refuse("non-finite metadata"));
+ }
+ self.number(depth, 5, v.to_le_bytes())
+ }
+ fn length(&mut self, n: usize) -> Written {
+ self.out.extend_from_slice(&u32::try_from(n).map_err(|_| refuse("length"))?.to_le_bytes());
+ self.fits()
+ }
+ fn text(&mut self, s: &str) -> Written {
+ self.length(s.len())?;
+ self.out.extend_from_slice(s.as_bytes());
+ self.fits()
+ }
+ fn string(&mut self, depth: usize, s: &str) -> Written {
+ if s.len() > 1 << 20 {
+ return Err(refuse("string budget"));
+ }
+ self.start(depth, 6)?;
+ self.text(s)
+ }
+ /// Open a collection at `depth`: its tag and room for its count, which goes at the place
+ /// returned.
+ fn open(&mut self, depth: usize, tag: u8) -> Written<usize> {
+ self.start(depth, tag)?;
+ let at = self.out.len();
+ self.out.extend_from_slice(&[0; 4]);
+ self.fits()?;
+ Ok(at)
+ }
+ fn count_at(&mut self, at: usize, n: usize) -> Written {
+ let n = u32::try_from(n).map_err(|_| refuse("length"))?.to_le_bytes();
+ self.out.get_mut(at..at + 4).ok_or_else(|| refuse("count"))?.copy_from_slice(&n);
+ Ok(())
+ }
+}
+
+/// A value to write at a depth.
+pub(super) struct Ser<'w, 'a> {
+ w: &'w mut Writer<'a>,
+ depth: usize,
+}
+
+impl<'w, 'a> Ser<'w, 'a> {
+ /// An object of one entry, named `variant`, whose value comes next (at the depth returned).
+ fn variant(self, variant: &str) -> Written<Ser<'w, 'a>> {
+ let at = self.w.open(self.depth, 8)?;
+ self.w.count_at(at, 1)?;
+ self.w.text(variant)?;
+ Ok(Ser { w: self.w, depth: self.depth + 1 })
+ }
+ fn array(self) -> Written<Array<'w, 'a>> {
+ let at = self.w.open(self.depth, 7)?;
+ Ok(Array { w: self.w, depth: self.depth, at, items: 0 })
+ }
+ fn object(self) -> Written<Object<'w, 'a>> {
+ let at = self.w.open(self.depth, 8)?;
+ Ok(Object { w: self.w, depth: self.depth, at, entries: Vec::new(), key: None })
+ }
+}
+
+/// An array being written: where its count goes, and how many items it has.
+pub(super) struct Array<'w, 'a> {
+ w: &'w mut Writer<'a>,
+ depth: usize,
+ at: usize,
+ items: usize,
+}
+
+impl Array<'_, '_> {
+ fn item<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
+ self.items += 1;
+ if self.items > MAX_ITEMS {
+ return Err(refuse("array budget"));
+ }
+ value.serialize(Ser { w: self.w, depth: self.depth + 1 })
+ }
+ fn close(self) -> Written {
+ self.w.count_at(self.at, self.items)
+ }
+}
+
+/// An object being written: where its count goes, and each entry's key and where it ends. The
+/// entries are written as they come and put in key order when it closes.
+pub(super) struct Object<'w, 'a> {
+ w: &'w mut Writer<'a>,
+ depth: usize,
+ at: usize,
+ entries: Vec<(String, usize)>,
+ /// The key of the entry whose value comes next.
+ key: Option<String>,
+}
+
+impl Object<'_, '_> {
+ fn key(&mut self, key: String) -> Written {
+ self.w.text(&key)?;
+ self.key = Some(key);
+ Ok(())
+ }
+ fn value<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
+ let key = self.key.take().ok_or_else(|| refuse("an object's value without its key"))?;
+ value.serialize(Ser { w: self.w, depth: self.depth + 1 })?;
+ self.entries.push((key, self.w.out.len()));
+ Ok(())
+ }
+ fn entry<T: serde::Serialize + ?Sized>(&mut self, key: &str, value: &T) -> Written {
+ self.key(key.to_owned())?;
+ self.value(value)
+ }
+ fn close(self) -> Written {
+ let Object { w, at, entries, .. } = self;
+ let first = at + 4;
+ if !entries.windows(2).all(|p| p[0].0 < p[1].0) {
+ // In key order, as a JSON object (a map by key) holds them. A key twice would keep
+ // only its last value there; no record repeats one.
+ let mut spans: Vec<(&str, usize, usize)> = Vec::with_capacity(entries.len());
+ let mut start = first;
+ for (key, end) in &entries {
+ spans.push((key.as_str(), start, *end));
+ start = *end;
+ }
+ spans.sort_by(|a, b| a.0.cmp(b.0));
+ if spans.windows(2).any(|p| p[0].0 == p[1].0) {
+ return Err(refuse("duplicate key"));
+ }
+ let written = w.out.split_off(first);
+ for (_, start, end) in spans {
+ w.out.extend_from_slice(written.get(start - first..end - first).ok_or_else(|| refuse("object"))?);
+ }
+ }
+ w.count_at(at, entries.len())
+ }
+}
+
+/// A map key as JSON writes it: a string.
+struct Key;
+
+impl serde::Serializer for Key {
+ type Ok = String;
+ type Error = WriteError;
+ type SerializeSeq = serde::ser::Impossible<String, WriteError>;
+ type SerializeTuple = serde::ser::Impossible<String, WriteError>;
+ type SerializeTupleStruct = serde::ser::Impossible<String, WriteError>;
+ type SerializeTupleVariant = serde::ser::Impossible<String, WriteError>;
+ type SerializeMap = serde::ser::Impossible<String, WriteError>;
+ type SerializeStruct = serde::ser::Impossible<String, WriteError>;
+ type SerializeStructVariant = serde::ser::Impossible<String, WriteError>;
+
+ fn serialize_bool(self, v: bool) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_i8(self, v: i8) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_i16(self, v: i16) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_i32(self, v: i32) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_i64(self, v: i64) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_i128(self, v: i128) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_u8(self, v: u8) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_u16(self, v: u16) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_u32(self, v: u32) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_u64(self, v: u64) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_u128(self, v: u128) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_f32(self, _: f32) -> Written<String> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_f64(self, _: f64) -> Written<String> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_char(self, v: char) -> Written<String> {
+ Ok(v.to_string())
+ }
+ fn serialize_str(self, v: &str) -> Written<String> {
+ Ok(v.to_owned())
+ }
+ fn serialize_bytes(self, _: &[u8]) -> Written<String> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_none(self) -> Written<String> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_some<T: serde::Serialize + ?Sized>(self, _: &T) -> Written<String> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_unit(self) -> Written<String> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_unit_struct(self, _: &'static str) -> Written<String> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_unit_variant(self, _: &'static str, _: u32, variant: &'static str) -> Written<String> {
+ Ok(variant.to_owned())
+ }
+ fn serialize_newtype_struct<T: serde::Serialize + ?Sized>(self, _: &'static str, value: &T) -> Written<String> {
+ value.serialize(self)
+ }
+ fn serialize_newtype_variant<T: serde::Serialize + ?Sized>(self, _: &'static str, _: u32, _: &'static str, _: &T) -> Written<String> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_seq(self, _: Option<usize>) -> Written<Self::SerializeSeq> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_tuple(self, _: usize) -> Written<Self::SerializeTuple> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Written<Self::SerializeTupleStruct> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Written<Self::SerializeTupleVariant> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_map(self, _: Option<usize>) -> Written<Self::SerializeMap> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_struct(self, _: &'static str, _: usize) -> Written<Self::SerializeStruct> {
+ Err(refuse("a map key must be a string"))
+ }
+ fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Written<Self::SerializeStructVariant> {
+ Err(refuse("a map key must be a string"))
+ }
+}
+
+impl<'w, 'a> serde::Serializer for Ser<'w, 'a> {
+ type Ok = ();
+ type Error = WriteError;
+ type SerializeSeq = Array<'w, 'a>;
+ type SerializeTuple = Array<'w, 'a>;
+ type SerializeTupleStruct = Array<'w, 'a>;
+ type SerializeTupleVariant = Array<'w, 'a>;
+ type SerializeMap = Object<'w, 'a>;
+ type SerializeStruct = Object<'w, 'a>;
+ type SerializeStructVariant = Object<'w, 'a>;
+
+ fn serialize_bool(self, v: bool) -> Written {
+ self.w.start(self.depth, if v { 2 } else { 1 })
+ }
+ fn serialize_i8(self, v: i8) -> Written {
+ self.w.signed(self.depth, v.into())
+ }
+ fn serialize_i16(self, v: i16) -> Written {
+ self.w.signed(self.depth, v.into())
+ }
+ fn serialize_i32(self, v: i32) -> Written {
+ self.w.signed(self.depth, v.into())
+ }
+ fn serialize_i64(self, v: i64) -> Written {
+ self.w.signed(self.depth, v)
+ }
+ fn serialize_i128(self, v: i128) -> Written {
+ match (u64::try_from(v), i64::try_from(v)) {
+ (Ok(u), _) => self.w.unsigned(self.depth, u),
+ (_, Ok(i)) => self.w.signed(self.depth, i),
+ _ => Err(refuse("number out of range")),
+ }
+ }
+ fn serialize_u8(self, v: u8) -> Written {
+ self.w.unsigned(self.depth, v.into())
+ }
+ fn serialize_u16(self, v: u16) -> Written {
+ self.w.unsigned(self.depth, v.into())
+ }
+ fn serialize_u32(self, v: u32) -> Written {
+ self.w.unsigned(self.depth, v.into())
+ }
+ fn serialize_u64(self, v: u64) -> Written {
+ self.w.unsigned(self.depth, v)
+ }
+ fn serialize_u128(self, v: u128) -> Written {
+ self.w.unsigned(self.depth, u64::try_from(v).map_err(|_| refuse("number out of range"))?)
+ }
+ fn serialize_f32(self, v: f32) -> Written {
+ self.w.float(self.depth, v.into())
+ }
+ fn serialize_f64(self, v: f64) -> Written {
+ self.w.float(self.depth, v)
+ }
+ fn serialize_char(self, v: char) -> Written {
+ self.w.string(self.depth, v.encode_utf8(&mut [0; 4]))
+ }
+ fn serialize_str(self, v: &str) -> Written {
+ self.w.string(self.depth, v)
+ }
+ fn serialize_bytes(self, v: &[u8]) -> Written {
+ let mut a = self.array()?;
+ for b in v {
+ a.item(b)?;
+ }
+ a.close()
+ }
+ fn serialize_none(self) -> Written {
+ self.w.start(self.depth, 0)
+ }
+ fn serialize_some<T: serde::Serialize + ?Sized>(self, value: &T) -> Written {
+ value.serialize(self)
+ }
+ fn serialize_unit(self) -> Written {
+ self.w.start(self.depth, 0)
+ }
+ fn serialize_unit_struct(self, _: &'static str) -> Written {
+ self.w.start(self.depth, 0)
+ }
+ fn serialize_unit_variant(self, _: &'static str, _: u32, variant: &'static str) -> Written {
+ self.w.string(self.depth, variant)
+ }
+ fn serialize_newtype_struct<T: serde::Serialize + ?Sized>(self, _: &'static str, value: &T) -> Written {
+ value.serialize(self)
+ }
+ fn serialize_newtype_variant<T: serde::Serialize + ?Sized>(self, _: &'static str, _: u32, variant: &'static str, value: &T) -> Written {
+ value.serialize(self.variant(variant)?)
+ }
+ fn serialize_seq(self, _: Option<usize>) -> Written<Array<'w, 'a>> {
+ self.array()
+ }
+ fn serialize_tuple(self, _: usize) -> Written<Array<'w, 'a>> {
+ self.array()
+ }
+ fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Written<Array<'w, 'a>> {
+ self.array()
+ }
+ fn serialize_tuple_variant(self, _: &'static str, _: u32, variant: &'static str, _: usize) -> Written<Array<'w, 'a>> {
+ self.variant(variant)?.array()
+ }
+ fn serialize_map(self, _: Option<usize>) -> Written<Object<'w, 'a>> {
+ self.object()
+ }
+ fn serialize_struct(self, _: &'static str, _: usize) -> Written<Object<'w, 'a>> {
+ self.object()
+ }
+ fn serialize_struct_variant(self, _: &'static str, _: u32, variant: &'static str, _: usize) -> Written<Object<'w, 'a>> {
+ self.variant(variant)?.object()
+ }
+}
+
+impl serde::ser::SerializeSeq for Array<'_, '_> {
+ type Ok = ();
+ type Error = WriteError;
+ fn serialize_element<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
+ self.item(value)
+ }
+ fn end(self) -> Written {
+ self.close()
+ }
+}
+
+impl serde::ser::SerializeTuple for Array<'_, '_> {
+ type Ok = ();
+ type Error = WriteError;
+ fn serialize_element<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
+ self.item(value)
+ }
+ fn end(self) -> Written {
+ self.close()
+ }
+}
+
+impl serde::ser::SerializeTupleStruct for Array<'_, '_> {
+ type Ok = ();
+ type Error = WriteError;
+ fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
+ self.item(value)
+ }
+ fn end(self) -> Written {
+ self.close()
+ }
+}
+
+impl serde::ser::SerializeTupleVariant for Array<'_, '_> {
+ type Ok = ();
+ type Error = WriteError;
+ fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
+ self.item(value)
+ }
+ fn end(self) -> Written {
+ self.close()
+ }
+}
+
+impl serde::ser::SerializeMap for Object<'_, '_> {
+ type Ok = ();
+ type Error = WriteError;
+ fn serialize_key<T: serde::Serialize + ?Sized>(&mut self, key: &T) -> Written {
+ let key = key.serialize(Key)?;
+ self.key(key)
+ }
+ fn serialize_value<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
+ self.value(value)
+ }
+ fn end(self) -> Written {
+ self.close()
+ }
+}
+
+impl serde::ser::SerializeStruct for Object<'_, '_> {
+ type Ok = ();
+ type Error = WriteError;
+ fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Written {
+ self.entry(key, value)
+ }
+ fn end(self) -> Written {
+ self.close()
+ }
+}
+
+impl serde::ser::SerializeStructVariant for Object<'_, '_> {
+ type Ok = ();
+ type Error = WriteError;
+ fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Written {
+ self.entry(key, value)
+ }
+ fn end(self) -> Written {
+ self.close()
+ }
+}
diff --git a/crates/kernel/src/prism_measure.rs b/crates/kernel/src/prism_measure.rs
index 41036f34b5..3c5b5de0bd 100644
--- a/crates/kernel/src/prism_measure.rs
+++ b/crates/kernel/src/prism_measure.rs
@@ -637,6 +637,54 @@ pub fn certified_prism_equivalent(a: &crate::Body, b: &crate::Body) -> crate::Re
})
}
+/// A uniform prism along a plane's normal, read off a body's record: its levels above the plane
+/// and its section in the plane's coordinates.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PrismSection {
+ /// The levels of its bottom and its top cap above the plane (`lo < hi`).
+ pub lo: f64,
+ pub hi: f64,
+ /// Its section, exact: lines and arcs, the outer loop counter-clockwise, the holes clockwise.
+ pub region: solidcraft_geom::Region2,
+ /// How far the levels may be off the body's caps (the caps' vertices lie within it of them).
+ pub tolerance: f64,
+}
+
+/// The uniform prism `body` is along `plane`'s normal, when its record proves it one: two caps
+/// square to the normal, every other face a wall running straight between them along the
+/// normal and standing on both caps' edges, the two caps one section (see [`certified_prism_equivalent`]
+/// for the profiles it proves: a convex straight outline or a circle, with separate round
+/// holes). The body's current geometry, not how it was made: a tool trimmed by a boolean that
+/// left it a prism is one. `None` when that is not proved.
+pub fn certified_prism_section(body: &crate::Body, plane: &Plane) -> crate::Result<Option<PrismSection>> {
+ crate::guard("certified prism section", || {
+ if body.is_mesh() || !body.size().is_finite() {
+ return Ok(None);
+ }
+ let record = crate::native::brep_record(body)?;
+ let tol = body.size().max(1.) * 1e-10;
+ let Some(c) = certificate(&record, body.size(), plane, tol) else { return Ok(None) };
+ let mut outer = None;
+ let mut holes = Vec::new();
+ for lp in c.loops {
+ let positive = lp.area.lo > 0.;
+ let lp = solidcraft_geom::Loop2 { segs: lp.segments.into_vec() };
+ if positive {
+ if outer.replace(lp).is_some() {
+ return Ok(None);
+ }
+ } else {
+ holes.push(lp);
+ }
+ }
+ let Some(outer) = outer else { return Ok(None) };
+ // The caps' vertices are within twice the tolerance of their levels (`certificate`), and
+ // the levels are worked out from the plane's origin.
+ let tolerance = 2. * tol + 128. * f64::EPSILON * (plane.origin.len() + c.lo.abs() + c.hi.abs()).max(1.);
+ Ok(Some(PrismSection { lo: c.lo, hi: c.hi, region: solidcraft_geom::Region2 { outer, holes }, tolerance }))
+ })
+}
+
/// [`certified_prism_equivalent`] of the records `a` and `b` of bodies of sizes `size_a` and
/// `size_b`.
fn equivalent(a: &Brep, size_a: f64, b: &Brep, size_b: f64) -> Option<bool> {
@@ -823,6 +871,31 @@ mod tests {
r.faces.iter().position(|f| plane_of(&f.surface).is_none()).unwrap()
}
+ /// A 10 x 10 tool from z = 0 cut by a pin of radius 2 standing through it, joined to a plate
+ /// at z 1 ... 2 (a To Object tool trimmed by its curved target): the lump under the plate is
+ /// a prism from 0 to 1 whose section is the square less the pin's circle, 100 - 4π; the lump
+ /// above it steps (the pin stands up through it) and is no prism.
+ #[test]
+ fn a_trimmed_tool_reads_as_the_prism_of_its_current_section() {
+ use solidcraft_geom::{Loop2, Region2};
+ let pin = crate::cylinder(Vec3::new(25., 25., 0.), Vec3::Z, 2., 20.).unwrap();
+ let stop = crate::box_solid(Vec3::new(19., 19., 1.), Vec3::new(31., 31., 2.)).unwrap();
+ let roof = crate::boolean(&pin, &stop, crate::BoolOp::Union).unwrap().unwrap();
+ let square =
+ Region2 { outer: Loop2::polygon(&[Vec2::new(20., 20.), Vec2::new(30., 20.), Vec2::new(30., 30.), Vec2::new(20., 30.)]), holes: vec![] };
+ let tool = crate::extrude(&Plane::XY, &[square], 0., 25.).unwrap().remove(0);
+ let lumps = crate::boolean(&tool, &roof, crate::BoolOp::Cut).unwrap().unwrap().lumps().unwrap();
+ assert_eq!(lumps.len(), 2);
+ let sections: Vec<Option<PrismSection>> = lumps.iter().map(|l| certified_prism_section(l, &Plane::XY).unwrap()).collect();
+ let lower = sections.iter().flatten().collect::<Vec<_>>();
+ assert_eq!(lower.len(), 1, "only the lump under the plate is a prism");
+ let lower = lower[0];
+ assert!(lower.lo.abs() <= lower.tolerance && (lower.hi - 1.).abs() <= lower.tolerance, "{} … {}", lower.lo, lower.hi);
+ assert_eq!(lower.region.holes.len(), 1);
+ assert!(lower.region.outer.signed_area() > 0. && lower.region.holes[0].signed_area() < 0.);
+ assert!((lower.region.area() - (100. - 4. * std::f64::consts::PI)).abs() < 1e-8, "{}", lower.region.area());
+ }
+
#[test]
fn actual_drilled_prism_and_step_reopen_are_certified_without_history() {
let source = drilled(6., 0.);