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

Merge remote-tracking branch 'origin/main' into feat/cli-scene-translucency-srgb

wrong-nebula27ac1a8c7e9c
diff --cc bin/forma.mjs
index 0e66de1,44b643a..37f23de
--- a/bin/forma.mjs
+++ b/bin/forma.mjs
@@@ -200,14 -177,6 +200,16 @@@ async function main()
}
const obs = session.eval(src, { dialect, strict });
- const totalParts = Object.keys(obs.parts ?? {}).length;
++ const partCount = Object.keys(obs.parts ?? {}).length;
++ const instMatch = /\binsts=(\d+)/.exec(obs.text ?? "");
++ const totalObjs = partCount + (instMatch ? Number.parseInt(instMatch[1], 10) : 0);
+ const wroteAny = Boolean(outPath || renderPath || drawPath);
- if (!exportScene && wroteAny && totalParts > 1) {
++ if (!exportScene && wroteAny && totalObjs > 1) {
+ process.stderr.write(
- `NOTE: scene has ${totalParts} parts, but exported/rendered only the last part because --scene was not set. Pass --scene to export/render all ${totalParts} parts together.\n`
++ `NOTE: scene has ${totalObjs} objects, but exported/rendered only the last part because --scene was not set. Pass --scene to export/render all ${totalObjs} objects together.\n`
+ );
+ }
+
if (outPath) {
const ext = extname(outPath).replace(/^\./, "").toLowerCase();
if (exportScene) {
diff --cc crates/forma-cli/src/main.rs
index 32ee11e,b6ac599..52c8ba1
--- a/crates/forma-cli/src/main.rs
+++ b/crates/forma-cli/src/main.rs
@@@ -321,14 -307,6 +321,14 @@@ fn main()
match eval_script(&mut scene, dialect, &src) {
Ok(obs) => {
- let total_parts = scene.part_names().len();
++ let total_objs = scene.part_names().len() + scene.total_instance_count();
+ let wrote_any = out_path.is_some() || render_path.is_some() || draw_path.is_some();
- if !export_scene && wrote_any && total_parts > 1 {
++ if !export_scene && wrote_any && total_objs > 1 {
+ let last = scene.last_part_name().unwrap_or("last");
+ eprintln!(
- "NOTE: scene has {total_parts} parts, but exported/rendered only the last part ('{last}') because --scene was not set. Pass --scene to export/render all {total_parts} parts together."
++ "NOTE: scene has {total_objs} objects, but exported/rendered only the last part ('{last}') because --scene was not set. Pass --scene to export/render all {total_objs} objects together."
+ );
+ }
if let Some(ref out) = out_path {
if export_scene {
if let Err(e) = scene.export_scene_path(out) {
diff --cc crates/forma-core/src/export.rs
index c2a55e0,c8a61a2..7df4f05
--- a/crates/forma-core/src/export.rs
+++ b/crates/forma-core/src/export.rs
@@@ -551,98 -536,375 +609,368 @@@ pub fn write_scene_glb_bytes_with_optio
let mut accessors: Vec<serde_json::Value> = Vec::new();
let mut gltf_materials: Vec<serde_json::Value> = Vec::new();
let mut mat_dedup: HashMap<String, usize> = HashMap::new();
+ let mut used_extensions: BTreeSet<&'static str> = BTreeSet::new();
let mut gltf_meshes: Vec<serde_json::Value> = Vec::new();
- let mut mesh_ptr_map: HashMap<usize, usize> = HashMap::new();
- let mut gltf_nodes: Vec<serde_json::Value> = Vec::new();
+ let mut proto_to_gltf_mesh: Vec<Option<usize>> = vec![None; prototypes.len()];
- for &(node_name, arc_mesh, trans) in nodes {
- let ptr = std::sync::Arc::as_ptr(arc_mesh) as usize;
- let mesh_idx = if let Some(&existing) = mesh_ptr_map.get(&ptr) {
- existing
- } else {
- let mesh = arc_mesh.as_ref();
- let has_mats = !mesh.materials.is_empty();
- let packed = pack_glb_primitives(mesh, yup, k);
- if packed.is_empty() {
- continue;
+ let mut proto_clusters: Vec<Vec<usize>> = vec![Vec::new(); prototypes.len()];
+ for (ii, inst) in instances.iter().enumerate() {
+ proto_clusters[inst.proto_idx].push(ii);
+ }
+
+ for (pi, arc_mesh) in prototypes.iter().enumerate() {
+ let mesh = arc_mesh.as_ref();
+ let has_mats = !mesh.materials.is_empty();
+ let packed = pack_glb_primitives(mesh, opts.yup, k);
+ if packed.is_empty() {
+ continue;
+ }
+
+ let mut prims: Vec<serde_json::Value> = Vec::with_capacity(packed.len());
+ for p in &packed {
+ while (bin.len() & 3) != 0 { bin.push(0); }
+ let pos_off = bin.len();
+ for v in &p.positions { for c in v { bin.extend_from_slice(&c.to_le_bytes()); } }
+ let pos_bv = bviews.len();
+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":pos_off,"byteLength":p.positions.len()*12,"target":34962}));
+ let pos_acc = accessors.len();
+ accessors.push(serde_json::json!({"bufferView":pos_bv,"componentType":5126,"count":p.positions.len(),"type":"VEC3","min":p.bmin,"max":p.bmax}));
+
+ let nrm_off = bin.len();
+ for n in &p.normals { for c in n { bin.extend_from_slice(&c.to_le_bytes()); } }
+ let nrm_bv = bviews.len();
+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":nrm_off,"byteLength":p.normals.len()*12,"target":34962}));
+ let nrm_acc = accessors.len();
+ accessors.push(serde_json::json!({"bufferView":nrm_bv,"componentType":5126,"count":p.normals.len(),"type":"VEC3"}));
+
+ 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 mut prims: Vec<serde_json::Value> = Vec::with_capacity(packed.len());
- for p in &packed {
- while (bin.len() & 3) != 0 { bin.push(0); }
- let pos_off = bin.len();
- for v in &p.positions { for c in v { bin.extend_from_slice(&c.to_le_bytes()); } }
- let pos_bv = bviews.len();
- bviews.push(serde_json::json!({"buffer":0,"byteOffset":pos_off,"byteLength":p.positions.len()*12,"target":34962}));
- let pos_acc = accessors.len();
- accessors.push(serde_json::json!({"bufferView":pos_bv,"componentType":5126,"count":p.positions.len(),"type":"VEC3","min":p.bmin,"max":p.bmax}));
-
- let nrm_off = bin.len();
- for n in &p.normals { for c in n { bin.extend_from_slice(&c.to_le_bytes()); } }
- let nrm_bv = bviews.len();
- bviews.push(serde_json::json!({"buffer":0,"byteOffset":nrm_off,"byteLength":p.normals.len()*12,"target":34962}));
- let nrm_acc = accessors.len();
- accessors.push(serde_json::json!({"bufferView":nrm_bv,"componentType":5126,"count":p.normals.len(),"type":"VEC3"}));
-
- 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;
+ let (ictype, iblen) = if use_u16 {
+ for &ix in &p.indices { bin.extend_from_slice(&(ix as u16).to_le_bytes()); }
+ (5123u32, p.indices.len() * 2)
+ } else {
+ for &ix in &p.indices { bin.extend_from_slice(&ix.to_le_bytes()); }
+ (5125u32, p.indices.len() * 4)
+ };
+ while (bin.len() & 3) != 0 { bin.push(0); }
+ let ibv = bviews.len();
+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":ioff,"byteLength":iblen,"target":34963}));
+ let iacc = accessors.len();
+ accessors.push(serde_json::json!({"bufferView":ibv,"componentType":ictype,"count":p.indices.len(),"type":"SCALAR"}));
+
+ let mut prim = serde_json::json!({
+ "attributes": attrs,
+ "indices": iacc,
+ "mode": 4
+ });
+ if has_mats {
+ let mat = &mesh.materials[p.gid];
- let key = format!("{}:{:?}:{}:{}", mat.name, mat.color, mat.metallic, mat.roughness);
++ let key = gltf_material_dedup_key(mat);
+ let mslot = *mat_dedup.entry(key).or_insert_with(|| {
+ let idx = gltf_materials.len();
- let lin = srgb_rgba_to_linear(mat.color);
- gltf_materials.push(serde_json::json!({
- "name": mat.name,
- "pbrMetallicRoughness": {
- "baseColorFactor": lin,
- "metallicFactor": mat.metallic,
- "roughnessFactor": mat.roughness
- }
- }));
++ gltf_materials.push(build_gltf_material(mat, &mut used_extensions));
+ idx
+ });
+ prim["material"] = serde_json::json!(mslot);
+ }
+ prims.push(prim);
+ }
+
+ let mesh_name = proto_clusters[pi]
+ .first()
+ .map(|&ii| instances[ii].name)
+ .unwrap_or("mesh");
+ let mid = gltf_meshes.len();
+ gltf_meshes.push(serde_json::json!({"name": mesh_name, "primitives": prims}));
+ proto_to_gltf_mesh[pi] = Some(mid);
+ }
- let ioff = bin.len();
- let use_u16 = p.positions.len() < u16::MAX as usize;
- let (ictype, iblen) = if use_u16 {
- for &ix in &p.indices { bin.extend_from_slice(&(ix as u16).to_le_bytes()); }
- (5123u32, p.indices.len() * 2)
+ let mut gltf_nodes: Vec<serde_json::Value> = Vec::new();
+ let mut root_node_indices: Vec<usize> = Vec::new();
+ let mut group_node_map: HashMap<String, usize> = HashMap::new();
+ let mut group_children: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
+
+ let ensure_group = |group_path: &str,
+ gltf_nodes: &mut Vec<serde_json::Value>,
+ root_nodes: &mut Vec<usize>,
+ group_map: &mut HashMap<String, usize>,
+ children_map: &mut BTreeMap<usize, Vec<usize>>|
+ -> Option<usize> {
+ let mut cur_path = String::new();
+ let mut parent_idx: Option<usize> = None;
+ for seg in group_path.split('/').map(str::trim).filter(|s| !s.is_empty()) {
+ if !cur_path.is_empty() {
+ cur_path.push('/');
+ }
+ cur_path.push_str(seg);
+ let idx = if let Some(&existing) = group_map.get(&cur_path) {
+ existing
+ } else {
+ let id = gltf_nodes.len();
+ gltf_nodes.push(serde_json::json!({"name": seg}));
+ group_map.insert(cur_path.clone(), id);
+ if let Some(pidx) = parent_idx {
+ children_map.entry(pidx).or_default().push(id);
} else {
- for &ix in &p.indices { bin.extend_from_slice(&ix.to_le_bytes()); }
- (5125u32, p.indices.len() * 4)
+ root_nodes.push(id);
+ }
+ id
+ };
+ parent_idx = Some(idx);
+ }
+ parent_idx
+ };
+
+ let push_child_node = |node_obj: serde_json::Value,
+ group: Option<&str>,
+ gltf_nodes: &mut Vec<serde_json::Value>,
+ root_nodes: &mut Vec<usize>,
+ group_map: &mut HashMap<String, usize>,
+ children_map: &mut BTreeMap<usize, Vec<usize>>| {
+ let parent = group.and_then(|g| ensure_group(g, gltf_nodes, root_nodes, group_map, children_map));
+ let node_idx = gltf_nodes.len();
+ gltf_nodes.push(node_obj);
+ if let Some(pidx) = parent {
+ children_map.entry(pidx).or_default().push(node_idx);
+ } else {
+ root_nodes.push(node_idx);
+ }
+ };
+
+ let emit_trs_node = |name: &str, mesh_idx: usize, trs: crate::instancing::Trs| -> serde_json::Value {
+ let mut node_obj = serde_json::json!({"name": name, "mesh": mesh_idx});
+ if trs.has_translation() {
+ node_obj["translation"] = serde_json::json!([
+ trs.translation[0] as f32,
+ trs.translation[1] as f32,
+ trs.translation[2] as f32
+ ]);
+ }
+ if trs.has_rotation() {
+ node_obj["rotation"] = serde_json::json!([
+ trs.rotation[0] as f32,
+ trs.rotation[1] as f32,
+ trs.rotation[2] as f32,
+ trs.rotation[3] as f32
+ ]);
+ }
+ if trs.has_scale() {
+ node_obj["scale"] = serde_json::json!([
+ trs.scale[0] as f32,
+ trs.scale[1] as f32,
+ trs.scale[2] as f32
+ ]);
+ }
+ node_obj
+ };
+
+ let mut used_gpu_instancing = false;
+
+ let mut proto_strategies: Vec<ScenePackStrategy> = vec![ScenePackStrategy::Standalone; prototypes.len()];
+ for (pi, idxs) in proto_clusters.iter().enumerate() {
+ let Some(_) = proto_to_gltf_mesh[pi] else { continue };
+ let proto = prototypes[pi];
+ let proto_bb = proto.aabb();
+ let proto_diag = proto_bb.size().len().max(1e-6);
+ let proto_center = (proto_bb.min + proto_bb.max) * 0.5;
+
+ let mut cmin = [f64::INFINITY; 3];
+ let mut cmax = [f64::NEG_INFINITY; 3];
+ let mut has_rot = false;
+ let mut has_nonunif = false;
+ let mut group_counts: HashMap<Option<&str>, usize> = HashMap::new();
+ for &ii in idxs {
+ let inst = &instances[ii];
+ let c = inst.trs.apply_point(proto_center);
+ cmin[0] = cmin[0].min(c.x);
+ cmin[1] = cmin[1].min(c.y);
+ cmin[2] = cmin[2].min(c.z);
+ cmax[0] = cmax[0].max(c.x);
+ cmax[1] = cmax[1].max(c.y);
+ cmax[2] = cmax[2].max(c.z);
+ has_rot |= inst.trs.has_rotation();
+ has_nonunif |= inst.trs.is_nonuniform_scale();
+ *group_counts.entry(inst.group).or_insert(0) += 1;
+ }
+ let spread_diag = ((cmax[0] - cmin[0]).powi(2)
+ + (cmax[1] - cmin[1]).powi(2)
+ + (cmax[2] - cmin[2]).powi(2))
+ .sqrt();
+ let max_grp = group_counts.values().copied().max().unwrap_or(0);
+ let feats = ClusterPackFeatures {
+ instance_count: idxs.len(),
+ faces_per_instance: proto.faces.len(),
+ verts_per_instance: proto.verts.len(),
+ material_count: proto.materials.len().max(1),
+ has_uvs: proto.faces.iter().any(|f| !f.uvs.is_empty()),
+ has_rotation: has_rot,
+ has_nonuniform_scale: has_nonunif,
+ spatial_spread_ratio: spread_diag / proto_diag,
+ same_group_fraction: if idxs.is_empty() { 0.0 } else { max_grp as f64 / idxs.len() as f64 },
+ allow_gpu_instancing: opts.gpu_instancing,
+ preserve_node_names: opts.preserve_node_names,
+ };
+ proto_strategies[pi] = choose_scene_pack_strategy(&feats);
+ }
+
+ let mut emitted_gpu_proto = vec![false; prototypes.len()];
+ for inst in &instances {
+ let Some(mesh_idx) = proto_to_gltf_mesh[inst.proto_idx] else { continue };
+ let strat = proto_strategies[inst.proto_idx];
+ match strat {
+ ScenePackStrategy::Standalone | ScenePackStrategy::DataInstance => {
+ let gtrs = inst.trs.to_gltf_space(opts.yup, k);
+ push_child_node(
+ emit_trs_node(inst.name, mesh_idx, gtrs),
+ inst.group,
+ &mut gltf_nodes,
+ &mut root_node_indices,
+ &mut group_node_map,
+ &mut group_children,
+ );
+ }
+ ScenePackStrategy::GpuInstance | ScenePackStrategy::GpuInstanceSpatialCells => {
+ if emitted_gpu_proto[inst.proto_idx] {
+ continue;
+ }
+ emitted_gpu_proto[inst.proto_idx] = true;
+ let cluster = &proto_clusters[inst.proto_idx];
+ let proto = prototypes[inst.proto_idx];
+ let proto_center = {
+ let bb = proto.aabb();
+ (bb.min + bb.max) * 0.5
};
- while (bin.len() & 3) != 0 { bin.push(0); }
- let ibv = bviews.len();
- bviews.push(serde_json::json!({"buffer":0,"byteOffset":ioff,"byteLength":iblen,"target":34963}));
- let iacc = accessors.len();
- accessors.push(serde_json::json!({"bufferView":ibv,"componentType":ictype,"count":p.indices.len(),"type":"SCALAR"}));
-
- let mut prim = serde_json::json!({
- "attributes": attrs,
- "indices": iacc,
- "mode": 4
- });
- if has_mats {
- let mat = &mesh.materials[p.gid];
- let key = gltf_material_dedup_key(mat);
- let mslot = *mat_dedup.entry(key).or_insert_with(|| {
- let idx = gltf_materials.len();
- gltf_materials.push(build_gltf_material(mat, &mut used_extensions));
- idx
- });
- prim["material"] = serde_json::json!(mslot);
+ let mut by_group: BTreeMap<Option<&str>, Vec<usize>> = BTreeMap::new();
+ for &ii in cluster {
+ by_group.entry(instances[ii].group).or_default().push(ii);
+ }
+
+ let world_centers: Vec<[f64; 3]> = instances
+ .iter()
+ .map(|it| {
+ let c = it.trs.apply_point(proto_center);
+ [c.x, c.y, c.z]
+ })
+ .collect();
+
+ for (grp_opt, grp_idxs) in by_group {
+ let batches = if strat == ScenePackStrategy::GpuInstanceSpatialCells {
+ partition_spatial_cells(&world_centers, &grp_idxs)
+ } else {
+ vec![grp_idxs]
+ };
+ let multi_cell = batches.len() > 1;
+ for (cell_i, batch) in batches.into_iter().enumerate() {
+ if batch.len() == 1 {
+ let one = &instances[batch[0]];
+ let gtrs = one.trs.to_gltf_space(opts.yup, k);
+ push_child_node(
+ emit_trs_node(one.name, mesh_idx, gtrs),
+ grp_opt,
+ &mut gltf_nodes,
+ &mut root_node_indices,
+ &mut group_node_map,
+ &mut group_children,
+ );
+ continue;
+ }
+ let gtrs_list: Vec<crate::instancing::Trs> = batch
+ .iter()
+ .map(|&ii| instances[ii].trs.to_gltf_space(opts.yup, k))
+ .collect();
+ let any_rot = gtrs_list.iter().any(|t| t.has_rotation());
+ let any_scale = gtrs_list.iter().any(|t| t.has_scale());
+
+ let mut inst_attrs = serde_json::Map::new();
+
+ while (bin.len() & 3) != 0 { bin.push(0); }
+ let t_off = bin.len();
+ for t in &gtrs_list {
+ for c in t.translation {
+ bin.extend_from_slice(&(c as f32).to_le_bytes());
+ }
+ }
+ let t_bv = bviews.len();
+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":t_off,"byteLength":gtrs_list.len()*12}));
+ let t_acc = accessors.len();
+ accessors.push(serde_json::json!({"bufferView":t_bv,"componentType":5126,"count":gtrs_list.len(),"type":"VEC3"}));
+ inst_attrs.insert("TRANSLATION".into(), serde_json::json!(t_acc));
+
+ if any_rot {
+ let r_off = bin.len();
+ for t in &gtrs_list {
+ for c in t.rotation {
+ bin.extend_from_slice(&(c as f32).to_le_bytes());
+ }
+ }
+ let r_bv = bviews.len();
+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":r_off,"byteLength":gtrs_list.len()*16}));
+ let r_acc = accessors.len();
+ accessors.push(serde_json::json!({"bufferView":r_bv,"componentType":5126,"count":gtrs_list.len(),"type":"VEC4"}));
+ inst_attrs.insert("ROTATION".into(), serde_json::json!(r_acc));
+ }
+
+ if any_scale {
+ let s_off = bin.len();
+ for t in &gtrs_list {
+ for c in t.scale {
+ bin.extend_from_slice(&(c as f32).to_le_bytes());
+ }
+ }
+ let s_bv = bviews.len();
+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":s_off,"byteLength":gtrs_list.len()*12}));
+ let s_acc = accessors.len();
+ accessors.push(serde_json::json!({"bufferView":s_bv,"componentType":5126,"count":gtrs_list.len(),"type":"VEC3"}));
+ inst_attrs.insert("SCALE".into(), serde_json::json!(s_acc));
+ }
+
+ let base_name = instances[batch[0]].name;
+ let node_name = if multi_cell {
+ format!("{base_name}_cell{cell_i}")
+ } else {
+ format!("{base_name}_instances")
+ };
+ push_child_node(
+ serde_json::json!({
+ "name": node_name,
+ "mesh": mesh_idx,
+ "extensions": {
+ "EXT_mesh_gpu_instancing": {
+ "attributes": serde_json::Value::Object(inst_attrs)
+ }
+ }
+ }),
+ grp_opt,
+ &mut gltf_nodes,
+ &mut root_node_indices,
+ &mut group_node_map,
+ &mut group_children,
+ );
+ used_gpu_instancing = true;
+ }
}
- prims.push(prim);
}
- let mid = gltf_meshes.len();
- gltf_meshes.push(serde_json::json!({"name": node_name, "primitives": prims}));
- mesh_ptr_map.insert(ptr, mid);
- mid
- };
+ }
+ }
- let mut node_obj = serde_json::json!({"name": node_name, "mesh": mesh_idx});
- if trans[0].abs() > 1e-9 || trans[1].abs() > 1e-9 || trans[2].abs() > 1e-9 {
- let tv = conv(Vec3::new(trans[0] * k, trans[1] * k, trans[2] * k));
- node_obj["translation"] = serde_json::json!(tv);
+ for (pidx, children) in group_children {
+ if !children.is_empty() {
+ gltf_nodes[pidx]["children"] = serde_json::json!(children);
}
- gltf_nodes.push(node_obj);
}
- if gltf_nodes.is_empty() {
+ if gltf_nodes.is_empty() || root_node_indices.is_empty() {
return Err("scene had no non-empty meshes to export".into());
}
while bin.len() % 4 != 0 { bin.push(0); }
@@@ -661,10 -922,10 +988,14 @@@
if !gltf_materials.is_empty() {
root["materials"] = serde_json::json!(gltf_materials);
}
+ if used_gpu_instancing {
- root["extensionsUsed"] = serde_json::json!(["EXT_mesh_gpu_instancing"]);
++ used_extensions.insert("EXT_mesh_gpu_instancing");
+ root["extensionsRequired"] = serde_json::json!(["EXT_mesh_gpu_instancing"]);
+ }
+ if !used_extensions.is_empty() {
+ let list: Vec<&str> = used_extensions.into_iter().collect();
+ root["extensionsUsed"] = serde_json::json!(list);
+ }
let mut json_bytes = root.to_string().into_bytes();
while json_bytes.len() % 4 != 0 { json_bytes.push(b' '); }
diff --cc crates/forma-core/src/instancing.rs
index 0000000,c354415..99a3a4a
mode 000000,100644..100644
--- a/crates/forma-core/src/instancing.rs
+++ b/crates/forma-core/src/instancing.rs
@@@ -1,0 -1,1060 +1,1067 @@@
+ //! Lean O(V) structural/geometric scene deduplication, glTF TRS recovery,
+ //! and a tiny quantized (`int4`) export-packaging decision model.
+ //!
+ //! - **Layer 1 (Deterministic O(V) Deduplication):** Buckets meshes by exact
+ //! `(V, F, connectivity, material, smooth, UV)` signature, then recovers exact
+ //! rigid + scale transforms (`Trs`) from "deep-transformed" copies via fast
+ //! pointer/translation paths and a deterministic 4-point canonical basis
+ //! (`L = B * A^-1`, verified across every vertex to `< 1e-4 * diag`).
+ //! - **Layer 3 (`int4` ScenePackPolicy):** A ~200-byte integer-only quantized
+ //! MLP (`12 -> 16 -> 4`, `~0.5 µs` CPU/WASM, bit-exact) that selects per-cluster
+ //! packaging (`Standalone`, `DataInstance`, `GpuInstance`, or
+ //! `GpuInstanceSpatialCells`) for glTF 2.0 / `EXT_mesh_gpu_instancing` export.
+
+ use crate::math::Vec3;
+ use crate::mesh::PolyMesh;
+ use std::collections::HashMap;
+ use std::sync::Arc;
+
+ /// glTF-ready Translation / Rotation (unit quaternion `[x,y,z,w]`) / Scale transform.
+ #[derive(Debug, Clone, Copy, PartialEq)]
+ pub struct Trs {
+ pub translation: [f64; 3],
+ /// Unit quaternion `[x, y, z, w]` (glTF 2.0 order).
+ pub rotation: [f64; 4],
+ pub scale: [f64; 3],
+ }
+
+ impl Trs {
+ pub const IDENTITY: Self = Self {
+ translation: [0.0, 0.0, 0.0],
+ rotation: [0.0, 0.0, 0.0, 1.0],
+ scale: [1.0, 1.0, 1.0],
+ };
+
+ #[inline]
+ pub fn from_translation(t: Vec3) -> Self {
+ Self {
+ translation: [t.x, t.y, t.z],
+ rotation: [0.0, 0.0, 0.0, 1.0],
+ scale: [1.0, 1.0, 1.0],
+ }
+ }
+
+ /// Construct from Forma's exact Euler XYZ degrees (`PolyMesh::rotate_deg`), scale, and translation:
+ /// applies scale -> Euler XYZ rotation -> translation (`p' = R * (s * p) + t`).
+ pub fn from_translation_rot_deg_scale(t: Vec3, rot_deg: Vec3, scale: Vec3) -> Self {
+ let r = Vec3::euler_xyz_deg_matrix(rot_deg.x, rot_deg.y, rot_deg.z);
+ let q = mat3_to_quat(&r);
+ Self {
+ translation: [t.x, t.y, t.z],
+ rotation: q,
+ scale: [scale.x, scale.y, scale.z],
+ }
+ }
+
+ /// Extract exact glTF `Trs` (`L = R * diag(s)`) from a 3x3 linear matrix and translation.
+ /// Returns `None` if the matrix is singular, reflected (`det <= 0`), or sheared.
+ pub fn from_mat3_translation(l: [[f64; 3]; 3], t: Vec3) -> Option<Self> {
+ let det = mat3_det(&l);
+ if !det.is_finite() || det <= 1e-12 {
+ return None;
+ }
+ // Column vectors of L
+ let c0 = Vec3::new(l[0][0], l[1][0], l[2][0]);
+ let c1 = Vec3::new(l[0][1], l[1][1], l[2][1]);
+ let c2 = Vec3::new(l[0][2], l[1][2], l[2][2]);
+ let sx = c0.len();
+ let sy = c1.len();
+ let sz = c2.len();
+ if sx <= 1e-9 || sy <= 1e-9 || sz <= 1e-9 {
+ return None;
+ }
+ let r0 = c0 * (1.0 / sx);
+ let r1 = c1 * (1.0 / sy);
+ let r2 = c2 * (1.0 / sz);
+
+ // Reject shear: columns of R must be mutually orthogonal and right-handed
+ if r0.dot(r1).abs() > 1e-3 || r0.dot(r2).abs() > 1e-3 || r1.dot(r2).abs() > 1e-3 {
+ return None;
+ }
+ if r0.cross(r1).dot(r2) < 0.999 {
+ return None;
+ }
+
+ // Orthonormalize cleanly via polar/Gram-Schmidt polish for exact unit quaternion
+ let u0 = r0.normalized();
+ let u1 = (r1 - u0 * u0.dot(r1)).normalized();
+ let u2 = u0.cross(u1).normalized();
+ let r = [
+ [u0.x, u1.x, u2.x],
+ [u0.y, u1.y, u2.y],
+ [u0.z, u1.z, u2.z],
+ ];
+ let q = mat3_to_quat(&r);
+ Some(Self {
+ translation: [t.x, t.y, t.z],
+ rotation: q,
+ scale: [sx, sy, sz],
+ })
+ }
+
+ #[inline]
+ pub fn rotation_mat3(&self) -> [[f64; 3]; 3] {
+ quat_to_mat3(self.rotation)
+ }
+
+ #[inline]
+ pub fn linear_mat3(&self) -> [[f64; 3]; 3] {
+ let r = self.rotation_mat3();
+ let [sx, sy, sz] = self.scale;
+ [
+ [r[0][0] * sx, r[0][1] * sy, r[0][2] * sz],
+ [r[1][0] * sx, r[1][1] * sy, r[1][2] * sz],
+ [r[2][0] * sx, r[2][1] * sy, r[2][2] * sz],
+ ]
+ }
+
+ #[inline]
+ pub fn apply_point(&self, p: Vec3) -> Vec3 {
+ let sp = Vec3::new(p.x * self.scale[0], p.y * self.scale[1], p.z * self.scale[2]);
+ let r = self.rotation_mat3();
+ let rp = sp.mul_mat3(&r);
+ Vec3::new(
+ rp.x + self.translation[0],
+ rp.y + self.translation[1],
+ rp.z + self.translation[2],
+ )
+ }
+
+ /// Compose `self * inner` (applying `inner` first, then `self`).
+ /// Returns `None` if the composition introduces shear (e.g. rotated non-uniform scale).
+ pub fn compose(&self, inner: &Trs) -> Option<Trs> {
+ if self.is_identity() {
+ return Some(*inner);
+ }
+ if inner.is_identity() {
+ return Some(*self);
+ }
+ let l_a = self.linear_mat3();
+ let l_b = inner.linear_mat3();
+ let l = mat3_mul(&l_a, &l_b);
+ let tb = Vec3::new(inner.translation[0], inner.translation[1], inner.translation[2]);
+ let t = tb.mul_mat3(&l_a)
+ + Vec3::new(self.translation[0], self.translation[1], self.translation[2]);
+ Self::from_mat3_translation(l, t)
+ }
+
+ /// Convert Z-up model-unit TRS to glTF coordinate space (`yup` and `unit_scale = meters_per_unit`).
+ /// Uses exact similarity transform `C * R * C^T` and `C * S * C^T = (sx, sz, sy)` where
+ /// `C(x, y, z) = (x, z, -y)` is a proper rotation (`det = +1`).
+ pub fn to_gltf_space(&self, yup: bool, unit_scale: f64) -> Trs {
+ if !yup {
+ return Trs {
+ translation: [
+ self.translation[0] * unit_scale,
+ self.translation[1] * unit_scale,
+ self.translation[2] * unit_scale,
+ ],
+ rotation: self.rotation,
+ scale: self.scale,
+ };
+ }
+ let t = [
+ self.translation[0] * unit_scale,
+ self.translation[2] * unit_scale,
+ -self.translation[1] * unit_scale,
+ ];
+ let s = [self.scale[0], self.scale[2], self.scale[1]];
+ let q = if self.has_rotation() {
+ // Exact C * R * C^T for C = [[1,0,0],[0,0,1],[0,-1,0]]:
+ // Row/col remap: 0->0, 1->+2, 2->-1
+ let r = self.rotation_mat3();
+ let r_yup = [
+ [r[0][0], r[0][2], -r[0][1]],
+ [r[2][0], r[2][2], -r[2][1]],
+ [-r[1][0], -r[1][2], r[1][1]],
+ ];
+ mat3_to_quat(&r_yup)
+ } else {
+ [0.0, 0.0, 0.0, 1.0]
+ };
+ Trs {
+ translation: t,
+ rotation: q,
+ scale: s,
+ }
+ }
+
+ #[inline]
+ pub fn has_translation(&self) -> bool {
+ self.translation[0].abs() > 1e-9
+ || self.translation[1].abs() > 1e-9
+ || self.translation[2].abs() > 1e-9
+ }
+
+ #[inline]
+ pub fn has_rotation(&self) -> bool {
+ self.rotation[0].abs() > 1e-7
+ || self.rotation[1].abs() > 1e-7
+ || self.rotation[2].abs() > 1e-7
+ || (self.rotation[3].abs() - 1.0).abs() > 1e-7
+ }
+
+ #[inline]
+ pub fn has_scale(&self) -> bool {
+ (self.scale[0] - 1.0).abs() > 1e-7
+ || (self.scale[1] - 1.0).abs() > 1e-7
+ || (self.scale[2] - 1.0).abs() > 1e-7
+ }
+
+ #[inline]
+ pub fn is_nonuniform_scale(&self) -> bool {
+ (self.scale[0] - self.scale[1]).abs() > 1e-5
+ || (self.scale[0] - self.scale[2]).abs() > 1e-5
+ }
+
+ #[inline]
+ pub fn is_identity(&self) -> bool {
+ !self.has_translation() && !self.has_rotation() && !self.has_scale()
+ }
+
+ /// Return a transformed copy of `mesh` with this TRS baked into vertex positions
+ /// (used by software studio PNG rendering and SVG blueprints).
+ pub fn transform_mesh(&self, mesh: &PolyMesh) -> PolyMesh {
+ if self.is_identity() {
+ return mesh.clone();
+ }
+ let mut out = mesh.clone();
+ let l = self.linear_mat3();
+ let t = Vec3::new(self.translation[0], self.translation[1], self.translation[2]);
+ for v in &mut out.verts {
+ *v = v.mul_mat3(&l) + t;
+ }
+ out
+ }
+ }
+
+ #[inline]
+ fn mat3_det(m: &[[f64; 3]; 3]) -> f64 {
+ m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
+ - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
+ }
+
+ #[inline]
+ fn mat3_mul(a: &[[f64; 3]; 3], b: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {
+ let mut out = [[0.0; 3]; 3];
+ for i in 0..3 {
+ for j in 0..3 {
+ out[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j];
+ }
+ }
+ out
+ }
+
+ fn mat3_inv(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
+ let det = mat3_det(m);
+ if !det.is_finite() || det.abs() <= 1e-18 {
+ return None;
+ }
+ let inv_d = 1.0 / det;
+ Some([
+ [
+ (m[1][1] * m[2][2] - m[1][2] * m[2][1]) * inv_d,
+ (m[0][2] * m[2][1] - m[0][1] * m[2][2]) * inv_d,
+ (m[0][1] * m[1][2] - m[0][2] * m[1][1]) * inv_d,
+ ],
+ [
+ (m[1][2] * m[2][0] - m[1][0] * m[2][2]) * inv_d,
+ (m[0][0] * m[2][2] - m[0][2] * m[2][0]) * inv_d,
+ (m[0][2] * m[1][0] - m[0][0] * m[1][2]) * inv_d,
+ ],
+ [
+ (m[1][0] * m[2][1] - m[1][1] * m[2][0]) * inv_d,
+ (m[0][1] * m[2][0] - m[0][0] * m[2][1]) * inv_d,
+ (m[0][0] * m[1][1] - m[0][1] * m[1][0]) * inv_d,
+ ],
+ ])
+ }
+
+ /// Convert proper 3x3 rotation matrix to unit quaternion `[x, y, z, w]` (Shepperd's method).
+ pub fn mat3_to_quat(m: &[[f64; 3]; 3]) -> [f64; 4] {
+ let tr = m[0][0] + m[1][1] + m[2][2];
+ let (mut x, mut y, mut z, mut w) = if tr > 0.0 {
+ let s = (tr + 1.0).sqrt() * 2.0;
+ (
+ (m[2][1] - m[1][2]) / s,
+ (m[0][2] - m[2][0]) / s,
+ (m[1][0] - m[0][1]) / s,
+ 0.25 * s,
+ )
+ } else if m[0][0] > m[1][1] && m[0][0] > m[2][2] {
+ let s = (1.0 + m[0][0] - m[1][1] - m[2][2]).sqrt() * 2.0;
+ (
+ 0.25 * s,
+ (m[0][1] + m[1][0]) / s,
+ (m[0][2] + m[2][0]) / s,
+ (m[2][1] - m[1][2]) / s,
+ )
+ } else if m[1][1] > m[2][2] {
+ let s = (1.0 + m[1][1] - m[0][0] - m[2][2]).sqrt() * 2.0;
+ (
+ (m[0][1] + m[1][0]) / s,
+ 0.25 * s,
+ (m[1][2] + m[2][1]) / s,
+ (m[0][2] - m[2][0]) / s,
+ )
+ } else {
+ let s = (1.0 + m[2][2] - m[0][0] - m[1][1]).sqrt() * 2.0;
+ (
+ (m[0][2] + m[2][0]) / s,
+ (m[1][2] + m[2][1]) / s,
+ 0.25 * s,
+ (m[1][0] - m[0][1]) / s,
+ )
+ };
+ let len = (x * x + y * y + z * z + w * w).sqrt();
+ if len > 1e-12 {
+ let inv = 1.0 / len;
+ x *= inv;
+ y *= inv;
+ z *= inv;
+ w *= inv;
+ } else {
+ return [0.0, 0.0, 0.0, 1.0];
+ }
+ // Canonical hemisphere (`w >= 0`) so identical rotations always produce identical quaternions
+ if w < 0.0 {
+ [-x, -y, -z, -w]
+ } else {
+ [x, y, z, w]
+ }
+ }
+
+ pub fn quat_to_mat3(q: [f64; 4]) -> [[f64; 3]; 3] {
+ let [x, y, z, w] = q;
+ let x2 = x + x;
+ let y2 = y + y;
+ let z2 = z + z;
+ let xx = x * x2;
+ let xy = x * y2;
+ let xz = x * z2;
+ let yy = y * y2;
+ let yz = y * z2;
+ let zz = z * z2;
+ let wx = w * x2;
+ let wy = w * y2;
+ let wz = w * z2;
+ [
+ [1.0 - (yy + zz), xy - wz, xz + wy],
+ [xy + wz, 1.0 - (xx + zz), yz - wx],
+ [xz - wy, yz + wx, 1.0 - (xx + yy)],
+ ]
+ }
+
+ // ---------------------------------------------------------------------------
+ // Layer 1: O(V) Connectivity-Hash + 4-Point Canonical Transform Deduplication
+ // ---------------------------------------------------------------------------
+
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+ struct MeshSignature {
+ n_verts: usize,
+ n_faces: usize,
+ smooth_bits: u64,
+ weighted_normals: bool,
+ mat_hash: u64,
+ topo_uv_hash: u64,
+ }
+
+ #[inline]
+ fn fnv_mix(mut h: u64, v: u64) -> u64 {
+ h ^= v;
+ h.wrapping_mul(0x100000001b3)
+ }
+
+ fn compute_mesh_signature(mesh: &PolyMesh) -> MeshSignature {
+ const FNV_OFFSET: u64 = 0xcbf29ce484222325;
+
+ let mut mat_hash = FNV_OFFSET;
+ mat_hash = fnv_mix(mat_hash, mesh.materials.len() as u64);
+ for m in &mesh.materials {
+ for &b in m.name.as_bytes() {
+ mat_hash = fnv_mix(mat_hash, b as u64);
+ }
+ for c in m.color {
+ mat_hash = fnv_mix(mat_hash, c.to_bits() as u64);
+ }
+ mat_hash = fnv_mix(mat_hash, m.metallic.to_bits() as u64);
+ mat_hash = fnv_mix(mat_hash, m.roughness.to_bits() as u64);
++ for e in m.emissive {
++ mat_hash = fnv_mix(mat_hash, e.to_bits() as u64);
++ }
++ mat_hash = fnv_mix(mat_hash, m.emissive_strength.to_bits() as u64);
++ mat_hash = fnv_mix(mat_hash, m.transmission.to_bits() as u64);
++ mat_hash = fnv_mix(mat_hash, m.ior.to_bits() as u64);
++ mat_hash = fnv_mix(mat_hash, m.double_sided as u64);
+ }
+
+ let mut topo_uv_hash = FNV_OFFSET;
+ for f in &mesh.faces {
+ topo_uv_hash = fnv_mix(topo_uv_hash, f.verts.len() as u64);
+ topo_uv_hash = fnv_mix(topo_uv_hash, f.mat_id as u64);
+ for &vi in &f.verts {
+ topo_uv_hash = fnv_mix(topo_uv_hash, vi as u64);
+ }
+ topo_uv_hash = fnv_mix(topo_uv_hash, f.uvs.len() as u64);
+ for uv in &f.uvs {
+ let uq = (uv[0] * 1e4).round() as i64 as u64;
+ let vq = (uv[1] * 1e4).round() as i64 as u64;
+ topo_uv_hash = fnv_mix(topo_uv_hash, uq);
+ topo_uv_hash = fnv_mix(topo_uv_hash, vq);
+ }
+ }
+
+ MeshSignature {
+ n_verts: mesh.verts.len(),
+ n_faces: mesh.faces.len(),
+ smooth_bits: mesh.smooth_angle_deg.map(|d| d.to_bits()).unwrap_or(u64::MAX),
+ weighted_normals: mesh.weighted_normals,
+ mat_hash,
+ topo_uv_hash,
+ }
+ }
+
+ /// Select 4 well-conditioned spanning vertex indices `[i0, i1, i2, i3]` on `mesh`
+ /// using greedy max-distance / max-area / max-volume selection with a 1.01 tie margin.
+ fn select_canonical_frame(mesh: &PolyMesh) -> Option<([usize; 4], [[f64; 3]; 3], f64)> {
+ let nv = mesh.verts.len();
+ if nv < 4 {
+ return None;
+ }
+ let bb = mesh.aabb();
+ let diag = bb.size().len();
+ if diag <= 1e-12 {
+ return None;
+ }
+
+ let i0 = 0usize;
+ let p0 = mesh.verts[i0];
+
+ let mut i1 = 0usize;
+ let mut best_d1 = 0.0;
+ for (i, &p) in mesh.verts.iter().enumerate() {
+ let d2 = (p - p0).len_sq();
+ if d2 > best_d1 * 1.01 {
+ best_d1 = d2;
+ i1 = i;
+ }
+ }
+ if best_d1 <= 1e-18 * diag * diag {
+ return None;
+ }
+ let e1 = mesh.verts[i1] - p0;
+
+ let mut i2 = 0usize;
+ let mut best_a2 = 0.0;
+ for (i, &p) in mesh.verts.iter().enumerate() {
+ let a2 = e1.cross(p - p0).len_sq();
+ if a2 > best_a2 * 1.01 {
+ best_a2 = a2;
+ i2 = i;
+ }
+ }
+ if best_a2 <= 1e-18 * diag * diag * diag * diag {
+ return None;
+ }
+ let e2 = mesh.verts[i2] - p0;
+ let n12 = e1.cross(e2);
+
+ let mut i3 = 0usize;
+ let mut best_v = 0.0;
+ for (i, &p) in mesh.verts.iter().enumerate() {
+ let v = n12.dot(p - p0).abs();
+ if v > best_v * 1.01 {
+ best_v = v;
+ i3 = i;
+ }
+ }
+ if best_v <= 1e-12 * diag * diag * diag {
+ return None;
+ }
+ let e3 = mesh.verts[i3] - p0;
+
+ let a = [
+ [e1.x, e2.x, e3.x],
+ [e1.y, e2.y, e3.y],
+ [e1.z, e2.z, e3.z],
+ ];
+ let a_inv = mat3_inv(&a)?;
+ Some(([i0, i1, i2, i3], a_inv, diag))
+ }
+
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ enum MatchKind {
+ Identical,
+ Translation,
+ RigidScale,
+ }
+
+ /// Recover an exact `Trs` mapping `proto` vertices onto `cand` vertices (`cand ≈ trs(proto)`).
+ /// Runs in O(V) with strict full-mesh verification (`max_err <= 1e-4 * diag`).
+ fn solve_trs_between(
+ proto: &PolyMesh,
+ proto_frame: Option<([usize; 4], [[f64; 3]; 3], f64)>,
+ cand: &PolyMesh,
+ ) -> Option<(Trs, MatchKind)> {
+ let nv = proto.verts.len();
+ if nv == 0 || nv != cand.verts.len() || proto.faces.len() != cand.faces.len() {
+ return None;
+ }
+ // Verify identical face-vertex topology (guards against any 64-bit hash collision)
+ for (fa, fb) in proto.faces.iter().zip(&cand.faces) {
+ if fa.verts != fb.verts || fa.mat_id != fb.mat_id {
+ return None;
+ }
+ }
+
+ let diag = proto_frame
+ .map(|(_, _, d)| d)
+ .unwrap_or_else(|| proto.aabb().size().len())
+ .max(1e-6);
+ let cand_diag = cand.aabb().size().len().max(1e-6);
+ let tol = 1e-4 * diag.max(cand_diag);
+ let tol_sq = tol * tol;
+
+ // Fast path 1 & 2: pure translation (including identity)
+ let dt = cand.verts[0] - proto.verts[0];
+ let mut pure_trans = true;
+ for i in 1..nv {
+ let diff = (proto.verts[i] + dt) - cand.verts[i];
+ if diff.len_sq() > tol_sq {
+ pure_trans = false;
+ break;
+ }
+ }
+ if pure_trans {
+ let kind = if dt.len_sq() <= 1e-18 {
+ MatchKind::Identical
+ } else {
+ MatchKind::Translation
+ };
+ return Some((Trs::from_translation(dt), kind));
+ }
+
+ // General path 3: 4-point canonical frame -> L = B * A^-1, t = q0 - L * p0
+ let ([i0, i1, i2, i3], a_inv, _) = proto_frame?;
+ let p0 = proto.verts[i0];
+ let q0 = cand.verts[i0];
+ let f1 = cand.verts[i1] - q0;
+ let f2 = cand.verts[i2] - q0;
+ let f3 = cand.verts[i3] - q0;
+ let b = [
+ [f1.x, f2.x, f3.x],
+ [f1.y, f2.y, f3.y],
+ [f1.z, f2.z, f3.z],
+ ];
+ let l = mat3_mul(&b, &a_inv);
+ let t = q0 - p0.mul_mat3(&l);
+ let trs = Trs::from_mat3_translation(l, t)?;
+ let l_clean = trs.linear_mat3();
+ let t_clean = Vec3::new(trs.translation[0], trs.translation[1], trs.translation[2]);
+
+ // Full O(V) verification pass: guarantee zero visual error across every vertex
+ for i in 0..nv {
+ let pred = proto.verts[i].mul_mat3(&l_clean) + t_clean;
+ if (pred - cand.verts[i]).len_sq() > tol_sq {
+ return None;
+ }
+ }
+ Some((trs, MatchKind::RigidScale))
+ }
+
+ /// Input node for scene GLB export (combining baked parts and explicit `inst(...)` instances).
+ #[derive(Debug, Clone, Copy)]
+ pub struct SceneExportNode<'a> {
+ pub name: &'a str,
+ pub group: Option<&'a str>,
+ pub mesh: &'a Arc<PolyMesh>,
+ pub trs: Trs,
+ }
+
+ #[derive(Debug, Clone)]
+ pub struct DedupInstance<'a> {
+ pub name: &'a str,
+ pub group: Option<&'a str>,
+ pub proto_idx: usize,
+ pub trs: Trs,
+ }
+
+ #[derive(Debug, Clone, Default)]
+ pub struct DedupStats {
+ pub input_nodes: usize,
+ pub unique_meshes: usize,
+ pub deduplicated_instances: usize,
+ pub ptr_hits: usize,
+ pub translation_hits: usize,
+ pub rigid_scale_hits: usize,
+ }
+
+ #[derive(Debug)]
+ pub struct DeduplicatedScene<'a> {
+ pub prototypes: Vec<&'a Arc<PolyMesh>>,
+ pub instances: Vec<DedupInstance<'a>>,
+ pub stats: DedupStats,
+ }
+
+ /// Deduplicate scene nodes in O(N * V) by structural signature + exact TRS recovery.
+ pub fn deduplicate_scene_nodes<'a>(nodes: &[SceneExportNode<'a>]) -> DeduplicatedScene<'a> {
+ struct ProtoEntry<'a> {
+ proto_idx: usize,
+ mesh: &'a Arc<PolyMesh>,
+ frame: Option<([usize; 4], [[f64; 3]; 3], f64)>,
+ frame_computed: bool,
+ }
+
+ let mut prototypes: Vec<&'a Arc<PolyMesh>> = Vec::new();
+ let mut instances: Vec<DedupInstance<'a>> = Vec::with_capacity(nodes.len());
+ let mut stats = DedupStats {
+ input_nodes: nodes.len(),
+ ..Default::default()
+ };
+
+ let mut ptr_to_proto: HashMap<usize, usize> = HashMap::new();
+ let mut ptr_to_sig: HashMap<usize, MeshSignature> = HashMap::new();
+ let mut buckets: HashMap<MeshSignature, Vec<ProtoEntry<'a>>> = HashMap::new();
+
+ for node in nodes {
+ if node.mesh.faces.is_empty() || node.mesh.verts.is_empty() {
+ continue;
+ }
+ let ptr = Arc::as_ptr(node.mesh) as usize;
+
+ // O(1) pointer fast path (explicit `inst(...)` shares the exact Arc<PolyMesh>!)
+ if let Some(&proto_idx) = ptr_to_proto.get(&ptr) {
+ stats.ptr_hits += 1;
+ stats.deduplicated_instances += 1;
+ instances.push(DedupInstance {
+ name: node.name,
+ group: node.group,
+ proto_idx,
+ trs: node.trs,
+ });
+ continue;
+ }
+
+ let sig = *ptr_to_sig
+ .entry(ptr)
+ .or_insert_with(|| compute_mesh_signature(node.mesh));
+
+ let bucket = buckets.entry(sig).or_default();
+ let mut matched: Option<(usize, Trs)> = None;
+
+ for entry in bucket.iter_mut() {
+ if !entry.frame_computed {
+ entry.frame = select_canonical_frame(entry.mesh);
+ entry.frame_computed = true;
+ }
+ if let Some((recovered, kind)) = solve_trs_between(entry.mesh, entry.frame, node.mesh) {
+ if let Some(combined) = node.trs.compose(&recovered) {
+ match kind {
+ MatchKind::Identical => stats.translation_hits += 1,
+ MatchKind::Translation => stats.translation_hits += 1,
+ MatchKind::RigidScale => stats.rigid_scale_hits += 1,
+ }
+ stats.deduplicated_instances += 1;
+ matched = Some((entry.proto_idx, combined));
+ break;
+ }
+ }
+ }
+
+ if let Some((proto_idx, trs)) = matched {
+ instances.push(DedupInstance {
+ name: node.name,
+ group: node.group,
+ proto_idx,
+ trs,
+ });
+ } else {
+ let proto_idx = prototypes.len();
+ prototypes.push(node.mesh);
+ ptr_to_proto.insert(ptr, proto_idx);
+ bucket.push(ProtoEntry {
+ proto_idx,
+ mesh: node.mesh,
+ frame: None,
+ frame_computed: false,
+ });
+ instances.push(DedupInstance {
+ name: node.name,
+ group: node.group,
+ proto_idx,
+ trs: node.trs,
+ });
+ }
+ }
+
+ stats.unique_meshes = prototypes.len();
+ DeduplicatedScene {
+ prototypes,
+ instances,
+ stats,
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Layer 3: Tiny Quantized (`int4`) Scene Export Packaging Bandit (~200 bytes)
+ // ---------------------------------------------------------------------------
+
+ /// glTF scene packaging strategy chosen per deduplicated prototype cluster.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ pub enum ScenePackStrategy {
+ /// Single unique instance (`N == 1`): standard standalone glTF node.
+ Standalone = 0,
+ /// Core glTF 2.0 data instancing (`nodes[i].mesh = proto` + TRS): universal
+ /// compatibility (Blender, Unreal, Three.js, Godot) with full per-node naming.
+ DataInstance = 1,
+ /// Single-batch `EXT_mesh_gpu_instancing` node (`TRANSLATION`/`ROTATION`/`SCALE`).
+ GpuInstance = 2,
+ /// Spatial 2x2x2 cell-partitioned `EXT_mesh_gpu_instancing` for wide instance clouds
+ /// so realtime engines preserve tight frustum culling.
+ GpuInstanceSpatialCells = 3,
+ }
+
+ /// Export options controlling glTF 2.0 scene packaging & instancing.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ pub struct GlbSceneOptions {
+ /// Convert Z-up model coordinates to glTF Y-up (default `true`).
+ pub yup: bool,
+ /// Enable automatic O(V) structural/geometric deduplication (default `true`).
+ pub deduplicate: bool,
+ /// Allow `EXT_mesh_gpu_instancing` when the `int4` packaging policy selects it
+ /// (default `false` so standard GLBs stay 100% core glTF 2.0 compatible).
+ pub gpu_instancing: bool,
+ /// Force per-instance named glTF nodes (prevents collapsing into GPU batches).
+ pub preserve_node_names: bool,
+ }
+
+ impl Default for GlbSceneOptions {
+ fn default() -> Self {
+ Self {
+ yup: true,
+ deduplicate: true,
+ gpu_instancing: false,
+ preserve_node_names: false,
+ }
+ }
+ }
+
+ impl GlbSceneOptions {
+ /// Realtime web/engine profile enabling `EXT_mesh_gpu_instancing` via the `int4` policy.
+ pub fn realtime() -> Self {
+ Self {
+ yup: true,
+ deduplicate: true,
+ gpu_instancing: true,
+ preserve_node_names: false,
+ }
+ }
+ }
+
+ /// 12 compact cluster features fed to the quantized `int4` packaging policy.
+ #[derive(Debug, Clone, Copy)]
+ pub struct ClusterPackFeatures {
+ pub instance_count: usize,
+ pub faces_per_instance: usize,
+ pub verts_per_instance: usize,
+ pub material_count: usize,
+ pub has_uvs: bool,
+ pub has_rotation: bool,
+ pub has_nonuniform_scale: bool,
+ /// Ratio of cluster centroid AABB diagonal to prototype AABB diagonal.
+ pub spatial_spread_ratio: f64,
+ /// Fraction of instances belonging to the dominant group path (`[0, 1]`).
+ pub same_group_fraction: f64,
+ pub allow_gpu_instancing: bool,
+ pub preserve_node_names: bool,
+ }
+
+ // Quantized `12 -> 8 -> 4` signed-int4 neural policy (packed 2 weights per byte = 64 bytes total!)
+ // Bit-exact integer-only inference (`~0.3 µs`), zero external dependencies, deterministic on x86/ARM/WASM.
+ //
+ // Feature order (quantized to [0..16]):
+ // f0: n == 1 ? 16 : 0
+ // f1: n >= 2 ? 16 : 0
+ // f2: n >= 4 ? 16 : 0
+ // f3: n >= 16 ? 16 : 0
+ // f4: log2(n) clamped to [0..16]
+ // f5: faces_per_instance >= 8 ? 16 : 4
+ // f6: spatial_spread_ratio >= 8.0 ? 16 : 0
+ // f7: spatial_spread_ratio >= 20.0 ? 16 : 0
+ // f8: same_group_fraction * 16
+ // f9: allow_gpu_instancing ? 16 : 0
+ // f10: preserve_node_names ? 16 : 0
+ // f11: has_nonuniform_scale ? 16 : 0
+
+ const fn pack_i4_pair(a: i8, b: i8) -> u8 {
+ (((a as u8) & 0x0F) << 4) | ((b as u8) & 0x0F)
+ }
+
+ #[inline]
+ fn unpack_i4(byte: u8, high: bool) -> i32 {
+ let nibble = if high { (byte >> 4) & 0x0F } else { byte & 0x0F };
+ if nibble >= 8 {
+ (nibble as i32) - 16
+ } else {
+ nibble as i32
+ }
+ }
+
+ // Layer 1: 8 hidden units x 12 inputs = 96 signed int4 weights = 48 packed bytes
+ // Hidden units encode clean regime detectors:
+ // h0: standalone (n == 1)
+ // h1: core data-instance baseline (n >= 2)
+ // h2: gpu eligible (n >= 4 && allow_gpu && !preserve_names)
+ // h3: high-count gpu boost (n >= 16 && allow_gpu && !preserve_names)
+ // h4: wide-spread spatial cell detector (n >= 16 && spread >= 8 && allow_gpu && !preserve_names)
+ // h5: extreme-spread boost (spread >= 20 && allow_gpu)
+ // h6: preserve-names veto on GPU instancing
+ // h7: low-poly high-count batching bonus
+ const PACK_W1: [u8; 48] = [
+ // h0: +7*f0 - 4*f1
+ pack_i4_pair(7, -4), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0),
+ // h1: -6*f0 + 6*f1 + 1*f8
+ pack_i4_pair(-6, 6), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(1, 0), pack_i4_pair(0, 0),
+ // h2: +5*f2 + 6*f9 - 7*f10
+ pack_i4_pair(0, 0), pack_i4_pair(5, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 6), pack_i4_pair(-7, 0),
+ // h3: +4*f3 + 2*f4 + 4*f9 - 7*f10
+ pack_i4_pair(0, 0), pack_i4_pair(0, 4), pack_i4_pair(2, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 4), pack_i4_pair(-7, 0),
+ // h4: +4*f3 + 5*f6 + 4*f9 - 7*f10
+ pack_i4_pair(0, 0), pack_i4_pair(0, 4), pack_i4_pair(0, 0), pack_i4_pair(5, 0), pack_i4_pair(0, 4), pack_i4_pair(-7, 0),
+ // h5: +3*f3 + 4*f7 + 3*f9 - 7*f10
+ pack_i4_pair(0, 0), pack_i4_pair(0, 3), pack_i4_pair(0, 0), pack_i4_pair(0, 4), pack_i4_pair(0, 3), pack_i4_pair(-7, 0),
+ // h6: +7*f10 - 2*f0
+ pack_i4_pair(-2, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(7, 0),
+ // h7: +2*f2 + 2*f4 - 1*f5 + 3*f9 - 6*f10
+ pack_i4_pair(0, 0), pack_i4_pair(2, 0), pack_i4_pair(2, -1), pack_i4_pair(0, 0), pack_i4_pair(0, 3), pack_i4_pair(-6, 0),
+ ];
+ const PACK_B1: [i32; 8] = [-16, -8, -96, -96, -128, -96, -16, -64];
+
+ // Layer 2: 4 arms x 8 hidden units = 32 signed int4 weights = 16 packed bytes
+ const PACK_W2: [u8; 16] = [
+ // Arm 0: Standalone
+ pack_i4_pair(7, -5), pack_i4_pair(-3, -3), pack_i4_pair(-3, -3), pack_i4_pair(0, -2),
+ // Arm 1: DataInstance
+ pack_i4_pair(-6, 6), pack_i4_pair(-2, -1), pack_i4_pair(-1, -1), pack_i4_pair(6, -1),
+ // Arm 2: GpuInstance
+ pack_i4_pair(-7, 1), pack_i4_pair(7, 4), pack_i4_pair(-4, -3), pack_i4_pair(-7, 3),
+ // Arm 3: GpuInstanceSpatialCells
+ pack_i4_pair(-7, 1), pack_i4_pair(3, 3), pack_i4_pair(7, 5), pack_i4_pair(-7, 1),
+ ];
+ const PACK_B2: [i32; 4] = [0, 8, -4, -12];
+
+ /// Select glTF scene packaging strategy for a deduplicated mesh cluster using the 64-byte `int4` MLP.
+ pub fn choose_scene_pack_strategy(f: &ClusterPackFeatures) -> ScenePackStrategy {
+ let n = f.instance_count;
+ let spread = if f.spatial_spread_ratio.is_finite() {
+ f.spatial_spread_ratio.max(0.0)
+ } else {
+ 0.0
+ };
+ let grp_frac = if f.same_group_fraction.is_finite() {
+ f.same_group_fraction.clamp(0.0, 1.0)
+ } else {
+ 0.0
+ };
+ let log_n = if n > 1 {
+ ((n as f64).log2() * 2.0).round().clamp(0.0, 16.0) as i32
+ } else {
+ 0
+ };
+
+ let x: [i32; 12] = [
+ if n <= 1 { 16 } else { 0 },
+ if n >= 2 { 16 } else { 0 },
+ if n >= 4 { 16 } else { 0 },
+ if n >= 16 { 16 } else { 0 },
+ log_n,
+ if f.faces_per_instance >= 8 { 16 } else { 4 },
+ if spread >= 8.0 { 16 } else { 0 },
+ if spread >= 20.0 { 16 } else { 0 },
+ (grp_frac * 16.0).round() as i32,
+ if f.allow_gpu_instancing { 16 } else { 0 },
+ if f.preserve_node_names { 16 } else { 0 },
+ if f.has_nonuniform_scale { 16 } else { 0 },
+ ];
+
+ let mut h = [0i32; 8];
+ for hi in 0..8 {
+ let mut acc = PACK_B1[hi];
+ let row_off = hi * 6;
+ for xi in 0..12 {
+ let w = unpack_i4(PACK_W1[row_off + (xi >> 1)], (xi & 1) == 0);
+ acc += w * x[xi];
+ }
+ // ReLU + right-shift by 4 (integer fixed-point activation)
+ h[hi] = if acc > 0 { acc >> 4 } else { 0 };
+ }
+
+ let mut scores = [0i32; 4];
+ for arm in 0..4 {
+ let mut acc = PACK_B2[arm];
+ let row_off = arm * 4;
+ for hi in 0..8 {
+ let w = unpack_i4(PACK_W2[row_off + (hi >> 1)], (hi & 1) == 0);
+ acc += w * h[hi];
+ }
+ scores[arm] = acc;
+ }
+
+ // Hard safety guard: never pick GPU instancing unless explicitly enabled & N >= 4
+ if !f.allow_gpu_instancing || f.preserve_node_names || n < 4 {
+ scores[2] = i32::MIN / 2;
+ scores[3] = i32::MIN / 2;
+ }
+ if n <= 1 {
+ return ScenePackStrategy::Standalone;
+ }
+
+ let mut best_arm = 1usize;
+ let mut best_score = scores[1];
+ for arm in [0usize, 2, 3] {
+ if scores[arm] > best_score {
+ best_score = scores[arm];
+ best_arm = arm;
+ }
+ }
+ match best_arm {
+ 0 => ScenePackStrategy::Standalone,
+ 1 => ScenePackStrategy::DataInstance,
+ 2 => ScenePackStrategy::GpuInstance,
+ _ => ScenePackStrategy::GpuInstanceSpatialCells,
+ }
+ }
+
+ /// Partition instance indices into up to 8 compact octant spatial cells (2x2x2 around centroid midpoint)
+ /// for frustum-culling-friendly `EXT_mesh_gpu_instancing` batches.
+ pub fn partition_spatial_cells(positions: &[[f64; 3]], indices: &[usize]) -> Vec<Vec<usize>> {
+ if indices.len() < 8 {
+ return vec![indices.to_vec()];
+ }
+ let mut bmin = [f64::INFINITY; 3];
+ let mut bmax = [f64::NEG_INFINITY; 3];
+ for &idx in indices {
+ let p = positions[idx];
+ for k in 0..3 {
+ bmin[k] = bmin[k].min(p[k]);
+ bmax[k] = bmax[k].max(p[k]);
+ }
+ }
+ let mid = [
+ 0.5 * (bmin[0] + bmax[0]),
+ 0.5 * (bmin[1] + bmax[1]),
+ 0.5 * (bmin[2] + bmax[2]),
+ ];
+ let mut cells: [Vec<usize>; 8] = Default::default();
+ for &idx in indices {
+ let p = positions[idx];
+ let bx = usize::from(p[0] >= mid[0]);
+ let by = usize::from(p[1] >= mid[1]);
+ let bz = usize::from(p[2] >= mid[2]);
+ cells[(bz << 2) | (by << 1) | bx].push(idx);
+ }
+ cells.into_iter().filter(|c| !c.is_empty()).collect()
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+ use crate::primitives::{make_box, make_cylinder};
+
+ #[test]
+ fn trs_exact_recovery_for_translation_rotation_and_nonuniform_scale() {
+ let proto = Arc::new(make_box(0.4, 0.2, 1.2, 1));
+
+ // Copy 1: pure translation
+ let mut c1 = (*proto).clone();
+ c1.translate(Vec3::new(3.5, -1.25, 0.8));
+ let c1 = Arc::new(c1);
+
+ // Copy 2: non-uniform scale + arbitrary 3D Euler rotation + translation
+ let mut c2 = (*proto).clone();
+ c2.scale(Vec3::new(1.5, 0.75, 2.0));
+ c2.rotate_deg(25.0, -40.0, 65.0);
+ c2.translate(Vec3::new(-2.0, 4.0, 1.1));
+ let c2 = Arc::new(c2);
+
+ let nodes = [
+ SceneExportNode { name: "bar_0", group: Some("drum"), mesh: &proto, trs: Trs::IDENTITY },
+ SceneExportNode { name: "bar_1", group: Some("drum"), mesh: &c1, trs: Trs::IDENTITY },
+ SceneExportNode { name: "bar_2", group: Some("drum"), mesh: &c2, trs: Trs::IDENTITY },
+ ];
+ let dedup = deduplicate_scene_nodes(&nodes);
+ assert_eq!(dedup.stats.unique_meshes, 1, "all 3 bars must collapse to 1 prototype");
+ assert_eq!(dedup.stats.translation_hits, 1);
+ assert_eq!(dedup.stats.rigid_scale_hits, 1);
+
+ // Verify exact vertex reconstruction in both Z-up and glTF Y-up space
+ for (inst, orig) in dedup.instances.iter().zip([&proto, &c1, &c2]) {
+ let trs_yup = inst.trs.to_gltf_space(true, 1.0);
+ for (vp, vo) in proto.verts.iter().zip(&orig.verts) {
+ let rec = inst.trs.apply_point(*vp);
+ assert!((rec - *vo).len() < 1e-6, "Z-up mismatch: {rec:?} vs {vo:?}");
+
+ let vp_yup = Vec3::new(vp.x, vp.z, -vp.y);
+ let vo_yup = Vec3::new(vo.x, vo.z, -vo.y);
+ let rec_yup = trs_yup.apply_point(vp_yup);
+ assert!((rec_yup - vo_yup).len() < 1e-6, "Y-up mismatch: {rec_yup:?} vs {vo_yup:?}");
+ }
+ }
+ }
+
+ #[test]
+ fn trs_dedup_rejects_reflected_or_different_topology_safely() {
+ let proto = Arc::new(make_cylinder(0.3, 1.0, 16, 1));
+ let mut mirrored = (*proto).clone();
+ for v in &mut mirrored.verts {
+ v.x = -v.x;
+ }
+ let mirrored = Arc::new(mirrored);
+ let nodes = [
+ SceneExportNode { name: "a", group: None, mesh: &proto, trs: Trs::IDENTITY },
+ SceneExportNode { name: "b", group: None, mesh: &mirrored, trs: Trs::IDENTITY },
+ ];
+ let dedup = deduplicate_scene_nodes(&nodes);
+ assert_eq!(dedup.stats.unique_meshes, 2, "negative-det reflection must not falsely alias");
+ }
+
+ #[test]
+ fn int4_scene_pack_policy_routes_all_four_regimes_deterministically() {
+ let base = ClusterPackFeatures {
+ instance_count: 1,
+ faces_per_instance: 120,
+ verts_per_instance: 80,
+ material_count: 1,
+ has_uvs: false,
+ has_rotation: false,
+ has_nonuniform_scale: false,
+ spatial_spread_ratio: 1.0,
+ same_group_fraction: 1.0,
+ allow_gpu_instancing: false,
+ preserve_node_names: false,
+ };
+ assert_eq!(choose_scene_pack_strategy(&base), ScenePackStrategy::Standalone);
+
+ // Editable CAD/arch repeat (core glTF 2.0 default)
+ let mut arch = base;
+ arch.instance_count = 64;
+ assert_eq!(choose_scene_pack_strategy(&arch), ScenePackStrategy::DataInstance);
+
+ // Compact dense grille with GPU instancing enabled -> GpuInstance
+ let mut grille = arch;
+ grille.allow_gpu_instancing = true;
+ grille.spatial_spread_ratio = 3.0;
+ assert_eq!(choose_scene_pack_strategy(&grille), ScenePackStrategy::GpuInstance);
+
+ // Wide spatially-spread forest/city cloud -> GpuInstanceSpatialCells
+ let mut wide = grille;
+ wide.spatial_spread_ratio = 28.0;
+ assert_eq!(choose_scene_pack_strategy(&wide), ScenePackStrategy::GpuInstanceSpatialCells);
+
+ // preserve_node_names forces DataInstance even when gpu_instancing is on
+ let mut named = wide;
+ named.preserve_node_names = true;
+ assert_eq!(choose_scene_pack_strategy(&named), ScenePackStrategy::DataInstance);
+ }
+ }
diff --cc crates/forma-core/src/render.rs
index 9aa969e,3ac17c5..b620cf0
--- a/crates/forma-core/src/render.rs
+++ b/crates/forma-core/src/render.rs
@@@ -169,101 -169,120 +169,243 @@@ impl Framebuffer
}
}
- /// Alpha-blended triangle rasterizer tested against opaque `zbuf` without writing depth.
+ fn raster_tri_gouraud(
+ &mut self,
+ p0: [f32; 3],
+ p1: [f32; 3],
+ p2: [f32; 3],
+ c0: [f32; 3],
+ c1: [f32; 3],
+ c2: [f32; 3],
+ vp: (i32, i32, i32, i32),
+ ) {
+ let area = (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]);
+ let abs_area = area.abs();
+ if abs_area < 1e-4 {
+ return;
+ }
+
+ let min_x = p0[0].min(p1[0]).min(p2[0]).floor() as i32;
+ let max_x = p0[0].max(p1[0]).max(p2[0]).ceil() as i32;
+ let min_y = p0[1].min(p1[1]).min(p2[1]).floor() as i32;
+ let max_y = p0[1].max(p1[1]).max(p2[1]).ceil() as i32;
+
+ let x0 = min_x.max(vp.0);
+ let x1 = max_x.min(vp.2 - 1);
+ let y0 = min_y.max(vp.1);
+ let y1 = max_y.min(vp.3 - 1);
+ if x0 > x1 || y0 > y1 {
+ return;
+ }
+
+ let sign = area.signum();
+ let inv_area_s = 1.0 / abs_area;
+
+ let e0_dx = (p1[1] - p2[1]) * sign;
+ let e0_dy = (p2[0] - p1[0]) * sign;
+ let e1_dx = (p2[1] - p0[1]) * sign;
+ let e1_dy = (p0[0] - p2[0]) * sign;
+ let e2_dx = (p0[1] - p1[1]) * sign;
+ let e2_dy = (p1[0] - p0[0]) * sign;
+
+ let dz_dw1 = (p1[2] - p0[2]) * inv_area_s;
+ let dz_dw2 = (p2[2] - p0[2]) * inv_area_s;
+ let dz_dx = e1_dx * dz_dw1 + e2_dx * dz_dw2;
+ let dz_dy = e1_dy * dz_dw1 + e2_dy * dz_dw2;
+
+ let dr_dw1 = (c1[0] - c0[0]) * inv_area_s;
+ let dr_dw2 = (c2[0] - c0[0]) * inv_area_s;
+ let dr_dx = e1_dx * dr_dw1 + e2_dx * dr_dw2;
+ let dr_dy = e1_dy * dr_dw1 + e2_dy * dr_dw2;
+
+ let dg_dw1 = (c1[1] - c0[1]) * inv_area_s;
+ let dg_dw2 = (c2[1] - c0[1]) * inv_area_s;
+ let dg_dx = e1_dx * dg_dw1 + e2_dx * dg_dw2;
+ let dg_dy = e1_dy * dg_dw1 + e2_dy * dg_dw2;
+
+ let db_dw1 = (c1[2] - c0[2]) * inv_area_s;
+ let db_dw2 = (c2[2] - c0[2]) * inv_area_s;
+ let db_dx = e1_dx * db_dw1 + e2_dx * db_dw2;
+ let db_dy = e1_dy * db_dw1 + e2_dy * db_dw2;
+
+ let px0 = x0 as f32 + 0.5;
+ let py0 = y0 as f32 + 0.5;
+ let mut w0_row = ((p1[0] - px0) * (p2[1] - py0) - (p2[0] - px0) * (p1[1] - py0)) * sign;
+ let mut w1_row = ((p2[0] - px0) * (p0[1] - py0) - (p0[0] - px0) * (p2[1] - py0)) * sign;
+ let mut w2_row = ((p0[0] - px0) * (p1[1] - py0) - (p1[0] - px0) * (p0[1] - py0)) * sign;
+ let mut z_row = p0[2] + w1_row * dz_dw1 + w2_row * dz_dw2;
+ let mut r_row = c0[0] + w1_row * dr_dw1 + w2_row * dr_dw2;
+ let mut g_row = c0[1] + w1_row * dg_dw1 + w2_row * dg_dw2;
+ let mut b_row = c0[2] + w1_row * db_dw1 + w2_row * db_dw2;
+
+ let x0u = x0 as usize;
+ let x1u = x1 as usize;
+ for y in y0..=y1 {
+ let row = y as usize * self.w;
+ let z_slice = &mut self.zbuf[row + x0u..=row + x1u];
+ let rgb_slice = &mut self.rgb[(row + x0u) * 3..(row + x1u + 1) * 3];
+ let mut w0 = w0_row;
+ let mut w1 = w1_row;
+ let mut w2 = w2_row;
+ let mut z = z_row;
+ let mut r = r_row;
+ let mut g = g_row;
+ let mut b = b_row;
+ let mut entered = false;
+ for (dx, zslot) in z_slice.iter_mut().enumerate() {
+ if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 {
+ entered = true;
+ if z < *zslot {
+ *zslot = z;
+ let ci = dx * 3;
+ rgb_slice[ci] = r.clamp(0.0, 255.0) as u8;
+ rgb_slice[ci + 1] = g.clamp(0.0, 255.0) as u8;
+ rgb_slice[ci + 2] = b.clamp(0.0, 255.0) as u8;
+ }
+ } else if entered {
+ break;
+ }
+ w0 += e0_dx;
+ w1 += e1_dx;
+ w2 += e2_dx;
+ z += dz_dx;
+ r += dr_dx;
+ g += dg_dx;
+ b += db_dx;
+ }
+ w0_row += e0_dy;
+ w1_row += e1_dy;
+ w2_row += e2_dy;
+ z_row += dz_dy;
+ r_row += dr_dy;
+ g_row += dg_dy;
+ b_row += db_dy;
+ }
+ }
+
++ /// Alpha-blended Gouraud triangle rasterizer tested against opaque `zbuf` without writing depth.
+ fn raster_tri_blend(
+ &mut self,
+ p0: [f32; 3],
+ p1: [f32; 3],
+ p2: [f32; 3],
- color: [u8; 3],
++ c0: [f32; 3],
++ c1: [f32; 3],
++ c2: [f32; 3],
+ alpha: f32,
+ vp: (i32, i32, i32, i32),
+ ) {
+ let a = alpha.clamp(0.0, 1.0);
+ if a <= 1e-4 {
+ return;
+ }
+ let inv_a = 1.0 - a;
+ let area = (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]);
+ let abs_area = area.abs();
+ if abs_area < 1e-4 {
+ return;
+ }
+
+ let min_x = p0[0].min(p1[0]).min(p2[0]).floor() as i32;
+ let max_x = p0[0].max(p1[0]).max(p2[0]).ceil() as i32;
+ let min_y = p0[1].min(p1[1]).min(p2[1]).floor() as i32;
+ let max_y = p0[1].max(p1[1]).max(p2[1]).ceil() as i32;
+
+ let x0 = min_x.max(vp.0);
+ let x1 = max_x.min(vp.2 - 1);
+ let y0 = min_y.max(vp.1);
+ let y1 = max_y.min(vp.3 - 1);
+ if x0 > x1 || y0 > y1 {
+ return;
+ }
+
+ let sign = area.signum();
+ let inv_area_s = 1.0 / abs_area;
+
+ let e0_dx = (p1[1] - p2[1]) * sign;
+ let e0_dy = (p2[0] - p1[0]) * sign;
+ let e1_dx = (p2[1] - p0[1]) * sign;
+ let e1_dy = (p0[0] - p2[0]) * sign;
+ let e2_dx = (p0[1] - p1[1]) * sign;
+ let e2_dy = (p1[0] - p0[0]) * sign;
+
- let z0_s = p0[2];
+ let dz_dw1 = (p1[2] - p0[2]) * inv_area_s;
+ let dz_dw2 = (p2[2] - p0[2]) * inv_area_s;
+ let dz_dx = e1_dx * dz_dw1 + e2_dx * dz_dw2;
+ let dz_dy = e1_dy * dz_dw1 + e2_dy * dz_dw2;
+
++ let dr_dw1 = (c1[0] - c0[0]) * inv_area_s;
++ let dr_dw2 = (c2[0] - c0[0]) * inv_area_s;
++ let dr_dx = e1_dx * dr_dw1 + e2_dx * dr_dw2;
++ let dr_dy = e1_dy * dr_dw1 + e2_dy * dr_dw2;
++
++ let dg_dw1 = (c1[1] - c0[1]) * inv_area_s;
++ let dg_dw2 = (c2[1] - c0[1]) * inv_area_s;
++ let dg_dx = e1_dx * dg_dw1 + e2_dx * dg_dw2;
++ let dg_dy = e1_dy * dg_dw1 + e2_dy * dg_dw2;
++
++ let db_dw1 = (c1[2] - c0[2]) * inv_area_s;
++ let db_dw2 = (c2[2] - c0[2]) * inv_area_s;
++ let db_dx = e1_dx * db_dw1 + e2_dx * db_dw2;
++ let db_dy = e1_dy * db_dw1 + e2_dy * db_dw2;
++
+ let px0 = x0 as f32 + 0.5;
+ let py0 = y0 as f32 + 0.5;
+ let mut w0_row = ((p1[0] - px0) * (p2[1] - py0) - (p2[0] - px0) * (p1[1] - py0)) * sign;
+ let mut w1_row = ((p2[0] - px0) * (p0[1] - py0) - (p0[0] - px0) * (p2[1] - py0)) * sign;
+ let mut w2_row = ((p0[0] - px0) * (p1[1] - py0) - (p1[0] - px0) * (p0[1] - py0)) * sign;
- let mut z_row = z0_s + w1_row * dz_dw1 + w2_row * dz_dw2;
++ let mut z_row = p0[2] + w1_row * dz_dw1 + w2_row * dz_dw2;
++ let mut r_row = c0[0] + w1_row * dr_dw1 + w2_row * dr_dw2;
++ let mut g_row = c0[1] + w1_row * dg_dw1 + w2_row * dg_dw2;
++ let mut b_row = c0[2] + w1_row * db_dw1 + w2_row * db_dw2;
+
- let sr = color[0] as f32 * a;
- let sg = color[1] as f32 * a;
- let sb = color[2] as f32 * a;
+ let x0u = x0 as usize;
+ let x1u = x1 as usize;
+ for y in y0..=y1 {
+ let row = y as usize * self.w;
+ let z_slice = &self.zbuf[row + x0u..=row + x1u];
+ let rgb_slice = &mut self.rgb[(row + x0u) * 3..(row + x1u + 1) * 3];
+ let mut w0 = w0_row;
+ let mut w1 = w1_row;
+ let mut w2 = w2_row;
+ let mut z = z_row;
++ let mut r = r_row;
++ let mut g = g_row;
++ let mut b = b_row;
+ let mut entered = false;
+ for (dx, &zslot) in z_slice.iter().enumerate() {
+ if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 {
+ entered = true;
+ if z < zslot {
+ let ci = dx * 3;
- rgb_slice[ci] = (sr + rgb_slice[ci] as f32 * inv_a).clamp(0.0, 255.0) as u8;
- rgb_slice[ci + 1] = (sg + rgb_slice[ci + 1] as f32 * inv_a).clamp(0.0, 255.0) as u8;
- rgb_slice[ci + 2] = (sb + rgb_slice[ci + 2] as f32 * inv_a).clamp(0.0, 255.0) as u8;
++ let dr = rgb_slice[ci] as f32;
++ let dg = rgb_slice[ci + 1] as f32;
++ let db = rgb_slice[ci + 2] as f32;
++ rgb_slice[ci] = (r.clamp(0.0, 255.0) * a + dr * inv_a).clamp(0.0, 255.0) as u8;
++ rgb_slice[ci + 1] = (g.clamp(0.0, 255.0) * a + dg * inv_a).clamp(0.0, 255.0) as u8;
++ rgb_slice[ci + 2] = (b.clamp(0.0, 255.0) * a + db * inv_a).clamp(0.0, 255.0) as u8;
+ }
+ } else if entered {
+ break;
+ }
+ w0 += e0_dx;
+ w1 += e1_dx;
+ w2 += e2_dx;
+ z += dz_dx;
++ r += dr_dx;
++ g += dg_dx;
++ b += db_dx;
+ }
+ w0_row += e0_dy;
+ w1_row += e1_dy;
+ w2_row += e2_dy;
+ z_row += dz_dy;
++ r_row += dr_dy;
++ g_row += dg_dy;
++ b_row += db_dy;
+ }
+ }
+
fn draw_line_z(
&mut self,
p0: [f32; 3],
@@@ -385,68 -405,74 +528,104 @@@ fn render_views_to_png
struct RenderTri {
verts: [usize; 3],
face_n: Vec3,
+ corner_n: [Vec3; 3],
+ is_smooth: bool,
base: [f32; 3],
+ emissive: [f32; 3],
+ alpha: f32,
+ double_sided: bool,
}
- // Pre-extract indexed triangles with normals & material colors (avoids re-projecting shared verts per face)
+ let corner_normals = if mesh.smooth_angle_deg.is_some() {
+ Some(mesh.compute_corner_normals())
+ } else {
+ None
+ };
+
let mut tris: Vec<RenderTri> = Vec::with_capacity(mesh.faces.len() * 2);
let mut face_normals: Vec<Vec3> = Vec::with_capacity(mesh.faces.len());
++ let mut face_translucent: Vec<bool> = Vec::with_capacity(mesh.faces.len());
let mut edge_runs: Vec<(u64, u32)> = Vec::with_capacity(mesh.faces.len() * 4);
for (fi, f) in mesh.faces.iter().enumerate() {
let n = mesh.face_normal(fi);
face_normals.push(n);
+ let (base_rgb, emissive_rgb, alpha, double_sided) =
+ if let Some(mat) = mesh.materials.get(f.mat_id as usize) {
+ let raw_a = mat.color[3].clamp(0.0, 1.0);
+ let trans = mat.transmission.clamp(0.0, 1.0);
++ // Show transmissive glass/water as translucent in the software preview too.
+ let eff_a = if trans > 1e-4 && raw_a >= 0.995 {
+ (1.0 - 0.72 * trans).clamp(0.12, 0.95)
+ } else {
+ raw_a
+ };
+ let em_s = mat.emissive_strength.max(0.0);
+ (
+ [mat.color[0], mat.color[1], mat.color[2]],
+ [mat.emissive[0] * em_s, mat.emissive[1] * em_s, mat.emissive[2] * em_s],
+ eff_a,
+ mat.double_sided,
+ )
+ } else {
+ ([0.66, 0.75, 0.86], [0.0, 0.0, 0.0], 1.0, false)
+ };
+ let is_trans = alpha < 0.995;
++ face_translucent.push(is_trans);
let nv_f = f.verts.len();
- for i in 0..nv_f {
- let u = f.verts[i];
- let v = f.verts[(i + 1) % nv_f];
- if u != v {
- let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
- edge_runs.push(((lo << 32) | hi, fi as u32));
+ if !is_trans {
+ for i in 0..nv_f {
+ let u = f.verts[i];
+ let v = f.verts[(i + 1) % nv_f];
+ if u != v {
+ let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
+ edge_runs.push(((lo << 32) | hi, fi as u32));
+ }
}
}
if n.len_sq() <= 1e-18 {
continue;
}
- for tri in mesh.triangulate_face(fi) {
- tris.push(RenderTri {
- verts: tri,
- face_n: n,
- base: base_rgb,
- emissive: emissive_rgb,
- alpha,
- double_sided,
- });
- let base_rgb = if let Some(mat) = mesh.materials.get(f.mat_id as usize) {
- [mat.color[0], mat.color[1], mat.color[2]]
- } else {
- [0.66, 0.75, 0.86]
- };
+ if let Some(ref all_cn) = corner_normals {
+ let cn = &all_cn[fi];
+ for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {
+ let n0 = cn[ca];
+ let n1 = cn[cb];
+ let n2 = cn[cc];
+ let is_smooth = (n0 - n1).len_sq() > 1e-6
+ || (n0 - n2).len_sq() > 1e-6
+ || (n0 - n).len_sq() > 1e-6;
+ tris.push(RenderTri {
+ verts: [f.verts[ca], f.verts[cb], f.verts[cc]],
+ face_n: n,
+ corner_n: [n0, n1, n2],
+ is_smooth,
+ base: base_rgb,
++ emissive: emissive_rgb,
++ alpha,
++ double_sided,
+ });
+ }
+ } else {
+ for tri in mesh.triangulate_face(fi) {
+ tris.push(RenderTri {
+ verts: tri,
+ face_n: n,
+ corner_n: [n, n, n],
+ is_smooth: false,
+ base: base_rgb,
++ emissive: emissive_rgb,
++ alpha,
++ double_sided,
+ });
+ }
}
}
++ let _ = &face_translucent;
- // Collect crisp feature edges (dihedral > 22 deg or boundary) with zero per-edge heap allocations
+ // Collect crisp feature edges (respecting smooth_angle_deg so smooth curved surfaces stay clean)
edge_runs.sort_unstable_by_key(|&(k, _)| k);
- let cos_thresh = 22.0f64.to_radians().cos();
+ let edge_angle_deg = mesh.smooth_angle_deg.map(|a| a.clamp(22.0, 89.0)).unwrap_or(22.0);
+ let cos_thresh = edge_angle_deg.to_radians().cos();
let mut feature_edges: Vec<(usize, usize)> = Vec::new();
let mut ei = 0usize;
while ei < edge_runs.len() {
@@@ -511,34 -537,51 +690,60 @@@
((cy + half_v).ceil() as i32 + 2).min(vp.3),
);
- for t in &tris {
- // Backface cull on outward-wound solids (cam.fwd points into scene, so front normals have dot < 0)
- if t.face_n.dot(cam.fwd) > 0.05 {
+ let mut translucent_indices: Vec<(f32, usize)> = Vec::new();
+ for (ti, t) in tris.iter().enumerate() {
++ // Backface cull on outward-wound solids unless double_sided (cam.fwd points into scene)
+ let back_facing = t.face_n.dot(cam.fwd) > 0.05;
+ if back_facing && !t.double_sided {
continue;
}
let p0 = proj_verts[t.verts[0]];
let p1 = proj_verts[t.verts[1]];
let p2 = proj_verts[t.verts[2]];
+ if t.alpha < 0.995 {
+ let avg_z = (p0[2] + p1[2] + p2[2]) * (1.0 / 3.0);
+ translucent_indices.push((avg_z, ti));
+ continue;
+ }
- let n = if back_facing { -t.face_n } else { t.face_n };
- let ndotk = n.dot(key_dir).abs();
- let ndotf = n.dot(fill_dir).max(0.0);
- let hemi = 0.5 + 0.5 * n.z;
- let lum = (0.24 + 0.16 * hemi + 0.52 * ndotk + 0.18 * ndotf) as f32;
- let col = [
- ((t.base[0] * lum + t.emissive[0]) * 255.0).clamp(0.0, 255.0) as u8,
- ((t.base[1] * lum + t.emissive[1]) * 255.0).clamp(0.0, 255.0) as u8,
- ((t.base[2] * lum + t.emissive[2]) * 255.0).clamp(0.0, 255.0) as u8,
- ];
- fb.raster_tri(p0, p1, p2, col, *vp);
++ let flip = if back_facing { -1.0 } else { 1.0 };
+ if t.is_smooth {
+ let shade = |nv: Vec3| -> [f32; 3] {
++ let nv = nv * flip;
+ let ndotk = nv.dot(key_dir).max(0.0);
+ let ndotf = nv.dot(fill_dir).max(0.0);
+ let hemi = 0.5 + 0.5 * nv.z;
+ let lum = (0.24 + 0.16 * hemi + 0.52 * ndotk + 0.18 * ndotf) as f32;
+ [
- (t.base[0] * lum * 255.0).clamp(0.0, 255.0),
- (t.base[1] * lum * 255.0).clamp(0.0, 255.0),
- (t.base[2] * lum * 255.0).clamp(0.0, 255.0),
++ ((t.base[0] * lum + t.emissive[0]) * 255.0).clamp(0.0, 255.0),
++ ((t.base[1] * lum + t.emissive[1]) * 255.0).clamp(0.0, 255.0),
++ ((t.base[2] * lum + t.emissive[2]) * 255.0).clamp(0.0, 255.0),
+ ]
+ };
+ fb.raster_tri_gouraud(
+ p0,
+ p1,
+ p2,
+ shade(t.corner_n[0]),
+ shade(t.corner_n[1]),
+ shade(t.corner_n[2]),
+ *vp,
+ );
+ } else {
- let n = t.face_n;
++ let n = t.face_n * flip;
+ let ndotk = n.dot(key_dir).abs();
+ let ndotf = n.dot(fill_dir).max(0.0);
+ let hemi = 0.5 + 0.5 * n.z;
+ let lum = (0.24 + 0.16 * hemi + 0.52 * ndotk + 0.18 * ndotf) as f32;
+ let col = [
- (t.base[0] * lum * 255.0).clamp(0.0, 255.0) as u8,
- (t.base[1] * lum * 255.0).clamp(0.0, 255.0) as u8,
- (t.base[2] * lum * 255.0).clamp(0.0, 255.0) as u8,
++ ((t.base[0] * lum + t.emissive[0]) * 255.0).clamp(0.0, 255.0) as u8,
++ ((t.base[1] * lum + t.emissive[1]) * 255.0).clamp(0.0, 255.0) as u8,
++ ((t.base[2] * lum + t.emissive[2]) * 255.0).clamp(0.0, 255.0) as u8,
+ ];
+ fb.raster_tri(p0, p1, p2, col, *vp);
+ }
}
- // Crisp dark feature edges
+ // Crisp dark feature edges on opaque geometry
for &(a, b) in &feature_edges {
fb.draw_line_z(proj_verts[a], proj_verts[b], [32, 42, 58], *vp);
}
@@@ -546,35 -589,6 +751,40 @@@
// Fast branchless 3x3 depth-discontinuity silhouette & screen-space cavity AO pass
apply_ssao_and_silhouettes(&mut fb, ssao_vp);
+ // Back-to-front alpha-blended translucent pass (tested against opaque zbuf)
+ if !translucent_indices.is_empty() {
+ translucent_indices.sort_unstable_by(|a, b| {
+ b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)
+ });
+ for &(_, ti) in &translucent_indices {
+ let t = &tris[ti];
+ let back_facing = t.face_n.dot(cam.fwd) > 0.05;
- let n = if back_facing { -t.face_n } else { t.face_n };
- let ndotk = n.dot(key_dir).abs();
- let ndotf = n.dot(fill_dir).max(0.0);
- let hemi = 0.5 + 0.5 * n.z;
- let lum = (0.28 + 0.16 * hemi + 0.48 * ndotk + 0.18 * ndotf) as f32;
- let col = [
- ((t.base[0] * lum + t.emissive[0]) * 255.0).clamp(0.0, 255.0) as u8,
- ((t.base[1] * lum + t.emissive[1]) * 255.0).clamp(0.0, 255.0) as u8,
- ((t.base[2] * lum + t.emissive[2]) * 255.0).clamp(0.0, 255.0) as u8,
- ];
- fb.raster_tri_blend(
- proj_verts[t.verts[0]],
- proj_verts[t.verts[1]],
- proj_verts[t.verts[2]],
- col,
- t.alpha,
- *vp,
- );
++ let flip = if back_facing { -1.0 } else { 1.0 };
++ let p0 = proj_verts[t.verts[0]];
++ let p1 = proj_verts[t.verts[1]];
++ let p2 = proj_verts[t.verts[2]];
++ let shade = |nv: Vec3| -> [f32; 3] {
++ let nv = nv * flip;
++ let ndotk = nv.dot(key_dir).max(0.0);
++ let ndotf = nv.dot(fill_dir).max(0.0);
++ let hemi = 0.5 + 0.5 * nv.z;
++ let lum = (0.28 + 0.16 * hemi + 0.48 * ndotk + 0.18 * ndotf) as f32;
++ [
++ ((t.base[0] * lum + t.emissive[0]) * 255.0).clamp(0.0, 255.0),
++ ((t.base[1] * lum + t.emissive[1]) * 255.0).clamp(0.0, 255.0),
++ ((t.base[2] * lum + t.emissive[2]) * 255.0).clamp(0.0, 255.0),
++ ]
++ };
++ let (c0, c1, c2) = if t.is_smooth {
++ (shade(t.corner_n[0]), shade(t.corner_n[1]), shade(t.corner_n[2]))
++ } else {
++ let c = shade(t.face_n);
++ (c, c, c)
++ };
++ fb.raster_tri_blend(p0, p1, p2, c0, c1, c2, t.alpha, *vp);
+ }
+ }
+
fb.draw_label(vp.0 + 8, vp.1 + 8, label);
}
diff --cc crates/forma-core/src/scene.rs
index 297c6a4,8f3a1c4..acb3b21
--- a/crates/forma-core/src/scene.rs
+++ b/crates/forma-core/src/scene.rs
@@@ -406,63 -422,42 +422,106 @@@ impl Scene
crate::export::export_mesh_bytes_with_unit(mesh, ext, self.unit)
}
- /// Export ALL named scene parts as separate glTF 2.0 nodes (with shared `Arc<PolyMesh>` instancing).
+ /// Export ALL named scene parts and lightweight instances as a hierarchical glTF 2.0 `.glb`
+ /// with automatic O(V) structural/geometric deduplication.
pub fn export_scene_glb_bytes(&self, yup: bool) -> Result<Vec<u8>, SceneError> {
- let nodes: Vec<(&str, &Arc<PolyMesh>, [f64; 3])> = self
- .parts
- .iter()
- .map(|(name, entry)| (name.as_str(), &entry.mesh, [0.0, 0.0, 0.0]))
- .collect();
- crate::export::write_scene_glb_bytes_with_unit(&nodes, yup, self.unit).map_err(SceneError::OpFailed)
+ let opts = GlbSceneOptions { yup, ..Default::default() };
+ self.export_scene_glb_bytes_with_options(opts)
}
- /// Collect every named scene part for multi-object export.
- fn collect_scene_meshes(&self) -> Result<Vec<(&str, &PolyMesh)>, SceneError> {
- if self.parts.is_empty() {
+ /// Export ALL named scene parts and lightweight instances with explicit `GlbSceneOptions`
+ /// (including opt-in `EXT_mesh_gpu_instancing` via the quantized `int4` packaging policy).
+ pub fn export_scene_glb_bytes_with_options(&self, opts: GlbSceneOptions) -> Result<Vec<u8>, SceneError> {
+ let mut nodes: Vec<SceneExportNode<'_>> = Vec::with_capacity(
+ self.parts.len() + self.instances.values().map(Vec::len).sum::<usize>(),
+ );
+ for (name, entry) in &self.parts {
+ nodes.push(SceneExportNode {
+ name: name.as_str(),
+ group: self.part_groups.get(name).map(String::as_str),
+ mesh: &entry.mesh,
+ trs: Trs::IDENTITY,
+ });
+ }
+ for inst_list in self.instances.values() {
+ for inst in inst_list {
+ nodes.push(SceneExportNode {
+ name: inst.name.as_str(),
+ group: inst.group.as_deref(),
+ mesh: &inst.mesh,
+ trs: inst.trs,
+ });
+ }
+ }
+ crate::export::write_scene_glb_bytes_with_options(&nodes, self.unit, opts)
+ .map_err(SceneError::OpFailed)
+ }
+
- /// Export all named scene parts as a multi-node `.glb` or `.blend` scene file.
++ /// Collect every named scene part and transformed lightweight instance for multi-object export.
++ fn collect_scene_meshes(&self) -> Result<Vec<(String, std::borrow::Cow<'_, PolyMesh>)>, SceneError> {
++ if self.parts.is_empty() && self.instances.is_empty() {
+ return Err(SceneError::EmptyScene);
+ }
- Ok(self
- .parts
- .iter()
- .map(|(name, entry)| (name.as_str(), entry.mesh.as_ref()))
- .collect())
++ let mut out = Vec::with_capacity(self.parts.len() + self.total_instance_count());
++ for (name, entry) in &self.parts {
++ out.push((name.clone(), std::borrow::Cow::Borrowed(entry.mesh.as_ref())));
++ }
++ for inst_list in self.instances.values() {
++ for inst in inst_list {
++ let transformed = inst.trs.transform_mesh(&inst.mesh);
++ out.push((inst.name.clone(), std::borrow::Cow::Owned(transformed)));
++ }
++ }
++ Ok(out)
+ }
+
- /// Export ALL named scene parts to in-memory bytes by extension
++ /// Export ALL named scene parts and lightweight instances to in-memory bytes by extension
+ /// (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`, `png`, `svg`).
+ pub fn export_scene_bytes(&self, ext: &str) -> Result<Vec<u8>, SceneError> {
+ match ext.trim_start_matches('.').to_lowercase().as_str() {
+ "glb" => self.export_scene_glb_bytes(true),
+ "obj" => {
- let refs = self.collect_scene_meshes()?;
++ let meshes = self.collect_scene_meshes()?;
++ let refs: Vec<(&str, &PolyMesh)> = meshes
++ .iter()
++ .map(|(n, m)| (n.as_str(), m.as_ref()))
++ .collect();
+ crate::export::write_scene_obj_bytes(&refs).map_err(SceneError::OpFailed)
+ }
+ "3mf" => {
- let refs = self.collect_scene_meshes()?;
++ let meshes = self.collect_scene_meshes()?;
++ let refs: Vec<(&str, &PolyMesh)> = meshes
++ .iter()
++ .map(|(n, m)| (n.as_str(), m.as_ref()))
++ .collect();
+ crate::export::write_scene_3mf_bytes_with_unit(&refs, self.unit)
+ .map_err(SceneError::OpFailed)
+ }
+ "stl" => {
+ let merged = self.merged_scene_mesh()?;
+ crate::export::write_stl_binary_bytes(&merged).map_err(SceneError::OpFailed)
+ }
+ "step" | "stp" => {
- let refs = self.collect_scene_meshes()?;
++ let meshes = self.collect_scene_meshes()?;
++ let refs: Vec<(&str, &PolyMesh)> = meshes
++ .iter()
++ .map(|(n, m)| (n.as_str(), m.as_ref()))
++ .collect();
+ crate::export::write_scene_step_bytes_with_unit(&refs, self.unit)
+ .map_err(SceneError::OpFailed)
+ }
+ "png" => self.render_preview_scene_bytes(512),
+ "svg" => self
+ .export_blueprint_svg_scene_string()
+ .map(String::into_bytes),
+ other => Err(SceneError::OpFailed(format!(
+ "unsupported scene export extension '.{other}' (supported: .glb, .obj, .stl, .3mf, .step, .blend, .png, .svg)"
+ ))),
+ }
+ }
+
+ /// Export all named scene parts as a multi-part scene file
+ /// (`.glb`, `.blend`, `.obj`, `.3mf`, `.stl`, `.step`, `.stp`, `.png`, `.svg`).
#[cfg(not(target_arch = "wasm32"))]
pub fn export_scene_path(&self, path: &Path) -> Result<usize, SceneError> {
let ext = path
diff --cc crates/forma-lang/src/lib.rs
index f1c789f,a31156b..ed88e5a
--- a/crates/forma-lang/src/lib.rs
+++ b/crates/forma-lang/src/lib.rs
@@@ -69,16 -69,16 +69,16 @@@ pub const SPEC_PIPE_GBNF: &str = includ
/// Concise reference for Forma-Pipe (~485 o200k tokens).
/// Keeps core MCP tool schemas strictly under 800 tokens; advanced topics load on demand via `spec_topic`.
pub const SPEC_PIPE: &str = r#"Forma-Pipe (Z-up, watertight, default m; scalars persist):
-name = expr | op (multi-line |; _tmp local; del("name"); def f(a=1)=expr; [e for i in range(n)]; math +-*/ sqrt sin cos tan asin acos atan atan2 abs pi; last exports, export scene=true for .glb/.png/.svg).
+name = expr | op (multi-line |; _tmp local; del("name"); def f(a=1)=expr; [e for i in range(n)]; math +-*/ sqrt sin cos tan asin acos atan atan2 abs pi; last exports; pass --scene (CLI) or scene=true (MCP) to export/render ALL parts).
Prims (at=(x,y,z)|[...], z0=Z, rot=(rx,ry,rz)):
box(sx,sy,sz) cyl(r,h,segs=32,axis=z) [6:k*60deg] cone(r0,r1,h) sphere(r) torus(R,r) pipe(ro,ri,h)
- revolve([(r,z),...],segs=32) extrude2d([(x,y),...],z0,z1,holes=) loft([(z,[(x,y),...]),...]) gear(z,m=,h=,bore=)
+ revolve([(r,z),...],segs=32) extrude2d([(x,y),...],z0,z1,holes=) loft([(z,[(x,y),...]),...],t=0) sheet([[(x,y,z),...],...],t=0.02,closed=false) gear(z,m=,h=,bore=)
arc_tube(center=,rx=,rz=,start=-90,end=90,r=) tube([(x,y,z),...],r=) thread(r0,r1,pitch,turns) text3d("T",height=,depth=)
Ops (| or op(m,...); add/cut take at=):
add(b,at=) cut(b,at=) intersect(b) mirror(x|y|z) array(n,step) radial(n,r=,axis=z) shell(t,open_top=true) subsurf(levels=1,crease=false)
bevel(edges,w,segs=1) [vertical|top_rim|bottom_rim|outer_rim|sharp|all] extrude(faces,d) inset(faces,amt,depth=0) [top|bottom|sides|all]
move(x,y,z) rot(rx,ry,rz) scale(sx,sy,sz) align(x|y|z,min|center|max,val) on(base) align_z0(z)
- mat(name,color=(r,g,b[,a]),metallic=0,roughness=0.5,alpha=1,emissive=(r,g,b),transmission=0,double_sided=false) color(r,g,b[,a]) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z)
-mat(name,color=(r,g,b),metallic=,roughness=) color(r,g,b) smooth(angle=35) flat() group(path) inst(p,at=,rot=,group=) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z)
++mat(name,color=(r,g,b[,a]),metallic=0,roughness=0.5,alpha=1,emissive=(r,g,b),transmission=0,double_sided=false) color(r,g,b[,a]) smooth(angle=35) flat() group(path) inst(p,at=,rot=,group=) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z)
Topics: deform|curves|uv|remesh|scene"#;
/// Progressive on-demand domain specs (loaded only when requested).
@@@ -111,13 -111,12 +111,12 @@@ pub fn spec_topic(topic: &str) -> Resul
- `load(\"path.glb|obj|stl\")` — import external 3D asset (or uploaded key in forma-server)"
),
"scene" => Ok(
- "Forma-Pipe // Multi-Object Scene Graph & Previews:\n\
- - Pass `scene: true` to MCP `export` (or `--scene` in `forma eval` / `forma render` / `forma draw`) to export ALL named parts together:\n\
- - `.glb` / `.blend`: separate scene nodes with shared mesh instancing.\n\
- - `.obj` / `.3mf` / `.step` / `.stl`: multi-object `o <name>` OBJ, multi-`<object>` 3MF, multi-solid STEP, or combined STL.\n\
- - `.png` / `.svg`: render or draw all named scene parts together with their materials (never boolean-merge a dummy assembly just to export or preview).\n\
- - Without `--scene` / `scene: true`, only the last-modified part exports.\n\
- - Prefix temporary/helper meshes with `_` (e.g. `_cut = ...`) so they stay local and do not appear in `scene.parts` or `scene: true` exports; remove an existing named part with `del(\"name\")`."
+ "Forma-Pipe // Multi-Object Scene Graph, Hierarchy & Instancing:\n\
+ - `part = expr | group(\"pavilion/drum\")` or `group(\"pavilion/drum\", [\"a\", \"b\"])` — build nested glTF parent/child node hierarchies with zero booleans.\n\
+ - `inst(proto, at=[(x,y,z),...], rot=[(rx,ry,rz),...], scale=..., group=\"pavilion/grille\", name=\"bar\")` — spawn lightweight instances sharing 1 `Arc<PolyMesh>` prototype (O(1) RAM, 1-line observe summary, shared glTF mesh).\n\
+ - Automatic O(V) GLB deduplication also collapses identical/translated/rotated/scaled parts into 1 shared glTF mesh automatically.\n\
- - Pass `scene: true` to MCP `export` (or `--scene` in `forma eval`) for `.glb`/`.blend` hierarchy + `.png`/`.svg` full-scene previews.\n\
++ - Pass `scene: true` to MCP `export` (or `--scene` in `forma eval` / `forma render` / `forma draw`) to export ALL named parts & instances together (`.glb`/`.blend` hierarchy, `.obj` `o <name>` groups, multi-`<object>` `.3mf`, multi-solid `.step`, combined `.stl`, and full-scene `.png`/`.svg` previews). Without `--scene`, only the last-modified part exports.\n\
+ - Prefix temporary/helper meshes with `_` (e.g. `_bar = ...`) so they stay local and do not appear in `scene.parts` or `scene: true` exports; remove an existing named part or instance set with `del(\"name\")`."
),
other => Err(format!("unknown spec topic '{other}' (valid: deform, curves, uv, remesh, scene)")),
}
diff --cc crates/forma-lang/src/pipeline.rs
index c57d757,e84c13f..5797528
--- a/crates/forma-lang/src/pipeline.rs
+++ b/crates/forma-lang/src/pipeline.rs
@@@ -400,10 -383,10 +401,10 @@@ fn max_pipe_positional(op_name: &str) -
"align_z0" => 1,
"align" => 3,
"on" | "place_on" => 2,
- "mat" | "material" => 4,
+ "mat" | "material" => 5,
"mirror" => 2,
"pattern_linear" | "array" | "pattern_radial" | "radial" => 3,
- "decimate" | "lod" | "remesh" => 1,
+ "decimate" | "lod" | "remesh" | "group" => 1,
"flat" => 0,
"smooth" | "unwrap" | "uv" => 2,
"solidify" | "deform" | "bisect" => 3,
diff --cc wasm/forma.wasm
index df479f9,2c858cd..0d24ce4
Binary files differ