Match UV tiles per file, skip empty imports, review cleanups

- Each tiled file is keyed by its own tile number and its image passed to
  use_images, so tiles named differently or renamed on import still match
- Files of a tiled set without one of its tiles, and maps missing a tile, go
  to unmatched instead of failing the import
- Nothing to import leaves no undo step
- The map is read from the file name after the set name
- Toast counts maps; a failed import keeps the file list
- Cap the bytes one import reads; whole-method cleanup of set, use_images,
  tile_images and new_project
This commit is contained in:
Rebornim committed 2026-11-07 09:14:41 +00:00
1 parent ffe8587e54
commit 6eed52435d
17 files changed
+258 -150

No files matched your search

+51 -28
View File
@@ -38,58 +38,81 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
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 resolution = s.edit("Use image as mesh map", |s| use_image(s, CMD, ts, map, name))?;
let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
let texture_set = s.doc.project.texture_set(ts)?;
let images = match texture_set.tile_grid() {
Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?,
None => BTreeMap::from([(FIRST_TILE, image)]),
};
let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?;
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<u32> {
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, cmd, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?;
/// The tile number a set without UV tiles keys its one image by
pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start();
// 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))),
None => {
let (width, height) = set.bake.common.output_size();
(width.saturating_mul(cols), height.saturating_mul(rows))
}
};
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")));
/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width
pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap<u32, Arc<ImageRes>>) -> Result<u32> {
let texture_set = s.doc.project.texture_set(ts)?;
let grid = texture_set.tile_grid();
if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
return Err(bad(cmd, format!("no image for UV tile {tile}")));
}
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)),
// Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile)
let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows));
let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) {
Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))),
None => {
let (width, height) = texture_set.bake.common.output_size();
(width.saturating_mul(columns), height.saturating_mul(rows))
}
};
let empty = width == 0 || height == 0;
let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS;
let too_wide = grid.is_none() && width > MAX_RESOLUTION;
if empty || too_many_texels || too_wide {
return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty")));
}
let flip_green = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
let data = match (grid, images.values().next()) {
(_, None) => return Err(bad(cmd, "no image to use")),
(None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)),
// 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| {
(Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |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()))
udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
}),
};
let entry = s.doc.baked.entry(ts).or_default();
entry.resolution = res;
entry.resolution = width;
entry.maps.insert(map, Arc::new(data));
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
Ok(res)
Ok(width)
}
/// 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<BTreeMap<u32, Arc<ImageRes>>> {
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")))?;
let tile_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")))?;
let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default());
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}")))
.map(|&tile| {
let tile_name = format!("{before_tile}{tile}{after_tile}");
images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}")))
})
.collect()
}
/// The UV tile number in a file name (`Body_ao.1002.png` → 1002)
pub(crate) fn tile_number(file_name: &str) -> Option<u32> {
udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok())
}
/// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts.
fn udim_in(name: &str) -> Option<usize> {
let b = name.as_bytes();
+39 -33
View File
@@ -5,13 +5,14 @@ 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] = [
const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[
("world", &["normal", "normals"], BakedMap::WorldNormal),
("bent", &["normal", "normals"], BakedMap::BentNormal),
("ambient", &["occlusion"], BakedMap::AmbientOcclusion),
];
const ONE_WORD_NAMES: [(&str, BakedMap); 20] = [
/// Mesh maps named by one word, including the two-word names written as one
const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[
("worldnormal", BakedMap::WorldNormal),
("worldnormals", BakedMap::WorldNormal),
("bentnormal", BakedMap::BentNormal),
@@ -38,29 +39,33 @@ 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 file name without its folder and extension
fn lowercase_stem(path: &str) -> String {
Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase()
}
/// The lowercase words of a file name, without UV tile numbers (`Body_AO.1001` → body, ao)
fn words(path: &str) -> Vec<String> {
stem(path)
.split(is_separator)
.filter(|w| !w.is_empty() && !w.parse::<u32>().is_ok_and(|n| w.len() == 4 && UDIM_RANGE.contains(&n)))
.map(str::to_lowercase)
.collect()
/// What follows `set_name` at the start of a lowercase stem, when a separator follows it
fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> {
if set_name.is_empty() {
return None;
}
stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator))
}
/// 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<BakedMap> {
let words = words(path);
let has = |word: &str| words.iter().any(|w| w == word);
/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins
pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option<BakedMap> {
let stem = lowercase_stem(path);
let rest = after_set_name(&stem, set_name).unwrap_or(&stem);
let is_tile_number = |word: &str| word.len() == 4 && word.parse::<u32>().is_ok_and(|number| UDIM_RANGE.contains(&number));
let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect();
let has = |name: &str| words.contains(&name);
TWO_WORD_NAMES
.iter()
.find(|(first, seconds, _)| has(first) && seconds.iter().any(|s| has(s)))
.find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second)))
.map(|(_, _, map)| *map)
.or_else(|| words.iter().rev().find_map(|w| ONE_WORD_NAMES.iter().find(|(name, _)| name == w).map(|(_, map)| *map)))
.or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).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)
@@ -69,14 +74,8 @@ pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Opti
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)
let stem = lowercase_stem(path);
set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts)
}
#[cfg(test)]
@@ -109,23 +108,30 @@ mod tests {
("Body_alpha.png", BakedMap::Opacity),
];
for (file, map) in cases {
assert_eq!(baked_map_from_file_name(file), Some(map), "{file}");
assert_eq!(baked_map_from_file_name(file, "Body"), 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!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion));
assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), 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);
assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None);
assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None);
assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None);
assert_eq!(baked_map_from_file_name("", "Body"), None);
}
#[test]
fn the_set_name_is_not_read_as_a_map() {
assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal));
assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None);
assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion));
}
#[test]
+56 -27
View File
@@ -1,20 +1,24 @@
//! 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 std::path::Path;
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_cmds::{FIRST_TILE, tile_number, use_images};
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;
/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles
const MAX_FILES: usize = 512;
/// Most bytes one import reads, since every file stays decoded in memory until the import ends
const MAX_TOTAL_BYTES: u64 = 2 << 30;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
@@ -22,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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",
"{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, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); desktop only",
always,
import
)]
@@ -34,39 +38,52 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(CMD, format!("at most {MAX_FILES} files at once")));
}
let set_names: Vec<String> = 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 set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect();
let mut slots: BTreeMap<(usize, BakedMap), BTreeMap<u32, &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),
let given_map = strp(file, "map").map(|id| BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))).transpose()?;
match slot_of(s, &set_names, path, given_map) {
Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => {
slots.entry(slot).or_default().insert(tile, path);
}
_ => unmatched.push(path),
}
}
// A UV-tiled map needs a file for every tile of its set
slots.retain(|(ts, _), tiles| {
let complete =
s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile)));
if !complete {
unmatched.extend(tiles.values());
}
complete
});
if slots.is_empty() {
return Ok(json!({ "assigned": [], "unmatched": unmatched }));
}
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)?;
}
let mut total_bytes = 0;
for ((ts, map), tiles) in &slots {
let mut images = BTreeMap::new();
for (tile, path) in tiles {
let bytes = read_image_file(CMD, path)?;
total_bytes += bytes.len() as u64;
if total_bytes > MAX_TOTAL_BYTES {
return Err(bad(CMD, format!("the files are larger than {} GB together", MAX_TOTAL_BYTES >> 30)));
}
assigned.extend(taken.iter().map(|path| json!({"path": path, "ts": ts, "map": map.id()})));
unmatched.extend(extra);
let name = s.add_image_resource(path, bytes)?;
if let Some(image) = s.images.get(&name) {
images.insert(*tile, image.clone());
}
assigned.push(json!({"path": path, "ts": ts, "map": map.id()}));
}
use_images(s, CMD, *ts, *map, &images)?;
}
Ok(assigned)
});
@@ -77,3 +94,15 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "assigned": result?, "unmatched": unmatched }))
}
/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles)
fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option<BakedMap>) -> Option<((usize, BakedMap), u32)> {
let ts = texture_set_from_file_name(path, set_names)?;
let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?;
let texture_set = s.doc.project.texture_sets.get(ts)?;
let tile = match texture_set.tile_grid() {
Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?,
None => FIRST_TILE,
};
Some(((ts, map), tile))
}
+1 -1
View File
@@ -36,7 +36,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
}
impl Session {
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name.
/// 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<u8>) -> Result<String> {
self.edit("Import resource", |s| s.add_image_resource(file_name, bytes))
}
+52 -16
View File
@@ -17,7 +17,7 @@ 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;
let gray = u8::try_from(20 + 20 * index).unwrap_or(u8::MAX);
image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap();
}
dir
@@ -41,13 +41,13 @@ fn file_names(list: &Value) -> Vec<String> {
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())
.map(|entry| entry.as_str().unwrap_or_else(|| entry["path"].as_str().unwrap()))
.map(|path| path.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)
s.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map)
}
#[test]
@@ -57,21 +57,21 @@ fn files_go_to_the_set_and_map_their_names_name() {
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 result = import(&mut s, &dir, &files.map(|file| (file, 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!(assigned.as_array().unwrap().iter().any(|entry| entry["ts"] == ts && entry["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");
assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()), "undo removes every imported map");
assert!(s.doc.resources.is_empty(), "undo removes the imported image resources");
std::fs::remove_dir_all(dir).ok();
}
@@ -103,8 +103,8 @@ fn a_second_file_for_one_slot_is_left_out() {
}
#[test]
fn a_failed_file_imports_nothing() {
let dir = bake_folder("failed", &["Ball_ao.png"]);
fn an_undecodable_file_imports_nothing() {
let dir = bake_folder("undecodable", &["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);
@@ -113,18 +113,24 @@ fn a_failed_file_imports_nothing() {
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.baked.values().all(|baked| baked.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();
/// The UV tile plane: one texture set "Plane" on tiles 1001 and 1002
fn tiled_session() -> Session {
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)]);
#[test]
fn a_uv_tiled_set_takes_one_file_per_tile_however_each_is_written() {
let files = ["Plane_ao.1001.png", "plane-AO-1002.png"];
let dir = bake_folder("tiles", &files);
let mut s = tiled_session();
let result = import(&mut s, &dir, &files.map(|file| (file, None)));
assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}");
let baked = &s.doc.baked[&0];
@@ -134,3 +140,33 @@ fn a_uv_tiled_set_takes_one_file_per_tile() {
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();
}
#[test]
fn tiled_files_without_their_tiles_are_left_out_alone() {
let files = ["Plane_ao.1001.png", "Plane_ao.1002.png", "Plane_normal.png", "Plane_curvature.1001.png", "Plane_id.1005.png"];
let dir = bake_folder("partial-tiles", &files);
let mut s = tiled_session();
let result = import(&mut s, &dir, &files.map(|file| (file, None)));
assert_eq!(file_names(&result["assigned"]), ["Plane_ao.1001.png", "Plane_ao.1002.png"]);
assert_eq!(file_names(&result["unmatched"]), ["Plane_normal.png", "Plane_id.1005.png", "Plane_curvature.1001.png"]);
assert!(has_map(&s, 0, BakedMap::AmbientOcclusion));
assert_eq!(s.doc.resources.len(), 2, "left-out files are not imported");
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn nothing_matched_makes_no_undo_step() {
let dir = bake_folder("none", &["Head_ao.png", "Ball_diffuse.png"]);
let mut s = session();
let label_before = s.undo_label().map(str::to_string);
let result = import(&mut s, &dir, &[("Head_ao.png", None), ("Ball_diffuse.png", None)]);
assert_eq!(file_names(&result["assigned"]), Vec::<String>::new());
assert_eq!(file_names(&result["unmatched"]).len(), 2);
assert_eq!(s.undo_label().map(str::to_string), label_before);
assert!(!s.modified);
std::fs::remove_dir_all(dir).ok();
}
+1 -1
View File
@@ -1039,6 +1039,6 @@ pub const TABLE: &[(&str, &str)] = &[
("Import baked maps", "استيراد خرائط مخبوزة"),
("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"),
("Add...", "إضافة..."),
("Imported {count} baked maps", "تم استيراد {count} من الخرائط المخبوزة"),
("Baked maps imported: {count}", "الخرائط المخبوزة المستوردة: {count}"),
("Not imported: {files}", "لم يتم استيرادها: {files}"),
];
+1 -1
View File
@@ -1082,6 +1082,6 @@ pub const TABLE: &[(&str, &str)] = &[
("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"),
("Baked maps imported: {count}", "Gebackene Maps importiert: {count}"),
("Not imported: {files}", "Nicht importiert: {files}"),
];
+1 -1
View File
@@ -1067,6 +1067,6 @@ pub const TABLE: &[(&str, &str)] = &[
("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"),
("Baked maps imported: {count}", "Mapas horneados importados: {count}"),
("Not imported: {files}", "Sin importar: {files}"),
];
+1 -1
View File
@@ -1091,6 +1091,6 @@ pub const TABLE: &[(&str, &str)] = &[
("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"),
("Baked maps imported: {count}", "Cartes précalculées importées : {count}"),
("Not imported: {files}", "Non importés : {files}"),
];
+1 -1
View File
@@ -1076,6 +1076,6 @@ pub const TABLE: &[(&str, &str)] = &[
("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"),
("Baked maps imported: {count}", "Mappe bake importate: {count}"),
("Not imported: {files}", "Non importati: {files}"),
];
+1 -1
View File
@@ -1061,6 +1061,6 @@ pub const TABLE: &[(&str, &str)] = &[
("Import baked maps", "ベイク済みマップを読み込む"),
("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"),
("Add...", "追加..."),
("Imported {count} baked maps", "ベイク済みマップを {count} 個読み込みました"),
("Baked maps imported: {count}", "読み込んだベイク済みマップ: {count}"),
("Not imported: {files}", "読み込まれなかったファイル: {files}"),
];
+1 -1
View File
@@ -1049,6 +1049,6 @@ pub const TABLE: &[(&str, &str)] = &[
("Import baked maps", "베이크된 맵 가져오기"),
("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"),
("Add...", "추가..."),
("Imported {count} baked maps", "베이크된 맵 {count}개를 가져왔습니다"),
("Baked maps imported: {count}", "가져온 베이크된 맵: {count}"),
("Not imported: {files}", "가져오지 않음: {files}"),
];
+1 -1
View File
@@ -1064,6 +1064,6 @@ pub const TABLE: &[(&str, &str)] = &[
("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"),
("Baked maps imported: {count}", "Mapas com bake importados: {count}"),
("Not imported: {files}", "Não importados: {files}"),
];
+1 -1
View File
@@ -1007,6 +1007,6 @@ pub const TABLE: &[(&str, &str)] = &[
("Import baked maps", "导入已烘焙贴图"),
("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"),
("Add...", "添加..."),
("Imported {count} baked maps", "已导入 {count} 张烘焙贴图"),
("Baked maps imported: {count}", "已导入的烘焙贴图:{count}"),
("Not imported: {files}", "未导入:{files}"),
];
+14 -6
View File
@@ -1,5 +1,7 @@
//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation
use std::collections::BTreeSet;
use egui::{RichText, Sense, Ui, vec2};
use serde_json::{Value, json};
use texturecraft_engine::core::NormalFormat;
@@ -19,7 +21,7 @@ const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolut
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;
pub(crate) const COMBO_WIDTH: f32 = 200.0;
/// Width of the Add... and Clear buttons
const FILE_BUTTON_WIDTH: f32 = 96.0;
@@ -64,8 +66,12 @@ pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut 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 template_format = builtin_templates()
.into_iter()
.chain(user_templates)
.find(|template| template.name == new_project.template)
.map(|template| template.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| {
@@ -114,7 +120,7 @@ pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec<String>) {
}
}
/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome
/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome; a failed import keeps the list
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)) {
@@ -129,14 +135,16 @@ pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewPro
return;
};
let assigned = result["assigned"].as_array().map_or(0, Vec::len);
let assigned = result["assigned"].as_array().into_iter().flatten();
let maps: BTreeSet<(u64, &str)> = assigned.filter_map(|entry| Some((entry["ts"].as_u64()?, entry["map"].as_str()?))).collect();
let not_imported: Vec<String> = 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)]);
let mut text = trf("Baked maps imported: {count}", &[("count", &maps.len())]);
if !not_imported.is_empty() {
text.push('\n');
text.push_str(&trf("Not imported: {files}", &[("files", &not_imported.join(", "))]));
}
app.toast(text, !not_imported.is_empty());
app.ui.new_project.baked_maps.clear();
}
fn file_name(path: &str) -> String {
+30 -26
View File
@@ -11,6 +11,7 @@ use texturecraft_render::ibl::ENVIRONMENTS;
use crate::TextureCraftApp;
use crate::i18n::LANGUAGES;
use crate::i18n::{tr, trf};
use crate::new_project_advanced::COMBO_WIDTH;
use crate::state::Mode;
use crate::theme::{Accent, Brightness, Tokens, caption};
use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit};
@@ -388,6 +389,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) {
if !app.ui.windows.new_project {
return;
}
let mut open = true;
let mut create = false;
dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| {
@@ -399,13 +401,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) {
BUILTINS
.iter()
.find(|(id, _)| *id == app.ui.new_project.mesh)
.map(|(_, l)| trf("Built-in: {mesh}", &[("mesh", &tr(l))]))
.map(|(_, builtin_label)| trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]))
.unwrap_or_default()
});
egui::ComboBox::from_id_salt("np_mesh").width(200.0).selected_text(label).show_ui(ui, |ui| {
for (id, l) in BUILTINS {
egui::ComboBox::from_id_salt("np_mesh").width(COMBO_WIDTH).selected_text(label).show_ui(ui, |ui| {
for (id, builtin_label) in BUILTINS {
if ui
.selectable_label(app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), trf("Built-in: {mesh}", &[("mesh", &tr(l))]))
.selectable_label(
app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(),
trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]),
)
.clicked()
{
app.ui.new_project.mesh = id.to_string();
@@ -415,21 +420,21 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) {
});
if file_dialogs_available()
&& ui.button(tr("Select...")).clicked()
&& let Some(p) = pick_mesh_file()
&& let Some(path) = pick_mesh_file()
{
app.ui.new_project.file = Some(p);
app.ui.new_project.file = Some(path);
}
});
ui.end_row();
ui.label(tr("Project template"));
let np = &mut app.ui.new_project;
egui::ComboBox::from_id_salt("np_template").width(200.0).selected_text(np.template.clone()).show_ui(ui, |ui| {
let user = app.session.templates.list.iter();
for t in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user) {
if ui.selectable_label(t.name == np.template, &t.name).clicked() {
np.template = t.name.clone();
np.resolution = t.resolution;
np.normal_format = None;
let new_project = &mut app.ui.new_project;
egui::ComboBox::from_id_salt("np_template").width(COMBO_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| {
let user_templates = app.session.templates.list.iter();
for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) {
if ui.selectable_label(template.name == new_project.template, &template.name).clicked() {
new_project.template = template.name.clone();
new_project.resolution = template.resolution;
new_project.normal_format = None;
}
}
});
@@ -448,20 +453,20 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) {
ui.end_row();
ui.label(tr("Document resolution"));
egui::ComboBox::from_id_salt("np_res").selected_text(format!("{0} x {0}", app.ui.new_project.resolution)).show_ui(ui, |ui| {
for r in [512u32, 1024, 2048, 4096] {
ui.selectable_value(&mut app.ui.new_project.resolution, r, format!("{r} x {r}"));
for size in [512u32, 1024, 2048, 4096] {
ui.selectable_value(&mut app.ui.new_project.resolution, size, format!("{size} x {size}"));
}
});
ui.end_row();
ui.label(tr("UV tiles (UDIM)"));
let tiles_label = |m: Option<bool>| match m {
let tiles_label = |tiles: Option<bool>| match tiles {
None => tr("Automatic (from the mesh UVs)"),
Some(true) => tr("On"),
Some(false) => tr("Off"),
};
egui::ComboBox::from_id_salt("np_tiles").selected_text(tiles_label(app.ui.new_project.uv_tiles)).show_ui(ui, |ui| {
for m in [None, Some(true), Some(false)] {
ui.selectable_value(&mut app.ui.new_project.uv_tiles, m, tiles_label(m));
for tiles in [None, Some(true), Some(false)] {
ui.selectable_value(&mut app.ui.new_project.uv_tiles, tiles, tiles_label(tiles));
}
});
ui.end_row();
@@ -484,17 +489,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) {
});
});
if create {
let np = app.ui.new_project.clone();
let (cmd, mesh) = match &np.file {
let new_project = app.ui.new_project.clone();
let (command, mesh) = match &new_project.file {
Some(path) => ("file.new", path.clone()),
None => ("project.new", np.mesh.clone()),
None => ("project.new", new_project.mesh.clone()),
};
let r = app.run(cmd, json!({"mesh": mesh, "resolution": np.resolution, "name": np.name, "uvTiles": np.uv_tiles, "template": np.template})).map(|_| ());
if r.is_some() {
let params = json!({"mesh": mesh, "resolution": new_project.resolution, "name": new_project.name, "uvTiles": new_project.uv_tiles, "template": new_project.template});
if app.run(command, params).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);
crate::new_project_advanced::apply_after_create(app, &new_project);
}
}
if !open {
@@ -21,7 +21,7 @@ fn harness() -> Harness<'static, TextureCraftApp> {
h
}
/// 4×4 PNGs named `files` in a fresh folder, as their full paths
/// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read
fn bake_files(test: &str, files: &[&str]) -> Vec<String> {
let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
@@ -29,7 +29,7 @@ fn bake_files(test: &str, files: &[&str]) -> Vec<String> {
.iter()
.map(|file| {
let path: PathBuf = dir.join(file);
image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 255, 255])).save(&path).unwrap();
image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).save(&path).unwrap();
path.display().to_string()
})
.collect()
@@ -70,11 +70,13 @@ fn create_imports_the_listed_maps_in_the_chosen_normal_format() {
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));
let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map));
assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion));
let normal_green = state.session.doc.baked[&0].maps[&BakedMap::Normal][1];
assert!(normal_green > 0.75, "the normal map is read as DirectX (green flipped): {normal_green}");
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!(toast.contains("Baked maps imported: 2") && 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"));
}