From fa23ac2a27d0d509007695c77888bf5473c0dcc6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 21 Nov 2026 20:30:49 +0100 Subject: [PATCH 1/4] Allow rebuilding mesh UVs when creating a project --- crates/core/src/project.rs | 13 ++++++-- crates/engine/src/file_cmds.rs | 31 +++++++++++++------ crates/formats/src/mesh_import/abc/tests.rs | 6 ++-- crates/formats/src/mesh_import/mod.rs | 16 +++++++--- crates/formats/src/project_file/mod.rs | 12 +++++-- crates/formats/src/project_file/tests.rs | 2 +- crates/ui-egui/src/new_project_advanced.rs | 21 ++++++++++--- crates/ui-egui/src/project_form.rs | 1 + crates/ui-egui/src/state.rs | 4 +++ crates/ui-egui/tests/it/new_project_window.rs | 18 ++++++++--- docs/control-protocol.md | 4 +++ 11 files changed, 95 insertions(+), 33 deletions(-) diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index ce14606b..6981e2d0 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -9,12 +9,15 @@ use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, L pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; -/// Project file format. 3: bent normal maps are in tangent space (older files hold world-space ones). -pub const FORMAT_VERSION: u32 = 3; +/// Latest project file format that TextureCraft can read. +pub const FORMAT_VERSION: u32 = REBUILT_MESH_UVS_VERSION; /// First format whose baked bent normal maps are in tangent space pub const TANGENT_BENT_NORMAL_VERSION: u32 = 3; +/// First format that can reopen a project using rebuilt mesh UVs. +pub const REBUILT_MESH_UVS_VERSION: u32 = 4; + /// Maximum group nesting (also bounds recursion over hostile project files) pub const MAX_DEPTH: usize = 16; @@ -417,6 +420,9 @@ pub struct Project { /// it, so parts the file leaves unnamed get the same name (from it) as on import. #[serde(default, skip_serializing_if = "String::is_empty")] pub mesh_file: String, + /// Rebuild the UVs again when reading the mesh stored in the project. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub mesh_rebuild_uvs: bool, /// Where the mesh file was imported from (the project's "3D mesh path"). Reimport mesh reads /// it again from there, so edits made to the file since are picked up. Empty when unknown /// (built-in meshes, web imports, projects saved before it was kept). @@ -435,10 +441,11 @@ pub struct Project { impl Project { pub fn new(name: impl Into, mesh: impl Into) -> Project { Project { - format_version: FORMAT_VERSION, + format_version: TANGENT_BENT_NORMAL_VERSION, name: name.into(), mesh: mesh.into(), mesh_file: String::new(), + mesh_rebuild_uvs: false, mesh_path: String::new(), normal_format: NormalFormat::OpenGl, texture_sets: Vec::new(), diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f493093b..d75723f6 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "New project from a mesh file", [], None, - "{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}", + "{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), rebuildUvs?: bool (default false: auto-unwrap where needed), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}", always, new_from_mesh ), @@ -101,7 +101,7 @@ fn leaf_of(name: &str) -> String { /// with, so its unnamed parts keep their names (and the geometry masks that use them). fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result { let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("mesh"); - texturecraft_formats::import_mesh_bytes(&format!("{stem}.{ext}"), bytes).map_err(fe) + texturecraft_formats::mesh_import::import_mesh_bytes_with_uvs(&format!("{stem}.{ext}"), bytes, project.mesh_rebuild_uvs).map_err(fe) } impl Session { @@ -160,11 +160,16 @@ impl Session { /// [`Session::from_mesh_bytes`] with a UV tile mode (see [`Session::new_project_tiled`]). pub fn from_mesh_bytes_tiled(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option) -> Result { - Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles) + Self::from_mesh_bytes_with_uvs(file_name, bytes, resolution, name, uv_tiles, false) } - fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option) -> Result { - let imported = texturecraft_formats::import_mesh_bytes(file_name, &bytes).map_err(fe)?; + /// Create a project with an explicit choice to rebuild the imported mesh's UVs. + pub fn from_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option, rebuild_uvs: bool) -> Result { + Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles, rebuild_uvs) + } + + fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option, rebuild_uvs: bool) -> Result { + let imported = texturecraft_formats::mesh_import::import_mesh_bytes_with_uvs(file_name, &bytes, rebuild_uvs).map_err(fe)?; let extension = ext_of(file_name); let mut session = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{extension}"), None, resolution, uv_tiles)?; @@ -173,6 +178,7 @@ impl Session { source.shrink_to_fit(); session.mesh_source = Some((extension, source)); session.doc.project.mesh_file = leaf_of(file_name); + session.doc.project.mesh_rebuild_uvs = rebuild_uvs; session.doc.project.cameras = imported.cameras; session.log.warnings("Importer", imported.report.warnings); @@ -500,7 +506,7 @@ mod native { #[cfg(not(target_arch = "wasm32"))] pub use native::{absolute, open_path, read_mesh}; -/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the +/// `file.new {mesh, name?, resolution?, uvTiles?, rebuildUvs?, template?, importCameras?}`: a new project from the /// mesh file `mesh`, remembering its path for Reimport mesh. #[cfg(not(target_arch = "wasm32"))] fn new_from_mesh(session: &mut Session, params: &Value) -> Result { @@ -511,9 +517,11 @@ fn new_from_mesh(session: &mut Session, params: &Value) -> Result { let resolution = u64p(params, "resolution").or(template.as_ref().map(|template| u64::from(template.resolution))).unwrap_or(DEFAULT_RESOLUTION_PX); let name = strp(params, "name").map(str::to_string).unwrap_or_else(|| stem_of(path)); let uv_tiles = crate::commands::boolp(params, "uvTiles"); + let rebuild_uvs = crate::commands::boolp(params, "rebuildUvs").unwrap_or(false); let mesh_file = native::read_mesh("file.new", path)?; - let mut next = Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles)?; + let mut next = + Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles, rebuild_uvs)?; next.doc.project.mesh_path = native::absolute(path); next.log.warnings("Importer", mesh_file.warnings); if crate::commands::boolp(params, "importCameras") == Some(false) { @@ -576,7 +584,7 @@ fn reimport(s: &mut Session, p: &Value) -> Result { fn change_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "path", "file.changeMesh")?; let file = native::read_mesh("file.changeMesh", path)?; - let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?; + let reply = s.replace_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true), false)?; // Only after the swap succeeded: Reimport mesh and Save keep following the new file. s.doc.project.mesh_path = native::absolute(path); Ok(reply) @@ -594,9 +602,13 @@ impl Session { /// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies /// like `file.reimportMesh`: `{preserved?}`. pub fn reimport_mesh(&mut self, file: Option, preserve_strokes: bool) -> Result { + self.replace_mesh(file, preserve_strokes, self.doc.project.mesh_rebuild_uvs) + } + + fn replace_mesh(&mut self, file: Option, preserve_strokes: bool, rebuild_uvs: bool) -> Result { let (mesh, source, warnings, mesh_file) = match file { Some(f) => { - let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh; + let m = texturecraft_formats::mesh_import::import_mesh_bytes_with_uvs(&f.name, &f.bytes, rebuild_uvs).map_err(fe)?.mesh; (m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name)) } None => match &self.mesh_source { @@ -611,6 +623,7 @@ impl Session { if let Some((ext, _)) = &source { doc.project.mesh = format!("mesh.{ext}"); doc.project.mesh_file = mesh_file; + doc.project.mesh_rebuild_uvs = rebuild_uvs; } let mut next = Session::new(doc, mesh, source)?; next.log.warnings("Importer", warnings); diff --git a/crates/formats/src/mesh_import/abc/tests.rs b/crates/formats/src/mesh_import/abc/tests.rs index f94f497d..9eadd181 100644 --- a/crates/formats/src/mesh_import/abc/tests.rs +++ b/crates/formats/src/mesh_import/abc/tests.rs @@ -217,10 +217,10 @@ fn imports_polymesh_through_xforms_with_face_sets_uvs_and_normals() { assert!((p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0])).z > 0.0); } } - let mesh = finish(raw).unwrap().mesh; + let mesh = finish(raw, false).unwrap().mesh; assert_eq!(mesh.materials.len(), 3); // The strip alone keeps its indexed face-varying UVs: u = x / 2 in the file's own space. - let strip = finish(read(&sample_file(false)).unwrap()).unwrap(); + let strip = finish(read(&sample_file(false)).unwrap(), false).unwrap(); assert!(!strip.report.uvs_generated); for (p, uv) in strip.mesh.positions.iter().zip(&strip.mesh.uvs) { let local = (*p - Vec3::new(1.0, 2.0, 3.0)) / 2.0; @@ -332,7 +332,7 @@ fn truncated_and_corrupted_files_never_panic() { b[i] = (rng >> 32) as u8; } if let Ok(raw) = read(&b) { - let _ = finish(raw); + let _ = finish(raw, false); } } } diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 315e4337..06ab5d93 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -108,7 +108,7 @@ pub struct MeshReport { pub triangles: usize, pub vertices: usize, pub materials: usize, - /// The file had no UVs; they were generated by the automatic unwrap. + /// The UVs were generated by the automatic unwrap. pub uvs_generated: bool, /// Triangles with a UV outside 0..1. pub uv_out_of_range: usize, @@ -295,7 +295,12 @@ fn extension(file_name: &str) -> String { /// self-contained (see [`self_contained_mesh`]); OBJ material libraries are not read (usemtl /// names are). pub fn import_mesh_bytes(file_name: &str, bytes: &[u8]) -> Result { - finish(read(file_name, bytes)?) + import_mesh_bytes_with_uvs(file_name, bytes, false) +} + +/// Import mesh bytes, optionally rebuilding the UV layout even when the mesh already has UVs. +pub fn import_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], rebuild_uvs: bool) -> Result { + finish(read(file_name, bytes)?, rebuild_uvs) } /// Import a mesh file with the files it references next to it ([`read_mesh_file`]). @@ -491,12 +496,12 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { } /// Complete a raw mesh: submeshes, normals, UVs, tangents, validation and the report. -pub(crate) fn finish(mut raw: RawMesh) -> Result { +pub(crate) fn finish(mut raw: RawMesh, rebuild_uvs: bool) -> Result { let mut raw_cameras = std::mem::take(&mut raw.cameras); raw_cameras.truncate(MAX_CAMERAS); let (mut mesh, mut warnings, uvs) = geometry(raw)?; let uvs_generated = match uvs { - Some(uv) if uv.len() == mesh.positions.len() => { + Some(uv) if !rebuild_uvs && uv.len() == mesh.positions.len() => { if uv.iter().any(|v| !v.is_finite()) { warnings.push("non-finite UVs were replaced with 0".into()); } @@ -506,7 +511,8 @@ pub(crate) fn finish(mut raw: RawMesh) -> Result { } _ => { let charts = auto_unwrap(&mut mesh, UNWRAP_PADDING, UNWRAP_RESOLUTION)?; - warnings.push(format!("the mesh has no UVs; generated an automatic unwrap with {charts} charts")); + let reason = if rebuild_uvs { "rebuild UVs was selected" } else { "the mesh has no UVs" }; + warnings.push(format!("{reason}; generated an automatic unwrap with {charts} charts")); true } }; diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index c5bf3bdb..b86f8ec1 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -18,12 +18,13 @@ //! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture //! set cover its whole atlas (`resolution` per tile, see `TileGrid`). -use std::borrow::Borrow; +use std::borrow::{Borrow, Cow}; use std::collections::{BTreeMap, HashSet}; use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; use texturecraft_compose::{BakedMaps, PixelStore}; +use texturecraft_core::project::REBUILT_MESH_UVS_VERSION; use texturecraft_core::{BakePaintTarget, BakedMap, Channel, FORMAT_VERSION, LayerId, Project, TANGENT_BENT_NORMAL_VERSION}; use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; @@ -190,7 +191,12 @@ fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) fn entries(pf: &ProjectFile>>) -> Result>> { let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); - let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?; + let mut project = Cow::Borrowed(&pf.project); + // An older reader would load the authored UVs and put paint in the wrong places. + if project.mesh_rebuild_uvs && project.format_version < REBUILT_MESH_UVS_VERSION { + project.to_mut().format_version = REBUILT_MESH_UVS_VERSION; + } + let json = serde_json::to_vec_pretty(project.as_ref()).map_err(|e| FormatError::Invalid(e.to_string()))?; let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }]; if let Some((ext, bytes)) = &pf.mesh { out.push(Entry { @@ -505,7 +511,7 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) if version < TANGENT_BENT_NORMAL_VERSION { drop_world_space_bent_normals(&mut pf); } - pf.project.format_version = FORMAT_VERSION; + pf.project.format_version = version.max(TANGENT_BENT_NORMAL_VERSION); if recovered { pf.warnings.push( diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 4364f39e..a4cc5a34 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -104,7 +104,7 @@ fn legacy_bakes_load_as_is_without_layout_conversion() { sample.pf.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() }); let loaded = load_project_bytes(&save_project_bytes(&sample.pf).unwrap()).unwrap(); - assert_eq!(loaded.project.format_version, FORMAT_VERSION); + assert_eq!(loaded.project.format_version, TANGENT_BENT_NORMAL_VERSION); assert_eq!(loaded.baked, sample.pf.baked, "old bake pixels are accepted without preserving their former layout"); assert_eq!(loaded.bake_paint, sample.pf.bake_paint, "correction paint remains in the working layout"); let reopened = load_project_bytes(&save_project_bytes(&loaded).unwrap()).unwrap(); diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 2d079b67..690cb15e 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -13,8 +13,8 @@ use texturecraft_engine::template_cmds::template_label; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; use crate::project_form::{ - FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, - unavailable, uv_tile_radios, + FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, + uv_tile_radios, }; use crate::state::{Mode, NewProject}; use crate::theme::{Tokens, caption}; @@ -136,6 +136,7 @@ pub fn create_command(new_project: &NewProject) -> Option { "uvTiles": new_project.uv_tiles == Some(true), "template": new_project.template, "importCameras": new_project.import_cameras, + "rebuildUvs": new_project.rebuild_uvs, })) } @@ -154,7 +155,14 @@ fn create_project(app: &mut TextureCraftApp) -> bool { let stem = std::path::Path::new(name).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Untitled").to_string(); let template = app.session.template(&new_project.template); - match texturecraft_engine::Session::from_mesh_bytes_tiled(name, bytes, new_project.resolution, &stem, Some(new_project.uv_tiles == Some(true))) { + match texturecraft_engine::Session::from_mesh_bytes_with_uvs( + name, + bytes, + new_project.resolution, + &stem, + Some(new_project.uv_tiles == Some(true)), + new_project.rebuild_uvs, + ) { Ok(mut next) => { if !new_project.import_cameras { next.doc.project.cameras.clear(); @@ -249,7 +257,12 @@ fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(4.0); sub_title(ui, tr("Import settings"), None); check_row(ui, Some(tr("Keep the cameras stored in the mesh file")), |ui| ui.checkbox(&mut new_project.import_cameras, tr("Import cameras")), |_| {}); - auto_unwrap_row(ui); + check_row( + ui, + Some(tr("Generate a fresh UV layout even when the mesh already has UVs. Meshes without UVs are always unwrapped.")), + |ui| ui.checkbox(&mut new_project.rebuild_uvs, tr("Rebuild mesh UVs")), + |_| {}, + ); ui.add_space(4.0); collapsible(ui, "np_import_baked_maps", tr("Import baked maps"), true, None, |ui| { diff --git a/crates/ui-egui/src/project_form.rs b/crates/ui-egui/src/project_form.rs index 171282e3..d340a344 100644 --- a/crates/ui-egui/src/project_form.rs +++ b/crates/ui-egui/src/project_form.rs @@ -158,6 +158,7 @@ pub(crate) fn uv_tile_radios(ui: &mut Ui, enabled: bool, disabled_hint: &str) { /// Import settings ▸ Auto-unwrap and its options. Meshes without UVs are always unwrapped, so the /// box is ticked; turning it off and the options are not available yet. +#[cfg(not(target_arch = "wasm32"))] pub(crate) fn auto_unwrap_row(ui: &mut Ui) { check_row( ui, diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c5dffbc9..05fd1b33 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -289,6 +289,9 @@ pub struct NewProject { /// Import settings > Import cameras: keep the cameras stored in the mesh file #[serde(default = "import_cameras_default")] pub import_cameras: bool, + /// Import settings > Rebuild mesh UVs. + #[serde(default)] + pub rebuild_uvs: bool, /// Color management as chosen in the window (the project is always created as Legacy) #[serde(skip)] pub color_management: crate::project_form::ColorManagement, @@ -326,6 +329,7 @@ impl Default for NewProject { template: default_template(), normal_format: None, import_cameras: true, + rebuild_uvs: false, color_management: crate::project_form::ColorManagement::Legacy, baked_maps: Vec::new(), } diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs index 7d95b501..aafec044 100644 --- a/crates/ui-egui/tests/it/new_project_window.rs +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -119,7 +119,7 @@ fn the_sections_follow_the_project_setup_order() { "Use a separate texture set for each tile", "Import settings", "Import cameras", - "Auto-unwrap", + "Rebuild mesh UVs", "Import baked maps", "Import mesh normal maps and baked maps for all materials.", "Normal map filename: _normal", @@ -151,7 +151,7 @@ fn the_defaults_match_the_reference() { assert!(ticked(&h, Role::RadioButton, "Keep UV tiles together per material")); assert!(disabled(&h, Role::RadioButton, "Keep UV tiles together per material"), "greyed while UV tiles are off"); assert!(ticked(&h, Role::CheckBox, "Import cameras") && !disabled(&h, Role::CheckBox, "Import cameras")); - assert!(ticked(&h, Role::CheckBox, "Auto-unwrap")); + assert!(!ticked(&h, Role::CheckBox, "Rebuild mesh UVs") && !disabled(&h, Role::CheckBox, "Rebuild mesh UVs")); assert!(ticked(&h, Role::RadioButton, "Use the mesh file’s unit scale")); assert!(!ticked(&h, Role::CheckBox, "Scale material fills in real-world units")); } @@ -186,8 +186,6 @@ fn settings_not_available_yet_are_disabled_with_a_hint() { let unavailable = [ (Role::CheckBox, "Compute tangent space per fragment"), (Role::RadioButton, "Use a separate texture set for each tile"), - (Role::CheckBox, "Auto-unwrap"), - (Role::Button, "Auto-unwrap options"), (Role::RadioButton, "Custom unit scale"), (Role::CheckBox, "Scale material fills in real-world units"), ]; @@ -326,7 +324,7 @@ fn the_supported_settings_reach_the_create_command() { #[test] fn ticking_uv_tiles_creates_a_uv_tile_project() { - for (tick, expected) in [(false, Vec::::new()), (true, vec![1002])] { + for (tick, rebuild_uvs, expected) in [(false, false, vec![]), (true, false, vec![1002]), (true, true, vec![1001])] { let mut h = harness(); let dir = TempDir::new("new-project-udim"); h.state_mut().ui.new_project.file = Some(mesh_file(&dir, TILE_1002_QUAD)); @@ -337,6 +335,10 @@ fn ticking_uv_tiles_creates_a_uv_tile_project() { h.run_steps(3); assert!(!disabled(&h, Role::RadioButton, "Keep UV tiles together per material")); } + if rebuild_uvs { + h.get_by_role_and_label(Role::CheckBox, "Rebuild mesh UVs").click(); + h.run_steps(3); + } h.get_by_role_and_label(Role::CheckBox, "Import cameras").click(); h.run_steps(2); h.get_by_role_and_label(Role::Button, "Create").click(); @@ -347,6 +349,12 @@ fn ticking_uv_tiles_creates_a_uv_tile_project() { assert_eq!(app.session.doc.project.name, "tiles"); assert_eq!(app.session.doc.project.texture_sets[0].uv_tiles, expected, "UV tiles ticked: {tick}"); assert_eq!(app.session.doc.project.texture_sets[0].resolution, 128); + if rebuild_uvs { + let bytes = texturecraft_engine::formats::save_project_bytes(&app.session.project_file()).unwrap(); + let reopened = texturecraft_engine::Session::from_project_bytes(&bytes).unwrap(); + assert_eq!(reopened.source_mesh().uvs, app.session.source_mesh().uvs); + assert_eq!(reopened.doc.project.format_version, texturecraft_engine::core::project::REBUILT_MESH_UVS_VERSION); + } } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bd11cb2d..979544a1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -295,6 +295,10 @@ takes a font family, not a path: it reads only the system's font folders. `file.close` leaves no project open: `session.inspect` then reports `projectOpen: false`, `command.list` marks every command but the project-independent ones as not enabled: the ones that open or create a project (`file.open`, `file.new`, `project.new`, `project.sample`), `project.inspect`, `viewport.frame`, `project.templates`, the `export.preset*` commands (`export.presets`, `export.preset.get`, `export.preset.save`, `export.preset.remove`) and the library and preset listings (`brush.preset.list`, `alpha.list`, `filter.list`, `material.list`, `mask.smart.list`, `text.fonts`), each still subject to its own enabled check. The rest are refused with "no project is open" until a project is opened or created. A `texturecraft --control` run starts with the sample project (an empty material ball with `--empty`); the app without `--control` starts with no project. +The desktop control channel accepts `rebuildUvs: true` on `file.new` to generate a new UV layout. +The default keeps a complete authored layout and unwraps meshes that need UVs. The project +remembers the rebuild choice for reopening and reimporting its mesh. + | Tool | Params | Notes | |---|---|---| | `session_inspect` | | The whole session as JSON | From 8f60ded96fae1231ccac874746c286b984c48b49 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:42:46 +0100 Subject: [PATCH 2/4] Save the rebuilt UV layout in the project file A project with rebuilt mesh UVs now stores the UV of every triangle corner in uv_layout.bin. Reopening and reimporting the project's own mesh apply that layout instead of running the unwrapper again, so a later unwrapper change cannot move saved paint. A format 4 project with rebuilt UVs but no valid layout is refused. --- crates/core/src/project.rs | 3 +- crates/engine/src/file_cmds.rs | 24 +++++-- crates/engine/src/material_lib.rs | 1 + crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/rebuilt_uv_layout.rs | 57 +++++++++++++++ crates/formats/src/mesh_import/mod.rs | 64 ++++++++++++++++- crates/formats/src/mesh_import/tests.rs | 17 +++++ crates/formats/src/project_file/mod.rs | 23 ++++++ crates/formats/src/project_file/tests.rs | 53 ++++++++++++++ crates/formats/src/project_file/uv_layout.rs | 73 ++++++++++++++++++++ docs/control-protocol.md | 5 +- docs/features.md | 2 +- 12 files changed, 311 insertions(+), 12 deletions(-) create mode 100644 crates/engine/tests/it/rebuilt_uv_layout.rs create mode 100644 crates/formats/src/project_file/uv_layout.rs diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index c7830075..ac33411a 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -432,7 +432,8 @@ pub struct Project { /// it, so parts the file leaves unnamed get the same name (from it) as on import. #[serde(default, skip_serializing_if = "String::is_empty")] pub mesh_file: String, - /// Rebuild the UVs again when reading the mesh stored in the project. + /// The mesh UVs were rebuilt on import. The project file keeps the generated layout for + /// reopening; reimporting the mesh from a file rebuilds them again. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub mesh_rebuild_uvs: bool, /// Where the mesh file was imported from (the project's "3D mesh path"). Reimport mesh reads diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index d75723f6..8df6928b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -10,6 +10,7 @@ use serde_json::{Value, json}; use texturecraft_core::{NormalFormat, PROJECT_EXT}; use texturecraft_core::{Project, TextureSet}; use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile}; +use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Mesh, primitives}; use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p}; @@ -98,10 +99,15 @@ fn leaf_of(name: &str) -> String { } /// Read the project's stored mesh `bytes` (extension `ext`) under the name it was imported -/// with, so its unnamed parts keep their names (and the geometry masks that use them). -fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result { +/// with, so its unnamed parts keep their names (and the geometry masks that use them). A saved +/// UV layout replaces the file's UVs and the automatic unwrap. +fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Option<&[Vec2]>) -> Result { let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("mesh"); - texturecraft_formats::mesh_import::import_mesh_bytes_with_uvs(&format!("{stem}.{ext}"), bytes, project.mesh_rebuild_uvs).map_err(fe) + let file_name = format!("{stem}.{ext}"); + match saved_layout { + Some(layout) => texturecraft_formats::mesh_import::import_mesh_bytes_with_layout(&file_name, bytes, layout).map_err(fe), + None => texturecraft_formats::mesh_import::import_mesh_bytes_with_uvs(&file_name, bytes, project.mesh_rebuild_uvs).map_err(fe), + } } impl Session { @@ -205,7 +211,7 @@ impl Session { pub fn from_project_file(pf: ProjectFile) -> Result { let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) { (_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?, - (Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh, + (Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes, pf.mesh_uvs.as_deref())?.mesh, (None, None) => return Err(EngineError::Other("the project has no mesh".into())), }; @@ -234,6 +240,11 @@ impl Session { self.project_with_resources(self.doc.resources.clone()) } + /// The layout a project with rebuilt mesh UVs saves, so reopening it never runs the unwrapper. + fn saved_uv_layout(&self) -> Option> { + (self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then(|| texturecraft_formats::mesh_import::corner_uvs(&self.source)) + } + fn project_with_resources(&self, resources: BTreeMap) -> ProjectFile { let mut pixels = self.doc.pixels.clone(); @@ -257,6 +268,7 @@ impl Session { pixels, baked: self.doc.baked.clone(), mesh: self.mesh_source.clone(), + mesh_uvs: self.saved_uv_layout(), high_poly, cage, bake_paint: self.saved_bake_paint(), @@ -613,7 +625,9 @@ impl Session { } None => match &self.mesh_source { Some((ext, bytes)) => { - (read_stored_mesh(&self.doc.project, ext, bytes)?.mesh, self.mesh_source.clone(), Vec::new(), self.doc.project.mesh_file.clone()) + let layout = self.saved_uv_layout(); + let mesh = read_stored_mesh(&self.doc.project, ext, bytes, layout.as_deref())?.mesh; + (mesh, self.mesh_source.clone(), Vec::new(), self.doc.project.mesh_file.clone()) } None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")), }, diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 678d7bb7..84c3b3f8 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -97,6 +97,7 @@ impl Session { pixels: mini.pixels, baked: BTreeMap::new(), mesh: None, + mesh_uvs: None, high_poly: Vec::new(), cage: None, bake_paint: BTreeMap::new(), diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c38e850b..d2e219dd 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -55,6 +55,7 @@ mod pbr_import; mod perf; mod polygon_fill; mod project_recovery; +mod rebuilt_uv_layout; mod resources_used; mod sample; mod solo; diff --git a/crates/engine/tests/it/rebuilt_uv_layout.rs b/crates/engine/tests/it/rebuilt_uv_layout.rs new file mode 100644 index 00000000..805fe1de --- /dev/null +++ b/crates/engine/tests/it/rebuilt_uv_layout.rs @@ -0,0 +1,57 @@ +use std::io::{Cursor, Write}; + +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_engine::formats::mesh_import::{corner_uvs, import_mesh_bytes_with_uvs}; +use texturecraft_engine::geom::glam::Vec2; +use zip::{ZipWriter, write::SimpleFileOptions}; + +const QUAD_OBJ: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n"; + +/// A layout no unwrapper of this build makes: the quad turned a quarter and inset, per corner +const LOCKED_LAYOUT: [[f32; 2]; 6] = [[0.9, 0.1], [0.9, 0.9], [0.1, 0.9], [0.9, 0.1], [0.1, 0.9], [0.1, 0.1]]; + +/// `uv_layout.bin` written by hand: magic, version 1, corner count, then u and v per corner +fn layout_entry(layout: &[[f32; 2]]) -> Vec { + let mut bytes = b"TCUV".to_vec(); + bytes.extend(1u32.to_le_bytes()); + bytes.extend(u32::try_from(layout.len()).unwrap().to_le_bytes()); + for [u, v] in layout { + bytes.extend(u.to_le_bytes()); + bytes.extend(v.to_le_bytes()); + } + bytes +} + +/// A format 4 archive of the quad with rebuilt UVs and the locked layout +fn locked_archive() -> Vec { + let session = Session::from_mesh_bytes_with_uvs("quad.obj", QUAD_OBJ.as_bytes(), 128, "quad", None, true).unwrap(); + let mut project = serde_json::to_value(&session.doc.project).unwrap(); + project["format_version"] = json!(4); + + let mut archive = ZipWriter::new(Cursor::new(Vec::new())); + for (name, bytes) in + [("project.json", serde_json::to_vec(&project).unwrap()), ("mesh.obj", QUAD_OBJ.as_bytes().to_vec()), ("uv_layout.bin", layout_entry(&LOCKED_LAYOUT))] + { + archive.start_file(name, SimpleFileOptions::default()).unwrap(); + archive.write_all(&bytes).unwrap(); + } + archive.finish().unwrap().into_inner() +} + +#[test] +fn a_rebuilt_project_reopens_with_its_saved_uv_layout_not_a_new_unwrap() { + let locked: Vec = LOCKED_LAYOUT.iter().map(|uv| Vec2::from_array(*uv)).collect(); + let unwrapped = import_mesh_bytes_with_uvs("quad.obj", QUAD_OBJ.as_bytes(), true).unwrap().mesh; + + let mut reopened = Session::from_project_bytes(&locked_archive()).unwrap(); + let opened_layout = corner_uvs(&reopened.source_mesh()); + reopened.reimport_mesh(None, false).unwrap(); + let reimported_layout = corner_uvs(&reopened.source_mesh()); + let resaved = Session::from_project_bytes(&reopened.to_project_bytes().unwrap()).unwrap(); + + assert_ne!(corner_uvs(&unwrapped), locked, "the locked layout differs from what the unwrapper makes now"); + assert_eq!(opened_layout, locked); + assert_eq!(reimported_layout, locked, "reimporting the project's own mesh keeps the saved layout"); + assert_eq!(corner_uvs(&resaved.source_mesh()), locked, "saving again keeps the layout"); +} diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 06ab5d93..f9eed9d6 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -303,6 +303,19 @@ pub fn import_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], rebuild_uvs: bo finish(read(file_name, bytes)?, rebuild_uvs) } +/// Import mesh bytes with a saved UV layout ([`corner_uvs`] of the mesh as first imported) +/// instead of the file's UVs or the automatic unwrap, so the layout does not depend on the +/// unwrapper of the running version. +pub fn import_mesh_bytes_with_layout(file_name: &str, bytes: &[u8], corner_uvs: &[Vec2]) -> Result { + finish_with_layout(read(file_name, bytes)?, false, Some(corner_uvs)) +} + +/// The UV of every triangle corner, in index order: a layout that [`import_mesh_bytes_with_layout`] +/// applies to the same mesh file again. +pub fn corner_uvs(mesh: &Mesh) -> Vec { + mesh.indices.iter().map(|index| mesh.uvs.get(*index as usize).copied().unwrap_or_default()).collect() +} + /// Import a mesh file with the files it references next to it ([`read_mesh_file`]). #[cfg(not(target_arch = "wasm32"))] pub fn import_mesh(path: &std::path::Path) -> Result { @@ -496,12 +509,21 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { } /// Complete a raw mesh: submeshes, normals, UVs, tangents, validation and the report. -pub(crate) fn finish(mut raw: RawMesh, rebuild_uvs: bool) -> Result { +pub(crate) fn finish(raw: RawMesh, rebuild_uvs: bool) -> Result { + finish_with_layout(raw, rebuild_uvs, None) +} + +/// [`finish`] with an optional saved UV layout that replaces both the file's UVs and the unwrap. +fn finish_with_layout(mut raw: RawMesh, rebuild_uvs: bool, saved_layout: Option<&[Vec2]>) -> Result { let mut raw_cameras = std::mem::take(&mut raw.cameras); raw_cameras.truncate(MAX_CAMERAS); let (mut mesh, mut warnings, uvs) = geometry(raw)?; - let uvs_generated = match uvs { - Some(uv) if !rebuild_uvs && uv.len() == mesh.positions.len() => { + let uvs_generated = match (saved_layout, uvs) { + (Some(layout), _) => { + apply_corner_uvs(&mut mesh, layout)?; + true + } + (None, Some(uv)) if !rebuild_uvs && uv.len() == mesh.positions.len() => { if uv.iter().any(|v| !v.is_finite()) { warnings.push("non-finite UVs were replaced with 0".into()); } @@ -522,6 +544,42 @@ pub(crate) fn finish(mut raw: RawMesh, rebuild_uvs: bool) -> Result Result<()> { + if layout.len() != mesh.indices.len() { + return Err(FormatError::Invalid(format!("the saved UV layout has {} corners but the mesh has {}", layout.len(), mesh.indices.len()))); + } + if layout.iter().any(|uv| !uv.is_finite()) { + return Err(FormatError::Invalid("the saved UV layout has non-finite UVs".into())); + } + + let mut vertex_of: HashMap<(u32, [u32; 2]), u32> = HashMap::with_capacity(mesh.positions.len() * 2); + let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut indices = Vec::with_capacity(mesh.indices.len()); + for (&vertex, &uv) in mesh.indices.iter().zip(layout) { + let index = *vertex_of.entry((vertex, [uv.x.to_bits(), uv.y.to_bits()])).or_insert_with(|| { + let source = vertex as usize; + positions.push(mesh.positions.get(source).copied().unwrap_or_default()); + normals.push(mesh.normals.get(source).copied().unwrap_or(Vec3::Y)); + if let Some(color) = mesh.colors.get(source) { + colors.push(*color); + } + uvs.push(uv); + (positions.len() - 1) as u32 + }); + indices.push(index); + } + + mesh.positions = positions; + mesh.normals = normals; + mesh.uvs = uvs; + mesh.colors = colors; + mesh.indices = indices; + mesh.compute_tangents(); + Ok(()) +} + /// File cameras as orbit cameras: the target is where the view axis passes the mesh center /// (at least a tenth of the mesh size ahead). shortcut: camera roll is dropped (orbit cameras /// keep +Y up); keep a free camera transform if imported rolls matter. diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index 0cfbae61..e61ba7b9 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -757,3 +757,20 @@ fn duplicate_gltf_material_names_keep_first_wins_and_order() { } assert_eq!(color_by_material.get("Dup").unwrap().factor, Vec4::new(1.0, 0.0, 0.0, 1.0)); } + +#[test] +fn a_saved_layout_reproduces_the_rebuilt_mesh_without_unwrapping() { + let rebuilt = import_mesh_bytes_with_uvs("a.obj", OBJ.as_bytes(), true).unwrap().mesh; + let layout = corner_uvs(&rebuilt); + + let reopened = import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &layout).unwrap(); + let short = import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &layout[1..]); + let mut non_finite = layout.clone(); + non_finite[0].x = f32::NAN; + + assert!(!reopened.report.warnings.iter().any(|warning| warning.contains("unwrap")), "{:?}", reopened.report.warnings); + assert_eq!((&reopened.mesh.positions, &reopened.mesh.indices, &reopened.mesh.uvs), (&rebuilt.positions, &rebuilt.indices, &rebuilt.uvs)); + assert_eq!(reopened.mesh.normals, rebuilt.normals); + assert!(short.is_err(), "a layout for another mesh is refused"); + assert!(import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &non_finite).is_err()); +} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index b86f8ec1..2f8b1d67 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -4,6 +4,7 @@ //! |---|---| //! | `project.json` | serde JSON of [`Project`] | //! | `mesh.` | the original imported mesh file (absent for built-in meshes, `Project.mesh = "builtin:"`) | +//! | `uv_layout.bin` | the UV of every triangle corner of a mesh whose UVs were rebuilt (format 4+, see `uv_layout`) | //! | `highpoly/` | a high-definition mesh file for baking, in list order | //! | `cage/` | the baking cage mesh file | //! | `bake_paint/_.bin` | cage or skew paint, stored as a one-component baked map | @@ -26,12 +27,14 @@ use std::sync::Arc; use texturecraft_compose::{BakedMaps, PixelStore}; use texturecraft_core::project::REBUILT_MESH_UVS_VERSION; use texturecraft_core::{BakePaintTarget, BakedMap, Channel, FORMAT_VERSION, LayerId, Project, TANGENT_BENT_NORMAL_VERSION}; +use texturecraft_geom::glam::Vec2; use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; use self::entries::Entry; use self::load_budget::LoadBudget; +use self::uv_layout::{MAX_UV_LAYOUT_BYTES, UV_LAYOUT_ENTRY, read_uv_layout, uv_layout_bytes, write_uv_layout}; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; mod entries; @@ -39,6 +42,7 @@ mod load_budget; mod project_open_limit; mod ram_operation; mod ram_reservation; +mod uv_layout; #[cfg(not(target_arch = "wasm32"))] pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, configured_ram_budget, save_ram_budget, set_save_resources}; pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; @@ -73,6 +77,9 @@ pub struct ProjectFile> { pub baked: BTreeMap, /// Original mesh file: (extension, bytes). pub mesh: Option<(String, Vec)>, + /// Saved UV layout of `mesh` when its UVs were rebuilt: the UV of every triangle corner, in + /// index order, as the mesh was first imported. + pub mesh_uvs: Option>, /// High-definition mesh files for baking: (file name, bytes). Names are /// [`sanitize_resource_name`]d on save. pub high_poly: Vec<(String, Vec)>, @@ -206,6 +213,14 @@ fn entries(pf: &ProjectFile>>) -> Result>> { body: Box::new(move |w| w.write_all(bytes)), }); } + if let Some(layout) = &pf.mesh_uvs { + out.push(Entry { + name: UV_LAYOUT_ENTRY.into(), + options: deflate, + weight: uv_layout_bytes(layout.len()), + body: Box::new(move |w| write_uv_layout(w, layout)), + }); + } let mut used = HashSet::new(); for (dir, (name, bytes)) in pf.high_poly.iter().map(|m| ("highpoly", m)).chain(pf.cage.iter().map(|m| ("cage", m))) { out.push(Entry { @@ -416,6 +431,7 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) pixels: PixelStore::default(), baked: BTreeMap::new(), mesh: None, + mesh_uvs: None, high_poly: Vec::new(), cage: None, bake_paint: BTreeMap::new(), @@ -468,6 +484,9 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) } else if let Some(ext) = name.strip_prefix("mesh.").filter(|e| !e.contains('/')) { let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?; pf.mesh = Some((ext.to_string(), bytes)); + } else if name == UV_LAYOUT_ENTRY { + let bytes = read_all(&mut f, MAX_UV_LAYOUT_BYTES, &mut budget, &name)?; + pf.mesh_uvs = Some(read_uv_layout(&bytes)?); } else if let Some(rest) = name.strip_prefix("pixels/layer_").and_then(|r| r.strip_suffix(".bin")) { let (id, chan) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; let id = LayerId(id.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?); @@ -508,6 +527,10 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) } } + // Rerunning the unwrapper could lay the saved paint over a different layout + if pf.project.mesh_rebuild_uvs && pf.mesh.is_some() && pf.mesh_uvs.is_none() { + return Err(malformed(KIND, "the mesh UVs were rebuilt but the project holds no saved UV layout")); + } if version < TANGENT_BENT_NORMAL_VERSION { drop_world_space_bent_normals(&mut pf); } diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index a4cc5a34..2bf55a31 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -32,6 +32,7 @@ fn sample() -> Sample { pixels, baked: [(0, baked)].into(), mesh: Some(("glb".into(), vec![1, 2, 3, 4, 5])), + mesh_uvs: None, high_poly: vec![("b_high.obj".into(), vec![7; 9]), ("a_high.ply".into(), vec![6])], cage: Some(("cage.obj".into(), vec![5, 5])), bake_paint: [((0, texturecraft_core::BakePaintTarget::Skew), BakePaintData { width: 3, height: 2, values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125] })] @@ -55,6 +56,7 @@ fn assert_same(a: &ProjectFile, b: &ProjectFile) { } assert_eq!(a.baked, b.baked); assert_eq!(a.mesh, b.mesh); + assert_eq!(a.mesh_uvs, b.mesh_uvs); assert_eq!((&a.high_poly, &a.cage), (&b.high_poly, &b.cage), "bake meshes keep their order"); assert_eq!(a.bake_paint, b.bake_paint); assert_eq!(a.thumbnail, b.thumbnail); @@ -920,3 +922,54 @@ fn zip64_entry_counts_remain_supported_and_bounded() { } } } + +fn rebuilt_uvs_sample() -> ProjectFile { + let mut project_file = sample().pf; + project_file.project.mesh_rebuild_uvs = true; + project_file.mesh_uvs = Some(vec![Vec2::new(0.25, 0.75), Vec2::new(1.0, 0.0), Vec2::new(0.5, 0.125)]); + project_file +} + +#[test] +fn a_saved_uv_layout_round_trips_in_format_4() { + let project_file = rebuilt_uvs_sample(); + + let loaded = load_project_bytes(&save_project_bytes(&project_file).unwrap()).unwrap(); + + assert_eq!(loaded.mesh_uvs, project_file.mesh_uvs); + assert_eq!(loaded.project.format_version, REBUILT_MESH_UVS_VERSION); +} + +#[test] +fn rebuilt_uvs_without_a_valid_saved_layout_are_refused() { + let project_file = rebuilt_uvs_sample(); + let without_layout = edit_archive(&project_file, |name, _| { + if name == UV_LAYOUT_ENTRY { + *name = "ignored.bin".into(); + } + }); + let edited_layout = |edit: fn(&mut Vec)| { + edit_archive(&project_file, |name, data| { + if name == UV_LAYOUT_ENTRY { + edit(data); + } + }) + }; + let truncated = edited_layout(|data| data.truncate(data.len() - 1)); + let short_header = edited_layout(|data| data.truncate(8)); + let wrong_count = edited_layout(|data| data[8] = 9); + let non_finite = edited_layout(|data| data[12..16].copy_from_slice(&f32::NAN.to_le_bytes())); + let bad_magic = edited_layout(|data| data[0] = b'X'); + + for (case, bytes) in [ + ("missing", without_layout), + ("truncated", truncated), + ("short header", short_header), + ("wrong count", wrong_count), + ("non-finite", non_finite), + ("bad magic", bad_magic), + ] { + let error = load_project_bytes(&bytes).unwrap_err(); + assert!(!is_guard_error(&error), "{case}: {error}"); + } +} diff --git a/crates/formats/src/project_file/uv_layout.rs b/crates/formats/src/project_file/uv_layout.rs new file mode 100644 index 00000000..cf6a638c --- /dev/null +++ b/crates/formats/src/project_file/uv_layout.rs @@ -0,0 +1,73 @@ +//! `uv_layout.bin`: the UVs of a mesh whose layout was rebuilt on import, so reopening does not +//! depend on the unwrapper of the running version. A header (magic `TCUV`, version, corner count; +//! u32 LE each) is followed by `u`, `v` (f32 LE) for every triangle corner in index order. + +use std::io::Write; + +use texturecraft_geom::MAX_TRIANGLES; +use texturecraft_geom::glam::Vec2; + +use super::KIND; +use crate::{Result, malformed}; + +/// Zip entry name of the saved layout. +pub const UV_LAYOUT_ENTRY: &str = "uv_layout.bin"; + +const UV_LAYOUT_MAGIC: &[u8; 4] = b"TCUV"; +const UV_LAYOUT_VERSION: u32 = 1; +const HEADER_BYTES: usize = 12; +const CORNER_BYTES: usize = 8; + +/// Largest entry a valid mesh can need: every corner of the most triangles accepted. +pub const MAX_UV_LAYOUT_BYTES: u64 = (HEADER_BYTES + MAX_TRIANGLES * 3 * CORNER_BYTES) as u64; + +/// Encoded size of a layout of `corners` UVs. +pub fn uv_layout_bytes(corners: usize) -> u64 { + (HEADER_BYTES + corners * CORNER_BYTES) as u64 +} + +pub fn write_uv_layout(w: &mut dyn Write, layout: &[Vec2]) -> std::io::Result<()> { + let corners = u32::try_from(layout.len()).map_err(|_| std::io::Error::other("the UV layout has too many corners"))?; + w.write_all(UV_LAYOUT_MAGIC)?; + w.write_all(&UV_LAYOUT_VERSION.to_le_bytes())?; + w.write_all(&corners.to_le_bytes())?; + + let mut body = Vec::with_capacity(layout.len() * CORNER_BYTES); + for uv in layout { + body.extend_from_slice(&uv.x.to_le_bytes()); + body.extend_from_slice(&uv.y.to_le_bytes()); + } + w.write_all(&body) +} + +/// Decode an entry; a wrong header, size or a non-finite UV is an error. +pub fn read_uv_layout(bytes: &[u8]) -> Result> { + let bad = |why: &str| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {why}")); + let Some((header, body)) = bytes.split_first_chunk::() else { return Err(bad("truncated header")) }; + let [magic, version, corners] = header.as_chunks::<4>().0 else { return Err(bad("truncated header")) }; + + if magic != UV_LAYOUT_MAGIC { + return Err(bad("bad magic")); + } + if u32::from_le_bytes(*version) != UV_LAYOUT_VERSION { + return Err(bad("unsupported version")); + } + let corners = u32::from_le_bytes(*corners) as usize; + if corners.checked_mul(CORNER_BYTES) != Some(body.len()) { + return Err(bad("the corner count does not match the entry size")); + } + + let layout: Vec = body + .as_chunks::() + .0 + .iter() + .map(|corner| { + let (u, v) = corner.split_at(4); + Vec2::new(f32::from_le_bytes(u.try_into().unwrap_or_default()), f32::from_le_bytes(v.try_into().unwrap_or_default())) + }) + .collect(); + if layout.iter().any(|uv| !uv.is_finite()) { + return Err(bad("non-finite UVs")); + } + Ok(layout) +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 878f1ba7..0754f7c1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -318,8 +318,9 @@ takes a font family, not a path: it reads only the system's font folders. `file.close` leaves no project open: `session.inspect` then reports `projectOpen: false`, `command.list` marks every command but the project-independent ones as not enabled: the ones that open or create a project (`file.open`, `file.new`, `project.new`, `project.sample`), `project.inspect`, `viewport.frame`, `project.templates`, the `export.preset*` commands (`export.presets`, `export.preset.get`, `export.preset.save`, `export.preset.remove`) and the library and preset listings (`brush.preset.list`, `alpha.list`, `filter.list`, `material.list`, `mask.smart.list`, `text.fonts`), each still subject to its own enabled check. The rest are refused with "no project is open" until a project is opened or created. A `texturecraft --control` run starts with the sample project (an empty material ball with `--empty`); the app without `--control` starts with no project. The desktop control channel accepts `rebuildUvs: true` on `file.new` to generate a new UV layout. -The default keeps a complete authored layout and unwraps meshes that need UVs. The project -remembers the rebuild choice for reopening and reimporting its mesh. +The default keeps a complete authored layout and unwraps meshes that need UVs. The project file +saves the generated layout, so reopening it never runs the unwrapper again; reimporting the mesh +from a file rebuilds its UVs. | Tool | Params | Notes | |---|---|---| diff --git a/docs/features.md b/docs/features.md index 82c650a4..6603b8af 100644 --- a/docs/features.md +++ b/docs/features.md @@ -138,7 +138,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel types to add or remove. Show, hide or invert them all at once, or **focus** on the active one. The project's **normal map format** (OpenGL or DirectX, in Texture Set Settings) says how a normal map image set as a mesh map is read, and is the default for export. -- **Projects** are a single `.tcraft` file: the mesh, every layer (sparse and lossless), baked maps +- **Projects** are a single `.tcraft` file: the mesh (with its generated UV layout when *Rebuild mesh UVs* was chosen), every layer (sparse and lossless), baked maps and imported images. **Project templates** start new work from a saved setup. *File › More save options › Save as template...* saves the open project's setup (dialog "Save template", in the user templates folder, no confirmation); New project lists "Default (OpenPBR)", the other built-ins with " (starter_assets)", yours with " (your_assets)", and opens on the template of the last project. *More save options* also has *Save as copy...* and *Save and reduce file size* (greyed, "Not available yet"). Closing the app, or opening, starting or closing another project, with unsaved changes asks whether to save them first (in the browser too, where Save downloads the project and closing or reloading the tab From a59e29bea19d76278a4fc321e4f4172a6982dcc5 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:55:25 +0100 Subject: [PATCH 3/4] Space the UV layout guards --- crates/formats/src/mesh_import/mod.rs | 1 + crates/formats/src/project_file/mod.rs | 1 + crates/formats/src/project_file/uv_layout.rs | 3 +++ 3 files changed, 5 insertions(+) diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index f9eed9d6..22eba9c9 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -550,6 +550,7 @@ fn apply_corner_uvs(mesh: &mut Mesh, layout: &[Vec2]) -> Result<()> { if layout.len() != mesh.indices.len() { return Err(FormatError::Invalid(format!("the saved UV layout has {} corners but the mesh has {}", layout.len(), mesh.indices.len()))); } + if layout.iter().any(|uv| !uv.is_finite()) { return Err(FormatError::Invalid("the saved UV layout has non-finite UVs".into())); } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 2f8b1d67..8052d627 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -531,6 +531,7 @@ fn load_archive(mut zip: ZipArchive, mut budget: LoadBudget) if pf.project.mesh_rebuild_uvs && pf.mesh.is_some() && pf.mesh_uvs.is_none() { return Err(malformed(KIND, "the mesh UVs were rebuilt but the project holds no saved UV layout")); } + if version < TANGENT_BENT_NORMAL_VERSION { drop_world_space_bent_normals(&mut pf); } diff --git a/crates/formats/src/project_file/uv_layout.rs b/crates/formats/src/project_file/uv_layout.rs index cf6a638c..645ff502 100644 --- a/crates/formats/src/project_file/uv_layout.rs +++ b/crates/formats/src/project_file/uv_layout.rs @@ -49,9 +49,11 @@ pub fn read_uv_layout(bytes: &[u8]) -> Result> { if magic != UV_LAYOUT_MAGIC { return Err(bad("bad magic")); } + if u32::from_le_bytes(*version) != UV_LAYOUT_VERSION { return Err(bad("unsupported version")); } + let corners = u32::from_le_bytes(*corners) as usize; if corners.checked_mul(CORNER_BYTES) != Some(body.len()) { return Err(bad("the corner count does not match the entry size")); @@ -69,5 +71,6 @@ pub fn read_uv_layout(bytes: &[u8]) -> Result> { if layout.iter().any(|uv| !uv.is_finite()) { return Err(bad("non-finite UVs")); } + Ok(layout) } From d88bb3ea4bf7b197a401eca0e6eeffa66ce27ede Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 10:41:37 +0100 Subject: [PATCH 4/4] Correct the UV persistence note in the control protocol docs --- docs/control-protocol.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 0754f7c1..2640b9a5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -318,9 +318,10 @@ takes a font family, not a path: it reads only the system's font folders. `file.close` leaves no project open: `session.inspect` then reports `projectOpen: false`, `command.list` marks every command but the project-independent ones as not enabled: the ones that open or create a project (`file.open`, `file.new`, `project.new`, `project.sample`), `project.inspect`, `viewport.frame`, `project.templates`, the `export.preset*` commands (`export.presets`, `export.preset.get`, `export.preset.save`, `export.preset.remove`) and the library and preset listings (`brush.preset.list`, `alpha.list`, `filter.list`, `material.list`, `mask.smart.list`, `text.fonts`), each still subject to its own enabled check. The rest are refused with "no project is open" until a project is opened or created. A `texturecraft --control` run starts with the sample project (an empty material ball with `--empty`); the app without `--control` starts with no project. The desktop control channel accepts `rebuildUvs: true` on `file.new` to generate a new UV layout. -The default keeps a complete authored layout and unwraps meshes that need UVs. The project file -saves the generated layout, so reopening it never runs the unwrapper again; reimporting the mesh -from a file rebuilds its UVs. +The default keeps a complete authored layout and unwraps meshes that need UVs. Reopening such a +project imports the mesh again and unwraps it again, as before. Only `rebuildUvs: true` makes the +project file save the generated layout, so reopening it never runs the unwrapper again; +reimporting the mesh from a file rebuilds its UVs. | Tool | Params | Notes | |---|---|---|