diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rs index 81ad052..0538eaa 100644 --- a/crates/forma-core/src/boolean.rs +++ b/crates/forma-core/src/boolean.rs @@ -1168,6 +1168,8 @@ impl<'a> PreparedCsgA<'a> { let (mut m, bad) = assemble_clean_mesh(out_tris, &self.tag_table, op_id); m.materials = self.merged_mats.clone(); + m.smooth_angle_deg = self.a.smooth_angle_deg; + m.weighted_normals = self.a.weighted_normals; (m, bad) } } diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rs index 5bc6303..c8a61a2 100644 --- a/crates/forma-core/src/export.rs +++ b/crates/forma-core/src/export.rs @@ -459,19 +459,77 @@ pub fn write_scene_glb_bytes( } /// Multi-node glTF export with positions and node translations scaled from `unit` to metres. +/// Automatically runs O(V) structural/geometric deduplication (`deduplicate_scene_nodes`) so +/// translated, rotated, or scaled copies share a single glTF mesh buffer. pub fn write_scene_glb_bytes_with_unit( nodes: &[(&str, &std::sync::Arc, [f64; 3])], yup: bool, unit: Unit, ) -> Result, String> { - use std::collections::HashMap; + use crate::instancing::{GlbSceneOptions, SceneExportNode, Trs}; + let wrapped: Vec> = nodes + .iter() + .map(|&(name, mesh, trans)| SceneExportNode { + name, + group: None, + mesh, + trs: Trs::from_translation(Vec3::new(trans[0], trans[1], trans[2])), + }) + .collect(); + let opts = GlbSceneOptions { yup, ..Default::default() }; + write_scene_glb_bytes_with_options(&wrapped, unit, opts) +} + +/// Hierarchical multi-node glTF 2.0 export with O(V) structural/geometric deduplication, +/// nested slash-path group nodes, and quantized `int4` packaging policy (`DataInstance`, +/// `EXT_mesh_gpu_instancing`, or spatial-cell GPU instancing). +pub fn write_scene_glb_bytes_with_options( + nodes: &[crate::instancing::SceneExportNode<'_>], + unit: Unit, + opts: crate::instancing::GlbSceneOptions, +) -> Result, String> { + use crate::instancing::{ + choose_scene_pack_strategy, deduplicate_scene_nodes, partition_spatial_cells, + ClusterPackFeatures, DedupInstance, ScenePackStrategy, + }; + use std::collections::{BTreeMap, HashMap}; + let k = unit.meters_per_unit(); if nodes.is_empty() { return Err("cannot export empty scene to GLB".into()); } - let conv = |p: Vec3| -> [f32; 3] { - if yup { [p.x as f32, p.z as f32, (-p.y) as f32] } else { p.to_f32_array() } - }; + + let (prototypes, instances): (Vec<&std::sync::Arc>, Vec>) = + if opts.deduplicate { + let dedup = deduplicate_scene_nodes(nodes); + (dedup.prototypes, dedup.instances) + } else { + let mut protos: Vec<&std::sync::Arc> = Vec::new(); + let mut ptr_map: HashMap = HashMap::new(); + let mut insts: Vec> = Vec::with_capacity(nodes.len()); + for n in nodes { + if n.mesh.faces.is_empty() || n.mesh.verts.is_empty() { + continue; + } + let ptr = std::sync::Arc::as_ptr(n.mesh) as usize; + let proto_idx = *ptr_map.entry(ptr).or_insert_with(|| { + let id = protos.len(); + protos.push(n.mesh); + id + }); + insts.push(DedupInstance { + name: n.name, + group: n.group, + proto_idx, + trs: n.trs, + }); + } + (protos, insts) + }; + + if prototypes.is_empty() || instances.is_empty() { + return Err("scene had no non-empty meshes to export".into()); + } let mut bin: Vec = Vec::new(); let mut bviews: Vec = Vec::new(); @@ -479,113 +537,382 @@ pub fn write_scene_glb_bytes_with_unit( let mut gltf_materials: Vec = Vec::new(); let mut mat_dedup: HashMap = HashMap::new(); let mut gltf_meshes: Vec = Vec::new(); - let mut mesh_ptr_map: HashMap = HashMap::new(); - let mut gltf_nodes: Vec = Vec::new(); + let mut proto_to_gltf_mesh: Vec> = 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![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 = 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 = 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 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 + } + })); + 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 = Vec::new(); + let mut root_node_indices: Vec = Vec::new(); + let mut group_node_map: HashMap = HashMap::new(); + let mut group_children: BTreeMap> = BTreeMap::new(); + + let ensure_group = |group_path: &str, + gltf_nodes: &mut Vec, + root_nodes: &mut Vec, + group_map: &mut HashMap, + children_map: &mut BTreeMap>| + -> Option { + let mut cur_path = String::new(); + let mut parent_idx: Option = 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, + root_nodes: &mut Vec, + group_map: &mut HashMap, + children_map: &mut BTreeMap>| { + 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 = 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, 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 = format!("{}:{:?}:{}:{}", mat.name, mat.color, mat.metallic, mat.roughness); - 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 + let mut by_group: BTreeMap, Vec> = 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 = 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 >rs_list { + for c in t.translation { + bin.extend_from_slice(&(c as f32).to_le_bytes()); } - })); - idx - }); - prim["material"] = serde_json::json!(mslot); + } + 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 >rs_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 >rs_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); } - let node_indices: Vec = (0..gltf_nodes.len()).collect(); let mut root = serde_json::json!({ - "asset": {"version": "2.0", "generator": "forma-core 0.4", "extras": {"forma_yup": yup}}, + "asset": {"version": "2.0", "generator": "forma-core 0.4", "extras": {"forma_yup": opts.yup}}, "scene": 0, - "scenes": [{"nodes": node_indices}], + "scenes": [{"nodes": root_node_indices}], "nodes": gltf_nodes, "meshes": gltf_meshes, "accessors": accessors, @@ -595,6 +922,10 @@ pub fn write_scene_glb_bytes_with_unit( 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"]); + root["extensionsRequired"] = serde_json::json!(["EXT_mesh_gpu_instancing"]); + } let mut json_bytes = root.to_string().into_bytes(); while json_bytes.len() % 4 != 0 { json_bytes.push(b' '); } diff --git a/crates/forma-core/src/instancing.rs b/crates/forma-core/src/instancing.rs new file mode 100644 index 0000000..c354415 --- /dev/null +++ b/crates/forma-core/src/instancing.rs @@ -0,0 +1,1060 @@ +//! 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 { + 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 { + 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); + } + + 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, + 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>, + pub instances: Vec>, + 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, + frame: Option<([usize; 4], [[f64; 3]; 3], f64)>, + frame_computed: bool, + } + + let mut prototypes: Vec<&'a Arc> = Vec::new(); + let mut instances: Vec> = Vec::with_capacity(nodes.len()); + let mut stats = DedupStats { + input_nodes: nodes.len(), + ..Default::default() + }; + + let mut ptr_to_proto: HashMap = HashMap::new(); + let mut ptr_to_sig: HashMap = HashMap::new(); + let mut buckets: HashMap>> = 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!) + 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> { + 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; 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 --git a/crates/forma-core/src/lib.rs b/crates/forma-core/src/lib.rs index b1bb97c..858f461 100644 --- a/crates/forma-core/src/lib.rs +++ b/crates/forma-core/src/lib.rs @@ -15,6 +15,7 @@ pub mod curves; pub mod deform; pub mod export; pub mod import; +pub mod instancing; pub mod invariants; pub mod math; pub mod mesh; diff --git a/crates/forma-core/src/mesh.rs b/crates/forma-core/src/mesh.rs index dd3db38..92290c8 100644 --- a/crates/forma-core/src/mesh.rs +++ b/crates/forma-core/src/mesh.rs @@ -105,14 +105,18 @@ impl Default for PolyMesh { } } +/// Default auto-smooth dihedral threshold in degrees (keeps 45°/60°/90° hard edges crisp +/// while smoothly shading curved primitives, multi-segment bevels, and organic surfaces). +pub const DEFAULT_SMOOTH_ANGLE_DEG: f64 = 35.0; + impl PolyMesh { pub fn new() -> Self { Self { verts: Vec::new(), faces: Vec::new(), materials: Vec::new(), - smooth_angle_deg: None, - weighted_normals: false, + smooth_angle_deg: Some(DEFAULT_SMOOTH_ANGLE_DEG), + weighted_normals: true, next_lineage: 1, } } diff --git a/crates/forma-core/src/ops.rs b/crates/forma-core/src/ops.rs index 2619a87..b1b8821 100644 --- a/crates/forma-core/src/ops.rs +++ b/crates/forma-core/src/ops.rs @@ -1470,6 +1470,8 @@ fn catmull_clark_step(mesh: &PolyMesh, crease_cos: Option, op_id: u32) -> P let n_edges = edge_keys.len(); let mut out = PolyMesh::new(); out.materials = mesh.materials.clone(); + out.smooth_angle_deg = mesh.smooth_angle_deg; + out.weighted_normals = mesh.weighted_normals; out.verts.reserve(n_verts + n_faces + n_edges); out.faces.reserve(n_faces * 4); @@ -2117,6 +2119,8 @@ pub fn decimate_mesh( // Compact live vertices and triangles into output PolyMesh let mut out = PolyMesh::new(); out.materials = mesh.materials.clone(); + out.smooth_angle_deg = mesh.smooth_angle_deg; + out.weighted_normals = mesh.weighted_normals; let mut remap: Vec> = vec![None; verts.len()]; for (ti, (t, mat_id, tags)) in tris.into_iter().enumerate() { if !alive_tri[ti] { continue; } diff --git a/crates/forma-core/src/primitives.rs b/crates/forma-core/src/primitives.rs index c4a7888..369eae2 100644 --- a/crates/forma-core/src/primitives.rs +++ b/crates/forma-core/src/primitives.rs @@ -482,7 +482,12 @@ fn resample_closed_2d(pts_raw: &[(f64, f64)], n: usize) -> Result Result = if area2 < 0.0 { - pts_raw.iter().rev().copied().collect() + let mut rev: Vec<(f64, f64)> = pts_raw.iter().rev().copied().collect(); + rev.rotate_right(1); + rev } else { pts_raw.to_vec() }; @@ -520,42 +527,185 @@ fn resample_closed_2d(pts_raw: &[(f64, f64)], n: usize) -> Result= best_cost { + break; + } + } + if cost < best_cost - 1e-12 { + best_cost = cost; + best_shift = shift; } } - sampled.rotate_left(best_i); - Ok(sampled) + curr.rotate_left(best_shift); } /// Watertight loft interpolating arbitrary 2D cross-section polygons across elevations `(z, poly_2d)`. pub fn make_loft(sections: &[(f64, Vec<(f64, f64)>)], segs: usize, op_id: u32) -> Result { + make_loft_ext(sections, segs, 0.0, true, op_id) +} + +/// Extended watertight loft supporting concave-safe cyclic ring alignment (`align`) and +/// open-ended thin-walled hollow shells (`thickness > 0`, ideal for draped mantles, skirts, +/// sleeves, collars, and curved architectural drums without booleans). +pub fn make_loft_ext( + sections: &[(f64, Vec<(f64, f64)>)], + segs: usize, + thickness: f64, + align: bool, + op_id: u32, +) -> Result { if sections.len() < 2 { return Err("loft requires at least 2 (z, profile) sections".into()); } + if !thickness.is_finite() || thickness < 0.0 { + return Err(format!("loft thickness must be finite and >= 0 (got {thickness})")); + } + for (z, _) in sections { + if !z.is_finite() { + return Err("loft section z elevation must be finite".into()); + } + } let segs = segs.clamp(8, 128); let mut ordered = sections.to_vec(); ordered.sort_by(|a, b| a.0.total_cmp(&b.0)); - let mut m = PolyMesh::new(); - let mut rings = Vec::with_capacity(ordered.len()); + let mut rings_2d: Vec<(f64, Vec<(f64, f64)>)> = Vec::with_capacity(ordered.len()); for (z, prof) in &ordered { - let resampled = resample_closed_2d(prof, segs)?; + let mut resampled = resample_closed_2d(prof, segs)?; + if align { + if let Some((_, prev)) = rings_2d.last() { + align_ring_to_prev(prev, &mut resampled); + } + } + rings_2d.push((*z, resampled)); + } + + if thickness > 1e-9 { + let n_rings = rings_2d.len(); + let outer_pts: Vec> = rings_2d + .iter() + .map(|(z, ring)| ring.iter().map(|&(x, y)| Vec3::new(x, y, *z)).collect()) + .collect(); + + // Accumulate smooth outward vertex normals from all incident outer quads + let mut normals = vec![vec![Vec3::ZERO; segs]; n_rings]; + for s in 0..(n_rings - 1) { + for i in 0..segs { + let j = (i + 1) % segs; + let p00 = outer_pts[s][i]; + let p01 = outer_pts[s][j]; + let p11 = outer_pts[s + 1][j]; + let p10 = outer_pts[s + 1][i]; + let n_tri1 = (p01 - p00).cross(p11 - p00); + let n_tri2 = (p11 - p00).cross(p10 - p00); + let qn = n_tri1 + n_tri2; + if qn.len_sq() > 1e-24 { + normals[s][i] += qn; + normals[s][j] += qn; + normals[s + 1][j] += qn; + normals[s + 1][i] += qn; + } + } + } + + let mut m = PolyMesh::new(); + let mut outer_idx = Vec::with_capacity(n_rings); + let mut inner_idx = Vec::with_capacity(n_rings); + for s in 0..n_rings { + let (mut cx, mut cy) = (0.0, 0.0); + for p in &outer_pts[s] { + cx += p.x; + cy += p.y; + } + cx /= segs as f64; + cy /= segs as f64; + let mut o_ring = Vec::with_capacity(segs); + let mut i_ring = Vec::with_capacity(segs); + for i in 0..segs { + let p = outer_pts[s][i]; + let mut n = normals[s][i]; + if n.len_sq() <= 1e-24 { + n = Vec3::new(p.x - cx, p.y - cy, 0.0); + } + let unit_n = if n.len_sq() > 1e-24 { n.normalized() } else { Vec3::X }; + o_ring.push(m.add_vert(p)); + i_ring.push(m.add_vert(p - unit_n * thickness)); + } + outer_idx.push(o_ring); + inner_idx.push(i_ring); + } + + for s in 0..(n_rings - 1) { + for i in 0..segs { + let j = (i + 1) % segs; + m.add_face( + smallvec![outer_idx[s][i], outer_idx[s][j], outer_idx[s + 1][j], outer_idx[s + 1][i]], + op_id, + Some("loft"), + ); + m.add_face( + smallvec![inner_idx[s][i], inner_idx[s + 1][i], inner_idx[s + 1][j], inner_idx[s][j]], + op_id, + Some("inner"), + ); + } + } + let last = n_rings - 1; + for i in 0..segs { + let j = (i + 1) % segs; + m.add_face( + smallvec![outer_idx[0][i], inner_idx[0][i], inner_idx[0][j], outer_idx[0][j]], + op_id, + Some("bottom"), + ); + m.add_face( + smallvec![outer_idx[last][i], outer_idx[last][j], inner_idx[last][j], inner_idx[last][i]], + op_id, + Some("top"), + ); + } + m.ensure_outward_winding(); + return Ok(m); + } + + let mut m = PolyMesh::new(); + let mut rings = Vec::with_capacity(rings_2d.len()); + for (z, resampled) in &rings_2d { let mut ring = Vec::with_capacity(segs); - for (x, y) in resampled { + for &(x, y) in resampled { ring.push(m.add_vert(Vec3::new(x, y, *z))); } rings.push(ring); @@ -578,6 +728,153 @@ pub fn make_loft(sections: &[(f64, Vec<(f64, f64)>)], segs: usize, op_id: u32) - Ok(m) } +/// Watertight thickened 3D parametric surface sheet built from a `rows x cols` grid of 3D points. +/// When `wrap_u == false`, emits an open-edged curved cloth/panel/cape/canopy patch (genus 0) +/// sealed cleanly along all four rims. When `wrap_u == true`, wraps seamlessly around the U +/// columns to form a draped 3D mantle/poncho/skirt (genus 1) with arbitrary non-planar rims. +pub fn make_sheet( + grid: &[Vec], + thickness: f64, + wrap_u: bool, + op_id: u32, +) -> Result { + let rows = grid.len(); + if rows < 2 { + return Err("sheet requires at least 2 rows of 3D points".into()); + } + let cols = grid[0].len(); + let min_cols = if wrap_u { 3 } else { 2 }; + if cols < min_cols { + return Err(format!("sheet requires at least {min_cols} columns per row (got {cols})")); + } + if rows * cols > 65_536 { + return Err(format!("sheet grid too large ({rows}x{cols} > 65536 vertices)")); + } + for (r, row) in grid.iter().enumerate() { + if row.len() != cols { + return Err(format!( + "sheet row {r} has {} points, expected uniform {cols}", + row.len() + )); + } + for p in row { + if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { + return Err("sheet grid contains non-finite coordinates".into()); + } + } + } + if !thickness.is_finite() || thickness <= 1e-6 { + return Err(format!("sheet thickness must be finite and > 0 (got {thickness})")); + } + + let n_u = if wrap_u { cols } else { cols - 1 }; + let mut normals = vec![vec![Vec3::ZERO; cols]; rows]; + for r in 0..(rows - 1) { + for c in 0..n_u { + let cn = (c + 1) % cols; + let p00 = grid[r][c]; + let p01 = grid[r][cn]; + let p11 = grid[r + 1][cn]; + let p10 = grid[r + 1][c]; + let qn = (p01 - p00).cross(p11 - p00) + (p11 - p00).cross(p10 - p00); + if qn.len_sq() > 1e-24 { + normals[r][c] += qn; + normals[r][cn] += qn; + normals[r + 1][cn] += qn; + normals[r + 1][c] += qn; + } + } + } + + let mut any_valid_n = Vec3::Z; + 'find_valid: for r in 0..rows { + for c in 0..cols { + if normals[r][c].len_sq() > 1e-24 { + any_valid_n = normals[r][c].normalized(); + break 'find_valid; + } + } + } + + let half_t = 0.5 * thickness; + let mut m = PolyMesh::new(); + let mut front = vec![vec![0usize; cols]; rows]; + let mut back = vec![vec![0usize; cols]; rows]; + for r in 0..rows { + for c in 0..cols { + let n = if normals[r][c].len_sq() > 1e-24 { + normals[r][c].normalized() + } else { + let mut fb = Vec3::ZERO; + for (dr, dc) in [(-1isize, 0isize), (1, 0), (0, -1), (0, 1)] { + let nr = r as isize + dr; + let nc = c as isize + dc; + if nr >= 0 && nr < rows as isize && nc >= 0 && nc < cols as isize { + let cand = normals[nr as usize][nc as usize]; + if cand.len_sq() > 1e-24 { + fb += cand.normalized(); + } + } + } + if fb.len_sq() > 1e-24 { fb.normalized() } else { any_valid_n } + }; + let p = grid[r][c]; + front[r][c] = m.add_vert(p + n * half_t); + back[r][c] = m.add_vert(p - n * half_t); + } + } + + for r in 0..(rows - 1) { + for c in 0..n_u { + let cn = (c + 1) % cols; + m.add_face( + smallvec![front[r][c], front[r][cn], front[r + 1][cn], front[r + 1][c]], + op_id, + Some("front"), + ); + m.add_face( + smallvec![back[r][c], back[r + 1][c], back[r + 1][cn], back[r][cn]], + op_id, + Some("back"), + ); + } + } + + let last_r = rows - 1; + for c in 0..n_u { + let cn = (c + 1) % cols; + m.add_face( + smallvec![front[0][c], back[0][c], back[0][cn], front[0][cn]], + op_id, + Some("rim"), + ); + m.add_face( + smallvec![front[last_r][c], front[last_r][cn], back[last_r][cn], back[last_r][c]], + op_id, + Some("rim"), + ); + } + + if !wrap_u { + let last_c = cols - 1; + for r in 0..(rows - 1) { + m.add_face( + smallvec![front[r][0], front[r + 1][0], back[r + 1][0], back[r][0]], + op_id, + Some("rim"), + ); + m.add_face( + smallvec![front[r][last_c], back[r][last_c], back[r + 1][last_c], front[r + 1][last_c]], + op_id, + Some("rim"), + ); + } + } + + m.ensure_outward_winding(); + Ok(m) +} + /// Watertight 3D-printable helical screw thread shaft aligned with Z (z in [0, pitch * turns]). /// Uses smooth trapezoidal V-thread radial displacement with clean entry/exit runout tapers. pub fn make_thread( diff --git a/crates/forma-core/src/render.rs b/crates/forma-core/src/render.rs index 3423179..3ac17c5 100644 --- a/crates/forma-core/src/render.rs +++ b/crates/forma-core/src/render.rs @@ -169,6 +169,120 @@ impl Framebuffer { } } + 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; + } + } + fn draw_line_z( &mut self, p0: [f32; 3], @@ -287,8 +401,22 @@ fn render_views_to_png( let size = size.clamp(128, 2048); let half = size / 2; - // Pre-extract indexed triangles with normals & base colors (avoids re-projecting shared verts per face) - let mut tris: Vec<([usize; 3], Vec3, [f32; 3])> = Vec::with_capacity(mesh.faces.len() * 2); + // Pre-extract indexed triangles with face + corner normals & base colors (avoids re-projecting shared verts per face) + struct RenderTri { + verts: [usize; 3], + face_n: Vec3, + corner_n: [Vec3; 3], + is_smooth: bool, + base: [f32; 3], + } + + let corner_normals = if mesh.smooth_angle_deg.is_some() { + Some(mesh.compute_corner_normals()) + } else { + None + }; + + let mut tris: Vec = Vec::with_capacity(mesh.faces.len() * 2); let mut face_normals: Vec = 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() { @@ -311,14 +439,40 @@ fn render_views_to_png( } else { [0.66, 0.75, 0.86] }; - for tri in mesh.triangulate_face(fi) { - tris.push((tri, n, base_rgb)); + 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, + }); + } + } 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, + }); + } } } - // 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() { @@ -383,21 +537,48 @@ fn render_views_to_png( ((cy + half_v).ceil() as i32 + 2).min(vp.3), ); - for (ti, n, base) in &tris { + for t in &tris { // Backface cull on outward-wound solids (cam.fwd points into scene, so front normals have dot < 0) - if n.dot(cam.fwd) > 0.05 { + if t.face_n.dot(cam.fwd) > 0.05 { continue; } - 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 = [ - (base[0] * lum * 255.0).clamp(0.0, 255.0) as u8, - (base[1] * lum * 255.0).clamp(0.0, 255.0) as u8, - (base[2] * lum * 255.0).clamp(0.0, 255.0) as u8, - ]; - fb.raster_tri(proj_verts[ti[0]], proj_verts[ti[1]], proj_verts[ti[2]], col, *vp); + let p0 = proj_verts[t.verts[0]]; + let p1 = proj_verts[t.verts[1]]; + let p2 = proj_verts[t.verts[2]]; + if t.is_smooth { + let shade = |nv: Vec3| -> [f32; 3] { + 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), + ] + }; + 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 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, + ]; + fb.raster_tri(p0, p1, p2, col, *vp); + } } // Crisp dark feature edges diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rs index c2e51bf..8f3a1c4 100644 --- a/crates/forma-core/src/scene.rs +++ b/crates/forma-core/src/scene.rs @@ -3,6 +3,7 @@ use crate::boolean::{boolean_op, BoolOp, OverlapCheck}; use crate::export::export_mesh_with_unit; +use crate::instancing::{GlbSceneOptions, SceneExportNode, Trs}; use crate::invariants::MeshInvariants; use crate::math::Vec3; use crate::mesh::PolyMesh; @@ -83,9 +84,20 @@ impl CachedPart { } } +/// Lightweight scene-graph instance sharing an immutable `Arc` prototype with a TRS transform. +#[derive(Debug, Clone)] +pub struct SceneInstance { + pub name: String, + pub mesh: Arc, + pub trs: Trs, + pub group: Option, +} + #[derive(Debug, Clone)] struct SceneSnapshot { parts: BTreeMap>, + part_groups: BTreeMap, + instances: BTreeMap>, scalars: BTreeMap, last_modified: Option, op_counter: u32, @@ -115,6 +127,8 @@ pub struct Observation { #[derive(Debug, Clone)] pub struct Scene { parts: BTreeMap>, + part_groups: BTreeMap, + instances: BTreeMap>, scalars: BTreeMap, last_modified: Option, snapshots: BTreeMap, @@ -145,6 +159,8 @@ impl Scene { pub fn new() -> Self { Self { parts: BTreeMap::new(), + part_groups: BTreeMap::new(), + instances: BTreeMap::new(), scalars: BTreeMap::new(), last_modified: None, snapshots: BTreeMap::new(), @@ -406,14 +422,39 @@ 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` 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, SceneError> { - let nodes: Vec<(&str, &Arc, [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) + } + + /// 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, SceneError> { + let mut nodes: Vec> = Vec::with_capacity( + self.parts.len() + self.instances.values().map(Vec::len).sum::(), + ); + 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. @@ -480,6 +521,8 @@ impl Scene { fn capture_snapshot(&self) -> SceneSnapshot { SceneSnapshot { parts: self.parts.clone(), + part_groups: self.part_groups.clone(), + instances: self.instances.clone(), scalars: self.scalars.clone(), last_modified: self.last_modified.clone(), op_counter: self.op_counter, @@ -512,6 +555,8 @@ impl Scene { pub fn abort_transaction(&mut self, tx: SceneTransaction) { self.parts = tx.pre_snapshot.parts; + self.part_groups = tx.pre_snapshot.part_groups; + self.instances = tx.pre_snapshot.instances; self.scalars = tx.pre_snapshot.scalars; self.last_modified = tx.pre_snapshot.last_modified; self.op_counter = tx.pre_snapshot.op_counter; @@ -553,6 +598,8 @@ impl Scene { })?; self.push_undo(); self.parts = snap.parts; + self.part_groups = snap.part_groups; + self.instances = snap.instances; self.scalars = snap.scalars; self.last_modified = snap.last_modified; self.op_counter = snap.op_counter; @@ -566,6 +613,8 @@ impl Scene { pub fn undo(&mut self) -> Result<(), SceneError> { let snap = self.undo_stack.pop().ok_or(SceneError::NothingToUndo)?; self.parts = snap.parts; + self.part_groups = snap.part_groups; + self.instances = snap.instances; self.scalars = snap.scalars; self.last_modified = snap.last_modified; self.op_counter = snap.op_counter; @@ -692,15 +741,151 @@ impl Scene { } pub fn remove_part(&mut self, name: &str) -> Result<(), SceneError> { - self.parts - .remove(name) - .map(|_| { - if self.last_modified.as_deref() == Some(name) { - self.last_modified = self.parts.keys().next_back().cloned(); - } - self.revision += 1; + let removed_part = self.parts.remove(name).is_some(); + let removed_inst = self.instances.remove(name).is_some(); + self.part_groups.remove(name); + if removed_part || removed_inst { + if self.last_modified.as_deref() == Some(name) { + self.last_modified = self.parts.keys().next_back().cloned(); + } + self.revision += 1; + Ok(()) + } else { + Err(SceneError::UnknownPart(name.to_string(), self.part_list_str())) + } + } + + /// Assign a hierarchical slash-separated group path (e.g. `"pavilion/drum"`) to an existing part + /// or instance set. Used by glTF scene export to build clean parent/child node hierarchies. + pub fn set_part_group(&mut self, name: &str, group: impl AsRef) -> Result<(), SceneError> { + let clean: String = group + .as_ref() + .split('/') + .map(str::trim) + .filter(|s| !s.is_empty()) + .collect::>() + .join("/"); + let mut found = false; + if self.parts.contains_key(name) { + if clean.is_empty() { + self.part_groups.remove(name); + } else { + self.part_groups.insert(name.to_string(), clean.clone()); + } + found = true; + } + if let Some(list) = self.instances.get_mut(name) { + let grp_opt = if clean.is_empty() { None } else { Some(clean.clone()) }; + for inst in list.iter_mut() { + inst.group = grp_opt.clone(); + } + found = true; + } + if !found { + return Err(SceneError::UnknownPart(name.to_string(), self.part_list_str())); + } + self.revision += 1; + Ok(()) + } + + /// Look up the hierarchical group path assigned to a named part, if any. + pub fn part_group(&self, name: &str) -> Option<&str> { + self.part_groups.get(name).map(String::as_str) + } + + /// Register a lightweight instanced set sharing ONE `Arc` prototype across `transforms`. + /// Under `strict_manifold`, validates the prototype ONCE (O(1) per instance!). + pub fn add_instances( + &mut self, + name: impl Into, + mut proto: PolyMesh, + transforms: Vec, + group: Option, + ) -> Result { + let name = name.into(); + if transforms.is_empty() { + return Err(SceneError::OpFailed(format!("inst '{name}' requires at least 1 transform"))); + } + if self.max_faces_per_part > 0 && proto.faces.len() > self.max_faces_per_part { + return Err(SceneError::OpFailed(format!( + "instance prototype '{name}' has {} faces, exceeding safety budget ({})", + proto.faces.len(), + self.max_faces_per_part + ))); + } + let mut inv = MeshInvariants::compute(&proto); + if inv.boundary_edges == 0 && inv.signed_volume < 0.0 { + proto.flip_winding(); + inv = MeshInvariants::compute(&proto); + } + if self.strict_manifold { + if proto.faces.is_empty() { + return Err(SceneError::InvariantViolation { + part: name, + reason: "empty instance prototype".into(), + }); + } + if !inv.watertight || !inv.consistent_winding || inv.non_manifold_edges > 0 || inv.nan_verts > 0 { + return Err(SceneError::InvariantViolation { + part: name, + reason: format!( + "non-manifold instance prototype (WT={}, CW={}, NM={}, B={}, NaN={})", + inv.watertight, + inv.consistent_winding, + inv.non_manifold_edges, + inv.boundary_edges, + inv.nan_verts + ), + }); + } + if inv.has_negligible_volume() { + return Err(SceneError::InvariantViolation { + part: name, + reason: format!("zero or negligible volume instance prototype (vol={:.3e})", inv.signed_volume), + }); + } + if let OverlapCheck::Overlap = + crate::boolean::check_self_intersections(&proto, crate::boolean::SELF_INTERSECTION_BUDGET) + { + return Err(SceneError::InvariantViolation { + part: name, + reason: "self-intersecting instance prototype".into(), + }); + } + } + let clean_group = group.and_then(|g| { + let s: String = g + .split('/') + .map(str::trim) + .filter(|seg| !seg.is_empty()) + .collect::>() + .join("/"); + if s.is_empty() { None } else { Some(s) } + }); + let arc_proto = Arc::new(proto); + let count = transforms.len(); + let entries: Vec = transforms + .into_iter() + .enumerate() + .map(|(i, trs)| SceneInstance { + name: if count == 1 { + name.clone() + } else { + format!("{name}_{i}") + }, + mesh: Arc::clone(&arc_proto), + trs, + group: clean_group.clone(), }) - .ok_or_else(|| SceneError::UnknownPart(name.to_string(), self.part_list_str())) + .collect(); + self.instances.insert(name, entries); + self.revision += 1; + Ok(count) + } + + /// Total number of lightweight scene instances currently registered across all instance sets. + pub fn total_instance_count(&self) -> usize { + self.instances.values().map(Vec::len).sum() } // --- High-level modeling commands --- @@ -928,15 +1113,26 @@ impl Scene { /// Combine ALL named scene parts into a single `PolyMesh`, preserving every part's materials and colors. pub fn merged_scene_mesh(&self) -> Result { - if self.parts.is_empty() { + if self.parts.is_empty() && self.instances.is_empty() { return Err(SceneError::EmptyScene); } - let mut iter = self.parts.values(); - let mut out = (*iter.next().unwrap().mesh).clone(); - for p in iter { - out.append_mesh(&p.mesh); + let mut out: Option = None; + for p in self.parts.values() { + match &mut out { + None => out = Some((*p.mesh).clone()), + Some(acc) => acc.append_mesh(&p.mesh), + } + } + for inst_list in self.instances.values() { + for inst in inst_list { + let transformed = inst.trs.transform_mesh(&inst.mesh); + match &mut out { + None => out = Some(transformed), + Some(acc) => acc.append_mesh(&transformed), + } + } } - Ok(out) + out.ok_or(SceneError::EmptyScene) } /// Return the requested part, or the last modified part (avoiding exporting leaked temp operands). @@ -1057,11 +1253,42 @@ impl Scene { lines.push(format!("unchanged({}): {} (all WT=ok)", unchanged_names.len(), preview)); } + if !self.instances.is_empty() { + let total_inst = self.total_instance_count(); + let summary: Vec = self + .instances + .iter() + .map(|(k, v)| { + if let Some(g) = v.first().and_then(|e| e.group.as_deref()) { + format!("{k} x{} [{g}]", v.len()) + } else { + format!("{k} x{}", v.len()) + } + }) + .collect(); + lines.push(format!( + "instances: {} ({} proto{}: {})", + total_inst, + self.instances.len(), + if self.instances.len() == 1 { "" } else { "s" }, + summary.join(", ") + )); + } + let status = if all_manifold { "OK" } else { "ERR" }; + let inst_suffix = if self.instances.is_empty() { + String::new() + } else { + format!(" insts={}", self.total_instance_count()) + }; lines[0] = if self.unit == Unit::default() { - format!("{status} [{elapsed_ms:.2}ms] parts={}", self.parts.len()) + format!("{status} [{elapsed_ms:.2}ms] parts={}{inst_suffix}", self.parts.len()) } else { - format!("{status} [{elapsed_ms:.2}ms] parts={} unit={}", self.parts.len(), self.unit) + format!( + "{status} [{elapsed_ms:.2}ms] parts={}{inst_suffix} unit={}", + self.parts.len(), + self.unit + ) }; let mut diff_parts = Vec::new(); diff --git a/crates/forma-core/tests/regression_fixes.rs b/crates/forma-core/tests/regression_fixes.rs index c5e4fdc..86a3eb7 100644 --- a/crates/forma-core/tests/regression_fixes.rs +++ b/crates/forma-core/tests/regression_fixes.rs @@ -94,7 +94,9 @@ fn test_glb_unconditional_welding_per_prim_compaction_and_u16_indices() { }, None, ); - // Raw mesh: smooth_angle_deg = None, no UVs + // Explicitly test flat raw mesh (smooth_angle_deg = None, no UVs) + a.smooth_angle_deg = None; + a.weighted_normals = false; a.append_mesh(&b); assert!(a.smooth_angle_deg.is_none()); @@ -374,3 +376,177 @@ fn test_glb_omits_unused_texcoord0_and_welds_smooth_vertices_without_45deg_split 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"); } + +#[test] +fn test_auto_smooth_default_propagation_and_smooth_render() { + use forma_core::boolean::{boolean_op, BoolOp}; + use forma_core::mesh::DEFAULT_SMOOTH_ANGLE_DEG; + use forma_core::ops::{decimate_mesh, subsurf_catmull_clark_creased}; + use forma_core::primitives::make_sphere; + use forma_core::render::render_view_png_bytes; + + // 1. Primitives default to 35° weighted auto-smooth + let sphere = make_sphere(1.0, 24, 16, 1); + assert_eq!(sphere.smooth_angle_deg, Some(DEFAULT_SMOOTH_ANGLE_DEG)); + assert!(sphere.weighted_normals); + + let mut flat_sphere = sphere.clone(); + flat_sphere.smooth_angle_deg = None; + flat_sphere.weighted_normals = false; + + let smooth_glb = write_glb_bytes(&sphere, true).expect("smooth glb"); + let flat_glb = write_glb_bytes(&flat_sphere, true).expect("flat glb"); + let (sjson, _) = parse_glb(&smooth_glb); + let (fjson, _) = parse_glb(&flat_glb); + let smooth_v = sjson["accessors"][sjson["meshes"][0]["primitives"][0]["attributes"]["POSITION"].as_u64().unwrap() as usize]["count"] + .as_u64() + .unwrap(); + let flat_v = fjson["accessors"][fjson["meshes"][0]["primitives"][0]["attributes"]["POSITION"].as_u64().unwrap() as usize]["count"] + .as_u64() + .unwrap(); + assert!( + smooth_v * 2 < flat_v, + "default auto-smooth sphere should weld far fewer GLB vertices than flat ({smooth_v} vs {flat_v})" + ); + assert!(smooth_glb.len() < flat_glb.len()); + + // 2. Sharp 90° box and 60° hex prism remain razor-sharp flat under 35° auto-smooth + for sharp_mesh in [make_box(2.0, 2.0, 2.0, 2), make_cylinder(1.0, 2.0, 6, 3)] { + let cn = sharp_mesh.compute_corner_normals(); + for (fi, face_cn) in cn.iter().enumerate() { + let fnrm = sharp_mesh.face_normal(fi).normalized(); + for &n in face_cn { + assert!(n.dot(fnrm) > 0.9999); + } + } + } + + // 3. Smooth settings propagate across boolean, subsurf, and decimate + let hole = make_cylinder(0.4, 3.0, 24, 4); + let cut_res = boolean_op(&sphere, &hole, BoolOp::Difference, Some("hole"), 5).unwrap(); + assert_eq!(cut_res.smooth_angle_deg, Some(DEFAULT_SMOOTH_ANGLE_DEG)); + assert!(cut_res.weighted_normals); + + let sub = subsurf_catmull_clark_creased(&make_box(1.0, 1.0, 1.0, 6), 1, Some(35.0), 7); + assert_eq!(sub.smooth_angle_deg, Some(DEFAULT_SMOOTH_ANGLE_DEG)); + assert!(sub.weighted_normals); + + let dec = decimate_mesh(&sphere, 0.6, None, 8).unwrap(); + assert_eq!(dec.smooth_angle_deg, Some(DEFAULT_SMOOTH_ANGLE_DEG)); + assert!(dec.weighted_normals); + + let flat_cut = boolean_op(&flat_sphere, &hole, BoolOp::Difference, Some("hole"), 9).unwrap(); + assert!(flat_cut.smooth_angle_deg.is_none()); + + // 4. Studio renderer visibly distinguishes smooth Gouraud shading from flat shading + let smooth_png = render_view_png_bytes(&sphere, 256, "iso").expect("smooth png"); + let flat_png = render_view_png_bytes(&flat_sphere, 256, "iso").expect("flat png"); + assert!(smooth_png.starts_with(b"\x89PNG\r\n\x1a\n")); + assert_ne!(smooth_png, flat_png); +} + +#[test] +fn test_concave_loft_alignment_hollow_loft_and_3d_sheet() { + use forma_core::boolean::has_self_intersections; + use forma_core::invariants::MeshInvariants; + use forma_core::primitives::{make_loft_ext, make_sheet}; + + let c_profile = |dx: f64, dy: f64, scale: f64, rot_idx: usize| -> Vec<(f64, f64)> { + let mut pts = vec![ + (1.0, 0.2), + (1.0, 1.0), + (-1.0, 1.0), + (-1.0, -1.0), + (1.0, -1.0), + (1.0, -0.2), + (0.4, -0.2), + (0.4, -0.6), + (-0.4, -0.6), + (-0.4, 0.6), + (0.4, 0.6), + (0.4, 0.2), + ]; + for p in &mut pts { + p.0 = p.0 * scale + dx; + p.1 = p.1 * scale + dy; + } + let len = pts.len(); + pts.rotate_left(rot_idx % len); + pts + }; + + let secs = vec![ + (0.0, c_profile(0.0, 0.0, 1.0, 0)), + (1.0, c_profile(0.35, -0.2, 0.9, 5)), + (2.0, c_profile(0.7, -0.4, 0.8, 9)), + ]; + let solid_c = make_loft_ext(&secs, 48, 0.0, true, 1).expect("concave solid loft"); + let inv_c = MeshInvariants::compute(&solid_c); + assert!(inv_c.watertight && inv_c.non_manifold_edges == 0 && inv_c.boundary_edges == 0); + assert_eq!(inv_c.genus, 0); + assert!(inv_c.signed_volume > 2.0); + assert!(!has_self_intersections(&solid_c)); + + let pleated_ring = |r_base: f64, amp: f64, n: usize| -> Vec<(f64, f64)> { + (0..n) + .map(|i| { + let a = 2.0 * std::f64::consts::PI * (i as f64) / (n as f64); + let r = r_base + amp * (6.0 * a).sin(); + (r * a.cos(), r * a.sin()) + }) + .collect() + }; + let mantle_secs = vec![ + (0.0, pleated_ring(0.75, 0.07, 48)), + (0.5, pleated_ring(0.52, 0.04, 48)), + (1.0, pleated_ring(0.28, 0.01, 48)), + ]; + let mantle = make_loft_ext(&mantle_secs, 48, 0.035, true, 2).expect("hollow loft mantle"); + let inv_m = MeshInvariants::compute(&mantle); + assert!(inv_m.watertight && inv_m.non_manifold_edges == 0 && inv_m.boundary_edges == 0); + assert_eq!(inv_m.genus, 1); + assert!(inv_m.signed_volume > 0.0); + assert!(!has_self_intersections(&mantle)); + + let open_grid: Vec> = (0..10) + .map(|r| { + let v = (r as f64) / 9.0 * 2.0 - 1.0; + (0..12) + .map(|c| { + let u = (c as f64) / 11.0 * 2.0 - 1.0; + let z = 0.25 * (u * u - v * v) + 0.08 * (3.0 * u).sin(); + Vec3::new(u, v, z) + }) + .collect() + }) + .collect(); + let canopy = make_sheet(&open_grid, 0.03, false, 3).expect("open 3D sheet"); + let inv_canopy = MeshInvariants::compute(&canopy); + assert!(inv_canopy.watertight && inv_canopy.non_manifold_edges == 0 && inv_canopy.boundary_edges == 0); + assert_eq!(inv_canopy.genus, 0); + assert!(inv_canopy.signed_volume > 0.0); + assert!(!has_self_intersections(&canopy)); + + let poncho_grid: Vec> = (0..9) + .map(|r| { + let t = (r as f64) / 8.0; + let r_base = 0.65 * (1.0 - t) + 0.20 * t; + let z_base = 0.72 * t; + (0..28) + .map(|c| { + let a = 2.0 * std::f64::consts::PI * (c as f64) / 28.0; + let pleat = (1.0 - t) * 0.045 * (5.0 * a).sin(); + let dip = (1.0 - t) * (-0.14 * a.cos().abs()); + let rad = r_base + pleat; + Vec3::new(rad * a.cos(), rad * a.sin(), z_base + dip) + }) + .collect() + }) + .collect(); + let poncho = make_sheet(&poncho_grid, 0.025, true, 4).expect("wrapped 3D poncho sheet"); + let inv_p = MeshInvariants::compute(&poncho); + assert!(inv_p.watertight && inv_p.non_manifold_edges == 0 && inv_p.boundary_edges == 0); + assert_eq!(inv_p.genus, 1); + assert!(inv_p.signed_volume > 0.0); + assert!(!has_self_intersections(&poncho)); +} diff --git a/crates/forma-lang/src/lib.rs b/crates/forma-lang/src/lib.rs index 78d9b62..a31156b 100644 --- a/crates/forma-lang/src/lib.rs +++ b/crates/forma-lang/src/lib.rs @@ -72,13 +72,13 @@ pub const SPEC_PIPE: &str = r#"Forma-Pipe (Z-up, watertight, default m; scalars 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). 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),metallic=,roughness=) color(r,g,b) 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) Topics: deform|curves|uv|remesh|scene"#; /// Progressive on-demand domain specs (loaded only when requested). @@ -111,11 +111,12 @@ pub fn spec_topic(topic: &str) -> Result<&'static str, String> { - `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`) for:\n\ - - `.glb` / `.blend`: export all named parts as separate scene nodes with shared mesh instancing.\n\ - - `.png` / `.svg`: render or draw all named scene parts together with their materials (no need to boolean-merge a dummy assembly).\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` 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\ + - 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 --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rs index 7902859..e84c13f 100644 --- a/crates/forma-lang/src/pipeline.rs +++ b/crates/forma-lang/src/pipeline.rs @@ -361,7 +361,8 @@ fn max_call_positional(name: &str) -> Option { "tube" => 3, "extrude2d" => 3, "pipe" | "hollow_cyl" => 5, - "loft" => 2, + "loft" => 3, + "sheet" => 3, "thread" | "helix" => 5, "sweep" => 2, "text3d" | "text" => 3, @@ -385,7 +386,7 @@ fn max_pipe_positional(op_name: &str) -> Option { "mat" | "material" => 4, "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, @@ -407,8 +408,8 @@ fn check_positional_count(n: usize, max: Option, allowed_kw: Option<&[&st const CALL_NAMES: &[&str] = &[ "box", "cyl", "cylinder", "prism", "cone", "frustum", "sphere", "torus", "revolve", "arc_tube", "tube", "extrude2d", - "pipe", "hollow_cyl", "loft", "thread", "helix", "sweep", "text3d", "text", "gear", "load", "import", "bezier", "nurbs", - "bspline", "clearance", "section", "checkpoint", "rollback", "undo", "units", "unit", "del", "remove", "sqrt", "sin", + "pipe", "hollow_cyl", "loft", "sheet", "thread", "helix", "sweep", "text3d", "text", "gear", "load", "import", "bezier", "nurbs", + "bspline", "clearance", "section", "checkpoint", "rollback", "undo", "units", "unit", "del", "remove", "group", "inst", "instance", "sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "abs", "deg", "rad", ]; @@ -416,7 +417,7 @@ const PIPE_OP_NAMES: &[&str] = &[ "add", "union", "cut", "sub", "diff", "intersect", "bevel", "shell", "extrude", "inset", "subsurf", "subdiv", "move", "translate", "rot", "rotate", "scale", "align_z0", "align", "on", "place_on", "mat", "material", "color", "mirror", "pattern_linear", "array", "pattern_radial", "radial", "decimate", "lod", "smooth", "flat", - "solidify", "deform", "unwrap", "uv", "remesh", "bisect", + "solidify", "deform", "unwrap", "uv", "remesh", "bisect", "group", ]; /// " — did you mean 'x'?" for the closest known name, plus the full list of accepted names. @@ -480,6 +481,8 @@ fn allowed_call_kwargs(name: &str) -> Option<&'static [&'static str]> { "clearance" => &["a", "b"], "section" => &["part", "p", "z"], "checkpoint" | "rollback" | "del" | "remove" => &["name", "tag"], + "group" => &["path", "name", "parts", "children"], + "inst" | "instance" => &["part", "mesh", "proto", "at", "pos", "rot", "rotate", "scale", "group", "parent", "name"], "units" | "unit" => &["name", "unit"], "undo" => &[], "box" => &["sx", "x", "w", "width", "sy", "y", "d", "depth", "sz", "z", "h", "height", "rot", "rotate", "at", "center", "z0"], @@ -492,7 +495,8 @@ fn allowed_call_kwargs(name: &str) -> Option<&'static [&'static str]> { "tube" => &["points", "pts", "r", "radius", "segs", "segments", "closed", "rot", "rotate", "at", "center", "z0"], "extrude2d" => &["points", "pts", "z0", "z1", "holes", "rot", "rotate", "at", "center"], "pipe" | "hollow_cyl" => &["r_out", "ro", "outer", "r", "r_in", "ri", "inner", "h", "height", "len", "length", "segs", "segments", "axis", "rot", "rotate", "at", "center", "z0"], - "loft" => &["sections", "profiles", "segs", "segments", "rot", "rotate", "at", "center", "z0"], + "loft" => &["sections", "profiles", "segs", "segments", "thickness", "t", "wall", "align", "rot", "rotate", "at", "center", "z0"], + "sheet" => &["rows", "grid", "points", "pts", "thickness", "t", "wall", "wrap_u", "closed", "rot", "rotate", "at", "center", "z0"], "thread" | "helix" => &["r_minor", "r_min", "r_in", "r0", "r", "r_major", "r_maj", "r_out", "r1", "pitch", "p", "turns", "n", "segs", "segments", "rot", "rotate", "at", "center", "z0"], "sweep" => &["profile", "path", "closed", "scale_end", "taper", "twist", "twist_deg", "rot", "rotate", "at", "center", "z0"], "text3d" | "text" => &["text", "size", "h", "height", "depth", "d", "t", "rot", "rotate", "at", "center", "z0"], @@ -524,6 +528,7 @@ fn allowed_pipe_kwargs(op_name: &str) -> Option<&'static [&'static str]> { "unwrap" | "uv" => &["angle", "margin"], "remesh" => &["voxel_size", "size"], "bisect" => &["normal", "offset", "clear_inner"], + "group" => &["path", "name"], _ => return None, }) } @@ -553,6 +558,7 @@ struct Parser<'a> { vars: HashMap, macros: HashMap, last_stmt_bare_selector: Option<(usize, String, String)>, + pending_group: Option, } impl<'a> Parser<'a> { @@ -623,6 +629,7 @@ impl<'a> Parser<'a> { fn parse_stmt(&mut self) -> Result<(), String> { let stmt_line = self.line(); self.last_stmt_bare_selector = None; + self.pending_group = None; // Check `def name(p1, p2=default) = expr` if matches!(self.peek(), Tok::Ident(s) if s == "def") && !matches!(self.toks.get(self.pos + 1).map(|t| &t.0), Some(Tok::Eq)) @@ -658,6 +665,11 @@ impl<'a> Parser<'a> { self.scene .set_part(name.clone(), m) .map_err(|e| format!("line {stmt_line}: {e}"))?; + if let Some(grp) = self.pending_group.take() { + self.scene + .set_part_group(&name, grp) + .map_err(|e| format!("line {stmt_line}: {e}"))?; + } // Keep Parser::vars synced with the winding-corrected mesh stored in Scene. Val::Mesh( (**self @@ -1394,6 +1406,144 @@ impl<'a> Parser<'a> { self.vars.remove(target); return Ok(Val::Bool(true)); } + "group" => { + let path = pos + .first() + .or_else(|| kw.get("path")) + .or_else(|| kw.get("name")) + .ok_or(format!("{ctx}: missing group path (e.g. group(\"pavilion/drum\", [\"a\", \"b\"]))"))? + .as_str(&ctx)? + .to_string(); + let parts_val = kw + .get("parts") + .or_else(|| kw.get("children")) + .or_else(|| pos.get(1)) + .ok_or(format!("{ctx}: missing parts list (e.g. [\"a\", \"b\"])"))?; + let mut count = 0usize; + match parts_val { + Val::Str(s) => { + self.scene.set_part_group(s, &path).map_err(|e| format!("{ctx}: {e}"))?; + count += 1; + } + Val::List(items) => { + for it in items { + let pname = it.as_str(&ctx)?; + self.scene.set_part_group(pname, &path).map_err(|e| format!("{ctx}: {e}"))?; + count += 1; + } + } + _ => return Err(format!("{ctx}: parts must be a part name string or list of part name strings")), + } + return Ok(Val::Num(count as f64)); + } + "inst" | "instance" => { + let proto = kw + .get("part") + .or_else(|| kw.get("mesh")) + .or_else(|| kw.get("proto")) + .or_else(|| pos.first()) + .ok_or(format!("{ctx}: missing prototype mesh"))? + .as_mesh(&ctx)?; + let at_val = kw + .get("at") + .or_else(|| kw.get("pos")) + .or_else(|| pos.get(1)) + .ok_or(format!("{ctx}: missing at=(x,y,z) or at=[(x,y,z), ...]"))?; + let positions: Vec = if let Ok(v) = at_val.as_vec3(&ctx) { + vec![v] + } else { + at_val.as_vec3_list(&ctx)? + }; + let n = positions.len(); + if n == 0 { + return Err(format!("{ctx}: at list must not be empty")); + } + let rots: Vec = if let Some(rv) = kw.get("rot").or_else(|| kw.get("rotate")).or_else(|| pos.get(2)) { + if let Ok(v) = rv.as_vec3(&ctx) { + vec![v; n] + } else { + let list = rv.as_vec3_list(&ctx)?; + if list.len() == 1 { + vec![list[0]; n] + } else if list.len() == n { + list + } else { + return Err(format!("{ctx}: rot list length ({}) must match at length ({n})", list.len())); + } + } + } else { + vec![Vec3::ZERO; n] + }; + let parse_scale_item = |v: &Val| -> Result { + if let Ok(s) = v.as_num(&ctx) { + if !s.is_finite() || s <= 1e-9 { + return Err(format!("{ctx}: scale must be positive (got {s})")); + } + Ok(Vec3::splat(s)) + } else { + let sv = v.as_vec3(&ctx)?; + if sv.x <= 1e-9 || sv.y <= 1e-9 || sv.z <= 1e-9 { + return Err(format!("{ctx}: scale components must be positive")); + } + Ok(sv) + } + }; + let scales: Vec = if let Some(sv) = kw.get("scale").or_else(|| pos.get(3)) { + if let Ok(one) = parse_scale_item(sv) { + vec![one; n] + } else if let Val::List(items) = sv { + let mut out = Vec::with_capacity(items.len()); + for it in items { + out.push(parse_scale_item(it)?); + } + if out.len() == 1 { + vec![out[0]; n] + } else if out.len() == n { + out + } else { + return Err(format!("{ctx}: scale list length ({}) must match at length ({n})", out.len())); + } + } else { + return Err(format!("{ctx}: invalid scale value")); + } + } else { + vec![Vec3::new(1.0, 1.0, 1.0); n] + }; + let grp = kw + .get("group") + .or_else(|| kw.get("parent")) + .map(|v| v.as_str(&ctx).map(str::to_string)) + .transpose()?; + let default_name = arg_names + .pos + .first() + .and_then(|o| o.as_deref()) + .or_else(|| arg_names.kw.get("part").map(String::as_str)) + .or_else(|| arg_names.kw.get("proto").map(String::as_str)) + .map(|s| s.trim_start_matches('_')) + .filter(|s| !s.is_empty()) + .unwrap_or("inst"); + let inst_name = kw + .get("name") + .map(|v| v.as_str(&ctx)) + .transpose()? + .unwrap_or(default_name) + .to_string(); + let transforms: Vec = (0..n) + .map(|i| { + forma_core::instancing::Trs::from_translation_rot_deg_scale( + positions[i], + rots[i], + scales[i], + ) + }) + .collect(); + let added = self + .scene + .add_instances(inst_name, proto, transforms, grp) + .map_err(|e| format!("{ctx}: {e}"))?; + return Ok(Val::Num(added as f64)); + } // Functional call equivalents of pipeline ops: e.g. cut(base, cyl(...)), bevel(nut, top_rim, 0.1) "add" | "union" | "cut" | "sub" | "diff" | "intersect" | "bevel" | "shell" | "extrude" | "inset" | "subsurf" | "subdiv" | "move" | "translate" | "rot" @@ -1592,8 +1742,42 @@ impl<'a> Parser<'a> { return Err(format!("{ctx}: sections must be a list")); } let segs = whole_count(get_num_any(1, &["segs", "segments"], Some(24.0))?, &ctx)?; + let thickness = get_num_any(2, &["thickness", "t", "wall"], Some(0.0))?; + let align = kw + .get("align") + .map(|v| v.as_bool(&ctx)) + .transpose()? + .unwrap_or(true); warn_if_clamped(self.scene, "loft", "segs", segs, 8, 128); - forma_core::primitives::make_loft(§ions, segs, op_id).map_err(|e| format!("{ctx}: {e}"))? + forma_core::primitives::make_loft_ext(§ions, segs, thickness, align, op_id) + .map_err(|e| format!("{ctx}: {e}"))? + } + "sheet" => { + let rows_val = kw + .get("rows") + .or_else(|| kw.get("grid")) + .or_else(|| kw.get("points")) + .or_else(|| kw.get("pts")) + .or_else(|| pos.first()) + .ok_or(format!("{ctx}: missing 3D point grid [[(x,y,z),...], ...]"))?; + let mut grid: Vec> = Vec::new(); + if let Val::List(row_vals) = rows_val { + for rv in row_vals { + grid.push(rv.as_vec3_list(&ctx)?); + } + } else { + return Err(format!("{ctx}: rows must be a list of 3D point lists")); + } + let thickness = get_num_any(1, &["thickness", "t", "wall"], Some(0.02))?; + let wrap_u = kw + .get("wrap_u") + .or_else(|| kw.get("closed")) + .or_else(|| pos.get(2)) + .map(|v| v.as_bool(&ctx)) + .transpose()? + .unwrap_or(false); + forma_core::primitives::make_sheet(&grid, thickness, wrap_u, op_id) + .map_err(|e| format!("{ctx}: {e}"))? } "thread" | "helix" => { let r_min = get_num_any(0, &["r_minor", "r_min", "r_in", "r0", "r"], None)?; @@ -2070,6 +2254,12 @@ impl<'a> Parser<'a> { let clear_inner = kw.get("clear_inner").or_else(|| pos.get(2)).map(|v| v.as_bool(&ctx)).transpose()?.unwrap_or(false); forma_core::remesh::bisect_mesh(&mesh, n, offset, clear_inner, op_id).map_err(|e| format!("{ctx}: {e}")) } + "group" => { + let path = kw.get("path").or_else(|| kw.get("name")).or_else(|| pos.first()) + .ok_or(format!("{ctx}: missing group path (e.g. | group(\"pavilion/drum\"))"))?.as_str(&ctx)?; + self.pending_group = Some(path.to_string()); + Ok(mesh) + } _ => Err(format!("{ctx}: unknown pipeline op '{op_name}'{}", unknown_name_hint(op_name, PIPE_OP_NAMES))), } } @@ -2093,6 +2283,7 @@ pub fn eval_pipe(scene: &mut Scene, src: &str) -> Result<(), String> { vars, macros: HashMap::new(), last_stmt_bare_selector: None, + pending_group: None, }; p.run() } diff --git a/crates/forma-lang/tests/lang_expressiveness.rs b/crates/forma-lang/tests/lang_expressiveness.rs index 424169f..8c622ef 100644 --- a/crates/forma-lang/tests/lang_expressiveness.rs +++ b/crates/forma-lang/tests/lang_expressiveness.rs @@ -365,3 +365,212 @@ wheel = gear(z2, m=m, h=h, bore=8, rot=(0, 0, 180 / z2), at=(center_dist, 0, 0), assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); assert!(png.len() > 2000); } + +#[test] +fn test_spec_smooth_hollow_loft_and_draped_poncho_sheet() { + // 1. Core SPEC_PIPE exposes smooth/flat and sheet/loft thickness directly + assert!(forma_lang::SPEC_PIPE.contains("smooth(angle=35)")); + assert!(forma_lang::SPEC_PIPE.contains("flat()")); + assert!(forma_lang::SPEC_PIPE.contains("sheet(")); + + // 2. End-to-end Forma-Pipe script combining draped 3D poncho sheet, hollow pleated loft, + // default auto-smooth dome, and explicit flat() opt-out under strict manifold checking. + let (s, obs) = eval_strict( + r#" +dome = revolve([(0.0, 1.0), (0.35, 0.94), (0.65, 0.78), (0.85, 0.5), (0.95, 0.15), (0.95, 0.0)], segs=32) + | mat("terracotta", color=(0.78, 0.42, 0.28)) + +faceted = sphere(0.4, at=(2.0, 0, 0.4)) | flat() + +skirt = loft([ + (0.0, [((0.6 + 0.05 * sin(6 * 2 * pi * i / 36)) * cos(2 * pi * i / 36), (0.6 + 0.05 * sin(6 * 2 * pi * i / 36)) * sin(2 * pi * i / 36)) for i in range(36)]), + (0.8, [(0.35 * cos(2 * pi * i / 36), 0.35 * sin(2 * pi * i / 36)) for i in range(36)]) +], segs=36, t=0.03) | move(-2.0, 0, 0) + +poncho = sheet([ + [ + ( + ((0.62 * (1 - v / 7) + 0.22 * (v / 7)) + (1 - v / 7) * 0.04 * sin(5 * 2 * pi * u / 24)) * cos(2 * pi * u / 24), + ((0.62 * (1 - v / 7) + 0.22 * (v / 7)) + (1 - v / 7) * 0.04 * sin(5 * 2 * pi * u / 24)) * sin(2 * pi * u / 24), + 0.7 * (v / 7) - (1 - v / 7) * 0.15 * abs(cos(2 * pi * u / 24)) + ) + for u in range(24) + ] + for v in range(8) +], t=0.025, closed=true) | mat("ochre_cloth", color=(0.76, 0.56, 0.24), roughness=0.85) +"#, + ); + assert!(obs.ok); + + let dome = s.get_part("dome").unwrap(); + assert_eq!(dome.smooth_angle_deg, Some(forma_core::mesh::DEFAULT_SMOOTH_ANGLE_DEG)); + assert!(dome.weighted_normals); + + let faceted = s.get_part("faceted").unwrap(); + assert!(faceted.smooth_angle_deg.is_none()); + + let skirt = s.get_part("skirt").unwrap(); + let inv_s = MeshInvariants::compute(skirt); + assert!(inv_s.watertight && inv_s.non_manifold_edges == 0 && inv_s.boundary_edges == 0); + assert_eq!(inv_s.genus, 1); + assert!(!has_self_intersections(skirt)); + + let poncho = s.get_part("poncho").unwrap(); + let inv_p = MeshInvariants::compute(poncho); + assert!(inv_p.watertight && inv_p.non_manifold_edges == 0 && inv_p.boundary_edges == 0); + assert_eq!(inv_p.genus, 1); + assert!(!has_self_intersections(poncho)); + + // Scene renders cleanly with smooth Gouraud shading + let png = s.render_preview_scene_bytes(512).unwrap(); + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); +} + +#[test] +fn test_scene_hierarchy_instancing_automatic_dedup_and_gpu_instancing() { + use forma_core::import::read_glb_bytes; + use forma_core::instancing::GlbSceneOptions; + + fn extract_glb_json_str(glb: &[u8]) -> String { + assert!(glb.len() > 20 && &glb[0..4] == b"glTF"); + let jlen = u32::from_le_bytes(glb[12..16].try_into().unwrap()) as usize; + String::from_utf8(glb[20..20 + jlen].to_vec()).expect("valid UTF-8 glTF JSON") + } + + // 1. Layer 1: Automatic O(V) deduplication on 48 separate deep-transformed parts + // (simulates naive agent scripts that bake move/rot/scale into distinct named parts) + let mut naive_src = String::new(); + for i in 0..48 { + let ang = (i as f64) * 360.0 / 48.0; + let rad = ang.to_radians(); + let x = 2.0 * rad.cos(); + let y = 2.0 * rad.sin(); + naive_src.push_str(&format!( + "bar_{i} = cyl(0.05, 1.2, segs=16) | rot(0, 0, {ang:.4}) | move({x:.5}, {y:.5}, 0.6)\n" + )); + } + let (s_naive, _) = eval_strict(&naive_src); + let glb_dedup = s_naive.export_scene_glb_bytes(true).expect("dedup glb"); + let glb_raw = s_naive + .export_scene_glb_bytes_with_options(GlbSceneOptions { + deduplicate: false, + ..Default::default() + }) + .expect("undeduplicated glb"); + let j_dedup = extract_glb_json_str(&glb_dedup); + let j_raw = extract_glb_json_str(&glb_raw); + assert_eq!(j_raw.matches("\"primitives\":").count(), 48); + assert_eq!( + j_dedup.matches("\"primitives\":").count(), + 1, + "48 deep-transformed cylinders must auto-deduplicate to 1 shared glTF mesh" + ); + assert!( + glb_dedup.len() * 5 < glb_raw.len(), + "auto-dedup GLB ({} B) should be >5x smaller than raw ({} B)", + glb_dedup.len(), + glb_raw.len() + ); + // Round-trip import reconstructs all 48 instances' exact triangle count + let rt = read_glb_bytes(&glb_dedup).expect("round-trip dedup glb"); + let one_tris = s_naive.get_part("bar_0").unwrap().triangulated().faces.len(); + assert_eq!(rt.faces.len(), one_tris * 48); + + // 2. Layer 2 + Layer 3: 504-instance Pavilion with nested group hierarchy + inst() + let (mut s, obs) = eval_strict( + r#" +dome = revolve([(0.0, 2.2), (0.5, 2.1), (1.0, 1.8), (1.4, 1.3), (1.6, 0.8), (1.6, 0.7)], segs=24) + | mat("gold", color=(0.85, 0.70, 0.28), metallic=0.8, roughness=0.3) + | group("pavilion/roof") + +drum = pipe(1.65, 1.50, 0.75, segs=24, z0=0) + | mat("stone", color=(0.82, 0.77, 0.68), roughness=0.75) + | group("pavilion/drum") + +_bar = cyl(0.03, 0.65, segs=12) | mat("wood", color=(0.45, 0.30, 0.18)) +inst(_bar, + at=[(1.58 * cos(2 * pi * i / 480), 1.58 * sin(2 * pi * i / 480), 0.37) for i in range(480)], + rot=[(0, 0, i * 360 / 480) for i in range(480)], + group="pavilion/drum/grille", + name="grille_bar" +) + +_stud = sphere(0.05, segs=12) | mat("brass", color=(0.9, 0.75, 0.3), metallic=0.9) +inst(_stud, + at=[(1.64 * cos(2 * pi * i / 24), 1.64 * sin(2 * pi * i / 24), 0.75) for i in range(24)], + group="pavilion/roof/rim", + name="stud" +) +"#, + ); + assert!(obs.ok); + assert_eq!(s.total_instance_count(), 504); + + // Token-efficient observation collapses 504 instances into 1 compact summary line! + assert!(obs.text.contains("insts=504"), "obs header should report insts=504: {}", obs.text); + assert!( + obs.text.contains("grille_bar x480 [pavilion/drum/grille]"), + "obs should summarize instance proto + group: {}", + obs.text + ); + assert!( + obs.text.lines().count() <= 14, + "obs must stay compact (got {} lines):\n{}", + obs.text.lines().count(), + obs.text + ); + + // Default core glTF 2.0 export: nested hierarchy + only 4 unique meshes + tiny file size! + let glb_core = s.export_scene_glb_bytes(true).expect("pavilion core glb"); + let j_core = extract_glb_json_str(&glb_core); + assert_eq!(j_core.matches("\"primitives\":").count(), 4); + assert!(!j_core.contains("extensionsRequired"), "default export stays core glTF 2.0"); + assert!( + glb_core.len() < 120_000, + "504-instance pavilion GLB should be <120 KB (got {} bytes)", + glb_core.len() + ); + assert!(j_core.contains("\"name\":\"pavilion\"")); + assert!(j_core.contains("\"name\":\"roof\"")); + assert!(j_core.contains("\"name\":\"drum\"")); + assert!(j_core.contains("\"name\":\"grille\"")); + assert!(j_core.contains("\"scenes\":[{\"nodes\":[0]}]"), "single root 'pavilion' node: {}", &j_core[..j_core.len().min(300)]); + + // Realtime profile triggers the int4 packaging policy -> EXT_mesh_gpu_instancing! + let glb_gpu = s + .export_scene_glb_bytes_with_options(GlbSceneOptions::realtime()) + .expect("pavilion gpu glb"); + let j_gpu = extract_glb_json_str(&glb_gpu); + assert_eq!(j_gpu.matches("\"primitives\":").count(), 4); + assert!(j_gpu.contains("\"extensionsUsed\":[\"EXT_mesh_gpu_instancing\"]")); + assert!(j_gpu.contains("\"extensionsRequired\":[\"EXT_mesh_gpu_instancing\"]")); + assert!( + glb_gpu.len() < glb_core.len(), + "GPU-instanced GLB ({} B) should be even smaller than data-instanced GLB ({} B)", + glb_gpu.len(), + glb_core.len() + ); + eprintln!( + "Pavilion benchmark (504 insts + 2 hero parts): 48-part naive raw={} B -> dedup={} B | 504-inst core={} B | 504-inst GPU={} B", + glb_raw.len(), + glb_dedup.len(), + glb_core.len(), + glb_gpu.len() + ); + + // Software studio PNG preview renders all 504 instances cleanly + let png = s.render_preview_scene_bytes(256).expect("pavilion preview"); + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + + // Transactional rollback & del() work cleanly on instance sets and groups + s.checkpoint("full_pavilion"); + let obs_del = eval_script(&mut s, Dialect::Pipe, r#"del("grille_bar")"#).unwrap(); + assert!(obs_del.ok); + assert_eq!(s.total_instance_count(), 24); + s.rollback("full_pavilion").unwrap(); + assert_eq!(s.total_instance_count(), 504); + + // Spec visibility check + assert!(forma_lang::SPEC_PIPE.contains("group(path)")); + assert!(forma_lang::SPEC_PIPE.contains("inst(p,at=,rot=,group=)")); +} diff --git a/grammar/forma_pipe.gbnf b/grammar/forma_pipe.gbnf index f9aa47d..34c4e13 100644 --- a/grammar/forma_pipe.gbnf +++ b/grammar/forma_pipe.gbnf @@ -36,7 +36,7 @@ pipe-op ::= "add" | "union" | "cut" | "sub" | "diff" | "intersect" | "pattern_linear" | "pattern_radial" | "array" | "radial" | "mat" | "material" | "color" | "decimate" | "lod" | "smooth" | "flat" | "solidify" | "deform" - | "unwrap" | "uv" | "remesh" | "bisect" + | "unwrap" | "uv" | "remesh" | "bisect" | "group" ident ::= [a-zA-Z_] [a-zA-Z0-9_]* number ::= ([0-9]+ ("." [0-9]*)? | "." [0-9]+) ([eE] [+-]? [0-9]+)?