Skip to content

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

Save the evaluated model with every design: exact, stored once, scaled caps (#3053) (#3093)

bherbruckd0afc31632da
diff --git a/Cargo.lock b/Cargo.lock
index c421d34bc5..96705531d8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4199,6 +4199,7 @@ dependencies = [
"cadmpeg-ir",
"cadmpeg-registry",
"gltf",
+ "log",
"quick-xml",
"rustix 1.1.5",
"serde",
diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs
index 6adaa8c463..5be417c49b 100644
--- a/apps/solidcraft-cli/src/main.rs
+++ b/apps/solidcraft-cli/src/main.rs
@@ -4,7 +4,7 @@
//! solidcraft-cli run <script.json|design.solidcraft|part.step|mesh.3mf> [--in design|part.step|mesh.3mf] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors]
//! solidcraft-cli eval <script.json|design.solidcraft|part.step> [--json-out FILE] (alias: inspect) measurements as JSON
//! solidcraft-cli script <design.solidcraft> [--out script.json] the design's history as a command script
-//! solidcraft-cli bench-open <design.solidcraft | part.step> [--parse-only] [--display LEVEL [--edit NAME EXPR]] loading timings as JSON lines
+//! solidcraft-cli bench-open <design.solidcraft | part.step> [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] loading timings as JSON lines
//! solidcraft-cli bench-agent [--scale F] [--save F] [--script-out F] a ~1,300-body design built command by command, timed
//! solidcraft-cli snapshot <script|design> [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes]
//! [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27]
@@ -49,7 +49,7 @@ const USAGE: &str = "usage:
as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark)
solidcraft-cli script <design.solidcraft|script.json> [--out script.json]
(the design's history as a command script that eval and run replay)
- solidcraft-cli bench-open <design.solidcraft | part.step> [--parse-only] [--display LEVEL [--edit NAME EXPR]]
+ solidcraft-cli bench-open <design.solidcraft | part.step> [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]]
solidcraft-cli bench-agent [--scale F] [--save design.solidcraft] [--script-out script.json]
solidcraft-cli snapshot <script|design> [--in design.solidcraft|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes]
[--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27]
@@ -655,10 +655,45 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> {
"{}",
json!({"step": "mesh", "ms": t.elapsed().as_secs_f64() * 1000.0, "place_ms": place_ms, "bodies": st.bodies.len(), "triangles": triangles})
);
+ let flag = |name: &str| args.iter().position(|a| a == name);
+ // `--save PATH`: save the opened design without its model cache (to PATH.plain.solidcraft) and
+ // as the app does, with it, then read the cache back.
+ let s = match flag("--save").and_then(|i| args.get(i + 1)) {
+ Some(out) => {
+ let mut s = s;
+ // Without the cache first, for comparison.
+ let plain = format!("{out}.plain.solidcraft");
+ let t = std::time::Instant::now();
+ s.execute("file.save_as", &json!({"path": plain, "cache": false})).map_err(|e| e.to_string())?;
+ let plain_ms = t.elapsed().as_secs_f64() * 1000.0;
+ let plain_bytes = std::fs::metadata(&plain).map(|m| m.len()).unwrap_or(0);
+ let t = std::time::Instant::now();
+ s.execute("file.save_as", &json!({"path": out})).map_err(|e| e.to_string())?;
+ let save_ms = t.elapsed().as_secs_f64() * 1000.0;
+ let bytes = std::fs::read(out).map_err(|e| format!("{out}: {e}"))?;
+ let t = std::time::Instant::now();
+ let cached = solidcraft_engine::io::read_design_geometry(&bytes).map(|m| m.bodies.len());
+ let read_ms = t.elapsed().as_secs_f64() * 1000.0;
+ // Why bodies could not be kept exactly, when the cache was left out.
+ let mut refused = std::collections::BTreeMap::<String, usize>::new();
+ if cached.is_none() {
+ for b in &s.model.state().bodies {
+ if let Err(e) = solidcraft_engine::kernel::encode_native_body(&b.body) {
+ *refused.entry(e.to_string()).or_default() += 1;
+ }
+ }
+ }
+ println!(
+ "{}",
+ json!({"step": "save", "ms": save_ms, "bytes": bytes.len(), "plain_ms": plain_ms, "plain_bytes": plain_bytes, "cached_bodies": cached, "cache_read_ms": read_ms, "refused": refused})
+ );
+ s
+ }
+ None => s,
+ };
// `--display LEVEL`: the display plans the viewport draws at that display quality, made as
// the GPU viewport makes them; `--edit NAME EXPR` then changes a parameter and times the
// evaluation and the plans of the bodies it changed.
- let flag = |name: &str| args.iter().position(|a| a == name);
let Some(level) = flag("--display").and_then(|i| args.get(i + 1)) else { return Ok(()) };
let q = solidcraft_engine::doc::display_quality::DisplayQuality::parse(level).ok_or("--display: coarse, normal, fine or ultra")?;
let plans = |st: &solidcraft_engine::doc::ModelState| {
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index eb7a1e5c3a..3c254beb51 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -1240,6 +1240,23 @@ impl Model {
})
}
+ /// Whether the results are `doc`'s evaluation: one per feature, each on the inputs `doc`
+ /// gives it, none stale, so [`Model::evaluate`] would keep every one of them. A document
+ /// changed without an evaluation since is not.
+ pub fn is_current(&self, doc: &Document) -> bool {
+ if self.results.len() != doc.features.len() || self.is_stale() {
+ return false;
+ }
+ let vals = evaluation_values(doc).0;
+ let steps = StepDigests::of(doc, &self.step_digests);
+ let marker = doc.marker.unwrap_or(usize::MAX);
+ let mut prev = 0;
+ doc.features.iter().zip(&self.results).enumerate().all(|(i, (f, r))| {
+ prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &steps);
+ r.id == f.id && r.fingerprint == prev
+ })
+ }
+
/// Re-evaluate the document, reusing results up to the first changed feature.
pub fn evaluate(&mut self, doc: &Document) {
let (vals, perr) = evaluation_values(doc);
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 9d336559e0..100c6435b1 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -33,11 +33,11 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("save")
.key("Ctrl+S")
.noundo()
- .params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (warm native geometry, default: false); preview?: bool (saved display meshes, default: false)"),
+ .params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"),
CommandSpec::new("file.save_as", "Save As", save_as)
.icon("save")
.noundo()
- .params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (warm native geometry, default: false); preview?: bool (saved display meshes, default: false)"),
+ .params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"),
CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).icon("restore")
.noundo()
.params("dir? (default: the recovery folder) → designs autosaved by apps that crashed or closed with unsaved changes"),
@@ -401,23 +401,21 @@ impl Session {
/// Container bytes for desktop and browser saves. Only already evaluated bodies
/// and warm meshes are eligible; saving never forces evaluation or tessellation.
pub fn design_container(&self, compression: solidcraft_io::DesignCompression, preview: bool, cache: bool) -> solidcraft_io::Result<Vec<u8>> {
- let geometry = cache.then(|| saved_geometry(self)).flatten();
+ let design = self.design();
+ let geometry = cache.then(|| saved_geometry(self, &design)).flatten();
let preview = preview.then(|| saved_preview(self)).flatten();
let thumbnail = cache.then(|| thumbnail::saved(self)).flatten();
- solidcraft_io::write_design_container_with_thumbnail(&self.design(), compression, preview.as_ref(), geometry.as_deref(), thumbnail.as_deref())
+ solidcraft_io::write_design_container_with_thumbnail(&design, compression, preview.as_ref(), geometry.as_deref(), thumbnail.as_deref())
}
}
-fn saved_geometry(s: &Session) -> Option<Vec<solidcraft_io::DesignGeometry>> {
- if s.active_sketch.is_some() || !s.pending_moves.is_empty() || s.model.results.iter().any(|r| r.error.is_some()) {
- return None;
- }
- let world = s.cached_world_state()?;
- if world.bodies.is_empty() || world.bodies.len() > 4096 {
+/// The evaluated model a save keeps, so opening need not rebuild it: only the finished evaluation
+/// of `design`, the document saved (no sketch being edited, no uncaptured moves, no feature errors).
+fn saved_geometry(s: &Session, design: &Document) -> Option<std::sync::Arc<solidcraft_doc::ModelState>> {
+ if s.active_sketch.is_some() || !s.pending_moves.is_empty() || s.model.results.iter().any(|r| r.error.is_some()) || !s.model.is_current(design) {
return None;
}
- let painted = s.doc.painted(&world);
- Some(painted.bodies.iter().map(|b| solidcraft_io::DesignGeometry { name: b.name.clone(), body: b.body.clone() }).collect())
+ Some(s.model.state()).filter(|st| !st.bodies.is_empty())
}
/// Cache only warm display geometry. A save never waits for an unevaluated mesh.
@@ -461,7 +459,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
str_(p, "format").unwrap_or(default_design_format(&path)),
str_(p, "compression").unwrap_or("fast"),
bool_(p, "preview").unwrap_or(false),
- bool_(p, "cache").unwrap_or(false),
+ bool_(p, "cache").unwrap_or(true),
)
}
@@ -477,7 +475,7 @@ fn save_as(s: &mut Session, p: &Value) -> Result<Value> {
str_(p, "format").unwrap_or(default_design_format(&path)),
str_(p, "compression").unwrap_or("fast"),
bool_(p, "preview").unwrap_or(false),
- bool_(p, "cache").unwrap_or(false),
+ bool_(p, "cache").unwrap_or(true),
)
}
@@ -744,7 +742,7 @@ mod tests {
let save_path = std::env::temp_dir().join(format!("solidcraft-preview-save-{}.solidcraft", std::process::id()));
s.execute("file.save", &json!({"path":save_path})).unwrap();
let saved = std::fs::read(&save_path).unwrap();
- assert!(solidcraft_io::read_design_geometry(&saved).is_none(), "ordinary saves omit native geometry caches");
+ assert!(solidcraft_io::read_design_geometry(&saved).is_some(), "ordinary saves keep the evaluated model");
assert!(!saved.windows(b"cache/preview.bin".len()).any(|s| s == b"cache/preview.bin"), "ordinary saves omit redundant display meshes");
s.execute("file.save", &json!({"path":save_path,"preview":true})).unwrap();
assert!(solidcraft_io::read_design_preview(&std::fs::read(&save_path).unwrap()).is_some());
@@ -788,7 +786,7 @@ mod tests {
}
*s.world_cache.lock().unwrap() = None;
assert!(saved_preview(&s).is_none());
- assert!(saved_geometry(&s).is_none());
+ assert!(saved_geometry(&s, &s.doc).is_some(), "the timeline's bodies need no placement");
assert!(s.world_cache.lock().unwrap().is_none(), "saving must not prepare cold placements");
for body in &s.world_state().bodies {
body.mesh();
@@ -800,7 +798,7 @@ mod tests {
}
assert!(!s.pending_moves.is_empty());
assert!(saved_preview(&s).is_none(), "uncaptured positions are not in the saved document");
- assert!(saved_geometry(&s).is_none());
+ assert!(saved_geometry(&s, &s.doc).is_none());
s.execute("component.capture_position", &json!({})).unwrap();
for body in &s.world_state().bodies {
body.mesh();
@@ -815,11 +813,11 @@ mod tests {
}
assert!(editing.active_sketch.is_some());
assert!(saved_preview(&editing).is_none());
- assert!(saved_geometry(&editing).is_none());
+ assert!(saved_geometry(&editing, &editing.doc).is_none());
}
#[test]
- fn save_and_save_as_require_explicit_native_cache_opt_in() {
+ fn save_and_save_as_keep_the_model_unless_opted_out() {
// Thumbnails are drawn by the renderer the host installs.
crate::capture::install_test_renderer();
let mut session = Session::new(Document::new("Cache opt-in"));
@@ -837,8 +835,8 @@ mod tests {
}
session.execute(command, &params).unwrap();
let bytes = std::fs::read(&path).unwrap();
- assert_eq!(solidcraft_io::read_design_geometry(&bytes).is_some(), cache == Some(true), "{command}: {cache:?}");
- assert_eq!(solidcraft_io::read_design_thumbnail(&bytes).is_some(), cache == Some(true), "{command}: {cache:?}");
+ assert_eq!(solidcraft_io::read_design_geometry(&bytes).is_some(), cache != Some(false), "{command}: {cache:?}");
+ assert_eq!(solidcraft_io::read_design_thumbnail(&bytes).is_some(), cache != Some(false), "{command}: {cache:?}");
assert!(
!bytes.windows(b"cache/preview.bin".len()).any(|entry| entry == b"cache/preview.bin"),
"display meshes require preview: true"
@@ -856,14 +854,14 @@ mod tests {
session.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap();
let world = session.world_state();
assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none()));
- let mut cached = saved_geometry(&session).unwrap();
+ let mut cached = (*saved_geometry(&session, &session.doc).unwrap()).clone();
let bytes = session.design_container(solidcraft_io::DesignCompression::Fast, false, true).unwrap();
assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none()), "saving native geometry must not triangulate");
assert!(solidcraft_io::read_design_geometry(&bytes).is_some());
assert!(
solidcraft_io::read_design_geometry(&session.design_container(solidcraft_io::DesignCompression::Fast, false, false).unwrap()).is_none()
);
- cached[0].body = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(100., 100., 100.)).unwrap();
+ cached.bodies[0].body = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(100., 100., 100.)).unwrap();
let bytes =
solidcraft_io::write_design_container_with_cache(&session.doc, solidcraft_io::DesignCompression::Fast, None, Some(&cached)).unwrap();
let path = std::env::temp_dir().join(format!("solidcraft-native-forged-{}.solidcraft", std::process::id()));
diff --git a/crates/engine/tests/save_as_cache.rs b/crates/engine/tests/save_as_cache.rs
index 5506002b4a..5bfd1f4e1b 100644
--- a/crates/engine/tests/save_as_cache.rs
+++ b/crates/engine/tests/save_as_cache.rs
@@ -1,5 +1,6 @@
-//! Optional save caches survive a filename-driven rename, without warming or
-//! certifying placements that do not match the document being saved.
+//! Save caches survive a filename-driven rename. Display caches are never warmed for a save
+//! nor certified for placements that do not match the document being saved; the model cache
+//! (the timeline's bodies, before placement) needs no warm display.
use serde_json::json;
use solidcraft_doc::Document;
use solidcraft_engine::Session;
@@ -27,6 +28,11 @@ fn save(session: &mut Session, label: &str) -> Vec<u8> {
bytes
}
+/// Whether the file holds saved display meshes (a picture is also drawn from the model cache).
+fn saved_display(bytes: &[u8]) -> bool {
+ bytes.windows(b"cache/preview.bin".len()).any(|entry| entry == b"cache/preview.bin")
+}
+
#[test]
fn a_filename_rename_preserves_opted_in_warm_assembly_caches() {
let mut session = assembly();
@@ -34,8 +40,8 @@ fn a_filename_rename_preserves_opted_in_warm_assembly_caches() {
for label in ["first-warm", "renamed-warm"] {
let bytes = save(&mut session, label);
let geometry = solidcraft_io::read_design_geometry(&bytes).expect("warm geometry survives the rename");
- assert_eq!(geometry.len(), 1);
- assert!((solidcraft_kernel::measure(&geometry[0].body).unwrap().volume - 24.0).abs() < 1e-9);
+ assert_eq!(geometry.bodies.len(), 1);
+ assert!((solidcraft_kernel::measure(&geometry.bodies[0].body).unwrap().volume - 24.0).abs() < 1e-9);
assert!(solidcraft_io::read_design_preview(&bytes).is_some(), "warm display meshes survive the rename");
warm(&session);
}
@@ -46,13 +52,22 @@ fn naming_a_design_does_not_warm_cold_or_revalidate_stale_placements() {
let original = assembly();
let mut cold = Session::new((*original.doc).clone());
let bytes = save(&mut cold, "cold");
- assert!(solidcraft_io::read_design_geometry(&bytes).is_none());
- assert!(solidcraft_io::read_design_preview(&bytes).is_none());
+ assert!(solidcraft_io::read_design_geometry(&bytes).is_some(), "the model needs no warm display");
+ assert!(!saved_display(&bytes));
let mut stale = assembly();
warm(&stale);
stale.doc_mut().occurrences.first_mut().unwrap().transform[3][0] = 25.0;
let bytes = save(&mut stale, "stale");
- assert!(solidcraft_io::read_design_geometry(&bytes).is_none(), "old placements must not be certified for a changed document");
- assert!(solidcraft_io::read_design_preview(&bytes).is_none());
+ assert!(solidcraft_io::read_design_geometry(&bytes).is_some(), "a placement is not part of the timeline's bodies");
+ assert!(!saved_display(&bytes), "old placements must not be certified for a changed document");
+
+ // A document edited without an evaluation since is not saved with the old one's bodies.
+ let mut edited = assembly();
+ let feature = edited.doc.features.last().unwrap().id;
+ if let solidcraft_doc::FeatureKind::Box { length, .. } = &mut edited.doc_mut().features.iter_mut().find(|f| f.id == feature).unwrap().kind {
+ *length = "20".into();
+ }
+ let bytes = save(&mut edited, "edited");
+ assert!(solidcraft_io::read_design_geometry(&bytes).is_none(), "bodies of another document must not be saved as this one's");
}
diff --git a/crates/geom/src/brep.rs b/crates/geom/src/brep.rs
index 2e01e680ed..f8875ad87b 100644
--- a/crates/geom/src/brep.rs
+++ b/crates/geom/src/brep.rs
@@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize};
pub mod envelope;
-pub const VERSION: u32 = 2;
-pub const MAX_ITEMS: usize = 100_000;
+pub const VERSION: u32 = 3;
+pub const MAX_ITEMS: usize = 1_000_000;
const MAX_DEPTH: usize = 16;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -58,26 +58,113 @@ pub struct Frame {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Curve {
- Line { start: [f64; 3], end: [f64; 3] },
- CircleArc { frame: Frame, radius: f64, angle: [f64; 2] },
- EllipseArc { frame: Frame, radii: [f64; 2], angle: [f64; 2] },
- Polyline { points: Vec<[f64; 3]> },
- Spline { knots: Vec<f64>, points: Vec<[f64; 3]> },
- RationalSpline { knots: Vec<f64>, homogeneous: Vec<[f64; 4]> },
- Intersection { knots: Vec<f64>, points: Vec<[f64; 3]>, fitting_tolerance: f64, faces: Option<[u32; 2]> },
+ Line {
+ start: [f64; 3],
+ end: [f64; 3],
+ },
+ CircleArc {
+ frame: Frame,
+ radius: f64,
+ angle: [f64; 2],
+ },
+ EllipseArc {
+ frame: Frame,
+ radii: [f64; 2],
+ angle: [f64; 2],
+ },
+ Polyline {
+ points: Vec<[f64; 3]>,
+ },
+ Spline {
+ knots: Vec<f64>,
+ points: Vec<[f64; 3]>,
+ },
+ RationalSpline {
+ knots: Vec<f64>,
+ homogeneous: Vec<[f64; 4]>,
+ },
+ Intersection {
+ knots: Vec<f64>,
+ points: Vec<[f64; 3]>,
+ fitting_tolerance: f64,
+ faces: Option<[u32; 2]>,
+ },
+ /// The intersection of two surfaces, traced from `leader` (a polyline or spline near it)
+ /// to within `tolerance`: the procedural curve itself, exactly as its producer holds it.
+ SurfaceIntersection {
+ surfaces: [Box<Surface>; 2],
+ leader: Box<Curve>,
+ tolerance: f64,
+ },
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Surface {
- Plane { origin: [f64; 3], u_axis: [f64; 3], v_axis: [f64; 3] },
- Cylinder { frame: Frame, radius: f64, angle: [f64; 2], height: [f64; 2] },
- Cone { frame: Frame, radius_at_origin: f64, half_angle: f64, angle: [f64; 2], height: [f64; 2] },
- Sphere { frame: Frame, radius: f64, longitude: [f64; 2], latitude: [f64; 2] },
- Torus { frame: Frame, major_radius: f64, minor_radius: f64, longitude: [f64; 2], meridian: [f64; 2] },
- Spline { u_knots: Vec<f64>, v_knots: Vec<f64>, points: Vec<Vec<[f64; 3]>> },
- RationalSpline { u_knots: Vec<f64>, v_knots: Vec<f64>, homogeneous: Vec<Vec<[f64; 4]>> },
- Revolution { profile: Box<Curve>, origin: [f64; 3], axis: [f64; 3], angle: [f64; 2] },
+ Plane {
+ origin: [f64; 3],
+ u_axis: [f64; 3],
+ v_axis: [f64; 3],
+ },
+ /// The plane through three points, parameter (1, 0) at `u_point` and (0, 1) at `v_point`:
+ /// the points themselves, as its producer holds them (axes worked out from them would round).
+ PlaneThrough {
+ origin: [f64; 3],
+ u_point: [f64; 3],
+ v_point: [f64; 3],
+ },
+ Cylinder {
+ frame: Frame,
+ radius: f64,
+ angle: [f64; 2],
+ height: [f64; 2],
+ },
+ Cone {
+ frame: Frame,
+ radius_at_origin: f64,
+ half_angle: f64,
+ angle: [f64; 2],
+ height: [f64; 2],
+ },
+ Sphere {
+ frame: Frame,
+ radius: f64,
+ longitude: [f64; 2],
+ latitude: [f64; 2],
+ },
+ Torus {
+ frame: Frame,
+ major_radius: f64,
+ minor_radius: f64,
+ longitude: [f64; 2],
+ meridian: [f64; 2],
+ },
+ Spline {
+ u_knots: Vec<f64>,
+ v_knots: Vec<f64>,
+ points: Vec<Vec<[f64; 3]>>,
+ },
+ RationalSpline {
+ u_knots: Vec<f64>,
+ v_knots: Vec<f64>,
+ homogeneous: Vec<Vec<[f64; 4]>>,
+ },
+ Revolution {
+ profile: Box<Curve>,
+ origin: [f64; 3],
+ axis: [f64; 3],
+ angle: [f64; 2],
+ },
+ /// A full revolution of `profile` about `origin` and unit `axis`, then mapped by the
+ /// column-major affine `matrix`, with the normal reversed unless `forward`: the
+ /// revolution exactly as its producer holds it, nothing baked into the profile.
+ PlacedRevolution {
+ profile: Box<Curve>,
+ origin: [f64; 3],
+ axis: [f64; 3],
+ matrix: [[f64; 4]; 4],
+ forward: bool,
+ },
}
#[derive(Clone, Debug, thiserror::Error)]
@@ -190,6 +277,27 @@ fn curve(c: &Curve, depth: usize, budget: &mut Budget) -> Result<()> {
knots(k, p.len(), budget)?;
points(p, budget)
}
+ Curve::SurfaceIntersection { surfaces, leader, tolerance } => {
+ require(tolerance.is_finite() && (0.0..=1e3).contains(tolerance), "intersection tolerance")?;
+ for s in surfaces {
+ surface(s, depth + 1, budget)?;
+ }
+ // The leader is only a starting guess for the trace: its knots are the producer's,
+ // and a traced polyline may repeat a point.
+ require(depth < MAX_DEPTH, "geometry depth")?;
+ budget.add(1)?;
+ match &**leader {
+ Curve::Polyline { points: p } => {
+ require(p.len() >= 2, "empty intersection leader")?;
+ points(p, budget)
+ }
+ Curve::Spline { knots: k, points: p } => {
+ knots(k, p.len(), budget)?;
+ points(p, budget)
+ }
+ _ => Err(Invalid("intersection leader")),
+ }
+ }
}
}
fn surface(s: &Surface, depth: usize, budget: &mut Budget) -> Result<()> {
@@ -200,6 +308,11 @@ fn surface(s: &Surface, depth: usize, budget: &mut Budget) -> Result<()> {
points(&[*origin, *u_axis, *v_axis], budget)?;
require(vector(*u_axis).cross(vector(*v_axis)).len() > 1e-12, "degenerate plane")
}
+ Surface::PlaneThrough { origin, u_point, v_point } => {
+ points(&[*origin, *u_point, *v_point], budget)?;
+ let o = vector(*origin);
+ require((vector(*u_point) - o).cross(vector(*v_point) - o).len() > 1e-12, "degenerate plane")
+ }
Surface::Cylinder { frame: f, radius: r, angle: a, height } => {
frame(f, budget)?;
radius(*r)?;
@@ -243,6 +356,14 @@ fn surface(s: &Surface, depth: usize, budget: &mut Budget) -> Result<()> {
angle(a)?;
curve(profile, depth + 1, budget)
}
+ Surface::PlacedRevolution { profile, origin, axis, matrix, .. } => {
+ points(&[*origin, *axis], budget)?;
+ require((vector(*axis).len() - 1.0).abs() <= 1e-8, "revolution axis is not unit length")?;
+ points(matrix, budget)?;
+ let [x, y, z, _] = matrix.map(|c| vector([c[0], c[1], c[2]]));
+ require(x.cross(y).dot(z).abs() > 1e-12, "singular revolution placement")?;
+ curve(profile, depth + 1, budget)
+ }
}
}
@@ -363,6 +484,31 @@ mod tests {
assert!(Budget(MAX_ITEMS).add(1).is_err());
}
+ #[test]
+ fn exact_procedural_records_are_validated_and_round_trip() {
+ let plane = |z: f64| Box::new(Surface::Plane { origin: [0., 0., z], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] });
+ let leader = Box::new(Curve::Polyline { points: vec![[0.; 3], [0.; 3], [1., 0., 0.]] });
+ let c = Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: leader.clone(), tolerance: 1e-6 };
+ curve(&c, 0, &mut Budget(0)).unwrap();
+ assert_eq!(serde_json::from_str::<Curve>(&serde_json::to_string(&c).unwrap()).unwrap(), c);
+ let line = Box::new(Curve::Line { start: [0.; 3], end: [1.; 3] });
+ for bad in [
+ Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: line.clone(), tolerance: 1e-6 },
+ Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: leader.clone(), tolerance: f64::NAN },
+ Curve::SurfaceIntersection { surfaces: [plane(f64::INFINITY), plane(1.)], leader, tolerance: 1e-6 },
+ ] {
+ assert!(curve(&bad, 0, &mut Budget(0)).is_err());
+ }
+ let identity = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]];
+ let s = Surface::PlacedRevolution { profile: line.clone(), origin: [0.; 3], axis: [0., 0., 1.], matrix: identity, forward: false };
+ surface(&s, 0, &mut Budget(0)).unwrap();
+ assert_eq!(serde_json::from_str::<Surface>(&serde_json::to_string(&s).unwrap()).unwrap(), s);
+ let mut flat = identity;
+ flat[2] = [0.; 4];
+ let bad = Surface::PlacedRevolution { profile: line, origin: [0.; 3], axis: [0., 0., 1.], matrix: flat, forward: true };
+ assert!(surface(&bad, 0, &mut Budget(0)).is_err());
+ }
+
#[test]
fn analytic_records_have_independent_frames_and_domains() {
use std::f64::consts::{FRAC_PI_2, TAU};
diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml
index de4a2ef07a..aaf73e5d67 100644
--- a/crates/io/Cargo.toml
+++ b/crates/io/Cargo.toml
@@ -13,6 +13,7 @@ solidcraft-geom = { workspace = true }
solidcraft-kernel = { workspace = true }
solidcraft-doc = { workspace = true }
thiserror = { workspace = true }
+log = { workspace = true }
zip = { workspace = true }
quick-xml = { workspace = true }
gltf = { workspace = true }
diff --git a/crates/io/build.rs b/crates/io/build.rs
new file mode 100644
index 0000000000..45c77eed47
--- /dev/null
+++ b/crates/io/build.rs
@@ -0,0 +1,20 @@
+//! The commit the model cache is keyed by (`SOLIDCRAFT_SOURCE_COMMIT`): a cache is only the
+//! result of evaluating its design when the same source computed it. "unknown" without git (a
+//! source tarball), which never trusts a cache.
+
+use std::process::Command;
+
+fn git(args: &[&str]) -> Option<String> {
+ let out = Command::new("git").args(args).output().ok()?;
+ out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty())
+}
+
+fn main() {
+ let commit = git(&["rev-parse", "HEAD"]).unwrap_or_else(|| "unknown".into());
+ println!("cargo:rustc-env=SOLIDCRAFT_SOURCE_COMMIT={commit}");
+ // A new commit in this checkout (or worktree) restamps the build.
+ if let Some(dir) = git(&["rev-parse", "--git-dir"]) {
+ println!("cargo:rerun-if-changed={dir}/logs/HEAD");
+ }
+ println!("cargo:rerun-if-changed=build.rs");
+}
diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs
index e3fbf151df..50a457fe29 100644
--- a/crates/io/src/design.rs
+++ b/crates/io/src/design.rs
@@ -1,12 +1,13 @@
-//! Versioned design packages. Geometry is rebuilt from authoritative inputs; no
-//! evaluated cache is trusted here. Entries are never extracted to filesystem paths.
+//! Versioned design packages. Entries are never extracted to filesystem paths. The optional
+//! model cache is only read back by the build that wrote it, for the exact document it was
+//! written with.
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::sync::Arc;
mod native_cache;
mod thumbnail;
-pub use native_cache::{DesignGeometry, read_design_geometry};
+pub use native_cache::read_design_geometry;
pub use thumbnail::{THUMBNAIL_SIZE, read_design_thumbnail, read_design_thumbnail_file};
use serde_json::{Map, Value, json};
@@ -105,13 +106,14 @@ pub fn write_design_container_with_preview(doc: &Document, compression: DesignCo
write_design_container_with_cache(doc, compression, preview, None)
}
-/// Save an optional warm native cache without making document saving depend on it.
-/// Display meshes remain separately opt-in; no evaluation or meshing happens here.
+/// Save an optional model cache (the evaluated timeline's bodies) without making document
+/// saving depend on it. Display meshes remain separately opt-in; no evaluation or meshing
+/// happens here.
pub fn write_design_container_with_cache(
doc: &Document,
compression: DesignCompression,
preview: Option<&DesignPreview>,
- geometry: Option<&[DesignGeometry]>,
+ geometry: Option<&solidcraft_doc::ModelState>,
) -> Result<Vec<u8>> {
write_design_container_with_thumbnail(doc, compression, preview, geometry, None)
}
@@ -122,8 +124,21 @@ pub fn write_design_container_with_thumbnail(
doc: &Document,
compression: DesignCompression,
preview: Option<&DesignPreview>,
- geometry: Option<&[DesignGeometry]>,
+ geometry: Option<&solidcraft_doc::ModelState>,
thumbnail: Option<&[u8]>,
+) -> Result<Vec<u8>> {
+ write_container(doc, compression, preview, geometry, thumbnail, MAX_DESIGN_BYTES)
+}
+
+/// [`write_design_container_with_thumbnail`] within `budget` bytes for the optional caches (the
+/// container's budget; tests pass less).
+fn write_container(
+ doc: &Document,
+ compression: DesignCompression,
+ preview: Option<&DesignPreview>,
+ geometry: Option<&solidcraft_doc::ModelState>,
+ thumbnail: Option<&[u8]>,
+ budget: usize,
) -> Result<Vec<u8>> {
let mut writer = PackageWriter { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), names: BTreeSet::new(), expanded: 0, resolved: 0 };
let mut features = Vec::with_capacity(doc.features.len());
@@ -172,18 +187,28 @@ pub fn write_design_container_with_thumbnail(
let metadata = serde_json::to_vec(&metadata).map_err(invalid)?;
writer.part("document.json", &metadata, true)?;
writer.part("container.json", &serde_json::to_vec(&json!({"format": VERSION})).map_err(invalid)?, false)?;
- if let Some((manifest, data)) = geometry.and_then(|g| native_cache::encode_geometry(g, &metadata).ok())
- && writer.names.len().saturating_add(2) <= MAX_ENTRIES
- && writer
- .expanded
- .saturating_add(manifest.len())
- .saturating_add(data.len())
- .saturating_add(writer.names.len().saturating_mul(256))
- .saturating_add(65_536)
- <= MAX_DESIGN_BYTES
- {
- writer.part("cache/key.json", &manifest, false)?;
- writer.part("cache/brep.bin", &data, compression == DesignCompression::Compact)?;
+ // The model cache is optional: one that does not fit the container is left out, never a
+ // failed save.
+ let cache = geometry.and_then(|g| native_cache::encode_model(g, &metadata).ok()).filter(|(manifest, data)| {
+ let fits = writer.names.len().saturating_add(2) <= MAX_ENTRIES
+ && writer
+ .expanded
+ .saturating_add(manifest.len())
+ .saturating_add(data.len())
+ .saturating_add(writer.names.len().saturating_mul(256))
+ .saturating_add(65_536)
+ <= budget;
+ if !fits {
+ log::info!("the model cache ({} MB) does not fit the design file: saved without it", (manifest.len() + data.len()) >> 20);
+ }
+ fits
+ });
+ if let Some((manifest, data)) = cache {
+ let [manifest_entry, payload_entry] = native_cache::ENTRIES;
+ // Deflated whatever the policy: the encoded bodies shrink about fourfold to tenfold, faster
+ // than the extra bytes would be written and read.
+ writer.part(manifest_entry, &manifest, true)?;
+ writer.part(payload_entry, &data, true)?;
}
if let Some((manifest, data)) = preview.and_then(|p| encode_preview(p, &metadata).ok())
&& writer.names.len().saturating_add(2) <= MAX_ENTRIES
@@ -193,7 +218,7 @@ pub fn write_design_container_with_thumbnail(
.saturating_add(data.len())
.saturating_add(writer.names.len().saturating_mul(256))
.saturating_add(65_536)
- <= MAX_DESIGN_BYTES
+ <= budget
{
writer.part("cache/preview.json", &manifest, false)?;
writer.part("cache/preview.bin", &data, false)?;
@@ -483,7 +508,10 @@ impl<R: Read + Seek> DesignContainerReader<R> {
pub fn preview(&mut self) -> Option<DesignPreview> {
// An explicitly saved mesh avoids tessellation. Native cache is the default
// fallback, generating a bounded provisional mesh without source imports.
- read_preview(&mut self.reader).ok().or_else(|| native_cache::geometry_preview(self.geometry()?).ok())
+ read_preview(&mut self.reader).ok().or_else(|| {
+ let document = self.reader.document(16 << 20).ok()?;
+ native_cache::geometry_preview(&document, self.geometry()?).ok()
+ })
}
/// Portable PNG picture only; no source blobs or geometry are evaluated.
@@ -491,8 +519,8 @@ impl<R: Read + Seek> DesignContainerReader<R> {
thumbnail::read(&mut self.reader).ok()
}
- /// Native geometry is provisional, never a substitute for rebuilding the document.
- pub fn geometry(&mut self) -> Option<Vec<DesignGeometry>> {
+ /// The cached model state, when this build wrote it for exactly this document.
+ pub fn geometry(&mut self) -> Option<solidcraft_doc::ModelState> {
let document = self.reader.document(16 << 20).ok()?;
native_cache::read_geometry_with(&mut self.reader, &document).ok()
}
@@ -693,11 +721,11 @@ mod tests {
assert!(result.is_err_and(|e| e.to_string().contains("not a regular file")));
}
- fn native_geometry() -> Vec<DesignGeometry> {
- vec![DesignGeometry {
- name: "Cube".into(),
- body: solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10., 20., 30.)).unwrap(),
- }]
+ fn native_geometry() -> solidcraft_doc::ModelState {
+ let cube = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10., 20., 30.)).unwrap();
+ let mut state = solidcraft_doc::ModelState::default();
+ state.bodies.push(solidcraft_doc::ModelBody::new("Cube".into(), cube, 1));
+ state
}
#[test]
@@ -709,9 +737,9 @@ mod tests {
let bodies = native_geometry();
let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&bodies)).unwrap();
let entries = parts(&bytes);
- assert!(entries.contains_key("cache/brep.bin"));
+ assert!(entries.contains_key("cache/bodies.bin"));
assert!(!entries.contains_key("cache/preview.bin"));
- assert_eq!(read_design_geometry(&bytes).unwrap()[0].body.face_count(), bodies[0].body.face_count());
+ assert_eq!(read_design_geometry(&bytes).unwrap().bodies[0].body.face_count(), bodies.bodies[0].body.face_count());
assert_eq!(bytes, write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&bodies)).unwrap());
let count = std::rc::Rc::new(std::cell::Cell::new(0));
let mut reader = DesignContainerReader::new(CountingReader { source: Cursor::new(bytes), count: count.clone() }).unwrap();
@@ -721,23 +749,73 @@ mod tests {
assert!(count.get() >= step.len());
}
+ #[test]
+ fn model_cache_stores_repeated_parts_once_and_keeps_placed_copies() {
+ use solidcraft_geom::Vec3;
+ let part = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap();
+ let share = solidcraft_kernel::DisplayShare::new(part.clone());
+ let t = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [50., 0., 0., 1.]];
+ let mut state = solidcraft_doc::ModelState::default();
+ state.body_counter = 7;
+ for (i, body) in [part.clone(), part.clone()].into_iter().enumerate() {
+ state.bodies.push(solidcraft_doc::ModelBody::new(format!("Part {i}"), body, 1));
+ }
+ for x in [50., 90.] {
+ let moved = solidcraft_kernel::transform(&part, Vec3::new(x, 0., 0.), Vec3::ZERO, Vec3::Z, 0.).unwrap();
+ let mut t = t;
+ t[3][0] = x;
+ let mut b = solidcraft_doc::ModelBody::new(format!("Copy {x}"), moved.with_display_share(&share, t), 2);
+ b.component = 3;
+ b.source_name = Some("Part".into());
+ state.bodies.push(b);
+ }
+ let doc = document();
+ let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&state)).unwrap();
+ let manifest: Value = serde_json::from_slice(&parts(&bytes)["cache/model.json"]).unwrap();
+ assert_eq!(manifest["bodies"].as_array().unwrap().len(), 3, "the part and each placed copy, once each");
+ let read = read_design_geometry(&bytes).unwrap();
+ assert_eq!(read.body_counter, 7);
+ assert_eq!(read.bodies.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["Part 0", "Part 1", "Copy 50", "Copy 90"]);
+ let copies: Vec<_> = read.bodies[2..].iter().map(|b| b.body.display_share().unwrap()).collect();
+ assert_eq!(copies[0].0.id(), copies[1].0.id(), "copies show one display again");
+ assert_eq!(copies[1].1[3][0], 90.);
+ assert_eq!((read.bodies[3].component, read.bodies[3].source_name.as_deref(), read.bodies[3].feature), (3, Some("Part"), 2));
+ for (a, b) in state.bodies.iter().zip(&read.bodies) {
+ assert_eq!(solidcraft_kernel::encode_native_body(&a.body).unwrap(), solidcraft_kernel::encode_native_body(&b.body).unwrap());
+ }
+ }
+
+ /// A model cache that does not fit the design file is left out: the save succeeds, and the
+ /// design reads back as saved.
+ #[test]
+ fn a_model_cache_too_big_for_the_file_is_left_out_not_a_failed_save() {
+ let doc = document();
+ let bytes = write_container(&doc, DesignCompression::Fast, None, Some(&native_geometry()), None, 70_000).unwrap();
+ assert!(!parts(&bytes).contains_key("cache/model.json") && !parts(&bytes).contains_key("cache/bodies.bin"));
+ assert!(read_design_geometry(&bytes).is_none());
+ assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json());
+ // With room for it, the same model is kept.
+ let bytes = write_container(&doc, DesignCompression::Fast, None, Some(&native_geometry()), None, MAX_DESIGN_BYTES).unwrap();
+ assert!(read_design_geometry(&bytes).is_some());
+ }
+
#[test]
fn native_cache_mismatch_is_only_a_cache_miss() {
let doc = document();
let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&native_geometry())).unwrap();
let original = parts(&bytes);
- for key in ["format", "producer", "app", "document", "payload"] {
+ for key in ["format", "producer", "app", "build", "document", "payload"] {
let mut entries = original.clone();
- let mut manifest: Value = serde_json::from_slice(&entries["cache/key.json"]).unwrap();
+ let mut manifest: Value = serde_json::from_slice(&entries["cache/model.json"]).unwrap();
manifest[key] = json!("unsupported-or-stale");
- entries.insert("cache/key.json".into(), serde_json::to_vec(&manifest).unwrap());
+ entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap());
let bytes = package(&entries);
assert!(read_design_geometry(&bytes).is_none());
assert!(read_design_preview(&bytes).is_none());
assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json());
}
let mut entries = original;
- entries.get_mut("cache/brep.bin").unwrap()[0] ^= 1;
+ entries.get_mut("cache/bodies.bin").unwrap()[0] ^= 1;
let bytes = package(&entries);
assert!(read_design_geometry(&bytes).is_none());
assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json());
diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rs
index bfa6b42e43..3450e7c1a1 100644
--- a/crates/io/src/design/native_cache.rs
+++ b/crates/io/src/design/native_cache.rs
@@ -1,105 +1,250 @@
-//! Optional native cache. Its SolidCraft schema is independent of the producing kernel.
+//! The model cache: the evaluated bodies of a design's timeline, saved with it so opening need
+//! not rebuild them. Its SolidCraft schema is independent of the producing kernel; its key ties it
+//! to the exact document, build and platform that computed it (docs/design-container.md).
use super::*;
-const PRODUCER: &str = "solidcraft-truck-adapter/2";
-/// Provisional evaluated geometry. Never an editable document state.
-#[derive(Clone)]
-pub struct DesignGeometry {
- pub name: String,
- pub body: solidcraft_kernel::Body,
+use solidcraft_doc::{ModelBody, ModelState};
+
+const FORMAT: &str = "solidcraft-model-cache/1";
+const PRODUCER: &str = "solidcraft-truck-adapter/3";
+const MANIFEST: &str = "cache/model.json";
+const PAYLOAD: &str = "cache/bodies.bin";
+/// Body records (a placed copy is one record; its part is stored once).
+const MAX_RECORDS: usize = 200_000;
+/// Distinct stored bodies.
+const MAX_UNIQUE: usize = 100_000;
+const MAX_MANIFEST: usize = 32 << 20;
+
+/// The build that computed a cache: the same source, compiled for the same platform, computes the
+/// same numbers, so only its own caches are its results.
+fn build() -> String {
+ format!("{}/{}-{}", env!("SOLIDCRAFT_SOURCE_COMMIT"), std::env::consts::ARCH, std::env::consts::OS)
+}
+
+/// A 4 x 4 matrix as its 16 numbers, in storage order.
+fn matrix(t: &[[f64; 4]; 4]) -> Vec<f64> {
+ t.iter().flatten().copied().collect()
+}
+
+fn look(look: &solidcraft_doc::appearance::ImportedLook) -> Value {
+ let faces: Vec<Value> = look.faces.iter().map(|(name, (color, opacity))| json!([name, color, opacity])).collect();
+ json!({"color": look.color, "opacity": look.opacity, "faces": faces})
}
-pub(super) fn encode_geometry(bodies: &[DesignGeometry], document: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
- if bodies.is_empty() || bodies.len() > 4096 {
- return Err(invalid("native body count"));
+
+fn load_look(v: &Value) -> Result<solidcraft_doc::appearance::ImportedLook> {
+ let unit = |x: f32| x.is_finite() && (0.0..=1.0).contains(&x);
+ let color = |v: &Value| -> Result<Option<[f32; 3]>> {
+ let c: Option<[f32; 3]> = serde_json::from_value(v.clone()).map_err(invalid)?;
+ if c.is_some_and(|c| !c.iter().copied().all(unit)) {
+ return Err(invalid("cached colour"));
+ }
+ Ok(c)
+ };
+ let opacity: Option<f32> = serde_json::from_value(v.get("opacity").cloned().unwrap_or(Value::Null)).map_err(invalid)?;
+ if opacity.is_some_and(|o| !unit(o)) {
+ return Err(invalid("cached opacity"));
+ }
+ let mut faces = BTreeMap::new();
+ for f in v.get("faces").and_then(Value::as_array).ok_or_else(|| invalid("cached face looks"))? {
+ let name = f.get(0).and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached face name"))?;
+ let c = color(f.get(1).unwrap_or(&Value::Null))?.ok_or_else(|| invalid("cached face colour"))?;
+ let o = f.get(2).and_then(Value::as_f64).map(|o| o as f32).filter(|o| unit(*o)).ok_or_else(|| invalid("cached face opacity"))?;
+ faces.insert(name.to_owned(), (c, o));
}
+ Ok(solidcraft_doc::appearance::ImportedLook { color: color(v.get("color").unwrap_or(&Value::Null))?, opacity, faces })
+}
+
+/// Encode a model state's bodies. Identical bodies (the same part placed many times, a body a
+/// feature passed through) are stored once; a placed copy of a part records the part and its
+/// matrix, so it shows that part's display as it did before saving.
+pub(super) fn encode_model(state: &ModelState, document: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
+ if state.bodies.is_empty() || state.bodies.len() > MAX_RECORDS {
+ return Err(invalid("cached body count"));
+ }
+ // What to encode: every body, and the part every placed copy shows.
+ let mut shares: Vec<solidcraft_kernel::DisplayShare> = Vec::new();
+ let mut share_index = std::collections::HashMap::new();
+ for b in &state.bodies {
+ if let Some((share, _)) = b.body.display_share() {
+ share_index.entry(share.id()).or_insert_with(|| {
+ shares.push(share.clone());
+ shares.len() - 1
+ });
+ }
+ }
+ let bodies: Vec<&solidcraft_kernel::Body> = state.bodies.iter().map(|b| &b.body).chain(shares.iter().map(|s| s.original())).collect();
+ let encoded = solidcraft_kernel::map_on_threads(&bodies, 16, |b| solidcraft_kernel::encode_native_body(b).ok());
let mut data = Vec::new();
- let mut entries = Vec::new();
- let mut faces = 0usize;
- for entry in bodies {
- faces = faces.saturating_add(entry.body.face_count());
- if faces > 100_000 || entry.name.len() > 1024 {
- return Err(invalid("native geometry budget"));
+ let mut slices = Vec::new();
+ let mut by_digest = std::collections::HashMap::new();
+ let mut index = Vec::with_capacity(encoded.len());
+ for bytes in encoded {
+ let bytes = bytes.flatten().ok_or_else(|| invalid("body not stored exactly"))?;
+ let next = slices.len();
+ let i = *by_digest.entry(Sha256::digest(&bytes)).or_insert(next);
+ if i == next {
+ if data.len().saturating_add(bytes.len()) > MAX_DESIGN_BYTES || slices.len() >= MAX_UNIQUE {
+ return Err(invalid("model cache size"));
+ }
+ slices.push(json!([data.len(), bytes.len()]));
+ data.extend(bytes);
+ }
+ index.push(i);
+ }
+ let (body_index, share_body) = index.split_at(state.bodies.len());
+ let mut records = Vec::with_capacity(state.bodies.len());
+ for (b, i) in state.bodies.iter().zip(body_index) {
+ if b.name.len() > 1024 {
+ return Err(invalid("cached body name"));
+ }
+ let mut r = json!({"name": b.name, "body": i, "feature": b.feature, "component": b.component});
+ if let Some(source) = &b.source_name {
+ r["source_name"] = json!(source);
+ }
+ if b.source_transform != solidcraft_doc::IDENTITY {
+ r["source_transform"] = json!(matrix(&b.source_transform));
}
- let bytes = solidcraft_kernel::encode_native_body(&entry.body).map_err(invalid)?;
- let offset = data.len();
- if offset.saturating_add(bytes.len()) > 64 << 20 {
- return Err(invalid("native cache size"));
+ if b.transferred {
+ r["transferred"] = json!(true);
}
- entries.push(json!({"name":entry.name,"offset":offset,"length":bytes.len()}));
- data.extend(bytes);
+ if let Some(l) = &b.imported {
+ r["imported"] = look(l);
+ }
+ if let Some((share, t)) = b.body.display_share() {
+ let s = share_index.get(&share.id()).ok_or_else(|| invalid("display share"))?;
+ r["share"] = json!([s, matrix(&t)]);
+ }
+ records.push(r);
}
let manifest = serde_json::to_vec(&json!({
- "format":"solidcraft-brep-cache/1", "producer":PRODUCER,
- "app":env!("CARGO_PKG_VERSION"), "document":digest(document), "payload":digest(&data), "bodies":entries
+ "format": FORMAT, "producer": PRODUCER, "app": env!("CARGO_PKG_VERSION"), "build": build(),
+ "document": digest(document), "payload": digest(&data),
+ "bodies": slices, "shares": share_body, "body_counter": state.body_counter, "state": records,
}))
.map_err(invalid)?;
- if manifest.len() > 1 << 20 {
- return Err(invalid("native manifest size"));
+ if manifest.len() > MAX_MANIFEST {
+ return Err(invalid("model cache manifest size"));
}
Ok((manifest, data))
}
-/// Read only metadata and the native cache. Original blobs are not read/decompressed
-/// until the authoritative document reader needs them for background reconstruction.
-/// Any optional geometry failure is a miss, never a document error.
-pub fn read_design_geometry(bytes: &[u8]) -> Option<Vec<DesignGeometry>> {
+/// The cached model state of a design, when it holds one this build computed for exactly this
+/// document. Any failure is a miss, never a document error.
+pub fn read_design_geometry(bytes: &[u8]) -> Option<ModelState> {
if bytes.len() > MAX_DESIGN_BYTES || !is_design_container(bytes) {
return None;
}
DesignContainerReader::new(Cursor::new(bytes)).ok()?.geometry()
}
-pub(super) fn read_geometry_with<R: Read + Seek>(reader: &mut PackageReader<R>, document: &[u8]) -> Result<Vec<DesignGeometry>> {
+
+/// Whether `manifest` is a model cache this build wrote for `document`.
+fn current(manifest: &Value, document: &[u8]) -> bool {
+ let is = |key: &str, value: &str| manifest.get(key).and_then(Value::as_str) == Some(value);
+ is("format", FORMAT)
+ && is("producer", PRODUCER)
+ && is("app", env!("CARGO_PKG_VERSION"))
+ && is("build", &build())
+ && is("document", &digest(document))
+ // A development build of unknown source never trusts a cache.
+ && env!("SOLIDCRAFT_SOURCE_COMMIT") != "unknown"
+}
+
+pub(super) fn read_geometry_with<R: Read + Seek>(reader: &mut PackageReader<R>, document: &[u8]) -> Result<ModelState> {
let container: Value = serde_json::from_slice(&reader.limited_part("container.json", 4096)?).map_err(invalid)?;
if container.get("format").and_then(Value::as_str) != Some(VERSION) {
return Err(invalid("container version"));
}
- let manifest: Value = serde_json::from_slice(&reader.limited_part("cache/key.json", 1 << 20)?).map_err(invalid)?;
- if manifest.get("format").and_then(Value::as_str) != Some("solidcraft-brep-cache/1")
- || manifest.get("producer").and_then(Value::as_str) != Some(PRODUCER)
- || manifest.get("app").and_then(Value::as_str) != Some(env!("CARGO_PKG_VERSION"))
- {
- return Err(invalid("native cache version"));
+ let manifest: Value = serde_json::from_slice(&reader.limited_part(MANIFEST, MAX_MANIFEST)?).map_err(invalid)?;
+ if !current(&manifest, document) {
+ return Err(invalid("model cache key"));
}
-
- if manifest.get("document").and_then(Value::as_str) != Some(digest(document).as_str()) {
- return Err(invalid("native document key"));
- }
- // Validate the small parametric metadata before showing a provisional model.
+ // Validate the small parametric metadata before decoding any geometry.
Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?;
- let data = reader.limited_part("cache/brep.bin", 64 << 20)?;
+ let data = reader.limited_part(PAYLOAD, MAX_DESIGN_BYTES)?;
if manifest.get("payload").and_then(Value::as_str) != Some(digest(&data).as_str()) {
- return Err(invalid("native payload key"));
+ return Err(invalid("model cache payload key"));
}
- let entries =
- manifest.get("bodies").and_then(Value::as_array).filter(|b| !b.is_empty() && b.len() <= 4096).ok_or_else(|| invalid("native bodies"))?;
- let mut bodies = Vec::new();
+ let count = |v: &Value| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("model cache number"));
+ let slices = manifest
+ .get("bodies")
+ .and_then(Value::as_array)
+ .filter(|b| !b.is_empty() && b.len() <= MAX_UNIQUE)
+ .ok_or_else(|| invalid("cached bodies"))?;
let mut end = 0usize;
- let mut faces = 0usize;
- for entry in entries {
- let n = |key| entry.get(key).and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("native slice"));
- let offset = n("offset")?;
- let length = n("length")?;
+ let mut parts = Vec::with_capacity(slices.len());
+ for s in slices {
+ let (offset, length) = (count(s.get(0).unwrap_or(&Value::Null))?, count(s.get(1).unwrap_or(&Value::Null))?);
if offset != end {
- return Err(invalid("overlapping native bodies"));
- }
- end = end.checked_add(length).ok_or_else(|| invalid("native length overflow"))?;
- let name = entry.get("name").and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("native body name"))?.to_owned();
- let body = solidcraft_kernel::decode_native_body(data.get(offset..end).ok_or_else(|| invalid("truncated native body"))?).map_err(invalid)?;
- faces = faces.saturating_add(body.face_count());
- if faces > 100_000 {
- return Err(invalid("native face budget"));
+ return Err(invalid("overlapping cached bodies"));
}
- bodies.push(DesignGeometry { name, body });
+ end = end.checked_add(length).ok_or_else(|| invalid("cached body length"))?;
+ parts.push(data.get(offset..end).ok_or_else(|| invalid("truncated cached body"))?);
}
if end != data.len() {
- return Err(invalid("trailing native data"));
+ return Err(invalid("trailing cached data"));
}
- Ok(bodies)
+ let decoded = solidcraft_kernel::map_on_threads(&parts, 16, |bytes| solidcraft_kernel::decode_native_body(bytes).ok());
+ let bodies = decoded.into_iter().map(Option::flatten).collect::<Option<Vec<_>>>().ok_or_else(|| invalid("cached body"))?;
+ let body = |v: &Value| bodies.get(count(v)?).ok_or_else(|| invalid("cached body index"));
+ let shares = manifest
+ .get("shares")
+ .and_then(Value::as_array)
+ .filter(|s| s.len() <= MAX_UNIQUE)
+ .ok_or_else(|| invalid("cached shares"))?
+ .iter()
+ .map(|i| Ok(solidcraft_kernel::DisplayShare::new(body(i)?.clone())))
+ .collect::<Result<Vec<_>>>()?;
+ let records =
+ manifest.get("state").and_then(Value::as_array).filter(|s| !s.is_empty() && s.len() <= MAX_RECORDS).ok_or_else(|| invalid("cached state"))?;
+ let mut state = ModelState::default();
+ state.body_counter = count(manifest.get("body_counter").unwrap_or(&Value::Null))?;
+ for r in records {
+ let name = r.get("name").and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached body name"))?;
+ let mut kernel_body = body(r.get("body").unwrap_or(&Value::Null))?.clone();
+ if let Some(share) = r.get("share") {
+ let s = shares.get(count(share.get(0).unwrap_or(&Value::Null))?).ok_or_else(|| invalid("cached share index"))?;
+ let numbers: Vec<f64> = serde_json::from_value(share.get(1).cloned().unwrap_or(Value::Null)).map_err(invalid)?;
+ let t = matrix_of(&numbers)?;
+ kernel_body = kernel_body.with_display_share(s, t);
+ }
+ let feature = r.get("feature").and_then(Value::as_u64).ok_or_else(|| invalid("cached body feature"))?;
+ let mut b = ModelBody::new(name.to_owned(), kernel_body, feature);
+ b.component = r.get("component").and_then(Value::as_u64).ok_or_else(|| invalid("cached body component"))?;
+ b.source_name = match r.get("source_name") {
+ None => None,
+ Some(v) => Some(v.as_str().filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached source name"))?.to_owned()),
+ };
+ if let Some(v) = r.get("source_transform") {
+ let numbers: Vec<f64> = serde_json::from_value(v.clone()).map_err(invalid)?;
+ b.source_transform = matrix_of(&numbers)?;
+ }
+ b.transferred = r.get("transferred").and_then(Value::as_bool).unwrap_or(false);
+ if let Some(l) = r.get("imported") {
+ b.imported = Some(Arc::new(load_look(l)?));
+ }
+ state.bodies.push(b);
+ }
+ Ok(state)
}
-pub(super) fn geometry_preview(bodies: Vec<DesignGeometry>) -> Result<DesignPreview> {
+
+/// A 4 x 4 matrix from its 16 numbers in storage order, finite.
+fn matrix_of(numbers: &[f64]) -> Result<[[f64; 4]; 4]> {
+ if numbers.len() != 16 || numbers.iter().any(|x| !x.is_finite() || x.abs() > 1e12) {
+ return Err(invalid("cached matrix"));
+ }
+ let mut t = [[0.0; 4]; 4];
+ for (slot, x) in t.iter_mut().flatten().zip(numbers) {
+ *slot = *x;
+ }
+ Ok(t)
+}
+
+pub(super) fn geometry_preview(document: &[u8], state: ModelState) -> Result<DesignPreview> {
+ let doc = Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?;
+ let world = solidcraft_doc::world_state(&doc, &state);
let mut preview = DesignPreview::default();
let mut triangles = 0usize;
let mut display_bytes = 0usize;
- let faces: usize = bodies.iter().map(|b| b.body.face_count()).sum();
+ let faces: usize = world.bodies.iter().map(|b| b.body.face_count()).sum();
let detail = if faces > 20_000 {
1
} else if faces > 4_000 {
@@ -108,7 +253,7 @@ pub(super) fn geometry_preview(bodies: Vec<DesignGeometry>) -> Result<DesignPrev
8
};
let mut work = 1_000_000usize;
- for entry in bodies {
+ for entry in &world.bodies {
let mesh = solidcraft_kernel::native_preview_mesh(&entry.body, detail, &mut work).map_err(invalid)?;
triangles = triangles.saturating_add(mesh.triangles.len());
display_bytes = display_bytes.saturating_add(mesh.positions.len().saturating_mul(24)).saturating_add(mesh.triangles.len().saturating_mul(12));
@@ -116,7 +261,7 @@ pub(super) fn geometry_preview(bodies: Vec<DesignGeometry>) -> Result<DesignPrev
return Err(invalid("regenerated display budget"));
}
let displayed = MeshData {
- name: entry.name,
+ name: entry.name.clone(),
positions: mesh.positions.iter().flat_map(|p| [p.x, p.y, p.z]).collect(),
triangles: mesh.triangles.iter().flatten().copied().collect(),
color: entry.body.color(),
@@ -126,3 +271,5 @@ pub(super) fn geometry_preview(bodies: Vec<DesignGeometry>) -> Result<DesignPrev
}
Ok(preview)
}
+
+pub(super) const ENTRIES: [&str; 2] = [MANIFEST, PAYLOAD];
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index cf8bb2b53b..060cc9107b 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -12,10 +12,9 @@ mod design_metadata;
mod dxf;
mod dxf_out;
pub use design::{
- DesignCompression, DesignContainerReader, DesignGeometry, DesignPreview, THUMBNAIL_SIZE, is_design_container, read_design_file,
- read_design_geometry, read_design_preview, read_design_thumbnail, read_design_thumbnail_file, write_design_container,
- write_design_container_with_cache, write_design_container_with_compression, write_design_container_with_preview,
- write_design_container_with_thumbnail,
+ DesignCompression, DesignContainerReader, DesignPreview, THUMBNAIL_SIZE, is_design_container, read_design_file, read_design_geometry,
+ read_design_preview, read_design_thumbnail, read_design_thumbnail_file, write_design_container, write_design_container_with_cache,
+ write_design_container_with_compression, write_design_container_with_preview, write_design_container_with_thumbnail,
};
mod legacy_dir;
#[cfg(test)]
diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs
index 4e0946b159..6cbb7578a6 100644
--- a/crates/kernel/src/body.rs
+++ b/crates/kernel/src/body.rs
@@ -82,6 +82,25 @@ impl SharedDisplay {
}
}
+/// The display one body shares with its placed copies (see [`Body::display_share`]), so a
+/// saved design can store the part once and give its copies the same display again.
+#[derive(Clone, Debug)]
+pub struct DisplayShare(std::sync::Arc<SharedDisplay>);
+
+impl DisplayShare {
+ pub fn new(original: Body) -> Self {
+ DisplayShare(std::sync::Arc::new(SharedDisplay::new(original)))
+ }
+ /// The body whose display the copies show.
+ pub fn original(&self) -> &Body {
+ &self.0.original
+ }
+ /// Identity: copies that show the same display have the same id.
+ pub fn id(&self) -> usize {
+ std::sync::Arc::as_ptr(&self.0) as usize
+ }
+}
+
/// `m` placed by the rigid matrix `t` (by columns, translation in `t[3]`, as the kernel's
/// transforms take it): positions, normals and edge polylines move, everything indexed stays.
/// `None` for anything but a rotation and translation (a reflection would turn the triangles
@@ -976,6 +995,23 @@ impl Body {
self
}
+ /// The display this body shows placed by a matrix (by columns), when it is a placed copy of
+ /// another body.
+ pub fn display_share(&self) -> Option<(DisplayShare, [[f64; 4]; 4])> {
+ self.display_of.as_deref().map(|(shared, t)| (DisplayShare(shared.clone()), *t))
+ }
+
+ /// The same body showing `share`'s display placed by `t` (see [`Body::display_share`]).
+ pub fn with_display_share(self, share: &DisplayShare, t: [[f64; 4]; 4]) -> Body {
+ self.with_display_of(share.0.clone(), t)
+ }
+
+ /// Identity of the solid: clones of a body (and bodies a feature passed through unchanged)
+ /// share it.
+ pub fn solid_id(&self) -> usize {
+ std::sync::Arc::as_ptr(&self.solid) as usize
+ }
+
pub fn with_split_lines(mut self, s: Option<std::sync::Arc<Vec<Vec<Vec3>>>>) -> Body {
self.splits = s.filter(|l| !l.is_empty());
// Split lines are drawn: the shared mesh does not have them.
diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs
index ece2cdc96b..a49cb3cedb 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -153,7 +153,7 @@ pub mod watch;
pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_max, fillet_max_each};
pub use blend_corner::fillet_radii;
pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper};
-pub use body::{Body, CapSignature, DISPLAY_ANGLE, EdgeInfo, FaceInfo, FacePaint, FaceSource, Paint};
+pub use body::{Body, CapSignature, DISPLAY_ANGLE, DisplayShare, EdgeInfo, FaceInfo, FacePaint, FaceSource, Paint};
pub use boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrategy, capture_boolean_diagnostics};
pub use boundary::{Boundary, boundary_patch};
pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDGE_PICKS, boundary_join, boundary_surface};
diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs
index 3afaf3bee5..0b1af58a54 100644
--- a/crates/kernel/src/native.rs
+++ b/crates/kernel/src/native.rs
@@ -1,5 +1,5 @@
//! SolidCraft native, versioned binary geometry. No STEP conversion or display meshes.
-//! A cache remains provisional until the document is rebuilt; hashes are not trust.
+//! Exact: a decoded body is the encoded one, number for number, for the same producer.
use crate::{Body, KernelError, Result, guard};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Number, Value};
@@ -11,23 +11,38 @@ mod metadata;
mod preview;
pub use preview::native_preview_mesh;
-// 01/02 were development-only prototypes; independent metadata records start at 03.
-const MAGIC: &[u8; 8] = b"SCBREP03";
-const MAX_BYTES: usize = 64 << 20;
-const MAX_ITEMS: usize = 100_000;
+// 01/02 were development-only prototypes; independent metadata records start at 03; 04 stores
+// procedural intersections and placed revolutions exactly, and the measured runtime values.
+const MAGIC: &[u8; 8] = b"SCBREP04";
+// A body's own limits. A design's cache holds many bodies within the container's budgets, and
+// decoding is linear in the bytes, so one large part (an imported casting) fits.
+const MAX_BYTES: usize = 256 << 20;
+const MAX_ITEMS: usize = 1_000_000;
+const MAX_VALUES: usize = 20_000_000;
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SavedBody {
solid: solidcraft_geom::brep::Brep,
metadata: solidcraft_geom::brep::envelope::Metadata,
+ runtime: Runtime,
+}
+
+/// What a body measured about itself that later operations read: kept so a decoded body works
+/// to the same tolerances as the one encoded, without measuring again.
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct Runtime {
+ /// [`Body::size`] as stored (0: not measured).
+ size: f64,
+ /// The orientation mesh's missing-face count at its tolerance.
+ coarse_missing: Option<(f64, u64)>,
}
fn invalid(detail: impl std::fmt::Display) -> KernelError {
KernelError::Invalid(format!("native B-rep: {detail}"))
}
-/// Explicit topology, spatial geometry, construction certificates and history.
-/// Procedural intersections use bounded fitting for provisional cache display.
+/// Explicit topology, spatial geometry, construction certificates and history, exactly.
/// Failure is a cache miss at the IO boundary, never a failed document save.
pub fn encode_native_body(body: &Body) -> Result<Vec<u8>> {
guard("encode native B-rep", || {
@@ -51,12 +66,13 @@ pub fn encode_native_body(body: &Body) -> Result<Vec<u8>> {
if body.mesh.is_some() {
return Err(invalid("mesh bodies are source blobs, not B-rep"));
}
- let saved = SavedBody { solid: adapter::encode(&body.solid)?, metadata: metadata::encode(body)? };
+ let runtime = Runtime { size: body.size, coarse_missing: body.coarse_missing.map(|(tol, n)| (tol, n as u64)) };
+ let saved = SavedBody { solid: adapter::encode(&body.solid)?, 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) > 2_000_000 {
+ if value_nodes(&value) > MAX_VALUES {
return Err(invalid("value budget"));
}
let mut out = MAGIC.to_vec();
@@ -66,14 +82,14 @@ pub fn encode_native_body(body: &Body) -> Result<Vec<u8>> {
}
/// Decode bounded untrusted data. Validate indices before topology extraction.
-/// Callers must not treat the decoded body as authoritative editing geometry.
+/// Only a caller that has checked who produced the data may treat it as evaluated geometry.
pub fn decode_native_body(bytes: &[u8]) -> Result<Body> {
if bytes.len() > MAX_BYTES || bytes.get(..8) != Some(MAGIC.as_slice()) {
return Err(invalid("version or size"));
}
guard("decode native B-rep", || {
let mut input = bytes.get(8..).ok_or_else(|| invalid("header"))?;
- let mut remaining = 2_000_000usize;
+ let mut remaining = MAX_VALUES;
let value = binary::read(&mut input, 0, &mut remaining)?;
if !input.is_empty() {
return Err(invalid("trailing data"));
@@ -82,11 +98,15 @@ pub fn decode_native_body(bytes: &[u8]) -> Result<Body> {
let saved: SavedBody = serde_json::from_value(value).map_err(invalid)?;
validate_topology(&saved)?;
let solid = adapter::decode(saved.solid)?;
+ let Runtime { size, coarse_missing } = saved.runtime;
+ if !(size.is_finite() && size >= 0.0) || coarse_missing.is_some_and(|(tol, n)| !tol.is_finite() || n > MAX_ITEMS as u64) {
+ return Err(invalid("runtime values"));
+ }
let mut body = Body {
solid: Arc::new(solid),
- size: 0.0,
+ size,
volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),
- coarse_missing: None,
+ coarse_missing: coarse_missing.map(|(tol, n)| (tol, n as usize)),
mesh: None,
color: None,
paint: None,
@@ -233,7 +253,7 @@ mod tests {
.iter()
.map(|body| {
let bytes = encode_native_body(body).unwrap();
- assert_eq!(&bytes[..8], b"SCBREP03");
+ assert_eq!(&bytes[..8], b"SCBREP04");
let mut raw = &bytes[8..];
let value = binary::read(&mut raw, 0, &mut 2_000_000).unwrap();
assert!(raw.is_empty());
@@ -241,7 +261,7 @@ mod tests {
})
.collect();
let actual = serde_json::json!(records);
- let expected: Value = serde_json::from_str(include_str!("native/fixtures/box-fillet-v3.json")).unwrap();
+ let expected: Value = serde_json::from_str(include_str!("native/fixtures/box-fillet-v4.json")).unwrap();
compare_wire(&expected, &actual);
}
diff --git a/crates/kernel/src/native/adapter.rs b/crates/kernel/src/native/adapter.rs
index ba661ec87f..8007244392 100644
--- a/crates/kernel/src/native/adapter.rs
+++ b/crates/kernel/src/native/adapter.rs
@@ -1,17 +1,12 @@
//! The truck adapter. Persisted data belongs to solidcraft_geom::brep, never truck.
use super::{Result, invalid};
-use mt::{BoundedCurve, EuclideanSpace, InnerSpace, Invertible, ParametricCurve, Transform, Transformed};
+use mt::Invertible;
use solidcraft_geom::brep as b;
use truck_modeling as mt;
-use truck_topology::compress as t;
-type Packed = t::CompressedSolid<mt::Point3, mt::Curve, mt::Surface>;
#[path = "analytic.rs"]
mod analytic;
-#[path = "fit.rs"]
-mod fit;
use analytic::{arc, full_turn, load_analytic, revolved};
-use fit::fit_intersection;
fn point(p: mt::Point3) -> [f64; 3] {
[p.x, p.y, p.z]
}
@@ -51,6 +46,8 @@ fn compatible_curve(c: &b::Curve) -> Result<()> {
b::Curve::Spline { knots, points } => clamped(knots, points.len()),
b::Curve::RationalSpline { knots, homogeneous } => clamped(knots, homogeneous.len()),
b::Curve::Intersection { knots, points, .. } => clamped(knots, points.len()),
+ // The producer's own trace: its surfaces must load; its leader is kept as it was.
+ b::Curve::SurfaceIntersection { surfaces, .. } => surfaces.iter().try_for_each(|s| compatible_surface(s)),
_ => Ok(()),
}
}
@@ -75,6 +72,8 @@ fn compatible_surface(s: &b::Surface) -> Result<()> {
full_turn(angle)?;
compatible_curve(profile)
}
+ b::Surface::PlaneThrough { .. } => Ok(()),
+ b::Surface::PlacedRevolution { profile, .. } => compatible_curve(profile),
b::Surface::Cylinder { angle, .. } | b::Surface::Cone { angle, .. } => full_turn(angle),
b::Surface::Sphere { longitude, .. } | b::Surface::Torus { longitude, .. } => full_turn(longitude),
}
@@ -93,19 +92,18 @@ fn compatible(body: &b::Brep) -> Result<()> {
pub(super) fn encode(solid: &mt::Solid) -> Result<b::Brep> {
let mut shells = Vec::new();
- let mut fitting_budget = 4096usize;
for shell in solid.compress().boundaries {
let vertices = shell.vertices.into_iter().map(point).collect();
let edges = shell
.edges
.into_iter()
- .map(|e| Ok(b::Edge { vertices: [index(e.vertices.0)?, index(e.vertices.1)?], curve: save_curve(&e.curve, 0, &mut fitting_budget)? }))
+ .map(|e| Ok(b::Edge { vertices: [index(e.vertices.0)?, index(e.vertices.1)?], curve: save_curve(&e.curve, 0)? }))
.collect::<Result<_>>()?;
let faces = shell
.faces
.into_iter()
.map(|f| {
- let (surface, normal_flip) = save_surface(&f.surface, 0, &mut fitting_budget)?;
+ let surface = save_surface(&f.surface, 0)?;
Ok(b::Face {
loops: f
.boundaries
@@ -123,7 +121,7 @@ pub(super) fn encode(solid: &mt::Solid) -> Result<b::Brep> {
})
.collect::<Result<_>>()?,
surface,
- forward: f.orientation != normal_flip,
+ forward: f.orientation,
})
})
.collect::<Result<_>>()?;
@@ -137,60 +135,60 @@ pub(super) fn encode(solid: &mt::Solid) -> Result<b::Brep> {
pub(super) fn decode(body: b::Brep) -> Result<mt::Solid> {
body.validate().map_err(invalid)?;
compatible(&body)?;
- if body.shells.iter().flat_map(|s| &s.edges).any(|e| e.vertices[0] == e.vertices[1]) {
- return Err(invalid("closed single-vertex edges are unsupported by this adapter"));
- }
- let packed = Packed {
- boundaries: body
- .shells
- .into_iter()
- .map(|s| {
- Ok(t::CompressedShell {
- vertices: s.vertices.into_iter().map(p).collect(),
- edges: s
- .edges
- .into_iter()
- .map(|e| Ok(t::CompressedEdge { vertices: (e.vertices[0] as usize, e.vertices[1] as usize), curve: load_curve(e.curve)? }))
- .collect::<Result<_>>()?,
- faces: s
- .faces
- .into_iter()
- .map(|f| {
- let mut loops = f.loops;
- if !f.forward {
- for wire in &mut loops {
- reverse_wire(wire);
- }
- }
- Ok(t::CompressedFace {
- boundaries: loops
- .into_iter()
- .map(|w| {
- w.into_iter().map(|e| t::CompressedEdgeIndex { index: e.edge as usize, orientation: e.forward }).collect()
- })
- .collect(),
- orientation: f.forward,
- surface: load_surface(f.surface)?,
- })
- })
- .collect::<Result<_>>()?,
- })
- })
- .collect::<Result<_>>()?,
- };
- let shells = packed.boundaries.into_iter().map(mt::Shell::extract).collect::<std::result::Result<Vec<_>, _>>().map_err(invalid)?;
+ let shells = body.shells.into_iter().map(shell).collect::<Result<Vec<_>>>()?;
if shells.iter().any(|s| s.shell_condition() == mt::ShellCondition::Irregular) {
return Err(invalid("non-manifold shell"));
}
Ok(mt::Solid::new_unchecked(shells))
}
+/// A shell's topology as recorded, references already checked: built as the kernel built it,
+/// without truck's checks for wires that touch themselves (a seam edge used twice, a closed edge
+/// on one vertex), which imported and modelled faces have.
+fn shell(s: b::Shell) -> Result<mt::Shell> {
+ let vertices: Vec<mt::Vertex> = s.vertices.into_iter().map(|v| mt::Vertex::new(p(v))).collect();
+ let vertex = |i: u32| vertices.get(i as usize).ok_or_else(|| invalid("edge vertices"));
+ let edges = s
+ .edges
+ .into_iter()
+ .map(|e| Ok(mt::Edge::new_unchecked(vertex(e.vertices[0])?, vertex(e.vertices[1])?, load_curve(e.curve)?)))
+ .collect::<Result<Vec<_>>>()?;
+ s.faces
+ .into_iter()
+ .map(|f| {
+ let mut loops = f.loops;
+ if !f.forward {
+ for wire in &mut loops {
+ reverse_wire(wire);
+ }
+ }
+ let wires = loops
+ .into_iter()
+ .map(|w| {
+ w.into_iter()
+ .map(|u| {
+ let e = edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?;
+ Ok(if u.forward { e.clone() } else { e.inverse() })
+ })
+ .collect::<Result<mt::Wire>>()
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let mut face = mt::Face::new_unchecked(wires, load_surface(f.surface)?);
+ if !f.forward {
+ face.invert();
+ }
+ Ok(face)
+ })
+ .collect()
+}
fn reverse_wire(wire: &mut [b::EdgeUse]) {
wire.reverse();
for edge in wire {
edge.forward = !edge.forward;
}
}
-fn save_curve(c: &mt::Curve, d: usize, fitting_budget: &mut usize) -> Result<b::Curve> {
+/// Exact: every record holds the producer's own numbers, so loading it gives back the same
+/// curve, never a refit.
+fn save_curve(c: &mt::Curve, d: usize) -> Result<b::Curve> {
depth(d)?;
Ok(match c {
mt::Curve::Line(c) => b::Curve::Line { start: point(c.0), end: point(c.1) },
@@ -201,14 +199,56 @@ fn save_curve(c: &mt::Curve, d: usize, fitting_budget: &mut usize) -> Result<b::
knots: c.knot_vec().iter().copied().collect(),
homogeneous: c.control_points().iter().copied().map(vector4).collect(),
},
- mt::Curve::IntersectionCurve(_) => fit_intersection(c, fitting_budget)?,
+ mt::Curve::IntersectionCurve(c) => {
+ let leader = match c.leader() {
+ mt::Leader::Polyline(p) => b::Curve::Polyline { points: p.0.iter().copied().map(point).collect() },
+ mt::Leader::BSpline(c) => b::Curve::Spline {
+ knots: c.knot_vec().iter().copied().collect(),
+ points: c.control_points().iter().copied().map(point).collect(),
+ },
+ };
+ b::Curve::SurfaceIntersection {
+ surfaces: [Box::new(save_surface(c.surface0(), d + 1)?), Box::new(save_surface(c.surface1(), d + 1)?)],
+ leader: Box::new(leader),
+ tolerance: c.tolerance(),
+ }
+ }
})
}
-fn save_surface(s: &mt::Surface, d: usize, fitting_budget: &mut usize) -> Result<(b::Surface, bool)> {
+/// A plane as truck holds it: three points.
+#[derive(serde::Serialize, serde::Deserialize)]
+struct PlanePoints {
+ o: mt::Point3,
+ p: mt::Point3,
+ q: mt::Point3,
+}
+
+/// A revolution as truck holds it, built from its parts as they are (its constructors normalize
+/// the axis and compose the placement with the identity, either of which can round).
+#[derive(serde::Serialize)]
+struct PlacedRevolution {
+ entity: Revolved,
+ transform: mt::Matrix4,
+ orientation: bool,
+}
+#[derive(serde::Serialize)]
+struct Revolved {
+ curve: mt::Curve,
+ revolution: Axis,
+}
+#[derive(serde::Serialize)]
+struct Axis {
+ origin: mt::Point3,
+ axis: mt::Vector3,
+}
+
+fn save_surface(s: &mt::Surface, d: usize) -> Result<b::Surface> {
depth(d)?;
- let mut normal_flip = false;
- let saved = match s {
- mt::Surface::Plane(s) => b::Surface::Plane { origin: point(s.origin()), u_axis: vector(s.u_axis()), v_axis: vector(s.v_axis()) },
+ Ok(match s {
+ mt::Surface::Plane(s) => {
+ let PlanePoints { o, p, q } = serde_json::from_value(serde_json::to_value(s).map_err(invalid)?).map_err(invalid)?;
+ b::Surface::PlaneThrough { origin: point(o), u_point: point(p), v_point: point(q) }
+ }
mt::Surface::BSplineSurface(s) => b::Surface::Spline {
u_knots: s.uknot_vec().iter().copied().collect(),
v_knots: s.vknot_vec().iter().copied().collect(),
@@ -220,39 +260,16 @@ fn save_surface(s: &mt::Surface, d: usize, fitting_budget: &mut usize) -> Result
homogeneous: s.control_points().iter().map(|r| r.iter().copied().map(vector4).collect()).collect(),
},
mt::Surface::RevolutedCurve(s) => {
- let m = s.transform();
- let (x, y, z) = (m.x.truncate(), m.y.truncate(), m.z.truncate());
- let scale = x.magnitude();
- let tolerance = scale * 1e-10;
- if !scale.is_finite()
- || scale <= 1e-12
- || (y.magnitude() - scale).abs() > tolerance
- || (z.magnitude() - scale).abs() > tolerance
- || x.dot(y).abs() > scale * tolerance
- || x.dot(z).abs() > scale * tolerance
- || y.dot(z).abs() > scale * tolerance
- || m.x.w != 0.
- || m.y.w != 0.
- || m.z.w != 0.
- || m.w.w != 1.
- {
- return Err(invalid("non-similarity revolution transform needs an exact spline conversion"));
- }
- // Bake a similarity into the geometry, never into persisted processor data.
- // An improper rotation reverses the oriented axis in the rotation identity.
- let sign = if x.dot(y.cross(z)) < 0. { -1. } else { 1. };
- let axis = m.transform_vector(s.entity().axis()).normalize() * sign;
- let profile = s.entity().entity_curve().transformed(*m);
- normal_flip = !s.orientation();
- b::Surface::Revolution {
- profile: Box::new(save_curve(&profile, d + 1, fitting_budget)?),
- origin: point(m.transform_point(s.entity().origin())),
- axis: vector(axis),
- angle: [0., std::f64::consts::TAU],
+ let m = *s.transform();
+ b::Surface::PlacedRevolution {
+ profile: Box::new(save_curve(s.entity().entity_curve(), d + 1)?),
+ origin: point(s.entity().origin()),
+ axis: vector(s.entity().axis()),
+ matrix: [m.x, m.y, m.z, m.w].map(vector4),
+ forward: s.orientation(),
}
}
- };
- Ok((saved, normal_flip))
+ })
}
fn load_curve(c: b::Curve) -> Result<mt::Curve> {
Ok(match c {
@@ -269,6 +286,17 @@ fn load_curve(c: b::Curve) -> Result<mt::Curve> {
b::Curve::Intersection { knots, points, .. } => {
mt::Curve::BSplineCurve(mt::BSplineCurve::try_new(knots.into(), points.into_iter().map(p).collect()).map_err(invalid)?)
}
+ b::Curve::SurfaceIntersection { surfaces: [s0, s1], leader, tolerance } => {
+ let leader = match *leader {
+ b::Curve::Polyline { points } => mt::Leader::Polyline(mt::PolylineCurve(points.into_iter().map(p).collect())),
+ b::Curve::Spline { knots, points } => {
+ mt::Leader::BSpline(mt::BSplineCurve::try_new(knots.into(), points.into_iter().map(p).collect()).map_err(invalid)?)
+ }
+ _ => return Err(invalid("intersection leader")),
+ };
+ let (s0, s1) = (load_surface(*s0)?, load_surface(*s1)?);
+ mt::Curve::IntersectionCurve(mt::IntersectionCurve::new_unchecked(Box::new(s0), Box::new(s1), leader, tolerance))
+ }
})
}
fn load_surface(s: b::Surface) -> Result<mt::Surface> {
@@ -286,6 +314,15 @@ fn load_surface(s: b::Surface) -> Result<mt::Surface> {
full_turn(&angle)?;
revolved(load_curve(*profile)?, p(origin), v(axis), false)
}
+ b::Surface::PlaneThrough { origin, u_point, v_point } => mt::Surface::Plane(mt::Plane::new(p(origin), p(u_point), p(v_point))),
+ b::Surface::PlacedRevolution { profile, origin, axis, matrix: [x, y, z, w], forward } => {
+ let placed = PlacedRevolution {
+ entity: Revolved { curve: load_curve(*profile)?, revolution: Axis { origin: p(origin), axis: v(axis) } },
+ transform: mt::Matrix4::from_cols(v4(x), v4(y), v4(z), v4(w)),
+ orientation: forward,
+ };
+ mt::Surface::RevolutedCurve(serde_json::from_value(serde_json::to_value(placed).map_err(invalid)?).map_err(invalid)?)
+ }
analytic => load_analytic(analytic)?,
})
}
@@ -293,6 +330,7 @@ fn load_surface(s: b::Surface) -> Result<mt::Surface> {
#[cfg(test)]
mod tests {
use super::*;
+ use mt::{BoundedCurve, InnerSpace, ParametricCurve, Transformed};
#[test]
fn refuses_domain_or_axis_changes_instead_of_approximating() {
@@ -342,28 +380,42 @@ mod tests {
}
#[test]
- fn intersection_fit_is_spatial_bounded_and_independent_of_surface_solvers() {
- use mt::MetricSpace;
+ fn intersections_and_revolutions_reload_exactly() {
use solidcraft_geom::Vec3;
let cyl = crate::cylinder(Vec3::ZERO, Vec3::Z, 5., 40.).unwrap();
let block = crate::box_solid(Vec3::new(-20., -20., 20.), Vec3::new(20., 20., 60.)).unwrap();
let block = crate::transform(&block, Vec3::ZERO, Vec3::new(0., 0., 20.), Vec3::X, 0.4).unwrap();
let cut = crate::boolean(&cyl, &block, crate::BoolOp::Cut).unwrap().unwrap();
let curve = cut.solid.edge_iter().map(|e| e.curve()).find(|c| matches!(c, mt::Curve::IntersectionCurve(_))).unwrap();
- assert!(save_curve(&curve, 0, &mut 0).is_err());
- let record = save_curve(&curve, 0, &mut 4096).unwrap();
- let encoded = serde_json::to_string(&record).unwrap();
- assert!(!encoded.contains("leader") && !encoded.contains("surfaces"));
- let b::Curve::Intersection { fitting_tolerance, .. } = &record else { panic!("explicit fitted record required") };
- let tolerance = *fitting_tolerance;
- let restored = load_curve(record).unwrap();
+ let record = save_curve(&curve, 0).unwrap();
+ assert!(matches!(record, b::Curve::SurfaceIntersection { .. }), "the procedural curve itself, not a fit");
+ let restored = load_curve(record.clone()).unwrap();
let (a, b) = curve.range_tuple();
- for i in 0..=512 {
- let t = a + (b - a) * i as f64 / 512.;
- assert!(curve.subs(t).distance(restored.subs(t)) <= tolerance * 1.1, "sample {i}: error {}", curve.subs(t).distance(restored.subs(t)));
+ for i in 0..=64 {
+ let t = a + (b - a) * i as f64 / 64.;
+ assert_eq!(curve.subs(t), restored.subs(t), "sample {i}");
+ }
+ assert_eq!(save_curve(&restored, 0).unwrap(), record);
+ // The whole body: the same records again, and the same volume to the last bit.
+ let bytes = crate::encode_native_body(&cut).unwrap();
+ let decoded = crate::decode_native_body(&bytes).unwrap();
+ assert_eq!(crate::encode_native_body(&decoded).unwrap(), bytes);
+ assert_eq!(crate::measure(&decoded).unwrap().volume, crate::measure(&cut).unwrap().volume);
+ // A revolution keeps its own placement, reversed normal included.
+ let line = mt::Curve::Line(mt::Line(mt::Point3::new(2., 0., 0.), mt::Point3::new(2.5, 0., 3.)));
+ let mt::Surface::RevolutedCurve(mut placed) = revolved(line, mt::Point3::new(0., 1., 0.), mt::Vector3::new(0., 0., 1.), true) else {
+ panic!("a revolution")
+ };
+ placed.transform_by(mt::Matrix4::from_translation(mt::Vector3::new(1., 2., 3.)) * mt::Matrix4::from_angle_x(mt::Rad(0.3)));
+ let placed = mt::Surface::RevolutedCurve(placed);
+ let record = save_surface(&placed, 0).unwrap();
+ assert!(matches!(record, b::Surface::PlacedRevolution { forward: false, .. }));
+ let restored = load_surface(record.clone()).unwrap();
+ assert_eq!(save_surface(&restored, 0).unwrap(), record);
+ use mt::{ParametricSurface, ParametricSurface3D};
+ for (u, v) in [(0., 0.), (1.3, 0.4), (4., 1.)] {
+ assert_eq!(placed.subs(u, v), restored.subs(u, v));
+ assert_eq!(placed.normal(u, v), restored.normal(u, v));
}
- let decoded = crate::decode_native_body(&crate::encode_native_body(&cut).unwrap()).unwrap();
- let original = crate::measure(&cut).unwrap().volume;
- assert!((crate::measure(&decoded).unwrap().volume - original).abs() < original * 1e-5);
}
}
diff --git a/crates/kernel/src/native/fit.rs b/crates/kernel/src/native/fit.rs
deleted file mode 100644
index f51c08b6e9..0000000000
--- a/crates/kernel/src/native/fit.rs
+++ /dev/null
@@ -1,85 +0,0 @@
-//! Bounded export of procedural intersections as ordinary spatial cubic splines.
-//! The stored tolerance is the fitting target; the result is always provisional.
-use super::*;
-
-fn point_at(c: &mt::Curve, t: f64, budget: &mut usize) -> Result<mt::Point3> {
- *budget = budget.checked_sub(1).ok_or_else(|| invalid("intersection fitting budget"))?;
- let p = c.subs(t);
- if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() {
- return Err(invalid("intersection sample"));
- }
- Ok(p)
-}
-pub(super) fn fit_intersection(c: &mt::Curve, budget: &mut usize) -> Result<b::Curve> {
- let tolerance = 1e-4;
- let (start, end) = c.range_tuple();
- if !start.is_finite() || !end.is_finite() || start >= end {
- return Err(invalid("intersection range"));
- }
- // Fit each smooth parameter interval using spatial samples, without backend derivative conventions.
- // Only the resulting spatial spline crosses the persisted format boundary.
- let mt::Curve::IntersectionCurve(intersection) = c else {
- return Err(invalid("expected intersection"));
- };
- let mut breaks = vec![start, end];
- match intersection.leader() {
- mt::Leader::Polyline(points) => {
- if points.len() > 4096 {
- return Err(invalid("intersection parameter budget"));
- }
- breaks.extend((0..points.len()).map(|i| i as f64).filter(|t| *t > start && *t < end));
- }
- mt::Leader::BSpline(curve) => {
- if curve.knot_vec().len() > 4096 {
- return Err(invalid("intersection parameter budget"));
- }
- breaks.extend(curve.knot_vec().iter().copied().filter(|t| *t > start && *t < end));
- }
- }
- breaks.sort_by(f64::total_cmp);
- breaks.dedup();
- let mut stack = Vec::new();
- for pair in breaks.windows(2).rev() {
- let (a, b) = (pair[0], pair[1]);
- stack.push((a, b, point_at(c, a, budget)?, point_at(c, b, budget)?, 0u8));
- }
- let mut pieces = Vec::new();
- while let Some((a, b, pa, pb, depth)) = stack.pop() {
- let p1 = point_at(c, a + (b - a) / 3., budget)?.to_vec();
- let p2 = point_at(c, a + (b - a) * 2. / 3., budget)?.to_vec();
- let x = p1 * 27. - pa.to_vec() * 8. - pb.to_vec();
- let y = p2 * 27. - pa.to_vec() - pb.to_vec() * 8.;
- let controls = [pa, mt::Point3::from_vec((x * 2. - y) / 18.), mt::Point3::from_vec((y * 2. - x) / 18.), pb];
- let mut fits = true;
- for fraction in [0.125, 0.25, 0.5, 0.75, 0.875] {
- let actual = point_at(c, a + (b - a) * fraction, budget)?;
- let u = 1. - fraction;
- let fitted = controls[0].to_vec() * u * u * u
- + controls[1].to_vec() * 3. * u * u * fraction
- + controls[2].to_vec() * 3. * u * fraction * fraction
- + controls[3].to_vec() * fraction * fraction * fraction;
- if (actual.to_vec() - fitted).magnitude() > tolerance * 0.1 {
- fits = false;
- }
- }
- if fits {
- pieces.push((a, b, controls));
- } else {
- if depth >= 12 || pieces.len() + stack.len() >= 1023 {
- return Err(invalid("intersection fit did not converge"));
- }
- let middle = a + (b - a) / 2.;
- let pm = point_at(c, middle, budget)?;
- stack.push((middle, b, pm, pb, depth + 1));
- stack.push((a, middle, pa, pm, depth + 1));
- }
- }
- let first = pieces.first().ok_or_else(|| invalid("empty intersection fit"))?;
- let mut points = vec![point(first.2[0])];
- let mut knots = vec![start; 4];
- for (i, (_, b, controls)) in pieces.iter().enumerate() {
- points.extend(controls.iter().skip(1).copied().map(point));
- knots.extend(std::iter::repeat_n(*b, if i + 1 == pieces.len() { 4 } else { 3 }));
- }
- Ok(b::Curve::Intersection { knots, points, fitting_tolerance: tolerance, faces: None })
-}
diff --git a/crates/kernel/src/native/fixtures/box-fillet-v3.json b/crates/kernel/src/native/fixtures/box-fillet-v4.json
similarity index 95%
rename from crates/kernel/src/native/fixtures/box-fillet-v3.json
rename to crates/kernel/src/native/fixtures/box-fillet-v4.json
index fa1d6aedf6..cb6f314edf 100644
--- a/crates/kernel/src/native/fixtures/box-fillet-v3.json
+++ b/crates/kernel/src/native/fixtures/box-fillet-v4.json
@@ -292,6 +292,13 @@
"preserve_boundaries": false,
"version": 1
},
+ "runtime": {
+ "coarse_missing": [
+ 0.5099019513592785,
+ 0
+ ],
+ "size": 50.99019513592785
+ },
"solid": {
"shells": [
{
@@ -549,20 +556,20 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
40.0,
30.0,
0.0
],
- "u_axis": [
- -40.0,
+ "u_point": [
0.0,
+ 30.0,
0.0
],
- "v_axis": [
+ "v_point": [
+ 40.0,
0.0,
- -30.0,
0.0
]
}
@@ -590,18 +597,18 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
0.0,
0.0,
0.0
],
- "u_axis": [
+ "u_point": [
40.0,
0.0,
0.0
],
- "v_axis": [
+ "v_point": [
0.0,
0.0,
10.0
@@ -631,19 +638,19 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
40.0,
0.0,
0.0
],
- "u_axis": [
- 0.0,
+ "u_point": [
+ 40.0,
30.0,
0.0
],
- "v_axis": [
- 0.0,
+ "v_point": [
+ 40.0,
0.0,
10.0
]
@@ -672,20 +679,20 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
40.0,
30.0,
0.0
],
- "u_axis": [
- -40.0,
+ "u_point": [
0.0,
+ 30.0,
0.0
],
- "v_axis": [
- 0.0,
- 0.0,
+ "v_point": [
+ 40.0,
+ 30.0,
10.0
]
}
@@ -713,20 +720,20 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
0.0,
30.0,
0.0
],
- "u_axis": [
+ "u_point": [
+ 0.0,
0.0,
- -30.0,
0.0
],
- "v_axis": [
- 0.0,
+ "v_point": [
0.0,
+ 30.0,
10.0
]
}
@@ -754,21 +761,21 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
40.0,
30.0,
10.0
],
- "u_axis": [
- -40.0,
+ "u_point": [
0.0,
- 0.0
+ 30.0,
+ 10.0
],
- "v_axis": [
+ "v_point": [
+ 40.0,
0.0,
- -30.0,
- 0.0
+ 10.0
]
}
}
@@ -817,7 +824,7 @@
]
}
],
- "version": 2
+ "version": 3
}
},
{
@@ -1157,6 +1164,13 @@
"preserve_boundaries": false,
"version": 1
},
+ "runtime": {
+ "coarse_missing": [
+ 0.5099019513592785,
+ 0
+ ],
+ "size": 50.99019513592785
+ },
"solid": {
"shells": [
{
@@ -1549,20 +1563,20 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
40.0,
30.0,
0.0
],
- "u_axis": [
- -40.0,
+ "u_point": [
0.0,
+ 30.0,
0.0
],
- "v_axis": [
+ "v_point": [
+ 40.0,
0.0,
- -30.0,
0.0
]
}
@@ -1590,18 +1604,18 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
0.0,
0.0,
0.0
],
- "u_axis": [
+ "u_point": [
40.0,
0.0,
0.0
],
- "v_axis": [
+ "v_point": [
0.0,
0.0,
10.0
@@ -1635,19 +1649,19 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
40.0,
0.0,
0.0
],
- "u_axis": [
- 0.0,
+ "u_point": [
+ 40.0,
30.0,
0.0
],
- "v_axis": [
- 0.0,
+ "v_point": [
+ 40.0,
0.0,
10.0
]
@@ -1676,20 +1690,20 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
40.0,
30.0,
0.0
],
- "u_axis": [
- -40.0,
+ "u_point": [
0.0,
+ 30.0,
0.0
],
- "v_axis": [
- 0.0,
- 0.0,
+ "v_point": [
+ 40.0,
+ 30.0,
10.0
]
}
@@ -1721,20 +1735,20 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
0.0,
30.0,
0.0
],
- "u_axis": [
+ "u_point": [
+ 0.0,
0.0,
- -30.0,
0.0
],
- "v_axis": [
- 0.0,
+ "v_point": [
0.0,
+ 30.0,
10.0
]
}
@@ -1762,21 +1776,21 @@
]
],
"surface": {
- "kind": "plane",
+ "kind": "plane_through",
"origin": [
40.0,
30.0,
10.0
],
- "u_axis": [
- -40.0,
+ "u_point": [
0.0,
- 0.0
+ 30.0,
+ 10.0
],
- "v_axis": [
+ "v_point": [
+ 40.0,
0.0,
- -30.0,
- 0.0
+ 10.0
]
}
},
@@ -1956,7 +1970,7 @@
]
}
],
- "version": 2
+ "version": 3
}
}
]
diff --git a/docs/design-container.md b/docs/design-container.md
index d84f43db63..29cddc7474 100644
--- a/docs/design-container.md
+++ b/docs/design-container.md
@@ -87,8 +87,8 @@ design remains intact until the complete rebuilt session is ready. Cancellation
any change of active document/revision discards both preview and completion.
Normal design reading, CLI and browser opening still rebuild authoritatively.
-Native B-rep caches can supply provisional display as described below; they never
-supply evaluated session state. The saved picture is not an interactive viewport.
+The model cache can supply provisional display as described below. The saved
+picture is not an interactive viewport.
## Seekable reader (phase 2, first increment)
@@ -110,45 +110,52 @@ stored blob; deferral means not loading or decoding the complete payload, not ze
physical reads of its byte range. Optional cache metadata is capped at 16 MiB;
larger metadata misses the cache and uses the normal authoritative part-size budget.
-## Native evaluated cache
-
-Engine Save/Save As can include `cache/key.json` and `cache/brep.bin` when
-explicitly requested with `cache: true` and geometry is warm. The default is
-`cache: false`, including browser downloads, to avoid extra save time and file size.
-JSON and recovery/autosave
-remain independent of the native cache. Saving never forces cold placement,
-evaluation or tessellation. Active sketches, uncaptured moves, errors, mesh bodies,
-unsupported adapter representations and exceeded budgets omit the cache.
-
-The manifest records `solidcraft-brep-cache/1`, the package version, the explicit
-producer revision `solidcraft-truck-adapter/2`, exact document/payload SHA-256 hashes
-and contiguous named body slices. The producer revision is deliberately maintained
-when adapter semantics change; it is not a source-tree fingerprint or build script.
-The binary data uses [SolidCraft's portable B-rep schema and codec](native-brep.md),
-including topology, curves/surfaces, face-source certificates, appearances and
-operation history. Truck's serialized structures are never stored. A different
-kernel can implement the same schema; until its adapter is tested it conservatively
-misses this producer's cache and rebuilds the authoritative document.
-
-Native caches cap 4,096 bodies, 100,000 total faces, a 1 MiB manifest and 64 MiB
-binary payload. Individual bodies have the schema/codec's additional limits.
-The reader validates metadata, manifest, slices and bodies before requesting a
-bounded provisional mesh. Original STEP/image/mesh blobs are resolved afterwards.
-No redundant display mesh is stored by default: `preview: true` remains a separate
-opt-in for already warm display meshes, which take precedence when present.
-
-Every failure in the optional cache is a miss. Even a checksum-valid forged body
-never becomes editable state: Open builds a fresh session from the document and
-original blobs, then replaces the provisional picture. Picking, measurements,
-persistent names and subsequent modelling use that rebuilt session. Existing
-cancellation/document-revision guards also apply. The web build retains synchronous
-authoritative rebuilding; portability does not imply background web evaluation.
-
-A counting-reader regression uses a 2.6 MB stored source blob and obtains the saved
-preview with fewer than 256 KiB read, then verifies the authoritative document is
-identical after resolving its source. Corrupt-source and preview-miss regressions,
-and truncation/seeded mutations through the combined reader, protect the boundary.
-This is an IO-volume test, not a geometry or first-frame benchmark.
+## Model cache
+
+Engine Save/Save As write the evaluated model with the design by default
+(`cache: true`; `cache: false` leaves it out): `cache/model.json` and
+`cache/bodies.bin`. Plain JSON, recovery/autosave and browser downloads do not
+carry it. Saving never forces placement, evaluation or tessellation: the model is
+the session's own evaluation, and only when it is the evaluation of the document
+being saved (`Model::is_current`). An active sketch, uncaptured moves, feature
+errors, mesh bodies or exceeded budgets leave the cache out; the design saves as
+before.
+
+Both entries are Deflate-compressed (level one) under either compression policy: the
+encoded bodies shrink about fourfold (an imported assembly) to tenfold (modelled parts),
+for a few tens of milliseconds.
+
+`cache/bodies.bin` holds every distinct body once, in
+[SolidCraft's native B-rep encoding](native-brep.md), as contiguous slices. The
+encoding is exact: a decoded body is the body that was saved, number for number
+(procedural intersection curves, placed revolutions and planes are stored as the
+kernel holds them, never refitted). Identical bodies share one slice (keyed by the
+SHA-256 of their encoding), and a placed copy of a repeated part (an instance from
+a STEP assembly) records the part and its matrix, so it shows that part's display
+again instead of being meshed on its own.
+
+`cache/model.json` records `solidcraft-model-cache/1`, the producer revision
+`solidcraft-truck-adapter/3`, the application version, the build (source commit,
+CPU architecture and OS), the SHA-256 of the exact `document.json` (whose blob
+references pin every STEP, mesh and image payload) and of `cache/bodies.bin`, the
+slices, and the bodies' records: name, feature, component, placement source,
+imported look and display share. A cache is read back only when every one of these
+matches: the same source compiled for the same platform computes the same numbers,
+so another build's cache is a miss. A build of unknown source (a tarball without
+git) never reads a cache.
+
+The fixed budgets of earlier caches (4,096 bodies, 100,000 faces, 64 MiB) scale
+with the design now: up to 200,000 body records, 100,000 distinct bodies, a 32 MiB
+manifest and a payload within the container's part budget (256 MiB), leaving room
+for the document. Individual bodies keep the codec's own limits. The archive-wide
+budgets (256 MiB per part, 512 MiB expanded, 10,000 entries) are unchanged, and the
+cache is left out when it would push the container near them. Decoding runs under
+`kernel::guard` and is linear in the payload's bytes.
+
+Opening still rebuilds the design from its timeline; the cache supplies the
+provisional picture (a bounded mesh of the placed bodies) before that finishes.
+Any failure in it is a miss, never a failed open. Earlier `cache/key.json` and
+`cache/brep.bin` entries are ignored.
## Review increments and kernel independence
@@ -188,7 +195,7 @@ run standalone wasm validation on each published code revision.
## Portable thumbnail
-A warm save with `cache: true` may add `cache/thumbnail.png` and its small
+A warm save (with `cache`, the default) may add `cache/thumbnail.png` and its small
`cache/thumbnail.json` key. The picture is a 240 x 150 PNG, bounded to 256 KiB,
keyed by `solidcraft-thumbnail/1`, application version, exact document SHA-256 and
PNG SHA-256. It contains an isometric view of visible solid bodies with their
@@ -200,9 +207,8 @@ work at four million supersampled pixels and face-color lookups at one million,
so overlapping triangles cannot make a small picture arbitrarily expensive.
It never evaluates or tessellates a cold
model for a picture. Active edits, pending moves, model errors, absent warm
-geometry or exceeded limits omit the picture. Ordinary saves and browser downloads
-default to `cache: false` and omit the PNG; `cache: true` explicitly opts in. Plain JSON
-never contains the PNG. The same writer is used by desktop and browser saves.
+geometry or exceeded limits omit the picture, as does `cache: false`. Browser
+downloads omit the PNG. Plain JSON never contains the PNG. The same writer is used by desktop and browser saves.
The seekable thumbnail reader checks the small key, retained document metadata,
PNG size/header and hashes without resolving source blobs. The Home/Recent Files
diff --git a/docs/native-brep.md b/docs/native-brep.md
index 2142583a0a..e60ea5aef2 100644
--- a/docs/native-brep.md
+++ b/docs/native-brep.md
@@ -1,11 +1,11 @@
-# Portable native B-rep, schema 2
+# Native B-rep, schema 3
-This is SolidCraft's geometry interchange data model in `solidcraft_geom::brep`.
-It has no modelling-backend dependency. It is the basis for #303's disposable
-native cache; it is not an editable-session snapshot or a STEP replacement for
-external interchange. The container reader, binary codec and kernel adapters are
-separate layers. Warm application saves can emit it as the optional native cache
-described in [the container format](design-container.md#native-evaluated-cache).
+This is SolidCraft's geometry data model in `solidcraft_geom::brep`. It has no
+modelling-backend dependency. It is the body encoding of a design's model cache
+([the container format](design-container.md#model-cache)); it is not a STEP
+replacement for external interchange. The container reader, binary codec and
+kernel adapters are separate layers. The truck adapter writes it exactly: a body
+decoded by the producer that encoded it is that body, number for number.
## Geometry and topology
@@ -38,7 +38,12 @@ Curves are tagged mathematical records:
- `intersection`: an explicit ordinary 3D polynomial spline (knots and Cartesian
control points), positive fitting tolerance in millimetres, and optional two
shell-local face references as hints. No supporting surfaces, leader, backend
- solver or parameter-search convention is required to evaluate it.
+ solver or parameter-search convention is required to evaluate it. (Read only;
+ schema 3 writers store the intersection itself, below.)
+- `surface_intersection`: the intersection of two surface records, traced from a
+ `leader` (a polyline or spline near it, its knots as the producer holds them) to
+ within `tolerance` mm. The curve is the procedural one, not a fit: a different
+ kernel must trace it again.
Surfaces include planes (origin and independent parameter axes), polynomial and
rational tensor-product splines, and explicit analytic records. Analytic frames
@@ -51,7 +56,14 @@ store origin and orthonormal x/y axes; z is x cross y. Angular ranges are radian
- torus: major/minor radii, longitude and meridian ranges;
- revolution: profile, origin, unit axis and angular range. Rotate the profile
around that axis using the right-hand rule. There is no persisted affine matrix
- or backend orientation/parameter-swap flag.
+ or backend orientation/parameter-swap flag. (Read only in schema 3.)
+- placed revolution: a full revolution of a profile about an origin and unit axis,
+ then mapped by a column-major affine `matrix` (non-singular), with the normal
+ reversed unless `forward`. Nothing is baked into the profile.
+
+A `plane_through` record is a plane given by three points: parameter (0, 0) at
+`origin`, (1, 0) at `u_point` and (0, 1) at `v_point`. Writers use it rather than
+the axis form, whose axes would be rounded differences of the points.
Cylinder/cone positions are origin + h*z + r(h)*(cos(u)*x + sin(u)*y).
Sphere positions are origin + r*(cos(v)*(cos(u)*x + sin(u)*y) + sin(v)*z).
@@ -62,7 +74,7 @@ when its runtime uses a different parameterization.
## Validation and trust
-Schema 2 caps 1,024 shells, 100,000 combined topology/geometry items, geometry
+Schema 3 caps 1,024 shells, 1,000,000 combined topology/geometry items, geometry
nesting at 16, spline degree at 16 and control points per spline dimension at
4,096. Numbers must be finite and bounded in magnitude by 1e12. Knot order, active
spline domain, multiplicities, rectangular grids, positive rational weights,
@@ -84,14 +96,17 @@ floating-point comparisons. A decoded cache remains provisional until authoritat
re-evaluation finishes. The document and original blobs remain sufficient to reopen
when a cache, representation, producer or adapter is unsupported.
-## Body binary envelope, version 3
+## Body binary envelope, version 4
-`SCBREP03` is the eight-byte envelope signature. Geometry schema 2 is nested in
-`solid`; metadata schema 1 is nested in `metadata`. These are separate version
-numbers because each contract can evolve independently. Signatures 01 and 02
-were development prototypes; 02 introduced the explicit geometry schema while
-03 also separates metadata from runtime Rust types. Unsupported versions are
-cache misses, not design-file migration failures.
+`SCBREP04` is the eight-byte envelope signature. Geometry schema 3 is nested in
+`solid`; metadata schema 1 is nested in `metadata`; `runtime` holds what the body
+measured about itself that later operations read (its size, from which kernel
+tolerances follow, and the orientation mesh's missing-face count), so a decoded
+body works to the same tolerances. These are separate version numbers because
+each contract can evolve independently. Signatures 01 and 02 were development
+prototypes; 02 introduced the explicit geometry schema while 03 also separated
+metadata from runtime Rust types and 04 made the encoding exact. Unsupported
+versions are cache misses, not design-file migration failures.
The envelope uses its own explicitly versioned records for color, paint, authored
boundaries, face-source certificates, operation history and boundary protection.
@@ -99,41 +114,36 @@ Plane, region and segment records are also owned by the wire schema. Exhaustive
manual adapter conversions separate these from runtime FaceSource, History,
FaceProv, EdgeProv, Paint, Seg2, Region2 and Plane types. Their serde derives or
internal refactors cannot silently redefine the saved fields. No truck serde
-record, pointer, tessellation or STEP string is written. Changing field semantics
+struct, pointer, tessellation or STEP string is written. Changing field semantics
requires a format version change, even if a Rust type keeps its name.
Values use tags: null=0, false=1, true=2, signed integer=3, unsigned integer=4,
binary64=5, UTF-8 string=6, array=7, object=8. Numbers use eight little-endian
bytes. Strings and collections use unsigned 32-bit little-endian lengths; object
keys are length-prefixed UTF-8, emitted lexicographically. Readers reject duplicate
-keys, unknown tags, non-finite numbers and trailing bytes. Limits are 64 MiB,
-2,000,000 values, depth 48, 100,000 entries per collection and 1 MiB per string.
-
-The truck adapter converts these records into runtime topology only after
-validation. It refuses single-vertex closed edges, standalone polylines,
-unclamped spline domains, non-full angular carrier surfaces and conversions that
-would change plane axes. Circle/ellipse arcs use exact rational quadratic loci;
-the adapter may reparameterize them. Similarity transforms on revolutions are
-baked into their profile, origin and axis (including reflections). Non-similarity
-transforms are refused until an exact independent spline conversion exists.
-Normal flips and backend boundary orientation are converted separately.
-
-Procedural intersections are exported with a bounded spatial cubic fit: 1e-4 mm
-fitting target, 4,096 evaluations shared across the body, at most 1,023 pieces and
-12 subdivisions per source interval. The target is checked at sampled positions;
-it is not a certified maximum error between samples. Failure to fit within these
-limits refuses the cache. A decoded fitted curve is an ordinary spatial spline;
-re-export may therefore use the `spline` record rather than retain its optional
-intersection annotation. This approximation is suitable only for the provisional
-cache, never authoritative modelling state.
-
-Decoded bodies remain provisional; the application must never use an untrusted
-cache as its editable model. Application integration keeps it provisional while
-rebuilding the document and original sources. A second
-backend needs its own tested adapter before cross-kernel interoperability can be
-claimed.
-
-The box-and-fillet golden JSON fixture pins the decoded version-3 envelope,
+keys, unknown tags, non-finite numbers and trailing bytes. Limits per body are
+256 MiB, 20,000,000 values, depth 48, 1,000,000 entries per collection and 1 MiB per
+string; a design's cache bounds the total (see the container format).
+
+The truck adapter writes every curve and surface as truck holds it: lines,
+B-spline and NURBS coefficients, the three points of a plane, a revolution's
+profile, axis, matrix and orientation, and an intersection's two surfaces, leader
+and tolerance. Decoding builds the same structures without the constructors that
+would round them (normalizing an axis, composing a matrix with the identity), and
+rebuilds each shell's topology as recorded, including closed edges on one vertex
+and seam edges a wire uses twice. On reading it refuses standalone polylines,
+unclamped spline domains and non-full angular carrier surfaces in the portable
+records it does not write. Circle/ellipse arcs use exact rational quadratic loci;
+the adapter may reparameterize them. Normal flips and backend boundary orientation
+are converted separately.
+
+Hashes prove which document and payload a cache belongs to, not who wrote it: the
+container's key ties a cache to the producer, application build and platform that
+computed it, and the decoder applies the structural and resource checks above to
+every body. A second backend needs its own tested adapter before cross-kernel
+interoperability can be claimed.
+
+The box-and-fillet golden JSON fixture pins the decoded version-4 envelope,
field names, tags, topology, geometry and metadata. Integer and structural values
are exact; floating coefficients allow 1e-10 relative/absolute platform rounding.
The signature is asserted separately. This protects the wire contract against