93a2922c5e
* STEP import: mesh band faces that wrap around a closed surface correctly Fixes two related bugs that caused SolidCraft to fail to mesh a face wrapping all the way around a closed, non-periodic surface (a revolved ridge band, or a tube-shaped B-spline surface): a missing face, a folded/self-overlapping triangulation, or a hole in the rendered body. 1. Ring edges that run slightly off their surface. STEP files write a surface and the curves bounding it to the file's own declared uncertainty, so a ring edge can legitimately sit a few micrometres off the surface it bounds. The code finding where a ring edge crosses the planned split line compared against the edge's raw (off-surface) point using a hardcoded tolerance far stricter than the file's own precision, rejecting a valid cut. Now matches against the point on the surface directly below the ring crossing, respecting the file's declared tolerance. 2. Closed B-spline surfaces, their slits and their slivers. truck only treats the rotation of a revolved surface as periodic; a face on a B-spline surface whose control net closes on itself (a tube) wasn't recognized as wrapping around at all. This produced a folded face, a hole (a boundary loop landing a full period away from where it should cut), and one near-zero-width sliver face costing the entire body its tessellation plan. Adds periodicity detection for closed B-spline surfaces, period- aware hole-loop alignment, dropping of zero-width slit boundaries, and isolating a too-thin-to-triangulate face so it no longer takes the rest of the body down with it. The GPU shader's periodic wrap mirrors the CPU math so the two don't drift apart. Regression tests: band_faces_split_when_ring_edges_run_off_their_surface, band_face_with_a_zero_width_slit_is_still_meshed, a_sliver_face_too_thin_to_triangulate_does_not_cost_the_body_its_plan. Ablation-tested: disabling either mechanism in (2) reproduces its target test's original failure message while leaving the other test unaffected. * STEP import: mesh the band's split faces, not just split them jyviko asked whether a band wall missing from the interactive app's render was a shading issue or a genuinely missing face. It was missing: the ring- edge split fix made the band's topology correct, but plan_face still produced zero triangles for the two new sub-faces. Two causes, both in plan_face (crates/kernel/src/tess/mod.rs): 1. The tolerance for how far an imported boundary may lie off its surface was tied to the requested mesh's chord tolerance instead of to the body's own size. A finer display tolerance could then reject a boundary a coarser one had just accepted, so the face would drop out exactly when zooming in on it. 2. Near a sharp corner of this flat-panelled band, several boundary points that are legitimately a few micrometres apart (within the STEP file's own declared precision) all projected onto the same surface point. The boundary loop then repeated a point in (u, v), which a triangulator can't follow, so the face's plan failed outright. One face without a plan costs the whole body its plan, and the fallback mesher can't handle a closed B-spline surface either, leaving both halves of the split band with no triangles at all: present in the topology, invisible in every renderer, and absent from the body's volume. Fix: scale the off-surface tolerance to the body's own extent (new Rules::extent), and collapse a run of boundary nodes that land on the same surface point to one (drop_collapsed) before triangulating. Regression test additions to band_faces_split_when_ring_edges_run_off_their_surface: the body's volume now matches the analytic pentagon prism (was a third of it - only the top cap - before this fix); display_plan leaves no face without triangles from coarse to fine tolerance; and the actual tolerance and facet angle the viewport draws with gives the split band its full lateral area on both halves. Confirmed on review_band_big.step, the fixture behind the review screenshots: volume's relative error against the analytic pentagon prism drops from 1.4e-4 to 4.1e-6, and the band wall now occludes the floor grid behind it in a snapshot the same way the top and bottom caps always did. Full kernel suite: 739 tests, 0 failed. * STEP import: hold an imported boundary to the file's own tolerance, not the part's size jyviko: the off-surface acceptance added in the last commit (rules.extent * OFF_SURFACE) scaled with the part, so a 2 m part silently accepted a boundary 2 mm off its surface while a 20 mm copy of the same part accepted only 0.02 mm. A STEP file's own declared uncertainty does not grow with the part, so the bound shouldn't either. Body gains boundary_tol: Option<f64>, Some(file's declared tolerance) for a body read from STEP (crate::step_in::Units::tol, already used by the ring-split fix in split.rs), None for anything this kernel built. It's set before the import's own unmeshed-face check runs, and carried over by the two face-split operations that re-cut an imported surface (splitface.rs, outline.rs), since the file's uncertainty still describes those boundaries afterward. plan_face's accept now reads: the file's own tolerance when the body declares one, or the old chord-tolerance/extent bound otherwise. The old bound's tol * 10.0 term had to go too, not just the extent term: at a 2 m part's typical display tolerance that term alone is ~20 mm, nearly ten times the extent bound jyviko objected to, so keeping it would have left the exact 2 m/2 mm example still silently accepted. Two new tests in step_in/tests.rs: - band_faces_split_when_a_scaled_copy_runs_off_its_surface: the same band fixture at a realistic 2 m scale with the same absolute slop and declared uncertainty as the small one, meshes the same way at every chord tolerance from coarse to fine. - off_surface_budget_follows_the_file_not_the_part_size: the actual regression. The same off-surface error is accepted or refused the same way whether the part is 20 mm or 2 m; a 2 mm error against a 1 µm declared uncertainty is refused at both sizes now (accepted at 2 m under the old bound, refused at 20 mm - that asymmetry was the bug). Checked at both a coarse and a fine display tolerance. Known gap, not fixed here: a STEP-imported body saved into a .solidcraft design and reopened loses boundary_tol (native.rs's decoder has no field to read it from) and falls back to the old extent-based bound on reload. Today's design format has no concept of this value at all; persisting it is a real format change, out of scope for this fix. Full kernel suite: 776 tests, 0 failed. clippy -D warnings clean. * Display plans for STEP threads and pointed ends (#3847) Three faces cost a threaded or pointed STEP part its whole display plan, so it was drawn from the reference mesh: cracked, faceted, and never refined up close. - A loop through a pole (a cone's apex on the boundary) seemed to wind around the surface: the jump at the apex, unwrapped to the nearest copy, was arbitrary. The loop is turned to end where it leaves the pole, so the step that closes it is an ordinary one (`seam::close_through_pole`). - Projection onto a spline with hundreds of spans (a helical flank) restarted from a 16 x 16 grid and settled on another turn; it now starts from two points per span, capped. - Sag refinement no longer inserts a point exactly on a boundary side, which split the side and failed the face. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * tess: a refused face's edges are divided finer and it is planned again (#2814) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * tess: sliver faces plan empty; a face no method plans is filled flat from its nodes (#2814) A face whose boundary runs out and back along itself (two edges between the same vertices, a rounding apart, as STEP files write slivers) encloses nothing and is planned with no triangles. A face still refused after its edges are divided finer (a cusp, a sliver whose sides sag across each other, a small cap at a pole) is filled flat from its shared boundary nodes, so the rest of the body keeps its display plan instead of falling back to the reference mesh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * display mesh tests: a rim the chord tolerance leaves a line is divided again (#2814) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * portable B-rep: up to 8192 control points along a spline direction (#2814) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * solidcraft-cli: --debug logs what the engine reports to stderr Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * STEP import: a spline written over a tiny parameter range is read over one (#2814) Some writers parameterize splines over a few millionths (a humanoid robot's edges span 5.4e-6). The kernel tells parameters apart only to 1e-6, so over such a range it evaluated the curve's end wrongly, and trimming an edge to its vertices dropped a control point: the bodies could not be stored exactly and the whole model cache was left out of the design. The knots are now stretched to span one; the curve is the same and edges are trimmed by their vertices, so nothing read from the file refers to the old parameters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * model cache: a body keeps its file's declared accuracy (#2814) A body restored from the cache dropped the accuracy the file it was read from declares, so the planner held its boundaries to the kernel's own bound and a reopened design drew differently from the import. It is stored with the body's runtime values, and only when there is one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * tess: a boundary within a hundredth of its body lies on its surface, at every quality (#2814) #1721 held a body read from a file to the accuracy the file declares. A writer declares what it aims for, not a bound its edges keep: a 251-body robot assembly declaring 0.01 µm has boundaries 10 to 30 µm off their surfaces, and 95 of its bodies lost their display plans. The bound is a hundredth of the body again, what Normal quality always allowed, and now the same at every quality, so zooming in still never drops a face (#1721's point). A file declaring more raises it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * STEP import: keep faces whose edge vertices sit slightly off their curves Some exporters write an edge's vertex beside the end of its curve, further off than the accuracy the file declares (a surface export declares 0.01 mm and puts a vertex 0.19 mm off two spline ends). The reader refused such edges and left the face, and with single-face bodies the body, out. A vertex may now sit up to the file's tolerance or 1/1000 of the model's size (the diagonal around its VERTEX_POINTs), whichever is larger, never more than the existing 1 mm ceiling. Spline and open-conic edges have the end control point moved onto the vertex, so every such edge meets its vertices exactly. The file's declared accuracy still governs closed-curve, seam and circle checks. * tess, io: review clean-ups (#2814) - A sliver face is one whose loops are all slit: drop_slits finds it in the retry after a failed plan, so the pre-check on every face (folded) is gone. - The flat fill uses cdt::triangulate (a lenient fill that leaves out sides crossing one already kept) and its flood-fill inside test, and the plane from geom::Plane. - Refinement only builds its indexes when a face was refused, takes the faces to plan again from edge_faces, and re-samples edges on the pool; Rules::finer for the finer rules. - One PackageWriter::fits for the model cache, the preview and the thumbnail. - The band split's ring tolerance lives in split.rs; comments say what the off-surface bound is now. - The CLI logger prints Level::as_str(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM --------- Co-authored-by: David Lackovic <lackovicdavid1234@gmail.com> Co-authored-by: bherbruck <brennen.herbruck@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com> Co-authored-by: Ray <raykholo@users.noreply.github.com>
354 lines
15 KiB
Rust
354 lines
15 KiB
Rust
//! SolidCraft native, versioned binary geometry. No STEP conversion or display meshes.
|
|
//! Exact: a decoded body is the encoded one, number for number, for the same producer.
|
|
use crate::{Body, KernelError, Result, guard};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{Map, Number, Value};
|
|
use std::sync::Arc;
|
|
|
|
mod adapter;
|
|
mod binary;
|
|
mod metadata;
|
|
mod preview;
|
|
pub use preview::native_preview_mesh;
|
|
|
|
// 01/02 were development-only prototypes; independent metadata records start at 03; 04 stores
|
|
// procedural intersections and placed revolutions exactly, and the measured runtime values.
|
|
const MAGIC: &[u8; 8] = b"SCBREP04";
|
|
// A body's own limits. A design's cache holds many bodies within the container's budgets, and
|
|
// decoding is linear in the bytes, so one large part (an imported casting) fits.
|
|
const MAX_BYTES: usize = 256 << 20;
|
|
const MAX_ITEMS: usize = 1_000_000;
|
|
const MAX_VALUES: usize = 20_000_000;
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct SavedBody {
|
|
solid: solidcraft_geom::brep::Brep,
|
|
metadata: solidcraft_geom::brep::envelope::Metadata,
|
|
runtime: Runtime,
|
|
}
|
|
|
|
/// What a body measured about itself that later operations read: kept so a decoded body works
|
|
/// to the same tolerances as the one encoded, without measuring again.
|
|
#[derive(Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct Runtime {
|
|
/// [`Body::size`] as stored (0: not measured).
|
|
size: f64,
|
|
/// The orientation mesh's missing-face count at its tolerance.
|
|
coarse_missing: Option<(f64, u64)>,
|
|
/// [`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}"))
|
|
}
|
|
|
|
/// Explicit topology, spatial geometry, construction certificates and history, exactly.
|
|
/// Failure is a cache miss at the IO boundary, never a failed document save.
|
|
pub fn encode_native_body(body: &Body) -> Result<Vec<u8>> {
|
|
guard("encode native B-rep", || {
|
|
for source in body.face_sources.iter().flat_map(|s| s.iter()).flatten() {
|
|
let mut at = source;
|
|
let mut depth = 0usize;
|
|
while let crate::FaceSource::ShellPlanar { source, .. } = at {
|
|
depth += 1;
|
|
if depth > 32 {
|
|
return Err(invalid("face-source nesting"));
|
|
}
|
|
at = source;
|
|
}
|
|
}
|
|
if body.face_count() > MAX_ITEMS
|
|
|| body.solid.edge_iter().take(MAX_ITEMS + 1).count() > MAX_ITEMS
|
|
|| body.mesh.as_ref().is_some_and(|m| m.positions.len() > MAX_ITEMS || m.triangles.len() > MAX_ITEMS)
|
|
{
|
|
return Err(invalid("native geometry budget"));
|
|
}
|
|
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)), 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)?;
|
|
let value = serde_json::to_value(saved).map_err(invalid)?;
|
|
validate_value(&value, 0)?;
|
|
if value_nodes(&value) > MAX_VALUES {
|
|
return Err(invalid("value budget"));
|
|
}
|
|
let mut out = MAGIC.to_vec();
|
|
binary::write(&value, &mut out, 0)?;
|
|
Ok(out)
|
|
})
|
|
}
|
|
|
|
/// Decode bounded untrusted data. Validate indices before topology extraction.
|
|
/// Only a caller that has checked who produced the data may treat it as evaluated geometry.
|
|
pub fn decode_native_body(bytes: &[u8]) -> Result<Body> {
|
|
if bytes.len() > MAX_BYTES || bytes.get(..8) != Some(MAGIC.as_slice()) {
|
|
return Err(invalid("version or size"));
|
|
}
|
|
guard("decode native B-rep", || {
|
|
let mut input = bytes.get(8..).ok_or_else(|| invalid("header"))?;
|
|
let mut remaining = MAX_VALUES;
|
|
let value = binary::read(&mut input, 0, &mut remaining)?;
|
|
if !input.is_empty() {
|
|
return Err(invalid("trailing data"));
|
|
}
|
|
validate_value(&value, 0)?;
|
|
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, 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,
|
|
color: None,
|
|
paint: None,
|
|
splits: None,
|
|
face_sources: None,
|
|
history: None,
|
|
display_of: None,
|
|
meshes: None,
|
|
phased: false,
|
|
regularization_protected: false,
|
|
};
|
|
metadata::apply(&mut body, saved.metadata)?;
|
|
Ok(body)
|
|
})
|
|
}
|
|
|
|
fn validate_topology(saved: &SavedBody) -> Result<()> {
|
|
saved.solid.validate().map_err(invalid)?;
|
|
let faces: usize = saved.solid.shells.iter().map(|s| s.faces.len()).sum();
|
|
let edges: usize = saved.solid.shells.iter().map(|s| s.edges.len()).sum();
|
|
let saved = &saved.metadata;
|
|
if saved.version != solidcraft_geom::brep::envelope::VERSION {
|
|
return Err(invalid("metadata version"));
|
|
}
|
|
if saved.face_sources.as_ref().is_some_and(|s| s.len() != faces) {
|
|
return Err(invalid("face source count"));
|
|
}
|
|
if let Some(history) = &saved.history
|
|
&& (history.faces.len() != faces
|
|
|| history.edges.len() != edges
|
|
|| history.operands as usize > MAX_ITEMS
|
|
|| history.edges.iter().flat_map(|e| &e.faces).any(|&f| f as usize >= faces))
|
|
{
|
|
return Err(invalid("history topology"));
|
|
}
|
|
if saved.color.is_some_and(|c| c.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v))) {
|
|
return Err(invalid("colour"));
|
|
}
|
|
if let Some(paint) = &saved.paint
|
|
&& (!paint.opacity.is_finite()
|
|
|| !(0.0..=1.0).contains(&paint.opacity)
|
|
|| paint.faces.iter().any(|p| {
|
|
p.face as usize >= faces
|
|
|| !p.opacity.is_finite()
|
|
|| !(0.0..=1.0).contains(&p.opacity)
|
|
|| p.color.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v))
|
|
}))
|
|
{
|
|
return Err(invalid("face paint"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
// The binary reader bounds allocation before deserialization. Geometry semantics
|
|
// are checked by the independent schema validator, not by backend serde internals.
|
|
fn validate_value(v: &Value, depth: usize) -> Result<()> {
|
|
if depth > 48 {
|
|
return Err(invalid("nesting"));
|
|
}
|
|
match v {
|
|
Value::String(s) if s.len() > 1 << 20 => return Err(invalid("string budget")),
|
|
Value::Number(n) if n.is_f64() && n.as_f64().is_none_or(|x| !x.is_finite() || x.abs() > 1e12) => return Err(invalid("non-finite metadata")),
|
|
Value::Array(a) => {
|
|
if a.len() > MAX_ITEMS {
|
|
return Err(invalid("array budget"));
|
|
}
|
|
for x in a {
|
|
validate_value(x, depth + 1)?;
|
|
}
|
|
}
|
|
Value::Object(o) => {
|
|
for x in o.values() {
|
|
validate_value(x, depth + 1)?;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn value_nodes(v: &Value) -> usize {
|
|
match v {
|
|
Value::Array(a) => a.iter().fold(1usize, |n, v| n.saturating_add(value_nodes(v))),
|
|
Value::Object(o) => o.values().fold(1usize, |n, v| n.saturating_add(value_nodes(v))),
|
|
_ => 1,
|
|
}
|
|
}
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use solidcraft_geom::Vec3;
|
|
fn equal(a: &Body, b: &Body) {
|
|
assert_eq!(a.face_count(), b.face_count());
|
|
assert_eq!(a.face_sources, b.face_sources);
|
|
assert_eq!(a.history, b.history);
|
|
assert_eq!(a.paint, b.paint);
|
|
assert_eq!(a.color, b.color);
|
|
assert_eq!(a.splits, b.splits);
|
|
assert_eq!(a.regularization_protected, b.regularization_protected);
|
|
assert_eq!(encode_native_body(a).unwrap(), encode_native_body(b).unwrap());
|
|
let am = crate::measure(a).unwrap();
|
|
let bm = crate::measure(b).unwrap();
|
|
assert!((am.volume - bm.volume).abs() < 1e-7);
|
|
}
|
|
#[test]
|
|
fn native_solids_keep_geometry_metadata_and_later_modelling() {
|
|
let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap();
|
|
let rounded = crate::fillet(&cube, &[Vec3::new(20., 0., 10.)], 2.).unwrap();
|
|
let bore = crate::cylinder(Vec3::new(10., 10., -1.), Vec3::Z, 3., 12.).unwrap();
|
|
let cut = crate::boolean(&rounded, &bore, crate::BoolOp::Cut).unwrap().unwrap();
|
|
for body in [cube, rounded, cut] {
|
|
let body = body.with_color(Some([0.1, 0.5, 0.9]));
|
|
let bytes = encode_native_body(&body).unwrap();
|
|
assert!(bytes.starts_with(MAGIC));
|
|
let decoded = decode_native_body(&bytes).unwrap();
|
|
equal(&body, &decoded);
|
|
let a = crate::boolean(&body, &bore, crate::BoolOp::Cut).unwrap().unwrap();
|
|
let b = crate::boolean(&decoded, &bore, crate::BoolOp::Cut).unwrap().unwrap();
|
|
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();
|
|
let surface = crate::copy_faces(&cube, &[Vec3::new(20., 15., 10.)]).unwrap();
|
|
let sphere = crate::sphere(Vec3::ZERO, 12.).unwrap();
|
|
let torus = crate::torus(Vec3::ZERO, 20., 4.).unwrap();
|
|
for body in [surface, sphere, torus] {
|
|
let encoded = encode_native_body(&body).unwrap();
|
|
let restored = decode_native_body(&encoded).unwrap();
|
|
assert_eq!(body.is_surface(), restored.is_surface());
|
|
assert_eq!(body.face_count(), restored.face_count());
|
|
assert_eq!(encoded, encode_native_body(&restored).unwrap());
|
|
if !body.is_surface() {
|
|
equal(&body, &restored);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn box_and_fillet_have_stable_wire_records() {
|
|
let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap();
|
|
let rounded = crate::fillet(&cube, &[Vec3::new(20., 0., 10.)], 2.).unwrap();
|
|
let records: Vec<_> = [cube, rounded]
|
|
.iter()
|
|
.map(|body| {
|
|
let bytes = encode_native_body(body).unwrap();
|
|
assert_eq!(&bytes[..8], b"SCBREP04");
|
|
let mut raw = &bytes[8..];
|
|
let value = binary::read(&mut raw, 0, &mut 2_000_000).unwrap();
|
|
assert!(raw.is_empty());
|
|
value
|
|
})
|
|
.collect();
|
|
let actual = serde_json::json!(records);
|
|
let expected: Value = serde_json::from_str(include_str!("native/fixtures/box-fillet-v4.json")).unwrap();
|
|
compare_wire(&expected, &actual);
|
|
}
|
|
|
|
fn compare_wire(expected: &Value, actual: &Value) {
|
|
match (expected, actual) {
|
|
(Value::Number(a), Value::Number(b)) if a.is_f64() && b.is_f64() => {
|
|
let (a, b) = (a.as_f64().unwrap(), b.as_f64().unwrap());
|
|
assert!((a - b).abs() <= 1e-10 * a.abs().max(1.), "wire number changed: {a} vs {b}");
|
|
}
|
|
(Value::Array(a), Value::Array(b)) => {
|
|
assert_eq!(a.len(), b.len());
|
|
for (a, b) in a.iter().zip(b) {
|
|
compare_wire(a, b);
|
|
}
|
|
}
|
|
(Value::Object(a), Value::Object(b)) => {
|
|
assert_eq!(a.keys().collect::<Vec<_>>(), b.keys().collect::<Vec<_>>());
|
|
for (key, a) in a {
|
|
compare_wire(a, &b[key]);
|
|
}
|
|
}
|
|
_ => assert_eq!(expected, actual),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn malformed_native_geometry_is_bounded_and_never_panics() {
|
|
let body = crate::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap();
|
|
let bytes = encode_native_body(&body).unwrap();
|
|
for n in [0, 1, 7, 8, 9, bytes.len() - 1] {
|
|
assert!(decode_native_body(&bytes[..n]).is_err());
|
|
}
|
|
for i in (0..bytes.len()).step_by((bytes.len() / 256).max(1)) {
|
|
let mut bad = bytes.clone();
|
|
bad[i] ^= 0xff;
|
|
assert!(std::panic::catch_unwind(|| decode_native_body(&bad)).is_ok());
|
|
}
|
|
let mut raw = &bytes[8..];
|
|
let value = binary::read(&mut raw, 0, &mut 2_000_000).unwrap();
|
|
for key in ["vertices", "index"] {
|
|
let mut v = value.clone();
|
|
if key == "vertices" {
|
|
v["solid"]["shells"][0]["edges"][0]["vertices"] = serde_json::json!([u64::MAX, 0]);
|
|
} else {
|
|
v["solid"]["shells"][0]["faces"][0]["loops"][0][0]["edge"] = serde_json::json!(u64::MAX);
|
|
}
|
|
let mut bad = MAGIC.to_vec();
|
|
binary::write(&v, &mut bad, 0).unwrap();
|
|
assert!(decode_native_body(&bad).is_err());
|
|
}
|
|
let mut huge = MAGIC.to_vec();
|
|
huge.push(7);
|
|
huge.extend(u32::MAX.to_le_bytes());
|
|
assert!(decode_native_body(&huge).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn native_preserves_face_appearance_and_authored_boundaries() {
|
|
let mut body = crate::box_solid(Vec3::new(1., 2., 3.), Vec3::new(10., 20., 30.))
|
|
.unwrap()
|
|
.with_paint(Some(crate::Paint { opacity: 0.7, faces: vec![crate::FacePaint { face: 2, color: [0.25, 0.5, 0.75], opacity: 0.6 }] }));
|
|
body.splits = Some(Arc::new(vec![vec![Vec3::new(1., 2., 3.), Vec3::new(11., 2., 3.)]]));
|
|
body.regularization_protected = true;
|
|
let restored = decode_native_body(&encode_native_body(&body).unwrap()).unwrap();
|
|
equal(&body, &restored);
|
|
}
|
|
}
|