diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 9f0d126b..922c380b 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -65,6 +65,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); v.extend(crate::meshmap_cmds::specs()); + v.extend(crate::meshmap_import_cmds::specs()); v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..da0ab3ae 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,8 @@ pub mod material_lib; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod meshmap_file_name; +pub mod meshmap_import_cmds; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 0fbe1f5b..932ba137 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -38,11 +38,17 @@ fn set(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; - let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let resolution = s.edit("Use image as mesh map", |s| use_image(s, CMD, ts, map, name))?; + Ok(json!({ "map": map.id(), "resolution": resolution })) +} + +/// Use image resource `name` as mesh map `map` of set `ts` inside the caller's edit; returns the map width +pub(crate) fn use_image(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, name: &str) -> Result { + let img = s.images.get(name).cloned().ok_or_else(|| bad(cmd, format!("no image resource `{name}`")))?; let set = s.doc.project.texture_set(ts)?.clone(); - let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; - // Every mesh map of a set shares one size: the other maps', or what a bake would make (a - // block of the bake resolution per tile of the atlas). + let tiles = set.tile_grid().map(|grid| tile_images(&s.images, cmd, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; + + // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), @@ -52,37 +58,34 @@ fn set(s: &mut Session, p: &Value) -> Result { } }; if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { - return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty"))); + return Err(bad(cmd, format!("mesh map size {res} × {height} is too large or empty"))); } + let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; let data = match &tiles { None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), - // An atlas texel reads the image of the tile its mesh UV falls in. + // An atlas texel reads the image of the tile its mesh UV falls in Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { let uv = grid.from_atlas([u, v]); udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) }), }; - s.edit("Use image as mesh map", |s| { - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = res; - entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(()) - })?; - Ok(json!({ "map": map.id(), "resolution": res })) + + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = res; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(res) } -/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for -/// each tile's. -fn tile_images(images: &ImageStore, name: &str, tiles: &[u32]) -> Result>> { - const CMD: &str = "textureSet.meshMap.set"; - let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; +/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's +fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> { + let at = udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; tiles .iter() .map(|&t| { let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default()); - images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}"))) + images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {t}"))) }) .collect() } diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs new file mode 100644 index 00000000..cfc4f125 --- /dev/null +++ b/crates/engine/src/meshmap_file_name.rs @@ -0,0 +1,153 @@ +//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion) + +use std::path::Path; + +use texturecraft_core::{BakedMap, UDIM_RANGE}; + +/// Mesh maps named by two words anywhere in the file name; they win over the one-word names +const TWO_WORD_NAMES: [(&str, &[&str], BakedMap); 3] = [ + ("world", &["normal", "normals"], BakedMap::WorldNormal), + ("bent", &["normal", "normals"], BakedMap::BentNormal), + ("ambient", &["occlusion"], BakedMap::AmbientOcclusion), +]; + +const ONE_WORD_NAMES: [(&str, BakedMap); 20] = [ + ("worldnormal", BakedMap::WorldNormal), + ("worldnormals", BakedMap::WorldNormal), + ("bentnormal", BakedMap::BentNormal), + ("bentnormals", BakedMap::BentNormal), + ("ambientocclusion", BakedMap::AmbientOcclusion), + ("normal", BakedMap::Normal), + ("normals", BakedMap::Normal), + ("nrm", BakedMap::Normal), + ("occlusion", BakedMap::AmbientOcclusion), + ("ao", BakedMap::AmbientOcclusion), + ("curvature", BakedMap::Curvature), + ("curv", BakedMap::Curvature), + ("id", BakedMap::Id), + ("position", BakedMap::Position), + ("pos", BakedMap::Position), + ("thickness", BakedMap::Thickness), + ("height", BakedMap::Height), + ("displacement", BakedMap::Height), + ("opacity", BakedMap::Opacity), + ("alpha", BakedMap::Opacity), +]; + +fn is_separator(c: char) -> bool { + matches!(c, '_' | '-' | '.' | ' ') +} + +/// The file name without its folder and extension +fn stem(path: &str) -> &str { + Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or_default() +} + +/// The lowercase words of a file name, without UV tile numbers (`Body_AO.1001` → body, ao) +fn words(path: &str) -> Vec { + stem(path) + .split(is_separator) + .filter(|w| !w.is_empty() && !w.parse::().is_ok_and(|n| w.len() == 4 && UDIM_RANGE.contains(&n))) + .map(str::to_lowercase) + .collect() +} + +/// The mesh map a file holds, from the words of its name; the last recognised word wins +pub(crate) fn baked_map_from_file_name(path: &str) -> Option { + let words = words(path); + let has = |word: &str| words.iter().any(|w| w == word); + TWO_WORD_NAMES + .iter() + .find(|(first, seconds, _)| has(first) && seconds.iter().any(|s| has(s))) + .map(|(_, _, map)| *map) + .or_else(|| words.iter().rev().find_map(|w| ONE_WORD_NAMES.iter().find(|(name, _)| name == w).map(|(_, map)| *map))) +} + +/// The set a file is for: the longest set name its name starts with before a separator (any name with one set) +pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option { + if set_names.len() == 1 { + return Some(0); + } + + let stem = stem(path).to_lowercase(); + set_names + .iter() + .enumerate() + .filter(|(_, name)| !name.is_empty()) + .filter(|(_, name)| stem.strip_prefix(&name.to_lowercase()).and_then(|rest| rest.chars().next()).is_some_and(is_separator)) + .max_by_key(|(_, name)| name.chars().count()) + .map(|(ts, _)| ts) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_word_names_its_map() { + let cases = [ + ("Body_normal.png", BakedMap::Normal), + ("Body_normals.png", BakedMap::Normal), + ("Body_nrm.png", BakedMap::Normal), + ("Body_world_normal.png", BakedMap::WorldNormal), + ("Body_normals_world.png", BakedMap::WorldNormal), + ("Body_WorldNormal.png", BakedMap::WorldNormal), + ("Body_bent_normals.png", BakedMap::BentNormal), + ("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion), + ("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion), + ("Body_occlusion.png", BakedMap::AmbientOcclusion), + ("Body AO.png", BakedMap::AmbientOcclusion), + ("Body_curvature.png", BakedMap::Curvature), + ("Body_curv.png", BakedMap::Curvature), + ("Body_ID.png", BakedMap::Id), + ("Body_position.png", BakedMap::Position), + ("Body_pos.png", BakedMap::Position), + ("Body_thickness.png", BakedMap::Thickness), + ("Body_height.png", BakedMap::Height), + ("Body_displacement.png", BakedMap::Height), + ("Body_opacity.png", BakedMap::Opacity), + ("Body_alpha.png", BakedMap::Opacity), + ]; + for (file, map) in cases { + assert_eq!(baked_map_from_file_name(file), Some(map), "{file}"); + } + } + + #[test] + fn tile_numbers_and_folders_are_ignored() { + assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png"), Some(BakedMap::AmbientOcclusion)); + assert_eq!(baked_map_from_file_name("Body_normal_1002.tga"), Some(BakedMap::Normal)); + assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1)); + } + + #[test] + fn unknown_words_match_no_map() { + assert_eq!(baked_map_from_file_name("Body_diffuse.png"), None); + assert_eq!(baked_map_from_file_name("Body_1001.png"), None); + assert_eq!(baked_map_from_file_name("ambient.png"), None); + assert_eq!(baked_map_from_file_name(""), None); + } + + #[test] + fn the_longest_set_name_wins() { + let sets = ["Body", "Body_Upper", "Head"]; + assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1)); + assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0)); + assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2)); + } + + #[test] + fn a_set_name_must_end_at_a_separator() { + let sets = ["Body", "Head"]; + assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Body.png", &sets), None); + } + + #[test] + fn one_set_takes_every_file() { + assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("ao.png", &[]), None); + } +} diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs new file mode 100644 index 00000000..9770cf63 --- /dev/null +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -0,0 +1,79 @@ +//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_core::BakedMap; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::meshmap_cmds::use_image; +use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; +use crate::resource_cmds::read_image_file; +use crate::{Result, Session, cmd}; + +const CMD: &str = "textureSet.meshMap.import"; + +/// Most files one import takes +const MAX_FILES: usize = 1024; + +pub fn specs() -> Vec { + vec![cmd!( + "textureSet.meshMap.import", + "Import baked maps", + [], + None, + "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set: a UV-tiled set takes one file per tile (`Body_ao.1001.png`, `Body_ao.1002.png`). Files matching no set or map, and any file after the first for one slot, are left out and listed in `unmatched`. One undo step; desktop only", + always, + import + )] +} + +fn import(s: &mut Session, p: &Value) -> Result { + let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?; + if files.len() > MAX_FILES { + return Err(bad(CMD, format!("at most {MAX_FILES} files at once"))); + } + + let set_names: Vec = s.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); + let set_names: Vec<&str> = set_names.iter().map(String::as_str).collect(); + let mut slots: BTreeMap<(usize, BakedMap), Vec<&str>> = BTreeMap::new(); + let mut unmatched = Vec::new(); + for file in files { + let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?; + let map = match strp(file, "map") { + Some(id) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?), + None => baked_map_from_file_name(path), + }; + match (texture_set_from_file_name(path, &set_names), map) { + (Some(ts), Some(map)) => slots.entry((ts, map)).or_default().push(path), + _ => unmatched.push(path), + } + } + + let result = s.edit("Import baked maps", |s| { + let mut assigned = Vec::new(); + for ((ts, map), paths) in &slots { + // A UV-tiled set reads every tile's file; any other set takes the first file for a slot + let files_used = if s.doc.project.texture_set(*ts)?.tile_grid().is_some() { paths.len() } else { 1 }; + let (taken, extra) = paths.split_at(files_used); + let mut image_name = None; + for path in taken { + let name = s.add_image_resource(path, read_image_file(CMD, path)?)?; + image_name.get_or_insert(name); + } + if let Some(name) = image_name { + use_image(s, CMD, *ts, *map, &name)?; + } + + assigned.extend(taken.iter().map(|path| json!({"path": path, "ts": ts, "map": map.id()}))); + unmatched.extend(extra); + } + Ok(assigned) + }); + // A failed edit leaves the document as it was; forget the images it decoded + if result.is_err() { + s.sync_images(); + } + + Ok(json!({ "assigned": result?, "unmatched": unmatched })) +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 87f6d50f..74682be8 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -38,9 +38,15 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name. pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + self.edit("Import resource", |s| s.add_image_resource(file_name, bytes)) + } + + /// [`Session::import_resource_bytes`] without its own undo step, for imports inside a larger edit + pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec) -> Result { if bytes.len() > MAX_BYTES { return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); } + let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image"); let base = texturecraft_formats::sanitize_resource_name(leaf); @@ -50,11 +56,8 @@ impl Session { name = format!("{n}_{base}"); n += 1; } - let key = name.clone(); - self.edit("Import resource", |s| { - s.doc.resources.insert(key, Arc::new(bytes)); - Ok(()) - })?; + + self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); Ok(name) } @@ -98,15 +101,27 @@ fn list(s: &Session) -> Value { #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; - let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; - if meta.len() > MAX_BYTES as u64 { - return Err(bad("resource.import", format!("{path} is too large"))); - } - let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; + let bytes = read_image_file("resource.import", path)?; let name = s.import_resource_bytes(path, bytes)?; Ok(json!({ "name": name })) } +/// The bytes of the image file at `path`, refused above [`MAX_BYTES`] +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_image_file(cmd: &str, path: &str) -> Result> { + let meta = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + if meta.len() > MAX_BYTES as u64 { + return Err(bad(cmd, format!("{path} is too large"))); + } + + std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}"))) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_image_file(cmd: &str, _: &str) -> Result> { + Err(bad(cmd, "file paths are not available in the browser")) +} + #[cfg(target_arch = "wasm32")] fn import(_: &mut Session, _: &Value) -> Result { Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into())) diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs new file mode 100644 index 00000000..62a983d6 --- /dev/null +++ b/crates/engine/tests/meshmap_import.rs @@ -0,0 +1,136 @@ +//! Importing baked map files at once: each lands in the texture set and mesh map its name names + +use std::path::PathBuf; + +use serde_json::{Value, json}; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The material ball: texture sets "Ball" and "Base" +fn session() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +/// A folder of 4×4 gray PNGs named `files`, each with its own gray level +fn bake_folder(test: &str, files: &[&str]) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (index, file) in files.iter().enumerate() { + let gray = 20 + 20 * index as u8; + image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap(); + } + dir +} + +fn import(s: &mut Session, dir: &PathBuf, files: &[(&str, Option<&str>)]) -> Value { + let files: Vec = files + .iter() + .map(|(file, map)| { + let path = dir.join(file).display().to_string(); + match map { + Some(map) => json!({"path": path, "map": map}), + None => json!({"path": path}), + } + }) + .collect(); + execute(s, "textureSet.meshMap.import", &json!({ "files": files })).unwrap() +} + +fn file_names(list: &Value) -> Vec { + list.as_array() + .unwrap() + .iter() + .map(|v| v.as_str().map_or_else(|| v["path"].as_str().unwrap(), |p| p)) + .map(|p| p.rsplit(['/', '\\']).next().unwrap().to_string()) + .collect() +} + +fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool { + s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) +} + +#[test] +fn files_go_to_the_set_and_map_their_names_name() { + let files = ["Ball_normal.png", "Ball_world_normal.png", "base-AO.png", "Base_curvature.png", "Ball_diffuse.png", "Head_ao.png", "Base_id.png"]; + let dir = bake_folder("sets", &files); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &files.map(|f| (f, None))); + + let assigned = &result["assigned"]; + assert_eq!(file_names(assigned).len(), 5, "{result}"); + for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] { + assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id()); + assert!(assigned.as_array().unwrap().iter().any(|a| a["ts"] == ts && a["map"] == map.id()), "{result}"); + } + assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]); + assert_eq!(s.undo_label(), Some("Import baked maps")); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step"); + assert!(s.doc.baked.values().all(|b| b.maps.is_empty()), "undo removes every imported map"); + assert!(s.doc.resources.is_empty(), "undo removes the imported images"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_given_map_overrides_the_name() { + let dir = bake_folder("override", &["Ball_bake3.png", "Base_normal.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_bake3.png", Some("thickness")), ("Base_normal.png", Some("height"))]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + assert!(has_map(&s, 0, BakedMap::Thickness)); + assert!(has_map(&s, 1, BakedMap::Height)); + assert!(!has_map(&s, 1, BakedMap::Normal)); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_second_file_for_one_slot_is_left_out() { + let dir = bake_folder("twice", &["Ball_ao.png", "Ball_occlusion.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_ao.png", None), ("Ball_occlusion.png", None)]); + + assert_eq!(file_names(&result["assigned"]), ["Ball_ao.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Ball_occlusion.png"]); + assert_eq!(s.doc.resources.len(), 1, "the left-out file is not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_failed_file_imports_nothing() { + let dir = bake_folder("failed", &["Ball_ao.png"]); + std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap(); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + let files = json!({"files": [{"path": dir.join("Ball_ao.png").display().to_string()}, {"path": dir.join("Base_ao.png").display().to_string()}]}); + + let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string(); + + assert!(error.contains("Base_ao.png"), "{error}"); + assert!(s.doc.baked.values().all(|b| b.maps.is_empty())); + assert!(s.doc.resources.is_empty() && s.images.is_empty()); + assert_eq!(s.undo_label().map(str::to_string), label_before); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_uv_tiled_set_takes_one_file_per_tile() { + let dir = bake_folder("tiles", &["Plane_ao.1001.png", "Plane_ao.1002.png"]); + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + + let result = import(&mut s, &dir, &[("Plane_ao.1001.png", None), ("Plane_ao.1002.png", None)]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + let baked = &s.doc.baked[&0]; + let ao = &baked.maps[&BakedMap::AmbientOcclusion]; + let width = baked.resolution as usize; + let middle_row = ao.len() / width / 2 * width; + assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file"); + std::fs::remove_dir_all(dir).ok(); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..e1746a31 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Advanced settings", "إعدادات متقدمة"), + ("Import baked maps", "استيراد خرائط مخبوزة"), + ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), + ("Add...", "إضافة..."), + ("Imported {count} baked maps", "تم استيراد {count} من الخرائط المخبوزة"), + ("Not imported: {files}", "لم يتم استيرادها: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..1b86b2e7 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Advanced settings", "Erweiterte Einstellungen"), + ("Import baked maps", "Gebackene Maps importieren"), + ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), + ("Add...", "Hinzufügen..."), + ("Imported {count} baked maps", "{count} gebackene Maps importiert"), + ("Not imported: {files}", "Nicht importiert: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..a0445eed 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Advanced settings", "Ajustes avanzados"), + ("Import baked maps", "Importar mapas horneados"), + ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), + ("Add...", "Añadir..."), + ("Imported {count} baked maps", "{count} mapas horneados importados"), + ("Not imported: {files}", "Sin importar: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..235bf5a9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Advanced settings", "Paramètres avancés"), + ("Import baked maps", "Importer des cartes précalculées"), + ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), + ("Add...", "Ajouter..."), + ("Imported {count} baked maps", "{count} cartes précalculées importées"), + ("Not imported: {files}", "Non importés : {files}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..12a180ed 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Advanced settings", "Impostazioni avanzate"), + ("Import baked maps", "Importa mappe bake"), + ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), + ("Add...", "Aggiungi..."), + ("Imported {count} baked maps", "{count} mappe bake importate"), + ("Not imported: {files}", "Non importati: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..8b930774 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Advanced settings", "詳細設定"), + ("Import baked maps", "ベイク済みマップを読み込む"), + ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), + ("Add...", "追加..."), + ("Imported {count} baked maps", "ベイク済みマップを {count} 個読み込みました"), + ("Not imported: {files}", "読み込まれなかったファイル: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..30d5eef5 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Advanced settings", "고급 설정"), + ("Import baked maps", "베이크된 맵 가져오기"), + ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), + ("Add...", "추가..."), + ("Imported {count} baked maps", "베이크된 맵 {count}개를 가져왔습니다"), + ("Not imported: {files}", "가져오지 않음: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..330c09a3 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Advanced settings", "Configurações avançadas"), + ("Import baked maps", "Importar mapas com bake"), + ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), + ("Add...", "Adicionar..."), + ("Imported {count} baked maps", "{count} mapas com bake importados"), + ("Not imported: {files}", "Não importados: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..f0731a7c 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Advanced settings", "高级设置"), + ("Import baked maps", "导入已烘焙贴图"), + ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), + ("Add...", "添加..."), + ("Imported {count} baked maps", "已导入 {count} 张烘焙贴图"), + ("Not imported: {files}", "未导入:{files}"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..23f67ca9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -19,6 +19,7 @@ pub mod keymap; mod mask_preview_image; mod mask_shape; pub mod menus; +pub mod new_project_advanced; pub mod parity; mod preview_image; mod preview_request; diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs new file mode 100644 index 00000000..50dd64c6 --- /dev/null +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -0,0 +1,155 @@ +//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation + +use egui::{RichText, Sense, Ui, vec2}; +use serde_json::{Value, json}; +use texturecraft_engine::core::NormalFormat; +use texturecraft_engine::template_cmds::builtin_templates; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::NewProject; +use crate::theme::{Tokens, caption}; +use crate::widgets::{section, section_chevron}; +use crate::windows::file_dialogs_available; + +/// Labels of every New project form row, so Basic and Advanced share one label column +const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolution", "UV tiles (UDIM)", "Name", "Normal map format"]; + +/// Each normal map format with its command id and label +const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; + +/// Width of the dialog's dropdowns +const COMBO_WIDTH: f32 = 200.0; + +/// Width of the Add... and Clear buttons +const FILE_BUTTON_WIDTH: f32 = 96.0; + +/// Tallest the list of added files grows before it scrolls +const FILE_LIST_HEIGHT: f32 = 160.0; + +/// Width of the widest form label, for the label column of every form grid in the dialog +pub(crate) fn form_label_width(ui: &Ui) -> f32 { + let font = egui::TextStyle::Body.resolve(ui.style()); + FORM_LABELS.iter().map(|label| ui.painter().layout_no_wrap(tr(label).to_string(), font.clone(), egui::Color32::WHITE).size().x).fold(0.0, f32::max) +} + +/// The collapsible Advanced settings section (closed until opened) +pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + let id = ui.make_persistent_id("np_advanced"); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false); + let header = ui + .horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); + ui.add(egui::Label::new(caption(tr("Advanced settings"))).selectable(false)); + }) + .response + .interact(Sense::click()); + if header.clicked() { + state.toggle(ui); + } + + state.show_body_unindented(ui, |ui| { + egui::Grid::new("np_advanced_grid").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(form_label_width(ui)).show(ui, |ui| { + ui.label(tr("Normal map format")); + normal_format_combo(app, ui); + ui.end_row(); + }); + if file_dialogs_available() { + ui.add_space(4.0); + section(ui, "np_baked_maps", tr("Import baked maps"), false, |ui| baked_maps(&mut app.ui.new_project, ui)); + } + }); +} + +fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { + let new_project = &mut app.ui.new_project; + let user_templates = app.session.templates.list.iter().cloned(); + let template_format = + builtin_templates().into_iter().chain(user_templates).find(|t| t.name == new_project.template).map(|t| t.normal_format).unwrap_or_default(); + let current = new_project.normal_format.unwrap_or(template_format); + let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); + egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { + for (format, _, label) in NORMAL_FORMATS { + if ui.selectable_label(format == current, label).clicked() { + new_project.normal_format = Some(format); + } + } + }); +} + +fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x; + let hint_width = (ui.available_width() - buttons_width - ui.spacing().item_spacing.x).max(0.0); + ui.allocate_ui_with_layout(vec2(hint_width, 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(hint_width); + ui.add(egui::Label::new(RichText::new(tr("Name each file after its texture set, like Body_normal.png")).color(tokens.text_dim)).wrap()); + }); + if ui.add(egui::Button::new(tr("Add...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + add_baked_map_files(new_project, pick_baked_map_files()); + } + if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + new_project.baked_maps.clear(); + } + }); + if new_project.baked_maps.is_empty() { + return; + } + + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(FILE_LIST_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); +} + +/// List picked baked map files (files already listed are skipped) +pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { + for path in paths { + if !new_project.baked_maps.contains(&path) { + new_project.baked_maps.push(path); + } + } +} + +/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome +pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { + let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); + if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { + app.run("textureSet.settings", json!({ "normalFormat": id })); + } + if new_project.baked_maps.is_empty() { + return; + } + + let files: Vec = new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); + let Some(result) = app.run("textureSet.meshMap.import", json!({ "files": files })) else { + return; + }; + + let assigned = result["assigned"].as_array().map_or(0, Vec::len); + let not_imported: Vec = result["unmatched"].as_array().into_iter().flatten().filter_map(Value::as_str).map(file_name).collect(); + let mut text = trf("Imported {count} baked maps", &[("count", &assigned)]); + if !not_imported.is_empty() { + text.push('\n'); + text.push_str(&trf("Not imported: {files}", &[("files", ¬_imported.join(", "))])); + } + app.toast(text, !not_imported.is_empty()); +} + +fn file_name(path: &str) -> String { + std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |name| name.to_string_lossy().into_owned()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn pick_baked_map_files() -> Vec { + let files = rfd::FileDialog::new().add_filter(tr("Images"), crate::web_files::IMAGE_EXTS).pick_files(); + files.unwrap_or_default().into_iter().map(|path| path.display().to_string()).collect() +} + +#[cfg(target_arch = "wasm32")] +fn pick_baked_map_files() -> Vec { + Vec::new() +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..f22d1d69 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; @@ -151,6 +151,12 @@ pub struct NewProject { /// Name typed to save the current project's settings as a template. #[serde(skip)] pub template_name: String, + /// Normal map format of the project and its imported normal maps; None keeps the template's + #[serde(default)] + pub normal_format: Option, + /// Baked map files to import at creation, matched to sets and mesh maps by name (desktop only) + #[serde(skip)] + pub baked_maps: Vec, } fn default_template() -> String { @@ -167,6 +173,8 @@ impl Default for NewProject { uv_tiles: None, template: default_template(), template_name: String::new(), + normal_format: None, + baked_maps: Vec::new(), } } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0c35d957..8ac07749 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -392,7 +392,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut create = false; dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { ui.label(caption(tr("Basic settings"))); - egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(crate::new_project_advanced::form_label_width(ui)).show(ui, |ui| { ui.label(tr("3D mesh")); ui.horizontal(|ui| { let label = app.ui.new_project.file.clone().unwrap_or_else(|| { @@ -429,6 +429,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if ui.selectable_label(t.name == np.template, &t.name).clicked() { np.template = t.name.clone(); np.resolution = t.resolution; + np.normal_format = None; } } }); @@ -469,6 +470,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); }); ui.add_space(8.0); + crate::new_project_advanced::advanced_settings(app, ui); + ui.add_space(8.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add(primary_button(ui, tr("Create"))).clicked() { @@ -490,6 +493,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if r.is_some() { app.ui.windows.new_project = false; app.ui.mode = Mode::Painting; + app.ui.new_project.baked_maps.clear(); + crate::new_project_advanced::apply_after_create(app, &np); } } if !open { diff --git a/crates/ui-egui/tests/new_project_baked_maps.rs b/crates/ui-egui/tests/new_project_baked_maps.rs new file mode 100644 index 00000000..a2c95e98 --- /dev/null +++ b/crates/ui-egui/tests/new_project_baked_maps.rs @@ -0,0 +1,80 @@ +//! New project ▸ Import baked maps: added files are listed, Clear empties the list, Create imports them + +use std::path::PathBuf; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakedMap, NormalFormat}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::new_project_advanced::add_baked_map_files; + +fn harness() -> 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)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.windows.new_project = true; + h.state_mut().ui.new_project.resolution = 256; + h.run_steps(3); + h.get_by_label("Advanced settings").click(); + h.run_steps(3); + h.get_by_label("Import baked maps").click(); + h.run_steps(3); + h +} + +/// 4×4 PNGs named `files` in a fresh folder, as their full paths +fn bake_files(test: &str, files: &[&str]) -> Vec { + let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + files + .iter() + .map(|file| { + let path: PathBuf = dir.join(file); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 255, 255])).save(&path).unwrap(); + path.display().to_string() + }) + .collect() +} + +#[test] +fn added_files_are_listed_once_and_clear_empties_the_list() { + let mut h = harness(); + let paths = bake_files("list", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + + add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.run_steps(3); + + assert_eq!(h.state().ui.new_project.baked_maps.len(), 3, "each file once"); + for file in ["Ball_normal.png", "Base_ao.png", "Ball_notes.png"] { + h.get_by_label(file); + } + + h.get_by_label("Clear").click(); + h.run_steps(3); + assert!(h.state().ui.new_project.baked_maps.is_empty()); + assert!(h.query_by_label("Ball_normal.png").is_none()); +} + +#[test] +fn create_imports_the_listed_maps_in_the_chosen_normal_format() { + let mut h = harness(); + let paths = bake_files("create", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); + h.run_steps(3); + + h.get_by_label("Create").click(); + h.run_steps(3); + + let state = h.state(); + assert!(!state.ui.windows.new_project, "the dialog closes"); + let project = &state.session.doc.project; + assert_eq!(project.normal_format, NormalFormat::DirectX); + let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)); + assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion)); + assert_eq!(state.session.doc.resources.len(), 2, "the file naming no map is not imported"); + let toast = &state.toasts.last().unwrap().text; + assert!(toast.contains("Imported 2 baked maps") && toast.contains("Ball_notes.png"), "{toast}"); + assert!(state.ui.new_project.baked_maps.is_empty(), "the next new project starts with no files"); + assert_eq!(state.session.undo_label(), Some("Import baked maps")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 78707aa1..734036ca 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -170,7 +170,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); many baked map files at once, matched to sets and maps by file name: `textureSet.meshMap.import {files: [{path, map?}]}` | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material, a MaterialCraft `.mcmat` material or a `.mcraft` package above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root |