From 90d63ca58f4e6253fef3dcdc695f9556223379e3 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:22:00 +0700 Subject: [PATCH] fix(formats): propagate shared OBJ writer errors (#703) * fix(formats): propagate OBJ writer failures before publication * style: format OBJ result propagation --- crates/engine/src/file_cmds.rs | 39 ++++++++++++++++++++++++++++--- crates/engine/tests/it/udim.rs | 2 +- crates/formats/README.md | 6 ++++- crates/formats/src/mesh_export.rs | 35 +++++++++++++++++---------- crates/ui-egui/src/web_files.rs | 6 ++--- 5 files changed, 68 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index b7033e0a..968acce2 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -106,8 +106,8 @@ fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result Vec { - texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name) + pub fn mesh_obj_bytes(&self) -> Result> { + texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name).map_err(fe) } /// [`Session::mesh_obj_bytes`] with an MTL material library and each material's maps (like @@ -121,7 +121,7 @@ impl Session { mesh.materials.push("default".into()); } let files = self.material_files(texturecraft_formats::usd_export_options(), false, mesh.materials.len())?; - Ok(texturecraft_formats::obj_with_mtl(&mesh, &self.doc.project.name, stem, &files)) + texturecraft_formats::obj_with_mtl(&mesh, &self.doc.project.name, stem, &files).map_err(fe) } /// The working mesh as binary glTF with each material's textures (from its texture set's @@ -897,6 +897,39 @@ f 1/1 2/2 3/3 assert_eq!(saved.project_id, project, "a reimport stays the same project"); } + #[test] + fn rejected_obj_export_preserves_existing_files_and_publishes_nothing() { + let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let dir = std::env::temp_dir().join(format!("tc_rejected_obj_export_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("cube.obj"); + // The same command first writes a valid mesh and all its companions. + crate::execute(&mut s, "file.exportMesh", &json!({ "path": path })).unwrap(); + assert!(std::fs::read_to_string(&path).unwrap().contains("\nf ")); + let snapshot = || { + std::fs::read_dir(&dir) + .unwrap() + .map(|entry| { + let path = entry.unwrap().path(); + let bytes = std::fs::read(&path).unwrap(); + (path, bytes) + }) + .collect::>() + }; + let before = snapshot(); + assert!(before.len() > 2, "the valid export includes its MTL and maps"); + // Keep the working/render mesh valid; corrupt only the source exported by both APIs. + Arc::make_mut(&mut s.source).indices[0] = u32::MAX; + assert!(s.mesh_obj_bytes().unwrap_err().to_string().contains("corner index is out of range")); + assert!(s.mesh_obj_with_mtl("cube").unwrap_err().to_string().contains("corner index is out of range")); + for destination in [path, dir.join("new.obj")] { + let error = crate::execute(&mut s, "file.exportMesh", &json!({ "path": destination })).unwrap_err(); + assert!(error.to_string().contains("corner index is out of range"), "{error}"); + assert_eq!(snapshot(), before, "a rejected mesh must neither overwrite nor publish any file"); + } + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn export_mesh_writes_obj_by_default_and_textured_glb() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/engine/tests/it/udim.rs b/crates/engine/tests/it/udim.rs index 9d8e256a..5fe4d582 100644 --- a/crates/engine/tests/it/udim.rs +++ b/crates/engine/tests/it/udim.rs @@ -114,7 +114,7 @@ fn projects_round_trip_and_meshes_export_their_own_uvs() { assert_eq!(red_per_tile(&back), red); // OBJ export keeps the mesh's UDIM UVs; the working mesh is in atlas space. assert!(s.mesh.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x))); - let obj = String::from_utf8(s.mesh_obj_bytes()).unwrap(); + let obj = String::from_utf8(s.mesh_obj_bytes().unwrap()).unwrap(); let max_u = obj.lines().filter_map(|l| l.strip_prefix("vt ")).filter_map(|l| l.split_whitespace().next()?.parse::().ok()).fold(0.0f32, f32::max); assert!((max_u - 2.0).abs() < 1e-4, "{max_u}"); // With its MTL: the same UVs, and no maps for the UV-tiled set (one image cannot hold them). diff --git a/crates/formats/README.md b/crates/formats/README.md index 161007c0..4033b1be 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -43,7 +43,8 @@ degenerate are refused (MikkTSpace crashes on them). ### Mesh export (`mesh_export`) ```rust -pub fn obj_bytes(mesh: &Mesh, name: &str) -> Vec; +pub fn obj_bytes(mesh: &Mesh, name: &str) -> Result>; +pub fn obj_with_mtl(mesh: &Mesh, name: &str, stem: &str, textures: &[Vec]) -> Result<(Vec, NamedFiles)>; pub fn glb_bytes(mesh: &Mesh, name: &str, textures: &[GlbTextures]) -> Result>; pub fn glb_export_options() -> ExportOptions; // render GlbTextures with these pub struct GlbTextures { pub base_color, pub orm, pub normal, pub emissive: Option> } // PNG @@ -53,6 +54,9 @@ pub enum UsdFormat { Usda, Usdc, Usdz } pub struct UsdExport { pub bytes: Vec, pub textures: Vec<(String, Vec)> } // textures: usda/usdc only ``` +OBJ export propagates shared writer validation and limit errors rather than returning empty bytes. +An unsuccessful OBJ export returns no material library or texture files. + USD: one `Mesh` prim (vertex normals and `primvars:st`, `subdivisionScheme = "none"`), one `materialBind` GeomSubset per material when there are several, and a UsdPreviewSurface material per material with a UsdUVTexture per map (base color and emissive sRGB; roughness, metallic, diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index 3d60861e..33ffdabc 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -17,17 +17,18 @@ use crate::{ExportOptions, ExportPreset, ExportedFile, FileFormat, FormatError, pub use usd::{NamedFiles, UsdExport, UsdFormat, usd_bytes, usd_export_options}; /// The mesh as OBJ text (UV v flipped back to OBJ's bottom-up convention). -pub fn obj_bytes(mesh: &Mesh, name: &str) -> Vec { +/// Invalid mesh data or shared writer limits return an error, never an empty successful export. +pub fn obj_bytes(mesh: &Mesh, name: &str) -> Result> { let scene = to_craft_scene(mesh, &token(name), mesh.materials.iter().map(|m| craft_mesh::Material::plain(token(m), [1.0; 4])).collect(), Vec::new()); - craft_mesh::obj::write(&scene, None, &craft_mesh::Limits::default()).unwrap_or_default().into_bytes() + craft_mesh::obj::write(&scene, None, &craft_mesh::Limits::default()).map(String::into_bytes).map_err(|e| FormatError::Invalid(e.to_string())) } /// The mesh as OBJ with a material library: the OBJ (naming `.mtl`, `stem` being the /// OBJ file's own, so exports beside each other keep their files apart) and the files to write /// next to it, the MTL first, then each material's maps (`textures[m]`, rendered with /// [`usd_export_options`], named like USD's). Roughness, metallic, normal and coat maps use the -/// MTL PBR extension's keys. -pub fn obj_with_mtl(mesh: &Mesh, name: &str, stem: &str, textures: &[Vec]) -> (Vec, NamedFiles) { +/// MTL PBR extension's keys. Writer failures return an error without companion files. +pub fn obj_with_mtl(mesh: &Mesh, name: &str, stem: &str, textures: &[Vec]) -> Result<(Vec, NamedFiles)> { let clean = sanitize_file_stem(stem); // OBJ names that sanitize alike (`ball 1`, `ball_1`) must not overwrite each other's files: // a changed name gets a hash of the original (FNV-1a). @@ -62,8 +63,8 @@ pub fn obj_with_mtl(mesh: &Mesh, name: &str, stem: &str, textures: &[Vec, images: Vec) -> craft_mesh::Scene { @@ -264,13 +265,23 @@ fn token(name: &str) -> String { mod tests { use super::*; + #[test] + fn obj_writers_report_invalid_corner_indices() { + let mut mesh = texturecraft_geom::primitives::cube(1.0); + mesh.indices[0] = u32::MAX; + for error in [obj_bytes(&mesh, "invalid").unwrap_err(), obj_with_mtl(&mesh, "invalid", "m", &[]).unwrap_err()] { + assert!(matches!(error, FormatError::Invalid(_))); + assert!(error.to_string().contains("corner index is out of range"), "{error}"); + } + } + #[test] fn name_with_newline_stays_in_the_header_comment() { let mesh = texturecraft_geom::primitives::cube(1.0); let name = "a\nv 9 9 9\r\nmtllib x"; - let obj = String::from_utf8(obj_bytes(&mesh, name)).unwrap(); + let obj = String::from_utf8(obj_bytes(&mesh, name).unwrap()).unwrap(); assert!(obj.lines().all(|l| !l.starts_with("v 9 9 9") && !l.starts_with("mtllib x"))); - let (obj, files) = obj_with_mtl(&mesh, name, "m", &[]); + let (obj, files) = obj_with_mtl(&mesh, name, "m", &[]).unwrap(); let obj = String::from_utf8(obj).unwrap(); assert!(obj.lines().all(|l| !l.starts_with("v 9 9 9") && !l.starts_with("mtllib x"))); let mtl = String::from_utf8(files[0].1.clone()).unwrap(); @@ -286,7 +297,7 @@ mod tests { SubMesh { name: "b".into(), material: 1, start: 18, count: mesh.indices.len() as u32 - 18 }, ]; let png = |name: &str| ExportedFile { name: name.into(), bytes: vec![1, 2, 3], width: 1, height: 1, warnings: Vec::new() }; - let (obj, files) = obj_with_mtl(&mesh, "project", "m", &[vec![png("BaseColor.png")], vec![png("BaseColor.png")]]); + let (obj, files) = obj_with_mtl(&mesh, "project", "m", &[vec![png("BaseColor.png")], vec![png("BaseColor.png")]]).unwrap(); let obj = String::from_utf8(obj).unwrap(); assert!(obj.contains("mtllib m.mtl\n") && obj.contains("usemtl Mat_A\n") && obj.contains("usemtl mat_a_2\n")); let names: Vec<_> = files.iter().map(|f| f.0.as_str()).collect(); @@ -307,7 +318,7 @@ mod tests { SubMesh { name: "b".into(), material: 1, start: 18, count: mesh.indices.len() as u32 - 18 }, ]; let png = || ExportedFile { name: "BaseColor.png".into(), bytes: vec![1], width: 1, height: 1, warnings: Vec::new() }; - let (obj, files) = obj_with_mtl(&mesh, "project", "m", &[vec![png()], vec![png()]]); + let (obj, files) = obj_with_mtl(&mesh, "project", "m", &[vec![png()], vec![png()]]).unwrap(); let obj = String::from_utf8(obj).unwrap(); let mtl = String::from_utf8(files[0].1.clone()).unwrap(); let used: Vec<_> = obj.lines().filter_map(|line| line.strip_prefix("usemtl ")).collect(); @@ -322,7 +333,7 @@ mod tests { fn obj_names_that_sanitize_alike_keep_their_companions_apart() { let mesh = texturecraft_geom::primitives::cube(1.0); let png = || vec![ExportedFile { name: "BaseColor.png".into(), bytes: vec![1], width: 1, height: 1, warnings: Vec::new() }]; - let names = |stem: &str| obj_with_mtl(&mesh, "p", stem, &[png()]).1.into_iter().map(|f| f.0).collect::>(); + let names = |stem: &str| obj_with_mtl(&mesh, "p", stem, &[png()]).unwrap().1.into_iter().map(|f| f.0).collect::>(); let (spaced, plain) = (names("ball 1"), names("ball_1")); assert_eq!(plain, ["ball_1.mtl", "ball_1_Cube_BaseColor.png"], "a clean name is kept"); assert!(spaced.iter().all(|n| n.starts_with("ball_1_") && !plain.contains(n)), "{spaced:?}"); @@ -332,7 +343,7 @@ mod tests { #[test] fn obj_round_trips_through_the_importer() { let mesh = texturecraft_geom::primitives::rounded_box(texturecraft_geom::glam::Vec3::splat(1.0), 0.1); - let bytes = obj_bytes(&mesh, "My box"); + let bytes = obj_bytes(&mesh, "My box").unwrap(); let back = crate::import_mesh_bytes("box.obj", &bytes).unwrap().mesh; assert_eq!(back.triangle_count(), mesh.triangle_count()); let (a, b) = (mesh.bounds(), back.bounds()); diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 7138e12a..048d7a97 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -334,7 +334,7 @@ mod web { let bytes = match ext { "glb" => app.session.mesh_glb_bytes(), "usdz" => app.session.mesh_usd(texturecraft_engine::formats::UsdFormat::Usdz).map(|u| u.bytes), - _ => Ok(app.session.mesh_obj_bytes()), + _ => app.session.mesh_obj_bytes(), }; match bytes.map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) { Ok(()) => app.toast(trf("Downloaded {name}", &[("name", &name)]), false), @@ -496,7 +496,7 @@ mod tests { let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); let old_project_id = harness.state().session.project_id; assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); - let cage = harness.state().session.mesh_obj_bytes(); + let cage = harness.state().session.mesh_obj_bytes().unwrap(); apply_picked( harness.state_mut(), @@ -510,7 +510,7 @@ mod tests { assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); let project_id = harness.state().session.project_id; - let mesh = harness.state().session.mesh_obj_bytes(); + let mesh = harness.state().session.mesh_obj_bytes().unwrap(); apply_picked( harness.state_mut(),