diff --git a/Cargo.lock b/Cargo.lock index 90fbf93d..2ccaed92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5982,6 +5982,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "tempfile", "texturecraft-engine", "texturecraft-formats", "texturecraft-render", @@ -6086,7 +6087,6 @@ dependencies = [ "half", "image", "png", - "quick-xml 0.41.0", "rayon", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 9a0cd63a..1f07aa7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,6 @@ rfd = "0.17" zip = { version = "9", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] } flate2 = "1" -quick-xml = "0.41" mikktspace = { version = "0.3", default-features = false, features = ["glam"] } rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] } diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index a0c3c0ad..eb28b995 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -28,4 +28,5 @@ getrandom = { workspace = true } rustix = { workspace = true } [dev-dependencies] +tempfile = "3" rmcp = { workspace = true, features = ["client"] } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 94e4924f..7eaed255 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -289,25 +289,50 @@ impl Headless { } /// Export textures to `dir` (`file.exportTextures` params: preset, ts, format, padding, size…). - pub fn export(&mut self, p: &Value) -> Result { + pub fn export(&mut self, params: &Value) -> Result { + use texturecraft_engine::shader_parameters::{shader_parameters_param, shader_parameters_sidecar}; + self.require_project()?; - let dir = p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| bad("`dir` is required"))?; - let opts = file_cmds::export_options(&self.session, p, "textures.export")?; - let n = self.session.set_count(); - let sets: Vec = match p.get("ts") { - None | Some(Value::Null) => (0..n).collect(), - Some(Value::String(a)) if a == "all" => (0..n).collect(), - Some(v) => vec![v.as_u64().and_then(|t| usize::try_from(t).ok()).filter(|t| *t < n).ok_or_else(|| bad(format!("invalid `ts` {v}")))?], + let dir = params.get("dir").and_then(Value::as_str).filter(|dir| !dir.is_empty()).ok_or_else(|| bad("`dir` is required"))?; + let options = file_cmds::export_options(&self.session, params, "textures.export")?; + let set_count = self.session.set_count(); + let sets: Vec = match params.get("ts") { + None | Some(Value::Null) => (0..set_count).collect(), + Some(Value::String(selection)) if selection == "all" => (0..set_count).collect(), + Some(value) => vec![ + value + .as_u64() + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < set_count) + .ok_or_else(|| bad(format!("invalid `ts` {value}")))?, + ], }; - let files = self.session.export_files(&sets, &opts)?; + let shader_sets = shader_parameters_param(&self.session.doc.project, params, &sets, "textures.export")?; + + let files = self.session.export_files(&sets, &options)?; + let sidecar = shader_sets.map(|sets| shader_parameters_sidecar(&self.session.doc.project, &sets, &files)); self.create_dir_all(dir)?; let mut written = Vec::new(); - for f in &files { - let path = join(dir, &f.name); - self.write(&path, &f.bytes)?; + let mut warnings = Vec::new(); + for file in files { + let path = join(dir, &file.name); + self.write(&path, &file.bytes)?; written.push(path); + warnings.extend(file.warnings); } - let warnings: Vec<&String> = files.iter().flat_map(|f| &f.warnings).collect(); + + if let Some(sidecar) = sidecar { + let result = sidecar.and_then(|file| { + let path = join(dir, &file.name); + self.write(&path, &file.bytes).map_err(|error| error.to_string())?; + Ok(path) + }); + match result { + Ok(path) => written.push(path), + Err(error) => warnings.push(format!("The shader settings file was not written: {error}")), + } + } + Ok(json!({ "files": written, "warnings": warnings })) } diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index f870ad9a..f2ebfee6 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -177,6 +177,9 @@ pub struct ExportParams { /// Settings for individual maps in the selected template. #[serde(default, skip_serializing_if = "Option::is_none")] pub maps: Option>, + /// Write shader settings for the exported sets (true) or the specified texture set indexes. + #[serde(default, rename = "shaderParameters", skip_serializing_if = "Option::is_none")] + pub shader_parameters: Option, } #[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] diff --git a/crates/automation/src/server/export_map_params.rs b/crates/automation/src/server/export_map_params.rs index b19aa8dd..7acffc96 100644 --- a/crates/automation/src/server/export_map_params.rs +++ b/crates/automation/src/server/export_map_params.rs @@ -19,4 +19,7 @@ pub struct ExportMapParams { /// Override dithering for this map's 8-bit outputs. #[serde(default, skip_serializing_if = "Option::is_none")] pub dithering: Option, + /// Side length in pixels for this map, overriding the export size. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, } diff --git a/crates/automation/tests/agent_tasks.rs b/crates/automation/tests/agent_tasks.rs index 93e59d23..4058e1c1 100644 --- a/crates/automation/tests/agent_tasks.rs +++ b/crates/automation/tests/agent_tasks.rs @@ -88,14 +88,15 @@ async fn inspect(c: &Conn) -> Value { #[tokio::test(flavor = "multi_thread")] async fn textures_export_accepts_per_map_settings() { - let dir = tmp("map-options"); - let (client, server) = connect(workspace(&dir)).await; + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + let (client, server) = connect(workspace(dir)).await; let result = tool( &client, "textures_export", json!({"dir": "textures", "preset": "glTF PBR Metal Roughness", "maps": [ - {"map": 0, "format": "pgm", "bitDepth": 16}, + {"map": 0, "format": "pgm", "bitDepth": 16, "size": 256}, {"map": 1, "enabled": false} ]}), ) @@ -104,9 +105,42 @@ async fn textures_export_accepts_per_map_settings() { let files = result["files"].as_array().unwrap(); assert_eq!(files.len(), 2, "{result}"); let graymap = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".pgm")).unwrap(); - assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n128 128\n65535\n")); + assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n256 256\n65535\n")); + let inherited = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".png")).unwrap(); + assert_eq!(image::image_dimensions(dir.join(inherited)).unwrap(), (128, 128)); + + shutdown(client, server).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn textures_export_reports_the_shader_sidecar_and_write_failures() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + let (client, server) = connect(workspace(dir)).await; + let params = json!({"dir": "textures", "shaderParameters": [0]}); + + let result = tool(&client, "textures_export", params.clone()).await; + + let files = result["files"].as_array().unwrap(); + let sidecar = files.iter().filter_map(Value::as_str).find(|name| name.ends_with("_shaders.json")).expect("shader settings file"); + let path = dir.join(sidecar); + let settings: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(settings["shaders"][0]["textureSets"].as_array().unwrap().len(), 1); + assert!(settings["shaders"][0]["model"].is_string()); + + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + let result = tool(&client, "textures_export", params).await; + + assert!(result["warnings"].as_array().unwrap().iter().any(|warning| warning.as_str().is_some_and(|text| text.contains("shader settings file")))); + assert!(result["files"].as_array().unwrap().iter().any(|file| file.as_str().is_some_and(|name| name.ends_with(".png")))); + + let error = tool_err(&client, "textures_export", json!({"dir": "invalid", "shaderParameters": [99]})).await; + + assert!(error.contains("shaderParameters")); + assert!(!dir.join("invalid").exists()); + shutdown(client, server).await; - std::fs::remove_dir_all(dir).unwrap(); } fn top(s: &Value) -> &Value { diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index c6af9341..ac846ba5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -13,14 +13,17 @@ use texturecraft_core::{NormalFormat, PROJECT_EXT}; use texturecraft_core::{Project, TextureSet}; use texturecraft_formats::PlannedFile; use texturecraft_formats::mesh_import::{MeshUvSource, import_mesh_geometry}; -use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile}; +use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, MapPreview, Padding, ProjectFile}; use texturecraft_geom::glam::Vec2; -use texturecraft_geom::{Mesh, primitives}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p}; use crate::session::{Document, Session}; use crate::{EngineError, Result, cmd}; +/// export.preview's picture width when the params name none +const DEFAULT_PREVIEW_SIDE_PIXELS: u32 = 128; + type BakePaintMaps = BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc>; fn prepare_archive(archive: &mut ProjectFile, uv_source: Option<&Mesh>, bake_paint: &BakePaintMaps) { @@ -82,7 +85,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), 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 .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?}", + "{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; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), 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?, size?: px (wins over `size`)}] (per map file type, bit depth and size), 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 .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), shaderParameters?: true|[texture set indexes] (also write _shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -100,10 +103,19 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)", + "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with or null, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)", always, plan ), + cmd!( + "export.preview", + "Preview an output map", + [], + None, + "{map: index into the preset's maps, side?: px (default 128, at most 512), plus the params of export.plan (the first texture set `ts` names)} → {width, height, channels: [\"R\", ...], pixels: [8-bit values as an sRGB file stores them, channels interleaved, row by row]}, or null when the texture set writes no file for the map", + always, + preview + ), ] } @@ -351,51 +363,119 @@ impl Session { } /// Render every export file for texture sets `sets` (in memory; works on the web). A file - /// named like one an earlier set exports is left out, with a warning (see - /// [`texturecraft_formats::skip_repeated_names`]). + /// named like one an earlier set exports is left out, with a warning. 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) + self.export_file_jobs(sets.iter().map(|&set| (set, opts))) } + /// Render one in-memory batch, using each set's own export settings when supplied. + pub fn export_file_jobs<'a>(&mut self, jobs: impl IntoIterator) -> Result> { + self.render_export_jobs(jobs, |_, plans| plans) + } + + #[cfg(not(target_arch = "wasm32"))] fn render_export_files( &mut self, sets: &[usize], options: &ExportOptions, + select: impl FnMut(usize, Vec) -> Vec, + ) -> Result> { + self.render_export_jobs(sets.iter().map(|&set| (set, options)), select) + } + + fn render_export_jobs<'a>( + &mut self, + jobs: impl IntoIterator, mut select: impl FnMut(usize, Vec) -> Vec, ) -> Result> { + let project = &self.doc.project; + let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); + let mut pending = Vec::new(); + for (set_index, options) in jobs { + let plans = texturecraft_formats::list_outputs(project, set_index, &mesh_name, options).map_err(fe)?; + let plans = select(set_index, plans); + if !plans.is_empty() { + pending.push((set_index, options, plans)); + } + } + + // Keep each winning plan with the options of the job that produced it + let plans = pending.iter_mut().enumerate().flat_map(|(job, (_, _, plans))| plans.drain(..).map(move |plan| (job, plan))); + let plans = texturecraft_formats::export::keep_first_planned_names(plans); + if pending.len() > 1 { + texturecraft_formats::export::validate_export_paths(plans.iter().map(|(_, plan)| plan.name.as_str())).map_err(fe)?; + } + + for (job, plan) in plans { + pending[job].2.push(plan); + } + pending.retain(|(_, _, plans)| !plans.is_empty()); + + let mut psd_bytes = 0; + for (set_index, options, plans) in &pending { + let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?; + texturecraft_formats::export::check_psd_batch(set, options, plans, &mut psd_bytes).map_err(fe)?; + } + if self.solo.is_none() { self.update(); } - let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); - let empty = Default::default(); - 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: set_index, - composite: &composite, - baked: self.doc.baked.get(&set_index).unwrap_or(&empty), - coverage: &coverage, - mesh_name: &mesh_name, - }; - out.extend(texturecraft_formats::export::render_planned_maps(&input, options, plans).map_err(fe)?); + for (set_index, options, plans) in pending { + let files = self.with_export_input( + set_index, + &mesh_name, + |grid| Cow::Owned(grid.coverage_mask()), + |input| texturecraft_formats::export::render_planned_maps(input, options, plans).map_err(fe), + )?; + out.extend(files); } Ok(out) } + + /// Run `with` on texture set `set_index`'s export input: its document composite, coverage and baked maps + fn with_export_input( + &self, + set_index: usize, + mesh_name: &str, + coverage: impl FnOnce(&UvGBuffer) -> Cow<'_, [Coverage]>, + with: impl FnOnce(&ExportInput) -> Result, + ) -> Result { + let missing = || EngineError::Other(format!("no texture set {set_index}")); + let cache = self.caches.get(set_index).ok_or_else(missing)?; + let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(missing)?; + let coverage = coverage(&cache.gbuf); + let empty = Default::default(); + let input = ExportInput { + project: &self.doc.project, + ts: set_index, + composite: &composite, + baked: self.doc.baked.get(&set_index).unwrap_or(&empty), + coverage: &coverage, + mesh_name, + }; + with(&input) + } + + /// A picture of output map `map` for the first texture set named in `params`, with each side at most `side` pixels. + /// Returns None when the map writes no file. + pub fn export_preview(&mut self, params: &Value, map: usize, side: u32) -> Result> { + let options = export_options(self, params, "export.preview")?; + let Some(&set_index) = sets_param(self, params, "export.preview")?.first() else { return Ok(None) }; + + if self.solo.is_none() { + self.update(); + } + let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); + self.with_export_input( + set_index, + &mesh_name, + |grid| Cow::Borrowed(&grid.tri), + |input| MapPreview::sample_triangles(input, &options, map, side).map_err(fe), + ) + } } fn check_materials(p: &texturecraft_core::Project, mesh: &Mesh) -> Result<()> { @@ -457,12 +537,12 @@ pub fn export_options(session: &Session, params: &Value, cmd: &str) -> Result Result> { let mut overrides = std::collections::BTreeMap::new(); let Some(list) = params.get("maps").filter(|value| !value.is_null()) else { return Ok(overrides) }; - let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?}"))?; + let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?, size?}"))?; for settings in list { let index = u64p(settings, "map").and_then(|value| usize::try_from(value).ok()).filter(|index| *index < map_count); let index = index.ok_or_else(|| bad(cmd, format!("`maps`: `map` must be the index of one of the preset's {map_count} maps")))?; @@ -481,6 +561,10 @@ fn map_overrides(params: &Value, map_count: usize, cmd: &str) -> Result Result { v.as_u64().and_then(|index| usize::try_from(index).ok()).filter(|index| *index < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`")) } +fn preview(session: &mut Session, params: &Value) -> Result { + let map = u64p(params, "map").and_then(|map| usize::try_from(map).ok()); + let map = map.ok_or_else(|| bad("export.preview", "`map` (an output map index) is required"))?; + let side = u64p(params, "side").map_or(DEFAULT_PREVIEW_SIDE_PIXELS, |side| side.clamp(1, u64::from(texturecraft_formats::MAX_PREVIEW_SIDE)) as u32); + + Ok(match session.export_preview(params, map, side)? { + Some(preview) => json!({ + "width": preview.width, + "height": preview.height, + "channels": preview.channels.iter().map(|dest| format!("{dest:?}")).collect::>(), + "pixels": preview.pixels, + }), + None => Value::Null, + }) +} + fn plan(session: &mut Session, params: &Value) -> Result { use texturecraft_formats::export::{list_set_outputs, scale_export_side}; @@ -527,18 +627,23 @@ fn plan(session: &mut Session, params: &Value) -> Result { let block_size = set.block_resolution(); for (_, output) in set_outputs { let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile)); - let size = scale_export_side(source_size, block_size, options.size); + + // A map's own size wins over the export's; a PSD is the size of its largest layer + let size = output.maps().map(|map| scale_export_side(source_size, block_size, options.map_size(map))).max().unwrap_or(source_size); files.push(json!({ "ts": set_index, "map": output.map, "file": output.name, + "tile": output.tile, + "udimPattern": output.udim_name, "format": output.format.extension(), "bitDepth": output.bit_depth, "dithering": output.dither, "size": size, "sourceSize": source_size, "warnings": output.warnings, + "layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::>(), })); } } @@ -771,6 +876,7 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { 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 usd_asset = usd_asset_param(session, params, &options, &sets)?; + let shader_sets = crate::shader_parameters::shader_parameters_param(&session.doc.project, params, &sets, "file.exportTextures")?; let mut warnings = Vec::new(); let mut udim_patterns = Vec::new(); @@ -830,6 +936,22 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { if let Some(exports) = &usd_asset { written.extend(write_usd_asset(session, dir, exports, &mut warnings)); } + if let Some(shader_sets) = shader_sets { + let name = crate::shader_parameters::shader_parameters_file(&session.doc.project.name); + let path = dir.join(&name); + let parameters = crate::shader_parameters::shader_parameters(&session.doc.project, &shader_sets); + + // Check the name against this command's files and the earlier commands' `reservedNames`, as the web download and headless export do + let roots = written.iter().filter_map(|written| written.strip_prefix(dir).ok()?.components().next()?.as_os_str().to_str()); + let checked = crate::shader_parameters::check_shader_parameters_name(&name, roots.chain(taken_names.keys().map(String::as_str))); + + // The textures are written by now: a shaders file that fails is a warning, as a failed USD asset is + let text = checked.and_then(|()| serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string())); + match text.and_then(|text| texturecraft_formats::write_atomic(&path, &text).map_err(|error| error.to_string())) { + Ok(()) => written.push(path), + Err(error) => warnings.push(format!("The shader settings file was not written: {error}")), + } + } 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 }); @@ -871,7 +993,7 @@ fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, s /// warning: the textures of the command are already written. #[cfg(not(target_arch = "wasm32"))] fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Option { - match build_usd_asset(session, dir, exports) { + match build_usd_asset(session, dir, exports, warnings) { Ok(path) => Some(path), Err(error) => { warnings.push(format!("{USD_ASSET_FAILED}: {error}")); @@ -881,7 +1003,7 @@ fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset } #[cfg(not(target_arch = "wasm32"))] -fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> Result { +fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Result { use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings}; let project = &session.doc.project; let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); @@ -902,6 +1024,15 @@ fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset // A map that lost any file (a tile of a UDIM map) is not bound: its `` name would read a file it does not own kept.retain(|file| !skipped_maps.contains(&file.map)); + let mut unsupported = HashSet::new(); + for file in kept.iter().filter(|file| !file.format.usable_by_usd_asset() && unsupported.insert(file.format)) { + let format = file.format.extension().to_ascii_uppercase(); + let warning = + format!("The USD asset doesn't read {format} files, so the material of texture set \"{}\" leaves out those maps", texture_set.name); + if !warnings.contains(&warning) { + warnings.push(warning); + } + } by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept)); } } @@ -948,8 +1079,20 @@ fn reserve_export_names( 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); + let reserved = reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)); + if !reserved && let Entry::Vacant(entry) = taken_names.entry(name) { + entry.insert(Some(set_index)); + return true; + } + + // A set warning outlives the file that carried it + for warning in plan.warnings.iter().filter(|warning| texturecraft_formats::export::is_set_warning(warning)) { + if !warnings.contains(warning) { + warnings.push(warning.clone()); + } + } + blocked_maps.extend(plan.maps()); + if reserved { 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 @@ -957,12 +1100,6 @@ fn reserve_export_names( return false; } - if let Entry::Vacant(entry) = taken_names.entry(name) { - entry.insert(Some(set_index)); - return true; - } - - 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", @@ -1039,11 +1176,11 @@ fn material_map_options(options: &ExportOptions, project_normal: NormalFormat) - continue; } - let mut overrides = MapOverride::default(); + let settings = replacement.and_then(|(index, _)| options.maps.get(&index)); + let mut overrides = MapOverride { size: settings.and_then(|settings| settings.size), ..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); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2a11e76a..d55a55c9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -88,6 +88,7 @@ pub mod resource_update_cmds; pub mod session; mod session_log; pub mod set_cmds; +pub mod shader_parameters; pub mod smart_masks; mod solo; mod stylized_lighting_params; diff --git a/crates/engine/src/preset_cmds.rs b/crates/engine/src/preset_cmds.rs index 73152301..9395ae2d 100644 --- a/crates/engine/src/preset_cmds.rs +++ b/crates/engine/src/preset_cmds.rs @@ -2,17 +2,19 @@ //! dialog's Output templates tab list, read, save and remove. On the desktop the user presets //! are mirrored as `.json` files in a library folder (see [`Session::load_export_presets`]). +use std::borrow::Cow; use std::collections::HashSet; use serde_json::{Value, json}; use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem}; -use texturecraft_formats::{ExportPreset, builtin_preset, builtin_presets, preset_from_json}; +use texturecraft_formats::{ExportPreset, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, preset_from_json}; use crate::commands::{CommandSpec, always, bad, strp}; use crate::{Result, Session, cmd}; /// Most user presets kept (and read from the library folder). const MAX_USER_PRESETS: usize = 512; +const BUILTIN_PRESET_PREFIX: &str = "builtin:"; /// The user's export presets. #[derive(Clone, Debug, Default)] @@ -51,6 +53,16 @@ fn same_name(a: &str, b: &str) -> bool { a.trim().eq_ignore_ascii_case(b.trim()) } +/// A qualified selector names a built-in independently of a saved library entry. +pub fn unqualified_preset_name(name: &str) -> &str { + let mut name = name.trim(); + while name.get(..BUILTIN_PRESET_PREFIX.len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case(BUILTIN_PRESET_PREFIX)) { + name = &name[BUILTIN_PRESET_PREFIX.len()..]; + } + + name +} + /// Library file stem: two names with the same stem would share a file. fn file_key(name: &str) -> String { sanitize_file_stem(name.trim()).to_ascii_lowercase() @@ -63,8 +75,25 @@ impl UserPresets { /// `name` belongs to a built-in or to a user preset other than `skip` (or shares its file). fn taken(&self, name: &str, skip: Option) -> bool { - builtin_preset(name).is_some() - || self.list.iter().enumerate().any(|(i, p)| Some(i) != skip && (same_name(&p.name, name) || file_key(&p.name) == file_key(name))) + let keeps_name = skip.and_then(|index| self.list.get(index)).is_some_and(|preset| same_name(&preset.name, name)); + (!keeps_name && builtin_preset(unqualified_preset_name(name)).is_some()) || self.user_name_taken(name, skip) + } + + fn user_name_taken(&self, name: &str, skip: Option) -> bool { + let key = file_key(name); + self.list.iter().enumerate().any(|(i, preset)| Some(i) != skip && (same_name(&preset.name, name) || file_key(&preset.name) == key)) + } + + /// Restore a saved preset under the name existing settings use. + pub fn restore(&mut self, preset: ExportPreset) -> std::result::Result<(), String> { + preset.validate().map_err(|error| error.to_string())?; + let reserved = builtin_preset(&preset.name).is_some_and(|builtin| !NEW_BUILTIN_PRESET_NAMES.contains(&builtin.name.as_str())); + if reserved || self.user_name_taken(&preset.name, None) || self.list.len() >= MAX_USER_PRESETS { + return Err(format!("preset \"{}\" exists already or the library is full", preset.name)); + } + + self.list.push(preset); + Ok(()) } /// The first available name, adding a numbered suffix and shortening the base to fit. @@ -119,7 +148,21 @@ impl UserPresets { impl Session { /// A built-in or user export preset by name (case-insensitive). pub fn export_preset(&self, name: &str) -> Option { - builtin_preset(name).or_else(|| self.export_presets.find(name).and_then(|i| self.export_presets.list.get(i).cloned())) + self.export_presets.find(name).and_then(|index| self.export_presets.list.get(index).cloned()).or_else(|| builtin_preset(unqualified_preset_name(name))) + } + + pub fn has_user_export_preset(&self, name: &str) -> bool { + self.export_presets.find(name).is_some() + } + + /// Use the familiar built-in name unless the user's library already owns that selector. + pub fn builtin_export_preset_id<'a>(&self, name: &'a str) -> Cow<'a, str> { + let mut id = Cow::Borrowed(name); + while self.has_user_export_preset(&id) { + id = Cow::Owned(format!("{BUILTIN_PRESET_PREFIX}{id}")); + } + + id } /// Use `dir` as the user preset library: read its `*.json` presets (replacing the list) and @@ -133,10 +176,8 @@ impl Session { files.sort(); let mut lib = UserPresets { list: Vec::new(), dir: Some(dir) }; for path in files.into_iter().take(MAX_USER_PRESETS) { - match texturecraft_formats::load_preset(&path).map_err(|e| e.to_string()) { - Ok(p) if lib.taken(&p.name, None) => warnings.push(format!("{}: preset \"{}\" exists already", path.display(), p.name)), - Ok(p) => lib.list.push(p), - Err(e) => warnings.push(format!("{}: {e}", path.display())), + if let Err(error) = texturecraft_formats::load_preset(&path).map_err(|error| error.to_string()).and_then(|preset| lib.restore(preset)) { + warnings.push(format!("{}: {error}", path.display())); } } self.export_presets = lib; @@ -144,10 +185,12 @@ impl Session { } } -fn list(s: &mut Session, _: &Value) -> Result { - let entry = |p: &ExportPreset, builtin: bool| json!({"name": p.name, "maps": p.maps.len(), "builtin": builtin}); - let builtins = builtin_presets(); - Ok(json!(builtins.iter().map(|p| entry(p, true)).chain(s.export_presets.list.iter().map(|p| entry(p, false))).collect::>())) +fn list(session: &mut Session, _: &Value) -> Result { + let entry = |name: &str, maps: usize, builtin: bool| json!({"name": name, "maps": maps, "builtin": builtin}); + let builtins = builtin_preset_catalog().iter().map(|preset| entry(&session.builtin_export_preset_id(&preset.name), preset.maps.len(), true)); + let custom = session.export_presets.list.iter().map(|preset| entry(&preset.name, preset.maps.len(), false)); + + Ok(json!(builtins.chain(custom).collect::>())) } fn name_param<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> { @@ -216,11 +259,16 @@ fn save(session: &mut Session, params: &Value) -> Result { fn remove(s: &mut Session, p: &Value) -> Result { const CMD: &str = "export.preset.remove"; let name = name_param(p, CMD)?; - if builtin_preset(name).is_some() { - return Err(bad(CMD, format!("\"{name}\" is a built-in preset and can't be removed"))); - } - let i = s.export_presets.find(name).ok_or_else(|| bad(CMD, format!("no user export preset `{name}`")))?; - let removed = s.export_presets.list.remove(i); + let Some(index) = s.export_presets.find(name) else { + let message = if builtin_preset(unqualified_preset_name(name)).is_some() { + format!("\"{name}\" is a built-in preset and can't be removed") + } else { + format!("no user export preset `{name}`") + }; + return Err(bad(CMD, message)); + }; + + let removed = s.export_presets.list.remove(index); s.export_presets.delete(&removed.name); Ok(Value::Null) } @@ -409,6 +457,36 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn feedback_existing_preset_keeps_its_name_and_export_maps() { + let dir = tempfile::tempdir().unwrap(); + let name = "Roblox SurfaceAppearance (separate maps)"; + let custom = preset(name); + std::fs::write(dir.path().join(format!("{}.json", sanitize_file_stem(name))), custom.to_string()).unwrap(); + let mut s = session(); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4); + + let warnings = s.load_export_presets(dir.path().to_path_buf()); + + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name.to_ascii_lowercase()})).unwrap(), custom); + let plan = run(&mut s, "export.plan", json!({"preset": name, "ts": 0})).unwrap(); + assert_eq!(plan.as_array().unwrap().len(), 1); + assert!(plan[0]["file"].as_str().unwrap().ends_with("_R.png")); + + let listed = run(&mut s, "export.presets", json!({})).unwrap(); + let names = listed.as_array().unwrap(); + assert!(names.iter().any(|entry| entry["name"] == name && entry["builtin"] == false)); + let builtin = format!("builtin:{name}"); + assert!(names.iter().any(|entry| entry["name"] == builtin && entry["builtin"] == true)); + let builtin_plan = run(&mut s, "export.plan", json!({"preset": builtin, "ts": 0})).unwrap(); + assert!(builtin_plan.as_array().unwrap().len() > 1); + run(&mut s, "export.preset.save", json!({"preset": custom})).unwrap(); + run(&mut s, "export.preset.remove", json!({"name": name})).unwrap(); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn the_library_folder_mirrors_saves_renames_and_removals() { diff --git a/crates/engine/src/shader_parameters.rs b/crates/engine/src/shader_parameters.rs new file mode 100644 index 00000000..12a04674 --- /dev/null +++ b/crates/engine/src/shader_parameters.rs @@ -0,0 +1,93 @@ +//! Export shader parameters: the project's shader, its settings and the texture sets using it, as JSON + +use serde_json::{Value, json}; +use texturecraft_core::Project; +use texturecraft_formats::ExportedFile; + +use crate::Result; +use crate::commands::bad; + +/// The project's one shader, its parameters and the names of `sets` (they all use it) +pub fn shader_parameters(project: &Project, sets: &[usize]) -> Value { + let display = &project.display; + let model = if display.spec_gloss { "specularGlossiness" } else { "metallicRoughness" }; + let names: Vec<&str> = sets.iter().filter_map(|ts| project.texture_sets.get(*ts)).map(|set| set.name.as_str()).collect(); + + json!({ + "shaders": [{ + "model": model, + "parameters": { + "aoIntensity": display.ao_intensity, + "ior": display.ior, + "scatterColor": display.scatter_color, + "scatterRadius": display.scatter_radius, + "displacement": display.displacement, + "parallax": display.parallax, + }, + "textureSets": names, + }] + }) +} + +/// The JSON file's name for project `name` +pub fn shader_parameters_file(name: &str) -> String { + format!("{}_shaders.json", texturecraft_formats::export::sanitize_file_stem(name)) +} + +/// Refuse the file name `name` when one of the export's texture paths (`/`-separated, relative to the export folder) is that file or lies in a folder of that name, ignoring case +pub fn check_shader_parameters_name<'a>(name: &str, texture_paths: impl IntoIterator) -> std::result::Result<(), String> { + if texture_paths.into_iter().any(|path| path.split('/').next().is_some_and(|root| root.eq_ignore_ascii_case(name))) { + return Err(format!("\"{name}\" is already used by a texture file or folder")); + } + + Ok(()) +} + +/// Build the download or headless sidecar after checking its name against every texture path. +pub fn shader_parameters_sidecar(project: &Project, sets: &[usize], textures: &[ExportedFile]) -> std::result::Result { + let name = shader_parameters_file(&project.name); + check_shader_parameters_name(&name, textures.iter().map(|texture| texture.name.as_str()))?; + + let bytes = serde_json::to_vec_pretty(&shader_parameters(project, sets)).map_err(|error| error.to_string())?; + Ok(ExportedFile { name, bytes, width: 0, height: 0, warnings: Vec::new() }) +} + +/// The texture sets `shaderParameters` asks to list: `true` takes the command's own `sets`, a list gives them all; None when it asks for no file +pub fn shader_parameters_param(project: &Project, params: &Value, sets: &[usize], cmd: &str) -> Result>> { + match params.get("shaderParameters") { + None | Some(Value::Null | Value::Bool(false)) => Ok(None), + Some(Value::Bool(true)) => Ok(Some(sets.to_vec())), + Some(Value::Array(indexes)) => indexes + .iter() + .map(|index| { + index + .as_u64() + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < project.texture_sets.len()) + .ok_or_else(|| bad(cmd, "`shaderParameters` lists texture set indexes")) + }) + .collect::>>() + .map(Some), + Some(_) => Err(bad(cmd, "`shaderParameters` must be true, false or a list of texture set indexes")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_json_names_the_shader_its_settings_and_its_texture_sets() { + let mut session = crate::sample_session(128, 32).unwrap(); + session.doc.project.display.ior = 1.33; + + let value = shader_parameters(&session.doc.project, &[1]); + + let shader = &value["shaders"][0]; + + assert_eq!(shader["model"], "metallicRoughness"); + assert!((shader["parameters"]["ior"].as_f64().unwrap() - 1.33).abs() < 1e-6); + assert_eq!(shader["textureSets"], json!([session.doc.project.texture_sets[1].name])); + assert!(shader_parameters_file("Material Ball").ends_with("_shaders.json")); + } +} diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index e4f0e56f..dca3a215 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -27,3 +27,161 @@ fn the_new_file_types_dithering_and_diffusion_export() { assert!(plan.as_array().unwrap().iter().all(|f| f["dithering"] == false), "float files are never dithered"); assert!(execute(&mut s, "export.plan", &json!({"padding": "smudge"})).is_err()); } + +#[test] +fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() { + const SMALL_SIDE: u32 = 128; + let mesh = texturecraft_engine::geom::primitives::udim_plane(); + let mut session = texturecraft_engine::Session::new_project("test", mesh, "builtin:udim_plane", None, SMALL_SIDE).unwrap(); + let preset = + json!({"name": "Roughness", "maps": [{"file": "rough", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]}); + let options = |size| texturecraft_engine::file_cmds::export_options(&session, &json!({"preset": preset, "size": size, "padding": "none"}), "test").unwrap(); + let small = options(SMALL_SIDE); + let large = options(4096); + let first = session.export_files(&[0], &small).unwrap(); + assert!(first.len() > 1, "the mesh supplies multiple PSD tiles"); + + let jobs = std::iter::once((0, &small)).chain(std::iter::repeat_n((0, &large), 4)); + let batch = session.export_file_jobs(jobs).unwrap(); + + assert_eq!(batch.len(), first.len()); + assert!(batch.iter().zip(&first).all(|(kept, original)| kept.name == original.name && kept.bytes == original.bytes)); + assert!(batch.iter().zip(&first).all(|(kept, original)| kept.warnings.len() > original.warnings.len())); + println!("Kept {} PSDs totaling {} encoded bytes", batch.len(), batch.iter().map(|file| file.bytes.len()).sum::()); +} + +#[test] +fn a_psd_file_and_another_sets_folder_conflict_during_planning() { + use texturecraft_engine::core::Channel; + use texturecraft_engine::file_cmds::export_options; + + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let sets = &mut session.doc.project.texture_sets; + sets[0].name = "Body".into(); + sets[0].channels.retain(|(channel, _)| *channel != Channel::Metallic); + sets[1].name = "Trim".into(); + let preset = json!({"name": "Conflicting outputs", "maps": [ + {"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}, + {"file": "$mesh_Body.psd/detail", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Metallic"}}]]} + ]}); + let dir = tempfile::tempdir().unwrap(); + let mut params = json!({"preset": preset, "padding": "none", "dir": dir.path()}); + + params["ts"] = json!(0); + let body = execute(&mut session, "export.plan", ¶ms).unwrap(); + params["ts"] = json!(1); + let trim = execute(&mut session, "export.plan", ¶ms).unwrap(); + let file = body[0]["file"].as_str().unwrap(); + let nested_file = trim.as_array().unwrap().iter().find_map(|file| file["file"].as_str().filter(|name| name.contains('/'))).unwrap(); + assert_eq!(nested_file.split('/').next(), Some(file), "separate plans collide when combined"); + + for order in [[0, 1], [1, 0]] { + params["ts"] = json!(order); + let plan_error = execute(&mut session, "export.plan", ¶ms).unwrap_err(); + let options = export_options(&session, ¶ms, "export.plan").unwrap(); + let render_error = session.export_files(&order, &options).unwrap_err(); + let write_error = execute(&mut session, "file.exportTextures", ¶ms).unwrap_err(); + + for error in [plan_error, render_error, write_error] { + assert!(error.to_string().contains("folder"), "{error}"); + } + assert!(std::fs::read_dir(dir.path()).unwrap().next().is_none()); + } +} + +#[test] +fn a_map_size_wins_over_the_export_size_in_the_plan() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + + let plan = execute(&mut session, "export.plan", &json!({"ts": 0, "size": 512, "maps": [{"map": 0, "size": 128}]})).unwrap(); + + let (overridden, inherited): (Vec<_>, Vec<_>) = plan.as_array().unwrap().iter().partition(|file| file["map"] == 0); + + assert!(!overridden.is_empty() && !inherited.is_empty(), "{plan}"); + assert!(overridden.iter().all(|file| file["size"] == 128), "{plan}"); + assert!(inherited.iter().all(|file| file["size"] == 512), "{plan}"); + assert!(execute(&mut session, "export.plan", &json!({"ts": 0, "maps": [{"map": 0, "size": 100}]})).is_err()); +} + +#[test] +fn shader_parameters_write_the_shaders_json_next_to_the_textures() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join(texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name)); + + let result = execute(&mut session, "file.exportTextures", &json!({"dir": dir.path().display().to_string(), "ts": 1, "shaderParameters": [0, 1]})).unwrap(); + + assert!(result["files"].as_array().unwrap().iter().any(|f| f.as_str() == Some(file.to_str().unwrap())), "{result}"); + let written: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let names: Vec<&str> = session.doc.project.texture_sets.iter().take(2).map(|set| set.name.as_str()).collect(); + + assert_eq!(written["shaders"][0]["textureSets"], json!(names)); + assert!(execute(&mut session, "file.exportTextures", &json!({"dir": dir.path().display().to_string(), "shaderParameters": "yes"})).is_err()); +} + +#[test] +fn a_shaders_json_that_cannot_be_written_is_a_warning_after_the_textures() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join(texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name)); + std::fs::create_dir_all(&file).unwrap(); + + let result = execute(&mut session, "file.exportTextures", &json!({"dir": dir.path().display().to_string(), "ts": 0, "shaderParameters": true})).unwrap(); + + let files = result["files"].as_array().unwrap(); + + assert!(!files.is_empty() && files.iter().all(|f| f.as_str() != Some(file.to_str().unwrap())), "{result}"); + let warnings = result["warnings"].as_array().unwrap(); + + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("The shader settings file was not written"))), "{result}"); +} + +#[test] +fn a_shaders_json_named_like_an_earlier_commands_folder_is_a_warning() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let name = texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name); + let reserved = format!("{}/Color.png", name.to_uppercase()); + + let result = execute( + &mut session, + "file.exportTextures", + &json!({"dir": dir.path().display().to_string(), "ts": 0, "shaderParameters": true, "reservedNames": [reserved]}), + ) + .unwrap(); + + assert!(!dir.path().join(&name).exists(), "{result}"); + let warnings = result["warnings"].as_array().unwrap(); + + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("already used by a texture file or folder"))), "{result}"); +} + +#[test] +fn a_psd_warning_outlives_a_reserved_file_that_carried_it() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let roughness = json!([["L", {"Channel": {"channel": "Roughness"}}]]); + let colour = json!([["R", {"Channel": {"channel": "BaseColor"}}], ["G", {"Channel": {"channel": "BaseColor", "component": 1}}], ["B", {"Channel": {"channel": "BaseColor", "component": 2}}], ["A", {"Constant": 0.5}]]); + let mut preset = json!({"name": "Two and a PSD", "maps": [ + {"file": "first", "format": "Png", "bit_depth": 8, "channels": roughness}, + {"file": "second", "format": "Png", "bit_depth": 8, "channels": roughness}, + ]}); + + // Four 16-bit RGBA layers at 8192 pixels exceed the 2 GiB PSD limit + for layer in 0..4 { + preset["maps"].as_array_mut().unwrap().push(json!({"file": format!("layer{layer}"), "format": "Psd", "bit_depth": 16, "channels": colour})); + } + let sizes: Vec<_> = (2..6).map(|map| json!({"map": map, "size": 8192})).collect(); + let params = |reserved: Vec| json!({"dir": dir.path().display().to_string(), "ts": 0, "preset": preset, "maps": sizes, "reservedNames": reserved}); + let plan = execute(&mut session, "export.plan", ¶ms(Vec::new())).unwrap(); + let first = plan[0]["file"].as_str().unwrap().to_owned(); + let second = plan[1]["file"].as_str().unwrap().to_owned(); + let psd_warning = + |warnings: &serde_json::Value| warnings.as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains(".psd\" was not written"))); + assert!(plan.as_array().unwrap().len() == 2 && psd_warning(&plan[0]["warnings"]), "{plan}"); + + let result = execute(&mut session, "file.exportTextures", ¶ms(vec![first.clone()])).unwrap(); + + assert!(psd_warning(&result["warnings"]), "{result}"); + assert!(dir.path().join(&second).exists() && !dir.path().join(&first).exists(), "{result}"); +} diff --git a/crates/engine/tests/it/export_maps.rs b/crates/engine/tests/it/export_maps.rs index 991b5f32..f147ef1b 100644 --- a/crates/engine/tests/it/export_maps.rs +++ b/crates/engine/tests/it/export_maps.rs @@ -105,3 +105,24 @@ fn a_file_name_an_earlier_texture_set_exports_is_not_overwritten() { } assert_eq!(result["files"].as_array().unwrap().len(), names.len()); } + +#[test] +fn export_preview_shows_a_packed_map_small_and_nothing_for_a_left_out_one() { + let mut s = session(); + let preset = s.export_preset("Unity HDRP (Mask Map)").unwrap(); + let mask = preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap(); + let params = json!({"preset": preset.name, "ts": 0, "map": mask, "side": 16}); + + let preview = execute(&mut s, "export.preview", ¶ms).unwrap(); + let (width, height) = (preview["width"].as_u64().unwrap(), preview["height"].as_u64().unwrap()); + + assert!(width <= 16 && height > 0, "{preview}"); + assert_eq!(preview["channels"], json!(["R", "G", "B", "A"]), "the mask map packs four channels"); + assert_eq!(preview["pixels"].as_array().unwrap().len() as u64, width * height * 4); + + let left_out = json!({"preset": preset.name, "ts": 0, "map": mask, "maps": [{"map": mask, "enabled": false}]}); + + assert!(execute(&mut s, "export.preview", &left_out).unwrap().is_null(), "a map the export leaves out has no file to show"); + assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name})).is_err(), "the map is required"); + assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name, "map": preset.maps.len()})).is_err()); +} diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index b69391bd..c6ee8dfe 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -197,11 +197,15 @@ fn a_file_type_a_material_cannot_use_falls_back_to_png() { ) .unwrap(); + // A PSD holds every map of the texture set as a layer 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 template_file = if format == "psd" { ".psd".to_string() } else { format!("_baseColor.{ext}") }; + + assert!(all.iter().any(|f| f.ends_with(&template_file)), "{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:?}"); @@ -209,6 +213,27 @@ fn a_file_type_a_material_cannot_use_falls_back_to_png() { } } +#[test] +fn materialx_png_fallback_preserves_the_selected_maps_size() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("map-size-fallback"); + let options = json!({ + "dir": dir.display().to_string(), "preset": OPENPBR, "ts": 0, "size": 128, "materialX": true, + "maps": [{"map": 0, "format": "psd", "size": 256}] + }); + + let result = execute(&mut session, "file.exportTextures", &options).unwrap(); + + let files = files(&result); + + assert!(files.iter().any(|file| file.ends_with(".psd")), "{result}"); + let base = files.iter().find(|file| file.ends_with("_base_color.png")).unwrap(); + let roughness = files.iter().find(|file| file.ends_with("_specular_roughness.png")).unwrap(); + + assert_eq!(image::image_dimensions(base).unwrap(), (256, 256)); + assert_eq!(image::image_dimensions(roughness).unwrap(), (128, 128)); +} + #[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(); diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index e6ef7bd9..a130f813 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -407,3 +407,17 @@ fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() { assert!(dir.join(&read.file).is_file(), "{} was written", read.file); } } + +#[test] +fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() { + let mut s = ball(); + let dir = temp("psd"); + + let r = export(&mut s, &dir, json!({"ts": 0, "format": "psd", "usdAsset": true})); + + assert!(files(&r).iter().any(|f| f.ends_with(".psd")), "{r}"); + let materials = read_back(&s, &dir); + + assert!(materials[material_of(&s, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&s, 0)]); + assert!(r["warnings"].to_string().contains("doesn't read PSD files"), "{r}"); +} diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 2319dbd7..8135b5b0 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -28,7 +28,6 @@ craft-image-codecs = { workspace = true } craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } flate2 = { workspace = true } half = { workspace = true } -quick-xml = { workspace = true } zip = { workspace = true } exr = { workspace = true } serde = { workspace = true } diff --git a/crates/formats/README.md b/crates/formats/README.md index 66ee79e0..f32292cb 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -106,9 +106,13 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result; collisions get `_2`, `_3`, … plus a warning. - A map is written only when one of its sources has data in the texture set (channel present, map baked, …); alpha from a missing channel is dropped. -- Formats: PNG 8/16, JPEG 8 (q 95), JNG 8 (JPEG colour, deflate alpha), PGM 8/16 (gray; colour - becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8, WebP 8 (lossless), PSD 8/16 (merged image, no - layers; alpha is an extra alpha channel, not transparency), EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. 8-bit files can be dithered +- Formats: PNG 8/16, JPEG 8 (q 95), JNG 8 (JPEG colour, + deflate alpha), PGM 8/16 (gray; colour becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8, + WebP 8 (lossless), PSD 8/16, EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. + PSD writes one file per texture set or UV tile, with each output map stored as a layer. + For tiled sets, `ExportOptions::atlas` writes one document for the whole set. Smaller maps + keep their sizes and align to the top left of the canvas. A `/` in a map + name creates a layer group inside the PSD. 8-bit files can be dithered (`ExportOptions::dither`, an 8×8 ordered pattern). When `ExportOptions::color_space` is unset, color maps default to sRGB in integer files and linear Rec.709 in float files. An explicit override can select another supported space. PGM writes sRGB or linear Rec.709 luminance and @@ -137,9 +141,24 @@ Built-in presets (each one lists the public specification its packing follows in | OpenPBR (separate maps) | one map per OpenPBR Surface input the set has: `base_color`, `base_metalness`, `specular_roughness`, `specular_roughness_anisotropy`, `coat_weight`, `coat_roughness`, `fuzz_weight`, `fuzz_color`, `fuzz_roughness`, `transmission_weight`, `subsurface_weight`, `emission_color`, `geometry_opacity`, `geometry_normal` (OpenGL), `height` (16-bit) | | Unity URP Lit (Metallic Smoothness) | `BaseMap`, `MetallicMap` (R metal, A smoothness), `NormalMap` (OpenGL), `OcclusionMap`, `EmissionMap` | | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | +| Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | +| glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | +| Redshift Standard Material (separate maps) | separate maps for the listed inputs when the set supplies their sources: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | +| Roblox SurfaceAppearance (separate maps) | `Color` (A = opacity), `Normal` (OpenGL), `Metalness`, `Roughness` | +| Sketchfab Metalness (separate maps) | `BaseColor` (no alpha), `Metalness`, `Roughness`, `Normal` (DirectX), `AmbientOcclusion`, `Emission` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | +The preset column gives the stable automation and saved-setting names. When a user preset shares +a table name, that name selects the user preset so saved settings keep working. To select the +built-in through automation, pass the exact `name` from its `builtin: true` entry in +`export.presets`. + +The export window describes four templates by their output. **Packed maps with a scattering mask** +targets Unreal Engine's subsurface input. **Separate coat, sheen and scattering maps** targets Redshift. +**Four maps with opacity in color** targets Roblox, and **Six maps with a negative-Y normal** +targets Sketchfab. + ### Project file (`project_file`) ```rust diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs new file mode 100644 index 00000000..f7be380c --- /dev/null +++ b/crates/formats/src/export/layered_psd.rs @@ -0,0 +1,242 @@ +//! A texture set's PSD: each output map a layer, a `/` in its name a layer group + +use craft_psd::{Compression, GroupSpec, LayerSpec, PixelData, PsdBuilder}; +use texturecraft_core::TextureSet; +use texturecraft_texel::linear_to_srgb; + +use super::encoding::Encoding; +use super::map_renderer::MapRenderer; +use super::{ + ExportOptions, ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, Padding, PlannedFile, PlannedLayer, check_psd_size, psd_size, + quantize_integer, quantize_u8, quantize_u16, +}; +use crate::{FormatError, Result}; + +/// Where alpha sits in an RGBA texel +const ALPHA_INDEX: usize = 3; + +/// Check the file limits and the working memory against `working_limit` (None: unlimited), returning the canvas size and estimated encoded bytes +pub(super) fn preflight<'a>( + set: &TextureSet, + options: &ExportOptions, + tile: Option, + depth: u8, + layers: impl Iterator + Clone, + working_limit: Option, +) -> Result<((u32, u32), u64)> { + let (canvas, file_bytes, working_bytes) = working_set(set, options, tile, depth, layers)?; + if working_limit.is_some_and(|limit| working_bytes >= limit) { + let (width, height) = canvas; + return Err(FormatError::Invalid(format!( + "a PSD at {width}×{height} would exceed the working memory budget; use a smaller export size, fewer PSD maps or another format" + ))); + } + + Ok((canvas, file_bytes)) +} + +/// The canvas size, estimated encoded bytes and peak working bytes of one PSD, after checking the file limits +fn working_set<'a>( + set: &TextureSet, + options: &ExportOptions, + tile: Option, + depth: u8, + layers: impl Iterator + Clone, +) -> Result<((u32, u32), u64, u64)> { + let texels = |(width, height)| u64::from(width) * u64::from(height); + let folder_count = layers.clone().map(|layer| layer.name.matches('/').count()).sum(); + let sizes = layers.map(|layer| psd_size(set, tile, options.map_size(layer.map))); + let (canvas, file_bytes) = check_psd_size(sizes.clone(), folder_count, depth)?; + let float_bytes_per_texel = (PSD_RGBA_PLANES * size_of::()) as u64; + let source_bytes = texels(psd_size(set, tile, None)).saturating_mul(float_bytes_per_texel); + let largest_layer_bytes = sizes.map(texels).max().unwrap_or(0) * float_bytes_per_texel; + + // The merged image is built a row at a time: a canvas row and a layer row in floating point + let merge_bytes = 2 * u64::from(canvas.0) * float_bytes_per_texel; + + // Resizing overlaps source and destination, and RGBA conversion can overlap two output buffers + let mut scratch_bytes = source_bytes.saturating_add(largest_layer_bytes).max(2 * largest_layer_bytes); + if matches!(options.padding, Padding::DilationDiffusion(_)) { + // A copied block, its weights, and the smaller pyramid levels fit within this source allowance + scratch_bytes = scratch_bytes.max(source_bytes.saturating_mul(3)); + } + + let mut padding_bytes = 0; + let mut padding_peak = 0; + if options.padding != Padding::None { + let atlas_texels = texels(set.size()); + padding_bytes = atlas_texels.saturating_mul(size_of::() as u64); + + // The atlas keeps its dilation indices after the frontiers are freed + padding_peak = padding_bytes.saturating_add(atlas_texels.saturating_mul((4 * size_of::()) as u64)); + } + + // The quantized layers kept so far and the merged image are part of the file; the encoder can hold staged pixels, planes and the output at once + let rendering = scratch_bytes.max(merge_bytes).saturating_add(file_bytes); + let encoding = 3 * file_bytes; + let working_bytes = padding_bytes.saturating_add(rendering.max(encoding)).max(padding_peak); + Ok((canvas, file_bytes, working_bytes)) +} + +/// Render each layer at its requested size, aligned to the upper-left corner of the PSD canvas. +pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u32, u32)) -> Result { + let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned; + + // Only the current layer is in floating point; the others are kept as the file stores them + let mut pixels = Vec::with_capacity(layers.len()); + let mut embedded = None; + for layer in layers.iter().rev() { + let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; + embedded = map.embed.or(embedded); + let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; + let layer_pixels = rgba_pixel_data(map.data, map.component_count, &map.srgb, map.size.0, encoding)?; + pixels.push((layer.name.as_str(), map.size, layer_pixels)); + } + if let Some(space) = embedded { + warnings.push(format!("PSD export does not embed a colour space; the colours are in {}", space.name())); + } + + let composite = merged_image(size, bit_depth, &pixels)?; + + let bytes = write_layers(size, bit_depth, pixels, composite).map_err(|error| FormatError::Invalid(format!("psd encoding failed: {error}")))?; + if bytes.len() as u64 >= PSD_MAX_FILE_BYTES { + return Err(FormatError::Invalid(format!("\"{name}\" would reach the 2 GiB PSD file limit; use a smaller export size or fewer PSD maps"))); + } + + Ok(ExportedFile { name, bytes, width: size.0, height: size.1, warnings }) +} + +/// The merged image of `layers` (bottom first, as the file stores them), one row at a time +fn merged_image((width, height): (u32, u32), depth: u8, layers: &[(&str, (u32, u32), PixelData)]) -> Result { + let row_len = width as usize * PSD_RGBA_PLANES; + let sample_count = row_len * height as usize; + let mut merged_row = vec![0.0f32; row_len]; + let mut layer_row = Vec::with_capacity(row_len); + let reserve_error = |error| FormatError::Invalid(format!("PSD merged image allocation failed: {error}")); + if depth == 16 { + let mut merged = Vec::new(); + merged.try_reserve_exact(sample_count).map_err(reserve_error)?; + for y in 0..height as usize { + merge_row(y, width, layers, &mut merged_row, &mut layer_row); + merged.extend(merged_row.iter().map(|&value| quantize_u16(value))); + } + return Ok(PixelData::Rgba16(merged)); + } + + let mut merged = Vec::new(); + merged.try_reserve_exact(sample_count).map_err(reserve_error)?; + for y in 0..height as usize { + merge_row(y, width, layers, &mut merged_row, &mut layer_row); + merged.extend(merged_row.iter().copied().map(quantize_u8)); + } + + Ok(PixelData::Rgba8(merged)) +} + +/// Row `y` of the merged image into `merged_row`, each layer's row decoded into `layer_row` in turn +fn merge_row(y: usize, width: u32, layers: &[(&str, (u32, u32), PixelData)], merged_row: &mut [f32], layer_row: &mut Vec) { + merged_row.fill(0.0); + for (_, (layer_width, layer_height), samples) in layers { + if y >= *layer_height as usize { + continue; + } + + let span = *layer_width as usize * PSD_RGBA_PLANES; + let range = y * span..(y + 1) * span; + layer_row.clear(); + match samples { + PixelData::Rgba8(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u8::MAX))), + PixelData::Rgba16(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u16::MAX))), + _ => continue, + } + over(merged_row, width, layer_row, *layer_width); + } +} + +/// Composite a straight-alpha RGBA layer at the top left of the canvas. +fn over(canvas: &mut [f32], canvas_width: u32, layer: &[f32], layer_width: u32) { + let canvas_rows = canvas.chunks_exact_mut(canvas_width as usize * PSD_RGBA_PLANES); + let layer_rows = layer.chunks_exact(layer_width as usize * PSD_RGBA_PLANES); + for (canvas_row, layer_row) in canvas_rows.zip(layer_rows) { + let canvas_texels = canvas_row.as_chunks_mut::().0; + let layer_texels = layer_row.as_chunks::().0; + for (under, top) in canvas_texels.iter_mut().zip(layer_texels) { + let (top_alpha, under_alpha) = (top[ALPHA_INDEX], under[ALPHA_INDEX]); + let alpha = top_alpha + under_alpha * (1.0 - top_alpha); + if alpha <= 0.0 { + continue; + } + + for (value, top_value) in under.iter_mut().zip(top).take(ALPHA_INDEX) { + *value = (top_value * top_alpha + *value * under_alpha * (1.0 - top_alpha)) / alpha; + } + under[ALPHA_INDEX] = alpha; + } + } +} + +/// L, LA, RGB or RGBA samples quantized as the RGBA the PSD builder accepts: gray repeated, opaque without alpha, sRGB transfer applied to the components `srgb` marks, values clamped to 0-1 +fn rgba_pixel_data(mut data: Vec, component_count: usize, srgb: &[bool], width: u32, encoding: Encoding) -> Result { + let component_count = component_count.max(1); + for texel in data.chunks_exact_mut(component_count) { + for (component, value) in texel.iter_mut().enumerate() { + *value = if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(*value) } else { value.clamp(0.0, 1.0) }; + } + } + + // Widen each texel while quantizing, so no floating-point RGBA copy of the layer is made + let texel_count = data.len() / component_count; + let rgba = (0..texel_count * PSD_RGBA_PLANES).map(|index| { + let (texel, component) = (index / PSD_RGBA_PLANES, index % PSD_RGBA_PLANES); + let source = match component_count { + 1 | 2 if component < ALPHA_INDEX => Some(0), + 1 | 3 if component == ALPHA_INDEX => None, + 2 => Some(1), + _ => Some(component), + }; + source.map_or(1.0, |source| data.get(texel * component_count + source).copied().unwrap_or(0.0)) + }); + + if encoding.depth == 16 { + let mut pixels = Vec::new(); + pixels.try_reserve_exact(rgba.len()).map_err(|error| FormatError::Invalid(format!("PSD sample buffer allocation failed: {error}")))?; + pixels.extend(rgba.map(quantize_u16)); + return Ok(PixelData::Rgba16(pixels)); + } + + quantize_integer(encoding, width, PSD_RGBA_PLANES, rgba).map(PixelData::Rgba8) +} + +/// An RGB PSD of `layers` (bottom first, each named by its `/`-separated group path) over the merged `composite`, uncompressed so its size is known up front +pub(super) fn write_layers( + (width, height): (u32, u32), + depth: u8, + layers: Vec<(&str, (u32, u32), PixelData)>, + composite: PixelData, +) -> craft_psd::Result> { + let mut builder = PsdBuilder::new(width, height).depth(u16::from(depth)).compression(Compression::Raw); + + // The builder stacks bottom up, so the groups open and close in that order too + let mut open: Vec<&str> = Vec::new(); + for (path, (layer_width, layer_height), pixels) in layers { + let mut parts: Vec<&str> = path.split('/').collect(); + let name = parts.pop().unwrap_or_default(); + let shared = open.iter().zip(&parts).take_while(|(open, part)| open == part).count(); + for _ in shared..open.len() { + builder.end_group()?; + } + open.truncate(shared); + for group in parts.iter().skip(shared) { + builder.begin_group(GroupSpec::new(*group)); + open.push(group); + } + + builder.push_layer(LayerSpec::new(name, 0, 0, layer_width, layer_height, pixels)); + } + for _ in open { + builder.end_group()?; + } + + builder.composite(composite); + builder.to_bytes() +} diff --git a/crates/formats/src/export/map_override.rs b/crates/formats/src/export/map_override.rs index 5ea62f5c..aec6ef56 100644 --- a/crates/formats/src/export/map_override.rs +++ b/crates/formats/src/export/map_override.rs @@ -14,10 +14,13 @@ pub struct MapOverride { /// Instead of the export's dithering of 8-bit files. #[serde(default)] pub dither: Option, + /// Output size (power of two) instead of the export's + #[serde(default)] + pub size: Option, } impl Default for MapOverride { fn default() -> Self { - MapOverride { enabled: true, format: None, bit_depth: None, dither: None } + MapOverride { enabled: true, format: None, bit_depth: None, dither: None, size: None } } } diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs new file mode 100644 index 00000000..a4401503 --- /dev/null +++ b/crates/formats/src/export/map_preview.rs @@ -0,0 +1,134 @@ +//! A small picture of one output map, sampled from the texture set as the export samples it + +use rayon::prelude::*; +use texturecraft_texel::linear_to_srgb; + +use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Sampler, SourceRef, layout, list_outputs, rec709_luminance}; +use crate::{FormatError, Result}; + +/// The largest preview side: a preview is a glance, never a second export +pub const MAX_PREVIEW_SIDE: u32 = 512; + +/// One output map, small: its channels in file order and the 8-bit values an sRGB file of it stores (colour channels sRGB-encoded, data as is) +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MapPreview { + pub width: u32, + pub height: u32, + pub channels: Vec, + /// `channels.len()` values per pixel, row by row + pub pixels: Vec, +} + +impl MapPreview { + /// Output map `map` of `options`' template for `input`'s set, with each side at most `side` pixels. + /// Returns None when the map writes no file. Texels off the UV islands show the default. + pub fn sample(input: &ExportInput, options: &ExportOptions, map: usize, side: u32) -> Result> { + Self::sample_coverage(input, options, map, side, false) + } + + /// Sample the engine's triangle indices directly, using the UV rasterizer's uncovered sentinel. + pub fn sample_triangles(input: &ExportInput, options: &ExportOptions, map: usize, side: u32) -> Result> { + Self::sample_coverage(input, options, map, side, texturecraft_geom::NO_TRI) + } + + fn sample_coverage( + input: &ExportInput, + options: &ExportOptions, + map: usize, + side: u32, + uncovered: Coverage, + ) -> Result> { + let set = input.project.texture_set(input.ts)?; + let spec = options.preset.maps.get(map).ok_or_else(|| FormatError::Invalid(format!("the template has no output map {map}")))?; + let planned = list_outputs(input.project, input.ts, input.mesh_name, options)?; + let Some(file) = planned.iter().find(|file| file.maps().any(|written| written == map)) else { + return Ok(None); + }; + + let (composite_width, height) = (input.composite.resolution, input.composite.height); + if composite_width == 0 || height == 0 || input.coverage.len() as u64 != u64::from(composite_width) * u64::from(height) { + return Err(FormatError::Invalid(format!("composite size {composite_width}×{height} does not match its coverage"))); + } + + // The file's longer side bounds the preview: the map's own size, else the export size, else the set's + let tile_res = (composite_width / set.tile_grid().map_or(1, |grid| grid.cols.max(1))).max(1); + let file_side = |source| super::scale_export_side(source, tile_res, options.map_size(map)); + let source_side = composite_width.max(height); + let preview_side = side.clamp(1, MAX_PREVIEW_SIDE).min(file_side(composite_width).max(file_side(height))).min(source_side); + let width = super::scale_export_side(composite_width, source_side, Some(preview_side)); + let rows = super::scale_export_side(height, source_side, Some(preview_side)); + let sampler = Sampler::new(input, options, set, tile_res, uncovered); + let mut channel_layout = layout(set, spec); + let grayscale = file.format == FileFormat::Pgm; + if grayscale || matches!(file.format, FileFormat::Jpeg | FileFormat::Hdr) { + channel_layout.retain(|(dest, _)| *dest != Dest::A); + } + + let gray_source = channel_layout.first().filter(|(dest, _)| *dest == Dest::L); + let psd = file.format == FileFormat::Psd; + let rgb_from_gray = gray_source.filter(|_| { + matches!(file.format, FileFormat::Psd | FileFormat::Hdr | FileFormat::Webp) + || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2)) + }); + let channels = if grayscale { + vec![Dest::L] + } else if psd { + vec![Dest::R, Dest::G, Dest::B, Dest::A] + } else if rgb_from_gray.is_some() { + [Dest::R, Dest::G, Dest::B].into_iter().chain(channel_layout.iter().skip(1).map(|(dest, _)| *dest)).collect() + } else { + channel_layout.iter().map(|(dest, _)| *dest).collect() + }; + + let component_count = channels.len(); + let color = spec.is_color(); + let max_sample = f32::from(u8::MAX); + let preview_sample = |value: f32, dest| { + let stored = if color && dest != Dest::A { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }; + (stored * max_sample + 0.5) as u8 + }; + + // Sample at the centre of each preview pixel + let source_texel = |pixel: u32, preview_side: u32, source_side: u32| { + ((u64::from(pixel) * 2 + 1) * u64::from(source_side) / (2 * u64::from(preview_side))).min(u64::from(source_side) - 1) as u32 + }; + + let mut pixels = vec![0u8; width as usize * rows as usize * component_count]; + pixels.par_chunks_mut(width as usize * component_count).enumerate().for_each(|(row, values)| { + let y = source_texel(row as u32, rows, height); + for (column, pixel) in values.chunks_exact_mut(component_count).enumerate() { + let x = source_texel(column as u32, width, composite_width); + let at = if sampler.covered(x, y) { At::Texel(x, y) } else { At::Default }; + let mut cache = None; + let mut sample = |&(dest, source): &(Dest, &SourceRef)| { + let sample = sampler.sample(source, at, &mut cache); + if spec.inverted.contains(&dest) { 1.0 - sample } else { sample } + }; + + if grayscale && let [luminance] = pixel { + let value = match channel_layout.as_slice() { + [red, green, blue] => rec709_luminance(sample(red), sample(green), sample(blue)), + [gray] => sample(gray), + _ => 0.0, + }; + *luminance = preview_sample(value, Dest::L); + } else if let (Some(gray), [red, green, blue, alpha @ ..]) = (rgb_from_gray, &mut *pixel) { + let value = preview_sample(sample(gray), Dest::L); + (*red, *green, *blue) = (value, value, value); + if let [alpha] = alpha { + *alpha = channel_layout.get(1).map_or(u8::MAX, |source| preview_sample(sample(source), Dest::A)); + } + } else { + for (output, channel) in pixel.iter_mut().zip(&channel_layout) { + *output = preview_sample(sample(channel), channel.0); + } + if psd && channel_layout.len() < component_count { + pixel[component_count - 1] = u8::MAX; + } + } + } + }); + + Ok(Some(MapPreview { width, height: rows, channels, pixels })) + } +} diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs new file mode 100644 index 00000000..3b493ab4 --- /dev/null +++ b/crates/formats/src/export/map_renderer.rs @@ -0,0 +1,133 @@ +use rayon::prelude::*; +use texturecraft_core::{TextureSet, TileGrid}; +use texturecraft_texel::{ColorSpace, DilationMap}; + +use super::rendered_map::RenderedMap; +use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Padding, Sampler, diffuse_blocks, layout, resize, scale_export_side, tile_side}; +use crate::{FormatError, MAX_IMAGE_SIZE, Result}; + +/// Renders the output maps of one texture set's export: the padding and sampling every map shares +pub(super) struct MapRenderer<'a> { + options: &'a ExportOptions, + set: &'a TextureSet, + sampler: Sampler<'a>, + dilation_map: Option, + grid: Option, + /// The composite's size + width: u32, + height: u32, + /// Texels per atlas block (the width for a set without UV tiles) + tile_res: u32, +} + +impl<'a> MapRenderer<'a> { + pub(super) fn new(input: &ExportInput<'a>, options: &'a ExportOptions) -> Result> { + let set = input.project.texture_set(input.ts)?; + let (width, height) = (input.composite.resolution, input.composite.height); + let grid = set.tile_grid(); + let tile_res = width / grid.map_or(1, |g| g.cols.max(1)); + if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) { + return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); + } + + if input.coverage.len() as u64 != u64::from(width) * u64::from(height) { + return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len()))); + } + + // Padding stays inside each UV tile + let dilation_map = match options.padding { + Padding::None => None, + Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => { + Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res)) + } + Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), + }; + let sampler = Sampler::new(input, options, set, tile_res, false); + Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res }) + } + + /// The export size of map `map_index`'s file of `tile` (None: the whole set) + pub(super) fn size(&self, map_index: usize, tile: Option) -> Result<(u32, u32)> { + let (_, _, w, h) = self.region(tile)?; + + // An atlas scales by the requested size per tile + let scale = |value| scale_export_side(value, self.tile_res, self.options.map_size(map_index)); + Ok((scale(w), scale(h))) + } + + /// The composite texels a file of `tile` covers: one tile, or the whole set + fn region(&self, tile: Option) -> Result<(u32, u32, u32, u32)> { + match (tile, self.grid) { + (Some(t), Some(g)) => { + let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; + + // A tile smaller than its block fills the block's top-left corner + let side = tile_side(self.set, t, self.tile_res); + Ok((bx * self.tile_res, by * self.tile_res, side, side)) + } + _ => Ok((0, 0, self.width, self.height)), + } + } + + /// Map `map_index` of the preset for `tile`, as `format` at `bit_depth` holds it + pub(super) fn render(&self, map_index: usize, tile: Option, format: FileFormat, bit_depth: u8) -> Result { + let options = self.options; + let map = options.preset.maps.get(map_index).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?; + let channel_layout = layout(self.set, map); + let component_count = channel_layout.len(); + let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); + let (x0, y0, w, h) = self.region(tile)?; + let size = self.size(map_index, tile)?; + let sampler = &self.sampler; + let dilation_map = self.dilation_map.as_ref(); + let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); + + let mut data = vec![0.0f32; w as usize * h as usize * component_count]; + data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { + let y = y0 + row_y as u32; + for (column, x) in (x0..x0 + w).enumerate() { + let at = if sampler.covered(x, y) { + Some(At::Texel(x, y)) + } else { + match dilation_map.and_then(|d| d.source(x, y)) { + Some((sx, sy)) => Some(At::Texel(sx, sy)), + None => beyond_default.then_some(At::Default), + } + }; + let Some(at) = at else { continue }; + let mut cache = None; + for (component, (_, source)) in channel_layout.iter().enumerate() { + if let Some(value) = row.get_mut(column * component_count + component) { + let sample = sampler.sample(source, at, &mut cache); + *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample }; + } + } + } + }); + + // Diffuse into the texels the dilation did not reach + if let (Padding::DilationDiffusion(_), Some(dilation)) = (options.padding, dilation_map) { + let block = if tile.is_none() && self.grid.is_some() { self.tile_res } else { w.max(h) }; + diffuse_blocks(&mut data, (w as usize, h as usize), component_count, dilation, (x0 as usize, y0 as usize), block as usize); + } + + let mut data = resize(data, (w, h), component_count, size); + + // Integer sRGB converts in `encode`; other color spaces convert here + let space = options.space_for_map(map, format, bit_depth); + let float = format.holds_float(bit_depth); + let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709; + if convert { + data.par_chunks_mut(component_count).for_each(|px| { + if let [r, g, b, ..] = px { + [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); + } + }); + } + let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); + + // A colour space the user chose is written into the colour maps (data maps have none) + let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space); + Ok(RenderedMap { data, size, component_count, srgb, embed }) + } +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 02420203..8ca37c57 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -21,21 +21,35 @@ use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; use texturecraft_geom::glam::Vec3; -use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; +use texturecraft_texel::{ColorSpace, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; mod encoding; +mod layered_psd; mod map_override; +mod map_preview; +mod map_renderer; +mod planned_layer; +mod psd_budget; +mod rendered_map; use encoding::Encoding; pub use map_override::MapOverride; +pub use map_preview::{MAX_PREVIEW_SIDE, MapPreview}; +use map_renderer::MapRenderer; +pub use planned_layer::PlannedLayer; +use psd_budget::PsdBudget; /// Height-to-normal slope: with strength 1, a height change of 1 across 1/16 of the texture /// width tilts the normal 45°, at any resolution. const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; +/// Glossiness a set lacks: the KHR_materials_pbrSpecularGlossiness glossinessFactor default +const MISSING_GLOSSINESS: SourceRef = SourceRef::Constant(1.0); const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// Planes of a PSD image or layer: red, green, blue and alpha +const PSD_RGBA_PLANES: usize = 4; /// Preset limits (user presets are untrusted JSON). const MAX_MAPS: usize = 64; const MAX_TEMPLATE: usize = 256; @@ -91,11 +105,16 @@ pub enum FileFormat { Jng, /// Portable graymap (binary). Pgm, - /// A PSD containing only its merged image. + /// Photoshop document: every output map of a texture set in this format as a layer of one file Psd, } impl FileFormat { + /// Whether the texture can be referenced by the USD asset exporter. + pub fn usable_by_usd_asset(self) -> bool { + self != Self::Psd + } + pub const ALL: [FileFormat; 11] = [ FileFormat::Png, FileFormat::Jpeg, @@ -315,6 +334,11 @@ pub struct MapSpec { } impl MapSpec { + /// Whether this set supplies at least one source used by the output map. + pub fn is_available_for(&self, set: &TextureSet) -> bool { + self.channels.iter().any(|(_, source)| source_present(set, source)) + } + /// Whether a non-alpha destination draws from a color source. pub fn is_color(&self) -> bool { self.channels.iter().any(|(dest, source)| { @@ -424,6 +448,20 @@ pub struct ExportOptions { } impl ExportOptions { + /// The output size of the preset's map `map`: its own, else the export's (None: the texture set's) + pub fn map_size(&self, map: usize) -> Option { + self.maps.get(&map).and_then(|own| own.size).or(self.size) + } + + /// The format, depth and dithering of a map before any PSD document-wide promotion. + pub fn map_file_type(&self, map_index: usize, map: &MapSpec) -> (FileFormat, u8, bool) { + let own = self.maps.get(&map_index); + let format = own.and_then(|o| o.format).or(self.format_override).unwrap_or(map.format); + let depth = format.depth(own.and_then(|o| o.bit_depth).or(self.bit_depth_override).unwrap_or(map.bit_depth)); + let dither = depth == 8 && !format.holds_float(depth) && own.and_then(|o| o.dither).unwrap_or(self.dither); + (format, depth, dither) + } + /// The colour space colour maps use at this format's default depth. pub fn space_for(&self, format: FileFormat) -> ColorSpace { self.space_for_depth(format, format.default_depth()) @@ -472,14 +510,14 @@ impl ExportOptions { } /// What is exported: one texture set's composite with its baked maps and UV coverage (one flag -/// per composite texel, row-major). +/// per composite texel, row-major). A preview can also borrow the UV rasterizer's triangle indices. #[derive(Clone, Copy)] -pub struct ExportInput<'a> { +pub struct ExportInput<'a, Coverage = bool> { pub project: &'a Project, pub ts: usize, pub composite: &'a Composite, pub baked: &'a BakedMaps, - pub coverage: &'a [bool], + pub coverage: &'a [Coverage], pub mesh_name: &'a str, } @@ -508,6 +546,16 @@ pub struct PlannedFile { /// covers every tile refers to); None when the file isn't tiled. pub udim_name: Option, pub warnings: Vec, + /// A PSD's output maps, top layer first (`map` is the first); empty for a file of one map + pub layers: Vec, +} + +impl PlannedFile { + /// The output maps the file writes + pub fn maps(&self) -> impl Iterator + '_ { + let own = self.layers.is_empty().then_some(self.map); + own.into_iter().chain(self.layers.iter().map(|layer| layer.map)) + } } // --------------------------------------------------------------------------------------------- @@ -538,7 +586,12 @@ pub(crate) fn source_present(set: &TextureSet, s: &SourceRef) -> bool { /// does not have is dropped. fn layout<'m>(set: &TextureSet, map: &'m MapSpec) -> Vec<(Dest, &'m SourceRef)> { let get = |d: Dest| map.channels.iter().find(|(x, _)| *x == d).map(|(_, s)| s); - let alpha = get(Dest::A).filter(|s| !matches!(s, SourceRef::Channel { channel, .. } if !set.has_channel(*channel))); + + // A glossiness alpha stays, fully glossy, so a specular/glossiness file is RGBA without the channel too + let alpha = match get(Dest::A) { + Some(SourceRef::Channel { channel: Channel::Glossiness, .. }) if !set.has_channel(Channel::Glossiness) => Some(&MISSING_GLOSSINESS), + alpha => alpha.filter(|s| !matches!(s, SourceRef::Channel { channel, .. } if !set.has_channel(*channel))), + }; let black = &SourceRef::Constant(0.0); let mut out = match get(Dest::L) { Some(l) => vec![(Dest::L, l)], @@ -565,7 +618,11 @@ pub fn channel_label(map: &MapSpec) -> &'static str { /// Keep `[A-Za-z0-9_.-]`, replace everything else with `_`; never empty or a reserved device name. pub fn sanitize_file_stem(s: &str) -> String { - let mut out: String = s.chars().take(MAX_STEM).map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).collect(); + sanitize_stem_with_limit(s, MAX_STEM) +} + +fn sanitize_stem_with_limit(s: &str, limit: usize) -> String { + let mut out: String = s.chars().take(limit).map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).collect(); if out.trim_matches('.').is_empty() { out = "texture".into(); } @@ -575,43 +632,129 @@ pub fn sanitize_file_stem(s: &str) -> String { if reserved { out.insert(0, '_'); } + + out.truncate(limit); out } +/// Leave room for the set's name, a set index if shortened, and the eventual tile suffix. +fn psd_stem(mesh_name: &str, set_name: &str, set_index: usize, max_len: usize) -> String { + let full = sanitize_stem_with_limit(&format!("{mesh_name}_{set_name}"), max_len + 1); + if full.len() <= max_len { + return full; + } + + let set_index = set_index.to_string(); + let set_budget = max_len / 2 - set_index.len() - 2; + let set = sanitize_stem_with_limit(set_name, set_budget); + let mesh = sanitize_stem_with_limit(mesh_name, max_len - set.len() - set_index.len() - 2); + format!("{mesh}_{set}_{set_index}") +} + +/// Compare against the whole project so a separate export and a batch agree on names. +fn untiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, atlas: bool) -> String { + let stem = psd_stem(mesh_name, &set.name, set_index, MAX_STEM); + let taken = |candidate: &str| { + let tile = psd_tile_suffix(candidate); + project.texture_sets.iter().enumerate().filter(|(index, _)| *index != set_index).any(|(index, other)| { + if atlas || other.uv_tiles.is_empty() { + candidate.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM)) + } else { + tile.is_some_and(|(base, number)| { + other.uv_tiles.contains(&number) + && base.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM - (candidate.len() - base.len()))) + }) + } + }) + }; + if taken(&stem) { disambiguated_psd_stem(&stem, set_index, MAX_STEM, taken) } else { stem } +} + +/// Only a canonical tile number can collide with a generated UDIM suffix. +fn psd_tile_suffix(stem: &str) -> Option<(&str, u32)> { + let (base, suffix) = stem.rsplit_once('.')?; + let number: u32 = suffix.parse().ok()?; + (number.to_string() == suffix).then_some((base, number)) +} + +/// Keep one UDIM base for all tiles of a set when any tile's ordinary name collides. +fn tiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, limit: usize) -> String { + let stem = psd_stem(mesh_name, &set.name, set_index, limit); + let other_sets = || project.texture_sets.iter().enumerate().filter(|(index, _)| *index != set_index); + let collides = other_sets().any(|(index, other)| { + !other.uv_tiles.is_empty() + && stem.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, limit)) + && other.uv_tiles.iter().any(|tile| set.uv_tiles.contains(tile)) + }); + if !collides { + return stem; + } + + // Reserve ordinary names so a generated suffix cannot take another document's name + disambiguated_psd_stem(&stem, set_index, limit, |candidate| { + other_sets().any(|(index, other)| { + if other.uv_tiles.is_empty() { + let untiled = psd_stem(mesh_name, &other.name, index, MAX_STEM); + psd_tile_suffix(&untiled).is_some_and(|(base, tile)| candidate.eq_ignore_ascii_case(base) && set.uv_tiles.contains(&tile)) + } else { + candidate.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, limit)) + } + }) + }) +} + +fn disambiguated_psd_stem(stem: &str, set_index: usize, limit: usize, taken: impl Fn(&str) -> bool) -> String { + let mut attempt = 0usize; + loop { + let suffix = if attempt == 0 { format!("_{set_index}") } else { format!("-{attempt}_{set_index}") }; + let name = format!("{}{suffix}", &stem[..stem.len().min(limit - suffix.len())]); + if !taken(&name) { + return name; + } + + attempt += 1; + } +} + /// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem. pub fn sanitize_file_path(s: &str) -> String { s.split('/').map(sanitize_file_stem).collect::>().join("/") } -/// The files `opts` produces for texture set `ts`, without rendering (for the export dialog). -/// Template variables: [`FILE_TOKENS`]. +/// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { + plan_outputs(project, ts, mesh_name, opts, PsdBudget::TARGET) +} + +/// [`list_outputs`] with the PSD memory limits of `budget` +fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions, budget: PsdBudget) -> Result> { opts.preset.validate()?; let set = project.texture_set(ts)?; - if let Some(s) = opts.size - && (!s.is_power_of_two() || s > MAX_IMAGE_SIZE) - { - return Err(FormatError::Invalid(format!("export size {s} must be a power of two up to {MAX_IMAGE_SIZE}"))); + for requested_size in opts.size.iter().chain(opts.maps.values().filter_map(|own| own.size.as_ref())) { + if !requested_size.is_power_of_two() || *requested_size > MAX_IMAGE_SIZE { + return Err(FormatError::Invalid(format!("export size {requested_size} must be a power of two up to {MAX_IMAGE_SIZE}"))); + } } let mut used = BTreeSet::new(); let mut active_files = BTreeSet::new(); let mut active_dirs = BTreeSet::new(); let mut out = Vec::new(); + + // Bucket layers in tile order to move their names into the corresponding PSD + let mut psd_layers = Vec::new(); + let project_stem = project.name.replace('/', "_"); + let mesh_stem = mesh_name.replace('/', "_"); + let set_stem = set.name.replace('/', "_"); let tiles: Vec> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() }; - let grid = set.tile_grid(); - let block_resolution = set.block_resolution(); - for (i, map) in opts.preset.maps.iter().enumerate() { - if !map.channels.iter().any(|(_, s)| source_present(set, s)) { + for (map_index, map) in opts.preset.maps.iter().enumerate() { + if !map.is_available_for(set) { continue; } - let own = opts.maps.get(&i); - let format = own.and_then(|o| o.format).or(opts.format_override).unwrap_or(map.format); - let bit_depth = format.depth(own.and_then(|o| o.bit_depth).or(opts.bit_depth_override).unwrap_or(map.bit_depth)); + let own = opts.maps.get(&map_index); + let (format, bit_depth, dither) = opts.map_file_type(map_index, map); let enabled = own.is_none_or(|o| o.enabled); - let psd_channels = (enabled && format == FileFormat::Psd).then(|| layout(set, map).len()); - let dither = bit_depth == 8 && !format.holds_float(bit_depth) && own.and_then(|o| o.dither).unwrap_or(opts.dither); let space = opts.space_for_map(map, format, bit_depth); let requested_space = opts.space_for_depth(format, bit_depth); let color_map = map.is_color(); @@ -624,52 +767,29 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export // Integer files clamp wide-gamut linear color to 0–1 let clamps = color_map && !format.holds_float(bit_depth) && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065); - // Append `$udim` to names for separate UV tiles - let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; - for &tile in &tiles { - if let Some(channels) = psd_channels { - let size = match (tile, grid) { - (Some(tile), Some(_)) => { - let side = tile_side(set, tile, block_resolution); - let side = scale_export_side(side, block_resolution, opts.size); - (side, side) - } - (_, Some(grid)) => { - let side = opts.size.unwrap_or(block_resolution); - (side.saturating_mul(grid.cols), side.saturating_mul(grid.rows)) - } - (_, None) => { - let side = opts.size.unwrap_or(block_resolution); - (side, side) - } - }; - check_psd_size(size, channels, bit_depth)?; - } - - // A name of the project, mesh or texture set never adds a folder - let no_folder = |name: &str| name.replace('/', "_"); - let stem = template - .replace("$udim", &tile.unwrap_or(1001).to_string()) - .replace("$project", &no_folder(&project.name)) - .replace("$mesh", &no_folder(mesh_name)) - .replace("$textureSet", &no_folder(&set.name)) + // A PSD layer needs only explicit tile tokens because its document name already holds the tile number + let template = if format != FileFormat::Psd && tiles[0].is_some() && !map.file.contains("$udim") { + std::borrow::Cow::Owned(format!("{}.$udim", map.file)) + } else { + std::borrow::Cow::Borrowed(map.file.as_str()) + }; + let expand_stem = |udim: &str| { + let expanded = template + .replace("$udim", udim) + .replace("$project", &project_stem) + .replace("$mesh", &mesh_stem) + .replace("$textureSet", &set_stem) .replace("$channel", channel_label(map)) .replace("$colorSpace", color_space); + sanitize_file_path(&expanded) + }; - // Replace the tile number with `` in the shared name - let token_stem = tile.map(|_| { - let t = template - .replace("$udim", "UDIMTOKEN") - .replace("$project", &no_folder(&project.name)) - .replace("$mesh", &no_folder(mesh_name)) - .replace("$textureSet", &no_folder(&set.name)) - .replace("$channel", channel_label(map)) - .replace("$colorSpace", color_space); - sanitize_file_path(&t) - }); - let stem = sanitize_file_path(&stem); + // A tiled raster's name with a placeholder for its tile, the same for every tile + let udim_template = (format != FileFormat::Psd && tiles[0].is_some()).then(|| expand_stem("UDIMTOKEN")); + for (tile_index, &tile) in tiles.iter().enumerate() { + let tile_number = tile.unwrap_or(1001).to_string(); + let stem = expand_stem(&tile_number); let ext = format.extension(); - let mut name = format!("{stem}.{ext}"); let mut warnings = Vec::new(); if color_map && format == FileFormat::Pgm @@ -689,59 +809,200 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export format.extension().to_uppercase() )); } + let packs_colour = |name: &str| { + (color_map && requested_space != space) + .then(|| format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())) + }; - // Compare names case-insensitively for Windows and macOS - let mut k = 2; - while used.contains(&name.to_ascii_lowercase()) { - name = format!("{stem}_{k}.{ext}"); - k += 1; + if format == FileFormat::Psd { + if enabled { + warnings.extend(packs_colour(&stem)); + if psd_layers.is_empty() { + psd_layers.resize_with(tiles.len(), Vec::new); + } + psd_layers[tile_index].push((PlannedLayer { map: map_index, name: stem, dither }, bit_depth, warnings)); + } + continue; } - if k > 2 { - warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); - } - let lower = name.to_ascii_lowercase(); - used.insert(lower.clone()); + + let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); if !enabled { continue; } - if active_dirs.contains(&lower) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); - } - let mut prefix = lower.as_str(); - while let Some((folder, _)) = prefix.rsplit_once('/') { - if active_files.contains(folder) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); - } - active_dirs.insert(folder.to_owned()); - prefix = folder; - } - active_files.insert(lower); - - if color_map && requested_space != space { - warnings.push(format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())); - } + claim_path(&mut active_files, &mut active_dirs, &name)?; + warnings.extend(packs_colour(&name)); // Use a UDIM name only when substituting its tile recovers the output name // Truncation or literal placeholder text can make that substitution ambiguous - let udim_name = token_stem.filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)).map(|t| { - let renamed = if k > 2 { format!("_{}", k - 1) } else { String::new() }; - format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "") - }); - out.push(PlannedFile { name, map: i, format, bit_depth, dither, tile, udim_name, warnings }); + let udim_name = udim_template + .as_deref() + .filter(|t| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &tile_number) == stem) + .map(|t| format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "")); + out.push(PlannedFile { name, map: map_index, format, bit_depth, dither, tile, udim_name, warnings, layers: Vec::new() }); } } + + // Reuse the base across tiles with the same suffix width + let mut tiled_bases = HashMap::new(); + + // Each tile's PSD maps are the layers of one file named after the texture set + let mut psd_failures = Vec::new(); + for (&tile, in_tile) in tiles.iter().zip(psd_layers) { + let Some((first_layer, ..)) = in_tile.first() else { continue }; + + let first_map = first_layer.map; + let bit_depth = in_tile.iter().map(|(_, depth, _)| *depth).max().unwrap_or(8); + let mut warnings = Vec::new(); + let mut layers = Vec::with_capacity(in_tile.len()); + let mut dither_requested = false; + for (mut layer, _, layer_warnings) in in_tile { + dither_requested |= layer.dither; + layer.dither &= bit_depth == 8; + layers.push(layer); + for warning in layer_warnings { + if !warnings.contains(&warning) { + warnings.push(warning); + } + } + } + if bit_depth == 16 && dither_requested { + warnings.push("PSD layers use the 16-bit document depth; 8-bit dithering was skipped".into()); + } + + let ext = FileFormat::Psd.extension(); + let (stem, udim_stem) = if let Some(number) = tile { + let suffix = format!(".{number}"); + let limit = MAX_STEM - suffix.len(); + let base = tiled_bases.entry(limit).or_insert_with(|| tiled_psd_stem(project, mesh_name, ts, set, limit)); + (format!("{base}{suffix}"), Some(format!("{base}."))) + } else { + (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) + }; + let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); + if let Err(error) = layered_psd::preflight(set, opts, tile, bit_depth, layers.iter(), budget.working_bytes) { + psd_failures.push((name, error)); + continue; + } + + claim_path(&mut active_files, &mut active_dirs, &name)?; + let udim_name = udim_stem.map(|stem| format!("{stem}{renamed}.{ext}")); + let dither = bit_depth == 8 && dither_requested; + out.push(PlannedFile { name, map: first_map, format: FileFormat::Psd, bit_depth, dither, tile, udim_name, warnings, layers }); + } + + // A PSD that cannot be written leaves the set's other files to export, its reason a warning on the first of them + for (name, error) in psd_failures { + let Some(first) = out.first_mut() else { return Err(error) }; + let reason = match error { + FormatError::Invalid(reason) | FormatError::TooLarge(reason) => reason, + other => other.to_string(), + }; + first.warnings.push(format!("\"{name}\" {PSD_NOT_WRITTEN}{reason}")); + } Ok(out) } -/// Plan a selection in export order, keeping only the first case-insensitive use of a name. -pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { - let mut files = Vec::new(); - for &set in sets { - files.extend(list_outputs(project, set, mesh_name, opts)?.into_iter().map(|file| (set, file))); +/// What a set's PSD planning failure says after the file name +const PSD_NOT_WRITTEN: &str = "was not written: "; + +/// Whether `warning` is about a PSD of the set that was not planned rather than the file carrying it, so it outlives that file +pub fn is_set_warning(warning: &str) -> bool { + warning.split_once(".psd\" ").is_some_and(|(name, rest)| name.starts_with('"') && rest.starts_with(PSD_NOT_WRITTEN)) +} + +/// `stem.ext`, or `stem_2.ext`… when an earlier file has the name ignoring case (as Windows and macOS file systems do): the name and the suffix added +fn unique_name(used: &mut BTreeSet, stem: &str, ext: &str, warnings: &mut Vec) -> (String, String) { + let mut name = format!("{stem}.{ext}"); + let mut renamed = String::new(); + let mut k = 2; + while used.contains(&name.to_ascii_lowercase()) { + renamed = format!("_{k}"); + name = format!("{stem}{renamed}.{ext}"); + k += 1; + } + if !renamed.is_empty() { + warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); } - Ok(keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings)) + used.insert(name.to_ascii_lowercase()); + (name, renamed) +} + +/// Record exported file `name` and its folders, refusing a name that is already a folder or a folder that is already a file, ignoring case +fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: &str) -> Result<()> { + let lower = name.to_ascii_lowercase(); + if dirs.contains(&lower) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); + } + + let mut prefix = lower.as_str(); + while let Some((folder, _)) = prefix.rsplit_once('/') { + if files.contains(folder) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another output exports that file"))); + } + + dirs.insert(folder.to_owned()); + prefix = folder; + } + files.insert(lower); + Ok(()) +} + +/// Reject file and folder conflicts across a selection's retained output paths, ignoring case. +pub fn validate_export_paths<'a>(names: impl IntoIterator) -> Result<()> { + let mut files = BTreeSet::new(); + let mut folders = BTreeSet::new(); + for name in names { + claim_path(&mut files, &mut folders, name)?; + } + + Ok(()) +} + +/// The size of a PSD layer of a texture set at `export_size` for `tile` (None: the whole set, an atlas of a UV-tiled one) +fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u32, u32) { + let block_resolution = set.block_resolution(); + match (tile, set.tile_grid()) { + (Some(tile), Some(_)) => { + let side = scale_export_side(tile_side(set, tile, block_resolution), block_resolution, export_size); + (side, side) + } + (_, Some(grid)) => { + let side = export_size.unwrap_or(block_resolution); + (side.saturating_mul(grid.cols), side.saturating_mul(grid.rows)) + } + (_, None) => { + let side = export_size.unwrap_or(block_resolution); + (side, side) + } + } +} + +/// Plan a selection in export order, keeping only the first case-insensitive use of a name. +pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { + plan_set_outputs(project, sets, mesh_name, opts, PsdBudget::TARGET) +} + +/// [`list_set_outputs`] with the PSD memory limits of `budget` +fn plan_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions, budget: PsdBudget) -> Result> { + let mut files = Vec::new(); + for &index in sets { + let planned = plan_outputs(project, index, mesh_name, opts, budget)?; + files.extend(planned.into_iter().map(|file| (index, file))); + } + + let files = keep_first_planned_names(files); + if sets.len() > 1 { + validate_export_paths(files.iter().map(|(_, file)| file.name.as_str()))?; + } + + let mut psd_bytes = 0; + for (index, file) in files.iter().filter(|(_, file)| file.format == FileFormat::Psd) { + check_psd_batch_within(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes, budget)?; + } + + Ok(files) } // --------------------------------------------------------------------------------------------- @@ -755,11 +1016,12 @@ enum At { Default, } -struct Sampler<'a> { +struct Sampler<'a, Coverage = bool> { set: &'a TextureSet, comp: &'a Composite, baked: &'a BakedMaps, - coverage: &'a [bool], + coverage: &'a [Coverage], + uncovered: Coverage, /// Composite width. res: u32, /// Texels per atlas block (`res` for a classic set): the height slope and the Sobel window @@ -784,7 +1046,26 @@ pub fn rnm(base: Vec3, detail: Vec3) -> Vec3 { (t * t.dot(u) / t.z.max(1e-4) - u).try_normalize().unwrap_or(base) } -impl Sampler<'_> { +impl<'a, Coverage> Sampler<'a, Coverage> { + /// The sampler of `input`'s texture set `set`, whose atlas blocks are `tile_res` texels wide + fn new(input: &ExportInput<'a, Coverage>, options: &ExportOptions, set: &'a TextureSet, tile_res: u32, uncovered: Coverage) -> Self { + Sampler { + set, + comp: input.composite, + baked: input.baked, + coverage: input.coverage, + uncovered, + res: input.composite.resolution, + tile_res, + scales: set.block_scales(), + normal_override: options.normal_format, + project_normal: input.project.normal_format, + dielectric_f0_scale: input.project.display.dielectric_f0_scale(), + } + } +} + +impl Sampler<'_, Coverage> { fn channel(&self, c: Channel, at: At) -> [f32; 3] { match at { At::Texel(x, y) if self.set.has_channel(c) => self.comp.value(c, x, y), @@ -802,7 +1083,7 @@ impl Sampler<'_> { } fn covered(&self, x: u32, y: u32) -> bool { - self.coverage.get((y as usize) * self.res as usize + x as usize).copied().unwrap_or(false) + self.coverage.get((y as usize) * self.res as usize + x as usize).is_some_and(|sample| sample != &self.uncovered) } /// Normal from the height channel (3×3 Sobel; uncovered neighbours repeat the centre). @@ -896,140 +1177,81 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result Result<()> { + check_psd_batch_within(set, options, planned, total_bytes, PsdBudget::TARGET) +} + +fn check_psd_batch_within(set: &TextureSet, options: &ExportOptions, planned: &[PlannedFile], total_bytes: &mut u64, budget: PsdBudget) -> Result<()> { + let mut estimate = *total_bytes; + for file in planned.iter().filter(|file| file.format == FileFormat::Psd) { + let (_, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter(), budget.working_bytes)?; + add_psd_batch_bytes(&mut estimate, file_bytes, budget.batch_bytes)?; + } + + *total_bytes = estimate; + Ok(()) +} + +fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64, limit: Option) -> Result<()> { + let estimate = total_bytes.saturating_add(file_bytes); + if limit.is_some_and(|limit| estimate > limit) { + return Err(FormatError::TooLarge("total PSD output would exceed 1 GiB; use a smaller export size, fewer PSD maps or separate exports".into())); + } + + *total_bytes = estimate; + Ok(()) +} + /// 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(); - let tile_res = width / grid.map_or(1, |g| g.cols.max(1)); - if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) { - return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); - } - - if input.coverage.len() != width as usize * height as usize { - return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len()))); - } + render_planned_maps_within(input, options, planned, PsdBudget::TARGET) +} +/// [`render_planned_maps`] with the PSD memory limits of `budget` +fn render_planned_maps_within(input: &ExportInput, options: &ExportOptions, planned: Vec, budget: PsdBudget) -> Result> { if planned.is_empty() { return Ok(Vec::new()); } - // Padding stays inside each UV tile - let dilation_map = match options.padding { - Padding::None => None, - Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => { - Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res)) + let mut psd_sizes = Vec::new(); + if planned.iter().any(|file| file.format == FileFormat::Psd) { + let set = input.project.texture_set(input.ts)?; + let expected = set.size(); + let actual = (input.composite.resolution, input.composite.height); + if actual != expected { + return Err(FormatError::Invalid(format!( + "PSD composite size {}×{} does not match the planned texture set size {}×{}", + actual.0, actual.1, expected.0, expected.1 + ))); } - Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), - }; - let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); - let diffuse = matches!(options.padding, Padding::DilationDiffusion(_)); - let sampler = Sampler { - set, - comp: input.composite, - baked: input.baked, - coverage: input.coverage, - res: width, - tile_res, - scales: set.block_scales(), - normal_override: options.normal_format, - project_normal: input.project.normal_format, - dielectric_f0_scale: input.project.display.dielectric_f0_scale(), - }; + let mut psd_bytes = 0; + for file in &planned { + if file.format == FileFormat::Psd { + let (size, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter(), budget.working_bytes)?; + add_psd_batch_bytes(&mut psd_bytes, file_bytes, budget.batch_bytes)?; + psd_sizes.push(Some(size)); + } else { + psd_sizes.push(None); + } + } + } + + let renderer = MapRenderer::new(input, options)?; planned .into_iter() - .map(|planned_file| { - let map = options.preset.maps.get(planned_file.map).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?; - let channel_layout = layout(set, map); - let component_count = channel_layout.len(); - let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); - - // The texels written: one tile, or the whole set - let (x0, y0, w, h) = match (planned_file.tile, grid) { - (Some(t), Some(g)) => { - let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; - - // A tile smaller than its block fills the block's top-left corner - let side = tile_side(set, t, tile_res); - (bx * tile_res, by * tile_res, side, side) - } - _ => (0, 0, width, height), - }; - - // An atlas scales by the requested size per tile - let scale = |value| scale_export_side(value, tile_res, options.size); - let size = (scale(w), scale(h)); - if planned_file.format == FileFormat::Psd { - check_psd_size(size, component_count, planned_file.bit_depth)?; + .zip(psd_sizes.into_iter().chain(std::iter::repeat(None))) + .map(|(planned_file, psd_size)| { + if let Some(size) = psd_size { + return layered_psd::render_psd(&renderer, planned_file, size); } - let mut data = vec![0.0f32; w as usize * h as usize * component_count]; - data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { - let y = y0 + row_y as u32; - for (column, x) in (x0..x0 + w).enumerate() { - let at = if sampler.covered(x, y) { - Some(At::Texel(x, y)) - } else { - match dilation_map.as_ref().and_then(|d| d.source(x, y)) { - Some((sx, sy)) => Some(At::Texel(sx, sy)), - None => beyond_default.then_some(At::Default), - } - }; - let Some(at) = at else { continue }; - let mut cache = None; - for (component, (_, source)) in channel_layout.iter().enumerate() { - if let Some(value) = row.get_mut(column * component_count + component) { - let sample = sampler.sample(source, at, &mut cache); - *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample }; - } - } - } - }); - - // Diffuse into the texels the dilation did not reach - if diffuse { - let known: Vec = (y0..y0 + h) - .flat_map(|y| (x0..x0 + w).map(move |x| (x, y))) - .map(|(x, y)| sampler.covered(x, y) || dilation_map.as_ref().is_some_and(|d| d.source(x, y).is_some())) - .collect(); - - // Keep diffusion within each UV tile when rendering an atlas - let block = if planned_file.tile.is_none() && grid.is_some() { tile_res } else { w.max(h) }; - diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, block as usize); - } - - let mut data = resize(data, (w, h), component_count, size); - - // Integer sRGB converts in `encode`; other color spaces convert here - let space = options.space_for_map(map, planned_file.format, planned_file.bit_depth); - let float = planned_file.format.holds_float(planned_file.bit_depth); - let rgb = component_count >= 3; + let map = renderer.render(planned_file.map, planned_file.tile, planned_file.format, planned_file.bit_depth)?; let mut warnings = planned_file.warnings; - let color_map = map.is_color(); - let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709; - - if convert { - data.par_chunks_mut(component_count).for_each(|px| { - if let [r, g, b, ..] = px { - [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); - } - }); - } - let srgb: Vec = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); - - // A colour space the user chose is written into the colour maps (data maps have none) - let embed = (options.color_space.is_some() && color_map && rgb).then_some(space); - let bytes = encode( - Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither }, - size, - component_count, - data, - &srgb, - embed, - &mut warnings, - )?; - Ok(ExportedFile { name: planned_file.name, bytes, width: size.0, height: size.1, warnings }) + let encoding = Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither }; + let bytes = encode(encoding, map.size, map.component_count, map.data, &map.srgb, map.embed, &mut warnings)?; + Ok(ExportedFile { name: planned_file.name, bytes, width: map.size.0, height: map.size.1, warnings }) }) .collect() } @@ -1045,21 +1267,40 @@ pub fn scale_export_side(source_side: u32, block_resolution: u32, export_size: O u32::try_from(scaled).unwrap_or(u32::MAX).max(u32::from(source_side > 0)) } -fn diffuse_blocks(data: &mut Vec, (width, height): (usize, usize), channels: usize, known: &[bool], block: usize) { - // A whole image or a separately exported tile already occupies a contiguous buffer - if block >= width.max(height) { - diffuse_fill(data, (width, height), channels, known); - return; - } +fn diffuse_blocks( + data: &mut Vec, + (width, height): (usize, usize), + channels: usize, + dilation: &texturecraft_texel::DilationMap, + (origin_x, origin_y): (usize, usize), + block: usize, +) { + use texturecraft_texel::dilate::NONE; - for block_y in (0..height).step_by(block.max(1)) { - for block_x in (0..width).step_by(block.max(1)) { + for block_y in (0..height).step_by(block) { + for block_x in (0..width).step_by(block) { let (block_width, block_height) = (block.min(width - block_x), block.min(height - block_y)); + let source_rows = (origin_y + block_y..origin_y + block_y + block_height).map(|y| { + let start = y * dilation.width as usize + origin_x + block_x; + &dilation.src[start..start + block_width] + }); + let mut coverage = source_rows.flatten().map(|source| *source != NONE); + let Some(first) = coverage.next() else { continue }; + if coverage.clone().all(|covered| covered == first) { + continue; + } + + // The dilation map already identifies every known texel, including original UV coverage + let weights = std::iter::once(first).chain(coverage).map(f32::from).collect(); + if block_width == width && block_height == height { + diffuse_fill(data, (width, height), channels, weights); + return; + } + let rows = || (block_y..block_y + block_height).map(|y| (y * width + block_x)..(y * width + block_x + block_width)); let mut block_data: Vec = rows().flat_map(|row| data.get(row.start * channels..row.end * channels).unwrap_or_default().iter().copied()).collect(); - let block_known: Vec = rows().flat_map(|row| known.get(row).unwrap_or_default().iter().copied()).collect(); - diffuse_fill(&mut block_data, (block_width, block_height), channels, &block_known); + diffuse_fill(&mut block_data, (block_width, block_height), channels, weights); for (row, chunk) in rows().zip(block_data.chunks(block_width * channels)) { if let Some(destination) = data.get_mut(row.start * channels..row.end * channels) { destination.copy_from_slice(chunk); @@ -1069,17 +1310,12 @@ fn diffuse_blocks(data: &mut Vec, (width, height): (usize, usize), channels } } -/// Fill the texels `known` leaves out of a `size` image of `n` components by pull-push +/// Fill the zero-weight texels of a `size` image of `n` components by pull-push /// diffusion: known texels are averaged down a pyramid, then every level fills its gaps from the /// smoothly upsampled level below, so a gap takes a soft blend of the nearby known colours. -fn diffuse_fill(data: &mut Vec, (w, h): (usize, usize), channels: usize, known: &[bool]) { - if known.iter().all(|channel| *channel) || !known.iter().any(|channel| *channel) { - return; - } - +fn diffuse_fill(data: &mut Vec, (w, h): (usize, usize), channels: usize, weights: Vec) { // Keep coverage weights alongside the colour samples at each level - let mut levels: Vec<(usize, usize, Vec, Vec)> = - vec![(w, h, std::mem::take(data), known.iter().map(|channel| if *channel { 1.0 } else { 0.0 }).collect())]; + let mut levels = vec![(w, h, std::mem::take(data), weights)]; let mut accumulator = vec![0.0f32; channels]; while let Some((width, height, colour, weight)) = levels.last() && (*width > 1 || *height > 1) @@ -1203,6 +1439,13 @@ const BAYER8: [u8; 64] = [ 19, 59, 27, 49, 17, 57, 25, 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21, ]; +fn rec709_luminance(red: f32, green: f32, blue: f32) -> f32 { + // Rec.709 luminance weights apply before the display transfer + const WEIGHTS: [f32; 3] = [0.2126, 0.7152, 0.0722]; + let [red_weight, green_weight, blue_weight] = WEIGHTS; + red_weight * red + green_weight * green + blue_weight * blue +} + /// Encode a linear image as L, LA, RGB or RGBA at the requested width and height. fn encode( encoding: Encoding, @@ -1218,7 +1461,7 @@ fn encode( // Embed ICC or EXR chromaticities only where the format supports them if let Some(space) = embed - && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd) + && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng) { warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name())); } @@ -1258,8 +1501,6 @@ fn encode( _ => {} } - // Rec.709 luminance weights convert linear RGB to PGM's single gray channel - const REC709_LUMINANCE_WEIGHTS: [f32; 3] = [0.2126, 0.7152, 0.0722]; let gray_srgb: [bool; 1]; let (integer_data, srgb, component_count): (Vec, &[bool], usize) = if format == FileFormat::Pgm && component_count > 1 { if component_count != 3 { @@ -1273,10 +1514,7 @@ fn encode( .chunks_exact(component_count) .map(|pixel| match pixel { [l, _] => *l, - [red, green, blue, ..] => { - let [red_weight, green_weight, blue_weight] = REC709_LUMINANCE_WEIGHTS; - red_weight * red + green_weight * green + blue_weight * blue - } + [red, green, blue, ..] => rec709_luminance(*red, *green, *blue), _ => 0.0, }) .collect(); @@ -1297,21 +1535,22 @@ fn encode( }; let transferred = integer_data - .iter() + .into_iter() .enumerate() - .map(|(index, value)| if srgb.get(index % component_count).copied().unwrap_or(false) { linear_to_srgb(*value) } else { value.clamp(0.0, 1.0) }); + .map(|(index, value)| if srgb.get(index % component_count).copied().unwrap_or(false) { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }); let (bytes, component_count) = if let Some(indices) = channel_indices { - // Transfer luminance once before TIFF repeats it across RGB + // Transfer each source sample once, then quantize directly in destination order let transferred: Vec = transferred.collect(); - drop(integer_data); - let remapped = remap(&transferred, component_count, indices); - drop(transferred); - (quantize_integer(encoding, size.0, indices.len(), remapped.into_iter())?, indices.len()) + let output_channels = indices.len(); + let sample_count = + (transferred.len() / component_count).checked_mul(output_channels).ok_or_else(|| encoding_error(&"remapped sample count overflows"))?; + let remapped = (0..sample_count).map(|sample| { + let pixel_start = sample / output_channels * component_count; + transferred[pixel_start + indices[sample % output_channels]] + }); + (quantize_integer(encoding, size.0, output_channels, remapped)?, output_channels) } else { - // Stream native-order samples directly into the integer buffer - let bytes = quantize_integer(encoding, size.0, component_count, transferred)?; - drop(integer_data); - (bytes, component_count) + (quantize_integer(encoding, size.0, component_count, transferred)?, component_count) }; let sample_type = if depth == 16 { SampleType::U16 } else { SampleType::U8 }; @@ -1323,9 +1562,9 @@ fn encode( FileFormat::Bmp => CodecFormat::Bmp, FileFormat::Webp => CodecFormat::WebP, FileFormat::Pgm => CodecFormat::Pnm, - FileFormat::Psd => return psd(bytes, size, component_count, depth).map_err(|error| encoding_error(&error)), FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)), FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")), + FileFormat::Psd => return Err(encoding_error(&"a PSD holds the layers of several maps (`layered_psd`)")), }; let layout = match component_count { 1 => ChannelLayout::Gray, @@ -1341,6 +1580,14 @@ fn encode( write_raster(&image, codec_format).map_err(|error| encoding_error(&error)) } +fn quantize_u8(value: f32) -> u8 { + (value * f32::from(u8::MAX) + 0.5) as u8 +} + +fn quantize_u16(value: f32) -> u16 { + (value * f32::from(u16::MAX) + 0.5) as u16 +} + fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samples: impl ExactSizeIterator) -> Result> { let Encoding { format, depth, dither } = encoding; let byte_count = samples @@ -1351,7 +1598,7 @@ fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samp bytes.try_reserve_exact(byte_count).map_err(|error| FormatError::Invalid(format!("{} sample buffer allocation failed: {error}", format.extension())))?; if depth == 16 { - bytes.extend(samples.flat_map(|value| ((value * f32::from(u16::MAX) + 0.5) as u16).to_ne_bytes())); + bytes.extend(samples.flat_map(|value| quantize_u16(value).to_ne_bytes())); } else { let width = width.max(1) as usize; let threshold = |sample_index: usize| { @@ -1365,42 +1612,56 @@ fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samp if dither { bytes.extend(samples.enumerate().map(|(index, value)| (value * max_sample + threshold(index)).floor().clamp(0.0, max_sample) as u8)); } else { - bytes.extend(samples.map(|value| (value * max_sample + 0.5) as u8)); + bytes.extend(samples.map(quantize_u8)); } } Ok(bytes) } -fn check_psd_size((width, height): (u32, u32), channels: usize, depth: u8) -> Result<()> { - if width == 0 || height == 0 || width > PSD_MAX_SIDE_PIXELS || height > PSD_MAX_SIDE_PIXELS { - return Err(FormatError::Invalid(format!("PSD size {width}×{height} must be between 1 and {PSD_MAX_SIDE_PIXELS} pixels per side"))); +/// Return the canvas size and conservative file size after checking PSD format limits. +fn check_psd_size(sizes: impl IntoIterator, folder_count: usize, depth: u8) -> Result<((u32, u32), u64)> { + // A layer record with its names, and each of a group's two records, stays below this + const PSD_RECORD_BYTES: u64 = 2048; + + let (mut width, mut height) = (1, 1); + let mut layer_texels = 0; + let mut layer_count = 0; + for (layer_width, layer_height) in sizes { + if !(1..=PSD_MAX_SIDE_PIXELS).contains(&layer_width) || !(1..=PSD_MAX_SIDE_PIXELS).contains(&layer_height) { + return Err(FormatError::Invalid(format!("PSD size {layer_width}×{layer_height} must be between 1 and {PSD_MAX_SIDE_PIXELS} pixels per side"))); + } + + width = width.max(layer_width); + height = height.max(layer_height); + layer_texels += u64::from(layer_width) * u64::from(layer_height); + layer_count += 1; } - // Measure the flat file's overhead without allocating any pixel buffers - let overhead = flat_psd((width, height), channels, depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?; - let sample_bytes = u64::from(width) * u64::from(height) * channels as u64 * u64::from(depth / 8); - if overhead + sample_bytes >= PSD_MAX_FILE_BYTES { - return Err(FormatError::Invalid(format!("PSD size {width}×{height} would reach the 2 GiB file limit; use a smaller export size or another format"))); + // Measure the merged image's overhead without allocating any pixel buffers + let merged = flat_psd((width, height), depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?; + let records = PSD_RECORD_BYTES * (layer_count + 2 * folder_count as u64); + let texels = u64::from(width) * u64::from(height) + layer_texels; + let sample_bytes = texels * PSD_RGBA_PLANES as u64 * u64::from(depth / 8); + let file_bytes = merged + records + sample_bytes; + if file_bytes >= PSD_MAX_FILE_BYTES { + return Err(FormatError::Invalid(format!( + "a PSD of {layer_count} maps at {width}×{height} would reach the 2 GiB file limit; use a smaller export size, fewer PSD maps or another format" + ))); } - Ok(()) + Ok(((width, height), file_bytes)) } -fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_psd::PsdFile { - use craft_psd::{ColorMode, Compression, Header, ImageData, ImageResource, PsdFile, Version}; - - const PSD_ALPHA_NAMES_RESOURCE_ID: u16 = 1006; - let color_mode = if channels <= 2 { ColorMode::Grayscale } else { ColorMode::Rgb }; - let header = Header::new(Version::Psd, width, height, channels as u16, u16::from(depth), color_mode); - - // A Pascal name marks the extra plane as a channel separate from merged transparency - let resources = if matches!(channels, 2 | 4) { vec![ImageResource::new(PSD_ALPHA_NAMES_RESOURCE_ID, b"\x05Alpha".to_vec())] } else { Vec::new() }; +/// A PSD of only an RGBA merged image with no pixels yet, to measure +fn flat_psd((width, height): (u32, u32), depth: u8) -> craft_psd::PsdFile { + use craft_psd::{ColorMode, Compression, Header, ImageData, PsdFile, Version}; + let header = Header::new(Version::Psd, width, height, PSD_RGBA_PLANES as u16, u16::from(depth), ColorMode::Rgb); PsdFile { header, color_mode_data: Vec::new(), - resources, + resources: Vec::new(), layer_info: None, layer_info_placement: Default::default(), global_layer_mask: None, @@ -1411,26 +1672,6 @@ fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_ps } } -/// Write a merged PSD image with raw planes, including an extra alpha plane when present. -fn psd(bytes: Vec, size: (u32, u32), channels: usize, depth: u8) -> craft_psd::Result> { - let mut file = flat_psd(size, channels, depth); - let planes = &mut file.image_data.data; - planes.try_reserve_exact(bytes.len()).map_err(|_| craft_psd::PsdError::OutOfMemory("cannot allocate PSD planes"))?; - if depth == 16 { - let samples = bytes.as_chunks::<2>().0; - for channel in 0..channels { - planes.extend(samples.iter().skip(channel).step_by(channels).flat_map(|sample| u16::from_ne_bytes(*sample).to_be_bytes())); - } - } else { - for channel in 0..channels { - planes.extend(bytes.iter().skip(channel).step_by(channels).copied()); - } - } - drop(bytes); - - file.to_bytes() -} - /// A JNG file: the colour as JPEG, alpha (when present) as lossless 8-bit deflate data. fn jng(bytes: &[u8], (w, h): (u32, u32), n: usize) -> std::result::Result, String> { use std::io::Write; @@ -1546,14 +1787,23 @@ pub fn skip_repeated_names(files: &mut Vec) { *files = keep_first_names(std::mem::take(files), |file| &file.name, |file| &mut file.warnings); } -fn keep_first_names(files: Vec, name: impl Fn(&T) -> &str, warnings: impl Fn(&mut T) -> &mut Vec) -> Vec { +/// Keep the first case-insensitive use of each filename and attach duplicate warnings to its plan. +pub fn keep_first_planned_names(files: impl IntoIterator) -> Vec<(T, PlannedFile)> { + keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings) +} + +fn keep_first_names(files: impl IntoIterator, name: impl Fn(&T) -> &str, warnings: impl Fn(&mut T) -> &mut Vec) -> Vec { + let files = files.into_iter(); let mut first = HashMap::new(); - let mut kept = Vec::with_capacity(files.len()); - for file in files { - let filename = name(&file); + let mut kept = Vec::with_capacity(files.size_hint().0); + for mut file in files { + let filename = name(&file).to_owned(); match first.entry(filename.to_ascii_lowercase()) { Entry::Occupied(previous) => { + // The later file's set warnings stay with the export + let moved: Vec<_> = warnings(&mut file).extract_if(.., |warning| is_set_warning(warning)).collect(); if let Some(winner) = kept.get_mut(*previous.get()) { + warnings(winner).extend(moved); warnings(winner).push(format!( "\"{}\" of a later texture set has the name of a file an earlier texture set exports, so it was not written; add $textureSet to the template's file names or rename a texture set", filename diff --git a/crates/formats/src/export/planned_layer.rs b/crates/formats/src/export/planned_layer.rs new file mode 100644 index 00000000..4f0adf39 --- /dev/null +++ b/crates/formats/src/export/planned_layer.rs @@ -0,0 +1,10 @@ +/// An output map written as a layer of a texture set's PSD (see [`super::list_outputs`]) +#[derive(Clone, Debug, PartialEq)] +pub struct PlannedLayer { + /// Index into the preset's maps + pub map: usize, + /// The map's file name, a `/` separating the groups the layer sits in + pub name: String, + /// 8-bit samples written with dithering + pub dither: bool, +} diff --git a/crates/formats/src/export/psd_budget.rs b/crates/formats/src/export/psd_budget.rs new file mode 100644 index 00000000..e6300254 --- /dev/null +++ b/crates/formats/src/export/psd_budget.rs @@ -0,0 +1,17 @@ +/// The memory limits PSD planning holds an export to: a browser tab's address space needs them, a native export renders one layer at a time without them +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct PsdBudget { + /// Pixel buffers of one document, including the renderer's padding and encoder + pub(super) working_bytes: Option, + /// Encoded documents one batch holds in memory, with headroom for a document's working buffers and ZIP packaging + pub(super) batch_bytes: Option, +} + +impl PsdBudget { + /// A browser tab's: the export and the app share its 4 GiB address space + pub(super) const WEB: Self = Self { working_bytes: Some(2 * 1024 * 1024 * 1024), batch_bytes: Some(1024 * 1024 * 1024) }; + /// A desktop export's: the machine bounds it, as it does every other file type + pub(super) const NATIVE: Self = Self { working_bytes: None, batch_bytes: None }; + /// The budget of the platform this build runs on + pub(super) const TARGET: Self = if cfg!(target_arch = "wasm32") { Self::WEB } else { Self::NATIVE }; +} diff --git a/crates/formats/src/export/rendered_map.rs b/crates/formats/src/export/rendered_map.rs new file mode 100644 index 00000000..df388464 --- /dev/null +++ b/crates/formats/src/export/rendered_map.rs @@ -0,0 +1,13 @@ +use texturecraft_texel::ColorSpace; + +/// One output map's linear samples at its export size, ready to encode +pub(super) struct RenderedMap { + /// Interleaved L, LA, RGB or RGBA samples + pub data: Vec, + pub size: (u32, u32), + pub component_count: usize, + /// Per component: whether encoding applies the sRGB transfer + pub srgb: Vec, + /// The colour space recorded in the file, when the user chose one for a colour map + pub embed: Option, +} diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index b2664af0..49f4b812 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -373,6 +373,7 @@ fn every_format_encodes_and_decodes() { opts.format_override = Some(format); opts.bit_depth_override = Some(depth); let files = fx.render(&opts); + assert_eq!(files.len(), 4, "{format:?}"); for f in &files { assert!(f.name.ends_with(format.extension())); @@ -385,6 +386,7 @@ fn every_format_encodes_and_decodes() { // Roughness 0.25 everywhere survives every format (JPEG within its loss) let px = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1]; + assert!((px - 0.25).abs() < 0.01, "{format:?}/{depth}: {px}"); let base = find(&files, "_BaseColor."); match format { @@ -555,6 +557,34 @@ fn gray_map(file: &str, src: SourceRef) -> MapSpec { MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)], inverted: Vec::new() } } +#[test] +fn an_output_with_its_own_size_keeps_it() { + let fx = Fx::new(&default_channels()); + let preset = ExportPreset { + name: "sizes".into(), + maps: vec![ + gray_map("small", SourceRef::Channel { channel: Channel::Roughness, component: 0 }), + gray_map("set_size", SourceRef::Channel { channel: Channel::Metallic, component: 0 }), + ], + }; + let mut options = ExportOptions::new(preset); + options.maps.insert(0, MapOverride { size: Some(32), ..MapOverride::default() }); + + for (export_size, other) in [(None, RES), (Some(128), 128)] { + let files = fx.render(&ExportOptions { size: export_size, ..options.clone() }); + + assert_eq!(find(&files, "small.png").width, 32, "its own size wins over {export_size:?}"); + assert_eq!(find(&files, "set_size.png").width, other); + } + + // A PSD is as large as its largest layer + options.format_override = Some(FileFormat::Psd); + assert_eq!(fx.render(&options)[0].width, RES); + + options.maps.insert(0, MapOverride { size: Some(100), ..MapOverride::default() }); + assert!(list_outputs(&fx.project, 0, "sphere", &options).is_err(), "a size that isn't a power of two is refused"); +} + #[test] fn validation_rejects_bad_presets() { let ok = ExportPreset { name: "Mine".into(), maps: vec![gray_map("$mesh_$textureSet_$channel ($colorSpace) $project", SourceRef::Constant(1.0))] }; @@ -729,6 +759,9 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() { // A folder stays in the placeholder name assert_eq!(udim_names("Base/$textureSet_$udim".into()), [Some("Base/Body_.png".to_string()), Some("Base/Body_.png".to_string())]); + + // A name without the token gets the tile as a suffix, and so does its placeholder + assert_eq!(udim_names("$textureSet".into()), [Some("Body..png".to_string()), Some("Body..png".to_string())]); } #[test] @@ -1121,45 +1154,121 @@ fn pgm_is_a_binary_graymap() { } #[test] -fn psd_holds_the_merged_image_planar() { +fn psd_holds_every_map_as_a_layer_over_their_merged_image() { let fx = Fx::new(&default_channels()); - let f = &fx.render(&one_map(FileFormat::Psd, 8, rgba_half_alpha()))[0]; - let b = &f.bytes; - assert_eq!(&b[0..4], b"8BPS"); - assert_eq!(u16::from_be_bytes([b[12], b[13]]), 4, "channels"); - assert_eq!((u32::from_be_bytes(b[14..18].try_into().unwrap()), u32::from_be_bytes(b[18..22].try_into().unwrap())), (64, 64)); - assert_eq!((u16::from_be_bytes([b[22], b[23]]), u16::from_be_bytes([b[24], b[25]])), (8, 3), "8-bit RGB"); - let parsed = craft_psd::PsdFile::from_bytes(b).unwrap(); - assert!(!parsed.merged_has_alpha()); - assert_eq!(parsed.alpha_channel_names(), ["Alpha"]); - let samples = parsed.decode_merged().unwrap(); - assert_eq!(samples.len(), 4 * 64 * 64); - let plane = |c: usize| &samples[c * 64 * 64..(c + 1) * 64 * 64]; - assert!(plane(3).iter().all(|a| *a == 128), "alpha plane"); - let png = decode(&fx.render(&one_map(FileFormat::Png, 8, rgba_half_alpha()))[0]).to_rgba8(); - assert_eq!(plane(0)[64 * 10 + 40], png.get_pixel(40, 10)[0], "the red plane holds the same values as a PNG"); + let mut png_options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); + png_options.bit_depth_override = Some(8); + let pngs = fx.render(&png_options); + let mut options = png_options.clone(); + options.format_override = Some(FileFormat::Psd); - let f16 = &fx.render(&one_map(FileFormat::Psd, 16, roughness()))[0]; - assert_eq!((u16::from_be_bytes([f16.bytes[12], f16.bytes[13]]), u16::from_be_bytes([f16.bytes[22], f16.bytes[23]])), (1, 16)); - assert_eq!(f16.bytes.len(), 26 + 12 + 2 + 2 * 64 * 64); + let planned = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + let files = fx.render(&options); - let mut gray_alpha = roughness(); - gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); - let f16 = &fx.render(&one_map(FileFormat::Psd, 16, gray_alpha))[0]; - let parsed = craft_psd::PsdFile::from_bytes(&f16.bytes).unwrap(); - assert!(!parsed.merged_has_alpha()); - assert_eq!(parsed.alpha_channel_names(), ["Alpha"]); - let samples = parsed.decode_merged().unwrap(); - assert_eq!(samples.len(), 2 * 2 * 64 * 64); - assert!(samples[2 * 64 * 64..].as_chunks::<2>().0.iter().all(|sample| *sample == [128, 0])); + assert_eq!(planned.len(), 1, "one PSD for the texture set: {planned:?}"); + assert_eq!(planned[0].layers.len(), pngs.len()); + assert_eq!(files.len(), 1); + assert_eq!(files[0].name, "sphere_Body_Set.psd"); + let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layers: Vec<_> = parsed.iter_layers().collect(); + + assert_eq!(layers.len(), pngs.len()); + + // The file stacks bottom up, so the first map is the top layer + for (layer, png) in layers.iter().rev().zip(&pngs) { + assert_eq!(format!("{}.png", layer.name()), png.name); + assert_eq!(layer.rgba8().unwrap().data, decode(png).to_rgba8().into_raw(), "{}: the layer holds the map's texels", png.name); + } + let top = layers.last().unwrap().rgba8().unwrap().data; + + assert!(top.as_chunks::<4>().0.iter().all(|texel| texel[3] == u8::MAX), "the base colour is opaque"); + assert_eq!(parsed.composite_rgba8().unwrap().data, top, "the merged image shows the opaque top layer"); + + options.bit_depth_override = Some(16); + let deep = &fx.render(&options)[0]; + + assert_eq!(craft_psd::PsdFile::from_bytes(&deep.bytes).unwrap().header.depth, 16); +} + +#[test] +fn psd_keeps_small_layers_at_the_requested_size() { + let fx = Fx::new(&default_channels()); + let mut options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); + options.format_override = Some(FileFormat::Psd); + options.bit_depth_override = Some(8); + options.maps.insert(0, MapOverride { size: Some(RES / 2), ..Default::default() }); + options.maps.insert(1, MapOverride { size: Some(RES / 4), ..Default::default() }); + + let files = fx.render(&options); + let psd = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layers: Vec<_> = psd.iter_layers().map(|layer| layer.rgba8().unwrap()).collect(); + let merged = psd.composite_rgba8().unwrap(); + + assert_eq!((merged.width, merged.height), (RES, RES)); + assert_eq!(layers.iter().map(|layer| (layer.width, layer.height)).collect::>(), [(RES, RES), (RES / 4, RES / 4), (RES / 2, RES / 2)]); + let pixel = |x: u32, y: u32| ((y * RES + x) * 4) as usize; + + assert_eq!(&merged.data[..4], &layers[2].data[..4]); + let outside_top_layers = pixel(RES - 1, 0); + + assert_eq!(&merged.data[outside_top_layers..outside_top_layers + 4], &layers[0].data[outside_top_layers..outside_top_layers + 4]); +} + +#[test] +fn psd_folder_templates_become_layer_groups_of_one_file_not_folders() { + let fx = Fx::new(&default_channels()); + let rough = |file: &str| gray_map(file, SourceRef::Channel { channel: Channel::Roughness, component: 0 }); + let preset = ExportPreset { name: "t".into(), maps: vec![rough("Body/$textureSet_Rough"), rough("Top/Inner/Leaf"), rough("Mask")] }; + let mut options = ExportOptions::new(preset); + options.format_override = Some(FileFormat::Psd); + + let files = fx.render(&options); + + assert_eq!(files.iter().map(|f| f.name.as_str()).collect::>(), ["sphere_Body_Set.psd"], "no folder for a PSD's layers"); + let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name(); + let tree = parsed.layer_tree(); + + // The tree lists bottom up and the first map is the top layer + let groups: Vec<_> = tree.iter().rev().filter(|node| node.is_group()).map(name).collect(); + + assert_eq!(groups, ["Body", "Top"]); + let body = tree.iter().find(|node| node.is_group() && name(node) == "Body").unwrap(); + + assert_eq!(body.children().iter().map(name).collect::>(), ["Body_Set_Rough"], "$textureSet is filled in inside a layer name"); + assert!(tree.iter().any(|node| !node.is_group() && name(node) == "Mask")); +} + +#[test] +fn psd_layer_groups_follow_the_slashes_of_their_names() { + let pixel = || craft_psd::PixelData::Rgba8(vec![10, 20, 30, 255]); + let layers = ["Mask", "Body/Rough", "Body/Color", "Top/Inner/Leaf"].into_iter().map(|name| (name, (1, 1), pixel())).collect(); + + let bytes = layered_psd::write_layers((1, 1), 8, layers, pixel()).unwrap(); + + let parsed = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name(); + let tree = parsed.layer_tree(); + + assert_eq!( + tree.iter().map(|node| (name(node), node.is_group())).collect::>(), + [("Mask".to_string(), false), ("Body".to_string(), true), ("Top".to_string(), true)] + ); + assert_eq!(tree[1].children().iter().map(name).collect::>(), ["Rough", "Color"]); + let inner = &tree[2].children()[0]; + + assert!(inner.is_group() && name(inner) == "Inner"); + assert_eq!(inner.children().iter().map(name).collect::>(), ["Leaf"]); } #[test] fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { let mut fx = Fx::new(&default_channels()); - fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + + // Eight tile columns make a 32768-wide atlas while the individual PSDs stay within budget + fx.project.texture_sets[0].uv_tiles = vec![1001, 1008]; let mut options = one_map(FileFormat::Psd, 8, roughness()); - options.size = Some(16_384); + options.size = Some(4096); options.atlas = true; let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); @@ -1170,7 +1279,123 @@ fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { } #[test] -fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() { +fn psd_plan_preserves_each_udim_suffix_after_truncating_the_stem() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + let options = one_map(FileFormat::Psd, 8, roughness()); + let mesh_name = "a".repeat(MAX_STEM); + + let plan = list_outputs(&fx.project, 0, &mesh_name, &options).unwrap(); + + assert_eq!(plan.len(), 2); + for (file, tile) in plan.iter().zip([1001, 1002]) { + assert!(file.name.ends_with(&format!(".{tile}.psd")), "{}", file.name); + assert_eq!(file.udim_name.as_ref().unwrap().replace("", &tile.to_string()), file.name); + } +} + +#[test] +fn feedback_psd_long_mesh_names_keep_distinct_texture_sets_and_tiles() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + let mut trim = fx.project.texture_sets[0].clone(); + trim.name = "Trim".into(); + fx.project.texture_sets.push(trim); + let options = one_map(FileFormat::Psd, 8, roughness()); + + let plan = list_set_outputs(&fx.project, &[0, 1], &"m".repeat(MAX_STEM), &options).unwrap(); + + assert_eq!(plan.len(), 4, "both tiles of both sets must survive deduplication"); + for (set, file) in plan { + let tile = file.tile.unwrap(); + let set_name = sanitize_file_stem(&fx.project.texture_sets[set].name); + assert!(file.name.contains(&set_name), "{}", file.name); + assert!(file.name.ends_with(&format!(".{tile}.psd")), "{}", file.name); + assert_eq!(file.udim_name.unwrap().replace("", &tile.to_string()), file.name); + } +} + +#[test] +fn feedback_reserved_export_stem_remains_bounded_and_idempotent() { + let raw = format!("CON.{}", "x".repeat(MAX_STEM)); + + let sanitized = sanitize_file_stem(&raw); + + assert!(sanitized.starts_with("_CON.")); + assert!(sanitized.len() <= MAX_STEM, "{} bytes", sanitized.len()); + assert_eq!(sanitize_file_stem(&sanitized), sanitized); +} + +#[test] +fn feedback_psd_dithering_tracks_the_document_depth() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.dither = true; + let mut second = options.preset.maps[0].clone(); + second.file = "second".into(); + options.preset.maps.push(second); + options.maps.insert(1, MapOverride { dither: Some(false), ..MapOverride::default() }); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert!(plan[0].dither && plan[0].layers[0].dither && !plan[0].layers[1].dither); + + options.preset.maps[1].bit_depth = 16; + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert_eq!(plan[0].bit_depth, 16); + assert!(!plan[0].dither && plan[0].layers.iter().all(|layer| !layer.dither)); + assert!(plan[0].warnings.iter().any(|warning| warning.contains("dithering") && warning.contains("16-bit"))); +} + +#[test] +fn feedback_psd_rejects_large_working_set_during_planning() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, rgba_half_alpha()); + options.size = Some(8192); + + let error = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err(); + + assert!(error.to_string().contains("working memory"), "{error}"); + options.size = Some(4096); + assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).is_ok()); +} + +#[test] +fn a_native_export_plans_psds_a_browser_tab_cannot_hold() { + let mut fx = Fx::new(&default_channels()); + let mut one = one_map(FileFormat::Psd, 8, rgba_half_alpha()); + one.size = Some(MAX_IMAGE_SIZE / 2); + let mut separate = ExportOptions::new(builtin_preset("Separate maps").unwrap()); + separate.format_override = Some(FileFormat::Psd); + separate.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1005).collect(); + + let plans = [list_outputs(&fx.project, 0, "sphere", &one), list_outputs(&fx.project, 0, "sphere", &separate)]; + + for plan in plans { + let plan = plan.unwrap(); + assert!(!plan.is_empty() && plan.iter().all(|file| file.format == FileFormat::Psd), "{plan:?}"); + } + assert!(list_set_outputs(&fx.project, &[0], "sphere", &separate).is_ok(), "a desktop batch holds every tile's PSD"); +} + +#[test] +fn a_psd_that_cannot_be_planned_leaves_the_sets_other_maps() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Png, 8, roughness()); + let mut psd = options.preset.maps[0].clone(); + (psd.file, psd.format, psd.bit_depth, psd.channels) = ("layered".into(), FileFormat::Psd, 16, rgba_half_alpha()); + options.preset.maps.push(psd); + options.size = Some(MAX_IMAGE_SIZE); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert!(plan.len() == 1 && plan[0].format == FileFormat::Png, "{plan:?}"); + assert!(plan[0].warnings.iter().any(|warning| warning.contains(".psd") && warning.contains("2 GiB")), "{:?}", plan[0].warnings); +} + +#[test] +fn psd_plan_counts_every_layer_against_the_version_one_byte_limit() { let fx = Fx::new(&default_channels()); let mut options = one_map(FileFormat::Psd, 16, rgba_half_alpha()); options.size = Some(16_384); @@ -1178,19 +1403,26 @@ fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() { let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); assert!(error.to_string().contains("PSD") && error.to_string().contains("2 GiB"), "{error}"); - options.bit_depth_override = Some(8); - assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); - options.bit_depth_override = None; - options.preset.maps[0].channels.pop(); - assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); + options.size = Some(8192); + let layer_size = (8192, 8192); + for copy in ["second", "third"] { + assert!(check_psd_size(std::iter::repeat_n(layer_size, options.preset.maps.len()), 0, 16).is_ok()); + let mut map = options.preset.maps[0].clone(); + map.file = copy.into(); + options.preset.maps.push(map); + } + let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); + + assert!(error.to_string().contains("3 maps") && error.to_string().contains("2 GiB"), "{error}"); } #[test] -fn psd_byte_limit_includes_resources_and_keeps_separate_tiles_valid() { - // These RGBA16 planes are 32 bytes below 2 GiB before headers and the alpha name - let (width, height) = (10_924, 24_573); - assert!(check_psd_size((width, height), 4, 16).is_err()); - assert!(check_psd_size((width, height - 1), 4, 16).is_ok()); +fn psd_byte_limit_includes_the_merged_image_and_keeps_separate_tiles_valid() { + // One RGBA16 layer and the merged image: 87360 bytes over 2 GiB, a row less 87424 bytes below + let (width, height) = (10_924, 12_287); + + assert!(check_psd_size([(width, height)], 0, 16).is_err()); + assert!(check_psd_size([(width, height - 1)], 0, 16).is_ok()); let mut fx = Fx::new(&default_channels()); fx.project.texture_sets[0].uv_tiles = vec![1001, 1003, 1011]; @@ -1201,10 +1433,25 @@ fn psd_byte_limit_includes_resources_and_keeps_separate_tiles_valid() { let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); assert!(error.to_string().contains("2 GiB"), "{error}"); + options.size = Some(4096); + assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err().to_string().contains("working memory")); options.atlas = false; assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 3); } +#[test] +fn psd_rejects_a_composite_with_a_different_size_from_the_plan() { + let mut fx = Fx::new(&default_channels()); + let source_size = RES * 2; + fx.comp = Composite::new(&default_channels(), source_size); + fx.coverage.resize((source_size * source_size) as usize, true); + let options = one_map(FileFormat::Psd, 8, roughness()); + + let error = render_maps(&fx.input(), &options).unwrap_err(); + + assert!(error.to_string().contains("does not match the planned texture set size"), "{error}"); +} + #[test] fn jng_has_jpeg_colour_and_lossless_alpha() { use std::io::Read; @@ -1576,6 +1823,527 @@ fn write_files_accepts_a_long_nested_folder_and_stem() { std::fs::remove_dir_all(&dir).unwrap(); } +#[test] +fn map_preview_bounds_the_longer_side_of_a_tall_atlas() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1031]; + fx.comp = Composite::with_size(&default_channels(), RES, RES * 4); + fx.coverage.resize((RES * RES * 4) as usize, true); + let options = one_map(FileFormat::Png, 8, roughness()); + let max_side = 32; + + let preview = MapPreview::sample(&fx.input(), &options, 0, max_side).unwrap().unwrap(); + + assert_eq!(preview.height, max_side); + assert_eq!(preview.width * 4, preview.height); + assert_eq!(preview.pixels.len(), (preview.width * preview.height) as usize); +} + +#[test] +fn a_map_preview_is_no_larger_than_the_maps_own_size() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Png, 8, roughness()); + let own = RES / 4; + options.maps.insert(0, MapOverride { size: Some(own), ..MapOverride::default() }); + let file = decode(&fx.render(&options)[0]); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + + assert_eq!((preview.width, preview.height), file.dimensions(), "the preview shows the file at its own size"); + options.size = Some(RES / 2); + options.maps.clear(); + let export_sized = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + + assert!(export_sized.width > preview.width && export_sized.width < RES, "the export size bounds a map without its own"); +} + +#[test] +fn a_map_preview_holds_the_values_its_file_stores() { + let mut fx = Fx::new(&default_channels()); + fx.set_all(Channel::Metallic, |x, _| [x as f32 / 63.0; 3]); + fx.set_all(Channel::Roughness, |_, y| [y as f32 / 63.0; 3]); + let mut options = ExportOptions::new(builtin_preset("Unity HDRP (Mask Map)").unwrap()); + let mask = options.preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap(); + let base = options.preset.maps.iter().position(|map| map.file.contains("BaseMap")).unwrap(); + options.preset.maps[mask].inverted.push(Dest::R); + let files = fx.render(&options); + + // The packed data map, one channel inverted, and the sRGB colour map + for (index, suffix) in [(mask, "MaskMap"), (base, "BaseMap")] { + let file = decode(find(&files, suffix)); + let preview = MapPreview::sample(&fx.input(), &options, index, RES).unwrap().unwrap(); + + assert_eq!((preview.width, preview.height), file.dimensions()); + assert_eq!(preview.channels.len(), usize::from(file.color().channel_count()), "{suffix}"); + assert!(preview.pixels == file.into_bytes(), "{suffix}: the preview shows what the file stores"); + } + + let small = MapPreview::sample(&fx.input(), &options, mask, 8).unwrap().unwrap(); + + assert!(small.width < RES && small.pixels.len() == (small.width * small.height) as usize * 4, "a smaller preview samples the same map"); + assert!(MapPreview::sample(&fx.input(), &options, options.preset.maps.len(), 8).is_err(), "a map the template doesn't have is an error"); +} + +#[test] +fn feedback_jpeg_previews_omit_the_alpha_channel() { + let fx = Fx::new(&default_channels()); + let mut la = roughness(); + la.push((Dest::A, SourceRef::Constant(0.5))); + for (channels, expected) in [(la, vec![Dest::L]), (rgba_half_alpha(), vec![Dest::R, Dest::G, Dest::B])] { + let mut options = one_map(FileFormat::Png, 8, channels); + let png_preview = MapPreview::sample(&fx.input(), &options, 0, 16).unwrap().unwrap(); + options.maps.insert(0, MapOverride { format: Some(FileFormat::Jpeg), ..MapOverride::default() }); + + let jpeg_preview = MapPreview::sample(&fx.input(), &options, 0, 16).unwrap().unwrap(); + let jpeg = decode(&fx.render(&options)[0]); + + assert_eq!(jpeg_preview.channels, expected); + assert_eq!(jpeg_preview.channels.len(), usize::from(jpeg.color().channel_count())); + let colors: Vec<_> = png_preview.pixels.chunks_exact(png_preview.channels.len()).flat_map(|pixel| pixel[..expected.len()].iter().copied()).collect(); + assert_eq!(jpeg_preview.pixels, colors); + } +} + +#[test] +fn webp_preview_matches_the_exported_channels_and_samples() { + let fx = Fx::new(&default_channels()); + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let mut rgb = rgba_half_alpha(); + rgb.retain(|(dest, _)| *dest != Dest::A); + + for (layout, expected) in + [(roughness(), &[Dest::R, Dest::G, Dest::B][..]), (gray_alpha, &[Dest::R, Dest::G, Dest::B, Dest::A][..]), (rgb, &[Dest::R, Dest::G, Dest::B][..])] + { + let options = one_map(FileFormat::Webp, 8, layout); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let image = decode(&fx.render(&options)[0]); + + assert_eq!(preview.channels, expected); + assert_eq!(preview.channels.len(), usize::from(image.color().channel_count())); + assert_eq!(preview.pixels, image.as_bytes()); + } +} + +#[test] +fn pgm_preview_shows_exported_luminance_without_alpha() { + let fx = Fx::new(&default_channels()); + let mut gray_with_alpha = roughness(); + gray_with_alpha.push((Dest::A, SourceRef::Constant(0.5))); + + for channels in [gray_with_alpha, rgba_half_alpha()] { + let mut options = one_map(FileFormat::Png, 8, channels); + options.maps.insert(0, MapOverride { format: Some(FileFormat::Pgm), ..MapOverride::default() }); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let files = fx.render(&options); + let pgm_samples = files[0].bytes.strip_prefix(b"P5\n64 64\n255\n").unwrap(); + + assert_eq!(preview.channels, [Dest::L]); + assert_eq!(preview.pixels, pgm_samples); + } +} + +#[test] +fn hdr_and_tiff_previews_show_channels_written_by_the_encoder() { + let fx = Fx::new(&default_channels()); + let mut gray_with_alpha = roughness(); + gray_with_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let rgb = [Dest::R, Dest::G, Dest::B]; + let rgba = [Dest::R, Dest::G, Dest::B, Dest::A]; + + for (format, depth, layout, expected) in [ + (FileFormat::Hdr, 32, &gray_with_alpha, rgb.as_slice()), + (FileFormat::Hdr, 32, &rgba_half_alpha(), rgb.as_slice()), + (FileFormat::Tiff, 8, &gray_with_alpha, rgba.as_slice()), + (FileFormat::Tiff, 32, &gray_with_alpha, rgba.as_slice()), + (FileFormat::Tiff, 32, &roughness(), rgb.as_slice()), + ] { + let mut options = one_map(format, depth, layout.clone()); + if layout[0].0 == Dest::L { + options.preset.maps[0].inverted.push(Dest::L); + } + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let file = decode(&fx.render(&options)[0]); + let components = usize::from(file.color().channel_count()); + + assert_eq!(preview.channels, expected, "{format:?} at {depth} bits"); + assert_eq!(preview.channels.len(), components); + assert_eq!(preview.pixels.len(), (file.width() * file.height()) as usize * components); + let decoded_pixels = file.to_rgba32f(); + for (preview_pixel, decoded) in preview.pixels.chunks_exact(components).zip(decoded_pixels.pixels()) { + for (actual, sample) in preview_pixel.iter().zip(decoded.0) { + let value = if options.preset.maps[0].is_color() && format == FileFormat::Hdr { linear_to_srgb(sample) } else { sample }; + assert!((i32::from(*actual) - byte(value)).abs() <= 2, "{format:?} at {depth} bits: {actual} vs {value}"); + } + } + } +} + +#[test] +fn triangle_coverage_preserves_uncovered_texels_and_height_normal_neighbours_in_previews() { + let mut fixture = Fx::new(&default_channels()); + fixture.set_all(Channel::Height, |x, y| [(x + y) as f32 / RES as f32; 3]); + for (index, covered) in fixture.coverage.iter_mut().enumerate() { + *covered = index % 3 != 0; + } + let triangles: Vec<_> = fixture.coverage.iter().map(|covered| if *covered { 0 } else { texturecraft_geom::NO_TRI }).collect(); + let input = fixture.input(); + let triangle_input = + ExportInput { project: input.project, ts: input.ts, composite: input.composite, baked: input.baked, coverage: &triangles, mesh_name: input.mesh_name }; + let options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); + + for map in 0..3 { + let expected = MapPreview::sample(&input, &options, map, RES).unwrap().unwrap(); + let actual = MapPreview::sample_triangles(&triangle_input, &options, map, RES).unwrap().unwrap(); + + assert_eq!(actual, expected); + } +} + +/// Tilts every normal of `fx` and returns the green byte an OpenGL normal map stores for it +fn tilt_normals(fx: &mut Fx) -> i32 { + let tilt = Vec3::new(0.3, 0.4, 0.0); + let tilt = Vec3::new(tilt.x, tilt.y, (1.0 - tilt.length_squared()).sqrt()); + fx.set_all(Channel::Normal, |_, _| (tilt * 0.5 + Vec3::splat(0.5)).to_array()); + byte(tilt.y * 0.5 + 0.5) +} + +#[test] +fn the_unreal_subsurface_template_writes_the_scatter_mask_beside_the_packed_maps() { + let mut channels = default_channels(); + channels.extend([Channel::AmbientOcclusion, Channel::Opacity, Channel::ScatterWeight]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::AmbientOcclusion, |_, _| [0.6; 3]); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Unreal Engine Subsurface Profile (Packed)"); + + let mask = find(&files, "_SubsurfaceMask.png"); + + assert_eq!(decode(mask).color(), image::ColorType::L8, "the mask is one 8-bit channel"); + assert_close(pixel(mask), [byte(0.7), byte(0.7), byte(0.7), 255], "scatter weight in the mask"); + let [r, g, b, _] = pixel(find(&files, "_OcclusionRoughnessMetallic.png")); + assert_close([r, g, b, 0], [byte(0.6), byte(0.4), byte(0.8), 0], "R occlusion, G roughness, B metallic"); + assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "opacity feeds the mask, not the base color's alpha"); + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); +} + +#[test] +fn the_gltf_specular_glossiness_template_packs_a_specular_glossiness_sets_own_channels() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::Normal, Channel::Height, Channel::Opacity]); + let specular = [0.2, 0.5, 0.8]; + fx.set_all(Channel::Specular, |_, _| specular); + fx.set_all(Channel::Glossiness, |_, _| [0.3; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("glTF Specular Glossiness (archived extension)"); + + let specular_glossiness = find(&files, "_SpecularGlossiness.png"); + + assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8); + let srgb = specular.map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(specular_glossiness), [srgb[0], srgb[1], srgb[2], byte(0.3)], "sRGB specular, linear glossiness in alpha"); + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(find(&files, "_Diffuse.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB diffuse, opacity in alpha"); + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); +} + +#[test] +fn the_gltf_specular_glossiness_file_is_rgba_and_fully_glossy_without_a_glossiness_channel() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Normal]); + fx.set_all(Channel::Specular, |_, _| [0.2, 0.5, 0.8]); + + let files = fx.render_preset("glTF Specular Glossiness (archived extension)"); + + let specular_glossiness = find(&files, "_SpecularGlossiness.png"); + assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8, "the extension reads glossiness from alpha"); + assert_eq!(pixel(specular_glossiness)[3], 255, "glossinessFactor defaults to 1"); +} + +#[test] +fn the_redshift_template_writes_one_map_per_input_the_set_has() { + let mut channels = default_channels(); + channels.extend([Channel::ScatterWeight, Channel::CoatWeight]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]); + fx.set_all(Channel::CoatWeight, |_, _| [0.2; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Redshift Standard Material (separate maps)"); + + let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect(); + for (input, expected) in [("Metalness", 0.8), ("ReflectionRoughness", 0.4), ("SubsurfaceWeight", 0.7), ("CoatWeight", 0.2)] { + let file = find(&files, &format!("_{input}.png")); + + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is one 8-bit channel: {names:?}"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); + assert!(!names.iter().any(|name| name.contains("Sheen") || name.contains("CoatRoughness")), "inputs the set lacks write no maps: {names:?}"); +} + +#[test] +fn the_roblox_template_writes_opacity_in_the_colour_alpha_and_opengl_normals() { + let mut fx = packing_fixture(); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Roblox SurfaceAppearance (separate maps)"); + + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(find(&files, "_Color.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB colour, opacity in alpha"); + for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4)] { + let file = find(&files, &format!("_{input}.png")); + + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is grayscale"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); +} + +#[test] +fn the_sketchfab_template_writes_directx_normals_and_one_map_per_channel() { + let mut fx = packing_fixture(); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Sketchfab Metalness (separate maps)"); + + assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "no alpha on the base color"); + for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4), ("AmbientOcclusion", 0.6)] { + let file = find(&files, &format!("_{input}.png")); + + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is linear grayscale"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + + assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); +} + +#[test] +fn feedback_psd_preview_matches_layer_rgba() { + let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]); + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + + for channels in [roughness(), gray_alpha, rgba_half_alpha()] { + let options = one_map(FileFormat::Psd, 8, channels); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let files = fx.render(&options); + let psd = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layer = psd.iter_layers().next().unwrap().rgba8().unwrap(); + + assert_eq!(preview.channels, [Dest::R, Dest::G, Dest::B, Dest::A]); + assert!(preview.pixels == layer.data, "the preview shows the layer's stored channels"); + } +} + +#[test] +fn psd_layers_hold_the_samples_of_the_same_png_at_every_layout_and_depth() { + let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]); + let base_colour = |component| SourceRef::Channel { channel: Channel::BaseColor, component }; + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let mut rgb = rgba_half_alpha(); + rgb.pop(); + let layouts = [roughness(), vec![(Dest::L, base_colour(0))], gray_alpha, rgb, rgba_half_alpha()]; + + for channels in layouts { + for (depth, dither) in [(8, false), (8, true), (16, false)] { + let mut png_options = one_map(FileFormat::Png, depth, channels.clone()); + png_options.dither = dither; + let mut psd_options = png_options.clone(); + psd_options.format_override = Some(FileFormat::Psd); + + let png = decode(&fx.render(&png_options)[0]); + let psd = craft_psd::PsdFile::from_bytes(&fx.render(&psd_options)[0].bytes).unwrap(); + let layer = psd.iter_layers().next().unwrap(); + + let context = format!("{channels:?} at {depth} bits, dithering {dither}"); + if depth == 16 { + // Planes of big-endian samples: red, green, blue, then transparency + let planes: Vec> = [0, 1, 2, -1].into_iter().map(|id| layer.channel_bytes(id).unwrap()).collect(); + let texel_count = planes[0].len() / 2; + let samples: Vec = + (0..texel_count).flat_map(|texel| planes.iter().map(move |plane| u16::from_be_bytes([plane[2 * texel], plane[2 * texel + 1]]))).collect(); + assert!(samples == png.to_rgba16().into_raw(), "{context}"); + } else { + assert!(layer.rgba8().unwrap().data == png.to_rgba8().into_raw(), "{context}"); + } + } + } +} + +#[test] +fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001]; + let mut options = one_map(FileFormat::Psd, 8, roughness()); + let literal = format!("{}.1001", "a".repeat(MAX_STEM - ".1001".len())); + options.preset.maps[0].file = literal.clone(); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert_eq!(plan[0].layers[0].name, literal); + + options.preset.maps[0].file = "Group/Map.$udim".into(); + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].layers[0].name, "Group/Map.1001"); + + options.preset.maps[0].file = "Map".into(); + options.format_override = Some(FileFormat::Png); + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].name, "Map.1001.png"); +} + +#[test] +fn feedback_psd_tiled_and_untiled_sets_keep_both_documents() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].name = "Body".into(); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + for name in ["body.1001", "Body.1001_1", "Trim"] { + let mut untiled = fx.project.texture_sets[0].clone(); + untiled.name = name.into(); + untiled.uv_tiles.clear(); + fx.project.texture_sets.push(untiled); + } + let options = one_map(FileFormat::Psd, 8, roughness()); + + let plans = list_set_outputs(&fx.project, &[1, 0, 2, 3], "sphere", &options).unwrap(); + + assert_eq!(plans.len(), 5); + assert_eq!(plans[1].1.name, "sphere_Body.1001.psd"); + assert_eq!(plans[2].1.name, "sphere_Body.1002.psd"); + assert_eq!(plans[3].1.name, "sphere_Body.1001_1.psd"); + assert_eq!(plans[4].1.name, "sphere_Trim.psd"); + let separate = list_outputs(&fx.project, 1, "sphere", &options).unwrap(); + assert_eq!(plans[0].1.name, separate[0].name, "individual desktop jobs agree with selection planning"); +} + +#[test] +fn psd_document_names_survive_sanitization_and_case_collisions() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].name = "Body Coat".into(); + for (name, tiles) in [ + ("body_coat", vec![]), + ("Body_Coat_0", vec![]), + ("Body Coat", vec![1001, 1002]), + ("BODY_COAT", vec![1001]), + ("Trim", vec![]), + ("body_coat", vec![1011]), + ] { + let mut set = fx.project.texture_sets[0].clone(); + set.name = name.into(); + set.uv_tiles = tiles; + fx.project.texture_sets.push(set); + } + let options = one_map(FileFormat::Psd, 8, roughness()); + let indices = [6, 5, 4, 3, 2, 1, 0]; + + let batch = list_set_outputs(&fx.project, &indices, "sphere", &options).unwrap(); + let separate: Vec<_> = indices + .into_iter() + .flat_map(|index| list_outputs(&fx.project, index, "sphere", &options).unwrap().into_iter().map(move |file| (index, file.name))) + .collect(); + + assert_eq!(batch.into_iter().map(|(index, file)| (index, file.name)).collect::>(), separate); + for (index, unchanged) in [(2, "sphere_Body_Coat_0.psd"), (5, "sphere_Trim.psd"), (6, "sphere_body_coat.1011.psd")] { + assert!(separate.iter().any(|(set, name)| *set == index && name == unchanged)); + } + let tiled = list_outputs(&fx.project, 3, "sphere", &options).unwrap(); + assert!(tiled[0].udim_name.is_some()); + assert_eq!(tiled[0].udim_name, tiled[1].udim_name, "tiles of one set keep the same pattern"); + + let atlas_options = ExportOptions { atlas: true, ..options }; + let atlas = list_set_outputs(&fx.project, &indices, "sphere", &atlas_options).unwrap(); + assert_eq!(atlas.len(), indices.len(), "atlas documents also need distinct names"); +} + +#[test] +fn psd_batch_budget_counts_only_retained_documents() { + let mut fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1006).collect(); + let mut other = fx.project.texture_sets[0].clone(); + other.name = "Other".into(); + fx.project.texture_sets.push(other); + + let once = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap(); + let repeated = plan_set_outputs(&fx.project, &[0, 0], "sphere", &options, PsdBudget::WEB).unwrap(); + let distinct = plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB); + let (_, bytes_per_tile) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); + + assert_eq!(once.len(), repeated.len()); + assert!(once.iter().zip(&repeated).all(|((_, first), (_, kept))| first.name == kept.name && kept.warnings.len() > first.warnings.len())); + assert!(matches!(distinct, Err(FormatError::TooLarge(message)) if message.contains("total PSD"))); + println!( + "PSD preflight: {bytes_per_tile} estimated bytes per tile, {} retained bytes, {} bytes if counted twice, limit {:?}", + bytes_per_tile * once.len() as u64, + bytes_per_tile * (once.len() + repeated.len()) as u64, + PsdBudget::WEB.batch_bytes + ); +} + +#[test] +fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { + let mut fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.padding = Padding::None; + options.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1008).collect(); + + let smaller = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap(); + assert_eq!(smaller.len(), 7, "seven 128 MiB payloads fit with record overhead"); + fx.project.texture_sets[0].uv_tiles.extend(1008..1034); + + let oversized = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB); + assert!(matches!(&oversized, Err(error) if error.to_string().contains("total PSD")), "the 33 individually valid tiles must be rejected as a batch"); + + let set = &fx.project.texture_sets[0]; + let (width, height) = set.size(); + fx.comp = Composite::with_size(&default_channels(), width, height); + fx.coverage.resize((width * height) as usize, true); + let planned = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap(); + let error = render_planned_maps_within(&fx.input(), &options, planned, PsdBudget::WEB).unwrap_err(); + assert!(error.to_string().contains("total PSD"), "{error}"); + + let (_, estimated_bytes) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); + println!( + "PSD preflight: {estimated_bytes} estimated bytes per tile; {} across 33 tiles; batch limit {:?}", + estimated_bytes * 33, + PsdBudget::WEB.batch_bytes + ); + + let mut small = fx.project.texture_sets[0].clone(); + small.uv_tiles = (1001..1006).collect(); + fx.project.texture_sets[0] = small.clone(); + small.name = "Other".into(); + fx.project.texture_sets.push(small); + assert!(plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).is_ok()); + assert!(plan_set_outputs(&fx.project, &[1], "sphere", &options, PsdBudget::WEB).is_ok()); + assert!(plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB).is_err(), "the budget includes all selected sets"); + assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_ok(), "a desktop batch has no such budget"); +} + #[test] fn specular_glossiness_exports_ignore_the_ior_specular_setting() { let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::SpecularLevel]); diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index a46a6f62..85356dce 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -42,8 +42,8 @@ pub mod project_file; pub mod zip_read; pub use export::{ - Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, - render_maps, skip_repeated_names, + Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MAX_PREVIEW_SIDE, MapOverride, MapPreview, MapSpec, Padding, PlannedFile, + SourceRef, VirtualMap, list_outputs, 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::{ @@ -53,7 +53,7 @@ pub use mesh_export::{ 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; -pub use presets::{DEFAULT_PRESET, builtin_preset, builtin_presets, preset_from_json, preset_to_json}; +pub use presets::{DEFAULT_PRESET, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, builtin_presets, preset_from_json, preset_to_json}; pub use project_file::{ BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, RamReservation, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes, set_project_open_limit_gib, diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index a3f2bddb..9441b31e 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -386,11 +386,16 @@ fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: /// 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. +/// follow it. Layered PSD files are omitted. 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 { + // PSD stores several maps in one file + if !file.format.usable_by_usd_asset() { + continue; + } + // The first tile stands for all the tiles of a map if seen_maps.contains(&file.map) { continue; @@ -405,6 +410,7 @@ pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_norm (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) { @@ -412,7 +418,7 @@ pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_norm } let Some((output, source)) = output_for_slot(slot, map, set, file.format) else { continue }; - let normal = (slot == 3).then(|| { + let normal = (SLOTS[slot].0 == "Normal").then(|| { opts.normal_format.unwrap_or(match source { SourceRef::Virtual { map: VirtualMap::NormalOpenGl, .. } => NormalFormat::OpenGl, SourceRef::Virtual { map: VirtualMap::NormalDirectX, .. } => NormalFormat::DirectX, @@ -585,6 +591,7 @@ mod texture_binding_tests { tile: None, udim_name: None, warnings: Vec::new(), + layers: Vec::new(), } } diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 2f2879a4..0b34ceb5 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -94,8 +94,8 @@ pub fn builtin_presets() -> Vec { }), // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material preset("glTF PBR Metal Roughness", gltf_pbr_maps(|s| format!("$mesh_$textureSet_{s}"))), - // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material (R occlusion, G roughness, B metallic) and the base color, roughness, metallic and normal inputs of - // https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine + // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material + // Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine preset( "Unreal Engine (Packed)", vec![map("BaseColor", 8, base_with_alpha()), map("OcclusionRoughnessMetallic", 8, orm()), map("Normal", 8, normal(VirtualMap::NormalDirectX))], @@ -219,6 +219,77 @@ pub fn builtin_presets() -> Vec { map("clearcoatRoughness", 8, gray(ch(Channel::CoatRoughness, 0))), ], ), + // Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/subsurface-profile-shading-model-in-unreal-engine (the Opacity input masks the scattering, so the base color has no alpha) + preset( + "Unreal Engine Subsurface Profile (Packed)", + vec![ + map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("OcclusionRoughnessMetallic", 8, orm()), + map("Normal", 8, normal(VirtualMap::NormalDirectX)), + map("SubsurfaceMask", 8, gray(ch(Channel::ScatterWeight, 0))), + ], + ), + // Spec: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md (diffuse with alpha, specular RGB with glossiness in A) + preset( + "glTF Specular Glossiness (archived extension)", + vec![ + map("Diffuse", 8, base_with_alpha()), + map("SpecularGlossiness", 8, { + let mut specular_glossiness = rgb(|k| ch(Channel::Specular, k)); + specular_glossiness.push((Dest::A, ch(Channel::Glossiness, 0))); + specular_glossiness + }), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + map("Occlusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("Emissive", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), + // Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Standard_Material.html (the Standard Material inputs) + // Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Bump+Map.html (normal maps in OpenGL format) + preset("Redshift Standard Material (separate maps)", { + let gray8 = |name: &str, c: Channel| map(name, 8, gray(ch(c, 0))); + let rgb8 = |name: &str, c: Channel| map(name, 8, rgb(|k| ch(c, k))); + vec![ + rgb8("BaseColor", Channel::BaseColor), + gray8("Metalness", Channel::Metallic), + gray8("ReflectionRoughness", Channel::Roughness), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + rgb8("EmissionColor", Channel::Emissive), + gray8("Opacity", Channel::Opacity), + gray8("SubsurfaceWeight", Channel::ScatterWeight), + gray8("CoatWeight", Channel::CoatWeight), + gray8("CoatRoughness", Channel::CoatRoughness), + gray8("SheenWeight", Channel::SheenWeight), + rgb8("SheenColor", Channel::SheenColor), + gray8("SheenRoughness", Channel::SheenRoughness), + ] + }), + // Spec: https://create.roblox.com/docs/art/modeling/surface-appearance (ColorMap alpha is opacity) + // Spec: https://create.roblox.com/docs/art/modeling/texture-specifications (OpenGL normals only; grayscale metalness and roughness) + // Spec: https://create.roblox.com/docs/art/modeling/reimport (the file name suffix it assigns to each map) + preset( + "Roblox SurfaceAppearance (separate maps)", + vec![ + map("Color", 8, base_with_alpha()), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + map("Metalness", 8, gray(ch(Channel::Metallic, 0))), + map("Roughness", 8, gray(ch(Channel::Roughness, 0))), + ], + ), + // Spec: https://help.sketchfab.com/en/articles/16152630-pbr-maps (sRGB base color, linear grayscale metalness; no alpha, the docs don't say opacity reads it) + // Spec: https://help.sketchfab.com/en/articles/16152634-materials-pbr (roughness, AO and emission channels) + // Spec: https://help.sketchfab.com/en/articles/16152621-normal-map-bump-map (DirectX normals by default) + preset( + "Sketchfab Metalness (separate maps)", + vec![ + map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("Metalness", 8, gray(ch(Channel::Metallic, 0))), + map("Roughness", 8, gray(ch(Channel::Roughness, 0))), + map("Normal", 8, normal(VirtualMap::NormalDirectX)), + map("AmbientOcclusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("Emission", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", @@ -240,11 +311,27 @@ pub const DEFAULT_PRESET: &str = "Document channels + Normal + AO (No Alpha)"; /// scripts still use it). const OLD_DEFAULT_PRESET: &str = "Document channels + Normal + AO"; +/// Names introduced with the export update, which could previously belong to saved user presets. +pub const NEW_BUILTIN_PRESET_NAMES: [&str; 5] = [ + "Unreal Engine Subsurface Profile (Packed)", + "glTF Specular Glossiness (archived extension)", + "Redshift Standard Material (separate maps)", + "Roblox SurfaceAppearance (separate maps)", + "Sketchfab Metalness (separate maps)", +]; + +/// The immutable built-in templates shared by menu and command lookups. +pub fn builtin_preset_catalog() -> &'static [ExportPreset] { + static CATALOG: std::sync::LazyLock> = std::sync::LazyLock::new(builtin_presets); + &CATALOG +} + /// A built-in preset by name (case-insensitive). pub fn builtin_preset(name: &str) -> Option { let name = name.trim(); let name = if name.eq_ignore_ascii_case(OLD_DEFAULT_PRESET) { DEFAULT_PRESET } else { name }; - builtin_presets().into_iter().find(|p| p.name.eq_ignore_ascii_case(name)) + + builtin_preset_catalog().iter().find(|preset| preset.name.eq_ignore_ascii_case(name)).cloned() } /// Parse and validate a user preset. diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 5f3fbc1c..57c15011 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1386,7 +1386,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con let layer_id = layer.id.0; let keymap = app.ui.keymap.clone(); - // The row menu can act on several selected layers. A thumbnail identifies one layer. + // A thumbnail menu always acts on its own layer let several = if content_thumbnail { None } else { selection_with(app, layer.id) }; let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, params: Value, enabled: bool| { let mut button = egui::Button::new(label); @@ -1479,7 +1479,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con /// Mask management is available from the row and directly from the mask thumbnail. fn mask_management_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, mask_thumbnail: bool) { - // An instance inherits its source mask until it has its own. + // An instance inherits its source mask until it has its own let project = &app.session.doc.project; let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.as_ref()); let (has_mask, mask_on) = (mask.is_some(), mask.is_some_and(|mask| mask.enabled)); diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 7fd10cc4..aa7f223d 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -4,7 +4,7 @@ //! Maps dragged from the Input maps, Mesh maps and Converted maps panes onto an output map's //! channel swatches fill its channels. -use egui::{Color32, RichText, Ui, vec2}; +use egui::{Color32, Rect, RichText, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{BakedMap, Channel}; @@ -12,15 +12,20 @@ use texturecraft_engine::formats::export::{FILE_TOKENS, MAX_PRESET_NAME, sanitiz use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef, VirtualMap}; use crate::TextureCraftApp; +use crate::export_window::{ExportLook, GUTTER, TAB_ROW_HEIGHT, drawn, template_label}; use crate::i18n::{n_, tr, trf}; -use crate::theme::{Tokens, caption}; +use crate::theme::Tokens; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::{chip, icon_button_without_tooltip}; +use crate::widgets::chip; mod channel_target; mod map_drag; mod map_lists; +mod map_preview_cache; +mod map_preview_pictures; +mod output_card; mod pending_drop; +mod planned_output; mod row_edit; mod source_pick; mod swatch_look; @@ -28,83 +33,197 @@ mod swatch_look; pub use channel_target::ChannelTarget; use map_drag::MapDrag; use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; +use map_preview_cache::MapPreviewCache; +use map_preview_pictures::MapPreviewPictures; +use output_card::OutputCard; pub use pending_drop::PendingDrop; +use planned_output::PlannedOutput; use row_edit::RowEdit; use source_pick::SourcePick; use swatch_look::SwatchLook; -const ICON_POINTS: f32 = 20.0; -/// Width of the Presets list -const LIST_WIDTH_POINTS: f32 = 220.0; -/// The tab's width in the reference-size window: a narrower window narrows the side panes in -/// proportion, so the output rows keep their room -const REFERENCE_TAB_WIDTH_POINTS: f32 = 1085.0; -/// The middle column's least width, and room for the separators and their spacing -const MIN_OUTPUTS_WIDTH_POINTS: f32 = 200.0; -const SEPARATOR_ALLOWANCE_POINTS: f32 = 6.0; -/// Width of the Input maps pane -const INPUTS_WIDTH_POINTS: f32 = 170.0; -/// Width of the pane with Mesh maps above Converted maps -const SIDE_MAPS_WIDTH_POINTS: f32 = 165.0; -/// Share of the side pane's height that Mesh maps take; Converted maps get the rest -const MESH_MAPS_SHARE: f32 = 0.45; const RENAME_ID: &str = "exp_rename"; -/// The name "+" gives a new template, as in the reference +/// Initial name for a new template const NEW_PRESET: &str = "new_export_preset"; -/// Height of a Presets list row, and where its icon and name start -const PRESET_ROW_HEIGHT_POINTS: f32 = 18.0; -const PRESET_ICON_INDENT_POINTS: f32 = 2.0; -const PRESET_TEXT_INDENT_POINTS: f32 = 20.0; +// Layout in points from the window content's top left corner, the side panes from its right edge, measured on the locked mock -/// Height of a map list entry, the gap between entries, and where its marker and name sit -const ENTRY_HEIGHT_POINTS: f32 = 21.0; -const ENTRY_GAP_POINTS: f32 = 2.0; -const ENTRY_TEXT_INDENT_POINTS: f32 = 22.0; -const ENTRY_TEXT_SIZE_POINTS: f32 = 12.0; -const MARKER_INDENT_POINTS: f32 = 10.0; -const MARKER_SIZE_POINTS: f32 = 10.0; +/// Width of the Presets column +const PRESETS_WIDTH: f32 = 216.2; +/// Middle of the column titles +const HEADER_Y: f32 = 73.0; +/// Centre of the Presets header's first glyph, from the column's right edge +const PRESET_ICON_FROM_RIGHT: f32 = 14.0; +/// Step between the Presets header's glyphs +const PRESET_ICON_STEP: f32 = 22.0; +/// Size of the Presets header's glyphs +const PRESET_ICON_SIZE: f32 = 13.0; +/// Top of the lists under the titles +const LIST_TOP: f32 = 88.0; +/// Height of a Presets row +const PRESET_ROW_HEIGHT: f32 = 20.0; +/// Centre of a Presets row's file glyph +const PRESET_ICON_X: f32 = 16.0; +/// Where a Presets row's name starts +const PRESET_NAME_LEFT: f32 = 26.3; +/// Size of a Presets row's file glyph +const PRESET_ROW_ICON_SIZE: f32 = 12.0; +/// The column titles' left edge, inside their column +const TITLE_INDENT: f32 = 7.5; + +/// The middle column's margin to the dividers on both sides +const MIDDLE_MARGIN: f32 = 10.0; +/// Middle of the Current preset line +const CURRENT_PRESET_Y: f32 = 69.0; +/// Gap after "Current preset:" +const NAME_GAP: f32 = 5.0; +/// From the template's name to its lock's centre +const LOCK_GAP: f32 = 12.0; +/// Middle of the Output maps row +const OUTPUT_MAPS_Y: f32 = 106.0; +/// The air around a Create button's name +const CREATE_PADDING: f32 = 22.0; +/// Gap between the Create buttons +const CREATE_GAP: f32 = 6.0; +/// Gap before "Create:" +const CREATE_LABEL_GAP: f32 = 2.0; +/// Top of the first output map card +const CARDS_TOP: f32 = 127.0; +/// The count strip's top, above the body's bottom +const COUNT_TOP_ABOVE_BOTTOM: f32 = 24.0; +/// The count strip's bottom, above the body's bottom +const COUNT_BOTTOM_ABOVE_BOTTOM: f32 = 1.0; +/// The count's indent in its strip +const COUNT_TEXT_INDENT: f32 = 6.0; + +/// Height of an output map card +const CARD_HEIGHT: f32 = 48.0; +/// Gap below a card +const CARD_GAP: f32 = 6.0; +/// Corner radius of a card +const CARD_RADIUS: u8 = 3; +/// Inset of a card's swatches from its top and bottom +const CARD_INSET: f32 = 6.0; +/// Centre of a card's grip +const GRIP_X: f32 = 10.0; +/// Width of the grip's click area +const GRIP_WIDTH: f32 = 16.0; +/// Size of the grip's glyph +const GRIP_SIZE: f32 = 14.0; +/// Where a card's file name field starts +const NAME_FIELD_LEFT: f32 = 20.0; +/// Width of the file name field +const NAME_FIELD_WIDTH: f32 = 150.0; +/// The file name field's least width in a narrow window +const MIN_NAME_FIELD_WIDTH: f32 = 60.0; +/// Gap before the "$" button +const DOLLAR_GAP: f32 = 4.0; +/// Width of the "$" button +const DOLLAR_WIDTH: f32 = 22.0; +/// Gap between "$" and the swatches +const SWATCHES_GAP: f32 = 8.0; +/// The lists' and icons' rows, above and below the card's middle +const CARD_ROW_OFFSET: f32 = 10.0; +/// Centre of a card's icons, from its right edge +const CARD_ICON_FROM_RIGHT: f32 = 14.0; +/// From the icons to the lists' chevrons +const CARD_CHEVRON_STEP: f32 = 22.0; +/// Gap between a list's value and its chevron +const CARD_VALUE_GAP: f32 = 8.0; +/// Size of a card's icons +const CARD_ICON_SIZE: f32 = 12.0; +/// Values the cards' lists line up on, so cards with shorter ones keep the same column +const CARD_VALUE_SAMPLES: [&str; 3] = ["png", "8 bits", "16 bits"]; + +/// The Input maps divider, from the window's right edge +const INPUTS_DIVIDER_FROM_RIGHT: f32 = 342.3; +/// The Mesh maps divider, from the window's right edge +const SIDE_DIVIDER_FROM_RIGHT: f32 = 161.9; +/// Where the Input maps pane starts after its divider +const PANE_FROM_DIVIDER: f32 = 2.0; +/// Where it ends before the next one +const INPUTS_END_BEFORE_DIVIDER: f32 = 3.5; +/// Where the Mesh maps pane starts after its divider +const SIDE_PANE_FROM_DIVIDER: f32 = 4.0; +/// The divider between Mesh maps and Converted maps, below the body's middle +const SIDE_SPLIT_BELOW_MIDDLE: f32 = 10.0; +/// Gap between Mesh maps' last row and that divider +const MESH_BOTTOM_GAP: f32 = 6.0; +/// Middle of Converted maps' title, below the divider +const CONVERTED_TITLE_Y: f32 = 18.0; +/// Top of Converted maps' rows, below the divider +const CONVERTED_ROWS_TOP: f32 = 33.0; +/// A map entry's inset in its pane +const ENTRY_INSET: f32 = 3.0; +/// Height of a map entry +const ENTRY_HEIGHT: f32 = 20.0; +/// Pitch of the map entries +const ENTRY_PITCH: f32 = 21.0; +/// Height of a group's name row +const GROUP_HEIGHT: f32 = 18.0; +/// Indent of the titles and group names +const GROUP_INDENT: f32 = 4.0; +/// Where a used map's square starts +const MARKER_LEFT: f32 = 9.0; +/// Side of that square +const MARKER_SIZE: f32 = 10.0; +/// Its corner radius +const MARKER_RADIUS: u8 = 1; +/// How much lighter its edge is than its fill +const MARKER_EDGE_LIGHTEN: u8 = 40; +/// Where a map entry's name starts +const ENTRY_NAME_LEFT: f32 = 25.0; /// How strongly a map TextureCraft does not have yet is dimmed const UNAVAILABLE_FADE: f32 = 0.6; -/// An output map row: padding, gap below it, grip width, file name field width, icon size -const ROW_MARGIN_POINTS: f32 = 6.0; -const ROW_GAP_POINTS: f32 = 4.0; -const GRIP_WIDTH_POINTS: f32 = 5.0; -const NAME_FIELD_WIDTH_POINTS: f32 = 150.0; -const ROW_ICON_POINTS: f32 = 16.0; -/// Width the "Output maps" title and the Create buttons need on one row -const OUTPUT_MAPS_ROW_WIDTH_POINTS: f32 = 420.0; -/// The narrowest file name field, the "$" button and the format, bit depth and icon columns at a -/// row's right end, and the gaps between a row's controls (besides the swatches') -const MIN_NAME_FIELD_WIDTH_POINTS: f32 = 60.0; -const DOLLAR_BUTTON_WIDTH_POINTS: f32 = 22.0; -const ROW_LISTS_WIDTH_POINTS: f32 = 100.0; -const ROW_GAPS: f32 = 4.0; -/// The accent frame around a drop target: its stroke and its gap to the target +/// Naming pattern's info glyph, from the window's right edge +const NAMING_INFO_FROM_RIGHT: f32 = 20.8; +/// Its dropdown's left edge, from the window's right edge +const NAMING_COMBO_LEFT_FROM_RIGHT: f32 = 182.4; +/// Its dropdown's right edge, from the window's right edge +const NAMING_COMBO_RIGHT_FROM_RIGHT: f32 = 34.0; +/// Its label's right edge, from the window's right edge +const NAMING_LABEL_FROM_RIGHT: f32 = 188.0; +/// Size of the info glyph +const INFO_SIZE: f32 = 14.0; + +/// The accent-free frame around a drop target: its stroke and its gap to the target const DROP_HIGHLIGHT_STROKE_POINTS: f32 = 1.5; const DROP_HIGHLIGHT_GAP_POINTS: f32 = 2.0; /// Side of the corner mark of an inverted swatch const INVERTED_MARK_POINTS: f32 = 8.0; +/// A swatch's file preview: the file's width, and the side of each channel's picture beside it +const PREVIEW_FILE_WIDTH_POINTS: f32 = 150.0; +const PREVIEW_CHANNEL_WIDTH_POINTS: f32 = 34.0; -/// A channel swatch: its side, the label's size and offset from the top, and the bars that show -/// which channels of the source it reads -const SWATCH_SIZE_POINTS: f32 = 32.0; -const SWATCH_TEXT_SIZE_POINTS: f32 = 11.0; -const SWATCH_TEXT_TOP_POINTS: f32 = 3.0; -const SWATCH_BAR_WIDTH_POINTS: f32 = 18.0; -const SWATCH_BAR_HEIGHT_POINTS: f32 = 2.0; -const SWATCH_BAR_BOTTOM_POINTS: f32 = 9.0; +/// Width of a channel swatch; its height is the card's less its inset +const SWATCH_WIDTH: f32 = 34.0; +/// Gap between swatches +const SWATCH_GAP: f32 = 2.0; +/// Middle of a swatch's letters, from its top +const SWATCH_LABEL_Y: f32 = 11.0; +/// A swatch's underline: its inset from the sides +const SWATCH_BAR_INSET: f32 = 6.0; +/// Its top, from the swatch's bottom +const SWATCH_BAR_BOTTOM: f32 = 10.0; +/// Its height +const SWATCH_BAR_HEIGHT: f32 = 2.0; -/// Swatch colours: one hue per map, spread by the golden ratio so neighbours differ, muted to -/// keep the white label readable +/// Golden-ratio spacing keeps neighbouring map hues distinct const HUE_STEP: f32 = 0.618_034; const SWATCH_SATURATION: f32 = 0.45; -const SWATCH_VALUE_DARK: f32 = 0.42; -const SWATCH_VALUE_LIGHT: f32 = 0.62; +const SWATCH_VALUE: f32 = 0.42; -/// The bars of the R, G and B channels a swatch reads -const COMPONENT_COLORS: [Color32; 3] = [Color32::from_rgb(220, 70, 70), Color32::from_rgb(80, 190, 90), Color32::from_rgb(80, 120, 230)]; +/// The underline of R +const BAR_RED: Color32 = Color32::from_rgb(230, 70, 70); +/// The underline of G +const BAR_GREEN: Color32 = Color32::from_rgb(80, 200, 90); +/// The underline of B +const BAR_BLUE: Color32 = Color32::from_rgb(80, 130, 240); +/// The underline of A +const BAR_ALPHA: Color32 = Color32::from_rgb(220, 220, 220); +/// The underline of RGB and gray +const BAR_WHOLE: Color32 = Color32::WHITE; /// What a cleared channel writes: black, or opaque in the alpha channel const CLEARED_VALUE: f32 = 0.0; @@ -179,8 +298,6 @@ const CONSTANT_DRAG_SPEED: f64 = 0.005; /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; -/// Width of the Naming pattern list -const NAMING_PATTERN_WIDTH_POINTS: f32 = 150.0; /// `s` reading component `k` (only 3-component sources have more than one). fn with_component(s: &SourceRef, k: u8) -> SourceRef { @@ -336,43 +453,50 @@ enum MapAction { Remove(usize), } -/// The Output templates tab: template list, the selected template's outputs, then the Input maps -/// pane and the pane with Mesh maps above Converted maps. -pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { +pub(crate) fn clear_map_previews(ctx: &egui::Context) { + MapPreviewCache::clear(ctx); +} + +/// The Output templates tab in `body`: presets, outputs, Input maps, then Mesh maps above Converted maps +pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, body: Rect, builtins: &[ExportPreset]) { + // Four swatches and the type menu share a row between the two map panes + const MIN_EDITOR_WIDTH: f32 = 960.0; + const MIN_EDITOR_HEIGHT: f32 = CARDS_TOP + 2.0 * CARD_HEIGHT + COUNT_TOP_ABOVE_BOTTOM; + let minimum = vec2(MIN_EDITOR_WIDTH, MIN_EDITOR_HEIGHT); + if body.width() >= minimum.x && body.height() >= minimum.y { + template_panes(app, ui, body, builtins); + return; + } + + ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| { + egui::ScrollArea::both().id_salt("export_template_editor").auto_shrink([false; 2]).show(ui, |ui| { + let (content, _) = ui.allocate_exact_size(ui.available_size().max(minimum), egui::Sense::hover()); + template_panes(app, ui, content, builtins); + }); + }); +} + +fn template_panes(app: &mut TextureCraftApp, ui: &mut Ui, body: Rect, builtins: &[ExportPreset]) { sync_draft(app); - let height = ui.available_height(); + let top = body.top() - TAB_ROW_HEIGHT; let names = crate::export_window::template_groups(app, builtins).1; - let scale = (ui.available_width() / REFERENCE_TAB_WIDTH_POINTS).min(1.0); - let (list_width, inputs_width, side_width) = (LIST_WIDTH_POINTS * scale, INPUTS_WIDTH_POINTS * scale, SIDE_MAPS_WIDTH_POINTS * scale); - let mut list_action = None; - ui.vertical(|ui| { - ui.set_width(list_width); - ui.set_height(height); - list_action = preset_list(app, ui, &names); - }); - ui.separator(); - ui.vertical(|ui| { - // Leave room for the two map panes and three separators - let panes = inputs_width + side_width + 8.0 * ui.spacing().item_spacing.x + SEPARATOR_ALLOWANCE_POINTS; - ui.set_width((ui.available_width() - panes).max(MIN_OUTPUTS_WIDTH_POINTS)); - ui.set_height(height); - outputs(app, ui); - }); + let presets_right = body.left() + PRESETS_WIDTH; + let inputs_divider = body.right() - INPUTS_DIVIDER_FROM_RIGHT; + let side_divider = body.right() - SIDE_DIVIDER_FROM_RIGHT; + for x in [presets_right, inputs_divider, side_divider] { + drawn::divider(ui, Rect::from_min_max(pos2(x, body.top()), pos2(x + 1.0, body.bottom()))); + } + + let list_action = preset_list(app, ui, Rect::from_min_max(body.min, pos2(presets_right, body.bottom())), top, &names); + let middle = Rect::from_min_max(pos2(presets_right + 1.0 + MIDDLE_MARGIN, body.top()), pos2(inputs_divider - MIDDLE_MARGIN, body.bottom())); + ui.scope(|ui| outputs(app, ui, middle, top)); // The panes mark the maps the selected template's outputs read - let marked = marked_sources(app, &Tokens::get(ui.ctx())); - ui.separator(); - ui.vertical(|ui| { - ui.set_width(inputs_width); - ui.set_height(height); - input_maps(ui, &marked); - }); - ui.separator(); - ui.vertical(|ui| { - ui.set_width(side_width); - ui.set_height(height); - mesh_and_converted_maps(ui, height, &marked); - }); + let marked = marked_sources(app); + let inputs = Rect::from_min_max(pos2(inputs_divider + PANE_FROM_DIVIDER, body.top()), pos2(side_divider - INPUTS_END_BEFORE_DIVIDER, body.bottom())); + input_maps(ui, inputs, top, &marked); + let side = Rect::from_min_max(pos2(side_divider + SIDE_PANE_FROM_DIVIDER, body.top()), body.max); + mesh_and_converted_maps(ui, side, top, &marked); if let Some(a) = list_action { apply(app, ui.ctx(), a); } @@ -388,93 +512,105 @@ pub fn select(app: &mut TextureCraftApp, name: String) { } } -/// "Naming pattern" with its info icon, at the right end of the tab row (laid out right to left) -pub(crate) fn naming_pattern(ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { +/// "Naming pattern", its list and its info glyph at the tab row's right end +pub(crate) fn naming_pattern(ui: &mut Ui, window_right: f32, y: f32) { + let look = ExportLook::get(ui.ctx()); + let info_at = pos2(window_right - NAMING_INFO_FROM_RIGHT, y); + drawn::glyph(ui, info_at, ic::INFO, INFO_SIZE, look.text_dim); + let info = ui.interact(Rect::from_center_size(info_at, vec2(INFO_SIZE, INFO_SIZE)), ui.scope_id().with("exp_naming_info"), egui::Sense::hover()); + info.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, ic::INFO)); + info.on_hover_ui(|ui| { ui.label(tr("Choose how the input maps are named in this editor.")); ui.label(tr("The active texture set’s shader can affect the available map names.")); }); - egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH_POINTS).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { + let combo = drawn::control_rect(window_right - NAMING_COMBO_LEFT_FROM_RIGHT, window_right - NAMING_COMBO_RIGHT_FROM_RIGHT, y); + drawn::combo(ui, combo, "exp_naming", NAMING_PATTERNS[0], |ui| { for p in NAMING_PATTERNS { let _ = ui.selectable_label(true, p); } }); - ui.label(tr("Naming pattern")); + let label = tr("Naming pattern"); + let left = window_right - NAMING_LABEL_FROM_RIGHT - drawn::text_width(ui, label, false); + drawn::label_at(ui, left, y, label, look.text, false); } -/// The Presets list: the templates sorted by name (built-in and user); a right click offers -/// Rename, Duplicate and Remove, F2 renames -fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Option { +/// The Presets list in `column` with its header's tools; a right click offers Rename, Duplicate and Remove, F2 renames +fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32, names: &[String]) -> Option { + let look = ExportLook::get(ui.ctx()); let mut act = None; - let sel = app.ui.export.preset.clone(); + let selected_name = app.ui.export.preset.clone(); let user = app.ui.export.draft.is_some(); - ui.horizontal(|ui| { - ui.label(caption(tr("Presets"))); + drawn::label_at(ui, column.left() + TITLE_INDENT, top + HEADER_Y, tr("Presets"), look.text, true); - // Copy, "−" and "+" from left to right, without tooltips as in the reference - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON_POINTS).clicked() { - act = Some(ListAction::New); - } - if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON_POINTS)).inner.clicked() - { - act = Some(ListAction::Remove(sel.clone())); - } - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON_POINTS).clicked() { - act = Some(ListAction::Duplicate(sel.clone())); - } - - // TextureCraft's template files: a focusable menu, as the row's right click is pointer only - let actions = icon_button_without_tooltip(ui, ic::DOTS_THREE, tr("Template actions"), false, ICON_POINTS); - let opened_now = actions.clicked(); - egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); - }); - }); - ui.add_space(2.0); - if std::mem::take(&mut app.ui.export.rename_key) && user { - act = Some(ListAction::StartRename(sel.clone())); + // Template actions, Duplicate, "−" and "+" from left to right, without tooltips as in the reference + let icon_at = |slot_from_right: f32| pos2(column.right() - PRESET_ICON_FROM_RIGHT - slot_from_right * PRESET_ICON_STEP, top + HEADER_Y); + if drawn::icon_button(ui, icon_at(0.0), ic::PLUS, PRESET_ICON_SIZE, tr("New template"), true, false).clicked() { + act = Some(ListAction::New); } - egui::ScrollArea::vertical().id_salt("exp_presets").auto_shrink([false; 2]).show(ui, |ui| { - for name in names { - let is_user = app.session.export_presets.list.iter().any(|p| p.name == *name); - match app.ui.export.renaming.as_mut().filter(|_| *name == sel) { - Some(buf) => { - let r = ui.add(egui::TextEdit::singleline(buf).id(egui::Id::unique(RENAME_ID)).desired_width(f32::INFINITY)); - if r.lost_focus() { - act = Some(if ui.input(|i| i.key_pressed(egui::Key::Escape)) { - ListAction::Select(name.clone()) - } else { - ListAction::Rename(buf.clone()) + if drawn::icon_button(ui, icon_at(1.0), ic::MINUS, PRESET_ICON_SIZE, tr("Delete the selected template"), user, false).clicked() { + act = Some(ListAction::Remove(selected_name.clone())); + } + if drawn::icon_button(ui, icon_at(2.0), ic::COPY, PRESET_ICON_SIZE, tr("Duplicate the selected template"), true, false).clicked() { + act = Some(ListAction::Duplicate(selected_name.clone())); + } + + // TextureCraft's template files: a focusable menu, as the row's right click is pointer only + let actions = drawn::icon_button(ui, icon_at(3.0), ic::DOTS_THREE, PRESET_ICON_SIZE, tr("Template actions"), true, false); + let opened_now = actions.clicked(); + egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); + if std::mem::take(&mut app.ui.export.rename_key) && user { + act = Some(ListAction::StartRename(selected_name.clone())); + } + + // The rows scroll, the scroll bar in its strip at the column's right + let rows = Rect::from_min_max(pos2(column.left(), top + LIST_TOP), column.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + egui::ScrollArea::vertical().id_salt("exp_presets").auto_shrink([false; 2]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + let width = rows.width() - GUTTER; + for name in names { + let is_user = app.session.export_presets.list.iter().any(|preset| preset.name == *name); + let (rect, _) = ui.allocate_exact_size(vec2(width, PRESET_ROW_HEIGHT), egui::Sense::hover()); + match app.ui.export.renaming.as_mut().filter(|_| *name == selected_name) { + Some(name_buffer) => { + let field = egui::TextEdit::singleline(name_buffer).id(egui::Id::unique(RENAME_ID)).margin(vec2(PRESET_NAME_LEFT, 0.0)); + let rename_field = ui.put(rect, field); + if rename_field.lost_focus() { + act = Some(if ui.input(|input| input.key_pressed(egui::Key::Escape)) { + ListAction::Select(name.clone()) + } else { + ListAction::Rename(name_buffer.clone()) + }); + } + } + None => { + let label = template_label(&app.session, name); + let response = preset_row(ui, rect, name, label, *name == selected_name, is_user).on_hover_text(name); + if response.double_clicked() && is_user { + act = Some(ListAction::StartRename(name.clone())); + } else if response.clicked() { + act = Some(ListAction::Select(name.clone())); + } + response.context_menu(|ui| { + let read_only = tr("Built-in templates are read-only: duplicate one to edit it"); + if ui.add_enabled(is_user, egui::Button::new(tr("Rename"))).on_disabled_hover_text(read_only).clicked() { + act = Some(ListAction::StartRename(name.clone())); + } + if ui.button(tr("Duplicate")).clicked() { + act = Some(ListAction::Duplicate(name.clone())); + } + if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { + act = Some(ListAction::Remove(name.clone())); + } + + // TextureCraft's template files, after the reference's entries + ui.separator(); + template_file_items(ui, &mut act, *name == selected_name, false); }); } } - None => { - let r = preset_row(ui, name, *name == sel).on_hover_text(name); - if r.double_clicked() && is_user { - act = Some(ListAction::StartRename(name.clone())); - } else if r.clicked() { - act = Some(ListAction::Select(name.clone())); - } - r.context_menu(|ui| { - let read_only = tr("Built-in templates are read-only: duplicate one to edit it"); - if ui.add_enabled(is_user, egui::Button::new(tr("Rename"))).on_disabled_hover_text(read_only).clicked() { - act = Some(ListAction::StartRename(name.clone())); - } - if ui.button(tr("Duplicate")).clicked() { - act = Some(ListAction::Duplicate(name.clone())); - } - if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { - act = Some(ListAction::Remove(name.clone())); - } - - // TextureCraft's template files, after the reference's entries - ui.separator(); - template_file_items(ui, &mut act, *name == sel, false); - }); - } } - } + }); }); act } @@ -497,25 +633,23 @@ fn template_file_items(ui: &mut Ui, act: &mut Option, with_export: b } } -/// A Presets list row: a document icon and the name (cut with "…" when long), the selected one in -/// the accent colour -fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT_POINTS), egui::Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); - +/// A Presets row: a locked file glyph for a built-in template, the name cut with "…", the selected one in bold +fn preset_row(ui: &mut Ui, rect: Rect, name: &str, label: &str, selected: bool, is_user: bool) -> egui::Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("exp_preset_row", name)), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, label)); let painter = ui.painter(); - if response.hovered() { - painter.rect_filled(rect, tokens.radius, tokens.row_hover); + if selected { + painter.rect_filled(rect, 0.0, look.chrome); + } else if response.hovered() { + painter.rect_filled(rect, 0.0, look.raised); } - let font = egui::TextStyle::Body.resolve(ui.style()); - painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT_POINTS, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); - let color = if selected { tokens.accent } else { tokens.text }; - let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font, color); - job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT_POINTS); - let galley = painter.layout_job(job); - let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT_POINTS, rect.center().y - galley.size().y / 2.0); - painter.galley(top_left, galley, color); + let icon = if is_user { ic::FILE_TEXT } else { ic::FILE_LOCK }; + drawn::glyph(ui, pos2(rect.left() + PRESET_ICON_X, rect.center().y), icon, PRESET_ROW_ICON_SIZE, look.text_dim); + let shown = drawn::fitted(ui, label, rect.width() - PRESET_NAME_LEFT, false, selected); + let color = if selected { look.text } else { look.list_text }; + drawn::text_at(ui, rect.left() + PRESET_NAME_LEFT, rect.center().y, &shown, color, selected); + drawn::paint_focus(ui, &response); response } @@ -549,7 +683,7 @@ fn perform(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) { } ListAction::Duplicate(name) => { if let Some(p) = app.session.export_preset(&name) { - let name = format!("{}_copy", p.name).chars().take(MAX_PRESET_NAME).collect(); + let name = format!("{}_copy", template_label(&app.session, &name)).chars().take(MAX_PRESET_NAME).collect(); save_new(app, &ExportPreset { name, ..p }); } } @@ -733,9 +867,9 @@ pub fn load_library(app: &mut TextureCraftApp, storage: Option<&dyn eframe::Stor app.session.log.warnings(texturecraft_engine::log::LIBRARY_SOURCE, skipped.into_iter().map(|w| format!("Export template skipped: {w}"))); } #[cfg(target_arch = "wasm32")] - for p in storage.and_then(|s| eframe::get_value::>(s, STORAGE_KEY)).unwrap_or_default() { - if let Ok(v) = serde_json::to_value(&p) { - app.run("export.preset.save", json!({ "preset": v, "unique": true })); + for preset in storage.and_then(|s| eframe::get_value::>(s, STORAGE_KEY)).unwrap_or_default() { + if let Err(error) = app.session.export_presets.restore(preset) { + app.session.log.warnings(texturecraft_engine::log::LIBRARY_SOURCE, [format!("Export template skipped: {error}")]); } } } @@ -751,89 +885,105 @@ pub fn save_library(app: &TextureCraftApp, storage: &mut dyn eframe::Storage) { let _ = (app, storage); } -/// The selected template's output maps (editable for user templates). -fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The selected template's output maps in `column`, editable for user templates +fn outputs(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32) { + let look = ExportLook::get(ui.ctx()); let tokens = Tokens::get(ui.ctx()); let (mut preset, editable) = match (&app.ui.export.draft, selected(app)) { (Some(d), _) => (d.clone(), true), (None, Some(b)) => (b, false), (None, None) => { - ui.label(RichText::new(tr("Select an output template")).color(tokens.text_dim)); + MapPreviewCache::clear(ui.ctx()); + drawn::label_at(ui, column.left(), top + CURRENT_PRESET_Y, tr("Select an output template"), look.text_dim, false); return; } }; - let preview = preview_names(app, &preset); + let params = plan_params(app, &preset); + let preview = match ¶ms { + Ok(params) => MapPreviewCache::plan(app, ui.ctx(), params), + Err(error) => { + MapPreviewCache::clear(ui.ctx()); + Err(error.clone()) + } + }; let mut edit = RowEdit::default(); - // The selected template in a strip, "Current preset:" in bold - egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Current preset:")).strong().color(tokens.text_strong)); - ui.label(&preset.name); - if !editable { - ui.label(RichText::new(ic::LOCK_SIMPLE).color(tokens.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); - } - }); - }); + // "Current preset:" in bold, the template's name, a lock on a built-in one + let y = top + CURRENT_PRESET_Y; + let title = tr("Current preset:"); + let name_left = column.left() + drawn::text_width(ui, title, true) + NAME_GAP; + drawn::label_at(ui, column.left(), y, title, look.text, true); + let name = drawn::label_at(ui, name_left, y, template_label(&app.session, &app.ui.export.preset), look.text, false); + if !editable { + let lock_at = pos2(name.rect.right() + LOCK_GAP, y); + drawn::glyph(ui, lock_at, ic::LOCK_SIMPLE, CARD_ICON_SIZE, look.text_dim); + let lock = + ui.interact(Rect::from_center_size(lock_at, vec2(CARD_ICON_SIZE, CARD_ICON_SIZE)), ui.scope_id().with("exp_preset_lock"), egui::Sense::hover()); + lock.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Read-only template"))); + lock.on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); + } - // "Output maps", with the Create buttons at the right end of the same row, or of the next one - // when the column is too narrow for both - let create_buttons = |ui: &mut Ui, edit: &mut RowEdit| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.add_enabled_ui(editable, |ui| { - for (label, layout, split, file) in CREATE.iter().rev() { - if ui.button(tr(label)).clicked() { - edit.action = Some(MapAction::Add(*layout, *split, file)); - } - } - ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); - }); - }); - }; - if ui.available_width() >= OUTPUT_MAPS_ROW_WIDTH_POINTS { - ui.horizontal(|ui| { - ui.label(caption(tr("Output maps"))); - create_buttons(ui, &mut edit); - }); - } else { - ui.label(caption(tr("Output maps"))); - ui.horizontal(|ui| create_buttons(ui, &mut edit)); - } - if let Err(e) = &preview { - ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tokens.danger).size(11.0)); + // A built-in template's cards and buttons keep their full look: the lock says they are read-only + ui.visuals_mut().disabled_alpha = 1.0; + let y = top + OUTPUT_MAPS_Y; + drawn::label_at(ui, column.left(), y, tr("Output maps"), look.text, true); + let mut right = column.right(); + for (label, layout, split, file) in CREATE.iter().rev() { + let width = drawn::text_width(ui, tr(label), false) + CREATE_PADDING; + if drawn::button(ui, drawn::control_rect(right - width, right, y), tr(label), false, editable).clicked() { + edit.action = Some(MapAction::Add(*layout, *split, file)); + } + right -= width + CREATE_GAP; } + let create = tr("Create:"); + drawn::label_at(ui, right - CREATE_LABEL_GAP - drawn::text_width(ui, create, false), y, create, look.text, false); + let mut changed = false; let map_count = preset.maps.len(); let mut split = app.ui.export.draft_split.clone(); split.resize(map_count, false); - // Leave room for the footer text and the framed count below - let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN_POINTS; - egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).max_height((ui.available_height() - footer).max(60.0)).show(ui, |ui| { - ui.add_enabled_ui(editable, |ui| { - // Every row takes the column's width, not the width a wider row before it left - let row_width = ui.available_width(); - for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { - let file = preview.as_ref().ok().and_then(|names| names.get(index).cloned().flatten()); - let planned = match file { - Some(file) => format!("{} {file}", ic::ARROW_RIGHT), - None => tr("Not exported: no source in this texture set").to_string(), - }; - changed |= ui.allocate_ui(vec2(row_width, 0.0), |ui| output_row(ui, index, map_count, map, row_split, &planned, &mut edit)).inner; - ui.add_space(ROW_GAP_POINTS); - } + // The cards scroll between the header and the count strip; their lists line up on one column + let strip = + Rect::from_min_max(pos2(column.left(), column.bottom() - COUNT_TOP_ABOVE_BOTTOM), pos2(column.right(), column.bottom() - COUNT_BOTTOM_ABOVE_BOTTOM)); + let cards = Rect::from_min_max(pos2(column.left(), top + CARDS_TOP), pos2(column.right(), strip.top() - CARD_GAP)); + let values = + preset.maps.iter().flat_map(|map| [map.format.extension().to_string(), crate::export_window::depth_label(Some(map.format), map.bit_depth, false)]); + let value_width = values.chain(CARD_VALUE_SAMPLES.map(str::to_string)).map(|value| drawn::text_width(ui, &value, false)).fold(0.0, f32::max); + ui.scope_builder(egui::UiBuilder::new().max_rect(cards), |ui| { + egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).show(ui, |ui| { + let height = map_count as f32 * (CARD_HEIGHT + CARD_GAP); + let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::hover()); + ui.add_enabled_ui(editable, |ui| { + for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { + let planned = preview.as_ref().ok().and_then(|outputs| outputs.get(index)).and_then(Option::as_ref); + let top = area.top() + index as f32 * (CARD_HEIGHT + CARD_GAP); + let card = Rect::from_min_size(pos2(area.left(), top), vec2(area.width(), CARD_HEIGHT)); + let row = OutputCard { index, count: map_count, value_width }; + changed |= output_row(ui, card, &row, map, row_split, planned, &mut edit); + } + }); }); }); - ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); - // Count only maps that have sources in the current set - if let Ok(names) = &preview { - let exported = names.iter().flatten().count(); - egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); - }); + // The hovered output's pictures show from the next frame on + if let (Some(index), Ok(params), Ok(plan)) = (edit.hovered_output, ¶ms, &preview) + && plan.get(index).is_some_and(Option::is_some) + { + MapPreviewCache::fill(app, ui.ctx(), params, index); + } + + // Count only maps that have sources in the current set; an edit that cannot be saved says why there + ui.painter().rect_filled(strip, 0.0, look.control); + let text_left = strip.left() + COUNT_TEXT_INDENT; + match &preview { + Ok(planned) => { + let exported = planned.iter().flatten().count(); + drawn::label_at(ui, text_left, strip.center().y, &trf("{n} output maps will be exported", &[("n", &exported)]), look.text, false); + } + Err(e) => { + drawn::label_at(ui, text_left, strip.center().y, &trf("Not saved: {error}", &[("error", e)]), tokens.danger, false); + } } if !editable { return; @@ -916,92 +1066,157 @@ fn commit(app: &mut TextureCraftApp, preset: ExportPreset, mut origin: Vec Result>, String> { - let mut p = crate::export_window::set_params(app, app.session.ts()); - p["preset"] = serde_json::to_value(preset).map_err(|e| e.to_string())?; +/// The `export.plan` and `export.preview` params of `preset` for the current texture set with the window's settings +fn plan_params(app: &TextureCraftApp, preset: &ExportPreset) -> Result { + let mut params = crate::export_window::set_params(app, app.session.ts()); + let export = &app.ui.export; + let same_template = params.get("preset").and_then(Value::as_str) == Some(export.preset.as_str()); - // The set's map overrides apply only to its own template - if let Some(p) = p.as_object_mut() { - p.remove("maps"); + if !same_template && let Some(params) = params.as_object_mut() { + params.remove("maps"); + } else if let (Some(_), Some(maps)) = (&export.draft, params.get_mut("maps").and_then(Value::as_array_mut)) { + // Draft positions have no override until they map to a saved output + maps.retain_mut(|settings| { + let Some(saved_index) = settings["map"].as_u64().and_then(|index| usize::try_from(index).ok()) else { return false }; + let Some(draft_index) = export.draft_maps.iter().position(|origin| *origin == Some(saved_index)) else { return false }; + + settings["map"] = json!(draft_index); + true + }); } - let plan = texturecraft_engine::execute(&mut app.session, "export.plan", &p).map_err(|e| e.to_string())?; - let mut names = vec![None; preset.maps.len()]; - for f in plan.as_array().into_iter().flatten() { - let map = f.get("map").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); - if let (Some(slot), Some(file)) = (map.and_then(|i| names.get_mut(i)), f.get("file").and_then(Value::as_str)) { - *slot = Some(file.to_string()); - } - } - Ok(names) + + params["preset"] = serde_json::to_value(preset).map_err(|error| error.to_string())?; + Ok(params) } -/// One output map row: drag grip, file name, "$", the channel swatches, then file type, bit depth, -/// duplicate and remove. `planned` is the file it writes for the current texture set. -fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: &mut bool, planned: &str, edit: &mut RowEdit) -> bool { - let tokens = Tokens::get(ui.ctx()); - let mut changed = false; - let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); +/// The file each map of `params`' template writes for the texture set (None: no sources), via `export.plan`; a PSD's maps each get the file and their layer +fn planned_outputs(app: &mut TextureCraftApp, params: &Value) -> Result>, String> { + let plan = texturecraft_engine::execute(&mut app.session, "export.plan", params).map_err(|e| e.to_string())?; + let map_count = params.pointer("/preset/maps").and_then(Value::as_array).map_or(0, Vec::len); + let index = |value: &Value| value.get("map").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); - // The name field gives way in a narrow window, so the swatches and lists stay in the row - let swatches = swatch_targets(map, *split).len() as f32; - let spacing = ui.spacing().item_spacing.x; - let others = GRIP_WIDTH_POINTS + DOLLAR_BUTTON_WIDTH_POINTS + swatches * (SWATCH_SIZE_POINTS + spacing) + ROW_LISTS_WIDTH_POINTS; - let name_width = (ui.available_width() - others - ROW_GAPS * spacing).clamp(MIN_NAME_FIELD_WIDTH_POINTS, NAME_FIELD_WIDTH_POINTS); + let mut outputs: Vec> = vec![None; map_count]; + let tile_files = tr("UV tile files"); + for file in plan.as_array().into_iter().flatten() { + let Some(name) = file.get("file").and_then(Value::as_str) else { continue }; - grip(ui, index, count, edit); - let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(name_width)).on_hover_ui(|ui| { - ui.label(tr("File name without extension; variables insert names")); - ui.label(planned); + let tiled = file["tile"].is_number(); + let display_name = if tiled { file["udimPattern"].as_str().unwrap_or(tile_files) } else { name }; + let mut remember = |entry: &Value, layer_name: Option<&str>| { + let Some(slot) = index(entry).and_then(|index| outputs.get_mut(index)) else { return }; + + if let Some(previous) = slot { + // Some disambiguated or truncated paths have no common tile pattern + if tiled && previous.file != display_name && previous.file != tile_files { + previous.file = tile_files.into(); + } + return; + } + + *slot = Some(PlannedOutput { + file: match layer_name { + Some(layer_name) if !tiled => format!("{name} › {layer_name}"), + _ => display_name.to_owned(), + }, + tiled, + size: file.get("size").and_then(Value::as_u64).unwrap_or(0), + format: file.get("format").and_then(Value::as_str).and_then(FileFormat::from_extension), + bit_depth: file.get("bitDepth").and_then(Value::as_u64).and_then(|depth| u8::try_from(depth).ok()).unwrap_or(0), + dithering: file.get("dithering").and_then(Value::as_bool).unwrap_or(false), }); - changed |= name.changed(); - changed |= token_menu(ui, &mut map.file); - changed |= channel_swatches(ui, index, map, split, edit); - - // The lists and icons at the row's right end: file format and duplicate, bit depth and remove - ui.add_space((ui.available_width() - ROW_LISTS_WIDTH_POINTS).max(0.0)); - ui.vertical(|ui| { - ui.horizontal(|ui| { - changed |= format_menu(ui, map); - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON_POINTS).clicked() { - edit.action = Some(MapAction::Duplicate(index)); - } - }); - ui.horizontal(|ui| { - changed |= depth_menu(ui, map); - if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON_POINTS).clicked() { - edit.action = Some(MapAction::Remove(index)); - } - }); - }); - }); - }); - - // Another row's grip dropped here moves that row here (the type check keeps a map list drop) - let row = frame.response; - let row_dragged_over = row.dnd_hover_payload::().is_some_and(|from| from.0 != index); - if row_dragged_over { - drop_highlight(ui, row.rect, &tokens); + }; + match file.get("layers").and_then(Value::as_array).filter(|layers| !layers.is_empty()) { + Some(layers) => { + for layer in layers { + remember(layer, layer.get("name").and_then(Value::as_str)); + } + } + None => remember(file, None), + } } - if row_dragged_over && let Some(from) = row.dnd_release_payload::() { + + Ok(outputs) +} + +/// One output map card: grip, file name, "$", swatches, then file type over bit depth beside duplicate and remove +fn output_row(ui: &mut Ui, card: Rect, row: &OutputCard, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { + let look = ExportLook::get(ui.ctx()); + let index = row.index; + + // The card takes a dragged row before its controls, which sit above it + let card_response = ui.interact(card, ui.scope_id().with(("exp_card", index)), egui::Sense::hover()); + ui.painter().rect_filled(card, CARD_RADIUS, look.control); + let mid = card.center().y; + let mut changed = false; + grip(ui, Rect::from_center_size(pos2(card.left() + GRIP_X, mid), vec2(GRIP_WIDTH, card.height())), index, row.count, edit); + + // The name field gives way in a narrow window, so the swatches and lists keep their room + let swatches_width = swatch_targets(map, *split).len() as f32 * (SWATCH_WIDTH + SWATCH_GAP); + let lists_width = CARD_ICON_FROM_RIGHT + CARD_CHEVRON_STEP + CARD_VALUE_GAP + row.value_width + SWATCHES_GAP; + let room = card.width() - NAME_FIELD_LEFT - DOLLAR_GAP - DOLLAR_WIDTH - SWATCHES_GAP - swatches_width - lists_width; + let name_width = room.clamp(MIN_NAME_FIELD_WIDTH, NAME_FIELD_WIDTH); + let name_rect = drawn::control_rect(card.left() + NAME_FIELD_LEFT, card.left() + NAME_FIELD_LEFT + name_width, mid); + changed |= name_field(ui, name_rect, index, &mut map.file, planned); + let dollar = drawn::control_rect(name_rect.right() + DOLLAR_GAP, name_rect.right() + DOLLAR_GAP + DOLLAR_WIDTH, mid); + changed |= token_menu(ui, dollar, index, &mut map.file); + let swatches = Rect::from_min_max(pos2(dollar.right() + SWATCHES_GAP, card.top() + CARD_INSET), pos2(card.right(), card.bottom() - CARD_INSET)); + changed |= channel_swatches(ui, swatches, index, map, split, planned, edit); + + // The right block: file type over bit depth on one column, duplicate over remove beside them + let icon_x = card.right() - CARD_ICON_FROM_RIGHT; + let chevron_x = icon_x - CARD_CHEVRON_STEP; + let value_left = chevron_x - CARD_VALUE_GAP - row.value_width; + let (upper, lower) = (mid - CARD_ROW_OFFSET, mid + CARD_ROW_OFFSET); + changed |= format_menu(ui, (value_left, chevron_x, upper), index, map); + changed |= depth_menu(ui, (value_left, chevron_x, lower), index, map); + let duplicate = trf("Duplicate output {number}", &[("number", &(index + 1))]); + if drawn::icon_button(ui, pos2(icon_x, upper), ic::COPY, CARD_ICON_SIZE, &duplicate, ui.is_enabled(), false).clicked() { + edit.action = Some(MapAction::Duplicate(index)); + } + let remove = trf("Remove output {number}", &[("number", &(index + 1))]); + if drawn::icon_button(ui, pos2(icon_x, lower), ic::X, CARD_ICON_SIZE, &remove, ui.is_enabled(), false).clicked() { + edit.action = Some(MapAction::Remove(index)); + } + + // Another card's grip dropped here moves that card here (the type check keeps a map list drop) + let row_dragged_over = card_response.dnd_hover_payload::().is_some_and(|from| from.0 != index); + if row_dragged_over { + drop_highlight(ui, card); + } + if row_dragged_over && let Some(from) = card_response.dnd_release_payload::() { edit.action = Some(MapAction::Move { from: from.0, to: index }); } changed } -/// The grip at a row's left: drag it onto another row to move the map there; the arrow keys and -/// its right-click menu move it one place -fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { - let tokens = Tokens::get(ui.ctx()); +/// The file name field; until it is typed in it shows the name's end, cut with "…"; true when it changed +fn name_field(ui: &mut Ui, rect: Rect, index: usize, file: &mut String, planned: Option<&PlannedOutput>) -> bool { + let look = ExportLook::get(ui.ctx()); + let id = ui.scope_id().with(("exp_map_name", index)); + let typing = ui.memory(|memory| memory.has_focus(id)); + let text_color = if typing { look.text } else { Color32::TRANSPARENT }; + let field = egui::TextEdit::singleline(file).id(id).margin(vec2(drawn::VALUE_INSET, 0.0)).background_color(look.control).text_color(text_color); + let response = ui.put(rect, field).on_hover_ui(|ui| { + ui.label(tr("File name without extension; variables insert names")); + ui.label(planned_text(planned)); + }); + if !typing { + let shown = drawn::fitted(ui, file, rect.width() - 2.0 * drawn::VALUE_INSET, true, false); + let color = if drawn::looks_disabled(ui, ui.is_enabled()) { look.text_dim } else { look.text }; + drawn::text_at(ui, rect.left() + drawn::VALUE_INSET, rect.center().y, &shown, color, false); + } + response.changed() +} + +/// A card's grip: drag it onto another card, or use the arrow keys or its menu, to move the map +fn grip(ui: &mut Ui, rect: Rect, index: usize, count: usize, edit: &mut RowEdit) { + let look = ExportLook::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click_and_drag()); + let response = ui.interact(rect, ui.scope_id().with(("exp_grip", index)), if enabled { egui::Sense::click_and_drag() } else { egui::Sense::hover() }); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tr("Reorder"))); - let color = if response.hovered() || response.dragged() { tokens.text } else { tokens.text_dim }; - ui.painter().rect_filled(rect, 1.0, color); + let color = if enabled && (response.hovered() || response.dragged()) { look.text } else { look.text_dim }; + drawn::glyph(ui, rect.center(), ic::DOTS_SIX_VERTICAL, GRIP_SIZE, color); + drawn::paint_focus(ui, &response); let response = response.on_hover_cursor(egui::CursorIcon::Grab); response.dnd_set_drag_payload(MapDrag(index)); @@ -1030,10 +1245,12 @@ fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { } } -/// The "$" button: the file name variables in the reference's order, then $channel -fn token_menu(ui: &mut Ui, file: &mut String) -> bool { +/// The "$" button in `rect`: the file name variables in the reference's order, then $channel +fn token_menu(ui: &mut Ui, rect: Rect, index: usize, file: &mut String) -> bool { let mut changed = false; - let menu = ui.menu_button("$", |ui| { + let id = ui.scope_id().with(("exp_tokens", index)); + let button = drawn::button_with_id(ui, id, rect, "$", "$", false, ui.is_enabled()).on_hover_text(tr("Insert a variable")); + egui::Popup::menu(&button).show(|ui| { let mut add = |ui: &mut Ui, token: &str| { if ui.button(RichText::new(token).monospace()).clicked() { file.push_str(token); @@ -1052,14 +1269,15 @@ fn token_menu(ui: &mut Ui, file: &mut String) -> bool { add(ui, token); } }); - menu.response.on_hover_text(tr("Insert a variable")); changed } -/// The file type menu of an output map ("png˅") -fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { +/// The file type menu of an output map ("png ⌄") at `place`: (value's left, chevron's centre, middle) +fn format_menu(ui: &mut Ui, (left, chevron, y): (f32, f32, f32), index: usize, map: &mut MapSpec) -> bool { let mut changed = false; - let menu = ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { + let id = ui.scope_id().with(("exp_map_format", index)); + let menu = drawn::text_dropdown(ui, id, left, chevron, y, map.format.extension()).on_hover_text(tr("File format")); + egui::Popup::menu(&menu).show(|ui| { for extension in MAP_FILE_TYPES { let Some(format) = FileFormat::from_extension(extension) else { ui.add_enabled(false, egui::Button::selectable(false, extension)).on_disabled_hover_text(tr(NOT_AVAILABLE)); @@ -1077,16 +1295,17 @@ fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); - menu.response.on_hover_text(tr("File format")); changed } -/// The bit depth menu of an output map ("8 bits˅"); templates do not keep dithering yet -fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { +/// The bit depth menu of an output map ("8 bits ⌄"); templates do not keep dithering yet +fn depth_menu(ui: &mut Ui, (left, chevron, y): (f32, f32, f32), index: usize, map: &mut MapSpec) -> bool { let format = map.format; let mut changed = false; let shown = crate::export_window::depth_label(Some(format), map.bit_depth, false); - let menu = ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { + let id = ui.scope_id().with(("exp_map_depth", index)); + let menu = drawn::text_dropdown(ui, id, left, chevron, y, &shown).on_hover_text(tr("Bit depth")); + egui::Popup::menu(&menu).show(|ui| { for (depth, dithering) in crate::export_window::depth_options(format) { let label = crate::export_window::depth_label(Some(format), depth, dithering); if dithering { @@ -1098,7 +1317,6 @@ fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); - menu.response.on_hover_text(tr("Bit depth")); changed } @@ -1239,8 +1457,8 @@ fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget, inve } } -/// The colour of a map on swatches and list markers (None for constants) -fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { +/// A map's colour on swatches and list markers (None for constants) +fn source_color(source: &SourceRef) -> Option { let channels = Channel::ALL.len(); let converted = VirtualMap::ALL.len(); let index = match source { @@ -1249,28 +1467,88 @@ fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { SourceRef::Baked { map, .. } => channels + converted + BakedMap::ALL.iter().position(|m| m == map)?, SourceRef::Constant(_) => return None, }; + let hue = (index as f32 * HUE_STEP).fract(); - let value = if tokens.dark { SWATCH_VALUE_DARK } else { SWATCH_VALUE_LIGHT }; - Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, value, 1.0).into()) + Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, SWATCH_VALUE, 1.0).into()) } -/// The bars under a swatch's letters: red, green and blue for a colour map's RGB, else the one -/// channel read (white for gray) -fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { - match source { - SourceRef::Constant(_) => Vec::new(), - _ if source.components() == 3 && target == ChannelTarget::Rgb && rgb_spread(map) => COMPONENT_COLORS.to_vec(), - _ if source.components() == 3 => COMPONENT_COLORS.get(usize::from(component_of(source))).copied().into_iter().collect(), - _ => vec![tokens.text_strong], +/// The underline of a swatch: the colour of the channel its letters name (white for RGB and gray) +fn swatch_bar(target: ChannelTarget) -> Color32 { + match target { + ChannelTarget::One(Dest::R) => BAR_RED, + ChannelTarget::One(Dest::G) => BAR_GREEN, + ChannelTarget::One(Dest::B) => BAR_BLUE, + ChannelTarget::One(Dest::A) => BAR_ALPHA, + ChannelTarget::Rgb | ChannelTarget::One(Dest::L) => BAR_WHOLE, } } -/// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel -/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. -fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { +/// "→ ", or why the output writes nothing +fn planned_text(planned: Option<&PlannedOutput>) -> String { + match planned { + Some(planned) => format!("{} {}", ic::ARROW_RIGHT, planned.file), + None => tr("Not exported: no source in this texture set").to_string(), + } +} + +/// Below a swatch's tooltip: the file its output writes, each channel with its source, then the file's size and type (built-in templates' swatches show it too) +fn output_preview(ui: &mut Ui, index: usize, map: &MapSpec, planned: Option<&PlannedOutput>) { let tokens = Tokens::get(ui.ctx()); + ui.separator(); + let Some(planned) = planned else { + ui.label(RichText::new(planned_text(None)).color(tokens.text_dim)); + return; + }; + + let title = if planned.tiled { trf("Atlas preview: {file}", &[("file", &planned.file)]) } else { planned.file.clone() }; + ui.label(RichText::new(title).color(tokens.text_strong)); + if let Some(Some(pictures)) = MapPreviewCache::get(ui.ctx(), index) { + preview_pictures(ui, map, &pictures); + } + + let file_type = planned.format.map_or("", FileFormat::extension); + let depth = crate::export_window::depth_label(planned.format, planned.bit_depth, planned.dithering); + let details = if planned.tiled { format!("{file_type} {depth}") } else { format!("{size} x {size} · {file_type} {depth}", size = planned.size) }; + ui.label(RichText::new(details).color(tokens.text_dim)); +} + +/// The file's picture with each channel's grey picture, letter and source beside it +fn preview_pictures(ui: &mut Ui, map: &MapSpec, pictures: &MapPreviewPictures) { + let tokens = Tokens::get(ui.ctx()); + let picture = |texture, width: f32| egui::Image::new(texture).fit_to_exact_size(vec2(width, width * pictures.aspect)).corner_radius(tokens.radius); + ui.horizontal_top(|ui| { + ui.add(picture(&pictures.file, PREVIEW_FILE_WIDTH_POINTS)); + if pictures.channels.is_empty() { + return; + } + + ui.vertical(|ui| { + for (dest, texture) in &pictures.channels { + let target = ChannelTarget::One(*dest); + let gray = ChannelTarget::One(Dest::L); + let source_target = match dest { + Dest::R | Dest::G | Dest::B if source_of(map, gray).is_some() => gray, + _ => target, + }; + let fallback = SourceRef::Constant(if *dest == Dest::A { CLEARED_ALPHA } else { CLEARED_VALUE }); + let source = source_of(map, source_target).unwrap_or(&fallback); + let inverted = source_target.dests().iter().any(|dest| map.inverted.contains(dest)); + + ui.horizontal(|ui| { + ui.add(picture(texture, PREVIEW_CHANNEL_WIDTH_POINTS)); + ui.label(RichText::new(target_label(target)).color(tokens.text_strong)); + ui.label(RichText::new(swatch_tooltip(map, source, source_target, inverted)).color(tokens.text_dim)); + }); + } + }); + }); +} + +/// A card's channel swatches from `area`'s left: drop targets for the map lists, with click and right-click menus +fn channel_swatches(ui: &mut Ui, area: Rect, index: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { let mut changed = false; let shows_split = *split || !rgb_collapsed(map); + let mut left = area.left(); for (slot, target) in swatch_targets(map, *split).into_iter().enumerate() { let Some(source) = source_of(map, target).cloned() else { continue }; @@ -1281,18 +1559,27 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo if inverted { name = trf("{swatch}, inverted", &[("swatch", &name)]); } - let look = SwatchLook { fill: source_color(&source, &tokens), bars: swatch_bars(map, &source, target, &tokens), inverted }; - let response = swatch(ui, label, &name, &look).on_hover_ui(|ui| { + let constant = matches!(source, SourceRef::Constant(_)); + let look = SwatchLook { fill: source_color(&source), bar: (!constant).then(|| swatch_bar(target)), inverted }; + let rect = Rect::from_min_max(pos2(left, area.top()), pos2(left + SWATCH_WIDTH, area.bottom())); + left += SWATCH_WIDTH + SWATCH_GAP; + let response = swatch(ui, ui.scope_id().with(("exp_swatch", index, slot)), rect, label, &name, &look); + if response.contains_pointer() { + edit.hovered_output = Some(index); + } + let hover = |ui: &mut Ui| { ui.label(&tooltip); if inverted { ui.label(tr("Inverted")); } - }); + output_preview(ui, index, map, planned); + }; + let response = response.on_hover_ui(hover).on_disabled_hover_ui(hover); // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row let map_dragged_over = response.dnd_hover_payload::().is_some(); if map_dragged_over { - drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS), &tokens); + drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS)); } if map_dragged_over && let Some(input) = response.dnd_release_payload::() { edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); @@ -1372,35 +1659,41 @@ fn set_constant(map: &mut MapSpec, target: ChannelTarget, value: f32) { } } -/// The accent frame around a drop target under a dragged map or row -fn drop_highlight(ui: &Ui, rect: egui::Rect, tokens: &Tokens) { - ui.painter().rect_stroke(rect, tokens.radius, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, tokens.accent), egui::StrokeKind::Outside); +/// The frame round a drop target, in the text colour: the accent is Export's alone +fn drop_highlight(ui: &Ui, rect: Rect) { + let look = ExportLook::get(ui.ctx()); + ui.painter().rect_stroke(rect, CARD_RADIUS, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, look.text), egui::StrokeKind::Outside); } -/// One channel swatch: `label` on top, filled with the source's colour, bars below for the -/// channels it reads, a corner mark when inverted -fn swatch(ui: &mut Ui, label: &str, name: &str, look: &SwatchLook) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); +/// One channel swatch `id`: its letters, the source's colour, its channel's underline, a corner mark when inverted +fn swatch(ui: &mut Ui, id: egui::Id, rect: Rect, label: &str, name: &str, swatch_look: &SwatchLook) -> egui::Response { + let look = ExportLook::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click()); + let response = ui.interact(rect, id, egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name)); let painter = ui.painter(); - let border = if response.hovered() { tokens.accent } else { tokens.button_border }; - painter.rect(rect, tokens.radius, look.fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); - let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE_POINTS); - painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP_POINTS), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); - let bar_width = SWATCH_BAR_WIDTH_POINTS / look.bars.len().max(1) as f32; - let left = rect.center().x - SWATCH_BAR_WIDTH_POINTS / 2.0; - for (k, color) in look.bars.iter().enumerate() { - let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM_POINTS); - painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT_POINTS)), 0.0, *color); + let fill = swatch_look.fill.unwrap_or(look.raised); + painter.rect_filled(rect, 0.0, fill); + if response.hovered() { + painter.rect_stroke(rect, 0.0, egui::Stroke::new(1.0, look.text_dim), egui::StrokeKind::Inside); } - if look.inverted { + let lettering = look.lettering_on(fill); + painter.text(pos2(rect.center().x, rect.top() + SWATCH_LABEL_Y), egui::Align2::CENTER_CENTER, label, drawn::font(false), lettering); + if let Some(bar) = swatch_look.bar { + let bottom = rect.bottom() - SWATCH_BAR_BOTTOM; + painter.rect_filled( + Rect::from_min_max(pos2(rect.left() + SWATCH_BAR_INSET, bottom), pos2(rect.right() - SWATCH_BAR_INSET, bottom + SWATCH_BAR_HEIGHT)), + 0.0, + bar, + ); + } + if swatch_look.inverted { let corner = rect.right_top(); let mark = vec![corner, corner - vec2(INVERTED_MARK_POINTS, 0.0), corner + vec2(0.0, INVERTED_MARK_POINTS)]; - painter.add(egui::Shape::convex_polygon(mark, tokens.text_strong, egui::Stroke::NONE)); + painter.add(egui::Shape::convex_polygon(mark, lettering, egui::Stroke::NONE)); } + drawn::paint_focus(ui, &response); response } @@ -1488,79 +1781,92 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ } /// The maps the selected template's outputs read, with their colours, for the panes' markers -fn marked_sources(app: &TextureCraftApp, tokens: &Tokens) -> Vec<(SourceRef, Color32)> { +fn marked_sources(app: &TextureCraftApp) -> Vec<(SourceRef, Color32)> { let Some(preset) = app.ui.export.draft.clone().or_else(|| selected(app)) else { return Vec::new() }; let sources = preset.maps.iter().flat_map(|map| map.channels.iter().map(|(_, source)| source)); - sources.filter_map(|source| source_color(source, tokens).map(|color| (source.clone(), color))).collect() + sources.filter_map(|source| source_color(source).map(|color| (source.clone(), color))).collect() } -/// The Input maps pane: the input maps in their groups -fn input_maps(ui: &mut Ui, marked: &[(SourceRef, Color32)]) { - ui.label(caption(tr("Input maps"))); - egui::ScrollArea::vertical().id_salt("exp_inputs").auto_shrink([false; 2]).show(ui, |ui| { +/// A pane's title at `left`, on the column titles' line +fn pane_title(ui: &mut Ui, left: f32, y: f32, title: &str) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, left + GROUP_INDENT, y, title, look.text, true); +} + +/// A pane's entries scrolling in `area`, the scroll bar in its strip at the right +fn pane_list(ui: &mut Ui, area: Rect, id: &str, add: impl FnOnce(&mut Ui, f32)) { + ui.scope_builder(egui::UiBuilder::new().max_rect(area), |ui| { + egui::ScrollArea::vertical().id_salt(id).auto_shrink([false; 2]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + add(ui, area.width() - GUTTER); + }); + }); +} + +/// The Input maps pane in `pane`: the input maps in their groups +fn input_maps(ui: &mut Ui, pane: Rect, top: f32, marked: &[(SourceRef, Color32)]) { + let look = ExportLook::get(ui.ctx()); + pane_title(ui, pane.left(), top + HEADER_Y, tr("Input maps")); + let list = Rect::from_min_max(pos2(pane.left(), top + LIST_TOP), pane.max); + pane_list(ui, list, "exp_inputs", |ui, width| { for (group, entries) in INPUT_MAPS.iter() { - ui.label(RichText::new(tr(group)).italics()); - map_entries(ui, entries, marked, false); + let (rect, _) = ui.allocate_exact_size(vec2(width, GROUP_HEIGHT), egui::Sense::hover()); + drawn::label_at(ui, rect.left() + GROUP_INDENT, rect.center().y, tr(group), look.text_dim, false); + map_entries(ui, width, entries, marked); } }); } -/// The side pane: Mesh maps above Converted maps (in the highlight colour, as in the reference) -fn mesh_and_converted_maps(ui: &mut Ui, height: f32, marked: &[(SourceRef, Color32)]) { - ui.label(caption(tr("Mesh maps"))); - egui::ScrollArea::vertical() - .id_salt("exp_mesh_maps") - .auto_shrink([false; 2]) - .max_height(height * MESH_MAPS_SHARE) - .show(ui, |ui| map_entries(ui, &MESH_MAPS, marked, false)); - ui.separator(); - ui.label(caption(tr("Converted maps"))); - egui::ScrollArea::vertical().id_salt("exp_converted_maps").auto_shrink([false; 2]).show(ui, |ui| map_entries(ui, &CONVERTED_MAPS, marked, true)); +/// The side pane in `pane`: Mesh maps above Converted maps, a divider between them +fn mesh_and_converted_maps(ui: &mut Ui, pane: Rect, top: f32, marked: &[(SourceRef, Color32)]) { + pane_title(ui, pane.left(), top + HEADER_Y, tr("Mesh maps")); + let split = pane.center().y + SIDE_SPLIT_BELOW_MIDDLE; + let mesh = Rect::from_min_max(pos2(pane.left(), top + LIST_TOP), pos2(pane.right(), split - MESH_BOTTOM_GAP)); + pane_list(ui, mesh, "exp_mesh_maps", |ui, width| map_entries(ui, width, &MESH_MAPS, marked)); + drawn::divider(ui, Rect::from_min_max(pos2(pane.left() - 1.0, split), pos2(pane.right(), split + 1.0))); + pane_title(ui, pane.left(), split + CONVERTED_TITLE_Y, tr("Converted maps")); + let converted = Rect::from_min_max(pos2(pane.left(), split + CONVERTED_ROWS_TOP), pane.max); + pane_list(ui, converted, "exp_converted_maps", |ui, width| map_entries(ui, width, &CONVERTED_MAPS, marked)); } -fn map_entries(ui: &mut Ui, entries: &[MapEntry], marked: &[(SourceRef, Color32)], converted: bool) { - let tokens = Tokens::get(ui.ctx()); - let text_color = if converted { tokens.warning } else { tokens.text }; +fn map_entries(ui: &mut Ui, width: f32, entries: &[MapEntry], marked: &[(SourceRef, Color32)]) { for (name, source) in entries { let marker = source.as_ref().and_then(|source| marked.iter().find(|(used, _)| same_source(used, source)).map(|(_, color)| *color)); - map_entry(ui, tr(name), source.as_ref(), text_color, marker); + map_entry(ui, width, tr(name), source.as_ref(), marker); } } -/// A map list entry to drag onto an output channel, with the colour marker of an output map that -/// reads it; a map TextureCraft does not have yet is greyed and cannot be dragged -fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Color32, marker: Option) { - let tokens = Tokens::get(ui.ctx()); +/// A map list entry to drag onto a channel; a used map shows a square of its colour, a missing one is greyed +fn map_entry(ui: &mut Ui, width: f32, name: &str, source: Option<&SourceRef>, marker: Option) { + let look = ExportLook::get(ui.ctx()); let available = source.is_some(); let sense = if available { egui::Sense::drag() } else { egui::Sense::hover() }; - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT_POINTS), sense); + let (rect, response) = ui.allocate_exact_size(vec2(width, ENTRY_PITCH), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, available, name)); + let row = Rect::from_min_max(pos2(rect.left() + ENTRY_INSET, rect.top()), pos2(rect.right(), rect.top() + ENTRY_HEIGHT)); let painter = ui.painter(); - let row = rect.shrink2(vec2(0.0, ENTRY_GAP_POINTS / 2.0)); - painter.rect_filled(row, 0.0, if available && response.hovered() { tokens.row_hover } else { tokens.row }); + painter.rect_filled(row, 0.0, if available && response.hovered() { look.raised } else { look.control }); if let Some(color) = marker { - painter.rect_filled( - egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT_POINTS, 0.0), egui::Vec2::splat(MARKER_SIZE_POINTS)), - 1.0, - color, + let square = Rect::from_min_size(pos2(rect.left() + MARKER_LEFT, row.center().y - MARKER_SIZE / 2.0), vec2(MARKER_SIZE, MARKER_SIZE)); + let edge = Color32::from_rgb( + color.r().saturating_add(MARKER_EDGE_LIGHTEN), + color.g().saturating_add(MARKER_EDGE_LIGHTEN), + color.b().saturating_add(MARKER_EDGE_LIGHTEN), ); + painter.rect(square, MARKER_RADIUS, color, egui::Stroke::new(1.0, edge), egui::StrokeKind::Inside); } - let color = if available { text_color } else { tokens.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; - painter.text( - row.left_center() + vec2(ENTRY_TEXT_INDENT_POINTS, 0.0), - egui::Align2::LEFT_CENTER, - name, - egui::FontId::proportional(ENTRY_TEXT_SIZE_POINTS), - color, - ); + let color = if available { look.text } else { look.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; + let shown = drawn::fitted(ui, name, row.right() - rect.left() - ENTRY_NAME_LEFT, false, false); + drawn::text_at(ui, rect.left() + ENTRY_NAME_LEFT, row.center().y, &shown, color, false); let Some(source) = source else { response.on_hover_text(tr(NOT_AVAILABLE)); return; }; - let response = response.on_hover_cursor(egui::CursorIcon::Grab); + // How to use the entry is its tooltip, not a line under the cards + let response = response.on_hover_cursor(egui::CursorIcon::Grab).on_hover_text(tr("Drop an input map onto a channel to assign it to that output.")); response.dnd_set_drag_payload(source.clone()); if response.dragged() && let Some(at) = response.interact_pointer_pos() @@ -1579,6 +1885,74 @@ mod tests { SourceRef::Channel { channel, component } } + #[test] + fn feedback_preview_follows_draft_maps_to_their_saved_overrides() { + use crate::state::{MapExport, SetExport}; + use egui_kittest::Harness; + + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let ts = app.session.ts(); + let saved = app.session.export_preset("Unreal Engine (Packed)").unwrap(); + let mut draft = saved.clone(); + draft.maps = vec![saved.maps[1].clone(), new_map(Layout::Gray, "New"), saved.maps[0].clone()]; + let resized = MapExport { size: Some(128), ..MapExport::default() }; + let disabled = MapExport { enabled: false, ..MapExport::default() }; + app.ui.export.preset = saved.name.clone(); + app.ui.export.sets.insert( + ts, + SetExport { + maps_template: saved.name, + maps: [(0, resized), (1, disabled), (2, MapExport { size: Some(512), ..MapExport::default() })].into(), + ..SetExport::default() + }, + ); + app.ui.export.draft = Some(draft.clone()); + app.ui.export.draft_maps = vec![Some(1), None, Some(0)]; + + let params = plan_params(app, &draft).unwrap(); + let outputs = planned_outputs(app, ¶ms).unwrap(); + + assert!(outputs[0].is_none(), "the disabled map stays disabled in its new position"); + assert_eq!(outputs[2].as_ref().unwrap().size, 128); + assert_eq!(params["maps"].as_array().unwrap().len(), 2, "the new map and the removed map get no override"); + } + + #[test] + fn tiled_raster_and_psd_previews_describe_the_whole_atlas() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable as _; + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives::udim_plane; + + let session = Session::new_project("Tiles", udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let mut preset = app.session.export_preset("Separate maps").unwrap(); + preset.maps.truncate(2); + preset.maps[0].file = "Raster".into(); + preset.maps[0].format = FileFormat::Png; + preset.maps[1].file = "Group/Layer.$udim".into(); + preset.maps[1].format = FileFormat::Psd; + let mut ambiguous = preset.maps[0].clone(); + ambiguous.file = "Literal_UDIMTOKEN.$udim".into(); + preset.maps.push(ambiguous); + let params = json!({"ts": 0, "preset": preset}); + + let outputs = planned_outputs(app, ¶ms).unwrap(); + let preview = Harness::builder().with_context_setup(crate::framework::install_headless).build_ui(|ui| { + for (index, map) in preset.maps.iter().enumerate() { + output_preview(ui, index, map, outputs[index].as_ref()); + } + }); + + assert!(preview.query_by_label("Atlas preview: Raster..png").is_some()); + assert!(preview.query_by_label_contains(".psd").is_some()); + assert!(preview.query_by_label("Atlas preview: UV tile files").is_some()); + assert!(preview.query_by_label_contains("128 x 128").is_none(), "the tile size must not describe the whole atlas"); + } + #[test] fn layouts_keep_sources_and_drops_fill_rgb() { let mut map = new_map(Layout::Rgb, "t"); diff --git a/crates/ui-egui/src/export_templates/map_preview_cache.rs b/crates/ui-egui/src/export_templates/map_preview_cache.rs new file mode 100644 index 00000000..4858114c --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_preview_cache.rs @@ -0,0 +1,84 @@ +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use egui::util::id_type_map::RawKey; +use serde_json::Value; + +use super::map_preview_pictures::MapPreviewPictures; +use super::{PlannedOutput, planned_outputs}; +use crate::TextureCraftApp; + +/// Pixels across an output map's hover preview: enough to read the packing, cheap to sample +const PREVIEW_SIDE_PIXELS: u32 = 150; + +/// The current template plan and its hover pictures, invalidated together on edits. +#[derive(Clone)] +pub(super) struct MapPreviewCache { + key: u64, + plan: Result]>, String>, + pictures: HashMap>>, +} + +impl MapPreviewCache { + fn id() -> egui::Id { + egui::Id::unique("export_map_preview_cache") + } + + fn key(app: &TextureCraftApp, params: &Value) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + params.hash(&mut hasher); + (app.session.project_id, app.session.revision).hash(&mut hasher); + hasher.finish() + } + + /// Output map `index`'s pictures once made; None until then + pub(super) fn get(ctx: &egui::Context, index: usize) -> Option>> { + ctx.data(|data| { + let cache = data.get_temp_raw(RawKey::new::(Self::id()))?.downcast_ref::()?; + cache.pictures.get(&index).cloned() + }) + } + + /// Release the plan and its pictures when their tab is dismissed. + pub(super) fn clear(ctx: &egui::Context) { + ctx.data_mut(|data| data.remove::(Self::id())); + } + + /// Keep one descriptor per map until the settings or document change. + pub(super) fn plan(app: &mut TextureCraftApp, ctx: &egui::Context, params: &Value) -> Result]>, String> { + let key = Self::key(app, params); + let cached = ctx.data_mut(|data| { + let cache = data.get_temp_raw(RawKey::new::(Self::id()))?.downcast_ref::()?; + if cache.key == key { + return Some(cache.plan.clone()); + } + + data.remove::(Self::id()); + None + }); + if let Some(plan) = cached { + return plan; + } + + let plan = planned_outputs(app, params).map(Arc::from); + ctx.data_mut(|data| data.insert_temp(Self::id(), Self { key, plan: plan.clone(), pictures: HashMap::new() })); + plan + } + + /// Make output map `index`'s pictures for `params` unless they are made, and draw again to show them + pub(super) fn fill(app: &mut TextureCraftApp, ctx: &egui::Context, params: &Value, index: usize) { + if Self::get(ctx, index).is_some() { + return; + } + + let preview = app.session.export_preview(params, index, PREVIEW_SIDE_PIXELS).ok().flatten(); + let pictures = preview.map(|preview| Arc::new(MapPreviewPictures::new(ctx, &preview, index))); + ctx.data_mut(|data| { + if let Some(cache) = data.get_temp_raw_mut(RawKey::new::(Self::id())).and_then(|entry| entry.downcast_mut::()) { + cache.pictures.insert(index, pictures); + } + }); + ctx.request_repaint(); + } +} diff --git a/crates/ui-egui/src/export_templates/map_preview_pictures.rs b/crates/ui-egui/src/export_templates/map_preview_pictures.rs new file mode 100644 index 00000000..633f4125 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_preview_pictures.rs @@ -0,0 +1,47 @@ +use egui::{Color32, ColorImage, TextureHandle, TextureOptions}; +use texturecraft_engine::formats::{Dest, MapPreview}; + +/// An output map's file, small, then each of its channels in grey, as textures to draw +pub(super) struct MapPreviewPictures { + pub(super) file: TextureHandle, + /// Empty for a one-channel file, whose picture is its channel + pub(super) channels: Vec<(Dest, TextureHandle)>, + /// Height over width + pub(super) aspect: f32, +} + +impl MapPreviewPictures { + /// The pictures of `preview`, the preview of output map `index` + pub(super) fn new(ctx: &egui::Context, preview: &MapPreview, index: usize) -> MapPreviewPictures { + let size = [preview.width as usize, preview.height as usize]; + let pixel_count = size[0] * size[1]; + let count = preview.channels.len().max(1); + let value = |pixel: usize, channel: usize| preview.pixels.get(pixel * count + channel).copied().unwrap_or(0); + let load = |name: String, image: ColorImage| ctx.load_texture(name, image, TextureOptions::LINEAR); + + // Keep alpha separate so the file preview shows the stored colour + let color = preview.channels.starts_with(&[Dest::R, Dest::G, Dest::B]); + let pixels: Vec<_> = (0..pixel_count) + .map(|pixel| if color { Color32::from_rgb(value(pixel, 0), value(pixel, 1), value(pixel, 2)) } else { Color32::from_gray(value(pixel, 0)) }) + .collect(); + let grayscale = !color || pixels.iter().all(|pixel| pixel.r() == pixel.g() && pixel.g() == pixel.b()); + let file = load(format!("export_map_preview_{index}"), ColorImage::new(size, pixels)); + + // A gray file texture can also draw each of its colour channels + let channels = if preview.channels.len() > 1 { + let channel = |(channel_index, dest): (usize, &Dest)| { + if grayscale && *dest != Dest::A { + return (*dest, file.clone()); + } + + let image = ColorImage::from_gray_iter(size, (0..pixel_count).map(|pixel| value(pixel, channel_index))); + (*dest, load(format!("export_map_preview_{index}_{channel_index}"), image)) + }; + preview.channels.iter().enumerate().map(channel).collect() + } else { + Vec::new() + }; + + MapPreviewPictures { file, channels, aspect: preview.height as f32 / preview.width.max(1) as f32 } + } +} diff --git a/crates/ui-egui/src/export_templates/output_card.rs b/crates/ui-egui/src/export_templates/output_card.rs new file mode 100644 index 00000000..a7f1eddc --- /dev/null +++ b/crates/ui-egui/src/export_templates/output_card.rs @@ -0,0 +1,6 @@ +/// An output map card's index, the card count (for the grip's moves) and the width its lists' values line up on +pub(super) struct OutputCard { + pub(super) index: usize, + pub(super) count: usize, + pub(super) value_width: f32, +} diff --git a/crates/ui-egui/src/export_templates/planned_output.rs b/crates/ui-egui/src/export_templates/planned_output.rs new file mode 100644 index 00000000..6c5bcf37 --- /dev/null +++ b/crates/ui-egui/src/export_templates/planned_output.rs @@ -0,0 +1,14 @@ +use texturecraft_engine::formats::FileFormat; + +/// A file an output map writes for the current texture set, as `export.plan` lists it +#[derive(Clone)] +pub(super) struct PlannedOutput { + pub(super) file: String, + /// The picture shows the full atlas while export writes individual tiles + pub(super) tiled: bool, + /// Pixels per side (export.plan never plans an atlas, so every file is square) + pub(super) size: u64, + pub(super) format: Option, + pub(super) bit_depth: u8, + pub(super) dithering: bool, +} diff --git a/crates/ui-egui/src/export_templates/row_edit.rs b/crates/ui-egui/src/export_templates/row_edit.rs index 6568dac9..2143edfb 100644 --- a/crates/ui-egui/src/export_templates/row_edit.rs +++ b/crates/ui-egui/src/export_templates/row_edit.rs @@ -6,4 +6,6 @@ pub(super) struct RowEdit { pub(super) action: Option, /// A map dropped on a channel swatch, to ask which of its channels to use. pub(super) pending: Option, + /// The output map whose channel swatch the pointer is on, for its file preview + pub(super) hovered_output: Option, } diff --git a/crates/ui-egui/src/export_templates/swatch_look.rs b/crates/ui-egui/src/export_templates/swatch_look.rs index 99d81b19..f33e86d8 100644 --- a/crates/ui-egui/src/export_templates/swatch_look.rs +++ b/crates/ui-egui/src/export_templates/swatch_look.rs @@ -4,7 +4,7 @@ use egui::Color32; pub(super) struct SwatchLook { /// The source map's colour (None: empty or a constant). pub(super) fill: Option, - /// One bar per channel of the source the swatch reads. - pub(super) bars: Vec, + /// The underline in the colour of the channel the swatch's letters name (None: a constant) + pub(super) bar: Option, pub(super) inverted: bool, } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 6a46f757..c346d033 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -12,44 +12,192 @@ use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; -use crate::theme::{Tokens, caption, semibold}; +use crate::theme::{Tokens, semibold}; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::icon_button; +pub(crate) mod drawn; +pub(crate) mod export_look; mod inherited_settings; mod map_row; +mod page_place; +mod tree_file; +pub(crate) use export_look::ExportLook; use inherited_settings::InheritedSettings; use map_row::MapRow; +use page_place::PagePlace; +use tree_file::TreeFile; /// The reference window's size; a smaller screen gets a smaller window const REFERENCE_WINDOW_SIZE_POINTS: egui::Vec2 = egui::vec2(1100.0, 740.0); /// Space kept free around the content on a small screen: the title bar, the frame and a gap const WINDOW_VIEWPORT_MARGIN_POINTS: f32 = 72.0; -/// Width of the texture set list -const LIST_WIDTH: f32 = 250.0; -const ICON: f32 = 20.0; -/// Width of the label column of the parameter rows, as in the reference -const LABEL_COLUMN_WIDTH: f32 = 200.0; -/// Width of the value column of the parameter rows -const VALUE_WIDTH: f32 = 360.0; -/// Width of the first File type list; the bit depth list fills the rest of the row -const FILE_TYPE_WIDTH: f32 = 166.0; -/// Width of the dilation button, with room for its drop-down arrow -const DILATION_BUTTON_WIDTH: f32 = 60.0; -/// Size of a drop-down arrow, and its distance from the button's right edge -const CARET_SIZE: f32 = 10.0; -const CARET_INSET: f32 = 6.0; -/// A tab: padding around its name, the accent line on top of the open one, the name's size -const TAB_PADDING: egui::Vec2 = egui::vec2(10.0, 6.0); -const TAB_ACCENT_HEIGHT: f32 = 2.0; -const TAB_TEXT_SIZE: f32 = 12.5; -/// Height of a full-width row of the texture set list and where its text starts -const LIST_ROW_HEIGHT: f32 = 24.0; -const LIST_ROW_INDENT: f32 = 16.0; +/// The content runs nearly to the window's frame: one point inside its edge +const CONTENT_INSET: i8 = 1; +/// The widest dilation the slider offers, the cap `export.run` puts on its `dilation` +const MAX_DILATION_PIXELS: u32 = 256; + +// Layout in points from the window content's top left corner, measured on the locked mocks + +/// The tab row's height, down to the divider under it +pub(crate) const TAB_ROW_HEIGHT: f32 = 42.0; +/// The tabs' top edge +const TAB_TOP: f32 = 16.0; +/// The first tab's left edge +const TABS_LEFT: f32 = 7.5; +/// Middle of the controls at the tab row's right end, 9 points of air above the divider +const TAB_ROW_CONTROLS_Y: f32 = 19.5; +/// From the window's left edge to the buttons there +const LEFT_MARGIN: f32 = 7.5; +/// From the window's right edge to the buttons there +const RIGHT_MARGIN: f32 = 10.5; +/// The bottom bar's height under its divider +const FOOTER_HEIGHT: f32 = 46.0; +/// Middle of the bottom bar's buttons, from the window's bottom +const FOOTER_MIDDLE_FROM_BOTTOM: f32 = 22.5; /// Width of the bottom bar's buttons, the same for all as in the reference -const FOOTER_BUTTON_WIDTH: f32 = 126.0; -/// Width of the keyboard focus outline on the window's drawn controls -const FOCUS_OUTLINE_WIDTH: f32 = 2.0; +const FOOTER_BUTTON_WIDTH: f32 = 117.5; +/// Gap between the bottom bar's buttons +const FOOTER_BUTTON_GAP: f32 = 6.5; +/// Air between the texture count and Cancel +const COUNT_GAP: f32 = 14.5; +/// Open output directory: the air around its name +const OPEN_DIRECTORY_PADDING: f32 = 24.0; +/// Open output directory: its distance from the window's right edge +const OPEN_DIRECTORY_FROM_RIGHT: f32 = 12.0; +/// The strip at a list's right edge that holds its scroll bar +pub(crate) const GUTTER: f32 = 12.0; +/// Size of the menu (≡) and reset glyphs of the lists and pages +const MENU_ICON_SIZE: f32 = 14.0; + +/// Width of the texture set list +const SET_LIST_WIDTH: f32 = 240.7; +/// Centre of the set list's menu, x +const SET_MENU_X: f32 = 227.5; +/// Centre of the set list's menu, y +const SET_MENU_Y: f32 = 57.0; +/// Top of the set list's first row, Global settings +const SET_ROWS_TOP: f32 = 70.0; +/// Height of a set list row +const SET_ROW_HEIGHT: f32 = 25.0; +/// Where a set row's check box starts +const SET_CHECK_LEFT: f32 = 18.8; +/// Where a set row's name starts +const SET_NAME_LEFT: f32 = 36.7; +/// Where Global settings starts, having no check box +const GLOBAL_NAME_LEFT: f32 = 16.0; +/// The override mark's distance from its row's end +const OVERRIDE_MARK_FROM_RIGHT: f32 = 14.0; +/// Side of a check box's click area +const CHECK_HIT_SIZE: f32 = 20.0; +/// How far a check box's click area reaches past its box on each side +const CHECK_HIT_OVERHANG: f32 = 3.5; + +/// A page's label column +const LABEL_LEFT: f32 = 257.6; +/// Where a page's controls start +const CONTROLS_LEFT: f32 = 455.0; +/// Where a page's controls end, from the window's right edge +const CONTROLS_RIGHT_MARGIN: f32 = 112.8; +/// A page header's glyph, from the window's right edge +const PAGE_ICON_FROM_RIGHT: f32 = 22.6; +/// Middle of the Global settings page's header +const GLOBAL_HEADER_Y: f32 = 71.0; +/// Middle of its reset glyph +const GLOBAL_ICON_Y: f32 = 70.0; +/// Middle of its first parameter row +const GLOBAL_FIRST_ROW_Y: f32 = 115.0; +/// Pitch of its parameter rows +const GLOBAL_ROW_PITCH: f32 = 35.5; +/// From the last parameter row to the first tick +const CHECKS_GAP: f32 = 30.0; +/// Pitch of the ticks +const CHECK_PITCH: f32 = 24.0; +/// The page's least width before it scrolls +const MIN_PAGE_WIDTH: f32 = 640.0; +/// The Global settings page's height under the tab row +const GLOBAL_PAGE_HEIGHT: f32 = 376.0; +/// The ticks sit a point in from the labels +const CHECK_INDENT: f32 = 1.0; +/// A tick's label starts after its box and the gap +const CHECK_LABEL_ROOM: f32 = 18.0; +/// Width of the output directory's "…" and reset buttons +#[cfg(not(target_arch = "wasm32"))] +const BROWSE_WIDTH: f32 = 22.0; +/// Gap before them +#[cfg(not(target_arch = "wasm32"))] +const BROWSE_GAP: f32 = 4.0; +/// Room the file type list keeps for its chevron past its longest entry +const FILE_TYPE_ROOM: f32 = 36.0; +/// Gap between two controls on one row +const PAIR_GAP: f32 = 6.6; +/// Width of the dilation width's dropdown +const DILATION_WIDTH: f32 = 56.4; + +/// Middle of a texture set page's header +const SET_HEADER_Y: f32 = 74.0; +/// Middle of its first override row +const SET_FIRST_ROW_Y: f32 = 121.0; +/// Pitch of its override rows +const SET_ROW_PITCH: f32 = 36.0; +/// Centre of the override pens +const PEN_CENTRE: f32 = 464.4; +/// Where an inherited value's text starts +const VALUE_LEFT: f32 = 479.4; +/// Where an override's control starts +const OVERRIDE_LEFT: f32 = 480.3; +/// The divider above Output maps +const SET_DIVIDER_Y: f32 = 257.0; +/// Middle of the Output maps header +const MAPS_HEADER_Y: f32 = 288.0; +/// Top of the first Output maps row +const MAPS_TOP: f32 = 318.0; +/// Pitch of the Output maps rows +const MAP_ROW_PITCH: f32 = 34.0; +/// Leave room for two map rows when the texture-set page scrolls vertically. +const MIN_SET_PAGE_HEIGHT: f32 = MAPS_TOP - TAB_ROW_HEIGHT + 2.0 * MAP_ROW_PITCH; +/// Where an Output maps row's tick starts +const MAP_CHECK_LEFT: f32 = 258.6; +/// Where its file name starts +const MAP_NAME_LEFT: f32 = 280.1; +/// The inherited bit depth's text, after the file type's +const BITS_TEXT_OFFSET: f32 = 32.0; +/// Width of a map's file type list +const MAP_FORMAT_WIDTH: f32 = 61.2; +/// Width of a map's own size list +const MAP_SIZE_WIDTH: f32 = 100.0; + +/// The console's least width: the reference's 300 at TextureCraft's narrower window +pub(crate) const CONSOLE_WIDTH: f32 = 284.0; +/// The file tree's least width +const MIN_TREE_WIDTH: f32 = 300.0; +/// Width of the strip that folds the console +const STRIP_WIDTH: f32 = 17.9; +/// Gap between the file tree and the strip +const STRIP_GAP: f32 = 1.9; +/// Size of the strip's glyph +const STRIP_GLYPH_SIZE: f32 = 13.0; +/// The console text's indent +const CONSOLE_TEXT_INDENT: f32 = 18.0; +/// Middle of the console's header +const CONSOLE_HEADER_Y: f32 = 66.0; +/// Where the console's lines start +const CONSOLE_BODY_TOP: f32 = 89.0; +/// Air above and below the console's lines +const CONSOLE_PADDING: f32 = 6.0; +/// Air above the file tree's first row +const TREE_TOP_PADDING: f32 = 3.0; +/// Height of a file tree row +const TREE_ROW_HEIGHT: f32 = 21.0; +/// Centre of a set's chevron +const TREE_CHEVRON_X: f32 = 13.2; +/// Where a set's name starts +const TREE_NAME_INDENT: f32 = 26.3; +/// Where its files start +const TREE_FILE_INDENT: f32 = 45.1; +/// Gap after the name and size columns +const TREE_COLUMN_GAP: f32 = 28.0; +/// Gap after the file type column +const TREE_BITS_GAP: f32 = 14.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -104,9 +252,16 @@ pub(crate) fn depth_label(format: Option, bit_depth: u8, dithering: } } -/// A file type list and its bit depth list; `from_template` adds "Based on output template" -/// (an empty `format`), which leaves the bit depth to the template. -fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, format: &mut String, bit_depth: &mut u8, dithering: &mut bool) { +/// A file type list and its bit depth list in `rects`; `from_template` adds "Based on output template" (an empty `format`) +fn file_type_lists( + ui: &mut Ui, + id: (&str, usize, usize), + from_template: bool, + rects: [egui::Rect; 2], + format: &mut String, + bit_depth: &mut u8, + dithering: &mut bool, +) { let parsed = FileFormat::from_extension(format); // A depth the type does not have (or none) becomes its default @@ -116,10 +271,7 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f (*bit_depth, *dithering) = (f.default_depth(), false); } let shown = if format.is_empty() { tr("Based on output template").to_string() } else { file_type_name(format) }; - - // Tall enough for the whole list - let list = egui::ComboBox::from_id_salt(("type", id)).width(if from_template { FILE_TYPE_WIDTH } else { 90.0 }).height(f32::INFINITY); - list.selected_text(shown).show_ui(ui, |ui| { + drawn::combo(ui, rects[0], ("type", id), shown, |ui| { if from_template { if ui.selectable_label(format.is_empty(), tr("Based on output template")).clicked() { format.clear(); @@ -141,18 +293,21 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f } } }); + + // A file type with one bit depth (or none) shows its bit depth list greyed let options = parsed.map(depth_options).unwrap_or_default(); let shown = if parsed.is_some() { depth_label(parsed, *bit_depth, *dithering) } else { String::new() }; - ui.add_enabled_ui(options.len() > 1, |ui| { - // On the global page the bit depth list fills the row - let width = if from_template { VALUE_WIDTH - FILE_TYPE_WIDTH - ui.spacing().item_spacing.x } else { 120.0 }; - egui::ComboBox::from_id_salt(("bits", id)).width(width).selected_text(shown).show_ui(ui, |ui| { - for (d, dither) in options { - if ui.selectable_label((*bit_depth, *dithering) == (d, dither), depth_label(parsed, d, dither)).clicked() { - (*bit_depth, *dithering) = (d, dither); - } + if options.len() < 2 { + drawn::disabled_combo(ui, rects[1], ("bits", id), &shown, tr("Bit depth")); + return; + } + + drawn::combo(ui, rects[1], ("bits", id), shown, |ui| { + for (depth, dither) in options { + if ui.selectable_label((*bit_depth, *dithering) == (depth, dither), depth_label(parsed, depth, dither)).clicked() { + (*bit_depth, *dithering) = (depth, dither); } - }); + } }); } @@ -179,21 +334,48 @@ fn file_type_name(format: &str) -> String { FileFormat::from_extension(format).map_or_else(|| format.to_string(), |f| f.name().to_string()) } +/// The label shown for a stored template name. Custom template names pass through unchanged. +pub(super) fn template_label<'a>(session: &texturecraft_engine::Session, name: &'a str) -> &'a str { + use texturecraft_engine::preset_cmds::unqualified_preset_name; + + let label = match unqualified_preset_name(name) { + "Unreal Engine Subsurface Profile (Packed)" => tr("Packed maps with a scattering mask"), + "Redshift Standard Material (separate maps)" => tr("Separate coat, sheen and scattering maps"), + "Roblox SurfaceAppearance (separate maps)" => tr("Four maps with opacity in color"), + "Sketchfab Metalness (separate maps)" => tr("Six maps with a negative-Y normal"), + _ => return name, + }; + + if session.has_user_export_preset(name) { name } else { label } +} + /// The template list: the first group (name, whether TextureCraft has it), then the others /// (built-in and user templates) sorted by name. pub(crate) fn template_groups(app: &TextureCraftApp, builtins: &[ExportPreset]) -> (Vec<(&'static str, bool)>, Vec) { let first = FIRST_GROUP.iter().map(|name| (*name, builtins.iter().any(|p| p.name == *name))).collect(); - let mut rest: Vec = builtins.iter().map(|p| p.name.clone()).filter(|n| !FIRST_GROUP.contains(&n.as_str())).collect(); + let mut rest: Vec = builtins + .iter() + .filter(|preset| !FIRST_GROUP.contains(&preset.name.as_str())) + .map(|preset| app.session.builtin_export_preset_id(&preset.name).into_owned()) + .collect(); rest.extend(app.session.export_presets.list.iter().map(|p| p.name.clone())); - rest.sort(); + rest.sort_by(|left, right| template_label(&app.session, left).cmp(template_label(&app.session, right)).then_with(|| left.cmp(right))); rest.dedup(); (first, rest) } -/// A template dropdown over `first` and `rest`; true when `current` changed -fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, bool)], rest: &[String]) -> bool { +/// A template dropdown in `rect` over `first` and `rest`; true when `current` changed +fn template_combo( + session: &texturecraft_engine::Session, + ui: &mut Ui, + rect: egui::Rect, + id: &str, + current: &mut String, + first: &[(&str, bool)], + rest: &[String], +) -> bool { let mut changed = false; - egui::ComboBox::from_id_salt(id).width(VALUE_WIDTH).selected_text(current.clone()).show_ui(ui, |ui| { + drawn::combo(ui, rect, id, template_label(session, current).to_owned(), |ui| { for (name, have) in first { if *have { changed |= ui.selectable_value(current, (*name).to_string(), *name).on_hover_text(*name).changed(); @@ -203,7 +385,7 @@ fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, b } ui.separator().on_hover_text(tr("Some templates in this list are unavailable")); for name in rest { - changed |= ui.selectable_value(current, name.clone(), name).on_hover_text(name).changed(); + changed |= ui.selectable_value(current, name.clone(), template_label(session, name)).on_hover_text(name).changed(); } }); changed @@ -261,7 +443,10 @@ fn start_export(app: &mut TextureCraftApp) { .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 error = preview.iter().find_map(|plan| plan.files.as_ref().err().cloned()).or_else(|| name_clash(&preview)).or_else(|| { + let paths = preview.iter().filter_map(|plan| plan.files.as_ref().ok()).flat_map(planned_names); + texturecraft_engine::formats::export::validate_export_paths(paths).err().map(|error| trf("Export stopped: {error}", &[("error", &error)])) + }); let e = &mut app.ui.export; e.tab = 2; @@ -272,7 +457,15 @@ fn start_export(app: &mut TextureCraftApp) { return; } - e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, usd_asset: e.usd_asset, ..Default::default() }); + e.job = Some(crate::state::ExportJob { + total: pending.len(), + pending, + preview, + directory: dir, + usd_asset: e.usd_asset, + shader_parameters: e.shader_parameters, + ..Default::default() + }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -373,6 +566,11 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { } } + // The last command writes the shader parameters, listing every texture set of the export + if let Some(job) = app.ui.export.job.as_ref().filter(|job| job.shader_parameters && job.pending.is_empty()) { + params["shaderParameters"] = job.preview.iter().filter_map(|plan| plan.index).collect(); + } + let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; @@ -394,8 +592,9 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { }; let files: Vec = response_strings(&response, "files").map(relative).collect(); let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; - // 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")) { + + // The USD asset and the shader parameters are no textures: they stay in the list of written files only + for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd") && !file.to_ascii_lowercase().ends_with(".json")) { 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)]))); @@ -507,6 +706,9 @@ pub(crate) fn set_params(app: &TextureCraftApp, set_index: usize) -> serde_json: settings["bitDepth"] = json!(file_type.bit_depth); settings["dithering"] = json!(file_type.dithering); } + if let Some(size) = map.size { + settings["size"] = json!(size); + } settings }) .collect(); @@ -519,103 +721,165 @@ fn set_template(app: &TextureCraftApp, ts: usize) -> String { app.ui.export.sets.get(&ts).and_then(|o| o.preset.clone()).unwrap_or_else(|| app.ui.export.preset.clone()) } -/// Shorten a long file name pattern at the front, as the reference's Output maps rows do -fn elide_front(text: &str) -> String { - const SHOWN: usize = 26; - let n = text.chars().count(); - if n <= SHOWN { text.to_string() } else { format!("…{}", text.chars().skip(n - (SHOWN - 1)).collect::()) } +/// A file type and bit depth as an Output maps row shows them ("png 8 bits"), and the two apart +fn file_type_text(t: &FileType) -> String { + let (format, bits) = file_type_parts(t); + format!("{format} {bits}") } -/// A file type and bit depth as an Output maps row shows them ("png 8 bits") -fn file_type_text(t: &FileType) -> String { - format!("{} {}", file_type_name(&t.format), depth_label(FileFormat::from_extension(&t.format), t.bit_depth, t.dithering)) +fn file_type_parts(t: &FileType) -> (String, String) { + (file_type_name(&t.format), depth_label(FileFormat::from_extension(&t.format), t.bit_depth, t.dithering)) } /// The rows of texture set `ts`'s Output maps: the template's maps the set has sources for -fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { - let mut p = set_params(app, ts); - if let Some(o) = p.as_object_mut() { - o.remove("maps"); - } - let preset = app.session.export_preset(&set_template(app, ts)); - let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", &p) else { return Vec::new() }; - let mut rows: Vec = Vec::new(); - for f in plan.as_array().into_iter().flatten() { - let Some(map) = f.get("map").and_then(serde_json::Value::as_u64).map(|m| m as usize) else { continue }; - if rows.iter().any(|r| r.map == map) { - continue; - } +fn map_rows(app: &TextureCraftApp, ts: usize) -> Vec { + let mut params = set_params(app, ts); - let format = f.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); - let bit_depth = f.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; - let dithering = f.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let pattern = preset - .as_ref() - .and_then(|p| p.maps.get(map)) - .map(|m| m.file.replace("$channel", texturecraft_engine::formats::export::channel_label(m))) - .unwrap_or_default(); - rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); + // Discover maps from their sources so invalid output sizes cannot hide the controls that fix them + if let Some(object) = params.as_object_mut() { + object.remove("maps"); + object.remove("size"); } + + let Ok(options) = texturecraft_engine::file_cmds::export_options(&app.session, ¶ms, "export.plan") else { return Vec::new() }; + let Ok(set) = app.session.doc.project.texture_set(ts) else { return Vec::new() }; + + let mut rows = Vec::new(); + let mut psd_rows = Vec::new(); + let mut psd_depth = 8; + let mut psd_dithering = false; + for (map, spec) in options.preset.maps.iter().enumerate().filter(|(_, spec)| spec.is_available_for(set)) { + let (format, bit_depth, dithering) = options.map_file_type(map, spec); + let pattern = spec.file.replace("$channel", texturecraft_engine::formats::export::channel_label(spec)); + let row = MapRow { map, pattern, inherited: FileType { format: format.name().to_owned(), bit_depth, dithering } }; + if format == FileFormat::Psd { + psd_depth = psd_depth.max(bit_depth); + psd_dithering |= dithering; + psd_rows.push(row); + } else { + rows.push(row); + } + } + + // All PSD rows inherit the document's file type and follow the standalone maps + for mut row in psd_rows { + row.inherited.bit_depth = psd_depth; + row.inherited.dithering = psd_depth == 8 && psd_dithering; + rows.push(row); + } + rows } -/// The Output maps section of texture set `ts`'s page -fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { +/// The Output maps section of texture set `ts`'s page: its header, then its rows scrolling in `area` +fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, area: egui::Rect) { + let look = ExportLook::get(ui.ctx()); let rows = map_rows(app, ts); let template = set_template(app, ts); - let o = app.ui.export.sets.entry(ts).or_default(); - if o.maps_template != template { - o.maps.clear(); - o.maps_template = template; + let overrides = app.ui.export.sets.entry(ts).or_default(); + if overrides.maps_template != template { + overrides.maps.clear(); + overrides.maps_template = template; } + let mut menu = None; - header(ui, tr("Output maps"), |ui| { - list_menu(ui, |ui| { - for (i, label) in [tr("Check all"), tr("Uncheck all"), tr("Invert all")].into_iter().enumerate() { - if ui.button(label).clicked() { - menu = Some(i); - } + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(MAPS_HEADER_Y), tr("Output maps"), look.text, true); + list_menu(ui, place.right_inset(PAGE_ICON_FROM_RIGHT, MAPS_HEADER_Y), tr("Output maps menu"), |ui| { + for (i, label) in [tr("Check all"), tr("Uncheck all"), tr("Invert all")].into_iter().enumerate() { + if ui.button(label).clicked() { + menu = Some(i); } - ui.separator(); - for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { - if ui.button(label).clicked() { - menu = Some(3 + i); - } + } + ui.separator(); + for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { + if ui.button(label).clicked() { + menu = Some(3 + i); + } + } + ui.separator(); + }); + + // The rows scroll under the header, the scroll bar in its strip at the window's right edge + ui.scope_builder(egui::UiBuilder::new().max_rect(area), |ui| { + egui::ScrollArea::vertical().id_salt(("exp_maps_scroll", ts)).auto_shrink([false; 2]).show(ui, |ui| { + let height = rows.len() as f32 * MAP_ROW_PITCH; + let (rows_rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::hover()); + for (index, row) in rows.iter().enumerate() { + let y = rows_rect.top() + (index as f32 + 0.5) * MAP_ROW_PITCH; + map_row(ui, place, y, ts, row, overrides.maps.entry(row.map).or_default()); } - ui.separator(); }); }); - egui::Grid::new(("exp_maps", ts)).num_columns(3).spacing(vec2(8.0, 6.0)).show(ui, |ui| { - for row in &rows { - let m = o.maps.entry(row.map).or_default(); - ui.checkbox(&mut m.enabled, ""); - ui.add(egui::Label::new(elide_front(&row.pattern)).selectable(false)).on_hover_text(&row.pattern); - ui.horizontal(|ui| { - if icon_button(ui, ic::PENCIL_SIMPLE, tr("Enable override"), m.file_type.is_some(), ICON).clicked() { - m.file_type = if m.file_type.is_some() { None } else { Some(row.inherited.clone()) }; - } - match &mut m.file_type { - Some(t) => file_type_combo(ui, ("exp_map", ts, row.map), t), - None => { - ui.label(file_type_text(&row.inherited)); - } - } - }); - ui.end_row(); - } - }); + for row in &rows { - let m = o.maps.entry(row.map).or_default(); + let map_export = overrides.maps.entry(row.map).or_default(); match menu { - Some(0) => m.enabled = true, - Some(1) => m.enabled = false, - Some(2) => m.enabled = !m.enabled, - Some(3) if m.file_type.is_none() => m.file_type = Some(row.inherited.clone()), - Some(4) => m.file_type = None, + Some(0) => map_export.enabled = true, + Some(1) => map_export.enabled = false, + Some(2) => map_export.enabled = !map_export.enabled, + Some(3) if map_export.file_type.is_none() => map_export.file_type = Some(row.inherited.clone()), + Some(4) => (map_export.file_type, map_export.size) = (None, None), _ => {} } } - o.maps.retain(|_, m| *m != MapExport::default()); + overrides.maps.retain(|_, map_export| *map_export != MapExport::default()); +} + +/// One Output maps row at `y`: tick, file name cut at the front, override pen, file type, the map's own size +fn map_row(ui: &mut Ui, place: PagePlace, y: f32, ts: usize, row: &MapRow, map_export: &mut MapExport) { + let look = ExportLook::get(ui.ctx()); + let check_left = place.x(MAP_CHECK_LEFT); + let hit = egui::Rect::from_center_size(egui::pos2(check_left + CHECK_HIT_SIZE / 2.0 - CHECK_HIT_OVERHANG, y), vec2(CHECK_HIT_SIZE, CHECK_HIT_SIZE)); + let name_left = place.x(MAP_NAME_LEFT); + let shown = drawn::fitted(ui, &row.pattern, place.x(CONTROLS_LEFT) - name_left, true, false); + drawn::check(ui, ui.scope_id().with(("exp_map_tick", ts, row.map)), hit, egui::pos2(check_left, y), &mut map_export.enabled, None, &shown); + let color = if map_export.enabled { look.text } else { look.text_dim }; + drawn::label_at(ui, name_left, y, &shown, color, false).on_hover_text(&row.pattern); + + let pen = egui::pos2(place.x(PEN_CENTRE), y); + let name = trf("Enable override for map {number} ({pattern})", &[("number", &(row.map + 1)), ("pattern", &row.pattern)]); + if drawn::icon_button(ui, pen, ic::PENCIL_SIMPLE, drawn::CHEVRON_SIZE, &name, true, map_export.file_type.is_some()).clicked() { + map_export.file_type = if map_export.file_type.is_some() { None } else { Some(row.inherited.clone()) }; + } + + // The map's size list keeps the row's right end; the file type and bit depth come before it + let right = place.right - CONTROLS_RIGHT_MARGIN; + let size_rect = drawn::control_rect(right - MAP_SIZE_WIDTH, right, y); + match &mut map_export.file_type { + Some(FileType { format, bit_depth, dithering }) => { + let format_rect = drawn::control_rect(place.x(OVERRIDE_LEFT), place.x(OVERRIDE_LEFT) + MAP_FORMAT_WIDTH, y); + let bits_rect = drawn::control_rect(format_rect.right() + PAIR_GAP, size_rect.left() - PAIR_GAP, y); + file_type_lists(ui, ("exp_map", ts, row.map), false, [format_rect, bits_rect], format, bit_depth, dithering); + } + None => inherited_file_type(ui, place, y, &row.inherited), + } + map_size_combo(ui, size_rect, ("exp_map_size", ts, row.map), &mut map_export.size); +} + +/// A map's inherited file type: "png" and "8 bits" in their columns, one text to assistive technology +fn inherited_file_type(ui: &mut Ui, place: PagePlace, y: f32, inherited: &FileType) { + let look = ExportLook::get(ui.ctx()); + let (format, bits) = file_type_parts(inherited); + let format_rect = drawn::text_at(ui, place.x(VALUE_LEFT), y, &format, look.text, false); + let bits_rect = drawn::text_at(ui, place.x(VALUE_LEFT + BITS_TEXT_OFFSET), y, &bits, look.text, false); + let text = file_type_text(inherited); + let response = + ui.interact(format_rect.union(bits_rect), ui.scope_id().with(("exp_map_inherited", place.y(0.0).to_bits(), y.to_bits())), egui::Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &text)); +} + +/// An output map's size in `rect`: the export's, or its own, which wins over it +fn map_size_combo(ui: &mut Ui, rect: egui::Rect, id: (&str, usize, usize), size: &mut Option) { + let shown = size.map_or_else(|| tr("Export size").to_string(), |side| format!("{side}x{side}")); + drawn::combo(ui, rect, id, shown, |ui| { + ui.selectable_value(size, None, tr("Export size")); + ui.separator(); + for side in SIZES { + ui.selectable_value(size, Some(side), format!("{side}x{side}")); + } + }) + .response + .on_hover_text(tr("This map's own size, which wins over the export size")); } /// Count the files planned across all selected texture sets. @@ -629,54 +893,10 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } -/// The keyboard focus outline of a drawn control: inside `response`'s rect, in the strong text -/// colour, so it differs from the accent of the selected one and the fill of the hovered one -fn paint_focus(ui: &Ui, response: &egui::Response) { - if response.has_focus() { - let stroke = egui::Stroke::new(FOCUS_OUTLINE_WIDTH, Tokens::get(ui.ctx()).text_strong); - ui.painter().rect_stroke(response.rect, 0.0, stroke, egui::StrokeKind::Inside); - } -} - -/// A window tab: a box, lighter and with an accent line on top when open -fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let color = if selected { tokens.text_strong } else { tokens.text }; - let galley = ui.painter().layout_no_wrap(label.to_string(), semibold(TAB_TEXT_SIZE), color); - let (rect, response) = ui.allocate_exact_size(galley.size() + 2.0 * TAB_PADDING, egui::Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, selected, label)); - - let painter = ui.painter(); - let fill = match (selected, response.hovered()) { - (true, _) => tokens.panel, - (false, true) => tokens.row_hover, - (false, false) => tokens.row, - }; - painter.rect(rect, 0.0, fill, egui::Stroke::new(1.0, tokens.separator), egui::StrokeKind::Inside); - if selected { - painter.rect_filled(egui::Rect::from_min_size(rect.min, vec2(rect.width(), TAB_ACCENT_HEIGHT)), 0.0, tokens.accent); - } - painter.galley(rect.min + TAB_PADDING, galley, color); - paint_focus(ui, &response); - response -} - -/// A bottom bar button, as wide as the others -fn footer_button(text: &str) -> egui::Button<'_> { - egui::Button::new(text).min_size(vec2(FOOTER_BUTTON_WIDTH, 0.0)) -} - -/// A header with a menu or tool at its right end -fn header(ui: &mut Ui, title: &str, right: impl FnOnce(&mut Ui)) { - ui.horizontal(|ui| { - ui.label(caption(title)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), right); - }); -} - -/// The menu button of a list header -fn list_menu(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { - ui.menu_button(RichText::new(ic::LIST_CHECKS).size(15.0), add); +/// The menu button (≡) of a list or page header centred on `centre`, called `name` for assistive technology; its menu holds `add` +fn list_menu(ui: &mut Ui, centre: egui::Pos2, name: &str, add: impl FnOnce(&mut Ui)) { + let response = drawn::icon_button(ui, centre, ic::LIST, MENU_ICON_SIZE, name, true, false); + egui::Popup::menu(&response).show(add); } /// Check all, Uncheck all, Invert all over the texture sets @@ -695,55 +915,57 @@ fn set_checks_menu(app: &mut TextureCraftApp, ui: &mut Ui) { ui.separator(); } -/// Output directory: the path as a button that opens the folder picker, and a reset -#[cfg(not(target_arch = "wasm32"))] -fn output_directory(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(tr("Output directory")); - ui.horizontal(|ui| { - let dir = app.ui.export.dir.clone(); - let button = egui::Button::new(dir.as_str()).truncate(); - if ui.add_sized(vec2(VALUE_WIDTH - 24.0, 20.0), button).on_hover_text(dir.as_str()).clicked() { - app.ask_file(FileDialog::folder().directory(dir), Bound::App, |app, paths| { - if let Some(d) = paths.first() { - app.ui.export.dir = d.display().to_string(); - } - }); - } - if ui.small_button("R").on_hover_text(tr("Reset to default")).clicked() { - app.ui.export.dir = ExportUi::default().dir; - } - }); - ui.end_row(); +/// A parameter's name at the label column, its middle at `y` +fn row_label(ui: &mut Ui, place: PagePlace, y: f32, text: &str) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, place.x(LABEL_LEFT), y, text, look.text, false); } -/// The dilation width: a button showing it, with a slider in its menu (only for paddings that -/// have a width) -fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { - let enabled = has_width(padding); - - // The menu stays open while the slider is used - let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); - let r = ui.add_enabled_ui(enabled, |ui| { - let button = egui::Button::new(dilation.to_string()).min_size(vec2(DILATION_BUTTON_WIDTH, 0.0)); - egui::containers::menu::MenuButton::from_button(button).config(config).ui(ui, |ui| { - ui.label(tr("Dilation (pixels)")); - ui.add(egui::Slider::new(dilation, 0..=256).step_by(1.0)); - }) - }); - - // The drop-down arrow is drawn apart, so the button's name stays the number - let tokens = Tokens::get(ui.ctx()); - let arrow_color = if enabled { tokens.text } else { tokens.text_dim }; - let arrow_at = r.response.rect.right_center() - vec2(CARET_INSET, 0.0); - ui.painter().text(arrow_at, egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_SIZE), arrow_color); - if enabled { - r.response.on_hover_text(tr("Dilation in pixels")); - } else { - r.response.on_disabled_hover_text(tr("This padding mode does not use a dilation width")); +/// Output directory at `y`: the path as a field that opens the folder picker, "…" and a reset +#[cfg(not(target_arch = "wasm32"))] +fn output_directory(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, y: f32) { + row_label(ui, place, y, tr("Output directory")); + let right = place.right - CONTROLS_RIGHT_MARGIN; + let dir = app.ui.export.dir.clone(); + let field = drawn::control_rect(place.x(CONTROLS_LEFT), right - BROWSE_WIDTH - BROWSE_GAP, y); + let path = drawn::field_button(ui, field, ui.scope_id().with("exp_dir"), &dir).on_hover_text(dir.as_str()); + let browse_rect = drawn::control_rect(right - BROWSE_WIDTH, right, y); + let browse_name = tr("Choose the output folder"); + let browse = drawn::button_with_id(ui, ui.scope_id().with("exp_dir_browse"), browse_rect, "…", browse_name, false, true).on_hover_text(browse_name); + if path.clicked() || browse.clicked() { + app.ask_file(FileDialog::folder().directory(dir), Bound::App, |app, paths| { + if let Some(directory) = paths.first() { + app.ui.export.dir = directory.display().to_string(); + } + }); + } + let reset = drawn::control_rect(right + BROWSE_GAP, right + BROWSE_GAP + BROWSE_WIDTH, y); + let reset_id = ui.scope_id().with("exp_dir_reset"); + let reset_name = tr("Reset to default"); + if drawn::button_with_id(ui, reset_id, reset, ic::ARROW_COUNTER_CLOCKWISE, reset_name, false, true).on_hover_text(reset_name).clicked() { + app.ui.export.dir = ExportUi::default().dir; } } +/// The dilation width in `rect`: a dropdown with a slider in its menu, greyed for paddings without a width +fn dilation_button(ui: &mut Ui, rect: egui::Rect, id_salt: &str, padding: &str, dilation: &mut u32) { + let enabled = has_width(padding); + let response = drawn::combo_button(ui, rect, ui.scope_id().with(("exp_dilation", id_salt)), &dilation.to_string(), enabled); + if !enabled { + response.on_hover_text(tr("This padding mode does not use a dilation width")); + return; + } + + // The menu stays open while the slider is used + let response = response.on_hover_text(tr("Dilation in pixels")); + egui::Popup::menu(&response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.label(tr("Dilation (pixels)")); + ui.add(egui::Slider::new(dilation, 0..=MAX_DILATION_PIXELS).step_by(1.0)); + }); +} + /// A greyed checkbox with its tooltip and the "not available" hint +#[cfg(target_arch = "wasm32")] fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { let mut off = false; ui.add_enabled(false, egui::Checkbox::new(&mut off, label)).on_disabled_hover_ui(|ui| { @@ -752,13 +974,21 @@ fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { }); } -/// The Global settings page -fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { - let mut reset = false; - header(ui, tr("General Export Parameters"), |ui| { - reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Restore the default export parameters"), false, ICON).clicked(); - }); - if reset { +/// A tick of the global page at `y` with its label after it +fn page_check(ui: &mut Ui, place: PagePlace, y: f32, on: &mut bool, label: &str) -> egui::Response { + let left = place.x(LABEL_LEFT + CHECK_INDENT); + let width = CHECK_LABEL_ROOM + drawn::text_width(ui, label, false); + let hit = egui::Rect::from_min_max(egui::pos2(left, y - CHECK_HIT_SIZE / 2.0), egui::pos2(left + width, y + CHECK_HIT_SIZE / 2.0)); + drawn::check(ui, ui.scope_id().with(("exp_check", label)), hit, egui::pos2(left, y), on, Some(label), label) +} + +/// The Global settings page, laid out from `place` +fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, builtins: &[ExportPreset]) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(GLOBAL_HEADER_Y), tr("General Export Parameters"), look.text, true); + let reset_at = place.right_inset(PAGE_ICON_FROM_RIGHT, GLOBAL_ICON_Y); + let reset_tip = tr("Restore the default export parameters"); + if drawn::icon_button(ui, reset_at, ic::ARROW_COUNTER_CLOCKWISE, MENU_ICON_SIZE, reset_tip, true, false).on_hover_text(reset_tip).clicked() { let defaults = ExportUi::default(); let settings = &mut app.ui.export; ( @@ -773,6 +1003,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] settings.color_space, settings.usd_asset, settings.materialx, + settings.shader_parameters, ) = ( defaults.dir, defaults.format, @@ -785,170 +1016,191 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] defaults.color_space, defaults.usd_asset, defaults.materialx, + defaults.shader_parameters, ); crate::export_templates::select(app, defaults.preset); } + + // One row per parameter at the reference's pitch; the browser has no output directory + let mut rows = (0..).map(|k| place.y(GLOBAL_FIRST_ROW_Y + k as f32 * GLOBAL_ROW_PITCH)); + let mut next_row = || rows.next().unwrap_or_default(); + let (left, right) = (place.x(CONTROLS_LEFT), place.right - CONTROLS_RIGHT_MARGIN); + #[cfg(not(target_arch = "wasm32"))] + output_directory(app, ui, place, next_row()); + + let y = next_row(); + row_label(ui, place, y, tr("Output template")); let (first, rest) = template_groups(app, builtins); - egui::Grid::new("exp_grid").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - // The browser downloads the files instead - #[cfg(not(target_arch = "wasm32"))] - output_directory(app, ui); - ui.label(tr("Output template")); - let mut picked = app.ui.export.preset.clone(); - if template_combo(ui, "exp_preset", &mut picked, &first, &rest) { - crate::export_templates::select(app, picked); + let mut picked = app.ui.export.preset.clone(); + if template_combo(&app.session, ui, drawn::control_rect(left, right, y), "exp_preset", &mut picked, &first, &rest) { + crate::export_templates::select(app, picked); + } + + // The file type list fits its longest entry, the bit depth list fills the rest + let y = next_row(); + row_label(ui, place, y, tr("File type")); + let type_right = left + drawn::text_width(ui, tr("Based on output template"), false) + FILE_TYPE_ROOM; + let rects = [drawn::control_rect(left, type_right, y), drawn::control_rect(type_right + PAIR_GAP, right, y)]; + let settings = &mut app.ui.export; + file_type_lists(ui, ("exp_global", 0, 0), true, rects, &mut settings.format, &mut settings.bit_depth, &mut settings.dithering); + + let y = next_row(); + row_label(ui, place, y, tr("Size")); + drawn::combo(ui, drawn::control_rect(left, right, y), "exp_size", size_label(settings.size), |ui| { + ui.selectable_value(&mut settings.size, 0, size_label(0)); + ui.separator(); + 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("File type")); - ui.horizontal(|ui| { - 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 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 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| { - let width = VALUE_WIDTH - DILATION_BUTTON_WIDTH - ui.spacing().item_spacing.x; - egui::ComboBox::from_id_salt("exp_pad").width(width).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, &settings.padding, &mut settings.dilation); - }); - ui.end_row(); }); - // 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("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures")); - #[cfg(target_arch = "wasm32")] - unavailable_checkbox( - ui, - tr("Export USD asset"), - tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"), - ); + let y = next_row(); + row_label(ui, place, y, tr("Padding")); + let padding_rect = drawn::control_rect(left, right - DILATION_WIDTH - PAIR_GAP, y); + drawn::combo(ui, padding_rect, "exp_pad", tr(padding_label(&settings.padding)), |ui| { + for (value, label) in PADDINGS { + ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); + } + }); + dilation_button(ui, drawn::control_rect(right - DILATION_WIDTH, right, y), "global", &settings.padding, &mut settings.dilation); - // The MaterialX export sits below the USD one; 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")); + let y = next_row(); + row_label(ui, place, y, tr("Normal map format")); + let normal_label = match settings.normal_format.as_str() { + "openGl" => "OpenGL", + "directX" => "DirectX", + _ => tr("From template / project"), + }; + drawn::combo(ui, drawn::control_rect(left, right, y), "exp_nf", normal_label, |ui| { + for (value, label) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] { + ui.selectable_value(&mut settings.normal_format, value.to_string(), label); + } + }); - // 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).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - let settings = &mut app.ui.export; - ui.label(tr("Normal map format")); - let normal_label = match settings.normal_format.as_str() { - "openGl" => "OpenGL", - "directX" => "DirectX", - _ => tr("From template / project"), + let y = next_row(); + row_label(ui, place, y, tr("Color space")); + let shown = if settings.color_space.is_empty() { tr("Default").to_string() } else { settings.color_space.clone() }; + let color_space = drawn::combo(ui, drawn::control_rect(left, right, y), "exp_cs", shown, |ui| { + 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 settings.color_space, name.to_string(), name); + } + }); + color_space.response.on_hover_text(tr("Color maps only: normal, roughness, metallic and other data maps stay linear")); + + // The extra files, ticked under the parameters + let mut checks = (0..).map(|k| y + CHECKS_GAP + k as f32 * CHECK_PITCH); + let mut next_check = || checks.next().unwrap_or_default(); + let usd_tip = tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"); + #[cfg(not(target_arch = "wasm32"))] + page_check(ui, place, next_check(), &mut settings.usd_asset, tr("Export USD asset")).on_hover_text(usd_tip); + #[cfg(not(target_arch = "wasm32"))] + page_check(ui, place, next_check(), &mut settings.materialx, tr("Export MaterialX")); + #[cfg(target_arch = "wasm32")] + { + let at = |y: f32| { + egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(egui::pos2(place.x(LABEL_LEFT), y - CHECK_HIT_SIZE / 2.0), vec2(right, CHECK_HIT_SIZE))) }; - 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 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 settings.color_space, String::new(), tr("Default")); - for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { - ui.selectable_value(&mut settings.color_space, name.to_string(), name); - } - }); - ui.end_row(); - }); + ui.scope_builder(at(next_check()), |ui| unavailable_checkbox(ui, tr("Export USD asset"), usd_tip)); + ui.scope_builder(at(next_check()), |ui| crate::unavailable::checkbox(ui, false, tr("Export MaterialX"))); + } + page_check(ui, place, next_check(), &mut settings.shader_parameters, tr("Export shader settings")) + .on_hover_text(tr("Save the settings of each shader instance in a JSON file")); } -/// The left column: Global settings, then a row per texture set with its export tick; a click -/// on a row shows the set's page, "*" marks a set with overrides -fn set_list(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| list_menu(ui, |ui| set_checks_menu(app, ui))); - }); - let header = list_row(ui, tr("Global settings"), app.ui.export.page.is_none()); - if header.clicked() { +/// The texture set list in `area`: Global settings, then a tick and a page per texture set, "*" on one with overrides +fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, area: egui::Rect) { + let top = area.top() - TAB_ROW_HEIGHT; + list_menu(ui, egui::pos2(area.left() + SET_MENU_X, top + SET_MENU_Y), tr("Texture set list menu"), |ui| set_checks_menu(app, ui)); + let rows_right = area.right() - GUTTER; + let header = egui::Rect::from_min_max(egui::pos2(area.left(), top + SET_ROWS_TOP), egui::pos2(rows_right, top + SET_ROWS_TOP + SET_ROW_HEIGHT)); + if list_row(ui, header, tr("Global settings"), app.ui.export.page.is_none()).clicked() { app.ui.export.page = None; } - // Many texture sets scroll inside the list; the footer stays in view - let list_height = ui.available_height(); - egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| set_rows(app, ui)); + // Many texture sets scroll under Global settings, the scroll bar in its strip at the list's right + let rows = egui::Rect::from_min_max(egui::pos2(area.left(), header.bottom()), area.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + egui::ScrollArea::vertical().id_salt("export_texture_sets").auto_shrink([false; 2]).show(ui, |ui| set_rows(app, ui, rows.width() - GUTTER)); + }); } -/// A row across the whole list, its name in bold; the selected one framed -fn list_row(ui: &mut Ui, text: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), LIST_ROW_HEIGHT), egui::Sense::click()); +/// A list row across `rect`, its name in bold +fn list_row(ui: &mut Ui, rect: egui::Rect, text: &str, selected: bool) -> egui::Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("exp_list_row", text)), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, text)); - - let painter = ui.painter(); - if selected { - painter.rect(rect, 0.0, tokens.row_selected, egui::Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); - } else if response.hovered() { - painter.rect_filled(rect, 0.0, tokens.row_hover); - } - let font = semibold(egui::TextStyle::Body.resolve(ui.style()).size); - painter.text(rect.left_center() + vec2(LIST_ROW_INDENT, 0.0), egui::Align2::LEFT_CENTER, text, font, tokens.text_strong); - paint_focus(ui, &response); + paint_row(ui, rect, selected, response.hovered()); + drawn::text_at(ui, rect.left() + GLOBAL_NAME_LEFT, rect.center().y, text, look.text, true); + drawn::paint_focus(ui, &response); response } -/// A row per texture set: its export tick, its name and the override mark -fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui) { +/// A list row's face: the selected one in the frame colour with a light edge; a hairline under every row +fn paint_row(ui: &Ui, rect: egui::Rect, selected: bool, hovered: bool) { + let look = ExportLook::get(ui.ctx()); + let painter = ui.painter(); + if selected { + painter.rect(rect, 0.0, look.chrome, egui::Stroke::new(1.0, look.outline), egui::StrokeKind::Inside); + } else if hovered { + painter.rect_filled(rect, 0.0, look.raised); + } + painter.rect_filled(egui::Rect::from_min_max(rect.left_bottom(), rect.right_bottom() + vec2(0.0, 1.0)), 0.0, look.chrome); +} + +/// A row per texture set, `width` wide: its export tick, its name and the override mark +fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32) { + let look = ExportLook::get(ui.ctx()); + ui.spacing_mut().item_spacing.y = 0.0; for i in 0..app.session.set_count() { let name = app.session.doc.project.texture_sets.get(i).map(|t| t.name.clone()).unwrap_or_default(); + let (row, _) = ui.allocate_exact_size(vec2(width, SET_ROW_HEIGHT), egui::Sense::hover()); + let y = row.center().y; + + // The tick leaves the set in or out, the name after it opens the set's page + let name_area = egui::Rect::from_min_max(egui::pos2(row.left() + SET_NAME_LEFT - drawn::CHECK_LABEL_GAP, row.top()), row.max); + let selected = app.ui.export.page == Some(i); + paint_row(ui, row, selected, ui.rect_contains_pointer(name_area)); let mut on = !app.ui.export.skip.contains(&i); - ui.horizontal(|ui| { - if ui.checkbox(&mut on, "").changed() { - if on { - app.ui.export.skip.retain(|x| *x != i); - } else { - app.ui.export.skip.push(i); - } + let tick_area = egui::Rect::from_min_max(row.min, egui::pos2(name_area.left(), row.bottom())); + let tick_name = trf("Include {set}", &[("set", &name)]); + if drawn::check(ui, ui.scope_id().with(("exp_set_tick", i)), tick_area, egui::pos2(row.left() + SET_CHECK_LEFT, y), &mut on, None, &tick_name).changed() + { + if on { + app.ui.export.skip.retain(|x| *x != i); + } else { + app.ui.export.skip.push(i); } - if ui.selectable_label(app.ui.export.page == Some(i), name).clicked() { - app.ui.export.page = Some(i); - } - if app.ui.export.sets.get(&i).is_some_and(SetExport::any) { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label("*").on_hover_text(tr("Override(s) active")); - }); - } - }); - ui.separator(); + } + + let page = ui.interact(name_area, ui.scope_id().with(("exp_set_row", i)), egui::Sense::click()); + page.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &name)); + if page.clicked() { + app.ui.export.page = Some(i); + } + + let color = if on { look.text } else { look.text_dim }; + drawn::text_at(ui, row.left() + SET_NAME_LEFT, y, &name, color, true); + drawn::paint_focus(ui, &page); + if app.ui.export.sets.get(&i).is_some_and(SetExport::any) { + drawn::label_at(ui, row.right() - OVERRIDE_MARK_FROM_RIGHT, y, "*", look.text_dim, true).on_hover_text(tr("Override(s) active")); + } } } -/// A texture set page row: the label, the override toggle, then the inherited value as text or, -/// overridden, `edit`; true when the toggle was clicked -fn override_row(ui: &mut Ui, label: &str, on: bool, inherited: &str, edit: impl FnOnce(&mut Ui)) -> bool { - ui.label(label); - let mut toggled = false; - ui.horizontal(|ui| { - toggled = icon_button(ui, ic::PENCIL_SIMPLE, tr("Enable override"), on, ICON).clicked(); - if on { - edit(ui); - } else { - ui.label(inherited); - } - }); - ui.end_row(); +/// A texture set page row at `y`: label, pen, then the inherited value or `edit`; true when the pen was clicked +fn override_row(ui: &mut Ui, place: PagePlace, y: f32, label: &str, on: bool, inherited: &str, edit: impl FnOnce(&mut Ui, egui::Rect)) -> bool { + let look = ExportLook::get(ui.ctx()); + row_label(ui, place, y, label); + let pen = egui::pos2(place.x(PEN_CENTRE), y); + let name = trf("Enable override for {setting}", &[("setting", &label)]); + let toggled = drawn::icon_button(ui, pen, ic::PENCIL_SIMPLE, drawn::CHEVRON_SIZE, &name, true, on).clicked(); + if on { + edit(ui, drawn::control_rect(place.x(OVERRIDE_LEFT), place.right - CONTROLS_RIGHT_MARGIN, y)); + } else { + drawn::label_at(ui, place.x(VALUE_LEFT), y, inherited, look.text, false); + } toggled } @@ -972,23 +1224,14 @@ fn toggle(o: &mut SetExport, row: usize, from: &InheritedSettings) { } } -/// A file type dropdown (without "Based on output template") and its bit depth -fn file_type_combo(ui: &mut Ui, id: (&str, usize, usize), t: &mut FileType) { - file_type_lists(ui, id, false, &mut t.format, &mut t.bit_depth, &mut t.dithering); -} - -/// A texture set's page: its overrides of the global settings -fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[ExportPreset]) { +/// A texture set's page from `place`: its overrides, then its output maps scrolling down to `bottom` +fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, bottom: f32, builtins: &[ExportPreset]) { let Some(set) = app.session.doc.project.texture_sets.get(ts) else { return }; let own = set.block_resolution(); let mut from = InheritedSettings::for_texture_set(app, own); - // "Based on output template": the override starts from what the template writes - if app.ui.export.format.is_empty() && app.ui.export.sets.get(&ts).is_none_or(|o| o.file_type.is_none()) { - from.file_type = template_file_type(app, ts); - } let (first, rest) = template_groups(app, builtins); - let first: Vec<(&str, bool)> = first.into_iter().filter(|(n, _)| !NOT_PER_SET.contains(n)).collect(); + let first: Vec<(&str, bool)> = first.into_iter().filter(|(name, _)| !NOT_PER_SET.contains(name)).collect(); let global = &app.ui.export; let inherited_file_type = if global.format.is_empty() { tr("Based on output template").to_string() } else { file_type_text(&from.file_type) }; let inherited_size = match global.size { @@ -997,135 +1240,131 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor }; let inherited_padding = tr(padding_label(&global.padding)).to_string(); - let o = app.ui.export.sets.entry(ts).or_default(); + let look = ExportLook::get(ui.ctx()); + let overrides = app.ui.export.sets.entry(ts).or_default(); let mut all = None; - header(ui, tr("General Export Parameters"), |ui| { - list_menu(ui, |ui| { - if ui.button(tr("Override every item")).clicked() { - all = Some(true); - } - if ui.button(tr("Clear all overrides")).clicked() { - all = Some(false); - } - ui.separator(); - }); + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(SET_HEADER_Y), tr("General Export Parameters"), look.text, true); + list_menu(ui, place.right_inset(PAGE_ICON_FROM_RIGHT, SET_HEADER_Y), tr("General Export Parameters menu"), |ui| { + if ui.button(tr("Override every item")).clicked() { + all = Some(true); + } + if ui.button(tr("Clear all overrides")).clicked() { + all = Some(false); + } + ui.separator(); }); + + let row_y = |row: usize| place.y(SET_FIRST_ROW_Y + row as f32 * SET_ROW_PITCH); let mut toggled = None; - egui::Grid::new(("exp_set_grid", ts)).num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - let on = o.preset.is_some(); - if override_row(ui, tr("Output template"), on, &from.preset, |ui| { - if let Some(p) = &mut o.preset { - template_combo(ui, "exp_set_preset", p, &first, &rest); - } - }) { - toggled = Some(0); + if override_row(ui, place, row_y(0), tr("Output template"), overrides.preset.is_some(), template_label(&app.session, &from.preset), |ui, rect| { + if let Some(preset) = &mut overrides.preset { + template_combo(&app.session, ui, rect, "exp_set_preset", preset, &first, &rest); } - let on = o.file_type.is_some(); - if override_row(ui, tr("File type"), on, &inherited_file_type, |ui| { - if let Some(t) = &mut o.file_type { - file_type_combo(ui, ("exp_set", ts, usize::MAX), t); - } - }) { - toggled = Some(1); - } - let on = o.size.is_some(); - if override_row(ui, tr("Size"), on, &inherited_size, |ui| { - if let Some(size) = &mut o.size { - egui::ComboBox::from_id_salt("exp_set_size").width(VALUE_WIDTH).selected_text(set_size_label(*size, own)).show_ui(ui, |ui| { - for r in SIZES { - ui.selectable_value(size, r, set_size_label(r, own)); - } - }); - } - }) { - toggled = Some(2); - } - let on = o.padding.is_some(); - if override_row(ui, tr("Padding"), on, &inherited_padding, |ui| { - if let Some((padding, dilation)) = &mut o.padding { - egui::ComboBox::from_id_salt("exp_set_pad").width(260.0).selected_text(tr(padding_label(padding))).show_ui(ui, |ui| { - for (v, l) in PADDINGS { - ui.selectable_value(padding, v.to_string(), tr(l)); - } - }); - dilation_button(ui, padding, dilation); - } - }) { - toggled = Some(3); - } - }); - if let Some(row) = toggled { - toggle(o, row, &from); + }) { + toggled = Some(0); } - match all { - Some(true) => { - for row in 0..4 { - let on = [o.preset.is_some(), o.file_type.is_some(), o.size.is_some(), o.padding.is_some()]; - if !on.get(row).copied().unwrap_or(true) { - toggle(o, row, &from); + if override_row(ui, place, row_y(1), tr("File type"), overrides.file_type.is_some(), &inherited_file_type, |ui, rect| { + if let Some(file_type) = &mut overrides.file_type { + let type_rect = rect.with_max_x(rect.left() + MAP_FORMAT_WIDTH); + let rects = [type_rect, rect.with_min_x(type_rect.right() + PAIR_GAP)]; + file_type_lists(ui, ("exp_set", ts, usize::MAX), false, rects, &mut file_type.format, &mut file_type.bit_depth, &mut file_type.dithering); + } + }) { + toggled = Some(1); + } + if override_row(ui, place, row_y(2), tr("Size"), overrides.size.is_some(), &inherited_size, |ui, rect| { + if let Some(size) = &mut overrides.size { + drawn::combo(ui, rect, "exp_set_size", set_size_label(*size, own), |ui| { + for side in SIZES { + ui.selectable_value(size, side, set_size_label(side, own)); + } + }); + } + }) { + toggled = Some(2); + } + if override_row(ui, place, row_y(3), tr("Padding"), overrides.padding.is_some(), &inherited_padding, |ui, rect| { + if let Some((padding, dilation)) = &mut overrides.padding { + drawn::combo(ui, rect.with_max_x(rect.right() - DILATION_WIDTH - PAIR_GAP), "exp_set_pad", tr(padding_label(padding)), |ui| { + for (value, label) in PADDINGS { + ui.selectable_value(padding, value.to_string(), tr(label)); + } + }); + dilation_button(ui, rect.with_min_x(rect.right() - DILATION_WIDTH), "set", padding, dilation); + } + }) { + toggled = Some(3); + } + if toggled.is_some() || all.is_some() { + // A new file-type override inherits the effective formats of the current template + if (toggled == Some(1) || all == Some(true)) && overrides.file_type.is_none() && app.ui.export.format.is_empty() { + from.file_type = template_file_type(app, ts); + } + + let overrides = app.ui.export.sets.entry(ts).or_default(); + if let Some(row) = toggled { + toggle(overrides, row, &from); + } + match all { + Some(true) => { + for row in 0..4 { + let on = [overrides.preset.is_some(), overrides.file_type.is_some(), overrides.size.is_some(), overrides.padding.is_some()]; + if !on.get(row).copied().unwrap_or(true) { + toggle(overrides, row, &from); + } } } + Some(false) => { + overrides.preset = None; + overrides.file_type = None; + overrides.size = None; + overrides.padding = None; + } + None => {} } - Some(false) => { - o.preset = None; - o.file_type = None; - o.size = None; - o.padding = None; - } - None => {} } - ui.add_space(8.0); - ui.separator(); - egui::ScrollArea::vertical().id_salt("exp_maps_scroll").auto_shrink([false; 2]).show(ui, |ui| output_maps(app, ui, ts)); + + // A divider across the page, then the output maps + let page_left = place.x(SET_LIST_WIDTH + 1.0); + drawn::divider(ui, egui::Rect::from_min_max(egui::pos2(page_left, place.y(SET_DIVIDER_Y)), egui::pos2(place.right, place.y(SET_DIVIDER_Y) + 1.0))); + let maps_area = egui::Rect::from_min_max(egui::pos2(page_left, place.y(MAPS_TOP)), egui::pos2(place.right, bottom)); + output_maps(app, ui, ts, place, maps_area); if app.ui.export.sets.get(&ts).is_some_and(SetExport::is_default) { app.ui.export.sets.remove(&ts); } } -/// The LIST OF EXPORTS console's and file tree's least width, as in the reference -const CONSOLE_WIDTH: f32 = 300.0; -const MIN_TREE_WIDTH: f32 = 300.0; -/// Width of the strip between the file tree and the console -const SPLITTER_WIDTH: f32 = 14.0; -/// Padding of the CONSOLE header band, about 45 points high as in the reference -const CONSOLE_HEADER_MARGIN_X: i8 = 12; -const CONSOLE_HEADER_MARGIN_Y: i8 = 14; -/// The file tree: indent of the file rows under their texture set, and the row height -const TREE_INDENT: f32 = 35.0; -const TREE_ROW_HEIGHT: f32 = 17.0; -/// Half the width of the tree's chevron -const CHEVRON_HALF_WIDTH: f32 = 4.0; - /// Green of the console's success lines fn success(tk: &Tokens) -> egui::Color32 { if tk.dark { egui::Color32::from_rgb(110, 200, 120) } else { egui::Color32::from_rgb(30, 130, 50) } } -/// The LIST OF EXPORTS tab: a tree of the files each ticked texture set exports (file, size, -/// file type, bit depth; the full path as tooltip), and the console -fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The LIST OF EXPORTS tab in `body`: the file tree with each file's path as tooltip, the fold strip and the console +fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { + let look = ExportLook::get(ui.ctx()); let tk = Tokens::get(ui.ctx()); let hidden = app.ui.export.console_hidden; - // Tree and console keep at least their reference width - let spacing = ui.spacing().item_spacing.x; - let room = ui.available_width() - SPLITTER_WIDTH - 2.0 * spacing; + // The console keeps at least its least width, the tree at least its own + let room = body.width() - STRIP_WIDTH - STRIP_GAP - 1.0; let console_width = app.ui.export.console_width.min(room - MIN_TREE_WIDTH).max(CONSOLE_WIDTH); - let tree_width = if hidden { room } else { room - console_width }; - ui.vertical(|ui| { - ui.set_width(tree_width); - egui::ScrollArea::vertical().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); + let console_left = if hidden { body.right() + 1.0 } else { body.right() - console_width }; + let strip = egui::Rect::from_min_max(egui::pos2(console_left - 1.0 - STRIP_WIDTH, body.top() + 1.0), egui::pos2(console_left - 1.0, body.bottom())); + let tree = egui::Rect::from_min_max(egui::pos2(body.left(), body.top() + 1.0), egui::pos2(strip.left() - STRIP_GAP, body.bottom())); + ui.painter().rect_filled(tree, 0.0, look.chrome); + ui.scope_builder(egui::UiBuilder::new().max_rect(tree), |ui| { + egui::ScrollArea::both().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); }); // The strip at the console's left edge: a click hides or shows the console, a drag resizes it - let (strip, response) = ui.allocate_exact_size(vec2(SPLITTER_WIDTH, ui.available_height()), egui::Sense::click_and_drag()); + drawn::divider(ui, egui::Rect::from_min_max(strip.right_top(), egui::pos2(strip.right() + 1.0, strip.bottom()))); + let response = ui.interact(strip, ui.scope_id().with("exp_console_strip"), egui::Sense::click_and_drag()); let tooltip = if hidden { tr("Show Console") } else { tr("Hide Console") }; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tooltip)); let glyph = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; - let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; - ui.painter().rect_filled(strip, 0.0, tk.chrome); - ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); - paint_focus(ui, &response); + let glyph_color = if response.hovered() { look.text } else { look.text_dim }; + drawn::glyph(ui, strip.center(), glyph, STRIP_GLYPH_SIZE, glyph_color); + drawn::paint_focus(ui, &response); let response = response.on_hover_text(tooltip); if !hidden && (response.hovered() || response.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); @@ -1135,31 +1374,33 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { } else if response.clicked() { app.ui.export.console_hidden = !hidden; } - if !hidden { - ui.vertical(|ui| { - ui.set_width(console_width); - egui::Frame::new().fill(tk.row).inner_margin(egui::Margin::symmetric(CONSOLE_HEADER_MARGIN_X, CONSOLE_HEADER_MARGIN_Y)).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(caption(&tr("Console").to_uppercase()).strong()); - }); - let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); - console.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show(ui, |ui| { - for line in &app.ui.export.console { - match line { - ConsoleLine::Step(t) => { - ui.label(t); - } - ConsoleLine::Done(t) => { - ui.label(RichText::new(t).color(success(&tk))); - } - ConsoleLine::Set(name) => { - ui.label(set_line(ui, name, &tk)); - } - } - } - }); - }); + if hidden { + return; } + + // The console: its header on the window colour, its lines on the frame colour below + let top = body.top() - TAB_ROW_HEIGHT; + let console = egui::Rect::from_min_max(egui::pos2(console_left, body.top() + 1.0), body.max); + drawn::label_at(ui, console.left() + CONSOLE_TEXT_INDENT, top + CONSOLE_HEADER_Y, tr("Console"), look.text, true); + let lines = egui::Rect::from_min_max(egui::pos2(console.left(), top + CONSOLE_BODY_TOP), console.max); + ui.painter().rect_filled(lines, 0.0, look.chrome); + let inner = lines.shrink2(vec2(0.0, CONSOLE_PADDING)).with_min_x(lines.left() + CONSOLE_TEXT_INDENT); + ui.scope_builder(egui::UiBuilder::new().max_rect(inner), |ui| { + let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); + console.show(ui, |ui| { + for (index, line) in app.ui.export.console.iter().enumerate() { + let response = match line { + ConsoleLine::Step(text) => ui.label(text), + ConsoleLine::Done(text) => ui.label(RichText::new(text).color(success(&tk))), + ConsoleLine::Set(name) => ui.label(set_line(ui, name, &tk)), + }; + + if index + 1 == app.ui.export.console.len() { + ui.ctx().accesskit_node_builder(response.id, |node| node.set_live(egui::accesskit::Live::Polite)); + } + } + }); + }); } /// "Texture set " with the name in bold @@ -1175,22 +1416,56 @@ fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { job } -/// One expandable node per ticked texture set, a row per file +/// One foldable node per ticked texture set, a row per file; the columns start after the longest file name fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { - if let Some(job) = &app.ui.export.job - && !job.preview.is_empty() - { - for (index, set) in job.preview.iter().enumerate() { - export_tree_set(ui, index, set, &job.directory, tk); + let (sets, directory): (Vec<(usize, ExportSetPlan)>, String) = match &app.ui.export.job { + Some(job) if !job.preview.is_empty() => (job.preview.iter().cloned().enumerate().collect(), job.directory.clone()), + _ => { + let planned = export_selection(app).into_iter().filter_map(|ts| { + let params = set_params(app, ts); + plan_set(app, ts, ¶ms).map(|set| (ts, set)) + }); + (planned.collect(), app.ui.export.dir.clone()) } - return; - } + }; + let rows: Vec> = sets.iter().map(|(_, set)| tree_files(set, &directory)).collect(); + let longest = |text: fn(&TreeFile) -> &str| rows.iter().flatten().map(|file| drawn::text_width(ui, text(file), false)).fold(0.0, f32::max); + let columns = { + let size = TREE_FILE_INDENT + longest(|f| &f.name) + TREE_COLUMN_GAP; + let format = size + longest(|f| &f.size) + TREE_COLUMN_GAP; + [size, format, format + longest(|f| &f.format) + TREE_BITS_GAP] + }; - for ts in export_selection(app) { - let params = set_params(app, ts); - if let Some(set) = plan_set(app, ts, ¶ms) { - export_tree_set(ui, ts, &set, &app.ui.export.dir, tk); + // Each set takes its header row, its files when open and a blank row + let open: Vec = sets.iter().map(|(index, _)| ui.data(|d| d.get_temp::(tree_id(ui, *index))).unwrap_or(true)).collect(); + let row_count: usize = sets + .iter() + .zip(&rows) + .zip(&open) + .map(|(((_, set), files), open)| 1 + 1 + if *open { files.len().max(usize::from(set.files.is_err())) } else { 0 }) + .sum(); + let width = ui.available_width().max(columns[2] + longest(|file| &file.bits) + TREE_BITS_GAP); + let height = TREE_TOP_PADDING + row_count as f32 * TREE_ROW_HEIGHT; + let (area, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); + + let mut y = area.top() + TREE_TOP_PADDING; + for (((index, set), files), open) in sets.iter().zip(&rows).zip(open) { + let header = egui::Rect::from_min_max(egui::pos2(area.left(), y), egui::pos2(area.right(), y + TREE_ROW_HEIGHT)); + if tree_header(ui, header, &set.name, open, tree_id(ui, *index)) { + ui.data_mut(|d| d.insert_temp(tree_id(ui, *index), !open)); } + y += TREE_ROW_HEIGHT; + if open { + if let Err(error) = &set.files { + drawn::label_at(ui, area.left() + TREE_FILE_INDENT, y + TREE_ROW_HEIGHT / 2.0, error, tk.danger, false); + y += TREE_ROW_HEIGHT; + } + for file in files { + tree_file(ui, area.left(), y + TREE_ROW_HEIGHT / 2.0, columns, file); + y += TREE_ROW_HEIGHT; + } + } + y += TREE_ROW_HEIGHT; } } @@ -1202,47 +1477,75 @@ fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) Some(ExportSetPlan { index: Some(index), name, files }) } -fn export_tree_set(ui: &mut Ui, index: usize, set: &ExportSetPlan, directory: &str, tokens: &Tokens) { - ui.spacing_mut().indent = TREE_INDENT; - let header = egui::CollapsingHeader::new(&set.name).id_salt(("exp_tree", index)).default_open(true).icon(chevron); - header.show(ui, |ui| match &set.files { - Ok(files) => { - egui::Grid::new(("exp_tree_grid", index)).num_columns(4).min_row_height(TREE_ROW_HEIGHT).spacing(vec2(12.0, 4.0)).show(ui, |ui| { - for output in files.as_array().into_iter().flatten() { - let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); - let format = FileFormat::from_extension(output.get("format").and_then(serde_json::Value::as_str).unwrap_or_default()); - let depth = output.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; - let dithering = output.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let size = output["size"].as_u64().unwrap_or_default() as u32; - let source_size = output["sourceSize"].as_u64().unwrap_or_default() as u32; - let path = std::path::Path::new(directory).join(file).display().to_string(); - ui.label(file).on_hover_text(&path); - ui.label(set_size_label(size, source_size)).on_hover_text(&path); - ui.label(format.map_or("", FileFormat::name)).on_hover_text(&path); - ui.label(depth_label(format, depth, dithering)).on_hover_text(&path); - ui.end_row(); - } - }); - } - Err(error) => { - ui.label(RichText::new(error).color(tokens.danger)); - } - }); +/// Where a texture set's node keeps whether it is open +fn tree_id(ui: &Ui, index: usize) -> egui::Id { + ui.scope_id().with(("exp_tree", index)) } -/// The tree's outline chevron: pointing down when open, right (left in right-to-left) when closed -fn chevron(ui: &mut Ui, openness: f32, response: &egui::Response) { - let color = Tokens::get(ui.ctx()).text; - let center = response.rect.center(); - let half = CHEVRON_HALF_WIDTH; - let points = if openness > 0.5 { - [center + vec2(-half, -half / 2.0), center + vec2(0.0, half / 2.0), center + vec2(half, -half / 2.0)] - } else if ui.style().right_to_left { - [center + vec2(half / 2.0, -half), center + vec2(-half / 2.0, 0.0), center + vec2(half / 2.0, half)] - } else { - [center + vec2(-half / 2.0, -half), center + vec2(half / 2.0, 0.0), center + vec2(-half / 2.0, half)] +/// The texts of each file `set` plans: name, size, file type, bit depth and its whole path +fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { + let Ok(files) = &set.files else { return Vec::new() }; + + let to_text = |output: &serde_json::Value| { + let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); + let format = FileFormat::from_extension(output.get("format").and_then(serde_json::Value::as_str).unwrap_or_default()); + let depth = output.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; + let dithering = output.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); + let size = output["size"].as_u64().unwrap_or_default() as u32; + let source_size = output["sourceSize"].as_u64().unwrap_or_default() as u32; + TreeFile { + name: file.to_string(), + size: set_size_label(size, source_size), + format: format.map_or("", FileFormat::name).to_string(), + bits: depth_label(format, depth, dithering), + path: std::path::Path::new(directory).join(file).display().to_string(), + } }; - ui.painter().add(egui::Shape::line(points.to_vec(), egui::Stroke::new(1.5, color))); + files.as_array().into_iter().flatten().map(to_text).collect() +} + +/// A texture set's node row: the chevron and its name in bold; true when clicked +fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui::Id) -> bool { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, id, egui::Sense::click()); + + // Expose the hand-drawn header as a disclosure control + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, true, name)); + + let y = rect.center().y; + let chevron = if open { + ic::CARET_DOWN + } else if ui.style().right_to_left { + ic::CARET_LEFT + } else { + ic::CARET_RIGHT + }; + drawn::glyph(ui, egui::pos2(rect.left() + TREE_CHEVRON_X, y), chevron, drawn::CHEVRON_SIZE, look.text); + drawn::text_at(ui, rect.left() + TREE_NAME_INDENT, y, name, look.text, true); + drawn::paint_focus(ui, &response); + + if response.has_focus() && rect.width() > ui.clip_rect().width() { + let direction = ui.input_mut(|input| { + let start = input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft); + let end = input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowRight); + i8::from(start) - i8::from(end) + }); + if direction != 0 { + ui.memory_mut(|memory| memory.move_focus(egui::FocusDirection::None)); + ui.scroll_with_delta(vec2(f32::from(direction) * ui.clip_rect().width() / 2.0, 0.0)); + } + } + + response.clicked() +} + +/// A file's row at `y`: its name, then size, file type and bit depth in `columns`, each with the whole path as tooltip +fn tree_file(ui: &mut Ui, left: f32, y: f32, columns: [f32; 3], file: &TreeFile) { + let look = ExportLook::get(ui.ctx()); + let texts = [(TREE_FILE_INDENT, &file.name), (columns[0], &file.size), (columns[1], &file.format), (columns[2], &file.bits)]; + for (x, text) in texts { + drawn::label_at(ui, left + x, y, text, look.text, false).on_hover_text(&file.path); + } } /// Show the output folder in the system's file manager (created first when missing) @@ -1422,8 +1725,106 @@ fn cancel(app: &mut TextureCraftApp) { app.ui.windows.export = false; } +/// Escape closes the window as Cancel does after shortcut routing checks higher-priority inputs. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { + if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { + app.ui.export.job = None; + cancel(app); + } +} + +/// The bottom bar: Export, Save settings, Cancel and the texture count, Reset all on SETTINGS; while exporting, progress +fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do_export: &mut bool, canceled: &mut bool) { + let slot = |k: f32| { + let right = window.right() - RIGHT_MARGIN - k * (FOOTER_BUTTON_WIDTH + FOOTER_BUTTON_GAP); + drawn::control_rect(right - FOOTER_BUTTON_WIDTH, right, y) + }; + if let Some(job) = &app.ui.export.job { + let done = job.total - job.pending.len(); + let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; + if drawn::button(ui, slot(0.0), tr("Cancel Export"), false, true).clicked() { + app.ui.export.job = None; + } + let bar = drawn::control_rect(window.left() + LEFT_MARGIN, slot(0.0).left() - FOOTER_BUTTON_GAP, y); + let look = ExportLook::get(ui.ctx()); + let response = ui.put(bar, egui::ProgressBar::new(progress).fill(look.outline).text(format!("{:.0}%", progress * 100.0))); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_live(egui::accesskit::Live::Polite)); + return; + } + + // OUTPUT TEMPLATES shows no count; a template edit that does not validate holds Save and Export + let templates_tab = app.ui.export.tab == 1; + let draft_valid = app.ui.export.draft.as_ref().is_none_or(|draft| draft.validate().is_ok()); + let any = !export_selection(app).is_empty() && draft_valid; + let export = drawn::button(ui, slot(0.0), tr("Export"), true, any); + if export.on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")).clicked() { + *do_export = true; + } + + // Saving closes the window without starting an export + let save = drawn::button(ui, slot(1.0), tr("Save settings"), false, draft_valid); + if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { + app.ui.windows.export = false; + } + let cancel = drawn::button(ui, slot(2.0), tr("Cancel"), false, true); + if cancel.on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { + *canceled = true; + } + if !templates_tab { + let look = ExportLook::get(ui.ctx()); + let count = trf("{n} textures selected for export", &[("n", &selected_texture_count(app))]); + let left = slot(2.0).left() - COUNT_GAP - drawn::text_width(ui, &count, false); + drawn::label_at(ui, left, y, &count, look.text_dim, false); + } + + let reset_rect = drawn::control_rect(window.left() + LEFT_MARGIN, window.left() + LEFT_MARGIN + FOOTER_BUTTON_WIDTH, y); + if app.ui.export.tab == 0 + && drawn::button(ui, reset_rect, tr("Reset all"), false, true).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() + { + // Keep ownership so Cancel can restore the opening settings + let e = &mut app.ui.export; + let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); + app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; + } +} + +/// The SETTINGS tab in `body`: the texture set list, a divider, then the selected page +fn settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect, presets: &[ExportPreset]) { + let list = body.with_max_x(body.left() + SET_LIST_WIDTH); + set_list(app, ui, list); + drawn::divider(ui, egui::Rect::from_min_max(list.right_top(), list.right_bottom() + vec2(1.0, 0.0))); + let page = body.with_min_x(list.right() + 1.0); + match app.ui.export.page { + Some(ts) if ts < app.session.set_count() => { + ui.scope_builder(egui::UiBuilder::new().max_rect(page), |ui| { + egui::ScrollArea::both().id_salt("export_texture_set_page").auto_shrink([false; 2]).show(ui, |ui| { + let size = vec2(ui.available_width().max(MIN_PAGE_WIDTH), ui.available_height().max(MIN_SET_PAGE_HEIGHT)); + let (content, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + let place = PagePlace { left: content.left() - list.width() - 1.0, top: content.top() - TAB_ROW_HEIGHT, right: content.right() }; + set_page(app, ui, ts, place, content.bottom(), presets); + }); + }); + } + + // A short or narrow window scrolls the page, so every control stays reachable + _ => { + ui.scope_builder(egui::UiBuilder::new().max_rect(page), |ui| { + egui::ScrollArea::both().id_salt("export_settings_page").auto_shrink([false; 2]).show(ui, |ui| { + let size = vec2(ui.available_width().max(MIN_PAGE_WIDTH), GLOBAL_PAGE_HEIGHT); + let (content, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + let place = PagePlace { left: content.left() - list.width() - 1.0, top: content.top() - TAB_ROW_HEIGHT, right: content.right() }; + global_page(app, ui, place, presets); + }); + }); + } + } +} + pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let showing_templates = app.ui.export.tab == 1; if !app.ui.windows.export { + crate::export_templates::clear_map_previews(ctx); + // The window opens on SETTINGS again; an export stops with it let e = &mut app.ui.export; e.job = None; @@ -1436,7 +1837,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } // Settings saved under the default template's old name - if let Some(b) = texturecraft_engine::formats::builtin_preset(&app.ui.export.preset) + if !app.session.has_user_export_preset(&app.ui.export.preset) + && let Some(b) = texturecraft_engine::formats::builtin_preset(&app.ui.export.preset) && b.name != app.ui.export.preset { app.ui.export.preset = b.name; @@ -1457,15 +1859,19 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let mut do_export = false; let mut canceled = false; - let presets = texturecraft_engine::formats::builtin_presets(); - // The reference size on a screen that has room for it, smaller on a smaller one; resizable from there. - // The window's size counts its frame and title bar, the reference size only the content + let presets = texturecraft_engine::formats::builtin_preset_catalog(); + let look = ExportLook::get(ctx); + + // The reference size includes the frame and title bar let style = ctx.global_style(); + let title_frame = egui::Frame::window(&style); + let frame = title_frame.inner_margin(CONTENT_INSET); let title_height = ctx.fonts_mut(|fonts| fonts.row_height(&egui::TextStyle::Heading.resolve(&style))) + style.spacing.item_spacing.y; - let chrome = egui::Frame::window(&style).total_margin().sum() + vec2(0.0, title_height); + let chrome = vec2(frame.total_margin().sum().x, title_frame.total_margin().sum().y + title_height); let window_size = (REFERENCE_WINDOW_SIZE_POINTS + chrome).min(ctx.content_rect().size() - vec2(WINDOW_VIEWPORT_MARGIN_POINTS, WINDOW_VIEWPORT_MARGIN_POINTS)); - let dialog = crate::windows::dialog(ctx, "export_textures", tr("Export Textures"), &mut open).default_size(window_size); + let dialog = + crate::windows::dialog(ctx, "export_textures", tr("Export textures"), &mut open).title_frame(title_frame).frame(frame).default_size(window_size); dialog.show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { @@ -1473,140 +1879,69 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { - // While exporting: the progress and Cancel Export - if let Some(job) = &app.ui.export.job { - let done = job.total - job.pending.len(); - let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Cancel Export")).clicked() { - app.ui.export.job = None; - } - let percent = format!("{:.0}%", progress * 100.0); - ui.add(egui::ProgressBar::new(progress).text(percent)); - }); - }); - } else { - // OUTPUT TEMPLATES edits the templates only: no count, nothing to reset, save or export there - let templates_tab = app.ui.export.tab == 1; - let selected = if templates_tab { 0 } else { selected_texture_count(app) }; - ui.horizontal(|ui| { - // Only on SETTINGS - if app.ui.export.tab == 0 - && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() - { - // Keep ownership so Cancel can restore the opening settings - let e = &mut app.ui.export; - let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); - app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // Nothing to write without a ticked texture set - let any = !export_selection(app).is_empty() && !templates_tab; - if ui - .add_enabled(any, footer_button(tr("Export"))) - .on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")) - .clicked() - { - do_export = true; - } + look.apply(ui.style_mut()); + let window = ui.max_rect(); + ui.allocate_rect(window, egui::Sense::hover()); + let body = + egui::Rect::from_min_max(egui::pos2(window.left(), window.top() + TAB_ROW_HEIGHT), egui::pos2(window.right(), window.bottom() - FOOTER_HEIGHT)); - // Saving closes the window without starting an export - let save = ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))); - if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { - app.ui.windows.export = false; - } - if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { - canceled = true; - } - if !templates_tab { - ui.label(trf("{n} textures selected for export", &[("n", &selected)])); - } - }); - }); - } - ui.separator(); - ui.add_space(8.0); - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.horizontal(|ui| { - // Boxed tabs side by side - ui.scope(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { - if tab_button(ui, &t.to_uppercase(), app.ui.export.tab == i as u8).clicked() { - app.ui.export.tab = i as u8; - } - } - }); + // The tabs, and the tab's own control at the row's right end + let tab_strip = egui::Rect::from_min_max(egui::pos2(window.left(), window.top() + TAB_TOP), egui::pos2(window.right(), body.top())); + let labels = [tr("Settings"), tr("Output templates"), tr("List of exports")]; + if let Some(tab) = drawn::tabs(ui, tab_strip, window.left() + TABS_LEFT, &labels, usize::from(app.ui.export.tab)) { + app.ui.export.tab = tab as u8; + } + let right = window.right() - RIGHT_MARGIN; + let row_y = window.top() + TAB_ROW_CONTROLS_Y; + match app.ui.export.tab { + 1 => crate::export_templates::naming_pattern(ui, window.right(), row_y), + 2 => { + let width = drawn::text_width(ui, tr("Open output directory"), false) + OPEN_DIRECTORY_PADDING; + let rect = drawn::control_rect(window.right() - OPEN_DIRECTORY_FROM_RIGHT - width, window.right() - OPEN_DIRECTORY_FROM_RIGHT, row_y); - // The file list opens the destination folder - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if app.ui.export.tab == 2 { - // The browser downloads the files instead - #[cfg(target_arch = "wasm32")] - crate::unavailable::greyed(ui, |ui| ui.button(tr("Open output directory"))); - #[cfg(not(target_arch = "wasm32"))] - if ui.button(tr("Open output directory")).clicked() { - open_output_directory(app); - } - } else if app.ui.export.tab == 1 { - crate::export_templates::naming_pattern(ui); - } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { - app.ui.export.skip.clear(); - for o in app.ui.export.sets.values_mut() { - o.maps.values_mut().for_each(|m| m.enabled = true); - } - app.ui.export.sets.retain(|_, o| !o.is_default()); - } - }); - }); - ui.separator(); - let body = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), ui.available_height().max(0.0))); - - // The tabs size their columns from the body's width. A child that cannot widen the - // resizable window holds them, so an overflow is clipped instead of growing the window each frame - let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); - body_ui.shrink_clip_rect(body); - ui.advance_cursor_after_rect(body); - let ui = &mut body_ui; - 'tab: { - ui.set_height(body.height()); - match app.ui.export.tab { - 1 => { - crate::export_templates::tab(app, ui, &presets); - break 'tab; - } - 2 => { - list_tab(app, ui); - break 'tab; - } - _ => {} - } - - ui.vertical(|ui| { - ui.set_width(LIST_WIDTH); - set_list(app, ui); - }); - ui.separator(); - - // A short or narrow window scrolls the settings, so the footer and every control stay reachable - ui.vertical(|ui| { - egui::ScrollArea::both().id_salt("export_settings_page").auto_shrink([false, false]).min_scrolled_height(0.0).show(ui, |ui| match app - .ui - .export - .page - { - Some(ts) if ts < app.session.set_count() => set_page(app, ui, ts, &presets), - _ => global_page(app, ui, &presets), - }); - }); + // The browser downloads the files instead + #[cfg(target_arch = "wasm32")] + drawn::button(ui, rect, tr("Open output directory"), false, false).on_hover_text(tr(NOT_AVAILABLE)); + #[cfg(not(target_arch = "wasm32"))] + if drawn::button(ui, rect, tr("Open output directory"), false, true).clicked() { + open_output_directory(app); } - }); - }); + } + _ => { + let rect = drawn::control_rect(right - FOOTER_BUTTON_WIDTH, right, row_y); + if drawn::button(ui, rect, tr("Include all"), false, true).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { + app.ui.export.skip.clear(); + for o in app.ui.export.sets.values_mut() { + o.maps.values_mut().for_each(|m| m.enabled = true); + } + app.ui.export.sets.retain(|_, o| !o.is_default()); + } + } + } + + let footer_y = window.bottom() - FOOTER_MIDDLE_FROM_BOTTOM; + drawn::divider(ui, egui::Rect::from_min_max(body.left_bottom(), body.right_bottom() + vec2(0.0, 1.0))); + footer(app, ui, window, footer_y, &mut do_export, &mut canceled); + + // The tabs lay out from the body; a child clips what an overflow would draw past it + let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body)); + body_ui.shrink_clip_rect(body); + let ui = &mut body_ui; + match app.ui.export.tab { + 1 => crate::export_templates::tab(app, ui, body, presets), + 2 => list_tab(app, ui, body), + _ => settings_tab(app, ui, body, presets), + } }); crate::export_templates::ask(app, ctx); + // Keep text focus before egui clears it on Escape + app.ui.export.field_had_keyboard = ctx.text_edit_focused(); + + if (showing_templates || app.ui.export.tab == 1) && (canceled || !open || !app.ui.windows.export || app.ui.export.tab != 1 || do_export) { + crate::export_templates::clear_map_previews(ctx); + } + // Dismissal must run before the next write if canceled || !open { app.ui.export.job = None; diff --git a/crates/ui-egui/src/export_window/drawn.rs b/crates/ui-egui/src/export_window/drawn.rs new file mode 100644 index 00000000..9f92508f --- /dev/null +++ b/crates/ui-egui/src/export_window/drawn.rs @@ -0,0 +1,334 @@ +//! The Export textures window's own controls, drawn at the places its layout gives them: tabs, +//! checks, dropdowns, buttons and icon buttons in the window's colours ([`ExportLook`]) + +use egui::{Align2, Color32, CornerRadius, FontId, Id, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::export_look::{CONTROL_HEIGHT, CONTROL_RADIUS, ExportLook, TEXT_SIZE}; +use crate::theme::semibold; + +/// Side and corner radius of a check box +const CHECK_SIZE: f32 = 13.0; +const CHECK_RADIUS: u8 = 2; + +/// The tick inside a check box: its three points from the box's left edge and centre, and its width +const TICK_POINTS: [(f32, f32); 3] = [(3.2, 0.2), (5.6, 2.6), (9.8, -2.6)]; +const TICK_WIDTH: f32 = 1.7; + +/// Air between a check box and its label +pub(crate) const CHECK_LABEL_GAP: f32 = 5.0; + +/// From a dropdown's left edge to its value, and from its right edge to its chevron's centre +pub(crate) const VALUE_INSET: f32 = 7.0; +pub(crate) const CHEVRON_INSET: f32 = 11.0; + +/// Size of a chevron and of the window's icons +pub(crate) const CHEVRON_SIZE: f32 = 12.0; + +/// The air on either side of a tab's name +const TAB_PADDING: f32 = 14.0; +/// A tab's corner radius +const TAB_RADIUS: u8 = 4; +/// Gap between tabs +const TAB_GAP: f32 = 3.0; +/// How far a tab reaches under the divider, where the body's colour covers its lower corners +const TAB_OVERLAP: f32 = 4.0; + +/// A quiet dropdown's hover face: its padding round the value and chevron, and half its height +const TEXT_DROPDOWN_PADDING: f32 = 3.0; +const TEXT_DROPDOWN_HALF_HEIGHT: f32 = 9.0; + +/// Hit area of an icon button around its glyph +const ICON_HIT_SIZE: f32 = 20.0; + +/// Width of the keyboard focus outline on the window's drawn controls +const FOCUS_OUTLINE_WIDTH: f32 = 2.0; + +/// Whether a control that cannot be used looks greyed; a built-in template's cards keep their look +pub(crate) fn looks_disabled(ui: &Ui, enabled: bool) -> bool { + !enabled && ui.visuals().disabled_alpha() < 1.0 +} + +/// The window's regular and semibold text +pub(crate) fn font(bold: bool) -> FontId { + if bold { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) } +} + +/// Width of `text` in the window's font +pub(crate) fn text_width(ui: &Ui, text: &str, bold: bool) -> f32 { + ui.painter().layout_no_wrap(text.to_owned(), font(bold), Color32::WHITE).size().x +} + +/// `text` with its left edge at `left` and its middle at `y` +pub(crate) fn text_at(ui: &Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Rect { + ui.painter().text(pos2(left, y), Align2::LEFT_CENTER, text, font(bold), color) +} + +/// `text` cut with "…" at its end (or its start, for file names) to fit `room` +pub(crate) fn fitted(ui: &Ui, text: &str, room: f32, from_start: bool, bold: bool) -> String { + if text_width(ui, text, bold) <= room { + return text.to_owned(); + } + + let mut cuts: Vec<_> = text.char_indices().skip(1).map(|(offset, _)| offset).collect(); + if !from_start { + cuts.reverse(); + } + + let truncate = |cut| if from_start { format!("…{}", &text[cut..]) } else { format!("{}…", &text[..cut]) }; + let first_fit = cuts.partition_point(|&cut| text_width(ui, &truncate(cut), bold) > room); + cuts.get(first_fit).map_or_else(|| "…".to_owned(), |&cut| truncate(cut)) +} + +/// A glyph centred on `centre` +pub(crate) fn glyph(ui: &Ui, centre: Pos2, glyph: &str, size: f32, color: Color32) { + ui.painter().text(centre, Align2::CENTER_CENTER, glyph, FontId::proportional(size), color); +} + +/// The keyboard focus outline of a drawn control, in the text colour +pub(crate) fn paint_focus(ui: &Ui, response: &Response) { + if response.has_focus() { + let stroke = Stroke::new(FOCUS_OUTLINE_WIDTH, ExportLook::get(ui.ctx()).text); + ui.painter().rect_stroke(response.rect, CONTROL_RADIUS, stroke, StrokeKind::Inside); + } +} + +/// A horizontal or vertical divider line, one point thick +pub(crate) fn divider(ui: &Ui, rect: Rect) { + ui.painter().rect_filled(rect, 0.0, ExportLook::get(ui.ctx()).divider); +} + +/// Sentence-case rounded tabs along `strip`'s bottom from `left`, the open one joined to the body; returns the clicked one +pub(crate) fn tabs(ui: &mut Ui, strip: Rect, left: f32, labels: &[&str], open: usize) -> Option { + let look = ExportLook::get(ui.ctx()); + let bottom = strip.bottom(); + divider(ui, Rect::from_min_max(pos2(strip.left(), bottom - 1.0), pos2(strip.right(), bottom))); + let mut clicked = None; + let mut x = left; + for (index, label) in labels.iter().enumerate() { + let selected = index == open; + let width = text_width(ui, label, selected) + 2.0 * TAB_PADDING; + let rect = Rect::from_min_max(pos2(x, strip.top()), pos2(x + width, bottom)); + let response = ui.interact(rect, ui.scope_id().with(("export_tab", index)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, selected, *label)); + + // The tab's lower corners reach under the divider and are covered by the body's colour + let painter = ui.painter(); + let face = Rect::from_min_max(rect.min, pos2(rect.right(), bottom + TAB_OVERLAP)); + let below = Rect::from_min_max(pos2(rect.left(), bottom - 1.0), pos2(rect.right(), bottom + TAB_OVERLAP + 1.0)); + if selected { + painter.rect(face, TAB_RADIUS, look.window, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.rect_filled(below.shrink2(vec2(1.0, 0.0)), 0.0, look.window); + } else { + let fill = if response.hovered() { look.raised } else { look.chrome }; + painter.rect_filled(face.with_min_y(face.top() + 1.0), TAB_RADIUS, fill); + painter.rect_filled(below, 0.0, look.window); + painter.rect_filled(below.with_max_y(bottom), 0.0, look.divider); + } + let color = if selected || response.hovered() { look.text } else { look.text_dim }; + painter.text(rect.center() + vec2(0.0, 1.0), Align2::CENTER_CENTER, *label, font(selected), color); + paint_focus(ui, &response); + if response.clicked() { + clicked = Some(index); + } + x += width + TAB_GAP; + } + clicked +} + +/// A check box from `left` with its middle at `y`: dim and ticked when on, dark with a light edge when off +pub(crate) fn paint_check(ui: &Ui, left: f32, y: f32, on: bool) { + let look = ExportLook::get(ui.ctx()); + let rect = Rect::from_min_size(pos2(left, y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); + let painter = ui.painter(); + if on { + painter.rect_filled(rect, CHECK_RADIUS, look.text_dim); + let points = TICK_POINTS.iter().map(|(dx, dy)| pos2(left + dx, y + dy)).collect(); + painter.add(egui::Shape::line(points, Stroke::new(TICK_WIDTH, look.window))); + } else { + painter.rect(rect, CHECK_RADIUS, look.control, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + } +} + +/// A check box at `at` (its left edge's middle) with `label` after it, toggled by a click in `hit` +pub(crate) fn check(ui: &mut Ui, id: Id, hit: Rect, at: Pos2, on: &mut bool, label: Option<&str>, name: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let mut response = ui.interact(hit, id, Sense::click()); + if response.clicked() { + *on = !*on; + response.mark_changed(); + } + let checked = *on; + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, checked, name)); + paint_check(ui, at.x, at.y, checked); + if let Some(label) = label { + text_at(ui, at.x + CHECK_SIZE + CHECK_LABEL_GAP, at.y, label, look.text, false); + } + paint_focus(ui, &response); + response +} + +/// The rect of a control `left`..`right` with its middle at `y` +pub(crate) fn control_rect(left: f32, right: f32, y: f32) -> Rect { + Rect::from_min_max(pos2(left, y - CONTROL_HEIGHT / 2.0), pos2(right, y + CONTROL_HEIGHT / 2.0)) +} + +/// A dropdown's chevron, pointing up while its list is open, drawn just inside the right edge of the button `rect` +pub(crate) fn chevron_icon(ui: &Ui, rect: Rect, visuals: &egui::style::WidgetVisuals, open: bool) { + let centre = pos2(rect.right() + VALUE_INSET - CHEVRON_INSET, rect.center().y); + glyph(ui, centre, if open { ic::CARET_UP } else { ic::CARET_DOWN }, CHEVRON_SIZE, visuals.fg_stroke.color); +} + +/// A dropdown filling `rect`, showing `shown`, its list as wide as it and flush under it +pub(crate) fn combo( + ui: &mut Ui, + rect: Rect, + id: impl std::hash::Hash + std::fmt::Debug, + shown: impl Into, + list: impl FnOnce(&mut Ui) -> R, +) -> egui::InnerResponse> { + let look = ExportLook::get(ui.ctx()); + let shown: String = shown.into(); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { + egui::ComboBox::from_id_salt(id) + .width(rect.width()) + .height(f32::INFINITY) + .selected_text(shown) + .wrap_mode(egui::TextWrapMode::Truncate) + .icon(chevron_icon) + .popup_style(look.list_style()) + .show_ui(ui, list) + }) + .inner +} + +/// A button drawn as a dropdown showing `shown`, for a menu that is no option list; lighter when it cannot be used +pub(crate) fn combo_button(ui: &mut Ui, rect: Rect, id: Id, shown: &str, enabled: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, id, sense); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, shown)); + let (fill, color) = match (enabled, response.hovered()) { + (false, _) => (look.raised, look.text_dim), + (true, true) => (look.raised, look.text), + (true, false) => (look.control, look.text), + }; + let painter = ui.painter(); + painter.rect(rect, CONTROL_RADIUS, fill, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), color); + glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, color); + paint_focus(ui, &response); + response +} + +/// A field showing `text` cut with "…" at its end that acts as a button, as the output directory does +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn field_button(ui: &mut Ui, rect: Rect, id: Id, text: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, text)); + let border = if response.hovered() { look.outline } else { look.control_border }; + ui.painter().rect(rect, CONTROL_RADIUS, look.control, Stroke::new(1.0, border), StrokeKind::Inside); + let shown = fitted(ui, text, rect.width() - 2.0 * VALUE_INSET, false, false); + text_at(ui, rect.left() + VALUE_INSET, rect.center().y, &shown, look.text, false); + paint_focus(ui, &response); + response +} + +/// A dropdown that cannot be used: a step lighter than the others, its value and chevron dim; `id` tells it from the rows' other ones +pub(crate) fn disabled_combo(ui: &mut Ui, rect: Rect, id: impl std::hash::Hash + std::fmt::Debug, shown: &str, name: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("export_disabled_combo", id)), Sense::hover()); + response.widget_info(|| { + let mut info = WidgetInfo::labeled(Role::ComboBox, false, name); + info.current_text_value = Some(shown.to_owned()); + info + }); + let painter = ui.painter(); + painter.rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), look.text_dim); + glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, look.text_dim); + response +} + +/// Text that reads as a label to assistive technology and tests: `text` from `left`, its middle at `y`; its response takes a tooltip +pub(crate) fn label_at(ui: &mut Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Response { + let rect = text_at(ui, left, y, text, color, bold); + let response = ui.interact(rect, ui.scope_id().with(("export_label", text, left.to_bits(), y.to_bits())), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, text)); + response +} + +/// A button filling `rect`: a step darker than the window with a light edge, or the accent for the one primary action +pub(crate) fn button(ui: &mut Ui, rect: Rect, label: &str, primary: bool, enabled: bool) -> Response { + let id = ui.scope_id().with(("export_button", label)); + button_with_id(ui, id, rect, label, label, primary, enabled) +} + +/// [`button`] for one of several buttons with the same label (each output map card's "$") +pub(crate) fn button_with_id(ui: &mut Ui, id: Id, rect: Rect, label: &str, name: &str, primary: bool, enabled: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, id, sense); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, name)); + let (fill, border) = match (primary, enabled && response.hovered()) { + (true, _) => (look.accent, look.accent), + (false, true) => (look.raised, look.outline), + (false, false) => (look.control, look.control_border), + }; + let painter = ui.painter(); + let fade = if enabled { 1.0 } else { ui.visuals().disabled_alpha() }; + painter.rect(rect, CONTROL_RADIUS, fill.gamma_multiply(fade), Stroke::new(1.0, border.gamma_multiply(fade)), StrokeKind::Inside); + let color = if looks_disabled(ui, enabled) { + look.text_dim + } else if primary { + look.lettering_on(fill) + } else { + look.text + }; + painter.text(rect.center(), Align2::CENTER_CENTER, label, font(primary), color); + paint_focus(ui, &response); + response +} + +/// A glyph that acts as a button, centred on `centre`; `lit` frames it as switched on +pub(crate) fn icon_button(ui: &mut Ui, centre: Pos2, icon: &str, size: f32, name: &str, enabled: bool, lit: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let rect = Rect::from_center_size(centre, vec2(ICON_HIT_SIZE, ICON_HIT_SIZE)); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, ui.scope_id().with(("export_icon", name)), sense); + response.widget_info(|| WidgetInfo::selected(Role::Button, enabled, lit, name)); + if lit { + ui.painter().rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + } + let color = match (enabled, lit || response.hovered()) { + (false, _) if looks_disabled(ui, enabled) => look.control_border, + (false, _) => look.text_dim, + (true, true) => look.text, + (true, false) => look.text_dim, + }; + glyph(ui, centre, icon, size, color); + paint_focus(ui, &response); + response +} + +/// A card's quiet dropdown: its value from `value_left` and a chevron at `chevron_x`, no box +pub(crate) fn text_dropdown(ui: &mut Ui, id: Id, value_left: f32, chevron_x: f32, y: f32, value: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let enabled = ui.is_enabled(); + let rect = Rect::from_min_max( + pos2(value_left - TEXT_DROPDOWN_PADDING, y - TEXT_DROPDOWN_HALF_HEIGHT), + pos2(chevron_x + CHEVRON_SIZE / 2.0 + TEXT_DROPDOWN_PADDING, y + TEXT_DROPDOWN_HALF_HEIGHT), + ); + let response = ui.interact(rect, id, if enabled { Sense::click() } else { Sense::hover() }); + let name = format!("{value} {}", ic::CARET_DOWN); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, &name)); + if response.hovered() && enabled { + ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), look.raised); + } + let color = if looks_disabled(ui, enabled) { look.text_dim } else { look.text }; + text_at(ui, value_left, y, value, color, false); + glyph(ui, pos2(chevron_x, y), ic::CARET_DOWN, CHEVRON_SIZE, color); + paint_focus(ui, &response); + response +} diff --git a/crates/ui-egui/src/export_window/export_look.rs b/crates/ui-egui/src/export_window/export_look.rs new file mode 100644 index 00000000..0d8c862b --- /dev/null +++ b/crates/ui-egui/src/export_window/export_look.rs @@ -0,0 +1,160 @@ +use egui::{Color32, CornerRadius, Stroke, Style, TextStyle, style::StyleModifier}; + +use crate::theme::{Tokens, contrast_ratio, lerp_color}; + +/// Text size of the whole window, labels and values alike +pub(crate) const TEXT_SIZE: f32 = 12.0; + +/// Height and corner radius of the window's controls: dropdowns, fields and buttons +pub(crate) const CONTROL_HEIGHT: f32 = 25.0; +pub(crate) const CONTROL_RADIUS: u8 = 3; + +/// Height of an option in an open list +const OPTION_HEIGHT: f32 = 22.0; +/// An open list's margin round its options +const LIST_MARGIN: i8 = 3; +/// An option's text inset, lining up with the dropdown's value above it +const OPTION_INSET: f32 = 3.0; + +/// A scroll bar's strip beside its list: the bar and the air on either side of it +const SCROLL_BAR_WIDTH: f32 = 4.0; +const SCROLL_BAR_MARGIN: f32 = 4.0; + +/// How far the dividers sit below the frame colour, so they read on it +const DIVIDER_DARKENING: f32 = 0.26; + +/// Split the difference between the field outline and text so control edges read against the panel +const BORDER_TEXT_MIX: f32 = 0.5; + +/// How far the Presets list's names sit from the text colour towards the dim one +const LIST_TEXT_DIMMING: f32 = 0.37; + +/// The Export textures window's colours from the theme: controls a step darker than the window, raised faces a step lighter +#[derive(Clone, Copy)] +pub(crate) struct ExportLook { + pub(crate) window: Color32, + pub(crate) control: Color32, + pub(crate) control_border: Color32, + /// A step lighter than controls: hover, lit and unusable faces + pub(crate) raised: Color32, + pub(crate) chrome: Color32, + pub(crate) divider: Color32, + pub(crate) outline: Color32, + pub(crate) text: Color32, + pub(crate) text_dim: Color32, + pub(crate) list_text: Color32, + pub(crate) accent: Color32, +} + +impl ExportLook { + pub(crate) fn get(ctx: &egui::Context) -> Self { + let tokens = Tokens::get(ctx); + Self { + window: tokens.panel, + control: tokens.row, + control_border: lerp_color(tokens.field_border, tokens.text, BORDER_TEXT_MIX), + raised: tokens.separator, + chrome: tokens.chrome, + divider: lerp_color(tokens.chrome, Color32::BLACK, DIVIDER_DARKENING), + outline: lerp_color(tokens.button_border, tokens.text, BORDER_TEXT_MIX), + text: tokens.text, + text_dim: tokens.text_dim, + list_text: lerp_color(tokens.text, tokens.text_dim, LIST_TEXT_DIMMING), + accent: tokens.accent, + } + } + + /// Prefer the theme lettering when it meets the normal-text contrast threshold. + pub(crate) fn lettering_on(&self, fill: Color32) -> Color32 { + const MIN_TEXT_CONTRAST: f32 = 4.5; + if contrast_ratio(self.text, fill) >= MIN_TEXT_CONTRAST { + return self.text; + } + + if contrast_ratio(Color32::WHITE, fill) >= MIN_TEXT_CONTRAST { Color32::WHITE } else { Color32::BLACK } + } + + /// 12 point text, the window's control colours, scroll bars in their own strip beside the list + pub(crate) fn apply(&self, style: &mut Style) { + for text_style in [TextStyle::Body, TextStyle::Button] { + if let Some(font) = style.text_styles.get_mut(&text_style) { + font.size = TEXT_SIZE; + } + } + style.spacing.interact_size.y = CONTROL_HEIGHT; + style.spacing.button_padding.x = super::drawn::VALUE_INSET; + style.spacing.scroll = egui::style::ScrollStyle { + bar_width: SCROLL_BAR_WIDTH, + bar_inner_margin: SCROLL_BAR_MARGIN, + bar_outer_margin: SCROLL_BAR_MARGIN, + ..egui::style::ScrollStyle::solid() + }; + + // The scroll strip shows no track, only the bar + style.visuals.extreme_bg_color = Color32::TRANSPARENT; + let widgets = &mut style.visuals.widgets; + for (state, fill, border) in [ + (&mut widgets.inactive, self.control, self.control_border), + (&mut widgets.hovered, self.raised, self.outline), + (&mut widgets.active, self.raised, self.outline), + (&mut widgets.open, self.control, self.control_border), + ] { + state.weak_bg_fill = fill; + state.bg_stroke = Stroke::new(1.0, border); + state.corner_radius = CornerRadius::same(CONTROL_RADIUS); + state.expansion = 0.0; + } + + // Scroll bars and checks use the strong fill: the raised grey + widgets.inactive.bg_fill = self.raised; + widgets.hovered.bg_fill = self.outline; + widgets.active.bg_fill = self.outline; + widgets.inactive.fg_stroke.color = self.text; + widgets.open.fg_stroke.color = self.text; + style.visuals.selection.bg_fill = self.chrome; + style.visuals.selection.stroke = Stroke::new(1.0, self.text); + } + + /// An open list: flush under its button, one light edge, the chosen option in the frame colour + pub(crate) fn list_style(&self) -> StyleModifier { + let look = *self; + StyleModifier::new(move |style: &mut Style| { + look.apply(style); + style.spacing.interact_size.y = OPTION_HEIGHT; + style.spacing.menu_margin = egui::Margin::same(LIST_MARGIN); + style.spacing.button_padding.x = OPTION_INSET; + style.spacing.item_spacing.y = 0.0; + style.visuals.window_fill = look.control; + style.visuals.window_stroke = Stroke::new(1.0, look.control_border); + style.visuals.menu_corner_radius = CornerRadius::same(CONTROL_RADIUS); + style.visuals.widgets.hovered.weak_bg_fill = look.raised; + style.visuals.widgets.hovered.bg_stroke = Stroke::NONE; + style.visuals.widgets.inactive.bg_stroke = Stroke::NONE; + style.visuals.widgets.active.bg_stroke = Stroke::NONE; + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::theme::{Accent, Brightness, apply}; + + #[test] + fn export_button_and_empty_swatch_text_and_control_edges_read_in_each_theme() { + let context = egui::Context::default(); + for brightness in Brightness::ALL { + for accent in Accent::ALL { + apply(&context, brightness, accent); + let look = ExportLook::get(&context); + + for fill in [look.accent, look.raised] { + assert!(contrast_ratio(look.lettering_on(fill), fill) >= 4.5, "{brightness:?} {accent:?}"); + } + for background in [look.window, look.control] { + assert!(contrast_ratio(look.control_border, background) >= 3.0, "{brightness:?}"); + } + } + } + } +} diff --git a/crates/ui-egui/src/export_window/page_place.rs b/crates/ui-egui/src/export_window/page_place.rs new file mode 100644 index 00000000..7a8c8269 --- /dev/null +++ b/crates/ui-egui/src/export_window/page_place.rs @@ -0,0 +1,26 @@ +use egui::{Pos2, pos2}; + +/// Where a Settings page lays out from: the window's left edge, the tab row's top and the page's right edge +#[derive(Clone, Copy)] +pub(super) struct PagePlace { + pub(super) left: f32, + pub(super) top: f32, + pub(super) right: f32, +} + +impl PagePlace { + /// `x` from the window's left edge + pub(super) fn x(&self, x: f32) -> f32 { + self.left + x + } + + /// `y` from the top of the tab row + pub(super) fn y(&self, y: f32) -> f32 { + self.top + y + } + + /// A point `from_right` in from the page's right edge, at `y` from the tab row's top + pub(super) fn right_inset(&self, from_right: f32, y: f32) -> Pos2 { + pos2(self.right - from_right, self.top + y) + } +} diff --git a/crates/ui-egui/src/export_window/tree_file.rs b/crates/ui-egui/src/export_window/tree_file.rs new file mode 100644 index 00000000..8b3f64fb --- /dev/null +++ b/crates/ui-egui/src/export_window/tree_file.rs @@ -0,0 +1,8 @@ +/// A file row of LIST OF EXPORTS: the texts of its columns and its whole path +pub(super) struct TreeFile { + pub(super) name: String, + pub(super) size: String, + pub(super) format: String, + pub(super) bits: String, + pub(super) path: String, +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 8f6bc3e0..5e5ced92 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -483,7 +483,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } // The dispatcher reads clipboard events as shortcuts; a pasted image also means Ctrl+V - // Unless bound, Shift+Delete and Shift+Insert become Ctrl+X and Ctrl+V + // Unbound Shift+Delete and Shift+Insert use the standard cut and paste shortcuts ctx.input_mut(|input| { let held = input.modifiers; let aliases: Vec<_> = input @@ -537,11 +537,14 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - // The open list or the picker window closes on this Escape itself + let export = &app.ui.export; let escape_is_free = !popup_open && !picker_open; + + // Local export inputs handle Escape during drawing + let export_input_active = app.ui.windows.export && (export.field_had_keyboard || export.pending_drop.is_some() || export.renaming.is_some()); if confirming_reset { // Its keys were handled before the shortcuts ran - } else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { // The Output templates question: Escape answers it with the safe choice app.ui.export.ask = None; } else if app.ui.windows.project_config.is_some() { @@ -551,19 +554,25 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); - } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if popup_open || export_input_active { + // The open list or export input handles the key + } else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; - } else if !popup_open && point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { cancel_point_pick = true; - } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if !escape_is_free { + // The picker window handles the key + } else if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { app.ui.rail_panel = None; - } else if escape_is_free && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { crate::id_color_pick::IdColorPick::end(app); - } else if escape_is_free && app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_symmetry_plane = false; - } else if escape_is_free && app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.ui.windows.export { + crate::export_window::keys_in(app, input); + } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.cancel_path(); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c11f6dc2..1ea83ab4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -404,6 +404,9 @@ pub struct ExportUi { /// `file.exportTextures`). #[serde(default)] pub materialx: bool, + /// Also write `_shaders.json`: the shader's settings and the texture sets using it (`shaderParameters` of `file.exportTextures`) + #[serde(default)] + pub shader_parameters: bool, /// Texture sets excluded from export. pub skip: Vec, /// Per texture set (by index) overrides of the settings above. @@ -447,6 +450,9 @@ pub struct ExportUi { /// Output templates tab: F2 asked to rename the selected preset. #[serde(skip)] pub rename_key: bool, + /// A text field of the window had the keyboard when the last frame ended + #[serde(skip)] + pub field_had_keyboard: bool, /// Output templates tab: the question waiting for an answer (delete, or drop an unsaved edit). #[serde(skip)] pub ask: Option, @@ -478,6 +484,7 @@ impl Default for ExportUi { color_space: String::new(), usd_asset: false, materialx: false, + shader_parameters: false, skip: Vec::new(), sets: Default::default(), owner: Vec::new(), @@ -492,6 +499,7 @@ impl Default for ExportUi { pending_drop: None, renaming: None, rename_key: false, + field_had_keyboard: false, ask: None, opened_with: None, job: None, @@ -503,7 +511,7 @@ impl Default for ExportUi { /// The LIST OF EXPORTS console's width when the window opens, as in the reference fn default_console_width() -> f32 { - 300.0 + crate::export_window::CONSOLE_WIDTH } fn default_export_dir() -> String { diff --git a/crates/ui-egui/src/state/export_job.rs b/crates/ui-egui/src/state/export_job.rs index cf4a87de..853ca813 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -20,6 +20,8 @@ pub struct ExportJob { /// 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, + /// Also write the shader parameters with the last texture set, listing every texture set of the export, as ticked when Export was clicked + pub shader_parameters: bool, /// The params of the texture sets written so far, for the USD asset. pub sent: Vec, /// Warning messages already shown in this export. diff --git a/crates/ui-egui/src/state/map_export.rs b/crates/ui-egui/src/state/map_export.rs index 339ee1bb..2b8a3e37 100644 --- a/crates/ui-egui/src/state/map_export.rs +++ b/crates/ui-egui/src/state/map_export.rs @@ -10,6 +10,9 @@ pub struct MapExport { pub enabled: bool, #[serde(default)] pub file_type: Option, + /// The map's own size in texels per side, which wins over the export size + #[serde(default)] + pub size: Option, } fn enabled_by_default() -> bool { @@ -18,6 +21,6 @@ fn enabled_by_default() -> bool { impl Default for MapExport { fn default() -> Self { - MapExport { enabled: true, file_type: None } + MapExport { enabled: true, file_type: None, size: None } } } diff --git a/crates/ui-egui/src/state/set_export.rs b/crates/ui-egui/src/state/set_export.rs index 0fb05522..7bb10770 100644 --- a/crates/ui-egui/src/state/set_export.rs +++ b/crates/ui-egui/src/state/set_export.rs @@ -26,7 +26,11 @@ pub struct SetExport { impl SetExport { /// Whether anything is overridden (the set is marked "*"). pub fn any(&self) -> bool { - self.preset.is_some() || self.file_type.is_some() || self.size.is_some() || self.padding.is_some() || self.maps.values().any(|m| m.file_type.is_some()) + self.preset.is_some() + || self.file_type.is_some() + || self.size.is_some() + || self.padding.is_some() + || self.maps.values().any(|m| m.file_type.is_some() || m.size.is_some()) } /// Whether the set exports as the global settings say (no override, every map ticked). diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 942f9450..30af4f1e 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -449,7 +449,7 @@ pub fn legible_tint(tint: Color32, background: Color32, text: Color32) -> Color3 const WCAG_FLARE: f32 = 0.05; /// The WCAG contrast ratio of two opaque colors (1..21) -fn contrast_ratio(a: Color32, b: Color32) -> f32 { +pub(crate) fn contrast_ratio(a: Color32, b: Color32) -> f32 { let luminance = |color: Color32| { let linear = egui::Rgba::from(color); diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index fd256356..19c3bd3a 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -234,12 +234,15 @@ pub fn project_file_name(app: &TextureCraftApp) -> String { fn zip_files(files: Vec) -> Result, String> { let mut zip = craft_zip::Writer::new(); for f in files { - // add_with reserves ZIP64 headers up front, even for small entries. + // Reserve ZIP64 headers up front, even for small entries zip.add_with(&f.name, craft_zip::Compression::Deflated, |out| out.write_all(&f.bytes)).map_err(|e| e.to_string())?; } zip.finish().map_err(|e| e.to_string()) } +#[cfg(any(target_arch = "wasm32", test))] +use texturecraft_engine::shader_parameters::shader_parameters_sidecar; + #[cfg(target_arch = "wasm32")] pub use web::{ download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, open_sample_project, @@ -357,14 +360,24 @@ mod web { } fn export(app: &mut TextureCraftApp, jobs: &[(usize, Value)]) -> Result { - let mut files = Vec::new(); - for (set_index, params) in jobs { - let options = texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures").map_err(|e| e.to_string())?; - files.extend(app.session.export_files(&[*set_index], &options).map_err(|e| e.to_string())?); - } + let options = jobs + .iter() + .map(|(_, params)| texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures")) + .collect::, _>>() + .map_err(|error| error.to_string())?; + let jobs_with_options = jobs.iter().zip(&options).map(|((set_index, _), options)| (*set_index, options)); + let mut files = app.session.export_file_jobs(jobs_with_options).map_err(|error| error.to_string())?; - // Keep one file for each case-insensitive name in the download - texturecraft_engine::formats::skip_repeated_names(&mut files); + if app.ui.export.shader_parameters { + let sets: Vec = jobs.iter().map(|(set_index, _)| *set_index).collect(); + match shader_parameters_sidecar(&app.session.doc.project, &sets, &files) { + Ok(sidecar) => files.push(sidecar), + Err(error) => { + app.session.log.warnings("MapExporter", [format!("The shader settings file was not written: {error}")]); + app.toast(trf("The shader settings file was not written: {error}", &[("error", &error)]), true); + } + } + } app.session.log.warnings("MapExporter", files.iter().flat_map(|file| file.warnings.iter().cloned())); let file_count = files.len(); @@ -530,6 +543,28 @@ mod tests { assert!(harness.state().session.doc.bake_meshes.cage.is_some()); } + #[test] + fn shader_sidecar_does_not_take_a_texture_folder_name() { + let project = texturecraft_engine::core::Project::new("Chair", "builtin:sphere"); + let name = "chair_SHADERS.json/Color.png"; + let mut files = vec![ExportedFile { name: name.into(), bytes: vec![1, 2, 3], width: 1, height: 1, warnings: Vec::new() }]; + + let error = shader_parameters_sidecar(&project, &[], &files).unwrap_err(); + + assert!(error.contains("Chair_shaders.json")); + assert_eq!(files.len(), 1); + assert_eq!(files[0].name, name); + + files[0].name = "Chair_shaders.json_backup/Color.png".into(); + files.push(shader_parameters_sidecar(&project, &[], &files).unwrap()); + let bytes = zip_files(files).unwrap(); + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + + assert_eq!(archive.len(), 2); + assert!(archive.by_name("Chair_shaders.json_backup/Color.png").is_ok()); + assert!(archive.by_name("Chair_shaders.json").is_ok()); + } + #[test] fn zip_round_trips_every_export_file() { let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() }; diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index d7be9973..d2edee62 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -2,15 +2,21 @@ //! name pattern, and its own file type and bit depth. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable as _; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{FileType, MapExport, SetExport}; +use super::temp_dir::TempDir; + /// The Export textures window open on the first texture set's page fn harness() -> Harness<'static, TextureCraftApp> { + harness_at(egui::vec2(1600.0, 960.0)) +} + +fn harness_at(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder() - .with_size(egui::vec2(1600.0, 960.0)) + .with_size(size) .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); @@ -48,25 +54,57 @@ fn plan(h: &mut Harness<'_, TextureCraftApp>) -> Vec { fn the_rows_show_each_map_with_its_pattern_and_file_type() { let mut h = harness(); let rows = plan(&mut h).len(); + assert!(h.query_by_label("Output maps").is_some()); // Four rows of General Export Parameters, then one per map - assert_eq!(h.get_all_by_label("Enable override").count(), 4 + rows); + assert_eq!(h.get_all_by_label_contains("Enable override for ").count(), 4 + rows); assert!(h.query_all_by_label("png 8 bits").next().is_some()); assert!(h.query_all_by_label("png 16 bits").next().is_some(), "height is 16-bit in the default template"); - // A pattern longer than the column is cut at the front, the whole one is its tooltip + // A pattern longer than the column (the packed template's) is cut at the front, the whole one is its tooltip + h.state_mut().ui.export.preset = "Unreal Engine (Packed)".into(); + h.run_steps(4); let preset = texturecraft_engine::formats::builtin_preset(&h.state().ui.export.preset).unwrap(); - let long = - plan(&mut h).iter().map(|f| preset.maps[f["map"].as_u64().unwrap() as usize].file.clone()).find(|p| p.chars().count() > 26).expect("a long pattern"); - let cut: String = format!("…{}", long.chars().skip(long.chars().count() - 25).collect::()); + let long = preset.maps.iter().map(|map| map.file.clone()).max_by_key(|file| file.chars().count()).unwrap(); + let cut = h + .query_all_by_label_contains("…") + .find_map(|node| node.accesskit_node().value().filter(|text| long.ends_with(text.trim_start_matches('…')))) + .expect("the pattern's end, cut at the front"); assert!(h.query_by_label(&long).is_none(), "{long} is cut"); - let at = h.get_all_by_label(&cut).next().unwrap().rect().center(); + let at = h.get_all_by_role_and_label(egui::Role::Label, &cut).next().unwrap().rect().center(); h.hover_at(at); h.run_steps(30); + assert!(h.query_by_label(&long).is_some(), "the tooltip has the whole {long}"); } +#[test] +fn feedback_psd_preflight_keeps_map_controls_available() { + let mut h = harness(); + let available = plan(&mut h).len(); + assert!(available >= 3); + let preset = h.state().ui.export.preset.clone(); + let settings = &mut h.state_mut().ui.export; + settings.format = "psd".into(); + settings.bit_depth = 16; + settings.size = 8192; + let params = serde_json::json!({"ts": 0, "preset": preset, "format": "psd", "bitDepth": 16, "size": 8192}); + + let error = texturecraft_engine::execute(&mut h.state_mut().session, "export.plan", ¶ms).unwrap_err(); + assert!(error.to_string().contains("2 GiB"), "{error}"); + h.run_steps(4); + + assert_eq!(h.get_all_by_label_contains("Enable override for map ").count(), available); + let size = h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map's size list"); + size.click(); + h.run_steps(4); + click(&mut h, "128x128"); + + assert!(maps(&h).values().any(|map| map.size == Some(128))); + assert_eq!(h.state().ui.export.size, 8192); +} + #[test] fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() { let mut h = harness(); @@ -77,21 +115,25 @@ fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() { let boxes = h.get_all_by_role(egui::Role::CheckBox).count(); h.get_all_by_role(egui::Role::CheckBox).nth(boxes - rows).unwrap().click(); h.run_steps(4); + assert_eq!(selected(&h), before - 1); assert_eq!(maps(&h).values().filter(|m| !m.enabled).count(), 1); assert!(h.query_by_label("*").is_none(), "a left-out map is not an override"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Uncheck all"); + assert_eq!(selected(&h), before - rows); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Invert all"); + assert_eq!(selected(&h), before); assert!(!h.state().ui.export.sets.contains_key(&0), "nothing left to remember"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Uncheck all"); click(&mut h, "Include all"); + assert_eq!(selected(&h), before, "Include all ticks the output maps too"); } @@ -99,18 +141,21 @@ fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() { fn a_map_override_sets_its_own_file_type_and_marks_the_set() { let mut h = harness(); let rows = plan(&mut h).len(); - h.get_all_by_label("Enable override").nth(4).unwrap().click(); + h.get_all_by_label_contains("Enable override for ").nth(4).unwrap().click(); h.run_steps(4); let m = maps(&h); let (_, first) = m.iter().next().unwrap(); + assert!(first.file_type.is_some(), "{m:?}"); assert!(h.query_by_label("*").is_some(), "the set is marked"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Override every item"); + assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Clear all overrides"); + assert!(maps(&h).is_empty()); } @@ -118,11 +163,10 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { fn export_writes_a_map_with_its_own_file_type() { let mut h = harness(); let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize; - let dir = std::env::temp_dir().join(format!("tc-export-map-overrides-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = TempDir::new("export-map-overrides"); let template = h.state().ui.export.preset.clone(); let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }) }); + o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }), size: None }); let e = &mut h.state_mut().ui.export; e.dir = dir.display().to_string(); e.sets.insert(0, o); @@ -139,9 +183,9 @@ fn export_writes_a_map_with_its_own_file_type() { h.run_steps(1); } h.run_steps(2); - let names: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + let names: Vec = std::fs::read_dir(&*dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names.iter().filter(|n| n.ends_with(".tga")).count(), 1, "{names:?}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -150,9 +194,10 @@ fn a_map_the_template_no_longer_has_is_ignored() { let before = selected(&h); let template = h.state().ui.export.preset.clone(); let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(999, MapExport { enabled: false, file_type: None }); + o.maps.insert(999, MapExport { enabled: false, file_type: None, size: None }); h.state_mut().ui.export.sets.insert(0, o); h.run_steps(3); + assert_eq!(selected(&h), before, "the export still plans every file"); } @@ -166,3 +211,91 @@ fn each_row_names_its_own_map() { assert!(h.query_all_by_label_contains(&format!("_{id}")).next().is_some(), "a row for {id}"); } } + +#[test] +fn texture_set_map_sizes_are_reachable_on_a_narrow_screen() { + let mut h = harness_at(egui::vec2(800.0, 480.0)); + let header = h.get_by_label("General Export Parameters").rect().center(); + let size_rect = |h: &Harness<'_, TextureCraftApp>| { + h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map size list").rect() + }; + let before = size_rect(&h); + + h.hover_at(header); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(-500.0, -200.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(12); + + let after = size_rect(&h); + + assert!(after.left() < before.left(), "{before:?} → {after:?}"); + assert!(h.ctx.content_rect().contains_rect(after), "{after:?}"); + h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).unwrap().click(); + h.run_steps(4); + click(&mut h, "128x128"); + + assert!(maps(&h).values().any(|map| map.size == Some(128))); +} + +#[test] +fn a_map_picks_its_own_size_and_the_export_writes_it_at_that_size() { + let mut h = harness(); + let expected = plan(&mut h); + let first = expected[0]["map"].as_u64().unwrap() as usize; + let combo = h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map's size list"); + combo.click(); + h.run_steps(4); + click(&mut h, "128x128"); + + assert_eq!(maps(&h).get(&first).and_then(|map| map.size), Some(128), "{:?}", maps(&h)); + assert!(h.query_by_label("*").is_some(), "the set is marked"); + + let dir = TempDir::new("export-map-sizes"); + let set_count = h.state().session.set_count(); + let export = &mut h.state_mut().ui.export; + export.dir = dir.display().to_string(); + export.skip = (1..set_count).collect(); + h.run_steps(3); + click(&mut h, "Export"); + for _ in 0..64 { + if h.state().ui.export.job.is_none() { + break; + } + + h.run_steps(1); + } + h.run_steps(2); + + assert_eq!(std::fs::read_dir(&*dir).unwrap().count(), expected.len()); + for file in expected { + let path = dir.join(file["file"].as_str().unwrap()); + let side = if file["map"].as_u64().unwrap() as usize == first { 128 } else { 256 }; + + assert_eq!(image::image_dimensions(&path).unwrap(), (side, side), "{}", path.display()); + } +} + +#[test] +fn rows_with_a_one_depth_file_type_each_have_their_own_bit_depth_list() { + let mut h = harness(); + let rows: Vec = plan(&mut h).iter().take(2).map(|file| file["map"].as_u64().unwrap() as usize).collect(); + let template = h.state().ui.export.preset.clone(); + let mut o = SetExport { maps_template: template, ..SetExport::default() }; + for map in &rows { + o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "hdr".into(), bit_depth: 32, dithering: false }), size: None }); + } + h.state_mut().ui.export.sets.insert(0, o); + h.run_steps(4); + + let greyed: Vec<_> = + h.get_all_by_role(egui::Role::ComboBox).filter(|node| node.value().as_deref() == Some("32f bits")).map(|node| node.accesskit_node().id()).collect(); + + assert_eq!(rows.len(), 2); + assert_eq!(greyed.len(), 2, "each row's greyed bit depth list is its own node"); + assert_ne!(greyed[0], greyed[1]); +} diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index c2eee653..3579ece6 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -33,13 +33,13 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { /// Open the General Export Parameters menu fn page_menu(h: &mut Harness<'_, TextureCraftApp>) { - h.get_all_by_label(egui_phosphor::regular::LIST_CHECKS).nth(1).unwrap().click(); + h.get_by_label("General Export Parameters menu").click(); h.run_steps(4); } /// The `row`th "Enable override" button (Output template, File type, Size, Padding) fn toggle(h: &mut Harness<'_, TextureCraftApp>, row: usize) { - h.get_all_by_label("Enable override").nth(row).unwrap().click(); + h.get_all_by_label_contains("Enable override for ").nth(row).unwrap().click(); h.run_steps(4); } @@ -63,8 +63,9 @@ fn png_width(path: &std::path::Path) -> u32 { #[test] fn a_texture_set_page_shows_what_it_inherits() { let h = harness(); + assert_eq!(h.state().ui.export.page, Some(0)); - assert!(h.get_all_by_label("Enable override").count() >= 4, "four rows, then the output maps"); + assert!(h.get_all_by_label_contains("Enable override for ").count() >= 4, "four rows, then the output maps"); let own = h.state().session.doc.project.texture_sets[0].resolution; for text in ["Document channels + Normal + AO (No Alpha)", "Based on output template", &format!("{own}x{own} (Texture Set size)"), "Dilation infinite"] { assert!(h.query_by_label(text).is_some(), "{text}"); @@ -302,3 +303,19 @@ fn an_empty_file_type_override_keeps_the_template_types_under_a_global_one() { h.run_steps(4); assert!(h.query_all_by_label("png 16 bits").next().is_some(), "the set still writes the template's types"); } + +#[test] +fn keyboard_size_override_changes_only_the_size_row() { + let mut harness = harness(); + let size = harness.state().session.doc.project.texture_sets[0].block_resolution(); + + harness.get_by_role_and_label(egui::Role::Button, "Enable override for Size").focus(); + harness.run_steps(2); + harness.key_press(egui::Key::Space); + harness.run_steps(4); + + let settings = overrides(&harness); + + assert_eq!(settings.size, Some(size)); + assert!(settings.preset.is_none() && settings.file_type.is_none() && settings.padding.is_none() && settings.maps.is_empty()); +} diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index ddcb5bca..ec4bf518 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -2,6 +2,7 @@ //! progress bar with Cancel Export, and the window staying open. use egui_kittest::Harness; +use egui_kittest::kittest::NodeT; use egui_kittest::kittest::Queryable as _; use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; @@ -50,6 +51,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { assert_eq!(h.state().ui.export.tab, 2, "Export switches to LIST OF EXPORTS"); h.run_steps(1); assert!(h.query_by_label("Cancel Export").is_some()); + assert_eq!(h.get_by_role(egui::Role::ProgressIndicator).accesskit_node().live(), egui::accesskit::Live::Polite); assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons"); assert_eq!(console(&h).first().map(String::as_str), Some("Preparing texture export")); @@ -134,7 +136,7 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { assert!(h.query_all_by_label("256x256 (Texture Set size)").next().is_some()); assert!(h.query_all_by_label("png").next().is_some() && h.query_all_by_label("16 bits").next().is_some()); assert!(h.query_by_label("Include all").is_none() && h.query_by_label("Reset all").is_none()); - assert!(h.query_by_label("CONSOLE").is_some()); + assert!(h.query_by_label("Console").is_some()); // A row's tooltip is the full path let preset = h.state().ui.export.preset.clone(); @@ -143,17 +145,50 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { let at = h.get_by_label(&file).rect().center(); h.hover_at(at); h.run_steps(30); + assert!(h.query_by_label(&dir.join(&file).display().to_string()).is_some()); // The strip at the console's edge hides it, then shows it again h.get_by_role_and_label(egui::Role::Button, "Hide Console").click(); h.run_steps(4); - assert!(h.state().ui.export.console_hidden && h.query_by_label("CONSOLE").is_none()); + + assert!(h.state().ui.export.console_hidden && h.query_by_label("Console").is_none()); h.get_by_role_and_label(egui::Role::Button, "Show Console").click(); h.run_steps(4); + assert!(!h.state().ui.export.console_hidden); } +#[test] +fn long_filenames_leave_the_export_details_reachable_by_scrolling() { + let (mut h, _) = harness("wide-tree"); + let name = "Wide".repeat(44); + h.state_mut().session.doc.project.texture_sets[0].name.clone_from(&name); + h.state_mut().ui.export.tab = 2; + h.run_steps(4); + let bits_label = "16 bits"; + let bits_fit = |h: &Harness<'_, TextureCraftApp>| { + h.output().shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == bits_label => clipped.clip_rect.contains_rect(text.visual_bounding_rect()), + _ => false, + }) + }; + assert!(!bits_fit(&h), "the bit-depth column starts beyond the viewport"); + h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).focus(); + h.run_steps(3); + assert!(h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).is_focused()); + + for _ in 0..12 { + h.key_press(egui::Key::ArrowRight); + h.run_steps(2); + } + h.run_steps(10); + + assert!(bits_fit(&h), "horizontal keyboard scrolling brings bit depth into the viewport"); + assert!(h.query_all_by_label(bits_label).next().is_some(), "bit depth has an accessibility label"); + assert!(h.query_by_label("Console").is_some()); +} + #[test] fn open_output_directory_asks_the_system_to_show_the_folder() { let (mut h, dir) = harness("open"); @@ -220,6 +255,40 @@ fn texture_sets_writing_the_same_file_name_do_not_start_an_export() { let _ = std::fs::remove_dir_all(&library); } +#[test] +fn a_texture_set_cannot_export_into_another_sets_psd_file() { + use texturecraft_ui_egui::state::SetExport; + + let (mut h, _) = harness("psd-folder-clash"); + let scratch = tempfile::tempdir().unwrap(); + let dir = scratch.path().join("textures"); + let library = tempfile::tempdir().unwrap(); + let app = h.state_mut(); + app.ui.export.dir = dir.display().to_string(); + app.session.load_export_presets(library.path().to_path_buf()); + let psd = json!({"name": "Layered", "maps": [ + {"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]} + ]}); + app.run("export.preset.save", json!({"preset": psd})).unwrap(); + let plan = app.run("export.plan", json!({"preset": "Layered", "ts": 0})).unwrap(); + let file_name = plan[0]["file"].as_str().unwrap(); + let nested = json!({"name": "Nested", "maps": [ + {"file": format!("{file_name}/detail"), "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]} + ]}); + app.run("export.preset.save", json!({"preset": nested})).unwrap(); + app.ui.export.preset = "Layered".into(); + app.ui.export.sets.insert(1, SetExport { preset: Some("Nested".into()), ..Default::default() }); + h.run_steps(4); + + click(&mut h, "Export"); + finish(&mut h); + + assert!(h.state().ui.export.job.is_none()); + assert_eq!(exports(&h), 0, "the full selection must be checked before starting"); + assert!(!dir.exists()); + assert!(console(&h).iter().any(|line| line.contains("folder")), "{:?}", console(&h)); +} + #[test] fn opening_another_project_stops_the_export() { let (mut h, dir) = harness("project"); diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index c33be805..041174fb 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -52,7 +52,7 @@ fn the_window_has_the_reference_size() { let h = harness(egui::vec2(1600.0, 960.0)); let reset = window_button_rect(&h, "Reset all", 1600.0); let export = window_button_rect(&h, "Export", 1600.0); - let tabs = h.get_by_label("SETTINGS").rect(); + let tabs = h.get_by_role_and_label(egui::Role::Tab, "Settings").rect(); let width = export.max.x - reset.min.x; let height = export.max.y - tabs.min.y; diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 749bab18..d3309e43 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -75,6 +75,47 @@ fn closing_the_window_is_cancel() { assert_eq!(h.state().ui.export.size, 0); } +#[test] +fn escape_is_cancel() { + let mut h = harness(); + h.state_mut().ui.export.size = 2048; + h.run_steps(3); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(h.state().ui.export.size, 0, "the opening settings are back"); +} + +#[test] +fn escape_cancels_when_a_button_has_keyboard_focus() { + let mut h = harness(); + h.get_by_role_and_label(egui::Role::Button, "Save settings").focus(); + h.run_steps(4); + + assert!(h.get_by_role_and_label(egui::Role::Button, "Save settings").is_focused()); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); +} + +#[test] +fn escape_in_an_open_dropdown_closes_only_the_dropdown() { + let mut h = harness(); + open_combo(&mut h, "Based on output template"); + + assert!(h.query_by_label("png").is_some()); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.query_by_label("png").is_none(), "the dropdown closed"); + assert!(h.state().ui.windows.export, "the window stays open"); +} + #[test] fn the_lists_hold_the_reference_entries() { let mut h = harness(); @@ -122,15 +163,18 @@ fn a_saved_legacy_preset_name_resolves_to_its_current_name() { fn the_set_list_menu_checks_unchecks_and_inverts() { let mut h = harness(); let sets = h.state().session.set_count(); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Uncheck all"); + assert_eq!(h.state().ui.export.skip.len(), sets); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Invert all"); + assert!(h.state().ui.export.skip.is_empty()); h.state_mut().ui.export.skip = vec![0]; - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Check all"); + assert!(h.state().ui.export.skip.is_empty()); } @@ -140,9 +184,8 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { let default = h.state().ui.export.dir.clone(); h.state_mut().ui.export.dir = "/somewhere/else".into(); h.run_steps(3); - hover(&mut h, "R"); - assert!(h.query_by_label("Reset to default").is_some()); - click(&mut h, "R"); + click(&mut h, "Reset to default"); + assert_eq!(h.state().ui.export.dir, default); hover(&mut h, "16"); @@ -152,11 +195,13 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { hover(&mut h, "16"); assert!(h.query_all_by_label("Dilation in pixels").next().is_some()); click(&mut h, "16"); + assert!(h.query_by_label("Dilation (pixels)").is_some()); // A click on the slider sets the width and leaves the menu open h.get_by_role(egui::Role::Slider).click(); h.run_steps(4); + assert_ne!(h.state().ui.export.dilation, 16); assert!(h.query_by_label("Dilation (pixels)").is_some(), "the menu stays open"); } @@ -174,3 +219,24 @@ fn the_page_reset_puts_the_parameters_back() { assert_eq!((e.size, e.padding.as_str()), (0, "infinite")); assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page"); } + +#[test] +fn feedback_escape_clears_a_pick_before_cancelling_export() { + let mut h = harness(); + let pick = egui::Id::unique("export_escape_screen_color_pick"); + h.state_mut().picking_color = Some(pick); + h.state_mut().ui.export.size = 512; + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.state().picking_color.is_none(), "the armed pick receives Escape first"); + assert!(h.query_by_role_and_label(egui::Role::Button, "Save settings").is_some()); + assert_eq!(h.state().ui.export.size, 512); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(h.state().ui.export.size, 0); +} diff --git a/crates/ui-egui/tests/it/export_shader_parameters.rs b/crates/ui-egui/tests/it/export_shader_parameters.rs new file mode 100644 index 00000000..7480cd63 --- /dev/null +++ b/crates/ui-egui/tests/it/export_shader_parameters.rs @@ -0,0 +1,44 @@ +//! Export textures › SETTINGS: Export shader settings writes `_shaders.json`, the +//! shader's settings and every texture set of the export, with the export's last texture set + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use texturecraft_ui_egui::TextureCraftApp; + +use super::temp_dir::TempDir; + +#[test] +fn ticking_export_shader_settings_writes_the_json_listing_every_exported_set() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + let dir = TempDir::new("export-shader-parameters"); + h.state_mut().ui.export.dir = dir.display().to_string(); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + + h.get_by_role_and_label(egui::Role::CheckBox, "Export shader settings").click(); + h.run_steps(4); + + assert!(h.state().ui.export.shader_parameters); + 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); + + let project = &h.state().session.doc.project; + let file = dir.join(texturecraft_engine::shader_parameters::shader_parameters_file(&project.name)); + let json: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap_or_else(|_| panic!("{} was written", file.display()))).unwrap(); + let names: Vec<&str> = project.texture_sets.iter().map(|set| set.name.as_str()).collect(); + + assert_eq!(json["shaders"][0]["textureSets"], serde_json::json!(names), "every texture set of the export, written once: {json}"); + assert!(json["shaders"][0]["parameters"]["ior"].is_number()); +} diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs index 76aa9e39..f9a72c03 100644 --- a/crates/ui-egui/tests/it/export_template_guards.rs +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -3,7 +3,7 @@ use egui::Key; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; @@ -169,3 +169,20 @@ fn the_settings_dropdown_asks_about_an_unfinished_edit_too() { texturecraft_ui_egui::export_templates::select(h.state_mut(), "Beta tpl".into()); assert_eq!(selected(&h), "Beta tpl", "a valid edit switches at once"); } + +#[test] +fn output_templates_keeps_export_and_save_until_an_edit_does_not_validate() { + let library = Library::new("footer-on-templates"); + let mut h = harness(&library); + + // The window's footer is drawn after the app's own menus, which have an Export too + let disabled = |h: &Harness<'_, TextureCraftApp>, label: &str| h.get_all_by_label(label).last().unwrap().accesskit_node().is_disabled(); + + assert!(!disabled(&h, "Export"), "Export works from the templates tab"); + assert!(!disabled(&h, "Save settings"), "Save settings works from the templates tab"); + + break_draft(&mut h); + + assert!(disabled(&h, "Export"), "an invalid edit holds Export"); + assert!(disabled(&h, "Save settings"), "an invalid edit holds Save settings"); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index d59d79a0..a2032fd2 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -447,6 +447,7 @@ fn thumbnail_menus_apply_actions_to_the_clicked_layer_and_stack() { layer }; h.run_steps(3); + assert_eq!(h.state().session.selected_layer(), Some(selected)); let at = thumb(&h, "Masked fill", true); @@ -455,19 +456,22 @@ fn thumbnail_menus_apply_actions_to_the_clicked_layer_and_stack() { h.get_by_label("Toggle mask").click(); h.run_steps(3); let project = &h.state().session.doc.project; + assert!(!project.layers[&clicked].mask.as_ref().unwrap().enabled); assert!(project.layers[&selected].mask.as_ref().unwrap().enabled); assert_eq!(h.state().session.target, StackTarget::Mask); - // The same layer's mask is still selected when its material menu opens. + // Opening the material menu must preserve the selected mask let at = thumb(&h, "Masked fill", false); right_click(&mut h, at); assert!(h.query_by_label("Toggle mask").is_none()); + // The same items as the toolbar's Add effect on the content: a generator can't go there, so it is greyed assert!(h.get_by_label_contains("Add generator").accesskit_node().is_disabled()); h.get_by_label_contains("Add levels").click(); h.run_steps(3); let layer = &h.state().session.doc.project.layers[&clicked]; + assert_eq!(layer.content_effects.len(), 2); assert_eq!(layer.mask.as_ref().unwrap().effects.len(), 1); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 5790c6ca..1c805d02 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -34,6 +34,7 @@ mod export_overrides; mod export_progress; mod export_reference_texts; mod export_settings; +mod export_shader_parameters; mod export_template_guards; mod export_usd_asset; mod file_dialogs; diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index d8033152..edb10bfe 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -18,9 +18,13 @@ use template_library::TemplateLibrary; /// OUTPUT TEMPLATES with the user template "Mine" selected fn harness(library: &TemplateLibrary) -> Harness<'static, TextureCraftApp> { + harness_at(library, egui::vec2(1600.0, 960.0)) +} + +fn harness_at(library: &TemplateLibrary, size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder() - .with_size(egui::vec2(1600.0, 960.0)) + .with_size(size) .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); @@ -98,24 +102,38 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { fn the_tab_shows_the_preset_tools_and_map_editor() { let library = TemplateLibrary::new("layout"); let mut h = harness(&library); - for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] { + for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:"] { assert!(h.query_by_label(text).is_some(), "{text}"); } + let hint = "Drop an input map onto a channel to assign it to that output."; + + assert!(h.query_by_label(hint).is_none(), "the drag hint is no line under the cards"); + let metallic = h.get_by_role_and_label(egui::Role::ListItem, "Metallic").rect().center(); + h.hover_at(metallic); + h.run_steps(30); + + assert!(h.query_by_label(hint).is_some(), "a map entry's tooltip says how to use it"); + h.hover_at(egui::pos2(1.0, 1.0)); + h.run_steps(4); + assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR"))); let maps = h.state().session.export_preset("Mine").unwrap().maps.len(); let ts = h.state().session.ts(); let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap(); let exported = plan.as_array().unwrap().len(); - assert!(h.query_by_label(&format!("{exported} output maps will be exported.")).is_some()); + + assert!(h.query_by_label(&format!("{exported} output maps will be exported")).is_some()); for create in ["Gray", "RGB", "R+G+B", "RGB+A", "R+G+B+A"] { assert!(h.query_by_label(create).is_some(), "{create}"); } click(&mut h, "R+G+B+A"); + assert_eq!(h.state().session.export_preset("Mine").unwrap().maps.len(), maps + 1, "Create adds an output map"); let info = h.get_by_label(egui_phosphor::regular::INFO).rect().center(); h.hover_at(info); h.run_steps(30); + assert!(h.query_by_label("Choose how the input maps are named in this editor.").is_some()); assert!(h.query_by_label("The active texture set’s shader can affect the available map names.").is_some()); } @@ -152,12 +170,17 @@ fn the_right_click_menu_renames_and_removes_user_templates_only() { assert!(!h.get_by_label(item).accesskit_node().is_disabled(), "{item}"); } click(&mut h, "Rename"); + assert_eq!(h.state().ui.export.renaming.as_deref(), Some("Mine")); h.key_press(egui::Key::Escape); h.run_steps(4); + assert!(h.state().ui.export.renaming.is_none(), "Escape ends the rename"); + assert!(h.state().ui.windows.export, "and leaves the window open"); + right_click(&mut h, "Mine"); click(&mut h, "Remove"); + assert!(matches!(&h.state().ui.export.ask, Some(texturecraft_ui_egui::export_templates::Ask::Delete(n)) if n == "Mine")); h.state_mut().ui.export.ask = None; h.run_steps(2); @@ -191,17 +214,19 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { h.state_mut().run("export.preset.save", json!({ "preset": two })).unwrap(); let own = "Unreal Engine (Packed)".to_string(); let mut o = texturecraft_ui_egui::state::SetExport { preset: Some(own.clone()), maps_template: own, ..Default::default() }; - o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None }); + o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); let ts = h.state().session.ts(); h.state_mut().ui.export.sets.insert(ts, o); h.state_mut().ui.export.preset = "Two".into(); h.run_steps(4); + assert!(h.query_by_label_contains("Not saved").is_none(), "the preview plans the template on show"); let plan = h.state_mut().run("export.plan", json!({"preset": "Two", "ts": ts})).unwrap(); for index in 0..2 { let file = plan.as_array().unwrap().iter().find(|f| f["map"] == index).unwrap()["file"].as_str().unwrap().to_string(); hover_name_field(&mut h, index); let planned = format!("{} {file}", egui_phosphor::regular::ARROW_RIGHT); + assert!(h.query_all_by_label(&planned).next().is_some(), "map {index} shows its own file {file}"); } } @@ -211,7 +236,7 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { let library = TemplateLibrary::new("follow"); let mut h = harness(&library); let mut o = texturecraft_ui_egui::state::SetExport { preset: Some("Mine".into()), maps_template: "Mine".into(), ..Default::default() }; - o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None }); + o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); // The override is there when the window opens h.state_mut().ui.windows.export = false; @@ -229,19 +254,23 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { h.state_mut().ui.export.renaming = Some("Yours".into()); h.key_press(egui::Key::Enter); h.run_steps(4); + assert_eq!(h.state().ui.export.preset, "Yours"); let o = h.state().ui.export.sets[&0].clone(); + assert_eq!((o.preset.as_deref(), o.maps_template.as_str()), (Some("Yours"), "Yours"), "the set keeps its template and map ticks"); assert_eq!(o.maps.len(), 1); right_click(&mut h, "Yours"); click(&mut h, "Remove"); click(&mut h, "Delete"); + assert!(h.state().session.export_preset("Yours").is_none()); assert!(!h.state().ui.export.sets.contains_key(&0), "the set exports with the global settings again"); // Cancel goes back to the settings the window opened with, minus the removed template click(&mut h, "Cancel"); + assert!(h.state().ui.export.sets.values().all(|o| o.preset.as_deref() != Some("Yours") && o.preset.as_deref() != Some("Mine"))); } @@ -260,11 +289,12 @@ fn the_footer_counts_only_the_maps_the_texture_set_exports() { h.run_steps(4); let ts = h.state().session.ts(); let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap(); + assert_eq!(plan.as_array().unwrap().len(), 1, "the sample set has no sheen: {plan}"); hover_name_field(&mut h, 1); assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen row says so"); - assert!(h.query_by_label("1 output maps will be exported.").is_some()); - assert!(h.query_by_label("2 output maps will be exported.").is_none()); + assert!(h.query_by_label("1 output maps will be exported").is_some()); + assert!(h.query_by_label("2 output maps will be exported").is_none()); } #[test] @@ -273,13 +303,14 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { let mut h = harness(&library); // The first texture set leaves out the template's first map - let off = MapExport { enabled: false, file_type: None }; + let off = MapExport { enabled: false, file_type: None, size: None }; h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); h.run_steps(2); let first = h.state().session.export_preset("Mine").unwrap().maps[0].file.clone(); move_map(&mut h, 0, "Move down"); assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[1].file, first, "the map moved down"); let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default(); + assert_eq!(maps, [(1, off)].into(), "the setting moved with its map"); } @@ -287,7 +318,7 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { let library = TemplateLibrary::new("stale"); let mut h = harness(&library); - let off = MapExport { enabled: false, file_type: None }; + let off = MapExport { enabled: false, file_type: None, size: None }; h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); h.run_steps(2); let saved = h.state().session.export_preset("Mine").unwrap(); @@ -309,8 +340,10 @@ fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { h.run_steps(2); move_map(&mut h, 0, "Move down"); let now = h.state().session.export_preset("Mine").unwrap(); + assert_eq!(now.maps[1].file, saved.maps[1].file, "{:?}", now.maps.iter().map(|m| &m.file).collect::>()); let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default(); + assert_eq!(maps, [(1, off)].into(), "counted from the agent's order, not the edit's old base"); } @@ -324,7 +357,7 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { let mut external = saved.clone(); external.maps.swap(0, 1); harness.state_mut().run("export.preset.save", json!({"preset": external})).unwrap(); - let disabled = MapExport { enabled: false, file_type: None }; + let disabled = MapExport { enabled: false, file_type: None, size: None }; harness.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, disabled.clone())].into(), ..SetExport::default() }); harness.run_steps(3); @@ -334,17 +367,18 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { harness.run_steps(4); let current = harness.state().session.export_preset("Mine").unwrap(); + assert_eq!(current, saved, "the corrected draft was saved in its own order"); assert_eq!(harness.state().ui.export.sets[&0].maps, [(1, disabled)].into()); } #[test] -fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { +fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_has_no_count_or_reset() { let library = TemplateLibrary::new("bottom-bar"); let h = harness(&library); let naming = h.get_by_label("Naming pattern").rect(); - let tabs = h.get_by_label("OUTPUT TEMPLATES").rect(); + let tabs = h.get_by_role_and_label(egui::Role::Tab, "Output templates").rect(); let presets = h.get_by_label("Presets").rect(); assert!(naming.center().y < presets.top() && (naming.center().y - tabs.center().y).abs() < tabs.height(), "on the tab row: {naming:?}"); @@ -353,13 +387,13 @@ fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { assert!(h.query_by_label(absent).is_none(), "{absent}"); } assert!(h.query_by_label_contains("textures selected for export").is_none()); - for greyed in ["Save settings", "Export"] { + for active in ["Save settings", "Export", "Cancel"] { // The rail at the right edge has an Export button of its own let button = - h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)).unwrap(); - assert!(button.accesskit_node().is_disabled(), "{greyed}"); + h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(active)).unwrap(); + + assert!(!button.accesskit_node().is_disabled(), "{active}"); } - assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); } #[test] @@ -494,6 +528,31 @@ fn a_color_map_dropped_on_the_rgb_swatch_offers_rgb_channels() { assert!(h.query_all_by_label("RGB: Base color, RGB").next().is_some()); } +#[test] +fn escape_in_a_file_name_field_leaves_the_field_and_keeps_the_window() { + let library = TemplateLibrary::new("escape-in-a-field"); + let mut h = harness(&library); + let field = name_field(&h, 0).center(); + h.hover_at(field); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: field, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(4); + + assert!(h.ctx.egui_wants_keyboard_input(), "the field has the keyboard"); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.state().ui.windows.export, "the window stays open"); + assert!(!h.ctx.egui_wants_keyboard_input(), "the field let go of the keyboard"); + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export, "a second Escape is Cancel"); +} + #[test] fn escape_closes_the_from_popup_without_assigning() { let library = TemplateLibrary::new("drop-escape"); @@ -513,6 +572,7 @@ fn escape_closes_the_from_popup_without_assigning() { assert!(h.query_by_label("Which part of Metallic?").is_none(), "Escape closes the popup"); assert!(h.state().ui.export.pending_drop.is_none()); + assert!(h.state().ui.windows.export, "the window stays open"); assert_eq!(h.state().session.export_preset("Mine").unwrap(), before, "nothing was assigned"); } @@ -592,7 +652,7 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { click(&mut h, "R+G+B+A"); let input_maps = h.get_by_label("Input maps").rect(); - let removes: Vec = h.get_all_by_label("Remove this output").map(|node| node.rect()).collect(); + let removes: Vec = h.get_all_by_label_contains("Remove output ").map(|node| node.rect()).collect(); let alpha = last_window_button(&h, "A: Empty (writes white)").rect(); assert!(!removes.is_empty()); @@ -610,12 +670,121 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { // The row's file format list starts right of its last swatch instead of covering it let format = h.get_all_by_role(egui::Role::Button).rfind(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("png"))).unwrap().rect(); + assert!(alpha.right() <= format.left(), "the swatches and the lists do not overlap: {alpha:?} {format:?}"); // The panes stay inside the window: the side pane ends where the bottom bar's buttons end let cancel = h.get_all_by_label("Cancel").last().unwrap().rect(); let export = last_window_button(&h, "Export").rect(); let converted = h.get_by_label("Converted maps").rect(); + assert!(cancel.max.x <= 1000.0 && cancel.max.y <= 700.0, "{cancel:?}"); assert!(converted.left() < export.right() && converted.right() <= export.right() + 1.0, "{converted:?} {export:?}"); } + +#[test] +fn a_narrow_template_editor_keeps_the_alpha_swatch_clear_of_the_file_type_menu() { + let library = TemplateLibrary::new("narrow-template-editor"); + let mut harness = harness_at(&library, egui::vec2(800.0, 480.0)); + let create = harness.get_by_role_and_label(egui::Role::Button, "R+G+B+A"); + create.scroll_to_me(); + harness.run_steps(4); + + click(&mut harness, "R+G+B+A"); + let alpha = last_window_button(&harness, "A: Empty (writes white)").rect(); + let format = harness + .get_all_by_role(egui::Role::Button) + .rfind(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("png"))) + .unwrap() + .rect(); + + assert!(alpha.right() <= format.left(), "alpha {alpha:?} overlaps format {format:?}"); +} + +#[test] +fn hovering_a_channel_swatch_shows_the_file_its_output_writes() { + let library = TemplateLibrary::new("map-preview"); + let mut h = harness(&library); + let swatch = + h.get_all_by_role(egui::Role::Button).find(|b| b.accesskit_node().label().is_some_and(|l| l.starts_with("B: Metallic"))).unwrap().rect().center(); + let pictures = h.query_all_by_role(egui::Role::Image).count(); + let roughness_lines = h.query_all_by_label("Roughness, gray value").count(); + let file_names = h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count(); + + assert!(h.query_by_label_contains(" · png").is_none(), "nothing shows before the hover"); + + h.hover_at(swatch); + h.run_steps(30); + + assert!(h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count() > file_names, "the file's name"); + assert!(h.query_by_label_contains(" · png").is_some(), "the file's size and type"); + assert!(h.query_all_by_role(egui::Role::Image).count() > pictures, "the file and its channels, small"); + assert!(h.query_all_by_label("Roughness, gray value").count() > roughness_lines, "another channel's source is named"); +} + +#[test] +fn leaving_output_templates_releases_pictures_from_each_hovered_map() { + let library = TemplateLibrary::new("preview-lifetime"); + let mut h = harness(&library); + let previews = |h: &Harness<'_, TextureCraftApp>| { + h.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("export_map_preview_")).count() + }; + let hover_map = |h: &mut Harness<'_, TextureCraftApp>, name: &str| { + let swatch = h + .get_all_by_role(egui::Role::Button) + .find(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with(name))) + .unwrap_or_else(|| panic!("no swatch for {name}")) + .rect(); + h.hover_at(swatch.center()); + h.run_steps(30); + }; + + hover_map(&mut h, "B: Metallic"); + let first = previews(&h); + + assert!(first > 0); + hover_map(&mut h, "RGB: Base color"); + assert!(previews(&h) > first); + + click(&mut h, "Settings"); + + assert_eq!(previews(&h), 0); + + click(&mut h, "Output templates"); + hover_map(&mut h, "B: Metallic"); + assert_eq!(previews(&h), first); + click(&mut h, "Cancel"); + + assert_eq!(previews(&h), 0); + + h.state_mut().ui.windows.export = true; + h.run_steps(4); + click(&mut h, "Output templates"); + hover_map(&mut h, "B: Metallic"); + assert_eq!(previews(&h), first); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(previews(&h), 0); +} + +#[test] +fn feedback_template_preview_counts_overrides_only_for_its_own_maps() { + let library = TemplateLibrary::new("preview-map-overrides"); + let mut h = harness(&library); + let ts = h.state().session.ts(); + let plan = h.state_mut().run("export.plan", json!({"ts": ts, "preset": "Mine"})).unwrap(); + let initial = plan.as_array().unwrap().len(); + assert!(initial > 0); + let disabled = MapExport { enabled: false, ..MapExport::default() }; + h.state_mut().ui.export.sets.insert(ts, SetExport { maps_template: "Mine".into(), maps: [(0, disabled)].into(), ..SetExport::default() }); + + h.run_steps(4); + + assert!(h.query_by_label(&format!("{} output maps will be exported", initial - 1)).is_some()); + h.state_mut().ui.export.sets.get_mut(&ts).unwrap().preset = Some("Separate maps".into()); + h.run_steps(4); + assert!(h.query_by_label(&format!("{initial} output maps will be exported")).is_some()); +} diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 9dad93e9..cd50cbca 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -115,22 +115,26 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { harness.run_steps(SETTLE_FRAMES); assert!(harness.state().ui.windows.export, "Export Textures... opens the Export textures window"); - for label in - ["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS", "Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] - { + for tab in ["Settings", "Output templates", "List of exports"] { + assert!(harness.query_by_role_and_label(egui::Role::Tab, tab).is_some(), "{tab}"); + } + for label in ["Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] { 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 shader settings")); + for label in ["Export USD asset", "Export shader settings"] { + assert!(!says_not_available(&mut harness, label), "{label}"); + } harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); + assert!(!harness.state().ui.windows.export, "Save settings closes the window"); click_rail(&mut harness, "Export"); button_left_of_rail(&harness, "Export Mesh...").click(); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Mesh Export Options").is_some(), "Export Mesh... asks for the options first"); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 352d5c88..ae1e7c83 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3445,3 +3445,93 @@ fn sheet_scroll_end_snapshots() { harness.run_steps(30); save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); } + +/// The Export textures window on each tab at its mocks' size; TC_SNAPSHOT_THEME=medium (default), dark or light +#[test] +#[ignore] +fn export_window_snapshots() { + use texturecraft_ui_egui::state::{FileType, MapExport, SetExport}; + + // Below General Export Parameters, where the 1112x662 window draws nothing + const EMPTY_SPOT: egui::Pos2 = egui::pos2(736.0, 530.0); + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let (brightness, theme) = match std::env::var("TC_SNAPSHOT_THEME").as_deref() { + Ok("dark") => (Brightness::Dark, "dark"), + Ok("light") => (Brightness::Light, "light"), + _ => (Brightness::MediumDark, "medium"), + }; + + // Ball and Base, then enough texture sets that the set list scrolls + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let template = session.doc.project.texture_sets[0].clone(); + while session.doc.project.texture_sets.len() < 60 { + let mut set = template.clone(); + set.name = format!("Set {}", session.doc.project.texture_sets.len() + 1); + session.doc.project.texture_sets.push(set); + } + let mut harness = Harness::builder() + .with_size(egui::vec2(1112.0, 662.0)) + .with_pixels_per_point(2.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .wgpu() + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.prefs.brightness = brightness; + harness.set_render_cursor(false); + { + let e = &mut harness.state_mut().ui.export; + e.dir = "/home/user/Documents/TextureCraft/export".into(); + e.preset = "Document channels + Normal + AO (No Alpha)".into(); + e.padding = "infinite".into(); + e.skip = vec![4]; + } + harness.state_mut().ui.windows.export = true; + harness.run_steps(4); + let color_space = harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Default")).unwrap().rect(); + harness.hover_at(color_space.center()); + harness.run_steps(30); + save(&mut harness, &output_dir, &format!("ep-settings-global-{theme}")); + harness.hover_at(egui::pos2(1.0, 1.0)); + + harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Based on output template")).unwrap().click(); + harness.run_steps(3); + save(&mut harness, &output_dir, &format!("ep-settings-file-type-open-{theme}")); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The closed list keeps the keyboard focus (and its ring) until a click lands on the page's empty column + harness.hover_at(EMPTY_SPOT); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: EMPTY_SPOT, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + harness.hover_at(egui::pos2(1.0, 1.0)); + harness.run_steps(3); + + // Base with its own size and its height map as 32-bit exr + { + let e = &mut harness.state_mut().ui.export; + e.page = Some(1); + let mut set = SetExport { size: Some(1024), ..SetExport::default() }; + set.maps_template = e.preset.clone(); + let template = texturecraft_engine::formats::builtin_preset(&e.preset).unwrap(); + let height = template.maps.iter().position(|map| texturecraft_engine::formats::export::channel_label(map) == "height").unwrap(); + set.maps.insert(height, MapExport { file_type: Some(FileType { format: "exr".into(), bit_depth: 32, dithering: false }), ..MapExport::default() }); + set.maps.insert(2, MapExport { enabled: false, ..MapExport::default() }); + e.sets.insert(1, set); + } + save(&mut harness, &output_dir, &format!("ep-settings-set-{theme}")); + + harness.state_mut().ui.export.page = None; + harness.state_mut().ui.export.tab = 1; + harness.state_mut().ui.export.preset = "Unreal Engine (Packed)".into(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Unreal Engine (Packed)").scroll_to_me(); + save(&mut harness, &output_dir, &format!("ep-templates-unreal-{theme}")); + + harness.state_mut().ui.export.preset = "Document channels + Normal + AO (No Alpha)".into(); + harness.state_mut().ui.export.tab = 2; + save(&mut harness, &output_dir, &format!("ep-list-{theme}")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 50799e0d..49070f1b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -42,11 +42,19 @@ file runs it; Copy mask to clipboard puts the same mask on the system clipboard grayscale image (the whole tile atlas for a UV-tiled set). `file.exportTextures`, `export.plan`, the automation `textures.export` method and the MCP -`textures_export` tool accept `maps: [{map, enabled?, format?, bitDepth?, dithering?}]`. +`textures_export` tool accept `maps: [{map, enabled?, format?, bitDepth?, dithering?, size?}]`. Each entry overrides that map's export settings. The `map` field is its index in the selected -template. `enabled: false` suppresses that file while reserving its name. When several texture -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. +template. A map's `size` in pixels overrides the export size. `enabled: false` leaves out a PSD layer +or suppresses a raster file while reserving its name. When several texture 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. Texture planning +rejects a selection that uses the same path as both a file and a folder before rendering. + +`shaderParameters: true` writes `_shaders.json` beside the textures with the shader +model, its settings and the names of the exported texture sets. An array of texture set +indexes selects which sets to list. The desktop command, headless `textures.export` and MCP +`textures_export` include a written sidecar in `files` and report a sidecar write failure in +`warnings` after writing the textures. `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 @@ -77,9 +85,31 @@ 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 -`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `padding: "diffusion"` dilates by +`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). +Tiled files include their UV tile number in `tile` and, when available, their filename template +with a `` placeholder in `udimPattern`. These fields are null when they do not apply. +`export.preview` takes the same parameters plus `map` (an index into the template's maps) and +`side` (the maximum width or height, in pixels, capped at 512). It returns +`{width, height, channels, pixels}` for the first texture set named by `ts`, or null when the +set writes no file for that map. For a UV-tiled set the picture shows the atlas. HDR previews +list RGB without alpha. TIFF and WebP previews list RGB or RGBA when the encoder stores +luminance in three channels. PSD previews show the output layer's RGBA channels. The preview uses 8-bit values, +with sRGB colour channels and linear data channels. Texels outside the UV islands use the +channel defaults. +`padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. +Layered PSD: the maps written as `psd` are the layers of one `_.psd` per +texture set and UV tile (`_..psd` for a tiled set), so the template's file +names don't name the file: they become the layer names, a `/` in one making layer groups. The +document name is sanitized like other file names and can be shortened or disambiguated (a +texture-set index suffix when two sets' names give the same stem, as "A B" and "A_B" do), so read +the actual names from `export.plan`. A PSD that would pass 30000 pixels a side or 2 GiB is left +out with a warning on the set's first other file (an error when it is the set's only file). In the +browser, estimates of a PSD's working buffers and of a batch's encoded PSD output are also bounded; +they don't bound the tab's total memory, as raster outputs and ZIP packaging use memory outside +them. MaterialX uses compatible companion maps for this format. USD omits their texture bindings and returns a warning. + `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus the supplied parameters; naming the current filter instead edits it without resetting omitted diff --git a/docs/features.md b/docs/features.md index 9424bb2d..e66cc81e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -186,7 +186,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA stroke turns it on for the Normal map if the set has no Auto-rebake map. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, Sketchfab (metalness), separate maps, mesh maps and document channels, in PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals.