diff --git a/README.md b/README.md index f714f68d..345c32c1 100644 --- a/README.md +++ b/README.md @@ -157,8 +157,8 @@ cd apps/texturecraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` -You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one; **File ▸ Close** returns to this empty state); **File ▸ New project** starts -from a built-in mesh, a project template or your own mesh file (UVs are generated if it has none). +You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). +**File ▸ New project** starts from your own mesh file and a project template. TextureCraft generates UVs if the mesh has none. Japanese, Chinese, Korean and Arabic interface text uses the fonts of [storytold/craft-fonts](https://github.com/storytold/craft-fonts) where it has them, an optional diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index ad339dca..168c438b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1,6 +1,8 @@ //! Files: projects (`.tcraft`), mesh import, texture export. Byte-based functions work on the //! web; path-based commands are native only. +use std::borrow::Cow; + use serde_json::{Value, json}; #[cfg(not(target_arch = "wasm32"))] use texturecraft_core::{NormalFormat, PROJECT_EXT}; @@ -19,7 +21,7 @@ pub fn specs() -> Vec { "New project from a mesh file", [], None, - "{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name}", + "{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}", always, new_from_mesh ), @@ -156,20 +158,31 @@ impl Session { /// [`Session::from_mesh_bytes`] with a UV tile mode (see [`Session::new_project_tiled`]). pub fn from_mesh_bytes_tiled(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option) -> Result { - let imported = texturecraft_formats::import_mesh_bytes(file_name, bytes).map_err(fe)?; - let ext = ext_of(file_name); - let mut s = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{ext}"), Some((ext, bytes.to_vec())), resolution, uv_tiles)?; - s.doc.project.mesh_file = leaf_of(file_name); - s.doc.project.cameras = imported.cameras; - s.log.extend(imported.report.warnings.iter().cloned()); - s.log.push(format!( + Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles) + } + + fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option) -> Result { + let imported = texturecraft_formats::import_mesh_bytes(file_name, &bytes).map_err(fe)?; + let extension = ext_of(file_name); + let mut session = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{extension}"), None, resolution, uv_tiles)?; + + // Packed mesh files can have spare capacity that the project would otherwise retain + let mut source = bytes.into_owned(); + source.shrink_to_fit(); + session.mesh_source = Some((extension, source)); + session.doc.project.mesh_file = leaf_of(file_name); + session.doc.project.cameras = imported.cameras; + + session.log.extend(imported.report.warnings); + session.log.push(format!( "Imported {} ({} triangles, {} materials{})", file_name, imported.report.triangles, imported.report.materials, if imported.report.uvs_generated { ", UVs generated" } else { "" } )); - Ok(s) + + Ok(session) } /// Open a `.tcraft` project from bytes. @@ -405,23 +418,32 @@ mod native { #[cfg(not(target_arch = "wasm32"))] pub use native::{absolute, open_path, read_mesh}; -/// `file.new {mesh, name?, resolution?, uvTiles?, template?}`: a new project from the mesh file `mesh`, -/// remembering its path for Reimport mesh. +/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the +/// mesh file `mesh`, remembering its path for Reimport mesh. #[cfg(not(target_arch = "wasm32"))] -fn new_from_mesh(s: &mut Session, p: &Value) -> Result { - let path = native::path_param(p, "mesh", "file.new")?; - let f = native::read_mesh("file.new", path)?; - let template = crate::template_cmds::template_param(s, p, "file.new")?; - let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048); - let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path)); - let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?; +fn new_from_mesh(session: &mut Session, params: &Value) -> Result { + const DEFAULT_RESOLUTION_PX: u64 = 2048; + + let path = native::path_param(params, "mesh", "file.new")?; + let template = crate::template_cmds::template_param(session, params, "file.new")?; + let resolution = u64p(params, "resolution").or(template.as_ref().map(|template| u64::from(template.resolution))).unwrap_or(DEFAULT_RESOLUTION_PX); + let name = strp(params, "name").map(str::to_string).unwrap_or_else(|| stem_of(path)); + let uv_tiles = crate::commands::boolp(params, "uvTiles"); + let mesh_file = native::read_mesh("file.new", path)?; + + let mut next = Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles)?; next.doc.project.mesh_path = native::absolute(path); - next.log.extend(f.warnings); - if let Some(t) = &template { - next.apply_template(t); + next.log.extend(mesh_file.warnings); + if crate::commands::boolp(params, "importCameras") == Some(false) { + next.doc.project.cameras.clear(); } - s.switch_to(next); - Ok(crate::inspect::session(s)) + if let Some(template) = &template { + next.apply_template(template); + } + + session.switch_to(next); + + Ok(crate::inspect::session(session)) } #[cfg(not(target_arch = "wasm32"))] @@ -693,6 +715,35 @@ fn close(s: &mut Session, _: &Value) -> Result { mod tests { use super::*; + /// `file.new` keeps the cameras stored in the mesh file unless `importCameras` is false. + #[test] + fn new_from_mesh_imports_cameras_unless_told_not_to() { + let dir = std::env::temp_dir().join(format!("tc_new_cameras_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("shot.gltf"); + let gltf = json!({ + "asset": {"version": "2.0"}, + "buffers": [{"byteLength": 36, "uri": "data:application/octet-stream;base64,AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAA"}], + "bufferViews": [{"buffer": 0, "byteLength": 36}], + "accessors": [{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0]}], + "meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}], + "cameras": [{"name": "Shot", "type": "perspective", "perspective": {"yfov": 0.8, "znear": 0.1}}], + "nodes": [{"mesh": 0}, {"camera": 0, "translation": [0.5, 0.5, 4.0]}], + "scenes": [{"nodes": [0, 1]}], + "scene": 0 + }); + std::fs::write(&file, serde_json::to_vec(&gltf).unwrap()).unwrap(); + let path = file.display().to_string(); + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128})).unwrap(); + assert_eq!(s.doc.project.cameras.len(), 1, "the file's camera comes along by default"); + + crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128, "importCameras": false})).unwrap(); + assert!(s.doc.project.cameras.is_empty(), "importCameras false leaves the cameras out"); + let _ = std::fs::remove_dir_all(&dir); + } + /// Reimport mesh reads the mesh file again from where it was imported, so a change saved to /// the file since shows up (it used to re-read the project's own copy and change nothing). #[test] diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 2c973280..97d0bd9a 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -6,13 +6,22 @@ use std::sync::Arc; use serde_json::{Value, json}; use texturecraft_compose::ImageRes; use texturecraft_core::{Channel, Fill, Layer, LayerKind, Source}; +use texturecraft_formats::{MAX_RESOURCE_NAME_LEN, sanitize_resource_name}; use crate::commands::{CommandSpec, always, bad, channel_param, strp}; use crate::{EngineError, Result, Session, cmd}; pub fn specs() -> Vec { vec![ - cmd!("resource.import", "Import resources", ["File"], None, "{path} — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)", always, import), + cmd!( + "resource.import", + "Import resources", + ["File"], + None, + "{path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr), prefix?: put in front of the resource name (anything outside A-Z a-z 0-9 _ . - becomes _)}", + always, + import + ), cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))), cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), @@ -38,22 +47,48 @@ 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", |session| session.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) + self.import_resource_bytes_prefixed("", file_name, bytes) + } + + /// Like [`Self::import_resource_bytes`], with `prefix` put in front of the resource's name + pub fn import_resource_bytes_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec) -> Result { + self.edit("Import resource", |session| session.add_image_resource_prefixed(prefix, file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) } /// Add an image within a decoded texel budget, inside the caller's edit pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec, max_texels: u64) -> Result { + self.add_image_resource_prefixed("", file_name, bytes, max_texels) + } + + fn add_image_resource_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec, max_texels: u64) -> 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_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image"); - let base = texturecraft_formats::sanitize_resource_name(leaf); + let mut base = sanitize_resource_name(leaf); + + // The file name has priority over the optional prefix + let prefix_room = MAX_RESOURCE_NAME_LEN - base.len(); + let prefix = prefix.trim(); + if !prefix.is_empty() && prefix_room > 0 { + let mut prefix = sanitize_resource_name(prefix); + prefix.truncate(prefix_room); + base.insert_str(0, &prefix); + } + + let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |extension_start| base.split_at(extension_start)); let mut name = base.clone(); let mut duplicate_index = 2; while self.doc.resources.contains_key(&name) { - name = format!("{duplicate_index}_{base}"); + let discriminator = format!("{duplicate_index}_"); + let available = MAX_RESOURCE_NAME_LEN - discriminator.len(); + + // Leave room for a stem even for names that end in an unusually long extension + let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") }; + let stem = stem.get(..stem.len().min(available - extension.len())).unwrap_or(stem); + name = format!("{discriminator}{stem}{extension}"); duplicate_index += 1; } @@ -101,7 +136,7 @@ fn list(s: &Session) -> Value { fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let name = s.import_resource_bytes(path, bytes)?; + let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; Ok(json!({ "name": name })) } @@ -114,10 +149,12 @@ pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result max_bytes { return Err(too_large()); } @@ -156,8 +193,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// Drop resources no layer, mask effect, the projection stencil or the environment uses (one undo -/// step). +/// Drop resources unused by layers, mask effects, the brush alpha, the stencil or the environment. fn remove_unused(s: &mut Session, _: &Value) -> Result { let mut used = Vec::new(); for set in &s.doc.project.texture_sets { @@ -166,6 +202,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { } } used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone())); + used.extend(s.tool.brush.alpha_image.clone()); used.extend(s.doc.project.display.environment_resource().map(str::to_string)); let unused: Vec = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect(); if !unused.is_empty() { @@ -240,4 +277,43 @@ mod tests { fn devices_are_rejected_before_reading() { assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular file")); } + + #[test] + fn duplicate_prefixed_image_names_survive_saving_and_reopening() { + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let file_name = format!("{}.png", "x".repeat(108)); + let prefix = "material"; + let mut names = Vec::new(); + + for _ in 0..10 { + let name = session.import_resource_bytes_prefixed(prefix, &file_name, png.clone()).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": name})).unwrap(); + names.push(name); + } + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(reopened.images.len(), names.len()); + for name in names { + assert!(reopened.images.contains_key(&name), "missing image after reload: {name}"); + assert!(name.ends_with(".png")); + } + } + + #[test] + fn removing_unused_resources_keeps_the_active_brush_alpha() { + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let alpha = session.import_resource_bytes("brush.png", png.clone()).unwrap(); + let unused = session.import_resource_bytes("unused.png", png).unwrap(); + crate::execute(&mut session, "tool.brush", &json!({"alpha": {"image": alpha}})).unwrap(); + + let result = crate::execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert_eq!(result["removed"], json!([unused])); + assert_eq!(session.tool.brush.alpha_image.as_deref(), Some(alpha.as_str())); + assert!(session.images.contains_key(&alpha)); + assert!(!session.images.contains_key(&unused)); + } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 17820459..73b6a055 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -51,8 +51,8 @@ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_h pub use presets::load_preset; pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json}; pub use project_file::{ - BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes, - set_project_open_limit_gib, + BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name, + save_project_bytes, set_project_open_limit_gib, }; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index fd13bec2..9f2053fc 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -81,9 +81,12 @@ pub struct ProjectFile { pub warnings: Vec, } +/// Maximum length of a resource name after sanitization. +pub const MAX_RESOURCE_NAME_LEN: usize = 120; + /// A resource name safe as a zip entry and a file name: `[A-Za-z0-9_.-]`, at most 120 chars. pub fn sanitize_resource_name(name: &str) -> String { - let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).take(120).collect(); + let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).take(MAX_RESOURCE_NAME_LEN).collect(); let s = s.trim_start_matches('.').to_string(); if s.is_empty() { "resource".into() } else { s } } diff --git a/crates/ui-egui/src/color_management.rs b/crates/ui-egui/src/color_management.rs new file mode 100644 index 00000000..148acf55 --- /dev/null +++ b/crates/ui-egui/src/color_management.rs @@ -0,0 +1,19 @@ +use crate::i18n::n_; + +/// How a project manages colour. Only Legacy is implemented; OpenColorIO can be chosen to see its +/// settings, but they stay disabled and a project is always created and kept as Legacy. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ColorManagement { + #[default] + Legacy, + OpenColorIo, +} + +impl ColorManagement { + pub(crate) fn label(self) -> &'static str { + match self { + ColorManagement::Legacy => n_("Legacy"), + ColorManagement::OpenColorIo => "OpenColorIO", + } + } +} diff --git a/crates/ui-egui/src/import_resources.rs b/crates/ui-egui/src/import_resources.rs new file mode 100644 index 00000000..629bc90a --- /dev/null +++ b/crates/ui-egui/src/import_resources.rs @@ -0,0 +1,338 @@ +//! File > Import resources...: a window to collect files, set what each is for, and import them +//! together. Images become project resources; materials load as smart materials. + +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicU64, Ordering}; + +use egui::{Key, Modifiers}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::{tr, trf}; +use crate::state::{ImportResources, ImportRow, ResourceUsage}; +use crate::web_files::{IMAGE_EXTS, MATERIAL_EXTS}; +use crate::widgets::primary_button; + +/// Width of the window +const WINDOW_WIDTH_POINTS: f32 = 640.0; +/// Height of the file list +const LIST_HEIGHT_POINTS: f32 = 300.0; +/// Width of a row's prefix field and usage dropdown +const PREFIX_WIDTH_POINTS: f32 = 160.0; +const USAGE_WIDTH_POINTS: f32 = 110.0; +/// Width of the destination dropdown +const TARGET_WIDTH_POINTS: f32 = 190.0; +/// Keep space for the file name in a narrow row +const MIN_NAME_WIDTH_POINTS: f32 = 40.0; + +/// Opens the window with an empty list (an open window stays as it is) +pub(crate) fn open(app: &mut TextureCraftApp) { + static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1); + + app.ui.windows.project_config = None; + if app.ui.windows.import_resources.is_none() { + app.ui.windows.import_resources = Some(ImportResources { + project: app.session.project_id, + opening_id: NEXT_OPENING_ID.fetch_add(1, Ordering::Relaxed), + ..ImportResources::default() + }); + } +} + +/// The keys of the open window: Escape closes it, Enter imports unless a text field or button had +/// the keyboard. An open dropdown takes both first. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool, popup_open: bool) { + if popup_open { + return; + } + + let escape = input.consume_key(Modifiers::NONE, Key::Escape); + let enter = input.consume_key(Modifiers::NONE, Key::Enter); + if escape { + app.ui.windows.import_resources = None; + } else if enter + && nothing_focused + && let Some(window) = app.ui.windows.import_resources.as_mut() + { + window.confirm = true; + } +} + +/// Whether the file is a material (loaded as a smart material, so it has no usage or prefix) +fn is_material(row: &ImportRow) -> bool { + row.path.extension().and_then(|e| e.to_str()).is_some_and(|e| MATERIAL_EXTS.contains(&e.to_ascii_lowercase().as_str())) +} + +fn file_name(row: &ImportRow) -> String { + row.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| row.path.display().to_string()) +} + +/// A click on row `id` of the `visible` rows: plain selects only it, Ctrl toggles it, Shift +/// selects from the anchor to it +fn click_row(window: &mut ImportResources, visible: &[u64], id: u64, modifiers: Modifiers) { + let ctrl = modifiers.command || modifiers.ctrl; + let from = window.anchor.and_then(|anchor| visible.iter().position(|v| *v == anchor)); + let to = visible.iter().position(|v| *v == id); + + match (modifiers.shift, from, to) { + (true, Some(from), Some(to)) => { + let range: BTreeSet = visible[from.min(to)..=from.max(to)].iter().copied().collect(); + if ctrl { + window.selected.extend(range); + } else { + window.selected = range; + } + } + _ if ctrl => { + if !window.selected.remove(&id) { + window.selected.insert(id); + } + window.anchor = Some(id); + } + _ => { + window.selected = BTreeSet::from([id]); + window.anchor = Some(id); + } + } +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut window) = app.ui.windows.import_resources.take() else { return }; + + // Files chosen for another project cannot be imported here + if window.project != app.session.project_id { + return; + } + + // A filter whose rows are gone shows everything again + if window.filter.is_some_and(|usage| !window.rows.iter().any(|row| row.usage == usage)) { + window.filter = None; + } + + let mut open = true; + let (mut import, mut cancel, mut add) = (std::mem::take(&mut window.confirm), false, false); + let mut remove = false; + + crate::windows::dialog("import_resources", tr("Import resources"), &mut open).default_width(WINDOW_WIDTH_POINTS).show(ctx, |ui| { + ui.set_min_width(WINDOW_WIDTH_POINTS); + ui.horizontal(|ui| { + ui.label(tr("Choose files and assign their roles")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(!window.selected.is_empty(), |ui| { + remove = ui.button(tr("Remove selected resources")).clicked(); + }); + add = ui.button(tr("Add resources")).clicked(); + }); + }); + ui.add_space(4.0); + + let all_label = trf("All files ({count})", &[("count", &window.rows.len())]); + let filter_text = match window.filter { + None => all_label.clone(), + Some(usage) => trf("{usage} ({count})", &[("usage", &usage.name()), ("count", &window.rows.iter().filter(|row| row.usage == usage).count())]), + }; + egui::ComboBox::from_id_salt("import_filter").width(ui.available_width()).selected_text(filter_text).show_ui(ui, |ui| { + if ui.selectable_label(window.filter.is_none(), &all_label).clicked() { + window.filter = None; + } + + // Only usages some row has, so the list is never empty by filter + for usage in ResourceUsage::ALL { + let count = window.rows.iter().filter(|row| row.usage == usage).count(); + if count > 0 && ui.selectable_label(window.filter == Some(usage), format!("{} ({count})", usage.name())).clicked() { + window.filter = Some(usage); + } + } + }); + ui.add_space(4.0); + + let filter = window.filter; + let visible = |row: &ImportRow| filter.is_none_or(|usage| row.usage == usage); + let modifiers = ui.input(|i| i.modifiers); + let mut clicked = None; + + egui::ScrollArea::vertical().min_scrolled_height(LIST_HEIGHT_POINTS).max_height(LIST_HEIGHT_POINTS).auto_shrink([false, false]).show(ui, |ui| { + for row in window.rows.iter_mut().filter(|row| visible(row)) { + let material = is_material(row); + let selected = window.selected.contains(&row.id); + ui.horizontal(|ui| { + let name_width = + (ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x).max(MIN_NAME_WIDTH_POINTS); + let name = ui.add_sized([name_width, ui.spacing().interact_size.y], egui::Button::selectable(selected, file_name(row)).truncate()); + if name.on_hover_text(row.path.display().to_string()).clicked() { + clicked = Some(row.id); + } + + let prefix = ui.add_enabled( + !material, + egui::TextEdit::singleline(&mut row.prefix).hint_text(tr("Optional prefix/path...")).desired_width(PREFIX_WIDTH_POINTS), + ); + if material { + prefix.on_disabled_hover_text(tr("Materials keep their own name")); + } else { + prefix.on_hover_text(tr("Put in front of the resource's name. Characters other than letters, digits and _ . - become _")); + } + + ui.add_enabled_ui(!material, |ui| { + egui::ComboBox::from_id_salt(("import_usage", row.id)).width(USAGE_WIDTH_POINTS).selected_text(row.usage.name()).show_ui(ui, |ui| { + for usage in ResourceUsage::ALL { + let item = ui.add_enabled(usage.available(), egui::Button::selectable(row.usage == usage, usage.name())); + if usage.available() { + if item.clicked() { + row.usage = usage; + ui.close(); + } + } else { + item.on_disabled_hover_text(tr("Not available yet")); + } + } + }); + }) + .response + .on_disabled_hover_text(tr("Materials need no usage")); + }); + } + }); + + if let Some(id) = clicked { + let visible: Vec = if modifiers.shift { window.rows.iter().filter(|row| visible(row)).map(|row| row.id).collect() } else { Vec::new() }; + click_row(&mut window, &visible, id, modifiers); + } + + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + egui::ComboBox::from_id_salt("import_target").width(TARGET_WIDTH_POINTS).selected_text(tr("Open project")).show_ui(ui, |ui| { + if ui.selectable_label(true, tr("Open project")).clicked() { + ui.close(); + } + + ui.add_enabled(false, egui::Button::selectable(false, tr("Asset library"))).on_disabled_hover_text(tr("Not available yet")); + }); + ui.label(tr("Destination")); + }); + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + cancel = ui.button(tr("Cancel")).clicked(); + import |= ui.add_enabled(!window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked(); + }); + }); + }); + + if cancel || !open { + return; + } + + if remove { + window.rows.retain(|row| !window.selected.contains(&row.id)); + window.selected.clear(); + window.anchor = None; + } + + if add { + let mut extensions: Vec<&str> = IMAGE_EXTS.to_vec(); + extensions.extend_from_slice(MATERIAL_EXTS); + let opening_id = window.opening_id; + app.ask_file(FileDialog::open_many().filter(tr("Resources"), &extensions), Bound::Project, move |app, paths| { + let Some(stored) = app.ui.windows.import_resources.as_mut().filter(|stored| stored.opening_id == opening_id) else { return }; + + for path in paths { + if stored.rows.iter().any(|row| row.path == path) { + continue; + } + + stored.rows.push(ImportRow { id: stored.next_row, path, prefix: String::new(), usage: ResourceUsage::Undefined }); + stored.next_row += 1; + } + }); + } + + if import && !window.rows.is_empty() { + window.rows.retain(|row| !import_row(app, row)); + if window.rows.is_empty() { + app.ui.dock.focus(crate::docking::Panel::Assets); + return; + } + + window.selected.clear(); + window.anchor = None; + } + + // File picker answers run between frames after the dialog state is restored + app.ui.windows.import_resources = Some(window); +} + +/// Import one row. A failed file is left in the dialog with its settings. +fn import_row(app: &mut TextureCraftApp, row: &ImportRow) -> bool { + let Some(path) = row.path.to_str() else { + app.toast(trf("Could not import a path that is not UTF-8: {path}", &[("path", &row.path.display())]), true); + return false; + }; + + if is_material(row) { + return app.run("material.load", json!({ "path": path })).is_some(); + } + + let Some(result) = app.run("resource.import", json!({ "path": path, "prefix": row.prefix })) else { return false }; + + let name = result["name"].as_str().unwrap_or_default(); + app.toast(trf("Imported {name}", &[("name", &name)]), false); + + match row.usage { + ResourceUsage::Environment => crate::web_files::use_environment(app, name), + ResourceUsage::Alpha => { + if app.run("tool.brush", json!({ "alpha": { "image": name } })).is_some() { + app.toast(trf("Brush alpha: {name}", &[("name", &name)]), false); + } + } + ResourceUsage::Undefined | ResourceUsage::Texture | ResourceUsage::ColorLut | ResourceUsage::PostFx => {} + } + + true +} + +#[cfg(test)] +mod tests { + use super::*; + + const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE }; + + fn selected(window: &ImportResources) -> Vec { + window.selected.iter().copied().collect() + } + + #[test] + fn a_plain_click_selects_one_row() { + let mut window = ImportResources::default(); + click_row(&mut window, &[1, 2, 3], 1, Modifiers::NONE); + click_row(&mut window, &[1, 2, 3], 3, Modifiers::NONE); + + assert_eq!(selected(&window), [3]); + } + + #[test] + fn ctrl_toggles_rows() { + let mut window = ImportResources::default(); + click_row(&mut window, &[1, 2, 3], 1, CTRL); + click_row(&mut window, &[1, 2, 3], 3, CTRL); + assert_eq!(selected(&window), [1, 3]); + + click_row(&mut window, &[1, 2, 3], 1, CTRL); + assert_eq!(selected(&window), [3]); + } + + #[test] + fn shift_selects_from_the_anchor_in_either_direction() { + let mut window = ImportResources::default(); + click_row(&mut window, &[1, 2, 3, 4], 2, Modifiers::NONE); + click_row(&mut window, &[1, 2, 3, 4], 4, SHIFT); + assert_eq!(selected(&window), [2, 3, 4]); + + click_row(&mut window, &[1, 2, 3, 4], 1, SHIFT); + assert_eq!(selected(&window), [1, 2]); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 94643a0e..f97008a3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ mod ask; mod bake_job; pub mod bake_mode; mod bake_scene; +mod color_management; mod color_selection_editor; pub mod control; mod decal_drop; @@ -30,6 +31,8 @@ mod gray_slider; mod grid_tile; pub mod i18n; pub mod id_color_pick; +#[cfg(not(target_arch = "wasm32"))] +mod import_resources; mod inactive_set_hint; pub mod keymap; pub mod layer_panel; @@ -62,6 +65,7 @@ mod preview_worker; pub mod profile; #[cfg(not(target_arch = "wasm32"))] mod project_config; +pub mod project_form; pub mod properties_popup; mod rail_popup; pub mod render_mode; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 16755672..65024d08 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -175,9 +175,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { return; } - if matches!(id, "ui.newProject" | "file.open" | "file.close" | "project.sample") - && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) - { + if matches!(id, "file.open" | "file.close" | "project.sample") && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) { return; } @@ -191,7 +189,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { } match id { - "ui.newProject" => app.ui.windows.new_project = true, + "ui.newProject" => crate::new_project_advanced::open(app), "ui.export" => app.ui.windows.export = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), #[cfg(not(target_arch = "wasm32"))] @@ -438,6 +436,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched #[cfg(not(target_arch = "wasm32"))] crate::project_config::keys_in(app, input, nothing_focused, popup_open); + } else if app.ui.windows.import_resources.is_some() { + #[cfg(not(target_arch = "wasm32"))] + crate::import_resources::keys_in(app, input, nothing_focused, popup_open); } else if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 3247fc8e..2cb8d635 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -1,68 +1,248 @@ -//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation +//! File > New project: BASIC SETTINGS (mesh file, template, resolution), ADVANCED SETTINGS (normal +//! map format, UV tiles, import settings, baked maps imported at creation, physical size, color +//! management), and Cancel / Create fixed below the scrolling form. use std::collections::BTreeSet; +use std::sync::atomic::{AtomicU64, Ordering}; -use egui::{RichText, Sense, Ui, vec2}; +use egui::{RichText, Ui, vec2}; use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; -use crate::state::NewProject; +use crate::project_form::{ + FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, + unavailable, uv_tile_radios, +}; +use crate::state::{Mode, 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"]; +use crate::widgets::primary_button; +use crate::windows::{dialog, file_dialogs_available}; /// 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 -pub(crate) const COMBO_WIDTH: f32 = 200.0; +/// Document resolutions offered (texture sets range from 128 to 8192 px) +const RESOLUTIONS: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; -/// Width of the Add... and Clear buttons -const FILE_BUTTON_WIDTH: f32 = 96.0; +/// Width of the dialog's form +const DIALOG_WIDTH_POINTS: f32 = 560.0; -/// Tallest the list of added files grows before it scrolls -const FILE_LIST_HEIGHT: f32 = 160.0; +/// Leave space around the centered dialog on short viewports +const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.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) +/// Room for the title bar and the button row below the scrolling form +const DIALOG_CHROME_HEIGHT_POINTS: f32 = 96.0; + +/// Width of the Add and Clear buttons +const FILE_BUTTON_WIDTH_POINTS: f32 = 96.0; + +/// Height of the list of added baked map files (it scrolls when longer) +const FILE_LIST_HEIGHT_POINTS: f32 = 120.0; + +/// Width of the Cancel and Create buttons +const BUTTON_WIDTH_POINTS: f32 = 90.0; + +/// File > New project...: start a fresh form, carrying over failed imports from a closed form. +pub(crate) fn open(app: &mut TextureCraftApp) { + let baked_maps = if app.ui.windows.new_project { Vec::new() } else { std::mem::take(&mut app.ui.new_project.baked_maps) }; + + app.ui.new_project = NewProject { baked_maps, opening_id: next_request_id(), ..NewProject::default() }; + app.ui.windows.new_project = true; } -/// 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); +fn next_request_id() -> u64 { + static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1); + NEXT_REQUEST_ID.fetch_add(1, Ordering::Relaxed) +} + +fn close(app: &mut TextureCraftApp) { + app.ui.windows.new_project = false; + app.ui.new_project.clear_mesh(); +} + +/// The New project dialog. +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !app.ui.windows.new_project { + return; } - 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(); + let mut open = true; + let (mut create, mut cancel) = (false, false); + + // A fixed height keeps the centered window still while its sections lay out + let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) + .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); + dialog("new_project", tr("New project"), &mut open).default_width(DIALOG_WIDTH_POINTS).show(ctx, |ui| { + ui.set_width(DIALOG_WIDTH_POINTS); + egui::ScrollArea::vertical().id_salt("np_form").min_scrolled_height(form_height).max_height(form_height).auto_shrink([false, true]).show(ui, |ui| { + basic_settings(app, ui); + ui.add_space(8.0); + advanced_settings(app, ui); }); - if file_dialogs_available() { - ui.add_space(4.0); - section(ui, "np_baked_maps", tr("Import baked maps"), false, |ui| { - if baked_maps(&mut app.ui.new_project, ui) { - ask_baked_map_files(app); - } + ui.separator(); + let can_create = app.ui.new_project.file.is_some(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + create = ui + .add_enabled(can_create, primary_button(ui, tr("Create")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0))) + .on_disabled_hover_text(tr("Select a 3D mesh first")) + .clicked(); + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); }); + }); + }); + + if cancel || !open { + app.ui.new_project.baked_maps = Vec::new(); + close(app); + } else if create && app.ui.windows.unsaved.is_none() { + let opening_id = app.ui.new_project.opening_id; + if !crate::windows::ask_to_save(app, crate::state::Unsaved::CreateProject(opening_id)) { + finish_create(app, opening_id); } + } +} + +pub(crate) fn finish_create(app: &mut TextureCraftApp, opening_id: u64) -> bool { + if !app.ui.windows.new_project || app.ui.new_project.opening_id != opening_id || !create_project(app) { + return false; + } + + close(app); + app.ui.mode = Mode::Painting; + apply_after_create(app); + true +} + +/// The `file.new` command for the form: the chosen mesh file with the settings the engine takes at +/// creation (the project is named after the file). None until a mesh file is chosen. +pub fn create_command(new_project: &NewProject) -> Option { + let mesh = new_project.file.as_ref()?; + Some(json!({ + "mesh": mesh, + "resolution": new_project.resolution, + "uvTiles": new_project.uv_tiles == Some(true), + "template": new_project.template, + "importCameras": new_project.import_cameras, + })) +} + +/// Create the project; false (with the error reported) when it failed. +#[cfg(not(target_arch = "wasm32"))] +fn create_project(app: &mut TextureCraftApp) -> bool { + create_command(&app.ui.new_project).is_some_and(|params| app.run("file.new", params).is_some()) +} + +/// Create the project from the mesh file's bytes picked in the browser, as `file.new` does on the +/// desktop. +#[cfg(target_arch = "wasm32")] +fn create_project(app: &mut TextureCraftApp) -> bool { + let new_project = &app.ui.new_project; + let (Some(name), Some(bytes)) = (new_project.file.as_deref(), new_project.file_bytes.as_deref()) else { return false }; + + let stem = std::path::Path::new(name).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Untitled").to_string(); + let template = app.session.template(&new_project.template); + match texturecraft_engine::Session::from_mesh_bytes_tiled(name, bytes, new_project.resolution, &stem, Some(new_project.uv_tiles == Some(true))) { + Ok(mut next) => { + if !new_project.import_cameras { + next.doc.project.cameras.clear(); + } + if let Some(template) = &template { + next.apply_template(template); + } + app.session.switch_to(next); + app.pbr_import = None; + app.resize = None; + app.layer_panel = Default::default(); + app.camera_glide = None; + true + } + Err(error) => { + app.toast(trf("Couldn't open {name}: {error}", &[("name", &name), ("error", &error)]), true); + false + } + } +} + +fn basic_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.label(caption(&tr("Basic settings").to_uppercase())); + let mut select = false; + row(ui, tr("3D mesh"), Some(tr("The mesh file to paint. Create is available once one is selected.")), |ui| { + select = ui.add(egui::Button::new(tr("Select...")).min_size(vec2(FILE_BUTTON_WIDTH_POINTS, 0.0))).clicked(); + match &app.ui.new_project.file { + Some(path) => { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + None => { + ui.label(RichText::new(tr("No file selected")).italics().color(tokens.text_dim)); + } + } + }); + if select { + ask_mesh_file(app, ui.ctx()); + } + + row(ui, tr("Project template"), Some(tr("The channels, resolution, normal map format and display settings a project starts with")), |ui| { + let new_project = &mut app.ui.new_project; + egui::ComboBox::from_id_salt("np_template").width(FIELD_WIDTH_POINTS).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; + } + } + }); + }); + + row(ui, tr("Document resolution (px)"), Some(tr("The texture size of every texture set. It can be changed later.")), |ui| { + let resolution = &mut app.ui.new_project.resolution; + egui::ComboBox::from_id_salt("np_res").width(FIELD_WIDTH_POINTS).selected_text(format!("{0} x {0}", *resolution)).show_ui(ui, |ui| { + for size in RESOLUTIONS { + ui.selectable_value(resolution, size, format!("{size} x {size}")); + } + }); + }); +} + +/// The collapsible ADVANCED SETTINGS section (open at first) +fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + collapsible(ui, "np_advanced_settings", &tr("Advanced settings").to_uppercase(), true, None, |ui| { + row( + ui, + tr("Normal map format"), + Some(tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")), + |ui| normal_format_combo(app, ui), + ); + tangent_space_row(ui); + + ui.add_space(4.0); + sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("Paint meshes whose UVs span several UV tiles (UDIMs)"))); + note(ui, tr("You can enable or disable UV tiles later in Texture Set Settings.")); + let new_project = &mut app.ui.new_project; + let mut uv_tiles = new_project.uv_tiles == Some(true); + if check_row(ui, None, |ui| ui.checkbox(&mut uv_tiles, tr("Use UV Tile workflow")), |_| {}).changed() { + new_project.uv_tiles = Some(uv_tiles); + } + uv_tile_radios(ui, uv_tiles, tr("Tick Use UV Tile workflow first")); + + ui.add_space(4.0); + sub_title(ui, tr("Import settings"), None); + check_row(ui, Some(tr("Keep the cameras stored in the mesh file")), |ui| ui.checkbox(&mut new_project.import_cameras, tr("Import cameras")), |_| {}); + auto_unwrap_row(ui); + + ui.add_space(4.0); + collapsible(ui, "np_import_baked_maps", tr("Import baked maps"), true, None, |ui| { + if baked_maps(&mut app.ui.new_project, ui) { + ask_baked_map_files(app); + } + }); + physical_size(ui, "np_physical_size", true); + color_management(ui, "np_color_management", &mut app.ui.new_project.color_management); }); } @@ -71,7 +251,7 @@ fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { let template_format = app.session.template(&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| { + egui::ComboBox::from_id_salt("np_normal_format").width(FIELD_WIDTH_POINTS).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); @@ -80,33 +260,43 @@ fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -/// The baked map list and its buttons; true when Add was clicked. +/// The baked map hint, buttons, file list and naming scheme; true when Add was clicked. fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) -> bool { let tokens = Tokens::get(ui.ctx()); let mut add = false; ui.horizontal(|ui| { - let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x; + ui.add_space(ROW_INDENT_POINTS); + let buttons_width = 2.0 * FILE_BUTTON_WIDTH_POINTS + 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()); + ui.add(egui::Label::new(tr("Import mesh normal maps and baked maps for all materials.")).wrap()); }); - if ui.add(egui::Button::new(tr("Add...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { - add = true; - } - if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + let add_button = ui.add_enabled(file_dialogs_available(), egui::Button::new(tr("Add")).min_size(vec2(FILE_BUTTON_WIDTH_POINTS, 0.0))); + add = unavailable(add_button).clicked(); + if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH_POINTS, 0.0))).clicked() { new_project.baked_maps.clear(); } }); - if new_project.baked_maps.is_empty() { - return add; - } 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()); - } + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + egui::Frame::new().fill(tokens.field).corner_radius(2.0).inner_margin(4.0).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("np_baked_map_list").max_height(FILE_LIST_HEIGHT_POINTS).auto_shrink([false, false]).show(ui, |ui| { + ui.vertical(|ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); + }); + }); + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + ui.label(RichText::new(tr("Normal map filename: _normal")).color(tokens.text_dim)) + .on_hover_text(tr("Name each file after its texture set, like Body_normal.png")); }); add } @@ -121,16 +311,17 @@ pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { } /// 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); +fn apply_after_create(app: &mut TextureCraftApp) { + let chosen_format = app.ui.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() { + + if app.ui.new_project.baked_maps.is_empty() { return; } - let files: Vec = new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); + let files: Vec = app.ui.new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); let Some(result) = app.run("textureSet.meshMap.import", json!({ "files": files })) else { return; }; @@ -151,11 +342,38 @@ 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 ask_mesh_file(app: &mut TextureCraftApp, _ctx: &egui::Context) { + use crate::file_dialogs::{Bound, FileDialog}; + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); + let opening_id = app.ui.new_project.opening_id; + app.ask_file(dialog, Bound::App, move |app, paths| { + if app.ui.windows.new_project + && app.ui.new_project.opening_id == opening_id + && let Some(path) = paths.first() + { + app.ui.new_project.file = Some(path.display().to_string()); + app.ui.new_project.file_bytes = None; + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn ask_mesh_file(app: &mut TextureCraftApp, ctx: &egui::Context) { + let request_id = next_request_id(); + app.ui.new_project.mesh_request_id = request_id; + crate::web_files::pick_new_project_mesh(ctx, request_id); +} + #[cfg(not(target_arch = "wasm32"))] fn ask_baked_map_files(app: &mut TextureCraftApp) { use crate::file_dialogs::{Bound, FileDialog}; - app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::App, |app, files| { - add_baked_map_files(&mut app.ui.new_project, files.into_iter().map(|path| path.display().to_string()).collect()); + + let opening_id = app.ui.new_project.opening_id; + app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::App, move |app, files| { + if app.ui.windows.new_project && app.ui.new_project.opening_id == opening_id { + add_baked_map_files(&mut app.ui.new_project, files.into_iter().map(|path| path.display().to_string()).collect()); + } }); } diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index 80942b1b..b6ae5bb1 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -1,5 +1,7 @@ -//! Edit > Project Configuration...: the project's settings in sections. Today it has one, the -//! 3D mesh: pick another mesh file for the project, or read the current one again. +//! Edit > Project Configuration...: the project's settings in sections. 3D MESH picks another mesh +//! file for the project or reads the current one again; PROJECT SETTINGS sets the normal map format +//! and shows the UV tiles. Settings TextureCraft does not have yet (tangent space per fragment, +//! physical size, OpenColorIO, import options other than stroke preservation) are shown disabled. use std::sync::atomic::{AtomicU64, Ordering}; @@ -11,18 +13,24 @@ use crate::TextureCraftApp; use crate::dock::info_icon; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{tr, trf}; +use crate::project_form::{ + FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, + uv_tile_radios, +}; use crate::state::ProjectConfig; -use crate::theme::caption; +use crate::theme::{Tokens, caption}; use crate::widgets::primary_button; /// Room for the Select... button and its info icon beside the path. -const SELECT_BUTTON_WIDTH_POINTS: f32 = 150.0; -/// Room for an info icon at the end of a row. -const INFO_WIDTH_POINTS: f32 = 28.0; +const SELECT_BUTTON_WIDTH_POINTS: f32 = 190.0; +/// Room for the title bar, the note and the button row below the scrolling form. +const DIALOG_CHROME_HEIGHT_POINTS: f32 = 120.0; +/// Width of the Cancel and OK buttons. +const BUTTON_WIDTH_POINTS: f32 = 90.0; /// Keep a usable field when the dialog is narrowed. const MIN_FIELD_WIDTH_POINTS: f32 = 60.0; /// Initial width of the configuration dialog. -const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 460.0; +const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 560.0; /// Leave space around the centered dialog on short viewports. const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0; @@ -31,11 +39,13 @@ pub(crate) fn open(app: &mut TextureCraftApp) { // Layout resets must not reuse an identity held by a pending file picker static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1); + app.ui.windows.import_resources = None; app.ui.windows.project_config = Some(ProjectConfig { mesh: None, reimport: false, preserve: true, normal_format: None, + color_management: crate::project_form::ColorManagement::Legacy, confirm: false, project: app.session.project_id, opening_id: NEXT_OPENING_ID.fetch_add(1, Ordering::Relaxed), @@ -106,151 +116,163 @@ fn format_name(format: NormalFormat) -> &'static str { } pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - let Some(mut config) = app.ui.windows.project_config.clone() else { return }; + let Some(mut config) = app.ui.windows.project_config.take() else { return }; // Choices for another project cannot be applied here if config.project != app.session.project_id { - app.ui.windows.project_config = None; return; } let project = &app.session.doc.project; - let current_mesh_path = project.mesh_path.clone(); + let current_mesh_path = &project.mesh_path; // Show the imported name when there is no file path - let mesh_label = if current_mesh_path.is_empty() { project.mesh_file.clone() } else { current_mesh_path.clone() }; + let mesh_label = if current_mesh_path.is_empty() { &project.mesh_file } else { current_mesh_path }; let source_file_available = app.session.remembered_mesh_path().is_some(); let current_normal_format = project.normal_format; - // Keep each texture set's tiles together for the read-only list - let texture_set_tiles: Vec<(String, Option)> = project - .texture_sets - .iter() - .map(|set| (set.name.clone(), (!set.uv_tiles.is_empty()).then(|| set.uv_tiles.iter().map(u32::to_string).collect::>().join(", ")))) - .collect(); - // Re-selecting the current path cancels an earlier choice - let chosen_mesh = config.mesh.as_ref().filter(|chosen| **chosen != current_mesh_path).cloned(); + let chosen_mesh = config.mesh.as_deref().filter(|chosen| *chosen != current_mesh_path); let mut open = true; let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); - let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open) - .default_width(DEFAULT_DIALOG_WIDTH_POINTS) - .max_height((ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS).max(0.0)) - .vscroll(true); + // A fixed height keeps the centered window still while its sections lay out + let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) + .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); + let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open).default_width(DEFAULT_DIALOG_WIDTH_POINTS); dialog.show(ctx, |ui| { - // Keep the project sections in the order users expect - ui.label(caption(tr("3D MESH"))); - ui.add_space(4.0); - ui.horizontal(|ui| { - ui.label(tr("3D mesh")); - info_icon(ui, tr("The mesh file the project is built on. Hover the path to see it in full.")); + ui.set_width(DEFAULT_DIALOG_WIDTH_POINTS); + egui::ScrollArea::vertical().id_salt("project_config_form").min_scrolled_height(form_height).max_height(form_height).auto_shrink([false, true]).show(ui, |ui| { + // Keep the project sections in the order users expect + ui.label(caption(tr("3D MESH"))); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + ui.label(tr("3D mesh")); - let display_path = chosen_mesh.clone().unwrap_or_else(|| mesh_label.clone()); - let font = egui::TextStyle::Body.resolve(ui.style()); - let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS); - let measure = |text: &str| ui.painter().layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points; + let display_path = chosen_mesh.unwrap_or(mesh_label); + let font = egui::TextStyle::Body.resolve(ui.style()); + let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS); + let painter = ui.painter().clone(); + let measure = |text: &str| painter.layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points; - if display_path.is_empty() { - ui.weak(tr("Built-in mesh")); - } else { - ui.label(elide_start(&display_path, measure)).on_hover_text(&display_path); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_icon(ui, tr("The mesh file the project is built on. Select... chooses another one, read when you press OK.")); + select = ui.button(tr("Select...")).clicked(); + if display_path.is_empty() { + ui.weak(tr("Built-in mesh")); + } else { + ui.label(elide_start(display_path, measure)).on_hover_text(display_path); + } + }); + }); + if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available { + ui.colored_label(ui.visuals().error_fg_color, tr("File not found")); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - info_icon(ui, tr("Choose another mesh file for the project. It is read when you press OK.")); - select = ui.button(tr("Select...")).clicked(); - }); - }); - if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available { - ui.colored_label(ui.visuals().error_fg_color, tr("File not found")); - } + // A selected replacement always reads the mesh again + // A missing source file cannot be reimported + let mut reimport = config.reimport || chosen_mesh.is_some(); + let can_reimport_source = chosen_mesh.is_none() && source_file_available; + let reimport_checkbox = check_row( + ui, + Some(tr("Read the mesh file again, keeping the layers and painted strokes")), + |ui| ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))), + |_| {}, + ); - ui.add_space(4.0); + if can_reimport_source { + config.reimport = reimport; + } else if chosen_mesh.is_none() { + reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); + } - // A selected replacement always reads the mesh again - // A missing source file cannot be reimported - let mut reimport = config.reimport || chosen_mesh.is_some(); - let can_reimport_source = chosen_mesh.is_none() && source_file_available; - let reimport_checkbox = ui - .horizontal(|ui| { - let checkbox = ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))); - info_icon(ui, tr("Read the mesh file again, keeping the layers and painted strokes")); - checkbox - }) - .inner; + ui.add_space(12.0); + ui.label(caption(tr("PROJECT SETTINGS"))); + ui.add_space(4.0); + let shown_format = config.normal_format.unwrap_or(current_normal_format); + row( + ui, + tr("Normal map format"), + Some(tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")), + |ui| { + egui::ComboBox::from_id_salt(tr("Normal map format")) + .width(FIELD_WIDTH_POINTS) + .wrap_mode(egui::TextWrapMode::Truncate) + .selected_text(format_name(shown_format)) + .show_ui(ui, |ui| { + for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { + if ui.selectable_label(format == shown_format, format_name(format)).clicked() { + config.normal_format = (format != current_normal_format).then_some(format); + } + } + }) + .response + .on_hover_text(tr( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + )); + }, + ); + tangent_space_row(ui); - if can_reimport_source { - config.reimport = reimport; - } else if chosen_mesh.is_none() { - reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); - } + // Texture Set Settings owns UV tile changes + ui.add_space(4.0); + sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("View the UV tiles assigned to each texture set"))); + let tiles_hint = tr("Change the UV tiles of a texture set in Texture Set Settings"); + note(ui, tiles_hint); + let mut has_tiles = project.texture_sets.iter().any(|set| !set.uv_tiles.is_empty()); - ui.add_space(8.0); - ui.label(caption(tr("Import settings"))); + check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles, tr("Use UV Tile workflow"))), |_| {}) + .on_disabled_hover_ui(|ui| { + ui.set_max_width(ui.spacing().tooltip_width); + if !has_tiles { + ui.label(tr("No UV tiles")); + } - // Import settings matter only when a mesh will be read - let importing = chosen_mesh.is_some() || (config.reimport && source_file_available); - ui.horizontal(|ui| { - ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))); - info_icon(ui, tr("Painted strokes follow the surface when the new mesh's UVs differ")); - }); - - ui.add_space(12.0); - ui.label(caption(tr("PROJECT SETTINGS"))); - ui.add_space(4.0); - let shown_format = config.normal_format.unwrap_or(current_normal_format); - ui.horizontal(|ui| { - ui.label(tr("Normal map format")); - egui::ComboBox::from_id_salt(tr("Normal map format")) - .width((ui.available_width() - INFO_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS)) - .wrap_mode(egui::TextWrapMode::Truncate) - .selected_text(format_name(shown_format)) - .show_ui(ui, |ui| { - for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { - if ui.selectable_label(format == shown_format, format_name(format)).clicked() { - config.normal_format = (format != current_normal_format).then_some(format); + for set in project.texture_sets.iter().filter(|set| !set.uv_tiles.is_empty()) { + let tiles = set.uv_tiles.iter().map(u32::to_string).collect::>().join(", "); + if project.texture_sets.len() > 1 { + ui.label(trf("{set}: {tiles}", &[("set", &set.name), ("tiles", &tiles)])); + } else { + ui.label(tiles); } } - }) - .response - .on_hover_text(tr( - "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", - )); - info_icon(ui, tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")); - }); - ui.add_space(4.0); + }); + uv_tile_radios(ui, false, tiles_hint); - // Texture Set Settings owns UV tile changes - ui.horizontal(|ui| { - ui.label(tr("UV Tile settings (UDIMs)")); - info_icon(ui, tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings.")); - }); - if texture_set_tiles.iter().all(|(_, tile_text)| tile_text.is_none()) { - ui.label(egui::RichText::new(tr("No UV tiles")).weak()); - } - for (name, tile_text) in texture_set_tiles.iter().filter(|(_, tile_text)| tile_text.is_some()) { - let tile_list = tile_text.as_deref().unwrap_or_default(); - ui.label( - egui::RichText::new(if texture_set_tiles.len() > 1 { - trf("{set}: {tiles}", &[("set", name), ("tiles", &tile_list)]) - } else { - tile_list.to_string() - }) - .weak(), + ui.add_space(4.0); + sub_title(ui, tr("Import settings"), None); + check_row( + ui, + Some(tr("Keep the cameras stored in the mesh file")), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Import cameras")))), + |_| {}, ); - } - ui.label(egui::RichText::new(tr("Change them in Texture Set Settings")).small().weak()); - ui.add_space(12.0); - ui.label(egui::RichText::new(tr("Choosing or reimporting a mesh recomputes all channels.")).small().weak()); + // Import settings matter only when a mesh will be read + let importing = chosen_mesh.is_some() || (config.reimport && source_file_available); + check_row( + ui, + Some(tr("Painted strokes follow the surface when the new mesh's UVs differ")), + |ui| ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))), + |_| {}, + ); + auto_unwrap_row(ui); + + ui.add_space(4.0); + physical_size(ui, "project_config_physical_size", false); + color_management(ui, "project_config_color_management", &mut config.color_management); + }); + + ui.add_space(8.0); + ui.label(egui::RichText::new(tr("Changing the mesh or normal format can recalculate texture channels.")).color(Tokens::get(ui.ctx()).warning)); ui.add_space(4.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ok |= ui.add(primary_button(ui, tr("OK"))).clicked(); - cancel = ui.button(tr("Cancel")).clicked(); + ok |= ui.add(primary_button(ui, tr("OK")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); }); }); }); @@ -261,17 +283,17 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ask_file(dialog, Bound::Project, move |app, paths| { let Some(path) = paths.first().map(|p| p.display().to_string()) else { return }; - let current_mesh_path = app.session.doc.project.mesh_path.clone(); + let current_mesh_path = &app.session.doc.project.mesh_path; if let Some(config) = app.ui.windows.project_config.as_mut().filter(|config| config.opening_id == opening_id) { // Re-selecting the source file drops an earlier choice - config.mesh = (path != current_mesh_path).then_some(path); + config.mesh = (path != *current_mesh_path).then_some(path); } }); } // Apply the mesh first so a failed mesh change leaves the format untouched let mut mesh_applied = false; - let done = ok && { + let done = ok && !cancel && open && { let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten(); mesh_applied = if config.reimport && chosen_mesh.is_none() && reimport.is_none() { // Drop a stale reimport tick so the user can retry the remaining settings @@ -279,7 +301,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { config.reimport = false; false } else { - match mesh_command(chosen_mesh.as_deref(), reimport.as_deref(), config.preserve) { + match mesh_command(chosen_mesh, reimport.as_deref(), config.preserve) { Some((command, params)) => app.run(command, params).is_some(), None => true, } @@ -296,16 +318,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } }; - if done || cancel || !open { - app.ui.windows.project_config = None; - } else if let Some(stored) = app.ui.windows.project_config.as_mut() { - // A file answer arrives later through the stored state - (stored.reimport, stored.preserve, stored.normal_format, stored.confirm) = (config.reimport, config.preserve, config.normal_format, false); - + if !done && !cancel && open { // A format retry must not reimport an already changed mesh if ok && mesh_applied { - (stored.mesh, stored.reimport) = (None, false); + (config.mesh, config.reimport) = (None, false); } + + app.ui.windows.project_config = Some(config); } } diff --git a/crates/ui-egui/src/project_form.rs b/crates/ui-egui/src/project_form.rs new file mode 100644 index 00000000..171282e3 --- /dev/null +++ b/crates/ui-egui/src/project_form.rs @@ -0,0 +1,270 @@ +//! Rows and sections that New project and Edit > Project Configuration share: the label, control +//! and info icon of a setting, collapsible sections, and the settings the engine does not have +//! yet (shown disabled, with a hover hint that says so). + +use egui::{Response, RichText, Sense, Ui}; + +pub use crate::color_management::ColorManagement; +use crate::dock::info_icon; +use crate::i18n::{n_, tr}; +use crate::theme::{Tokens, caption}; +use crate::widgets::section_chevron; + +/// Hover hint of a control whose function TextureCraft does not have yet. +pub const NOT_AVAILABLE: &str = n_("Not available yet"); + +/// Hover hint of the Color management dropdown while OpenColorIO is chosen. +pub const OCIO_NOT_AVAILABLE: &str = n_("OpenColorIO is not available yet. The project uses Legacy."); + +/// Width of the dropdowns and fields at the right of a row. +pub(crate) const FIELD_WIDTH_POINTS: f32 = 220.0; + +/// Tallest the scrolling form of the two windows grows (the rest scrolls). +pub(crate) const FORM_HEIGHT_POINTS: f32 = 760.0; + +/// Scrolling form height when viewport space is limited. +pub(crate) const MIN_FORM_HEIGHT_POINTS: f32 = 120.0; + +/// Indent of the rows below a section title. +pub(crate) const ROW_INDENT_POINTS: f32 = 16.0; + +/// `response` with the not-available hint while it is disabled. +pub(crate) fn unavailable(response: Response) -> Response { + response.on_disabled_hover_text(tr(NOT_AVAILABLE)) +} + +/// A row: `label` at the left, then `control` right-aligned before the info icon (`info`). +pub(crate) fn row(ui: &mut Ui, label: &str, info: Option<&str>, control: impl FnOnce(&mut Ui) -> R) -> R { + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + ui.label(label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_slot(ui, info); + control(ui) + }) + .inner + }) + .inner +} + +/// A row that starts with its control (a checkbox or radio button) and ends with the info icon. +/// `trailing` adds a control just before the icon (a button). +pub(crate) fn check_row(ui: &mut Ui, info: Option<&str>, control: impl FnOnce(&mut Ui) -> R, trailing: impl FnOnce(&mut Ui)) -> R { + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + let inner = control(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_slot(ui, info); + trailing(ui); + }); + inner + }) + .inner +} + +fn info_slot(ui: &mut Ui, info: Option<&str>) { + match info { + Some(text) => info_icon(ui, text), + + // An invisible icon keeps the controls of rows without one in the same column + None => { + ui.add_visible(false, egui::Label::new(egui_phosphor::regular::INFO)); + } + } +} + +/// A bold sub-section title such as Import settings, with an optional info icon at the end. +pub(crate) fn sub_title(ui: &mut Ui, title: &str, info: Option<&str>) { + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + ui.label(caption(title)); + if let Some(text) = info { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, text)); + } + }); +} + +/// A dim italic note in a section. +pub(crate) fn note(ui: &mut Ui, text: &str) { + ui.horizontal(|ui| { + ui.add_space(2.0 * ROW_INDENT_POINTS); + ui.add(egui::Label::new(RichText::new(text).italics().color(Tokens::get(ui.ctx()).text_dim)).wrap()); + }); +} + +/// A dropdown that cannot be opened, showing `value`, with the not-available hint. +pub(crate) fn disabled_combo(ui: &mut Ui, id: &str, value: &str) -> Response { + let response = + ui.add_enabled_ui(false, |ui| egui::ComboBox::from_id_salt(id).width(FIELD_WIDTH_POINTS).selected_text(value).show_ui(ui, |_| {}).response).inner; + unavailable(response) +} + +/// A collapsible section: a chevron and `title` (clicking either toggles it), an optional info +/// icon at the end of the header, and `body` while open. +pub(crate) fn collapsible(ui: &mut Ui, id: &str, title: &str, default_open: bool, info: Option<&str>, body: impl FnOnce(&mut Ui)) { + let id = ui.make_persistent_id(id); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + let header = ui + .horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); + ui.add(egui::Label::new(caption(title)).selectable(false)); + }) + .response + .interact(Sense::click()); + if header.clicked() { + state.toggle(ui); + } + if let Some(text) = info { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, text)); + } + }); + state.show_body_unindented(ui, |ui| { + ui.indent(id.with("body"), body); + }); +} + +/// "Compute tangent space per fragment" (not available yet, so unticked and disabled). +pub(crate) fn tangent_space_row(ui: &mut Ui) { + check_row( + ui, + Some(tr("Compute the tangent space of normal maps per pixel instead of per vertex")), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Compute tangent space per fragment")))), + |_| {}, + ); +} + +/// The UV tile workflow radios under "Use UV Tile workflow": per material (what the UV tile +/// workflow does) or one texture set per tile (not available yet). `enabled` while the workflow +/// can be chosen and is on. +pub(crate) fn uv_tile_radios(ui: &mut Ui, enabled: bool, disabled_hint: &str) { + ui.indent("uv_tile_radios", |ui| { + let preserve = check_row( + ui, + Some(tr("Each material keeps its UV tiles in one texture set, and strokes paint across tiles")), + |ui| ui.add_enabled(enabled, egui::RadioButton::new(true, tr("Keep UV tiles together per material"))), + |_| {}, + ); + preserve.on_disabled_hover_text(disabled_hint); + check_row( + ui, + Some(tr("Each UV tile becomes a texture set of its own")), + |ui| unavailable(ui.add_enabled(false, egui::RadioButton::new(false, tr("Use a separate texture set for each tile")))), + |_| {}, + ); + }); +} + +/// Import settings ▸ Auto-unwrap and its options. Meshes without UVs are always unwrapped, so the +/// box is ticked; turning it off and the options are not available yet. +pub(crate) fn auto_unwrap_row(ui: &mut Ui) { + check_row( + ui, + Some(tr("Generate UVs for meshes that have none")), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut true, tr("Auto-unwrap")))), + |ui| { + unavailable(ui.add_enabled(false, egui::Button::new(tr("Auto-unwrap options")))); + }, + ); +} + +/// The Physical size section: the mesh file's own unit scale is what TextureCraft uses; a custom +/// scale and physical-size fill layers are not available yet. +pub(crate) fn physical_size(ui: &mut Ui, id: &str, default_open: bool) { + const UNIT_FIELD_WIDTH_POINTS: f32 = 60.0; + + collapsible(ui, id, tr("Physical size"), default_open, Some(tr("The real-world size of one unit of the mesh")), |ui| { + check_row(ui, Some(tr("Use the unit scale stored in the mesh file")), |ui| ui.radio(true, tr("Use the mesh file’s unit scale")), |_| {}); + check_row( + ui, + Some(tr("Set the size of one unit yourself")), + |ui| unavailable(ui.add_enabled(false, egui::RadioButton::new(false, tr("Custom unit scale")))), + |_| {}, + ); + ui.horizontal(|ui| { + ui.add_space(3.0 * ROW_INDENT_POINTS); + ui.label(tr("1 unit =")); + unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(UNIT_FIELD_WIDTH_POINTS))); + ui.label(tr("cm")); + }); + check_row( + ui, + Some(tr("Fill layers of applied materials are scaled in physical size instead of UV space")), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Scale material fills in real-world units")))), + |_| {}, + ); + }); +} + +/// Rows of the OpenColorIO settings: (label, shown value, info). They are not available yet. +const OCIO_CONFIGURATION: [(&str, &str, Option<&str>); 1] = + [(n_("OpenColorIO configuration"), "ACES 2.0", Some(n_("The OpenColorIO configuration that defines the color spaces")))]; +const OCIO_IMPORT: [(&str, &str, Option<&str>); 4] = [ + (n_("8 bit images"), "sRGB Encoded Rec.709 (sRGB)", None), + (n_("16 bit images"), "sRGB Encoded Rec.709 (sRGB)", None), + (n_("Floating point images"), "Linear Rec.709 (sRGB)", None), + (n_("Auto detect color spaces"), n_("Parse file name"), Some(n_("Read an imported image's color space from its file name"))), +]; +const OCIO_EXPORT: [(&str, &str, Option<&str>); 3] = [ + (n_("8 bit images"), "sRGB Encoded Rec.709 (sRGB)", None), + (n_("16 bit images"), "sRGB Encoded Rec.709 (sRGB)", None), + (n_("Floating point images"), "ACEScg", None), +]; + +/// The Color management section. `mode` is the dropdown's choice: Legacy shows the working color +/// space. OpenColorIO previews disabled settings while the project continues to use Legacy. +pub(crate) fn color_management(ui: &mut Ui, id: &str, mode: &mut ColorManagement) { + collapsible(ui, id, tr("Color management"), true, None, |ui| { + ui.label(caption(tr("Configuration"))); + row(ui, tr("Color management"), Some(tr("Legacy works in linear sRGB. OpenColorIO manages color through a configuration")), |ui| { + let response = egui::ComboBox::from_id_salt(format!("{id}_mode")) + .width(FIELD_WIDTH_POINTS) + .selected_text(tr(mode.label())) + .show_ui(ui, |ui| { + for choice in [ColorManagement::Legacy, ColorManagement::OpenColorIo] { + ui.selectable_value(mode, choice, tr(choice.label())); + } + }) + .response; + if *mode == ColorManagement::OpenColorIo { + response.on_hover_text(tr(OCIO_NOT_AVAILABLE)); + } + }); + if *mode == ColorManagement::OpenColorIo { + for (label, value, info) in OCIO_CONFIGURATION { + row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_{label}"), tr(value))); + } + row(ui, tr("Configuration file"), Some(tr("A custom OpenColorIO configuration file")), |ui| { + unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(FIELD_WIDTH_POINTS))); + }); + } + + ui.add_space(4.0); + ui.label(caption(tr("Color settings"))); + let working_space = if *mode == ColorManagement::OpenColorIo { "ACEScg" } else { "Linear - sRGB Chrominance (ITU-R BT.709)" }; + row(ui, tr("Working color space"), Some(tr("The color space layers are blended in")), |ui| ui.label(working_space)); + if *mode != ColorManagement::OpenColorIo { + return; + } + + row(ui, tr("Standard sRGB color space"), Some(tr("The color space of sRGB images and colors")), |ui| { + disabled_combo(ui, &format!("{id}_srgb"), "sRGB Encoded Rec.709 (sRGB)") + }); + ui.add_space(4.0); + ui.label(caption(tr("Bitmap import color space defaults"))); + for (label, value, info) in OCIO_IMPORT { + row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_import_{label}"), tr(value))); + } + ui.add_space(4.0); + ui.label(caption(tr("Materials"))); + row(ui, tr("Material color space default"), Some(tr("The color space of material inputs that do not state one")), |ui| { + disabled_combo(ui, &format!("{id}_material"), "sRGB Encoded Rec.709 (sRGB)") + }); + ui.add_space(4.0); + ui.label(caption(tr("Export color spaces"))); + for (label, value, info) in OCIO_EXPORT { + row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_export_{label}"), tr(value))); + } + }); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 509acdc3..139910e3 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -9,8 +9,14 @@ use crate::saved_search::SavedSearch; use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; +mod import_resources; +mod import_row; mod project_config; +mod resource_usage; +pub use import_resources::ImportResources; +pub use import_row::ImportRow; pub use project_config::ProjectConfig; +pub use resource_usage::ResourceUsage; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Mode { @@ -82,6 +88,9 @@ pub struct Windows { /// Edit > Project Configuration: what is chosen so far, applied by OK. #[serde(skip)] pub project_config: Option, + /// File > Import resources: the files added so far, imported by Import. + #[serde(skip)] + pub import_resources: Option, /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, @@ -94,8 +103,10 @@ pub struct Windows { #[derive(Clone, Debug, PartialEq)] pub enum Unsaved { Quit, - /// A menu command (New project, Open, Close, Open sample project). + /// A menu command (Open, Close, Open sample project). Command(String), + /// Create from the New project form that requested confirmation. + CreateProject(u64), /// Open this project or mesh file. #[cfg(not(target_arch = "wasm32"))] Open(String), @@ -163,22 +174,32 @@ impl Prefs { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NewProject { - pub mesh: String, pub resolution: u32, - pub name: String, - /// A mesh file chosen from disk (desktop only). + /// The mesh file chosen with Select... (its path on the desktop, its name in the browser). pub file: Option, - /// UV tile (UDIM) workflow: on, off, or None for when the mesh's UVs leave tile 1001. + /// The browser's copy of the chosen mesh file, read when Create is pressed. + #[serde(skip)] + pub file_bytes: Option>>, + /// The active form opening, used to reject late file picker answers. + #[serde(skip)] + pub opening_id: u64, + /// The latest mesh pick requested by this form. + #[serde(skip)] + pub mesh_request_id: u64, + /// Use UV Tile workflow: Some(true) makes UV tile (UDIM) texture sets; otherwise each set paints tile 1001. pub uv_tiles: Option, /// Project template name (built-in or the user's). #[serde(default = "default_template")] pub template: String, - /// 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, + /// Import settings > Import cameras: keep the cameras stored in the mesh file + #[serde(default = "import_cameras_default")] + pub import_cameras: bool, + /// Color management as chosen in the window (the project is always created as Legacy) + #[serde(skip)] + pub color_management: crate::project_form::ColorManagement, /// Baked map files to import at creation, matched to sets and mesh maps by name (desktop only) #[serde(skip)] pub baked_maps: Vec, @@ -188,17 +209,32 @@ fn default_template() -> String { texturecraft_engine::template_cmds::DEFAULT_TEMPLATE.into() } +fn import_cameras_default() -> bool { + true +} + +impl NewProject { + pub(crate) fn clear_mesh(&mut self) { + self.file = None; + self.file_bytes = None; + self.opening_id = 0; + self.mesh_request_id = 0; + } +} + impl Default for NewProject { fn default() -> Self { NewProject { - mesh: "material_ball".into(), - resolution: 2048, - name: "Untitled".into(), + resolution: 1024, file: None, + file_bytes: None, + opening_id: 0, + mesh_request_id: 0, uv_tiles: None, template: default_template(), - template_name: String::new(), normal_format: None, + import_cameras: true, + color_management: crate::project_form::ColorManagement::Legacy, baked_maps: Vec::new(), } } @@ -428,6 +464,15 @@ impl UiState { pub fn adopt_layout(&mut self, layout: UiState) { let keep = std::mem::replace(self, layout); self.new_project = keep.new_project; + if !self.windows.new_project { + self.new_project.clear_mesh(); + + // Keep a failed import queued when the form was already closed + if keep.windows.new_project { + self.new_project.baked_maps = Vec::new(); + } + } + self.export = keep.export; self.recent = keep.recent; self.prefs = keep.prefs; diff --git a/crates/ui-egui/src/state/import_resources.rs b/crates/ui-egui/src/state/import_resources.rs new file mode 100644 index 00000000..583e39c1 --- /dev/null +++ b/crates/ui-egui/src/state/import_resources.rs @@ -0,0 +1,22 @@ +use std::collections::BTreeSet; + +use super::{ImportRow, ResourceUsage}; + +/// File > Import resources: the files added so far, imported by the Import button +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ImportResources { + pub rows: Vec, + /// Ids of the selected rows + pub selected: BTreeSet, + /// The row a Shift click extends from + pub anchor: Option, + /// The usage the list is narrowed to (None: all) + pub filter: Option, + /// Whether Enter requested the import in the next frame + pub confirm: bool, + /// The project that was open when this window opened + pub project: u64, + /// This opening's identity, used to reject late file picker answers + pub(crate) opening_id: u64, + pub(crate) next_row: u64, +} diff --git a/crates/ui-egui/src/state/import_row.rs b/crates/ui-egui/src/state/import_row.rs new file mode 100644 index 00000000..305548da --- /dev/null +++ b/crates/ui-egui/src/state/import_row.rs @@ -0,0 +1,12 @@ +use std::path::PathBuf; + +use super::ResourceUsage; + +/// One file waiting in the window +#[derive(Clone, Debug, PartialEq)] +pub struct ImportRow { + pub id: u64, + pub path: PathBuf, + pub prefix: String, + pub usage: ResourceUsage, +} diff --git a/crates/ui-egui/src/state/project_config.rs b/crates/ui-egui/src/state/project_config.rs index 33992ec4..174b0987 100644 --- a/crates/ui-egui/src/state/project_config.rs +++ b/crates/ui-egui/src/state/project_config.rs @@ -9,6 +9,8 @@ pub struct ProjectConfig { pub preserve: bool, /// The selected normal map format when it differs from the project's pub normal_format: Option, + /// Color management as chosen in the window; nothing is applied (the project stays Legacy) + pub color_management: crate::project_form::ColorManagement, /// Whether Enter requested confirmation in the next frame pub confirm: bool, /// The project that was open when this window opened diff --git a/crates/ui-egui/src/state/resource_usage.rs b/crates/ui-egui/src/state/resource_usage.rs new file mode 100644 index 00000000..5cf40d3b --- /dev/null +++ b/crates/ui-egui/src/state/resource_usage.rs @@ -0,0 +1,39 @@ +/// What an imported resource is for +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ResourceUsage { + /// Imported as an image resource, nothing more + #[default] + Undefined, + /// An image resource that also becomes the brush alpha + Alpha, + /// Color lookup tables (not available yet) + ColorLut, + /// An image resource that also lights the scene + Environment, + /// Post effect resources (not available yet) + PostFx, + /// An image resource for fills and stencils + Texture, +} + +impl ResourceUsage { + /// The usages in the dropdown's order + pub const ALL: [ResourceUsage; 6] = [Self::Undefined, Self::Alpha, Self::ColorLut, Self::Environment, Self::PostFx, Self::Texture]; + + /// The name shown in the dropdowns (the same in every language, as in the reference) + pub fn name(self) -> &'static str { + match self { + Self::Undefined => "undefined", + Self::Alpha => "alpha", + Self::ColorLut => "colorlut", + Self::Environment => "environment", + Self::PostFx => "postfx", + Self::Texture => "texture", + } + } + + /// Whether the app can do something with resources of this usage + pub fn available(self) -> bool { + !matches!(self, Self::ColorLut | Self::PostFx) + } +} diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index fe4bcd83..51dbd4b7 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -46,6 +46,8 @@ enum Pick { Cage(u64), /// Export dialog › Output templates: an export template (`.json`). ExportPreset, + /// New project › 3D mesh › Select...: the mesh the project is created from. + NewProjectMesh(u64), } /// Files picked in the browser, waiting for the next frame: (file name, bytes, purpose). @@ -70,13 +72,23 @@ fn apply_picked(app: &mut TextureCraftApp, picked: Vec<(String, Vec, Pick)>) app.toast(tr("No project is open"), true); continue; } + Pick::Environment(project_id) | Pick::HighPoly(project_id) | Pick::Cage(project_id) if project_id != app.session.project_id => { app.toast(tr("The project changed while the dialog was open, so nothing was done"), true); continue; } + Pick::Environment(_) => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)), Pick::HighPoly(_) => app.session.add_high_poly_bytes(&name, bytes).map(|n| app.toast(trf("High poly: {name}", &[("name", &n)]), false)), Pick::Cage(_) => app.session.set_cage_bytes(&name, bytes).map(|n| app.toast(trf("Cage: {name}", &[("name", &n)]), false)), + Pick::NewProjectMesh(request_id) => { + if app.ui.windows.new_project && app.ui.new_project.mesh_request_id == request_id { + app.ui.new_project.file = Some(name); + app.ui.new_project.file_bytes = Some(std::sync::Arc::new(bytes)); + } + continue; + } + Pick::ExportPreset => { match texturecraft_engine::formats::preset_from_json(&String::from_utf8_lossy(&bytes)) { Ok(p) => crate::export_templates::import(app, &p), @@ -121,7 +133,7 @@ pub fn import_environment(app: &mut TextureCraftApp, _ctx: &egui::Context) { } /// Make image resource `name` the environment. -fn use_environment(app: &mut TextureCraftApp, name: &str) { +pub(crate) fn use_environment(app: &mut TextureCraftApp, name: &str) { let env = format!("{}{name}", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX); if app.run("display.set", serde_json::json!({ "environment": env })).is_some() { app.toast(trf("Environment: {name}", &[("name", &name)]), false); @@ -230,8 +242,8 @@ fn zip_files(files: &[ExportedFile]) -> Result, String> { #[cfg(target_arch = "wasm32")] pub use web::{ - download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, save_project, - sync_unsaved, unsaved, + download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, pick_new_project_mesh, + save_project, sync_unsaved, unsaved, }; #[cfg(target_arch = "wasm32")] @@ -284,6 +296,11 @@ mod web { pick(ctx, tr("Export templates"), &["json"], false, Pick::ExportPreset); } + /// New project › Select...: pick the mesh file; Create reads it once it has arrived. + pub fn pick_new_project_mesh(ctx: &egui::Context, request_id: u64) { + pick(ctx, tr("3D meshes"), &MESH_EXTENSIONS, false, Pick::NewProjectMesh(request_id)); + } + fn pick(ctx: &egui::Context, filter: &'static str, exts: &'static [&'static str], multiple: bool, kind: Pick) { let ctx = ctx.clone(); wasm_bindgen_futures::spawn_local(async move { @@ -386,6 +403,28 @@ mod tests { use egui_kittest::Harness; + #[test] + fn mesh_picks_only_update_the_current_new_project_request() { + let session = Session::closed().unwrap(); + let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + crate::new_project_advanced::open(app); + app.ui.new_project.mesh_request_id = 2; + + apply_picked(app, vec![("new.obj".into(), vec![2; 4096], Pick::NewProjectMesh(2)), ("stale.obj".into(), vec![1; 8192], Pick::NewProjectMesh(1))]); + + assert_eq!(app.ui.new_project.file.as_deref(), Some("new.obj")); + assert_eq!(app.ui.new_project.file_bytes.as_deref().unwrap().as_slice(), &[2; 4096]); + let previous_buffer = std::sync::Arc::downgrade(app.ui.new_project.file_bytes.as_ref().unwrap()); + + crate::new_project_advanced::open(app); + apply_picked(app, vec![("previous.obj".into(), vec![3; 2048], Pick::NewProjectMesh(2))]); + + assert!(app.ui.new_project.file.is_none()); + assert!(app.ui.new_project.file_bytes.is_none()); + assert!(previous_buffer.upgrade().is_none()); + } + #[test] fn environment_pick_after_close_does_not_edit_the_placeholder() { let session = texturecraft_engine::sample_session(128, 32).unwrap(); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 3c507dc3..54863a7c 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -5,7 +5,6 @@ use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::core::ToneMapping; use texturecraft_engine::core::project::{DisplaySettings, ENV_RESOURCE_PREFIX}; -use texturecraft_engine::geom::primitives::BUILTINS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; @@ -13,17 +12,20 @@ use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::LANGUAGES; use crate::i18n::{tr, tr_history, trf}; -use crate::new_project_advanced::COMBO_WIDTH; +#[cfg(not(target_arch = "wasm32"))] use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, section_with_reset, slider}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - new_project(app, ctx); + crate::new_project_advanced::show(app, ctx); about(app, ctx); settings(app, ctx); #[cfg(not(target_arch = "wasm32"))] - crate::project_config::show(app, ctx); + { + crate::project_config::show(app, ctx); + crate::import_resources::show(app, ctx); + } crate::keymap::window(app, ctx); crate::windows::export(app, ctx); #[cfg(target_arch = "wasm32")] @@ -154,6 +156,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { } } + let discard_after_create = matches!(pending, Unsaved::CreateProject(_)) && save_first == Some(false) && app.session.modified; match save_first { Some(true) => { // An untitled project is saved from a dialog that answers on a later frame @@ -173,10 +176,16 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.session.modified { return; } + app.ui.windows.unsaved = None; match pending { Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id), + Unsaved::CreateProject(opening_id) => { + if !crate::new_project_advanced::finish_create(app, opening_id) && discard_after_create { + app.session.modified = true; + } + } #[cfg(not(target_arch = "wasm32"))] Unsaved::Open(path) => open_path(app, &path), Unsaved::Load(name, bytes) => crate::web_files::load(app, &name, std::sync::Arc::unwrap_or_clone(bytes)), @@ -445,124 +454,6 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { } } -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| { - ui.label(caption(tr("Basic settings"))); - 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(|| { - BUILTINS - .iter() - .find(|(id, _)| *id == app.ui.new_project.mesh) - .map(|(_, builtin_label)| trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))])) - .unwrap_or_default() - }); - 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(builtin_label))]), - ) - .clicked() - { - app.ui.new_project.mesh = id.to_string(); - app.ui.new_project.file = None; - } - } - }); - if file_dialogs_available() && ui.button(tr("Select...")).clicked() { - ask_mesh_file(app); - } - }); - ui.end_row(); - ui.label(tr("Project template")); - 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; - } - } - }); - ui.end_row(); - ui.label(""); - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut app.ui.new_project.template_name).hint_text(tr("Template name")).desired_width(120.0)); - let name = app.ui.new_project.template_name.trim().to_string(); - if ui.add_enabled(!name.is_empty() && app.session.project_open, egui::Button::new(tr("Save current project as template"))).clicked() - && app.run("project.template.save", json!({"name": name})).is_some() - { - app.ui.new_project.template = name; - app.ui.new_project.template_name.clear(); - } - }); - 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 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 = |tiles: Option| 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 tiles in [None, Some(true), Some(false)] { - ui.selectable_value(&mut app.ui.new_project.uv_tiles, tiles, tiles_label(tiles)); - } - }); - ui.end_row(); - ui.label(tr("Name")); - ui.text_edit_singleline(&mut app.ui.new_project.name); - 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() { - create = true; - } - if ui.button(tr("Cancel")).clicked() { - app.ui.windows.new_project = false; - } - }); - }); - }); - if create { - let new_project = app.ui.new_project.clone(); - let (command, mesh) = match &new_project.file { - Some(path) => ("file.new", path.clone()), - None => ("project.new", new_project.mesh.clone()), - }; - 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; - crate::new_project_advanced::apply_after_create(app, &new_project); - } - } - if !open { - app.ui.windows.new_project = false; - } -} - #[cfg(not(target_arch = "wasm32"))] fn settings_resources(ctx: &egui::Context) -> (u32, u64) { let id = egui::Id::unique("settings_resources"); @@ -810,19 +701,6 @@ pub fn file_dialogs_available() -> bool { cfg!(not(target_arch = "wasm32")) } -#[cfg(not(target_arch = "wasm32"))] -fn ask_mesh_file(app: &mut TextureCraftApp) { - let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); - app.ask_file(dialog, Bound::App, |app, paths| { - if let Some(p) = paths.first() { - app.ui.new_project.file = Some(p.display().to_string()); - } - }); -} - -#[cfg(target_arch = "wasm32")] -fn ask_mesh_file(_app: &mut TextureCraftApp) {} - /// Remember a project path in File ▸ Recent projects. pub fn remember(app: &mut TextureCraftApp, path: &str) { app.ui.recent.retain(|p| p != path); @@ -871,16 +749,16 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> match id { "file.open" => { app.ask_file(FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS), Bound::App, |app, paths| { - if let Some(p) = paths.first() { - open_path(app, &p.display().to_string()); + if let Some(path) = paths.first() { + open_path(app, &path.display().to_string()); } }); true } "file.save" if app.session.path.is_some() => { - if let Some(r) = app.run("file.save", json!({})) { - let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Saved {path}", &[("path", &p)]), false); + if let Some(result) = app.run("file.save", json!({})) { + let saved_path = result["path"].as_str().unwrap_or_default(); + app.toast(trf("Saved {path}", &[("path", &saved_path)]), false); } true } @@ -894,36 +772,24 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } "material.load" => { app.ask_file(FileDialog::open_many().filter(tr("Materials"), crate::web_files::MATERIAL_EXTS), Bound::Project, |app, paths| { - for p in paths { - app.run("material.load", json!({"path": p.display().to_string()})); + for path in paths { + app.run("material.load", json!({"path": path.display().to_string()})); } }); true } "file.importResources" | "resource.import" => { - app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::Project, |app, paths| { - if paths.is_empty() { - return; - } - - for p in paths { - if let Some(r) = app.run("resource.import", json!({"path": p.display().to_string()})) { - let name = r.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Imported {name}", &[("name", &name)]), false); - } - } - app.ui.dock.focus(crate::docking::Panel::Assets); - }); + crate::import_resources::open(app); true } "file.importMaterialX" => { app.ask_file(FileDialog::open().filter(tr("MaterialX materials"), &["mtlx"]), Bound::Project, |app, paths| { - if let Some(p) = paths.first() - && let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()})) + if let Some(path) = paths.first() + && let Some(result) = app.run("file.importMaterialX", json!({"path": path.display().to_string()})) { - let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) { - app.session.log.push(format!("MaterialX {name}: {w}")); + let name = result["material"].as_str().unwrap_or_default(); + for warning in result["warnings"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str) { + app.session.log.push(format!("MaterialX {name}: {warning}")); } app.toast(trf("Imported {name}", &[("name", &name)]), false); app.ui.dock.focus(crate::docking::Panel::Layers); @@ -945,25 +811,26 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> .filter(tr("USD binary, textures alongside"), &["usdc"]) .file_name(name); app.ask_file(dialog, Bound::Project, |app, paths| { - if let Some(p) = paths.first() - && let Some(r) = app.run("file.exportMesh", json!({"path": p.display().to_string()})) + if let Some(path) = paths.first() + && let Some(result) = app.run("file.exportMesh", json!({"path": path.display().to_string()})) { - let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Exported mesh to {path}", &[("path", &p)]), false); + let saved_path = result["path"].as_str().unwrap_or_default(); + app.toast(trf("Exported mesh to {path}", &[("path", &saved_path)]), false); } }); true } "file.reimportMesh" => { - // The file the mesh came from is read again from disk; ask only when it's gone. + // Ask for a replacement only when the mesh source is missing if let Some(path) = app.session.remembered_mesh_path().map(str::to_string) { reimport_mesh(app, path); return true; } + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); app.ask_file(dialog, Bound::Project, |app, paths| { - if let Some(p) = paths.first() { - reimport_mesh(app, p.display().to_string()); + if let Some(path) = paths.first() { + reimport_mesh(app, path.display().to_string()); } }); true diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index 5c13c6d8..bf21686e 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -146,7 +146,7 @@ fn answered_after_the_project_changed(ask: impl FnOnce(&mut Harness<'_, TextureC #[test] fn every_project_dialog_does_nothing_for_a_replaced_project() { let file = temp_file("replaced-actions", "chosen.obj"); - for id in ["material.load", "resource.import", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] { + for id in ["material.load", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] { let h = answered_after_the_project_changed(|h| invoke(h, id), &file); assert!(h.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "{id}"); assert!(!file.exists(), "{id} wrote nothing"); diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs new file mode 100644 index 00000000..173a3dc9 --- /dev/null +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -0,0 +1,270 @@ +//! File > Import resources...: the window that collects files and imports them together. File +//! pickers are answered by the override, never shown. + +use std::path::{Path, PathBuf}; + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; + +use super::temp_dir::TempDir; + +const TITLE: &str = "Import resources"; +/// The prefix field's tooltip, which is its accessible label. +const PREFIX_HINT: &str = "Put in front of the resource's name. Characters other than letters, digits and _ . - become _"; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).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.prefs.language = "en".into(); + h.run_steps(4); + + h +} + +fn png(dir: &Path, name: &str) -> PathBuf { + let file = dir.join(name); + image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 200, 30, 255])).save(&file).unwrap(); + + file +} + +fn invoke(h: &mut Harness<'_, TextureCraftApp>) { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "resource.import"); + h.run_steps(3); +} + +fn is_open(h: &Harness<'_, TextureCraftApp>) -> bool { + h.query_by_label(TITLE).is_some() +} + +fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + h.get_by_role_and_label(Role::Button, label).click(); + h.run_steps(3); +} + +/// Add resources, answered with `files`. +fn add(h: &mut Harness<'_, TextureCraftApp>, files: &[PathBuf]) { + let files = files.to_vec(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(files.clone())))); + click(h, "Add resources"); +} + +/// The dropdowns showing `value` (they have no label, only a value). +fn combos<'h>(h: &'h Harness<'_, TextureCraftApp>, value: &'h str) -> impl Iterator> { + h.get_all_by_role(Role::ComboBox).filter(move |node| node.value().as_deref() == Some(value)) +} + +fn resources(h: &Harness<'_, TextureCraftApp>) -> Vec { + h.state().session.doc.resources.keys().cloned().collect() +} + +/// Pick `usage` in the dropdown of the `n`th row (the dropdowns show "undefined" until changed). +fn choose_usage(h: &mut Harness<'_, TextureCraftApp>, n: usize, usage: &str) { + let combo = combos(h, "undefined").nth(n).expect("a usage dropdown"); + combo.click(); + h.run_steps(3); + h.get_by_label(usage).click(); + h.run_steps(3); +} + +#[test] +fn the_menu_opens_the_window_without_importing_or_asking() { + let mut h = app(); + invoke(&mut h); + + assert!(is_open(&h)); + assert!(resources(&h).is_empty()); + assert!(h.query_by_label("Choose files and assign their roles").is_some()); + assert!(combos(&h, "All files (0)").next().is_some()); + assert!(h.get_by_label("Remove selected resources").accesskit_node().is_disabled(), "nothing is selected"); +} + +#[test] +fn added_files_are_listed_and_import_keeps_their_names() { + let dir = TempDir::new("import-resources-add"); + let (a, b) = (png(&dir, "bluenoise.png"), png(&dir, "scratch.png")); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[a.clone(), b]); + + assert!(combos(&h, "All files (2)").next().is_some()); + assert!(h.query_by_label("bluenoise.png").is_some() && h.query_by_label("scratch.png").is_some()); + assert!(resources(&h).is_empty(), "adding only lists"); + + // The same file twice is one row + add(&mut h, &[a]); + assert!(combos(&h, "All files (2)").next().is_some()); + + click(&mut h, "Import"); + assert!(!is_open(&h)); + assert_eq!(resources(&h), ["bluenoise.png", "scratch.png"]); +} + +#[test] +fn remove_selected_drops_only_the_selected_rows() { + let dir = TempDir::new("import-resources-remove"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(&dir, "one.png"), png(&dir, "two.png")]); + + h.get_by_label("one.png").click(); + h.run_steps(3); + click(&mut h, "Remove selected resources"); + + assert!(h.query_by_label("one.png").is_none()); + assert!(h.query_by_label("two.png").is_some()); + assert!(combos(&h, "All files (1)").next().is_some()); + click(&mut h, "Import"); + assert_eq!(resources(&h), ["two.png"]); +} + +#[test] +fn the_usage_defaults_to_undefined_and_the_choice_reaches_the_import() { + let dir = TempDir::new("import-resources-usage"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(&dir, "plain.png"), png(&dir, "brush.png"), png(&dir, "sky.png")]); + assert_eq!(combos(&h, "undefined").count(), 3); + + choose_usage(&mut h, 1, "alpha"); + choose_usage(&mut h, 1, "environment"); + click(&mut h, "Import"); + + assert_eq!(resources(&h), ["brush.png", "plain.png", "sky.png"]); + let project = &h.state().session.doc.project; + assert_eq!(project.display.environment_resource(), Some("sky.png"), "the environment usage lights the scene"); + assert_eq!(h.state().session.tool.brush.alpha_image.as_deref(), Some("brush.png"), "the alpha usage sets the brush alpha"); +} + +#[test] +fn a_prefix_goes_in_front_of_the_resource_name() { + let dir = TempDir::new("import-resources-prefix"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(&dir, "dust.png")]); + + h.get_by_role_and_label(Role::TextInput, PREFIX_HINT).click(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, PREFIX_HINT).type_text("wear/"); + h.run_steps(3); + click(&mut h, "Import"); + + assert_eq!(resources(&h), ["wear_dust.png"]); +} + +#[test] +fn unsupported_usages_and_the_user_library_are_listed_but_disabled() { + let dir = TempDir::new("import-resources-disabled"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(&dir, "x.png")]); + + combos(&h, "undefined").next().expect("the dropdown").click(); + h.run_steps(3); + for usage in ["colorlut", "postfx"] { + assert!(h.get_by_label(usage).accesskit_node().is_disabled(), "{usage}"); + } + assert!(!h.get_by_label("texture").accesskit_node().is_disabled()); + h.get_by_label("texture").click(); + h.run_steps(3); + + combos(&h, "Open project").next().expect("the dropdown").click(); + h.run_steps(3); + assert!(h.get_by_label("Asset library").accesskit_node().is_disabled()); +} + +#[test] +fn cancel_imports_nothing() { + let dir = TempDir::new("import-resources-cancel"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(&dir, "never.png")]); + click(&mut h, "Cancel"); + + assert!(!is_open(&h)); + assert!(resources(&h).is_empty()); + + // Reopening starts empty + invoke(&mut h); + assert!(combos(&h, "All files (0)").next().is_some()); +} + +#[test] +fn the_engine_command_still_imports_a_path_with_an_optional_prefix() { + let dir = TempDir::new("import-resources-command"); + let file = png(&dir, "tile.png"); + let mut session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + + let plain = texturecraft_engine::execute(&mut session, "resource.import", &serde_json::json!({"path": file.display().to_string()})).unwrap(); + let prefixed = + texturecraft_engine::execute(&mut session, "resource.import", &serde_json::json!({"path": file.display().to_string(), "prefix": "a/b/"})).unwrap(); + + assert_eq!(plain["name"], "tile.png"); + assert_eq!(prefixed["name"], "a_b_tile.png"); +} + +#[test] +fn only_failed_rows_remain_after_a_partial_import() { + let dir = TempDir::new("import-resources-retry"); + let good = png(&dir, "good.png"); + let failed = dir.join("retry.png"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[good, failed.clone()]); + choose_usage(&mut h, 1, "alpha"); + { + let rows = &mut h.state_mut().ui.windows.import_resources.as_mut().unwrap().rows; + rows[1].prefix = "brush_".into(); + } + h.run_steps(2); + + click(&mut h, "Import"); + + let rows = &h.state().ui.windows.import_resources.as_ref().expect("failed row stays open").rows; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].path, failed); + assert_eq!(rows[0].prefix, "brush_"); + assert_eq!(resources(&h), ["good.png"]); + + png(&dir, "retry.png"); + click(&mut h, "Import"); + + assert!(!is_open(&h)); + assert_eq!(resources(&h), ["brush_retry.png", "good.png"]); + assert_eq!(h.state().session.tool.brush.alpha_image.as_deref(), Some("brush_retry.png")); +} + +#[test] +fn opening_import_resources_replaces_project_configuration() { + let mut h = app(); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.projectConfig"); + assert!(h.state().ui.windows.project_config.is_some()); + + invoke(&mut h); + + assert!(is_open(&h)); + assert!(h.state().ui.windows.project_config.is_none()); +} + +#[test] +#[ignore = "offscreen GPU snapshot; set TC_UI_SNAPSHOTS to an output directory"] +fn import_resources_snapshot() { + let output_dir = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let dir = TempDir::new("import-resources-snapshot"); + let session = Session::new_project("Resources", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + + invoke(&mut h); + add(&mut h, &[png(&dir, "panel_basecolor.png"), png(&dir, "brush_alpha.png")]); + choose_usage(&mut h, 1, "alpha"); + + std::fs::create_dir_all(&output_dir).unwrap(); + h.render().unwrap().save(output_dir.join("import-resources.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index d58f564b..03c5713c 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -28,6 +28,7 @@ mod frame_selection; mod generator_panel; mod gradient_map_menu; mod history_panel; +mod import_resources; mod inactive_set_hint; mod layer_blending_options; mod layer_clipboard; @@ -40,6 +41,7 @@ mod mask_value_swap; mod named_layouts; mod nav_buttons; mod new_project_baked_maps; +mod new_project_window; mod path_in_view; mod path_list; mod pen_pressure; @@ -62,6 +64,7 @@ mod skew_paint; mod smudge_channels; mod snapped_lines; mod split_divider; +mod temp_dir; mod template_invert; mod tool_availability; mod tool_settings_saved; diff --git a/crates/ui-egui/tests/it/new_project_baked_maps.rs b/crates/ui-egui/tests/it/new_project_baked_maps.rs index 39a7c813..d171b8ef 100644 --- a/crates/ui-egui/tests/it/new_project_baked_maps.rs +++ b/crates/ui-egui/tests/it/new_project_baked_maps.rs @@ -1,6 +1,6 @@ //! New project ▸ Import baked maps: added files are listed, Clear empties the list, Create imports them -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -8,23 +8,33 @@ 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> { +use super::temp_dir::TempDir; + +/// Two quads with the materials Ball and Base, like the sample's texture sets +const TWO_MATERIALS: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv 0 0 1\nv 1 0 1\nv 1 1 1\nv 0 1 1\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n\ +usemtl Ball\nf 1/1 2/2 3/3 4/4\nusemtl Base\nf 5/1 6/2 7/3 8/4\n"; + +/// The New project window with `test`'s mesh file (materials Ball and Base) selected +fn harness_for(dir: &Path) -> Harness<'static, TextureCraftApp> { + let mesh = dir.join("Ball.obj"); + std::fs::write(&mesh, TWO_MATERIALS).unwrap(); 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.state_mut().ui.new_project.file = Some(mesh.display().to_string()); h.run_steps(3); h } +/// Click Create (fixed below the form) +fn create(h: &mut Harness<'_, TextureCraftApp>) { + h.get_by_label("Create").click(); + h.run_steps(3); +} + /// 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 { - let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); +fn bake_files(dir: &Path, files: &[&str]) -> Vec { files .iter() .map(|file| { @@ -37,17 +47,19 @@ fn bake_files(test: &str, files: &[&str]) -> Vec { #[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"]); + let dir = TempDir::new("new-project-baked-maps-list"); + let mut h = harness_for(&dir); + let paths = bake_files(&dir, &["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); - } + let first = h.get_by_label("Ball_normal.png").rect(); + let second = h.get_by_label("Base_ao.png").rect(); + let third = h.get_by_label("Ball_notes.png").rect(); + assert!(first.bottom() < second.top() && second.bottom() < third.top(), "the files appear on separate rows"); h.get_by_label("Clear").click(); h.run_steps(3); @@ -57,14 +69,14 @@ fn added_files_are_listed_once_and_clear_empties_the_list() { #[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"]); + let dir = TempDir::new("new-project-baked-maps-create"); + let mut h = harness_for(&dir); + let paths = bake_files(&dir, &["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); + create(&mut h); let state = h.state(); assert!(!state.ui.windows.new_project, "the dialog closes"); @@ -83,24 +95,32 @@ fn create_imports_the_listed_maps_in_the_chosen_normal_format() { #[test] fn a_failed_import_keeps_the_file_list_and_created_project() { - let mut h = harness(); - let paths = bake_files("failure", &["Ball_normal.png", "Base_ao.png"]); + let dir = TempDir::new("new-project-baked-maps-failure"); + let mut h = harness_for(&dir); + let paths = bake_files(&dir, &["Ball_normal.png", "Base_ao.png"]); std::fs::write(&paths[1], b"not an image").unwrap(); add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); - h.state_mut().ui.new_project.name = "Import failure".to_string(); h.run_steps(3); - h.get_by_label("Create").click(); - h.run_steps(3); + create(&mut h); let app = h.state(); assert!(!app.ui.windows.new_project); - assert_eq!(app.session.doc.project.name, "Import failure"); + assert_eq!(app.session.doc.project.name, "Ball", "the project is named after the mesh file"); assert_eq!(app.ui.new_project.baked_maps, paths); assert!(app.session.doc.resources.is_empty() && app.session.images.is_empty()); assert!(app.session.doc.baked.values().all(|baked| baked.maps.is_empty())); let toast = app.toasts.last().unwrap(); assert!(toast.error && toast.text.contains("Base_ao.png"), "{}", toast.text); + + h.state_mut().ui.adopt_layout(texturecraft_ui_egui::UiState::default()); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject"); + h.run_steps(3); + + assert_eq!(h.state().ui.new_project.baked_maps, paths); + h.get_by_label("Ball_normal.png"); + h.get_by_label("Base_ao.png"); } #[test] @@ -114,14 +134,14 @@ fn new_project_baked_maps_snapshots() { eprintln!("snapshot adapter: {adapter:?}"); TextureCraftApp::new(cc, session) }); + let dir = TempDir::new("new-project-baked-maps-snapshots"); + let mesh = dir.join("Ball.obj"); + std::fs::write(&mesh, TWO_MATERIALS).unwrap(); h.state_mut().ui.windows.new_project = true; h.state_mut().ui.new_project.resolution = 256; + h.state_mut().ui.new_project.file = Some(mesh.display().to_string()); h.run_steps(6); - h.get_by_label("Advanced settings").click(); - h.run_steps(6); - h.get_by_label("Import baked maps").click(); - h.run_steps(6); - let paths = bake_files("snapshots", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + let paths = bake_files(&dir, &["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(6); @@ -135,11 +155,28 @@ fn new_project_baked_maps_snapshots() { h.run_steps(3); assert!(h.state().session.doc.baked[&0].maps.contains_key(&BakedMap::Normal)); h.render().unwrap().save(output_dir.join("new-project-imported.png")).unwrap(); + + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject"); + let paths = bake_files(&dir, &["Ball_normal.png"]); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.run_steps(6); + h.get_by_label("Ball_normal.png"); + + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert!(!h.state().ui.windows.new_project); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject"); + h.run_steps(6); + + assert!(h.query_by_label("Ball_normal.png").is_none()); + h.render().unwrap().save(output_dir.join("new-project-after-cancel.png")).unwrap(); } #[test] fn normal_format_preview_uses_the_same_template_lookup_as_creation() { - let mut h = harness(); + let dir = TempDir::new("new-project-baked-maps-template"); + let mut h = harness_for(&dir); h.state_mut().session.templates.dir = None; h.state_mut().run("textureSet.settings", serde_json::json!({"normalFormat": "directX"})).unwrap(); h.state_mut().run("project.template.save", serde_json::json!({"name": "Custom DirectX"})).unwrap(); @@ -147,7 +184,6 @@ fn normal_format_preview_uses_the_same_template_lookup_as_creation() { h.run_steps(3); h.get_by_value("DirectX"); - h.get_by_label("Create").click(); - h.run_steps(3); + create(&mut h); assert_eq!(h.state().session.doc.project.normal_format, NormalFormat::DirectX); } diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs new file mode 100644 index 00000000..2a175df3 --- /dev/null +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -0,0 +1,439 @@ +//! File > New project: the sections and their order, the defaults, settings shown disabled with a +//! hint until TextureCraft has them, Create waiting for a mesh file, and the settings that reach +//! the `file.new` command. + +use egui::Role; +use egui::accesskit::Toggled; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::template_cmds::DEFAULT_TEMPLATE; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::Answer; +use texturecraft_ui_egui::new_project_advanced::create_command; +use texturecraft_ui_egui::project_form::{NOT_AVAILABLE, OCIO_NOT_AVAILABLE}; + +use super::temp_dir::TempDir; + +/// A quad whose UVs lie in UV tile 1002 and a camera-free OBJ +const TILE_1002_QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 1.1 0.1\nvt 1.9 0.1\nvt 1.9 0.9\nvt 1.1 0.9\nf 1/1 2/2 3/3 4/4\n"; + +/// The app with New project opened from the menu, tall enough to show the whole form +fn harness() -> Harness<'static, TextureCraftApp> { + harness_sized(egui::vec2(1600.0, 2400.0)) +} + +fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::Session::new_project("Open", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut h = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(2); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject"); + h.run_steps(4); + h +} + +fn mesh_file(dir: &std::path::Path, contents: &str) -> String { + let path = dir.join("tiles.obj"); + std::fs::write(&path, contents).unwrap(); + + path.display().to_string() +} + +#[test] +fn cancel_drops_the_selected_mesh_buffer() { + let mut h = harness(); + let bytes = std::sync::Arc::new(vec![0; 1024 * 1024]); + let buffer = std::sync::Arc::downgrade(&bytes); + h.state_mut().ui.new_project.file = Some("cancel.obj".into()); + h.state_mut().ui.new_project.file_bytes = Some(bytes); + h.run_steps(3); + + h.get_by_role_and_label(Role::Button, "Cancel").click(); + h.run_steps(3); + + assert!(!h.state().ui.windows.new_project); + assert!(buffer.upgrade().is_none()); +} + +#[test] +fn create_keeps_the_mesh_buffer_for_retry_and_drops_it_after_success() { + let dir = TempDir::new("new-project-create-retry"); + let path = dir.join("retry.obj"); + let mut h = harness(); + let bytes = std::sync::Arc::new(vec![0; 2 * 1024 * 1024]); + let buffer = std::sync::Arc::downgrade(&bytes); + h.state_mut().ui.new_project.resolution = 128; + h.state_mut().ui.new_project.file = Some(path.display().to_string()); + h.state_mut().ui.new_project.file_bytes = Some(bytes); + h.run_steps(3); + + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + + assert!(h.state().ui.windows.new_project); + assert!(buffer.upgrade().is_some()); + assert_eq!(h.state().session.doc.project.name, "Open"); + + std::fs::write(&path, TILE_1002_QUAD).unwrap(); + let color_map = dir.join("retry_basecolor.png"); + image::RgbaImage::new(4, 4).save(&color_map).unwrap(); + texturecraft_ui_egui::pbr_import::begin(h.state_mut(), serde_json::json!({"files": [color_map]})); + assert!(h.state().pbr_import.is_some()); + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + + assert!(!h.state().ui.windows.new_project); + assert!(buffer.upgrade().is_none()); + assert!(h.state().pbr_import.is_none()); + assert_eq!(h.state().session.doc.project.name, "retry"); +} + +fn top(h: &Harness<'_, TextureCraftApp>, label: &str) -> f32 { + h.get_all_by_label(label).map(|node| node.rect().top()).fold(f32::INFINITY, f32::min) +} + +fn disabled(h: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().is_disabled() +} + +fn ticked(h: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(Toggled::True) +} + +#[test] +fn the_sections_follow_the_project_setup_order() { + let h = harness(); + let order = [ + "BASIC SETTINGS", + "3D mesh", + "Project template", + "Document resolution (px)", + "ADVANCED SETTINGS", + "Normal map format", + "Compute tangent space per fragment", + "UV Tile settings (UDIMs)", + "You can enable or disable UV tiles later in Texture Set Settings.", + "Use UV Tile workflow", + "Keep UV tiles together per material", + "Use a separate texture set for each tile", + "Import settings", + "Import cameras", + "Auto-unwrap", + "Import baked maps", + "Import mesh normal maps and baked maps for all materials.", + "Normal map filename: _normal", + "Physical size", + "Use the mesh file’s unit scale", + "Custom unit scale", + "Scale material fills in real-world units", + "Color management", + "Working color space", + ]; + let tops: Vec = order.iter().map(|label| top(&h, label)).collect(); + for (pair, labels) in tops.windows(2).zip(order.windows(2)) { + assert!(pair[0] < pair[1], "{} comes before {}: {pair:?}", labels[0], labels[1]); + } + assert!(h.query_by_label("Linear - sRGB Chrominance (ITU-R BT.709)").is_some()); +} + +#[test] +fn the_defaults_match_the_reference() { + let h = harness(); + + assert!(h.query_by_label("No file selected").is_some()); + assert!(h.query_by_value(DEFAULT_TEMPLATE).is_some(), "the default template"); + assert!(h.query_by_value("1024 x 1024").is_some()); + assert!(h.query_by_value("OpenGL").is_some()); + assert!(h.query_by_value("Legacy").is_some()); + assert!(!ticked(&h, Role::CheckBox, "Compute tangent space per fragment")); + assert!(!ticked(&h, Role::CheckBox, "Use UV Tile workflow")); + assert!(ticked(&h, Role::RadioButton, "Keep UV tiles together per material")); + assert!(disabled(&h, Role::RadioButton, "Keep UV tiles together per material"), "greyed while UV tiles are off"); + assert!(ticked(&h, Role::CheckBox, "Import cameras") && !disabled(&h, Role::CheckBox, "Import cameras")); + assert!(ticked(&h, Role::CheckBox, "Auto-unwrap")); + assert!(ticked(&h, Role::RadioButton, "Use the mesh file’s unit scale")); + assert!(!ticked(&h, Role::CheckBox, "Scale material fills in real-world units")); +} + +#[test] +fn template_controls_name_and_built_in_meshes_are_gone() { + let h = harness(); + + for label in ["Template name", "Save current project as template", "Name", "UV tiles (UDIM)"] { + assert!(h.query_by_label(label).is_none(), "{label} is not in the window"); + } + assert!(h.query_by_label_contains("Built-in:").is_none(), "no built-in mesh dropdown"); +} + +#[test] +fn create_waits_for_a_mesh_file() { + let mut h = harness(); + + assert!(disabled(&h, Role::Button, "Create")); + + let dir = TempDir::new("new-project-create-enabled"); + h.state_mut().ui.new_project.file = Some(mesh_file(&dir, TILE_1002_QUAD)); + h.run_steps(2); + + assert!(!disabled(&h, Role::Button, "Create")); + assert!(h.query_by_label("tiles.obj").is_some(), "the chosen file is shown"); +} + +#[test] +fn settings_not_available_yet_are_disabled_with_a_hint() { + let mut h = harness(); + let unavailable = [ + (Role::CheckBox, "Compute tangent space per fragment"), + (Role::RadioButton, "Use a separate texture set for each tile"), + (Role::CheckBox, "Auto-unwrap"), + (Role::Button, "Auto-unwrap options"), + (Role::RadioButton, "Custom unit scale"), + (Role::CheckBox, "Scale material fills in real-world units"), + ]; + for (role, label) in unavailable { + assert!(disabled(&h, role, label), "{label} is disabled"); + } + assert!(!disabled(&h, Role::RadioButton, "Use the mesh file’s unit scale")); + + for (role, label) in unavailable { + let center = h.get_by_role_and_label(role, label).rect().center(); + h.hover_at(egui::pos2(1.0, 1.0)); + h.run_steps(2); + assert!(h.query_by_label(NOT_AVAILABLE).is_none(), "no hint before hovering {label}"); + h.hover_at(center); + h.run_steps(30); + assert!(h.query_by_label(NOT_AVAILABLE).is_some(), "hovering {label} says it is not available yet"); + } +} + +#[test] +fn opencolorio_shows_its_settings_disabled_and_creates_legacy() { + let mut h = harness(); + + assert!(h.query_by_label("OpenColorIO configuration").is_none(), "Legacy shows only the working color space"); + assert!(h.query_by_label(OCIO_NOT_AVAILABLE).is_none(), "no OpenColorIO hint while Legacy is chosen"); + + h.get_by_value("Legacy").scroll_to_me(); + h.run_steps(3); + h.get_by_value("Legacy").click(); + h.run_steps(3); + h.get_by_label("OpenColorIO").click(); + h.run_steps(3); + + assert!(h.query_by_label(OCIO_NOT_AVAILABLE).is_some(), "the dropdown's hover hint says OpenColorIO is not available yet"); + for label in ["OpenColorIO configuration", "Configuration file", "Standard sRGB color space", "Auto detect color spaces", "Material color space default"] { + assert!(h.query_by_label(label).is_some(), "{label} is shown"); + } + assert!(h.query_by_label("ACEScg").is_some(), "the OpenColorIO working color space"); + let ocio_config = h.get_by_value("ACES 2.0"); + assert!(ocio_config.accesskit_node().is_disabled(), "the OpenColorIO settings are disabled"); + let center = ocio_config.rect().center(); + h.hover_at(center); + h.run_steps(30); + assert!(h.query_by_label(NOT_AVAILABLE).is_some(), "with the not-available hint"); + let params = create_command(&texturecraft_ui_egui::state::NewProject { file: Some("a.obj".into()), ..h.state().ui.new_project.clone() }).unwrap(); + assert!(params.get("colorManagement").is_none(), "nothing about color management reaches the command"); +} + +#[test] +fn the_menu_opens_a_fresh_form_after_cancel() { + let mut h = harness(); + { + let form = &mut h.state_mut().ui.new_project; + form.file = Some("/old/mesh.obj".into()); + form.resolution = 4096; + form.uv_tiles = Some(true); + form.import_cameras = false; + } + queue_baked_maps(&mut h); + + h.get_by_role_and_label(Role::Button, "Cancel").click(); + h.run_steps(3); + assert!(!h.state().ui.windows.new_project); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject"); + h.run_steps(3); + + let form = &h.state().ui.new_project; + assert_eq!((form.file.as_deref(), form.resolution, form.uv_tiles, form.import_cameras), (None, 1024, None, true)); + assert_eq!(form.template, DEFAULT_TEMPLATE); + assert!(form.baked_maps.is_empty(), "canceled files stayed queued: {:?}", form.baked_maps); + assert!(h.query_by_label("Ball_normal.png").is_none()); +} + +fn queue_baked_maps(h: &mut Harness<'_, TextureCraftApp>) { + h.state_mut().file_dialogs.set_override(Some(Box::new(|_| { + Answer::Paths(["Ball_normal.png", "Ball_ao.png", "Ball_curvature.png"].into_iter().map(std::path::PathBuf::from).collect()) + }))); + h.get_by_role_and_label(Role::Button, "Add").click(); + h.run_steps(3); + + h.get_by_label("Ball_normal.png"); + h.get_by_label("Ball_ao.png"); + h.get_by_label("Ball_curvature.png"); +} + +#[test] +fn closing_the_form_from_its_title_bar_discards_baked_maps() { + let mut h = harness(); + queue_baked_maps(&mut h); + + h.get_by_role_and_label(Role::Button, "Close window").click(); + h.run_steps(3); + + assert!(!h.state().ui.windows.new_project); + assert!(h.state().ui.new_project.baked_maps.is_empty()); +} + +#[test] +fn invoking_new_project_again_discards_the_open_forms_baked_maps() { + let mut h = harness(); + queue_baked_maps(&mut h); + + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject"); + h.run_steps(3); + + assert!(h.state().ui.windows.new_project); + assert!(h.query_by_label("Ball_normal.png").is_none()); + assert!(h.state().ui.new_project.baked_maps.is_empty()); +} + +#[test] +fn the_supported_settings_reach_the_create_command() { + let mut form = texturecraft_ui_egui::state::NewProject::default(); + + assert!(create_command(&form).is_none(), "no command without a mesh file"); + + form.file = Some("/meshes/robot.fbx".into()); + let params = create_command(&form).unwrap(); + + assert_eq!(params["mesh"], "/meshes/robot.fbx"); + assert_eq!(params["resolution"], 1024); + assert_eq!(params["uvTiles"], false, "UV tiles are off unless ticked"); + assert_eq!(params["importCameras"], true); + assert_eq!(params["template"], DEFAULT_TEMPLATE); + assert!(params.get("name").is_none(), "the project is named after the file"); + + form.uv_tiles = Some(true); + form.import_cameras = false; + form.resolution = 2048; + let params = create_command(&form).unwrap(); + + assert_eq!((params["uvTiles"].as_bool(), params["importCameras"].as_bool(), params["resolution"].as_u64()), (Some(true), Some(false), Some(2048))); +} + +#[test] +fn ticking_uv_tiles_creates_a_uv_tile_project() { + for (tick, expected) in [(false, Vec::::new()), (true, vec![1002])] { + let mut h = harness(); + let dir = TempDir::new("new-project-udim"); + h.state_mut().ui.new_project.file = Some(mesh_file(&dir, TILE_1002_QUAD)); + h.state_mut().ui.new_project.resolution = 128; + h.run_steps(2); + if tick { + h.get_by_role_and_label(Role::CheckBox, "Use UV Tile workflow").click(); + h.run_steps(3); + assert!(!disabled(&h, Role::RadioButton, "Keep UV tiles together per material")); + } + h.get_by_role_and_label(Role::CheckBox, "Import cameras").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + + let app = h.state(); + assert!(!app.ui.windows.new_project, "the window closes"); + assert_eq!(app.session.doc.project.name, "tiles"); + assert_eq!(app.session.doc.project.texture_sets[0].uv_tiles, expected, "UV tiles ticked: {tick}"); + assert_eq!(app.session.doc.project.texture_sets[0].resolution, 128); + } +} + +#[test] +fn create_stays_on_screen_in_a_short_window() { + let h = harness_sized(egui::vec2(1024.0, 600.0)); + + let create = h.get_by_role_and_label(Role::Button, "Create").rect(); + let cancel = h.get_by_role_and_label(Role::Button, "Cancel").rect(); + + assert!(create.bottom() <= 600.0 && create.top() >= 0.0, "Create is visible without scrolling: {create:?}"); + assert!(cancel.bottom() <= 600.0, "{cancel:?}"); +} + +#[test] +fn picking_a_template_sets_its_resolution_and_normal_map_format() { + let mut h = harness(); + h.state_mut().session.templates.dir = None; + h.state_mut().run("textureSet.settings", serde_json::json!({"normalFormat": "directX"})).unwrap(); + h.state_mut().run("project.template.save", serde_json::json!({"name": "Small DirectX"})).unwrap(); + h.run_steps(2); + + h.get_by_value(DEFAULT_TEMPLATE).click(); + h.run_steps(3); + h.get_by_label("Small DirectX").click(); + h.run_steps(3); + + assert!(h.query_by_value("Small DirectX").is_some()); + assert!(h.query_by_value("128 x 128").is_some(), "the template's resolution (the open project's 128 px)"); + assert!(h.query_by_value("DirectX").is_some(), "the template's normal map format"); + assert_eq!(h.state().ui.new_project.resolution, 128); +} + +#[test] +fn create_asks_before_discarding_edits_made_after_the_form_opened() { + let dir = TempDir::new("new-project-unsaved"); + let path = dir.join("tiles.obj"); + let mut h = harness(); + h.state_mut().ui.new_project.file = Some(path.display().to_string()); + h.state_mut().ui.new_project.resolution = 128; + h.state_mut().run("layer.add.paint", serde_json::Value::Null).unwrap(); + h.run_steps(3); + + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + + assert!(h.query_by_label("Unsaved changes").is_some()); + assert_eq!(h.state().session.doc.project.name, "Open"); + + h.get_by_role_and_label(Role::Button, "Don't save").click(); + h.run_steps(3); + + assert!(h.state().ui.windows.new_project); + assert!(h.state().session.modified, "a failed replacement keeps the old project dirty"); + assert_eq!(h.state().session.doc.project.name, "Open"); + + std::fs::write(path, TILE_1002_QUAD).unwrap(); + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Don't save").click(); + h.run_steps(3); + + assert_eq!(h.state().session.doc.project.name, "tiles"); + assert!(!h.state().ui.windows.new_project); +} + +#[test] +fn a_layout_that_closes_new_project_discards_selected_files() { + let mut h = harness(); + queue_baked_maps(&mut h); + let bytes = std::sync::Arc::new(vec![0; 1024 * 1024]); + let buffer = std::sync::Arc::downgrade(&bytes); + let ui = &mut h.state_mut().ui; + ui.new_project.file = Some("reset.obj".into()); + ui.new_project.file_bytes = Some(bytes); + + let mut open_layout = texturecraft_ui_egui::UiState::default(); + open_layout.windows.new_project = true; + ui.adopt_layout(open_layout); + + assert!(ui.windows.new_project); + assert!(buffer.upgrade().is_some()); + assert!(!ui.new_project.baked_maps.is_empty()); + + ui.adopt_layout(texturecraft_ui_egui::UiState::default()); + + assert!(!ui.windows.new_project); + assert!(buffer.upgrade().is_none()); + assert!(ui.new_project.baked_maps.is_empty()); +} diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 49c86c46..1371e05b 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -9,8 +9,7 @@ use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; -mod temp_dir; -use temp_dir::TempDir; +use super::temp_dir::TempDir; const QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n"; const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"; @@ -136,20 +135,95 @@ fn every_setting_has_an_info_icon_and_the_window_ends_with_a_note() { let icons: Vec<_> = h.get_all_by_label(egui_phosphor::regular::INFO).collect(); let tip = "Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it."; - assert!(h.query_by_label("Choosing or reimporting a mesh recomputes all channels.").is_some(), "the note above the buttons"); - assert_eq!(icons.len(), 6, "mesh path, Select, Reimport mesh, Preserve strokes, Normal map format, UV tiles"); + assert!(h.query_by_label("Changing the mesh or normal format can recalculate texture channels.").is_some(), "the note above the buttons"); + assert_eq!( + icons.len(), + 13, + "3D mesh, Reimport mesh, Normal map format, tangent space, UV tiles and its two layouts, Import cameras, Preserve strokes, Auto-unwrap, \ + Physical size, Color management, Working color space" + ); assert!(h.query_by_label(tip).is_none(), "no tooltip before hovering"); - // The format icon is fifth in the window's rows + // The format icon is third in the window's rows let mut centers: Vec<_> = icons.iter().map(|n| n.rect().center()).collect(); centers.sort_by(|a, b| a.y.total_cmp(&b.y)); - let format_center = centers[4]; + let format_center = centers[2]; h.hover_at(format_center); h.run_steps(30); assert!(h.query_by_label(tip).is_some(), "hovering the normal map format icon explains it"); } +#[test] +fn the_window_follows_the_reference_layout() { + let dir = temp_dir("layout"); + let mut h = app_on_a_quad(&dir); + h.set_size(egui::vec2(1600.0, 2000.0)); + + open_window(&mut h); + + let order = [ + "3D MESH", + "Reimport mesh", + "PROJECT SETTINGS", + "Compute tangent space per fragment", + "UV Tile settings (UDIMs)", + "Change the UV tiles of a texture set in Texture Set Settings", + "Use UV Tile workflow", + "Use a separate texture set for each tile", + "Import settings", + "Import cameras", + "Preserve stroke positions on mesh", + "Auto-unwrap", + "Physical size", + "Working color space", + ]; + let top = |label: &str| h.get_all_by_label(label).map(|n| n.rect().top()).fold(f32::INFINITY, f32::min); + for labels in order.windows(2) { + assert!(top(labels[0]) < top(labels[1]), "{} comes before {}", labels[0], labels[1]); + } + assert!(h.query_by_label("Custom unit scale").is_none(), "Physical size starts collapsed"); + let disabled = |role: Role, label: &str| h.get_by_role_and_label(role, label).accesskit_node().is_disabled(); + for (role, label) in [ + (Role::CheckBox, "Compute tangent space per fragment"), + (Role::CheckBox, "Use UV Tile workflow"), + (Role::RadioButton, "Keep UV tiles together per material"), + (Role::RadioButton, "Use a separate texture set for each tile"), + (Role::CheckBox, "Import cameras"), + (Role::CheckBox, "Auto-unwrap"), + (Role::Button, "Auto-unwrap options"), + ] { + assert!(disabled(role, label), "{label} is disabled"); + } + + let center = h.get_by_role_and_label(Role::CheckBox, "Compute tangent space per fragment").rect().center(); + h.hover_at(center); + h.run_steps(30); + assert!(h.query_by_label("Not available yet").is_some(), "the hint of a setting TextureCraft does not have yet"); +} + +#[test] +fn opencolorio_can_be_looked_at_but_changes_nothing() { + let dir = temp_dir("ocio"); + let mut h = app_on_a_quad(&dir); + h.set_size(egui::vec2(1600.0, 2000.0)); + open_window(&mut h); + let before = h.state().session.doc.project.clone(); + + h.get_by_value("Legacy").click(); + h.run_steps(3); + h.get_by_label("OpenColorIO").click(); + h.run_steps(3); + + assert!(h.query_by_label("Bitmap import color space defaults").is_some()); + assert!(h.query_by_label("Export color spaces").is_some()); + + click(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.doc.project, before, "OK applies nothing for color management"); +} + #[test] fn another_file_shows_its_path_and_ticks_reimport() { let dir = temp_dir("select"); @@ -553,8 +627,9 @@ fn uv_tiles_are_shown_read_only() { open_window(&mut h); assert!(h.query_by_label("UV Tile settings (UDIMs)").is_some()); - assert!(h.query_by_label("No UV tiles").is_some(), "a project without UV tiles"); - assert!(h.query_by_label("Change them in Texture Set Settings").is_some()); + hover_uv_tile_box(&mut h); + assert!(h.query_by_label_contains("No UV tiles").is_some(), "a project without UV tiles"); + assert!(h.query_by_label("Change the UV tiles of a texture set in Texture Set Settings").is_some()); click(&mut h, Role::Button, "Cancel"); @@ -562,8 +637,16 @@ fn uv_tiles_are_shown_read_only() { open_window(&mut h); - assert!(h.query_by_label("No UV tiles").is_none()); - assert!(h.query_by_label("1001").is_some(), "the tile list of a UDIM project"); + hover_uv_tile_box(&mut h); + assert!(h.query_by_label_contains("No UV tiles").is_none()); + assert!(h.query_by_label_contains("1001").is_some(), "the tile list of a UDIM project"); +} + +/// Hover the disabled Use UV Tile workflow box, whose hint lists the project's UV tiles. +fn hover_uv_tile_box(h: &mut Harness<'_, TextureCraftApp>) { + let center = h.get_by_role_and_label(Role::CheckBox, "Use UV Tile workflow").rect().center(); + h.hover_at(center); + h.run_steps(30); } #[test] @@ -720,3 +803,29 @@ fn a_format_the_project_already_has_is_not_set_again() { assert_eq!(project_normal_format(&h), NormalFormat::DirectX); assert_eq!(h.state().session.history_labels().len(), steps, "no extra undo step"); } + +#[test] +#[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"] +fn project_config_snapshots() { + let output_dir = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&output_dir).unwrap(); + let dir = temp_dir("snapshots"); + let file = dir.join("quad.obj"); + std::fs::write(&file, QUAD).unwrap(); + let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap(); + session.doc.project.mesh_path = file.display().to_string(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(6); + open_window(&mut h); + h.run_steps(6); + h.render().unwrap().save(output_dir.join("project-config-legacy.png")).unwrap(); + h.get_by_value("Legacy").scroll_to_me(); + h.run_steps(3); + h.get_by_value("Legacy").click(); + h.run_steps(3); + h.get_by_label("OpenColorIO").click(); + h.run_steps(3); + h.get_by_label("Export color spaces").scroll_to_me(); + h.run_steps(6); + h.render().unwrap().save(output_dir.join("project-config-ocio.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/project_config/temp_dir.rs b/crates/ui-egui/tests/it/temp_dir.rs similarity index 66% rename from crates/ui-egui/tests/it/project_config/temp_dir.rs rename to crates/ui-egui/tests/it/temp_dir.rs index 1c3ab71d..1f112493 100644 --- a/crates/ui-egui/tests/it/project_config/temp_dir.rs +++ b/crates/ui-egui/tests/it/temp_dir.rs @@ -1,12 +1,16 @@ use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; /// A test folder removed when its owner drops pub(super) struct TempDir(PathBuf); impl TempDir { pub(super) fn new(test: &str) -> Self { - let path = std::env::temp_dir().join(format!("texturecraft-project-config-{test}-{}", std::process::id())); - std::fs::create_dir_all(&path).unwrap(); + static NEXT_ID: AtomicU64 = AtomicU64::new(0); + + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!("texturecraft-{test}-{}-{id}", std::process::id())); + std::fs::create_dir(&path).unwrap(); Self(path) } diff --git a/docs/features.md b/docs/features.md index 57f28206..19b63553 100644 --- a/docs/features.md +++ b/docs/features.md @@ -88,6 +88,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA the brush's material: the next stroke paints its pattern (colour, metallic, roughness, height), fixed to the surface and sized with the brush. A click on a smart material, which is several layers, only highlights it; drag it to add its layers. +- **Import resources:** *File › Import resources...* opens a window: *Add resources* (images and + materials), an optional name prefix and a role for each image. Environment images light the scene, + and alpha images become the brush alpha. Filter by role or remove selected rows before importing. + Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are + unavailable. The browser imports images straight from its file picker. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. *Create smart mask* in the same menu saves just the layer's mask (all its effects, painted pixels and images); it appears under @@ -104,14 +109,23 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA ## Files and texture sets - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, - OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers + OBJ, PLY and STL, or a built-in mesh (the `project.new` command; *File › Open sample project...* opens the + material ball); UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. Reimport a changed mesh and your painted strokes stay on the surface. The `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. **Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. *Import settings* decides whether painted strokes follow the surface (on by default), and PROJECT SETTINGS sets the project's normal map format and - lists its UV tiles (read only; Texture Set Settings changes them). + shows its UV tiles in the UV workflow tooltip. Edit the tiles in Texture Set Settings. + Physical size and color management show the same settings as New project. +- **File › New project...** opens a setup form with BASIC SETTINGS (*Select...* a mesh file, + the project template, the document resolution; Create waits for a mesh) and ADVANCED SETTINGS (normal + map format, *Use UV Tile workflow*, *Import cameras*, *Import baked maps*, physical size, color + management). The project is named after the mesh file. Settings TextureCraft does not have yet + (tangent space per fragment, UV tiles as separate texture sets, turning auto-unwrap off and its + options, a custom unit scale, OpenColorIO) are shown disabled with a hint; projects use Legacy color + management. In the browser, *Select...* opens the browser's file picker. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 622852ba..e8ed4ba3 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -63,6 +63,13 @@ The relevant implementations are [layer rows, menus and fill/brush editors](../c | UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart. Since then: the Layers toolbar stays on one row at 1280 × 800 (its channel box shrinks), and a cut-short layer name or type shows in full on hover. Properties scrolling and restart persistence are unchanged | | UI-14 | Assets panel filters | **UI + source.** The type dropdown lists the reference entries in its order, Fonts and Show all included. Saved searches and Filter by path are separate scrollable panes with a divider that supports pointer and keyboard resizing and saves its position with the UI state ([#640](https://github.com/storytold/texturecraft/issues/640)). Fonts, the built-in saved searches Favorites, 3D Assets and Flattened layers, and the System fonts and User fonts libraries are listed but greyed with "Not available yet" | Give fonts, favorites, 3D assets and flattened layers real assets, then enable those rows and check that each one filters the grid | +File > Import resources ([#638](https://github.com/storytold/texturecraft/issues/638)) queues +images and materials for the open project. Images support a name prefix and a usage. Texture +and undefined usages store the image, while environment and alpha also apply it to the scene +or brush. Filter the list by usage or remove rows before importing. Color LUT, post effects +and asset-library import remain unavailable. The browser imports images straight from its file +picker. + Broader properties/filter work remains tracked in [#433](https://github.com/storytold/texturecraft/issues/433). Its individual rows need checking against current code; an open issue is not proof that every control it lists is still missing. @@ -74,7 +81,7 @@ list, not a feature-completion denominator. | Check | Surface | Result | Observable evidence / limit | |---|---|---|---| -| F01 New project | UI | Pass | Ctrl+N, built-in Cube, 1024 px, Create produced a new project with one empty paint layer. The native mesh-file selection path was not completed in this deeper pass | +| F01 New project | UI | Pass (tests) | The window no longer offers built-in meshes ([#636](https://github.com/storytold/texturecraft/issues/636)). `tests/it/new_project_window.rs` covers the section order, the defaults, the disabled settings and their hint, Create waiting for a mesh file, and a UV tile project created from a mesh file. A manual pass with the native file picker is still to do | | F02 Paint in 3D | UI | Pass | A mouse drag produced a visible stroke in 3D and its UV representation; inspection showed a Paint stroke undo step and painted tiles | | F03 Paint in 2D | UI | Pass | A separate UV-view drag increased painted tiles from 7 to 21 per active channel and changed the visible image | | F04 Undo and redo | UI | Pass | Ctrl+Z restored 7 tiles and history depth 2; Ctrl+Y restored 21 tiles and depth 3 |