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/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f493093b..b006b38b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -3,12 +3,15 @@ use std::borrow::Cow; use std::collections::BTreeMap; +#[cfg(not(target_arch = "wasm32"))] +use std::collections::{HashMap, HashSet, hash_map::Entry}; use std::sync::Arc; use serde_json::{Value, json}; #[cfg(not(target_arch = "wasm32"))] use texturecraft_core::{NormalFormat, PROJECT_EXT}; use texturecraft_core::{Project, TextureSet}; +use texturecraft_formats::PlannedFile; use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile}; use texturecraft_geom::{Mesh, primitives}; @@ -55,7 +58,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), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -269,6 +272,17 @@ impl Session { /// named like one an earlier set exports is left out, with a warning (see /// [`texturecraft_formats::skip_repeated_names`]). pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result> { + let mut files = self.render_export_files(sets, opts, |_, plans| plans)?; + texturecraft_formats::skip_repeated_names(&mut files); + Ok(files) + } + + fn render_export_files( + &mut self, + sets: &[usize], + options: &ExportOptions, + mut select: impl FnMut(usize, Vec) -> Vec, + ) -> Result> { if self.solo.is_none() { self.update(); } @@ -276,23 +290,28 @@ impl Session { let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); let empty = Default::default(); - for &ts in sets { - let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?; - let composite = self.document_composite(ts, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?; + for &set_index in sets { + let cache = self.caches.get(set_index).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; + let plans = texturecraft_formats::list_outputs(&self.doc.project, set_index, &mesh_name, options).map_err(fe)?; + let plans = select(set_index, plans); + if plans.is_empty() { + continue; + } + + let composite = + self.document_composite(set_index, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; let coverage = cache.gbuf.coverage_mask(); let input = ExportInput { project: &self.doc.project, - ts, + ts: set_index, composite: &composite, - baked: self.doc.baked.get(&ts).unwrap_or(&empty), + baked: self.doc.baked.get(&set_index).unwrap_or(&empty), coverage: &coverage, mesh_name: &mesh_name, }; - out.extend(texturecraft_formats::render_maps(&input, opts).map_err(fe)?); + out.extend(texturecraft_formats::export::render_planned_maps(&input, options, plans).map_err(fe)?); } - // A later set's file would replace an earlier set's of the same name - texturecraft_formats::skip_repeated_names(&mut out); Ok(out) } } @@ -636,93 +655,368 @@ impl Session { } #[cfg(not(target_arch = "wasm32"))] -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 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)?; - 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)?); +fn export_textures(session: &mut Session, params: &Value) -> Result { + let dir = std::path::Path::new(native::path_param(params, "dir", "file.exportTextures")?); + let options = export_options(session, params, "file.exportTextures")?; + let sets = sets_param(session, params, "file.exportTextures")?; + let mut taken_names = reserved_names(params)?; + let reserved_patterns: Vec<_> = taken_names.keys().filter(|name| name.contains("")).cloned().collect(); + let material = params.get("materialX").and_then(Value::as_bool).unwrap_or(false); + let mut warnings = Vec::new(); + let mut udim_patterns = Vec::new(); + + std::fs::create_dir_all(dir).map_err(|error| bad("file.exportTextures", format!("cannot create {}: {error}", dir.display())))?; + + let written = if material { + let (fallback, selected_inputs, fallback_inputs) = material_map_options(&options, session.doc.project.normal_format)?; + let mut textures = BTreeMap::new(); + + let selected = session.render_export_files(&sets, &options, |set, mut plans| { + let blocked = reserve_export_names(set, &mut plans, &mut taken_names, &reserved_patterns, &mut warnings, false); + collect_material_maps(&options, &selected_inputs, &plans, &blocked, textures.entry(set).or_default(), &mut warnings); + plans + })?; + + append_export_warnings(&mut warnings, &selected); + let mut written = texturecraft_formats::write_files(&selected, dir).map_err(fe)?; + drop(selected); + + if !fallback_inputs.is_empty() { + let maps = session.render_export_files(&sets, &fallback, |set, mut plans| { + let blocked = reserve_export_names(set, &mut plans, &mut taken_names, &reserved_patterns, &mut warnings, true); + collect_material_maps(&fallback, &fallback_inputs, &plans, &blocked, textures.entry(set).or_default(), &mut warnings); + plans + })?; + + if options.normal_format == Some(NormalFormat::DirectX) + && options.preset.maps.iter().any(|map| texturecraft_formats::materialx::input_of_template(&map.file) == Some("geometry_normal")) + && fallback_inputs.values().any(|input| *input == "geometry_normal") + && textures.values().flatten().any(|texture| texture.input == "geometry_normal") + { + warnings.push( + "MaterialX: the normalmap node reads OpenGL (+Y) normals. The material uses a separate OpenGL map alongside the selected DirectX map" + .into(), + ); + } + + append_export_warnings(&mut warnings, &maps); + written.extend(texturecraft_formats::write_files(&maps, dir).map_err(fe)?); + } + + written.extend(write_materialx(session, &sets, &mut textures, dir, &mut taken_names, &mut warnings, &mut udim_patterns)?); + written + } else if taken_names.is_empty() { + let files = session.export_files(&sets, &options)?; + warnings.extend(files.iter().flat_map(|file| file.warnings.iter().cloned())); + texturecraft_formats::write_files(&files, dir).map_err(fe)? + } else { + let files = session.render_export_files(&sets, &options, |set, mut plans| { + reserve_export_names(set, &mut plans, &mut taken_names, &reserved_patterns, &mut warnings, false); + plans + })?; + append_export_warnings(&mut warnings, &files); + texturecraft_formats::write_files(&files, dir).map_err(fe)? + }; + + session.log.info("MapExporter", format!("Exported {} textures to {}", written.len(), dir.display())); + let mut response = json!({ "files": written.iter().map(|path| path.display().to_string()).collect::>(), "warnings": warnings }); + if !udim_patterns.is_empty() { + response["materialUdimPatterns"] = json!(udim_patterns); } - 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 })) + + Ok(response) } -/// 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. +/// Reserve paths and UDIM patterns from earlier commands without assigning them to a current set. #[cfg(not(target_arch = "wasm32"))] -fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std::path::Path, warnings: &mut Vec) -> 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 normal_map_written = false; - let aces2065_tag = materialx::colorspace_name(texturecraft_texel::ColorSpace::Aces2065); - let mut aces2065_written = false; - for &ts in sets { - let set = s.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?; - let files = texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, opts).map_err(fe)?; +fn reserved_names(params: &Value) -> Result>> { + match params.get("reservedNames") { + None | Some(Value::Null) => Ok(HashMap::new()), + Some(Value::Array(names)) => names + .iter() + .map(|name| { + name.as_str() + .map(|name| (name.to_ascii_lowercase(), None)) + .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")), + } +} - // If any tile of a map was skipped, its UDIM reference could pick up another set's pixels - let mut skipped_maps = std::collections::HashSet::new(); - for file in &files { - if !written_names.insert(file.name.to_ascii_lowercase()) { - skipped_maps.insert(file.map); - } +#[cfg(not(target_arch = "wasm32"))] +fn reserve_export_names( + set_index: usize, + plans: &mut Vec, + taken_names: &mut HashMap>, + reserved_patterns: &[String], + warnings: &mut Vec, + fallback: bool, +) -> HashSet { + let mut blocked_maps = HashSet::new(); + plans.retain(|plan| { + let name = plan.name.to_ascii_lowercase(); + if reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)) { + blocked_maps.insert(plan.map); + warnings.push(format!( + "\"{}\" was not written: an earlier MaterialX document uses that UDIM pattern. Rename a texture set or change the template file names", + plan.name + )); + return false; } - let mut textures: Vec = Vec::new(); - for file in files.into_iter().filter(|file| !skipped_maps.contains(&file.map)) { - let Some(map) = opts.preset.maps.get(file.map) else { continue }; - let Some(input) = materialx::input_of_template(&map.file) else { continue }; - - // The first tile stands for all the tiles with the same naming pattern - let filename = file.udim_name.unwrap_or(file.name); - let space = opts.space_for_map(map, file.format, file.bit_depth); - let colorspace = materialx::colorspace_name(space); - if !textures.iter().any(|texture| texture.input == input) { - textures.push(Texture { input: input.to_owned(), file: filename, colorspace }); - } + if let Entry::Vacant(entry) = taken_names.entry(name) { + entry.insert(Some(set_index)); + return true; } - 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)); + + blocked_maps.insert(plan.map); + if fallback { + warnings.push(format!( + "MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name. Rename a texture set or change the template file names", + plan.name + )); + } else { + warnings.push(format!( + "\"{}\" was not written: an earlier file of this export has the same name. Rename a texture set or change the template file names", + plan.name + )); + } + false + }); + blocked_maps +} + +#[cfg(not(target_arch = "wasm32"))] +fn udim_matches(pattern: &str, filename: &str) -> bool { + let Some((prefix, suffix)) = pattern.split_once("") else { return false }; + + filename + .strip_prefix(prefix) + .and_then(|name| name.strip_suffix(suffix)) + .is_some_and(|tile| tile.len() == 4 && tile.parse::().is_ok_and(|tile| texturecraft_core::project::UDIM_RANGE.contains(&tile))) +} + +#[cfg(not(target_arch = "wasm32"))] +fn append_export_warnings(warnings: &mut Vec, files: &[ExportedFile]) { + for warning in files.iter().flat_map(|file| &file.warnings) { + if !warnings.contains(warning) { + warnings.push(warning.clone()); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +type MaterialInputs = BTreeMap; + +/// Identify reusable maps and prepare separate, canonical maps for the remaining inputs. +#[cfg(not(target_arch = "wasm32"))] +fn material_map_options(options: &ExportOptions, project_normal: NormalFormat) -> Result<(ExportOptions, MaterialInputs, MaterialInputs)> { + use texturecraft_formats::materialx::input_of_template; + + let canonical = texturecraft_formats::builtin_preset("OpenPBR (separate maps)") + .ok_or_else(|| bad("file.exportTextures", "the OpenPBR export preset is unavailable"))?; + let mut fallback = ExportOptions::new(texturecraft_formats::ExportPreset { name: canonical.name, maps: Vec::new() }); + fallback.padding = options.padding; + fallback.size = options.size; + fallback.normal_format = Some(NormalFormat::OpenGl); + fallback.atlas = options.atlas; + fallback.color_space = options.color_space; + fallback.dither = options.dither; + let mut reusable = BTreeMap::new(); + let mut generated = BTreeMap::new(); + + for mut map in canonical.maps { + let Some(input) = input_of_template(&map.file) else { continue }; + + let selected = options.preset.maps.iter().enumerate().filter(|(_, selected)| selected.file == map.file); + let selected_format = |index: usize| { + options.maps.get(&index).and_then(|settings| settings.format).or(options.format_override).unwrap_or(options.preset.maps[index].format) + }; + let enabled = |index: usize| options.maps.get(&index).is_none_or(|settings| settings.enabled); + let compatible = selected.clone().find(|(index, selected)| { + enabled(*index) && material_format(selected_format(*index)) && compatible_material_map(&map, selected, options.normal_format, project_normal) + }); + if let Some((index, _)) = compatible { + reusable.insert(index, input); continue; } - let stem = texturecraft_formats::export::sanitize_file_stem(&format!("{mesh_name}_{}", set.name)); + let replacement = selected.clone().find(|(index, _)| enabled(*index)); + if replacement.is_none() && selected.clone().next().is_some() { + continue; + } - // Case-insensitive: Windows and macOS file systems are - if !stems.insert(stem.to_ascii_lowercase()) { + let mut overrides = MapOverride::default(); + let requested_format = replacement.map(|(index, _)| selected_format(index)).or(options.format_override); + if requested_format.is_none_or(material_format) { + overrides.format = requested_format; + let settings = replacement.and_then(|(index, _)| options.maps.get(&index)); + overrides.bit_depth = + settings.and_then(|settings| settings.bit_depth).or(options.bit_depth_override).or_else(|| replacement.map(|(_, selected)| selected.bit_depth)); + overrides.dither = settings.and_then(|settings| settings.dither); + } + + // A replacement with the same format needs its own name beside the selected output + if selected.filter(|(index, _)| enabled(*index)).any(|(index, _)| selected_format(index) == overrides.format.unwrap_or(map.format)) { + map.file.push_str("_mtlx"); + } + + let index = fallback.preset.maps.len(); + generated.insert(index, input); + fallback.maps.insert(index, overrides); + fallback.preset.maps.push(map); + } + + Ok((fallback, reusable, generated)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn material_format(format: FileFormat) -> bool { + !matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp) +} + +#[cfg(not(target_arch = "wasm32"))] +fn compatible_material_map( + canonical: &texturecraft_formats::MapSpec, + selected: &texturecraft_formats::MapSpec, + normal_override: Option, + project_normal: NormalFormat, +) -> bool { + use texturecraft_formats::{Dest, SourceRef, VirtualMap}; + + canonical.channels.iter().all(|(dest, expected)| { + !selected.inverted.contains(dest) + && selected.channels.iter().any(|(actual_dest, actual)| { + if actual_dest != dest { + return false; + } + + match (expected, actual) { + ( + SourceRef::Virtual { map: VirtualMap::NormalOpenGl, component }, + SourceRef::Virtual { map: VirtualMap::NormalOpenGl | VirtualMap::NormalDirectX, component: selected_component }, + ) => { + let default = if matches!(actual, SourceRef::Virtual { map: VirtualMap::NormalDirectX, .. }) { + NormalFormat::DirectX + } else { + NormalFormat::OpenGl + }; + component == selected_component && normal_override.unwrap_or(default) == NormalFormat::OpenGl + } + ( + SourceRef::Virtual { map: VirtualMap::NormalOpenGl, component }, + SourceRef::Channel { channel: texturecraft_core::Channel::Normal, component: selected_component }, + ) => component == selected_component && normal_override.unwrap_or(project_normal) == NormalFormat::OpenGl, + _ => expected == actual, + } + }) + }) && selected.channels.iter().all(|(dest, _)| *dest == Dest::A || canonical.channels.iter().any(|(canonical_dest, _)| canonical_dest == dest)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn collect_material_maps( + options: &ExportOptions, + inputs: &MaterialInputs, + plans: &[PlannedFile], + blocked_maps: &HashSet, + textures: &mut Vec, + warnings: &mut Vec, +) { + use texturecraft_formats::materialx::{Texture, colorspace_name}; + + for (&map_index, &input) in inputs { + // A UDIM pattern is safe only if every tile was retained + if blocked_maps.contains(&map_index) { + continue; + } + + let mut tiles = plans.iter().filter(|plan| plan.map == map_index); + let Some(first) = tiles.next() else { continue }; + + let filename = if first.tile.is_none() { + &first.name + } else if let Some(pattern) = &first.udim_name + && tiles.all(|plan| plan.udim_name.as_ref() == Some(pattern)) + { + pattern + } else { + warnings.push(format!("MaterialX: \"{}\" has no consistent UDIM pattern. Shorten the texture set or template name", first.name)); + continue; + }; + + let space = options.space_for_map(&options.preset.maps[map_index], first.format, first.bit_depth); + textures.push(Texture { input: input.into(), file: filename.clone(), colorspace: colorspace_name(space) }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_materialx( + session: &Session, + sets: &[usize], + textures: &mut BTreeMap>, + dir: &std::path::Path, + taken_names: &mut HashMap>, + warnings: &mut Vec, + udim_patterns: &mut Vec, +) -> Result> { + use texturecraft_formats::materialx::{self, Kind}; + + let mesh_name = stem_of(session.doc.project.mesh.trim_start_matches("builtin:")); + let mut paths = Vec::new(); + let mut aces2065_written = false; + let aces2065_tag = materialx::colorspace_name(texturecraft_texel::ColorSpace::Aces2065); + for &index in sets { + let set = session.doc.project.texture_set(index).map_err(|error| EngineError::Other(error.to_string()))?; + let Some(inputs) = textures.get_mut(&index) else { continue }; + + inputs.retain(|texture| { + if !texture.file.contains("") { + return true; + } + + let pattern = texture.file.to_ascii_lowercase(); + if taken_names.iter().any(|(filename, owner)| *owner != Some(index) && udim_matches(&pattern, filename)) { + warnings.push(format!( + "MaterialX: \"{}\" also matches another texture set's files. Rename a texture set or change the template file names", + texture.file + )); + return false; + } + + true + }); + if inputs.is_empty() { + warnings.push(format!("MaterialX: texture set \"{}\" has no OpenPBR maps to refer to", set.name)); + continue; + } + + let material_name = format!("{mesh_name}_{}", set.name); + let stem = texturecraft_formats::export::sanitize_file_stem(&material_name); + let filename = format!("{stem}.mtlx"); + let Entry::Vacant(entry) = taken_names.entry(filename.to_ascii_lowercase()) else { warnings.push(format!( - "MaterialX: texture set \"{}\" exports as \"{stem}\" like an earlier set, so its .mtlx was not written; rename one of them", + "MaterialX: texture set \"{}\" exports as \"{filename}\" like an earlier file of this export, so its .mtlx was not written. Rename one of the texture sets", set.name )); continue; - } + }; - let path = dir.join(format!("{stem}.mtlx")); - texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?; + entry.insert(Some(index)); + + let path = dir.join(filename); + texturecraft_formats::write_atomic(&path, materialx::write(&material_name, inputs, None).as_bytes()).map_err(fe)?; + udim_patterns.extend(inputs.iter().filter(|texture| texture.file.contains("")).map(|texture| texture.file.clone())); aces2065_written |= - textures.iter().any(|texture| texture.colorspace == aces2065_tag && materialx::INPUTS.contains(&(texture.input.as_str(), materialx::Kind::Color))); - out.push(path); + inputs.iter().any(|texture| texture.colorspace == aces2065_tag && materialx::INPUTS.contains(&(texture.input.as_str(), Kind::Color))); + paths.push(path); } if aces2065_written { warnings.push("MaterialX: version 1.39 has no ACES2065-1 colour space; the colour maps are tagged lin_ap0_scene, its name in later versions, which older readers may not know".into()); } - // The normalmap node only exists in a material that has a normal map - if normal_map_written && opts.normal_format == Some(NormalFormat::DirectX) { - warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into()); - } - Ok(out) + Ok(paths) } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index 9af10e2c..b69391bd 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); @@ -30,27 +31,30 @@ fn temp(tag: &str) -> Scratch { Scratch(dir) } -fn export(s: &mut Session, dir: &std::path::Path, preset: &str, mtlx: bool) -> Value { - execute(s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": preset, "materialX": mtlx})).unwrap() +fn export(session: &mut Session, dir: &std::path::Path, preset: &str, mtlx: bool) -> Value { + execute(session, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": preset, "materialX": mtlx})).unwrap() } -fn files(r: &Value) -> Vec { - r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect() +fn files(result: &Value) -> Vec { + result["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect() } #[test] fn writes_a_material_that_names_the_exported_textures() { - let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); let dir = temp("ball"); - let r = export(&mut s, &dir, OPENPBR, true); - let all = files(&r); + + let result = export(&mut session, &dir, OPENPBR, true); + + let all = files(&result); let mtlx: Vec<&String> = all.iter().filter(|f| f.ends_with(".mtlx")).collect(); - assert_eq!(mtlx.len(), s.set_count(), "one material per texture set: {all:?}"); + assert_eq!(mtlx.len(), session.set_count(), "one material per texture set: {all:?}"); for path in mtlx { let set = path.rsplit(['/', '\\']).next().unwrap().trim_end_matches(".mtlx").to_string(); let text = std::fs::read_to_string(path).unwrap(); assert!(text.contains(" Vec { + text.split("name=\"file\" type=\"filename\" value=\"").skip(1).map(|part| part.split('"').next().unwrap().to_string()).collect() +} + +fn names(result: &Value) -> Vec { + files(result).iter().map(|f| f.rsplit(['/', '\\']).next().unwrap().to_string()).collect() +} + +#[test] +fn any_template_gets_the_openpbr_maps_beside_its_own_files() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let plain = temp("plain"); + let own = names(&export(&mut session, &plain, DEFAULT, false)); + let dir = temp("default-template"); + + let result = export(&mut session, &dir, DEFAULT, true); + + let all = names(&result); + for file in &own { + assert!(all.contains(file), "the template's own file {file} is still written: {all:?}"); + } + + let mtlx: Vec = files(&result).into_iter().filter(|f| f.ends_with(".mtlx")).collect(); + assert_eq!(mtlx.len(), session.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 session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let without = temp("openpbr-without"); + let plain = names(&export(&mut session, &without, OPENPBR, false)); + + let dir = temp("openpbr-with"); + let mut all = names(&export(&mut session, &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 session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("override"); + + // Use overrides that would affect different maps if applied to the OpenPBR template + let result = execute( + &mut session, + "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(&result); + 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 session = 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 result = execute( + &mut session, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "format": format, "bitDepth": bit_depth, "materialX": true}), + ) + .unwrap(); + + let all = names(&result); + assert!(all.iter().any(|f| f.ends_with(&format!("_baseColor.{ext}"))), "{format}: the template's files keep the file type: {all:?}"); + let mtlx = files(&result).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 session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("size"); + + let result = execute( + &mut session, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "size": 256, "colorSpace": "ACEScg", "materialX": true}), + ) + .unwrap(); + + let png = files(&result).into_iter().find(|f| f.ends_with("_base_color.png")).unwrap(); + assert_eq!(image::image_dimensions(png).unwrap(), (256, 256)); + let text = std::fs::read_to_string(files(&result).into_iter().find(|f| f.ends_with(".mtlx")).unwrap()).unwrap(); + assert!(text.contains("_base_color.png\" colorspace=\"acescg\""), "{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] +fn a_file_of_the_template_is_never_replaced_by_an_openpbr_map() { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + execute(&mut session, "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 session, "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 session, "file.exportTextures", ¶ms(&plain, false)).unwrap(); + + let dir = temp("clash"); + let result = execute(&mut session, "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!( + result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("material_ball_a_base_color.png\" was not written")), + "{result}" + ); + 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}"); +} + +/// 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(session: &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(session, "file.exportTextures", ¶ms).unwrap() +} + +fn warned(result: &Value, text: &str) -> bool { + result["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 session = 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 session, "textureSet.rename", &json!({"ts": 0, "name": "a_base_color"})).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "a"})).unwrap(); + let dir = temp("later-extra"); + + let first = export_set(&mut session, &dir, 0, &[]); + let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(); + let second = export_set(&mut session, &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: 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) { + 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 session = 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 session, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "a_base_color"})).unwrap(); + let dir = temp("later-own"); + + let first = export_set(&mut session, &dir, 0, &[]); + let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(); + let second = export_set(&mut session, &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 session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap(); + let dir = temp("mtlx-name"); + + let result = export_set(&mut session, &dir, 0, &["MATERIAL_BALL_A.MTLX".to_string()]); + + assert!(!files(&result).iter().any(|f| f.ends_with(".mtlx")), "{result}"); + assert!(warned(&result, "exports as \"material_ball_a.mtlx\" like an earlier file of this export"), "{result}"); + + let result = export_set(&mut session, &dir, 0, &["unrelated.mtlx".to_string()]); + assert!(files(&result).iter().any(|f| f.ends_with("material_ball_a.mtlx")), "{result}"); +} + +#[test] +fn reserved_names_must_be_a_list_of_names() { + let mut session = 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 session, "file.exportTextures", ¶ms).is_err()); + } + + assert!(!dir.exists(), "a bad parameter creates no folder"); } #[test] fn float_colour_maps_are_tagged_linear() { - let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); let dir = temp("exr"); - let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "materialX": true})).unwrap(); - let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap(); + + let result = + execute(&mut session, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "materialX": true})) + .unwrap(); + + let mtlx = files(&result).into_iter().find(|f| f.ends_with(".mtlx")).unwrap(); let text = std::fs::read_to_string(mtlx).unwrap(); assert!(text.contains("_base_color.exr\" colorspace=\"lin_rec709\"") && !text.contains("srgb_texture"), "{text}"); } #[test] fn colour_maps_are_tagged_with_the_export_colour_space() { - let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); for (space, tag, warns) in [("ACEScg", "acescg", false), ("ACES2065-1", "lin_ap0_scene", true), ("sRGB", "srgb_texture", false)] { let dir = temp(tag); - let r = execute( - &mut s, + + let result = execute( + &mut session, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "colorSpace": space, "materialX": true}), ) .unwrap(); - let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap(); + + let mtlx = files(&result).into_iter().find(|f| f.ends_with(".mtlx")).unwrap(); let text = std::fs::read_to_string(mtlx).unwrap(); assert!(text.contains(&format!("_base_color.exr\" colorspace=\"{tag}\"")), "{space}: {text}"); - let warned = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("ACES2065-1")); - assert_eq!(warned, warns, "{space}: {r}"); + let warned = result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("ACES2065-1")); + assert_eq!(warned, warns, "{space}: {result}"); } } #[test] -fn pgm_colour_maps_are_tagged_with_the_written_luminance_space() { +fn materialx_uses_rgb_fallbacks_beside_selected_pgm_colour_maps() { let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); - for (space, tag) in [(None, "srgb_texture"), (Some("ACEScg"), "lin_rec709"), (Some("ACES2065-1"), "lin_rec709")] { + for (space, tag) in [(None, "srgb_texture"), (Some("ACEScg"), "acescg"), (Some("ACES2065-1"), "lin_ap0_scene")] { let directory = temp(tag); + let result = execute( &mut session, "file.exportTextures", @@ -115,10 +422,13 @@ fn pgm_colour_maps_are_tagged_with_the_written_luminance_space() { ) .unwrap(); - let material = files(&result).into_iter().find(|path| path.ends_with(".mtlx")).unwrap(); + let paths = files(&result); + let selected = paths.iter().find(|path| path.ends_with("_base_color.pgm")).unwrap(); + let material = paths.iter().find(|path| path.ends_with(".mtlx")).unwrap(); let text = std::fs::read_to_string(material).unwrap(); - assert!(text.contains(&format!("_base_color.pgm\" colorspace=\"{tag}\"")), "{space:?}: {text}"); - assert!(!result["warnings"].to_string().contains("lin_ap0_scene"), "{result}"); + assert!(text.contains(&format!("_base_color.png\" colorspace=\"{tag}\"")), "{space:?}: {text}"); + assert!(std::fs::read(selected).unwrap().starts_with(b"P5"), "the selected output is still binary PGM"); + assert!(!text.contains(".pgm"), "{text}"); } } @@ -140,6 +450,7 @@ fn explicit_srgb_float_tiff_tags_match_gray_and_rgb_samples() { name: "TIFF base colour".into(), maps: vec![MapSpec { file: "$mesh_$textureSet_base_color".into(), format: FileFormat::Tiff, bit_depth: 32, channels, inverted: Vec::new() }], }; + let result = execute( &mut session, "file.exportTextures", @@ -152,7 +463,10 @@ fn explicit_srgb_float_tiff_tags_match_gray_and_rgb_samples() { let material = std::fs::read_to_string(paths.iter().find(|file| file.ends_with(".mtlx")).unwrap()).unwrap(); let warned = result["warnings"].to_string().contains("written in linear Rec.709"); let samples = image::open(texture).unwrap().to_rgb32f(); - assert!(material.contains(&format!("_base_color.tif\" colorspace=\"{tag}\"")), "{material}"); + let expected_name = if tag == "lin_rec709" { "_base_color_mtlx.tif" } else { "_base_color.tif" }; + assert!(material.contains(&format!("{expected_name}\" colorspace=\"srgb_texture\"")), "{material}"); + let reference = referenced(&material).into_iter().find(|name| name.ends_with(expected_name)).unwrap(); + assert_eq!(image::open(directory.join(reference)).unwrap().color(), image::ColorType::Rgb32F); assert_eq!(warned, tag == "lin_rec709", "{result}"); if let Some(expected) = linear_sample { let (x, y, red) = expected; @@ -167,14 +481,17 @@ fn explicit_srgb_float_tiff_tags_match_gray_and_rgb_samples() { #[test] fn sets_with_the_same_file_name_warn_instead_of_overwriting() { - 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 mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + assert!(session.set_count() >= 2); + execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "a b"})).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "A_B"})).unwrap(); let dir = temp("clash"); - let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "ts": "all", "materialX": true})).unwrap(); - assert_eq!(files(&r).iter().filter(|f| f.ends_with(".mtlx")).count(), s.set_count() - 1, "{r}"); - assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("\"A_B\"")), "{r}"); + + let result = + execute(&mut session, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "ts": "all", "materialX": true})).unwrap(); + + assert_eq!(files(&result).iter().filter(|f| f.ends_with(".mtlx")).count(), session.set_count() - 1, "{result}"); + assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("\"A_B\"")), "{result}"); } #[test] @@ -198,10 +515,12 @@ fn a_material_never_points_at_a_texture_kept_for_another_set() { #[test] fn udim_sets_use_the_udim_token() { - let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let mut session = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); let dir = temp("udim"); - let r = export(&mut s, &dir, OPENPBR, true); - let all = files(&r); + + let result = export(&mut session, &dir, OPENPBR, true); + + let all = files(&result); let mtlx = all.iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("no .mtlx in {all:?}")); let text = std::fs::read_to_string(mtlx).unwrap(); assert!(text.contains(".<UDIM>.png"), "{text}"); @@ -211,16 +530,19 @@ fn udim_sets_use_the_udim_token() { #[test] fn the_udim_placeholder_replaces_the_tile_number_not_a_look_alike_in_the_name() { - let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); - execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "cloth.1001.body"})).unwrap(); + let mut session = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "cloth.1001.body"})).unwrap(); let dir = temp("lookalike"); - let r = export(&mut s, &dir, OPENPBR, true); - let all = files(&r); + + let result = export(&mut session, &dir, OPENPBR, true); + + let all = files(&result); let mtlx = all.iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("no .mtlx in {all:?}")); let text = std::fs::read_to_string(mtlx).unwrap(); assert!(text.contains("cloth.1001.body"), "the set's own name stays as it is: {text}"); assert!(text.contains("<UDIM>"), "{text}"); - // Every texture the document names exists for the first tile. + + // Verify the token for the first tile for part in text.split("name=\"file\" type=\"filename\" value=\"").skip(1) { let file = part.split('"').next().unwrap().replace("<UDIM>", "1001"); assert!(dir.join(&file).is_file(), "{file} is not in {all:?}"); @@ -229,13 +551,181 @@ fn the_udim_placeholder_replaces_the_tile_number_not_a_look_alike_in_the_name() #[test] fn the_directx_warning_comes_once_and_only_with_a_normal_map() { - let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); let dir = temp("dx"); - let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "materialX": true, "normalFormat": "directX"})) - .unwrap(); - let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap()).filter(|w| w.contains("DirectX")).collect(); - assert_eq!(warnings.len(), 1, "{r}"); + + let result = execute( + &mut session, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "materialX": true, "normalFormat": "directX"}), + ) + .unwrap(); + + let warnings: Vec<&str> = result["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap()).filter(|w| w.contains("DirectX")).collect(); + assert_eq!(warnings.len(), 1, "{result}"); + let dir = temp("gl"); - let r = export(&mut s, &dir, OPENPBR, true); - assert!(!r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("DirectX")), "{r}"); + let result = export(&mut session, &dir, OPENPBR, true); + assert!(!result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("DirectX")), "{result}"); +} + +/// 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 session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // Use a tilted normal so the green values separate by convention + let image = session.import_resource_bytes("n.png", normal_png([128, 64, 255])).unwrap(); + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "normal", "image": image})).unwrap(); + let dir = temp("normal-format"); + + let result = execute( + &mut session, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "ts": 0, "normalFormat": "directX", "materialX": true}), + ) + .unwrap(); + + let all = files(&result); + 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!(!result["warnings"].to_string().contains("DirectX"), "nothing to flip in the material: {result}"); +} + +#[test] +fn the_bit_depth_of_the_export_applies_to_the_openpbr_maps_unless_the_file_type_fell_back() { + let mut session = 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 result = execute(&mut session, "file.exportTextures", ¶ms).unwrap(); + + let png = files(&result).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 session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + assert!(session.set_count() >= 2); + execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "a b"})).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "A_B"})).unwrap(); + let dir = temp("all-skipped"); + + let result = + execute(&mut session, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "ts": "all", "materialX": true})).unwrap(); + + assert_eq!(files(&result).iter().filter(|f| f.ends_with(".mtlx")).count(), session.set_count() - 1, "{result}"); + let warnings: Vec<&str> = result["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:?}"); +} + +#[test] +fn openpbr_template_preserves_directx_export_and_references_an_opengl_normal() { + let mut session = Session::new_project("material", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let image = session.import_resource_bytes("normal.png", normal_png([128, 64, 255])).unwrap(); + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "normal", "image": image})).unwrap(); + let directory = temp("openpbr-directx"); + let params = json!({"dir": directory.display().to_string(), "preset": OPENPBR, "ts": 0, "normalFormat": "directX", "materialX": true}); + + let result = execute(&mut session, "file.exportTextures", ¶ms).unwrap(); + + let all = files(&result); + let selected = all.iter().find(|path| path.ends_with("_geometry_normal.png")).unwrap(); + let document = std::fs::read_to_string(all.iter().find(|path| path.ends_with(".mtlx")).unwrap()).unwrap(); + let reference = referenced(&document).into_iter().find(|name| name.contains("_geometry_normal")).unwrap(); + assert!(green_at_centre(selected) > 128, "the selected normal must retain the DirectX convention"); + assert!(green_at_centre(&directory.join(reference).to_string_lossy()) < 128, "the material must reference an OpenGL normal"); +} + +#[test] +fn an_openpbr_filename_does_not_turn_a_data_map_into_base_color() { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + + let mut session = Session::new_project("material", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let template = ExportPreset { + name: "roughness with a custom filename".into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet_base_color".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::L, SourceRef::Channel { channel: texturecraft_engine::core::Channel::Roughness, component: 0 })], + inverted: Vec::new(), + }], + }; + let directory = temp("misleading-map"); + let params = json!({"dir": directory.display().to_string(), "preset": template, "ts": 0, "materialX": true}); + + let result = execute(&mut session, "file.exportTextures", ¶ms).unwrap(); + + let all = files(&result); + let selected = all.iter().find(|path| path.ends_with("_base_color.png")).unwrap(); + let document = std::fs::read_to_string(all.iter().find(|path| path.ends_with(".mtlx")).unwrap()).unwrap(); + let reference = referenced(&document).into_iter().find(|name| name.contains("_base_color")).unwrap(); + assert_eq!(image::open(selected).unwrap().color(), image::ColorType::L8); + assert_eq!(image::open(directory.join(reference)).unwrap().color(), image::ColorType::Rgb8); +} + +#[test] +fn a_material_udim_pattern_never_captures_a_tile_written_by_another_command() { + let mut session = Session::new_project("material", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let directory = temp("udim-collision"); + let plain = export(&mut session, &directory, OPENPBR, true); + let material = files(&plain).into_iter().find(|path| path.ends_with(".mtlx")).unwrap(); + let document = std::fs::read_to_string(material).unwrap(); + let reference = referenced(&document).into_iter().find(|name| name.contains("_base_color")).unwrap(); + let other_tile = reference.replace("<UDIM>", "1003"); + let earlier_tile = directory.join(&other_tile); + std::fs::copy(directory.join(reference.replace("<UDIM>", "1001")), &earlier_tile).unwrap(); + + let result = execute( + &mut session, + "file.exportTextures", + &json!({"dir": directory.display().to_string(), "preset": OPENPBR, "materialX": true, "reservedNames": [other_tile]}), + ) + .unwrap(); + + let material = files(&result).into_iter().find(|path| path.ends_with(".mtlx")).unwrap(); + let document = std::fs::read_to_string(material).unwrap(); + assert!(!referenced(&document).contains(&reference), "{document}"); + assert!(warned(&result, "also matches another texture set's files"), "{result}"); + + std::fs::remove_file(&earlier_tile).unwrap(); + let mut conflicting_preset = texturecraft_engine::formats::builtin_preset(OPENPBR).unwrap(); + conflicting_preset.maps.truncate(1); + conflicting_preset.maps[0].file = other_tile.trim_end_matches(".png").into(); + + let mut plain_session = Session::new_project("other", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + + let result = execute( + &mut plain_session, + "file.exportTextures", + &json!({ + "dir": directory.display().to_string(), + "preset": conflicting_preset, + "reservedNames": plain["materialUdimPatterns"] + }), + ) + .unwrap(); + + assert!(files(&result).is_empty(), "{result}"); + assert!(warned(&result, "an earlier MaterialX document uses that UDIM pattern"), "{result}"); + assert!(!directory.join(other_tile).exists()); } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index cdcb9c36..f92ebbb4 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -864,6 +864,11 @@ impl Sampler<'_> { /// Render every file of `opts` for `input`'s texture set. pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result> { let planned = list_outputs(input.project, input.ts, input.mesh_name, options)?; + render_planned_maps(input, options, planned) +} + +/// Render the retained plans from `list_outputs` for this input and these options. +pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned: Vec) -> Result> { let set = input.project.texture_set(input.ts)?; let (width, height) = (input.composite.resolution, input.composite.height); let grid = set.tile_grid(); @@ -901,6 +906,7 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result = selection .into_iter() - .map(|ts| { - let mut p = set_params(app, ts); - p["dir"] = json!(dir); + .map(|set_index| { + let mut params = set_params(app, set_index); + params["dir"] = json!(dir); // Capture the template so edits during export cannot change the files - let preset = p.get("preset").and_then(serde_json::Value::as_str).and_then(|name| app.session.export_preset(name)); - if let Some(v) = preset.and_then(|t| serde_json::to_value(t).ok()) { - p["preset"] = v; + let preset = params.get("preset").and_then(serde_json::Value::as_str).and_then(|name| app.session.export_preset(name)); + if let Some(preset) = preset.and_then(|preset| serde_json::to_value(preset).ok()) { + params["preset"] = preset; } - (ts, p) + + (set_index, params) }) .collect(); + let preview: Vec<_> = pending.iter().filter_map(|(index, params)| plan_set(app, *index, params)).collect(); let error = preview.iter().find_map(|plan| plan.files.as_ref().err().cloned()).or_else(|| name_clash(&preview)); + let e = &mut app.ui.export; e.tab = 2; e.console = vec![ConsoleLine::Step(tr("Preparing texture export").into())]; @@ -245,7 +248,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, ..Default::default() }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -295,14 +298,19 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { job.frame = frame; if job.pending.is_empty() { let written = std::mem::take(&mut job.written); - let mut lines = vec![ - ConsoleLine::Step(tr("All selected texture sets processed").into()), - ConsoleLine::Step(tr("Collecting the exported files").into()), - ConsoleLine::Done(tr("Texture export complete").into()), - ConsoleLine::Done(tr("Files saved").into()), - ]; - lines.extend(written.into_iter().map(ConsoleLine::Done)); - app.ui.export.console.extend(lines); + let console = &mut app.ui.export.console; + console.push(ConsoleLine::Step(tr("All selected texture sets processed").into())); + if written.is_empty() { + console.push(ConsoleLine::Step(tr("No files were written").into())); + } else { + console.extend([ + ConsoleLine::Step(tr("Collecting the exported files").into()), + ConsoleLine::Done(tr("Texture export complete").into()), + ConsoleLine::Done(tr("Files saved").into()), + ]); + console.extend(written.into_iter().map(ConsoleLine::Done)); + } + app.ui.export.job = None; return; } @@ -326,17 +334,17 @@ 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())]); + // Protect concrete files and UDIM references from earlier texture sets + if let Some(job) = app.ui.export.job.as_ref().filter(|job| !job.written.is_empty()) { + params["reservedNames"] = job.written.iter().chain(&job.material_udim_patterns).map(|name| json!(name)).collect(); + } + let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; }; - let files: Vec = response - .get("files") - .and_then(|file| file.as_array()) - .into_iter() - .flatten() - .filter_map(|file| file.as_str()) + let files: Vec = response_strings(&response, "files") .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) .collect(); let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; @@ -345,36 +353,63 @@ 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_strings(&response, "warnings"); + for warning in warnings { + let Some(job) = app.ui.export.job.as_mut() else { break }; + if job.shown_warnings.iter().any(|seen| seen == warning) { + continue; + } + + job.shown_warnings.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() { job.written.extend(files); + job.material_udim_patterns.extend(response_strings(&response, "materialUdimPatterns").map(str::to_owned)); } } +fn response_strings<'a>(response: &'a serde_json::Value, field: &str) -> impl Iterator { + response.get(field).and_then(|items| items.as_array()).into_iter().flatten().filter_map(|item| item.as_str()) +} + /// The `file.exportTextures` / `export.plan` parameters of the window's global settings pub(crate) fn export_params(app: &TextureCraftApp) -> serde_json::Value { - let e = &app.ui.export; - let mut p = json!({"preset": e.preset, "padding": e.padding, "dilation": e.dilation}); - if !e.format.is_empty() { - p["format"] = json!(e.format); + let settings = &app.ui.export; + let mut params = json!({"preset": settings.preset, "padding": settings.padding, "dilation": settings.dilation}); + if !settings.format.is_empty() { + params["format"] = json!(settings.format); } - if !e.format.is_empty() && e.bit_depth > 0 { - p["bitDepth"] = json!(e.bit_depth); - p["dithering"] = json!(e.dithering); + if !settings.format.is_empty() && settings.bit_depth > 0 { + params["bitDepth"] = json!(settings.bit_depth); + params["dithering"] = json!(settings.dithering); } - match e.size { + match settings.size { 0 => {} - SIZE_OF_LARGEST_SET => p["size"] = json!(largest_set(app)), - n => p["size"] = json!(n), + SIZE_OF_LARGEST_SET => params["size"] = json!(largest_set(app)), + size => params["size"] = json!(size), } - if !e.normal_format.is_empty() { - p["normalFormat"] = json!(e.normal_format); + if !settings.normal_format.is_empty() { + params["normalFormat"] = json!(settings.normal_format); } - if !e.color_space.is_empty() { - p["colorSpace"] = json!(e.color_space); + if !settings.color_space.is_empty() { + params["colorSpace"] = json!(settings.color_space); } - p + + // The browser downloads the textures only + #[cfg(not(target_arch = "wasm32"))] + if settings.materialx { + params["materialX"] = json!(true); + } + + params } /// The parameters exporting texture set `ts`: the global settings with the set's overrides @@ -629,11 +664,32 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Restore the default export parameters"), false, ICON).clicked(); }); 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); - crate::export_templates::select(app, d.preset); + let defaults = ExportUi::default(); + let settings = &mut app.ui.export; + ( + settings.dir, + settings.format, + settings.bit_depth, + settings.dithering, + settings.size, + settings.padding, + settings.dilation, + settings.normal_format, + settings.color_space, + settings.materialx, + ) = ( + defaults.dir, + defaults.format, + defaults.bit_depth, + defaults.dithering, + defaults.size, + defaults.padding, + defaults.dilation, + defaults.normal_format, + defaults.color_space, + defaults.materialx, + ); + crate::export_templates::select(app, defaults.preset); } let (first, rest) = template_groups(app, builtins); egui::Grid::new("exp_grid").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { @@ -648,29 +704,29 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] ui.end_row(); ui.label(tr("File type")); ui.horizontal(|ui| { - let e = &mut app.ui.export; - file_type_lists(ui, ("exp_global", 0, 0), true, &mut e.format, &mut e.bit_depth, &mut e.dithering); + let settings = &mut app.ui.export; + file_type_lists(ui, ("exp_global", 0, 0), true, &mut settings.format, &mut settings.bit_depth, &mut settings.dithering); }); ui.end_row(); ui.label(tr("Size")); - let e = &mut app.ui.export; - egui::ComboBox::from_id_salt("exp_size").width(VALUE_WIDTH).selected_text(size_label(e.size)).show_ui(ui, |ui| { - ui.selectable_value(&mut e.size, 0, size_label(0)); + let settings = &mut app.ui.export; + egui::ComboBox::from_id_salt("exp_size").width(VALUE_WIDTH).selected_text(size_label(settings.size)).show_ui(ui, |ui| { + ui.selectable_value(&mut settings.size, 0, size_label(0)); ui.separator(); - ui.selectable_value(&mut e.size, SIZE_OF_LARGEST_SET, size_label(SIZE_OF_LARGEST_SET)); - for r in SIZES { - ui.selectable_value(&mut e.size, r, size_label(r)); + ui.selectable_value(&mut settings.size, SIZE_OF_LARGEST_SET, size_label(SIZE_OF_LARGEST_SET)); + for size in SIZES { + ui.selectable_value(&mut settings.size, size, size_label(size)); } }); ui.end_row(); ui.label(tr("Padding")); ui.horizontal(|ui| { - egui::ComboBox::from_id_salt("exp_pad").width(260.0).selected_text(tr(padding_label(&e.padding))).show_ui(ui, |ui| { - for (v, l) in PADDINGS { - ui.selectable_value(&mut e.padding, v.to_string(), tr(l)); + egui::ComboBox::from_id_salt("exp_pad").width(260.0).selected_text(tr(padding_label(&settings.padding))).show_ui(ui, |ui| { + for (value, label) in PADDINGS { + ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); } }); - dilation_button(ui, &e.padding, &mut e.dilation); + dilation_button(ui, &settings.padding, &mut settings.dilation); }); ui.end_row(); }); @@ -678,27 +734,33 @@ 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 + #[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; + let settings = &mut app.ui.export; ui.label(tr("Normal map format")); - let nf = match e.normal_format.as_str() { + let normal_label = match settings.normal_format.as_str() { "openGl" => "OpenGL", "directX" => "DirectX", _ => tr("From template / project"), }; - egui::ComboBox::from_id_salt("exp_nf").selected_text(nf).show_ui(ui, |ui| { - for (v, l) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] { - ui.selectable_value(&mut e.normal_format, v.to_string(), l); + egui::ComboBox::from_id_salt("exp_nf").selected_text(normal_label).show_ui(ui, |ui| { + for (value, label) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] { + ui.selectable_value(&mut settings.normal_format, value.to_string(), label); } }); ui.end_row(); ui.label(tr("Color space")); - let shown = if e.color_space.is_empty() { tr("Default") } else { e.color_space.as_str() }; + let shown = if settings.color_space.is_empty() { tr("Default") } else { settings.color_space.as_str() }; egui::ComboBox::from_id_salt("exp_cs").selected_text(shown).show_ui(ui, |ui| { - ui.selectable_value(&mut e.color_space, String::new(), tr("Default")); + ui.selectable_value(&mut settings.color_space, String::new(), tr("Default")); for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { - ui.selectable_value(&mut e.color_space, name.to_string(), name); + ui.selectable_value(&mut settings.color_space, name.to_string(), name); } }); ui.end_row(); 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/src/state/export_job.rs b/crates/ui-egui/src/state/export_job.rs index 4ba0d485..4668df27 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -13,6 +13,10 @@ pub struct ExportJob { pub directory: String, /// File names written so far. pub written: Vec, + /// UDIM file patterns referenced by materials written earlier in this export. + pub material_udim_patterns: Vec, /// The frame that wrote the last texture set (a frame's second pass writes none). pub frame: u64, + /// Warning messages already shown in this export. + pub shown_warnings: Vec, } 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..9a26f2be --- /dev/null +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -0,0 +1,306 @@ +//! 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; +use texturecraft_ui_egui::state::ConsoleLine; + +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 app_harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + app_harness.state_mut().ui.prefs.language = "en".into(); + app_harness.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); + app_harness.state_mut().ui.export.dir = dir.display().to_string(); + app_harness.state_mut().ui.windows.export = true; + app_harness.run_steps(4); + + (app_harness, dir) +} + +fn checkbox<'a>(app_harness: &'a Harness<'static, TextureCraftApp>) -> egui_kittest::Node<'a> { + app_harness.get_by_role_and_label(egui::Role::CheckBox, "Export MaterialX") +} + +/// Click Export and run frames until the export ends +fn export(app_harness: &mut Harness<'static, TextureCraftApp>) { + app_harness.get_all_by_label("Export").last().unwrap().click(); + for _ in 0..64 { + app_harness.run_steps(1); + if app_harness.state().ui.export.job.is_none() { + break; + } + } + app_harness.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 (app_harness, _dir) = harness("offer"); + + assert!(!checkbox(&app_harness).accesskit_node().is_disabled()); + assert!(!app_harness.state().ui.export.materialx); +} + +#[test] +fn ticking_export_materialx_writes_one_mtlx_per_texture_set() { + let (mut app_harness, dir) = harness("on"); + app_harness.state_mut().ui.export.preset = OPENPBR.into(); + app_harness.run_steps(3); + + checkbox(&app_harness).click(); + app_harness.run_steps(3); + assert!(app_harness.state().ui.export.materialx); + + export(&mut app_harness); + + let files = mtlx_files(&dir); + assert_eq!(files.len(), app_harness.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(" 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); +} + +#[test] +fn materialx_uses_the_selected_sets_effective_file_type_and_size() { + use texturecraft_ui_egui::state::{FileType, SetExport}; + + let (mut harness, directory) = harness("set-overrides"); + harness.state_mut().ui.export.skip = vec![0]; + harness + .state_mut() + .ui + .export + .sets + .insert(1, SetExport { file_type: Some(FileType { format: "tiff".into(), bit_depth: 16, dithering: false }), size: Some(128), ..Default::default() }); + harness.run_steps(3); + checkbox(&harness).click(); + harness.run_steps(3); + + export(&mut harness); + + let materials = mtlx_files(&directory); + assert_eq!(materials.len(), 1); + let selected_set = &harness.state().session.doc.project.texture_sets[1]; + let expected_stem = texturecraft_engine::formats::export::sanitize_file_stem(&format!("material_ball_{}", selected_set.name)); + assert_eq!(materials[0].file_stem().unwrap(), expected_stem.as_str()); + + let document = std::fs::read_to_string(&materials[0]).unwrap(); + let reference = document + .split("name=\"file\" type=\"filename\" value=\"") + .skip(1) + .filter_map(|input| input.split('"').next()) + .find(|filename| filename.ends_with("_base_color.tif")) + .unwrap(); + let image = image::open(directory.join(reference)).unwrap(); + assert_eq!((image.width(), image.height()), (128, 128)); + assert_eq!(image.color(), image::ColorType::Rgb16); + let _ = std::fs::remove_dir_all(&directory); +} + +/// 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() { + let (mut app_harness, dir) = harness("off"); + app_harness.state_mut().ui.export.preset = OPENPBR.into(); + app_harness.run_steps(3); + + export(&mut app_harness); + + assert!(std::fs::read_dir(&dir).unwrap().next().is_some(), "the textures were written"); + assert!(mtlx_files(&dir).is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn restoring_the_default_parameters_unticks_export_materialx() { + let (mut app_harness, _dir) = harness("reset"); + checkbox(&app_harness).click(); + app_harness.run_steps(3); + assert!(app_harness.state().ui.export.materialx); + + app_harness.get_by_label("Restore the default export parameters").click(); + app_harness.run_steps(3); + assert!(!app_harness.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 app_harness, dir) = harness("warning"); + assert!(app_harness.state().session.set_count() >= 2, "the warning has to come from more than one texture set"); + let e = &mut app_harness.state_mut().ui.export; + e.preset = OPENPBR.into(); + e.normal_format = "directX".into(); + app_harness.run_steps(3); + + checkbox(&app_harness).click(); + app_harness.run_steps(3); + export(&mut app_harness); + + let lines: Vec<&str> = app_harness + .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!(app_harness.state().session.log.iter().filter(|line| line.contains(DIRECTX_WARNING)).count(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_export_with_no_enabled_maps_reports_that_no_files_were_written() { + use texturecraft_ui_egui::state::{MapExport, SetExport}; + + let (mut app_harness, directory) = harness("empty"); + let map_count = app_harness.state().session.export_preset(OPENPBR).unwrap().maps.len(); + let maps = (0..map_count).map(|index| (index, MapExport { enabled: false, ..Default::default() })).collect(); + let skipped = (1..app_harness.state().session.set_count()).collect(); + let settings = &mut app_harness.state_mut().ui.export; + settings.preset = OPENPBR.into(); + settings.skip = skipped; + settings.sets.insert(0, SetExport { maps_template: OPENPBR.into(), maps, ..Default::default() }); + settings.materialx = true; + app_harness.run_steps(3); + + export(&mut app_harness); + + assert!(std::fs::read_dir(&directory).unwrap().next().is_none()); + let console = &app_harness.state().ui.export.console; + assert!(console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.contains("has no OpenPBR maps"))), "{console:?}"); + assert!(matches!(console.last(), Some(ConsoleLine::Step(text)) if text == "No files were written"), "{console:?}"); + let _ = std::fs::remove_dir(&directory); +} + +/// 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(app_harness: &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 app_harness.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"; + + 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", "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)", "base colour only", Some("material_ball_a.mtlx")), + ]; + for (index, (first, second, template_of_set_0, template_of_set_1, referred_by)) in cases.into_iter().enumerate() { + let (mut app_harness, dir) = harness(&format!("overwrite-{index}")); + let project = &mut app_harness.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(); + app_harness.state_mut().session.export_presets.list.push(template); + app_harness.state_mut().ui.export.preset = name; + app_harness.run_steps(3); + checkbox(&app_harness).click(); + app_harness.run_steps(3); + + export(&mut app_harness); + + let want = expected(&mut app_harness, 0, template_of_set_0, SHARED, &index.to_string()); + let rival = expected(&mut app_harness, 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 = + app_harness.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:?}"); + 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/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index ef91cc44..d9ed98f0 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -22,6 +22,7 @@ mod effect_sliders; mod empty_start; mod export_file_types; mod export_map_overrides; +mod export_materialx; mod export_overrides; mod export_progress; mod export_settings; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d963eb9c..ecb5cdbf 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -47,6 +47,19 @@ 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 an OpenPBR `.mtlx` beside each texture +set's maps. It reuses compatible maps with OpenPBR names and writes dedicated maps for remaining +inputs with data. A named OpenPBR map explicitly disabled in `maps` stays disabled. Dedicated maps +use the effective size, padding and color space. A dedicated replacement for a named map keeps +its file settings where supported. PSD, JNG, PGM and WebP fall back to the OpenPBR template's PNG +format and bit depth. MaterialX uses OpenGL normals. + +`reservedNames: [file names]` takes the basenames and `materialUdimPatterns` returned by earlier +`file.exportTextures` calls in the same export. The desktop window passes both when exporting +one set at a time. Comparisons ignore case. If a name is reserved, the command skips the file +and names it in `warnings`. Materials omit any map with incomplete tiles or a UDIM pattern +shared by different sets. + `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 82c650a4..14e1be68 100644 --- a/docs/features.md +++ b/docs/features.md @@ -175,8 +175,18 @@ 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 an OpenPBR `.mtlx` for + each selected texture set with usable maps. Materials reference textures beside the document. + The export reuses compatible OpenPBR maps and writes dedicated maps for the other supported + inputs using the set's effective settings. Dedicated maps use PNG when the chosen file type + is unsuitable, and a DirectX export keeps its selected normal alongside a separate OpenGL + normal for the material. The export console identifies collisions and skipped files. + The browser shows the option disabled. The exporter supports OpenPBR maps including base + color, roughness and normals. Standard Surface, coat normal, specular level, anisotropy angle + and constants such as IOR remain open. - **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). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f7dad7ed..b8e6d060 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -69,7 +69,8 @@ that closes it back onto the bar; the float is saved with the UI state. *Mesh Export Options* prompt, then the file choice) and *Export Textures...* (the Export textures window: *Global settings* above the texture sets, *General Export Parameters*, *Export USD asset* and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected - for export"). The prompt's *With displacement/tessellation* choice and both option checkboxes are + for export"). *Export MaterialX* beside them is a TextureCraft addition: it adds `materialX: true` + to the export. The prompt's *With displacement/tessellation* choice and both option checkboxes are greyed; TextureCraft exports the mesh as it is. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the samples so far and a note; it floats when first opened and is not opened by itself in Rendering @@ -220,7 +221,7 @@ built-in `udim_plane`, a uniform fill and a tile-1002 resolution override. - The shelf displayed four columns at the larger size, with type controls and search. Do not treat every older shelf-layout request as a currently missing implementation. - A missing mask-thumbnail menu does not mean mask effects are unavailable: the layer-name menu - worked. A missing MaterialX UI option does not mean the exporter is absent. + worked. ## Still unverified