Skip to content

armgit / forma

Public Imported from GitHub
0

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

36.3 KB
Raw Blame
//! Lean O(V) structural/geometric scene deduplication, glTF TRS recovery,
//! and a tiny quantized (`int4`) export-packaging decision model.
//!
//! - **Layer 1 (Deterministic O(V) Deduplication):** Buckets meshes by exact
//!   `(V, F, connectivity, material, smooth, UV)` signature, then recovers exact
//!   rigid + scale transforms (`Trs`) from "deep-transformed" copies via fast
//!   pointer/translation paths and a deterministic 4-point canonical basis
//!   (`L = B * A^-1`, verified across every vertex to `< 1e-4 * diag`).
//! - **Layer 3 (`int4` ScenePackPolicy):** A ~200-byte integer-only quantized
//!   MLP (`12 -> 16 -> 4`, `~0.5 µs` CPU/WASM, bit-exact) that selects per-cluster
//!   packaging (`Standalone`, `DataInstance`, `GpuInstance`, or
//!   `GpuInstanceSpatialCells`) for glTF 2.0 / `EXT_mesh_gpu_instancing` export.

use crate::math::Vec3;
use crate::mesh::PolyMesh;
use std::collections::HashMap;
use std::sync::Arc;

/// glTF-ready Translation / Rotation (unit quaternion `[x,y,z,w]`) / Scale transform.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Trs {
    pub translation: [f64; 3],
    /// Unit quaternion `[x, y, z, w]` (glTF 2.0 order).
    pub rotation: [f64; 4],
    pub scale: [f64; 3],
}

impl Trs {
    pub const IDENTITY: Self = Self {
        translation: [0.0, 0.0, 0.0],
        rotation: [0.0, 0.0, 0.0, 1.0],
        scale: [1.0, 1.0, 1.0],
    };

    #[inline]
    pub fn from_translation(t: Vec3) -> Self {
        Self {
            translation: [t.x, t.y, t.z],
            rotation: [0.0, 0.0, 0.0, 1.0],
            scale: [1.0, 1.0, 1.0],
        }
    }

    /// Construct from Forma's exact Euler XYZ degrees (`PolyMesh::rotate_deg`), scale, and translation:
    /// applies scale -> Euler XYZ rotation -> translation (`p' = R * (s * p) + t`).
    pub fn from_translation_rot_deg_scale(t: Vec3, rot_deg: Vec3, scale: Vec3) -> Self {
        let r = Vec3::euler_xyz_deg_matrix(rot_deg.x, rot_deg.y, rot_deg.z);
        let q = mat3_to_quat(&r);
        Self {
            translation: [t.x, t.y, t.z],
            rotation: q,
            scale: [scale.x, scale.y, scale.z],
        }
    }

    /// Extract exact glTF `Trs` (`L = R * diag(s)`) from a 3x3 linear matrix and translation.
    /// Returns `None` if the matrix is singular, reflected (`det <= 0`), or sheared.
    pub fn from_mat3_translation(l: [[f64; 3]; 3], t: Vec3) -> Option<Self> {
        let det = mat3_det(&l);
        if !det.is_finite() || det <= 1e-12 {
            return None;
        }
        // Column vectors of L
        let c0 = Vec3::new(l[0][0], l[1][0], l[2][0]);
        let c1 = Vec3::new(l[0][1], l[1][1], l[2][1]);
        let c2 = Vec3::new(l[0][2], l[1][2], l[2][2]);
        let sx = c0.len();
        let sy = c1.len();
        let sz = c2.len();
        if sx <= 1e-9 || sy <= 1e-9 || sz <= 1e-9 {
            return None;
        }
        let r0 = c0 * (1.0 / sx);
        let r1 = c1 * (1.0 / sy);
        let r2 = c2 * (1.0 / sz);

        // Reject shear: columns of R must be mutually orthogonal and right-handed
        if r0.dot(r1).abs() > 1e-3 || r0.dot(r2).abs() > 1e-3 || r1.dot(r2).abs() > 1e-3 {
            return None;
        }
        if r0.cross(r1).dot(r2) < 0.999 {
            return None;
        }

        // Orthonormalize cleanly via polar/Gram-Schmidt polish for exact unit quaternion
        let u0 = r0.normalized();
        let u1 = (r1 - u0 * u0.dot(r1)).normalized();
        let u2 = u0.cross(u1).normalized();
        let r = [
            [u0.x, u1.x, u2.x],
            [u0.y, u1.y, u2.y],
            [u0.z, u1.z, u2.z],
        ];
        let q = mat3_to_quat(&r);
        Some(Self {
            translation: [t.x, t.y, t.z],
            rotation: q,
            scale: [sx, sy, sz],
        })
    }

    #[inline]
    pub fn rotation_mat3(&self) -> [[f64; 3]; 3] {
        quat_to_mat3(self.rotation)
    }

    #[inline]
    pub fn linear_mat3(&self) -> [[f64; 3]; 3] {
        let r = self.rotation_mat3();
        let [sx, sy, sz] = self.scale;
        [
            [r[0][0] * sx, r[0][1] * sy, r[0][2] * sz],
            [r[1][0] * sx, r[1][1] * sy, r[1][2] * sz],
            [r[2][0] * sx, r[2][1] * sy, r[2][2] * sz],
        ]
    }

