From 2df185b2a6a427ea91470cf6e1ab56a104c2b48e Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:46 +0400 Subject: [PATCH] PBR folder import: dialog, menu item, folder drop, library copy, translations, docs File > Import PBR texture folder..., drop a folder, zip or several map files, choose between candidate files, normal convention and projection, optionally keep the material in the library. Documented in docs/control-protocol.md. --- ROADMAP.md | 2 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/pbr_cmds.rs | 50 +++---- crates/formats/src/pbr_maps.rs | 28 +++- crates/ui-egui/src/i18n/ar.rs | 15 +++ crates/ui-egui/src/i18n/de.rs | 15 +++ crates/ui-egui/src/i18n/es.rs | 15 +++ crates/ui-egui/src/i18n/fr.rs | 15 +++ crates/ui-egui/src/i18n/it.rs | 15 +++ crates/ui-egui/src/i18n/ja.rs | 15 +++ crates/ui-egui/src/i18n/ko.rs | 15 +++ crates/ui-egui/src/i18n/pt_br.rs | 15 +++ crates/ui-egui/src/i18n/zh_hans.rs | 15 +++ crates/ui-egui/src/lib.rs | 14 +- crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/pbr_import.rs | 202 +++++++++++++++++++++++++++++ crates/ui-egui/src/windows.rs | 7 +- docs/control-protocol.md | 51 ++++++++ docs/parity.md | 3 +- 19 files changed, 459 insertions(+), 36 deletions(-) create mode 100644 crates/ui-egui/src/pbr_import.rs diff --git a/ROADMAP.md b/ROADMAP.md index 654f5c35..d105bb1c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -11,7 +11,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Area | Weight | Done | What works | Main gaps | |---|---:|---:|---|---| -| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | +| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), **PBR folder import** (`file.importPbrFolder`: a folder, zip or dropped files of albedo / roughness / metallic / normal (OpenGL or DirectX) / height / occlusion / emissive / opacity / packed ORM maps become one fill layer, with a dialog and an optional library copy), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — | | Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ab954994..b10e9f21 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -28,10 +28,10 @@ pub mod mask_cmds; pub mod material_lib; pub mod materials; pub mod materialx_cmds; -pub mod pbr_cmds; pub mod meshmap_cmds; pub mod painting; pub mod path_tool; +pub mod pbr_cmds; // Mesh reimport reads files: native only. #[cfg(not(target_arch = "wasm32"))] mod preserve; diff --git a/crates/engine/src/pbr_cmds.rs b/crates/engine/src/pbr_cmds.rs index 19b62986..22fbf460 100644 --- a/crates/engine/src/pbr_cmds.rs +++ b/crates/engine/src/pbr_cmds.rs @@ -59,7 +59,7 @@ pub type FileList = Vec<(String, u64)>; pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; /// How to import. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub struct PbrOptions { pub name: Option, /// Forces every normal map's convention; `None` reads it from the file name (default OpenGL). @@ -69,24 +69,19 @@ pub struct PbrOptions { pub choose: BTreeMap, } -impl Default for PbrOptions { - fn default() -> Self { - PbrOptions { name: None, normal_format: None, projection: Projection::default(), choose: BTreeMap::new() } - } -} - /// The detection for a file list with the caller's choices applied. fn detect_with(files: &FileList, choose: &BTreeMap) -> Result { let mut set = pbr_maps::detect(files.iter().map(|(n, s)| (n.as_str(), *s))); for (kind, file) in choose { let list = set.candidates.get(kind).ok_or_else(|| EngineError::Other(format!("choose: no file names the map {}", kind.id())))?; - let pick = list.iter().find(|c| c.name == *file).ok_or_else(|| EngineError::Other(format!("choose: {file} is not a candidate for {}", kind.id())))?.clone(); + let pick = + list.iter().find(|c| c.name == *file).ok_or_else(|| EngineError::Other(format!("choose: {file} is not a candidate for {}", kind.id())))?.clone(); // The previously chosen file becomes an ignored one, the picked one stops being ignored. - if let Some(old) = set.chosen.insert(*kind, pick.clone()) { - if old.name != pick.name { - set.ignored.retain(|(n, _)| *n != pick.name); - set.ignored.push((old.name, format!("another file is used for {}", kind.id()))); - } + if let Some(old) = set.chosen.insert(*kind, pick.clone()) + && old.name != pick.name + { + set.ignored.retain(|(n, _)| *n != pick.name); + set.ignored.push((old.name, format!("another file is used for {}", kind.id()))); } } Ok(set) @@ -116,6 +111,9 @@ fn report(set: &PbrSet, forced: Option) -> Value { }) } +/// A file's bytes and its decoded image. +type Loaded = (Arc>, texturecraft_formats::DecodedImage); + /// How a channel's image is made from the file chosen for a map. #[derive(Clone, Copy, PartialEq)] enum Take { @@ -160,7 +158,9 @@ impl Session { } // Separate files win; a packed image fills what they leave open (R = occlusion, G = roughness, B = metallic). let orm = has(MapKind::PackedOrm); - for (channel, kind, index) in [(Channel::AmbientOcclusion, MapKind::AmbientOcclusion, 0), (Channel::Roughness, MapKind::Roughness, 1), (Channel::Metallic, MapKind::Metallic, 2)] { + for (channel, kind, index) in + [(Channel::AmbientOcclusion, MapKind::AmbientOcclusion, 0), (Channel::Roughness, MapKind::Roughness, 1), (Channel::Metallic, MapKind::Metallic, 2)] + { if has(kind) { plan.push((channel, kind, Take::Whole)); } else if channel == Channel::Roughness && has(MapKind::Glossiness) { @@ -182,7 +182,7 @@ impl Session { let mut channels: Vec = Vec::new(); let mut total_texels = 0u64; // Decoded source files by name (a packed image feeds three channels). - let mut sources: BTreeMap>, texturecraft_formats::DecodedImage)>> = BTreeMap::new(); + let mut sources: BTreeMap> = BTreeMap::new(); // Resource per (file, how) so a file used twice is stored once. let mut made: BTreeMap<(String, usize), String> = BTreeMap::new(); @@ -334,12 +334,7 @@ fn options(cmd: &str, p: &Value) -> Result { choose.insert(kind, file.to_string()); } } - Ok(PbrOptions { - name: strp(p, "name").map(str::to_string), - normal_format, - projection: crate::layer_cmds::projection_from(p, cmd, None)?, - choose, - }) + Ok(PbrOptions { name: strp(p, "name").map(str::to_string), normal_format, projection: crate::layer_cmds::projection_from(p, cmd, None)?, choose }) } /// Pick the one group of files that holds a material: the files at the root if they hold maps, @@ -359,7 +354,10 @@ fn pick_group(cmd: &str, files: &FileList) -> Result { [one] => Ok(format!("{one}/")), many => { let shown: Vec<&str> = many.iter().take(8).map(|d| d.as_str()).collect(); - Err(bad(cmd, format!("{} folders hold PBR maps ({}{}): import one of them", many.len(), shown.join(", "), if many.len() > 8 { ", ..." } else { "" }))) + Err(bad( + cmd, + format!("{} folders hold PBR maps ({}{}): import one of them", many.len(), shown.join(", "), if many.len() > 8 { ", ..." } else { "" }), + )) } } } @@ -440,7 +438,8 @@ mod native { walk(&root, &root, 0, &mut files); let group = pick_group(cmd, &files)?; let files: FileList = files.into_iter().filter(|(n, _)| n.strip_prefix(group.as_str()).is_some_and(|rest| !rest.contains('/'))).collect(); - let name = if group.is_empty() { stem(path) } else { stem(group.trim_end_matches('/')) }.or_else(|| root.file_name().map(|n| n.to_string_lossy().into_owned())); + let name = if group.is_empty() { stem(path) } else { stem(group.trim_end_matches('/')) } + .or_else(|| root.file_name().map(|n| n.to_string_lossy().into_owned())); let root = if group.is_empty() { root } else { root.join(group.trim_end_matches('/')) }; let files = files.into_iter().map(|(n, s)| (n.rsplit('/').next().unwrap_or(&n).to_string(), s)).collect(); return Ok(Found { source: Origin::Folder { root }, files, name }); @@ -508,7 +507,10 @@ fn scan(s: &mut Session, p: &Value) -> Result { let mut reply = report(&set, opts.normal_format); if let Some(o) = reply.as_object_mut() { o.insert("name".into(), json!(opts.name.or(found.name))); - o.insert("channelsAvailable".into(), json!(s.doc.project.texture_set(s.ts()).map(|t| t.channel_list()).unwrap_or_default().iter().map(|c| c.id()).collect::>())); + o.insert( + "channelsAvailable".into(), + json!(s.doc.project.texture_set(s.ts()).map(|t| t.channel_list()).unwrap_or_default().iter().map(|c| c.id()).collect::>()), + ); } Ok(reply) } diff --git a/crates/formats/src/pbr_maps.rs b/crates/formats/src/pbr_maps.rs index 50062244..356530fe 100644 --- a/crates/formats/src/pbr_maps.rs +++ b/crates/formats/src/pbr_maps.rs @@ -154,7 +154,8 @@ fn tokens(stem: &str) -> Vec { if let Some(p) = prev { let next_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase()); // aB -> a|B; ABc -> A|Bc; a1 -> a|1; 1a -> 1|a. - let split = (p.is_lowercase() && c.is_uppercase()) || (p.is_uppercase() && c.is_uppercase() && next_lower) || (p.is_alphabetic() != c.is_alphabetic()); + let split = + (p.is_lowercase() && c.is_uppercase()) || (p.is_uppercase() && c.is_uppercase() && next_lower) || (p.is_alphabetic() != c.is_alphabetic()); if split && !cur.is_empty() { out.push(std::mem::take(&mut cur)); } @@ -204,7 +205,9 @@ fn normal_format_of(t: &str) -> Option { fn word(t: &str) -> Option<(MapKind, u8)> { use MapKind::*; Some(match t { - "basecolor" | "basecolour" | "albedo" | "diffuse" | "diff" | "dif" | "col" | "color" | "colour" | "bc" | "basemap" | "maintex" | "alb" => (BaseColor, 3), + "basecolor" | "basecolour" | "albedo" | "diffuse" | "diff" | "dif" | "col" | "color" | "colour" | "bc" | "basemap" | "maintex" | "alb" => { + (BaseColor, 3) + } "roughness" | "rough" | "rgh" | "rou" => (Roughness, 3), "gloss" | "glossiness" | "glossy" | "smoothness" | "smooth" => (Glossiness, 3), "metallic" | "metalness" | "metal" | "mtl" | "met" => (Metallic, 3), @@ -215,9 +218,8 @@ fn word(t: &str) -> Option<(MapKind, u8)> { "emissive" | "emission" | "emit" | "emis" | "glow" | "emissivecolor" | "emissionmap" | "illum" => (Emissive, 3), "opacity" | "alpha" | "opac" | "transparency" | "cutout" | "coverage" => (Opacity, 3), "orm" | "arm" | "aorm" => (PackedOrm, 4), - "cavity" | "curvature" | "specular" | "spec" | "translucency" | "thickness" | "scatter" | "sss" | "fuzz" | "sheen" | "ior" | "mask" | "flow" | "reflection" => { - (Unused, 1) - } + "cavity" | "curvature" | "specular" | "spec" | "translucency" | "thickness" | "scatter" | "sss" | "fuzz" | "sheen" | "ior" | "mask" | "flow" + | "reflection" => (Unused, 1), _ => return None, }) } @@ -278,7 +280,8 @@ pub fn classify(name: &str) -> std::result::Result { let single = words.iter().rev().find(|(i, kind, _)| { // A lone `n` only names a normal map as the final meaningful token. let lone_n = toks.get(*i).is_some_and(|t| t == "n"); - !lone_n || (*kind == MapKind::Normal && toks.iter().skip(i + 1).all(|t| resolution_of(t).is_some() || normal_format_of(t).is_some() || t.ends_with("bit"))) + !lone_n + || (*kind == MapKind::Normal && toks.iter().skip(i + 1).all(|t| resolution_of(t).is_some() || normal_format_of(t).is_some() || t.ends_with("bit"))) }); match (pair, single) { (Some((pi, kind)), Some((si, _, _))) if pi >= *si => done(kind, 3), @@ -488,7 +491,18 @@ mod tests { fn empty_and_hostile_names_do_not_panic() { assert!(detect([]).is_empty()); let long = "a".repeat(100_000); - let weird = ["\u{0}.png", "....png", "ÄÖÜ_Ålbedo.png", "🙂.png", "_.png", "-.exr", long.as_str(), "x/../../y_albedo.png", "C:\\a\\b_albedo.png", "99999999999999_albedo.png"]; + let weird = [ + "\u{0}.png", + "....png", + "ÄÖÜ_Ålbedo.png", + "🙂.png", + "_.png", + "-.exr", + long.as_str(), + "x/../../y_albedo.png", + "C:\\a\\b_albedo.png", + "99999999999999_albedo.png", + ]; let set = detect(weird.iter().map(|n| (*n, 0))); assert!(set.chosen.contains_key(&BaseColor)); } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..aef46c3d 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1041,4 +1041,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "الحد الأقصى للقيمة"), ("Value Bounds Min", "الحد الأدنى للقيمة"), ("Vertex Color", "لون الرأس"), + ("Add to the material library", "إضافة إلى مكتبة المواد"), + ("Added {name} to the library", "تمت إضافة {name} إلى المكتبة"), + ("Automatic", "تلقائي"), + ("Detected maps", "الخرائط المكتشفة"), + ("DirectX", "DirectX"), + ("Import", "استيراد"), + ("Import PBR texture folder...", "استيراد مجلد خامات PBR..."), + ("Import PBR textures", "استيراد خامات PBR"), + ("Layer name", "اسم الطبقة"), + ("Nothing recognised in this folder", "لم يتم التعرف على شيء في هذا المجلد"), + ("OpenGL", "OpenGL"), + ("Packed (occlusion, roughness, metallic)", "مدمجة (الإطباق، الخشونة، المعدنية)"), + ("Triplanar", "ثلاثي المستويات"), + ("UV", "UV"), + ("{n} files ignored", "تم تجاهل {n} ملفات"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..b2e41ca6 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1090,4 +1090,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Maximaler Grenzwert"), ("Value Bounds Min", "Minimaler Grenzwert"), ("Vertex Color", "Scheitelpunktfarbe"), + ("Add to the material library", "Zur Materialbibliothek hinzufügen"), + ("Added {name} to the library", "{name} zur Bibliothek hinzugefügt"), + ("Automatic", "Automatisch"), + ("Detected maps", "Erkannte Maps"), + ("DirectX", "DirectX"), + ("Import", "Importieren"), + ("Import PBR texture folder...", "PBR-Texturordner importieren..."), + ("Import PBR textures", "PBR-Texturen importieren"), + ("Layer name", "Ebenenname"), + ("Nothing recognised in this folder", "In diesem Ordner wurde nichts erkannt"), + ("OpenGL", "OpenGL"), + ("Packed (occlusion, roughness, metallic)", "Gepackt (Okklusion, Rauheit, Metallisch)"), + ("Triplanar", "Triplanar"), + ("UV", "UV"), + ("{n} files ignored", "{n} Dateien ignoriert"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..8e7e4f56 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1075,4 +1075,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Límite máximo"), ("Value Bounds Min", "Límite mínimo"), ("Vertex Color", "Color de vértice"), + ("Add to the material library", "Añadir a la biblioteca de materiales"), + ("Added {name} to the library", "{name} añadido a la biblioteca"), + ("Automatic", "Automático"), + ("Detected maps", "Mapas detectados"), + ("DirectX", "DirectX"), + ("Import", "Importar"), + ("Import PBR texture folder...", "Importar carpeta de texturas PBR..."), + ("Import PBR textures", "Importar texturas PBR"), + ("Layer name", "Nombre de la capa"), + ("Nothing recognised in this folder", "No se reconoció nada en esta carpeta"), + ("OpenGL", "OpenGL"), + ("Packed (occlusion, roughness, metallic)", "Empaquetado (oclusión, rugosidad, metálico)"), + ("Triplanar", "Triplanar"), + ("UV", "UV"), + ("{n} files ignored", "{n} archivos ignorados"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..5726b061 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1099,4 +1099,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Borne maximale"), ("Value Bounds Min", "Borne minimale"), ("Vertex Color", "Couleur des sommets"), + ("Add to the material library", "Ajouter à la bibliothèque de matériaux"), + ("Added {name} to the library", "{name} ajouté à la bibliothèque"), + ("Automatic", "Automatique"), + ("Detected maps", "Cartes détectées"), + ("DirectX", "DirectX"), + ("Import", "Importer"), + ("Import PBR texture folder...", "Importer un dossier de textures PBR..."), + ("Import PBR textures", "Importer des textures PBR"), + ("Layer name", "Nom du calque"), + ("Nothing recognised in this folder", "Rien de reconnu dans ce dossier"), + ("OpenGL", "OpenGL"), + ("Packed (occlusion, roughness, metallic)", "Packée (occlusion, rugosité, métallique)"), + ("Triplanar", "Triplanaire"), + ("UV", "UV"), + ("{n} files ignored", "{n} fichiers ignorés"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..9474bc7c 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1084,4 +1084,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite massimo"), ("Value Bounds Min", "Limite minimo"), ("Vertex Color", "Colore dei vertici"), + ("Add to the material library", "Aggiungi alla libreria dei materiali"), + ("Added {name} to the library", "{name} aggiunto alla libreria"), + ("Automatic", "Automatico"), + ("Detected maps", "Mappe rilevate"), + ("DirectX", "DirectX"), + ("Import", "Importa"), + ("Import PBR texture folder...", "Importa cartella di texture PBR..."), + ("Import PBR textures", "Importa texture PBR"), + ("Layer name", "Nome del livello"), + ("Nothing recognised in this folder", "Nulla di riconosciuto in questa cartella"), + ("OpenGL", "OpenGL"), + ("Packed (occlusion, roughness, metallic)", "Impacchettata (occlusione, ruvidità, metallico)"), + ("Triplanar", "Triplanare"), + ("UV", "UV"), + ("{n} files ignored", "{n} file ignorati"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..b96b7519 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1069,4 +1069,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "値の上限"), ("Value Bounds Min", "値の下限"), ("Vertex Color", "頂点カラー"), + ("Add to the material library", "マテリアルライブラリに追加"), + ("Added {name} to the library", "{name} をライブラリに追加しました"), + ("Automatic", "自動"), + ("Detected maps", "検出されたマップ"), + ("DirectX", "DirectX"), + ("Import", "インポート"), + ("Import PBR texture folder...", "PBR テクスチャフォルダをインポート..."), + ("Import PBR textures", "PBR テクスチャをインポート"), + ("Layer name", "レイヤー名"), + ("Nothing recognised in this folder", "このフォルダで認識できるものはありません"), + ("OpenGL", "OpenGL"), + ("Packed (occlusion, roughness, metallic)", "パック (オクルージョン、粗さ、メタリック)"), + ("Triplanar", "トライプラナー"), + ("UV", "UV"), + ("{n} files ignored", "{n} 個のファイルを無視しました"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..cc6c46b0 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1054,4 +1054,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "값 상한"), ("Value Bounds Min", "값 하한"), ("Vertex Color", "정점 색상"), + ("Add to the material library", "머티리얼 라이브러리에 추가"), + ("Added {name} to the library", "{name}을(를) 라이브러리에 추가했습니다"), + ("Automatic", "자동"), + ("Detected maps", "감지된 맵"), + ("DirectX", "DirectX"), + ("Import", "가져오기"), + ("Import PBR texture folder...", "PBR 텍스처 폴더 가져오기..."), + ("Import PBR textures", "PBR 텍스처 가져오기"), + ("Layer name", "레이어 이름"), + ("Nothing recognised in this folder", "이 폴더에서 인식된 항목이 없습니다"), + ("OpenGL", "OpenGL"), + ("Packed (occlusion, roughness, metallic)", "패킹됨 (오클루전, 거칠기, 메탈릭)"), + ("Triplanar", "트라이플래너"), + ("UV", "UV"), + ("{n} files ignored", "파일 {n}개 무시됨"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..c7aa4984 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1072,4 +1072,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite máximo"), ("Value Bounds Min", "Limite mínimo"), ("Vertex Color", "Cor do vértice"), + ("Add to the material library", "Adicionar à biblioteca de materiais"), + ("Added {name} to the library", "{name} adicionado à biblioteca"), + ("Automatic", "Automático"), + ("Detected maps", "Mapas detectados"), + ("DirectX", "DirectX"), + ("Import", "Importar"), + ("Import PBR texture folder...", "Importar pasta de texturas PBR..."), + ("Import PBR textures", "Importar texturas PBR"), + ("Layer name", "Nome da camada"), + ("Nothing recognised in this folder", "Nada reconhecido nesta pasta"), + ("OpenGL", "OpenGL"), + ("Packed (occlusion, roughness, metallic)", "Empacotado (oclusão, rugosidade, metálico)"), + ("Triplanar", "Triplanar"), + ("UV", "UV"), + ("{n} files ignored", "{n} arquivos ignorados"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..54064669 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1000,4 +1000,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "值上限"), ("Value Bounds Min", "值下限"), ("Vertex Color", "顶点颜色"), + ("Add to the material library", "添加到材质库"), + ("Added {name} to the library", "已将 {name} 添加到库"), + ("Automatic", "自动"), + ("Detected maps", "检测到的贴图"), + ("DirectX", "DirectX"), + ("Import", "导入"), + ("Import PBR texture folder...", "导入 PBR 纹理文件夹..."), + ("Import PBR textures", "导入 PBR 纹理"), + ("Layer name", "图层名称"), + ("Nothing recognised in this folder", "此文件夹中没有可识别的内容"), + ("OpenGL", "OpenGL"), + ("Packed (occlusion, roughness, metallic)", "打包 (遮蔽、粗糙度、金属度)"), + ("Triplanar", "三平面"), + ("UV", "UV"), + ("{n} files ignored", "已忽略 {n} 个文件"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..2c73c7ef 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -18,6 +18,7 @@ pub mod i18n; pub mod keymap; pub mod menus; pub mod parity; +pub mod pbr_import; pub mod profile; pub mod render_mode; pub mod shelf; @@ -82,6 +83,8 @@ pub struct TextureCraftApp { /// Texture sets the GPU could not hold, and the text of the one sticky toast naming them. pub(crate) gpu_memory: (Vec, Option), pub bake: Option, + /// The Import PBR textures dialog while it is open. + pub pbr_import: Option, pub resize: Option, pub link_cooks: Vec, pub thumbs: thumbs::Thumbs, @@ -142,6 +145,7 @@ impl TextureCraftApp { toasts: Vec::new(), gpu_memory: (Vec::new(), None), bake: None, + pbr_import: None, resize: None, link_cooks: Vec::new(), thumbs: thumbs::Thumbs::default(), @@ -445,7 +449,15 @@ impl eframe::App for TextureCraftApp { control::poll(self, ctx); web_files::poll(self); let dropped = ctx.input(|i| i.raw.dropped_files.clone()); - for f in &dropped { + // A folder, a zip or several PBR maps dropped together open the PBR import dialog. + #[cfg(not(target_arch = "wasm32"))] + let taken = !dropped.is_empty() && { + let paths: Vec = dropped.iter().map(|f| f.path().to_path_buf()).collect(); + pbr_import::dropped(self, &paths) + }; + #[cfg(target_arch = "wasm32")] + let taken = false; + for f in dropped.iter().filter(|_| !taken) { web_files::dropped(self, ctx, f); } self.poll_bake(ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a2e85bf7..0512bf77 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -46,6 +46,7 @@ pub const CATALOG: &[Item] = &[ sep("File"), it("File", "Import resources...", "resource.import", None), it("File", "Import MaterialX material...", "file.importMaterialX", None), + it("File", "Import PBR texture folder...", "file.importPbrFolder", None), it("File", "Import material...", "material.load", None), it("File", "Export Textures...", "ui.export", Some("Ctrl+Shift+E")), it("File", "Export Mesh...", "file.exportMesh", None), diff --git a/crates/ui-egui/src/pbr_import.rs b/crates/ui-egui/src/pbr_import.rs new file mode 100644 index 00000000..3aefeecb --- /dev/null +++ b/crates/ui-egui/src/pbr_import.rs @@ -0,0 +1,202 @@ +//! File › Import PBR texture folder: pick a folder (or drop a folder, a zip or several image +//! files), check which maps were found, then import them as one fill layer. +//! +//! The dialog is a thin front end over `file.scanPbrFolder` and `file.importPbrFolder`: it +//! holds the choices (layer name, a file where several name one map, the normal-map convention, +//! the projection, whether to keep the material in the library) and passes them as params. + +use std::collections::BTreeMap; + +use egui::RichText; +use serde_json::{Value, json}; + +use crate::TextureCraftApp; +use crate::i18n::{n_, tr, trf}; +use crate::widgets::{combo, primary_button}; + +/// The open import dialog. +pub struct PbrDialog { + /// `{path}` or `{files}`: where the maps come from. + source: Value, + /// What the scan found. + scan: Value, + name: String, + /// The file picked per map where several were found. + choose: BTreeMap, + /// 0: automatic (from the file name), 1: OpenGL, 2: DirectX. + normal: usize, + triplanar: bool, + library: bool, +} + +/// Map ids in the order they are listed, with their English label. +const MAPS: [(&str, &str); 10] = [ + ("baseColor", "Base color"), + ("roughness", "Roughness"), + ("glossiness", "Glossiness"), + ("metallic", "Metallic"), + ("normal", "Normal"), + ("height", "Height"), + ("ambientOcclusion", "Ambient occlusion"), + ("emissive", "Emissive"), + ("opacity", "Opacity"), + ("orm", n_("Packed (occlusion, roughness, metallic)")), +]; + +/// Scan `source` and open the dialog on the result (an error toast when nothing is found). +pub fn begin(app: &mut TextureCraftApp, source: Value) { + let Some(scan) = app.run("file.scanPbrFolder", source.clone()) else { return }; + let name = scan.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + app.pbr_import = Some(PbrDialog { source, scan, name, choose: BTreeMap::new(), normal: 0, triplanar: false, library: false }); +} + +/// File › Import PBR texture folder: choose the folder. +#[cfg(not(target_arch = "wasm32"))] +pub fn pick(app: &mut TextureCraftApp) { + if let Some(dir) = rfd::FileDialog::new().pick_folder() { + begin(app, json!({ "path": dir.display().to_string() })); + } +} + +/// Dropped paths: a folder, a zip, or two or more image files that name PBR maps open the +/// dialog. Returns true when the drop was taken. +#[cfg(not(target_arch = "wasm32"))] +pub fn dropped(app: &mut TextureCraftApp, paths: &[std::path::PathBuf]) -> bool { + use texturecraft_engine::formats::pbr_maps; + if let Some(dir) = paths.iter().find(|p| p.is_dir()) { + begin(app, json!({ "path": dir.display().to_string() })); + return true; + } + if let Some(zip) = paths.iter().find(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip"))) { + begin(app, json!({ "path": zip.display().to_string() })); + return true; + } + let names: Vec = paths.iter().filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).collect(); + if names.len() >= 2 && pbr_maps::detect(names.iter().map(|n| (n.as_str(), 0))).chosen.len() >= 2 { + begin(app, json!({ "files": paths.iter().map(|p| p.display().to_string()).collect::>() })); + return true; + } + false +} + +fn label_of(id: &str) -> &'static str { + MAPS.iter().find(|(i, _)| *i == id).map_or("", |(_, l)| *l) +} + +/// The dialog, while open. +pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut d) = app.pbr_import.take() else { return }; + let mut open = true; + let (mut go, mut cancel) = (false, false); + crate::windows::dialog("pbrImport", tr("Import PBR textures"), &mut open).show(ctx, |ui| { + ui.set_min_width(380.0); + ui.horizontal(|ui| { + ui.label(tr("Layer name")); + ui.text_edit_singleline(&mut d.name); + }); + ui.add_space(4.0); + ui.label(RichText::new(tr("Detected maps")).strong()); + let maps = d.scan.get("maps").and_then(Value::as_object).cloned().unwrap_or_default(); + let candidates = d.scan.get("candidates").and_then(Value::as_object).cloned().unwrap_or_default(); + for (id, _) in MAPS { + let Some(file) = maps.get(id).and_then(Value::as_str) else { continue }; + let shown = d.choose.get(id).map(String::as_str).unwrap_or(file).to_string(); + match candidates.get(id).and_then(Value::as_array) { + Some(all) => { + combo(ui, tr(label_of(id)), shown, |ui| { + for c in all.iter().filter_map(Value::as_str) { + let mut cur = d.choose.get(id).cloned().unwrap_or_else(|| file.to_string()); + if ui.selectable_value(&mut cur, c.to_string(), c).clicked() { + d.choose.insert(id.to_string(), cur); + } + } + }); + } + None => { + ui.horizontal(|ui| { + ui.label(tr(label_of(id))); + ui.label(RichText::new(shown).weak()); + }); + } + } + } + if maps.is_empty() { + ui.label(tr("Nothing recognised in this folder")); + } + let ignored = d.scan.get("ignored").and_then(Value::as_array).map_or(0, Vec::len); + if ignored > 0 { + ui.label(RichText::new(trf("{n} files ignored", &[("n", &ignored)])).weak()); + } + ui.add_space(6.0); + if maps.contains_key("normal") { + let found = d.scan.get("normalFormat").and_then(Value::as_str).unwrap_or("openGl") == "directX"; + let auto = if found { format!("{} ({})", tr("Automatic"), tr("DirectX")) } else { format!("{} ({})", tr("Automatic"), tr("OpenGL")) }; + let shown = [auto.clone(), tr("OpenGL").to_string(), tr("DirectX").to_string()][d.normal.min(2)].clone(); + combo(ui, tr("Normal map format"), shown, |ui| { + ui.selectable_value(&mut d.normal, 0, auto); + ui.selectable_value(&mut d.normal, 1, tr("OpenGL")); + ui.selectable_value(&mut d.normal, 2, tr("DirectX")); + }); + } + combo(ui, tr("Projection"), if d.triplanar { tr("Triplanar") } else { tr("UV") }, |ui| { + ui.selectable_value(&mut d.triplanar, false, tr("UV")); + ui.selectable_value(&mut d.triplanar, true, tr("Triplanar")); + }); + #[cfg(not(target_arch = "wasm32"))] + ui.checkbox(&mut d.library, tr("Add to the material library")); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(!maps.is_empty(), |ui| go = ui.add(primary_button(ui, tr("Import"))).clicked()); + cancel = ui.button(tr("Cancel")).clicked(); + }); + }); + if go { + run(app, &d); + } + if open && !go && !cancel { + app.pbr_import = Some(d); + } +} + +/// Import with the dialog's choices. +fn run(app: &mut TextureCraftApp, d: &PbrDialog) { + let mut p = d.source.clone(); + p["name"] = json!(d.name.trim()); + p["normalFormat"] = json!(["auto", "openGl", "directX"][d.normal.min(2)]); + if d.triplanar { + p["projection"] = json!("triplanar"); + } + if !d.choose.is_empty() { + p["choose"] = json!(d.choose); + } + let Some(r) = app.run("file.importPbrFolder", p) else { return }; + let name = r.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + for w in r.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + app.session.log.push(format!("PBR {name}: {w}")); + } + app.toast(trf("Imported {name}", &[("name", &name)]), false); + app.ui.dock.focus(crate::docking::Panel::Layers); + #[cfg(not(target_arch = "wasm32"))] + if d.library + && let Some(layer) = r.get("layer").and_then(Value::as_u64) + { + save_to_library(app, layer, &name); + } +} + +/// Keep the imported layer as a smart material in the user library (shelf › Materials). +#[cfg(not(target_arch = "wasm32"))] +fn save_to_library(app: &mut TextureCraftApp, layer: u64, name: &str) { + let stem = texturecraft_engine::formats::export::sanitize_file_stem(name); + let dir = crate::library_dir(); + let mut path = dir.join(format!("{stem}.{}", texturecraft_engine::material_lib::SMART_MATERIAL_EXT)); + let mut n = 2; + while path.exists() { + path = dir.join(format!("{stem} {n}.{}", texturecraft_engine::material_lib::SMART_MATERIAL_EXT)); + n += 1; + } + if app.run("material.save", json!({ "layer": layer, "path": path.display().to_string(), "name": name })).is_some() { + app.library = None; + app.toast(trf("Added {name} to the library", &[("name", &name)]), false); + } +} diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index c8bd72c5..f905c0a5 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -24,6 +24,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::windows::export(app, ctx); #[cfg(target_arch = "wasm32")] export_mesh(app, ctx); + crate::pbr_import::window(app, ctx); unsaved(app, ctx); } @@ -101,7 +102,7 @@ pub(crate) fn window<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Win } /// A centered dialog; `id` keeps its place across UI languages. -fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> { +pub(crate) fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> { egui::Window::new(title.to_owned()) .id(egui::Id::unique(id)) .open(open) @@ -793,6 +794,10 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } true } + "file.importPbrFolder" => { + crate::pbr_import::pick(app); + true + } "file.exportMesh" => { let name = format!("{}.obj", texturecraft_engine::formats::export::sanitize_file_stem(&app.session.doc.project.name)); if let Some(p) = rfd::FileDialog::new() diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3d7c2206..cb427a28 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -223,6 +223,57 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para '{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve ``` +## PBR texture folders + +`file.importPbrFolder` turns a folder, a `.zip` or a list of image files of PBR maps into one fill layer +(one undo step), the way `file.importMaterialX` does for a `.mtlx`. `file.scanPbrFolder` takes the same +`path` / `files` and reports what would be used without changing anything. Both are `file.*` commands, so +they run over the control channel and the CLI, not through MCP `command_run` (which refuses `file.*` +commands and host paths). + +| Command | Params | +|---|---| +| `file.importPbrFolder` | `{path \| files, name?, normalFormat?: auto\|openGl\|directX, projection?: uv\|triplanar\|planar..., scale?, choose?: {map: file}}` → `{layer, name, maps, candidates, normalFormat, channels, resources, ignored, warnings}` | +| `file.scanPbrFolder` | `{path \| files, normalFormat?, choose?}` → `{name, maps, candidates, normalFormat, ignored, channelsAvailable}` | + +Maps are found by file name, case-insensitively, from the last known word in the name; resolution +(`2k`, `4096`), bit depth and other tokens are skipped: + +| Map (`maps` key) | Words | +|---|---| +| `baseColor` | `basecolor`, `base_color`, `albedo`, `diffuse`, `diff`, `col`, `color`, `bc`, `basemap`, `maintex` | +| `roughness` | `roughness`, `rough`, `rgh` | +| `glossiness` (inverted into roughness; a roughness file wins) | `gloss`, `glossiness`, `smoothness` | +| `metallic` | `metallic`, `metalness`, `metal`, `mtl` | +| `normal` | `normal`, `nrm`, `nor`, `norm`, `normalmap`, `bumpmap`, a trailing `n` | +| `height` | `height`, `disp`, `displacement`, `hgt`, `bump` (weakest) | +| `ambientOcclusion` | `ao`, `ambientocclusion`, `ambient_occlusion`, `occlusion`, `occ` | +| `emissive` | `emissive`, `emission`, `emit`, `glow` | +| `opacity` | `opacity`, `alpha`, `transparency` | +| `orm` (split: R occlusion, G roughness, B metallic; separate files win) | `orm`, `arm`, `ao_rough_metal` | + +- **Normal convention.** `gl` / `opengl` in the name is OpenGL, `dx` / `directx` is DirectX (the layer's + normal source is flagged DirectX, so its green is flipped where it is sampled). With neither the map is + OpenGL. `normalFormat: openGl|directX` forces every normal map; `auto` (the default) reads the name. +- **Ignored**: other files, dot files and `__MACOSX`, preview images (`preview`, `thumb`, `thumbnail`, + `sphere`, `render`, `swatch`, `icon`), and maps with no channel here (cavity, curvature, specular...). + Each is listed in `ignored` with the reason. +- **Several files for one map** (resolutions, formats, GL and DX): the OpenGL normal, then the highest + resolution token, then the largest file wins. A programmatic call never asks; `candidates` lists the + alternatives and `choose: {"baseColor": "file.png"}` picks one (the app's dialog shows a drop-down). +- **Where.** A folder's own files if they hold maps; otherwise the one sub-folder that does (several are + an error that names them). The layer is named after the folder, archive or shared file-name prefix. +- **Channels** the texture set doesn't have are skipped with a warning. Projection defaults to UV + (`scale` 1); `projection: triplanar` is the option for models without good UVs. +- **Hostile input.** Links, pipes and devices are not followed, at most 4096 files are listed, a file is + at most 256 MB, an image 64 M texels (320 M per import), a zip entry is read through the same limit. + An image that doesn't decode is skipped with a warning; if none decodes the import is an error that + changes nothing. + +In the app: File › Import PBR texture folder... or drop a folder, a `.zip` or several map files on the +window. The dialog shows the maps found, lets you pick between candidates, set the normal convention and +projection, and keep the material in the library (shelf › Materials). + ## MaterialCraft materials A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is diff --git a/docs/parity.md b/docs/parity.md index d6543d54..2b61a985 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**55 of 55 menu items live (100%).** +**56 of 56 menu items live (100%).** ## File @@ -18,6 +18,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Remove unused resources... | `file.removeUnused` | | live | | Import resources... | `resource.import` | | live | | Import MaterialX material... | `file.importMaterialX` | | live | +| Import PBR texture folder... | `file.importPbrFolder` | | live | | Import material... | `material.load` | | live | | Export Textures... | `ui.export` | Ctrl+Shift+E | live | | Export Mesh... | `file.exportMesh` | | live |