From 4a02f8cc4f75d828c6b21635548591e857d51bc2 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 1 Nov 2026 12:24:17 +0700 Subject: [PATCH] FBX texture files beside the mesh An FBX whose base color textures are files (as most exporters write them) now keeps them: like a loose USD layer becomes a .usdz, opening, importing or adding it as a high poly packages the FBX with the texture files it names, so color map bakes see them and the project stores them. - fbx::package: a stored zip of the FBX (first) and the files found below its folder, by the Texture's (or Video's) RelativeFilename, else its absolute FileName's file name next to it; textures found nowhere are named in the log - fbx::read opens such a package like the FBX (embedded content still wins) - shared zip limits and entry reading for usdz and FBX packages (mesh_import::zip_entry) - test: relative and file-name-only lookups, binary and ASCII, missing files warn, packages re-import as they are, packages without an FBX or nested ones are errors --- crates/formats/README.md | 2 +- crates/formats/src/mesh_import/external.rs | 12 ++- crates/formats/src/mesh_import/fbx.rs | 96 +++++++++++++++++-- crates/formats/src/mesh_import/mod.rs | 14 +++ crates/formats/src/mesh_import/scene_tests.rs | 60 +++++++++++- crates/formats/src/mesh_import/usd/mod.rs | 12 +-- 6 files changed, 173 insertions(+), 23 deletions(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index 1f3b33df..e0f2d569 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -26,7 +26,7 @@ pub struct MeshReport { | Format | Notes | |---|---| | `.glb` / `.gltf` | Default scene's node tree flattened to world space; normals by inverse transpose; winding flipped under mirroring transforms; one submesh per material (`Default` for none, `Material_` when unnamed); missing normals are flat (glTF rule). Bytes: GLB or data-URI buffers and images; `self_contained_mesh` folds a `.gltf`'s `.bin` files and images from its folder in as data URIs (files outside the folder are never read). Triangle primitives only; sparse accessors are refused. Cameras (perspective `yfov`, orthographic `ymag`) become `ImportedMesh::cameras`. | -| `.fbx` | FBX 6.x and 7.x, binary (32- and 64-bit node records, zlib arrays) and ASCII. Every `Mesh` geometry connected to a Model, with the Model hierarchy's transforms (`Lcl Translation/Rotation/Scaling`, `RotationOrder`, `Pre/PostRotation`, pivots and offsets, geometric transform); normals and UV set 0 from the layer elements (`ByPolygonVertex`, `ByControlPoint`, `ByPolygon`, `AllSame`; `Direct` / `IndexToDirect`); per-polygon materials named by the Materials connected to the Model. Units (`UnitScaleFactor`, cm by default) become meters and the axis system becomes Y up. Camera Models become cameras (looking down +X; lens from the Camera NodeAttribute or, in FBX 6, the Model: `FocalLength` over `FilmHeight`, else `FieldOfViewY` / `FieldOfView`; `CameraProjectionType` 1 orthographic); FBX 6's Producer views are skipped. Materials bring `DiffuseColor` × `DiffuseFactor` and an embedded diffuse texture. FBX 5 and older are refused; decoded data is capped at 2 GiB. | +| `.fbx` | FBX 6.x and 7.x, binary (32- and 64-bit node records, zlib arrays) and ASCII. Every `Mesh` geometry connected to a Model, with the Model hierarchy's transforms (`Lcl Translation/Rotation/Scaling`, `RotationOrder`, `Pre/PostRotation`, pivots and offsets, geometric transform); normals and UV set 0 from the layer elements (`ByPolygonVertex`, `ByControlPoint`, `ByPolygon`, `AllSame`; `Direct` / `IndexToDirect`); per-polygon materials named by the Materials connected to the Model. Units (`UnitScaleFactor`, cm by default) become meters and the axis system becomes Y up. Camera Models become cameras (looking down +X; lens from the Camera NodeAttribute or, in FBX 6, the Model: `FocalLength` over `FilmHeight`, else `FieldOfViewY` / `FieldOfView`; `CameraProjectionType` 1 orthographic); FBX 6's Producer views are skipped. Materials bring `DiffuseColor` × `DiffuseFactor` and the diffuse texture, embedded or a file: `self_contained_mesh` packages an FBX with the texture files it names (`RelativeFilename`, else the file name of `FileName`) found in its folder, a stored zip that still reads as `.fbx`. FBX 5 and older are refused; decoded data is capped at 2 GiB. | | `.dae` | COLLADA: `triangles`, `polylist`, `polygons` (holes ignored) with `VERTEX` / `NORMAL` / `TEXCOORD` inputs at any offset (lowest `set`); materials by `bind_material` symbol; the visual scene's node tree (`matrix`, `translate`, `rotate`, `scale`, `lookat`, `instance_node`, skinned `instance_controller` with its bind shape); `instance_camera` (perspective `yfov` or `xfov` + `aspect_ratio`, orthographic `ymag` or `xmag` + `aspect_ratio`) as cameras; `unit` to meters, `Z_UP` / `X_UP` to Y up. Lines and strips are skipped with a warning. | | `.usda` / `.usdc` / `.usd` / `.usdz` | USD, text or Crate binary (0.4.0 and newer: LZ4 sections, compressed integer and float arrays, inlined values; `.usd` by magic) or a usdz package (its first layer). Every defined, active, non-guide, visible `Mesh` prim: points, faceVertexCounts/Indices (holes skipped, n-gons fanned), normals (`primvars:normals` or `normals`) and UVs (`primvars:st`, `st0`, `UVMap`, `uv` or the first `texCoord2f[]` primvar), indexed or not, any interpolation; `orientation = leftHanded`. Xform ops (`translate`, `scale`, `rotateX/Y/Z`, the six `rotateXYZ` orders, `orient`, `transform`, `!invert!`, `!resetXformStack!`) by `xformOpOrder`. Material names from `material:binding` (inherited) and `materialBind` GeomSubsets. Internal references compose (`class` prims are only drawn through them); time samples use the first sample. Stage `metersPerUnit` (fallback 0.01, as in USD) and `upAxis` become meters, Y up. `Camera` prims (`focalLength` over `verticalAperture`, `projection`) become cameras. Skipped with a warning: external references and payloads, variant sets, PointInstancers. Decoded data is capped at 2 GiB. `self_contained_mesh` packages a loose layer whose UsdPreviewSurface base color textures sit in its folder into a `.usdz` with them, so high polys keep their textures. | | `.obj` | Triangulated, one vertex per unique `v/vt/vn`, **v flipped** (OBJ is bottom-left). Material names come from `usemtl` (MTL files are never read; they only carry shading data). | diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs index 6cf1fbba..25fa8bbd 100644 --- a/crates/formats/src/mesh_import/external.rs +++ b/crates/formats/src/mesh_import/external.rs @@ -1,5 +1,5 @@ //! Meshes that keep part of their data in other files: a `.gltf`'s buffers and images, a loose -//! USD layer's textures. [`self_contained_mesh`] folds those files in, so a project stores the +//! USD layer's textures, an FBX's texture files. [`self_contained_mesh`] folds those files in, so a project stores the //! mesh as one file and imports it again from its bytes alone. use base64::Engine as _; @@ -20,8 +20,9 @@ pub struct MeshFile { } /// `bytes` of mesh `name` with the files it references folded in: a `.gltf`'s external buffers -/// and images become data URIs, and a `.usd`/`.usda`/`.usdc` layer whose materials use texture -/// files becomes a `.usdz` package holding them. `read` gets a referenced file by its path below +/// and images become data URIs, a `.usd`/`.usda`/`.usdc` layer whose materials use texture files +/// becomes a `.usdz` package holding them, and an FBX whose base color textures are files becomes +/// a package of it and them (still named `.fbx`). `read` gets a referenced file by its path below /// the mesh's folder (`/`-separated); files outside that folder (absolute paths, URLs, `..` above /// it) are not read. Other formats, and meshes that reference nothing, come back unchanged. pub fn self_contained_mesh(name: &str, bytes: Vec, read: &mut dyn FnMut(&str) -> Option>) -> Result { @@ -36,6 +37,11 @@ pub fn self_contained_mesh(name: &str, bytes: Vec, read: &mut dyn FnMut(&str }; let (name, bytes) = match super::extension(name).as_str() { "gltf" => (name.to_string(), inline_gltf(bytes, &mut found)?), + "fbx" => { + let (package, missing) = super::fbx::package(name, &bytes, &mut |asset| below(asset).and_then(|p| read(&p)))?; + warnings.extend(missing.into_iter().map(|asset| format!("{name}: {asset} was not found next to the mesh"))); + (name.to_string(), package.unwrap_or(bytes)) + } "usd" | "usda" | "usdc" => match super::usd::package(name, &bytes, &mut found)? { Some(usdz) => (std::path::Path::new(name).with_extension("usdz").to_string_lossy().into_owned(), usdz), None => (name.to_string(), bytes), diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 709e51eb..43fea71e 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -4,7 +4,9 @@ //! meters, Y up, like glTF). FBX 6 keeps the geometry inside its Model, names objects instead of //! numbering them and lists properties in `Properties60`; both read into the same scene. //! Materials bring their diffuse color and, when the file embeds it (a Video's `Content`), the -//! diffuse texture (for high-poly color map bakes). Camera Models become the file's cameras (lens +//! diffuse texture (for high-poly color map bakes); a texture kept as a file beside the FBX comes +//! along when the FBX is packaged with it ([`package`]: a stored zip of the FBX first and the +//! files under their paths below its folder, which [`read`] opens like the FBX). Camera Models become the file's cameras (lens //! from their camera NodeAttribute, or the Model's own properties in FBX 6). use std::borrow::Cow; @@ -14,11 +16,16 @@ use std::io::Read as _; use base64::Engine as _; use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; -use super::{Corner, PolygonSink, RawBaseColor, RawCamera, RawMesh, check_vertices, lens_fov}; +use super::external::below; +use super::{ + Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh, check_vertices, lens_fov, zip_entry, +}; use crate::{FormatError, Result, malformed}; const KIND: &str = "FBX"; const MAGIC: &[u8] = b"Kaydara FBX Binary \0"; +/// A zip package of an FBX and its texture files ([`package`]). +const ZIP_MAGIC: &[u8] = b"PK\x03\x04"; /// First FBX version with the object/connection layout read here (6.0). const MIN_VERSION: i64 = 6000; /// Deepest node nesting (and Model parent chain) followed. @@ -424,11 +431,69 @@ fn parse_ascii(s: &[u8]) -> Result<(Vec, i64)> { // --------------------------------------------------------------------------------------------- // Scene. +/// The bytes of the first of a texture's candidate file paths (relative to the FBX's folder) +/// that exists. +type Files<'a> = dyn FnMut(&[&str]) -> Option> + 'a; + +/// An FBX, or a package of one and its texture files. pub(crate) fn read(bytes: &[u8]) -> Result { - crate::guard(KIND, || read_inner(bytes)) + if !bytes.starts_with(ZIP_MAGIC) { + return crate::guard(KIND, || read_inner(bytes, &mut |_| None)); + } + crate::guard(KIND, || { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| malformed(KIND, format!("FBX package: {e}")))?; + if zip.len() > MAX_ZIP_ENTRIES { + return Err(FormatError::TooLarge(format!("the FBX package has more than {MAX_ZIP_ENTRIES} entries"))); + } + let name = zip.file_names().filter(|n| super::extension(n) == "fbx").min_by_key(|n| zip.index_for_name(n)).map(str::to_string); + let name = name.ok_or_else(|| malformed(KIND, "the package contains no FBX file"))?; + let fbx = zip_entry(&mut zip, &name, MAX_MESH_FILE_BYTES) + .ok_or_else(|| FormatError::TooLarge("the packaged FBX is unreadable or larger than 2 GiB".into()))?; + if fbx.starts_with(ZIP_MAGIC) { + return Err(malformed(KIND, "the package holds another package")); + } + read_inner(&fbx, &mut |paths| paths.iter().find_map(|p| zip_entry(&mut zip, &below(p)?, MAX_TEXTURE_BYTES))) + }) } -fn read_inner(bytes: &[u8]) -> Result { +/// An FBX whose base color textures are files, as a package holding it (first) and the files +/// `found` has, under their paths below its folder; None when it found none (or `bytes` is a +/// package already). Also the texture paths it could not find. +pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) -> Option>) -> Result<(Option>, Vec)> { + if bytes.starts_with(ZIP_MAGIC) { + return Ok((None, Vec::new())); + } + crate::guard(KIND, || { + let (mut files, mut missing): (Vec<(String, Vec)>, Vec) = (Vec::new(), Vec::new()); + read_inner(bytes, &mut |paths| { + if let Some((_, data)) = files.iter().find(|(n, _)| paths.iter().any(|p| below(p).as_ref() == Some(n))) { + return Some(data.clone()); + } + for p in paths { + if let (Some(name), Some(data)) = (below(p), found(p).filter(|d| d.len() as u64 <= MAX_TEXTURE_BYTES)) { + files.push((name, data.clone())); + return Some(data); + } + } + // A texture is missing when none of its paths was found; named by its first. + if let Some(first) = paths.first().filter(|f| !missing.iter().any(|m| m == *f)) { + missing.push(first.to_string()); + } + None + })?; + if files.is_empty() { + return Ok((None, missing)); + } + let total = files.iter().fold(bytes.len() as u64, |t, (_, d)| t.saturating_add(d.len() as u64)); + if total > MAX_MESH_FILE_BYTES { + return Err(FormatError::TooLarge("the FBX and its textures exceed 2 GiB".into())); + } + let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh.fbx"); + Ok((Some(crate::mesh_export::usd::usdz(leaf, bytes, &files)?), missing)) + }) +} + +fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let (nodes, version) = if bytes.starts_with(MAGIC) { parse_binary(bytes)? } else { parse_ascii(bytes)? }; if version < MIN_VERSION { return Err(FormatError::Unsupported(format!("FBX version {version} (re-export as FBX 2006 / 6.1 or newer)"))); @@ -482,7 +547,7 @@ fn read_inner(bytes: &[u8]) -> Result { unplaced.sort_unstable(); instances.extend(unplaced.into_iter().map(|g| (g, None))); - let base_colors = base_colors(&materials, &textures, &videos, &connections); + let base_colors = base_colors(&materials, &textures, &videos, &connections, files); let global = global_transform(root("GlobalSettings").or_else(|| objects.child("GlobalSettings"))); let mut sink = PolygonSink::default(); let no_slots = Vec::new(); @@ -540,6 +605,7 @@ fn base_colors( textures: &HashMap, videos: &HashMap, connections: &[&Node], + files: &mut Files, ) -> Vec { // Texture → its Video, material → its diffuse texture (a property connection wins). let (mut video_of, mut diffuse) = (HashMap::new(), HashMap::new()); @@ -563,8 +629,9 @@ fn base_colors( .iter() .filter_map(|(id, m)| { let texture = diffuse.get(id); - let image = - texture.and_then(|t| video_of.get(t)).and_then(|v| videos.get(v)).or_else(|| texture.and_then(|t| textures.get(t))).and_then(|n| n.content()); + let (video, tex) = (texture.and_then(|t| video_of.get(t)).and_then(|v| videos.get(v)), texture.and_then(|t| textures.get(t))); + // Embedded content first, then the file the texture (or its video) names. + let image = video.or(tex).and_then(|n| n.content()).or_else(|| [tex, video].into_iter().flatten().find_map(|n| texture_file(n, files))); let factor = match (&image, m.property("DiffuseColor").as_deref()) { (None, Some([r, g, b, ..])) => { let f = m.number("DiffuseFactor").unwrap_or(1.0); @@ -579,6 +646,21 @@ fn base_colors( out } +/// The file a Texture or Video names: its relative path, else its absolute path's file name +/// (looked for in the FBX's folder). +fn texture_file(n: &Node, files: &mut Files) -> Option> { + let relative = n.child_str("RelativeFilename"); + let absolute = [n.child_str("FileName"), n.child_str("Filename")].into_iter().find(|s| !s.is_empty()).unwrap_or_default(); + let leaf = absolute.rsplit(['/', '\\']).next().unwrap_or_default(); + let mut paths: Vec<&str> = Vec::new(); + for p in [relative, leaf] { + if !p.is_empty() && !paths.contains(&p) { + paths.push(p); + } + } + if paths.is_empty() { None } else { files(&paths) } +} + /// `Name\0\1Class` (binary) or `Class::Name` (ASCII) to `Name`. fn clean_name(s: &str) -> &str { match s.split_once("\u{0}\u{1}") { diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index a8e6ed1d..521cab30 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -54,6 +54,20 @@ pub struct ImportedMesh { pub cameras: Vec, } +/// Most entries of a zip package (usdz, an FBX with its textures). +pub(crate) const MAX_ZIP_ENTRIES: usize = 100_000; +/// Largest texture file read from a package or beside a mesh. +pub(crate) const MAX_TEXTURE_BYTES: u64 = 1 << 28; + +/// Entry `name` of a zip package, at most `cap` bytes (None when missing, larger or unreadable). +pub(crate) fn zip_entry(zip: &mut zip::ZipArchive>, name: &str, cap: u64) -> Option> { + use std::io::Read as _; + let f = zip.by_name(name).ok()?; + let mut data = Vec::new(); + f.take(cap + 1).read_to_end(&mut data).ok()?; + (data.len() as u64 <= cap).then_some(data) +} + /// Cameras read from a file (at most [`MAX_CAMERAS`]). pub(crate) const MAX_CAMERAS: usize = 64; diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 68b035e9..08609687 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -312,11 +312,17 @@ fn textured_scene(png: &[u8]) -> Vec { nodes } -#[test] -fn fbx_diffuse_colors_and_embedded_textures_reach_high_polys() { +/// A 2 × 2 PNG: red in the left column, green in the top row, blue 7. +fn tiny_png() -> Vec { let mut png = Vec::new(); let img = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([if x == 0 { 255 } else { 0 }, if y == 0 { 255 } else { 0 }, 7, 255])); image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + png +} + +#[test] +fn fbx_diffuse_colors_and_embedded_textures_reach_high_polys() { + let png = tiny_png(); let nodes = textured_scene(&png); for (label, bytes) in [("binary", binary_fbx(&nodes, 7500, true)), ("ascii", ascii_fbx(&nodes).into_bytes())] { let hp = import_high_poly_bytes("textured.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}")); @@ -332,6 +338,56 @@ fn fbx_diffuse_colors_and_embedded_textures_reach_high_polys() { hammer("x.fbx", &binary_fbx(&nodes, 7500, false)); } +/// [`textured_scene`] with Blue's texture kept as a file: `tex/wood.png` relative to the FBX, or +/// only an absolute path elsewhere (found by its file name next to the FBX). +fn texture_file_scene(relative: &'static str) -> Vec { + let mut nodes = textured_scene(&[]); + let objects = nodes.iter_mut().find(|n| n.name == "Objects").unwrap(); + objects.children.retain(|n| n.name != "Video"); + let tex = objects.children.iter_mut().find(|n| n.name == "Texture").unwrap(); + tex.children.push(n("FileName", vec![P::S("C:/Users/artist/maps/wood.png")], vec![])); + tex.children.push(n("RelativeFilename", vec![P::S(relative)], vec![])); + nodes +} + +#[test] +fn fbx_texture_files_are_packaged_with_the_mesh() { + let png = tiny_png(); + let blue = |bytes: &[u8]| import_high_poly_bytes("wood.fbx", bytes).unwrap().base_color[1].as_ref().map(|b| (b.width, b.texels[0])); + for (label, bytes) in + [("binary", binary_fbx(&texture_file_scene("tex\\wood.png"), 7500, true)), ("ascii", ascii_fbx(&texture_file_scene("tex/wood.png")).into_bytes())] + { + assert_eq!(blue(&bytes), None, "{label}: the file alone has no texture"); + // Beside the FBX under its relative path: packaged, and the package reads like the FBX. + let mut asked = Vec::new(); + let f = self_contained_mesh("scenes/wood.fbx", bytes.clone(), &mut |p| { + asked.push(p.to_string()); + (p == "tex/wood.png").then(|| png.clone()) + }) + .unwrap(); + assert_eq!(asked, ["tex/wood.png"], "{label}"); + assert!(f.warnings.is_empty() && f.name == "scenes/wood.fbx" && f.bytes.starts_with(b"PK"), "{label}: {:?}", f.warnings); + assert_eq!(blue(&f.bytes), Some((2, [255, 255, 7, 255])), "{label}"); + check_fbx_scene(&import_mesh_bytes("wood.fbx", &f.bytes).unwrap().mesh, false); + assert_eq!(self_contained_mesh("wood.fbx", f.bytes.clone(), &mut |_| panic!("packaged already")).unwrap().bytes, f.bytes); + // Only the absolute path's file name next to the FBX. + let g = self_contained_mesh("wood.fbx", bytes.clone(), &mut |p| (p == "wood.png").then(|| png.clone())).unwrap(); + assert!(g.warnings.is_empty(), "{label}: {:?}", g.warnings); + assert_eq!(blue(&g.bytes), Some((2, [255, 255, 7, 255])), "{label}"); + // Missing: unchanged, with a warning naming it. + let h = self_contained_mesh("wood.fbx", bytes.clone(), &mut |_| None).unwrap(); + assert_eq!(h.bytes, bytes, "{label}"); + assert!(h.warnings.iter().any(|w| w.contains("wood.png") && w.contains("not found")), "{label}: {:?}", h.warnings); + } + let packaged = self_contained_mesh("wood.fbx", ascii_fbx(&texture_file_scene("tex/wood.png")).into_bytes(), &mut |_| Some(png.clone())).unwrap(); + hammer("x.fbx", &packaged.bytes[..packaged.bytes.len().min(4096)]); + // A package without an FBX, or holding another package, is an error. + let empty = crate::mesh_export::usd::usdz("a.png", &png, &[]).unwrap(); + assert!(import_mesh_bytes("x.fbx", &empty).is_err()); + let nested = crate::mesh_export::usd::usdz("inner.fbx", &packaged.bytes, &[]).unwrap(); + assert!(import_mesh_bytes("x.fbx", &nested).is_err()); +} + #[test] fn fbx_ascii_and_z_up() { let text = ascii_fbx(&scene(false)); diff --git a/crates/formats/src/mesh_import/usd/mod.rs b/crates/formats/src/mesh_import/usd/mod.rs index 6af1d254..fc1544bb 100644 --- a/crates/formats/src/mesh_import/usd/mod.rs +++ b/crates/formats/src/mesh_import/usd/mod.rs @@ -21,12 +21,11 @@ mod usda; mod usdc; use std::collections::HashMap; -use std::io::Read as _; use texturecraft_geom::glam::{DMat4, DQuat, DVec3, DVec4, Mat3, Mat4, Vec2, Vec3, Vec4}; use super::external::below; -use super::{Corner, MAX_MESH_FILE_BYTES, PolygonSink, RawBaseColor, RawCamera, RawMesh, lens_fov}; +use super::{Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh, lens_fov, zip_entry}; use crate::{FormatError, Result, malformed}; pub(crate) const KIND: &str = "USD"; @@ -36,10 +35,6 @@ const MAX_DECODED_BYTES: usize = 1 << 31; const MAX_DEPTH: usize = 128; /// Composed prims visited (bounds exponential instancing through references). const MAX_PRIM_VISITS: usize = 1_000_000; -/// Entries accepted in a `.usdz` package. -const MAX_ZIP_ENTRIES: usize = 100_000; -/// Largest texture file read from a `.usdz` package. -const MAX_TEXTURE_BYTES: u64 = 1 << 28; /// A decoded value: numbers (scalars, vectors, quaternions as w x y z, matrices row-major and /// bools all flattened), tokens / strings / asset paths, or paths. @@ -166,10 +161,7 @@ struct Package<'a> { impl Package<'_> { /// Entry `name`'s bytes, at most `cap` (None when missing, larger or unreadable). fn read(&mut self, name: &str, cap: u64) -> Option> { - let f = self.zip.by_name(name).ok()?; - let mut data = Vec::new(); - f.take(cap + 1).read_to_end(&mut data).ok()?; - (data.len() as u64 <= cap).then_some(data) + zip_entry(&mut self.zip, name, cap) } }