Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

fix(export): omit unused TEXCOORD_0 and weld untextured GLBs on (POSITION, NORMAL)

Sukhpal Gill108a8e8d2d44
diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rs
index 198c409..4b7123c 100644
--- a/crates/forma-core/src/export.rs
+++ b/crates/forma-core/src/export.rs
@@ -74,6 +74,13 @@ fn pack_glb_primitives(mesh: &PolyMesh, yup: bool, scale: f64) -> Vec<PackedGlbP
let has_mats = !mesh.materials.is_empty();
let num_groups = if has_mats { mesh.materials.len() } else { 1 };
+ let mut group_has_uvs = vec![false; num_groups];
+ for f in &mesh.faces {
+ if !f.uvs.is_empty() && f.uvs.len() == f.verts.len() {
+ let gid = if has_mats { (f.mat_id as usize).min(num_groups - 1) } else { 0 };
+ group_has_uvs[gid] = true;
+ }
+ }
let corner_normals = mesh.compute_corner_normals();
type WeldKey = ([i64; 3], [i64; 3], [u32; 2]);
@@ -102,6 +109,7 @@ fn pack_glb_primitives(mesh: &PolyMesh, yup: bool, scale: f64) -> Vec<PackedGlbP
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 emit_group_uvs = group_has_uvs[gid];
let grp = &mut groups[gid];
let has_face_uvs = f.uvs.len() == f.verts.len();
let cn = &corner_normals[fi];
@@ -130,18 +138,27 @@ fn pack_glb_primitives(mesh: &PolyMesh, yup: bool, scale: f64) -> Vec<PackedGlbP
let v = mesh.verts[vi] * scale;
let p = conv(v);
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 },
- ]
+ let uv_opt = if emit_group_uvs {
+ 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 {
+ triplanar_uv(v, proj_n)
+ };
+ Some(uv)
} else {
- triplanar_uv(v, proj_n)
+ None
};
let uv_bits = |x: f32| -> u32 {
if x == 0.0 { 0 } else { x.to_bits() }
};
+ let uv_key = match uv_opt {
+ Some(uv) => [uv_bits(uv[0]), uv_bits(uv[1])],
+ None => [0, 0],
+ };
let key = (
[
(p[0] as f64 * pos_quant).round() as i64,
@@ -153,7 +170,7 @@ fn pack_glb_primitives(mesh: &PolyMesh, yup: bool, scale: f64) -> Vec<PackedGlbP
(n[1] as f64 * 1e4).round() as i64,
(n[2] as f64 * 1e4).round() as i64,
],
- [uv_bits(uv[0]), uv_bits(uv[1])],
+ uv_key,
);
let idx = *grp.cache.entry(key).or_insert_with(|| {
let id = grp.positions.len() as u32;
@@ -163,7 +180,9 @@ fn pack_glb_primitives(mesh: &PolyMesh, yup: bool, scale: f64) -> Vec<PackedGlbP
}
grp.positions.push(p);
grp.normals.push(n);
- grp.uvs.push(uv);
+ if let Some(uv) = uv_opt {
+ grp.uvs.push(uv);
+ }
id
});
tri_idx[slot] = idx;
@@ -207,7 +226,7 @@ pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Resu
let est_bytes: usize = prims
.iter()
- .map(|p| p.positions.len() * 32 + p.indices.len() * 4 + 16)
+ .map(|p| p.positions.len() * if p.uvs.is_empty() { 24 } else { 32 } + p.indices.len() * 4 + 16)
.sum();
let mut bin = Vec::with_capacity(est_bytes);
let mut bviews_json = String::new();
@@ -236,12 +255,17 @@ pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Resu
}
let nrm_blen = p.normals.len() * 12;
- let uv_off = bin.len();
- for uv in &p.uvs {
- bin.extend_from_slice(&uv[0].to_le_bytes());
- bin.extend_from_slice(&uv[1].to_le_bytes());
- }
- let uv_blen = p.uvs.len() * 8;
+ let has_uvs = !p.uvs.is_empty();
+ let uv_slice = if has_uvs {
+ let uv_off = bin.len();
+ for uv in &p.uvs {
+ bin.extend_from_slice(&uv[0].to_le_bytes());
+ bin.extend_from_slice(&uv[1].to_le_bytes());
+ }
+ Some((uv_off, p.uvs.len() * 8))
+ } else {
+ None
+ };
let idx_off = bin.len();
let use_u16 = p.positions.len() < u16::MAX as usize;
@@ -265,32 +289,65 @@ pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Resu
accs_json.push(',');
prims_json.push(',');
}
- let (pos_bv, nrm_bv, uv_bv, idx_bv) = (bv_idx, bv_idx + 1, bv_idx + 2, bv_idx + 3);
- let (pos_acc, nrm_acc, uv_acc, idx_acc) = (acc_idx, acc_idx + 1, acc_idx + 2, acc_idx + 3);
- bv_idx += 4;
- acc_idx += 4;
+ let pos_bv = bv_idx;
+ let pos_acc = acc_idx;
+ let nrm_bv = bv_idx + 1;
+ let nrm_acc = acc_idx + 1;
+ bv_idx += 2;
+ acc_idx += 2;
bviews_json.push_str(&format!(
- r#"{{"buffer":0,"byteOffset":{pos_off},"byteLength":{pos_blen},"target":34962}},{{"buffer":0,"byteOffset":{nrm_off},"byteLength":{nrm_blen},"target":34962}},{{"buffer":0,"byteOffset":{uv_off},"byteLength":{uv_blen},"target":34962}},{{"buffer":0,"byteOffset":{idx_off},"byteLength":{idx_blen},"target":34963}}"#
+ r#"{{"buffer":0,"byteOffset":{pos_off},"byteLength":{pos_blen},"target":34962}},{{"buffer":0,"byteOffset":{nrm_off},"byteLength":{nrm_blen},"target":34962}}"#
));
accs_json.push_str(&format!(
- r#"{{"bufferView":{pos_bv},"componentType":5126,"count":{},"type":"VEC3","min":[{},{},{}],"max":[{},{},{}]}},{{"bufferView":{nrm_bv},"componentType":5126,"count":{},"type":"VEC3"}},{{"bufferView":{uv_bv},"componentType":5126,"count":{},"type":"VEC2"}},{{"bufferView":{idx_bv},"componentType":{idx_ctype},"count":{},"type":"SCALAR"}}"#,
+ r#"{{"bufferView":{pos_bv},"componentType":5126,"count":{},"type":"VEC3","min":[{},{},{}],"max":[{},{},{}]}},{{"bufferView":{nrm_bv},"componentType":5126,"count":{},"type":"VEC3"}}"#,
p.positions.len(),
p.bmin[0], p.bmin[1], p.bmin[2],
p.bmax[0], p.bmax[1], p.bmax[2],
p.normals.len(),
- p.uvs.len(),
+ ));
+
+ let uv_acc_opt = if let Some((uv_off, uv_blen)) = uv_slice {
+ let uv_bv = bv_idx;
+ let uv_acc = acc_idx;
+ bv_idx += 1;
+ acc_idx += 1;
+ bviews_json.push_str(&format!(
+ r#",{{"buffer":0,"byteOffset":{uv_off},"byteLength":{uv_blen},"target":34962}}"#
+ ));
+ accs_json.push_str(&format!(
+ r#",{{"bufferView":{uv_bv},"componentType":5126,"count":{},"type":"VEC2"}}"#,
+ p.uvs.len(),
+ ));
+ Some(uv_acc)
+ } else {
+ None
+ };
+
+ let idx_bv = bv_idx;
+ let idx_acc = acc_idx;
+ bv_idx += 1;
+ acc_idx += 1;
+ bviews_json.push_str(&format!(
+ r#",{{"buffer":0,"byteOffset":{idx_off},"byteLength":{idx_blen},"target":34963}}"#
+ ));
+ accs_json.push_str(&format!(
+ r#",{{"bufferView":{idx_bv},"componentType":{idx_ctype},"count":{},"type":"SCALAR"}}"#,
p.indices.len(),
));
+ let attrs = match uv_acc_opt {
+ Some(uv_acc) => format!(r#"{{"POSITION":{pos_acc},"NORMAL":{nrm_acc},"TEXCOORD_0":{uv_acc}}}"#),
+ None => format!(r#"{{"POSITION":{pos_acc},"NORMAL":{nrm_acc}}}"#),
+ };
if has_mats {
prims_json.push_str(&format!(
- r#"{{"attributes":{{"POSITION":{pos_acc},"NORMAL":{nrm_acc},"TEXCOORD_0":{uv_acc}}},"indices":{idx_acc},"material":{},"mode":4}}"#,
+ r#"{{"attributes":{attrs},"indices":{idx_acc},"material":{},"mode":4}}"#,
p.gid
));
} else {
prims_json.push_str(&format!(
- r#"{{"attributes":{{"POSITION":{pos_acc},"NORMAL":{nrm_acc},"TEXCOORD_0":{uv_acc}}},"indices":{idx_acc},"mode":4}}"#,
+ r#"{{"attributes":{attrs},"indices":{idx_acc},"mode":4}}"#,
));
}
}
@@ -409,12 +466,16 @@ pub fn write_scene_glb_bytes_with_unit(
let nrm_acc = accessors.len();
accessors.push(serde_json::json!({"bufferView":nrm_bv,"componentType":5126,"count":p.normals.len(),"type":"VEC3"}));
- let uv_off = bin.len();
- for uv in &p.uvs { for c in uv { bin.extend_from_slice(&c.to_le_bytes()); } }
- let uv_bv = bviews.len();
- bviews.push(serde_json::json!({"buffer":0,"byteOffset":uv_off,"byteLength":p.uvs.len()*8,"target":34962}));
- let uv_acc = accessors.len();
- accessors.push(serde_json::json!({"bufferView":uv_bv,"componentType":5126,"count":p.uvs.len(),"type":"VEC2"}));
+ let mut attrs = serde_json::json!({"POSITION": pos_acc, "NORMAL": nrm_acc});
+ if !p.uvs.is_empty() {
+ let uv_off = bin.len();
+ for uv in &p.uvs { for c in uv { bin.extend_from_slice(&c.to_le_bytes()); } }
+ let uv_bv = bviews.len();
+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":uv_off,"byteLength":p.uvs.len()*8,"target":34962}));
+ let uv_acc = accessors.len();
+ accessors.push(serde_json::json!({"bufferView":uv_bv,"componentType":5126,"count":p.uvs.len(),"type":"VEC2"}));
+ attrs["TEXCOORD_0"] = serde_json::json!(uv_acc);
+ }
let ioff = bin.len();
let use_u16 = p.positions.len() < u16::MAX as usize;
@@ -432,7 +493,7 @@ pub fn write_scene_glb_bytes_with_unit(
accessors.push(serde_json::json!({"bufferView":ibv,"componentType":ictype,"count":p.indices.len(),"type":"SCALAR"}));
let mut prim = serde_json::json!({
- "attributes": {"POSITION": pos_acc, "NORMAL": nrm_acc, "TEXCOORD_0": uv_acc},
+ "attributes": attrs,
"indices": iacc,
"mode": 4
});
@@ -507,7 +568,8 @@ pub fn write_scene_glb_bytes_with_unit(
}
/// Export a PolyMesh to binary glTF 2.0 (.glb) with flat/smooth normals,
-/// automatic triplanar or unwrapped `TEXCOORD_0` UVs, and optional per-face PBR `materials`.
+/// optional explicit `TEXCOORD_0` UVs (omitted when no UVs exist so smooth `(POSITION, NORMAL)` vertices weld cleanly),
+/// and optional per-face PBR `materials`.
/// Note: `yup = true` emits glTF 2.0 spec-compliant Y-up coordinates (`(x,y,z) -> (x,z,-y)`).
pub fn write_glb(mesh: &PolyMesh, path: &Path, yup: bool) -> Result<(), String> {
write_glb_with_unit(mesh, path, yup, Unit::Meter)
diff --git a/crates/forma-core/tests/kernel_tests.rs b/crates/forma-core/tests/kernel_tests.rs
index 5095959..b52b902 100644
--- a/crates/forma-core/tests/kernel_tests.rs
+++ b/crates/forma-core/tests/kernel_tests.rs
@@ -324,13 +324,19 @@ fn test_pbr_materials_spatial_queries_and_headless_png_renderer() {
forma_core::spatial::place_on_mesh(&mut cap_placed, s.get_part("flange").unwrap(), 0.0);
assert!((cap_placed.aabb().min.z - 0.2).abs() < 1e-6);
- // Verify GLB contains PBR materials & TEXCOORD_0
+ // Verify GLB contains PBR materials, omits unused TEXCOORD_0 when un-unwrapped, and emits TEXCOORD_0 after unwrap
let glb_path = std::env::temp_dir().join("forma_pbr_test.glb");
s.export(&glb_path, Some("flange")).unwrap();
let glb_bytes = std::fs::read(&glb_path).unwrap();
let glb_str = String::from_utf8_lossy(&glb_bytes);
assert!(glb_str.contains("brushed_steel"), "GLB missing PBR material name");
- assert!(glb_str.contains("TEXCOORD_0"), "GLB missing triplanar UVs");
+ assert!(!glb_str.contains("TEXCOORD_0"), "untextured GLB without UVs should omit unused TEXCOORD_0");
+
+ let mut unwrapped_flange = (**s.get_part("flange").unwrap()).clone();
+ forma_core::uv::unwrap_lscm(&mut unwrapped_flange, 45.0, 0.01).unwrap();
+ let unwrapped_glb = forma_core::export::write_glb_bytes(&unwrapped_flange, true).unwrap();
+ let unwrapped_str = String::from_utf8_lossy(&unwrapped_glb);
+ assert!(unwrapped_str.contains("TEXCOORD_0"), "unwrapped GLB missing TEXCOORD_0 UVs");
// Verify pure-Rust <5ms headless PNG software renderer
let png_path = std::env::temp_dir().join("forma_preview_test.png");
diff --git a/crates/forma-core/tests/regression_fixes.rs b/crates/forma-core/tests/regression_fixes.rs
index fcc0dde..c5e4fdc 100644
--- a/crates/forma-core/tests/regression_fixes.rs
+++ b/crates/forma-core/tests/regression_fixes.rs
@@ -266,3 +266,111 @@ fn test_sweep_and_prune_many_disjoint_shells_fast_and_accurate() {
"valid negative-volume inner cavity must not trigger overlap"
);
}
+
+#[test]
+fn test_glb_omits_unused_texcoord0_and_welds_smooth_vertices_without_45deg_splits() {
+ use forma_core::primitives::{make_sphere, make_thread};
+ use std::collections::HashSet;
+
+ fn count_unique_pos_normal_pairs(mesh: &PolyMesh) -> usize {
+ let cn = mesh.compute_corner_normals();
+ let mut uniq: HashSet<([i64; 3], [i64; 3])> = HashSet::new();
+ for (fi, f) in mesh.faces.iter().enumerate() {
+ let raw_n = mesh.face_normal(fi);
+ for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {
+ 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 fb = if tri_n.len_sq() > 1e-18 { tri_n } else { raw_n };
+ for ci in [ca, cb, cc] {
+ let v = mesh.verts[f.verts[ci]];
+ let p = [v.x as f32, v.z as f32, (-v.y) as f32];
+ let raw = cn[fi][ci];
+ let n_raw = [raw.x as f32, raw.z as f32, (-raw.y) as f32];
+ let n = if n_raw.iter().all(|x| x.is_finite()) {
+ let l = ((n_raw[0] as f64).powi(2)
+ + (n_raw[1] as f64).powi(2)
+ + (n_raw[2] as f64).powi(2))
+ .sqrt();
+ if l > 1e-6 {
+ [(n_raw[0] as f64 / l) as f32, (n_raw[1] as f64 / l) as f32, (n_raw[2] as f64 / l) as f32]
+ } else {
+ [fb.x as f32, fb.z as f32, (-fb.y) as f32]
+ }
+ } else {
+ [fb.x as f32, fb.z as f32, (-fb.y) as f32]
+ };
+ uniq.insert((
+ [
+ (p[0] as f64 * 1e6).round() as i64,
+ (p[1] as f64 * 1e6).round() as i64,
+ (p[2] as f64 * 1e6).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,
+ ],
+ ));
+ }
+ }
+ }
+ uniq.len()
+ }
+
+ // 1. Smooth sphere & smooth thread (crosses 45° normal octant boundaries repeatedly)
+ let mut sphere = make_sphere(1.0, 32, 16, 1);
+ sphere.smooth_angle_deg = Some(60.0);
+ sphere.weighted_normals = true;
+
+ let mut thread = make_thread(0.12, 0.25, 0.15, 6.0, 32, 2).unwrap();
+ thread.smooth_angle_deg = Some(180.0);
+ thread.weighted_normals = true;
+
+ for (label, mesh) in [("sphere", &sphere), ("thread", &thread)] {
+ let expected_verts = count_unique_pos_normal_pairs(mesh);
+ let glb = write_glb_bytes(mesh, true).expect("glb export");
+ let (json, _bin) = parse_glb(&glb);
+ let prim = &json["meshes"][0]["primitives"][0];
+ let attrs = prim["attributes"].as_object().unwrap();
+ assert!(attrs.get("TEXCOORD_0").is_none(), "{label}: untextured GLB must omit TEXCOORD_0");
+ assert!(attrs.contains_key("POSITION") && attrs.contains_key("NORMAL"));
+ let pos_cnt = json["accessors"][attrs["POSITION"].as_u64().unwrap() as usize]["count"]
+ .as_u64()
+ .unwrap() as usize;
+ assert_eq!(
+ pos_cnt, expected_verts,
+ "{label}: UV-less GLB should weld strictly on (POSITION, NORMAL) ({pos_cnt} != {expected_verts})"
+ );
+ let rt = read_glb_bytes(&glb).expect("round-trip untextured glb");
+ assert_eq!(rt.faces.len(), mesh.triangulated().faces.len());
+ }
+
+ // 2. Scene GLB export also omits TEXCOORD_0 when untextured and preserves it when unwrapped
+ let arc_sphere = Arc::new(sphere.clone());
+ let mut unwrapped_box = make_box(1.0, 1.0, 1.0, 3);
+ unwrap_lscm(&mut unwrapped_box, 45.0, 0.01).expect("unwrap box");
+ let arc_box = Arc::new(unwrapped_box);
+
+ let sglb = write_scene_glb_bytes(
+ &[("smooth_sphere", &arc_sphere, [0.0, 0.0, 0.0]), ("uv_box", &arc_box, [3.0, 0.0, 0.0])],
+ true,
+ )
+ .expect("scene glb");
+ let (sjson, _) = parse_glb(&sglb);
+ let sphere_prim = &sjson["meshes"][0]["primitives"][0]["attributes"];
+ let box_prim = &sjson["meshes"][1]["primitives"][0]["attributes"];
+ assert!(sphere_prim.get("TEXCOORD_0").is_none(), "untextured scene mesh must omit TEXCOORD_0");
+ assert!(box_prim.get("TEXCOORD_0").is_some(), "unwrapped scene mesh must keep TEXCOORD_0");
+
+ // 3. Mixed partial-UV primitive group still emits a valid TEXCOORD_0 accessor matching POSITION count
+ let mut mixed = make_box(1.0, 1.0, 1.0, 4);
+ mixed.faces[0].uvs = vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
+ let mglb = write_glb_bytes(&mixed, true).expect("mixed uv glb");
+ let (mjson, _) = parse_glb(&mglb);
+ let mattrs = &mjson["meshes"][0]["primitives"][0]["attributes"];
+ let mpos = mjson["accessors"][mattrs["POSITION"].as_u64().unwrap() as usize]["count"].as_u64().unwrap();
+ let muv = mjson["accessors"][mattrs["TEXCOORD_0"].as_u64().unwrap() as usize]["count"].as_u64().unwrap();
+ assert_eq!(mpos, muv, "mixed-UV primitive TEXCOORD_0 count must match POSITION count");
+}
diff --git a/docs/reference/language-and-formats.md b/docs/reference/language-and-formats.md
index dd83274..e552824 100644
--- a/docs/reference/language-and-formats.md
+++ b/docs/reference/language-and-formats.md
@@ -95,7 +95,7 @@ Query via `forma spec --topic <name>`, `npx forma-3d spec --topic <name>`, `GET
| Format | Extension | Direction | Unit handling | Axis / notes |
| --- | --- | --- | --- | --- |
-| Binary glTF 2.0 | `.glb` | Import + Export | Scaled to meters (`meters_per_unit()`) | Y-up conversion, PBR materials, triplanar or LSCM UVs; supports multi-node `--scene` / `scene: true`. |
+| Binary glTF 2.0 | `.glb` | Import + Export | Scaled to meters (`meters_per_unit()`) | Y-up conversion, PBR materials, optional `TEXCOORD_0` UVs (via `unwrap()`); supports multi-node `--scene` / `scene: true`. |
| STEP AP214 | `.step`, `.stp` | Export | Declares model unit in header | Faceted B-Rep solid for CAD interoperability. |
| 3D Manufacturing Format | `.3mf` | Export | Declares `model/@unit` | Ready for modern 3D-printing slicers. |
| Binary STL | `.stl` | Import + Export | Raw model units (format has no unit field) | Triangulated mesh. |