    #[inline]
    pub fn apply_point(&self, p: Vec3) -> Vec3 {
        let sp = Vec3::new(p.x * self.scale[0], p.y * self.scale[1], p.z * self.scale[2]);
        let r = self.rotation_mat3();
        let rp = sp.mul_mat3(&r);
        Vec3::new(
            rp.x + self.translation[0],
            rp.y + self.translation[1],
            rp.z + self.translation[2],
        )
    }

    /// Compose `self * inner` (applying `inner` first, then `self`).
    /// Returns `None` if the composition introduces shear (e.g. rotated non-uniform scale).
    pub fn compose(&self, inner: &Trs) -> Option<Trs> {
        if self.is_identity() {
            return Some(*inner);
        }
        if inner.is_identity() {
            return Some(*self);
        }
        let l_a = self.linear_mat3();
        let l_b = inner.linear_mat3();
        let l = mat3_mul(&l_a, &l_b);
        let tb = Vec3::new(inner.translation[0], inner.translation[1], inner.translation[2]);
        let t = tb.mul_mat3(&l_a)
            + Vec3::new(self.translation[0], self.translation[1], self.translation[2]);
        Self::from_mat3_translation(l, t)
    }

    /// Convert Z-up model-unit TRS to glTF coordinate space (`yup` and `unit_scale = meters_per_unit`).
    /// Uses exact similarity transform `C * R * C^T` and `C * S * C^T = (sx, sz, sy)` where
    /// `C(x, y, z) = (x, z, -y)` is a proper rotation (`det = +1`).
    pub fn to_gltf_space(&self, yup: bool, unit_scale: f64) -> Trs {
        if !yup {
            return Trs {
                translation: [
                    self.translation[0] * unit_scale,
                    self.translation[1] * unit_scale,
                    self.translation[2] * unit_scale,
                ],
                rotation: self.rotation,
                scale: self.scale,
            };
        }
        let t = [
            self.translation[0] * unit_scale,
            self.translation[2] * unit_scale,
            -self.translation[1] * unit_scale,
        ];
        let s = [self.scale[0], self.scale[2], self.scale[1]];
        let q = if self.has_rotation() {
            // Exact C * R * C^T for C = [[1,0,0],[0,0,1],[0,-1,0]]:
            // Row/col remap: 0->0, 1->+2, 2->-1
            let r = self.rotation_mat3();
            let r_yup = [
                [r[0][0], r[0][2], -r[0][1]],
                [r[2][0], r[2][2], -r[2][1]],
                [-r[1][0], -r[1][2], r[1][1]],
            ];
            mat3_to_quat(&r_yup)
        } else {
            [0.0, 0.0, 0.0, 1.0]
        };
        Trs {
            translation: t,
            rotation: q,
            scale: s,
        }
    }

    #[inline]
    pub fn has_translation(&self) -> bool {
        self.translation[0].abs() > 1e-9
            || self.translation[1].abs() > 1e-9
            || self.translation[2].abs() > 1e-9
    }

    #[inline]
    pub fn has_rotation(&self) -> bool {
        self.rotation[0].abs() > 1e-7
            || self.rotation[1].abs() > 1e-7
            || self.rotation[2].abs() > 1e-7
            || (self.rotation[3].abs() - 1.0).abs() > 1e-7
    }

    #[inline]
    pub fn has_scale(&self) -> bool {
        (self.scale[0] - 1.0).abs() > 1e-7
            || (self.scale[1] - 1.0).abs() > 1e-7
            || (self.scale[2] - 1.0).abs() > 1e-7
    }

    #[inline]
    pub fn is_nonuniform_scale(&self) -> bool {
        (self.scale[0] - self.scale[1]).abs() > 1e-5
            || (self.scale[0] - self.scale[2]).abs() > 1e-5
    }

    #[inline]
    pub fn is_identity(&self) -> bool {
        !self.has_translation() && !self.has_rotation() && !self.has_scale()
    }

    /// Return a transformed copy of `mesh` with this TRS baked into vertex positions
    /// (used by software studio PNG rendering and SVG blueprints).
    pub fn transform_mesh(&self, mesh: &PolyMesh) -> PolyMesh {
        if self.is_identity() {
            return mesh.clone();
        }
        let mut out = mesh.clone();
        let l = self.linear_mat3();
        let t = Vec3::new(self.translation[0], self.translation[1], self.translation[2]);
        for v in &mut out.verts {
            *v = v.mul_mat3(&l) + t;
        }
        out
    }
}

#[inline]
fn mat3_det(m: &[[f64; 3]; 3]) -> f64 {
    m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
        - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
        + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
}

