diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 6f86119e..94e4924f 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -225,9 +225,9 @@ impl Headless { /// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the /// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it. - pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result { + pub fn export_mesh(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result { self.require_project()?; - let out = self.session.mesh_export(path, format)?; + let out = self.session.mesh_export_with_normals(path, format, recompute_normals)?; let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or("."); self.create_dir_all(dir)?; let mut textures = Vec::new(); diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index d159bc80..aefb4919 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -4,8 +4,9 @@ //! //! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`, //! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`, -//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `mesh.reimport {path?, -//! preserveStrokes?}`, `mesh.export {path, format?}`, `bake.mesh.add {path, cage?}`, +//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, +//! `mesh.reimport {path?, preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`, +//! `bake.mesh.add {path, cage?}`, //! `resource.import {path}`, `material.save {path, layer?, name?}`, `material.load {path}` //! (workspace-scoped versions of the engine commands), //! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the @@ -94,7 +95,7 @@ impl Headless { "project.save" => self.save(str_of(p, "path")), "mesh.import" => self.import_mesh(required(p, "path")?, u32_of(p, "resolution")?, str_of(p, "name")), "mesh.reimport" => self.reimport_mesh(str_of(p, "path"), bool_of(p, "preserveStrokes")?), - "mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format")), + "mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format"), bool_of(p, "recomputeNormals")?), "bake.mesh.add" => self.add_bake_mesh(required(p, "path")?, bool_of(p, "cage")?), "resource.import" => self.import_resource(required(p, "path")?), "material.save" => self.material_save(p), diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 0ce54f55..f870ad9a 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -141,6 +141,9 @@ pub struct MeshExportParams { /// written next to it) or usdz (textures packaged); default: from the extension, else obj. #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option, + /// Replace stored normals with smooth area-weighted normals on the exported copy (default false). + #[serde(default, rename = "recomputeNormals", skip_serializing_if = "Option::is_none")] + pub recompute_normals: Option, } #[derive(Debug, Deserialize, Serialize, JsonSchema)] diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 5c813d46..9c447c3c 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -91,7 +91,7 @@ pub fn specs() -> Vec { "Export Mesh...", ["File"], None, - "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}", + "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj), recomputeNormals?: bool (default false: smooth area-weighted normals replace the stored normals on the exported copy only); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}", always, export_mesh ), @@ -137,15 +137,32 @@ fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Op impl Session { /// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included). pub fn mesh_obj_bytes(&self) -> Result> { - texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name).map_err(fe) + self.mesh_obj_bytes_with_normals(false) + } + + /// [`Session::mesh_obj_bytes`], optionally replacing normals on the exported copy only. + pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result> { + let mut mesh = self.source_mesh(); + if recompute_normals { + mesh.compute_smooth_normals(); + } + texturecraft_formats::obj_bytes(&mesh, &self.doc.project.name).map_err(fe) } /// [`Session::mesh_obj_bytes`] with an MTL material library and each material's maps (like /// [`Session::mesh_usd`]'s), to write next to it, named after `stem` (the OBJ file's). pub fn mesh_obj_with_mtl(&mut self, stem: &str) -> Result<(Vec, texturecraft_formats::NamedFiles)> { + self.mesh_obj_with_mtl_and_normals(stem, false) + } + + /// [`Session::mesh_obj_with_mtl`], optionally replacing normals on the exported copy only. + pub fn mesh_obj_with_mtl_and_normals(&mut self, stem: &str, recompute_normals: bool) -> Result<(Vec, texturecraft_formats::NamedFiles)> { // shortcut: UV-tiled sets get no maps (the OBJ keeps the mesh's UDIM UVs and an MTL map is // one image); their tiles export through Export textures with `$udim` names. let mut mesh = self.source_mesh(); + if recompute_normals { + mesh.compute_smooth_normals(); + } // A mesh without materials has one implicit material (and texture set). if mesh.materials.is_empty() { mesh.materials.push("default".into()); @@ -158,16 +175,34 @@ impl Session { /// composite, through the texture export pipeline) embedded. glTF has no UV tiles: a /// UV-tiled set embeds its tile atlas, with the mesh's UVs in atlas space. pub fn mesh_glb_bytes(&mut self) -> Result> { + self.mesh_glb_bytes_with_normals(false) + } + + /// [`Session::mesh_glb_bytes`], optionally replacing normals on the exported copy only. + pub fn mesh_glb_bytes_with_normals(&mut self, recompute_normals: bool) -> Result> { let files = self.material_files(texturecraft_formats::glb_export_options(), true, self.mesh.materials.len())?; let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect(); - texturecraft_formats::glb_bytes(&self.mesh, &self.doc.project.name, &textures).map_err(fe) + let mut mesh = self.mesh.as_ref().clone(); + if recompute_normals { + mesh.compute_smooth_normals(); + } + texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe) } /// The working mesh as USD with a UsdPreviewSurface per material (textures like /// [`Session::mesh_glb_bytes`]): usdz packages them, usda / usdc list them to write alongside. pub fn mesh_usd(&mut self, format: texturecraft_formats::UsdFormat) -> Result { + self.mesh_usd_with_normals(format, false) + } + + /// [`Session::mesh_usd`], optionally replacing normals on the exported copy only. + pub fn mesh_usd_with_normals(&mut self, format: texturecraft_formats::UsdFormat, recompute_normals: bool) -> Result { let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?; - texturecraft_formats::usd_bytes(&self.mesh, &self.doc.project.name, &files, format).map_err(fe) + let mut mesh = self.mesh.as_ref().clone(); + if recompute_normals { + mesh.compute_smooth_normals(); + } + texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe) } /// The texture sets of the first `materials` materials rendered with `opts` (as a tile atlas @@ -1169,7 +1204,7 @@ fn write_materialx( #[cfg(not(target_arch = "wasm32"))] fn export_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "path", "file.exportMesh")?; - let out = s.mesh_export(path, strp(p, "format"))?; + let out = s.mesh_export_with_normals(path, strp(p, "format"), crate::commands::boolp(p, "recomputeNormals").unwrap_or(false))?; let dir = std::path::Path::new(&out.path).parent().unwrap_or(std::path::Path::new("")); let texture_paths: Vec = out.textures.iter().map(|(name, _)| dir.join(name)).collect(); let main_path = std::path::PathBuf::from(&out.path); @@ -1206,6 +1241,12 @@ impl Session { /// The working mesh as a file for `path`, in `format` (obj, glb, usda, usdc, usdz; default: /// from the extension, else OBJ). The extension is appended when it doesn't match. pub fn mesh_export(&mut self, path: &str, format: Option<&str>) -> Result { + self.mesh_export_with_normals(path, format, false) + } + + /// [`Session::mesh_export`], optionally computing smooth area-weighted normals on the + /// exported copy. The project's source and render meshes are never changed. + pub fn mesh_export_with_normals(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result { let ext = match format { Some(f) if MESH_EXPORT_FORMATS.contains(&f) => f.to_string(), Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` ({})", MESH_EXPORT_FORMATS.join(", ")))), @@ -1214,12 +1255,12 @@ impl Session { }; let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") }; let (bytes, textures) = match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) { - ("glb", _) => (self.mesh_glb_bytes()?, Vec::new()), + ("glb", _) => (self.mesh_glb_bytes_with_normals(recompute_normals)?, Vec::new()), (_, Some(format)) => { - let usd = self.mesh_usd(format)?; + let usd = self.mesh_usd_with_normals(format, recompute_normals)?; (usd.bytes, usd.textures) } - _ => self.mesh_obj_with_mtl(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"))?, + _ => self.mesh_obj_with_mtl_and_normals(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"), recompute_normals)?, }; Ok(MeshExport { path, bytes, textures }) } @@ -1412,6 +1453,66 @@ f 1/1 2/2 3/3 let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn mesh_export_can_recompute_normals_without_changing_the_project() { + let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + std::sync::Arc::make_mut(&mut s.source).normals.fill(texturecraft_geom::glam::Vec3::Y); + std::sync::Arc::make_mut(&mut s.mesh).normals.fill(texturecraft_geom::glam::Vec3::Y); + let mut expected = s.source_mesh(); + expected.compute_smooth_normals(); + let dir = std::env::temp_dir().join(format!("tc_export_recompute_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for (format, suffix) in [("obj", "obj"), ("glb", "glb"), ("usda", "usda")] { + let path = dir.join(format!("cube-{format}.{suffix}")); + let reply = crate::execute(&mut s, "file.exportMesh", &json!({"path": path, "recomputeNormals": true})).unwrap(); + let bytes = std::fs::read(reply["path"].as_str().unwrap()).unwrap(); + let back = texturecraft_formats::import_mesh_bytes(&format!("cube.{suffix}"), &bytes).unwrap().mesh; + assert_eq!(back.normals.len(), expected.normals.len(), "{format}: one normal per exported vertex"); + for (position, actual) in back.positions.iter().zip(&back.normals) { + let wanted = expected + .positions + .iter() + .zip(&expected.normals) + .find_map(|(expected_position, normal)| ((*expected_position - *position).length() < 1e-4).then_some(*normal)) + .unwrap_or_else(|| panic!("{format}: exported position {position:?} is missing from the source")); + assert!((*actual - wanted).length() < 1e-4, "{format}: actual {actual:?}, wanted {wanted:?}"); + } + } + assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged"); + assert!(s.mesh.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the render project is unchanged"); + let stored_path = dir.join("stored.obj"); + let stored = crate::execute(&mut s, "file.exportMesh", &json!({"path": stored_path})).unwrap(); + let stored = std::fs::read(stored["path"].as_str().unwrap()).unwrap(); + let stored = texturecraft_formats::import_mesh_bytes("stored.obj", &stored).unwrap().mesh; + assert!(stored.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the default keeps stored normals for compatibility"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn recomputed_normals_weld_uv_seams_in_exported_mesh() { + use texturecraft_geom::glam::Vec3; + + // Two triangles meet along 0--2, but their UV island split duplicates that edge as 3--4. + let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO, Vec3::Y, Vec3::new(-1.0, 0.0, 1.0)]; + let mesh = Mesh::from_parts( + positions, + Some(vec![Vec3::Y; 6]), + vec![Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.5), Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.5, 1.0)], + vec![0, 1, 2, 3, 4, 5], + "Default", + ) + .unwrap(); + let mut s = Session::new_project("seam", mesh, "builtin:seam", None, 128).unwrap(); + let bytes = s.mesh_glb_bytes_with_normals(true).unwrap(); + let back = texturecraft_formats::import_mesh_bytes("seam.glb", &bytes).unwrap().mesh; + for point in [Vec3::ZERO, Vec3::Y] { + let normals: Vec<_> = back.positions.iter().zip(&back.normals).filter_map(|(position, normal)| (*position == point).then_some(*normal)).collect(); + assert!(normals.len() >= 2, "{point:?}: the UV seam must still have two exported vertices"); + assert!(normals.windows(2).all(|pair| (pair[0] - pair[1]).length() < 1e-5), "{point:?}: UV split normals disagree: {normals:?}"); + } + } + #[test] fn rejected_glb_export_preserves_existing_files_and_publishes_nothing() { let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 6450878b..5e0d2468 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -25,7 +25,7 @@ use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4}; -use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap, weld_ids}; +use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap}; use texturecraft_geom::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh, UvGBuffer}; use crate::{FormatError, Result}; @@ -508,7 +508,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { mesh.normals = match normals { Some(n) if n.len() == mesh.positions.len() => n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(), - _ => smooth_normals(&mesh), + _ => mesh.smooth_normals(), }; if let Some(c) = colors.filter(|c| c.len() == mesh.positions.len()) { mesh.colors = c.into_iter().map(|v| if v.is_finite() { v.clamp(Vec4::ZERO, Vec4::ONE) } else { Vec4::ONE }).collect(); @@ -641,23 +641,6 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec Vec { - let welded_vertices = weld_ids(&mesh.positions); - let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; - for triangle in mesh.indices.as_chunks::<3>().0 { - let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default(); - let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0])); - for v in triangle { - if let Some(a) = welded_vertices.get(*v as usize).and_then(|w| normals.get_mut(*w as usize)) { - *a += face; - } - } - } - - welded_vertices.iter().map(|w| normals.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect() -} - /// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings). pub fn mesh_report(mesh: &Mesh) -> MeshReport { report(mesh, false, Vec::new()) diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index e00ed374..395e6c5e 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -245,6 +245,27 @@ impl Mesh { self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); } + /// Area-weighted smooth normals over welded positions, so UV and material seams do not split shading. + pub fn smooth_normals(&self) -> Vec { + let welded_vertices = crate::unwrap::weld_ids(&self.positions); + let mut normals = vec![Vec3::ZERO; self.positions.len()]; + for triangle in self.indices.as_chunks::<3>().0 { + let p = |i: u32| self.positions.get(i as usize).copied().unwrap_or_default(); + let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0])); + for v in triangle { + if let Some(accumulated) = welded_vertices.get(*v as usize).and_then(|welded| normals.get_mut(*welded as usize)) { + *accumulated += face; + } + } + } + welded_vertices.iter().map(|welded| normals.get(*welded as usize).and_then(|normal| normal.try_normalize()).unwrap_or(Vec3::Y)).collect() + } + + /// Replace normals with [`Mesh::smooth_normals`] on this mesh. + pub fn compute_smooth_normals(&mut self) { + self.normals = self.smooth_normals(); + } + /// The faces MikkTSpace sees: each importer quad (a fan pair marked in [`Mesh::diagonals`]) /// as one four-corner face, like Blender hands it over, and every other triangle as a /// triangle. Polygons with more than four corners stay fan triangles. The vertex and index diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 8458db61..7d5cb5c2 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -31,6 +31,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut export, mut cancel) = (false, false); + let mut triangulated = true; crate::windows::dialog(ctx, "mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| { ui.set_width(DIALOG_WIDTH); @@ -38,24 +39,26 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); option( ui, - true, + &mut triangulated, + false, tr("Apply triangulation"), &[ tr("Splits every face with more than three corners into triangles; triangles stay as they are."), tr("TextureCraft keeps meshes as triangles, so the exported mesh is always triangulated."), ], ); - ui.add_space(GROUP_GAP); - unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); option( ui, + &mut app.ui.mesh_recompute_normals, true, tr("Recompute vertex normals"), &[ tr("Replaces the mesh's vertex normals with newly computed ones in the exported file."), - tr("TextureCraft cannot do this yet: it writes the vertex normals the mesh has in the project."), + tr("On: smooth area-weighted normals from the exported geometry. Off: the project's stored normals. The project itself is not changed."), ], ); + ui.add_space(GROUP_GAP); + unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); ui.add_space(8.0); // One row keeps the window to its contents; a bare right-to-left layout fills the screen height @@ -76,12 +79,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -/// A greyed option under a choice, ticked as the reference shows it, with an info icon at the -/// row's right end whose tooltip has the paragraphs `info` -fn option(ui: &mut Ui, checked: bool, label: &str, info: &[&str]) { +/// An option under a choice, greyed when `enabled` is false, with an info icon at the row's right +/// end whose tooltip has the paragraphs `info`. +fn option(ui: &mut Ui, checked: &mut bool, enabled: bool, label: &str, info: &[&str]) { ui.horizontal(|ui| { ui.add_space(OPTION_INDENT); - unavailable::checkbox(ui, checked, label); + if enabled { + ui.checkbox(checked, label); + } else { + unavailable::checkbox(ui, *checked, label); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let icon = ui.label(egui::RichText::new(egui_phosphor::regular::INFO).color(Tokens::get(ui.ctx()).text_dim)); icon.on_hover_ui(|ui| { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 11be5a36..54daa752 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -588,6 +588,10 @@ pub struct UiState { /// Window ▸ Hide UI (Tab): only the viewport. pub hide_ui: bool, pub windows: Windows, + /// Mesh Export Options: compute smooth normals on the exported copy, not the project. + /// Off by default so an export keeps the project's authored normals unless the user opts in. + #[serde(default)] + pub mesh_recompute_normals: bool, pub uv_zoom: f32, pub uv_pan: [f32; 2], /// The 2D view's turn, counter-clockwise on screen in radians (Alt+left drag) @@ -763,6 +767,7 @@ impl UiState { } self.export = keep.export; + self.mesh_recompute_normals = keep.mesh_recompute_normals; self.recent = keep.recent; self.last_template = keep.last_template; self.prefs = keep.prefs; @@ -802,6 +807,7 @@ impl Default for UiState { selected_baked_map: None, hide_ui: false, windows: Windows::default(), + mesh_recompute_normals: false, uv_zoom: 1.0, uv_pan: [0.0, 0.0], uv_rotation: 0.0, @@ -884,6 +890,15 @@ mod tests { assert_eq!(crate::start_ui(None, &mut session).prefs.language, crate::i18n::SYSTEM_LANGUAGE); } + #[test] + fn mesh_export_normal_choice_defaults_off_for_older_saved_states() { + assert!(!UiState::default().mesh_recompute_normals); + let mut saved = serde_json::to_value(UiState::default()).unwrap(); + saved.as_object_mut().unwrap().remove("mesh_recompute_normals"); + let loaded: UiState = serde_json::from_value(saved).unwrap(); + assert!(!loaded.mesh_recompute_normals, "older states keep the project's stored normals unless the user opts in"); + } + #[test] fn adopting_a_layout_keeps_recent_files_and_user_settings() { use crate::frame_gizmo::warp_toolbar::{GizmoMode, GizmoSpace, WarpToolbarSettings}; @@ -893,7 +908,9 @@ mod tests { ui.warp_toolbar = warp_toolbar; ui.export.preset = "Mine".into(); ui.keymap.insert("file.save".into(), "F5".into()); + ui.mesh_recompute_normals = false; let mut layout = UiState::default(); + layout.mesh_recompute_normals = true; layout.dock.close(crate::docking::Panel::Assets); ui.adopt_layout(layout); @@ -902,6 +919,7 @@ mod tests { assert_eq!(ui.recent, vec!["a.tcraft".to_string()]); assert_eq!(ui.export.preset, "Mine"); assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5")); + assert!(!ui.mesh_recompute_normals, "a layout does not change the user's export setting"); assert_eq!(ui.warp_toolbar, warp_toolbar, "loading a layout keeps the user's warp settings"); } diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 02a17d8c..fd256356 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -337,9 +337,9 @@ mod web { pub fn export_mesh(app: &mut TextureCraftApp, ext: &str) { let name = format!("{}.{ext}", sanitize_file_stem(&app.session.doc.project.name)); let bytes = match ext { - "glb" => app.session.mesh_glb_bytes(), - "usdz" => app.session.mesh_usd(texturecraft_engine::formats::UsdFormat::Usdz).map(|u| u.bytes), - _ => app.session.mesh_obj_bytes(), + "glb" => app.session.mesh_glb_bytes_with_normals(app.ui.mesh_recompute_normals), + "usdz" => app.session.mesh_usd_with_normals(texturecraft_engine::formats::UsdFormat::Usdz, app.ui.mesh_recompute_normals).map(|u| u.bytes), + _ => app.session.mesh_obj_bytes_with_normals(app.ui.mesh_recompute_normals), }; match bytes.map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) { Ok(()) => app.toast(trf("Downloaded {name}", &[("name", &name)]), false), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 398c3871..09a61b17 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -631,7 +631,8 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> .file_name(name); app.ask_file(dialog, Bound::Project, |app, paths| { if let Some(path) = paths.first() - && let Some(result) = app.run("file.exportMesh", json!({"path": path.display().to_string()})) + && let Some(result) = + app.run("file.exportMesh", json!({"path": path.display().to_string(), "recomputeNormals": app.ui.mesh_recompute_normals})) { let saved_path = result["path"].as_str().unwrap_or_default(); app.toast(trf("Exported mesh to {path}", &[("path", &saved_path)]), false); diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 76962df4..399a5161 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -177,6 +177,31 @@ fn export_mesh_asks_the_options_then_the_file() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn recompute_normals_is_an_enabled_keyboard_operable_checkbox() { + let mut harness = app(); + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "file.exportMesh"); + harness.run_steps(SETTLE_FRAMES); + let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"); + assert!(!checkbox.accesskit_node().is_disabled(), "the option is really available"); + assert!(!is_on(&checkbox), "stored normals are kept until the user opts in"); + assert!(!harness.state().ui.mesh_recompute_normals); + + checkbox.focus(); + harness.key_press(egui::Key::Space); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.mesh_recompute_normals, "Space changes the setting used by export"); + let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"); + assert!(is_on(&checkbox), "the accessibility tree reports the checked state"); + assert_eq!(checkbox.accesskit_node().label().as_deref(), Some("Recompute vertex normals")); + + checkbox.click(); + harness.run_steps(SETTLE_FRAMES); + assert!(!harness.state().ui.mesh_recompute_normals, "a pointer click turns it back off"); + assert!(!is_on(&harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"))); +} + /// Whether the Log lists `line` (the status bar under it repeats the last message) fn log_lists(harness: &Harness<'_, TextureCraftApp>, line: &str) -> bool { harness.query_all_by_label(line).any(|node| node.rect().bottom() < STATUS_BAR_TOP) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9053c4e3..b3ce3b4a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -390,7 +390,7 @@ With `rebuildUvs: true`, the project file saves the generated layout. Reopening | `project_save` | `{path?}` | `.tcraft` (appended if missing), relative to the write root | | `mesh_import` | `{path, resolution?}` | New project from .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl; a .gltf's buffers and images and a loose USD layer's textures are read from its folder | | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | -| `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | +| `mesh_export` | `{path, format?, recomputeNormals?}` | The mesh as obj, glb, usda, usdc or usdz below the write root; `recomputeNormals: true` writes smooth area-weighted normals on the exported copy (default false) (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | | `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); call it once per baked map file (the desktop app's `textureSet.meshMap.import`, which takes host paths, is refused through `command_run`) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | @@ -465,7 +465,7 @@ File access follows `--read-root` / `--write-root` as for MCP. | `project.save` | `{path?}` | | `mesh.import` | `{path, resolution?, name?}` | | `mesh.reimport` | `{path?, preserveStrokes?}` | -| `mesh.export` | `{path, format?}` | +| `mesh.export` | `{path, format?, recomputeNormals?}` | | `bake.mesh.add` | `{path, cage?}` | | `resource.import` | `{path}` | | `material.save` | `{path, layer?, name?}` | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7c074f95..73f4c393 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -71,8 +71,10 @@ that closes it back onto the bar; the float is saved with the UI state. with materials that refer to the exported textures; greyed in the browser), *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected for export"). *Export MaterialX* beside them is a TextureCraft addition: it adds `materialX: true` to the - export. The prompt's *With displacement/tessellation* choice and both option checkboxes are - greyed; TextureCraft exports the mesh as it is. + export. The prompt's *With displacement/tessellation* choice and *Apply triangulation* are greyed + (TextureCraft exports the mesh as it is, triangulated). *Recompute vertex normals* works and sits under + *Without displacement/tessellation*, off by default: it writes smooth area-weighted normals to the + exported copy only. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the samples so far and a note; it floats when first opened and is not opened by itself in Rendering mode), *Properties - Paint* while a project is open (other tools read "Properties - ",