mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-24 08:20:46 +01:00
Bind only the textures the export kept in the USD asset
Each usdAsset entry now carries the reservedNames its command ran with, and the asset applies the same reservation rule as the texture export (reserved file names and UDIM patterns, then earlier files of the job), so it never binds a file the export skipped.
This commit is contained in:
1 parent
0924e1314d
commit
e1577e3686
6 files changed
+106
-53
No files matched your search
@@ -58,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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), 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), usdAsset?: true|[export params, one object per texture set (not empty)] (also write <mesh>.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)} → {files, warnings, materialUdimPatterns?}",
|
||||
"{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), usdAsset?: true|[export params, one object per texture set (not empty)] (also write <mesh>.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, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}",
|
||||
always,
|
||||
export_textures
|
||||
),
|
||||
@@ -735,20 +735,22 @@ fn export_textures(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
/// 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.
|
||||
/// The texture sets, options and `reservedNames` of one export a USD asset refers to.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
type UsdExports = Vec<(Vec<usize>, ExportOptions)>;
|
||||
type UsdAssetExport = (Vec<usize>, ExportOptions, HashMap<String, Option<usize>>);
|
||||
|
||||
/// 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.
|
||||
/// What `usdAsset` asks for: the texture sets, options and `reservedNames` of each export whose
|
||||
/// textures the USD asset refers to. `true` is this command's own; a list gives every entry's.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn usd_asset_param(s: &Session, p: &Value, opts: &ExportOptions, sets: &[usize]) -> Result<Option<UsdExports>> {
|
||||
match p.get("usdAsset") {
|
||||
fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, sets: &[usize]) -> Result<Option<Vec<UsdAssetExport>>> {
|
||||
match params.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::Bool(true)) => Ok(Some(vec![(sets.to_vec(), options.clone(), reserved_names(params)?)])),
|
||||
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")?)))
|
||||
.map(|export| {
|
||||
Ok((sets_param(session, export, "file.exportTextures")?, export_options(session, export, "file.exportTextures")?, reserved_names(export)?))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map(Some),
|
||||
Some(_) => Err(bad("file.exportTextures", "`usdAsset` must be true, false or a non-empty list of export param objects")),
|
||||
@@ -760,53 +762,49 @@ fn usd_asset_param(s: &Session, p: &Value, opts: &ExportOptions, sets: &[usize])
|
||||
/// 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<usize>, ExportOptions)], warnings: &mut Vec<String>) -> Option<std::path::PathBuf> {
|
||||
match build_usd_asset(s, dir, exports) {
|
||||
fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec<String>) -> Option<std::path::PathBuf> {
|
||||
match build_usd_asset(session, dir, exports) {
|
||||
Ok(path) => Some(path),
|
||||
Err(e) => {
|
||||
warnings.push(format!("{USD_ASSET_FAILED}: {e}"));
|
||||
Err(error) => {
|
||||
warnings.push(format!("{USD_ASSET_FAILED}: {error}"));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn build_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec<usize>, ExportOptions)]) -> Result<std::path::PathBuf> {
|
||||
fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> Result<std::path::PathBuf> {
|
||||
use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings};
|
||||
let project = &s.doc.project;
|
||||
let project = &session.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 {
|
||||
// Keep the files each export kept, by the rule `file.exportTextures` applies to its reserved and earlier names
|
||||
let mut taken_names = HashMap::new();
|
||||
let mut by_set = HashMap::new();
|
||||
for (sets, options, reserved) in exports {
|
||||
for name in reserved.keys() {
|
||||
taken_names.entry(name.clone()).or_insert(None);
|
||||
}
|
||||
let reserved_patterns: Vec<_> = reserved.keys().filter(|name| name.contains("<udim>")).cloned().collect();
|
||||
|
||||
for &set in sets {
|
||||
let texture_set = project.texture_set(set).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
|
||||
// A file whose name an earlier file of this job has was not written by this export. A
|
||||
// map that lost any file (a tile of a UDIM map) is not bound: its `<UDIM>` name would
|
||||
// read the tile of another texture set.
|
||||
let mut skipped_maps = std::collections::HashSet::new();
|
||||
let mut kept = Vec::new();
|
||||
for file in list_outputs(project, set, &mesh_name, opts).map_err(fe)? {
|
||||
if taken.insert(file.name.to_ascii_lowercase()) {
|
||||
kept.push(file);
|
||||
} else {
|
||||
skipped_maps.insert(file.map);
|
||||
}
|
||||
}
|
||||
let texture_set = project.texture_set(set).map_err(|error| EngineError::Other(error.to_string()))?;
|
||||
let mut kept = list_outputs(project, set, &mesh_name, options).map_err(fe)?;
|
||||
let skipped_maps = reserve_export_names(set, &mut kept, &mut taken_names, &reserved_patterns, &mut Vec::new(), false);
|
||||
|
||||
// A map that lost any file (a tile of a UDIM map) is not bound: its `<UDIM>` name would read a file it does not own
|
||||
kept.retain(|file| !skipped_maps.contains(&file.map));
|
||||
by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, opts, project.normal_format, &kept));
|
||||
by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept));
|
||||
}
|
||||
}
|
||||
|
||||
// A mesh without materials has one implicit material (and texture set)
|
||||
let mut mesh = s.source_mesh();
|
||||
let mut mesh = session.source_mesh();
|
||||
if mesh.materials.is_empty() {
|
||||
mesh.materials.push("default".into());
|
||||
}
|
||||
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 bindings: Vec<_> =
|
||||
(0..mesh.materials.len()).map(|material| session.texture_set_of_material(material).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)?;
|
||||
|
||||
@@ -318,21 +318,34 @@ fn a_material_without_a_texture_set_has_no_textures() {
|
||||
assert!(materials[1].0.is_empty(), "{:?}", materials[1]);
|
||||
}
|
||||
|
||||
/// A material per half of a two-tile plane: the first material covers tiles 1001 and 1002, the second 1002 and 1003
|
||||
fn overlapping_tiles() -> Session {
|
||||
/// Two two-tile planes, a material each: the first covers tiles 1001 and 1002, the second starts `shift_tiles` tiles to the right
|
||||
fn two_udim_sets(shift_tiles: f32) -> Session {
|
||||
let mut mesh = primitives::udim_plane();
|
||||
let mut second = primitives::udim_plane();
|
||||
second.materials[0] = "Other".into();
|
||||
for uv in &mut second.uvs {
|
||||
uv.x += 1.0;
|
||||
uv.x += shift_tiles;
|
||||
}
|
||||
mesh.append(&second);
|
||||
let s = Session::new_project("t", mesh, "builtin:udim_plane", None, 128).unwrap();
|
||||
Session::new_project("t", mesh, "builtin:udim_plane", None, 128).unwrap()
|
||||
}
|
||||
|
||||
/// A material per half of a two-tile plane: the first material covers tiles 1001 and 1002, the second 1002 and 1003
|
||||
fn overlapping_tiles() -> Session {
|
||||
let s = two_udim_sets(1.0);
|
||||
assert_eq!(s.doc.project.texture_sets[0].uv_tiles, [1001, 1002]);
|
||||
assert_eq!(s.doc.project.texture_sets[1].uv_tiles, [1002, 1003]);
|
||||
s
|
||||
}
|
||||
|
||||
/// The shared colour map plus a roughness map whose names tell the texture sets apart
|
||||
fn colour_and_own_roughness_template() -> Value {
|
||||
let gray = json!([["L", {"Channel": {"channel": "Roughness", "component": 0}}]]);
|
||||
let mut preset = shared_name_template();
|
||||
preset["maps"].as_array_mut().unwrap().push(json!({"file": "rough_$textureSet", "format": "Png", "bit_depth": 8, "channels": gray}));
|
||||
preset
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_udim_map_that_lost_a_tile_to_a_name_clash_is_not_bound_but_the_other_maps_are() {
|
||||
let mut s = overlapping_tiles();
|
||||
@@ -340,10 +353,7 @@ fn a_udim_map_that_lost_a_tile_to_a_name_clash_is_not_bound_but_the_other_maps_a
|
||||
|
||||
// The colour map's names do not tell the sets apart, so tile 1002 of the second set is not written;
|
||||
// the roughness map's names do.
|
||||
let gray = json!([["L", {"Channel": {"channel": "Roughness", "component": 0}}]]);
|
||||
let mut preset = shared_name_template();
|
||||
preset["maps"].as_array_mut().unwrap().push(json!({"file": "rough_$textureSet", "format": "Png", "bit_depth": 8, "channels": gray}));
|
||||
export(&mut s, &dir, json!({"ts": [0, 1], "preset": preset, "usdAsset": true}));
|
||||
export(&mut s, &dir, json!({"ts": [0, 1], "preset": colour_and_own_roughness_template(), "usdAsset": true}));
|
||||
|
||||
let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &s.mesh.materials);
|
||||
let (first, second) = (&materials[material_of(&s, 0)].0, &materials[material_of(&s, 1)].0);
|
||||
@@ -354,6 +364,31 @@ fn a_udim_map_that_lost_a_tile_to_a_name_clash_is_not_bound_but_the_other_maps_a
|
||||
assert_ne!(first["roughness"].file, second["roughness"].file);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_udim_map_whose_tiles_the_window_reserved_for_an_earlier_command_is_not_bound() {
|
||||
let mut session = two_udim_sets(2.0);
|
||||
assert_eq!(session.doc.project.texture_sets[1].uv_tiles, [1003, 1004]);
|
||||
let dir = temp("reserved");
|
||||
let first = json!({"ts": 0, "preset": colour_and_own_roughness_template()});
|
||||
let written = export(&mut session, &dir, first.clone());
|
||||
|
||||
// The window reserves the earlier files and the UDIM patterns of earlier MaterialX documents
|
||||
let mut reserved: Vec<Value> = files(&written).iter().map(|file| json!(std::path::Path::new(file).file_name().unwrap().to_str().unwrap())).collect();
|
||||
reserved.push(json!("colour.<UDIM>.png"));
|
||||
let second = json!({"ts": 1, "preset": colour_and_own_roughness_template(), "reservedNames": reserved});
|
||||
let mut last = second.clone();
|
||||
last["usdAsset"] = json!([first, second]);
|
||||
export(&mut session, &dir, last);
|
||||
|
||||
let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &session.mesh.materials);
|
||||
let (first, second) = (&materials[material_of(&session, 0)].0, &materials[material_of(&session, 1)].0);
|
||||
assert_eq!(first["diffuseColor"].file, "colour.<UDIM>.png", "{first:?}");
|
||||
assert!(!dir.join("colour.1003.png").exists(), "the texture export skipped the reserved pattern");
|
||||
assert!(!second.contains_key("diffuseColor"), "the second set's colour tiles were not written: {second:?}");
|
||||
assert!(second["roughness"].file.starts_with("rough_") && second["roughness"].file.contains("<UDIM>"), "{second:?}");
|
||||
assert!(dir.join(second["roughness"].file.replace("<UDIM>", "1003")).is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() {
|
||||
let mut mesh = primitives::plane(2.0, 4);
|
||||
|
||||
@@ -339,8 +339,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) {
|
||||
params["reservedNames"] = job.written.iter().chain(&job.material_udim_patterns).map(|name| json!(name)).collect();
|
||||
}
|
||||
|
||||
// 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
|
||||
// The last command writes the USD asset from the params of every command, 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() {
|
||||
@@ -353,8 +352,8 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) {
|
||||
return;
|
||||
};
|
||||
|
||||
// The one warning the window shows: the USD asset that could not be written
|
||||
let usd_failure = response_strings(&response, "warnings").find(|w| w.starts_with(texturecraft_engine::file_cmds::USD_ASSET_FAILED));
|
||||
// A USD asset that could not be written also shows as an error toast
|
||||
let usd_failure = response_strings(&response, "warnings").find(|warning| warning.starts_with(texturecraft_engine::file_cmds::USD_ASSET_FAILED));
|
||||
if let Some(warning) = usd_failure {
|
||||
app.toast(warning.to_string(), true);
|
||||
}
|
||||
|
||||
@@ -254,3 +254,24 @@ fn the_sent_command_of_a_texture_set_that_leaves_the_export_is_dropped() {
|
||||
h.run_steps(1);
|
||||
assert_eq!((sent_ts(&h, 0), sent_ts(&h, 1)), (vec![0], vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_sent_command_keeps_the_names_it_reserved_for_the_asset() {
|
||||
let (mut app_harness, dir) = harness("sent-reserved");
|
||||
let params = serde_json::json!({"dir": dir.display().to_string()});
|
||||
let pending = vec![(0, params.clone()), (1, params)];
|
||||
let settings = &mut app_harness.state_mut().ui.export;
|
||||
settings.tab = 2;
|
||||
settings.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, written: vec!["earlier.png".into()], ..ExportJob::default() });
|
||||
|
||||
for _ in 0..8 {
|
||||
app_harness.run_steps(1);
|
||||
if app_harness.state().ui.export.job.as_ref().is_none_or(|job| !job.sent.is_empty()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let job = app_harness.state().ui.export.job.as_ref().expect("the export is still running");
|
||||
let reserved = job.sent.first().and_then(|params| params["reservedNames"].as_array()).expect("the sent command carries its reserved names");
|
||||
assert!(reserved.iter().any(|name| name == "earlier.png"), "the asset skips what the texture export skipped: {reserved:?}");
|
||||
}
|
||||
@@ -50,13 +50,13 @@ and warn about later duplicates. The desktop export window reports the collision
|
||||
`file.exportTextures` with `usdAsset` also writes `<mesh>.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,
|
||||
(`usdAsset: true`: the sets, options and `reservedNames` 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, options and `reservedNames`, 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; other maps (ambient occlusion, height, specular...) are not bound, a UDIM map that lost a tile to an earlier
|
||||
set's file name is not bound, a mesh with no materials gets one implicit `default` material bound to the Default set, and a texture set outside the export has
|
||||
set's file name or to an entry's `reservedNames` is not bound, a mesh with no materials gets one implicit `default` material bound to the Default set, and a texture set outside the export has
|
||||
no textures. A file name is relative to the file (`./<file>`, with `<UDIM>` for UV tiles). A failure
|
||||
to build or write it is named in `warnings` and the command still succeeds. The file is in `files`.
|
||||
|
||||
|
||||
+2
-2
@@ -184,8 +184,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
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. A UDIM map that lost a tile to an earlier texture set's file name gets no
|
||||
binding, and a mesh with no materials gets one implicit "default" material bound to the Default
|
||||
channels of one file. A UDIM map that lost a tile to an earlier texture set's file name or to a
|
||||
UDIM pattern an earlier MaterialX document of the export uses gets no binding, and a mesh with no materials gets one implicit "default" material bound to the Default
|
||||
texture set. Ambient occlusion, height and specular are not bound (the material has occlusion,
|
||||
displacement and specularColor inputs, but TextureCraft does not fill them), nor are glossiness
|
||||
(no matching input) and baked maps; sheen, anisotropy, transmission, scatter and coat normal have no
|
||||
|
||||
Reference in new issue
Block a user