A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
Merge pull request #36 from arcman7/fix-glb-uv-render-overlap
wrong-nebula6be3ba426867
diff --cc crates/forma-cli/src/main.rsindex 359d6b8,bbd8ec2..59cc8cb--- a/crates/forma-cli/src/main.rs+++ b/crates/forma-cli/src/main.rs@@@ -16,10 -16,10 +16,10 @@@ fn print_help()"forma 0.4.2 — ultra-fast, headless, watertight, LLM-native 3D modeling engine\n\\n\USAGE:\n\- forma eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--draw blueprint.svg] [file|-]\n\- forma render [--size 512] --out preview.png [file|-]\n\- forma eval [--dialect pipe|compact] [--strict|--no-strict] [--json] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--view quad|front|back|right|left|top|iso] [--draw blueprint.svg] [file|-]\n\++ forma eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--view quad|front|back|right|left|top|iso] [--draw blueprint.svg] [file|-]\n\+ forma render [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n\forma draw --out blueprint.svg [file|-]\n\- forma spec [--dialect pipe|compact] [--gbnf]\n\+ forma spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]\n\forma --help\n\\n\Reads modeling commands from file or stdin, runs automatic topological invariant checks,\n\@@@ -200,12 -189,17 +201,20 @@@ fn main()eprintln!("ERR: --size requires pixel integer");process::exit(2);}- render_size = args[i + 1].parse().unwrap_or(512);+ render_size = args[i + 1].parse().unwrap_or_else(|_| {+ eprintln!("ERR: invalid --size '{}': expected positive integer", args[i + 1]);+ process::exit(2);+ });i += 2;}+ "--view" => {+ if i + 1 >= args.len() {+ eprintln!("ERR: --view requires value (quad|front|back|right|left|top|iso)");+ process::exit(2);+ }+ render_view = args[i + 1].clone();+ i += 2;+ }"--strict" => {strict = true;i += 1;diff --cc crates/forma-core/src/export.rsindex c4268ef,01fe135..70b6932--- a/crates/forma-core/src/export.rs+++ b/crates/forma-core/src/export.rs@@@ -23,16 -22,45 +23,47 @@@ fn triplanar_uv(p: Vec3, n: Vec3) -> [f}}- /// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes in memory (zero disk I/O),- /// treating model coordinates as metres.- pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {- write_glb_bytes_with_unit(mesh, yup, Unit::Meter)+ #[inline]+ fn normalize_f32_unit(n: [f32; 3], fallback: [f32; 3], yup: bool) -> [f32; 3] {+ if n[0].is_finite() && n[1].is_finite() && n[2].is_finite() {+ let l2 = (n[0] as f64) * (n[0] as f64) + (n[1] as f64) * (n[1] as f64) + (n[2] as f64) * (n[2] as f64);+ if l2 > 1e-12 {+ let inv = 1.0 / l2.sqrt();+ return [(n[0] as f64 * inv) as f32, (n[1] as f64 * inv) as f32, (n[2] as f64 * inv) as f32];+ }+ }+ if fallback[0].is_finite() && fallback[1].is_finite() && fallback[2].is_finite() {+ let l2 = (fallback[0] as f64) * (fallback[0] as f64)+ + (fallback[1] as f64) * (fallback[1] as f64)+ + (fallback[2] as f64) * (fallback[2] as f64);+ if l2 > 1e-12 {+ let inv = 1.0 / l2.sqrt();+ return [+ (fallback[0] as f64 * inv) as f32,+ (fallback[1] as f64 * inv) as f32,+ (fallback[2] as f64 * inv) as f32,+ ];+ }+ }+ if yup { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }}- /// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes. glTF positions are defined in metres,- /// so vertex positions are scaled from `unit` to metres (normals are unaffected).- pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Result<Vec<u8>, String> {- let k = unit.meters_per_unit();+ struct PackedGlbPrim {+ gid: usize,+ positions: Vec<[f32; 3]>,+ normals: Vec<[f32; 3]>,+ uvs: Vec<[f32; 2]>,+ indices: Vec<u32>,+ bmin: [f32; 3],+ bmax: [f32; 3],+ }++ /// Build per-material-group compacted, unconditionally welded triangle primitives with+ /// strictly unit-length normals for compact, engine-clean glTF 2.0 export.-fn pack_glb_primitives(mesh: &PolyMesh, yup: bool) -> Vec<PackedGlbPrim> {++/// Positions are scaled by `scale` (`unit.meters_per_unit()`) to glTF metres.++fn pack_glb_primitives(mesh: &PolyMesh, yup: bool, scale: f64) -> Vec<PackedGlbPrim> {+ use std::collections::HashMap;++ let pos_quant = 1e6 / scale.min(1.0).max(1e-12);let conv = |p: Vec3| -> [f32; 3] {if yup {[p.x as f32, p.z as f32, (-p.y) as f32]@@@ -71,42 -104,94 +107,101 @@@let cn = &corner_normals[fi];for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {- for ci in [ca, cb, cc] {+ let va = mesh.verts[f.verts[ca]];+ let vb = mesh.verts[f.verts[cb]];+ let vc = mesh.verts[f.verts[cc]];+ let tri_n = (vb - va).cross(vc - va).normalized();+ let fallback_n = if tri_n.len_sq() > 1e-18 {+ conv(tri_n)+ } else {+ conv(raw_n)+ };+ let proj_n = if raw_n.len_sq() > 1e-18 {+ raw_n+ } else if tri_n.len_sq() > 1e-18 {+ tri_n+ } else {+ cn[ca]+ };++ let mut tri_idx = [0u32; 3];+ for (slot, ci) in [ca, cb, cc].into_iter().enumerate() {let vi = f.verts[ci];- let v = mesh.verts[vi] * k;- let v = mesh.verts[vi];++ let v = mesh.verts[vi] * scale;let p = conv(v);- let n = conv(cn[ci]);- let uv = if has_face_uvs { f.uvs[ci] } else { triplanar_uv(v, raw_n) };- for k in 0..3 {- bmin[k] = bmin[k].min(p[k]);- bmax[k] = bmax[k].max(p[k]);- }- if use_weld {- let key = (- [(p[0] * 1e5).round() as i32, (p[1] * 1e5).round() as i32, (p[2] * 1e5).round() as i32],- [(n[0] * 1e4).round() as i32, (n[1] * 1e4).round() as i32, (n[2] * 1e4).round() as i32],- [(uv[0] * 1e5).round() as i32, (uv[1] * 1e5).round() as i32],- );- let idx = *vert_cache.entry(key).or_insert_with(|| {- let id = positions.len() as u32;- positions.push(p);- normals.push(n);- uvs.push(uv);- id- });- idxs.push(idx);+ let n = normalize_f32_unit(conv(cn[ci]), fallback_n, yup);+ let uv = if has_face_uvs {+ let u = f.uvs[ci];+ [+ if u[0].is_finite() { u[0] } else { 0.0 },+ if u[1].is_finite() { u[1] } else { 0.0 },+ ]} else {- let id = positions.len() as u32;- positions.push(p);- normals.push(n);- uvs.push(uv);- idxs.push(id);- }+ triplanar_uv(v, proj_n)+ };+ let uv_bits = |x: f32| -> u32 {+ if x == 0.0 { 0 } else { x.to_bits() }+ };+ let key = (+ [- (p[0] as f64 * 1e6).round() as i64,- (p[1] as f64 * 1e6).round() as i64,- (p[2] as f64 * 1e6).round() as i64,++ (p[0] as f64 * pos_quant).round() as i64,++ (p[1] as f64 * pos_quant).round() as i64,++ (p[2] as f64 * pos_quant).round() as i64,+ ],+ [+ (n[0] as f64 * 1e4).round() as i64,+ (n[1] as f64 * 1e4).round() as i64,+ (n[2] as f64 * 1e4).round() as i64,+ ],+ [uv_bits(uv[0]), uv_bits(uv[1])],+ );+ let idx = *grp.cache.entry(key).or_insert_with(|| {+ let id = grp.positions.len() as u32;+ for (k, &coord) in p.iter().enumerate() {+ grp.bmin[k] = grp.bmin[k].min(coord);+ grp.bmax[k] = grp.bmax[k].max(coord);+ }+ grp.positions.push(p);+ grp.normals.push(n);+ grp.uvs.push(uv);+ id+ });+ tri_idx[slot] = idx;+ }+ if tri_idx[0] != tri_idx[1] && tri_idx[1] != tri_idx[2] && tri_idx[2] != tri_idx[0] {+ grp.indices.extend_from_slice(&tri_idx);}}}- if positions.is_empty() {+ groups+ .into_iter()+ .enumerate()+ .filter(|(_, g)| !g.indices.is_empty() && !g.positions.is_empty())+ .map(|(gid, g)| PackedGlbPrim {+ gid,+ positions: g.positions,+ normals: g.normals,+ uvs: g.uvs,+ indices: g.indices,+ bmin: g.bmin,+ bmax: g.bmax,+ })+ .collect()+ }+-/// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes in memory (zero disk I/O).++/// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes in memory (zero disk I/O),++/// treating model coordinates as metres.+ pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {++ write_glb_bytes_with_unit(mesh, yup, Unit::Meter)++}++++/// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes. glTF positions are defined in metres,++/// so vertex positions are scaled from `unit` to metres (normals are unaffected).++pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Result<Vec<u8>, String> {+ let has_mats = !mesh.materials.is_empty();- let prims = pack_glb_primitives(mesh, yup);++ let prims = pack_glb_primitives(mesh, yup, unit.meters_per_unit());+ if prims.is_empty() {return Err("cannot export empty mesh to GLB".into());}@@@ -283,40 -367,8 +387,8 @@@ pub fn write_scene_glb_bytes_with_unit} else {let mesh = arc_mesh.as_ref();let has_mats = !mesh.materials.is_empty();- let num_groups = if has_mats { mesh.materials.len() } else { 1 };- let corner_normals = mesh.compute_corner_normals();- let mut positions: Vec<[f32; 3]> = Vec::new();- let mut normals: Vec<[f32; 3]> = Vec::new();- let mut uvs: Vec<[f32; 2]> = Vec::new();- let mut group_indices: Vec<Vec<u32>> = (0..num_groups).map(|_| Vec::new()).collect();- let mut bmin = [f32::INFINITY; 3];- let mut bmax = [f32::NEG_INFINITY; 3];-- for (fi, f) in mesh.faces.iter().enumerate() {- let raw_n = mesh.face_normal(fi);- let gid = if has_mats { (f.mat_id as usize).min(num_groups - 1) } else { 0 };- let has_uvs = f.uvs.len() == f.verts.len();- let cn = &corner_normals[fi];- for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {- for ci in [ca, cb, cc] {- let vi = f.verts[ci];- let v = mesh.verts[vi] * k;- let p = conv(v);- let n = conv(cn[ci]);- let uv = if has_uvs { f.uvs[ci] } else { triplanar_uv(v, raw_n) };- for k in 0..3 {- bmin[k] = bmin[k].min(p[k]);- bmax[k] = bmax[k].max(p[k]);- }- let id = positions.len() as u32;- positions.push(p);- normals.push(n);- uvs.push(uv);- group_indices[gid].push(id);- }- }- }- if positions.is_empty() {- let packed = pack_glb_primitives(mesh, yup);++ let packed = pack_glb_primitives(mesh, yup, k);+ if packed.is_empty() {continue;}