craft-mesh: add COLLADA (.dae) and Alembic (.abc) readers (#2462)

* craft-mesh: add COLLADA (.dae) and Alembic (.abc) readers

* fix(mesh): use str::to_owned instead of into_owned in dae

* craft-mesh: make dae and abc opt-in features

* fix(mesh): remove unused Error import and use Entry API in abc
This commit is contained in:
Dylan M. Taylor
2026-11-19 20:01:05 -05:00
committed by GitHub
parent 7258e42d8d
commit d0ca0cdb28
8 changed files with 1644 additions and 3 deletions
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-mesh"
description = "3D mesh file formats behind one neutral model: STL and Wavefront OBJ/MTL readers and writers, a glTF 2.0 / GLB reader and GLB writer, and PLY, FBX and 3MF readers, bounded on hostile input"
description = "3D mesh file formats behind one neutral model: STL and Wavefront OBJ/MTL readers and writers, a glTF 2.0 / GLB reader and GLB writer, and PLY, FBX, 3MF, COLLADA and Alembic readers, bounded on hostile input"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -18,6 +18,8 @@ ply = []
gltf = ["dep:serde_json"]
fbx = ["dep:miniz_oxide", "dep:craft-zip"]
threemf = ["dep:craft-opc", "dep:craft-xml"]
dae = ["dep:craft-xml"]
abc = []
[dependencies]
serde_json = { workspace = true, optional = true }
+3 -1
View File
@@ -11,8 +11,10 @@ a `Scene` into bytes. One Cargo feature per format, all on by default.
| `gltf` | glTF 2.0 (`.gltf`) and GLB | yes | GLB | `serde_json` |
| `threemf` | 3MF, core and materials extension | yes | no | `craft-opc`, `craft-xml` |
| `fbx` | FBX 6.x and 7.x, binary and ASCII | yes | no | `miniz_oxide` |
| `dae` | COLLADA (`.dae`), scenes, transforms, cameras | yes | no | `craft-xml` |
| `abc` | Alembic (`.abc`), Ogawa container | yes | no | none |
USD, Alembic and COLLADA are not here yet.
USD is not here yet.
## The neutral model
+709
View File
@@ -0,0 +1,709 @@
//! Alembic (`.abc`), read: the Ogawa container, `AbcGeom_Xform` hierarchy (matrix, translate,
//! rotate, scale ops; `.inherits`), `AbcGeom_PolyMesh` at its first sample (positions `P`,
//! polygons `.faceIndices` / `.faceCounts` turned counter-clockwise from Alembic's clockwise
//! winding, normals `N` and UVs `uv` at any geometry scope, indexed or not), and
//! `AbcGeom_FaceSet` children as materials.
//!
//! UVs are flipped to top-left origin (`1.0 - v`), matching the rest of this crate. HDF5-based
//! Alembic files are refused with [`Error::Unsupported`].
use std::collections::HashMap;
use crate::{Corner, Error, IDENTITY, Limits, Mat4, Material, Mesh, Node, Part, Result, Scene, malformed, mat_mul, too_large};
const KIND: &str = "Alembic";
const OGAWA_MAGIC: &[u8] = b"Ogawa";
const HDF5_MAGIC: &[u8] = b"\x89HDF\r\n\x1a\n";
const DATA_BIT: u64 = 1 << 63;
const KEY_BYTES: usize = 16;
const OBJECT_HASH_BYTES: usize = 32;
const MAX_INDEXED_META: usize = 255;
/// Read an Alembic (`.abc` Ogawa) file into a [`Scene`].
pub fn read(bytes: &[u8], limits: &Limits) -> Result<Scene> {
if bytes.starts_with(HDF5_MAGIC) {
return Err(Error::Unsupported("HDF5-based Alembic (re-export the file as Alembic Ogawa, the default since Alembic 1.5)".into()));
}
if !bytes.starts_with(OGAWA_MAGIC) || bytes.len() < 16 {
return Err(malformed(KIND, "not an Alembic Ogawa file"));
}
let mut o = Ogawa { b: bytes, budget: limits.max_data_bytes, max_budget: limits.max_data_bytes, indexed_meta: vec![String::new()] };
let root_ref = o.u64_at(8)?;
let root = o.group(root_ref)?;
let is_data = |i: usize| root.get(i).is_some_and(|r| r & DATA_BIT != 0);
if root.len() < 6 || !(0..6).all(|i| is_data(i) != (i == 2)) {
return Err(malformed(KIND, "the archive group does not have the Alembic layout"));
}
let block = o.data(root[5])?;
read_indexed_meta(block, &mut o.indexed_meta)?;
let mut walk = Walk { o, limits, scene: Scene::default(), materials: HashMap::new(), visits: 0, triangles: 0, parts: 0 };
walk.object(root[2], None, "", 0)?;
Ok(walk.scene)
}
struct Ogawa<'a> {
b: &'a [u8],
budget: usize,
max_budget: usize,
indexed_meta: Vec<String>,
}
#[derive(Clone, Copy, PartialEq)]
enum PropKind {
Compound,
Scalar,
Array,
}
struct Prop {
name: String,
meta: String,
kind: PropKind,
pod: u32,
extent: usize,
group: u64,
}
fn meta_get<'m>(meta: &'m str, key: &str) -> Option<&'m str> {
meta.split(';').filter_map(|kv| kv.split_once('=')).find(|(k, _)| *k == key).map(|(_, v)| v)
}
struct Cursor<'a> {
b: &'a [u8],
pos: usize,
}
impl<'a> Cursor<'a> {
fn take(&mut self, n: usize) -> Result<&'a [u8]> {
let s = self.pos.checked_add(n).and_then(|end| self.b.get(self.pos..end)).ok_or_else(|| malformed(KIND, "header block ends early"))?;
self.pos += n;
Ok(s)
}
fn u8(&mut self) -> Result<u8> {
Ok(self.take(1)?.first().copied().unwrap_or(0))
}
fn u32(&mut self) -> Result<u32> {
let s = self.take(4)?;
Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
fn hinted(&mut self, hint: u32) -> Result<usize> {
Ok(match hint {
0 => self.u8()? as usize,
1 => {
let s = self.take(2)?;
u16::from_le_bytes([s[0], s[1]]) as usize
}
2 => self.u32()? as usize,
_ => return Err(malformed(KIND, format!("bad size hint {hint}"))),
})
}
fn string(&mut self, n: usize) -> Result<String> {
Ok(String::from_utf8_lossy(self.take(n)?).into_owned())
}
}
fn f16_to_f64(bits: u16) -> f64 {
let sign = if bits & 0x8000 != 0 { -1.0_f64 } else { 1.0_f64 };
let exp = (bits >> 10) & 0x1f;
let mant = bits & 0x03ff;
match exp {
0 => sign * (f64::from(mant) * 2.0_f64.powi(-24)),
31 => {
if mant == 0 {
sign * f64::INFINITY
} else {
f64::NAN
}
}
_ => sign * ((1.0 + f64::from(mant) / 1024.0) * 2.0_f64.powi(i32::from(exp) - 15)),
}
}
impl<'a> Ogawa<'a> {
fn charge(&mut self, bytes: usize) -> Result<()> {
self.budget = self.budget.checked_sub(bytes).ok_or_else(|| too_large(KIND, format!("decodes to more than {} bytes", self.max_budget)))?;
Ok(())
}
fn u64_at(&self, pos: u64) -> Result<u64> {
let p = usize::try_from(pos).map_err(|_| malformed(KIND, "offset out of range"))?;
let s =
p.checked_add(8).and_then(|e| self.b.get(p..e)).ok_or_else(|| malformed(KIND, format!("offset {pos} is past the end of the file")))?;
let mut a = [0u8; 8];
a.copy_from_slice(s);
Ok(u64::from_le_bytes(a))
}
fn group(&mut self, r: u64) -> Result<Vec<u64>> {
if r & DATA_BIT != 0 {
return Err(malformed(KIND, "expected a group, found a data block"));
}
if r == 0 {
return Ok(Vec::new());
}
let n = self.u64_at(r)?;
let room = (self.b.len() as u64).saturating_sub(r.saturating_add(8)) / 8;
if n > room {
return Err(malformed(KIND, format!("group at {r} claims {n} children")));
}
self.charge(n as usize * 8)?;
(0..n).map(|i| self.u64_at(r + 8 + 8 * i)).collect()
}
fn data(&self, r: u64) -> Result<&'a [u8]> {
if r & DATA_BIT == 0 {
return Err(malformed(KIND, "expected a data block, found a group"));
}
let off = r & !DATA_BIT;
if off == 0 {
return Ok(&[]);
}
let size = self.u64_at(off)?;
let start = usize::try_from(off + 8).map_err(|_| malformed(KIND, "offset out of range"))?;
usize::try_from(size)
.ok()
.and_then(|s| start.checked_add(s))
.and_then(|end| self.b.get(start..end))
.ok_or_else(|| malformed(KIND, format!("data block at {off} ({size} bytes) overruns the file")))
}
fn meta_at(&self, index: u8) -> String {
self.indexed_meta.get(index as usize).cloned().unwrap_or_default()
}
fn compound(&mut self, r: u64) -> Result<Vec<Prop>> {
let children = self.group(r)?;
let Some(&last) = children.last().filter(|c| **c & DATA_BIT != 0) else { return Ok(Vec::new()) };
let block = self.data(last)?;
self.charge(block.len())?;
let mut c = Cursor { b: block, pos: 0 };
let mut out = Vec::new();
while c.pos < block.len() {
let info = c.u32()?;
let hint = (info & 0xc) >> 2;
let kind = match info & 0x3 {
0 => PropKind::Compound,
1 => PropKind::Scalar,
_ => PropKind::Array,
};
let (pod, extent) = ((info & 0xf0) >> 4, ((info & 0xff000) >> 12) as usize);
if kind != PropKind::Compound {
let _samples = c.hinted(hint)?;
if info & 0x200 != 0 {
c.hinted(hint)?;
c.hinted(hint)?;
}
if info & 0x100 != 0 {
c.hinted(hint)?;
}
}
let name_len = c.hinted(hint)?;
let name = c.string(name_len)?;
let meta_index = ((info & 0xff0_0000) >> 20) as u8;
let meta = if meta_index == 0xff {
let n = c.hinted(hint)?;
c.string(n)?
} else {
self.meta_at(meta_index)
};
let group = children.get(out.len()).copied().ok_or_else(|| malformed(KIND, format!("property \"{name}\" has no group")))?;
out.push(Prop { name, meta, kind, pod, extent, group });
}
Ok(out)
}
fn values(&mut self, property: &Prop) -> Result<Vec<f64>> {
let samples = self.group(property.group)?;
let Some(&first) = samples.first() else { return Ok(Vec::new()) };
let raw = self.data(first)?;
let raw = if raw.is_empty() {
raw
} else {
raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", property.name)))?
};
let value_bytes = match property.pod {
0..=2 => 1,
3 | 4 | 9 => 2,
5 | 6 | 10 => 4,
7 | 8 | 11 => 8,
other => return Err(Error::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))),
};
self.charge((raw.len() / value_bytes).saturating_mul(8))?;
Ok(match property.pod {
0 | 1 => raw.iter().map(|v| *v as f64).collect(),
2 => raw.iter().map(|v| *v as i8 as f64).collect(),
3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c) as f64).collect(),
4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c) as f64).collect(),
5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as f64).collect(),
6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(),
7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(),
8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(),
9 => raw.as_chunks::<2>().0.iter().map(|c| f16_to_f64(u16::from_le_bytes(*c))).collect(),
10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(),
_ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(),
})
}
fn object_headers(&mut self, children: &[u64]) -> Result<Vec<(String, String)>> {
let Some(&last) = children.last().filter(|c| **c & DATA_BIT != 0) else { return Ok(Vec::new()) };
let block = self.data(last)?;
self.charge(block.len())?;
let body = block.get(..block.len().saturating_sub(OBJECT_HASH_BYTES)).unwrap_or_default();
let mut c = Cursor { b: body, pos: 0 };
let mut out = Vec::new();
while c.pos < body.len() {
let n = c.u32()? as usize;
let name = c.string(n)?;
let index = c.u8()?;
let meta = if index == 0xff {
let n = c.u32()? as usize;
c.string(n)?
} else {
self.meta_at(index)
};
out.push((name, meta));
}
Ok(out)
}
}
fn read_indexed_meta(block: &[u8], out: &mut Vec<String>) -> Result<()> {
let mut c = Cursor { b: block, pos: 0 };
while c.pos < block.len() && out.len() < MAX_INDEXED_META {
let n = c.u8()? as usize;
out.push(c.string(n)?);
}
Ok(())
}
#[derive(Clone, Copy)]
enum Scope {
Constant,
Uniform,
Vertex,
FaceVarying,
}
struct Param {
vals: Vec<f64>,
indices: Option<Vec<f64>>,
scope: Scope,
}
impl Param {
fn get<const W: usize>(&self, k: usize, p: usize, f: usize) -> Option<[f64; W]> {
let i = match self.scope {
Scope::Constant => 0,
Scope::Uniform => f,
Scope::Vertex => p,
Scope::FaceVarying => k,
};
let i = match &self.indices {
Some(ix) => Some(*ix.get(i)?).filter(|v| *v >= 0.0)? as usize,
None => i,
};
let start = i.checked_mul(W)?;
self.vals.get(start..start.checked_add(W)?)?.try_into().ok()
}
}
fn find<'p>(props: &'p [Prop], name: &str) -> Option<&'p Prop> {
props.iter().find(|p| p.name == name)
}
fn schema_compound<'p>(props: &'p [Prop], schema: &str, name: &str) -> Option<&'p Prop> {
let compounds = || props.iter().filter(|p| p.kind == PropKind::Compound);
compounds().find(|p| meta_get(&p.meta, "schema") == Some(schema)).or_else(|| compounds().find(|p| p.name == name))
}
struct Walk<'a> {
o: Ogawa<'a>,
limits: &'a Limits,
scene: Scene,
materials: HashMap<String, usize>,
visits: usize,
triangles: usize,
parts: usize,
}
impl Walk<'_> {
fn warn(&mut self, msg: String) {
if !self.scene.warnings.contains(&msg) {
self.scene.warnings.push(msg);
}
}
fn push_node(&mut self, node: Node, parent: Option<usize>) -> Result<usize> {
if self.scene.nodes.len() >= self.limits.max_nodes {
return Err(too_large(KIND, format!("more than {} nodes", self.limits.max_nodes)));
}
let idx = self.scene.nodes.len();
self.scene.nodes.push(node);
match parent {
Some(p) => self.scene.nodes[p].children.push(idx),
None => self.scene.roots.push(idx),
}
Ok(idx)
}
fn intern_material(&mut self, name: &str) -> Result<usize> {
if let Some(&idx) = self.materials.get(name) {
return Ok(idx);
}
if self.scene.materials.len() >= self.limits.max_materials {
return Err(too_large(KIND, format!("more than {} materials", self.limits.max_materials)));
}
let idx = self.scene.materials.len();
self.scene.materials.push(Material { name: name.to_owned(), ..Material::default() });
self.materials.insert(name.to_owned(), idx);
Ok(idx)
}
fn object(&mut self, r: u64, parent_node: Option<usize>, xform_name: &str, depth: usize) -> Result<()> {
self.visits += 1;
if depth > self.limits.max_depth || self.visits > self.limits.max_nodes {
return Err(malformed(KIND, "objects are nested too deeply or shared too often"));
}
let children = self.o.group(r)?;
let headers = self.o.object_headers(&children)?;
for (i, (name, meta)) in headers.iter().enumerate() {
let group = children
.get(i + 1)
.copied()
.filter(|g| g & DATA_BIT == 0)
.ok_or_else(|| malformed(KIND, format!("object \"{name}\" has no group")))?;
let schema = meta_get(meta, "schema").unwrap_or_default();
let kids = self.o.group(group)?;
let props = match kids.first() {
Some(&p) if p & DATA_BIT == 0 => self.o.compound(p)?,
_ => Vec::new(),
};
let mut next_parent = parent_node;
if schema.starts_with("AbcGeom_Xform") {
if let Some(xf) = schema_compound(&props, schema, ".xform") {
let (local, inherits) = self.xform(xf.group)?;
let attach_to = if inherits { parent_node } else { None };
let node_idx = self.push_node(Node { name: name.clone(), transform: local, ..Node::default() }, attach_to)?;
next_parent = Some(node_idx);
}
} else if schema.starts_with("AbcGeom_PolyMesh")
&& let Some(geom) = schema_compound(&props, schema, ".geom")
{
let part_name = if xform_name.is_empty() { name.clone() } else { xform_name.to_string() };
let sets = self.face_sets(&kids)?;
let mesh = self.mesh(geom.group, &part_name, &sets)?;
if self.scene.meshes.len() >= self.limits.max_meshes {
return Err(too_large(KIND, format!("more than {} meshes", self.limits.max_meshes)));
}
let mesh_idx = self.scene.meshes.len();
self.scene.meshes.push(mesh);
let node_idx = self.push_node(Node { name: part_name, mesh: Some(mesh_idx), ..Node::default() }, parent_node)?;
next_parent = Some(node_idx);
}
if !schema.starts_with("AbcGeom_FaceSet") {
let owner = if schema.starts_with("AbcGeom_Xform") { name.as_str() } else { "" };
self.object(group, next_parent, owner, depth + 1)?;
}
}
Ok(())
}
fn xform(&mut self, r: u64) -> Result<(Mat4, bool)> {
let props = self.o.compound(r)?;
let ops = match find(&props, ".ops") {
Some(p) => self.o.values(p)?,
None => Vec::new(),
};
let vals = match find(&props, ".vals") {
Some(p) => self.o.values(p)?,
None => Vec::new(),
};
let inherits = match find(&props, ".inherits") {
Some(p) => self.o.values(p)?.first().is_none_or(|v| *v != 0.0),
None => true,
};
let mut m = IDENTITY;
let mut ch = 0usize;
for op in ops {
let kind = (op as u32) >> 4;
let n = match kind {
0 | 1 => 3,
2 => 4,
3 => 16,
4..=6 => 1,
_ => return Err(malformed(KIND, format!("unknown xform operation {kind}"))),
};
let Some(v) = vals.get(ch..ch + n) else { return Err(malformed(KIND, "xform has fewer values than its operations need")) };
ch += n;
let op_m = match kind {
0 => [v[0], 0.0, 0.0, 0.0, 0.0, v[1], 0.0, 0.0, 0.0, 0.0, v[2], 0.0, 0.0, 0.0, 0.0, 1.0],
1 => [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, v[0], v[1], v[2], 1.0],
2 => axis_angle_matrix([v[0], v[1], v[2]], v[3].to_radians()),
3 => {
let mut a = [0.0; 16];
a.copy_from_slice(v);
a
}
4 => rot_x(v[0].to_radians()),
5 => rot_y(v[0].to_radians()),
_ => rot_z(v[0].to_radians()),
};
m = mat_mul(&m, &op_m);
}
if !m.iter().all(|x| x.is_finite()) {
return Err(malformed(KIND, "xform has non-finite values"));
}
Ok((m, inherits))
}
fn face_sets(&mut self, kids: &[u64]) -> Result<Vec<(String, Vec<f64>)>> {
let headers = self.o.object_headers(kids)?;
let mut out = Vec::new();
for (i, (name, meta)) in headers.iter().enumerate() {
let schema = meta_get(meta, "schema").unwrap_or_default();
if !schema.starts_with("AbcGeom_FaceSet") {
continue;
}
let Some(&g) = kids.get(i + 1).filter(|g| **g & DATA_BIT == 0) else { continue };
let props = match self.o.group(g)?.first() {
Some(&p) if p & DATA_BIT == 0 => self.o.compound(p)?,
_ => continue,
};
let Some(fs) = schema_compound(&props, schema, ".faceset") else { continue };
let inner = self.o.compound(fs.group)?;
if let Some(faces) = find(&inner, ".faces") {
out.push((name.clone(), self.o.values(faces)?));
}
}
Ok(out)
}
fn param(&mut self, props: &[Prop], name: &str, counts: [usize; 3]) -> Result<Option<Param>> {
let Some(p) = find(props, name) else { return Ok(None) };
let (vals, indices) = match p.kind {
PropKind::Array => (self.o.values(p)?, None),
PropKind::Compound => {
let inner = self.o.compound(p.group)?;
let Some(v) = find(&inner, ".vals") else { return Ok(None) };
let vals = self.o.values(v)?;
let indices = match find(&inner, ".indices") {
Some(ix) => Some(self.o.values(ix)?),
None => None,
};
(vals, indices)
}
PropKind::Scalar => return Ok(None),
};
let width = p.extent.max(1);
let items = indices.as_ref().map_or(vals.len() / width, Vec::len);
let [points, faces, corners] = counts;
let scope = match meta_get(&p.meta, "geoScope") {
Some("con") => Scope::Constant,
Some("uni") => Scope::Uniform,
Some("vtx" | "var") => Scope::Vertex,
Some("fvr") => Scope::FaceVarying,
_ if items == corners => Scope::FaceVarying,
_ if items == points => Scope::Vertex,
_ if items == faces => Scope::Uniform,
_ => Scope::Constant,
};
Ok(Some(Param { vals, indices, scope }))
}
fn mesh(&mut self, r: u64, name: &str, sets: &[(String, Vec<f64>)]) -> Result<Mesh> {
let properties = self.o.compound(r)?;
let get = |o: &mut Ogawa, prop_name: &str| -> Result<Vec<f64>> {
match find(&properties, prop_name) {
Some(p) => o.values(p),
None => Err(malformed(KIND, format!("PolyMesh has no {prop_name}"))),
}
};
let p = get(&mut self.o, "P")?;
let indices = get(&mut self.o, ".faceIndices")?;
let counts = get(&mut self.o, ".faceCounts")?;
let num_points = p.len() / 3;
if num_points > self.limits.max_vertices {
return Err(too_large(KIND, format!("more than {} vertices", self.limits.max_vertices)));
}
let positions: Vec<[f64; 3]> = p.as_chunks::<3>().0.to_vec();
let n = [positions.len(), counts.len(), indices.len()];
let normals_param = self.param(&properties, "N", n)?;
let uvs_param = self.param(&properties, "uv", n)?;
let mut face_material = vec![None::<usize>; counts.len()];
for (s, (_, faces)) in sets.iter().enumerate() {
for f in faces {
if let Some(m) = face_material.get_mut(*f as usize).filter(|m| m.is_none() && *f >= 0.0) {
*m = Some(s);
}
}
}
let mut mesh = Mesh { name: name.to_string(), positions, ..Mesh::default() };
let mut norm_ids: HashMap<[u64; 3], u32> = HashMap::new();
let mut uv_ids: HashMap<[u32; 2], u32> = HashMap::new();
let mut uv_pool: Vec<[f32; 2]> = Vec::new();
let mut parts_by_mat: HashMap<Option<usize>, Part> = HashMap::new();
let mut part_order: Vec<Option<usize>> = Vec::new();
let (mut k, mut face_corners, mut bad_uvs) = (0usize, Vec::new(), 0usize);
for (f, &count) in counts.iter().enumerate() {
let end = (count >= 0.0).then(|| k.checked_add(count as usize)).flatten().filter(|e| *e <= indices.len());
let end = end.ok_or_else(|| malformed(KIND, format!("face {f} has {count} corners past the index list")))?;
let face_len = end - k;
if face_len > self.limits.max_face_corners {
return Err(too_large(KIND, format!("face {f} has more than {} corners", self.limits.max_face_corners)));
}
if face_len >= 3 {
self.triangles = self.triangles.saturating_add(face_len - 2);
if self.triangles > self.limits.max_triangles {
return Err(too_large(KIND, format!("more than {} triangles", self.limits.max_triangles)));
}
face_corners.clear();
for (corner_index, &point_index) in indices.iter().enumerate().take(end).skip(k) {
if point_index < 0.0 || (point_index as usize) >= mesh.positions.len() {
return Err(malformed(KIND, format!("point index {point_index} out of range")));
}
let pt = point_index as usize;
let norm_idx = match normals_param.as_ref().and_then(|l| l.get::<3>(corner_index, pt, f)) {
Some(norm) => intern_norm(&mut mesh.normals, &mut norm_ids, norm, self.limits.max_vertices)?,
None => crate::NONE,
};
let uv_idx = match &uvs_param {
Some(l) => {
let uv = match l.get::<2>(corner_index, pt, f) {
Some([u, v]) => [u as f32, 1.0 - v as f32],
None => {
bad_uvs += 1;
[0.0, 0.0]
}
};
intern_uv(&mut uv_pool, &mut uv_ids, uv, self.limits.max_vertices)?
}
None => crate::NONE,
};
face_corners.push(Corner { position: pt as u32, normal: norm_idx, uv: uv_idx });
}
// Alembic winds polygons clockwise; reverse to counter-clockwise.
face_corners.reverse();
let mat_idx = match face_material.get(f).copied().flatten().and_then(|s| sets.get(s)) {
Some((mat_name, _)) => Some(self.intern_material(mat_name)?),
None => None,
};
let part = match parts_by_mat.entry(mat_idx) {
std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
std::collections::hash_map::Entry::Vacant(e) => {
self.parts += 1;
if self.parts > self.limits.max_parts {
return Err(too_large(KIND, format!("more than {} parts", self.limits.max_parts)));
}
part_order.push(mat_idx);
e.insert(Part { material: mat_idx, ..Part::default() })
}
};
part.corners.extend_from_slice(&face_corners);
part.face_sizes.push(face_corners.len() as u32);
}
k = end;
}
for mat_idx in part_order {
if let Some(mut part) = parts_by_mat.remove(&mat_idx) {
if part.face_sizes.iter().all(|&s| s == 3) {
part.face_sizes.clear();
}
mesh.parts.push(part);
}
}
if !uv_pool.is_empty() {
mesh.uv_sets.push(uv_pool);
}
if bad_uvs > 0 {
self.warn(format!("{bad_uvs} polygon corners have no UV in the Alembic uv parameter (set to 0, 0)"));
}
Ok(mesh)
}
}
fn intern_norm(pool: &mut Vec<[f64; 3]>, map: &mut HashMap<[u64; 3], u32>, val: [f64; 3], limit: usize) -> Result<u32> {
let key = val.map(f64::to_bits);
if let Some(&id) = map.get(&key) {
return Ok(id);
}
if pool.len() >= limit {
return Err(too_large(KIND, format!("more than {limit} normals")));
}
let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many normals"))?;
pool.push(val);
map.insert(key, id);
Ok(id)
}
fn intern_uv(pool: &mut Vec<[f32; 2]>, map: &mut HashMap<[u32; 2], u32>, val: [f32; 2], limit: usize) -> Result<u32> {
let key = val.map(f32::to_bits);
if let Some(&id) = map.get(&key) {
return Ok(id);
}
if pool.len() >= limit {
return Err(too_large(KIND, format!("more than {limit} UVs")));
}
let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many UVs"))?;
pool.push(val);
map.insert(key, id);
Ok(id)
}
fn axis_angle_matrix(axis: [f64; 3], angle: f64) -> Mat4 {
let len = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
if !len.is_finite() || len == 0.0 {
return IDENTITY;
}
let [x, y, z] = axis.map(|v| v / len);
let (s, c) = angle.sin_cos();
let t = 1.0 - c;
[
t * x * x + c,
t * x * y + s * z,
t * x * z - s * y,
0.0,
t * x * y - s * z,
t * y * y + c,
t * y * z + s * x,
0.0,
t * x * z + s * y,
t * y * z - s * x,
t * z * z + c,
0.0,
0.0,
0.0,
0.0,
1.0,
]
}
fn rot_x(a: f64) -> Mat4 {
let (s, c) = a.sin_cos();
[1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0]
}
fn rot_y(a: f64) -> Mat4 {
let (s, c) = a.sin_cos();
[c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0]
}
fn rot_z(a: f64) -> Mat4 {
let (s, c) = a.sin_cos();
[c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]
}
+583
View File
@@ -0,0 +1,583 @@
//! COLLADA (`.dae`), read: `triangles`, `polylist` and `polygons` with `VERTEX` / `NORMAL` /
//! `TEXCOORD` inputs, materials bound through `instance_geometry` and `instance_controller`, the
//! visual scene's node hierarchy and transforms (`matrix`, `translate`, `rotate`, `scale`,
//! `lookat`), `instance_node`, `instance_camera`, and the asset's unit (`meter`) and `up_axis`.
//!
//! [`read_document`] returns the [`Scene`] in the file's own axes and units alongside
//! [`Document::meter`] and [`Document::up_axis`] (and [`Document::global_transform`] to convert to
//! Y-up metres). [`read`] returns the [`Scene`] directly.
//!
//! UVs are flipped to top-left origin (`1.0 - v`), matching the rest of this crate.
use std::collections::HashMap;
use std::rc::Rc;
use craft_xml::{El, Options, UnknownEntity};
use crate::{Camera, Corner, IDENTITY, Limits, Mat4, Material, Mesh, Node, Part, Projection, Result, Scene, malformed, mat_mul, too_large};
const KIND: &str = "COLLADA";
const MAX_XML_DEPTH: usize = 256;
const MAX_XML_NODES: usize = 2_000_000;
/// Up axis of a COLLADA `<asset>`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum UpAxis {
#[default]
YUp,
ZUp,
XUp,
}
impl UpAxis {
/// Rotation matrix that turns this axis into +Y up.
pub fn to_y_up(self) -> Mat4 {
match self {
UpAxis::YUp => IDENTITY,
UpAxis::ZUp => [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
UpAxis::XUp => [0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0],
}
}
}
/// A COLLADA document: the scene in the file's own axes and units, plus its `<asset>` scale and
/// up axis.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Document {
pub scene: Scene,
/// Metres per file unit (default `1.0`).
pub meter: f64,
pub up_axis: UpAxis,
}
impl Document {
/// Transform from the file's axes and units to Y-up metres.
pub fn global_transform(&self) -> Mat4 {
let scale = [self.meter, 0.0, 0.0, 0.0, 0.0, self.meter, 0.0, 0.0, 0.0, 0.0, self.meter, 0.0, 0.0, 0.0, 0.0, 1.0];
mat_mul(&self.up_axis.to_y_up(), &scale)
}
}
/// Read a COLLADA file into a [`Scene`] (in the file's own axes and units).
pub fn read(bytes: &[u8], limits: &Limits) -> Result<Scene> {
Ok(read_document(bytes, limits)?.scene)
}
/// Read a COLLADA file into a [`Document`].
pub fn read_document(bytes: &[u8], limits: &Limits) -> Result<Document> {
let mut opts = Options::local();
opts.unknown_entity = UnknownEntity::Literal;
opts.strict_end_tags = true;
opts.limits.max_input = limits.max_data_bytes;
opts.limits.max_depth = MAX_XML_DEPTH;
opts.limits.max_nodes = MAX_XML_NODES;
let root = opts.parse(bytes).map_err(|e| if e.is_limit() { too_large(KIND, e) } else { malformed(KIND, e) })?;
if root.name != "COLLADA" {
return Err(malformed(KIND, "not a COLLADA document"));
}
let mut ids: HashMap<&str, &El> = HashMap::new();
let mut stack = vec![&root];
while let Some(el) = stack.pop() {
if let Some(id) = el.attr("id") {
ids.entry(id).or_insert(el);
}
stack.extend(el.elements());
}
let asset = root.child("asset");
let meter = asset
.and_then(|a| a.child("unit"))
.and_then(|u| u.attr("meter"))
.and_then(|m| m.trim().parse::<f64>().ok())
.filter(|m| m.is_finite() && *m > 0.0)
.unwrap_or(1.0);
let up_axis = match asset.and_then(|a| a.child("up_axis")).map(|u| u.text().trim().to_owned()).as_deref() {
Some("Z_UP") => UpAxis::ZUp,
Some("X_UP") => UpAxis::XUp,
_ => UpAxis::YUp,
};
let mut reader =
Reader { ids, sources: HashMap::new(), limits, scene: Scene::default(), materials: HashMap::new(), mesh_cache: HashMap::new(), triangles: 0 };
let visual_scene = root
.child("scene")
.and_then(|s| s.child("instance_visual_scene"))
.and_then(|i| reader.get(i.attr("url")))
.or_else(|| root.child("library_visual_scenes").and_then(|l| l.child("visual_scene")));
if let Some(vs) = visual_scene {
for n in vs.children("node") {
let idx = reader.read_node(n, 0)?;
reader.scene.roots.push(idx);
}
} else {
for geom in root.children("library_geometries").flat_map(|l| l.children("geometry")) {
let mesh_idx = reader.get_or_build_mesh(geom, &[])?;
let name = reader.scene.meshes[mesh_idx].name.clone();
let node_idx = reader.push_node(Node { name, mesh: Some(mesh_idx), ..Node::default() })?;
reader.scene.roots.push(node_idx);
}
}
Ok(Document { scene: reader.scene, meter, up_axis })
}
struct Source {
data: Vec<f64>,
stride: usize,
offset: usize,
}
impl Source {
fn get<const W: usize>(&self, i: u32) -> Option<[f64; W]> {
let start = (i as usize).checked_mul(self.stride)?.checked_add(self.offset)?;
self.data.get(start..start.checked_add(W)?)?.try_into().ok()
}
}
struct Input {
offset: usize,
source: Rc<Source>,
}
struct Reader<'a> {
ids: HashMap<&'a str, &'a El>,
sources: HashMap<&'a str, Rc<Source>>,
limits: &'a Limits,
scene: Scene,
materials: HashMap<String, usize>,
/// Keyed by `(geometry element pointer, sorted (symbol, material_name) bindings)`.
mesh_cache: HashMap<(usize, Vec<(String, String)>), usize>,
triangles: usize,
}
impl<'a> Reader<'a> {
fn get(&self, url: Option<&str>) -> Option<&'a El> {
url.and_then(|u| u.strip_prefix('#')).and_then(|id| self.ids.get(id)).copied()
}
fn warn(&mut self, msg: String) {
if !self.scene.warnings.contains(&msg) {
self.scene.warnings.push(msg);
}
}
fn push_node(&mut self, node: Node) -> Result<usize> {
if self.scene.nodes.len() >= self.limits.max_nodes {
return Err(too_large(KIND, format!("more than {} nodes", self.limits.max_nodes)));
}
let idx = self.scene.nodes.len();
self.scene.nodes.push(node);
Ok(idx)
}
fn intern_material(&mut self, name: &str) -> Result<usize> {
if let Some(&idx) = self.materials.get(name) {
return Ok(idx);
}
if self.scene.materials.len() >= self.limits.max_materials {
return Err(too_large(KIND, format!("more than {} materials", self.limits.max_materials)));
}
let idx = self.scene.materials.len();
self.scene.materials.push(Material { name: name.to_owned(), ..Material::default() });
self.materials.insert(name.to_owned(), idx);
Ok(idx)
}
fn source(&mut self, url: Option<&str>) -> Result<Rc<Source>> {
let el = self.get(url).ok_or_else(|| malformed(KIND, format!("missing source {}", url.unwrap_or("(none)"))))?;
let id = el.attr("id").unwrap_or_default();
if !id.is_empty()
&& let Some(s) = self.sources.get(id)
{
return Ok(s.clone());
}
let acc = el.child("technique_common").and_then(|t| t.child("accessor"));
let array = acc.and_then(|a| self.get(a.attr("source"))).or_else(|| el.child("float_array"));
let array = array.ok_or_else(|| malformed(KIND, format!("source \"{id}\" has no float_array")))?;
let num = |k: &str, default: usize| acc.and_then(|a| a.attr(k)).and_then(|v| v.parse().ok()).unwrap_or(default);
let data = parse_floats(array)?;
if data.len() / 3 > self.limits.max_vertices {
return Err(too_large(KIND, format!("source has more than {} vertices", self.limits.max_vertices)));
}
let s = Rc::new(Source { data, stride: num("stride", 1).max(1), offset: num("offset", 0) });
if !id.is_empty() {
self.sources.insert(id, s.clone());
}
Ok(s)
}
fn read_node(&mut self, el: &'a El, depth: usize) -> Result<usize> {
if depth > self.limits.max_depth {
return Err(too_large(KIND, format!("node hierarchy is deeper than {}", self.limits.max_depth)));
}
let name = el.attr("name").or_else(|| el.attr("id")).unwrap_or_default().to_string();
let transform = node_transform(el)?;
let mut node = Node { name: name.clone(), transform, ..Node::default() };
for inst in el.elements() {
if inst.name == "instance_camera" {
if node.camera.is_none()
&& let Some(cam_el) = self.get(inst.attr("url"))
&& let Some(cam) = parse_camera(cam_el, &name)
&& self.scene.cameras.len() < self.limits.max_extras
{
let cam_idx = self.scene.cameras.len();
self.scene.cameras.push(cam);
node.camera = Some(cam_idx);
}
continue;
}
let (geom, bind_shape) = match inst.name.as_str() {
"instance_geometry" => (self.get(inst.attr("url")), IDENTITY),
"instance_controller" => {
let skin = self.get(inst.attr("url")).and_then(|c| c.child("skin"));
let bind = skin.and_then(|s| s.child("bind_shape_matrix")).map(parse_floats).transpose()?.and_then(|v| row_major_matrix(&v));
(skin.and_then(|s| self.get(s.attr("source"))), bind.unwrap_or(IDENTITY))
}
_ => continue,
};
let Some(geom) = geom else {
self.warn("an instanced geometry is missing from the file".into());
continue;
};
let bind = self.bindings(inst);
let mesh_idx = self.get_or_build_mesh(geom, &bind)?;
if node.mesh.is_none() && bind_shape == IDENTITY {
node.mesh = Some(mesh_idx);
} else {
let child = self.push_node(Node { name: name.clone(), transform: bind_shape, mesh: Some(mesh_idx), ..Node::default() })?;
node.children.push(child);
}
}
for child_el in el.children("node") {
let child = self.read_node(child_el, depth + 1)?;
node.children.push(child);
}
for inst_node in el.children("instance_node") {
if let Some(target) = self.get(inst_node.attr("url")) {
let child = self.read_node(target, depth + 1)?;
node.children.push(child);
}
}
self.push_node(node)
}
fn bindings(&self, inst: &El) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = inst
.child("bind_material")
.and_then(|b| b.child("technique_common"))
.into_iter()
.flat_map(|t| t.children("instance_material"))
.filter_map(|im| {
let symbol = im.attr("symbol")?;
let mat = self.get(im.attr("target"));
let name = mat.and_then(|m| m.attr("name").or_else(|| m.attr("id"))).unwrap_or(symbol);
Some((symbol.to_string(), name.to_string()))
})
.collect();
out.sort();
out
}
fn get_or_build_mesh(&mut self, geom: &'a El, bind: &[(String, String)]) -> Result<usize> {
let key = ((geom as *const El) as usize, bind.to_vec());
if let Some(&idx) = self.mesh_cache.get(&key) {
return Ok(idx);
}
if self.scene.meshes.len() >= self.limits.max_meshes {
return Err(too_large(KIND, format!("more than {} meshes", self.limits.max_meshes)));
}
let mesh = self.build_mesh(geom, bind)?;
let idx = self.scene.meshes.len();
self.scene.meshes.push(mesh);
self.mesh_cache.insert(key, idx);
Ok(idx)
}
fn build_mesh(&mut self, geom: &'a El, bind: &[(String, String)]) -> Result<Mesh> {
let name = geom.attr("name").or_else(|| geom.attr("id")).unwrap_or_default().to_string();
let mut mesh = Mesh { name, ..Mesh::default() };
let Some(mesh_el) = geom.child("mesh") else { return Ok(mesh) };
let mut pools = MeshPools::default();
let mut part_count: usize = self.scene.meshes.iter().map(|m| m.parts.len()).sum();
for prim in mesh_el.elements() {
if !matches!(prim.name.as_str(), "triangles" | "polylist" | "polygons") {
if matches!(prim.name.as_str(), "lines" | "linestrips" | "trifans" | "tristrips") {
self.warn(format!("skipped COLLADA <{}> (only triangles and polygons are supported)", prim.name));
}
continue;
}
let Some(inputs) = self.read_primitive_inputs(prim)? else {
self.warn("skipped COLLADA primitives without positions".into());
continue;
};
part_count += 1;
if part_count > self.limits.max_parts {
return Err(too_large(KIND, format!("more than {} parts", self.limits.max_parts)));
}
let material = match prim.attr("material") {
Some(sym) => {
let mat_name = bind.binary_search_by(|(k, _)| k.as_str().cmp(sym)).ok().map_or(sym, |i| bind[i].1.as_str());
Some(self.intern_material(mat_name)?)
}
None => None,
};
let lists = read_primitive_lists(prim, inputs.stride)?;
let part = self.build_part(material, &inputs, &lists, &mut mesh, &mut pools)?;
if !part.corners.is_empty() {
mesh.parts.push(part);
}
}
if !pools.uvs.is_empty() {
mesh.uv_sets.push(pools.uvs);
}
Ok(mesh)
}
fn read_primitive_inputs(&mut self, prim: &'a El) -> Result<Option<PrimInputs>> {
let (mut position, mut normal, mut uv): (Option<Input>, Option<Input>, Option<(u32, Input)>) = (None, None, None);
let mut stride = 1usize;
for input in prim.children("input") {
let offset: usize = input.attr("offset").and_then(|o| o.parse().ok()).unwrap_or(0);
stride = stride.max(offset.saturating_add(1));
let nested: Vec<&El> = match input.attr("semantic") {
Some("VERTEX") => self.get(input.attr("source")).map(|v| v.children("input").collect()).unwrap_or_default(),
_ => vec![input],
};
for i in nested {
let set: u32 = input.attr("set").or_else(|| i.attr("set")).and_then(|s| s.parse().ok()).unwrap_or(0);
match i.attr("semantic") {
Some("POSITION") => position = Some(Input { offset, source: self.source(i.attr("source"))? }),
Some("NORMAL") if normal.is_none() => normal = Some(Input { offset, source: self.source(i.attr("source"))? }),
Some("TEXCOORD") if uv.as_ref().is_none_or(|(s, _)| set < *s) => {
uv = Some((set, Input { offset, source: self.source(i.attr("source"))? }))
}
_ => {}
}
}
}
Ok(position.map(|position| PrimInputs { stride, position, normal, uv: uv.map(|(_, i)| i) }))
}
fn build_part(
&mut self,
material: Option<usize>,
inputs: &PrimInputs,
lists: &[(Vec<u32>, Vec<usize>)],
mesh: &mut Mesh,
pools: &mut MeshPools,
) -> Result<Part> {
let mut part = Part { material, ..Part::default() };
let mut all_triangles = true;
for (p, sizes) in lists {
let mut next = 0usize;
for &size in sizes {
if size > self.limits.max_face_corners {
return Err(too_large(KIND, format!("face has more than {} corners", self.limits.max_face_corners)));
}
if size >= 3 {
self.triangles = self.triangles.saturating_add(size - 2);
if self.triangles > self.limits.max_triangles {
return Err(too_large(KIND, format!("more than {} triangles", self.limits.max_triangles)));
}
if size != 3 {
all_triangles = false;
}
for c in next..next.saturating_add(size) {
let idx =
|input: &Input| c.checked_mul(inputs.stride).and_then(|b| b.checked_add(input.offset)).and_then(|k| p.get(k)).copied();
let pos = idx(&inputs.position)
.and_then(|i| inputs.position.source.get::<3>(i))
.ok_or_else(|| malformed(KIND, "polygon index out of range"))?;
let pos_idx = intern_f64_3(&mut mesh.positions, &mut pools.pos_ids, pos, self.limits.max_vertices, "positions")?;
let norm_idx = match inputs.normal.as_ref().and_then(|n| idx(n).and_then(|i| n.source.get::<3>(i))) {
Some(n) => intern_f64_3(&mut mesh.normals, &mut pools.norm_ids, n, self.limits.max_vertices, "normals")?,
None => crate::NONE,
};
let uv_idx = match inputs.uv.as_ref().and_then(|t| idx(t).and_then(|i| t.source.get::<2>(i))) {
Some([u, v]) => intern_uv(&mut pools.uvs, &mut pools.uv_ids, [u as f32, 1.0 - v as f32], self.limits.max_vertices)?,
None => crate::NONE,
};
part.corners.push(Corner { position: pos_idx, normal: norm_idx, uv: uv_idx });
}
part.face_sizes.push(size as u32);
}
next = next.saturating_add(size);
}
}
if all_triangles {
part.face_sizes.clear();
}
Ok(part)
}
}
#[derive(Default)]
struct MeshPools {
pos_ids: HashMap<[u64; 3], u32>,
norm_ids: HashMap<[u64; 3], u32>,
uv_ids: HashMap<[u32; 2], u32>,
uvs: Vec<[f32; 2]>,
}
struct PrimInputs {
stride: usize,
position: Input,
normal: Option<Input>,
uv: Option<Input>,
}
fn read_primitive_lists(prim: &El, stride: usize) -> Result<Vec<(Vec<u32>, Vec<usize>)>> {
match prim.name.as_str() {
"polygons" => prim
.children("p")
.map(|p| {
let p = parse_indices(p)?;
let n = p.len() / stride;
Ok((p, vec![n]))
})
.collect(),
_ => {
let p = prim.child("p").map(parse_indices).transpose()?.unwrap_or_default();
let sizes = match prim.child("vcount") {
Some(v) if prim.name == "polylist" => parse_indices(v)?.into_iter().map(|c| c as usize).collect(),
_ => vec![3; p.len() / stride / 3],
};
Ok(vec![(p, sizes)])
}
}
}
fn intern_f64_3(pool: &mut Vec<[f64; 3]>, map: &mut HashMap<[u64; 3], u32>, val: [f64; 3], limit: usize, what: &str) -> Result<u32> {
let key = val.map(f64::to_bits);
if let Some(&id) = map.get(&key) {
return Ok(id);
}
if pool.len() >= limit {
return Err(too_large(KIND, format!("more than {limit} {what}")));
}
let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, format!("too many {what}")))?;
pool.push(val);
map.insert(key, id);
Ok(id)
}
fn intern_uv(pool: &mut Vec<[f32; 2]>, map: &mut HashMap<[u32; 2], u32>, val: [f32; 2], limit: usize) -> Result<u32> {
let key = val.map(f32::to_bits);
if let Some(&id) = map.get(&key) {
return Ok(id);
}
if pool.len() >= limit {
return Err(too_large(KIND, format!("more than {limit} UVs")));
}
let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many UVs"))?;
pool.push(val);
map.insert(key, id);
Ok(id)
}
fn parse_floats(el: &El) -> Result<Vec<f64>> {
el.text().split_whitespace().map(|w| w.parse::<f64>().map_err(|_| malformed(KIND, format!("bad number \"{w}\" in <{}>", el.name)))).collect()
}
fn parse_indices(el: &El) -> Result<Vec<u32>> {
el.text().split_whitespace().map(|w| w.parse::<u32>().map_err(|_| malformed(KIND, format!("bad index \"{w}\" in <{}>", el.name)))).collect()
}
fn parse_camera(cam: &El, node_name: &str) -> Option<Camera> {
let tc = cam.child("optics")?.child("technique_common")?;
let num = |e: &El, k: &str| e.child(k).and_then(|v| v.text().trim().parse::<f64>().ok()).filter(|v| v.is_finite() && *v > 0.0);
let name = if node_name.is_empty() { cam.attr("name").or_else(|| cam.attr("id")).unwrap_or_default().to_string() } else { node_name.to_string() };
if let Some(p) = tc.child("perspective") {
let x_to_y = |x: f64| Some(2.0 * ((x * 0.5).to_radians().tan() / num(p, "aspect_ratio")?).atan().to_degrees());
let fov_deg = num(p, "yfov").or_else(|| num(p, "xfov").and_then(x_to_y)).or_else(|| num(p, "xfov")).unwrap_or(40.0);
let aspect = num(p, "aspect_ratio");
let znear = num(p, "znear").unwrap_or(0.1);
let zfar = num(p, "zfar");
return Some(Camera { name, projection: Projection::Perspective { yfov: fov_deg.to_radians(), aspect, znear, zfar } });
}
let o = tc.child("orthographic")?;
let aspect = num(o, "aspect_ratio");
let ymag = num(o, "ymag").or_else(|| Some(num(o, "xmag")? / aspect?)).or_else(|| num(o, "xmag")).unwrap_or(1.0);
let xmag = num(o, "xmag").unwrap_or_else(|| ymag * aspect.unwrap_or(1.0));
let znear = num(o, "znear").unwrap_or(0.1);
let zfar = num(o, "zfar").unwrap_or(1000.0);
Some(Camera { name, projection: Projection::Orthographic { xmag, ymag, znear, zfar } })
}
/// Row-major 4×4 floats to a column-major matrix.
fn row_major_matrix(v: &[f64]) -> Option<Mat4> {
let a: [f64; 16] = v.get(..16)?.try_into().ok()?;
Some([a[0], a[4], a[8], a[12], a[1], a[5], a[9], a[13], a[2], a[6], a[10], a[14], a[3], a[7], a[11], a[15]])
}
fn node_transform(node: &El) -> Result<Mat4> {
let mut m = IDENTITY;
for t in node.elements() {
let v = match t.name.as_str() {
"matrix" | "translate" | "rotate" | "scale" | "lookat" => parse_floats(t)?,
_ => continue,
};
let step = match (t.name.as_str(), v.as_slice()) {
("matrix", _) => row_major_matrix(&v),
("translate", [x, y, z, ..]) => Some([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, *x, *y, *z, 1.0]),
("scale", [x, y, z, ..]) => Some([*x, 0.0, 0.0, 0.0, 0.0, *y, 0.0, 0.0, 0.0, 0.0, *z, 0.0, 0.0, 0.0, 0.0, 1.0]),
("rotate", [x, y, z, deg, ..]) => axis_angle_matrix([*x, *y, *z], deg.to_radians()),
("lookat", [ex, ey, ez, ix, iy, iz, ux, uy, uz, ..]) => lookat_matrix([*ex, *ey, *ez], [*ix, *iy, *iz], [*ux, *uy, *uz]),
_ => None,
};
if let Some(s) = step {
m = mat_mul(&m, &s);
}
}
Ok(m)
}
fn normalize(v: [f64; 3]) -> Option<[f64; 3]> {
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
(len.is_finite() && len > 0.0).then(|| v.map(|x| x / len))
}
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn axis_angle_matrix(axis: [f64; 3], angle: f64) -> Option<Mat4> {
let [x, y, z] = normalize(axis)?;
let (s, c) = angle.sin_cos();
let t = 1.0 - c;
let m = [
t * x * x + c,
t * x * y + s * z,
t * x * z - s * y,
0.0,
t * x * y - s * z,
t * y * y + c,
t * y * z + s * x,
0.0,
t * x * z + s * y,
t * y * z - s * x,
t * z * z + c,
0.0,
0.0,
0.0,
0.0,
1.0,
];
m.iter().all(|v| v.is_finite()).then_some(m)
}
fn lookat_matrix(eye: [f64; 3], center: [f64; 3], up: [f64; 3]) -> Option<Mat4> {
let f = normalize([center[0] - eye[0], center[1] - eye[1], center[2] - eye[2]])?;
let s = normalize(cross(f, up))?;
let u = cross(s, f);
let m = [s[0], s[1], s[2], 0.0, u[0], u[1], u[2], 0.0, -f[0], -f[1], -f[2], 0.0, eye[0], eye[1], eye[2], 1.0];
m.iter().all(|v| v.is_finite()).then_some(m)
}
+14 -1
View File
@@ -31,10 +31,23 @@
#![forbid(unsafe_code)]
// The helpers the formats share are not all used by every subset of them.
#![cfg_attr(
not(all(feature = "stl", feature = "obj", feature = "ply", feature = "gltf", feature = "fbx", feature = "threemf")),
not(all(
feature = "stl",
feature = "obj",
feature = "ply",
feature = "gltf",
feature = "fbx",
feature = "threemf",
feature = "dae",
feature = "abc"
)),
allow(dead_code, unused_imports)
)]
#[cfg(feature = "abc")]
pub mod abc;
#[cfg(feature = "dae")]
pub mod dae;
#[cfg(feature = "fbx")]
pub mod fbx;
#[cfg(feature = "gltf")]
+4
View File
@@ -2,6 +2,10 @@
use super::*;
#[cfg(feature = "abc")]
mod abc;
#[cfg(feature = "dae")]
mod dae;
#[cfg(feature = "fbx")]
mod fbx;
#[cfg(feature = "gltf")]
+198
View File
@@ -0,0 +1,198 @@
use super::*;
use crate::abc::read;
const DATA_BIT: u64 = 1 << 63;
const OGAWA_MAGIC: &[u8] = b"Ogawa";
const KEY_BYTES: usize = 16;
const OBJECT_HASH_BYTES: usize = 32;
const F32: u32 = 10;
const I32: u32 = 6;
const U32: u32 = 5;
const U8: u32 = 1;
const F64: u32 = 11;
struct Writer {
b: Vec<u8>,
}
impl Writer {
fn new() -> Writer {
Writer { b: vec![0; 16] }
}
fn data(&mut self, bytes: &[u8]) -> u64 {
let at = self.b.len() as u64;
self.b.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
self.b.extend_from_slice(bytes);
at | DATA_BIT
}
fn group(&mut self, children: &[u64]) -> u64 {
let at = self.b.len() as u64;
self.b.extend_from_slice(&(children.len() as u64).to_le_bytes());
for c in children {
self.b.extend_from_slice(&c.to_le_bytes());
}
at
}
fn finish(mut self, root: u64) -> Vec<u8> {
self.b[..5].copy_from_slice(OGAWA_MAGIC);
self.b[5] = 0xff;
self.b[6..8].copy_from_slice(&[0, 1]);
self.b[8..16].copy_from_slice(&root.to_le_bytes());
self.b
}
}
struct P {
name: &'static str,
meta: String,
info: u32,
group: u64,
}
struct Abc {
w: Writer,
}
impl Abc {
fn sample(&mut self, raw: &[u8]) -> u64 {
let mut v = vec![7u8; KEY_BYTES];
v.extend_from_slice(raw);
self.w.data(&v)
}
fn array(&mut self, name: &'static str, meta: &str, pod: u32, extent: u32, raw: &[u8]) -> P {
let (d, dims) = (self.sample(raw), self.w.data(&[]));
let group = self.w.group(&[d, dims]);
P { name, meta: meta.into(), info: 2 | (2 << 2) | (pod << 4) | (extent << 12), group }
}
fn scalar(&mut self, name: &'static str, pod: u32, extent: u32, raw: &[u8]) -> P {
let d = self.sample(raw);
let group = self.w.group(&[d]);
P { name, meta: String::new(), info: 1 | (2 << 2) | (pod << 4) | (extent << 12), group }
}
fn compound(&mut self, name: &'static str, meta: &str, props: Vec<P>) -> P {
let mut header = Vec::new();
for p in &props {
let info = p.info | (0xff << 20);
header.extend_from_slice(&info.to_le_bytes());
if info & 3 != 0 {
header.extend_from_slice(&1u32.to_le_bytes());
}
header.extend_from_slice(&(p.name.len() as u32).to_le_bytes());
header.extend_from_slice(p.name.as_bytes());
header.extend_from_slice(&(p.meta.len() as u32).to_le_bytes());
header.extend_from_slice(p.meta.as_bytes());
}
let mut children: Vec<u64> = props.iter().map(|p| p.group).collect();
children.push(self.w.data(&header));
let group = self.w.group(&children);
P { name, meta: meta.into(), info: 2 << 2, group }
}
fn object(&mut self, props: Vec<P>, children: &[(&str, &str, u64)]) -> u64 {
let props = self.compound("", "", props).group;
let mut header = Vec::new();
for (name, meta, _) in children {
header.extend_from_slice(&(name.len() as u32).to_le_bytes());
header.extend_from_slice(name.as_bytes());
if meta.is_empty() {
header.push(1);
} else {
header.push(0xff);
header.extend_from_slice(&(meta.len() as u32).to_le_bytes());
header.extend_from_slice(meta.as_bytes());
}
}
header.extend_from_slice(&[0; OBJECT_HASH_BYTES]);
let mut kids = vec![props];
kids.extend(children.iter().map(|c| c.2));
kids.push(self.w.data(&header));
self.w.group(&kids)
}
fn archive(mut self, top: u64, indexed_meta: &[&str]) -> Vec<u8> {
let mut im = Vec::new();
for m in indexed_meta {
im.push(m.len() as u8);
im.extend_from_slice(m.as_bytes());
}
let kids = [
self.w.data(&0i32.to_le_bytes()),
self.w.data(&10709i32.to_le_bytes()),
top,
self.w.data(b"_ai_Application=test"),
self.w.data(&[]),
self.w.data(&im),
];
let root = self.w.group(&kids);
self.w.finish(root)
}
}
fn f32s(v: &[f32]) -> Vec<u8> {
v.iter().flat_map(|x| x.to_le_bytes()).collect()
}
fn i32s(v: &[i32]) -> Vec<u8> {
v.iter().flat_map(|x| x.to_le_bytes()).collect()
}
fn sample_file() -> Vec<u8> {
let mut a = Abc { w: Writer::new() };
let p = f32s(&[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 2.0, 1.0, 0.0]);
let indices = i32s(&[0, 3, 4, 1, 1, 4, 5, 2]);
let counts = i32s(&[4, 4]);
let pp = a.array("P", "interpretation=point", F32, 3, &p);
let fi = a.array(".faceIndices", "", I32, 1, &indices);
let fc = a.array(".faceCounts", "", I32, 1, &counts);
let vals = a.array(".vals", "", F32, 2, &f32s(&[0.0, 0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.5, 1.0, 1.0, 1.0]));
let uvi = a.array(".indices", "", U32, 1, &i32s(&[0, 3, 4, 1, 1, 4, 5, 2]));
let uv = a.compound("uv", "geoScope=fvr;podName=float32_t;podExtent=2", vec![vals, uvi]);
let n = a.array("N", "geoScope=vtx", F32, 3, &f32s(&[0.0, 0.0, 1.0].repeat(6)));
let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc, uv, n]);
let left_faces = a.array(".faces", "", I32, 1, &i32s(&[0]));
let left_fs = a.compound(".faceset", "schema=AbcGeom_FaceSet_v1", vec![left_faces]);
let left = a.object(vec![left_fs], &[]);
let right_faces = a.array(".faces", "", I32, 1, &i32s(&[1]));
let right_fs = a.compound(".faceset", "schema=AbcGeom_FaceSet_v1", vec![right_faces]);
let right = a.object(vec![right_fs], &[]);
let fs_meta = "schema=AbcGeom_FaceSet_v1;schemaObjTitle=AbcGeom_FaceSet_v1:.faceset";
let mesh = a.object(vec![geom], &[("left", fs_meta, left), ("right", fs_meta, right)]);
let ops = a.scalar(".ops", U8, 2, &[0x10, 0x00]);
let xv: Vec<u8> = [1.0f64, 2.0, 3.0, 2.0, 2.0, 2.0].iter().flat_map(|x| x.to_le_bytes()).collect();
let vals = a.scalar(".vals", F64, 6, &xv);
let xform = a.compound(".xform", "schema=AbcGeom_Xform_v3", vec![ops, vals]);
let xf = a.object(vec![xform], &[("stripShape", "schema=AbcGeom_PolyMesh_v1;schemaObjTitle=AbcGeom_PolyMesh_v1:.geom", mesh)]);
let top = a.object(vec![], &[("strip", "schema=AbcGeom_Xform_v3", xf)]);
a.archive(top, &["schema=AbcGeom_PolyMesh_v1"])
}
#[test]
fn reads_polymesh_xform_face_sets_and_uvs() {
let scene = read(&sample_file(), &Limits::default()).unwrap();
scene.validate().unwrap();
assert_eq!(scene.materials.iter().map(|m| m.name.as_str()).collect::<Vec<_>>(), ["left", "right"]);
assert_eq!(scene.meshes.len(), 1);
assert_eq!(scene.meshes[0].name, "strip");
assert_eq!(scene.meshes[0].triangle_count(), 4);
let inst = scene.instances(&Limits::default()).unwrap();
assert_eq!(inst.len(), 1);
let p0 = transform_point(&inst[0].1, scene.meshes[0].positions[0]);
assert_eq!(p0, [1.0, 2.0, 3.0]);
}
#[test]
fn hdf5_returns_unsupported() {
let err = read(b"\x89HDF\r\n\x1a\n rest", &Limits::default()).unwrap_err();
assert!(matches!(err, Error::Unsupported(_)));
}
#[test]
fn hammer_never_panics() {
hammer(&sample_file(), &|b| read(b, &Limits::default()));
}
+130
View File
@@ -0,0 +1,130 @@
use super::*;
use crate::dae::{UpAxis, read, read_document};
const DAE: &str = r##"<?xml version="1.0" encoding="utf-8"?>
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
<asset><unit name="centimeter" meter="0.5"/><up_axis>Z_UP</up_axis></asset>
<library_materials>
<material id="red-mat" name="Red"/>
<material id="blue-mat" name="Blue"/>
</library_materials>
<library_geometries>
<geometry id="quad" name="Quad">
<mesh>
<source id="quad-pos">
<float_array id="quad-pos-array" count="12">0 0 0 2 0 0 2 2 0 0 2 0</float_array>
<technique_common><accessor source="#quad-pos-array" count="4" stride="3"/></technique_common>
</source>
<source id="quad-nrm">
<float_array id="quad-nrm-array" count="3">0 0 1</float_array>
<technique_common><accessor source="#quad-nrm-array" count="1" stride="3"/></technique_common>
</source>
<source id="quad-uv">
<float_array id="quad-uv-array" count="8">0 0 1 0 1 1 0 1</float_array>
<technique_common><accessor source="#quad-uv-array" count="4" stride="2"/></technique_common>
</source>
<vertices id="quad-verts"><input semantic="POSITION" source="#quad-pos"/></vertices>
<polylist material="mat0" count="1">
<input semantic="VERTEX" source="#quad-verts" offset="0"/>
<input semantic="NORMAL" source="#quad-nrm" offset="1"/>
<input semantic="TEXCOORD" source="#quad-uv" offset="2" set="0"/>
<vcount>4</vcount>
<p>0 0 0 1 0 1 2 0 2 3 0 3</p>
</polylist>
</mesh>
</geometry>
<geometry id="tris" name="Tris">
<mesh>
<source id="tris-pos">
<float_array id="tris-pos-array" count="21">4 0 0 6 0 0 4 2 0 8 0 0 10 0 0 10 2 0 8 2 0</float_array>
<technique_common><accessor source="#tris-pos-array" count="7" stride="3"/></technique_common>
</source>
<source id="tris-uv">
<float_array id="tris-uv-array" count="14">0 0 1 0 0 1 0 0 1 0 1 1 0 1</float_array>
<technique_common><accessor source="#tris-uv-array" count="7" stride="2"/></technique_common>
</source>
<vertices id="tris-verts">
<input semantic="POSITION" source="#tris-pos"/>
<input semantic="TEXCOORD" source="#tris-uv"/>
</vertices>
<triangles material="mat1" count="1"><input semantic="VERTEX" source="#tris-verts" offset="0"/><p>0 1 2</p></triangles>
<polygons material="mat1" count="1"><input semantic="VERTEX" source="#tris-verts" offset="0"/><p>3 4 5 6</p></polygons>
<lines count="1"><input semantic="VERTEX" source="#tris-verts" offset="0"/><p>0 1</p></lines>
</mesh>
</geometry>
</library_geometries>
<library_cameras>
<camera id="lens"><optics><technique_common><perspective><yfov>30</yfov></perspective></technique_common></optics></camera>
</library_cameras>
<library_visual_scenes>
<visual_scene id="scene">
<node id="parent">
<translate>0 0 2</translate>
<rotate>0 0 1 90</rotate>
<node id="child">
<scale>2 2 2</scale>
<instance_geometry url="#quad">
<bind_material><technique_common><instance_material symbol="mat0" target="#red-mat"/></technique_common></bind_material>
</instance_geometry>
</node>
</node>
<node id="cam" name="Overview">
<lookat>0 -10 0 0 0 0 0 0 1</lookat>
<instance_camera url="#lens"/>
</node>
<node id="other">
<instance_geometry url="#tris">
<bind_material><technique_common><instance_material symbol="mat1" target="#blue-mat"/></technique_common></bind_material>
</instance_geometry>
</node>
</visual_scene>
</library_visual_scenes>
<scene><instance_visual_scene url="#scene"/></scene>
</COLLADA>
"##;
#[test]
fn reads_polylist_transforms_units_and_cameras() {
let doc = read_document(DAE.as_bytes(), &Limits::default()).unwrap();
doc.scene.validate().unwrap();
assert_eq!(doc.meter, 0.5);
assert_eq!(doc.up_axis, UpAxis::ZUp);
assert_eq!(doc.scene.materials.iter().map(|m| m.name.as_str()).collect::<Vec<_>>(), ["Red", "Blue"]);
assert!(doc.scene.warnings.iter().any(|w| w.contains("lines")));
assert_eq!(doc.scene.cameras.len(), 1);
assert_eq!(doc.scene.cameras[0].name, "Overview");
let global = doc.global_transform();
let inst = doc.scene.instances(&Limits::default()).unwrap();
assert_eq!(inst.len(), 2);
let mut tris = 0usize;
for (m_idx, xform) in inst {
let m = &doc.scene.meshes[m_idx];
tris += m.triangle_count();
let w = mat_mul(&global, &xform);
for p in &m.positions {
let wp = transform_point(&w, *p);
assert!(wp.iter().all(|v| v.is_finite()));
}
}
assert_eq!(tris, 5);
}
#[test]
fn entities_and_limits_are_enforced() {
let dae = DAE
.replace(r#"<node id="other">"#, r#"<node id="other" name="Tom &amp; Jerry &lt;&quot;&apos;&#65;&#x42;">"#)
.replace(r#"name="Red""#, r#"name="R&amp;D""#);
let scene = read(dae.as_bytes(), &Limits::default()).unwrap();
scene.validate().unwrap();
assert!(scene.nodes.iter().any(|n| n.name == "Tom & Jerry <\"'AB"));
assert_eq!(scene.materials[0].name, "R&D");
let tight = Limits { max_triangles: 2, ..Limits::default() };
assert!(matches!(read(DAE.as_bytes(), &tight), Err(Error::TooLarge(_))));
}
#[test]
fn hammer_never_panics() {
hammer(DAE.as_bytes(), &|b| read(b, &Limits::default()));
}