#[inline]
fn mat3_mul(a: &[[f64; 3]; 3], b: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {
    let mut out = [[0.0; 3]; 3];
    for i in 0..3 {
        for j in 0..3 {
            out[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j];
        }
    }
    out
}

fn mat3_inv(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
    let det = mat3_det(m);
    if !det.is_finite() || det.abs() <= 1e-18 {
        return None;
    }
    let inv_d = 1.0 / det;
    Some([
        [
            (m[1][1] * m[2][2] - m[1][2] * m[2][1]) * inv_d,
            (m[0][2] * m[2][1] - m[0][1] * m[2][2]) * inv_d,
            (m[0][1] * m[1][2] - m[0][2] * m[1][1]) * inv_d,
        ],
        [
            (m[1][2] * m[2][0] - m[1][0] * m[2][2]) * inv_d,
            (m[0][0] * m[2][2] - m[0][2] * m[2][0]) * inv_d,
            (m[0][2] * m[1][0] - m[0][0] * m[1][2]) * inv_d,
        ],
        [
            (m[1][0] * m[2][1] - m[1][1] * m[2][0]) * inv_d,
            (m[0][1] * m[2][0] - m[0][0] * m[2][1]) * inv_d,
            (m[0][0] * m[1][1] - m[0][1] * m[1][0]) * inv_d,
        ],
    ])
}

/// Convert proper 3x3 rotation matrix to unit quaternion `[x, y, z, w]` (Shepperd's method).
pub fn mat3_to_quat(m: &[[f64; 3]; 3]) -> [f64; 4] {
    let tr = m[0][0] + m[1][1] + m[2][2];
    let (mut x, mut y, mut z, mut w) = if tr > 0.0 {
        let s = (tr + 1.0).sqrt() * 2.0;
        (
            (m[2][1] - m[1][2]) / s,
            (m[0][2] - m[2][0]) / s,
            (m[1][0] - m[0][1]) / s,
            0.25 * s,
        )
    } else if m[0][0] > m[1][1] && m[0][0] > m[2][2] {
        let s = (1.0 + m[0][0] - m[1][1] - m[2][2]).sqrt() * 2.0;
        (
            0.25 * s,
            (m[0][1] + m[1][0]) / s,
            (m[0][2] + m[2][0]) / s,
            (m[2][1] - m[1][2]) / s,
        )
    } else if m[1][1] > m[2][2] {
        let s = (1.0 + m[1][1] - m[0][0] - m[2][2]).sqrt() * 2.0;
        (
            (m[0][1] + m[1][0]) / s,
            0.25 * s,
            (m[1][2] + m[2][1]) / s,
            (m[0][2] - m[2][0]) / s,
        )
    } else {
        let s = (1.0 + m[2][2] - m[0][0] - m[1][1]).sqrt() * 2.0;
        (
            (m[0][2] + m[2][0]) / s,
            (m[1][2] + m[2][1]) / s,
            0.25 * s,
            (m[1][0] - m[0][1]) / s,
        )
    };
    let len = (x * x + y * y + z * z + w * w).sqrt();
    if len > 1e-12 {
        let inv = 1.0 / len;
        x *= inv;
        y *= inv;
        z *= inv;
        w *= inv;
    } else {
        return [0.0, 0.0, 0.0, 1.0];
    }
    // Canonical hemisphere (`w >= 0`) so identical rotations always produce identical quaternions
    if w < 0.0 {
        [-x, -y, -z, -w]
    } else {
        [x, y, z, w]
    }
}

pub fn quat_to_mat3(q: [f64; 4]) -> [[f64; 3]; 3] {
    let [x, y, z, w] = q;
    let x2 = x + x;
    let y2 = y + y;
    let z2 = z + z;
    let xx = x * x2;
    let xy = x * y2;
    let xz = x * z2;
    let yy = y * y2;
    let yz = y * z2;
    let zz = z * z2;
    let wx = w * x2;
    let wy = w * y2;
    let wz = w * z2;
    [
        [1.0 - (yy + zz), xy - wz, xz + wy],
        [xy + wz, 1.0 - (xx + zz), yz - wx],
        [xz - wy, yz + wx, 1.0 - (xx + yy)],
    ]
}

// ---------------------------------------------------------------------------
// Layer 1: O(V) Connectivity-Hash + 4-Point Canonical Transform Deduplication
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct MeshSignature {
    n_verts: usize,
    n_faces: usize,
    smooth_bits: u64,
    weighted_normals: bool,
    mat_hash: u64,
    topo_uv_hash: u64,
}

#[inline]
fn fnv_mix(mut h: u64, v: u64) -> u64 {
    h ^= v;
    h.wrapping_mul(0x100000001b3)
}

fn compute_mesh_signature(mesh: &PolyMesh) -> MeshSignature {
    const FNV_OFFSET: u64 = 0xcbf29ce484222325;

    let mut mat_hash = FNV_OFFSET;
    mat_hash = fnv_mix(mat_hash, mesh.materials.len() as u64);
    for m in &mesh.materials {
        for &b in m.name.as_bytes() {
            mat_hash = fnv_mix(mat_hash, b as u64);
        }
        for c in m.color {
            mat_hash = fnv_mix(mat_hash, c.to_bits() as u64);
        }
        mat_hash = fnv_mix(mat_hash, m.metallic.to_bits() as u64);
        mat_hash = fnv_mix(mat_hash, m.roughness.to_bits() as u64);
        for e in m.emissive {
            mat_hash = fnv_mix(mat_hash, e.to_bits() as u64);
        }
        mat_hash = fnv_mix(mat_hash, m.emissive_strength.to_bits() as u64);
        mat_hash = fnv_mix(mat_hash, m.transmission.to_bits() as u64);
        mat_hash = fnv_mix(mat_hash, m.ior.to_bits() as u64);
        mat_hash = fnv_mix(mat_hash, m.double_sided as u64);
    }

    let mut topo_uv_hash = FNV_OFFSET;
    for f in &mesh.faces {
        topo_uv_hash = fnv_mix(topo_uv_hash, f.verts.len() as u64);
        topo_uv_hash = fnv_mix(topo_uv_hash, f.mat_id as u64);
        for &vi in &f.verts {
            topo_uv_hash = fnv_mix(topo_uv_hash, vi as u64);
        }
        topo_uv_hash = fnv_mix(topo_uv_hash, f.uvs.len() as u64);
        for uv in &f.uvs {
            let uq = (uv[0] * 1e4).round() as i64 as u64;
            let vq = (uv[1] * 1e4).round() as i64 as u64;
            topo_uv_hash = fnv_mix(topo_uv_hash, uq);
            topo_uv_hash = fnv_mix(topo_uv_hash, vq);
        }
    }

    MeshSignature {
        n_verts: mesh.verts.len(),
        n_faces: mesh.faces.len(),
        smooth_bits: mesh.smooth_angle_deg.map(|d| d.to_bits()).unwrap_or(u64::MAX),
        weighted_normals: mesh.weighted_normals,
        mat_hash,
        topo_uv_hash,
    }
}

/// Select 4 well-conditioned spanning vertex indices `[i0, i1, i2, i3]` on `mesh`
/// using greedy max-distance / max-area / max-volume selection with a 1.01 tie margin.
fn select_canonical_frame(mesh: &PolyMesh) -> Option<([usize; 4], [[f64; 3]; 3], f64)> {
    let nv = mesh.verts.len();
    if nv < 4 {
        return None;
    }
    let bb = mesh.aabb();
    let diag = bb.size().len();
    if diag <= 1e-12 {
        return None;
    }

    let i0 = 0usize;
    let p0 = mesh.verts[i0];

    let mut i1 = 0usize;
    let mut best_d1 = 0.0;
    for (i, &p) in mesh.verts.iter().enumerate() {
        let d2 = (p - p0).len_sq();
        if d2 > best_d1 * 1.01 {
            best_d1 = d2;
            i1 = i;
        }
    }
    if best_d1 <= 1e-18 * diag * diag {
        return None;
    }
    let e1 = mesh.verts[i1] - p0;

    let mut i2 = 0usize;
    let mut best_a2 = 0.0;
    for (i, &p) in mesh.verts.iter().enumerate() {
        let a2 = e1.cross(p - p0).len_sq();
        if a2 > best_a2 * 1.01 {
            best_a2 = a2;
            i2 = i;
        }
    }
    if best_a2 <= 1e-18 * diag * diag * diag * diag {
        return None;
    }
    let e2 = mesh.verts[i2] - p0;
    let n12 = e1.cross(e2);

    let mut i3 = 0usize;
    let mut best_v = 0.0;
    for (i, &p) in mesh.verts.iter().enumerate() {
        let v = n12.dot(p - p0).abs();
        if v > best_v * 1.01 {
            best_v = v;
            i3 = i;
        }
    }
    if best_v <= 1e-12 * diag * diag * diag {
        return None;
    }
    let e3 = mesh.verts[i3] - p0;

    let a = [
        [e1.x, e2.x, e3.x],
        [e1.y, e2.y, e3.y],
        [e1.z, e2.z, e3.z],
    ];
    let a_inv = mat3_inv(&a)?;
    Some(([i0, i1, i2, i3], a_inv, diag))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MatchKind {
    Identical,
    Translation,
    RigidScale,
}

/// Recover an exact `Trs` mapping `proto` vertices onto `cand` vertices (`cand ≈ trs(proto)`).
/// Runs in O(V) with strict full-mesh verification (`max_err <= 1e-4 * diag`).
fn solve_trs_between(
    proto: &PolyMesh,
    proto_frame: Option<([usize; 4], [[f64; 3]; 3], f64)>,
    cand: &PolyMesh,
) -> Option<(Trs, MatchKind)> {
    let nv = proto.verts.len();
    if nv == 0 || nv != cand.verts.len() || proto.faces.len() != cand.faces.len() {
        return None;
    }
    // Verify identical face-vertex topology (guards against any 64-bit hash collision)
    for (fa, fb) in proto.faces.iter().zip(&cand.faces) {
        if fa.verts != fb.verts || fa.mat_id != fb.mat_id {
            return None;
        }
    }

    let diag = proto_frame
        .map(|(_, _, d)| d)
        .unwrap_or_else(|| proto.aabb().size().len())
        .max(1e-6);
    let cand_diag = cand.aabb().size().len().max(1e-6);
    let tol = 1e-4 * diag.max(cand_diag);
    let tol_sq = tol * tol;

    // Fast path 1 & 2: pure translation (including identity)
    let dt = cand.verts[0] - proto.verts[0];
    let mut pure_trans = true;
    for i in 1..nv {
        let diff = (proto.verts[i] + dt) - cand.verts[i];
        if diff.len_sq() > tol_sq {
            pure_trans = false;
            break;
        }
    }
    if pure_trans {
        let kind = if dt.len_sq() <= 1e-18 {
            MatchKind::Identical
        } else {
            MatchKind::Translation
        };
        return Some((Trs::from_translation(dt), kind));
    }

    // General path 3: 4-point canonical frame -> L = B * A^-1, t = q0 - L * p0
    let ([i0, i1, i2, i3], a_inv, _) = proto_frame?;
    let p0 = proto.verts[i0];
    let q0 = cand.verts[i0];
    let f1 = cand.verts[i1] - q0;
    let f2 = cand.verts[i2] - q0;
    let f3 = cand.verts[i3] - q0;
    let b = [
        [f1.x, f2.x, f3.x],
        [f1.y, f2.y, f3.y],
        [f1.z, f2.z, f3.z],
    ];
    let l = mat3_mul(&b, &a_inv);
    let t = q0 - p0.mul_mat3(&l);
    let trs = Trs::from_mat3_translation(l, t)?;
    let l_clean = trs.linear_mat3();
    let t_clean = Vec3::new(trs.translation[0], trs.translation[1], trs.translation[2]);

    // Full O(V) verification pass: guarantee zero visual error across every vertex
    for i in 0..nv {
        let pred = proto.verts[i].mul_mat3(&l_clean) + t_clean;
        if (pred - cand.verts[i]).len_sq() > tol_sq {
            return None;
        }
    }
    Some((trs, MatchKind::RigidScale))
}

/// Input node for scene GLB export (combining baked parts and explicit `inst(...)` instances).
#[derive(Debug, Clone, Copy)]
pub struct SceneExportNode<'a> {
    pub name: &'a str,
    pub group: Option<&'a str>,
    pub mesh: &'a Arc<PolyMesh>,
    pub trs: Trs,
}

#[derive(Debug, Clone)]
pub struct DedupInstance<'a> {
    pub name: &'a str,
    pub group: Option<&'a str>,
    pub proto_idx: usize,
    pub trs: Trs,
}

