diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index 136e3e0c..92e52f72 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -28,9 +28,9 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option>)> { let (json, blob) = if bytes.starts_with(b"glTF") { let mut glb = gltf::Glb::from_slice(bytes).map_err(|e| malformed(KIND, e))?; let blob = glb.bin.take().map(std::borrow::Cow::into_owned); - (glb.json.into_owned(), blob) + (glb.json, blob) } else { - (bytes.to_vec(), None) + (std::borrow::Cow::Borrowed(bytes), None) }; let mut value: serde_json::Value = serde_json::from_slice(&json).map_err(|e| malformed(KIND, e))?; if let Some(scenes) = value.get_mut("scenes").and_then(serde_json::Value::as_array_mut) { @@ -40,8 +40,8 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option>)> { } } } - let json = serde_json::to_vec(&value).map_err(|e| malformed(KIND, e))?; - let root = gltf::json::Root::from_slice(&json).map_err(|e| malformed(KIND, e))?; + // Consume the DOM directly rather than serialising it back to a second full-size buffer. + let root: gltf::json::Root = serde_json::from_value(value).map_err(|e| malformed(KIND, e))?; let document = gltf::Document::from_json(root).map_err(|e| malformed(KIND, e))?; Ok((document, blob)) } diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index 2f284704..bf949625 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -1,5 +1,7 @@ //! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn. +use std::io::{BufReader, Read}; + use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use super::{RawMesh, check_triangles, check_vertices}; @@ -27,12 +29,15 @@ fn read_inner(bytes: &[u8]) -> Result { } let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect(); - let source = format!("mtllib texturecraft-usemtl.mtl\n{text}"); + let prefix = "mtllib texturecraft-usemtl.mtl\n"; + + // Feed the prefix and the borrowed (or lossily converted) body as one reader: neither a + // whole-file copy nor an extra string is needed before tobj parses it. + let mut source = BufReader::new(prefix.as_bytes().chain(text.as_bytes())); // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; - let (models, materials) = - tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; + let (models, materials) = tobj::load_obj_buf(&mut source, &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; let materials = materials.unwrap_or_default(); let mut raw = RawMesh::default();