SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Display plans and the model cache for large STEP assemblies (#2814) (#4021)
Irakli Kourtis93a2922c5ee2
diff --git a/Cargo.lock b/Cargo.lockindex 7f962de598..943092f3ec 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4200,6 +4200,7 @@ name = "solidcraft-cli"version = "0.18.2"dependencies = ["image",+ "log","serde_json","solidcraft-engine","solidcraft-gpu",diff --git a/apps/solidcraft-cli/Cargo.toml b/apps/solidcraft-cli/Cargo.tomlindex 85401bae65..09354a55d0 100644--- a/apps/solidcraft-cli/Cargo.toml+++ b/apps/solidcraft-cli/Cargo.toml@@ -23,6 +23,7 @@ path = "src/alias.rs"solidcraft-engine = { workspace = true }solidcraft-gpu = { workspace = true }solidcraft-mcp = { workspace = true }+log = { workspace = true }serde_json = { workspace = true }[dev-dependencies]diff --git a/apps/solidcraft-cli/src/logger.rs b/apps/solidcraft-cli/src/logger.rsnew file mode 100644index 0000000000..d8503f5c90--- /dev/null+++ b/apps/solidcraft-cli/src/logger.rs@@ -0,0 +1,49 @@+//! What the engine logs (`log::info!`, `log::debug!`: why a body has no display plan, why a save+//! left its model cache out), written to stderr. Off unless asked for, so the CLI's output and+//! the scripts reading it stay as they are: `--debug` shows SolidCraft's own debug messages (and+//! other crates' warnings, whose debug output is large), `RUST_LOG=error|warn|info|debug|trace`+//! sets one level for every crate.++use log::{LevelFilter, Log, Metadata, Record};++struct Stderr {+ /// The level for SolidCraft's crates.+ ours: LevelFilter,+ /// The level for every other crate.+ others: LevelFilter,+}++impl Log for Stderr {+ fn enabled(&self, m: &Metadata) -> bool {+ m.level() <= if m.target().starts_with("solidcraft") { self.ours } else { self.others }+ }++ fn log(&self, r: &Record) {+ if self.enabled(r.metadata()) {+ use std::io::Write as _;+ // A closed stderr is no reason to stop.+ let _ = writeln!(std::io::stderr().lock(), "[{} {}] {}", r.level().as_str().to_ascii_lowercase(), r.target(), r.args());+ }+ }++ fn flush(&self) {}+}++/// Removes `--debug` from `args`, wherever it is (every subcommand takes it), and installs the+/// logger when it or `RUST_LOG` asks for one.+pub fn init(args: &mut Vec<String>) {+ let before = args.len();+ args.retain(|a| a != "--debug");+ let debug = args.len() != before;+ let env = std::env::var("RUST_LOG").ok().and_then(|v| v.trim().parse::<LevelFilter>().ok());+ let (ours, others) = match (debug, env) {+ (false, Some(all)) => (all, all),+ (true, Some(all)) => (all.max(LevelFilter::Debug), all),+ (true, None) => (LevelFilter::Debug, LevelFilter::Warn),+ (false, None) => return,+ };+ // Installed once, for the life of the process.+ if log::set_logger(Box::leak(Box::new(Stderr { ours, others }))).is_ok() {+ log::set_max_level(ours.max(others));+ }+}diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rsindex 04bc9766ce..fbeb6500ab 100644--- a/apps/solidcraft-cli/src/main.rs+++ b/apps/solidcraft-cli/src/main.rs@@ -17,6 +17,8 @@//! MCP server on stdio (docs/mcp.md)//! solidcraft-cli licences SolidCraft's licence and the third-party licences//! solidcraft-cli icon --out F.png|F.ico [--size N] the app icon (packaging; drawn, not a file)+//!+//! --debug (with any command) SolidCraft's debug log on stderr (or RUST_LOG=LEVEL)//! ```#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]#![forbid(unsafe_code)]@@ -24,6 +26,7 @@mod bench_agent;mod crashes;mod fuzz;+mod logger;mod oracle;mod preview;mod recipe;@@ -82,10 +85,13 @@ const USAGE: &str = "usage:lands on: gpu, gpu-software, or the CPU rasterizer (auto with no adapter, or cpu); the policy defaultsto SOLIDCRAFT_GPU, else auto; exits with an error when hardware or software finds no such adapter)solidcraft-cli icon --out icon.png [--size 256] | --out icon.ico+ --debug, with any command: what SolidCraft logs (why a body has no display plan, why a save left its+ model cache out), on stderr; RUST_LOG=error|warn|info|debug|trace sets one level for every crate";fn main() -> ExitCode {- let args: Vec<String> = std::env::args().skip(1).collect();+ let mut args: Vec<String> = std::env::args().skip(1).collect();+ logger::init(&mut args);let r = match args.first().map(String::as_str) {Some("run") => cmd_run(&args[1..]),Some("eval" | "inspect") => cmd_eval(&args[1..]),diff --git a/crates/geom/src/brep.rs b/crates/geom/src/brep.rsindex f8875ad87b..aef024e530 100644--- a/crates/geom/src/brep.rs+++ b/crates/geom/src/brep.rs@@ -8,6 +8,9 @@ pub mod envelope;pub const VERSION: u32 = 3;pub const MAX_ITEMS: usize = 1_000_000;const MAX_DEPTH: usize = 16;+/// Most control points along one direction of a spline (a helical thread flank written as one+/// spline has thousands along the helix); the item budget bounds a surface's grid as a whole.+pub const MAX_SPLINE_CONTROLS: usize = 8192;#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]@@ -195,7 +198,7 @@ fn knots(values: &[f64], count: usize, budget: &mut Budget) -> Result<()> {budget.add(values.len())?;numbers(values.iter().copied())?;let degree = values.len().checked_sub(count.saturating_add(1)).ok_or(Invalid("spline degree"))?;- require((2..=4096).contains(&count) && (1..=16).contains(°ree) && degree < count, "spline degree or size")?;+ require((2..=MAX_SPLINE_CONTROLS).contains(&count) && (1..=16).contains(°ree) && degree < count, "spline degree or size")?;require(values.windows(2).all(|w| w.first() <= w.get(1)), "unordered knots")?;require(values.get(degree) < values.get(count), "empty spline domain")?;// No knot may have multiplicity greater than degree + 1.@@ -482,6 +485,15 @@ mod tests {assert!(surface(&p, 0, &mut Budget(0)).is_err());assert!(curve(&Curve::Line { start: [0.; 3], end: [1.; 3] }, MAX_DEPTH + 1, &mut Budget(0)).is_err());assert!(Budget(MAX_ITEMS).add(1).is_err());+ // Control points along one direction: up to the cap, not one more (a clamped cubic).+ let clamped = |count: usize| {+ let mut k = vec![0.0; 4];+ k.extend((1..count - 3).map(|i| i as f64));+ k.extend([(count - 3) as f64; 4]);+ k+ };+ assert!(knots(&clamped(MAX_SPLINE_CONTROLS), MAX_SPLINE_CONTROLS, &mut Budget(0)).is_ok());+ assert!(knots(&clamped(MAX_SPLINE_CONTROLS + 1), MAX_SPLINE_CONTROLS + 1, &mut Budget(0)).is_err());}#[test]diff --git a/crates/geom/src/tess.rs b/crates/geom/src/tess.rsindex 3bb3e47ac2..036b32079f 100644--- a/crates/geom/src/tess.rs+++ b/crates/geom/src/tess.rs@@ -36,7 +36,10 @@ pub enum EvalSurface {/// `origin + u·du + v·dv`.Plane { origin: Vec3, du: Vec3, dv: Vec3 },/// A rational tensor B-spline; control point `(i, j)` is `ctrl[j·count[0] + i]`.- Nurbs { degree: [usize; 2], knots: [Vec<f64>; 2], count: [usize; 2], ctrl: Vec<[f64; 4]> },+ /// `closed[d]`: the surface joins itself along direction `d` (a B-spline tube's way round).+ /// Such a direction is periodic: a parameter outside the knot range is moved by whole+ /// ranges back into it, so a face whose boundary runs across the join still evaluates.+ Nurbs { degree: [usize; 2], knots: [Vec<f64>; 2], count: [usize; 2], ctrl: Vec<[f64; 4]>, closed: [bool; 2] },/// `profile(u)` turned by the angle `v` (right-handed) about the axis through `origin`/// along the unit `axis`, then mapped by the affine `transform` (row-major 3×4); with/// `swap` the parameters are exchanged first (the surface is evaluated at `(v, u)`).@@ -128,7 +131,7 @@ impl TessPlan {.iter().map(|s| match s {EvalSurface::Plane { origin, du, dv } => EvalSurface::Plane { origin: point(*origin), du: vector(*du), dv: vector(*dv) },- EvalSurface::Nurbs { degree, knots, count, ctrl } => EvalSurface::Nurbs {+ EvalSurface::Nurbs { degree, knots, count, ctrl, closed } => EvalSurface::Nurbs {degree: *degree,knots: knots.clone(),count: *count,@@ -140,6 +143,9 @@ impl TessPlan {[q.x, q.y, q.z, c[3]]}).collect(),+ // Which directions the surface joins itself along is a property of its+ // parameters: moving the surface does not change it.+ closed: *closed,},EvalSurface::Revolved { profile, origin, axis, transform, swap } => {// `m` (as rows) after the surface's own affine map.@@ -235,7 +241,20 @@ impl EvalSurface {}match self {EvalSurface::Plane { origin, du, dv } => Some((*origin + *du * u + *dv * v, *du, *dv)),- EvalSurface::Nurbs { degree, knots, count, ctrl } => nurbs_derivs(*degree, knots, *count, ctrl, u, v),+ EvalSurface::Nurbs { degree, knots, count, ctrl, closed } => {+ // The knot range of direction `d`: the parameters the surface is defined over.+ let range = |d: usize| -> Option<(f64, f64)> {+ let k = knots.get(d)?;+ Some((*k.get(*degree.get(d)?)?, *k.get(*count.get(d)?)?))+ };+ // A direction the surface joins itself along repeats, so a parameter outside the+ // range is moved by whole ranges back into it. Any other direction is left alone.+ let wrap = |d: usize, t: f64| match range(d) {+ Some((a, b)) if closed.get(d).copied().unwrap_or(false) && b > a && !(a..=b).contains(&t) => a + (t - a).rem_euclid(b - a),+ _ => t,+ };+ nurbs_derivs(*degree, knots, *count, ctrl, wrap(0, u), wrap(1, v))+ }EvalSurface::Revolved { profile, origin, axis, transform, swap } => {let (s, a) = if *swap { (v, u) } else { (u, v) };let (c, dc) = profile.eval(s)?;@@ -390,6 +409,7 @@ mod tests {knots: [vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]],count: [3, 2],ctrl: vec![[1.0, 0.0, 0.0, 1.0], [w, w, 0.0, w], [0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 2.0, 1.0], [w, w, 2.0 * w, w], [0.0, 1.0, 2.0, 1.0]],+ closed: [false, false],};let revolved = EvalSurface::Revolved {profile: line(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 0.0, 1.0)),@@ -511,7 +531,13 @@ mod tests {fn bilinear_nurbs_patch_and_derivatives() {// Degree (1, 1) over [0, 2] × [0, 1] with corners lifted: a hyperbolic paraboloid.let ctrl = vec![[0.0, 0.0, 0.0, 1.0], [2.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [2.0, 1.0, 1.0, 1.0]];- let s = EvalSurface::Nurbs { degree: [1, 1], knots: [vec![0.0, 0.0, 2.0, 2.0], vec![0.0, 0.0, 1.0, 1.0]], count: [2, 2], ctrl };+ let s = EvalSurface::Nurbs {+ degree: [1, 1],+ knots: [vec![0.0, 0.0, 2.0, 2.0], vec![0.0, 0.0, 1.0, 1.0]],+ count: [2, 2],+ ctrl,+ closed: [false, false],+ };let Some((p, du, dv)) = s.derivs(1.0, 0.5) else { panic!("evaluates") };assert!(close(p, Vec3::new(1.0, 0.5, 0.25), 1e-12), "{p:?}");assert!(close(du, Vec3::new(1.0, 0.0, 0.25), 1e-12), "{du:?}");@@ -533,7 +559,7 @@ mod tests {}let Ok(reference) = crate::bspline::NurbsSurface::new([3, 2], knots.clone(), &pts, &wts) else { panic!("valid surface") };let ctrl = reference.homogeneous().iter().map(|h| [h.x, h.y, h.z, h.w]).collect();- let s = EvalSurface::Nurbs { degree: [3, 2], knots, count: [nu, nv], ctrl };+ let s = EvalSurface::Nurbs { degree: [3, 2], knots, count: [nu, nv], ctrl, closed: [false, false] };for i in 0..=8 {for j in 0..=8 {let (u, v) = (i as f64 / 8.0, j as f64 / 4.0);@@ -557,12 +583,13 @@ mod tests {#[test]fn hostile_surfaces_do_not_panic() {let bad = [- EvalSurface::Nurbs { degree: [9, 1], knots: [vec![0.0; 3], vec![0.0; 3]], count: [1, 1], ctrl: vec![] },+ EvalSurface::Nurbs { degree: [9, 1], knots: [vec![0.0; 3], vec![0.0; 3]], count: [1, 1], ctrl: vec![], closed: [false, false] },EvalSurface::Nurbs {degree: [1, 1],knots: [vec![0.0, 0.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]],count: [2, 2],ctrl: vec![[0.0; 4]; 4],+ closed: [false, false],},EvalSurface::Revolved {profile: EvalCurve { degree: 0, knots: vec![], ctrl: vec![] },diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rsindex 6be54f701f..2883ac989c 100644--- a/crates/gpu/src/lib.rs+++ b/crates/gpu/src/lib.rs@@ -466,8 +466,9 @@ fn pack(plans: &[&TessPlan]) -> Result<Packed> {push3(&mut data, *du);push3(&mut data, *dv);}- EvalSurface::Nurbs { degree, knots, count, ctrl } => {+ EvalSurface::Nurbs { degree, knots, count, ctrl, closed } => {head[0] = 1;+ head[11] = u32::from(closed[0]) | (u32::from(closed[1]) << 1);head[1] = word(degree[0])?;head[2] = word(degree[1])?;head[3] = word(count[0])?;diff --git a/crates/gpu/src/tess.wgsl b/crates/gpu/src/tess.wgslindex 1bb3051d62..3e350a6b1b 100644--- a/crates/gpu/src/tess.wgsl+++ b/crates/gpu/src/tess.wgsl@@ -27,7 +27,8 @@ struct Surface {// Revolved: parameters exchanged; mirror transform (normal reversed).swap: u32,mirror: u32,- _pad: u32,+ // NURBS: bit 0 the surface joins itself along u, bit 1 along v (the direction is periodic).+ closed: u32,};struct Vertex {@@ -159,8 +160,20 @@ fn rational_der(a: vec4<f32>, da: vec4<f32>) -> vec3<f32> {return (da.xyz - rational_point(a) * da.w) / a.w;}-fn nurbs(s: Surface, u: f32, v: f32) -> Derivs {+// A parameter outside the knot range of a direction the surface joins itself along, moved by+// whole ranges back into it (the CPU evaluator's `EvalSurface::derivs` does the same).+fn wrap_closed(knots: u32, p: u32, n: u32, t: f32, closed: bool) -> f32 {+ if (!closed) { return t; }+ let a = data[knots + p];+ let b = data[knots + n];+ if (!(b > a) || (t >= a && t <= b)) { return t; }+ return a + (t - a) - floor((t - a) / (b - a)) * (b - a);+}++fn nurbs(s: Surface, u_in: f32, v_in: f32) -> Derivs {var r: Derivs;+ let u = wrap_closed(s.knots_u, s.pu, s.nu, u_in, (s.closed & 1u) != 0u);+ let v = wrap_closed(s.knots_v, s.pv, s.nv, v_in, (s.closed & 2u) != 0u);let su = span_of(s.knots_u, s.pu, s.nu, u);let sv = span_of(s.knots_v, s.pv, s.nv, v);let bu0 = basis_funs(s.knots_u, su, s.pu, u);diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rsindex e5de0d6983..07048a28f9 100644--- a/crates/kernel/src/body.rs+++ b/crates/kernel/src/body.rs@@ -23,6 +23,16 @@ pub struct Body {/// Bounding-box diagonal, measured by [`Body::new`] while it read the vertices anyway; 0/// means "not measured, walk the geometry". Every kernel tolerance is a fraction of it.pub(crate) size: f64,+ /// How far this body's face boundaries may lie off their surfaces (mm) and still be taken as+ /// lying on them. `Some` for a body read from a file that declares its own numeric+ /// uncertainty (a STEP file's `GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT`, see+ /// `crate::step_in::Units::tol`); `None` for a body this kernel built, which has no such+ /// declaration.+ ///+ /// A band face's ring edges are held to it when the importer splits the band (see+ /// `crate::step_in::split`). The display planner takes it only where it is more than its own+ /// bound, a hundredth of the body (see `accept` in [`crate::tess::plan_face`]).+ pub(crate) boundary_tol: Option<f64>,/// The last volume measured for this solid and the tolerance it was measured at, shared by/// clones because they share the solid. A boolean measures its operands, and a later boolean/// takes the result as an operand again, so the same body is measured twice otherwise.@@ -636,6 +646,7 @@ impl Body {Ok(Body {solid: std::sync::Arc::new(solid),size: if span.is_finite() && span > 0.0 { span } else { 0.0 },+ boundary_tol: None,volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),coarse_missing: Some((tol, missing)),mesh: None,@@ -677,6 +688,7 @@ impl Body {Ok(Body {solid: std::sync::Arc::new(solid),size: if span.is_finite() && span > 0.0 { span } else { 0.0 },+ boundary_tol: None,volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),coarse_missing: coarse,mesh: None,@@ -706,7 +718,12 @@ impl Body {return Err(KernelError::Invalid("degenerate placement".into()));}let rigid = crate::ops::rigid_placement(&a);- Body::placed_as_is(mt::builder::transformed(&*self.solid, *m), det < 0.0, rigid.then_some(self.coarse_missing).flatten())+ let out = Body::placed_as_is(mt::builder::transformed(&*self.solid, *m), det < 0.0, rigid.then_some(self.coarse_missing).flatten())?;+ // A placement that does not change distances leaves the boundaries exactly as far off+ // their surfaces as they were, so the file's own figure still describes them (see+ // [`Body::boundary_tol`]); one that scales the part does not, and the copy declares+ // nothing. The same rule as the mesh count above.+ Ok(if rigid { out.with_boundary_tol(self.boundary_tol) } else { out })}pub(crate) fn inherit_regularization_protection(mut self, input: &Body) -> Self {@@ -992,6 +1009,14 @@ impl Body {self.color}+ /// The same body, with how far its boundaries may lie off their surfaces (mm) as the file it+ /// was read from declares (see [`Body::boundary_tol`]). A value that is not finite and above+ /// zero clears the declaration, which puts the body back on the kernel's own bound.+ pub(crate) fn with_boundary_tol(mut self, tol: Option<f64>) -> Body {+ self.boundary_tol = tol.filter(|t| t.is_finite() && *t > 0.0);+ self+ }+/// The same body with a display colour.pub fn with_color(mut self, c: Option<[f32; 3]>) -> Body {self.color = c.filter(|c| c.iter().all(|x| x.is_finite())).map(|c| c.map(|x| x.clamp(0.0, 1.0)));@@ -1241,15 +1266,19 @@ impl Body {if let Some(m) = &self.mesh {return Ok(m.to_mesh());}- // A face trimmed by a helix (a modelled thread from another CAD system) turns more than- // once around its cylinder; truck meshes it with triangles across the solid (#1289).- // Such a body is meshed from its display plan, which cuts the face along a seam.- if guard("tessellate", || Ok(crate::tess::seam::turns_more_than_once(&self.solid))).unwrap_or(false) {+ // Two kinds of face truck cannot mesh in its surface's parameters: one trimmed by a+ // helix, which turns more than once around its cylinder and comes out with triangles+ // across the solid (#1289), and one that runs across the join of a B-spline surface that+ // closes on itself, which comes out folded over itself or with a hole in it.+ // Such a body is meshed from its display plan, which cuts and unwraps those faces.+ let planned =+ guard("tessellate", || Ok(crate::tess::seam::turns_more_than_once(&self.solid) || crate::tess::seam::closes_on_itself(&self.solid)));+ if planned.unwrap_or(false) {let turn = (angle.is_finite() && angle > 0.0).then(|| crate::tess::size::Turn { angle: angle.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR });- match guard("tessellate", || crate::tess::plan(&self.solid, tol, turn)) {+ match guard("tessellate", || crate::tess::plan(&self.solid, tol, turn, self.boundary_tol)) {Ok((plan, _)) => return Ok(plan.evaluate()),- Err(e) => log::debug!("helical faces: no display plan ({e}); meshing the reference way"),+ Err(e) => log::debug!("no display plan ({e}); meshing the reference way"),}}let deflection = if angle.is_finite() && angle > 0.0 {@@ -1358,7 +1387,7 @@ impl Body {// The same angle and floor as the reference mesher's angular display mesh.let turn =angle.filter(|a| a.is_finite()).map(|a| crate::tess::size::Turn { angle: a.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR });- guard("tessellate", || crate::tess::plan(&self.solid, tol, turn).map(|(plan, _)| plan))+ guard("tessellate", || crate::tess::plan(&self.solid, tol, turn, self.boundary_tol).map(|(plan, _)| plan))}/// Planar faces whose boundary crosses itself: two of its loops crossing each other, or a@@ -1443,25 +1472,49 @@ impl Body {Ok(crossed)}- /// Faces with no triangles in a coarse tessellation (the mesher failed or gave up).+ /// Faces with no triangles of their own, and so not shown: none in a coarse tessellation,+ /// and none in the display plan either (the plan is what the viewport draws, and it meshes+ /// faces the reference mesher gives up on). Only faces the coarse tessellation misses are+ /// looked for in the plan, so a sound body costs no planning.pub fn unmeshed_faces(&self) -> usize {if self.is_mesh() {return 0;}let tol = orientation_tolerance(self.size());- if let Some((cached_tol, missing)) = self.coarse_missing- && cached_tol == tol- {- return missing;+ // The count [`Body::new`] already took at this tolerance, else the same count made now.+ let missing = match self.coarse_missing {+ Some((cached_tol, missing)) if cached_tol == tol => missing,+ _ => {+ let Ok(m) = self.tessellate(tol) else { return self.face_count() };+ let mut has = vec![false; self.face_count()];+ for f in &m.tri_face {+ if let Some(h) = has.get_mut(*f as usize) {+ *h = true;+ }+ }+ has.iter().filter(|h| !**h).count()+ }+ };+ // A body the coarse mesh covers whole is shown whole: no plan is made for it, whether the+ // count came from the cache or from the mesh above.+ if missing == 0 {+ return 0;}- let Ok(m) = self.tessellate(tol) else { return self.face_count() };+ self.unmeshed_in_plan(tol).unwrap_or(missing)+ }++ /// Faces the display plan leaves without triangles; `None` when the body has no plan.+ fn unmeshed_in_plan(&self, tol: f64) -> Option<usize> {+ let plan = self.display_plan(tol).ok()?;let mut has = vec![false; self.face_count()];- for f in &m.tri_face {- if let Some(h) = has.get_mut(*f as usize) {+ for f in &plan.faces {+ if !f.triangles.is_empty()+ && let Some(h) = has.get_mut(f.face as usize)+ {*h = true;}}- has.iter().filter(|h| !**h).count()+ Some(has.iter().filter(|h| !**h).count())}/// Display mesh: like [`Body::tessellate`], with seam edges flagged. Meshed from thediff --git a/crates/kernel/src/display_mesh_tests.rs b/crates/kernel/src/display_mesh_tests.rsindex c1cf7d45a7..d94945e20a 100644--- a/crates/kernel/src/display_mesh_tests.rs+++ b/crates/kernel/src/display_mesh_tests.rs@@ -228,8 +228,10 @@ fn a_small_hole_on_a_large_plate_has_a_round_rim() {let segments = (TAU / DISPLAY_ANGLE).ceil() as usize;assert_eq!(segments, 18);for z in [0.0, 2.0] {- // The chord tolerance alone: each half circle is one segment, the rim a line.- assert_eq!(rim(&coarse, centre, 2.0, z).0, 2);+ // The chord tolerance alone leaves each half circle one segment, the rim a line no face+ // can be bounded by: its edges are divided again, and the rim stays a coarse polygon.+ let (n, _) = rim(&coarse, centre, 2.0, z);+ assert!((3..segments).contains(&n), "{n} segments around the rim at the chord tolerance");let (n, widest) = rim(&round, centre, 2.0, z);assert!(n >= segments, "{n} segments around the rim at z = {z}");assert!(widest <= DISPLAY_ANGLE * 1.001, "a segment spans {} degrees", widest.to_degrees());@@ -291,9 +293,12 @@ fn a_face_crowded_with_holes_gets_a_coarser_angle_and_bounded_work() {let boundary = |m: &Mesh, z: f64| m.edges.iter().filter(|e| e.iter().all(|p| (p.z - z).abs() < 1e-6)).map(|e| e.len() - 1).sum::<usize>();let budget = truck_meshalgo::tessellation::Deflection::MAX_ANGLE_BOUNDARY;for z in [0.0, 2.0] {- assert_eq!(boundary(&coarse, z), 4 + 2 * centres.len());+ // At the chord tolerance alone each rim is divided only as far as a face can be bounded+ // by it (two segments, a line, are divided again).+ assert!(boundary(&coarse, z) < 6 * centres.len(), "{}", boundary(&coarse, z));let n = boundary(&round, z);- assert!(n > boundary(&coarse, z), "the rims are still rounder than the chord tolerance leaves them: {n}");+ let (rounder, chord) = (rim(&round, centres[0], 2.0, z).0, rim(&coarse, centres[0], 2.0, z).0);+ assert!(rounder >= chord, "the rims are at least as round as the chord tolerance leaves them: {rounder} < {chord}");assert!(n <= budget, "{n} segments bound the face at z = {z}");}// Every rim got the same share, and the walls follow their rims.diff --git a/crates/kernel/src/meshbody.rs b/crates/kernel/src/meshbody.rsindex 07436cf3e5..2633313af0 100644--- a/crates/kernel/src/meshbody.rs+++ b/crates/kernel/src/meshbody.rs@@ -104,6 +104,7 @@ pub fn mesh_body(positions: &[Vec3], triangles: &[[u32; 3]]) -> Result<Body> {Ok(Body {solid: Arc::new(crate::body::Solid::new_unchecked(Vec::new())),size: 0.0,+ boundary_tol: None,volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),coarse_missing: None,mesh: Some(Arc::new(out)),@@ -203,6 +204,7 @@ impl Body {Some(Body {solid: self.solid.clone(),size: 0.0,+ boundary_tol: None,volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),coarse_missing: None,mesh: Some(Arc::new(out)),diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rsindex 97a3bc60fe..fe05f55da3 100644--- a/crates/kernel/src/native.rs+++ b/crates/kernel/src/native.rs@@ -37,6 +37,10 @@ struct Runtime {size: f64,/// The orientation mesh's missing-face count at its tolerance.coarse_missing: Option<(f64, u64)>,+ /// [`Body::boundary_tol`]: the accuracy the file it was read from declares. Written only+ /// when there is one, so a body without it is stored as before.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ boundary_tol: Option<f64>,}fn invalid(detail: impl std::fmt::Display) -> KernelError {KernelError::Invalid(format!("native B-rep: {detail}"))@@ -66,7 +70,8 @@ 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 runtime = Runtime { size: body.size, coarse_missing: body.coarse_missing.map(|(tol, n)| (tol, n as u64)) };+ let runtime =+ Runtime { size: body.size, coarse_missing: body.coarse_missing.map(|(tol, n)| (tol, n as u64)), boundary_tol: body.boundary_tol };let saved = SavedBody { solid: adapter::encode(&body.solid)?, metadata: metadata::encode(body)?, runtime };// Structural validation does not invoke another geometric reconstruction.validate_topology(&saved)?;@@ -98,13 +103,17 @@ 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) {+ let Runtime { size, coarse_missing, boundary_tol } = saved.runtime;+ if !(size.is_finite() && size >= 0.0)+ || coarse_missing.is_some_and(|(tol, n)| !tol.is_finite() || n > MAX_ITEMS as u64)+ || boundary_tol.is_some_and(|t| !(t.is_finite() && t > 0.0))+ {return Err(invalid("runtime values"));}let mut body = Body {solid: Arc::new(solid),size,+ boundary_tol,volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),coarse_missing: coarse_missing.map(|(tol, n)| (tol, n as usize)),mesh: None,@@ -228,6 +237,18 @@ mod tests {assert!((crate::measure(&a).unwrap().volume - crate::measure(&b).unwrap().volume).abs() < 1e-7);}}+ /// A body read from a file keeps the accuracy the file declares through the model cache, so+ /// a reopened design plans its faces as the import did; one without it is stored as before.+ #[test]+ fn a_files_declared_accuracy_survives_the_model_cache() {+ let cube = crate::box_solid(Vec3::ZERO, Vec3::new(4., 3., 1.)).unwrap();+ let plain = encode_native_body(&cube).unwrap();+ assert_eq!(decode_native_body(&plain).unwrap().boundary_tol, None);+ let read = cube.with_boundary_tol(Some(1e-5));+ let bytes = encode_native_body(&read).unwrap();+ assert_ne!(bytes, plain);+ assert_eq!(decode_native_body(&bytes).unwrap().boundary_tol, Some(1e-5));+ }#[test]fn native_spheres_tori_and_open_faces_round_trip_without_conversion() {let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap();diff --git a/crates/kernel/src/outline.rs b/crates/kernel/src/outline.rsindex e65d9331f6..456e88c10b 100644--- a/crates/kernel/src/outline.rs+++ b/crates/kernel/src/outline.rs@@ -503,6 +503,7 @@ fn divided(body: &Body, faces: &[usize], other: &[(mt::Edge, Piece)], fr: &Framelet split = Body {solid: std::sync::Arc::new(solid),size: 0.0,+ boundary_tol: body.boundary_tol,volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),coarse_missing: None,mesh: None,diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rsindex 6575c2c5b0..b6551a5346 100644--- a/crates/kernel/src/splitface.rs+++ b/crates/kernel/src/splitface.rs@@ -636,6 +636,7 @@ pub(crate) fn split_edges_at(body: &Body, points: &[Vec3]) -> Result<Body> {let split = Body {solid: std::sync::Arc::new(solid),size: 0.0,+ boundary_tol: body.boundary_tol,volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),coarse_missing: None,mesh: None,@@ -1173,6 +1174,7 @@ pub(crate) fn split_any(body: &Body, faces: &[usize], tool: &SplitTool) -> Resullet split = Body {solid: std::sync::Arc::new(solid),size: 0.0,+ boundary_tol: body.boundary_tol,volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),coarse_missing: None,mesh: None,diff --git a/crates/kernel/src/step_in/brep.rs b/crates/kernel/src/step_in/brep.rsindex e10f909fe3..37591e5acf 100644--- a/crates/kernel/src/step_in/brep.rs+++ b/crates/kernel/src/step_in/brep.rs@@ -194,8 +194,9 @@ impl Builder {let sense = p.get(4).and_then(Param::as_bool).unwrap_or(true);let g = geom::curve(cx, rid(p.get(3), "edge geometry")?, 0)?;let closed = vs_id == ve_id;- let pieces = guard("step edge", || geom::edge_pieces(&g, vs.point(), ve.point(), sense, closed, cx.tol).map_err(crate::KernelError::Failed))- .map_err(|e| e.to_string())?;+ let pieces =+ guard("step edge", || geom::edge_pieces(&g, vs.point(), ve.point(), sense, closed, cx.tol, cx.snap).map_err(crate::KernelError::Failed))+ .map_err(|e| e.to_string())?;let n = pieces.len();let mut out = Vec::with_capacity(n);let mut cur = vs.clone();@@ -503,7 +504,7 @@ impl Builder {origin = vec![file_face; patches.len()];out = patches;}- let out = super::split::split_bands(out, &mut origin, failed);+ let out = super::split::split_bands(out, &mut origin, failed, cx.tol);Ok((out.into(), closed, read, origin))}}diff --git a/crates/kernel/src/step_in/conic_tests.rs b/crates/kernel/src/step_in/conic_tests.rsindex 5ed01d8cc8..1f25923e89 100644--- a/crates/kernel/src/step_in/conic_tests.rs+++ b/crates/kernel/src/step_in/conic_tests.rs@@ -35,7 +35,7 @@ fn extruded_ellipse_seam_uses_profile_angles_for_oblique_sweeps() {{TAIL}");let ex = p21::parse(&text).unwrap();- let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };let origin = mt::Point3::new(10.0, -20.0, 3.0);let d = mt::Vector3::new(0.5, 0.25, 1.0).normalize();let point = |angle: f64, h: f64| origin + mt::Vector3::new(9.0 * angle.cos(), 4.0 * angle.sin(), 0.0) + d * h;diff --git a/crates/kernel/src/step_in/geom.rs b/crates/kernel/src/step_in/geom.rsindex f6ccd817df..e5f27f3200 100644--- a/crates/kernel/src/step_in/geom.rs+++ b/crates/kernel/src/step_in/geom.rs@@ -176,7 +176,32 @@ fn knot_vec(mults: Option<&Param>, knots: Option<&Param>, expected: usize) -> R<if m.len() > expected || m.iter().try_fold(0usize, |a, v| a.checked_add(*v)) != Some(expected) {return Err("knot multiplicities do not match the control points".into());}- mt::KnotVec::from_single_multi(k, m).map_err(|e| format!("knot vector: {e}"))+ mt::KnotVec::from_single_multi(spanning_one(k), m).map_err(|e| format!("knot vector: {e}"))+}++/// Shortest parameter range a spline is read with.+const MIN_KNOT_RANGE: f64 = 1.0;++/// `knots` stretched, when they span less than [`MIN_KNOT_RANGE`], to span exactly that from the+/// same first knot. A STEP writer may parameterize a spline over any range (some write a few+/// millionths, as if in metres of a part drawn in millimetres), and the kernel tells parameters+/// apart only to a fixed tolerance (1e-6): over such a range it took distinct knots for one, and+/// trimming an edge to its vertices dropped a control point. Stretching the knots changes the+/// parameters, never the curve (every point is where it was), and nothing read from the file+/// refers to them: edges are trimmed by their vertices.+fn spanning_one(knots: Vec<f64>) -> Vec<f64> {+ let (Some(&first), Some(&last)) = (knots.first(), knots.last()) else { return knots };+ let range = last - first;+ if !(range > 0.0 && range < MIN_KNOT_RANGE) {+ return knots;+ }+ let scale = MIN_KNOT_RANGE / range;+ let mut out: Vec<f64> = knots.iter().map(|k| first + (k - first) * scale).collect();+ // The last knot exactly at the end of the range (the product can miss it by a rounding).+ if let Some(k) = out.last_mut() {+ *k = first + MIN_KNOT_RANGE;+ }+ out}fn generated_knots(kind: &str, n_ctrl: usize, degree: usize) -> R<mt::KnotVec> {@@ -539,15 +564,16 @@ fn sub_curve<C: Cut + BoundedCurve + Clone>(c: &C, a: f64, b: f64) -> C {out}-/// Pieces of a spline edge from `ps` to `pe` (two pieces for a closed edge).-fn spline_pieces<C>(c: &C, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64) -> R<Vec<C>>+/// Pieces of a spline edge from `ps` to `pe` (two pieces for a closed edge). The vertices may+/// be up to `snap` off the curve; `tol` decides whether the curve closes on itself.+fn spline_pieces<C>(c: &C, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64, snap: f64) -> R<Vec<C>>whereC: ParametricCurve<Point = mt::Point3> + BoundedCurve + SearchNearestParameter<mt::D1, Point = mt::Point3> + Cut + Clone + Invertible,{let (t0, t1) = c.range_tuple();let (ts, ds) = nearest_param(c, ps).ok_or("spline evaluation failed")?;let (te, de) = nearest_param(c, pe).ok_or("spline evaluation failed")?;- if ds > tol || de > tol {+ if !(ds <= snap && de <= snap) {return Err(format!("edge vertices are {:.3e} mm off their curve", ds.max(de)));}let span = t1 - t0;@@ -589,9 +615,51 @@ whereOk(pieces)}+/// Moves one end of a spline piece (`back`: its end, else its start) onto its vertex `p` by+/// the control point that end sits on, so the piece meets the vertex exactly and keeps its+/// shape away from that end. A piece whose end is not a control point (an unclamped spline) is+/// left as it is.+fn pin_end(c: &mut mt::Curve, p: mt::Point3, back: bool) {+ let end = if back { c.back() } else { c.front() };+ let d = p - end;+ if !(d.magnitude2() > 0.0) {+ return;+ }+ let at_end = |q: mt::Point3| q.distance(end) <= mt::TOLERANCE;+ match c {+ mt::Curve::BSplineCurve(b) => {+ let cp = if back { b.control_points_mut().last() } else { b.control_points_mut().next() };+ if let Some(q) = cp.filter(|q| at_end(**q)) {+ *q += d;+ }+ }+ mt::Curve::NurbsCurve(n) => {+ let cp = if back { n.control_points_mut().last() } else { n.control_points_mut().next() };+ if let Some(q) = cp.filter(|q| q.w != 0.0 && at_end(mt::Point3::from_homogeneous(**q))) {+ *q = (mt::Point3::from_homogeneous(*q) + d).to_homogeneous() * q.w;+ }+ }+ _ => {}+ }+}+/// Kernel curves for an edge from `ps` to `pe`: one piece, or two for a closed edge (so no-/// kernel edge starts and ends at the same vertex).-pub(crate) fn edge_pieces(g: &CurveGeo, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64) -> R<Vec<mt::Curve>> {+/// kernel edge starts and ends at the same vertex). A spline or open-conic edge's ends are+/// moved onto vertices up to `snap` off its curve, so the pieces meet the vertices exactly.+pub(crate) fn edge_pieces(g: &CurveGeo, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64, snap: f64) -> R<Vec<mt::Curve>> {+ let mut pieces = curve_pieces(g, ps, pe, sense, closed, tol, snap)?;+ if matches!(g, CurveGeo::BSpline(_) | CurveGeo::Nurbs(_) | CurveGeo::Hyperbola { .. } | CurveGeo::Parabola { .. }) {+ if let Some(c) = pieces.first_mut() {+ pin_end(c, ps, false);+ }+ if let Some(c) = pieces.last_mut() {+ pin_end(c, pe, true);+ }+ }+ Ok(pieces)+}++fn curve_pieces(g: &CurveGeo, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64, snap: f64) -> R<Vec<mt::Curve>> {match g {CurveGeo::Line { .. } => {if closed {@@ -628,15 +696,15 @@ pub(crate) fn edge_pieces(g: &CurveGeo, ps: mt::Point3, pe: mt::Point3, sense: b}// The curve is open, so the edge is the parameters between its vertices: rising// for the same sense, falling for the opposite one.- let (ts, te) = (open_conic_param(g, ps, tol)?, open_conic_param(g, pe, tol)?);+ let (ts, te) = (open_conic_param(g, ps, snap)?, open_conic_param(g, pe, snap)?);let scale = 1.0 + ts.abs().max(te.abs());if (te - ts).abs() <= 1e-9 * scale {return Err("degenerate conic edge".into());}Ok(vec![open_conic_curve(g, ts, te)?])}- CurveGeo::BSpline(c) => Ok(spline_pieces(c, ps, pe, sense, closed, tol)?.into_iter().map(mt::Curve::BSplineCurve).collect()),- CurveGeo::Nurbs(c) => Ok(spline_pieces(c, ps, pe, sense, closed, tol)?.into_iter().map(mt::Curve::NurbsCurve).collect()),+ CurveGeo::BSpline(c) => Ok(spline_pieces(c, ps, pe, sense, closed, tol, snap)?.into_iter().map(mt::Curve::BSplineCurve).collect()),+ CurveGeo::Nurbs(c) => Ok(spline_pieces(c, ps, pe, sense, closed, tol, snap)?.into_iter().map(mt::Curve::NurbsCurve).collect()),}}diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rsindex a4971d3749..b2bad9b422 100644--- a/crates/kernel/src/step_in/mod.rs+++ b/crates/kernel/src/step_in/mod.rs@@ -114,6 +114,9 @@ pub(crate) struct Ctx<'a> {pub ang: f64,/// Vertex-on-curve tolerance (mm).pub tol: f64,+ /// Farthest an edge's vertex may sit off its curve and still be moved onto it (mm, at least+ /// `tol`): see [`snap_limit`].+ pub snap: f64,}#[derive(Clone, Copy)]@@ -121,9 +124,29 @@ struct Units {len: f64,ang: f64,tol: f64,+ snap: f64,}-const DEFAULT_UNITS: Units = Units { len: 1.0, ang: 1.0, tol: 0.01 };+const DEFAULT_UNITS: Units = Units { len: 1.0, ang: 1.0, tol: 0.01, snap: 0.01 };++/// Largest tolerance a file can ask for (mm), however coarse the accuracy it declares.+const MAX_TOL: f64 = 1.0;++/// Gap between an edge's vertex and its curve that is still read as the same point, as a share+/// of the model's size: the chord error the kernel's own coarse meshes allow at that size+/// (`Body::size() * 1e-3`), so moving the vertex onto the curve changes the shape by less than+/// those meshes already do.+const SNAP_SHARE: f64 = 1e-3;++/// Farthest a vertex may sit off its edge's curve and be moved onto it (mm): the file's own+/// tolerance `tol`, or up to [`SNAP_SHARE`] of the model's size `extent` (mm) when that is+/// larger. Some exporters write vertices further off than the accuracy they declare (a surface+/// export may declare 0.01 mm and join two curves 0.38 mm apart at a vertex between them).+/// Never more than [`MAX_TOL`], so a far stray point cannot turn the check off.+fn snap_limit(tol: f64, extent: f64) -> f64 {+ let share = if extent.is_finite() { extent * SNAP_SHARE } else { 0.0 };+ tol.max(share.min(MAX_TOL))+}fn si_prefix(p: Option<&Param>) -> f64 {match p.and_then(Param::as_enum) {@@ -208,7 +231,8 @@ fn context_units(ex: &Exchange, ctx: Option<u64>, cache: &mut HashMap<u64, Units}}}- u.tol = tol_file.filter(|t| t.is_finite() && *t > 0.0).map(|t| (t * 10.0).max(1e-3)).unwrap_or(u.len * 1e-2).clamp(1e-4, 1.0);+ u.tol = tol_file.filter(|t| t.is_finite() && *t > 0.0).map(|t| (t * 10.0).max(1e-3)).unwrap_or(u.len * 1e-2).clamp(1e-4, MAX_TOL);+ u.snap = snap_limit(u.tol, ex.vertex_extent() * u.len);cache.insert(id, u);u}@@ -560,7 +584,7 @@ impl Reader {}fn placement_matrix(&mut self, item: u64, u: Units) -> R<mt::Matrix4> {- let cx = Ctx { ex: &self.ex, len: u.len, ang: u.ang, tol: u.tol };+ let cx = Ctx { ex: &self.ex, len: u.len, ang: u.ang, tol: u.tol, snap: u.snap };let e = geom::entity(&cx, item)?;if matches!(e.name(), "CARTESIAN_TRANSFORMATION_OPERATOR_3D" | "CARTESIAN_TRANSFORMATION_OPERATOR_3D_NON_UNIFORM") {let p = e.params();@@ -761,7 +785,7 @@ impl Reader {};let placement = self.batches.get(p.batch).map_or(mt::Matrix4::from_scale(1.0), |b| b.m);sources.push((i, item));- jobs.push(parallel::Job { source, placement, check_mesh: !self.unmeshed_checked.contains(&item) });+ jobs.push(parallel::Job { source, placement, check_mesh: !self.unmeshed_checked.contains(&item), tol: units.tol });}// Reading and orienting new parts is shared out between the workers.let prepared = parallel::bodies(&ex, &jobs, self.workers);diff --git a/crates/kernel/src/step_in/p21.rs b/crates/kernel/src/step_in/p21.rsindex 29e6595ca7..855aa92eb8 100644--- a/crates/kernel/src/step_in/p21.rs+++ b/crates/kernel/src/step_in/p21.rs@@ -125,12 +125,36 @@ pub struct Exchange {pub entities: HashMap<u64, Entity>,/// Ids defined more than once (the first definition is kept).pub duplicates: Vec<u64>,+ /// [`Exchange::vertex_extent`], worked out on first use.+ extent: std::sync::OnceLock<f64>,}impl Exchange {pub fn get(&self, id: u64) -> Option<&Entity> {self.entities.get(&id)}++ /// The size of the model in the file's own coordinates: the diagonal of the box around every+ /// VERTEX_POINT (0 for a file without one). Non-finite coordinates are skipped.+ pub fn vertex_extent(&self) -> f64 {+ *self.extent.get_or_init(|| {+ let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);+ for e in self.entities.values().filter(|e| e.name() == "VERTEX_POINT") {+ let Some(p) = e.params().get(1).and_then(Param::as_ref_id).and_then(|id| self.get(id)) else { continue };+ let Some(xyz) = p.params().get(1).and_then(Param::as_list) else { continue };+ let c: Vec<f64> = xyz.iter().take(3).filter_map(Param::as_f64).collect();+ if c.len() != 3 || !c.iter().all(|x| x.is_finite()) {+ continue;+ }+ for ((l, h), x) in lo.iter_mut().zip(hi.iter_mut()).zip(c) {+ *l = l.min(x);+ *h = h.max(x);+ }+ }+ let d = lo.iter().zip(&hi).map(|(l, h)| (h - l).powi(2)).sum::<f64>().sqrt();+ if d.is_finite() { d } else { 0.0 }+ })+ }}struct Lexer<'a> {diff --git a/crates/kernel/src/step_in/parallel.rs b/crates/kernel/src/step_in/parallel.rsindex c8327ac98e..42ec63f39d 100644--- a/crates/kernel/src/step_in/parallel.rs+++ b/crates/kernel/src/step_in/parallel.rs@@ -8,6 +8,11 @@ pub(super) struct Job {/// Where the body goes (its instance's placement in the assembly).pub placement: mt::Matrix4,pub check_mesh: bool,+ /// The file's point-on-surface tolerance (`super::Units::tol`) for the representation this+ /// solid was read from: how far its boundaries may lie off their surfaces (mm). The body+ /// keeps it, so the tessellator holds an imported boundary to the file's own uncertainty+ /// rather than to a fraction of the part's size (see `crate::body::Body::boundary_tol`).+ pub tol: f64,}/// What a job places: a solid item to read from the file (and orient), or a part an earlier@@ -62,19 +67,23 @@ fn prepare(ex: &Exchange, job: &Job) -> Prepared {let (part, read) = match &job.source {Source::Oriented(part) => (part.clone(), None),Source::Item { item, units } => {- let cx = Ctx { ex, len: units.len, ang: units.ang, tol: units.tol };+ let cx = Ctx { ex, len: units.len, ang: units.ang, tol: units.tol, snap: units.snap };let out = guard("step brep", || brep::read_item(&cx, *item).map_err(KernelError::Failed)).map_err(|e| Failure { read: true, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() })?;// Orient once where the file defines the solid; each placement then takes its// orientation from the matrix instead of meshing the whole part again.let body = guard("STEP body preparation", || Body::new(out.solid)).map_err(|e| Failure { read: false, msg: e.to_string() })?;+ // The file's tolerance is set on the part itself, before anything meshes it: the+ // unmeshed-face count below is the import's own warning and must judge the body by+ // the file's uncertainty too, and every placement of the part carries the figure on.+ let body = body.with_boundary_tol(Some(job.tol));(Arc::new(Part { body, closed: out.closed, file_faces: out.file_faces, face_origin: out.face_origin }), Some(out.failed))}};guard("STEP body preparation", || {let body = part.body.placed(&job.placement)?;// Counted where the orientation mesh already counted them (a placement meshes the- // same faces).+ // same faces), and on the part, which carries the file's tolerance.let missing = if job.check_mesh { part.body.unmeshed_faces() } else { 0 };Ok((body, missing))})diff --git a/crates/kernel/src/step_in/split.rs b/crates/kernel/src/step_in/split.rsindex 2a3cb22b5e..509c046c1c 100644--- a/crates/kernel/src/step_in/split.rs+++ b/crates/kernel/src/step_in/split.rs@@ -13,6 +13,10 @@ use truck_modeling as mt;use super::geom::{Frame, R, conic_arc};+/// How far a band's ring edge may lie off its surface, as a fraction of the body, for a body that+/// declares no accuracy of its own.+const RING_OFF_SURFACE: f64 = 1e-3;+/// Samples per edge when looking for the split crossing.const SAMPLES: usize = 48;@@ -34,6 +38,14 @@ fn coord(d: Dir, uv: (f64, f64)) -> f64 {}}+/// The direction the split line runs along (the one that does not wrap).+fn along(d: Dir) -> Dir {+ match d {+ Dir::U => Dir::V,+ Dir::V => Dir::U,+ }+}+/// The closed, non-periodic direction of a surface with its range; with `periodic`, a revolved/// surface's turn around its axis too.fn closed_dirs(s: &mt::Surface, periodic: bool) -> Vec<(Dir, f64, f64)> {@@ -140,8 +152,11 @@ fn crossing(s: &mt::Surface, d: Dir, chain: &[mt::Edge], mid: f64, period: f64)Err("no crossing with the split line".into())}-/// Iso-parameter edge curve `w = mid` from `q1` to `q2`.-fn iso_curve(s: &mt::Surface, d: Dir, mid: f64, q1: mt::Point3, q2: mt::Point3, seam: &[mt::Point3]) -> R<mt::Curve> {+/// Iso-parameter edge curve `w = mid` from `q1` to `q2`. `tol` is how far a ring edge may lie off+/// the surface the split line lies on: a STEP file writes the surface and the curves bounding it+/// to the file's own declared uncertainty only, so the line is matched to the surface points+/// below `q1` and `q2`, not to them.+fn iso_curve(s: &mt::Surface, d: Dir, mid: f64, q1: mt::Point3, q2: mt::Point3, seam: &[mt::Point3], tol: f64) -> R<mt::Curve> {match s {// Across the turn of a cylinder or cone: a straight line along it.mt::Surface::RevolutedCurve(_) if turn_dir(s).is_some_and(|t| t.0 == d) => {@@ -181,7 +196,7 @@ fn iso_curve(s: &mt::Surface, d: Dir, mid: f64, q1: mt::Point3, q2: mt::Point3,}let f = if sweep > 0.0 { f } else { Frame { o: c, x, y: -a.cross(x), z: -a } };let arc = conic_arc(&f, r, r, 0.0, sweep.abs());- if arc.back().distance(q2) > 1e-6 * (1.0 + r) {+ if arc.back().distance(q2) > (1e-6 * (1.0 + r)).max(tol) {return Err("split line does not reach the other ring".into());}Ok(mt::Curve::NurbsCurve(arc))@@ -196,20 +211,27 @@ fn iso_curve(s: &mt::Surface, d: Dir, mid: f64, q1: mt::Point3, q2: mt::Point3,_ => return Err("unsupported surface".into()),};let iso = mt::Curve::NurbsCurve(iso_bsp(&hom, mid, d == Dir::V)?);+ let (t0, t1) = iso.range_tuple();+ // Where the split line comes nearest `p`: the point on the surface below `p` (the+ // line runs on the surface, `p` only within the file's tolerance of it), looked for+ // from its own surface parameter and from a scan of the whole line.let near = |p: mt::Point3| {- let (t0, t1) = iso.range_tuple();+ let foot = uv_of(s, p).filter(|uv| s.subs(uv.0, uv.1).distance(p) <= tol);+ let target = foot.map_or(p, |uv| s.subs(uv.0, uv.1));let mut best = (t0, f64::INFINITY);for i in 0..=256 {let t = t0 + (t1 - t0) * i as f64 / 256.0;- let dd = iso.subs(t).distance(p);+ let dd = iso.subs(t).distance(target);if dd < best.1 {best = (t, dd);}}- if let Some(t) = iso.search_nearest_parameter(p, best.0, 64) {+ let seeds = foot.map(|uv| coord(along(d), uv)).into_iter().chain(iso.search_nearest_parameter(target, best.0, 64));+ for t in seeds {let t = t.clamp(t0, t1);- if iso.subs(t).distance(p) <= best.1 {- best = (t, iso.subs(t).distance(p));+ let dd = iso.subs(t).distance(target);+ if dd <= best.1 {+ best = (t, dd);}}best@@ -220,7 +242,6 @@ fn iso_curve(s: &mt::Surface, d: Dir, mid: f64, q1: mt::Point3, q2: mt::Point3,return Err("split line does not reach the rings".into());}let (lo, hi) = if ta < tb { (ta, tb) } else { (tb, ta) };- let (t0, t1) = iso.range_tuple();let mut c = iso;let eps = (t1 - t0) * 1e-9;if lo > t0 + eps {@@ -292,7 +313,10 @@ struct Plan {faces: (mt::Face, mt::Face),}-fn plan(face: &mt::Face, periodic: bool) -> R<Option<Plan>> {+/// How to cut `face` in two along the line opposite its seam. `periodic` also cuts a face that+/// runs round the turn of a revolved surface (see [`closed_dirs`]). `tol` is how far a ring edge+/// of the face may lie off the surface it bounds (see [`iso_curve`]).+fn plan(face: &mt::Face, periodic: bool, tol: f64) -> R<Option<Plan>> {let s = face.surface();let wires = face.absolute_boundaries().clone();let mut uses: HashMap<mt::EdgeID, usize> = HashMap::new();@@ -333,7 +357,7 @@ fn plan(face: &mt::Face, periodic: bool) -> R<Option<Plan>> {}// A cone's tip: the seam runs from the ring to the apex and straight back.if let [(true, sm), (false, ring)] = chains.as_slice() {- return apex_plan(face, &s, (d, mid, period), sm, ring, &wires, outer_idx).map(Some);+ return apex_plan(face, &s, (d, mid, period), sm, ring, &wires, outer_idx, tol).map(Some);}let [(true, s1), (false, r1), (true, s2), (false, r2)] = chains.as_slice() else {return Err(format!("unsupported seam loop layout ({} runs)", chains.len()));@@ -345,7 +369,7 @@ fn plan(face: &mt::Face, periodic: bool) -> R<Option<Plan>> {let (k1, t1, q1) = crossing(&s, d, r1, mid, period)?;let (k2, t2, q2) = crossing(&s, d, r2, mid, period)?;let seam_line: Vec<mt::Point3> = s1.iter().flat_map(|e| samples(&e.oriented_curve(), 16).into_iter().map(|x| x.1)).collect();- let iso = iso_curve(&s, d, mid, q1, q2, &seam_line)?;+ let iso = iso_curve(&s, d, mid, q1, q2, &seam_line, tol)?;let (r1a, r1b, c1, v1) = split_chain(r1, k1, t1, q1)?;let (r2a, r2b, c2, v2) = split_chain(r2, k2, t2, q2)?;let e_split = mt::Edge::new_unchecked(&v1, &v2, iso);@@ -404,6 +428,7 @@ fn apex_plan(ring: &[mt::Edge],wires: &[mt::Wire],outer_idx: usize,+ tol: f64,) -> R<Plan> {let h = sm.len() / 2;if !sm.len().is_multiple_of(2) || h == 0 {@@ -416,7 +441,7 @@ fn apex_plan(let apex = out.last().ok_or("seam")?.back().clone();let (k, t, q) = crossing(s, d, ring, mid, period)?;let seam_line: Vec<mt::Point3> = out.iter().flat_map(|e| samples(&e.oriented_curve(), 16).into_iter().map(|x| x.1)).collect();- let iso = iso_curve(s, d, mid, q, apex.point(), &seam_line)?;+ let iso = iso_curve(s, d, mid, q, apex.point(), &seam_line, tol)?;let (ra, rb, c, vq) = split_chain(ring, k, t, q)?;let e = mt::Edge::new_unchecked(&vq, &apex, iso);// Face A: out to the apex, down the split line, the ring's second part; face B the rest.@@ -500,6 +525,9 @@ pub(crate) fn split_seams(body: &crate::Body) -> Option<crate::Body> {if !body.solid.face_iter().any(seamed) {return None;}+ // How far a ring edge of such a face may lie off the surface it bounds (see `iso_curve`):+ // the file's own declared uncertainty for a body read from one, else a thousandth of the body.+ let tol = body.boundary_tol.unwrap_or(body.size() * RING_OFF_SURFACE).max(1e-6);let mut shells: Vec<mt::Shell> = Vec::new();for sh in body.solid.boundaries() {let mut faces: Vec<mt::Face> = sh.face_iter().cloned().collect();@@ -509,7 +537,7 @@ pub(crate) fn split_seams(body: &crate::Body) -> Option<crate::Body> {if !seamed(&face) {continue;}- let p = crate::guard("seam split", || plan(&face, true).map_err(crate::KernelError::Failed)).ok()??;+ let p = crate::guard("seam split", || plan(&face, true, tol).map_err(crate::KernelError::Failed)).ok()??;faces = faces.iter().map(|f| recut(f, &p.cuts)).collect();if let Some(slot) = faces.get_mut(i) {*slot = p.faces.0;@@ -525,11 +553,16 @@ pub(crate) fn split_seams(body: &crate::Body) -> Option<crate::Body> {/// Split every band face of a shell (see the module docs). Faces that cannot be split stay as/// they are and are reported.-pub(crate) fn split_bands(mut faces: Vec<mt::Face>, origin: &mut Vec<u64>, warnings: &mut Vec<String>) -> Vec<mt::Face> {+///+/// `tol` is the file's point-on-surface tolerance (`step_in::mod::Units::tol`): 10x the file's+/// declared uncertainty, floored at 1 µm and clamped to [1e-4, 1] mm. A ring edge is written to+/// within this distance of the surface it bounds, so it is how far `iso_curve` may accept a+/// crossing point as lying on the surface.+pub(crate) fn split_bands(mut faces: Vec<mt::Face>, origin: &mut Vec<u64>, warnings: &mut Vec<String>, tol: f64) -> Vec<mt::Face> {let n = faces.len();for i in 0..n {let Some(face) = faces.get(i).cloned() else { continue };- match crate::guard("step band split", || plan(&face, false).map_err(crate::KernelError::Failed)) {+ match crate::guard("step band split", || plan(&face, false, tol).map_err(crate::KernelError::Failed)) {Ok(Some(p)) => {faces = faces.iter().map(|f| recut(f, &p.cuts)).collect();if let Some(slot) = faces.get_mut(i) {diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rsindex 34aa60be78..89afd01bdd 100644--- a/crates/kernel/src/step_in/tests.rs+++ b/crates/kernel/src/step_in/tests.rs@@ -164,7 +164,7 @@ fn benchmark_independent_step_solids() {let start = std::time::Instant::now();let ex = p21::parse(&text).unwrap();let parse = start.elapsed();- let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 0.01 };+ let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 0.01, snap: 0.01 };let mut items: Vec<_> = ex.entities.iter().filter(|(_, e)| e.name() == "MANIFOLD_SOLID_BREP").map(|(id, _)| *id).collect();items.sort();let start = std::time::Instant::now();@@ -271,7 +271,7 @@ fn parallel_body_preparation_reports_errors_in_place_and_preserves_placement() {// The second item is not in the file.let jobs: Vec<_> = [solid, 999_999_999, solid, solid].into_iter()- .map(|item| parallel::Job { source: parallel::Source::Item { item, units }, placement, check_mesh: true })+ .map(|item| parallel::Job { source: parallel::Source::Item { item, units }, placement, check_mesh: true, tol: units.tol }).collect();let serial = parallel::bodies(&ex, &jobs, 1);let threaded = parallel::bodies(&ex, &jobs, 4);@@ -433,7 +433,7 @@ fn offset_geometry(definition: &str, offset: &str, len: f64, sense: bool, points"{HEAD}#1=CARTESIAN_POINT('',(0.,0.,0.));\n#2=AXIS2_PLACEMENT_3D('',#1,$,$);\n#3={definition};\n#4=OFFSET_SURFACE('',#3,{offset},.U.);\n{TAIL}");let ex = p21::parse(&text).unwrap();- let cx = Ctx { ex: &ex, len, ang: 1.0, tol: 1e-6 };+ let cx = Ctx { ex: &ex, len, ang: 1.0, tol: 1e-6, snap: 1e-6 };crate::guard("test offset surface", || geom::surface(&cx, 4, points, &[], sense, 0).map_err(KernelError::Failed))}@@ -483,13 +483,13 @@ fn offset_surfaces_nested_and_hostile() {}let text = format!("{HEAD}#1=OFFSET_SURFACE('',#1,1.,.F.);{TAIL}");let ex = p21::parse(&text).unwrap();- let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };assert!(geom::surface(&cx, 1, &points, &[], true, 0).unwrap_err().contains("nested too deeply"));let text = format!("{HEAD}#1=CARTESIAN_POINT('',(0.,0.,0.));#2=AXIS2_PLACEMENT_3D('',#1,$,$);#3=CYLINDRICAL_SURFACE('',#2,5.);#4=OFFSET_SURFACE('',#3,-6.,.F.);#5=OFFSET_SURFACE('',#4,6.,.F.);{TAIL}");let ex = p21::parse(&text).unwrap();- let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };assert!(geom::surface(&cx, 5, &points, &[], true, 0).is_err());}@@ -903,6 +903,75 @@ fn unsupported_face_is_left_out_and_reported() {assert!(imp.warnings.iter().any(|w| w.contains("open body")), "{:?}", imp.warnings);}+/// A flat square sheet `size` mm across in millimetres (declared accuracy 1e-6 mm) whose right+/// edge is a straight spline ending `gap` mm beside the corner vertex it runs to, as exporters+/// write two curves meeting at a vertex between them. `stray` adds an unused vertex that far+/// out, which makes the model look that large.+fn gapped_sheet(size: f64, gap: f64, stray: Option<f64>) -> String {+ let mut t = String::from(HEAD);+ for (k, (x, y)) in [(0.0, 0.0), (size, 0.0), (size, size), (0.0, size)].iter().enumerate() {+ t += &format!("#{}=CARTESIAN_POINT('',({x:.6},{y:.6},0.));\n#{}=VERTEX_POINT('',#{});\n", 20 + k, 30 + k, 20 + k);+ }+ if let Some(far) = stray {+ t += &format!("#38=CARTESIAN_POINT('',({far:.6},0.,0.));\n#39=VERTEX_POINT('',#38);\n");+ }+ t += &format!(+ "#46=CARTESIAN_POINT('',({:.6},{size:.6},0.));\n#47=B_SPLINE_CURVE_WITH_KNOTS('',1,(#21,#46),.UNSPECIFIED.,.F.,.F.,(2,2),(0.,1.),.UNSPECIFIED.);\n",+ size + gap+ );+ t += "#40=DIRECTION('',(1.,0.,0.));\n#41=VECTOR('',#40,1.);\n#50=LINE('',#20,#41);\n#52=LINE('',#22,#41);\n#53=LINE('',#23,#41);\n";+ for (k, curve) in [50, 47, 52, 53].iter().enumerate() {+ t += &format!(+ "#{}=EDGE_CURVE('',#{},#{},#{curve},.T.);\n#{}=ORIENTED_EDGE('',*,*,#{},.T.);\n",+ 60 + k,+ 30 + k,+ 30 + (k + 1) % 4,+ 70 + k,+ 60 + k+ );+ }+ t += "#80=EDGE_LOOP('',(#70,#71,#72,#73));\n#81=FACE_OUTER_BOUND('',#80,.T.);\n#90=CARTESIAN_POINT('',(0.,0.,0.));\n#91=DIRECTION('',(0.,0.,1.));\n";+ t += "#92=AXIS2_PLACEMENT_3D('',#90,#91,#40);\n#93=PLANE('',#92);\n#82=ADVANCED_FACE('',(#81),#93,.T.);\n";+ t += "#110=OPEN_SHELL('',(#82));\n#111=SHELL_BASED_SURFACE_MODEL('Sheet',(#110));\n#112=SHAPE_REPRESENTATION('',(#111),#10);\n";+ t += &context(10, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))");+ t += TAIL;+ t+}++#[test]+fn a_vertex_off_its_curve_by_a_small_share_of_the_model_is_moved_onto_it() {+ // 0.19 mm on a 1 m sheet: 190 000 times the file's declared accuracy, 1.3e-4 of its size.+ let imp = step_import(&gapped_sheet(1000.0, 0.19, None)).unwrap();+ assert!(!imp.warnings.iter().any(|w| w.contains("off their curve")), "{:?}", imp.warnings);+ assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings);+ let body = &imp.bodies[0].body;+ assert_eq!(body.face_count(), 1);+ // Every edge meets its vertices exactly: the spline's end was moved onto the corner.+ use mt::{BoundedCurve as _, MetricSpace as _};+ for e in body.solid.edge_iter() {+ let c = e.curve();+ assert!(c.front().distance(e.front().point()) < 1e-9 && c.back().distance(e.back().point()) < 1e-9);+ }+ let m = measure(body).unwrap();+ assert!(rel(m.area, 1e6) < 1e-4, "area {}", m.area);+}++#[test]+fn a_vertex_further_off_its_curve_than_the_model_allows_leaves_the_face_out() {+ // 0.19 mm on a 10 mm sheet is 1.3 % of the part; and a stray point a kilometre out cannot+ // stretch the limit past 1 mm.+ for text in [gapped_sheet(10.0, 0.19, None), gapped_sheet(1000.0, 2.0, Some(1e6))] {+ let warnings = match step_import(&text) {+ Ok(imp) => {+ assert!(imp.bodies.is_empty());+ imp.warnings.join("\n")+ }+ Err(e) => e.to_string(),+ };+ assert!(warnings.contains("off their curve"), "{warnings}");+ }+}+#[test]fn hostile_files_never_panic() {let good = step_export(&[&box_solid(Vec3::ZERO, Vec3::new(5.0, 5.0, 5.0)).unwrap()], "t").unwrap();@@ -1020,6 +1089,206 @@ fn split_band_edges_are_seams() {assert!(m.seams.iter().filter(|s| **s).count() >= 2, "{:?}", m.seams);}+/// A five-sided tube on a B-spline surface closed around (radius `r`, height `h`), as one band+/// face bounded by ring edges `off` mm outside the surface, with a seam edge up one corner used+/// both ways; plus the two flat ends on the planes the rings lie in. The file declares+/// `uncertainty` mm of uncertainty of its own, which is what tells a reader how far the rings+/// may lie off the surface.+///+/// The part's size, the rings' off-surface distance and the declared uncertainty are separate on+/// purpose: a real file's slop stays a few micrometres whether the part is 20 mm or 2 m across+/// (see `off_surface_budget_follows_the_file_not_the_part_size`).+#[derive(Clone, Copy)]+struct RingEdgeTube {+ /// Radius of the surface (mm).+ r: f64,+ /// Height of the tube (mm).+ h: f64,+ /// How far outside the surface the ring edges run (mm).+ off: f64,+ /// The uncertainty the file declares for itself (mm).+ uncertainty: f64,+}++impl RingEdgeTube {+ /// A 20 mm part with a few micrometres of slop and a micrometre of declared uncertainty:+ /// what a well-behaved writer puts out.+ fn small() -> RingEdgeTube {+ RingEdgeTube { r: 10.0, h: 8.0, off: 0.004, uncertainty: 1e-3 }+ }++ /// The same part, and the same slop, scaled to about 2 m across.+ fn large() -> RingEdgeTube {+ RingEdgeTube { r: 1000.0, h: 800.0, ..RingEdgeTube::small() }+ }++ /// The volume the closed pentagon prism encloses (mm³).+ fn volume(&self) -> f64 {+ 2.5 * self.r * self.r * (std::f64::consts::TAU / 5.0).sin() * self.h+ }++ /// The area of the five sides and the two five-sided ends together (mm²).+ fn area(&self) -> f64 {+ let side = 2.0 * self.r * (std::f64::consts::TAU / 10.0).sin();+ 5.0 * side * self.h + 5.0 * side * self.r * (std::f64::consts::TAU / 10.0).cos()+ }++ fn step(&self) -> String {+ ring_edge_tube_step(self.r, self.h, self.off, self.uncertainty)+ }+}++fn ring_edge_tube_step(r: f64, h: f64, off: f64, uncertainty: f64) -> String {+ let corner = |k: usize, radius: f64| {+ let a = std::f64::consts::TAU * (k % 5) as f64 / 5.0;+ (radius * a.cos(), radius * a.sin())+ };+ let mut t = String::from(HEAD);+ // Control net: the corners around (the first repeated to close it) x the two ends.+ let mut rows = Vec::new();+ for k in 0..=5 {+ let (x, y) = corner(k, r);+ let id = 100 + 2 * k as u64;+ t += &format!("#{id}=CARTESIAN_POINT('',({x:.9},{y:.9},0.));\n#{}=CARTESIAN_POINT('',({x:.9},{y:.9},{h:.9}));\n", id + 1);+ rows.push(format!("(#{id},#{})", id + 1));+ }+ t += &format!(+ "#200=B_SPLINE_SURFACE_WITH_KNOTS('',1,1,({}),.UNSPECIFIED.,.T.,.F.,.F.,(2,1,1,1,1,2),(2,2),(0.,1.,2.,3.,4.,5.),(0.,1.),.UNSPECIFIED.);\n",+ rows.join(",")+ );+ // The rings, `off` mm outside the surface: each is one closed polyline edge.+ for k in 0..5u64 {+ let (x, y) = corner(k as usize, r + off);+ t += &format!("#{}=CARTESIAN_POINT('',({x:.9},{y:.9},0.));\n#{}=CARTESIAN_POINT('',({x:.9},{y:.9},{h:.9}));\n", 300 + k, 310 + k);+ }+ t += "#320=VERTEX_POINT('',#300);\n#321=VERTEX_POINT('',#310);\n";+ t += "#330=POLYLINE('',(#300,#301,#302,#303,#304,#300));\n#331=POLYLINE('',(#310,#311,#312,#313,#314,#310));\n";+ t += "#340=DIRECTION('',(0.,0.,1.));\n#341=VECTOR('',#340,1.);\n#342=LINE('',#300,#341);\n";+ t += "#350=EDGE_CURVE('',#320,#320,#330,.T.);\n#351=EDGE_CURVE('',#321,#321,#331,.T.);\n#352=EDGE_CURVE('',#320,#321,#342,.T.);\n";+ // The band's loop: around the bottom ring, up the seam, back around the top, down the seam.+ t += "#360=ORIENTED_EDGE('',*,*,#350,.T.);\n#361=ORIENTED_EDGE('',*,*,#352,.T.);\n#362=ORIENTED_EDGE('',*,*,#351,.F.);\n#363=ORIENTED_EDGE('',*,*,#352,.F.);\n";+ t += "#364=EDGE_LOOP('',(#360,#361,#362,#363));\n#365=FACE_OUTER_BOUND('',#364,.T.);\n#366=ADVANCED_FACE('',(#365),#200,.T.);\n";+ // The two ends, on the planes the rings lie in.+ t += "#370=CARTESIAN_POINT('',(0.,0.,0.));\n#371=DIRECTION('',(1.,0.,0.));\n#372=AXIS2_PLACEMENT_3D('',#370,#340,#371);\n#373=PLANE('',#372);\n";+ t += "#374=ORIENTED_EDGE('',*,*,#350,.F.);\n#375=EDGE_LOOP('',(#374));\n#376=FACE_OUTER_BOUND('',#375,.T.);\n#377=ADVANCED_FACE('',(#376),#373,.F.);\n";+ t += &format!("#380=CARTESIAN_POINT('',(0.,0.,{h:.9}));\n#381=AXIS2_PLACEMENT_3D('',#380,#340,#371);\n#382=PLANE('',#381);\n");+ t += "#383=ORIENTED_EDGE('',*,*,#351,.T.);\n#384=EDGE_LOOP('',(#383));\n#385=FACE_OUTER_BOUND('',#384,.T.);\n#386=ADVANCED_FACE('',(#385),#382,.T.);\n";+ t += "#390=CLOSED_SHELL('',(#366,#377,#386));\n#391=MANIFOLD_SOLID_BREP('Tube',#390);\n#392=SHAPE_REPRESENTATION('',(#391),#20);\n";+ // What the file declares about its own numbers. This, and not the part's size, is how far a+ // reader may let the ring edges lie off the surface.+ t += "#20=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#21))GLOBAL_UNIT_ASSIGNED_CONTEXT((#22,#23))REPRESENTATION_CONTEXT('',''));\n";+ t += &format!("#21=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE({uncertainty:.9}),#22,'','');\n");+ t += "#22=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n#23=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n";+ t += TAIL;+ t+}++/// Every check the split band must pass, at whatever size the part is: the band comes in as two+/// faces, every face has triangles at every chord tolerance from coarse to fine, and the four+/// faces together cover the tube once and close it.+///+/// Every tolerance here is a fraction of the body, so the same mesh is asked for at every scale;+/// the rings' off-surface distance is the one thing that stays absolute.+fn assert_ring_edge_tube_meshes(tube: &RingEdgeTube) {+ let imp = step_import(&tube.step()).unwrap();+ assert!(!imp.warnings.iter().any(|w| w.contains("kept whole")), "{:?}", imp.warnings);+ let ib = &imp.bodies[0];+ assert_eq!(ib.file_faces, 3);+ assert_eq!(ib.body.face_count(), 4, "the band face is split in two: {:?}", imp.warnings);+ assert_eq!(ib.body.unmeshed_faces(), 0, "{:?}", imp.warnings);+ let size = ib.body.size();+ // Every face is meshed, and the four together cover the tube once: five sides of+ // 2*R*sin(36 deg) by the height, plus the two five-sided ends.+ let m = ib.body.display_mesh(size * 2e-3).unwrap();+ let mut area = vec![0.0f64; ib.body.face_count()];+ for (t, f) in m.triangles.iter().zip(&m.tri_face) {+ let (a, b, c) = (m.positions[t[0] as usize], m.positions[t[1] as usize], m.positions[t[2] as usize]);+ if let Some(sum) = area.get_mut(*f as usize) {+ *sum += 0.5 * (b - a).cross(c - a).len();+ }+ }+ let side = 2.0 * tube.r * (std::f64::consts::TAU / 10.0).sin();+ let want = tube.area();+ assert!(rel(area.iter().sum::<f64>(), want) < 5e-3, "{area:?} sums to {} not {want}", area.iter().sum::<f64>());+ // Neither half of the split is a sliver: the split line runs from ring to ring.+ assert!(area.iter().all(|a| *a > 0.2 * side * tube.h), "a face of the split tube is nearly empty: {area:?}");+ // The body closes: its volume is the pentagon prism's. `measure` tessellates far finer than+ // any display does, and the planner used to give up on a boundary running off its surface+ // once the chord tolerance came near the gap. One face without a plan costs the whole body+ // its plan, and the reference mesher cannot mesh a face on a closed B-spline surface at all,+ // so both halves of the band came out with no triangles: the volume was the top cap's alone.+ let vol = measure(&ib.body).unwrap().volume;+ let want_vol = tube.volume();+ assert!(rel(vol, want_vol) < 1e-3, "the split band does not close the body: {vol} not {want_vol}");+ // Every face keeps its triangles at every tolerance, coarse to fine.+ for frac in [2e-3, 4e-4, 4e-5, 1.1e-5, 4e-6] {+ let t = size * frac;+ let plan = ib.body.display_plan(t).unwrap_or_else(|e| panic!("no display plan at tol {t}: {e}"));+ let bare: Vec<u32> = plan.faces.iter().filter(|f| f.triangles.is_empty()).map(|f| f.face).collect();+ assert!(bare.is_empty(), "faces {bare:?} have no triangles at tol {t}");+ }+ // What the viewport and a snapshot actually draw: the display tolerance with a facet angle.+ // The angle divides an edge wherever it kinks, far below the chord tolerance, which is what+ // used to crowd the boundary against a corner of the surface and leave the band undrawn.+ let tol = (size * 1e-3).max(1e-3);+ let shown = ib.body.reference_display_mesh_angular(tol, crate::DISPLAY_ANGLE).unwrap();+ let mut drawn = vec![0.0f64; ib.body.face_count()];+ for (t, f) in shown.triangles.iter().zip(&shown.tri_face) {+ let (a, b, c) = (shown.positions[t[0] as usize], shown.positions[t[1] as usize], shown.positions[t[2] as usize]);+ if let Some(sum) = drawn.get_mut(*f as usize) {+ *sum += 0.5 * (b - a).cross(c - a).len();+ }+ }+ assert!(drawn.iter().all(|a| *a > 0.2 * side * tube.h), "a face of the split tube is not drawn: {drawn:?}");+ assert!(rel(drawn.iter().sum::<f64>(), want) < 5e-3, "{drawn:?} sums to {} not {want}", drawn.iter().sum::<f64>());+}++/// A band face is split although its ring edges run a little off its surface. A file writes+/// edges and surfaces to its own uncertainty, so the two disagree by a few micrometres; the+/// split line lies on the surface and can only reach the surface points below the rings.+#[test]+fn band_faces_split_when_ring_edges_run_off_their_surface() {+ assert_ring_edge_tube_meshes(&RingEdgeTube::small());+}++/// The very same fixture, the very same few micrometres of slop in the file, scaled to a part+/// about 2 m across: it meshes the same way (#1721).+#[test]+fn band_faces_split_when_a_scaled_copy_runs_off_its_surface() {+ assert_ring_edge_tube_meshes(&RingEdgeTube::large());+}++/// How far a boundary may lie off its surface is a hundredth of the part, at every chord+/// tolerance, and more only where the file declares more. A writer's declared accuracy is what it+/// aimed for, not a bound its edges keep (a robot assembly declaring 0.01 µm has edges 10 to+/// 30 µm off), so it never tightens the bound; and it must not depend on the mesh asked for, or a+/// face accepted while the model is far away would drop out when the user zooms in (#1721).+#[test]+fn off_surface_budget_is_a_hundredth_of_the_part_at_every_chord_tolerance() {+ let accepted = |tube: &RingEdgeTube| -> bool {+ let imp = step_import(&tube.step()).unwrap();+ let ib = &imp.bodies[0];+ let size = ib.body.size();+ [2e-3, 4e-6].iter().all(|fraction| ib.body.display_plan(size * fraction).is_ok())+ };+ // A few micrometres, whatever the file declares, at either size.+ for uncertainty in [1e-3, 1e-5] {+ for tube in [RingEdgeTube { uncertainty, ..RingEdgeTube::small() }, RingEdgeTube { uncertainty, ..RingEdgeTube::large() }] {+ assert!(accepted(&tube), "a part {} mm across, {} mm off on {uncertainty} declared", 2.0 * tube.r, tube.off);+ }+ }+ // Within a hundredth of the part: a 20 mm part takes 0.15 mm, a 2 m part 2 mm; past it, no.+ assert!(accepted(&RingEdgeTube { off: 0.15, ..RingEdgeTube::small() }));+ assert!(accepted(&RingEdgeTube { off: 2.0, ..RingEdgeTube::large() }));+ assert!(!accepted(&RingEdgeTube { off: 2.0, ..RingEdgeTube::small() }), "a 20 mm part accepts a boundary 2 mm off its surface");+ assert!(!accepted(&RingEdgeTube { off: 100.0, ..RingEdgeTube::large() }), "a 2 m part accepts a boundary 100 mm off its surface");+ // A file declaring more raises it: half a millimetre on a 20 mm part, refused on a declared+ // micrometre, accepted on a declared 60 µm (ten times which is 0.6 mm).+ let tight = RingEdgeTube { off: 0.5, ..RingEdgeTube::small() };+ assert!(!accepted(&tight));+ assert!(accepted(&RingEdgeTube { uncertainty: 0.06, ..tight }));+}+/// Revolved faces of a mirrored tool keep their orientation through STEP (the writer used to/// drop an inverted or mirrored revolution's sense).#[test]@@ -1310,7 +1579,7 @@ fn knot_multiplicities_are_checked_before_they_are_expanded() {};let read = |text: &str| {let ex = p21::parse(text).unwrap();- let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };geom::curve(&cx, 3, 0)};let error = read(&curve(1_000_000, 64)).unwrap_err();@@ -1322,6 +1591,50 @@ fn knot_multiplicities_are_checked_before_they_are_expanded() {assert!(read(&curve(2, 3)).is_err());}+/// A spline written over a parameter range of a few millionths (as if in metres of a part drawn+/// in millimetres: piecewise cubic Bézier over 5.4e-6, as a STEP part of a humanoid robot+/// writes its edges) is read over a range of 1. Over the file's own range the kernel took knots+/// a millionth apart for one, so trimming an edge to its vertices dropped a control point and+/// left a curve no exact store could keep (every reopen of that design imported it again).+#[test]+fn a_spline_over_a_tiny_parameter_range_is_read_over_one() {+ use mt::{BoundedCurve, Cut, MetricSpace, ParametricCurve};+ let a = 1.8024e-6;+ let knots = [0.0, a, 3.0304e-6, 3.8749e-6, 4.7103e-6, 5.0653e-6, 5.4274e-6];+ let n = 3 * (knots.len() - 1) + 1;+ let points: String = (0..n).map(|i| format!("#{}=CARTESIAN_POINT('',({}.,{}.,0.));\n", 10 + i, i, (i * i) % 7)).collect();+ let refs: Vec<String> = (0..n).map(|i| format!("#{}", 10 + i)).collect();+ let mults: Vec<String> = (0..knots.len()).map(|i| if i == 0 || i + 1 == knots.len() { "4".into() } else { "3".into() }).collect();+ let text = format!(+ "{HEAD}{points}#3=B_SPLINE_CURVE_WITH_KNOTS('',3,({}),.UNSPECIFIED.,.F.,.F.,({}),({}),.UNSPECIFIED.);\n{TAIL}",+ refs.join(","),+ mults.join(","),+ knots.iter().map(|k| format!("{k:e}")).collect::<Vec<_>>().join(",")+ );+ let ex = p21::parse(&text).unwrap();+ let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };+ let Ok(geom::CurveGeo::BSpline(c)) = geom::curve(&cx, 3, 0) else { panic!("a B-spline") };+ let (t0, t1) = c.range_tuple();+ assert_eq!((t0, t1), (0.0, 1.0));+ // The same curve: its ends are the first and last control points.+ assert!(c.subs(t0).distance(mt::Point3::new(0.0, 0.0, 0.0)) < 1e-12);+ assert!(c.subs(t1).distance(mt::Point3::new((n - 1) as f64, ((n - 1) * (n - 1) % 7) as f64, 0.0)) < 1e-12);+ // Cut between knots, as an edge is trimmed to its vertices: both pieces keep clamped ends+ // and every control point, and meet where the curve was cut.+ for t in [0.3, 0.33, 0.9, 0.95] {+ let mut head = c.clone();+ let tail = head.cut(t);+ for piece in [&head, &tail] {+ let k: Vec<f64> = piece.knot_vec().iter().copied().collect();+ let d = piece.degree();+ assert_eq!(piece.control_points().len() + d + 1, k.len());+ assert!(k.iter().take(d + 1).all(|x| *x == k[0]) && k.iter().rev().take(d + 1).all(|x| Some(x) == k.last()), "{t}: {k:?}");+ }+ assert!(head.subs(head.range_tuple().1).distance(c.subs(t)) < 1e-9);+ assert!(tail.subs(tail.range_tuple().0).distance(c.subs(t)) < 1e-9);+ }+}+/// One `ADVANCED_FACE` may list any number of bounds, and each one clones its edge handles into/// a new wire that the face extent then samples. A face naming the same loop a million times/// held 1e11 handles.@@ -1461,6 +1774,189 @@ fn large_imports_are_freed_with_their_last_user() {assert!(weak.upgrade().is_none(), "the cache must not keep a large import alive after its design is gone");}+/// A face that runs all the way around a closed (but not periodic) B-spline surface and carries+/// a zero-width slit of its own: a pair of curves a hundredth of a micrometre apart between the+/// same two vertices, which the loop walks up and straight back down. STEP writers leave such a+/// slit where two surfaces were trimmed apart. It stands away from the surface's join, so the+/// band splitter leaves the face whole and the mesher has to draw it; the boundary then runs+/// along itself in (u, v). That used to fail the planner, and with it the whole body's plan, so+/// the body fell back to the reference mesher, which drew bands folded over themselves and left+/// holes in others.+#[test]+fn band_face_with_a_zero_width_slit_is_still_meshed() {+ const R: f64 = 10.0;+ const H: f64 = 8.0;+ /// How far the slit's two sides stand apart (a hundredth of a micrometre).+ const LENS: f64 = 1.0e-5;+ let corner = |k: usize, r: f64| {+ let a = std::f64::consts::TAU * (k % 5) as f64 / 5.0;+ (r * a.cos(), r * a.sin())+ };+ let mut t = String::from(HEAD);+ // Control net: the five corners around (the first repeated to close it) × the two ends.+ let mut rows = Vec::new();+ for k in 0..=5 {+ let (x, y) = corner(k, R);+ let id = 100 + 2 * k as u64;+ t += &format!("#{id}=CARTESIAN_POINT('',({x:.12},{y:.12},0.));\n#{}=CARTESIAN_POINT('',({x:.12},{y:.12},{H:.1}));\n", id + 1);+ rows.push(format!("(#{id},#{})", id + 1));+ }+ t += &format!(+ "#200=B_SPLINE_SURFACE_WITH_KNOTS('',1,1,({}),.UNSPECIFIED.,.T.,.F.,.F.,(2,1,1,1,1,2),(2,2),(0.,1.,2.,3.,4.,5.),(0.,1.),.UNSPECIFIED.);\n",+ rows.join(",")+ );+ // The seam runs up corner 0; the slit stands at corner 2, where each ring is cut in two.+ let (mx, my) = corner(2, R + LENS);+ t += &format!("#210=CARTESIAN_POINT('',({mx:.12},{my:.12},{:.1}));\n", H * 0.5);+ t += "#300=VERTEX_POINT('',#100);\n#301=VERTEX_POINT('',#101);\n#302=VERTEX_POINT('',#104);\n#303=VERTEX_POINT('',#105);\n";+ t += "#310=DIRECTION('',(0.,0.,1.));\n#311=VECTOR('',#310,1.);\n#312=LINE('',#100,#311);\n";+ // The slit's two sides: straight up corner 2, and back down a hair outside it.+ t += "#313=POLYLINE('',(#104,#105));\n#314=POLYLINE('',(#105,#210,#104));\n";+ t += "#320=POLYLINE('',(#100,#102,#104));\n#321=POLYLINE('',(#104,#106,#108,#100));\n";+ t += "#322=POLYLINE('',(#101,#103,#105));\n#323=POLYLINE('',(#105,#107,#109,#101));\n";+ t += "#330=EDGE_CURVE('',#300,#301,#312,.T.);\n";+ t += "#331=EDGE_CURVE('',#302,#303,#313,.T.);\n#332=EDGE_CURVE('',#303,#302,#314,.T.);\n";+ t += "#333=EDGE_CURVE('',#300,#302,#320,.T.);\n#334=EDGE_CURVE('',#302,#300,#321,.T.);\n";+ t += "#335=EDGE_CURVE('',#301,#303,#322,.T.);\n#336=EDGE_CURVE('',#303,#301,#323,.T.);\n";+ // The band: round the bottom to the slit, up one side of it and down the other, on round the+ // bottom, up the seam, back along the top to the slit, down it and up again, on to the seam.+ t += "#340=ORIENTED_EDGE('',*,*,#333,.T.);\n#341=ORIENTED_EDGE('',*,*,#331,.T.);\n#342=ORIENTED_EDGE('',*,*,#332,.T.);\n";+ t += "#343=ORIENTED_EDGE('',*,*,#334,.T.);\n#344=ORIENTED_EDGE('',*,*,#330,.T.);\n#345=ORIENTED_EDGE('',*,*,#336,.F.);\n";+ t += "#346=ORIENTED_EDGE('',*,*,#331,.F.);\n#347=ORIENTED_EDGE('',*,*,#332,.F.);\n#348=ORIENTED_EDGE('',*,*,#335,.F.);\n";+ t += "#349=ORIENTED_EDGE('',*,*,#330,.F.);\n";+ t += "#350=EDGE_LOOP('',(#340,#341,#342,#343,#344,#345,#346,#347,#348,#349));\n#351=FACE_OUTER_BOUND('',#350,.T.);\n";+ t += "#352=ADVANCED_FACE('',(#351),#200,.T.);\n";+ // The two ends, on the planes the rings lie in.+ t += "#360=CARTESIAN_POINT('',(0.,0.,0.));\n#361=DIRECTION('',(1.,0.,0.));\n#362=AXIS2_PLACEMENT_3D('',#360,#310,#361);\n#363=PLANE('',#362);\n";+ t += "#364=ORIENTED_EDGE('',*,*,#334,.F.);\n#365=ORIENTED_EDGE('',*,*,#333,.F.);\n#366=EDGE_LOOP('',(#364,#365));\n";+ t += "#367=FACE_OUTER_BOUND('',#366,.T.);\n#368=ADVANCED_FACE('',(#367),#363,.F.);\n";+ t += &format!("#370=CARTESIAN_POINT('',(0.,0.,{H:.1}));\n#371=AXIS2_PLACEMENT_3D('',#370,#310,#361);\n#372=PLANE('',#371);\n");+ t += "#373=ORIENTED_EDGE('',*,*,#335,.T.);\n#374=ORIENTED_EDGE('',*,*,#336,.T.);\n#375=EDGE_LOOP('',(#373,#374));\n";+ t += "#376=FACE_OUTER_BOUND('',#375,.T.);\n#377=ADVANCED_FACE('',(#376),#372,.T.);\n";+ t += "#390=CLOSED_SHELL('',(#352,#368,#377));\n#391=MANIFOLD_SOLID_BREP('Slit tube',#390);\n#392=SHAPE_REPRESENTATION('',(#391),#20);\n";+ t += "#20=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#21))GLOBAL_UNIT_ASSIGNED_CONTEXT((#22,#23))REPRESENTATION_CONTEXT('',''));\n";+ t += "#21=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-3),#22,'','');\n";+ t += "#22=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n#23=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n";+ t += TAIL;+ let imp = step_import(&t).unwrap();+ assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);+ let ib = &imp.bodies[0];+ assert_eq!(ib.file_faces, 3);+ assert_eq!(ib.body.unmeshed_faces(), 0);+ // Every face is planned: one face the planner gives up on costs the whole body its plan.+ let tol = 0.05;+ assert!(ib.body.display_plan(tol).is_ok(), "{:?}", ib.body.display_plan(tol).err());+ // The mesh covers the tube once: five sides of 2·R·sin(36°) by the height, plus the ends.+ let m = ib.body.display_mesh(tol).unwrap();+ let mut area = vec![0.0f64; ib.body.face_count()];+ for (t, f) in m.triangles.iter().zip(&m.tri_face) {+ let (a, b, c) = (m.positions[t[0] as usize], m.positions[t[1] as usize], m.positions[t[2] as usize]);+ if let Some(sum) = area.get_mut(*f as usize) {+ *sum += 0.5 * (b - a).cross(c - a).len();+ }+ }+ let side = 2.0 * R * (std::f64::consts::TAU / 10.0).sin();+ let want = 5.0 * side * H + 5.0 * side * R * (std::f64::consts::TAU / 10.0).cos();+ assert!(rel(area.iter().sum::<f64>(), want) < 5e-3, "{area:?} sums to {} not {want}", area.iter().sum::<f64>());+ // The band itself is drawn once over: not folded over itself, and with no gap left in it.+ let band: f64 = (0..ib.body.face_count()).filter(|i| ib.face_origin.get(*i) == Some(&352)).map(|i| area[i]).sum();+ assert!(rel(band, 5.0 * side * H) < 5e-3, "the band covers {band} not {}", 5.0 * side * H);+}++/// A face so thin that its whole boundary is two chords: a lens between a straight edge and an+/// arc that bows away from it by a ten-thousandth of a millimetre. The edge sampler rightly+/// leaves each side as one segment, so the boundary comes to two nodes — too few to hold a+/// triangle. The planner used to give up on such a face, and one face it gives up on costs the+/// whole body its plan, so every other face fell back to the reference mesher. STEP writers+/// leave these slivers where two surfaces were trimmed apart.+#[test]+fn a_sliver_face_too_thin_to_triangulate_does_not_cost_the_body_its_plan() {+ /// The lens is shorter than one facet of the body it sits on: its whole boundary is then+ /// two chords, however finely the rest of the body is meshed.+ const L: f64 = 0.05;+ const H: f64 = 60.0;+ /// How far the arc bows away from the straight side, at its middle (above the file's own+ /// uncertainty, so the two sides are not the same curve).+ const BOW: f64 = 5.0e-3;+ let mut t = String::from(HEAD);+ // The lens lies in the xy plane: straight along y = 0, the arc bowing to y = BOW.+ t += &format!("#100=CARTESIAN_POINT('',(0.,0.,0.));\n#101=CARTESIAN_POINT('',(0.,0.,{H:.1}));\n");+ t += &format!("#102=CARTESIAN_POINT('',({L:.6},0.,0.));\n#103=CARTESIAN_POINT('',({L:.6},0.,{H:.1}));\n");+ // A degree-2 spline through the ends with this middle control point bows by BOW (half of it).+ t += &format!(+ "#104=CARTESIAN_POINT('',({:.6},{:.9},0.));\n#105=CARTESIAN_POINT('',({:.6},{:.9},{H:.1}));\n",+ L * 0.5,+ 2.0 * BOW,+ L * 0.5,+ 2.0 * BOW+ );+ t += "#110=VERTEX_POINT('',#100);\n#111=VERTEX_POINT('',#101);\n#112=VERTEX_POINT('',#102);\n#113=VERTEX_POINT('',#103);\n";+ t += "#114=DIRECTION('',(1.,0.,0.));\n#115=DIRECTION('',(0.,0.,1.));\n#116=DIRECTION('',(0.,1.,0.));\n";+ t += "#120=VECTOR('',#114,1.);\n#121=LINE('',#100,#120);\n#122=LINE('',#101,#120);\n";+ t += "#123=VECTOR('',#115,1.);\n#124=LINE('',#100,#123);\n#125=LINE('',#102,#123);\n";+ t += "#126=B_SPLINE_CURVE_WITH_KNOTS('',2,(#100,#104,#102),.UNSPECIFIED.,.F.,.F.,(3,3),(0.,1.),.UNSPECIFIED.);\n";+ t += "#127=B_SPLINE_CURVE_WITH_KNOTS('',2,(#101,#105,#103),.UNSPECIFIED.,.F.,.F.,(3,3),(0.,1.),.UNSPECIFIED.);\n";+ t += "#130=EDGE_CURVE('',#110,#112,#121,.T.);\n#131=EDGE_CURVE('',#111,#113,#122,.T.);\n";+ t += "#132=EDGE_CURVE('',#110,#112,#126,.T.);\n#133=EDGE_CURVE('',#111,#113,#127,.T.);\n";+ t += "#134=EDGE_CURVE('',#110,#111,#124,.T.);\n#135=EDGE_CURVE('',#112,#113,#125,.T.);\n";+ // The four surfaces: the two lens ends, the flat side and the bowed side.+ t += "#140=AXIS2_PLACEMENT_3D('',#100,#115,#114);\n#141=PLANE('',#140);\n";+ t += &format!("#142=CARTESIAN_POINT('',(0.,0.,{H:.1}));\n#143=AXIS2_PLACEMENT_3D('',#142,#115,#114);\n#144=PLANE('',#143);\n");+ t += "#145=AXIS2_PLACEMENT_3D('',#100,#116,#114);\n#146=PLANE('',#145);\n";+ t += "#147=B_SPLINE_SURFACE_WITH_KNOTS('',2,1,((#100,#101),(#104,#105),(#102,#103)),.UNSPECIFIED.,.F.,.F.,.F.,(3,3),(2,2),(0.,1.),(0.,1.),.UNSPECIFIED.);\n";+ // The lens ends: two edges each, and so two nodes. Every edge of the shell is walked once+ // each way, and each face's ring turns anticlockwise seen from outside the solid.+ t += "#150=ORIENTED_EDGE('',*,*,#132,.T.);\n#151=ORIENTED_EDGE('',*,*,#130,.F.);\n#152=EDGE_LOOP('',(#150,#151));\n";+ t += "#153=FACE_OUTER_BOUND('',#152,.T.);\n#154=ADVANCED_FACE('',(#153),#141,.F.);\n";+ t += "#155=ORIENTED_EDGE('',*,*,#131,.T.);\n#156=ORIENTED_EDGE('',*,*,#133,.F.);\n#157=EDGE_LOOP('',(#155,#156));\n";+ t += "#158=FACE_OUTER_BOUND('',#157,.T.);\n#159=ADVANCED_FACE('',(#158),#144,.T.);\n";+ // The flat side and the bowed side, each a four-edge ring.+ t += "#160=ORIENTED_EDGE('',*,*,#130,.T.);\n#161=ORIENTED_EDGE('',*,*,#135,.T.);\n#162=ORIENTED_EDGE('',*,*,#131,.F.);\n#163=ORIENTED_EDGE('',*,*,#134,.F.);\n";+ t += "#164=EDGE_LOOP('',(#160,#161,#162,#163));\n#165=FACE_OUTER_BOUND('',#164,.T.);\n#166=ADVANCED_FACE('',(#165),#146,.F.);\n";+ t += "#170=ORIENTED_EDGE('',*,*,#134,.T.);\n#171=ORIENTED_EDGE('',*,*,#133,.T.);\n#172=ORIENTED_EDGE('',*,*,#135,.F.);\n#173=ORIENTED_EDGE('',*,*,#132,.F.);\n";+ t += "#174=EDGE_LOOP('',(#170,#171,#172,#173));\n#175=FACE_OUTER_BOUND('',#174,.T.);\n#176=ADVANCED_FACE('',(#175),#147,.F.);\n";+ t += "#180=CLOSED_SHELL('',(#154,#159,#166,#176));\n#181=MANIFOLD_SOLID_BREP('Sliver lens',#180);\n#182=SHAPE_REPRESENTATION('',(#181),#20);\n";+ t += "#20=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#21))GLOBAL_UNIT_ASSIGNED_CONTEXT((#22,#23))REPRESENTATION_CONTEXT('',''));\n";+ t += "#21=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-3),#22,'','');\n";+ t += "#22=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n#23=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n";+ t += TAIL;+ let imp = step_import(&t).unwrap();+ assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);+ let ib = &imp.bodies[0];+ assert_eq!(ib.file_faces, 4);+ // Nothing is left unshown, and the body keeps its plan although one face cannot hold a+ // triangle until its boundary is sampled again.+ assert_eq!(ib.body.unmeshed_faces(), 0);+ let tol = 0.05;+ let plan = ib.body.display_plan(tol).expect("a sliver face must not cost the body its plan");+ for f in &plan.faces {+ assert!(!f.triangles.is_empty(), "face {} has no triangles", f.face);+ }+ // The sides carry the area: L by H flat, a shade more over the bow. The lens ends are+ // slivers, so what matters is that they are drawn at all, not how wide they come out.+ let m = ib.body.display_mesh(tol).unwrap();+ let mut area = vec![0.0f64; ib.body.face_count()];+ for (tri, f) in m.triangles.iter().zip(&m.tri_face) {+ if let Some([p, q, r]) = m.tri(tri)+ && let Some(sum) = area.get_mut(*f as usize)+ {+ *sum += 0.5 * (q - p).cross(r - p).len();+ }+ }+ let mut sides: Vec<f64> = area.iter().copied().filter(|a| *a > 0.1).collect();+ sides.sort_by(|a, b| a.total_cmp(b));+ assert_eq!(sides.len(), 2, "two sides carry the area: {area:?}");+ // The flat side is exactly L by H; the bowed one is longer by the bow, within a tenth.+ assert!(rel(sides[0], L * H) < 1e-6, "the flat side covers {} not {}", sides[0], L * H);+ assert!((1.0..1.1).contains(&(sides[1] / (L * H))), "the bowed side covers {}", sides[1]);+ // Both lens ends are drawn, each a sliver no wider than its own bow.+ let ends: Vec<f64> = area.iter().copied().filter(|a| *a <= 0.1).collect();+ assert_eq!(ends.len(), 2, "two lens ends: {area:?}");+ for e in ends {+ assert!(e > 0.0 && e < L * BOW, "a lens end covers {e}, not a sliver under {}", L * BOW);+ }+}+/// A three-quarter turn of a rectangle about Z: planar end caps, revolved cylinders and annuli.fn three_quarter_ring() -> Body {let rect =@@ -1571,14 +2067,15 @@ fn periodic_knot_bsplines_are_read_on_their_domain() {row.join(","));let ex = p21::parse(&text).unwrap();- let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };let pi = std::f64::consts::PI;let on_tube = |p: mt::Point3| (p.x.hypot(p.y) - r).abs() < 1e-9 && p.z > -1e-9 && p.z < h + 1e-9;let surface_id = ex.get(face).and_then(|e| e.params().get(2)).and_then(Param::as_ref_id).unwrap();let surface = geom::bspline_surface(&cx, ex.get(surface_id).unwrap()).unwrap();let (Some((u0, u1)), Some((v0, v1))) = surface.try_range_tuple() else { panic!("unbounded surface") };- assert!(u0.abs() < 1e-12 && (u1 - h / r).abs() < 1e-12, "u range {u0} .. {u1}");+ // Along the tube the file's range (h / r) is shorter than one: it is read over one.+ assert!(h / r < 1.0 && u0.abs() < 1e-12 && (u1 - 1.0).abs() < 1e-12, "u range {u0} .. {u1}");assert!((v0 + pi).abs() < 1e-9 && (v1 - pi).abs() < 1e-9, "v range {v0} .. {v1}");for i in 0..=8 {for j in 0..=16 {diff --git a/crates/kernel/src/step_out.rs b/crates/kernel/src/step_out.rsindex e50c059ba6..ce1851ce89 100644--- a/crates/kernel/src/step_out.rs+++ b/crates/kernel/src/step_out.rs@@ -500,7 +500,7 @@ fn circle3(a: V3, b: V3, c: V3) -> Option<(V3, f64, V3)> {fn analytic_revolution(ex: &p21::Exchange, e: &p21::Entity) -> Option<Analytic> {use crate::step_in::geom::{self, CurveGeo};use truck_modeling::{BoundedCurve, ParametricCurve};- let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };let p = e.params();let (ao, ad) = geom::axis1(&cx, p.get(2)?.as_ref_id()?).ok()?;let (oa, a) = ([ao.x, ao.y, ao.z], [ad.x, ad.y, ad.z]);@@ -641,7 +641,7 @@ fn planar_bspline(ex: &p21::Exchange, e: &p21::Entity) -> Option<AnalyticKind> {if !(e.has("B_SPLINE_SURFACE") || e.name() == "B_SPLINE_SURFACE_WITH_KNOTS") {return None;}- let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };let s = crate::step_in::geom::bspline_surface(&cx, e).ok()?;let (ctrl, (u0, u1), (v0, v1)) = match &s {truck_modeling::Surface::BSplineSurface(b) => {@@ -678,7 +678,7 @@ fn ruled_bspline(ex: &p21::Exchange, e: &p21::Entity) -> Option<Analytic> {if !(e.has("B_SPLINE_SURFACE") || e.name() == "B_SPLINE_SURFACE_WITH_KNOTS") {return None;}- let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };let s = crate::step_in::geom::bspline_surface(&cx, e).ok()?;let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { return None };let at = |u: f64, v: f64| {@@ -790,7 +790,7 @@ fn edge_points(ex: &p21::Exchange, edge: u64, n: usize) -> Option<Vec<V3>> {use truck_modeling::{BoundedCurve, ParametricCurve};let p = ex.get(edge)?.params();let ends = [vertex_point(ex, p.get(1)?.as_ref_id()?)?, vertex_point(ex, p.get(2)?.as_ref_id()?)?];- let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };let sample = |f: &dyn Fn(f64) -> truck_modeling::Point3, (t0, t1): (f64, f64)| {(0..=n).map(|k| f(t0 + (t1 - t0) * k as f64 / n.max(1) as f64)).map(|q| [q.x, q.y, q.z]).collect::<Vec<V3>>()};@@ -859,7 +859,7 @@ fn collapse_short_edges(ex: &mut p21::Exchange) {// The curve itself must be short too (not a whole circle between two coincident vertices).let short = e.params().get(3).and_then(Param::as_ref_id).and_then(|c| {use truck_modeling::{BoundedCurve, ParametricCurve};- let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };let mid = match crate::step_in::geom::curve(&cx, c, 0).ok()? {crate::step_in::geom::CurveGeo::Line { .. } => return Some(true),crate::step_in::geom::CurveGeo::BSpline(c) => c.subs((c.range_tuple().0 + c.range_tuple().1) / 2.0),@@ -996,7 +996,7 @@ fn merge_split_faces(ex: &mut p21::Exchange, paint: &mut HashMap<u64, FaceLook>,"SURFACE_OF_REVOLUTION" => analytic_revolution(ex, se),// Coplanar pieces (a face split where a mirrored half was glued on)."PLANE" => {- let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };let f = crate::step_in::geom::frame(&cx, se.params().get(1)?.as_ref_id()?).ok()?;let v = |a: truck_modeling::Vector3| [a.x, a.y, a.z];Some(Analytic { kind: AnalyticKind::Plane { o: [f.o.x, f.o.y, f.o.z], z: v(f.z), x: v(f.x) }, flip: false })@@ -1438,7 +1438,7 @@ fn trimmed_sheets(ex: &p21::Exchange, analytic: &HashMap<u64, V3>) -> HashMap<u6continue;};let pts: Vec<V3> = pts.into_iter().flatten().collect();- let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6 };+ let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 };let Ok(sheet) = crate::step_in::geom::bspline_surface(&cx, se) else { continue };if let Ok(Some(cut)) = crate::guard("STEP sheet trim", || Ok(trim_sheet(&sheet, &pts))) {out.insert(sid, cut);diff --git a/crates/kernel/src/surface_extend.rs b/crates/kernel/src/surface_extend.rsindex 202bd1c3b9..78931c3c35 100644--- a/crates/kernel/src/surface_extend.rs+++ b/crates/kernel/src/surface_extend.rs@@ -1133,7 +1133,8 @@ fn continued(surface: &mt::Surface, eval: &EvalSurface, need: &[(f64, f64); 2])match surface {mt::Surface::Plane(_) => Ok(Continued { surface: surface.clone(), map: identity }),mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_) => {- let (Some(EvalSurface::Nurbs { degree, knots, count, ctrl }), rational) = (Some(eval), matches!(surface, mt::Surface::NurbsSurface(_)))+ let (Some(EvalSurface::Nurbs { degree, knots, count, ctrl, .. }), rational) =+ (Some(eval), matches!(surface, mt::Surface::NurbsSurface(_)))else {return Err(unsupported());};diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rsindex 87be141471..e691332ee5 100644--- a/crates/kernel/src/surfaces.rs+++ b/crates/kernel/src/surfaces.rs@@ -33,6 +33,7 @@ fn surface_of(shell: mt::Shell) -> Body {Body {solid: std::sync::Arc::new(mt::Solid::new_unchecked(vec![shell])),size: 0.0,+ boundary_tol: None,volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),coarse_missing: None,mesh: None,diff --git a/crates/kernel/src/tess/cdt.rs b/crates/kernel/src/tess/cdt.rsindex 17a547fee9..c2d3c387ec 100644--- a/crates/kernel/src/tess/cdt.rs+++ b/crates/kernel/src/tess/cdt.rs@@ -50,6 +50,9 @@ pub(crate) struct Fill<'a> {/// varies: a plane is shaded the same by any triangles, so planar faces skip it (around many/// small holes it grades out from each rim and multiplies the triangles).pub shape: bool,+ /// A side crossing one already kept is left out instead of refusing the loops (the last+ /// resort for a boundary that crosses itself, see `fallback`).+ pub lenient: bool,}/// Triangulate the region bounded by `loops` (ranges of `boundary`, each closed). Boundary@@ -83,6 +86,9 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range<usize>continue;}if !cdt.can_add_constraint(a, b) {+ if fill.lenient {+ continue;+ }return None;}cdt.add_constraint(a, b);@@ -267,7 +273,7 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2<f64>if added >= budget {return added;}- if cdt.insert(spade::mitigate_underflow(p)).is_ok() {+ if insert_off_boundary(cdt, p) {added += 1;}}@@ -275,6 +281,22 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2<f64>added}+/// Insert `p` unless it lies exactly on a side of the boundary (the middle of a sliver along+/// it, at a cone's apex): that would split the side, while the face's boundary nodes are shared+/// with its neighbours, which would not have the new one, and the face lost its plan.+fn insert_off_boundary(cdt: &mut Cdt, p: Point2<f64>) -> bool {+ let p = spade::mitigate_underflow(p);+ if !(p.x.is_finite() && p.y.is_finite()) {+ return false;+ }+ if let spade::PositionInTriangulation::OnEdge(e) = cdt.locate(p)+ && cdt.is_constraint_edge(e.as_undirected())+ {+ return false;+ }+ cdt.insert(p).is_ok()+}+/// Per face (by index): inside the region the constraint loops bound. A flood fill from the/// outer face that flips parity each time it crosses a constraint edge (holes are out), linear/// in the number of triangles.@@ -431,7 +453,7 @@ mod tests {for refine in [false, true] {let refine = refine.then_some((Sag { eval: &flat, tol: 1e-3, h: 0.1, turn: None, scale: [2.0, 1.0] }, 2000));let label = refine.is_some();- let Some((extra, tris)) = triangulate(&b, &loops, Fill { seeds: &[[0.2, 0.2], [0.5, 0.5]], refine, shape: true }) else {+ let Some((extra, tris)) = triangulate(&b, &loops, Fill { seeds: &[[0.2, 0.2], [0.5, 0.5]], refine, shape: true, lenient: false }) else {panic!("meshes")};let mut uv = b.clone();@@ -450,11 +472,26 @@ mod tests {}}+ #[test]+ fn a_point_on_a_boundary_side_is_not_inserted() {+ let mut cdt = Cdt::new();+ let corners = [[0.0, 0.0], [4.0, 0.0], [4.0, 1.0], [0.0, 1.0]];+ let Ok(handles) = corners.iter().map(|p| cdt.insert(Point2::new(p[0], p[1]))).collect::<Result<Vec<_>, _>>() else { panic!("insert") };+ for k in 0..4 {+ cdt.add_constraint(handles[k], handles[(k + 1) % 4]);+ }+ assert!(!insert_off_boundary(&mut cdt, Point2::new(2.0, 0.0)));+ assert!(!insert_off_boundary(&mut cdt, Point2::new(f64::NAN, 0.5)));+ assert_eq!((cdt.num_constraints(), cdt.num_vertices()), (4, 4));+ assert!(insert_off_boundary(&mut cdt, Point2::new(2.0, 0.5)));+ assert_eq!((cdt.num_constraints(), cdt.num_vertices()), (4, 5));+ }+#[test]fn crossing_loops_are_refused() {let b = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]];let whole = std::slice::from_ref(&(0..4));- assert!(triangulate(&b, whole, Fill { seeds: &[], refine: None, shape: false }).is_none());+ assert!(triangulate(&b, whole, Fill { seeds: &[], refine: None, shape: false, lenient: false }).is_none());}#[test]@@ -478,7 +515,7 @@ mod tests {// A parameter that is zero in exact arithmetic, left at 1e-300 by projection.let b = [[1e-300, 0.0], [1.0, -1e-310], [1.0, 1.0], [0.0, 1.0]];let whole = std::slice::from_ref(&(0..4));- let Some((extra, tris)) = triangulate(&b, whole, Fill { seeds: &[], refine: None, shape: false }) else { panic!("meshes") };+ let Some((extra, tris)) = triangulate(&b, whole, Fill { seeds: &[], refine: None, shape: false, lenient: false }) else { panic!("meshes") };assert!(extra.is_empty());assert_eq!(tris.len(), 2);}diff --git a/crates/kernel/src/tess/edges.rs b/crates/kernel/src/tess/edges.rsindex 11d620a871..bccd3db5f1 100644--- a/crates/kernel/src/tess/edges.rs+++ b/crates/kernel/src/tess/edges.rs@@ -162,7 +162,7 @@ mod tests {let Ok(cyl) = crate::cylinder(Vec3::ZERO, Vec3::Z, 10.0, 5.0) else { panic!("cylinder") };for tol in [0.1, 0.01, 0.001] {for e in cyl.solid.edge_iter() {- let pts = sample_edge(&e, &Rules { tol, max_len: f64::INFINITY, turn: None }, f64::INFINITY).points;+ let pts = sample_edge(&e, &Rules { tol, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None }, f64::INFINITY).points;assert!(pts.len() >= 2);assert_eq!(pts.first().copied(), Some(from_p3(e.absolute_front().point())));assert_eq!(pts.last().copied(), Some(from_p3(e.absolute_back().point())));@@ -184,7 +184,7 @@ mod tests {fn edges_are_split_to_the_side_length_and_turn() {let Ok(cyl) = crate::cylinder(Vec3::ZERO, Vec3::Z, 10.0, 5.0) else { panic!("cylinder") };for e in cyl.solid.edge_iter() {- let pts = sample_edge(&e, &Rules { tol: 1.0, max_len: f64::INFINITY, turn: None }, 1.2).points;+ let pts = sample_edge(&e, &Rules { tol: 1.0, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None }, 1.2).points;for w in pts.windows(2) {assert!(w[0].dist(w[1]) <= 1.2 + 1e-9, "side {}", w[0].dist(w[1]));}@@ -198,8 +198,13 @@ mod tests {}// A coarse tolerance alone would leave a few long chords; a 30° facet angle keeps every// side within 30° of arc: at least 12 around each of the two circles.- let thirty =- Rules { tol: 5.0, max_len: f64::INFINITY, turn: Some(crate::tess::size::Turn { angle: std::f64::consts::PI / 6.0, floor: 0.0 }) };+ let thirty = Rules {+ tol: 5.0,+ max_len: f64::INFINITY,+ extent: 0.0,+ turn: Some(crate::tess::size::Turn { angle: std::f64::consts::PI / 6.0, floor: 0.0 }),+ boundary_tol: None,+ };let mut seen = std::collections::HashSet::new();let sides: usize = cyl.solid@@ -217,7 +222,7 @@ mod tests {let Ok(pin) = crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 6.0) else { panic!("pin") };let Ok(cross) = crate::cylinder(Vec3::new(5.0, -1.0, 2.0), Vec3::Y, 1.0, 12.0) else { panic!("cross") };let Ok(Some(body)) = crate::boolean(&pin, &cross, crate::BoolOp::Cut) else { panic!("cut") };- let rules = Rules { tol: 0.01, max_len: f64::INFINITY, turn: None };+ let rules = Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None };let surfaces: Vec<EvalSurface> = body.solid.face_iter().filter_map(|f| super::super::surface::eval_surface(&f.surface())).collect();let (mut edges, mut checked) = (0, 0);let mut seen = std::collections::HashSet::new();diff --git a/crates/kernel/src/tess/fallback.rs b/crates/kernel/src/tess/fallback.rsnew file mode 100644index 0000000000..4a6c59f14c--- /dev/null+++ b/crates/kernel/src/tess/fallback.rs@@ -0,0 +1,112 @@+//! The last resort for a face the planner cannot plan however finely its edges are divided: a+//! leftover of the file's own modelling, such as a cusp where two edges leave a point at a zero+//! angle, a sliver whose two sides sag across each other, or a small cap round a pole. Its+//! boundary is filled flat, so the rest of the body keeps its plan rather than the whole body+//! falling back to the reference mesh.+//!+//! The boundary nodes (the shared edge nodes, so the face still meets its neighbours exactly)+//! are laid onto the plane that best fits them and triangulated there (see `cdt::triangulate`):+//! every boundary side is kept as a constraint unless it crosses one already kept (the defect+//! itself), and a triangle is in the face when it lies inside an odd number of loops. The fill is+//! kept only where it stays within the chord tolerance of the surface, so a real curved face is+//! left to the body's reference mesh. The triangles turn the way the surface does, and each node+//! keeps its parameters on the surface for its normal.++use solidcraft_geom::tess::{EvalSurface, FacePlan};+use solidcraft_geom::{Plane, Vec3};++use super::{cdt, uv};++/// Most boundary nodes a face is filled at.+const MAX_NODES: usize = 50_000;+/// Nodes the surface's normal is sampled at to find which way it faces.+const NORMAL_SAMPLES: usize = 16;++/// The face `fi` of surface `s`, bounded by the loops `loops` (in space), filled flat; `None`+/// when its nodes do not lie on the surface within `accept`, span no plane, enclose nothing, or+/// the flat fill strays from the surface by more than the chord tolerance `tol` (a real curved+/// face, which the body's reference mesh draws better).+pub(crate) fn fill(fi: usize, s: &EvalSurface, loops: &[Vec<Vec3>], accept: f64, tol: f64) -> Option<FacePlan> {+ let fixed: Vec<Vec3> = loops.iter().flatten().copied().collect();+ if fixed.len() < 3 || fixed.len() > MAX_NODES {+ return None;+ }+ // Each node's parameters, for its normal (a projection from the previous node's).+ let dom = uv::domain(s);+ let mut params: Vec<[f64; 2]> = Vec::with_capacity(fixed.len());+ let mut ranges = Vec::with_capacity(loops.len());+ for l in loops {+ let start = params.len();+ let mut prev = None;+ for p in l {+ let q = uv::project(s, &dom, *p, prev, accept)?;+ params.push(q);+ prev = Some(q);+ }+ ranges.push(start..params.len());+ }+ // The plane: the loops' area vector (holes count against the outer loop) through their+ // centroid.+ let normal = loops.iter().fold(Vec3::ZERO, |n, l| n + crate::plane_fit::loop_area(l));+ let centre = fixed.iter().fold(Vec3::ZERO, |c, p| c + *p) * (1.0 / fixed.len() as f64);+ let plane = Plane::from_normal(centre, normal)?;+ let flat: Vec<[f64; 2]> = fixed.iter().map(|p| plane.to_local(*p)).map(|q| [q.x, q.y]).collect();+ let fill = cdt::Fill { seeds: &[], refine: None, shape: false, lenient: true };+ let (_, mut triangles) = cdt::triangulate(&flat, &ranges, fill)?;+ if triangles.is_empty() {+ return None;+ }+ // Flat only where flat is close enough: each triangle's middle within the chord tolerance of+ // the surface (found from its first corner's parameters).+ let off = |t: &[u32; 3]| -> Option<f64> {+ let [a, b, c] = t.map(|i| fixed.get(i as usize).copied());+ let mid = (a? + b? + c?) * (1.0 / 3.0);+ let q = uv::project(s, &dom, mid, params.get(t[0] as usize).copied(), f64::INFINITY)?;+ Some(s.derivs(q[0], q[1])?.0.dist(mid))+ };+ if !triangles.iter().all(|t| off(t).is_some_and(|d| d <= tol)) {+ return None;+ }+ // Counter-clockwise about the plane's normal; turned over where the surface faces the other way.+ let step = (params.len() / NORMAL_SAMPLES).max(1);+ let along: f64 = params.iter().step_by(step).filter_map(|q| s.derivs(q[0], q[1])).map(|(_, su, sv)| su.cross(sv).dot(plane.normal())).sum();+ if along < 0.0 {+ for t in &mut triangles {+ t.swap(1, 2);+ }+ }+ Some(FacePlan { face: u32::try_from(fi).unwrap_or(u32::MAX), surface: None, uv: params, fixed, normals: Vec::new(), flip: false, triangles })+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A plane face whose right side folds back over itself at a zero angle (a cusp): no side+ /// crossing another may be kept, yet the face is filled and turns the plane's way.+ #[test]+ fn a_cusp_is_filled_the_surfaces_way() {+ let s = EvalSurface::Plane { origin: Vec3::ZERO, du: Vec3::X, dv: Vec3::Y };+ let corners = [[0.0, 0.0], [4.0, 0.0], [4.0, 3.0], [3.0, 4.2], [3.8, 3.6], [0.0, 4.0]];+ let l: Vec<Vec3> = corners.iter().map(|q| Vec3::new(q[0], q[1], 0.0)).collect();+ let Some(f) = fill(0, &s, &[l], 1e-9, 1e-9) else { panic!("filled") };+ assert!(!f.triangles.is_empty());+ let area: f64 = f+ .triangles+ .iter()+ .map(|t| {+ let [a, b, c] = t.map(|i| f.fixed[i as usize]);+ (b - a).cross(c - a).z * 0.5+ })+ .sum();+ assert!(area > 14.0 && area < 16.5, "area {area}");+ assert_eq!(f.uv.len(), f.fixed.len());+ }++ #[test]+ fn a_boundary_enclosing_nothing_is_not_filled() {+ let s = EvalSurface::Plane { origin: Vec3::ZERO, du: Vec3::X, dv: Vec3::Y };+ let l = vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(2.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0)];+ assert!(fill(0, &s, &[l], 1e-3, 1e-3).is_none());+ }+}diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rsindex 8d87a199bb..63dd8c8353 100644--- a/crates/kernel/src/tess/mod.rs+++ b/crates/kernel/src/tess/mod.rs@@ -21,6 +21,7 @@ pub(crate) mod collar;pub(crate) mod coons;pub(crate) mod cutgrid;pub(crate) mod edges;+pub(crate) mod fallback;pub(crate) mod grid;pub(crate) mod motorcycle;pub(crate) mod pieces;@@ -45,6 +46,8 @@ pub struct PlanStats {pub planar: usize,pub structured: usize,pub delaunay: usize,+ /// Faces no method could plan, filled flat from their boundary nodes.+ pub filled: usize,}/// Curved faces from which their sizes are worked out on the worker pool.@@ -61,6 +64,15 @@ const PARALLEL_EDGES: usize = 256;const MAX_LINES: usize = 1024;/// Most points Ruppert refinement may add to one face, beyond its seeds.const MAX_REFINE: usize = 20_000;+/// Two boundary nodes this close together on the surface (mm) are one node. Far below any+/// spacing a mesh can carry, and far above the parameters a projection tells apart. See+/// [`drop_collapsed`].+const SAME_NODE: f64 = 1e-6;+/// How far a face's boundary may lie off its surface and still be planned on it, as a fraction of+/// the body's extent, at every display quality (ten chord tolerances at Normal).+const ON_SURFACE: f64 = 1e-2;+/// How much finer a refused face's edges are divided, retry by retry.+const REFINE_STEPS: [f64; 2] = [3.0, 10.0];fn unsupported(what: impl std::fmt::Display) -> KernelError {KernelError::Failed(format!("not supported yet: tessellation: {what}"))@@ -68,10 +80,13 @@ fn unsupported(what: impl std::fmt::Display) -> KernelError {/// Plan the display tessellation of `solid` with chord tolerance `tol` and, when given, a/// facet angle no facet may turn more than (where it sags above the angle's floor).-pub(crate) fn plan(solid: &Solid, tol: f64, turn: Option<size::Turn>) -> Result<(TessPlan, PlanStats)> {+/// `boundary_tol`: how far the body's boundaries may lie off their surfaces (mm) as the file it+/// was read from declares, `None` for a body this kernel built (see+/// [`crate::body::Body::boundary_tol`]).+pub(crate) fn plan(solid: &Solid, tol: f64, turn: Option<size::Turn>, boundary_tol: Option<f64>) -> Result<(TessPlan, PlanStats)> {let faces: Vec<&mt::Face> = solid.face_iter().collect();let (edges, edge_faces) = edge_order(faces.iter().copied());- let rules = size::Rules::new(tol, size::extent(solid.vertex_iter().map(|v| crate::body::from_p3(v.point()))), turn);+ let rules = size::Rules::new(tol, size::extent(solid.vertex_iter().map(|v| crate::body::from_p3(v.point()))), turn, boundary_tol);// Each face's surface and target side length, then every edge once at the smaller size of// its faces; faces then read their nodes. A planar face costs microseconds and a curved// one about a hundred, so the pool is used only where curved faces (or intersection@@ -94,30 +109,20 @@ pub(crate) fn plan(solid: &Solid, tol: f64, turn: Option<size::Turn>) -> Result<nodes.insert(e.id(), n?);}relax_crowded_faces(&faces, &jobs, &rules, &mut nodes);- let oriented = |e: &mt::Edge| -> Option<Vec<Vec3>> {- let mut pts = nodes.get(&e.id())?.points.clone();- if !e.orientation() {- pts.reverse();- }- Some(pts)- };+ divide_collapsed_faces(&faces, &jobs, &rules, &mut nodes);let indexed: Vec<(usize, &mt::Face)> = faces.iter().copied().enumerate().collect();- let planned = crate::par::map("face tessellation", &indexed, curved >= PARALLEL_FACES, |(fi, face)| {- let fi = *fi;- let (eval, size) = match sized.get(fi) {- Some((Some(eval), Some(size))) => (eval.clone(), *size),- _ => return Err(unsupported(format!("face {fi}: surface not evaluable"))),- };- // Boundary nodes, loop by loop (each edge's last node is the next edge's first), with- // their parameters on this face where the edge knows them (an intersection edge on- // this face's surface).+ // A face's boundary nodes, loop by loop (each edge's last node is the next edge's first),+ // with their parameters on the face's surface where the edge knows them (an intersection+ // edge on this face's surface).+ type Boundary = (Vec<Vec<Vec3>>, Vec<Vec<Option<[f64; 2]>>>);+ let boundary = |face: &mt::Face, eval: &EvalSurface, nodes: &HashMap<mt::EdgeID, edges::Nodes>| -> Result<Boundary> {let mut loops3: Vec<Vec<Vec3>> = Vec::new();let mut known: Vec<Vec<Option<[f64; 2]>>> = Vec::new();for wire in face.absolute_boundaries() {let (mut pts, mut uvs) = (Vec::new(), Vec::new());for e in wire.edge_iter() {let n = nodes.get(&e.id()).ok_or_else(|| unsupported("edge without nodes"))?;- let (mut ep, mut eq) = (n.points.clone(), n.params_on(&eval).unwrap_or_else(|| vec![None; n.points.len()]));+ let (mut ep, mut eq) = (n.points.clone(), n.params_on(eval).unwrap_or_else(|| vec![None; n.points.len()]));if !e.orientation() {ep.reverse();eq.reverse();@@ -132,15 +137,108 @@ pub(crate) fn plan(solid: &Solid, tol: f64, turn: Option<size::Turn>) -> Result<known.push(uvs);}}+ Ok((loops3, known))+ };+ // A plan in the surface's orientation turned the face's way.+ let oriented_face = |face: &mt::Face, fp: FacePlan| FacePlan {+ flip: !face.orientation(),+ triangles: if face.orientation() { fp.triangles } else { fp.triangles.into_iter().map(|[a, b, c]| [a, c, b]).collect() },+ ..fp+ };+ let surface_of = |fi: usize| match sized.get(fi) {+ Some((Some(eval), Some(size))) => Ok((eval.clone(), *size)),+ _ => Err(unsupported(format!("face {fi}: surface not evaluable"))),+ };+ // One face, from the edge nodes as they are and with the rules for its level of detail.+ let plan_one = |fi: usize, face: &mt::Face, nodes: &HashMap<mt::EdgeID, edges::Nodes>, rules: &size::Rules| {+ let (eval, size) = surface_of(fi)?;+ let (loops3, known) = boundary(face, &eval, nodes)?;let mut stats = PlanStats::default();- let fp = plan_face(fi, &eval, &loops3, &known, &rules, size, &mut stats)?;- let fp = FacePlan {- flip: !face.orientation(),- triangles: if face.orientation() { fp.triangles } else { fp.triangles.into_iter().map(|[a, b, c]| [a, c, b]).collect() },- ..fp+ let replan = |stats: &mut PlanStats| match plan_face(fi, &eval, &loops3, &known, rules, size, stats) {+ Ok(fp) => Ok(fp),+ // A boundary that doubles straight back on itself (a zero-width slit in the face,+ // which some STEP writers leave where two surfaces were trimmed apart) encloses no+ // area but crosses itself in (u, v). Dropping the slits leaves the same face.+ Err(first) => {+ let (slit3, slitq) = drop_slits(&loops3, &known, rules.tol * 1e-2);+ if slit3 == loops3 {+ return Err(first);+ }+ // Nothing left but slits: a sliver face (two edges between the same two vertices,+ // as STEP files write one) encloses no area, and the faces on either side already+ // meet along its nodes.+ if slit3.iter().all(|l| l.len() < 3) {+ return Ok(FacePlan { face: u32::try_from(fi).unwrap_or(u32::MAX), ..FacePlan::default() });+ }+ *stats = PlanStats::default();+ plan_face(fi, &eval, &slit3, &slitq, rules, size, stats).map_err(|_| first)+ }};- Ok((fp, eval, stats))- });+ let fp = replan(&mut stats)?;+ Ok((oriented_face(face, fp), eval, stats))+ };+ let mut planned = crate::par::map("face tessellation", &indexed, curved >= PARALLEL_FACES, |(fi, face)| plan_one(*fi, face, &nodes, &rules));+ // A face refused at this level of detail (a boundary that comes out degenerate, or that a+ // triangulation cannot follow, between nodes too far apart) has its edges divided again,+ // finer, and it and the faces beside those edges, which share their nodes, are planned+ // again from them.+ if planned.iter().any(Result::is_err) {+ let index_of: HashMap<mt::EdgeID, usize> = edges.iter().enumerate().map(|(i, e)| (e.id(), i)).collect();+ let face_edges: Vec<Vec<usize>> = faces+ .iter()+ .map(|f| f.absolute_boundaries().iter().flat_map(|w| w.edge_iter().filter_map(|e| index_of.get(&e.id()).copied())).collect())+ .collect();+ let mut finer: HashMap<usize, size::Rules> = HashMap::new();+ for factor in REFINE_STEPS {+ let refused: Vec<usize> = planned.iter().enumerate().filter(|(_, r)| r.is_err()).map(|(i, _)| i).collect();+ if refused.is_empty() {+ break;+ }+ let fine = rules.finer(factor);+ let mut touched: Vec<usize> = refused.iter().filter_map(|f| face_edges.get(*f)).flatten().copied().collect();+ touched.sort_unstable();+ touched.dedup();+ let resampled = crate::par::map("edge nodes", &touched, touched.len() >= PARALLEL_EDGES, |i| {+ Ok(jobs.get(*i).map(|(e, h)| (e.id(), edges::sample_edge(e, &fine, *h / factor))))+ });+ for (id, n) in resampled.into_iter().flatten().flatten() {+ nodes.insert(id, n);+ }+ finer.extend(refused.iter().map(|f| (*f, fine)));+ // The faces sharing a divided edge read its new nodes.+ let mut again: Vec<usize> = touched.iter().filter_map(|i| edge_faces.get(*i)).flatten().copied().collect();+ again.sort_unstable();+ again.dedup();+ let again: Vec<(usize, &mt::Face)> = again.into_iter().filter_map(|f| faces.get(f).map(|face| (f, *face))).collect();+ let results = crate::par::map("face tessellation", &again, again.len() >= PARALLEL_FACES, |(fi, face)| {+ plan_one(*fi, face, &nodes, finer.get(fi).unwrap_or(&rules))+ });+ for ((f, _), r) in again.iter().zip(results) {+ if let Some(slot) = planned.get_mut(*f) {+ *slot = r;+ }+ }+ }+ }+ // A face refused however finely its edges are divided is filled flat from its boundary+ // nodes (see `fallback`), so the rest of the body keeps its plan.+ for (fi, slot) in planned.iter_mut().enumerate() {+ if slot.is_ok() {+ continue;+ }+ let (Some(face), Ok((eval, _))) = (faces.get(fi), surface_of(fi)) else { continue };+ let Ok((loops3, _)) = boundary(face, &eval, &nodes) else { continue };+ if let Some(fp) = fallback::fill(fi, &eval, &loops3, off_surface(&rules), rules.tol) {+ *slot = Ok((oriented_face(face, fp), eval, PlanStats { filled: 1, ..PlanStats::default() }));+ }+ }+ let oriented = |e: &mt::Edge| -> Option<Vec<Vec3>> {+ let mut pts = nodes.get(&e.id())?.points.clone();+ if !e.orientation() {+ pts.reverse();+ }+ Some(pts)+ };let mut plan = TessPlan::default();let mut stats = PlanStats::default();for r in planned {@@ -151,6 +249,7 @@ pub(crate) fn plan(solid: &Solid, tol: f64, turn: Option<size::Turn>) -> Result<stats.planar += s.planar;stats.structured += s.structured;stats.delaunay += s.delaunay;+ stats.filled += s.filled;}plan.edges = edges.iter().filter_map(oriented).collect();plan.edge_faces = edge_faces.into_iter().map(|fs| fs.into_iter().map(|f| u32::try_from(f).unwrap_or(u32::MAX)).collect()).collect();@@ -222,6 +321,151 @@ fn relax_crowded_faces(faces: &[&mt::Face], jobs: &[(&mt::Edge, f64)], rules: &s}}+/// Every loop with its zero-width slits removed: wherever the boundary steps out to a node and+/// straight back to where it came from, the pair is dropped. A slit encloses no area, so the+/// face is the same without it, and without it the boundary no longer runs along itself. The+/// two sides need only agree within `eps` (a hundredth of the chord tolerance): a STEP writer+/// may draw them as two curves a few nanometres apart, which no mesh could tell apart anyway.+fn drop_slits(loops3: &[Vec<Vec3>], known: &[Vec<Option<[f64; 2]>>], eps: f64) -> (Vec<Vec<Vec3>>, Vec<Vec<Option<[f64; 2]>>>) {+ /// Slits dropped from one loop before giving up (the search is a scan per slit).+ const MAX_SLITS: usize = 4096;+ let mut out3: Vec<Vec<Vec3>> = Vec::with_capacity(loops3.len());+ let mut outq: Vec<Vec<Option<[f64; 2]>>> = Vec::with_capacity(loops3.len());+ for (li, pts) in loops3.iter().enumerate() {+ let mut pts = pts.clone();+ let mut qs = known.get(li).cloned().unwrap_or_else(|| vec![None; pts.len()]);+ qs.resize(pts.len(), None);+ for _ in 0..MAX_SLITS {+ let n = pts.len();+ if n < 3 {+ break;+ }+ let same = |a: usize, b: usize| pts.get(a).zip(pts.get(b)).is_some_and(|(p, q)| p.dist(*q) <= eps);+ let tip = (0..n).find(|&k| same((k + n - 1) % n, (k + 1) % n));+ let Some(k) = tip else { break };+ // Drop the tip and the node that repeats the one before it.+ let mut drop = [k, (k + 1) % n];+ drop.sort_unstable();+ for &i in drop.iter().rev() {+ if i < pts.len() {+ pts.remove(i);+ }+ if i < qs.len() {+ qs.remove(i);+ }+ }+ }+ if pts.len() >= 2 {+ out3.push(pts);+ outq.push(qs);+ }+ }+ (out3, outq)+}++/// Boundary nodes a loop keeps only one of: nodes whose parameters land on the node before them.+///+/// A boundary that runs a little off its surface (a STEP file writes its curves and surfaces to+/// its own uncertainty, so an edge may lie micrometres off the face it bounds) projects onto the+/// nearest surface point. Around a convex corner of the surface every point of such an edge is+/// nearest that corner, so a whole run of nodes comes out with the corner's parameters. The finer+/// the chord tolerance, the more nodes the run holds, and a boundary that repeats a point in+/// (u, v) encloses no area there and cannot be triangulated (#1721).+///+/// One node stands for the run. The nodes dropped are nearer to it than `SAME_NODE` on the+/// surface, so the face is the same without them.+fn drop_collapsed(l: &mut seam::Loop, speed: [f64; 2]) {+ let eps = |d: usize| {+ let s = speed.get(d).copied().unwrap_or(1.0);+ if s.is_finite() && s > 0.0 { SAME_NODE / s } else { 0.0 }+ };+ let (eu, ev) = (eps(0), eps(1));+ let same = |a: &[f64; 2], b: &[f64; 2]| (a[0] - b[0]).abs() <= eu && (a[1] - b[1]).abs() <= ev;+ let (mut uv, mut pts) = (Vec::with_capacity(l.uv.len()), Vec::with_capacity(l.pts.len()));+ for (q, p) in l.uv.iter().zip(&l.pts) {+ if uv.last().is_some_and(|last| same(last, q)) {+ continue;+ }+ uv.push(*q);+ pts.push(*p);+ }+ // The loop is cyclic: its last node may land on its first.+ while uv.len() > 2 && uv.last().zip(uv.first()).is_some_and(|(a, b)| same(a, b)) {+ uv.pop();+ pts.pop();+ }+ l.uv = uv;+ l.pts = pts;+}++/// Bring every loop of a face into the same period as its outer boundary. A loop is projected+/// on its own, and a periodic surface repeats, so a hole can come out a whole turn away from the+/// boundary it lies in — where it no longer cuts the face, and the face is drawn over its hole.+fn align_periods(loops: &mut [seam::Loop], dom: &uv::Domain) {+ for d in 0..2 {+ let Some(per) = dom.period.get(d).copied().flatten().filter(|p| *p > 0.0) else { continue };+ let middle = |l: &seam::Loop| {+ let (lo, hi) = l.uv.iter().filter_map(|q| q.get(d)).fold((f64::MAX, f64::MIN), |(a, b), x| (a.min(*x), b.max(*x)));+ 0.5 * (lo + hi)+ };+ let Some(outer) = loops.first().map(middle) else { continue };+ if !outer.is_finite() {+ continue;+ }+ for l in loops.iter_mut().skip(1) {+ let shift = ((outer - middle(l)) / per).round() * per;+ if shift != 0.0 && shift.is_finite() {+ for q in l.uv.iter_mut() {+ if let Some(x) = q.get_mut(d) {+ *x += shift;+ }+ }+ }+ }+ }+}++/// Nodes a face's boundary needs before it can hold a triangle.+const MIN_BOUNDARY_NODES: usize = 3;++/// A face whose whole boundary comes to fewer than three nodes has no triangle to stand on: it is+/// a sliver no wider than the tolerance (a chord with the shallow arc beside it, which the edge+/// sampler rightly leaves as one segment each). Its edges are sampled again, halved until the+/// boundary has nodes enough, so the sliver is drawn instead of failing the whole body's plan.+/// The nodes stay shared, so the faces beside it follow the same points.+fn divide_collapsed_faces(faces: &[&mt::Face], jobs: &[(&mt::Edge, f64)], rules: &size::Rules, nodes: &mut HashMap<mt::EdgeID, edges::Nodes>) {+ /// Halvings before giving up (a boundary of two edges reaches four nodes in one).+ const MAX_HALVINGS: usize = 8;+ let h_of: HashMap<mt::EdgeID, (&mt::Edge, f64)> = jobs.iter().map(|(e, h)| (e.id(), (*e, *h))).collect();+ for f in faces {+ let ids: Vec<mt::EdgeID> = f.absolute_boundaries().iter().flat_map(|w| w.edge_iter().map(|e| e.id())).collect();+ let count = |nodes: &HashMap<mt::EdgeID, edges::Nodes>| {+ ids.iter().map(|id| nodes.get(id).map_or(0, |n| n.points.len().saturating_sub(1))).sum::<usize>()+ };+ if count(nodes) >= MIN_BOUNDARY_NODES {+ continue;+ }+ for _ in 0..MAX_HALVINGS {+ for id in &ids {+ let Some((e, h)) = h_of.get(id) else { continue };+ let longest =+ nodes.get(id).map_or(0.0, |n| n.points.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?))).fold(0.0, f64::max));+ let finer = if longest > 0.0 { (longest * 0.5).min(*h) } else { *h };+ nodes.insert(*id, edges::sample_edge(e, rules, finer));+ }+ if count(nodes) >= MIN_BOUNDARY_NODES {+ break;+ }+ }+ }+}++/// How far a boundary node may lie off its surface and still be projected onto it (see the note+/// in [`plan_face`]).+fn off_surface(rules: &size::Rules) -> f64 {+ (rules.extent * ON_SURFACE).max(rules.boundary_tol.unwrap_or(0.0)).max(1e-6)+}+/// One face: boundary loops in 3D (shared edge nodes) to parameters and triangles./// `size`: the face's target side length (mm) and the surface's mean speed along u and v.fn plan_face(@@ -236,7 +480,12 @@ fn plan_face(let tol = rules.tol;let (h, speed) = size;let dom = uv::domain(s);- let accept = (tol * 10.0).max(1e-6);+ // How far a boundary node may lie off its surface and still be projected onto it: a property+ // of the body, not of the mesh asked for, so a finer chord tolerance never refuses a boundary+ // a coarser one accepted, and zooming in never drops a face (#1721). A hundredth of the body,+ // or more where the file it was read from declares more; a file's declared accuracy never+ // lowers it, since writers' edges stray farther from their surfaces than they declare.+ let accept = off_surface(rules);let fail = |why: &str| unsupported(format!("face {fi}: {why}"));// Project every loop, unwrapping periodic parameters along it.let mut projected: Vec<seam::Loop> = Vec::with_capacity(loops3.len());@@ -259,8 +508,16 @@ fn plan_face(luv.push(q);prev = Some(q);}- projected.push(seam::Loop { uv: luv, pts: pts.clone() });+ let mut l = seam::Loop { uv: luv, pts: pts.clone() };+ drop_collapsed(&mut l, speed);+ for (d, per) in dom.period.iter().enumerate() {+ if let Some(per) = per {+ seam::close_through_pole(s, &mut l, d, *per);+ }+ }+ projected.push(l);}+ align_periods(&mut projected, &dom);// A loop that winds around a periodic direction does not close in (u, v): the face is cut// along a parameter line into one period (a seamless cylinder face, a helical trim).let wound: Vec<usize> = (0..2).filter(|&d| dom.period[d].is_some_and(|per| seam::winds(&projected, d, per))).collect();@@ -309,7 +566,7 @@ fn plan_face(}ranges.push(start..uvs.len());}- if uvs.len() < 3 {+ if uvs.len() < MIN_BOUNDARY_NODES {return Err(fail("degenerate boundary"));}let mut bbox = [(f64::MAX, f64::MIN); 2];@@ -326,7 +583,7 @@ fn plan_face(let seeds = cdt::lattice(bbox, [h / speed[0], h / speed[1]], &polys, speed);let eval = |u: f64, v: f64| s.derivs(u, v).map(|(p, su, sv)| (p, su.cross(sv).normalized()));let sag = cdt::Sag { eval: &eval, tol, h, turn: rules.turn, scale: speed };- let fill = cdt::Fill { seeds: &seeds, refine: Some((sag, MAX_REFINE)), shape: !matches!(s, EvalSurface::Plane { .. }) };+ let fill = cdt::Fill { seeds: &seeds, refine: Some((sag, MAX_REFINE)), shape: !matches!(s, EvalSurface::Plane { .. }), lenient: false };cdt::triangulate(&uvs, &ranges, fill).ok_or_else(|| fail("boundary crosses itself"))};// Planar and curved faces alike: a structured grid where the boundary runs along the@@ -547,7 +804,7 @@ fn plan_pieces(f: &Region) -> Option<(Vec<[f64; 2]>, Vec<[u32; 3]>)> {let seeds = cdt::lattice(bbox, [f.h / f.speed[0], f.h / f.speed[1]], &polys, f.speed);let eval = |u: f64, v: f64| s.derivs(u, v).map(|(p, su, sv)| (p, su.cross(sv).normalized()));let sag = cdt::Sag { eval: &eval, tol: f.rules.tol, h: f.h, turn: f.rules.turn, scale: f.speed };- cdt::triangulate(&luv, &ranges, cdt::Fill { seeds: &seeds, refine: Some((sag, MAX_REFINE)), shape: true })+ cdt::triangulate(&luv, &ranges, cdt::Fill { seeds: &seeds, refine: Some((sag, MAX_REFINE)), shape: true, lenient: false })})?;let (lextra, ltris) = local;let base = u32::try_from(n + extra.len()).ok()?;diff --git a/crates/kernel/src/tess/seam.rs b/crates/kernel/src/tess/seam.rsindex 13b516158d..1982cb67c8 100644--- a/crates/kernel/src/tess/seam.rs+++ b/crates/kernel/src/tess/seam.rs@@ -37,6 +37,41 @@ pub(crate) fn winds(loops: &[Loop], d: usize, per: f64) -> bool {loops.iter().any(|l| drift(l, d, per).abs() > per * 0.5)}+/// A loop through a pole of the closed direction `d` (a cone's apex or a sphere's pole on the+/// boundary): the parameter along `d` is free there, so the step into or out of the pole may be+/// any length. Unwrapped to the nearest copy at every step, a sector wider than half a turn, or+/// a cone face written as its rim, the seam up to the apex and the seam back (as STEP files+/// write a pointed end, a screw's tip), seems to wind around the surface, and the face cannot+/// be cut along a seam it does not have. The step out of the pole is made the one that closes+/// the loop. A loop that closes already, has no pole or passes more than one stays as it is.+pub(crate) fn close_through_pole(s: &EvalSurface, l: &mut Loop, d: usize, per: f64) {+ let w = drift(l, d, per);+ let n = l.uv.len();+ if w.abs() <= per * 0.5 || n < 3 || l.pts.len() != n {+ return;+ }+ let pole: Vec<bool> = l.uv.iter().map(|q| super::uv::degenerate(s, *q, d)).collect();+ let Some(k) = pole.iter().position(|p| *p) else { return };+ // The node the loop leaves the pole for: the loop is turned to end there, so the step that+ // closes it is an ordinary one, and the step from the pole takes what is left. A loop+ // through a pole twice is left alone.+ let Some(out) = (1..n).map(|i| (k + i) % n).find(|&i| !pole.get(i).copied().unwrap_or(true)) else { return };+ if pole.iter().enumerate().any(|(i, p)| *p && (i + n - out) % n < (k + n - out) % n) {+ return;+ }+ let start = (out + 1) % n;+ l.uv.rotate_left(start);+ l.pts.rotate_left(start);+ // Unwrapped again from the new start; the last node, where the loop leaves the pole, is+ // taken next to the first instead of next to the pole.+ for i in 1..n {+ let near = if i + 1 == n { l.uv.first() } else { l.uv.get(i - 1) }.map(|q| q[d]);+ if let (Some(near), Some(q)) = (near, l.uv.get_mut(i)) {+ q[d] = super::uv::unwrap(q[d], near, Some(per));+ }+ }+}+/// A point where the boundary crosses a cut line: its place along the line, its 3D point, and/// whether the face lies above it (towards larger parameters across the line) or below.#[derive(Clone, Copy, Debug)]@@ -350,6 +385,15 @@ fn seam_nodes(s: &EvalSurface, swap: bool, x: f64, y0: f64, y1: f64, rules: &RulSome(inner.iter().map(|&y| (y, s.eval(uv(y)[0], uv(y)[1]).0)).collect())}+/// Whether a face of `solid` lies on a B-spline surface that joins itself (a lofted tube).+/// Truck meshes a face in its surface's parameters and treats only a revolved surface's+/// rotation as periodic, so a face that runs across such a join comes out folded over itself or+/// with a hole in it. The reference mesh of such a body is made from the display plan,+/// which knows the join is periodic.+pub(crate) fn closes_on_itself(solid: &crate::body::Solid) -> bool {+ solid.face_iter().any(|f| matches!(super::surface::eval_surface(&f.surface()), Some(EvalSurface::Nurbs { closed, .. }) if closed[0] || closed[1]))+}+/// Whether a face of `solid` lies on a surface of revolution and has a boundary loop turning/// more than once around its axis (a helical trim). Truck's mesher cannot mesh such a face (its/// triangles cut across the solid), so the reference mesh is made from the display plan instead.diff --git a/crates/kernel/src/tess/size.rs b/crates/kernel/src/tess/size.rsindex 9cbad54c3c..357a5b2a5d 100644--- a/crates/kernel/src/tess/size.rs+++ b/crates/kernel/src/tess/size.rs@@ -55,14 +55,35 @@ impl Turn {pub(crate) struct Rules {pub tol: f64,pub max_len: f64,+ /// The body's extent (see [`extent`]); 0 when it has none. Tolerances that measure the+ /// body's own geometry rather than the mesh are fractions of it.+ pub extent: f64,pub turn: Option<Turn>,+ /// How far the body's boundaries may lie off their surfaces (mm), as the file the body was+ /// read from declares; `None` for a body this kernel built (see+ /// [`crate::body::Body::boundary_tol`]). It raises the planner's bound (a hundredth of the+ /// extent) where it is larger, never lowers it.+ pub boundary_tol: Option<f64>,}impl Rules {- /// Rules for a body of extent `extent` (see [`extent`]).- pub(crate) fn new(tol: f64, extent: f64, turn: Option<Turn>) -> Rules {- let max_len = if extent.is_finite() && extent > 0.0 { extent * MAX_LEN_FRACTION } else { f64::INFINITY };- Rules { tol, max_len: max_len.max(tol), turn }+ /// The same rules with a chord tolerance `k` times finer.+ pub(crate) fn finer(self, k: f64) -> Rules {+ Rules { tol: self.tol / k, ..self }+ }++ /// Rules for a body of extent `extent` (see [`extent`]). `boundary_tol`: the body's declared+ /// off-surface budget (mm), `None` for a body this kernel built.+ pub(crate) fn new(tol: f64, extent: f64, turn: Option<Turn>, boundary_tol: Option<f64>) -> Rules {+ let sound = extent.is_finite() && extent > 0.0;+ let max_len = if sound { extent * MAX_LEN_FRACTION } else { f64::INFINITY };+ Rules {+ tol,+ max_len: max_len.max(tol),+ extent: if sound { extent } else { 0.0 },+ turn,+ boundary_tol: boundary_tol.filter(|t| t.is_finite() && *t > 0.0),+ }}/// The side length for a curvature `k` (1/mm): the chord sags at most the tolerance across@@ -172,21 +193,21 @@ mod tests {swap: false,};// A 20 mm body: sides from 1 mm (the floor, a quarter of the longest) to 4 mm.- let rules = Rules::new(0.01, 20.0, THIRTY);+ let rules = Rules::new(0.01, 20.0, THIRTY, None);let (h, speed) = face_size(&s, &super::super::uv::domain(&s), &rules);// r = 3: 30° of turn is 1.57 mm; the 0.01 mm sag chord is √(8·3·0.01) = 0.49 mm, times the// aspect, unless that is under the floor.assert!((h - (ASPECT * (8.0 * 3.0 * 0.01f64).sqrt()).max(20.0 * MAX_LEN_FRACTION * MIN_LEN_FRACTION)).abs() < 0.01, "{h}");assert!((speed[0] - 40.0).abs() < 1e-6 && (speed[1] - 3.0).abs() < 1e-6, "{speed:?}");// Coarser: the turn limit governs.- let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, THIRTY));+ let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, THIRTY, None));assert!((h - (ASPECT * 3.0 * std::f64::consts::PI / 6.0).max(100.0 * MAX_LEN_FRACTION * MIN_LEN_FRACTION)).abs() < 0.01, "{h}");// Without a facet angle the sag alone: √(8·3·0.5) = 3.46 mm, four times along.- let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, None));+ let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, None, None));assert!((h - ASPECT * (8.0 * 3.0 * 0.5f64).sqrt()).abs() < 0.01, "{h}");// A turn that sags below its floor does not divide.let floored = Some(Turn { angle: std::f64::consts::PI / 6.0, floor: 1.0 });- let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, floored));+ let (h, _) = face_size(&s, &super::super::uv::domain(&s), &Rules::new(0.5, 100.0, floored, None));assert!((h - ASPECT * (8.0 * 3.0 * 0.5f64).sqrt()).abs() < 0.01, "{h}");}@@ -197,10 +218,11 @@ mod tests {knots: [vec![0.0, 0.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]],count: [2, 2],ctrl: vec![[0.0, 0.0, 0.0, 1.0], [4.0, 0.0, 0.0, 1.0], [0.0, 3.0, 0.0, 1.0], [4.0, 3.0, z, 1.0]],+ closed: [false, false],};assert!(planar(&patch(0.0)));assert!(!planar(&patch(0.5)));- let rules = Rules::new(0.01, 100.0, THIRTY);+ let rules = Rules::new(0.01, 100.0, THIRTY, None);let (h, speed) = face_size(&patch(0.0), &super::super::uv::domain(&patch(0.0)), &rules);assert_eq!(h, rules.max_len);assert!((speed[0] - 4.0).abs() < 1e-9 && (speed[1] - 3.0).abs() < 1e-9, "{speed:?}");@@ -217,7 +239,7 @@ mod tests {transform: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],swap: false,};- let rules = Rules::new(0.1, 100.0, THIRTY);+ let rules = Rules::new(0.1, 100.0, THIRTY, None);let (h, _) = face_size(&s, &super::super::uv::domain(&s), &rules);assert!((h - rules.max_len * MIN_LEN_FRACTION).abs() < 1e-9, "{h}");}@@ -225,7 +247,7 @@ mod tests {#[test]fn a_plane_takes_the_longest_side() {let s = EvalSurface::Plane { origin: Vec3::ZERO, du: Vec3::X, dv: Vec3::Y };- let rules = Rules::new(0.01, 100.0, THIRTY);+ let rules = Rules::new(0.01, 100.0, THIRTY, None);assert_eq!(face_size(&s, &super::super::uv::domain(&s), &rules).0, 20.0);}}diff --git a/crates/kernel/src/tess/surface.rs b/crates/kernel/src/tess/surface.rsindex f263e34397..86b254fb42 100644--- a/crates/kernel/src/tess/surface.rs+++ b/crates/kernel/src/tess/surface.rs@@ -66,7 +66,39 @@ fn nurbs((pu, pv): (usize, usize), kv: &(mt::KnotVec, mt::KnotVec), rows: Vec<Vereturn None;}let knots = [knots(&kv.0)?, knots(&kv.1)?];- (knots[0].len() == nu + pu + 1 && knots[1].len() == nv + pv + 1).then_some(EvalSurface::Nurbs { degree: [pu, pv], knots, count: [nu, nv], ctrl })+ if !(knots[0].len() == nu + pu + 1 && knots[1].len() == nv + pv + 1) {+ return None;+ }+ let closed = [closed_along(0, &ctrl, [nu, nv], [pu, pv], &knots), closed_along(1, &ctrl, [nu, nv], [pu, pv], &knots)];+ Some(EvalSurface::Nurbs { degree: [pu, pv], knots, count: [nu, nv], ctrl, closed })+}++/// Does the surface join itself along direction `d` (a tube's way round)? Its knots there must+/// be clamped, so the ends of the range are the first and last rows of control points, and+/// those two rows must be the same points: the join is then the parameter line `d = end`, and+/// the direction is periodic.+fn closed_along(d: usize, ctrl: &[[f64; 4]], count: [usize; 2], degree: [usize; 2], knots: &[Vec<f64>; 2]) -> bool {+ let (n, p) = (count[d], degree[d]);+ if n < 2 {+ return false;+ }+ let Some(k) = knots.get(d) else { return false };+ let Some((&a, &b)) = k.first().zip(k.last()) else { return false };+ // Clamped: degree + 1 knots equal at each end, and a range to speak of.+ if !(b > a && k.iter().take(p + 1).all(|x| *x == a) && k.iter().rev().take(p + 1).all(|x| *x == b)) {+ return false;+ }+ // Control point `(i, j)` with `i` along u, as a point.+ let at =+ |i: usize, j: usize| ctrl.get(j * count[0] + i).and_then(|h| (h[3].abs() > 1e-300).then(|| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])));+ let along_d = |x: usize, t: usize| if d == 0 { at(x, t) } else { at(t, x) };+ let (mut extent, mut gap) = (0.0f64, 0.0f64);+ for t in 0..count[1 - d] {+ let (Some(first), Some(last)) = (along_d(0, t), along_d(n - 1, t)) else { return false };+ extent = extent.max(first.len()).max(last.len());+ gap = gap.max(first.dist(last));+ }+ gap <= 1e-9 * extent.max(1.0)}/// A profile curve in the evaluator's form (a line extends for ever, as truck's does).diff --git a/crates/kernel/src/tess/tests.rs b/crates/kernel/src/tess/tests.rsindex 5587fb7d67..c103a7f1f4 100644--- a/crates/kernel/src/tess/tests.rs+++ b/crates/kernel/src/tess/tests.rs@@ -27,7 +27,7 @@ fn assert_watertight(m: &Mesh, name: &str) {}fn plan_body(b: &Body, tol: f64) -> (Mesh, PlanStats) {- match plan(&b.solid, tol, Some(crate::tess::size::Turn { angle: crate::DISPLAY_ANGLE, floor: tol * 1e-3 })) {+ match plan(&b.solid, tol, Some(crate::tess::size::Turn { angle: crate::DISPLAY_ANGLE, floor: tol * 1e-3 }), b.boundary_tol) {Ok((p, stats)) => (p.evaluate(), stats),Err(e) => panic!("plan: {e}"),}@@ -94,7 +94,7 @@ fn a_box_is_a_regular_grid_on_every_face() {fn primitives_are_watertight_with_the_right_volume() {for tol in [0.05, 0.005] {let s = check("box", &ok(crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 6.0, 4.0))), tol, 240.0);- assert_eq!(s, PlanStats { planar: 6, structured: 0, delaunay: 0 });+ assert_eq!(s, PlanStats { planar: 6, structured: 0, delaunay: 0, filled: 0 });let s = check("cylinder", &ok(crate::cylinder(Vec3::new(1.0, 2.0, 3.0), Vec3::new(0.0, 1.0, 1.0), 2.5, 7.0)), tol, PI * 2.5 * 2.5 * 7.0);assert_eq!(s.delaunay, 0, "cylinder walls are structured");let s = check("torus", &ok(crate::torus(Vec3::ZERO, 6.0, 1.5)), tol, 2.0 * PI * PI * 6.0 * 1.5 * 1.5);@@ -176,7 +176,7 @@ fn render_wireframes() {let Ok(old) = body.tessellate(tol) else { panic!("reference") };let t_old = t0.elapsed().as_secs_f64() * 1e3;let t0 = std::time::Instant::now();- let new = match plan(&body.solid, tol, Some(crate::tess::size::Turn { angle: crate::DISPLAY_ANGLE, floor: tol * 1e-3 })) {+ let new = match plan(&body.solid, tol, Some(crate::tess::size::Turn { angle: crate::DISPLAY_ANGLE, floor: tol * 1e-3 }), body.boundary_tol) {Ok((p, st)) => Some((p.evaluate(), st)),Err(e) => {println!("{name}: no plan ({e})");@@ -296,3 +296,156 @@ fn trace_seeds_grade_from_one_end_to_the_other() {assert_eq!(even.len(), 3);assert!(graded([0.0, 0.0], [0.5, 0.0], 1.0, 1.0, 10.0, [1.0, 1.0], &|_, _| true).is_empty());}++/// A surface that joins itself along a direction is periodic there: its parameters repeat, so+/// the evaluator takes a parameter outside the range back into it. A boundary that runs across+/// the join is unwrapped past the range's end and must still land on the surface.+#[test]+fn a_closed_spline_surface_is_periodic_and_evaluates_outside_its_range() {+ use solidcraft_geom::tess::EvalSurface;+ // A five-sided tube: the control net's last column repeats its first.+ let corner = |k: usize| {+ let a = std::f64::consts::TAU * (k % 5) as f64 / 5.0;+ (10.0 * a.cos(), 10.0 * a.sin())+ };+ let mut ctrl = Vec::new();+ for j in 0..2 {+ for k in 0..=5 {+ let (x, y) = corner(k);+ ctrl.push([x, y, f64::from(j) * 8.0, 1.0]);+ }+ }+ let s = EvalSurface::Nurbs {+ degree: [1, 1],+ knots: [vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0], vec![0.0, 0.0, 1.0, 1.0]],+ count: [6, 2],+ ctrl,+ closed: [true, false],+ };+ let dom = uv::domain(&s);+ assert_eq!(dom.period, [Some(5.0), None]);+ assert_eq!(dom.range, [Some((0.0, 5.0)), Some((0.0, 1.0))]);+ // A parameter a whole range below the start is the same point as one inside it.+ for (a, b) in [(-0.5, 4.5), (-2.0, 3.0), (5.5, 0.5), (7.0, 2.0)] {+ let (Some(out), Some(inside)) = (s.derivs(a, 0.25), s.derivs(b, 0.25)) else { panic!("evaluates") };+ assert!(out.0.dist(inside.0) < 1e-12, "u = {a} and u = {b}: {:?} vs {:?}", out.0, inside.0);+ }+ // The same net left open is not periodic, and keeps truck's end-span extension outside it.+ let EvalSurface::Nurbs { degree, knots, count, ctrl, .. } = s else { panic!("nurbs") };+ let open = EvalSurface::Nurbs { degree, knots, count, ctrl, closed: [false, false] };+ assert_eq!(uv::domain(&open).period, [None, None]);+ let (Some(out), Some(inside)) = (open.derivs(-0.5, 0.25), open.derivs(4.5, 0.25)) else { panic!("evaluates") };+ assert!(out.0.dist(inside.0) > 1.0, "an open surface does not wrap");+}++/// Each loop of a face is projected on its own, so on a periodic surface a hole can come out a+/// whole turn away from the boundary that holds it. Every loop is brought into the outer+/// boundary's period, where the hole cuts the face again.+#[test]+fn holes_are_brought_into_the_outer_boundarys_period() {+ let tau = std::f64::consts::TAU;+ let at = |u: f64, v: f64| seam::Loop { uv: vec![[u, v], [u + 0.2, v], [u + 0.2, v + 0.2], [u, v + 0.2]], pts: vec![Vec3::ZERO; 4] };+ let dom = uv::Domain { range: [Some((0.0, 1.0)), Some((0.0, tau))], period: [None, Some(tau)] };+ let mut loops = vec![at(0.0, -tau), at(0.4, 1.5), at(0.6, 1.5 - tau)];+ align_periods(&mut loops, &dom);+ // The outer loop stays where it is; both holes land beside it, a whole turn moved or not.+ assert_eq!(loops[0].uv[0], [0.0, -tau]);+ assert!((loops[1].uv[0][1] - (1.5 - tau)).abs() < 1e-12, "{:?}", loops[1].uv[0]);+ assert!((loops[2].uv[0][1] - (1.5 - tau)).abs() < 1e-12, "{:?}", loops[2].uv[0]);+ // Nothing moves along a direction that does not repeat.+ assert_eq!(loops[1].uv[0][0], 0.4);+}++/// A boundary that steps out to a node and straight back encloses no area: the pair is dropped,+/// so what is left no longer runs along itself. The two sides need only agree within the given+/// distance — a STEP writer may draw them as two curves a hair apart.+#[test]+fn zero_width_slits_are_dropped_from_a_boundary() {+ let p = |x: f64| Vec3::new(x, 0.0, 0.0);+ // A square with a slit poked into it from the corner (2, 1): out to (2, 2) and back.+ let slit = vec![+ p(0.0),+ p(1.0),+ Vec3::new(2.0, 1.0, 0.0),+ Vec3::new(2.0, 2.0, 0.0),+ Vec3::new(2.0 + 1e-9, 1.0, 0.0),+ p(3.0),+ Vec3::new(3.0, 3.0, 0.0),+ Vec3::new(0.0, 3.0, 0.0),+ ];+ let (out, known) = drop_slits(&[slit], &[Vec::new()], 1e-6);+ assert_eq!(out.len(), 1);+ assert_eq!(out[0], vec![p(0.0), p(1.0), Vec3::new(2.0, 1.0, 0.0), p(3.0), Vec3::new(3.0, 3.0, 0.0), Vec3::new(0.0, 3.0, 0.0)]);+ assert_eq!(known[0].len(), out[0].len());+ // Too far apart to be one slit: the boundary is left as it is.+ let wide = vec![p(0.0), p(1.0), Vec3::new(2.0, 1.0, 0.0), Vec3::new(2.0, 2.0, 0.0), Vec3::new(2.5, 1.0, 0.0), p(3.0)];+ let kept = drop_slits(std::slice::from_ref(&wide), &[Vec::new()], 1e-6).0;+ assert_eq!(kept, vec![wide]);+}++/// A pointed end read back from STEP (a screw's tip, a cone): its cone face is written as the+/// rim, the seam up to the apex and the seam back, and a sector of one as its rim and two+/// sides meeting at the apex. Unwrapped to the nearest copy at every step, the jump at the+/// apex made such a loop seem to wind around the cone; the face could not be cut along a seam+/// it did not have, and the whole body lost its display plan.+#[test]+fn a_pointed_end_read_back_from_step_is_planned() {+ use solidcraft_geom::{Loop2, Plane, Region2, Vec2};+ let (r, tip, len) = (3.0, 4.0, 20.0);+ let Some(axis) = Plane::new(Vec3::ZERO, Vec3::X, Vec3::Z) else { panic!("plane") };+ let pts = [Vec2::new(0.0, 0.0), Vec2::new(r, tip), Vec2::new(r, len), Vec2::new(0.0, len)];+ for turn in [360.0f64, 300.0, 270.0, 200.0] {+ let region = Region2 { outer: Loop2::polygon(&pts), holes: vec![] };+ let Some(body) = ok(crate::revolve(&axis, &[region], Vec2::ZERO, Vec2::Y, turn.to_radians())).pop() else { panic!("revolve") };+ let imported = ok(crate::step_import(&ok(crate::step_export(&[&body], "pointed end"))));+ let Some(copy) = imported.bodies.first() else { panic!("no body") };+ let volume = std::f64::consts::PI * r * r * (len - tip + tip / 3.0) * turn / 360.0;+ check(&format!("pointed end turned {turn} deg"), ©.body, 0.02, volume);+ }+}++/// A point on a spline that turns many times (a thread's helical flank, as other CAD systems+/// write it to STEP, has hundreds of spans along the helix) is found from a hint a few turns+/// away: between 16 starts across the whole spline Newton settled on another turn, the point+/// was taken as off the surface and the body lost its display plan.+#[test]+fn a_point_on_a_long_helical_spline_projects() {+ let (turns, per_turn, pitch) = (40usize, 24usize, 0.5);+ let n = turns * per_turn + 1;+ let at = |i: usize, r: f64| {+ let t = std::f64::consts::TAU * i as f64 / per_turn as f64;+ [r * t.cos(), r * t.sin(), pitch * t / std::f64::consts::TAU, 1.0]+ };+ let mut ctrl: Vec<[f64; 4]> = Vec::with_capacity(2 * n);+ for i in 0..n {+ ctrl.push(at(i, 0.7));+ ctrl.push(at(i, 0.55));+ }+ let mut ku = vec![0.0; 3];+ ku.extend((1..n - 2).map(|i| i as f64 / (n - 2) as f64));+ ku.extend([1.0; 3]);+ let s = EvalSurface::Nurbs { degree: [2, 1], knots: [ku, vec![0.0, 0.0, 1.0, 1.0]], count: [n, 2], ctrl, closed: [false, false] };+ let dom = uv::domain(&s);+ for (target, hint) in [([0.5, 1.0], [0.488, 1.0]), ([0.2, 0.0], [0.23, 1.0]), ([0.9, 0.5], [0.1, 0.5])] {+ let Some((p, _, _)) = s.derivs(target[0], target[1]) else { panic!("evaluate") };+ let Some(q) = uv::project(&s, &dom, p, Some(hint), 1e-4) else { panic!("{target:?} from {hint:?}: not found") };+ let Some((back, _, _)) = s.derivs(q[0], q[1]) else { panic!("evaluate") };+ assert!(back.dist(p) <= 1e-4, "{target:?} from {hint:?}: {q:?} is {} away", back.dist(p));+ }+}++/// A sliver face as STEP files write one: two edges between the same two vertices, a rounding+/// apart, so its boundary runs out and back along itself. Its slits dropped, nothing is left to+/// bound a face (it is planned empty); a boundary enclosing anything keeps its loop.+#[test]+fn a_boundary_running_back_along_itself_is_all_slit() {+ let out: Vec<Vec3> = (0..5).map(|i| Vec3::new(f64::from(i), 0.5 * f64::from(i), 0.0)).collect();+ let mut sliver = out.clone();+ sliver.extend(out.iter().rev().skip(1).take(3).map(|p| *p + Vec3::new(0.0, 1e-14, 0.0)));+ let (left, _) = drop_slits(&[sliver], &[Vec::new()], 1e-9);+ assert!(left.iter().all(|l| l.len() < 3), "{left:?}");+ let mut lens = out.clone();+ lens.extend(out.iter().rev().skip(1).take(3).map(|p| *p + Vec3::new(0.0, 1e-3, 0.0)));+ let (kept, _) = drop_slits(std::slice::from_ref(&lens), &[Vec::new()], 1e-9);+ assert_eq!(kept, vec![lens]);+}diff --git a/crates/kernel/src/tess/uv.rs b/crates/kernel/src/tess/uv.rsindex 4e15853f3a..b74e7706ed 100644--- a/crates/kernel/src/tess/uv.rs+++ b/crates/kernel/src/tess/uv.rs@@ -19,9 +19,12 @@ pub(crate) fn domain(s: &EvalSurface) -> Domain {let tau = std::f64::consts::TAU;match s {EvalSurface::Plane { .. } => Domain { range: [None, None], period: [None, None] },- EvalSurface::Nurbs { degree, knots, count, .. } => {- let r = |d: usize| Some((*knots[d].get(degree[d])?, *knots[d].get(count[d])?));- Domain { range: [r(0), r(1)], period: [None, None] }+ EvalSurface::Nurbs { degree, knots, count, closed, .. } => {+ let r = |d: usize| Some((*knots.get(d)?.get(*degree.get(d)?)?, *knots.get(d)?.get(*count.get(d)?)?));+ // A direction the surface joins itself along is periodic: a boundary that runs+ // across the join is unwrapped past the range's end, and the evaluator wraps it back.+ let p = |d: usize| closed.get(d).copied().unwrap_or(false).then(|| r(d).map(|(a, b)| b - a)).flatten().filter(|x| *x > 0.0);+ Domain { range: [r(0), r(1)], period: [p(0), p(1)] }}EvalSurface::Revolved { profile, swap, .. } => {let r = (|| Some((*profile.knots.get(profile.degree)?, *profile.knots.get(profile.ctrl.len())?)))();@@ -109,11 +112,11 @@ pub(crate) fn project(s: &EvalSurface, dom: &Domain, p: Vec3, hint: Option<[f64;best = Some((uv, d));}let (ur, vr) = (dom.range[0]?, dom.range[1]?);- const N: usize = 16;- let mut starts: Vec<(f64, [f64; 2])> = Vec::with_capacity((N + 1) * (N + 1));- for i in 0..=N {- for j in 0..=N {- let uv = [ur.0 + (ur.1 - ur.0) * i as f64 / N as f64, vr.0 + (vr.1 - vr.0) * j as f64 / N as f64];+ let [nu, nv] = start_lines(s);+ let mut starts: Vec<(f64, [f64; 2])> = Vec::with_capacity((nu + 1) * (nv + 1));+ for i in 0..=nu {+ for j in 0..=nv {+ let uv = [ur.0 + (ur.1 - ur.0) * i as f64 / nu as f64, vr.0 + (vr.1 - vr.0) * j as f64 / nv as f64];if let Some((q, _, _)) = s.derivs(uv[0], uv[1]) {starts.push(((q - p).len2(), uv));}@@ -130,6 +133,28 @@ pub(crate) fn project(s: &EvalSurface, dom: &Domain, p: Vec3, hint: Option<[f64;best.filter(|(_, d)| *d <= accept).map(|(uv, _)| uv)}+/// Most starts [`project`] tries along one direction, and over the whole domain.+const MAX_START_LINES: usize = 4096;+const MAX_STARTS: usize = 16_384;++/// How many divisions of each direction [`project`] starts from: 16, or two per span of a+/// spline with more. A long spline (a thread's helical flank, as other CAD systems write it to+/// STEP: hundreds of spans along the helix) turns many times between 16 starts, and from the+/// nearest of them Newton settles on another turn, so a point of its boundary was taken as off+/// the surface and the body lost its display plan.+fn start_lines(s: &EvalSurface) -> [usize; 2] {+ const N: usize = 16;+ let spans = |d: usize| match s {+ EvalSurface::Nurbs { degree, count, .. } => count.get(d).zip(degree.get(d)).map_or(0, |(c, g)| c.saturating_sub(*g)),+ _ => 0,+ };+ let mut lines = [0, 1].map(|d| (2 * spans(d)).clamp(N, MAX_START_LINES));+ // The longer direction keeps its spans; the other gives way to the cap on starts.+ let (long, short) = if lines[0] >= lines[1] { (0, 1) } else { (1, 0) };+ lines[short] = lines[short].min((MAX_STARTS / (lines[long] + 1)).max(N));+ lines+}+/// `x` moved by whole periods to lie within half a period of `near`.pub(crate) fn unwrap(x: f64, near: f64, period: Option<f64>) -> f64 {match period {@@ -288,15 +313,37 @@ mod tests {#[test]fn divides_the_turn_but_not_the_straight_direction() {let s = cylinder();- let turn =- divide(&s, 1, (0.0, std::f64::consts::TAU), (0.0, 1.0), &Rules { tol: 0.01, max_len: f64::INFINITY, turn: None }, f64::INFINITY, 10_000);- let along =- divide(&s, 0, (0.0, 1.0), (0.0, std::f64::consts::TAU), &Rules { tol: 0.01, max_len: f64::INFINITY, turn: None }, f64::INFINITY, 10_000);+ let turn = divide(+ &s,+ 1,+ (0.0, std::f64::consts::TAU),+ (0.0, 1.0),+ &Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None },+ f64::INFINITY,+ 10_000,+ );+ let along = divide(+ &s,+ 0,+ (0.0, 1.0),+ (0.0, std::f64::consts::TAU),+ &Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None },+ f64::INFINITY,+ 10_000,+ );assert_eq!(along, vec![0.0, 1.0]);// Chord sag r(1 − cos(θ/2)) ≤ 0.01 with r = 3 needs θ ≤ 0.163: at least 39 segments.assert!(turn.len() >= 40 && turn.len() < 80, "{}", turn.len());// With a longest side the straight direction is divided too: 4 mm in sides ≤ 0.5.- let along = divide(&s, 0, (0.0, 1.0), (0.0, std::f64::consts::TAU), &Rules { tol: 0.01, max_len: f64::INFINITY, turn: None }, 0.5, 10_000);+ let along = divide(+ &s,+ 0,+ (0.0, 1.0),+ (0.0, std::f64::consts::TAU),+ &Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None },+ 0.5,+ 10_000,+ );assert_eq!(along.len(), 9);}@@ -306,7 +353,15 @@ mod tests {#[test]fn divides_with_the_ends_exactly() {let (a0, a1) = (-1.010485317689877, 1.083909784703316);- let lines = divide(&cylinder(), 1, (a0, a1), (0.0, 1.0), &Rules { tol: 0.01, max_len: f64::INFINITY, turn: None }, f64::INFINITY, 10_000);+ let lines = divide(+ &cylinder(),+ 1,+ (a0, a1),+ (0.0, 1.0),+ &Rules { tol: 0.01, max_len: f64::INFINITY, extent: 0.0, turn: None, boundary_tol: None },+ f64::INFINITY,+ 10_000,+ );assert_eq!(lines.first().copied(), Some(a0));assert_eq!(lines.last().copied(), Some(a1));}diff --git a/docs/native-brep.md b/docs/native-brep.mdindex e60ea5aef2..ab4157d4da 100644--- a/docs/native-brep.md+++ b/docs/native-brep.md@@ -76,7 +76,7 @@ when its runtime uses a different parameterization.Schema 3 caps 1,024 shells, 1,000,000 combined topology/geometry items, geometrynesting 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+8,192. Numbers must be finite and bounded in magnitude by 1e12. Knot order, activespline domain, multiplicities, rectangular grids, positive rational weights,nondegenerate planes, orthonormal frames, unit revolution axes, positive radii,valid angular/height ranges and intersection face references are checked before an adapter is called. These are resource and structural guards,diff --git a/docs/step-import.md b/docs/step-import.mdindex 9c22b4668b..2bc84d4893 100644--- a/docs/step-import.md+++ b/docs/step-import.md@@ -47,6 +47,7 @@ Files from different systems differ in which way is up and in what they call the- **`up`**: `"z"` (the default) keeps the file's axes. Many systems write Y up, so such a part lies on its back in SolidCraft's Z-up space. `"up": "y"` turns the import's component a quarter turn about X (+90°: Y becomes Z), as the window's "Stand it up" offer does, so an assembly's parts and instances turn together. The import and the turn are one undo step, the reply names the turned occurrence as `stand_up`, and only the file's component turns, not what is already in the design. The window offers to stand a part up after a STEP file opens unless the call said which way is up (`up: "z"` as well as `"y"`).- **`names`**: `"auto"` (the default) keeps meaningful solid names and replaces placeholders such as `Body1` or `Body 2 (3)` with the nearest named product, then the occurrence name if no product is named. `"solid"` keeps the solid's name; `"product"` chooses the part's name; `"instance"` chooses the assembly occurrence (`Post-2`), falling back to the product. If the chosen name is missing, the solid's name remains. Repeated names are numbered (`Post`, `Post (2)`). Names are stored with the Import feature and survive reopening the design. Files without names or assembly metadata retain generated body names and a flat structure.+- **Vertices off their curves**: some systems write an edge's vertex a little beside the end of its curve, often further off than the accuracy the file declares (`UNCERTAINTY_MEASURE_WITH_UNIT`). A vertex up to the file's own tolerance off, or up to 1/1000 of the model's size (never more than 1 mm), is read as that end of the edge: the curve's end is moved onto the vertex. A vertex further off leaves its face out, with a warning that says how far off it is.```json{"command": "file.insert_step", "params": {"path": "frame.step", "up": "y", "names": "instance"}}