#[derive(Debug, Clone, Default)]
pub struct DedupStats {
    pub input_nodes: usize,
    pub unique_meshes: usize,
    pub deduplicated_instances: usize,
    pub ptr_hits: usize,
    pub translation_hits: usize,
    pub rigid_scale_hits: usize,
}

#[derive(Debug)]
pub struct DeduplicatedScene<'a> {
    pub prototypes: Vec<&'a Arc<PolyMesh>>,
    pub instances: Vec<DedupInstance<'a>>,
    pub stats: DedupStats,
}

/// Deduplicate scene nodes in O(N * V) by structural signature + exact TRS recovery.
pub fn deduplicate_scene_nodes<'a>(nodes: &[SceneExportNode<'a>]) -> DeduplicatedScene<'a> {
    struct ProtoEntry<'a> {
        proto_idx: usize,
        mesh: &'a Arc<PolyMesh>,
        frame: Option<([usize; 4], [[f64; 3]; 3], f64)>,
        frame_computed: bool,
    }

    let mut prototypes: Vec<&'a Arc<PolyMesh>> = Vec::new();
    let mut instances: Vec<DedupInstance<'a>> = Vec::with_capacity(nodes.len());
    let mut stats = DedupStats {
        input_nodes: nodes.len(),
        ..Default::default()
    };

    let mut ptr_to_proto: HashMap<usize, usize> = HashMap::new();
    let mut ptr_to_sig: HashMap<usize, MeshSignature> = HashMap::new();
    let mut buckets: HashMap<MeshSignature, Vec<ProtoEntry<'a>>> = HashMap::new();

    for node in nodes {
        if node.mesh.faces.is_empty() || node.mesh.verts.is_empty() {
            continue;
        }
        let ptr = Arc::as_ptr(node.mesh) as usize;

        // O(1) pointer fast path (explicit `inst(...)` shares the exact Arc<PolyMesh>!)
        if let Some(&proto_idx) = ptr_to_proto.get(&ptr) {
            stats.ptr_hits += 1;
            stats.deduplicated_instances += 1;
            instances.push(DedupInstance {
                name: node.name,
                group: node.group,
                proto_idx,
                trs: node.trs,
            });
            continue;
        }

        let sig = *ptr_to_sig
            .entry(ptr)
            .or_insert_with(|| compute_mesh_signature(node.mesh));

        let bucket = buckets.entry(sig).or_default();
        let mut matched: Option<(usize, Trs)> = None;

        for entry in bucket.iter_mut() {
            if !entry.frame_computed {
                entry.frame = select_canonical_frame(entry.mesh);
                entry.frame_computed = true;
            }
            if let Some((recovered, kind)) = solve_trs_between(entry.mesh, entry.frame, node.mesh) {
                if let Some(combined) = node.trs.compose(&recovered) {
                    match kind {
                        MatchKind::Identical => stats.translation_hits += 1,
                        MatchKind::Translation => stats.translation_hits += 1,
                        MatchKind::RigidScale => stats.rigid_scale_hits += 1,
                    }
                    stats.deduplicated_instances += 1;
                    matched = Some((entry.proto_idx, combined));
                    break;
                }
            }
        }

        if let Some((proto_idx, trs)) = matched {
            instances.push(DedupInstance {
                name: node.name,
                group: node.group,
                proto_idx,
                trs,
            });
        } else {
            let proto_idx = prototypes.len();
            prototypes.push(node.mesh);
            ptr_to_proto.insert(ptr, proto_idx);
            bucket.push(ProtoEntry {
                proto_idx,
                mesh: node.mesh,
                frame: None,
                frame_computed: false,
            });
            instances.push(DedupInstance {
                name: node.name,
                group: node.group,
                proto_idx,
                trs: node.trs,
            });
        }
    }

    stats.unique_meshes = prototypes.len();
    DeduplicatedScene {
        prototypes,
        instances,
        stats,
    }
}

