From b53c9312482b34592c37a96737b00767e08d5487 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 18:49:37 +0100 Subject: [PATCH 1/6] Add a MaterialX export option to the export window --- ROADMAP.md | 6 +- crates/ui-egui/src/export_window.rs | 16 +++- crates/ui-egui/src/state.rs | 5 ++ crates/ui-egui/tests/it/export_materialx.rs | 94 +++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/features.md | 6 ++ docs/ui-parity.md | 5 +- 7 files changed, 126 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/tests/it/export_materialx.rs diff --git a/ROADMAP.md b/ROADMAP.md index 759dfde7..cb114376 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -63,7 +63,7 @@ Why alpha. Mouse/keyboard tasks verified 3D/2D painting, undo/redo, material dra and generator editing, UV rectangle fill, UI baking, native saving and texture export. Separate command checks covered high-to-low transfer, UDIM sizes/packing and scene/material exports. The interface is recognizably close in its painting, bake and export workspaces, but still lacks -mask-thumbnail effect menus, several fill controls and a MaterialX export option. +mask-thumbnail effect menus and several fill controls. Generator depth is limited, bake equivalence is open, and hardware/performance coverage is incomplete. There were **96 open issues** on the review date; these include requests and older reports, not 96 reproduced defects. The published @@ -118,7 +118,7 @@ menu entries. Feature rows overlap and are not an additional additive score. | Baking | ~60% | TBD | All ten maps completed through the UI on CPU at 256 px and through commands on GPU at 128 px. Separate high/low normal/height transfer produced varying maps; cross-app pixel equivalence, larger assets and resolution-stable wear remain unproven | | Viewport, shading and rendering | ~70% | TBD | PBR/IBL, extra shading lobes, 3D/2D views, displacement and CPU/GPU path-tracing paths. Matching material/display behavior, larger scenes and hardware ray tracing remain open | | Color management | ~35% | TBD | Linear/sRGB handling, fixed export spaces and profile metadata; display model has Linear/ACES-filmic tone mapping. Configurable OCIO project/display workflows are absent | -| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX UI output, complex materials and larger UDIM assets remain incomplete | +| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX export covers OpenPBR only (no standard_surface); complex materials and larger UDIM assets remain incomplete | | Read-only `.spp` compatibility | 0% | TBD after feasibility study | Planned; no reader, version matrix or import-fidelity corpus. `.tcraft` remains the save format | | Workspace, panels and preferences | ~65% | TBD | Current views/layouts checked; narrow labels truncate. Incoming ArtCraft UI refactoring/shared components can change these surfaces; task, shortcut, accessibility and layout/preferences persistence checks must be repeated | | Automation | ~80% | TBD | Command inspection and scripted editing/export work; UI, CLI and MCP surfaces share engine commands. This review exercised the control channel and CLI, not every MCP/tool path | @@ -135,7 +135,7 @@ the legacy promise must not be carried forward automatically. The [UI gap inventory](docs/ui-parity.md#missing-controls-and-workflows) records reproduction routes and acceptance checks: mask context/save/export actions; independent U/V tiling, -filtering/wrap, physical-size and warp/per-tile projections; MaterialX UI output; +filtering/wrap, physical-size and warp/per-tile projections; and configurable color-management settings. Generator depth and narrow-layout readability are tracked as partial areas. Direct hardness/angle controls and polygon/UV rectangle fill already exist; older reports must not turn them into fresh missing-feature claims. diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 37590454..5a014fd3 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -374,6 +374,12 @@ pub(crate) fn export_params(app: &TextureCraftApp) -> serde_json::Value { if !e.color_space.is_empty() { p["colorSpace"] = json!(e.color_space); } + + // The browser downloads the textures only + #[cfg(not(target_arch = "wasm32"))] + if e.materialx { + p["materialX"] = json!(true); + } p } @@ -631,8 +637,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] if reset { let d = ExportUi::default(); let e = &mut app.ui.export; - (e.dir, e.format, e.bit_depth, e.dithering, e.size, e.padding, e.dilation, e.normal_format, e.color_space) = - (d.dir, d.format, d.bit_depth, d.dithering, d.size, d.padding, d.dilation, d.normal_format, d.color_space); + (e.dir, e.format, e.bit_depth, e.dithering, e.size, e.padding, e.dilation, e.normal_format, e.color_space, e.materialx) = + (d.dir, d.format, d.bit_depth, d.dithering, d.size, d.padding, d.dilation, d.normal_format, d.color_space, d.materialx); crate::export_templates::select(app, d.preset); } let (first, rest) = template_groups(app, builtins); @@ -678,6 +684,12 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] // Unavailable export controls stay disabled unavailable_checkbox(ui, tr("Export USD asset"), tr("Package the mesh, materials and textures together as USD")); unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); + + // The browser downloads the textures only, so it has no MaterialX file to add + #[cfg(not(target_arch = "wasm32"))] + ui.checkbox(&mut app.ui.export.materialx, tr("Export MaterialX")); + #[cfg(target_arch = "wasm32")] + crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let e = &mut app.ui.export; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e2a36d40..8f949d76 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -357,6 +357,10 @@ pub struct ExportUi { /// "" (by file format: sRGB, or linear for float files), or a colour space name. #[serde(default)] pub color_space: String, + /// Also write an OpenPBR MaterialX (`.mtlx`) file per texture set (`materialX` of + /// `file.exportTextures`). + #[serde(default)] + pub materialx: bool, /// Texture sets excluded from export. pub skip: Vec, /// Per texture set (by index) overrides of the settings above. @@ -418,6 +422,7 @@ impl Default for ExportUi { size: 0, normal_format: String::new(), color_space: String::new(), + materialx: false, skip: Vec::new(), sets: Default::default(), owner: Vec::new(), diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs new file mode 100644 index 00000000..0431fa62 --- /dev/null +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -0,0 +1,94 @@ +//! Export textures › SETTINGS: the Export MaterialX option (texturecraft #760). It passes +//! `materialX: true` to `file.exportTextures`, which writes an OpenPBR material per texture set. + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; +use texturecraft_ui_egui::TextureCraftApp; + +const OPENPBR: &str = "OpenPBR (separate maps)"; + +/// The Export textures window writing into a scratch folder of its own for `name` +fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, std::path::PathBuf) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + let dir = std::env::temp_dir().join(format!("tc-export-materialx-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + h.state_mut().ui.export.dir = dir.display().to_string(); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + (h, dir) +} + +fn checkbox<'a>(h: &'a Harness<'static, TextureCraftApp>) -> egui_kittest::Node<'a> { + h.get_by_role_and_label(egui::Role::CheckBox, "Export MaterialX") +} + +/// Click Export and run frames until the export ends +fn export(h: &mut Harness<'static, TextureCraftApp>) { + h.get_all_by_label("Export").last().unwrap().click(); + for _ in 0..64 { + h.run_steps(1); + if h.state().ui.export.job.is_none() { + break; + } + } + h.run_steps(2); +} + +fn mtlx_files(dir: &std::path::Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut files: Vec<_> = entries.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "mtlx")).collect(); + files.sort(); + files +} + +#[test] +fn the_window_offers_export_materialx_off_by_default() { + let (h, _dir) = harness("offer"); + assert!(!checkbox(&h).accesskit_node().is_disabled()); + assert!(!h.state().ui.export.materialx); +} + +#[test] +fn ticking_export_materialx_writes_one_mtlx_per_texture_set() { + let (mut h, dir) = harness("on"); + h.state_mut().ui.export.preset = OPENPBR.into(); + h.run_steps(3); + checkbox(&h).click(); + h.run_steps(3); + assert!(h.state().ui.export.materialx); + export(&mut h); + + let files = mtlx_files(&dir); + assert_eq!(files.len(), h.state().session.set_count(), "one material per texture set: {files:?}"); + for file in &files { + let text = std::fs::read_to_string(file).unwrap(); + assert!(text.contains(" Date: Mon, 23 Nov 2026 19:23:50 +0100 Subject: [PATCH 2/6] Write the OpenPBR maps for the MaterialX whatever template is selected --- crates/engine/src/file_cmds.rs | 79 ++++++++- crates/engine/tests/it/materialx.rs | 172 +++++++++++++++++++- crates/ui-egui/tests/it/export_materialx.rs | 25 +++ docs/features.md | 5 +- 4 files changed, 270 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f493093b..98ad2ad5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files)}", always, export_textures ), @@ -645,23 +645,86 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { - written.extend(write_materialx(s, &sets, &opts, std::path::Path::new(&dir), &mut warnings)?); + // The material reads OpenPBR maps whatever template was chosen: a template without + // their file names gets an extra pass of the built-in OpenPBR template beside its own files + let extra = openpbr_options(&opts); + let material_opts = extra.as_ref().unwrap_or(&opts); + let mut taken = std::collections::HashSet::new(); + if extra.is_some() { + taken.extend(files.iter().map(|f| f.name.to_ascii_lowercase())); + let mut maps = s.export_files(&sets, material_opts)?; + for file in &maps { + for warning in &file.warnings { + if !warnings.contains(warning) { + warnings.push(warning.clone()); + } + } + } + + // A file of the chosen template is never replaced; the material leaves out the map it would have used + let before = maps.len(); + maps.retain(|f| !taken.contains(&f.name.to_ascii_lowercase())); + if maps.len() < before { + warnings + .push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template, so the material does not use it".into()); + } + written.extend(texturecraft_formats::write_files(&maps, std::path::Path::new(&dir)).map_err(fe)?); + } + written.extend(write_materialx(s, &sets, material_opts, std::path::Path::new(&dir), &mut warnings, taken, extra.is_some())?); } s.log.info("MapExporter", format!("Exported {} textures to {dir}", written.len())); Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::>(), "warnings": warnings })) } +/// The options of the extra pass that writes the maps a MaterialX reads, or None when `opts`' +/// template already has maps with the OpenPBR file names (`texturecraft_formats::materialx`). +/// The pass uses the built-in "OpenPBR (separate maps)" template with the export's size, +/// padding, normal format, colour space, atlas and dithering, but not `opts.maps` (its indexes +/// belong to the chosen template). A file type override stays when a material can refer to it; +/// PSD, JNG, PGM (colour maps become luminance) and WebP (few readers) fall back to the +/// template's own PNG 8-bit (16-bit for height), so the bit depth override goes with them. +#[cfg(not(target_arch = "wasm32"))] +fn openpbr_options(opts: &ExportOptions) -> Option { + use texturecraft_formats::materialx::input_of_template; + if opts.preset.maps.iter().any(|map| input_of_template(&map.file).is_some()) { + return None; + } + + let mut options = ExportOptions::new(texturecraft_formats::builtin_preset("OpenPBR (separate maps)")?); + options.padding = opts.padding; + options.size = opts.size; + options.normal_format = opts.normal_format; + options.atlas = opts.atlas; + options.color_space = opts.color_space; + options.dither = opts.dither; + if let Some(format) = opts.format_override.filter(|format| !matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp)) { + options.format_override = Some(format); + options.bit_depth_override = opts.bit_depth_override; + } + Some(options) +} + /// One `_.mtlx` per texture set, next to the textures `opts` just wrote: the /// OpenPBR inputs those textures feed (see `texturecraft_formats::materialx`). UDIM sets name /// their files with the `` token. Sets with no recognised map, or whose name gives the -/// same file name as an earlier set's, are skipped with a warning. +/// same file name as an earlier set's, are skipped with a warning. `taken` holds the lower-case +/// names of files this export wrote for other maps: a texture of that name is not referenced. +/// `own_maps`: `opts` is the extra OpenPBR pass, not the template the user chose. #[cfg(not(target_arch = "wasm32"))] -fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std::path::Path, warnings: &mut Vec) -> Result> { +fn write_materialx( + s: &Session, + sets: &[usize], + opts: &ExportOptions, + dir: &std::path::Path, + warnings: &mut Vec, + taken: std::collections::HashSet, + own_maps: bool, +) -> Result> { use texturecraft_formats::materialx::{self, Texture}; let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); let mut stems = std::collections::HashSet::new(); - let mut written_names = std::collections::HashSet::new(); + let mut written_names = taken; let mut normal_map_written = false; let aces2065_tag = materialx::colorspace_name(texturecraft_texel::ColorSpace::Aces2065); let mut aces2065_written = false; @@ -692,7 +755,11 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: } normal_map_written |= textures.iter().any(|t| t.input == "geometry_normal"); if textures.is_empty() { - warnings.push(format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name)); + warnings.push(if own_maps { + format!("MaterialX: texture set \"{}\" has no channels an OpenPBR map can use", set.name) + } else { + format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name) + }); continue; } diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index 9af10e2c..4bf38421 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -5,6 +5,7 @@ use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; const OPENPBR: &str = "OpenPBR (separate maps)"; +const DEFAULT: &str = "Document channels + Normal + AO (No Alpha)"; /// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. struct Scratch(std::path::PathBuf); @@ -64,16 +65,181 @@ fn writes_a_material_that_names_the_exported_textures() { } #[test] -fn off_by_default_and_warns_without_openpbr_maps() { +fn off_by_default() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); let dir = temp("off"); assert!(!files(&export(&mut s, &dir, OPENPBR, false)).iter().any(|f| f.ends_with(".mtlx"))); - let dir = temp("other"); - let r = export(&mut s, &dir, "Document channels + Normal + AO", true); + let dir = temp("off-other"); + assert!(!files(&export(&mut s, &dir, DEFAULT, false)).iter().any(|f| f.ends_with(".mtlx") || f.ends_with("_base_color.png"))); +} + +#[test] +fn warns_when_a_template_with_openpbr_names_has_no_channels_to_write() { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // The default set has no coat + let preset = ExportPreset { + name: "coat".into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet_coat_weight".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::L, SourceRef::Channel { channel: texturecraft_engine::core::Channel::CoatWeight, component: 0 })], + inverted: Vec::new(), + }], + }; + let dir = temp("nocoat"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": preset, "materialX": true})).unwrap(); assert!(!files(&r).iter().any(|f| f.ends_with(".mtlx"))); assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("OpenPBR")), "{r}"); } +/// The `file` values a `.mtlx` refers to +fn referenced(text: &str) -> Vec { + text.split("name=\"file\" type=\"filename\" value=\"").skip(1).map(|part| part.split('"').next().unwrap().to_string()).collect() +} + +fn names(r: &Value) -> Vec { + files(r).iter().map(|f| f.rsplit(['/', '\\']).next().unwrap().to_string()).collect() +} + +#[test] +fn any_template_gets_the_openpbr_maps_beside_its_own_files() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let plain = temp("plain"); + let own = names(&export(&mut s, &plain, DEFAULT, false)); + let dir = temp("default-template"); + let r = export(&mut s, &dir, DEFAULT, true); + let all = names(&r); + for file in &own { + assert!(all.contains(file), "the template's own file {file} is still written: {all:?}"); + } + + let mtlx: Vec = files(&r).into_iter().filter(|f| f.ends_with(".mtlx")).collect(); + assert_eq!(mtlx.len(), s.set_count(), "{all:?}"); + for path in &mtlx { + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("= 3, "{text}"); + for file in refs { + assert!(dir.join(&file).is_file(), "{file} is not in {all:?}"); + assert!(!own.contains(&file), "{file} is a file of the chosen template"); + } + } + + // Every file is written once + let mut sorted = all.clone(); + sorted.sort(); + sorted.dedup(); + assert_eq!(sorted.len(), all.len(), "{all:?}"); +} + +#[test] +fn the_openpbr_template_writes_no_second_set_of_maps() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let without = temp("openpbr-without"); + let plain = names(&export(&mut s, &without, OPENPBR, false)); + let dir = temp("openpbr-with"); + let mut all = names(&export(&mut s, &dir, OPENPBR, true)); + all.retain(|f| !f.ends_with(".mtlx")); + let mut plain = plain; + plain.sort(); + all.sort(); + assert_eq!(all, plain); +} + +#[test] +fn per_map_overrides_of_the_template_do_not_reach_the_openpbr_maps() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("override"); + + // Map 0 is the base colour of the default template and also of the OpenPBR template; map 19 is the default template's normal map + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "materialX": true, "maps": [{"map": 0, "enabled": false}, {"map": 19, "format": "tiff", "bitDepth": 16}]}), + ) + .unwrap(); + let all = names(&r); + assert!(!all.iter().any(|f| f.ends_with("_baseColor.png")), "the template's base colour was left out: {all:?}"); + assert!(all.iter().any(|f| f.ends_with("_base_color.png")), "the material's base colour is still written: {all:?}"); + assert!(all.iter().any(|f| f.ends_with("_geometry_normal.png")), "{all:?}"); + assert!(all.iter().any(|f| f.ends_with("_normal.tif")), "the override applies to the template's own normal map: {all:?}"); + assert!(!all.iter().any(|f| f.ends_with(".tif") && f.contains("_geometry_")), "{all:?}"); +} + +#[test] +fn a_file_type_a_material_cannot_use_falls_back_to_png() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + for (format, bit_depth, ext) in [("psd", 16, "psd"), ("pgm", 8, "pgm"), ("jng", 8, "jng"), ("tiff", 16, "tif")] { + let dir = temp(format); + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "format": format, "bitDepth": bit_depth, "materialX": true}), + ) + .unwrap(); + let all = names(&r); + assert!(all.iter().any(|f| f.ends_with(&format!("_baseColor.{ext}"))), "{format}: the template's files keep the file type: {all:?}"); + let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("{format}: no .mtlx in {all:?}")); + let text = std::fs::read_to_string(mtlx).unwrap(); + let wanted = if format == "tiff" { "tif" } else { "png" }; + assert!(text.contains(&format!("_base_color.{wanted}\"")), "{format}: {text}"); + for file in referenced(&text) { + assert!(dir.join(&file).is_file(), "{format}: {file} is not in {all:?}"); + } + } +} + +#[test] +fn the_openpbr_maps_follow_the_size_and_colour_space_of_the_export() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("size"); + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "size": 64, "colorSpace": "ACEScg", "materialX": true}), + ) + .unwrap(); + let png = files(&r).into_iter().find(|f| f.ends_with("_base_color.png")).unwrap(); + assert_eq!(image::image_dimensions(png).unwrap(), (64, 64)); + let text = std::fs::read_to_string(files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap()).unwrap(); + assert!(text.contains("_base_color.png\" colorspace=\"acescg\""), "{text}"); + assert!(text.contains("_specular_roughness.png\" colorspace=\"lin_rec709\""), "{text}"); +} + +#[test] +fn a_file_of_the_template_is_never_replaced_by_an_openpbr_map() { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap(); + + // Set 1's file from the template has the name set 0's OpenPBR base colour would get + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "a_base_color"})).unwrap(); + let source = |component| SourceRef::Channel { channel: texturecraft_engine::core::Channel::BaseColor, component }; + let preset = ExportPreset { + name: "base colour only".into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::R, source(0)), (Dest::G, source(1)), (Dest::B, source(2))], + inverted: Vec::new(), + }], + }; + let params = |dir: &std::path::Path, mtlx: bool| json!({"dir": dir.display().to_string(), "preset": preset, "ts": [0, 1], "materialX": mtlx}); + let plain = temp("clash-plain"); + execute(&mut s, "file.exportTextures", ¶ms(&plain, false)).unwrap(); + let dir = temp("clash"); + let r = execute(&mut s, "file.exportTextures", ¶ms(&dir, true)).unwrap(); + assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), std::fs::read(plain.join("material_ball_a_base_color.png")).unwrap()); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("file name of a map of the chosen template")), "{r}"); + let first = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); + assert!(!referenced(&first).contains(&"material_ball_a_base_color.png".to_string()), "{first}"); +} + #[test] fn float_colour_maps_are_tagged_linear() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 0431fa62..175f91d3 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -70,6 +70,31 @@ fn ticking_export_materialx_writes_one_mtlx_per_texture_set() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn ticking_export_materialx_with_any_template_writes_the_openpbr_maps_beside_its_files() { + let (mut h, dir) = harness("any-template"); + assert_eq!(h.state().ui.export.preset, texturecraft_engine::formats::DEFAULT_PRESET); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let files = mtlx_files(&dir); + assert_eq!(files.len(), h.state().session.set_count(), "one material per texture set: {files:?}"); + let mut references = 0; + for file in &files { + for reference in std::fs::read_to_string(file).unwrap().split("name=\"file\" type=\"filename\" value=\"").skip(1) { + let name = reference.split('"').next().unwrap(); + assert!(dir.join(name).is_file(), "{name} is not next to the material"); + references += 1; + } + } + assert!(references > 0); + let written: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + assert!(written.iter().any(|f| f.ends_with("_baseColor.png")), "the template's own maps are still written: {written:?}"); + assert!(written.iter().any(|f| f.ends_with("_base_color.png")), "{written:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// The option is off by default, so a plain export writes no `.mtlx` even with the OpenPBR template #[test] fn no_mtlx_is_written_when_the_option_is_off() { diff --git a/docs/features.md b/docs/features.md index 98daa7a0..13fdb52b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -179,8 +179,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA between texture sets). - **MaterialX export:** the *Export MaterialX* checkbox on the Export textures window's Global settings (off by default, remembered with the other settings) writes one OpenPBR `.mtlx` per - texture set next to the exported maps. It reads the maps of output templates that use the - OpenPBR file names, such as *OpenPBR (separate maps)*. Not covered yet: MaterialX + texture set next to the exported maps. The material always uses OpenPBR maps, whatever output + template is selected: a template without their file names gets them written beside its own + files. Not covered yet: MaterialX standard_surface, Coat Normal, Specular Level, Anisotropy Angle and constants such as IOR. In the browser the option is greyed. - **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for From fa47c2c183103b4898d89fae988e630966436982 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 19:40:01 +0100 Subject: [PATCH 3/6] Force an OpenGL normal and keep the bit depth for the MaterialX maps --- crates/engine/src/file_cmds.rs | 32 +++++++----- crates/engine/tests/it/materialx.rs | 76 +++++++++++++++++++++++++++-- docs/control-protocol.md | 4 ++ docs/features.md | 9 ++-- 4 files changed, 101 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 98ad2ad5..d057f030 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files)}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files, without the per-map `maps` overrides)}", always, export_textures ), @@ -644,14 +644,18 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let files = s.export_files(&sets, &opts)?; let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; + + // The rendered files are not needed after this; only their names are + let mut taken: std::collections::HashSet = files.iter().map(|f| f.name.to_ascii_lowercase()).collect(); + drop(files); if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { // The material reads OpenPBR maps whatever template was chosen: a template without // their file names gets an extra pass of the built-in OpenPBR template beside its own files let extra = openpbr_options(&opts); let material_opts = extra.as_ref().unwrap_or(&opts); - let mut taken = std::collections::HashSet::new(); - if extra.is_some() { - taken.extend(files.iter().map(|f| f.name.to_ascii_lowercase())); + if extra.is_none() { + taken.clear(); + } else { let mut maps = s.export_files(&sets, material_opts)?; for file in &maps { for warning in &file.warnings { @@ -677,12 +681,14 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { } /// The options of the extra pass that writes the maps a MaterialX reads, or None when `opts`' -/// template already has maps with the OpenPBR file names (`texturecraft_formats::materialx`). +/// template already has a map with an OpenPBR file name (`texturecraft_formats::materialx`). /// The pass uses the built-in "OpenPBR (separate maps)" template with the export's size, -/// padding, normal format, colour space, atlas and dithering, but not `opts.maps` (its indexes -/// belong to the chosen template). A file type override stays when a material can refer to it; -/// PSD, JNG, PGM (colour maps become luminance) and WebP (few readers) fall back to the -/// template's own PNG 8-bit (16-bit for height), so the bit depth override goes with them. +/// padding, atlas, colour space and dithering, but not `opts.maps` (its indexes belong to the +/// chosen template). The normal map is always OpenGL, which the material's normalmap node reads, +/// whatever normal format the export asks for. A file type and bit depth override stay when a +/// material can refer to the file type; PSD, JNG, PGM (colour maps become luminance) and WebP +/// (few readers) fall back to the template's own PNG 8-bit (16-bit for height), and the bit +/// depth override goes with them. #[cfg(not(target_arch = "wasm32"))] fn openpbr_options(opts: &ExportOptions) -> Option { use texturecraft_formats::materialx::input_of_template; @@ -693,12 +699,12 @@ fn openpbr_options(opts: &ExportOptions) -> Option { let mut options = ExportOptions::new(texturecraft_formats::builtin_preset("OpenPBR (separate maps)")?); options.padding = opts.padding; options.size = opts.size; - options.normal_format = opts.normal_format; + options.normal_format = Some(NormalFormat::OpenGl); options.atlas = opts.atlas; options.color_space = opts.color_space; options.dither = opts.dither; - if let Some(format) = opts.format_override.filter(|format| !matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp)) { - options.format_override = Some(format); + if !opts.format_override.is_some_and(|format| matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp)) { + options.format_override = opts.format_override; options.bit_depth_override = opts.bit_depth_override; } Some(options) @@ -756,7 +762,7 @@ fn write_materialx( normal_map_written |= textures.iter().any(|t| t.input == "geometry_normal"); if textures.is_empty() { warnings.push(if own_maps { - format!("MaterialX: texture set \"{}\" has no channels an OpenPBR map can use", set.name) + format!("MaterialX: texture set \"{}\" has no OpenPBR maps to refer to", set.name) } else { format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name) }); diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index 4bf38421..1b92b827 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -200,14 +200,23 @@ fn the_openpbr_maps_follow_the_size_and_colour_space_of_the_export() { let r = execute( &mut s, "file.exportTextures", - &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "size": 64, "colorSpace": "ACEScg", "materialX": true}), + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "size": 256, "colorSpace": "ACEScg", "materialX": true}), ) .unwrap(); let png = files(&r).into_iter().find(|f| f.ends_with("_base_color.png")).unwrap(); - assert_eq!(image::image_dimensions(png).unwrap(), (64, 64)); + assert_eq!(image::image_dimensions(png).unwrap(), (256, 256)); let text = std::fs::read_to_string(files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap()).unwrap(); assert!(text.contains("_base_color.png\" colorspace=\"acescg\""), "{text}"); - assert!(text.contains("_specular_roughness.png\" colorspace=\"lin_rec709\""), "{text}"); + + // Only colour inputs carry a colour space, and the data maps are still referenced + let roughness = referenced(&text).into_iter().find(|f| f.ends_with("_specular_roughness.png")).unwrap_or_else(|| panic!("{text}")); + assert!(dir.join(&roughness).is_file()); + for part in text.split("name=\"file\" type=\"filename\" value=\"").skip(1) { + let (file, rest) = part.split_once('"').unwrap(); + if rest.starts_with(" colorspace=\"acescg\"") { + assert!(["_base_color.", "_fuzz_color.", "_emission_color."].iter().any(|input| file.contains(input)), "{file}"); + } + } } #[test] @@ -405,3 +414,64 @@ fn the_directx_warning_comes_once_and_only_with_a_normal_map() { let r = export(&mut s, &dir, OPENPBR, true); assert!(!r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("DirectX")), "{r}"); } + +/// A tangent-space normal image of one colour as PNG bytes +fn normal_png(rgb: [u8; 3]) -> Vec { + let image = image::RgbImage::from_pixel(4, 4, image::Rgb(rgb)); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +fn green_at_centre(path: &str) -> u8 { + let image = image::open(path).unwrap().to_rgb8(); + image.get_pixel(image.width() / 2, image.height() / 2)[1] +} + +#[test] +fn the_materials_normal_map_is_opengl_whatever_the_export_asks_for() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // A baked normal that tilts: green 64 in the file, 71 / 184 once normalised in OpenGL / DirectX + let image = s.import_resource_bytes("n.png", normal_png([128, 64, 255])).unwrap(); + execute(&mut s, "textureSet.meshMap.set", &json!({"map": "normal", "image": image})).unwrap(); + let dir = temp("normal-format"); + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "ts": 0, "normalFormat": "directX", "materialX": true}), + ) + .unwrap(); + let all = files(&r); + let own = all.iter().find(|f| f.ends_with("_normal.png")).unwrap(); + let material = all.iter().find(|f| f.ends_with("_geometry_normal.png")).unwrap(); + assert!(green_at_centre(own).abs_diff(184) <= 3, "the template's own normal map is DirectX: {}", green_at_centre(own)); + assert!(green_at_centre(material).abs_diff(71) <= 3, "the material's normal map is OpenGL: {}", green_at_centre(material)); + assert!(!r["warnings"].to_string().contains("DirectX"), "nothing to flip in the material: {r}"); +} + +#[test] +fn the_bit_depth_of_the_export_applies_to_the_openpbr_maps_unless_the_file_type_fell_back() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + for (extra, expected) in [(json!({}), image::ColorType::Rgb16), (json!({"format": "psd"}), image::ColorType::Rgb8)] { + let dir = temp("depth"); + let mut params = json!({"dir": dir.display().to_string(), "preset": DEFAULT, "ts": 0, "bitDepth": 16, "materialX": true}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = execute(&mut s, "file.exportTextures", ¶ms).unwrap(); + let png = files(&r).into_iter().find(|f| f.ends_with("_base_color.png")).unwrap(); + assert_eq!(image::open(png).unwrap().color(), expected, "{params}"); + } +} + +#[test] +fn a_set_whose_openpbr_maps_were_all_skipped_gets_no_material_and_a_warning() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + assert!(s.set_count() >= 2); + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a b"})).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "A_B"})).unwrap(); + let dir = temp("all-skipped"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "ts": "all", "materialX": true})).unwrap(); + assert_eq!(files(&r).iter().filter(|f| f.ends_with(".mtlx")).count(), s.set_count() - 1, "{r}"); + let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap()).collect(); + assert!(warnings.contains(&"MaterialX: texture set \"A_B\" has no OpenPBR maps to refer to"), "{warnings:?}"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d963eb9c..8d6ed911 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -47,6 +47,10 @@ template. `enabled: false` suppresses that file while reserving its name. When s sets produce the same name (ignoring case), programmatic and browser exports keep the first file and warn about later duplicates. The desktop export window reports the collision before writing. +`file.exportTextures` with `materialX: true` also writes a `.mtlx` OpenPBR material per texture set. +A template without OpenPBR file names gets the maps of the "OpenPBR (separate maps)" template written +beside its own files for it; the `maps` overrides above do not reach those maps. + `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, `hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and diff --git a/docs/features.md b/docs/features.md index 13fdb52b..f7c6be63 100644 --- a/docs/features.md +++ b/docs/features.md @@ -180,10 +180,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **MaterialX export:** the *Export MaterialX* checkbox on the Export textures window's Global settings (off by default, remembered with the other settings) writes one OpenPBR `.mtlx` per texture set next to the exported maps. The material always uses OpenPBR maps, whatever output - template is selected: a template without their file names gets them written beside its own - files. Not covered yet: MaterialX - standard_surface, Coat Normal, Specular Level, Anisotropy Angle and constants such as IOR. In - the browser the option is greyed. + template is selected: a template without OpenPBR file names gets the maps of *OpenPBR (separate + maps)* written beside its own files, with the export's size, padding, colour space, file type + and bit depth (PNG when that file type has no use in a material) and always an OpenGL normal + map. Not covered yet: MaterialX standard_surface, Coat Normal, Specular Level, Anisotropy + Angle and constants such as IOR. In the browser the option is greyed. - **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for roughness, metallic, normal and coat; UV-tiled sets keep their UDIM UVs and export their maps through Export textures), textured GLB (with clear coat and sheen) and USD (with clear coat). From 927fedf31390dad8c2ea8c6c2f18a3f7ec45d457 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 20:18:21 +0100 Subject: [PATCH 4/6] Show the export's warnings in the export console --- crates/ui-egui/src/export_window.rs | 16 ++++++++++- crates/ui-egui/src/state/export_job.rs | 2 ++ crates/ui-egui/tests/it/export_materialx.rs | 32 +++++++++++++++++++++ docs/features.md | 4 +-- 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 5a014fd3..f64498b0 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -245,7 +245,7 @@ fn start_export(app: &mut TextureCraftApp) { return; } - e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, written: Vec::new(), frame: 0 }); + e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, written: Vec::new(), frame: 0, warned: Vec::new() }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -345,6 +345,20 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { lines.push(set()); lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); } + + // The export's warnings go to the console and the log, each once per export + let warnings = response.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()); + for warning in warnings { + let Some(job) = app.ui.export.job.as_mut() else { break }; + if job.warned.iter().any(|seen| seen == warning) { + continue; + } + + job.warned.push(warning.to_string()); + app.session.log.warn("MapExporter", warning); + lines.push(set()); + lines.push(ConsoleLine::Step(trf("Warning: {message}", &[("message", &warning)]))); + } lines.extend([set(), ConsoleLine::Step(tr("Finished writing this texture set").into())]); app.ui.export.console.extend(lines); if let Some(job) = app.ui.export.job.as_mut() { diff --git a/crates/ui-egui/src/state/export_job.rs b/crates/ui-egui/src/state/export_job.rs index 4ba0d485..570fe3b4 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -15,4 +15,6 @@ pub struct ExportJob { pub written: Vec, /// The frame that wrote the last texture set (a frame's second pass writes none). pub frame: u64, + /// The warnings already shown, so a warning every texture set raises shows once per export. + pub warned: Vec, } diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 175f91d3..59d379cb 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -4,6 +4,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT as _, Queryable as _}; use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ConsoleLine; const OPENPBR: &str = "OpenPBR (separate maps)"; @@ -117,3 +118,34 @@ fn restoring_the_default_parameters_unticks_export_materialx() { h.run_steps(3); assert!(!h.state().ui.export.materialx); } + +/// Every texture set's export raises this warning: the material's normal map is read as OpenGL +const DIRECTX_WARNING: &str = "MaterialX: the normalmap node reads OpenGL (+Y) normals"; + +#[test] +fn a_warning_every_texture_set_raises_shows_once_in_the_console_and_the_log() { + let (mut h, dir) = harness("warning"); + assert!(h.state().session.set_count() >= 2, "the warning has to come from more than one texture set"); + let e = &mut h.state_mut().ui.export; + e.preset = OPENPBR.into(); + e.normal_format = "directX".into(); + h.run_steps(3); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let lines: Vec<&str> = h + .state() + .ui + .export + .console + .iter() + .filter_map(|line| match line { + ConsoleLine::Step(text) if text.starts_with("Warning: ") => Some(text.as_str()), + _ => None, + }) + .collect(); + assert_eq!(lines.iter().filter(|line| line.contains(DIRECTX_WARNING)).count(), 1, "{lines:?}"); + assert_eq!(h.state().session.log.iter().filter(|line| line.contains(DIRECTX_WARNING)).count(), 1); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features.md b/docs/features.md index f7c6be63..4e3d40d3 100644 --- a/docs/features.md +++ b/docs/features.md @@ -175,8 +175,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA *Cancel* goes back to the settings the window opened with, *Maximum size for all Texture Sets* exports every set at the largest set's size; a click on a texture set overrides its template, file type, size or padding, and each output map's file type and bit depth, or leaves a map out; - Export shows the progress, a console of its steps and the written files, and can be canceled - between texture sets). + Export shows the progress, a console of its steps, the written files and the export's + warnings (each once), and can be canceled between texture sets). - **MaterialX export:** the *Export MaterialX* checkbox on the Export textures window's Global settings (off by default, remembered with the other settings) writes one OpenPBR `.mtlx` per texture set next to the exported maps. The material always uses OpenPBR maps, whatever output From c9640bae075c3fecc4b2e88c436359474eb4916d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 20:23:09 +0100 Subject: [PATCH 5/6] Keep the files of earlier texture sets of an export when writing the MaterialX maps --- crates/engine/src/file_cmds.rs | 47 +++++++++-- crates/engine/tests/it/materialx.rs | 90 +++++++++++++++++++++ crates/ui-egui/src/export_window.rs | 4 + crates/ui-egui/tests/it/export_materialx.rs | 72 +++++++++++++++++ docs/control-protocol.md | 5 ++ docs/features.md | 5 +- 6 files changed, 213 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index d057f030..1f8d2415 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files, without the per-map `maps` overrides)}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names] (files an earlier command of the same export wrote, compared ignoring case: this command leaves out its own files and OpenPBR maps of these names and says so in `warnings`; the export window passes it), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files, without the per-map `maps` overrides)}", always, export_textures ), @@ -641,21 +641,29 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let opts = export_options(s, p, "file.exportTextures")?; let sets = sets_param(s, p, "file.exportTextures")?; std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; + let reserved = reserved_names(p)?; let files = s.export_files(&sets, &opts)?; + + // A file an earlier command of the same export wrote keeps its name: the export window runs + // one command per texture set, and a later set's file must not replace an earlier one (which an + // earlier .mtlx may refer to) + let (files, skipped): (Vec<_>, Vec<_>) = files.into_iter().partition(|f| !reserved.contains(&f.name.to_ascii_lowercase())); let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); + warnings.extend(skipped.iter().map(|f| format!("\"{}\" was not written: an earlier file of this export has the same name", f.name))); let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; // The rendered files are not needed after this; only their names are - let mut taken: std::collections::HashSet = files.iter().map(|f| f.name.to_ascii_lowercase()).collect(); + let own: std::collections::HashSet = files.iter().map(|f| f.name.to_ascii_lowercase()).collect(); drop(files); + drop(skipped); + let mut taken = reserved; if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { // The material reads OpenPBR maps whatever template was chosen: a template without // their file names gets an extra pass of the built-in OpenPBR template beside its own files let extra = openpbr_options(&opts); let material_opts = extra.as_ref().unwrap_or(&opts); - if extra.is_none() { - taken.clear(); - } else { + if extra.is_some() { + taken.extend(own); let mut maps = s.export_files(&sets, material_opts)?; for file in &maps { for warning in &file.warnings { @@ -665,12 +673,12 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { } } - // A file of the chosen template is never replaced; the material leaves out the map it would have used + // A file of the chosen template, or of an earlier command of this export, is never replaced; the material leaves out the map it would have used let before = maps.len(); maps.retain(|f| !taken.contains(&f.name.to_ascii_lowercase())); if maps.len() < before { warnings - .push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template, so the material does not use it".into()); + .push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template or of an earlier file of this export, so the material does not use it".into()); } written.extend(texturecraft_formats::write_files(&maps, std::path::Path::new(&dir)).map_err(fe)?); } @@ -680,6 +688,19 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::>(), "warnings": warnings })) } +/// `reservedNames`: the names of files earlier commands of the same export wrote (lower-cased). +#[cfg(not(target_arch = "wasm32"))] +fn reserved_names(p: &Value) -> Result> { + match p.get("reservedNames") { + None | Some(Value::Null) => Ok(Default::default()), + Some(Value::Array(names)) => names + .iter() + .map(|name| name.as_str().map(str::to_ascii_lowercase).ok_or_else(|| bad("file.exportTextures", "`reservedNames` must be a list of file names"))) + .collect(), + Some(_) => Err(bad("file.exportTextures", "`reservedNames` must be a list of file names")), + } +} + /// The options of the extra pass that writes the maps a MaterialX reads, or None when `opts`' /// template already has a map with an OpenPBR file name (`texturecraft_formats::materialx`). /// The pass uses the built-in "OpenPBR (separate maps)" template with the export's size, @@ -730,6 +751,7 @@ fn write_materialx( let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); let mut stems = std::collections::HashSet::new(); + let reserved = taken.clone(); let mut written_names = taken; let mut normal_map_written = false; let aces2065_tag = materialx::colorspace_name(texturecraft_texel::ColorSpace::Aces2065); @@ -780,7 +802,16 @@ fn write_materialx( continue; } - let path = dir.join(format!("{stem}.mtlx")); + let file_name = format!("{stem}.mtlx"); + if reserved.contains(&file_name.to_ascii_lowercase()) { + warnings.push(format!( + "MaterialX: texture set \"{}\" exports as \"{file_name}\" like an earlier file of this export, so its .mtlx was not written", + set.name + )); + continue; + } + + let path = dir.join(file_name); texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?; aces2065_written |= textures.iter().any(|texture| texture.colorspace == aces2065_tag && materialx::INPUTS.contains(&(texture.input.as_str(), materialx::Kind::Color))); diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index 1b92b827..f1979d38 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -249,6 +249,96 @@ fn a_file_of_the_template_is_never_replaced_by_an_openpbr_map() { assert!(!referenced(&first).contains(&"material_ball_a_base_color.png".to_string()), "{first}"); } +/// A template with one map, the base colour, named `$mesh_$textureSet` (no input suffix) +fn base_colour_template() -> texturecraft_engine::formats::ExportPreset { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + let source = |component| SourceRef::Channel { channel: texturecraft_engine::core::Channel::BaseColor, component }; + ExportPreset { + name: "base colour only".into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::R, source(0)), (Dest::G, source(1)), (Dest::B, source(2))], + inverted: Vec::new(), + }], + } +} + +/// One `file.exportTextures` command of texture set `ts`, as the export window sends them: the +/// names of the files the earlier commands wrote are passed as `reservedNames` +fn export_set(s: &mut Session, dir: &std::path::Path, ts: usize, earlier: &[String]) -> Value { + let params = json!({"dir": dir.display().to_string(), "preset": base_colour_template(), "ts": ts, "materialX": true, "reservedNames": earlier}); + execute(s, "file.exportTextures", ¶ms).unwrap() +} + +fn warned(r: &Value, text: &str) -> bool { + r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains(text)) +} + +#[test] +fn an_openpbr_map_never_replaces_a_file_an_earlier_command_of_the_export_wrote() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // Set 0's own file is named like the base colour map set 1 gets from the OpenPBR template + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a_base_color"})).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "a"})).unwrap(); + let dir = temp("later-extra"); + let first = export_set(&mut s, &dir, 0, &[]); + let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(); + let second = export_set(&mut s, &dir, 1, &names(&first)); + assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), kept, "the earlier file is untouched"); + assert!(warned(&second, "has the file name of a map of the chosen template or of an earlier file of this export"), "{second}"); + let material = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); + assert!(!referenced(&material).contains(&"material_ball_a_base_color.png".to_string()), "{material}"); + for file in referenced(&material) { + assert!(dir.join(&file).is_file(), "{file}"); + } +} + +#[test] +fn a_file_of_the_template_never_replaces_an_openpbr_map_an_earlier_command_wrote() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // Set 0's OpenPBR base colour has the name set 1's own file gets from the template + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "a_base_color"})).unwrap(); + let dir = temp("later-own"); + let first = export_set(&mut s, &dir, 0, &[]); + let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(); + let second = export_set(&mut s, &dir, 1, &names(&first)); + assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), kept, "the earlier file is untouched"); + assert!(warned(&second, "\"material_ball_a_base_color.png\" was not written"), "{second}"); + + // The earlier material still points at the file it was written with + let earlier = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); + assert!(referenced(&earlier).contains(&"material_ball_a_base_color.png".to_string()), "{earlier}"); + let later = std::fs::read_to_string(dir.join("material_ball_a_base_color.mtlx")).unwrap(); + assert!(!referenced(&later).contains(&"material_ball_a_base_color.png".to_string()), "{later}"); +} + +#[test] +fn a_material_is_not_written_over_a_file_an_earlier_command_wrote() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap(); + let dir = temp("mtlx-name"); + let r = export_set(&mut s, &dir, 0, &["MATERIAL_BALL_A.MTLX".to_string()]); + assert!(!files(&r).iter().any(|f| f.ends_with(".mtlx")), "{r}"); + assert!(warned(&r, "exports as \"material_ball_a.mtlx\" like an earlier file of this export"), "{r}"); + let r = export_set(&mut s, &dir, 0, &["unrelated.mtlx".to_string()]); + assert!(files(&r).iter().any(|f| f.ends_with("material_ball_a.mtlx")), "{r}"); +} + +#[test] +fn reserved_names_must_be_a_list_of_names() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("bad-reserved"); + for bad in [json!("a.png"), json!([1])] { + let params = json!({"dir": dir.display().to_string(), "preset": OPENPBR, "reservedNames": bad}); + assert!(execute(&mut s, "file.exportTextures", ¶ms).is_err()); + } +} + #[test] fn float_colour_maps_are_tagged_linear() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index f64498b0..4eeca695 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -326,6 +326,10 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let set = || ConsoleLine::Set(name.clone()); app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Rendering the selected maps").into())]); + // The files of the earlier texture sets keep their names, the material's extra maps and .mtlx files included + if let Some(job) = app.ui.export.job.as_ref().filter(|job| !job.written.is_empty()) { + params["reservedNames"] = json!(job.written); + } let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 59d379cb..099dcc5c 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -149,3 +149,75 @@ fn a_warning_every_texture_set_raises_shows_once_in_the_console_and_the_log() { assert_eq!(h.state().session.log.iter().filter(|line| line.contains(DIRECTX_WARNING)).count(), 1); let _ = std::fs::remove_dir_all(&dir); } + +/// A template with one map, the base colour, named `$mesh_$textureSet` (no input suffix) +fn base_colour_template() -> texturecraft_engine::formats::ExportPreset { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + let source = |component| SourceRef::Channel { channel: texturecraft_engine::core::Channel::BaseColor, component }; + ExportPreset { + name: "base colour only".into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::R, source(0)), (Dest::G, source(1)), (Dest::B, source(2))], + inverted: Vec::new(), + }], + } +} + +/// The base colour of texture set `ts` as the template writes it, from a plain export +fn expected(h: &mut Harness<'static, TextureCraftApp>, ts: usize, preset: &str, file: &str, tag: &str) -> Vec { + let dir = std::env::temp_dir().join(format!("tc-export-materialx-expected-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let params = serde_json::json!({"dir": dir.display().to_string(), "preset": preset, "ts": ts}); + texturecraft_engine::execute(&mut h.state_mut().session, "file.exportTextures", ¶ms).unwrap(); + let bytes = std::fs::read(dir.join(file)).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + bytes +} + +#[test] +fn texture_sets_of_one_export_never_overwrite_each_others_files() { + const SHARED: &str = "material_ball_a_base_color.png"; + + // (names of set 0 and set 1, the template whose export of set 0 must be what SHARED holds, + // the material that refers to SHARED) + let cases = [ + // Set 0's own file has the name set 1's OpenPBR base colour would get + ("a_base_color", "a", "base colour only", None), + // Set 0's OpenPBR base colour has the name set 1's own file would get + ("a", "a_base_color", "OpenPBR (separate maps)", Some("material_ball_a.mtlx")), + ]; + for (index, (first, second, template_of_set_0, referred_by)) in cases.into_iter().enumerate() { + let (mut h, dir) = harness(&format!("overwrite-{index}")); + let project = &mut h.state_mut().session.doc.project; + project.texture_sets[0].name = first.into(); + project.texture_sets[1].name = second.into(); + let template = base_colour_template(); + let name = template.name.clone(); + h.state_mut().session.export_presets.list.push(template); + h.state_mut().ui.export.preset = name; + h.run_steps(3); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let want = expected(&mut h, 0, template_of_set_0, SHARED, &index.to_string()); + assert_eq!(std::fs::read(dir.join(SHARED)).unwrap(), want, "case {index}: the earlier texture set's file was replaced"); + + // A material only points at files that exist, and only the earlier set's material at SHARED + let materials = mtlx_files(&dir); + assert_eq!(materials.len(), 2, "{materials:?}"); + for material in materials { + let text = std::fs::read_to_string(&material).unwrap(); + let file_name = material.file_name().unwrap().to_string_lossy().into_owned(); + for reference in text.split("name=\"file\" type=\"filename\" value=\"").skip(1) { + let name = reference.split('"').next().unwrap(); + assert!(dir.join(name).is_file(), "case {index}: {name} is missing"); + assert!(name != SHARED || referred_by == Some(file_name.as_str()), "case {index}: {file_name} refers to {name}"); + } + } + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8d6ed911..71c61b40 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -50,6 +50,11 @@ and warn about later duplicates. The desktop export window reports the collision `file.exportTextures` with `materialX: true` also writes a `.mtlx` OpenPBR material per texture set. A template without OpenPBR file names gets the maps of the "OpenPBR (separate maps)" template written beside its own files for it; the `maps` overrides above do not reach those maps. +`reservedNames: [file names]` lists the files earlier `file.exportTextures` commands of the same +export wrote (the export window runs one command per texture set and passes it). The command +compares them ignoring case, does not write a file, an OpenPBR map or a `.mtlx` of such a name, +and names it in `warnings`; a material leaves out the input of a map it did not write. Without it +nothing is reserved. `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, `hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for diff --git a/docs/features.md b/docs/features.md index 4e3d40d3..0cf74ec4 100644 --- a/docs/features.md +++ b/docs/features.md @@ -183,8 +183,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA template is selected: a template without OpenPBR file names gets the maps of *OpenPBR (separate maps)* written beside its own files, with the export's size, padding, colour space, file type and bit depth (PNG when that file type has no use in a material) and always an OpenGL normal - map. Not covered yet: MaterialX standard_surface, Coat Normal, Specular Level, Anisotropy - Angle and constants such as IOR. In the browser the option is greyed. + map. A file of one texture set never replaces a file of an earlier one in the same export, the + material's maps included. Not covered yet: MaterialX standard_surface, Coat Normal, Specular + Level, Anisotropy Angle and constants such as IOR. In the browser the option is greyed. - **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for roughness, metallic, normal and coat; UV-tiled sets keep their UDIM UVs and export their maps through Export textures), textured GLB (with clear coat and sheen) and USD (with clear coat). From 94daa7370ce7c7631f2e72994f753d93ba476c13 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 20:33:42 +0100 Subject: [PATCH 6/6] Name the file in the MaterialX map warning and check reservedNames before creating the folder --- crates/engine/src/file_cmds.rs | 15 +++++++-------- crates/engine/tests/it/materialx.rs | 5 +++-- crates/ui-egui/tests/it/export_materialx.rs | 17 +++++++++++++---- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 1f8d2415..86837a42 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -640,8 +640,8 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let dir = native::path_param(p, "dir", "file.exportTextures")?.to_string(); let opts = export_options(s, p, "file.exportTextures")?; let sets = sets_param(s, p, "file.exportTextures")?; - std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; let reserved = reserved_names(p)?; + std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; let files = s.export_files(&sets, &opts)?; // A file an earlier command of the same export wrote keeps its name: the export window runs @@ -664,7 +664,7 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let material_opts = extra.as_ref().unwrap_or(&opts); if extra.is_some() { taken.extend(own); - let mut maps = s.export_files(&sets, material_opts)?; + let maps = s.export_files(&sets, material_opts)?; for file in &maps { for warning in &file.warnings { if !warnings.contains(warning) { @@ -674,12 +674,11 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { } // A file of the chosen template, or of an earlier command of this export, is never replaced; the material leaves out the map it would have used - let before = maps.len(); - maps.retain(|f| !taken.contains(&f.name.to_ascii_lowercase())); - if maps.len() < before { - warnings - .push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template or of an earlier file of this export, so the material does not use it".into()); - } + let (kept, dropped): (Vec<_>, Vec<_>) = maps.into_iter().partition(|f| !taken.contains(&f.name.to_ascii_lowercase())); + warnings.extend(dropped.iter().map(|f| { + format!("MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name, so the material does not use it", f.name) + })); + let maps = kept; written.extend(texturecraft_formats::write_files(&maps, std::path::Path::new(&dir)).map_err(fe)?); } written.extend(write_materialx(s, &sets, material_opts, std::path::Path::new(&dir), &mut warnings, taken, extra.is_some())?); diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index f1979d38..2836f7c5 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -244,7 +244,7 @@ fn a_file_of_the_template_is_never_replaced_by_an_openpbr_map() { let dir = temp("clash"); let r = execute(&mut s, "file.exportTextures", ¶ms(&dir, true)).unwrap(); assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), std::fs::read(plain.join("material_ball_a_base_color.png")).unwrap()); - assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("file name of a map of the chosen template")), "{r}"); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("material_ball_a_base_color.png\" was not written")), "{r}"); let first = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); assert!(!referenced(&first).contains(&"material_ball_a_base_color.png".to_string()), "{first}"); } @@ -288,7 +288,7 @@ fn an_openpbr_map_never_replaces_a_file_an_earlier_command_of_the_export_wrote() let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(); let second = export_set(&mut s, &dir, 1, &names(&first)); assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), kept, "the earlier file is untouched"); - assert!(warned(&second, "has the file name of a map of the chosen template or of an earlier file of this export"), "{second}"); + assert!(warned(&second, "\"material_ball_a_base_color.png\" was not written: a file of the chosen template or of an earlier command"), "{second}"); let material = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); assert!(!referenced(&material).contains(&"material_ball_a_base_color.png".to_string()), "{material}"); for file in referenced(&material) { @@ -337,6 +337,7 @@ fn reserved_names_must_be_a_list_of_names() { let params = json!({"dir": dir.display().to_string(), "preset": OPENPBR, "reservedNames": bad}); assert!(execute(&mut s, "file.exportTextures", ¶ms).is_err()); } + assert!(!dir.exists(), "a bad parameter creates no folder"); } #[test] diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 099dcc5c..424de7a8 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -182,14 +182,14 @@ fn texture_sets_of_one_export_never_overwrite_each_others_files() { const SHARED: &str = "material_ball_a_base_color.png"; // (names of set 0 and set 1, the template whose export of set 0 must be what SHARED holds, - // the material that refers to SHARED) + // the template whose export of set 1 would replace it, the material that refers to SHARED) let cases = [ // Set 0's own file has the name set 1's OpenPBR base colour would get - ("a_base_color", "a", "base colour only", None), + ("a_base_color", "a", "base colour only", "OpenPBR (separate maps)", None), // Set 0's OpenPBR base colour has the name set 1's own file would get - ("a", "a_base_color", "OpenPBR (separate maps)", Some("material_ball_a.mtlx")), + ("a", "a_base_color", "OpenPBR (separate maps)", "base colour only", Some("material_ball_a.mtlx")), ]; - for (index, (first, second, template_of_set_0, referred_by)) in cases.into_iter().enumerate() { + for (index, (first, second, template_of_set_0, template_of_set_1, referred_by)) in cases.into_iter().enumerate() { let (mut h, dir) = harness(&format!("overwrite-{index}")); let project = &mut h.state_mut().session.doc.project; project.texture_sets[0].name = first.into(); @@ -204,8 +204,17 @@ fn texture_sets_of_one_export_never_overwrite_each_others_files() { export(&mut h); let want = expected(&mut h, 0, template_of_set_0, SHARED, &index.to_string()); + let rival = expected(&mut h, 1, template_of_set_1, SHARED, &format!("{index}-rival")); + assert_ne!(want, rival, "case {index}: the two files differ, so a replacement shows"); assert_eq!(std::fs::read(dir.join(SHARED)).unwrap(), want, "case {index}: the earlier texture set's file was replaced"); + let console = h.state().ui.export.console.iter().filter_map(|line| if let ConsoleLine::Step(text) = line { Some(text.as_str()) } else { None }); + assert!( + console.clone().any(|text| text.starts_with("Warning: ") && text.contains("\"material_ball_a_base_color.png\" was not written")), + "case {index}: {:?}", + console.collect::>() + ); + // A material only points at files that exist, and only the earlier set's material at SHARED let materials = mtlx_files(&dir); assert_eq!(materials.len(), 2, "{materials:?}");