Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(cad): smooth tessellation; small models skip simplification entirely
Sidwebworks4bb808cb1f2d
diff --git a/apps/assembler/src/actions/optimize.rs b/apps/assembler/src/actions/optimize.rsindex 1004c83672..c50592a9f7 100644--- a/apps/assembler/src/actions/optimize.rs+++ b/apps/assembler/src/actions/optimize.rs@@ -203,20 +203,25 @@ impl Src {}}-/// Map tessellated GLB weight → auto-mode error budget (normalized, a fraction of-/// each mesh's extent). Log-scaled between two anchors: at/below `SMALL` the-/// baseline high-quality budget (unchanged from today, so small models never-/// regress), ramping up to `MAX_ERR` at/above `LARGE`. Still bounded and per-mesh-/// adaptive — this decimates more on heavy models, it does not switch to unbounded-/// ratio targeting.-fn derive_auto_error(input_bytes: usize) -> f32 {- const SMALL: f64 = 512.0 * 1024.0; // 512 KiB+/// Map tessellated GLB weight → auto-mode error budget (normalized, a fraction+/// of each mesh's extent). At/below `SMALL` there is NO simplification at all+/// (`None` — lossless weld/reorder/encode only): a small model needs no size+/// win, and even a "high-quality" error budget visibly chamfers features that+/// are small relative to the part (a hole in a long part decimates to a+/// polygon). Above that, log-ramp from the baseline budget to `MAX_ERR` at+/// `LARGE`. Always error-bounded and per-mesh adaptive — never unbounded ratio+/// targeting.+fn derive_auto_error(input_bytes: usize) -> Option<f32> {+ const SMALL: f64 = 2.0 * 1024.0 * 1024.0; // 2 MiB — below this, losslessconst LARGE: f64 = 32.0 * 1024.0 * 1024.0; // 32 MiBconst MAX_ERR: f64 = 0.02; // 2% of extent — heavier but still reasonable+ if (input_bytes as f64) <= SMALL {+ return None;+ }let min_err = optimize::DEFAULT_AUTO_ERROR as f64; // 0.5%- let b = (input_bytes as f64).clamp(SMALL, LARGE);+ let b = (input_bytes as f64).min(LARGE);let t = (b.ln() - SMALL.ln()) / (LARGE.ln() - SMALL.ln()); // 0..1- (min_err + (MAX_ERR - min_err) * t) as f32+ Some((min_err + (MAX_ERR - min_err) * t) as f32)}/// Resolve the format, load the source into GLB bytes, then walk the simplify@@ -239,15 +244,14 @@ fn run_optimize(let glb = src.bytes();let input_bytes = glb.len();- // Size-adaptive quality (only when the caller gave no explicit knob): scale the- // auto-mode error budget by the tessellated GLB weight, so small models keep- // the baseline high-quality budget and large ones decimate harder within a- // still-bounded, per-mesh-adaptive budget. This smooths the old fit-or-fail- // cliff (mid-size models now decimate proportionally instead of not at all- // until they bust the size gate). The gate + coarse ratio rungs stay the final- // safety net below.+ // Size-adaptive quality (only when the caller gave no explicit knob): scale+ // the auto-mode error budget by the tessellated GLB weight — small models+ // skip simplification entirely (lossless), mid-size decimate within a+ // still-bounded per-mesh budget, large ones harder. Smooths the old+ // fit-or-fail cliff. The gate + coarse ratio rungs stay the final safety+ // net below.let auto_error = if opts.auto_scale {- Some(derive_auto_error(input_bytes))+ derive_auto_error(input_bytes)} else {opts.auto_error};@@ -460,14 +464,14 @@ mod tests {#[test]fn auto_error_scales_with_size() {let base = optimize::DEFAULT_AUTO_ERROR;- // Small models keep the baseline high-quality budget (no regression).- assert!((derive_auto_error(64 * 1024) - base).abs() < 1e-6);- assert!((derive_auto_error(512 * 1024) - base).abs() < 1e-6);+ // Small models get NO simplification — lossless encode only.+ assert_eq!(derive_auto_error(64 * 1024), None);+ assert_eq!(derive_auto_error(2 * 1024 * 1024), None);// Large models decimate harder, capped at 2%.- assert!((derive_auto_error(64 * 1024 * 1024) - 0.02).abs() < 1e-6);- // Monotonic, strictly increasing through the ramp, and always within bounds.- let mid = derive_auto_error(4 * 1024 * 1024);+ assert!((derive_auto_error(64 * 1024 * 1024).unwrap() - 0.02).abs() < 1e-6);+ // Monotonic through the ramp, within bounds.+ let mid = derive_auto_error(8 * 1024 * 1024).unwrap();assert!(mid > base && mid < 0.02);- assert!(derive_auto_error(2 * 1024 * 1024) < mid);+ assert!(derive_auto_error(4 * 1024 * 1024).unwrap() < mid);}}diff --git a/apps/assembler/src/main.rs b/apps/assembler/src/main.rsindex 3ccdff8cb3..5b5c34bf33 100644--- a/apps/assembler/src/main.rs+++ b/apps/assembler/src/main.rs@@ -472,7 +472,10 @@ async fn create_convert(glb_path: req["outputs"]["glb"]["path"].as_str().map(str::to_string),graph_path: req["outputs"]["graph"]["path"].as_str().map(str::to_string),lin: req["options"]["linearDeflection"].as_f64().unwrap_or(0.1),- ang: req["options"]["angularDeflection"].as_f64().unwrap_or(0.5),+ // Matches the optimize default: 0.25 rad keeps circles smooth+ // (≥ ~25 segments; 0.5 gave a blocky ~13). Also part of the+ // convert result-cache key, so older coarse results aren't reused.+ ang: req["options"]["angularDeflection"].as_f64().unwrap_or(0.25),optimize: req["options"]["optimize"].as_bool().unwrap_or(true),},);@@ -579,7 +582,10 @@ pub fn optimize_opts(out: &Value, q: &Value) -> actions::optimize::Opts {.as_u64().unwrap_or(DEFAULT_MAX_OUTPUT_BYTES) as usize,lin: q["linear_deflection"].as_f64().unwrap_or(0.1),- ang: q["angular_deflection"].as_f64().unwrap_or(0.5),+ // 0.25 rad → a full circle tessellates with ≥ ~25 segments (0.5 gave a+ // visibly blocky ~13). The bridge also scales linear deflection to each+ // shape, so small parts keep smooth curvature too.+ ang: q["angular_deflection"].as_f64().unwrap_or(0.25),// Per-request budget wins; else the env default (set on the Lambda path).budget: q["time_budget_secs"].as_u64()diff --git a/crates/converter/tests/tessellation_smoothness.rs b/crates/converter/tests/tessellation_smoothness.rsnew file mode 100644index 0000000000..1757d15469--- /dev/null+++ b/crates/converter/tests/tessellation_smoothness.rs@@ -0,0 +1,64 @@+//! Circles must tessellate smoothly — the old defaults (angular 0.5 rad,+//! absolute linear 0.1 mm) gave every circle a blocky ~13 segments, and even+//! fewer on small parts. The bridge now scales linear deflection to each+//! shape's size, and the service defaults tightened angular to 0.25 rad.+//! Hermetic: the cylinder fixture is generated by the occt bridge itself.++use converter::convert::convert_step;++fn cylinder_tris(radius: f64, height: f64, lin: f64, ang: f64) -> u64 {+ let dir = std::env::temp_dir().join(format!(+ "carbon-cyl-{radius}-{height}-{}-{}",+ (lin * 1000.0) as u64,+ (ang * 1000.0) as u64+ ));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("cyl.step");+ let path_str = path.to_str().unwrap();+ assert!(+ occt_bridge::write_test_cylinder(path_str, radius, height),+ "failed to write test cylinder STEP"+ );+ let text = std::fs::read_to_string(path_str).unwrap();+ let conv = convert_step(path_str, &text, lin, ang).expect("convert");+ conv.triangles as u64+}++/// Small circular features on a LONG part are where angular deflection binds:+/// the bbox-scaled linear deflection stays coarse (sized to the long extent),+/// so the circle's segment count falls to the angular floor — 0.5 rad gave a+/// blocky ~13-gon, 0.25 rad keeps >= ~25 segments. This is the user-visible+/// "blocky hole in an elongated part" case.+#[test]+fn quarter_rad_angular_deflection_smooths_small_features_on_long_parts() {+ let coarse = cylinder_tris(1.0, 200.0, 0.1, 0.5);+ let smooth = cylinder_tris(1.0, 200.0, 0.1, 0.25);+ assert!(+ smooth > coarse,+ "0.25 rad should out-tessellate 0.5 rad on a thin long cylinder (got {smooth} vs {coarse})"+ );+ assert!(+ smooth >= 90,+ "thin cylinder at 0.25 rad should have >= ~25 circle segments (got {smooth} tris)"+ );+}++/// A SMALL part must not tessellate coarser than a big one of the same shape:+/// the bridge scales linear deflection to the shape's bbox, so a 2 mm-radius+/// cylinder keeps proportionally as many circle segments as a 50 mm one.+#[test]+fn small_parts_keep_proportional_smoothness() {+ let small = cylinder_tris(2.0, 8.0, 0.1, 0.25);+ let big = cylinder_tris(50.0, 200.0, 0.1, 0.25);+ // Angular deflection dominates both (scale-invariant), so the small+ // cylinder should be within ~2x of the big one's tessellation — not an+ // order of magnitude blockier as with a fixed absolute 0.1 mm sag.+ assert!(+ small * 2 >= big / 2,+ "small cylinder tessellated disproportionately coarse ({small} vs {big} tris)"+ );+ assert!(+ small >= 90,+ "small cylinder should still have >= ~25 circle segments (got {small} tris)"+ );+}diff --git a/crates/occt-bridge/src/lib.rs b/crates/occt-bridge/src/lib.rsindex 6c339ee0b8..dcef5ba17a 100644--- a/crates/occt-bridge/src/lib.rs+++ b/crates/occt-bridge/src/lib.rs@@ -63,7 +63,14 @@ pub mod ffi {/// product (flat multi-body, no assembly tree) to a STEP file./// Hermetic tests use this instead of committed fixture files.fn write_test_step(path: &str, boxes: u32) -> bool;++ /// Test fixture generator: a single cylinder — the canonical curved+ /// surface for asserting tessellation smoothness (circle segments).+ fn write_test_cylinder(path: &str, radius: f64, height: f64) -> bool;}}-pub use ffi::{read_brep, read_iges, read_step, read_xbf, step_to_xbf, write_test_step, RawNode, Tree};+pub use ffi::{+ read_brep, read_iges, read_step, read_xbf, step_to_xbf, write_test_cylinder, write_test_step,+ RawNode, Tree,+};diff --git a/crates/occt-bridge/src/occt.cc b/crates/occt-bridge/src/occt.ccindex 0db7c9e3d8..31323b882d 100644--- a/crates/occt-bridge/src/occt.cc+++ b/crates/occt-bridge/src/occt.cc@@ -13,6 +13,7 @@#include <BinXCAFDrivers.hxx>#include <BRepMesh_IncrementalMesh.hxx>#include <BRepPrimAPI_MakeBox.hxx>+#include <BRepPrimAPI_MakeCylinder.hxx>#include <BRep_Builder.hxx>#include <BRep_Tool.hxx>#include <Bnd_Box.hxx>@@ -133,9 +134,26 @@ static bool mesh_parallel() {return v;}+// The caller's linear deflection is an ABSOLUTE sag in mm, sized for typical+// parts — on a small part the same 0.1 mm sag leaves a curved face with only a+// handful of facets. Scale it to the shape: 0.05% of the bbox diagonal, never+// coarser than requested, floored at 5% of the request so a tiny part can't+// demand micron-level meshes.+static double adaptive_deflection(const TopoDS_Shape &shape, double lin) {+ Bnd_Box box;+ BRepBndLib::Add(shape, box);+ if (box.IsVoid()) return lin;+ Standard_Real x0, y0, z0, x1, y1, z1;+ box.Get(x0, y0, z0, x1, y1, z1);+ const double dx = x1 - x0, dy = y1 - y0, dz = z1 - z0;+ const double diag = std::sqrt(dx * dx + dy * dy + dz * dz);+ return std::min(lin, std::max(diag * 5e-4, lin * 0.05));+}+static void tessellate(const TopoDS_Shape &shape, double lin, double ang,std::vector<float> &verts, std::vector<uint32_t> &indices) {- BRepMesh_IncrementalMesh(shape, lin, Standard_False, ang,+ BRepMesh_IncrementalMesh(shape, adaptive_deflection(shape, lin),+ Standard_False, ang,mesh_parallel() ? Standard_True : Standard_False);uint32_t offset = 0;for (TopExp_Explorer exp(shape, TopAbs_FACE); exp.More(); exp.Next()) {@@ -628,6 +646,21 @@ Tree read_xbf(rust::Str path, double linear_deflection, double angular_deflectio// compound, no assembly tree) — the flat multi-body export shape the split// path handles. Hermetic converter tests build their own STEP with this// instead of committing fixture files.+bool write_test_cylinder(rust::Str path, double radius, double height) {+ try {+ ensure_step_init();+ TopoDS_Shape shape = BRepPrimAPI_MakeCylinder(radius, height).Shape();+ STEPControl_Writer writer;+ if (writer.Transfer(shape, STEPControl_AsIs) != IFSelect_RetDone) {+ return false;+ }+ std::string p(path);+ return writer.Write(p.c_str()) == IFSelect_RetDone;+ } catch (...) {+ return false;+ }+}+bool write_test_step(rust::Str path, uint32_t boxes) {try {ensure_step_init();diff --git a/crates/occt-bridge/src/occt.h b/crates/occt-bridge/src/occt.hindex 654d765756..edfdf91ab9 100644--- a/crates/occt-bridge/src/occt.h+++ b/crates/occt-bridge/src/occt.h@@ -16,4 +16,6 @@ bool step_to_xbf(rust::Str step_path, rust::Str xbf_path);Tree read_xbf(rust::Str path, double linear_deflection, double angular_deflection);bool write_test_step(rust::Str path, uint32_t boxes);++bool write_test_cylinder(rust::Str path, double radius, double height);} // namespace carbon_occt