// ---------------------------------------------------------------------------
// Layer 3: Tiny Quantized (`int4`) Scene Export Packaging Bandit (~200 bytes)
// ---------------------------------------------------------------------------

/// glTF scene packaging strategy chosen per deduplicated prototype cluster.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScenePackStrategy {
    /// Single unique instance (`N == 1`): standard standalone glTF node.
    Standalone = 0,
    /// Core glTF 2.0 data instancing (`nodes[i].mesh = proto` + TRS): universal
    /// compatibility (Blender, Unreal, Three.js, Godot) with full per-node naming.
    DataInstance = 1,
    /// Single-batch `EXT_mesh_gpu_instancing` node (`TRANSLATION`/`ROTATION`/`SCALE`).
    GpuInstance = 2,
    /// Spatial 2x2x2 cell-partitioned `EXT_mesh_gpu_instancing` for wide instance clouds
    /// so realtime engines preserve tight frustum culling.
    GpuInstanceSpatialCells = 3,
}

/// Export options controlling glTF 2.0 scene packaging & instancing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GlbSceneOptions {
    /// Convert Z-up model coordinates to glTF Y-up (default `true`).
    pub yup: bool,
    /// Enable automatic O(V) structural/geometric deduplication (default `true`).
    pub deduplicate: bool,
    /// Allow `EXT_mesh_gpu_instancing` when the `int4` packaging policy selects it
    /// (default `false` so standard GLBs stay 100% core glTF 2.0 compatible).
    pub gpu_instancing: bool,
    /// Force per-instance named glTF nodes (prevents collapsing into GPU batches).
    pub preserve_node_names: bool,
}

