From c0523d2f68336ad9855dc9813bd4041bbe3f07a3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 20:40:46 +0100 Subject: [PATCH] Write the model as a USD file that uses the exported textures from the export window --- Cargo.lock | 2 + crates/engine/Cargo.toml | 1 + crates/engine/src/file_cmds.rs | 75 +++- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/usd_asset.rs | 319 ++++++++++++++ crates/formats/README.md | 8 + crates/formats/src/export/mod.rs | 2 +- crates/formats/src/lib.rs | 5 +- crates/formats/src/mesh_export.rs | 2 +- crates/formats/src/mesh_export/usd.rs | 440 +++++++++++++++++++- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/export_window.rs | 45 +- crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/state/export_job.rs | 5 + crates/ui-egui/tests/it/export_usd_asset.rs | 211 ++++++++++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/side_panels.rs | 3 +- docs/control-protocol.md | 12 + docs/features.md | 13 + docs/ui-parity.md | 6 +- 20 files changed, 1138 insertions(+), 19 deletions(-) create mode 100644 crates/engine/tests/it/usd_asset.rs create mode 100644 crates/ui-egui/tests/it/export_usd_asset.rs diff --git a/Cargo.lock b/Cargo.lock index 84a1a752..18976898 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5173,6 +5173,7 @@ name = "texturecraft-engine" version = "0.6.1" dependencies = [ "chrono", + "craft-usd", "epaint_default_fonts", "image", "processkit", @@ -5292,6 +5293,7 @@ dependencies = [ "craft-quit", "craft-ui", "craft-update", + "craft-usd", "craft-window", "eframe", "egui", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b6082f63..52b37891 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -37,5 +37,6 @@ tokio = { workspace = true } rustix = { workspace = true } [dev-dependencies] +craft-usd.workspace = true image = { workspace = true } zip = { workspace = true } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f493093b..43dc4087 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts and options, a list gives each texture set's own `ts` and options, the export window sends it with the last command; a failure is a warning)}", always, export_textures ), @@ -640,6 +640,7 @@ 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")?; + let usd_asset = usd_asset_param(s, p, &opts, &sets)?; 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(); @@ -647,10 +648,82 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { 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)?); } + if let Some(exports) = &usd_asset { + written.extend(write_usd_asset(s, std::path::Path::new(&dir), exports, &mut warnings)); + } 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 })) } +/// What the warning of a USD asset that could not be written starts with (`file.exportTextures`). +pub const USD_ASSET_FAILED: &str = "The USD asset was not written"; + +/// The texture sets and options of the exports a USD asset refers to. +#[cfg(not(target_arch = "wasm32"))] +type UsdExports = Vec<(Vec, ExportOptions)>; + +/// What `usdAsset` asks for: the texture sets and options of each export whose textures the USD +/// asset refers to. `true` is this command's own; a list gives every entry's `ts` and options. +#[cfg(not(target_arch = "wasm32"))] +fn usd_asset_param(s: &Session, p: &Value, opts: &ExportOptions, sets: &[usize]) -> Result> { + match p.get("usdAsset") { + None | Some(Value::Null | Value::Bool(false)) => Ok(None), + Some(Value::Bool(true)) => Ok(Some(vec![(sets.to_vec(), opts.clone())])), + Some(Value::Array(exports)) if !exports.is_empty() && exports.iter().all(Value::is_object) => exports + .iter() + .map(|export| Ok((sets_param(s, export, "file.exportTextures")?, export_options(s, export, "file.exportTextures")?))) + .collect::>>() + .map(Some), + Some(_) => Err(bad("file.exportTextures", "`usdAsset` must be true, false or a non-empty list of export param objects")), + } +} + +/// `.usd` (binary USD) next to the textures: the whole mesh (every texture set, not only the sets of this +/// command) with a UsdPreviewSurface material per texture set that reads the files `exports` +/// wrote (see `texturecraft_formats::usd_texture_bindings`). A failure to build or write it is a +/// warning: the textures of the command are already written. +#[cfg(not(target_arch = "wasm32"))] +fn write_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec, ExportOptions)], warnings: &mut Vec) -> Option { + match build_usd_asset(s, dir, exports) { + Ok(path) => Some(path), + Err(e) => { + warnings.push(format!("{USD_ASSET_FAILED}: {e}")); + None + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn build_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec, ExportOptions)]) -> Result { + use texturecraft_formats::{export::list_set_outputs, usd_layer_with_textures, usd_texture_bindings}; + let project = &s.doc.project; + let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); + + // The bindings of every texture set that was exported, from the files its export planned + let mut taken = std::collections::HashSet::new(); + let mut by_set = std::collections::HashMap::new(); + for (sets, opts) in exports { + // A file whose name an earlier export of this job has was not written by this one + let planned: Vec<_> = list_set_outputs(project, sets, &mesh_name, opts) + .map_err(fe)? + .into_iter() + .filter(|(_, file)| taken.insert(file.name.to_ascii_lowercase())) + .collect(); + for &set in sets { + let files: Vec<_> = planned.iter().filter(|(ts, _)| *ts == set).map(|(_, file)| file.clone()).collect(); + let texture_set = project.texture_set(set).map_err(|e| EngineError::Other(e.to_string()))?; + by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, opts, project.normal_format, &files)); + } + } + + let mesh = s.source_mesh(); + let bindings: Vec<_> = (0..mesh.materials.len()).map(|m| s.texture_set_of_material(m).and_then(|set| by_set.remove(&set)).unwrap_or_default()).collect(); + let layer = usd_layer_with_textures(&mesh, &project.name, &bindings).map_err(fe)?; + let path = dir.join(format!("{}.usd", texturecraft_formats::export::sanitize_file_stem(&mesh_name))); + texturecraft_formats::write_atomic(&path, &layer).map_err(fe)?; + Ok(path) +} + /// 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 diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c38e850b..ce9f1614 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -66,5 +66,6 @@ mod tool_availability; mod tool_settings; mod tools; mod udim; +mod usd_asset; mod user_smart_mask; mod uv_strokes; diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs new file mode 100644 index 00000000..3c6458a4 --- /dev/null +++ b/crates/engine/tests/it/usd_asset.rs @@ -0,0 +1,319 @@ +//! `file.exportTextures` with `usdAsset`: `.usd` next to the textures, the whole mesh with +//! a material per texture set that reads the textures the export wrote. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. +struct Scratch(std::path::PathBuf); + +impl std::ops::Deref for Scratch { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn temp(tag: &str) -> Scratch { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("tc_usd_asset_{tag}_{}_{seq}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Scratch(dir) +} + +fn ball() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +fn files(r: &Value) -> Vec { + r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect() +} + +fn export(s: &mut Session, dir: &std::path::Path, params: Value) -> Value { + let mut params = params; + params["dir"] = json!(dir.display().to_string()); + execute(s, "file.exportTextures", ¶ms).unwrap() +} + +/// What a UsdPreviewSurface input reads +#[derive(Debug, PartialEq, Clone)] +struct Read { + file: String, + output: String, + colour_space: String, + /// The texture shader flips green (a DirectX normal map) + flips_green: bool, +} + +/// The prim name the exporter gives a mesh material +fn identifier(name: &str) -> String { + let mut id: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); + if !id.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') { + id.insert(0, '_'); + } + id +} + +/// The binary USD file read back: per mesh material, the inputs of its UsdPreviewSurface that read a texture, and the number of texture shaders +fn materials(bytes: &[u8], mesh_materials: &[String]) -> Vec<(BTreeMap, usize)> { + use craft_usd::scene::Val; + let layer = craft_usd::scene::read_layer(bytes).unwrap(); + let prim = |path: &str| layer.prims.iter().find(|p| p.path == path).unwrap_or_else(|| panic!("no prim {path}")); + let first = |prop: Option<&craft_usd::scene::Prop>| match prop.and_then(|p| p.value.as_ref()) { + Some(Val::Tok(values)) => values.first().cloned().unwrap_or_default(), + other => panic!("not a token or an asset: {other:?}"), + }; + mesh_materials + .iter() + .map(|name| { + let id = identifier(name); + let material = layer.prims.iter().find(|p| p.type_name == "Material" && p.name == id).unwrap_or_else(|| panic!("no material {id}")); + let pbr = prim(&format!("{}/PBR", material.path)); + let mut inputs = BTreeMap::new(); + for (key, prop) in &pbr.props { + let (Some(input), Some(source)) = (key.strip_prefix("inputs:"), &prop.connect) else { continue }; + let (shader, output) = source.rsplit_once('/').unwrap().1.split_once(".outputs:").unwrap(); + let texture = prim(&format!("{}/{shader}", material.path)); + let flips_green = match texture.props.get("inputs:scale").and_then(|p| p.value.as_ref()) { + Some(Val::Num(scale)) => scale.get(1).is_some_and(|green| *green < 0.0), + _ => false, + }; + let read = Read { + file: first(texture.props.get("inputs:file")).trim_start_matches("./").to_string(), + output: output.into(), + colour_space: first(texture.props.get("inputs:sourceColorSpace")), + flips_green, + }; + inputs.insert(input.to_string(), read); + } + let prefix = format!("{}/", material.path); + (inputs, layer.prims.iter().filter(|p| p.path.starts_with(&prefix) && p.props.contains_key("inputs:file")).count()) + }) + .collect() +} + +/// The materials of `/material_ball.usd`, indexed by mesh material +fn read_back(s: &Session, dir: &std::path::Path) -> Vec<(BTreeMap, usize)> { + let materials = materials(&std::fs::read(dir.join("material_ball.usd")).unwrap(), &s.mesh.materials); + assert_eq!(materials.len(), s.set_count()); + materials +} + +fn material_of(s: &Session, set: usize) -> usize { + s.doc.project.texture_sets[set].material +} + +#[test] +fn it_writes_the_mesh_with_materials_that_read_the_exported_textures() { + let mut s = ball(); + assert!(s.set_count() > 1, "the test needs several texture sets"); + let dir = temp("default"); + let r = export(&mut s, &dir, json!({"usdAsset": true})); + assert!(files(&r).iter().any(|f| f.ends_with("material_ball.usd")), "the asset is listed: {r}"); + + let materials = read_back(&s, &dir); + for set in 0..s.set_count() { + let name = &texturecraft_formats::export::sanitize_file_stem(&s.doc.project.texture_sets[set].name); + let inputs = &materials[material_of(&s, set)].0; + let read = |input: &str| inputs.get(input).unwrap_or_else(|| panic!("{input} of {name}: {inputs:?}")).clone(); + for (input, output, space) in [("diffuseColor", "rgb", "sRGB"), ("roughness", "r", "raw"), ("metallic", "r", "raw"), ("normal", "rgb", "raw")] { + let read = read(input); + assert_eq!((read.output.as_str(), read.colour_space.as_str()), (output, space), "{input} of {name}"); + assert!(read.file.starts_with(&format!("material_ball_{name}_")), "{input} reads a file of its own texture set: {}", read.file); + assert!(dir.join(&read.file).is_file(), "{} was written", read.file); + assert!(!read.flips_green, "the project's normals are OpenGL"); + } + assert!(!inputs.contains_key("opacity") && !inputs.contains_key("clearcoat"), "channels the set does not have stay unbound: {inputs:?}"); + } +} + +#[test] +fn a_packed_template_reads_different_outputs_of_one_file() { + let mut s = ball(); + let dir = temp("packed"); + export(&mut s, &dir, json!({"preset": "Unreal Engine (Packed)", "usdAsset": true})); + + for (inputs, shaders) in read_back(&s, &dir) { + assert_eq!(shaders, 3, "four inputs read three files: {inputs:?}"); + let (roughness, metallic) = (&inputs["roughness"], &inputs["metallic"]); + assert_eq!(roughness.file, metallic.file, "{inputs:?}"); + assert!(roughness.file.contains("OcclusionRoughnessMetallic"), "{}", roughness.file); + assert_eq!((roughness.output.as_str(), metallic.output.as_str()), ("g", "b")); + assert_ne!(inputs["diffuseColor"].file, roughness.file); + + // The template writes DirectX normals + assert!(inputs["normal"].flips_green, "{inputs:?}"); + assert!(!inputs.contains_key("opacity"), "the base colour file has no alpha without an opacity channel"); + } +} + +#[test] +fn the_normal_convention_of_the_files_decides_whether_green_is_flipped() { + let mut s = ball(); + let (open_gl, direct_x) = (temp("normal-gl"), temp("normal-dx")); + export(&mut s, &open_gl, json!({"usdAsset": true, "normalFormat": "openGl"})); + export(&mut s, &direct_x, json!({"usdAsset": true, "normalFormat": "directX"})); + for (inputs, _) in read_back(&s, &open_gl) { + assert!(!inputs["normal"].flips_green); + } + for (inputs, _) in read_back(&s, &direct_x) { + assert!(inputs["normal"].flips_green); + } +} + +#[test] +fn a_texture_set_outside_the_export_has_no_textures() { + let mut s = ball(); + let dir = temp("subset"); + export(&mut s, &dir, json!({"ts": 0, "usdAsset": true})); + + let materials = read_back(&s, &dir); + assert!(!materials[material_of(&s, 0)].0.is_empty()); + assert!(materials[material_of(&s, 1)].0.is_empty(), "{:?}", materials[material_of(&s, 1)]); + let name = texturecraft_formats::export::sanitize_file_stem(&s.doc.project.texture_sets[1].name); + assert!(!std::fs::read_dir(&*dir).unwrap().flatten().any(|e| e.file_name().to_string_lossy().contains(&format!("_{name}_"))), "set 1 was not written"); +} + +#[test] +fn a_list_gives_each_texture_set_its_own_options() { + let mut s = ball(); + let dir = temp("list"); + export(&mut s, &dir, json!({"ts": 0})); + let list = json!([{"ts": 0}, {"ts": 1, "preset": "Unreal Engine (Packed)"}]); + export(&mut s, &dir, json!({"ts": 1, "preset": "Unreal Engine (Packed)", "usdAsset": list})); + + let materials = read_back(&s, &dir); + let first = &materials[material_of(&s, 0)].0; + let second = &materials[material_of(&s, 1)].0; + assert_eq!(first["roughness"].output, "r", "{first:?}"); + assert_eq!(second["roughness"].output, "g", "{second:?}"); + for read in first.values().chain(second.values()) { + assert!(dir.join(&read.file).is_file(), "{} was written", read.file); + } +} + +#[test] +fn it_is_not_written_unless_asked_for() { + let mut s = ball(); + let dir = temp("off"); + let off = export(&mut s, &dir, json!({})); + let explicit = export(&mut s, &dir, json!({"usdAsset": false})); + for r in [off, explicit] { + assert!(!files(&r).is_empty(), "the textures are written"); + assert!(!files(&r).iter().any(|f| f.ends_with(".usd")), "{r}"); + } + assert!(!dir.join("material_ball.usd").exists()); +} + +#[test] +fn a_failure_to_write_it_is_a_warning_and_the_textures_are_still_reported() { + let mut s = ball(); + let dir = temp("blocked"); + + // A folder where the file belongs: the asset cannot be written there + std::fs::create_dir_all(dir.join("material_ball.usd")).unwrap(); + let r = export(&mut s, &dir, json!({"usdAsset": true})); + + assert!(!files(&r).iter().any(|f| f.ends_with(".usd")), "{r}"); + assert!(files(&r).iter().any(|f| f.ends_with(".png")), "the textures are reported: {r}"); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().unwrap().starts_with("The USD asset was not written")), "{r}"); + assert!(dir.join("material_ball.usd").is_dir()); +} + +#[test] +fn the_asset_opens_again_with_its_textures_from_the_folder() { + let mut s = ball(); + let dir = temp("roundtrip"); + export(&mut s, &dir, json!({"usdAsset": true})); + + // The importer reads only the texture of the base colour, but every input the file binds reads a file of the folder + for (inputs, _) in read_back(&s, &dir) { + assert!(inputs.len() >= 4, "{inputs:?}"); + for read in inputs.values() { + assert!(dir.join(&read.file).is_file(), "{} is in the folder", read.file); + } + } + + let file = texturecraft_formats::read_mesh_file(&dir.join("material_ball.usd")).unwrap(); + assert!(file.warnings.is_empty(), "every texture it names is in the folder: {:?}", file.warnings); + assert!(file.name.ends_with(".usdz"), "the base colour texture is found and packaged: {}", file.name); + let package = zip::ZipArchive::new(std::io::Cursor::new(&file.bytes)).unwrap(); + assert!(package.file_names().any(|name| name.is_ok_and(|name| name.ends_with(".png")))); + + let back = texturecraft_formats::import_mesh_bytes(&file.name, &file.bytes).unwrap(); + assert_eq!(back.mesh.triangle_count(), s.mesh.triangle_count()); + assert_eq!(back.mesh.materials.len(), s.set_count()); +} + +#[test] +fn a_bad_usd_asset_value_is_an_error_before_anything_is_written() { + let mut s = ball(); + for value in [json!("x"), json!([]), json!([1]), json!([{"ts": 0}, "x"]), json!([{"ts": 99}]), json!({"ts": 0})] { + let dir = temp("bad"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "usdAsset": value})); + assert!(r.is_err(), "{value}"); + assert!(!dir.exists(), "nothing was written for {value}"); + } +} + +#[test] +fn the_tiles_of_a_uv_tiled_set_are_read_through_one_udim_name() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let dir = temp("udim"); + export(&mut s, &dir, json!({"usdAsset": true})); + + let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &s.mesh.materials); + let colour = &materials[0].0["diffuseColor"]; + assert!(colour.file.ends_with("..png"), "{}", colour.file); + for tile in ["1001", "1002"] { + assert!(dir.join(colour.file.replace("", tile)).is_file(), "tile {tile} was written"); + } +} + +/// A template with one map, the base colour, whose name does not tell texture sets apart +fn shared_name_template() -> Value { + let rgb: Vec = (0..3) + .map(|k| { + let dest = ["R", "G", "B"][k]; + json!([dest, {"Channel": {"channel": "BaseColor", "component": k}}]) + }) + .collect(); + json!({"name": "shared", "maps": [{"file": "colour", "format": "Png", "bit_depth": 8, "channels": rgb}]}) +} + +#[test] +fn a_file_name_an_earlier_export_of_the_job_has_is_not_read_by_a_later_one() { + let mut s = ball(); + let dir = temp("same-name"); + let list = json!([{"ts": 0, "preset": shared_name_template()}, {"ts": 1, "preset": shared_name_template()}]); + export(&mut s, &dir, json!({"ts": 1, "preset": shared_name_template(), "usdAsset": list})); + + let materials = read_back(&s, &dir); + assert_eq!(materials[material_of(&s, 0)].0["diffuseColor"].file, "colour.png"); + assert!(materials[material_of(&s, 1)].0.is_empty(), "the later set's file would have replaced the earlier one: {:?}", materials[material_of(&s, 1)]); +} + +#[test] +fn a_material_without_a_texture_set_has_no_textures() { + let mut s = ball(); + + // Both texture sets paint the first material (which the first set stands for): the second has none + s.doc.project.texture_sets[1].material = 0; + let dir = temp("no-set"); + export(&mut s, &dir, json!({"usdAsset": true})); + + let materials = read_back(&s, &dir); + assert!(!materials[0].0.is_empty()); + assert!(materials[1].0.is_empty(), "{:?}", materials[1]); +} diff --git a/crates/formats/README.md b/crates/formats/README.md index 4033b1be..f56dbc36 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -52,6 +52,9 @@ pub fn usd_bytes(mesh: &Mesh, name: &str, textures: &[Vec], format pub fn usd_export_options() -> ExportOptions; // render each material's textures with these pub enum UsdFormat { Usda, Usdc, Usdz } pub struct UsdExport { pub bytes: Vec, pub textures: Vec<(String, Vec)> } // textures: usda/usdc only +pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec; // which UsdPreviewSurface input reads which output of which exported file +pub fn usd_layer_with_textures(mesh: &Mesh, name: &str, bindings: &[Vec]) -> Result>; // binary `.usd` (Crate) only; material m reads bindings[m] as ./ +pub struct UsdTextureBinding { /* opaque */ } ``` OBJ export propagates shared writer validation and limit errors rather than returning empty bytes. @@ -65,6 +68,11 @@ emissive maps dropped, and both clear coat maps when the coat is black). Meters, `.usdc` is a Crate 0.8.0 file; `.usdz` is that layer first plus the PNGs, stored uncompressed at 64-byte aligned offsets; `.usda` / `.usdc` reference `__.png` next to the layer. +`usd_layer_with_textures` writes the same scene as a binary `.usd` (Crate) whose materials read texture files the +caller already wrote (the Export textures window's USD asset): `usd_texture_bindings` binds base +color, roughness, metallic, normal (scale/bias for the file's green convention), emissive color, +opacity, clear coat and clear coat roughness by what each map of the template holds, each reading +the `rgb`, `r`, `g`, `b` or `a` output of its file; one texture shader per file, so packed maps work. GLB: one primitive per submesh, one metallic-roughness material per mesh material with its textures embedded in the binary chunk (base color sRGB, `alphaMode: BLEND` when it has alpha; diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index cdcb9c36..35edb66a 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -514,7 +514,7 @@ fn normal_present(set: &TextureSet) -> bool { } /// A source with real data in this texture set (constants never count). -fn source_present(set: &TextureSet, s: &SourceRef) -> bool { +pub(crate) fn source_present(set: &TextureSet, s: &SourceRef) -> bool { match s { SourceRef::Channel { channel: Channel::Normal, .. } => normal_present(set), SourceRef::Channel { channel, .. } => set.has_channel(*channel), diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 3fd12036..8dc7d67e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -46,7 +46,10 @@ pub use export::{ render_maps, skip_repeated_names, }; pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource}; -pub use mesh_export::{GlbTextures, NamedFiles, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options}; +pub use mesh_export::{ + GlbTextures, NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options, + usd_layer_with_textures, usd_texture_bindings, +}; pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh}; #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index d35156a9..4cc3b24e 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -15,7 +15,7 @@ use crate::export::sanitize_file_stem; use crate::presets::{GLTF_BASE_COLOR, GLTF_CLEARCOAT, GLTF_EMISSIVE, GLTF_NORMAL, GLTF_ORM, GLTF_SHEEN, gltf_pbr_maps}; use crate::{ExportOptions, ExportPreset, ExportedFile, FileFormat, FormatError, Result}; -pub use usd::{NamedFiles, UsdExport, UsdFormat, usd_bytes, usd_export_options}; +pub use usd::{NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, usd_bytes, usd_export_options, usd_layer_with_textures, usd_texture_bindings}; /// The mesh as OBJ text (UV v flipped back to OBJ's bottom-up convention). /// Invalid mesh data or shared writer limits return an error, never an empty successful export. diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index ee1a7166..c9ace034 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -6,11 +6,15 @@ //! UsdUVTexture shaders. Meters, Y up. use craft_usd::scene::{SceneError, UsdAttr, UsdLayer, UsdPrim, UsdValue, write_usda, write_usdc}; -use texturecraft_core::{Channel, NormalFormat}; +use texturecraft_core::{Channel, NormalFormat, TextureSet}; use texturecraft_geom::Mesh; +use texturecraft_texel::ColorSpace; + use super::{is_black, parts}; -use crate::export::{ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, VirtualMap, sanitize_file_stem}; +use crate::export::{ + Dest, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, PlannedFile, SourceRef, VirtualMap, sanitize_file_stem, source_present, +}; use crate::presets::{ch, gray, rgb, virt}; use crate::{FormatError, Result}; @@ -103,9 +107,9 @@ fn identifier(s: &str, taken: &mut Vec) -> String { id } -/// The export scene: `/` with the `Mesh` and `Materials`. `files[m]` are the texture -/// file names (by slot) of material `m`. -fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result { +/// The export scene: `/` with the `Mesh` and `Materials`. `material(m, path, id)` makes the +/// Material prim `id` at `path` for mesh material `m`. +fn scene(mesh: &Mesh, name: &str, material: impl Fn(usize, &str, &str) -> UsdPrim) -> Result { let vertex_count = mesh.positions.len(); if vertex_count == 0 || mesh.indices.len() < 3 { return Err(FormatError::Invalid("the mesh is empty".into())); @@ -177,7 +181,7 @@ fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result UsdPrim { pub fn usd_bytes(mesh: &Mesh, name: &str, textures: &[Vec], format: UsdFormat) -> Result { let stem = sanitize_file_stem(name); let (names, files) = material_maps(mesh, &stem, textures); - let layer = scene(mesh, name, &names)?; + let layer = scene(mesh, name, |m, path, id| material(path, id, names.get(m).map_or(&[][..], Vec::as_slice)))?; Ok(match format { UsdFormat::Usda => UsdExport { bytes: write_usda(&layer).into_bytes(), textures: files }, UsdFormat::Usdc => UsdExport { bytes: write_usdc(&layer).map_err(map_scene_err)?, textures: files }, @@ -291,6 +295,219 @@ pub(crate) fn usdz(layer_name: &str, layer: &[u8], files: &[(String, Vec)]) zip.finish().map_err(err) } +/// A UsdPreviewSurface input that reads a texture file the export wrote. +#[derive(Clone, Debug, PartialEq)] +pub struct UsdTextureBinding { + /// The input, as an index into the table of UsdPreviewSurface inputs (`SLOTS`). + slot: usize, + /// The file name, `` for a UV-tiled set's tiles. + file: String, + /// The texture output the input reads: `r`, `g`, `b`, `a` or `rgb`. + output: &'static str, + /// The file holds sRGB-encoded colour. + srgb: bool, + /// A normal map: the green convention of its file. + normal: Option, +} + +/// Whether `source` is what UsdPreviewSurface input `slot` (an index into [`SLOTS`]) reads. +fn feeds_slot(slot: usize, source: &SourceRef) -> bool { + let channel = match (slot, source) { + (1, SourceRef::Virtual { map: VirtualMap::Roughness, .. }) => return true, + (3, SourceRef::Virtual { map: VirtualMap::NormalOpenGl | VirtualMap::NormalDirectX, .. }) => return true, + (_, SourceRef::Channel { channel, .. }) => *channel, + _ => return false, + }; + let wanted = match slot { + 0 => Channel::BaseColor, + 1 => Channel::Roughness, + 2 => Channel::Metallic, + 3 => Channel::Normal, + 4 => Channel::Emissive, + 5 => Channel::Opacity, + 6 => Channel::CoatWeight, + _ => Channel::CoatRoughness, + }; + channel == wanted +} + +fn component_of(source: &SourceRef) -> u8 { + match source { + SourceRef::Channel { component, .. } | SourceRef::Virtual { component, .. } | SourceRef::Baked { component, .. } => *component, + SourceRef::Constant(_) => 0, + } +} + +/// The texture output of `map` that input `slot` reads, and the source it takes: a colour or +/// normal input needs the three components in R, G and B, a scalar input reads the destination +/// that holds it. None when the map does not hold the input, when `set` has no data for it (the +/// file then holds a default), when it is written inverted, or when `format` cannot keep it: JPEG +/// and HDR files drop alpha, a PGM file holds one gray channel (a colour map becomes its +/// luminance), which only a map written as L can bind. +fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: FileFormat) -> Option<(&'static str, &'m SourceRef)> { + let holds = |dest: Dest, component: Option| { + map.channels + .iter() + .find(|(d, source)| { + *d == dest + && feeds_slot(slot, source) + && source_present(set, source) + && component.is_none_or(|k| component_of(source) == k) + && !map.inverted.contains(d) + }) + .map(|(_, source)| source) + }; + if SLOTS[slot].2 == "float" { + return [(Dest::R, "r"), (Dest::L, "r"), (Dest::G, "g"), (Dest::B, "b"), (Dest::A, "a")] + .into_iter() + .filter(|(dest, _)| match format { + FileFormat::Pgm => *dest == Dest::L, + FileFormat::Jpeg | FileFormat::Hdr => *dest != Dest::A, + _ => true, + }) + .find_map(|(dest, output)| holds(dest, None).map(|source| (output, source))); + } + + if format == FileFormat::Pgm { + return None; + } + + let red = holds(Dest::R, Some(0))?; + holds(Dest::G, Some(1))?; + holds(Dest::B, Some(2))?; + Some(("rgb", red)) +} + +/// The UsdPreviewSurface inputs the exported `files` of texture set `set` (planned with `opts`) +/// can feed, by what each map holds: base colour, roughness, metallic, normal, emissive colour, +/// opacity, clear coat and clear coat roughness. Maps with none of them (ambient occlusion, +/// height, specular/glossiness, baked maps...) bind nothing, and neither do channels the set has +/// no data for. `project_normal` is the project's normal convention, used by normal maps that +/// follow it. +pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec { + let mut out: Vec = Vec::new(); + let mut seen_maps = Vec::new(); + for file in files { + // The first tile stands for all the tiles of a map + if seen_maps.contains(&file.map) { + continue; + } + + seen_maps.push(file.map); + let Some(map) = opts.preset.maps.get(file.map) else { continue }; + + // A tile whose name has no `` token cannot stand for the others + let name = match (&file.udim_name, file.tile) { + (Some(udim), _) => udim.clone(), + (None, None) => file.name.clone(), + (None, Some(_)) => continue, + }; + let srgb = opts.space_for_map(map, file.format, file.bit_depth) == ColorSpace::Srgb; + for slot in 0..SLOTS.len() { + if out.iter().any(|binding| binding.slot == slot) { + continue; + } + + let Some((output, source)) = output_for_slot(slot, map, set, file.format) else { continue }; + let normal = (slot == 3).then(|| { + opts.normal_format.unwrap_or(match source { + SourceRef::Virtual { map: VirtualMap::NormalOpenGl, .. } => NormalFormat::OpenGl, + SourceRef::Virtual { map: VirtualMap::NormalDirectX, .. } => NormalFormat::DirectX, + _ => project_normal, + }) + }); + out.push(UsdTextureBinding { slot, file: name.clone(), output, srgb, normal }); + } + } + out +} + +/// The mesh as a layer named `name` whose material `m` reads the textures of `bindings[m]`, by +/// relative file name (`./`). +fn textured_layer(mesh: &Mesh, name: &str, bindings: &[Vec]) -> Result { + scene(mesh, name, |m, path, id| textured_material(path, id, bindings.get(m).map_or(&[][..], Vec::as_slice))) +} + +/// The mesh as a binary USD (Crate) file named `name` whose material `m` reads the textures of +/// `bindings[m]`, by relative file name (`./`): the textures are not part of the result. +pub fn usd_layer_with_textures(mesh: &Mesh, name: &str, bindings: &[Vec]) -> Result> { + write_usdc(&textured_layer(mesh, name, bindings)?).map_err(map_scene_err) +} + +/// A UsdPreviewSurface material at `path` whose inputs read `bindings`. One texture shader reads +/// each file (once per colour space and normal convention), so inputs packed into one file read +/// different outputs of it. +fn textured_material(path: &str, id: &str, bindings: &[UsdTextureBinding]) -> UsdPrim { + let mut mat = UsdPrim::new(id, "Material"); + mat.attrs.push(UsdAttr::connected("outputs:surface", "token", format!("{path}/PBR.outputs:surface"))); + let mut pbr = UsdPrim::new("PBR", "Shader"); + pbr.attrs.push(UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPreviewSurface".into()))).uniform()); + + // (shader name, a binding that has its file, colour space and normal convention, outputs read) + let mut taken = vec!["PBR".to_string(), "st".to_string()]; + let mut shaders: Vec<(String, &UsdTextureBinding, Vec<&'static str>)> = Vec::new(); + for binding in bindings { + let Some(&(_, input, input_type, ..)) = SLOTS.get(binding.slot) else { continue }; + let at = match shaders.iter().position(|(_, key, _)| (&key.file, key.srgb, key.normal) == (&binding.file, binding.srgb, binding.normal)) { + Some(at) => at, + None => { + let stem = binding.file.rsplit_once('.').map_or(binding.file.as_str(), |(stem, _)| stem); + shaders.push((identifier(stem, &mut taken), binding, Vec::new())); + shaders.len() - 1 + } + }; + let (shader, _, outputs) = &mut shaders[at]; + if !outputs.contains(&binding.output) { + outputs.push(binding.output); + } + + pbr.attrs.push(UsdAttr::connected(&format!("inputs:{input}"), input_type, format!("{path}/{shader}.outputs:{}", binding.output))); + } + + let mut textures = Vec::new(); + for (shader, binding, outputs) in shaders { + let mut tex = UsdPrim::new(&shader, "Shader"); + let token = |s: &str| Some(UsdValue::Token(s.into())); + tex.attrs = vec![ + UsdAttr::new("info:id", "token", token("UsdUVTexture")).uniform(), + UsdAttr::new("inputs:file", "asset", Some(UsdValue::Asset(format!("./{}", binding.file)))), + UsdAttr::connected("inputs:st", "float2", format!("{path}/st.outputs:result")), + UsdAttr::new("inputs:sourceColorSpace", "token", token(if binding.srgb { "sRGB" } else { "raw" })), + UsdAttr::new("inputs:wrapS", "token", token("repeat")), + UsdAttr::new("inputs:wrapT", "token", token("repeat")), + ]; + + // Unpack 0..1 texels to -1..1 vectors; a DirectX file also flips green to the OpenGL convention + if let Some(format) = binding.normal { + let (scale, bias) = match format { + NormalFormat::OpenGl => ([2.0, 2.0, 2.0, 1.0], [-1.0, -1.0, -1.0, 0.0]), + NormalFormat::DirectX => ([2.0, -2.0, 2.0, 1.0], [-1.0, 1.0, -1.0, 0.0]), + }; + tex.attrs.push(UsdAttr::new("inputs:scale", "float4", Some(UsdValue::Float4(scale)))); + tex.attrs.push(UsdAttr::new("inputs:bias", "float4", Some(UsdValue::Float4(bias)))); + } + for output in outputs { + tex.attrs.push(UsdAttr::new(&format!("outputs:{output}"), if output == "rgb" { "float3" } else { "float" }, None)); + } + textures.push(tex); + } + pbr.attrs.push(UsdAttr::new("inputs:useSpecularWorkflow", "int", Some(UsdValue::Int(0)))); + pbr.attrs.push(UsdAttr::new("outputs:surface", "token", None)); + mat.children.push(pbr); + if !textures.is_empty() { + let mut st = UsdPrim::new("st", "Shader"); + st.attrs = vec![ + UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPrimvarReader_float2".into()))).uniform(), + // A string, not a token: usdchecker's ARKit profile refuses a token here. + UsdAttr::new("inputs:varname", "string", Some(UsdValue::Str("st".into()))), + UsdAttr::new("outputs:result", "float2", None), + ]; + mat.children.push(st); + mat.children.extend(textures); + } + mat +} + #[cfg(test)] mod aligned_package_tests { use super::*; @@ -328,3 +545,212 @@ mod aligned_package_tests { assert!(matches!(err, FormatError::Invalid(ref why) if why.starts_with("usdz package:"))); } } + +#[cfg(test)] +mod texture_binding_tests { + use super::*; + use texturecraft_core::ChannelFormat; + + const BASE_COLOR: usize = 0; + const ROUGHNESS: usize = 1; + const METALLIC: usize = 2; + const NORMAL: usize = 3; + const OPACITY: usize = 5; + + fn set_with(extra: &[Channel]) -> TextureSet { + let mut set = TextureSet::new("Body", 0, 128); + set.channels.extend(extra.iter().map(|c| (*c, ChannelFormat::default_for(*c)))); + set + } + + fn map(file: &str, format: FileFormat, channels: Vec<(Dest, SourceRef)>) -> MapSpec { + MapSpec { file: file.into(), format, bit_depth: 8, channels, inverted: Vec::new() } + } + + fn options(maps: Vec) -> ExportOptions { + ExportOptions::new(ExportPreset { name: "test".into(), maps }) + } + + fn planned(opts: &ExportOptions, index: usize) -> PlannedFile { + let map = &opts.preset.maps[index]; + PlannedFile { + name: format!("{}.{}", map.file, map.format.extension()), + map: index, + format: map.format, + bit_depth: map.bit_depth, + dither: false, + tile: None, + udim_name: None, + warnings: Vec::new(), + } + } + + fn bind(set: &TextureSet, opts: &ExportOptions, normal: NormalFormat) -> Vec { + let files: Vec = (0..opts.preset.maps.len()).map(|i| planned(opts, i)).collect(); + usd_texture_bindings(set, opts, normal, &files) + } + + fn slot(bindings: &[UsdTextureBinding], slot: usize) -> Option<&UsdTextureBinding> { + bindings.iter().find(|b| b.slot == slot) + } + + fn rgba() -> Vec<(Dest, SourceRef)> { + vec![ + (Dest::R, ch(Channel::BaseColor, 0)), + (Dest::G, ch(Channel::BaseColor, 1)), + (Dest::B, ch(Channel::BaseColor, 2)), + (Dest::A, ch(Channel::Opacity, 0)), + ] + } + + #[test] + fn colour_and_opacity_of_one_file_are_read_by_one_texture_shader() { + let opts = options(vec![map("albedo", FileFormat::Png, rgba())]); + let bindings = bind(&set_with(&[Channel::Opacity]), &opts, NormalFormat::OpenGl); + assert_eq!(slot(&bindings, BASE_COLOR).map(|b| b.output), Some("rgb")); + assert_eq!(slot(&bindings, OPACITY).map(|b| (b.output, b.file.as_str())), Some(("a", "albedo.png"))); + + // PBR, the st reader and a single texture shader + assert_eq!(textured_material("/m", "M", &bindings).children.len(), 3); + + // A set without opacity has no alpha in the file + let bindings = bind(&set_with(&[]), &opts, NormalFormat::OpenGl); + assert!(slot(&bindings, OPACITY).is_none()); + assert!(slot(&bindings, BASE_COLOR).is_some()); + } + + #[test] + fn the_layer_reads_each_file_with_its_output_and_colour_space() { + let opts = options(vec![ + map("albedo", FileFormat::Png, rgba()), + map("orm", FileFormat::Png, vec![(Dest::G, ch(Channel::Roughness, 0)), (Dest::B, ch(Channel::Metallic, 0))]), + ]); + let bindings = vec![bind(&set_with(&[Channel::Opacity]), &opts, NormalFormat::OpenGl), Vec::new()]; + let mesh = texturecraft_geom::primitives::material_ball(); + assert_eq!(mesh.materials.len(), 2); + + let text = write_usda(&textured_layer(&mesh, "ball", &bindings).unwrap()); + for expected in [ + "asset inputs:file = @./albedo.png@", + "asset inputs:file = @./orm.png@", + "color3f inputs:diffuseColor.connect = ") && text.contains("/orm.outputs:b>") && text.contains("/albedo.outputs:a>"), "{text}"); + assert!(text.contains("token inputs:sourceColorSpace = \"sRGB\"") && text.contains("token inputs:sourceColorSpace = \"raw\""), "{text}"); + assert_eq!(text.matches("\"UsdUVTexture\"").count(), 2, "one texture shader per file: {text}"); + + // The binary file holds the same layer + let bytes = usd_layer_with_textures(&mesh, "ball", &bindings).unwrap(); + assert!(bytes.starts_with(b"PXR-USDC")); + } + + #[test] + fn an_inverted_destination_is_not_bound() { + let mut inverted = map("rough", FileFormat::Png, vec![(Dest::L, ch(Channel::Roughness, 0))]); + inverted.inverted = vec![Dest::L]; + let plain = map("rough", FileFormat::Png, vec![(Dest::L, ch(Channel::Roughness, 0))]); + let set = set_with(&[]); + assert!(slot(&bind(&set, &options(vec![inverted]), NormalFormat::OpenGl), ROUGHNESS).is_none()); + assert!(slot(&bind(&set, &options(vec![plain]), NormalFormat::OpenGl), ROUGHNESS).is_some()); + } + + #[test] + fn the_tiles_of_a_uv_tiled_set_are_read_through_the_udim_name() { + let opts = options(vec![map("color.$udim", FileFormat::Png, rgba())]); + let set = set_with(&[]); + let mut tile = planned(&opts, 0); + tile.name = "color.1001.png".into(); + tile.tile = Some(1001); + let mut second = tile.clone(); + second.name = "color.1002.png".into(); + second.tile = Some(1002); + + // Tiles without a `` name cannot stand for the others + assert!(usd_texture_bindings(&set, &opts, NormalFormat::OpenGl, &[tile.clone(), second.clone()]).is_empty()); + + tile.udim_name = Some("color..png".into()); + second.udim_name = tile.udim_name.clone(); + let bindings = usd_texture_bindings(&set, &opts, NormalFormat::OpenGl, &[tile, second]); + assert_eq!(slot(&bindings, BASE_COLOR).map(|b| b.file.as_str()), Some("color..png")); + assert_eq!(bindings.len(), 1, "the tiles of one map make one binding"); + } + + #[test] + fn only_colour_maps_in_integer_srgb_files_are_tagged_srgb() { + let colour = || vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::BaseColor, 1)), (Dest::B, ch(Channel::BaseColor, 2))]; + let set = set_with(&[]); + let tag = |format: FileFormat, depth: u8, space: Option| { + let mut spec = map("c", format, colour()); + spec.bit_depth = depth; + let mut opts = options(vec![spec]); + opts.color_space = space; + let file = planned(&opts, 0); + let expected = opts.space_for_map(&opts.preset.maps[0], file.format, file.bit_depth) == ColorSpace::Srgb; + let bindings = usd_texture_bindings(&set, &opts, NormalFormat::OpenGl, &[PlannedFile { bit_depth: depth, ..file }]); + let srgb = slot(&bindings, BASE_COLOR).unwrap().srgb; + assert_eq!(srgb, expected); + srgb + }; + assert!(tag(FileFormat::Png, 8, None)); + assert!(tag(FileFormat::Png, 16, None)); + assert!(!tag(FileFormat::Exr, 16, None), "float files hold linear colour"); + assert!(!tag(FileFormat::Png, 8, Some(ColorSpace::AcesCg)), "UsdPreviewSurface knows only sRGB and raw"); + + // Data maps are raw + let data = options(vec![map("m", FileFormat::Png, vec![(Dest::L, ch(Channel::Metallic, 0))])]); + assert!(!slot(&bind(&set, &data, NormalFormat::OpenGl), METALLIC).unwrap().srgb); + } + + #[test] + fn roughness_from_glossiness_is_bound_only_for_a_set_with_glossiness() { + let from_glossiness = options(vec![map("r", FileFormat::Png, vec![(Dest::L, virt(VirtualMap::Roughness, 0))])]); + assert!(slot(&bind(&set_with(&[Channel::Glossiness]), &from_glossiness, NormalFormat::OpenGl), ROUGHNESS).is_some()); + assert!(slot(&bind(&set_with(&[]), &from_glossiness, NormalFormat::OpenGl), ROUGHNESS).is_none()); + + // Glossiness itself is the opposite of roughness + let glossiness = options(vec![map("g", FileFormat::Png, vec![(Dest::L, virt(VirtualMap::Glossiness, 0))])]); + assert!(bind(&set_with(&[]), &glossiness, NormalFormat::OpenGl).is_empty()); + } + + #[test] + fn a_file_that_cannot_hold_alpha_or_colour_is_not_bound_for_them() { + let set = set_with(&[Channel::Opacity]); + for format in [FileFormat::Jpeg, FileFormat::Hdr] { + let bindings = bind(&set, &options(vec![map("albedo", format, rgba())]), NormalFormat::OpenGl); + assert!(slot(&bindings, BASE_COLOR).is_some(), "{format:?} keeps the colour"); + assert!(slot(&bindings, OPACITY).is_none(), "{format:?} drops alpha"); + } + assert!(slot(&bind(&set, &options(vec![map("albedo", FileFormat::Png, rgba())]), NormalFormat::OpenGl), OPACITY).is_some()); + + // PGM is one gray channel: colour becomes luminance, and only a map written as L is bound + let pgm = options(vec![ + map("albedo", FileFormat::Pgm, rgba()), + map("orm", FileFormat::Pgm, vec![(Dest::G, ch(Channel::Roughness, 0)), (Dest::B, ch(Channel::Metallic, 0))]), + map("metal", FileFormat::Pgm, vec![(Dest::L, ch(Channel::Metallic, 0))]), + ]); + let bindings = bind(&set, &pgm, NormalFormat::OpenGl); + assert!(slot(&bindings, BASE_COLOR).is_none()); + assert!(slot(&bindings, ROUGHNESS).is_none()); + assert_eq!(slot(&bindings, METALLIC).map(|b| (b.output, b.file.as_str())), Some(("r", "metal.pgm"))); + } + + #[test] + fn a_normal_map_unpacks_with_the_convention_of_its_file() { + let set = set_with(&[]); + let normal = |source: fn(u8) -> SourceRef| { + options(vec![map("n", FileFormat::Png, (0..3).map(|k| ([Dest::R, Dest::G, Dest::B][k as usize], source(k))).collect())]) + }; + let convention = |opts: &ExportOptions| slot(&bind(&set, opts, NormalFormat::DirectX), NORMAL).unwrap().normal; + assert_eq!(convention(&normal(|k| ch(Channel::Normal, k))), Some(NormalFormat::DirectX), "follows the project"); + assert_eq!(convention(&normal(|k| virt(VirtualMap::NormalOpenGl, k))), Some(NormalFormat::OpenGl)); + + let mut forced = normal(|k| virt(VirtualMap::NormalOpenGl, k)); + forced.normal_format = Some(NormalFormat::DirectX); + assert_eq!(convention(&forced), Some(NormalFormat::DirectX), "the export's normal format wins"); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 5b3ed2d3..c60a2bbf 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -70,6 +70,7 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H # winit needs a window system on Linux, so the crate's own tests build with X11. [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +craft-usd.workspace = true eframe = { workspace = true, features = ["x11"] } # Offscreen pictures of the whole window (tests/ui_snapshots.rs). egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 37590454..02678d0d 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -245,7 +245,16 @@ fn start_export(app: &mut TextureCraftApp) { return; } - e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, written: Vec::new(), frame: 0 }); + e.job = Some(crate::state::ExportJob { + total: pending.len(), + pending, + preview, + directory: dir, + written: Vec::new(), + frame: 0, + usd_asset: e.usd_asset, + sent: Vec::new(), + }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -326,11 +335,31 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let set = || ConsoleLine::Set(name.clone()); app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Rendering the selected maps").into())]); + // The USD asset covers the whole mesh and refers to the textures of every texture set: the last command writes it, given + // the params every command of the export ran with, so a canceled or failed export writes none + if let Some(job) = app.ui.export.job.as_mut().filter(|job| job.usd_asset) { + job.sent.push(params.clone()); + if job.pending.is_empty() { + params["usdAsset"] = json!(job.sent); + } + } let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; }; + // The one warning the window shows: the USD asset that could not be written + let usd_failure = response + .get("warnings") + .and_then(|w| w.as_array()) + .into_iter() + .flatten() + .filter_map(|w| w.as_str()) + .find(|w| w.starts_with(texturecraft_engine::file_cmds::USD_ASSET_FAILED)); + if let Some(warning) = usd_failure { + app.toast(warning.to_string(), true); + } + let files: Vec = response .get("files") .and_then(|file| file.as_array()) @@ -340,7 +369,8 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { .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())]; - for file in &files { + // The USD asset is no texture: it stays in the list of written files only + for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); @@ -631,8 +661,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] if reset { let d = ExportUi::default(); let e = &mut app.ui.export; - (e.dir, e.format, e.bit_depth, e.dithering, e.size, e.padding, e.dilation, e.normal_format, e.color_space) = - (d.dir, d.format, d.bit_depth, d.dithering, d.size, d.padding, d.dilation, d.normal_format, d.color_space); + (e.dir, e.format, e.bit_depth, e.dithering, e.size, e.padding, e.dilation, e.normal_format, e.color_space, e.usd_asset) = + (d.dir, d.format, d.bit_depth, d.dithering, d.size, d.padding, d.dilation, d.normal_format, d.color_space, d.usd_asset); crate::export_templates::select(app, d.preset); } let (first, rest) = template_groups(app, builtins); @@ -675,8 +705,13 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] ui.end_row(); }); - // Unavailable export controls stay disabled + // The browser downloads the textures only, so it has no USD asset to add + #[cfg(not(target_arch = "wasm32"))] + ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")).on_hover_text(tr("Package the mesh, materials and textures together as USD")); + #[cfg(target_arch = "wasm32")] unavailable_checkbox(ui, tr("Export USD asset"), tr("Package the mesh, materials and textures together as USD")); + + // Unavailable export controls stay disabled unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e2a36d40..a3c458c4 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 `.usd`: the mesh and a material per texture set that reads the exported + /// textures (`usdAsset` of `file.exportTextures`). + #[serde(default)] + pub usd_asset: 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(), + usd_asset: 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..a2143a8c 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -15,4 +15,9 @@ pub struct ExportJob { pub written: Vec, /// The frame that wrote the last texture set (a frame's second pass writes none). pub frame: u64, + /// Also write the mesh and materials as a USD asset with the last texture set, as ticked when + /// Export was clicked. + pub usd_asset: bool, + /// The params of the texture sets written so far, for the USD asset. + pub sent: Vec, } diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs new file mode 100644 index 00000000..ddc54014 --- /dev/null +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -0,0 +1,211 @@ +//! Export textures › SETTINGS: the Export USD asset option. It writes `.usd` (the mesh and a +//! material per texture set that reads the exported textures) next to the textures, with the +//! export's last 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, ExportJob}; + +/// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. +struct Scratch(std::path::PathBuf); + +impl std::ops::Deref for Scratch { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The Export textures window writing into a scratch folder of its own for `name` +fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, Scratch) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + let dir = std::env::temp_dir().join(format!("tc-export-usd-asset-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let dir = Scratch(dir); + h.state_mut().ui.export.dir = dir.display().to_string(); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + (h, dir) +} + +fn checkbox<'a>(h: &'a Harness<'static, TextureCraftApp>) -> egui_kittest::Node<'a> { + h.get_by_role_and_label(egui::Role::CheckBox, "Export USD asset") +} + +/// Click Export and run frames until the export ends +fn export(h: &mut Harness<'static, TextureCraftApp>) { + h.get_all_by_label("Export").last().unwrap().click(); + for _ in 0..64 { + h.run_steps(1); + if h.state().ui.export.job.is_none() { + break; + } + } + h.run_steps(2); +} + +/// The texture files `/material_ball.usd` refers to +fn referenced_files(dir: &std::path::Path) -> Vec { + let bytes = std::fs::read(dir.join("material_ball.usd")).expect("material_ball.usd"); + let layer = craft_usd::scene::read_layer(&bytes).unwrap(); + layer + .prims + .iter() + .filter_map(|prim| match prim.props.get("inputs:file")?.value.as_ref()? { + craft_usd::scene::Val::Tok(values) => values.first().map(|file| file.trim_start_matches("./").to_string()), + _ => None, + }) + .collect() +} + +#[test] +fn the_window_offers_export_usd_asset_off_by_default() { + let (h, _dir) = harness("offer"); + assert!(!checkbox(&h).accesskit_node().is_disabled()); + assert!(!h.state().ui.export.usd_asset); +} + +#[test] +fn ticking_export_usd_asset_writes_one_file_that_refers_to_the_exported_textures() { + let (mut h, dir) = harness("on"); + checkbox(&h).click(); + h.run_steps(3); + assert!(h.state().ui.export.usd_asset); + export(&mut h); + + let files = referenced_files(&dir); + assert!(h.state().session.set_count() >= 2, "one file has to cover several texture sets"); + assert!(files.len() >= h.state().session.set_count(), "every material reads textures: {files:?}"); + for file in &files { + assert!(dir.join(file).is_file(), "{file} was written"); + } + let usd = std::fs::read_dir(&*dir).unwrap().flatten().filter(|e| e.path().extension().is_some_and(|x| x == "usd")).count(); + assert_eq!(usd, 1, "one file for the whole export, not one per texture set"); +} + +#[test] +fn the_file_refers_to_the_textures_each_texture_set_was_exported_with() { + let (mut h, dir) = harness("overrides"); + h.state_mut().ui.export.sets.entry(1).or_default().preset = Some("Unreal Engine (Packed)".into()); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let files = referenced_files(&dir); + assert!(files.iter().any(|f| f.ends_with("_OcclusionRoughnessMetallic.png")), "the second texture set's template: {files:?}"); + assert!(files.iter().any(|f| f.ends_with("_roughness.png")), "the first texture set's template: {files:?}"); + for file in &files { + assert!(dir.join(file).is_file(), "{file} was written"); + } +} + +#[test] +fn only_the_exported_texture_sets_have_textures() { + let (mut h, dir) = harness("subset"); + h.state_mut().ui.export.skip = vec![0]; + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let first = texturecraft_engine::formats::export::sanitize_file_stem(&h.state().session.doc.project.texture_sets[0].name); + let files = referenced_files(&dir); + assert!(!files.is_empty()); + assert!(files.iter().all(|f| !f.starts_with(&format!("material_ball_{first}_"))), "the skipped texture set has none: {files:?}"); +} + +#[test] +fn the_console_lists_the_asset_as_a_file_but_not_as_a_saved_texture() { + let (mut h, _dir) = harness("console"); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let console = &h.state().ui.export.console; + assert!(console.iter().any(|line| matches!(line, ConsoleLine::Done(file) if file == "material_ball.usd")), "{console:?}"); + assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Saved texture material_ball")), "{console:?}"); + assert!(console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Saved texture "))), "the textures are still listed"); +} + +#[test] +fn a_canceled_export_writes_no_asset() { + let (mut h, dir) = harness("cancel"); + + // A long export, as the window starts it with the option ticked + let sets = h.state().session.set_count(); + let params = serde_json::json!({"dir": dir.display().to_string()}); + let pending: Vec<(usize, serde_json::Value)> = (0..sets).cycle().take(sets * 8).map(|ts| (ts, params.clone())).collect(); + let e = &mut h.state_mut().ui.export; + e.tab = 2; + e.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, ..ExportJob::default() }); + h.run_steps(2); + h.get_all_by_label("Cancel Export").last().unwrap().click(); + h.run_steps(3); + assert!(h.state().ui.export.job.is_none()); + assert!(!dir.join("material_ball.usd").exists()); + + // The same job run to its end writes it + let pending: Vec<(usize, serde_json::Value)> = (0..sets).map(|ts| (ts, params.clone())).collect(); + h.state_mut().ui.export.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, ..ExportJob::default() }); + for _ in 0..64 { + if h.state().ui.export.job.is_none() { + break; + } + h.run_steps(1); + } + assert!(dir.join("material_ball.usd").is_file()); +} + +#[test] +fn no_asset_is_written_when_the_option_is_off() { + let (mut h, dir) = harness("off"); + export(&mut h); + assert!(std::fs::read_dir(&*dir).unwrap().next().is_some(), "the textures were written"); + assert!(!dir.join("material_ball.usd").exists()); +} + +#[test] +fn restoring_the_default_parameters_unticks_export_usd_asset() { + let (mut h, _dir) = harness("reset"); + checkbox(&h).click(); + h.run_steps(3); + assert!(h.state().ui.export.usd_asset); + h.get_by_label("Restore the default export parameters").click(); + h.run_steps(3); + assert!(!h.state().ui.export.usd_asset); +} + +#[test] +fn reset_all_unticks_export_usd_asset() { + let (mut h, _dir) = harness("reset-all"); + checkbox(&h).click(); + h.run_steps(3); + h.get_by_label("Reset all").click(); + h.run_steps(3); + assert!(!h.state().ui.export.usd_asset); +} + +#[test] +fn an_asset_that_cannot_be_written_shows_an_error_toast_and_the_textures_stay() { + let (mut h, dir) = harness("blocked"); + + // A folder where the file belongs: the asset cannot be written there + std::fs::create_dir_all(dir.join("material_ball.usd")).unwrap(); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let toast = h.state().toasts.iter().find(|toast| toast.text.starts_with("The USD asset was not written")).expect("a toast names the failure"); + assert!(toast.error); + assert!(h.state().ui.export.job.is_none(), "the export ran to its end"); + assert!(std::fs::read_dir(&*dir).unwrap().flatten().any(|e| e.path().extension().is_some_and(|x| x == "png")), "the textures were written"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index ef91cc44..246e7c8d 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -26,6 +26,7 @@ mod export_overrides; mod export_progress; mod export_settings; mod export_template_guards; +mod export_usd_asset; mod file_dialogs; mod fill_channel_image; mod fill_material_rows; diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index d05f19a1..80bd801d 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -116,7 +116,8 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { assert!(harness.query_by_label(label).is_some(), "{label}"); } assert!(harness.query_by_label_contains("textures selected for export").is_some()); - assert!(says_not_available(&mut harness, "Export USD asset")); + assert!(!says_not_available(&mut harness, "Export USD asset")); + assert!(says_not_available(&mut harness, "Export shader settings")); harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d963eb9c..2b7e3638 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -47,6 +47,18 @@ 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 `usdAsset` also writes `.usd` (binary USD, Crate) next to the textures: the whole mesh +(every texture set, whatever `ts` selects) with one UsdPreviewSurface material per texture set. A +material's inputs read the texture files the export planned for that set with its output template +(`usdAsset: true`: the sets and options of this command; a list of export params such as +`[{"ts": 0, "preset": "..."}, {"ts": 1}]`, not empty, every entry an object: each entry's sets and options, the way the export window, +which runs one command per texture set, passes the params of all its commands with the last one). +Bound inputs: `diffuseColor`, `roughness`, `metallic`, `normal`, `emissiveColor`, `opacity`, +`clearcoat` and `clearcoatRoughness`, each reading the `rgb`, `r`, `g`, `b` or `a` output of the +file that holds it; maps with no such input are not bound, and a texture set outside the export has +no textures. A file name is relative to the file (`./`, with `` for UV tiles). A failure +to build or write it is named in `warnings` and the command still succeeds. The file is in `files`. + `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..bb428323 100644 --- a/docs/features.md +++ b/docs/features.md @@ -177,6 +177,19 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA 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). +- **USD asset export:** the *Export USD asset* checkbox on the Export textures window's Global + settings (off by default, remembered with the other settings) also writes `.usd` (binary USD) next to + the exported textures when the last selected texture set is written. It holds the whole mesh with + one UsdPreviewSurface material per texture set; each material refers to the textures that texture + set was exported with (its own output template, file type, size and normal format) by relative + file name. Base colour, roughness, metallic, normal, emissive colour, opacity, clear coat and clear + coat roughness are bound; a packed template (ORM, mask map) binds several inputs to different + channels of one file. Ambient occlusion, height, specular/glossiness, sheen, anisotropy, + transmission, scatter, coat normal and baked maps have no UsdPreviewSurface input and are not + bound. Colour maps written as sRGB are tagged sRGB, other maps raw; a DirectX normal map is + flipped back in the material. A texture set outside the export has no textures in the file. A + canceled export writes none, and a failure to write it is a warning. In the browser the option is + greyed. - **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for roughness, metallic, normal and coat; UV-tiled sets keep their UDIM UVs and export their maps through Export textures), textured GLB (with clear coat and sheen) and USD (with clear coat). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f7dad7ed..f4454953 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -68,8 +68,10 @@ that closes it back onto the bar; the float is saved with the UI state. *Send to compositing app* and *Send to 3D staging app*. EXPORT has *Export Mesh...* (the *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 + (off by default; it adds `usdAsset` to the last texture set's export, which writes `.usd` + with materials that refer to the exported textures; greyed in the browser), *Export shaders + parameters* greyed, *Include all*, *Save settings* and "N textures selected for export"). 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