A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
//! Pure-Rust, zero-external-crate 3D asset importers (`.glb`, `.obj`, `.stl`).
//! Designed for fast, deterministic headless server item processing & CAD round-tripping.
use crate::math::Vec3;
use crate::mesh::{Material, PolyMesh};
use serde_json::Value;
use smallvec::SmallVec;
use std::collections::HashMap;
use std::path::Path;
const MAX_IMPORT_BYTES: usize = 32 * 1024 * 1024;
const MAX_IMPORT_FACES: usize = 200_000;
fn ensure_outward_winding_if_closed(mesh: &mut PolyMesh) {
let inv = crate::invariants::MeshInvariants::compute(mesh);
if inv.boundary_edges == 0 && inv.signed_volume < 0.0 {
mesh.flip_winding();
}
}
fn weld_key(v: Vec3) -> (i64, i64, i64) {
(
(v.x * 1e5).round() as i64,
(v.y * 1e5).round() as i64,
(v.z * 1e5).round() as i64,
)
}
/// Import a Wavefront `.obj` mesh from bytes (supports `v`, `f`, `v/vt/vn`, negative indices, n-gons).
pub fn read_obj_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {
if bytes.len() > MAX_IMPORT_BYTES {
return Err(format!("OBJ exceeds max size ({MAX_IMPORT_BYTES} bytes)"));
}
let text = std::str::from_utf8(bytes).map_err(|e| format!("OBJ invalid UTF-8: {e}"))?;
let mut raw_verts: Vec<Vec3> = Vec::new();
let mut mesh = PolyMesh::new();
let mut weld: HashMap<(i64, i64, i64), usize> = HashMap::new();
for line in text.lines() {
let l = line.trim();
if l.is_empty() || l.starts_with('#') {
continue;
}
let mut parts = l.split_whitespace();
let Some(tag) = parts.next() else { continue };
if tag == "v" {
let x: f64 = parts.next().ok_or("OBJ v missing x")?.parse().map_err(|e| format!("OBJ v x: {e}"))?;
let y: f64 = parts.next().ok_or("OBJ v missing y")?.parse().map_err(|e| format!("OBJ v y: {e}"))?;
let z: f64 = parts.next().ok_or("OBJ v missing z")?.parse().map_err(|e| format!("OBJ v z: {e}"))?;
if !x.is_finite() || !y.is_finite() || !z.is_finite() {
return Err("OBJ contains non-finite vertex coordinate".into());
}
raw_verts.push(Vec3::new(x, y, z));
} else if tag == "f" {
if mesh.faces.len() >= MAX_IMPORT_FACES {
return Err(format!("OBJ exceeds max face budget ({MAX_IMPORT_FACES})"));
}
let mut face_verts: SmallVec<[usize; 4]> = SmallVec::new();
for tok in parts {
let idx_str = tok.split('/').next().unwrap_or("");
if idx_str.is_empty() {
continue;
}
let raw_idx: isize = idx_str.parse().map_err(|e| format!("OBJ face index '{tok}': {e}"))?;
let vi = if raw_idx > 0 {
(raw_idx - 1) as usize
} else if raw_idx < 0 {
let abs = raw_idx.unsigned_abs();
if abs > raw_verts.len() {
return Err(format!("OBJ negative vertex index {raw_idx} out of range"));
}
raw_verts.len() - abs
} else {
return Err("OBJ vertex index 0 is invalid".into());
};
if vi >= raw_verts.len() {
return Err(format!("OBJ vertex index {raw_idx} out of range"));
}
let p = raw_verts[vi];
let mapped = *weld.entry(weld_key(p)).or_insert_with(|| mesh.add_vert(p));
if face_verts.last().copied() != Some(mapped) {
face_verts.push(mapped);
}
}
if face_verts.len() >= 3 && face_verts.first() == face_verts.last() {
face_verts.pop();
}
if face_verts.len() >= 3 {
mesh.add_face(face_verts, 0, Some("imported"));
}
}
}
if mesh.faces.is_empty() {
return Err("OBJ contained no valid faces".into());
}
ensure_outward_winding_if_closed(&mut mesh);
Ok(mesh)
}
/// Import a binary or ASCII `.stl` mesh from bytes with automatic vertex welding.
pub fn read_stl_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {
if bytes.len() > MAX_IMPORT_BYTES {
return Err(format!("STL exceeds max size ({MAX_IMPORT_BYTES} bytes)"));
}
// Check binary STL exact length match
if bytes.len() >= 84 {
let n_tris = u32::from_le_bytes([bytes[80], bytes[81], bytes[82], bytes[83]]) as usize;
if n_tris > 0 && n_tris <= MAX_IMPORT_FACES && 84 + n_tris * 50 == bytes.len() {
let mut mesh = PolyMesh::new();
let mut weld: HashMap<(i64, i64, i64), usize> = HashMap::with_capacity(n_tris);
for i in 0..n_tris {
let base = 84 + i * 50 + 12; // skip normal (12 bytes)
let mut tri = [0usize; 3];
for (k, slot) in tri.iter_mut().enumerate() {
let off = base + k * 12;
let x = f32::from_le_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]) as f64;
let y = f32::from_le_bytes([bytes[off + 4], bytes[off + 5], bytes[off + 6], bytes[off + 7]]) as f64;
let z = f32::from_le_bytes([bytes[off + 8], bytes[off + 9], bytes[off + 10], bytes[off + 11]]) as f64;
if !x.is_finite() || !y.is_finite() || !z.is_finite() {
return Err("STL contains non-finite vertex".into());
}
let p = Vec3::new(x, y, z);
*slot = *weld.entry(weld_key(p)).or_insert_with(|| mesh.add_vert(p));
}
if tri[0] != tri[1] && tri[1] != tri[2] && tri[2] != tri[0] {
mesh.add_face(SmallVec::from_slice(&tri), 0, Some("imported"));
}
}
if mesh.faces.is_empty() {
return Err("binary STL contained no valid triangles".into());
}
ensure_outward_winding_if_closed(&mut mesh);
return Ok(mesh);
}
}
// Fallback: ASCII STL
let text = std::str::from_utf8(bytes).map_err(|_| "STL is neither valid binary nor UTF-8 ASCII".to_string())?;
let mut mesh = PolyMesh::new();
let mut weld: HashMap<(i64, i64, i64), usize> = HashMap::new();
let mut cur: Vec<usize> = Vec::with_capacity(3);
for line in text.lines() {
let l = line.trim();
if let Some(rest) = l.strip_prefix("vertex") {
let mut nums = rest.split_whitespace();
let x: f64 = nums.next().ok_or("ASCII STL vertex x")?.parse().map_err(|e| format!("STL x: {e}"))?;
let y: f64 = nums.next().ok_or("ASCII STL vertex y")?.parse().map_err(|e| format!("STL y: {e}"))?;
let z: f64 = nums.next().ok_or("ASCII STL vertex z")?.parse().map_err(|e| format!("STL z: {e}"))?;
if !x.is_finite() || !y.is_finite() || !z.is_finite() {
return Err("ASCII STL contains non-finite vertex".into());
}
let p = Vec3::new(x, y, z);
let vi = *weld.entry(weld_key(p)).or_insert_with(|| mesh.add_vert(p));
cur.push(vi);
if cur.len() == 3 {
if mesh.faces.len() >= MAX_IMPORT_FACES {
return Err(format!("STL exceeds max face budget ({MAX_IMPORT_FACES})"));
}
if cur[0] != cur[1] && cur[1] != cur[2] && cur[2] != cur[0] {
mesh.add_face(SmallVec::from_slice(&cur), 0, Some("imported"));
}
cur.clear();
}
}
}
if mesh.faces.is_empty() {
return Err("STL contained no valid triangles".into());
}
ensure_outward_winding_if_closed(&mut mesh);
Ok(mesh)
}
fn mat4_identity() -> [[f64; 4]; 4] {
[
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
}
fn mat4_mul(a: &[[f64; 4]; 4], b: &[[f64; 4]; 4]) -> [[f64; 4]; 4] {
let mut out = [[0.0; 4]; 4];
for r in 0..4 {
for c in 0..4 {
out[r][c] = a[r][0] * b[0][c] + a[r][1] * b[1][c] + a[r][2] * b[2][c] + a[r][3] * b[3][c];
}
}
out
}
fn mat4_transform_pt(m: &[[f64; 4]; 4], p: Vec3) -> Vec3 {
Vec3::new(
m[0][0] * p.x + m[0][1] * p.y + m[0][2] * p.z + m[0][3],
m[1][0] * p.x + m[1][1] * p.y + m[1][2] * p.z + m[1][3],
m[2][0] * p.x + m[2][1] * p.y + m[2][2] * p.z + m[2][3],
)
}
fn mat4_det3(m: &[[f64; 4]; 4]) -> 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])
}
fn node_local_matrix(node: &Value) -> [[f64; 4]; 4] {
if let Some(arr) = node.get("matrix").and_then(|v| v.as_array()) {
if arr.len() == 16 {
// glTF column-major matrix
let mut m = mat4_identity();
for c in 0..4 {
for r in 0..4 {
m[r][c] = arr[c * 4 + r].as_f64().unwrap_or(if r == c { 1.0 } else { 0.0 });
}
}
return m;
}
}
let t = node
.get("translation")
.and_then(|v| v.as_array())
.filter(|a| a.len() == 3)
.map(|a| [a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0), a[2].as_f64().unwrap_or(0.0)])
.unwrap_or([0.0, 0.0, 0.0]);
let s = node
.get("scale")
.and_then(|v| v.as_array())
.filter(|a| a.len() == 3)
.map(|a| [a[0].as_f64().unwrap_or(1.0), a[1].as_f64().unwrap_or(1.0), a[2].as_f64().unwrap_or(1.0)])
.unwrap_or([1.0, 1.0, 1.0]);
let q = node
.get("rotation")
.and_then(|v| v.as_array())
.filter(|a| a.len() == 4)
.map(|a| [a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0), a[2].as_f64().unwrap_or(0.0), a[3].as_f64().unwrap_or(1.0)])
.unwrap_or([0.0, 0.0, 0.0, 1.0]);
let qlen = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
let (qx, qy, qz, qw) = if qlen > 1e-12 {
(q[0] / qlen, q[1] / qlen, q[2] / qlen, q[3] / qlen)
} else {
(0.0, 0.0, 0.0, 1.0)
};
let r00 = 1.0 - 2.0 * (qy * qy + qz * qz);
let r01 = 2.0 * (qx * qy - qz * qw);
let r02 = 2.0 * (qx * qz + qy * qw);
let r10 = 2.0 * (qx * qy + qz * qw);
let r11 = 1.0 - 2.0 * (qx * qx + qz * qz);
let r12 = 2.0 * (qy * qz - qx * qw);
let r20 = 2.0 * (qx * qz - qy * qw);
let r21 = 2.0 * (qy * qz + qx * qw);
let r22 = 1.0 - 2.0 * (qx * qx + qy * qy);
[
[r00 * s[0], r01 * s[1], r02 * s[2], t[0]],
[r10 * s[0], r11 * s[1], r12 * s[2], t[1]],
[r20 * s[0], r21 * s[1], r22 * s[2], t[2]],
[0.0, 0.0, 0.0, 1.0],
]
}
/// Import a glTF 2.0 binary `.glb` mesh from bytes (positions, triangle indices, node transforms, PBR materials).
/// By default (`yup_override = None`), converts glTF 2.0 Y-up coordinates into Forma's Z-up convention
/// `(x, y, z) -> (x, -z, y)`, while auto-detecting legacy `forma-core 0.2`/`0.4` Z-up exports.
pub fn read_glb_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {
read_glb_bytes_with_opts(bytes, None)
}
/// Import a glTF 2.0 binary `.glb` mesh from bytes with an optional explicit `yup` axis override.
pub fn read_glb_bytes_with_opts(bytes: &[u8], yup_override: Option<bool>) -> Result<PolyMesh, String> {
if bytes.len() < 20 {
return Err("GLB too short".into());
}
if bytes.len() > MAX_IMPORT_BYTES {
return Err(format!("GLB exceeds max size ({MAX_IMPORT_BYTES} bytes)"));
}
let magic = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
if magic != 0x4654_6C67 {
return Err("GLB invalid magic header (expected 'glTF')".into());
}
let version = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
if version != 2 {
return Err(format!("unsupported GLB version {version} (expected 2)"));
}
let mut off = 12usize;
let mut json_slice: Option<&[u8]> = None;
let mut bin_slice: Option<&[u8]> = None;
while bytes.len().saturating_sub(off) >= 8 {
let clen = u32::from_le_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]) as usize;
let ctype = u32::from_le_bytes([bytes[off + 4], bytes[off + 5], bytes[off + 6], bytes[off + 7]]);
off += 8;
let end = off.checked_add(clen).ok_or("GLB chunk length overflow")?;
if end > bytes.len() {
return Err("GLB chunk length out of bounds".into());
}
let chunk = &bytes[off..end];
if ctype == 0x4E4F_534A {
json_slice = Some(chunk);
} else if ctype == 0x004E_4942 {
bin_slice = Some(chunk);
}
off = end;
}
let json_bytes = json_slice.ok_or("GLB missing JSON chunk")?;
let bin = bin_slice.ok_or("GLB missing BIN chunk")?;
let gltf: Value = serde_json::from_slice(json_bytes).map_err(|e| format!("GLB JSON parse: {e}"))?;
// Determine whether to convert glTF Y-up -> Forma Z-up: (x, y, z) -> (x, -z, y).
// Standard glTF 2.0 is strictly Y-up; legacy forma-core 0.2/0.4 GLBs without `asset.extras.forma_yup`
// were emitted Z-up and are preserved transparently for backwards compatibility.
let convert_yup = if let Some(explicit) = yup_override {
explicit
} else if let Some(flag) = gltf
.get("asset")
.and_then(|a| a.get("extras"))
.and_then(|e| e.get("forma_yup"))
.and_then(|v| v.as_bool())
{
flag
} else {
let gen = gltf
.get("asset")
.and_then(|a| a.get("generator"))
.and_then(|v| v.as_str())
.unwrap_or("");
!(gen.starts_with("forma-core 0.2") || gen.starts_with("forma-core 0.4"))
};
let accessors = gltf.get("accessors").and_then(|v| v.as_array()).ok_or("GLB missing accessors")?;
let buffer_views = gltf.get("bufferViews").and_then(|v| v.as_array()).ok_or("GLB missing bufferViews")?;
let meshes_arr = gltf.get("meshes").and_then(|v| v.as_array()).ok_or("GLB missing meshes")?;
let mats_arr = gltf.get("materials").and_then(|v| v.as_array());
// Build node world transforms -> (mesh_idx, world_matrix) starting from active scene roots
let mut mesh_instances: Vec<(usize, [[f64; 4]; 4])> = Vec::new();
if let Some(nodes) = gltf.get("nodes").and_then(|v| v.as_array()) {
let mut stack: Vec<(usize, [[f64; 4]; 4], usize)> = Vec::new();
let active_scene_idx = gltf.get("scene").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
if let Some(root_nodes) = gltf
.get("scenes")
.and_then(|v| v.as_array())
.and_then(|arr| arr.get(active_scene_idx).or_else(|| arr.first()))
.and_then(|sc| sc.get("nodes"))
.and_then(|v| v.as_array())
{
for rn in root_nodes.iter().rev() {
if let Some(ri) = rn.as_u64().map(|x| x as usize) {
if ri < nodes.len() {
stack.push((ri, mat4_identity(), 0));
}
}
}
}
if stack.is_empty() {
let mut has_parent = vec![false; nodes.len()];
for n in nodes {
if let Some(ch) = n.get("children").and_then(|v| v.as_array()) {
for c in ch {
if let Some(ci) = c.as_u64().map(|x| x as usize) {
if ci < has_parent.len() {
has_parent[ci] = true;
}
}
}
}
}
for (i, &hp) in has_parent.iter().enumerate() {
if !hp {
stack.push((i, mat4_identity(), 0));
}
}
}
const MAX_GLB_NODE_VISITS: usize = 16_384;
const MAX_GLB_MESH_INSTANCES: usize = 4_096;
let mut visits = 0usize;
while let Some((ni, parent_m, depth)) = stack.pop() {
if depth > 64 || ni >= nodes.len() {
continue;
}
visits += 1;
if visits > MAX_GLB_NODE_VISITS {
return Err(format!(
"GLB node hierarchy exceeds max traversal budget ({MAX_GLB_NODE_VISITS}; possible cycle or DAG blowup)"
));
}
let local = node_local_matrix(&nodes[ni]);
let world = mat4_mul(&parent_m, &local);
if let Some(mi) = nodes[ni].get("mesh").and_then(|v| v.as_u64()) {
if mesh_instances.len() >= MAX_GLB_MESH_INSTANCES {
return Err(format!(
"GLB exceeds max mesh instance budget ({MAX_GLB_MESH_INSTANCES})"
));
}
mesh_instances.push((mi as usize, world));
}
if let Some(ch) = nodes[ni].get("children").and_then(|v| v.as_array()) {
for c in ch {
if let Some(ci) = c.as_u64() {
if let Ok(ci_usize) = usize::try_from(ci) {
stack.push((ci_usize, world, depth + 1));
}
}
}
}
}
}
if mesh_instances.is_empty() {
for i in 0..meshes_arr.len() {
mesh_instances.push((i, mat4_identity()));
}
}
let mut out = PolyMesh::new();
let mut weld: HashMap<(i64, i64, i64), usize> = HashMap::new();
let mut mat_map: HashMap<usize, u16> = HashMap::new();
for (mesh_idx, world_m) in mesh_instances {
let Some(mobj) = meshes_arr.get(mesh_idx) else { continue };
let Some(prims) = mobj.get("primitives").and_then(|v| v.as_array()) else { continue };
let flip_winding = mat4_det3(&world_m) < 0.0;
for prim in prims {
// Mode defaults to 4 (TRIANGLES)
let mode = prim.get("mode").and_then(|v| v.as_u64()).unwrap_or(4);
if mode != 4 {
continue;
}
let Some(pos_acc_i) = prim.get("attributes").and_then(|a| a.get("POSITION")).and_then(|v| v.as_u64()) else {
continue;
};
let pos_acc = accessors.get(pos_acc_i as usize).ok_or("GLB POSITION accessor OOB")?;
let pos_bv_i = pos_acc.get("bufferView").and_then(|v| v.as_u64()).ok_or("GLB POSITION missing bufferView")? as usize;
let pos_bv = buffer_views.get(pos_bv_i).ok_or("GLB POSITION bufferView OOB")?;
let pos_count = usize::try_from(pos_acc.get("count").and_then(|v| v.as_u64()).unwrap_or(0))
.map_err(|_| "GLB POSITION count overflow")?;
let pos_bv_off = usize::try_from(pos_bv.get("byteOffset").and_then(|v| v.as_u64()).unwrap_or(0))
.map_err(|_| "GLB POSITION bufferView offset overflow")?;
let pos_acc_off = usize::try_from(pos_acc.get("byteOffset").and_then(|v| v.as_u64()).unwrap_or(0))
.map_err(|_| "GLB POSITION accessor offset overflow")?;
let pos_off = pos_bv_off.checked_add(pos_acc_off).ok_or("GLB POSITION offset overflow")?;
let pos_stride = usize::try_from(pos_bv.get("byteStride").and_then(|v| v.as_u64()).unwrap_or(12))
.map_err(|_| "GLB POSITION stride overflow")?;
let pos_end = pos_count
.checked_sub(1)
.and_then(|last| last.checked_mul(pos_stride))
.and_then(|span| pos_off.checked_add(span))
.and_then(|end| end.checked_add(12));
if pos_stride < 12 || pos_count == 0 || pos_end.is_none_or(|end| end > bin.len()) {
return Err("GLB POSITION buffer slice out of bounds".into());
}
if pos_count > MAX_IMPORT_FACES * 3 {
return Err(format!("GLB POSITION vertex count ({pos_count}) exceeds budget"));
}
let mut local_v: Vec<usize> = Vec::with_capacity(pos_count);
for i in 0..pos_count {
let p_off = pos_off + i * pos_stride;
let x = f32::from_le_bytes([bin[p_off], bin[p_off + 1], bin[p_off + 2], bin[p_off + 3]]) as f64;
let y = f32::from_le_bytes([bin[p_off + 4], bin[p_off + 5], bin[p_off + 6], bin[p_off + 7]]) as f64;
let z = f32::from_le_bytes([bin[p_off + 8], bin[p_off + 9], bin[p_off + 10], bin[p_off + 11]]) as f64;
if !x.is_finite() || !y.is_finite() || !z.is_finite() {
return Err("GLB contains non-finite vertex".into());
}
let wp_raw = mat4_transform_pt(&world_m, Vec3::new(x, y, z));
let wp = if convert_yup {
Vec3::new(wp_raw.x, -wp_raw.z, wp_raw.y)
} else {
wp_raw
};
let vi = *weld.entry(weld_key(wp)).or_insert_with(|| out.add_vert(wp));
local_v.push(vi);
}
// Optional PBR material
let mat_slot: Option<u16> = prim
.get("material")
.and_then(|v| v.as_u64())
.map(|mi| mi as usize)
.and_then(|mi| {
if let Some(&slot) = mat_map.get(&mi) {
return Some(slot);
}
let mval = mats_arr?.get(mi)?;
let pbr = mval.get("pbrMetallicRoughness");
let col = pbr
.and_then(|p| p.get("baseColorFactor"))
.and_then(|v| v.as_array())
.filter(|a| a.len() >= 3)
.map(|a| {
crate::export::linear_rgba_to_srgb([
a[0].as_f64().unwrap_or(0.7) as f32,
a[1].as_f64().unwrap_or(0.7) as f32,
a[2].as_f64().unwrap_or(0.7) as f32,
a.get(3).and_then(|x| x.as_f64()).unwrap_or(1.0) as f32,
])
})
.unwrap_or([0.72, 0.75, 0.80, 1.0]);
let metallic = pbr.and_then(|p| p.get("metallicFactor")).and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
let roughness = pbr.and_then(|p| p.get("roughnessFactor")).and_then(|v| v.as_f64()).unwrap_or(0.5) as f32;
let emissive = mval
.get("emissiveFactor")
.and_then(|v| v.as_array())
.filter(|a| a.len() >= 3)
.map(|a| [
crate::export::linear_to_srgb(a[0].as_f64().unwrap_or(0.0) as f32),
crate::export::linear_to_srgb(a[1].as_f64().unwrap_or(0.0) as f32),
crate::export::linear_to_srgb(a[2].as_f64().unwrap_or(0.0) as f32),
])
.unwrap_or([0.0, 0.0, 0.0]);
let exts = mval.get("extensions");
let emissive_strength = exts
.and_then(|e| e.get("KHR_materials_emissive_strength"))
.and_then(|e| e.get("emissiveStrength"))
.and_then(|v| v.as_f64())
.unwrap_or(1.0) as f32;
let transmission = exts
.and_then(|e| e.get("KHR_materials_transmission"))
.and_then(|e| e.get("transmissionFactor"))
.and_then(|v| v.as_f64())
.unwrap_or(0.0) as f32;
let ior = exts
.and_then(|e| e.get("KHR_materials_ior"))
.and_then(|e| e.get("ior"))
.and_then(|v| v.as_f64())
.unwrap_or(1.5) as f32;
let double_sided = mval
.get("doubleSided")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let name = mval.get("name").and_then(|v| v.as_str()).unwrap_or("imported_mat").to_string();
let slot = out.materials.len() as u16;
out.materials.push(Material {
name,
color: col,
metallic,
roughness,
emissive,
emissive_strength,
transmission,
ior,
double_sided,
});
mat_map.insert(mi, slot);
Some(slot)
});
// Read triangle indices (or non-indexed triples)
let indices: Vec<usize> = if let Some(idx_acc_i) = prim.get("indices").and_then(|v| v.as_u64()) {
let idx_acc = accessors.get(idx_acc_i as usize).ok_or("GLB indices accessor OOB")?;
let idx_bv_i = idx_acc.get("bufferView").and_then(|v| v.as_u64()).ok_or("GLB indices missing bufferView")? as usize;
let idx_bv = buffer_views.get(idx_bv_i).ok_or("GLB indices bufferView OOB")?;
let count = usize::try_from(idx_acc.get("count").and_then(|v| v.as_u64()).unwrap_or(0))
.map_err(|_| "GLB indices count overflow")?;
let ctype = idx_acc.get("componentType").and_then(|v| v.as_u64()).unwrap_or(5123);
let idx_bv_off = usize::try_from(idx_bv.get("byteOffset").and_then(|v| v.as_u64()).unwrap_or(0))
.map_err(|_| "GLB indices bufferView offset overflow")?;
let idx_acc_off = usize::try_from(idx_acc.get("byteOffset").and_then(|v| v.as_u64()).unwrap_or(0))
.map_err(|_| "GLB indices accessor offset overflow")?;
let ioff = idx_bv_off.checked_add(idx_acc_off).ok_or("GLB indices offset overflow")?;
let elem_sz = match ctype {
5121 => 1usize,
5123 => 2usize,
5125 => 4usize,
other => return Err(format!("GLB unsupported index componentType {other}")),
};
let iend = count.checked_mul(elem_sz).and_then(|n| ioff.checked_add(n));
if iend.is_none_or(|end| end > bin.len()) {
return Err("GLB indices buffer out of bounds".into());
}
if count > MAX_IMPORT_FACES * 3 + 3 {
return Err(format!("GLB exceeds max face budget ({MAX_IMPORT_FACES})"));
}
let mut v = Vec::with_capacity(count);
for i in 0..count {
let o = ioff + i * elem_sz;
let ix = match ctype {
5121 => bin[o] as usize,
5123 => u16::from_le_bytes([bin[o], bin[o + 1]]) as usize,
5125 => u32::from_le_bytes([bin[o], bin[o + 1], bin[o + 2], bin[o + 3]]) as usize,
_ => 0,
};
if ix >= local_v.len() {
return Err("GLB index exceeds POSITION count".into());
}
v.push(local_v[ix]);
}
v
} else {
local_v
};
for tri in indices.chunks_exact(3) {
if out.faces.len() >= MAX_IMPORT_FACES {
return Err(format!("GLB exceeds max face budget ({MAX_IMPORT_FACES})"));
}
if tri[0] != tri[1] && tri[1] != tri[2] && tri[2] != tri[0] {
let ordered = if flip_winding {
[tri[0], tri[2], tri[1]]
} else {
[tri[0], tri[1], tri[2]]
};
let fi = out.add_face(SmallVec::from_slice(&ordered), 0, Some("imported"));
if let Some(slot) = mat_slot {
out.faces[fi].mat_id = slot;
}
}
}
}
}
if out.faces.is_empty() {
return Err("GLB contained no triangle meshes".into());
}
ensure_outward_winding_if_closed(&mut out);
Ok(out)
}
/// Import mesh bytes by format extension (`glb`, `obj`, `stl`) with optional `yup` override for `.glb`.
pub fn import_mesh_bytes_with_opts(bytes: &[u8], ext: &str, yup: Option<bool>) -> Result<PolyMesh, String> {
match ext.trim_start_matches('.').to_lowercase().as_str() {
"glb" => read_glb_bytes_with_opts(bytes, yup),
"obj" => read_obj_bytes(bytes),
"stl" => read_stl_bytes(bytes),
other => Err(format!("unsupported import extension '.{other}' (supported: .glb, .obj, .stl)")),
}
}
/// Import mesh bytes by format extension (`glb`, `obj`, `stl`).
pub fn import_mesh_bytes(bytes: &[u8], ext: &str) -> Result<PolyMesh, String> {
import_mesh_bytes_with_opts(bytes, ext, None)
}
/// Import mesh file from disk by extension (`.glb`, `.obj`, `.stl`) with optional `yup` override for `.glb`.
pub fn import_mesh_with_opts(path: &Path, yup: Option<bool>) -> Result<PolyMesh, String> {
let ext = path
.extension()
.and_then(|s| s.to_str())
.unwrap_or("");
let bytes = std::fs::read(path).map_err(|e| format!("read {}: {e}", path.display()))?;
import_mesh_bytes_with_opts(&bytes, ext, yup)
}
/// Import mesh file from disk by extension (`.glb`, `.obj`, `.stl`).
pub fn import_mesh(path: &Path) -> Result<PolyMesh, String> {
import_mesh_with_opts(path, None)
}