impl Default for GlbSceneOptions {
    fn default() -> Self {
        Self {
            yup: true,
            deduplicate: true,
            gpu_instancing: false,
            preserve_node_names: false,
        }
    }
}

impl GlbSceneOptions {
    /// Realtime web/engine profile enabling `EXT_mesh_gpu_instancing` via the `int4` policy.
    pub fn realtime() -> Self {
        Self {
            yup: true,
            deduplicate: true,
            gpu_instancing: true,
            preserve_node_names: false,
        }
    }
}

/// 12 compact cluster features fed to the quantized `int4` packaging policy.
#[derive(Debug, Clone, Copy)]
pub struct ClusterPackFeatures {
    pub instance_count: usize,
    pub faces_per_instance: usize,
    pub verts_per_instance: usize,
    pub material_count: usize,
    pub has_uvs: bool,
    pub has_rotation: bool,
    pub has_nonuniform_scale: bool,
    /// Ratio of cluster centroid AABB diagonal to prototype AABB diagonal.
    pub spatial_spread_ratio: f64,
    /// Fraction of instances belonging to the dominant group path (`[0, 1]`).
    pub same_group_fraction: f64,
    pub allow_gpu_instancing: bool,
    pub preserve_node_names: bool,
}

// Quantized `12 -> 8 -> 4` signed-int4 neural policy (packed 2 weights per byte = 64 bytes total!)
// Bit-exact integer-only inference (`~0.3 µs`), zero external dependencies, deterministic on x86/ARM/WASM.
//
// Feature order (quantized to [0..16]):
//  f0: n == 1 ? 16 : 0
//  f1: n >= 2 ? 16 : 0
//  f2: n >= 4 ? 16 : 0
//  f3: n >= 16 ? 16 : 0
//  f4: log2(n) clamped to [0..16]
//  f5: faces_per_instance >= 8 ? 16 : 4
//  f6: spatial_spread_ratio >= 8.0 ? 16 : 0
//  f7: spatial_spread_ratio >= 20.0 ? 16 : 0
//  f8: same_group_fraction * 16
//  f9: allow_gpu_instancing ? 16 : 0
//  f10: preserve_node_names ? 16 : 0
//  f11: has_nonuniform_scale ? 16 : 0

const fn pack_i4_pair(a: i8, b: i8) -> u8 {
    (((a as u8) & 0x0F) << 4) | ((b as u8) & 0x0F)
}

#[inline]
fn unpack_i4(byte: u8, high: bool) -> i32 {
    let nibble = if high { (byte >> 4) & 0x0F } else { byte & 0x0F };
    if nibble >= 8 {
        (nibble as i32) - 16
    } else {
        nibble as i32
    }
}

// Layer 1: 8 hidden units x 12 inputs = 96 signed int4 weights = 48 packed bytes
// Hidden units encode clean regime detectors:
//  h0: standalone (n == 1)
//  h1: core data-instance baseline (n >= 2)
//  h2: gpu eligible (n >= 4 && allow_gpu && !preserve_names)
//  h3: high-count gpu boost (n >= 16 && allow_gpu && !preserve_names)
//  h4: wide-spread spatial cell detector (n >= 16 && spread >= 8 && allow_gpu && !preserve_names)
//  h5: extreme-spread boost (spread >= 20 && allow_gpu)
//  h6: preserve-names veto on GPU instancing
//  h7: low-poly high-count batching bonus
const PACK_W1: [u8; 48] = [
    // h0: +7*f0 - 4*f1
    pack_i4_pair(7, -4), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0),
    // h1: -6*f0 + 6*f1 + 1*f8
    pack_i4_pair(-6, 6), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(1, 0), pack_i4_pair(0, 0),
    // h2: +5*f2 + 6*f9 - 7*f10
    pack_i4_pair(0, 0), pack_i4_pair(5, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 6), pack_i4_pair(-7, 0),
    // h3: +4*f3 + 2*f4 + 4*f9 - 7*f10
    pack_i4_pair(0, 0), pack_i4_pair(0, 4), pack_i4_pair(2, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 4), pack_i4_pair(-7, 0),
    // h4: +4*f3 + 5*f6 + 4*f9 - 7*f10
    pack_i4_pair(0, 0), pack_i4_pair(0, 4), pack_i4_pair(0, 0), pack_i4_pair(5, 0), pack_i4_pair(0, 4), pack_i4_pair(-7, 0),
    // h5: +3*f3 + 4*f7 + 3*f9 - 7*f10
    pack_i4_pair(0, 0), pack_i4_pair(0, 3), pack_i4_pair(0, 0), pack_i4_pair(0, 4), pack_i4_pair(0, 3), pack_i4_pair(-7, 0),
    // h6: +7*f10 - 2*f0
    pack_i4_pair(-2, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(0, 0), pack_i4_pair(7, 0),
    // h7: +2*f2 + 2*f4 - 1*f5 + 3*f9 - 6*f10
    pack_i4_pair(0, 0), pack_i4_pair(2, 0), pack_i4_pair(2, -1), pack_i4_pair(0, 0), pack_i4_pair(0, 3), pack_i4_pair(-6, 0),
];
const PACK_B1: [i32; 8] = [-16, -8, -96, -96, -128, -96, -16, -64];

// Layer 2: 4 arms x 8 hidden units = 32 signed int4 weights = 16 packed bytes
const PACK_W2: [u8; 16] = [
    // Arm 0: Standalone
    pack_i4_pair(7, -5), pack_i4_pair(-3, -3), pack_i4_pair(-3, -3), pack_i4_pair(0, -2),
    // Arm 1: DataInstance
    pack_i4_pair(-6, 6), pack_i4_pair(-2, -1), pack_i4_pair(-1, -1), pack_i4_pair(6, -1),
    // Arm 2: GpuInstance
    pack_i4_pair(-7, 1), pack_i4_pair(7, 4), pack_i4_pair(-4, -3), pack_i4_pair(-7, 3),
    // Arm 3: GpuInstanceSpatialCells
    pack_i4_pair(-7, 1), pack_i4_pair(3, 3), pack_i4_pair(7, 5), pack_i4_pair(-7, 1),
];
const PACK_B2: [i32; 4] = [0, 8, -4, -12];

/// Select glTF scene packaging strategy for a deduplicated mesh cluster using the 64-byte `int4` MLP.
pub fn choose_scene_pack_strategy(f: &ClusterPackFeatures) -> ScenePackStrategy {
    let n = f.instance_count;
    let spread = if f.spatial_spread_ratio.is_finite() {
        f.spatial_spread_ratio.max(0.0)
    } else {
        0.0
    };
    let grp_frac = if f.same_group_fraction.is_finite() {
        f.same_group_fraction.clamp(0.0, 1.0)
    } else {
        0.0
    };
    let log_n = if n > 1 {
        ((n as f64).log2() * 2.0).round().clamp(0.0, 16.0) as i32
    } else {
        0
    };

    let x: [i32; 12] = [
        if n <= 1 { 16 } else { 0 },
        if n >= 2 { 16 } else { 0 },
        if n >= 4 { 16 } else { 0 },
        if n >= 16 { 16 } else { 0 },
        log_n,
        if f.faces_per_instance >= 8 { 16 } else { 4 },
        if spread >= 8.0 { 16 } else { 0 },
        if spread >= 20.0 { 16 } else { 0 },
        (grp_frac * 16.0).round() as i32,
        if f.allow_gpu_instancing { 16 } else { 0 },
        if f.preserve_node_names { 16 } else { 0 },
        if f.has_nonuniform_scale { 16 } else { 0 },
    ];

    let mut h = [0i32; 8];
    for hi in 0..8 {
        let mut acc = PACK_B1[hi];
        let row_off = hi * 6;
        for xi in 0..12 {
            let w = unpack_i4(PACK_W1[row_off + (xi >> 1)], (xi & 1) == 0);
            acc += w * x[xi];
        }
        // ReLU + right-shift by 4 (integer fixed-point activation)
        h[hi] = if acc > 0 { acc >> 4 } else { 0 };
    }

    let mut scores = [0i32; 4];
    for arm in 0..4 {
        let mut acc = PACK_B2[arm];
        let row_off = arm * 4;
        for hi in 0..8 {
            let w = unpack_i4(PACK_W2[row_off + (hi >> 1)], (hi & 1) == 0);
            acc += w * h[hi];
        }
        scores[arm] = acc;
    }

    // Hard safety guard: never pick GPU instancing unless explicitly enabled & N >= 4
    if !f.allow_gpu_instancing || f.preserve_node_names || n < 4 {
        scores[2] = i32::MIN / 2;
        scores[3] = i32::MIN / 2;
    }
    if n <= 1 {
        return ScenePackStrategy::Standalone;
    }

    let mut best_arm = 1usize;
    let mut best_score = scores[1];
    for arm in [0usize, 2, 3] {
        if scores[arm] > best_score {
            best_score = scores[arm];
            best_arm = arm;
        }
    }
    match best_arm {
        0 => ScenePackStrategy::Standalone,
        1 => ScenePackStrategy::DataInstance,
        2 => ScenePackStrategy::GpuInstance,
        _ => ScenePackStrategy::GpuInstanceSpatialCells,
    }
}

/// Partition instance indices into up to 8 compact octant spatial cells (2x2x2 around centroid midpoint)
/// for frustum-culling-friendly `EXT_mesh_gpu_instancing` batches.
pub fn partition_spatial_cells(positions: &[[f64; 3]], indices: &[usize]) -> Vec<Vec<usize>> {
    if indices.len() < 8 {
        return vec![indices.to_vec()];
    }
    let mut bmin = [f64::INFINITY; 3];
    let mut bmax = [f64::NEG_INFINITY; 3];
    for &idx in indices {
        let p = positions[idx];
        for k in 0..3 {
            bmin[k] = bmin[k].min(p[k]);
            bmax[k] = bmax[k].max(p[k]);
        }
    }
    let mid = [
        0.5 * (bmin[0] + bmax[0]),
        0.5 * (bmin[1] + bmax[1]),
        0.5 * (bmin[2] + bmax[2]),
    ];
    let mut cells: [Vec<usize>; 8] = Default::default();
    for &idx in indices {
        let p = positions[idx];
        let bx = usize::from(p[0] >= mid[0]);
        let by = usize::from(p[1] >= mid[1]);
        let bz = usize::from(p[2] >= mid[2]);
        cells[(bz << 2) | (by << 1) | bx].push(idx);
    }
    cells.into_iter().filter(|c| !c.is_empty()).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::{make_box, make_cylinder};

    #[test]
    fn trs_exact_recovery_for_translation_rotation_and_nonuniform_scale() {
        let proto = Arc::new(make_box(0.4, 0.2, 1.2, 1));

        // Copy 1: pure translation
        let mut c1 = (*proto).clone();
        c1.translate(Vec3::new(3.5, -1.25, 0.8));
        let c1 = Arc::new(c1);

        // Copy 2: non-uniform scale + arbitrary 3D Euler rotation + translation
        let mut c2 = (*proto).clone();
        c2.scale(Vec3::new(1.5, 0.75, 2.0));
        c2.rotate_deg(25.0, -40.0, 65.0);
        c2.translate(Vec3::new(-2.0, 4.0, 1.1));
        let c2 = Arc::new(c2);

        let nodes = [
            SceneExportNode { name: "bar_0", group: Some("drum"), mesh: &proto, trs: Trs::IDENTITY },
            SceneExportNode { name: "bar_1", group: Some("drum"), mesh: &c1, trs: Trs::IDENTITY },
            SceneExportNode { name: "bar_2", group: Some("drum"), mesh: &c2, trs: Trs::IDENTITY },
        ];
        let dedup = deduplicate_scene_nodes(&nodes);
        assert_eq!(dedup.stats.unique_meshes, 1, "all 3 bars must collapse to 1 prototype");
        assert_eq!(dedup.stats.translation_hits, 1);
        assert_eq!(dedup.stats.rigid_scale_hits, 1);

        // Verify exact vertex reconstruction in both Z-up and glTF Y-up space
        for (inst, orig) in dedup.instances.iter().zip([&proto, &c1, &c2]) {
            let trs_yup = inst.trs.to_gltf_space(true, 1.0);
            for (vp, vo) in proto.verts.iter().zip(&orig.verts) {
                let rec = inst.trs.apply_point(*vp);
                assert!((rec - *vo).len() < 1e-6, "Z-up mismatch: {rec:?} vs {vo:?}");

                let vp_yup = Vec3::new(vp.x, vp.z, -vp.y);
                let vo_yup = Vec3::new(vo.x, vo.z, -vo.y);
                let rec_yup = trs_yup.apply_point(vp_yup);
                assert!((rec_yup - vo_yup).len() < 1e-6, "Y-up mismatch: {rec_yup:?} vs {vo_yup:?}");
            }
        }
    }

    #[test]
    fn trs_dedup_rejects_reflected_or_different_topology_safely() {
        let proto = Arc::new(make_cylinder(0.3, 1.0, 16, 1));
        let mut mirrored = (*proto).clone();
        for v in &mut mirrored.verts {
            v.x = -v.x;
        }
        let mirrored = Arc::new(mirrored);
        let nodes = [
            SceneExportNode { name: "a", group: None, mesh: &proto, trs: Trs::IDENTITY },
            SceneExportNode { name: "b", group: None, mesh: &mirrored, trs: Trs::IDENTITY },
        ];
        let dedup = deduplicate_scene_nodes(&nodes);
        assert_eq!(dedup.stats.unique_meshes, 2, "negative-det reflection must not falsely alias");
    }

    #[test]
    fn int4_scene_pack_policy_routes_all_four_regimes_deterministically() {
        let base = ClusterPackFeatures {
            instance_count: 1,
            faces_per_instance: 120,
            verts_per_instance: 80,
            material_count: 1,
            has_uvs: false,
            has_rotation: false,
            has_nonuniform_scale: false,
            spatial_spread_ratio: 1.0,
            same_group_fraction: 1.0,
            allow_gpu_instancing: false,
            preserve_node_names: false,
        };
        assert_eq!(choose_scene_pack_strategy(&base), ScenePackStrategy::Standalone);

        // Editable CAD/arch repeat (core glTF 2.0 default)
        let mut arch = base;
        arch.instance_count = 64;
        assert_eq!(choose_scene_pack_strategy(&arch), ScenePackStrategy::DataInstance);

        // Compact dense grille with GPU instancing enabled -> GpuInstance
        let mut grille = arch;
        grille.allow_gpu_instancing = true;
        grille.spatial_spread_ratio = 3.0;
        assert_eq!(choose_scene_pack_strategy(&grille), ScenePackStrategy::GpuInstance);

        // Wide spatially-spread forest/city cloud -> GpuInstanceSpatialCells
        let mut wide = grille;
        wide.spatial_spread_ratio = 28.0;
        assert_eq!(choose_scene_pack_strategy(&wide), ScenePackStrategy::GpuInstanceSpatialCells);

        // preserve_node_names forces DataInstance even when gpu_instancing is on
        let mut named = wide;
        named.preserve_node_names = true;
        assert_eq!(choose_scene_pack_strategy(&named), ScenePackStrategy::DataInstance);
    }
}