diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 51ac774f..61714f01 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -100,7 +100,15 @@ "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", "trust": { "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" - } + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] }, "macos-aarch64": { "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", diff --git a/Cargo.lock b/Cargo.lock index b8d1d044..01e17558 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6118,6 +6118,7 @@ dependencies = [ "harfrust 0.12.0", "rayon", "serde", + "serde_json", "skrifa 0.44.0", "texturecraft-compose", "texturecraft-core", diff --git a/apps/texturecraft-cli/src/args.rs b/apps/texturecraft-cli/src/args.rs index 64373804..549d8b0c 100644 --- a/apps/texturecraft-cli/src/args.rs +++ b/apps/texturecraft-cli/src/args.rs @@ -48,7 +48,7 @@ pub(crate) enum Command { /// /// --camera looks through a camera saved in the project (camera.add); --samples path traces it /// instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on - /// the CPU. + /// the CPU (no GPU needed). #[command(after_help = INPUTS)] Render(RenderArgs), /// A new project from a mesh or a built-in mesh diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index a5089e96..0d838118 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -184,6 +184,34 @@ fn render_writes_a_png() { let _ = std::fs::remove_dir_all(&d); } +/// Without a GPU, the viewport render's error says what still works, and that does work. A backend +/// this platform lacks stands in for a machine without a GPU: the CLI's wgpu instance reads +/// `WGPU_BACKEND`. +#[test] +fn render_without_a_gpu_points_to_path_tracing() { + let d = tmp("no-gpu"); + let out = d.join("cube.png"); + let absent = if cfg!(target_os = "macos") { "dx12" } else { "metal" }; + let render = |extra: &[&str]| { + Command::new(cli_binary()) + .env("WGPU_BACKEND", absent) + .env_remove("WGPU_ADAPTER_NAME") + .env_remove("WGPU_POWER_PREF") + .args(["render", "builtin:cube", p(&out), "--size", "64x64"]) + .args(extra) + .output() + .unwrap() + }; + let o = render(&[]); + let err = String::from_utf8_lossy(&o.stderr); + assert_eq!(o.status.code(), Some(1), "{err}"); + assert!(err.contains("cannot render") && err.contains("path tracing (`samples`) needs no GPU"), "{err}"); + let o = render(&["--samples", "2"]); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + assert_eq!(image::open(&out).unwrap().width(), 64); + let _ = std::fs::remove_dir_all(&d); +} + #[test] fn path_traced_render_needs_no_gpu() { let d = tmp("trace"); diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 7eaed255..e536444e 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -401,7 +401,7 @@ impl Headless { let gpu = match self.gpu.get_or_insert_with(Gpu::new) { Ok(g) => g, - Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}"))), + Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}; path tracing (`samples`) needs no GPU"))), }; // Last-resort guard: wgpu panics on device errors; drop the device and report instead diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 5fbff34d..e07c2551 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -124,8 +124,9 @@ impl Headless { } } -/// Answer one request line. A panic inside a command becomes an error reply (edits run on a -/// snapshot, so the session stays consistent). +/// Answer one request line. A panic inside a command becomes an error reply. `Session::edit` +/// rolls the document back on unwind, but work outside it (scripted strokes) and other session +/// state, such as the selection or tool, is not rolled back. pub fn respond(h: &Mutex, line: &str) -> Value { let req: Value = match serde_json::from_str(line) { Ok(v) => v, diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index f2ebfee6..3b71dbd2 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -338,8 +338,9 @@ impl TexturecraftMcp { match &*self.backend { Backend::Headless(h) => { let (h, m) = (h.clone(), method.to_string()); - // A panicking command poisons the lock, but edits run on a document snapshot - // (`Session::edit`), so the session stays consistent: keep serving. + // A panicking command poisons the lock: keep serving. `Session::edit` rolls the + // document back on unwind, but work outside it (scripted strokes) and other + // session state, such as the selection or tool, is not rolled back. tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p)) .await .unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`")))) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 52184129..07936750 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -67,6 +67,9 @@ const MIN_BOUNDS_EXTENT: f32 = 1e-6; /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; +/// What the live stroke's stencil lets through at a texel ([`Stencil::paint_world`]) +type StencilPaint = Option<(Option<[f32; 3]>, f32)>; + /// How tall a baked height of 1 stands, as a fraction of a UV tile, when Baked Lighting Stylized tilts normals by its slope const HEIGHT_RELIEF: f32 = 1.0 / 32.0; @@ -82,39 +85,66 @@ pub enum PaintTarget { Mask(LayerId), } -/// A screen-pinned image painted through the camera (projection tool / stencil). +/// Smallest clip w a stencil paints at and smallest half extent it divides by +const STENCIL_EPSILON: f32 = 1e-6; + +/// Rec. 709 red, green and blue weights of a gray's luminance +const REC709_LUMINANCE_WEIGHTS: [f32; 3] = [0.2126, 0.7152, 0.0722]; + +/// A screen-pinned image every brush tool paints through #[derive(Clone, Debug)] pub struct Stencil { pub image: std::sync::Arc, - /// Camera view-projection captured when the stroke started. + /// Camera view-projection captured when the stroke started pub view_proj: texturecraft_geom::glam::Mat4, - /// Image placement in normalized device coordinates: center, half extents, rotation. + /// Image placement in normalized device coordinates: center, half extents, rotation pub center: [f32; 2], pub half: [f32; 2], pub rotation: f32, - /// Repeat the image beyond its bounds (otherwise nothing is painted outside it). + /// Repeat the image beyond its bounds (otherwise nothing is painted outside it) pub tile: bool, + /// The Projection tool paints the image's colors; every other tool paints through its gray + pub colors: bool, } impl Stencil { - /// Linear color and alpha of the stencil at world point `p` (None outside the image). - pub fn sample_world(&self, p: Vec3) -> Option<([f32; 3], f32)> { - let c = self.view_proj * p.extend(1.0); - if c.w <= 1e-6 { + /// Linear color and alpha of the stencil at world point `point` (None outside the image) + pub fn sample_world(&self, point: Vec3) -> Option<([f32; 3], f32)> { + let sample = self.sample_raw(point)?; + let rgb = [sample[0], sample[1], sample[2]]; + let rgb = if self.image.srgb { rgb.map(texturecraft_texel::srgb_to_linear) } else { rgb }; + Some((rgb, sample[3].clamp(0.0, 1.0))) + } + + /// How much paint passes at world point `point` when the stencil masks a stroke: its gray times its alpha, read as stored like a brush alpha image (0 outside the image) + pub fn mask_world(&self, point: Vec3) -> f32 { + let Some([red, green, blue, alpha]) = self.sample_raw(point) else { return 0.0 }; + let [red_weight, green_weight, blue_weight] = REC709_LUMINANCE_WEIGHTS; + ((red_weight * red + green_weight * green + blue_weight * blue) * alpha).clamp(0.0, 1.0) + } + + /// The paint a stroke receives at world point `point`: the stencil's color (Projection only) and the factor scaling the stroke there, None where nothing is painted + pub fn paint_world(&self, point: Vec3) -> Option<(Option<[f32; 3]>, f32)> { + if self.colors { self.sample_world(point).map(|(color, alpha)| (Some(color), alpha)) } else { Some((None, self.mask_world(point))) } + } + + /// The stored image value under world point `point` (None outside the image) + fn sample_raw(&self, point: Vec3) -> Option<[f32; 4]> { + let clip = self.view_proj * point.extend(1.0); + if clip.w <= STENCIL_EPSILON { return None; } - let (dx, dy) = (c.x / c.w - self.center[0], c.y / c.w - self.center[1]); - let (sn, cs) = (-self.rotation).sin_cos(); - let lx = (dx * cs - dy * sn) / self.half[0].max(1e-6); - let ly = (dx * sn + dy * cs) / self.half[1].max(1e-6); - if !self.tile && (lx.abs() > 1.0 || ly.abs() > 1.0) { + let offset_x = clip.x / clip.w - self.center[0]; + let offset_y = clip.y / clip.w - self.center[1]; + let (sine, cosine) = (-self.rotation).sin_cos(); + let local_x = (offset_x * cosine - offset_y * sine) / self.half[0].max(STENCIL_EPSILON); + let local_y = (offset_x * sine + offset_y * cosine) / self.half[1].max(STENCIL_EPSILON); + if !self.tile && (local_x.abs() > 1.0 || local_y.abs() > 1.0) { return None; } - let s = self.image.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5); - let rgb = if self.image.srgb { [s[0], s[1], s[2]].map(texturecraft_texel::srgb_to_linear) } else { [s[0], s[1], s[2]] }; - Some((rgb, s[3].clamp(0.0, 1.0))) + Some(self.image.sample(local_x * 0.5 + 0.5, 0.5 - local_y * 0.5)) } } @@ -3015,6 +3045,8 @@ struct Texel<'a, 'b> { tape: Tape<'b>, /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip copy: Option<(usize, FillCopy)>, + /// The live stroke's stencil sampled here once for every channel (None until a channel reads it) + stencil_paint: Option, } /// What a layer contributes (its mask, its content value and coverage per channel): evaluated @@ -3050,7 +3082,22 @@ type ChannelContents = [Option<([f32; 3], f32)>; NCH]; impl<'a, 'b> Texel<'a, 'b> { fn new(inp: &'b Inputs<'a>, x: u32, y: u32, o: usize, stroke: f32) -> Self { - Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), below: None, lit: None, tape: Tape::Off, copy: None } + Texel { + inp, + x, + y, + o, + res: inp.gbuf.width, + coords: None, + stroke, + stop: None, + anchors: Vec::new(), + below: None, + lit: None, + tape: Tape::Off, + copy: None, + stencil_paint: None, + } } /// Run `f` with `tape` as this texel's tape. @@ -3193,6 +3240,24 @@ impl<'a, 'b> Texel<'a, 'b> { self.surface((self.y * self.inp.gbuf.width + self.x) as usize).map(|s| s.pos) } + /// What the live stroke's `stencil` lets through here, sampled once for all of the texel's channels + fn stencil_paint(&mut self, stencil: &Stencil) -> StencilPaint { + let sample = |texel: &Self| texel.world().and_then(|world| stencil.paint_world(world)); + + // A symmetric fill's copy sees another surface point, so only the texel's own sample is kept + if self.copy.is_some() { + return sample(self); + } + + if let Some(paint) = self.stencil_paint { + return paint; + } + + let paint = sample(self); + self.stencil_paint = Some(paint); + paint + } + /// The surface at G-buffer index `i`, as the fill copy being sampled sees it #[inline(always)] fn surface(&self, i: usize) -> Option { @@ -3897,7 +3962,7 @@ impl<'a, 'b> Texel<'a, 'b> { self.mask_effects(plan, value, skip, plan.effects.len()) } - /// Mask effects `from..to` of `plan` over `value`, recording the anchors among them. + /// Mask effects `from..to` of `plan` over `value`, recording the anchors among them fn mask_effects(&mut self, plan: &MaskPlan, mut value: f32, from: usize, to: usize) -> f32 { // Avoid amplifying rounding error when unpremultiplying faint paint const MIN_PAINT_COVERAGE: f32 = 1e-5; @@ -3915,10 +3980,19 @@ impl<'a, 'b> Texel<'a, 'b> { Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), }; + if effect.preview && let Some(preview) = self.inp.preview { - let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + let mut stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + + // The stencil shapes the stroke as the commit does + if let Some(stencil) = preview.stencil.as_ref() + && stroke > 0.0 + { + stroke *= self.stencil_paint(stencil).map_or(0.0, |(_, factor)| factor); + } + if preview.erase { painted *= 1.0 - stroke; coverage *= 1.0 - stroke; @@ -3932,6 +4006,7 @@ impl<'a, 'b> Texel<'a, 'b> { coverage = stroke + coverage * (1.0 - stroke); } } + if coverage > 0.0 { let layer_value = painted / coverage.max(MIN_PAINT_COVERAGE); value += (blend1(effect.blend, value, layer_value) - value) * coverage * opacity; @@ -4271,62 +4346,66 @@ impl<'a, 'b> Texel<'a, 'b> { (coverage > 0.0).then_some((value, coverage.min(1.0))) } - /// Straight value and coverage of painted data of one channel (premultiplied values plus - /// coverage per texel), with the live stroke when `preview`. - fn painted(&mut self, data: Option<&[u16]>, c: &ChanPlan, preview: bool) -> ([f32; 3], f32) { - let pv = if preview { self.inp.preview } else { None }; - let mut sa = pv.map(|p| (self.stroke * p.opacity).clamp(0.0, 1.0)).unwrap_or(0.0); + /// Straight value and coverage of one channel's painted data (premultiplied values plus coverage per texel), with the live stroke when `preview` + fn painted(&mut self, data: Option<&[u16]>, chan_plan: &ChanPlan, preview: bool) -> ([f32; 3], f32) { + // Coverage floor the premultiplied value is divided by + const MIN_COVERAGE: f32 = 1e-5; - // Projection: the stencil's alpha shapes the stroke and its color is the base color - let stencil = match pv.and_then(|p| p.stencil.as_ref()) { - Some(st) if sa > 0.0 => { - let s = self.world().and_then(|w| st.sample_world(w)); - sa *= s.map(|(_, a)| a).unwrap_or(0.0); - s.map(|(c, _)| c) + let stroke_preview = if preview { self.inp.preview } else { None }; + let mut stroke_alpha = stroke_preview.map(|stroke| (self.stroke * stroke.opacity).clamp(0.0, 1.0)).unwrap_or(0.0); + + // The stencil shapes the stroke; on the Projection tool its color is the base color + let stencil_color = match stroke_preview.and_then(|stroke| stroke.stencil.as_ref()) { + Some(stencil) if stroke_alpha > 0.0 => { + let stencil_paint = self.stencil_paint(stencil); + stroke_alpha *= stencil_paint.map(|(_, factor)| factor).unwrap_or(0.0); + stencil_paint.and_then(|(color, _)| color) } _ => None, }; - let mut val = [0.0f32; 3]; - let mut cov = 0.0f32; - if let Some(d) = data { - let base = self.o * (c.comps + 1); - for (k, slot) in val.iter_mut().take(c.comps).enumerate() { - *slot = decode(c.kind, d.get(base + k).copied().unwrap_or(0)); + + let mut value = [0.0f32; 3]; + let mut coverage = 0.0f32; + if let Some(texels) = data { + let base = self.o * (chan_plan.comps + 1); + for (component, slot) in value.iter_mut().take(chan_plan.comps).enumerate() { + *slot = decode(chan_plan.kind, texels.get(base + component).copied().unwrap_or(0)); } - cov = from_u16(d.get(base + c.comps).copied().unwrap_or(0)); + coverage = from_u16(texels.get(base + chan_plan.comps).copied().unwrap_or(0)); } - if let Some(p) = pv - && sa > 0.0 + + if let Some(stroke) = stroke_preview + && stroke_alpha > 0.0 { - if p.erase { - val = val.map(|v| v * (1.0 - sa)); - cov *= 1.0 - sa; - } else if let Some(ch) = Channel::ALL.get(c.ch) - && let Some(pval) = p.values.get(ch) + if stroke.erase { + value = value.map(|component| component * (1.0 - stroke_alpha)); + coverage *= 1.0 - stroke_alpha; + } else if let Some(channel) = Channel::ALL.get(chan_plan.ch) + && let Some(stroke_value) = stroke.values.get(channel) { - let pval = match stencil { - Some(col) if *ch == Channel::BaseColor => col, - _ => match p.carried.get(ch) { - Some(img) => { - let raw = img.get(self.x, self.y).map(|v| decode(c.kind, v)); + let stroke_value = match stencil_color { + Some(color) if *channel == Channel::BaseColor => color, + _ => match stroke.carried.get(channel) { + Some(carried) => { + let raw = carried.get(self.x, self.y).map(|stored| decode(chan_plan.kind, stored)); [raw[0], raw[1], raw[2]] } - None => *pval, + None => *stroke_value, }, }; - for k in 0..c.comps { - val[k] = pval[k] * sa + val[k] * (1.0 - sa); + for component in 0..chan_plan.comps { + value[component] = stroke_value[component] * stroke_alpha + value[component] * (1.0 - stroke_alpha); } - cov = sa + cov * (1.0 - sa); + coverage = stroke_alpha + coverage * (1.0 - stroke_alpha); } } - if cov <= 0.0 { + if coverage <= 0.0 { return ([0.0; 3], 0.0); } - let inv = 1.0 / cov.max(1e-5); - let v = if c.comps == 3 { val.map(|x| x * inv) } else { [val[0] * inv; 3] }; - (v, cov.min(1.0)) + let inverse_coverage = 1.0 / coverage.max(MIN_COVERAGE); + let straight = if chan_plan.comps == 3 { value.map(|component| component * inverse_coverage) } else { [value[0] * inverse_coverage; 3] }; + (straight, coverage.min(1.0)) } /// Apply one content effect to a channel's straight value and coverage diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 73a4317e..1e28b781 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -313,7 +313,8 @@ fn save_source(_: &mut Session, _: &Value) -> Result { Err(EngineError::Other("file paths are not available in the browser".into())) } -/// A MaterialCraft executable: `$`, else next to this program, else `name` on `PATH`. +/// A MaterialCraft executable: `$`, else next to this program, else in the sibling +/// `MaterialCraft` folder (the launcher's layout), else `name` on `PATH`. #[cfg(not(target_arch = "wasm32"))] pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf { if let Some(p) = std::env::var_os(env).filter(|p| !p.is_empty()) { @@ -321,7 +322,18 @@ pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf { } let exe = format!("{name}{}", std::env::consts::EXE_SUFFIX); - std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join(&exe))).filter(|p| p.is_file()).unwrap_or_else(|| exe.into()) + let app_dir = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf)); + app_dir.and_then(|d| find_installed_tool(&d, &exe)).unwrap_or_else(|| exe.into()) +} + +/// `exe` in `app_dir` (next to this program), else in the sibling `MaterialCraft` folder beside `app_dir` +/// (`/TextureCraft` and `/MaterialCraft`, as the ArtCraft Launcher installs them). `None` if neither has it. +/// Versioned `//` layouts and macOS `.app` bundles are not searched. +#[cfg(not(target_arch = "wasm32"))] +fn find_installed_tool(app_dir: &std::path::Path, exe: &str) -> Option { + let beside = app_dir.join(exe); + let sibling = app_dir.parent().map(|root| root.join("MaterialCraft").join(exe)); + std::iter::once(beside).chain(sibling).find(|p| p.is_file()) } /// A command for a MaterialCraft executable that opens no console window. @@ -335,12 +347,15 @@ fn quiet(program: &std::path::Path) -> std::process::Command { } /// Open `package` (a published material or authoring package) in the MaterialCraft app (`$MATERIALCRAFT`, next to this -/// program, or on `PATH`). +/// program, in the sibling `MaterialCraft` folder, or on `PATH`). #[cfg(not(target_arch = "wasm32"))] pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { let app = materialcraft_tool("materialcraft", "MATERIALCRAFT"); quiet(&app).arg(package).spawn().map(drop).map_err(|e| { - EngineError::Other(format!("MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT", app.display())) + EngineError::Other(format!( + "MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT", + app.display() + )) }) } @@ -775,6 +790,70 @@ mod tests { assert!(typed(&p, &json!("#ff8000")).is_some()); } + #[cfg(not(target_arch = "wasm32"))] + fn touch(dir: &std::path::Path, exe: &str) -> std::path::PathBuf { + std::fs::create_dir_all(dir).unwrap(); + let p = dir.join(exe); + std::fs::write(&p, b"").unwrap(); + p + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn launcher_layout_finds_the_sibling_materialcraft_folder() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + std::fs::create_dir_all(&app).unwrap(); + let tool = touch(&root.path().join("MaterialCraft"), "materialcraft-cli"); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(tool)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_tool_beside_the_program_wins_over_the_sibling_folder() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + let beside = touch(&app, "materialcraft-cli"); + touch(&root.path().join("MaterialCraft"), "materialcraft-cli"); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(beside)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_missing_tool_is_none_so_the_caller_falls_back_to_path() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + std::fs::create_dir_all(root.path().join("MaterialCraft")).unwrap(); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_named_like_the_tool_is_not_the_tool() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + std::fs::create_dir_all(app.join("materialcraft-cli")).unwrap(); + std::fs::create_dir_all(root.path().join("MaterialCraft").join("materialcraft-cli")).unwrap(); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_app_folder_with_no_parent_does_not_panic() { + // The root (or an empty path) has no parent: only the beside-the-program step can apply. + assert_eq!(super::find_installed_tool(std::path::Path::new(""), "no-such-materialcraft-tool"), None); + let root = std::env::temp_dir().ancestors().last().map(std::path::Path::to_path_buf).unwrap_or_default(); + assert_eq!(super::find_installed_tool(&root, "no-such-materialcraft-tool"), None); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_missing_app_folder_is_none() { + let root = tempfile::tempdir().unwrap(); + let gone = root.path().join("nowhere").join("TextureCraft"); + assert_eq!(super::find_installed_tool(&gone, "materialcraft-cli"), None); + } + #[cfg(not(target_arch = "wasm32"))] fn scratch(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("tc_handoff_{name}_{}", std::process::id())); diff --git a/crates/engine/src/link_cmds/link_job.rs b/crates/engine/src/link_cmds/link_job.rs index 145be0e3..ceb350da 100644 --- a/crates/engine/src/link_cmds/link_job.rs +++ b/crates/engine/src/link_cmds/link_job.rs @@ -120,7 +120,7 @@ fn run_bounded(command: &std::process::Command, stdout: &Path, stderr: &Path, re .stdout(std::fs::File::create(stdout).map_err(io)?) .stderr(std::fs::File::create(stderr).map_err(io)?) .spawn() - .map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft or set MATERIALCRAFT_CLI")))?; + .map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT_CLI")))?; loop { if canceled.load(Ordering::Relaxed) { diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 8a5d9a57..4f29a4c2 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -217,15 +217,17 @@ impl Session { .collect() } - /// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh - /// (the Clone tool's destination anchor). + /// Common setup of 3D and 2D strokes, `first_uv` being where the stroke starts on the mesh (the Clone tool's destination anchor) fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option) -> Result<()> { + // Texture size a stroke paints at before the texture set has a cache + const FALLBACK_TEXTURE_SIZE: (u32, u32) = (1024, 1024); + self.refuse_while_baking()?; let tool = self.tool.tool; let erase = tool == Tool::Eraser; let quick_mask = self.quick_mask.editing; let ts = self.ts(); - let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); + let size = self.caches.get(ts).map_or(FALLBACK_TEXTURE_SIZE, |cache| cache.size); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; let composite_pickup = tool == Tool::Smudge || (tool == Tool::Clone && self.tool.clone_from == CloneFrom::Composite); if pickup.is_some() && composite_pickup && !self.paints_mask() && self.solo.is_none() { @@ -240,26 +242,30 @@ impl Session { } _ => None, }; + let before = self.doc.clone(); let target = if quick_mask { None } else { match self.paint_target() { - Ok(t) => Some(t), - Err(e) => { + Ok(target) => Some(target), + Err(error) => { self.doc = before; - return Err(e); + return Err(error); } } }; - let values = target.map(|t| self.stroke_values(t)).unwrap_or_default(); + + let values = target.map(|target| self.stroke_values(target)).unwrap_or_default(); // Clone and smudge on a mask read the mask as it was before the stroke let mask_owner = match target { Some(PaintTarget::Mask(effect)) if pickup.is_some() => self.doc.project.effect(effect).map(|(owner, _)| owner), _ => None, }; - let stencil = if tool == Tool::Projection && !quick_mask { self.capture_stencil(viewport) } else { None }; + + // The 2D view doesn't show the stencil, so there it shapes only the Projection tool + let stencil = if !quick_mask && tool.uses_stencil() && (tool == Tool::Projection || !uv_mode) { self.capture_stencil(viewport) } else { None }; let problem = if !erase && values.is_empty() && matches!(target, Some(PaintTarget::Layer(_))) { Some("no channel enabled to paint: enable channels in the tool's material") } else if tool == Tool::Projection && !quick_mask && stencil.is_none() && !uv_mode { @@ -267,9 +273,10 @@ impl Session { } else { None }; - if let Some(msg) = problem { + + if let Some(message) = problem { self.doc = before; - return Err(EngineError::Other(msg.into())); + return Err(EngineError::Other(message.into())); } let depth = (!uv_mode).then(|| self.eye_depth(viewport)); @@ -278,6 +285,7 @@ impl Session { if !quick_mask { canvas.limit = self.stroke_limit(ts, size); } + if let Some((mode, offset)) = pickup && let Some(cache) = self.caches.get(ts) { @@ -285,7 +293,7 @@ impl Session { PickupMode::Clone { .. } => { PickupMode::Clone { offset: [(offset[0] * size.0 as f32).round() as i64, (offset[1] * size.1 as f32).round() as i64] } } - m => m, + other_mode => other_mode, }; let mut pickup = match (&layer_source, mask_owner) { // On a mask the stroke reads the mask's own values @@ -317,20 +325,23 @@ impl Session { canvas.pickup = Some(pickup); if tool == Tool::Clone && self.tool.clone_aligned - && let Some(src) = self.tool.clone_source.as_mut() + && let Some(clone_source) = self.tool.clone_source.as_mut() { - src.offset.get_or_insert(offset); + clone_source.offset.get_or_insert(offset); } } + if canvas.pickup.is_none() && tool == Tool::Paint && matches!(target, Some(PaintTarget::Layer(_))) { canvas.pickup = self.brush_pattern(&values); } + let label = if quick_mask { QUICK_MASK_STROKE_LABEL.to_string() } else { let on_mask = matches!(target, Some(PaintTarget::Mask(_))); history_label(stroke_template(tool, on_mask), &self.stroke_layer_name()) }; + self.stroke = Some(ActiveStroke { ts, target, @@ -345,6 +356,7 @@ impl Session { erase, stencil, before, + start_revision: self.revision, label, staging: Staging::default(), }); @@ -394,13 +406,14 @@ impl Session { } } - /// The stencil placed for the current camera and viewport. + /// The stencil placed for the current camera and viewport fn capture_stencil(&self, viewport: Vec2) -> Option { - let st = self.tool.stencil.as_ref()?; - let image = self.images.get(&st.image)?.clone(); + let stencil_state = self.tool.stencil.as_ref()?; + let image = self.images.get(&stencil_state.image)?.clone(); let aspect = viewport.x.max(1.0) / viewport.y.max(1.0); - let (center, half, rotation) = st.placement(image.width as f32 / image.height.max(1) as f32, aspect); - Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile }) + let (center, half, rotation) = stencil_state.placement(image.width as f32 / image.height.max(1) as f32, aspect); + let colors = self.tool.tool == Tool::Projection; + Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: stencil_state.tile, colors }) } /// Painting is paused while a bake preview shows the baked maps instead of the material. @@ -569,6 +582,12 @@ impl Session { } let gbuf = self.caches.get(stroke.ts).map(|c| c.gbuf.clone()); + if stroke.stencil.is_some() && !with_commit_source(&stroke, gbuf.as_deref(), &self.mesh, &stroke.canvas.dirty, stencil_allows_stroke) { + self.mark_painted(stroke.ts, stroke.target, stroke.canvas.dirty.iter().copied()); + self.discard_unused_stroke_mask(&stroke); + return Ok(()); + } + let mesh = self.mesh.clone(); let mut staging = std::mem::take(&mut stroke.staging); match stroke.target { @@ -601,6 +620,32 @@ impl Session { Ok(()) } + fn discard_unused_stroke_mask(&mut self, stroke: &ActiveStroke) { + // An intervening edit may already have recorded the mask effect + if self.revision != stroke.start_revision { + return; + } + + self.doc.project.next_id = stroke.before.project.next_id; + if let Some(PaintTarget::Mask(effect)) = stroke.target + && let Some((owner, _)) = self.doc.project.effect(effect) + && let Some(previous_layer) = stroke.before.project.layers.get(&owner) + && !previous_layer.mask.iter().flat_map(|mask| &mask.effects).any(|previous| previous.id == effect) + && let Some(layer) = self.doc.project.layers.get_mut(&owner) + { + layer.mask = previous_layer.mask.clone(); + + // Removing a new mask background can change texels outside the dabs + if previous_layer.mask.is_none() { + for texture_set in self.doc.project.sets_drawing(owner) { + if let Some(cache) = self.caches.get_mut(texture_set) { + cache.invalidate_all(); + } + } + } + } + } + /// Abandon the active stroke (Esc). pub fn cancel_stroke(&mut self) { if let Some(st) = self.stroke.take() { @@ -744,22 +789,44 @@ impl Session { } } -/// Run `f` with stroke `st` as a commit source over `tiles` (the Projection tool's stencil -/// colors and alpha come from the surface under each texel). +/// Check that some rasterized paint survives the stencil before writing tiles or history. +fn stencil_allows_stroke(source: CommitSource) -> bool { + use texturecraft_texel::{TILE, from_u16}; + + let Some(sample_stencil) = source.per_texel else { return true }; + let opacity = source.opacity.clamp(0.0, 1.0); + source.tiles.iter().any(|&(tile_x, tile_y)| { + source.alpha.tile(tile_x, tile_y).is_some_and(|alpha| { + alpha.iter().enumerate().any(|(index, &coverage)| { + let weight = from_u16(coverage) * opacity; + if weight <= 0.0 { + return false; + } + + let x = tile_x * TILE + index as u32 % TILE; + let y = tile_y * TILE + index as u32 / TILE; + sample_stencil(x, y).is_some_and(|(_, factor)| weight * factor > 0.0) + }) + }) + }) +} + +/// Run `f` with `stroke` as a commit source over `tiles` (the stencil's alpha and, on the Projection tool, its colors come from the surface under each texel) fn with_commit_source( - st: &ActiveStroke, - gbuf: Option<&texturecraft_geom::UvGBuffer>, + stroke: &ActiveStroke, + gbuffer: Option<&texturecraft_geom::UvGBuffer>, mesh: &texturecraft_geom::Mesh, tiles: &BTreeSet<(u32, u32)>, f: impl FnOnce(CommitSource) -> R, ) -> R { - let stencil_fn = |x: u32, y: u32| -> Option<([f32; 3], f32)> { - let g = gbuf?; - let p = g.surface(mesh, (y * g.width + x) as usize)?.pos; - st.stencil.as_ref()?.sample_world(p) + let stencil_fn = |x: u32, y: u32| -> Option<(Option<[f32; 3]>, f32)> { + let gbuffer = gbuffer?; + let position = gbuffer.surface(mesh, (y * gbuffer.width + x) as usize)?.pos; + stroke.stencil.as_ref()?.paint_world(position) }; - let per_texel: Option = if st.stencil.is_some() { Some(&stencil_fn) } else { None }; - let carried = st.canvas.pickup.as_ref().map(|p| &p.values); - let carried_mask = st.canvas.pickup.as_ref().and_then(|p| p.mask_values()); - f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried, carried_mask }) + let per_texel: Option = if stroke.stencil.is_some() { Some(&stencil_fn) } else { None }; + + let carried = stroke.canvas.pickup.as_ref().map(|pickup| &pickup.values); + let carried_mask = stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values()); + f(CommitSource { alpha: &stroke.canvas.alpha, tiles, opacity: stroke.stroke.settings.opacity, erase: stroke.erase, per_texel, carried, carried_mask }) } diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 8b74dcb2..5efc1215 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -197,7 +197,8 @@ fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { /// snapshot) and snapshot k holds every tile as it was after k paths, so each snapshot, newest /// first, is charged for the tile buffers no live pixels, kept newer snapshot or `edited` already /// hold: what freeing it would release at most. The first (empty) and the last cost nothing. -fn evict(snaps: &mut [Option], budget: usize, edited: usize) { +/// Returns the bytes the kept snapshots are charged. +fn evict(snaps: &mut [Option], budget: usize, edited: usize) -> usize { let mut seen = BTreeSet::new(); for k in [snaps.len().saturating_sub(1), edited] { if let Some(Some(snap)) = snaps.get(k) { @@ -217,6 +218,32 @@ fn evict(snaps: &mut [Option], budget: usize, edited: usize) { seen = with; } } + bytes +} + +/// Runs [`evict`] only when the snapshots may have outgrown the budget. `evict` charges every +/// kept snapshot, so calling it after each appended path made a repaint of n paths cost n +/// scans of up to n snapshots. A snapshot differs from the one before it only in the tiles its +/// path painted, so those tiles bound what it adds: `held` is an upper bound on the bytes +/// charged, and the scan runs once it passes the budget (then `held` is exact again). +struct EvictPacer { + held: usize, +} + +impl EvictPacer { + /// Scan the snapshots kept from the previous repaint once, trimming them to the budget. + fn start(snaps: &mut [Option], edited: usize) -> Self { + Self { held: evict(snaps, CACHE_BYTES, edited) } + } + + /// A snapshot was appended after a path that painted `tiles` tile positions of `state`'s images. + fn appended(&mut self, snaps: &mut [Option], edited: usize, state: &Snap, tiles: usize) { + let tile_bytes: usize = state.values().map(|image| texturecraft_texel::TILE_AREA * image.comps() * 2).sum(); + self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)); + if self.held > CACHE_BYTES { + self.held = evict(snaps, CACHE_BYTES, edited); + } + } } fn same_handle(a: Option<&Arc>, b: Option<&Arc>) -> bool { @@ -1108,52 +1135,69 @@ impl Session { let mut snaps = old.as_ref().map_or_else(|| vec![Some(Snap::new())], |c| c.snaps[..=start].to_vec()); let mut tiles = old.as_ref().map_or_else(Vec::new, |c| c.tiles[..start].to_vec()); let mut state = snaps[start].clone().unwrap_or_default(); + let mut pacer = EvictPacer::start(&mut snaps, prefix); // Each path goes through the regular stroke and fill code with its own settings; their // own history entries are dropped (the caller records one step). + let mut out = vec![Value::Null; start]; + let result = self.while_painting_paths(eid, |s| { + let mut result = Ok(()); + for (j, (sh, _)) in new.iter().enumerate().skip(start) { + // Painting is per tile: over the same tiles, an unchanged path paints the same. + let o = if j < prefix { Some(j) } else { (j >= new.len() - suffix).then(|| j + old.as_ref().map_or(0, |c| c.shapes.len()) - new.len()) }; + if let (Some(c), Some(o)) = (&old, o) + && let (Some(below), Some(after)) = (&c.snaps[o], &c.snaps[o + 1]) + && same_tiles(&state, below, &c.tiles[o]) + { + copy_tiles(&mut state, after, &c.tiles[o]); + tiles.push(c.tiles[o].clone()); + snaps.push(Some(state.clone())); + pacer.appended(&mut snaps, prefix, &state, c.tiles[o].len()); + out.push(Value::Null); + continue; + } + s.put_snap(eid, &state); + s.path_tiles.clear(); + match s.paint_shape(sh) { + Ok(v) => out.push(v), + Err(e) => { + result = Err(e); + break; + } + } + state = s.take_snap(eid); + tiles.push(std::mem::take(&mut s.path_tiles)); + snaps.push(Some(state.clone())); + pacer.appended(&mut snaps, prefix, &state, tiles.last().map_or(0, BTreeSet::len)); + } + s.put_snap(eid, &state); + result + }); + if result.is_ok() { + self.path_cache = Some(PathCache { eid, key, shapes: new, snaps, tiles }); + } + result.map(|_| out) + } + + /// Run `f` with the session switched into path-painting state (path tool on sublayer `eid`, + /// empty history), then put the tool, camera, target, quick-mask flag and the undo/redo + /// stacks back. A panic in `f` restores them too before it continues unwinding: the + /// automation servers catch panics and keep serving this session, and must not find its + /// history gone. + fn while_painting_paths(&mut self, eid: LayerId, f: impl FnOnce(&mut Session) -> T) -> T { let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing); let history = (std::mem::take(&mut self.undo), std::mem::take(&mut self.redo)); self.target = StackTarget::Effect(eid); self.quick_mask.editing = false; self.tool.tool = Tool::Path; self.painting_paths = true; - let mut out = vec![Value::Null; start]; - let mut result = Ok(()); - for (j, (sh, _)) in new.iter().enumerate().skip(start) { - // Painting is per tile: over the same tiles, an unchanged path paints the same. - let o = if j < prefix { Some(j) } else { (j >= new.len() - suffix).then(|| j + old.as_ref().map_or(0, |c| c.shapes.len()) - new.len()) }; - if let (Some(c), Some(o)) = (&old, o) - && let (Some(below), Some(after)) = (&c.snaps[o], &c.snaps[o + 1]) - && same_tiles(&state, below, &c.tiles[o]) - { - copy_tiles(&mut state, after, &c.tiles[o]); - tiles.push(c.tiles[o].clone()); - snaps.push(Some(state.clone())); - evict(&mut snaps, CACHE_BYTES, prefix); - out.push(Value::Null); - continue; - } - self.put_snap(eid, &state); - self.path_tiles.clear(); - match self.paint_shape(sh) { - Ok(v) => out.push(v), - Err(e) => { - result = Err(e); - break; - } - } - state = self.take_snap(eid); - tiles.push(std::mem::take(&mut self.path_tiles)); - snaps.push(Some(state.clone())); - evict(&mut snaps, CACHE_BYTES, prefix); - } - self.put_snap(eid, &state); + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))); self.painting_paths = false; (self.tool, self.camera, self.target, self.quick_mask.editing) = saved; (self.undo, self.redo) = history; - if result.is_ok() { - self.path_cache = Some(PathCache { eid, key, shapes: new, snaps, tiles }); + match ran { + Ok(v) => v, + Err(panic) => std::panic::resume_unwind(panic), } - result.map(|_| out) } fn take_snap(&self, eid: LayerId) -> Snap { @@ -1486,6 +1530,23 @@ mod tests { assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); } + #[test] + fn appending_paths_scans_the_snapshots_only_when_the_budget_may_be_passed() { + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + let mut snaps = vec![Some(empty.clone()), Some(painted(&empty, &[(0, 0)]))]; + let mut pacer = super::EvictPacer::start(&mut snaps, 0); + assert_eq!(pacer.held, 0, "the first and last snapshots are free"); + // A few small paths add up to an estimate without a scan (a scan would reset it to the exact 0). + for n in 1..=3 { + pacer.appended(&mut snaps, 0, &empty, 1); + assert_eq!(pacer.held, n * tile_bytes, "after {n} paths"); + } + // Past the budget the estimate gives way to an exact scan. + pacer.appended(&mut snaps, 0, &empty, super::CACHE_BYTES / tile_bytes + 1); + assert!(pacer.held < super::CACHE_BYTES, "scanned: {}", pacer.held); + } + #[test] fn a_snapshot_is_charged_only_for_what_no_kept_snapshot_shares() { let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); @@ -1712,4 +1773,27 @@ mod tests { assert!(!off_mesh.is_empty()); assert!(off_mesh.iter().flatten().all(Option::is_none)); } + + #[test] + fn a_panic_while_painting_paths_restores_history_and_tool_state() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + s.update(); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.2], [0.9, 0.25]], "commit": true})).unwrap(); + let eid = texturecraft_core::LayerId(r["committed"]["effect"].as_u64().unwrap()); + assert!(!s.history_labels().is_empty()); + let labels = s.history_labels(); + let (target, tool) = (s.target, s.tool.tool); + + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + s.while_painting_paths(eid, |s| { + s.edit("nested", |_| Ok(())).unwrap(); + panic!("paint failed"); + }) + })); + assert!(panicked.is_err()); + assert_eq!(s.history_labels(), labels); + assert_eq!((s.target, s.tool.tool), (target, tool)); + assert!(!s.painting_paths); + } } diff --git a/crates/engine/src/preset_cmds.rs b/crates/engine/src/preset_cmds.rs index 9395ae2d..ee11f119 100644 --- a/crates/engine/src/preset_cmds.rs +++ b/crates/engine/src/preset_cmds.rs @@ -472,6 +472,7 @@ mod tests { assert!(warnings.is_empty(), "{warnings:?}"); assert_eq!(run(&mut s, "export.preset.get", json!({"name": name.to_ascii_lowercase()})).unwrap(), custom); let plan = run(&mut s, "export.plan", json!({"preset": name, "ts": 0})).unwrap(); + assert_eq!(plan.as_array().unwrap().len(), 1); assert!(plan[0]["file"].as_str().unwrap().ends_with("_R.png")); @@ -481,9 +482,11 @@ mod tests { let builtin = format!("builtin:{name}"); assert!(names.iter().any(|entry| entry["name"] == builtin && entry["builtin"] == true)); let builtin_plan = run(&mut s, "export.plan", json!({"preset": builtin, "ts": 0})).unwrap(); + assert!(builtin_plan.as_array().unwrap().len() > 1); run(&mut s, "export.preset.save", json!({"preset": custom})).unwrap(); run(&mut s, "export.preset.remove", json!({"name": name})).unwrap(); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4); } diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 024243c3..e4265659 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -341,6 +341,7 @@ fn rename(s: &mut Session, p: &Value) -> Result { if to == name { return Ok(json!({ "name": name })); } + if s.doc.resources.contains_key(&to) || crate::fill_alpha::library_alpha_of(&to).is_some() { return Err(bad(command, format!("a resource named `{to}` exists already"))); } @@ -348,6 +349,7 @@ fn rename(s: &mut Session, p: &Value) -> Result { s.edit("Rename resource", |s| { let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?; s.doc.resources.insert(to.clone(), bytes); + // The Resources Updater keeps following the file the image came from if let Some(source) = s.doc.project.resource_sources.remove(&name) { s.doc.project.resource_sources.insert(to.clone(), source); @@ -428,17 +430,23 @@ fn images_in_use(s: &Session) -> Vec { } /// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step) -fn remove_unused(s: &mut Session, _: &Value) -> Result { - let used = images_in_use(s); - let unused: Vec = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect(); +fn remove_unused(session: &mut Session, _: &Value) -> Result { + let mut used = images_in_use(session); + used.sort_unstable(); + let unused: Vec<_> = session.doc.resources.keys().filter(|name| used.binary_search(name).is_err()).cloned().collect(); + if !unused.is_empty() { - s.edit("Remove unused resources", |s| { - s.doc.resources.retain(|k, _| !unused.contains(k)); - s.doc.project.resource_sources.retain(|k, _| !unused.contains(k)); + session.edit("Remove unused resources", |session| { + for name in &unused { + session.doc.resources.remove(name); + session.doc.project.resource_sources.remove(name); + } + Ok(()) })?; - s.sync_images(); + session.sync_images(); } + Ok(json!({ "removed": unused })) } @@ -538,6 +546,7 @@ mod tests { let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap(); + // An equal-size file counts as changed once its time moved, as a later save's does let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10); std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 1c94d2c0..a1d710b7 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -110,6 +110,12 @@ pub enum Tool { impl Tool { pub const ALL: [Tool; 9] = [Tool::Paint, Tool::Eraser, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::Path, Tool::GeometryMask]; + + /// The brush tools whose strokes the stencil shapes + pub fn uses_stencil(self) -> bool { + matches!(self, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone) + } + pub fn label(self) -> &'static str { match self { Tool::Paint => "Paint", @@ -181,7 +187,7 @@ impl ViewMode { } } -/// A screen-pinned image for the Projection tool (a stencil). +/// A screen-pinned image the brush tools paint through (a stencil) #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StencilState { /// Image resource name. @@ -252,7 +258,7 @@ pub struct ToolState { /// Polygon fill boxes in the 3D view select only the polygons the camera sees #[serde(default = "default_fill_visible_only")] pub fill_visible_only: bool, - /// Stencil used by the Projection tool. + /// Stencil the brush tools paint through (the Projection tool paints its colors) #[serde(default)] pub stencil: Option, /// Placement the next stencil starts with: the last stencil's, kept when the stencil is @@ -364,10 +370,12 @@ pub(crate) struct ActiveStroke { /// What a mask stroke paints, resolved once so staging, preview and commit read one image pub mask_gray: texturecraft_compose::MaskGray, pub erase: bool, - /// Projection tool: the stencil captured with the stroke's camera. + /// The stencil captured with the stroke's camera. pub stencil: Option, /// History snapshot taken when the stroke began. pub before: Document, + /// Document revision before any edits made during the stroke. + pub start_revision: u64, pub label: String, /// The commit's destination tiles, copied as the stroke reaches them. pub staging: texturecraft_paint::Staging, @@ -703,7 +711,8 @@ impl Session { // ----------------------------------------------------------------------------------------- // History - /// Run an undoable edit. On error the document is left untouched. + /// Run an undoable edit. On error, or if `f` panics, the document is left untouched (other + /// session state, such as the selection, is not restored). pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { self.edit_merging(label, self.merge_edits, f) } @@ -719,7 +728,18 @@ impl Session { self.end_polygon_fill_box(); let before = self.doc.clone(); - let result = change(self).and_then(|(value, changed)| { + // A panic inside `change` must not leave a half-edited document behind: the automation + // servers catch panics and keep serving this session. (On wasm a panic aborts, so + // there is nothing to restore.) + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| change(self))); + let result = match ran { + Ok(result) => result, + Err(panic) => { + self.restore_after_failed_edit(before); + std::panic::resume_unwind(panic); + } + }; + let result = result.and_then(|(value, changed)| { if changed && let Some(id) = self.doc.project.instance_cycle() { return Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))); } @@ -735,15 +755,21 @@ impl Session { Ok(value) } Err(error) => { - self.doc = before; - - // A failed repaint may have cached tiles from the discarded document - self.path_cache = None; + self.restore_after_failed_edit(before); Err(error) } } } + /// Put `before` back after an edit failed or panicked. The edit may have recomposited the + /// discarded document (draining the dirty tiles) or cached path tiles from it, so mark what + /// differs between the two dirty again, as undo does. + fn restore_after_failed_edit(&mut self, before: Document) { + let discarded = std::mem::replace(&mut self.doc, before); + self.path_cache = None; + self.invalidate_changed(&discarded); + } + pub(crate) fn push_history(&mut self, label: &str, before: Document) { self.record(label, before, false); } @@ -1043,13 +1069,17 @@ impl Session { self.invalidate_changed(other); // An undone add or duplicate takes the selected effect away - if let StackTarget::Effect(e) = self.target - && self.doc.project.effect(e).is_none() + if let StackTarget::Effect(effect_id) = self.target + && self.doc.project.effect(effect_id).is_none() { - let p = &other.project; - let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e)); + let previous_project = &other.project; + let content = previous_project + .effect(effect_id) + .and_then(|(owner, _)| previous_project.layers.get(&owner)) + .is_some_and(|layer| layer.content_effects.iter().any(|effect| effect.id == effect_id)); self.target = if content { StackTarget::Content } else { StackTarget::Mask }; } + let has_mask = self.selected_layer().and_then(|lid| self.doc.project.layer(self.doc.project.mask_owner(lid)).ok()).is_some_and(|l| l.mask.is_some()); if self.target == StackTarget::Mask && !has_mask { self.target = StackTarget::Content; diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 977f34d6..a890113d 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -12,6 +12,12 @@ use crate::fill_mode::FillMode; use crate::session::{CloneFrom, CloneSource, StackTarget, Tool}; use crate::{Result, Session, cmd}; +/// Brush size the UI's full size slider stands for +const MAX_BRUSH_SIZE: f32 = 0.25; + +/// Full value of the UI's 0–100 brush scales +const PERCENT: f32 = 100.0; + pub fn specs() -> Vec { vec![ cmd!("tool.paint", "Paint", ["Tools"], Some("1"), "{}", always, |s, _| set_tool(s, Tool::Paint)), @@ -36,7 +42,7 @@ pub fn specs() -> Vec { "Brush settings", [], None, - "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", + "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, angleFade?: [from, to] degrees 0..90 (culled faces fade out between them), screenSpace? (the size follows the view), stampDepth?: 0.05..4, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, sizePressure? (default true: pen pressure shrinks the size towards minSize), smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", always, brush ), @@ -64,7 +70,7 @@ pub fn specs() -> Vec { ), cmd!( "tool.stencil", - "Projection stencil", + "Stencil", [], None, "{image?: resource name, center?: [x,y] NDC, scale?: 0.01..10, rotation?: degrees, tile?, opacity?, clear?: bool}", @@ -132,14 +138,17 @@ fn select(s: &mut Session, p: &Value) -> Result { /// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers fn brush(session: &mut Session, params: &Value) -> Result { let mut settings = session.tool.brush.clone(); - let percent = |key: &str| f32p(params, key).map(|value| value / 100.0); + let percent = |key: &str| f32p(params, key).map(|value| value / PERCENT); if let Some(value) = percent("size") { - settings.size = value * 0.25; + settings.size = value * MAX_BRUSH_SIZE; } if let Some(value) = percent("minSize") { settings.min_size = value; } + if let Some(value) = boolp(params, "sizePressure") { + settings.size_pressure = value; + } if let Some(value) = percent("flow") { settings.flow = value; @@ -174,11 +183,11 @@ fn brush(session: &mut Session, params: &Value) -> Result { for (key, slot) in [("jitterSize", &mut settings.jitter_size), ("jitterAngle", &mut settings.jitter_angle), ("jitterFlow", &mut settings.jitter_flow)] { if let Some(value) = f32p(params, key) { - *slot = value / 100.0; + *slot = value / PERCENT; } } if let Some(value) = f32p(params, "jitterPosition") { - settings.jitter_position = value / 100.0; + settings.jitter_position = value / PERCENT; } let alpha = params.get("alpha"); @@ -215,6 +224,13 @@ fn brush(session: &mut Session, params: &Value) -> Result { if let Some(value) = boolp(params, "backfaceCulling") { settings.backface_culling = value; } + if params.get("angleFade").is_some() { + let [from, to] = pair(params, "angleFade").ok_or_else(|| bad("tool.brush", "`angleFade` must be [from, to] in degrees"))?; + settings.angle_fade = (from, to); + } + if let Some(value) = f32p(params, "stampDepth") { + settings.depth = value; + } if let Some(value) = boolp(params, "symmetryOn") { settings.symmetry.enabled = value; @@ -282,30 +298,32 @@ fn brush(session: &mut Session, params: &Value) -> Result { } } if let Some(value) = f32p(params, "smudgeStrength") { - session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0); + session.tool.smudge_strength = (value / PERCENT).clamp(0.0, 1.0); } session.revision = session.revision.wrapping_add(1); Ok(brush_json(session)) } +/// The brush settings `tool.brush` reports, on the UI's 0–100 scales pub(crate) fn brush_json(session: &Session) -> Value { let settings = &session.tool.brush; json!({ - "size": settings.size / 0.25 * 100.0, "minSize": settings.min_size * 100.0, "flow": settings.flow * 100.0, "opacity": settings.opacity * 100.0, - "spacing": settings.spacing * 100.0, "hardness": settings.hardness * 100.0, "angle": settings.angle, "followPath": settings.follow_path, + "size": settings.size / MAX_BRUSH_SIZE * PERCENT, "minSize": settings.min_size * PERCENT, "sizePressure": settings.size_pressure, "flow": settings.flow * PERCENT, "opacity": settings.opacity * PERCENT, + "spacing": settings.spacing * PERCENT, "hardness": settings.hardness * PERCENT, "angle": settings.angle, "followPath": settings.follow_path, "alignment": format!("{:?}", settings.alignment).to_lowercase(), "lazy": settings.lazy, "alpha": match (&settings.alpha_image, &settings.alpha_library) { (Some(name), _) => json!({ "image": name }), (None, Some(id)) => json!({ "library": id }), (None, None) => json!(settings.alpha.label()), }, - "alphaSizeX": settings.alpha_params.size_x * 100.0, "alphaSizeY": settings.alpha_params.size_y * 100.0, - "alphaRoundness": settings.alpha_params.roundness * 100.0, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert, - "backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z], + "alphaSizeX": settings.alpha_params.size_x * PERCENT, "alphaSizeY": settings.alpha_params.size_y * PERCENT, + "alphaRoundness": settings.alpha_params.roundness * PERCENT, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert, + "backfaceCulling": settings.backface_culling, "angleFade": [settings.angle_fade.0, settings.angle_fade.1], "screenSpace": settings.screen_space, + "stampDepth": settings.depth, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z], "radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) }, "symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span, - "material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles, + "material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * PERCENT, "particles": settings.particles, "cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" }, "cloneAligned": session.tool.clone_aligned, }) diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index dca3a215..e5a01740 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -39,6 +39,7 @@ fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() { let small = options(SMALL_SIDE); let large = options(4096); let first = session.export_files(&[0], &small).unwrap(); + assert!(first.len() > 1, "the mesh supplies multiple PSD tiles"); let jobs = std::iter::once((0, &small)).chain(std::iter::repeat_n((0, &large), 4)); diff --git a/crates/engine/tests/it/tool_settings.rs b/crates/engine/tests/it/tool_settings.rs index 281e28a0..ef5a921b 100644 --- a/crates/engine/tests/it/tool_settings.rs +++ b/crates/engine/tests/it/tool_settings.rs @@ -148,3 +148,26 @@ fn restored_stencil_and_smudge_settings_use_the_tool_limits() { let look = session.tool.stencil_look; assert_eq!((look.center, look.scale, look.opacity, look.rotation), ([-4.0, 4.0], 0.01, 0.0, 345.0)); } + +#[test] +fn tool_brush_sets_and_reports_the_projection_bands_settings() { + let mut session = another_project(); + let defaults = session.tool.brush.clone(); + let reported = execute(&mut session, "tool.brush", &json!({"angleFade": [20, 40], "stampDepth": 2.5, "screenSpace": !defaults.screen_space})).unwrap(); + + let brush = &session.tool.brush; + assert_ne!(brush.angle_fade, defaults.angle_fade, "Angle fade from / to changes through the command"); + assert_ne!(brush.depth, defaults.depth, "Stamp depth changes through the command"); + assert_eq!(reported["angleFade"], json!([brush.angle_fade.0, brush.angle_fade.1])); + assert_eq!(reported["stampDepth"], json!(brush.depth)); + assert_eq!(reported["screenSpace"], json!(brush.screen_space)); +} + +#[test] +fn a_malformed_angle_fade_leaves_the_brush_unchanged() { + let mut session = another_project(); + let before = session.tool.brush.clone(); + + assert!(execute(&mut session, "tool.brush", &json!({"size": 50, "angleFade": "steep"})).is_err()); + assert_eq!(session.tool.brush, before); +} diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index a130f813..55d5eacd 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -410,14 +410,14 @@ fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() { #[test] fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() { - let mut s = ball(); + let mut session = ball(); let dir = temp("psd"); - let r = export(&mut s, &dir, json!({"ts": 0, "format": "psd", "usdAsset": true})); + let result = export(&mut session, &dir, json!({"ts": 0, "format": "psd", "usdAsset": true})); - assert!(files(&r).iter().any(|f| f.ends_with(".psd")), "{r}"); - let materials = read_back(&s, &dir); + assert!(files(&result).iter().any(|f| f.ends_with(".psd")), "{result}"); + let materials = read_back(&session, &dir); - assert!(materials[material_of(&s, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&s, 0)]); - assert!(r["warnings"].to_string().contains("doesn't read PSD files"), "{r}"); + assert!(materials[material_of(&session, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&session, 0)]); + assert!(result["warnings"].to_string().contains("doesn't read PSD files"), "{result}"); } diff --git a/crates/engine/tests/it/uv_strokes.rs b/crates/engine/tests/it/uv_strokes.rs index 18a33fda..9d8466bc 100644 --- a/crates/engine/tests/it/uv_strokes.rs +++ b/crates/engine/tests/it/uv_strokes.rs @@ -103,3 +103,19 @@ fn decreasing_pressure_does_not_stamp_behind_a_turn() { assert!(red_at(&session, 0.33, 0.55), "the new segment is painted"); assert!(!red_at(&session, 0.33, 0.45), "a smaller step must not stamp behind the turn"); } + +#[test] +fn a_light_pen_paints_at_full_size_with_size_pressure_off() { + let painted_across = |size_pressure: bool| { + let mut session = red_brush_session(json!({"size": 10.0, "minSize": 0.0, "sizePressure": size_pressure, "hardness": 90})); + session.begin_stroke_uv([0.5, 0.5].into(), 0.2).unwrap(); + session.continue_stroke_uv([0.5, 0.5001].into(), 0.2); + session.end_stroke().unwrap(); + session.update(); + (0..RESOLUTION).filter(|x| red_at(&session, *x as f32 / RESOLUTION as f32, 0.5)).count() + }; + + let (pressed, ignored) = (painted_across(true), painted_across(false)); + assert!(pressed > 0, "a light pen still paints"); + assert!(ignored > pressed, "with size pressure off a light pen paints wider ({ignored} vs {pressed} texels)"); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 0fc0b848..3387f652 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -1,8 +1,9 @@ use serde_json::{Value, json}; +use texturecraft_engine::compose::PixelStore; use texturecraft_engine::core::{Channel, MIN_RESOLUTION}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, command_specs, execute}; +use texturecraft_engine::{Document, Session, command_specs, execute}; fn session() -> Session { session_at(256) @@ -17,6 +18,23 @@ fn session_at(texture_size: u32) -> Session { s } +/// Whether two documents hold the same content (`Document` has no `PartialEq`). Destructured so +/// a new public field must be compared here too (crate-private fields, such as `painted_regions`, +/// can't be reached from an integration test). +fn same_document(a: &Document, b: &Document) -> bool { + let Document { project, pixels: PixelStore { layers, masks }, baked, bake_paint, resources, bake_meshes, .. } = a; + // Bake meshes have no equality (each holds a mesh and its BVH): the same high polys and cage + // stand in for them. + let same_meshes = bake_meshes.high.len() == b.bake_meshes.high.len() && bake_meshes.cage.is_some() == b.bake_meshes.cage.is_some(); + *project == b.project + && *layers == b.pixels.layers + && *masks == b.pixels.masks + && *baked == b.baked + && *bake_paint == b.bake_paint + && *resources == b.resources + && same_meshes +} + #[test] fn scripted_stroke_paints_and_undo_restores() { let mut s = session(); @@ -500,6 +518,92 @@ fn an_srgb_hex_colour_matches_its_linear_rgb_value() { assert!(digits[0] - hex[0] > 0.1, "{digits:?} {hex:?}"); } +/// A command that panics halfway through an edit leaves the document and history as they were. +#[test] +fn a_panic_inside_an_edit_restores_the_document() { + let mut s = session(); + let before = s.doc.clone(); + let history = s.history_labels(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = s.edit("Half done", |s| -> texturecraft_engine::Result<()> { + s.doc.project.name = "changed".into(); + s.doc.pixels.mask_mut(texturecraft_engine::core::LayerId(u64::MAX), (64, 64)); + s.doc.resources.insert("half.png".into(), std::sync::Arc::new(vec![1, 2, 3])); + panic!("boom"); + }); + })); + assert!(r.is_err(), "the panic still reaches the caller"); + assert!(same_document(&s.doc, &before), "the half-made change was rolled back"); + assert_eq!(s.history_labels(), history, "no undo step was recorded"); +} + +/// An edit that recomposites the discarded document and then fails or panics: the display shows the +/// restored document again after the next `update`, not the discarded one. +#[test] +fn a_failed_or_panicking_edit_recomposites_the_restored_document() { + for panics in [false, true] { + let mut s = session(); + let hit = s.pick(texturecraft_engine::geom::glam::Vec2::new(200.0, 200.0), s.viewport).unwrap(); + let (x, y) = ((hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32); + let red_at = |s: &mut Session| { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, x, y)[0] + }; + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + let painted = red_at(&mut s); + assert!(painted > 0.9, "the stroke painted: {painted}"); + + let edit = |s: &mut Session| { + let _ = s.edit("Hide everything", |s| -> texturecraft_engine::Result<()> { + s.doc.project.texture_sets[0].stack.clear(); + s.touched(); + s.update(); + assert!(s.caches[0].composite.value(Channel::BaseColor, x, y)[0] < 0.9, "the edit shows the empty stack"); + if panics { + panic!("boom"); + } + Err(texturecraft_engine::EngineError::Other("nope".into())) + }); + }; + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| edit(&mut s))); + assert_eq!(r.is_err(), panics); + let shown = red_at(&mut s); + assert!(shown > 0.9, "panics={panics}: the restored paint is shown again: {shown}"); + } +} + +/// A command that fails leaves the document and history as they were (commands are atomic). +#[test] +fn failed_commands_leave_the_document_unchanged() { + let hostile = [ + Value::Null, + json!({}), + json!({"layer": u64::MAX, "ts": 99, "channel": "nope", "mode": "???", "opacity": f64::MAX}), + json!({"layer": 1, "index": -5, "delta": i64::MIN, "above": "x", "points": [[f64::MAX, -1e300]], "size": -1e30}), + json!({"resolution": 0, "maps": ["x"], "rays": u64::MAX, "antialiasing": 3, "color": [1], "value": "nan"}), + json!({"effect": 0, "x": 1e30, "y": -1e30, "viewport": [0, 0], "mesh": "../../etc", "material": ""}), + ]; + let mut offenders = Vec::new(); + for spec in command_specs() { + if spec.id == "project.sample" { + continue; // slow (bakes); covered elsewhere + } + for p in &hostile { + let mut s = session_at(MIN_RESOLUTION); + for texture_set in &mut s.doc.project.texture_sets { + texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R64; + } + let (before, history) = (s.doc.clone(), s.history_labels()); + if execute(&mut s, spec.id, p).is_err() && (!same_document(&s.doc, &before) || s.history_labels() != history) { + offenders.push(format!("{} {p}", spec.id)); + } + } + } + assert!(offenders.is_empty(), "failed commands changed the document:\n{}", offenders.join("\n")); +} + #[test] fn copy_paste_flatten_and_resize_keep_the_look() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); @@ -697,6 +801,224 @@ fn projection_tool_paints_the_stencil_colors() { assert!(right[1] > 0.8 && right[0] < 0.2, "right {right:?}"); } +/// The stencil tests' texture size, to turn a picked UV into a texel +const TEXTURE_SIZE: u32 = 256; + +/// Side of the stencil black on its left half and white on its right +const STENCIL_SIZE: u32 = 16; + +/// The view's row over the sphere the stencil tests paint along +const DAB_Y: f32 = 200.0; + +/// A dab behind the stencil's black half +const BLACK_DAB_X: f32 = 150.0; + +/// A dab behind the stencil's white half +const WHITE_DAB_X: f32 = 250.0; + +/// Imports a stencil black on its left half and white on its right, returning its resource name +fn half_black_stencil(session: &mut Session) -> String { + let stencil = image::RgbaImage::from_fn(STENCIL_SIZE, STENCIL_SIZE, |x, _| { + if x < STENCIL_SIZE / 2 { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([255, 255, 255, 255]) } + }); + let mut png = Vec::new(); + stencil.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + + session.import_resource_bytes("half.png", png).unwrap() +} + +/// The composite base color under the view's point at `x` on the dab row +fn base_color_at(session: &Session, x: f32) -> [f32; 3] { + let hit = session.pick(Vec2::new(x, DAB_Y), session.viewport).unwrap(); + let texel = |coordinate: f32| (coordinate * TEXTURE_SIZE as f32) as u32; + + session.caches[0].composite.value(Channel::BaseColor, texel(hit.uv.x), texel(hit.uv.y)) +} + +#[test] +fn the_paint_tool_paints_its_own_color_through_the_stencils_gray() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + let left_before = base_color_at(&session, BLACK_DAB_X); + + for x in [BLACK_DAB_X, WHITE_DAB_X] { + execute(&mut session, "tool.stroke", &json!({"points": [[x, DAB_Y]]})).unwrap(); + } + + let (left, right) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + assert_eq!(left, left_before, "black stencil blocks the paint"); + assert!(right[0] > 0.8 && right[1] < 0.2 && right[2] < 0.2, "white stencil lets the tool's red through: {right:?}"); +} + +#[test] +fn a_stroke_blocked_by_a_stencil_keeps_pixels_and_history() { + for (tool, alpha) in [("paint", 255), ("projection", 0)] { + let mut session = session_at(TEXTURE_SIZE); + let stencil = image::RgbaImage::from_pixel(STENCIL_SIZE, STENCIL_SIZE, image::Rgba([0, 0, 0, alpha])); + let mut png = Vec::new(); + stencil.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("blocked.png", png).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + let layer = session.selected_layer_id().unwrap(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let history = session.history_labels(); + let redo = session.redo_labels(); + let revision = session.revision; + let tile_bytes = session.doc.pixels.bytes(); + let tiles = session.doc.pixels.layers.values().map(texturecraft_texel::TileImage::allocated_count).sum::(); + let color = base_color_at(&session, BLACK_DAB_X); + + let stroke = execute(&mut session, "tool.stroke", &json!({"points": [[BLACK_DAB_X, DAB_Y]]})).unwrap(); + let after_tiles = session.doc.pixels.layers.values().map(texturecraft_texel::TileImage::allocated_count).sum::(); + let after_tile_bytes = session.doc.pixels.bytes(); + println!("{tool}: {tiles} -> {after_tiles} retained tiles, {tile_bytes} -> {after_tile_bytes} retained tile bytes"); + + assert!(stroke["stamps"].as_u64().unwrap() > 0); + assert_eq!(base_color_at(&session, BLACK_DAB_X), color); + assert_eq!(after_tile_bytes, tile_bytes, "{tool} stored empty tiles"); + assert_eq!(after_tiles, tiles); + assert_eq!(session.history_labels(), history); + assert_eq!(session.redo_labels(), redo); + assert_eq!(session.revision, revision); + } +} + +#[test] +fn a_stroke_blocked_by_a_stencil_drops_its_unused_mask_effect() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.stroke", &json!({"points": [[WHITE_DAB_X, DAB_Y]]})).unwrap(); + let painted_color = base_color_at(&session, WHITE_DAB_X); + let id = session.selected_layer_id().unwrap(); + session.target = texturecraft_engine::StackTarget::Mask; + let history = session.history_labels(); + let next_id = session.doc.project.next_id; + assert!(session.doc.project.layers[&id].mask.is_none()); + + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), session.viewport, 1.0).unwrap(); + + assert!(session.stroke_tiles() > 0); + session.caches[0].invalidate_all(); + session.update(); + assert_ne!(base_color_at(&session, WHITE_DAB_X), painted_color); + session.end_stroke().unwrap(); + session.update(); + + assert!(session.doc.project.layers[&id].mask.is_none()); + assert_eq!(session.doc.project.next_id, next_id); + assert!(session.doc.pixels.masks.is_empty()); + assert_eq!(session.history_labels(), history); + assert_eq!(base_color_at(&session, WHITE_DAB_X), painted_color); + + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), session.viewport, 1.0).unwrap(); + + assert!(session.stroke_tiles() > 0); + execute(&mut session, "layer.rename", &json!({"layer": id.0, "name": "Renamed while painting"})).unwrap(); + let history_after_rename = session.history_labels(); + + session.end_stroke().unwrap(); + + assert_eq!(session.doc.project.layers[&id].name, "Renamed while painting"); + assert!(session.doc.project.layers[&id].mask.is_some()); + assert_eq!(session.history_labels(), history_after_rename); + assert!(session.doc.pixels.masks.is_empty()); +} + +#[test] +fn the_eraser_erases_only_through_the_stencils_gray() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + for x in [BLACK_DAB_X, WHITE_DAB_X] { + execute(&mut session, "tool.stroke", &json!({"points": [[x, DAB_Y]]})).unwrap(); + } + let (left_painted, right_painted) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + + execute(&mut session, "tool.eraser", &Value::Null).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + for x in [BLACK_DAB_X, WHITE_DAB_X] { + execute(&mut session, "tool.stroke", &json!({"points": [[x, DAB_Y]]})).unwrap(); + } + + assert_eq!(base_color_at(&session, BLACK_DAB_X), left_painted, "black stencil keeps the paint from the eraser"); + assert_ne!(base_color_at(&session, WHITE_DAB_X), right_painted, "white stencil lets the eraser through"); +} + +#[test] +fn a_mask_stroke_shows_through_the_stencil_while_painting_as_it_commits() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + + // A red fill under a white mask the stroke paints black + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "mask.add.white", &Value::Null).unwrap(); + session.target = texturecraft_engine::StackTarget::Mask; + session.tool.mask_value = 0.0; + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + session.update(); + let (left_before, right_before) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + + // A stroke from behind the stencil's black half to its white half + let viewport = session.viewport; + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), viewport, 1.0).unwrap(); + session.continue_stroke(Vec2::new(WHITE_DAB_X, DAB_Y), 1.0); + session.update(); + let (left_preview, right_preview) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + assert_eq!(left_preview, left_before, "black stencil hides the live stroke"); + assert_ne!(right_preview, right_before, "white stencil shows the live stroke"); + + session.end_stroke().unwrap(); + session.update(); + let (left_committed, right_committed) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + assert_eq!(left_committed, left_before, "black stencil blocks the committed stroke"); + assert_ne!(right_committed, right_before, "white stencil lets the committed stroke through"); +} + +#[test] +fn a_live_paint_stroke_shows_through_the_stencil_on_every_channel_it_paints() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "roughness", "value": 0.0})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + let channel_at = |session: &Session, channel: Channel, x: f32| { + let hit = session.pick(Vec2::new(x, DAB_Y), session.viewport).unwrap(); + let texel = |coordinate: f32| (coordinate * TEXTURE_SIZE as f32) as u32; + session.caches[0].composite.value(channel, texel(hit.uv.x), texel(hit.uv.y)) + }; + let before = + [Channel::BaseColor, Channel::Roughness].map(|channel| (channel_at(&session, channel, BLACK_DAB_X), channel_at(&session, channel, WHITE_DAB_X))); + + // A stroke from behind the stencil's black half to its white half, shown before it commits + let viewport = session.viewport; + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), viewport, 1.0).unwrap(); + session.continue_stroke(Vec2::new(WHITE_DAB_X, DAB_Y), 1.0); + session.update(); + + for (channel, (left_before, right_before)) in [Channel::BaseColor, Channel::Roughness].into_iter().zip(before) { + assert_eq!(channel_at(&session, channel, BLACK_DAB_X), left_before, "black stencil hides the live {channel:?}"); + assert_ne!(channel_at(&session, channel, WHITE_DAB_X), right_before, "white stencil shows the live {channel:?}"); + } +} + #[test] fn smart_materials_save_and_load_with_pixels() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index f7be380c..abbf0256 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -71,7 +71,7 @@ fn working_set<'a>( padding_peak = padding_bytes.saturating_add(atlas_texels.saturating_mul((4 * size_of::()) as u64)); } - // The quantized layers kept so far and the merged image are part of the file; the encoder can hold staged pixels, planes and the output at once + // Budget for the retained layers and merged image alongside encoder planes, staging and output let rendering = scratch_bytes.max(merge_bytes).saturating_add(file_bytes); let encoding = 3 * file_bytes; let working_bytes = padding_bytes.saturating_add(rendering.max(encoding)).max(padding_peak); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 824a37ea..6dda7b2d 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -944,12 +944,14 @@ pub fn is_set_warning(warning: &str) -> bool { fn unique_name(used: &mut BTreeSet, stem: &str, ext: &str, warnings: &mut Vec) -> (String, String) { let mut name = format!("{stem}.{ext}"); let mut renamed = String::new(); - let mut k = 2; + let mut suffix_number = 2; + while used.contains(&name.to_ascii_lowercase()) { - renamed = format!("_{k}"); + renamed = format!("_{suffix_number}"); name = format!("{stem}{renamed}.{ext}"); - k += 1; + suffix_number += 1; } + if !renamed.is_empty() { warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); } diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 49f4b812..ad87ff10 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -378,16 +378,17 @@ fn every_format_encodes_and_decodes() { for f in &files { assert!(f.name.ends_with(format.extension())); if format == FileFormat::Exr && f.name.starts_with("la") { - continue; // Y/A EXR is checked with the EXR crate in `exr_exports_luminance_and_alpha_at_both_depths`. + // The EXR-specific test reads luminance and alpha through the native decoder + continue; } assert_eq!(decode(f).dimensions(), (RES, RES), "{}", f.name); } // Roughness 0.25 everywhere survives every format (JPEG within its loss) - let px = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1]; + let roughness_sample = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1]; - assert!((px - 0.25).abs() < 0.01, "{format:?}/{depth}: {px}"); + assert!((roughness_sample - 0.25).abs() < 0.01, "{format:?}/{depth}: {roughness_sample}"); let base = find(&files, "_BaseColor."); match format { FileFormat::Jpeg | FileFormat::Hdr => assert!(base.warnings.iter().any(|w| w.contains("alpha")), "{format:?}"), @@ -1337,6 +1338,7 @@ fn feedback_psd_dithering_tracks_the_document_depth() { options.maps.insert(1, MapOverride { dither: Some(false), ..MapOverride::default() }); let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert!(plan[0].dither && plan[0].layers[0].dither && !plan[0].layers[1].dither); options.preset.maps[1].bit_depth = 16; @@ -1887,9 +1889,10 @@ fn a_map_preview_holds_the_values_its_file_stores() { #[test] fn feedback_jpeg_previews_omit_the_alpha_channel() { let fx = Fx::new(&default_channels()); - let mut la = roughness(); - la.push((Dest::A, SourceRef::Constant(0.5))); - for (channels, expected) in [(la, vec![Dest::L]), (rgba_half_alpha(), vec![Dest::R, Dest::G, Dest::B])] { + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + + for (channels, expected) in [(gray_alpha, vec![Dest::L]), (rgba_half_alpha(), vec![Dest::R, Dest::G, Dest::B])] { let mut options = one_map(FileFormat::Png, 8, channels); let png_preview = MapPreview::sample(&fx.input(), &options, 0, 16).unwrap().unwrap(); options.maps.insert(0, MapOverride { format: Some(FileFormat::Jpeg), ..MapOverride::default() }); @@ -2206,11 +2209,13 @@ fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() { options.preset.maps[0].file = "Group/Map.$udim".into(); let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].layers[0].name, "Group/Map.1001"); options.preset.maps[0].file = "Map".into(); options.format_override = Some(FileFormat::Png); let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].name, "Map.1001.png"); } @@ -2235,6 +2240,7 @@ fn feedback_psd_tiled_and_untiled_sets_keep_both_documents() { assert_eq!(plans[3].1.name, "sphere_Body.1001_1.psd"); assert_eq!(plans[4].1.name, "sphere_Trim.psd"); let separate = list_outputs(&fx.project, 1, "sphere", &options).unwrap(); + assert_eq!(plans[0].1.name, separate[0].name, "individual desktop jobs agree with selection planning"); } @@ -2269,6 +2275,7 @@ fn psd_document_names_survive_sanitization_and_case_collisions() { assert!(separate.iter().any(|(set, name)| *set == index && name == unchanged)); } let tiled = list_outputs(&fx.project, 3, "sphere", &options).unwrap(); + assert!(tiled[0].udim_name.is_some()); assert_eq!(tiled[0].udim_name, tiled[1].udim_name, "tiles of one set keep the same pattern"); @@ -2312,10 +2319,12 @@ fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { fx.project.texture_sets[0].uv_tiles = (1001..1008).collect(); let smaller = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap(); + assert_eq!(smaller.len(), 7, "seven 128 MiB payloads fit with record overhead"); fx.project.texture_sets[0].uv_tiles.extend(1008..1034); let oversized = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB); + assert!(matches!(&oversized, Err(error) if error.to_string().contains("total PSD")), "the 33 individually valid tiles must be rejected as a batch"); let set = &fx.project.texture_sets[0]; diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs index 3bf375cf..19ee954f 100644 --- a/crates/formats/src/mesh_import/external.rs +++ b/crates/formats/src/mesh_import/external.rs @@ -79,6 +79,7 @@ fn read_inside(dir: &std::path::Path, rel: &str) -> Option> { if !file.starts_with(&root) { return None; } + crate::read_capped(&file, MAX_MESH_FILE_BYTES).ok() } @@ -178,20 +179,22 @@ mod tests { assert_eq!(read_inside(&dir, "tex/missing.png"), None); assert!(link_dir(&dir.join("out"), &outside), "this system would not make a link"); assert_eq!(read_inside(&dir, "out/key.txt"), None, "through a link to another folder"); - // A link that stays inside the folder is an ordinary shortcut and still works. + assert!(link_dir(&dir.join("shortcut"), &dir.join("tex")), "this system would not make a link"); assert_eq!(read_inside(&dir, "shortcut/a.png").as_deref(), Some(&b"inside"[..]), "through a link to a folder inside"); - // A link to a single outside file (Unix symbolic links; Windows file links need privileges). + + // Windows file links can require privileges #[cfg(unix)] { std::os::unix::fs::symlink(outside.join("key.txt"), dir.join("tex/key.png")).unwrap(); assert_eq!(read_inside(&dir, "tex/key.png"), None, "through a link to an outside file"); } - // The mesh's own folder reached through a link is fine: both sides are resolved. + + // Resolve the mesh folder and the linked target before comparing them assert!(link_dir(&base.join("alias"), &dir), "this system would not make a link"); assert_eq!(read_inside(&base.join("alias"), "tex/a.png").as_deref(), Some(&b"inside"[..]), "folder given through a link"); - // The same through read_mesh_file: the outside bytes must not end up in the glTF. + // Check the bytes embedded in the exported mesh std::fs::write( dir.join("m.gltf"), br#"{"asset": {"version": "2.0"}, "buffers": [{"uri": "out/key.txt", "byteLength": 7}, {"uri": "tex/a.png", "byteLength": 6}]}"#, diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml index 0b4bb7af..bff08e96 100644 --- a/crates/paint/Cargo.toml +++ b/crates/paint/Cargo.toml @@ -20,3 +20,4 @@ serde = { workspace = true } [dev-dependencies] epaint_default_fonts = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index d1a55036..ffc45e22 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -296,6 +296,9 @@ pub struct BrushSettings { pub size: f32, /// Pen pressure may shrink the size down to this fraction. pub min_size: f32, + /// Pen pressure shrinks the size towards `min_size`; on for projects saved before it could be turned off + #[serde(default = "pressure_on")] + pub size_pressure: bool, /// Per-stamp alpha 0..1. pub flow: f32, /// Caps a whole stroke 0..1. @@ -343,6 +346,7 @@ impl Default for BrushSettings { BrushSettings { size: 0.02, min_size: 0.05, + size_pressure: true, flow: 1.0, opacity: 1.0, spacing: 0.1, @@ -370,11 +374,15 @@ impl Default for BrushSettings { } impl BrushSettings { - /// Radius of a 2D (UV) stamp as a fraction of the UV square, for pen `pressure` 0..1: twice the - /// brush size, shrunk towards `min_size` by a light pen. Painting and the 2D cursor share it. + /// Radius of a 2D (UV) stamp as a fraction of the UV square at pen `pressure` 0..1: twice the brush size, shrunk towards `min_size` by a light pen (shared by painting and the 2D cursor) pub fn uv_stamp_radius(&self, pressure: f32) -> f32 { - let p = pressure.clamp(0.0, 1.0); - self.size * 2.0 * if p < 1.0 { self.min_size + (1.0 - self.min_size) * p } else { 1.0 } + self.size * 2.0 * self.pressure_size(pressure) + } + + /// The fraction of the size a stamp gets at pen `pressure` 0..1: full when size pressure is off + pub fn pressure_size(&self, pressure: f32) -> f32 { + let pressure = pressure.clamp(0.0, 1.0); + if self.size_pressure && pressure < 1.0 { self.min_size + (1.0 - self.min_size) * pressure } else { 1.0 } } /// Clamp every value into its valid range (input from UI, CLI or agents) @@ -415,8 +423,31 @@ impl BrushSettings { } } +fn pressure_on() -> bool { + true +} + #[cfg(test)] mod tests { + #[test] + fn size_pressure_off_keeps_a_light_pen_at_full_size() { + let pressed = BrushSettings { size: 0.1, min_size: 0.2, ..BrushSettings::default() }; + let mouse = BrushSettings { size_pressure: false, ..pressed.clone() }; + + assert!(pressed.uv_stamp_radius(0.3) < mouse.uv_stamp_radius(0.3)); + assert_eq!(mouse.uv_stamp_radius(0.3), mouse.uv_stamp_radius(1.0)); + } + + #[test] + fn settings_saved_before_the_size_pressure_switch_keep_pen_pressure() { + let mut saved = serde_json::to_value(BrushSettings { size_pressure: false, ..BrushSettings::default() }).unwrap(); + saved.as_object_mut().unwrap().remove("size_pressure"); + + let loaded: BrushSettings = serde_json::from_value(saved).unwrap(); + + assert!(loaded.size_pressure); + } + #[test] fn uv_stamp_radius_follows_pen_pressure() { let b = BrushSettings { size: 0.1, min_size: 0.5, ..BrushSettings::default() }; diff --git a/crates/paint/src/commit.rs b/crates/paint/src/commit.rs index e40548bf..d7d105bf 100644 --- a/crates/paint/src/commit.rs +++ b/crates/paint/src/commit.rs @@ -71,26 +71,34 @@ fn over(img: &mut TileImage, b: &Blend, src: &CommitSource, mut staged: Option) { +/// Blend the stroke's alpha tile `stroke_alpha` into tile `(tile_x, tile_y)` of an image (`dst`, `components` per texel) +fn blend_tile( + dst: &mut [u16], + components: usize, + stroke_alpha: &[u16], + (tile_x, tile_y): (u32, u32), + blend: &Blend, + source: &CommitSource, + carried: Option<&[u16]>, +) { // The last component is the coverage, the ones before it the value let value_count = components.saturating_sub(1); let opacity = source.opacity.clamp(0.0, 1.0); let gray_source = if source.erase || carried.is_some() { None } else { blend.gray }; - for i in 0..TILE_AREA { - let mut weight = from_u16(stroke_alpha.get(i).copied().unwrap_or(0)) * opacity; + for texel_index in 0..TILE_AREA { + let mut weight = from_u16(stroke_alpha.get(texel_index).copied().unwrap_or(0)) * opacity; if weight <= 0.0 { continue; } let mut stencil = None; - let (x, y) = (tx * TILE + i as u32 % TILE, ty * TILE + i as u32 / TILE); + let (x, y) = (tile_x * TILE + texel_index as u32 % TILE, tile_y * TILE + texel_index as u32 / TILE); if let Some(per_texel) = source.per_texel { match per_texel(x, y) { Some((color, alpha_factor)) => { weight *= alpha_factor; - stencil = Some(color); + stencil = color; } None => continue, } @@ -99,13 +107,16 @@ fn blend_tile(dst: &mut [u16], components: usize, stroke_alpha: &[u16], (tx, ty) } } - let Some((coverage_slot, values)) = dst.get_mut(i * components..(i + 1) * components).and_then(<[u16]>::split_last_mut) else { continue }; + let Some((coverage_slot, values)) = dst.get_mut(texel_index * components..(texel_index + 1) * components).and_then(<[u16]>::split_last_mut) else { + continue; + }; + let gray = gray_source.map(|gray| gray.at(x, y, (source.alpha.width(), source.alpha.height()))); let coverage = from_u16(*coverage_slot); for (component, slot) in values.iter_mut().enumerate() { let previous = dec(blend.kind, *slot); let target = match (carried, stencil) { - (Some(carried_tile), _) => dec(blend.kind, carried_tile.get(i * value_count + component).copied().unwrap_or(0)), + (Some(carried_tile), _) => dec(blend.kind, carried_tile.get(texel_index * value_count + component).copied().unwrap_or(0)), (None, _) if let Some(gray) = gray => gray, (None, Some(color)) if blend.stencil_color => color.get(component).copied().unwrap_or(0.0), _ => blend.value.get(component).copied().unwrap_or(0.0), @@ -318,8 +329,8 @@ fn mask_blend<'a>(gray: &'a MaskGray, value: &'a [f32; 1]) -> Blend<'a> { Blend { kind: ChannelKind::Scalar, value, stencil_color: false, carried: None, gray } } -/// Per-texel override of a stroke: `(x, y)` → (base color, alpha factor), None = no paint. -pub type TexelFn<'a> = &'a (dyn Fn(u32, u32) -> Option<([f32; 3], f32)> + Sync); +/// Per-texel override of a stroke: `(x, y)` → (base color, alpha factor), None = no paint; a None color keeps the stroke's own value +pub type TexelFn<'a> = &'a (dyn Fn(u32, u32) -> Option<(Option<[f32; 3]>, f32)> + Sync); /// The stroke being committed: its alpha, touched tiles, opacity cap and mode. #[derive(Clone, Copy)] @@ -328,7 +339,7 @@ pub struct CommitSource<'a> { pub tiles: &'a BTreeSet<(u32, u32)>, pub opacity: f32, pub erase: bool, - /// Projection tool: base color and alpha per texel from a stencil. + /// The stencil: alpha per texel and, on the Projection tool, base color pub per_texel: Option>, /// Clone and smudge: straight values per channel carried by the stroke (replace `values`). pub carried: Option<&'a BTreeMap>, diff --git a/crates/paint/src/stroke.rs b/crates/paint/src/stroke.rs index fcca6427..5aef41cb 100644 --- a/crates/paint/src/stroke.rs +++ b/crates/paint/src/stroke.rs @@ -125,11 +125,13 @@ impl Stroke { all } + /// The stamp radius at `pos` under `pressure`, scaled by its distance from the camera for a screen-space brush fn radius_at(&self, ctx: &PickCtx, pos: Vec3, pressure: f32) -> f32 { - let p = pressure.clamp(0.0, 1.0); - let scale = self.settings.min_size + (1.0 - self.settings.min_size) * p; - let r = self.radius * if pressure < 1.0 { scale } else { 1.0 }; - if self.settings.screen_space { r * (pos.distance(ctx.camera.eye()) / ctx.camera.distance.max(1e-4)) } else { r } + // Keeps the screen-space scale finite with the camera on its target + const MIN_CAMERA_DISTANCE: f32 = 1e-4; + + let radius = self.radius * self.settings.pressure_size(pressure); + if self.settings.screen_space { radius * (pos.distance(ctx.camera.eye()) / ctx.camera.distance.max(MIN_CAMERA_DISTANCE)) } else { radius } } fn feed(&mut self, ctx: &PickCtx, screen: Vec2, pressure: f32, depth: u32, out: &mut Vec) { diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 1e045f28..0f7d2e2e 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -31,3 +31,7 @@ wasm-bindgen-futures = "0.4" [dev-dependencies] image = { workspace = true } texturecraft-formats = { workspace = true } + +# The noop backend stands in for an adapter without compute shaders in the headless tests. +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +wgpu = { workspace = true, features = ["noop"] } diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index 0a8a357c..dbfe1860 100644 --- a/crates/render/src/gpu_bake.rs +++ b/crates/render/src/gpu_bake.rs @@ -121,9 +121,7 @@ pub fn raytracing_available() -> bool { } fn bake_adapter() -> Result<(wgpu::Adapter, String, wgpu::Limits), String> { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); - let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }; - let adapter = pollster::block_on(instance.request_adapter(&options)).map_err(|e| format!("no GPU adapter: {e}"))?; + let adapter = crate::headless::adapter()?; let info = adapter.get_info(); let limits = adapter.limits(); let flags = adapter.get_downlevel_capabilities().flags; @@ -134,7 +132,7 @@ fn bake_adapter() -> Result<(wgpu::Adapter, String, wgpu::Limits), String> { Ok((adapter, info.name, limits)) } -fn unsupported_adapter(device_type: wgpu::DeviceType, flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> Option<&'static str> { +pub(crate) fn unsupported_adapter(device_type: wgpu::DeviceType, flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> Option<&'static str> { if device_type == wgpu::DeviceType::Cpu { return Some("is a software renderer"); } diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 5d092a0f..e79574e8 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -834,7 +834,17 @@ mod tests { } fn gpu() -> Option<(Headless, GpuTracer)> { - let Ok(h) = Headless::new() else { + gpu_on(Headless::new()) + } + + /// A tracer on a device whose buffers hold at most 256 MiB, as wgpu's default limits do: a GPU's + /// own limits (several GiB on a desktop card) would let an 8192² render succeed. + fn small_buffer_gpu() -> Option<(Headless, GpuTracer)> { + gpu_on(Headless::with_buffer_cap(256 << 20)) + } + + fn gpu_on(headless: Result) -> Option<(Headless, GpuTracer)> { + let Ok(h) = headless else { eprintln!("skipping: no GPU adapter"); return None; }; @@ -908,7 +918,7 @@ mod tests { /// Rejecting an oversized render preserves the image and lets tracing continue. #[test] fn failed_reset_retains_the_active_render() { - let Some((mut headless, mut tracer)) = gpu() else { return }; + let Some((mut headless, mut tracer)) = small_buffer_gpu() else { return }; let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE); let camera = camera(); let settings = TraceSettings::default(); diff --git a/crates/render/src/headless.rs b/crates/render/src/headless.rs index f22dd1d4..a5241dd2 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -9,15 +9,89 @@ pub struct Headless { pub adapter_name: String, } +/// The adapter for work without a window (renders, path tracing, GPU baking). Like the desktop app, +/// it honours `WGPU_ADAPTER_NAME` (part of the adapter's name or backend, any case) and `WGPU_POWER_PREF` +/// (`high`, the default, `low` or `none`); the instance reads wgpu's other variables +/// (`WGPU_BACKEND`, `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER`, ...). +pub fn adapter() -> Result { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let power = wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::HighPerformance); + if let Ok(name) = std::env::var("WGPU_ADAPTER_NAME") { + let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())); + let infos: Vec = adapters.iter().map(wgpu::Adapter::get_info).collect(); + if let Some(a) = pick_adapter(&infos, &name, power).and_then(|i| adapters.into_iter().nth(i)) { + return Ok(a); + } + log::warn!("no GPU adapter matches WGPU_ADAPTER_NAME `{name}`; choosing by power preference"); + } + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() })) + .map_err(|e| format!("no GPU adapter: {e}")) +} + +/// Which of `infos` `WGPU_ADAPTER_NAME=name` picks. Several adapters may match (the same GPU on two +/// backends, two GPUs of one vendor): rank them as the desktop app's selector does, hardware before +/// software, then `power`, then native backends before OpenGL, then the listing order. +fn pick_adapter(infos: &[wgpu::AdapterInfo], name: &str, power: wgpu::PowerPreference) -> Option { + use wgpu::{Backend, DeviceType, PowerPreference}; + let wanted = name.to_lowercase(); + infos + .iter() + .enumerate() + .filter(|(_, info)| info.name.to_lowercase().contains(&wanted) || format!("{:?}", info.backend).to_lowercase().contains(&wanted)) + .min_by_key(|(index, info)| { + let lower = info.name.to_lowercase(); + let software = info.device_type == DeviceType::Cpu || ["llvmpipe", "lavapipe", "warp"].iter().any(|s| lower.contains(s)); + let power_rank = match (power, info.device_type) { + (PowerPreference::None, DeviceType::Cpu) => 1, + (PowerPreference::None, _) => 0, + (PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 0, + (PowerPreference::LowPower, DeviceType::DiscreteGpu) | (PowerPreference::HighPerformance, DeviceType::IntegratedGpu) => 1, + (_, DeviceType::Other) => 2, + (_, DeviceType::VirtualGpu) => 3, + (_, DeviceType::Cpu) => 4, + }; + let backend_rank = match (power, info.backend) { + (PowerPreference::None, _) | (_, Backend::Vulkan | Backend::Metal | Backend::Dx12) => 0, + (_, Backend::Gl) => 1, + _ => 2, + }; + (software, power_rank, backend_rank, *index) + }) + .map(|(index, _)| index) +} + +/// A device on `adapter` with all its limits. The viewport draws with fragment passes only, so an +/// adapter without compute shaders (WebGL2-class, or the GL driver WSL2 offers on an integrated GPU) +/// still renders it; the GPU path tracer checks the device's limits itself. +fn device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue), String> { + device_with_limits(adapter, adapter.limits()) +} + +fn device_with_limits(adapter: &wgpu::Adapter, limits: wgpu::Limits) -> Result<(wgpu::Device, wgpu::Queue), String> { + let desc = wgpu::DeviceDescriptor { label: Some("tc_headless"), required_limits: limits, ..Default::default() }; + pollster::block_on(adapter.request_device(&desc)).map_err(|e| format!("no GPU device on {}: {e}", adapter.get_info().name)) +} + impl Headless { - /// Create a device on the default adapter. Errors when no GPU (or software) adapter exists. + /// Create a device on [`adapter`]. Errors when no GPU (or software) adapter exists. pub fn new() -> Result { - let instance = wgpu::Instance::default(); - let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).map_err(|e| format!("no GPU adapter: {e}"))?; - let adapter_name = adapter.get_info().name; - let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).map_err(|e| format!("no GPU device: {e}"))?; + let adapter = adapter()?; + let (device, queue) = device(&adapter)?; let renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); - Ok(Headless { device, queue, renderer, adapter_name }) + Ok(Headless { device, queue, renderer, adapter_name: adapter.get_info().name }) + } + + /// A device whose buffers are capped at `bytes` (or the adapter's own limit when that is lower), + /// so tests of "too big for this GPU" paths do not depend on how large the machine's limits are. + #[cfg(test)] + pub(crate) fn with_buffer_cap(bytes: u64) -> Result { + let adapter = adapter()?; + let mut limits = adapter.limits(); + limits.max_buffer_size = limits.max_buffer_size.min(bytes); + limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(bytes); + let (device, queue) = device_with_limits(&adapter, limits)?; + let renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); + Ok(Headless { device, queue, renderer, adapter_name: adapter.get_info().name }) } /// Render a frame and read it back as RGBA8 (sRGB-encoded). @@ -28,3 +102,72 @@ impl Headless { self.renderer.read_view(&self.device, &self.queue, frame.view_id) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// An adapter without compute shaders still gets a device for the viewport. wgpu's noop backend + /// stands in for one (WSL2's GL driver on an Intel GPU, a WebGL2-class GPU): asking it for + /// `Limits::default()` failed with "Limit 'max_compute_workgroups_per_dimension' value 65535 is + /// better than allowed 0". + #[test] + fn an_adapter_without_compute_shaders_gets_a_device() { + let noop = wgpu::NoopBackendOptions { enable: true, limits: Some(wgpu::Limits::downlevel_webgl2_defaults()), ..Default::default() }; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::NOOP, + backend_options: wgpu::BackendOptions { noop, ..Default::default() }, + ..wgpu::InstanceDescriptor::new_without_display_handle() + }); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); + assert_eq!(adapter.limits().max_compute_workgroups_per_dimension, 0); + device(&adapter).unwrap(); + } + + fn info(name: &str, device_type: wgpu::DeviceType, backend: wgpu::Backend) -> wgpu::AdapterInfo { + wgpu::AdapterInfo { name: name.into(), ..wgpu::AdapterInfo::new(device_type, backend) } + } + + /// A `WGPU_ADAPTER_NAME` that several adapters match still follows `WGPU_POWER_PREF`, and an + /// empty one matches them all. + #[test] + fn a_name_several_adapters_match_follows_the_power_preference() { + use wgpu::{Backend::*, DeviceType::*, PowerPreference as P}; + let gpus = [ + info("Intel(R) Iris(R) Xe Graphics", IntegratedGpu, Vulkan), + info("Intel(R) Arc(TM) A770", DiscreteGpu, Vulkan), + info("llvmpipe (LLVM 15)", Cpu, Gl), + ]; + assert_eq!(pick_adapter(&gpus, "intel", P::HighPerformance), Some(1)); + assert_eq!(pick_adapter(&gpus, "intel", P::LowPower), Some(0)); + assert_eq!(pick_adapter(&gpus, "INTEL", P::None), Some(0)); + assert_eq!(pick_adapter(&gpus, "", P::HighPerformance), Some(1)); + assert_eq!(pick_adapter(&gpus, "llvm", P::HighPerformance), Some(2)); + assert_eq!(pick_adapter(&gpus, "gl", P::HighPerformance), Some(2)); + assert_eq!(pick_adapter(&gpus, "nvidia", P::HighPerformance), None); + // One GPU on two backends: the native one before OpenGL. + let twice = [info("D3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Gl), info("Microsoft Direct3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Vulkan)]; + assert_eq!(pick_adapter(&twice, "rtx 4050", P::HighPerformance), Some(1)); + } + + /// On an adapter with WebGL2-class limits (no compute shaders) the viewport renderer still builds, + /// the GPU path tracer and the GPU baker each refuse with a message instead of panicking. + #[test] + fn an_adapter_without_compute_shaders_gets_an_error_not_a_panic() { + let noop = wgpu::NoopBackendOptions { enable: true, limits: Some(wgpu::Limits::downlevel_webgl2_defaults()), ..Default::default() }; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::NOOP, + backend_options: wgpu::BackendOptions { noop, ..Default::default() }, + ..wgpu::InstanceDescriptor::new_without_display_handle() + }); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); + let (device, queue) = device(&adapter).unwrap(); + let _renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); + assert!(!crate::gpu_trace::GpuTracer::supported(&device)); + let err = crate::gpu_trace::GpuTracer::new(&device).err().expect("the tracer needs compute shaders"); + assert!(err.contains("compute shaders"), "{err}"); + let flags = adapter.get_downlevel_capabilities().flags; + let reason = crate::gpu_bake::unsupported_adapter(wgpu::DeviceType::IntegratedGpu, flags, &adapter.limits()); + assert!(reason.is_some_and(|r| r.contains("compute")), "{reason:?}"); + } +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 64b44d9a..2eadf143 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -398,6 +398,20 @@ pub fn aux_size(size: (u32, u32)) -> u32 { impl Tex { fn new(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, mips: u32) -> Tex { + // COPY_SRC: the GPU path tracer copies the display textures into its arrays. + let usage = + wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC; + Self::with_usage(device, label, w, h, format, mips, usage) + } + + /// The environment map, uploaded from the CPU and sampled, never drawn into. As a render target + /// it would need float color buffers, which GLES and WebGL2 may lack (see [`hdr_renderable`]). + fn environment(device: &wgpu::Device, w: u32, h: u32) -> Tex { + let usage = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST; + Self::with_usage(device, "tc_env", w, h, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS, usage) + } + + fn with_usage(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, mips: u32, usage: wgpu::TextureUsages) -> Tex { let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some(label), size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, @@ -405,11 +419,7 @@ impl Tex { sample_count: 1, dimension: wgpu::TextureDimension::D2, format, - // COPY_SRC: the GPU path tracer copies the display textures into its arrays. - usage: wgpu::TextureUsages::TEXTURE_BINDING - | wgpu::TextureUsages::COPY_DST - | wgpu::TextureUsages::RENDER_ATTACHMENT - | wgpu::TextureUsages::COPY_SRC, + usage, view_formats: &[], }); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); @@ -1245,7 +1255,7 @@ impl Renderer { layout: &refraction_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }], }); - let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + let env = Tex::environment(device, PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1]); let mut renderer = Renderer { target_format, @@ -1336,7 +1346,7 @@ impl Renderer { let levels = ibl::prefilter(&img, ENV_LEVELS); if self.env.texture.width() != img.width || self.env.texture.height() != img.height { - self.env = Tex::new(device, "tc_env", img.width, img.height, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + self.env = Tex::environment(device, img.width, img.height); } for (l, lv) in levels.iter().enumerate() { let bytes: Vec = lv.data.iter().flat_map(|c| [c[0], c[1], c[2], 1.0]).flat_map(|v| half::f16::from_f32(v).to_le_bytes()).collect(); @@ -2640,6 +2650,23 @@ mod tests { h.renderer.display_textures()[0][0].width() } + /// The environment map is only uploaded and sampled. A render target usage would ask for float + /// color buffers, which GLES and WebGL2 adapters may not have. + #[test] + fn the_environment_map_is_not_a_render_target() { + let Ok(mut h) = Headless::new() else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let usage = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST; + assert_eq!(h.renderer.env.texture.usage(), usage, "the built-in environment"); + // An imported image of another size makes a new texture. + let image = ImageRes::new(256, 128, vec![[0.5, 0.5, 0.5, 1.0]; 256 * 128], false); + h.renderer.set_environment(&h.device, &h.queue, "resource:grey", Some(&image)); + assert_eq!(h.renderer.env.texture.width(), 256); + assert_eq!(h.renderer.env.texture.usage(), usage, "an imported environment"); + } + fn prepare(h: &mut Headless) { let mut enc = h.device.create_command_encoder(&Default::default()); h.renderer.resolve_pending(&h.device); diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 269cde1e..274690a6 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -70,8 +70,8 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: let wanted = if wasm { web } else { desktop }; let mut out = String::new(); for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { - let f: Vec<&str> = line.split(" | ").map(str::trim).collect(); - let [family, style, file, scripts, ..] = f.as_slice() else { + let fields: Vec<&str> = line.split(" | ").map(str::trim).collect(); + let [family, style, file, scripts, ..] = fields.as_slice() else { return Err(format!("malformed manifest line: {line}")); }; @@ -82,9 +82,9 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: let mut path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; println!("cargo::rerun-if-changed={}", path.display()); let tags: Vec<&str> = scripts.split(',').map(str::trim).filter(|s| !s.is_empty()).collect(); - // The Latin faces lose their Private Use Area everywhere; a web build also cuts its CJK - // faces to the characters the shipped catalogs use. The desktop keeps its CJK faces whole: - // the same face draws text the app never ships, a user's Japanese file name. + + // Leave the Private Use Area to the icon font + // Desktop CJK fonts also cover user file names outside the catalogs let cut = rel == LATIN_MANIFEST || (wasm && !catalogs.is_empty() && tags.iter().any(|tag| CJK_SCRIPTS.contains(tag))); if cut { let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?; diff --git a/crates/ui-egui/i18n_build.rs b/crates/ui-egui/i18n_build.rs index 1065757c..25de61b3 100644 --- a/crates/ui-egui/i18n_build.rs +++ b/crates/ui-egui/i18n_build.rs @@ -46,7 +46,7 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat Some(_) => String::from("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[\n"), None => String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"), }; - let close = |mut source: String| { + let finish_source = |mut source: String| { source.push_str("];\n"); source.push_str(if deflated_in.is_some() { INFLATE_FN @@ -55,11 +55,13 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat }); source }; + let Some(dir) = dir else { if required { return Err("CRAFT_I18N_REQUIRED=1 requires CRAFT_I18N_DIR".into()); } - return Ok((close(source), Vec::new())); + + return Ok((finish_source(source), Vec::new())); }; if !dir.is_absolute() { @@ -69,6 +71,7 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat let locales = dir.join("locales"); let entries = std::fs::read_dir(&locales).map_err(|e| format!("{}: {e}", locales.display()))?; println!("cargo::rerun-if-changed={}", locales.display()); + let mut paths = Vec::new(); for entry in entries { let entry = entry.map_err(|e| e.to_string())?; @@ -80,7 +83,8 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat paths.sort(); let mut count = 0; let mut catalogs = Vec::new(); - let mut characters = Vec::new(); + let mut characters = std::collections::HashSet::new(); + for path in paths { // Watch directories so adding or removing an app catalog rebuilds the embedding println!("cargo::rerun-if-changed={}", path.display()); @@ -104,9 +108,11 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat } None => format!("include_str!({name:?})"), }; + // The shared runtime needs static inputs for this short-lived build process Ok((include, Box::leak(text.into_boxed_str()))) }; + let empty = if deflated_in.is_some() { "&[]" } else { "\"\"" }; let (shared, shared_text) = if common.is_file() { embed(&common)? } else { (empty.into(), "") }; let (app, app_text) = embed(&app)?; @@ -116,6 +122,7 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat let _ = writeln!(source, " ({locale:?}, {shared}, {app}),"); count += 1; } + if required && count == 0 { return Err("no TextureCraft translation catalogs found".into()); } @@ -127,9 +134,9 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; "))); } + let mut characters: Vec<_> = characters.into_iter().collect(); characters.sort_unstable(); - characters.dedup(); - Ok((close(source), characters)) + Ok((finish_source(source), characters)) } /// Write the embedding for both desktop and wasm, reporting optional failures as warnings. diff --git a/crates/ui-egui/src/alpha_choice.rs b/crates/ui-egui/src/alpha_choice.rs new file mode 100644 index 00000000..234601d0 --- /dev/null +++ b/crates/ui-egui/src/alpha_choice.rs @@ -0,0 +1,12 @@ +//! What the brush Alpha slot's picker offers + +use texturecraft_engine::paint::BrushAlpha; + +/// One tile of the Alpha slot's picker: a built-in shape, a library alpha, an image resource, or importing one +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum AlphaChoice { + Shape(BrushAlpha), + Library(&'static str), + Image(String), + Import, +} diff --git a/crates/ui-egui/src/alpha_sheet.rs b/crates/ui-egui/src/alpha_sheet.rs new file mode 100644 index 00000000..1123b2b7 --- /dev/null +++ b/crates/ui-egui/src/alpha_sheet.rs @@ -0,0 +1,297 @@ +//! The Alpha section of a paint tool's Properties: the alpha's slot with its picker, its Parameters beside a picture of the shape they make, and the Text band + +use std::ops::RangeInclusive; + +use egui::{Color32, CornerRadius, Painter, Rect, Stroke, Ui, pos2}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::Session; +use texturecraft_engine::core::Channel; +use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; + +use crate::TextureCraftApp; +use crate::alpha_choice::AlphaChoice; +use crate::brush_pictures::alpha_image; +use crate::brush_stroke_preview::BrushStrokePreview; +use crate::i18n::{n_, tr}; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::theme::Tokens; +use crate::tile_picture::TilePicture; + +/// Hardness, Roundness and Size X / Y, in percent +const HARDNESS_PERCENT_RANGE: RangeInclusive = 0.0..=99.9; +const ROUNDNESS_PERCENT_RANGE: RangeInclusive = 0.0..=100.0; +const ALPHA_SIZE_PERCENT_RANGE: RangeInclusive = 5.0..=100.0; + +/// Rows the text box shows before it scrolls +const TEXT_ROWS: usize = 2; + +/// Air inside the text box, around its words +const TEXT_BOX_MARGIN: i8 = 6; + +/// Corner radius of the text box, as the sheet's fields +const TEXT_BOX_ROUNDING: u8 = 3; + +/// Width of the text box's outline +const TEXT_BOX_OUTLINE_WIDTH: f32 = 1.0; + +/// The Alpha section: the alpha's slot, its Parameters band and the Text band +pub(crate) fn alpha_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + alpha_slot(app, sheet); + parameters_band(app, sheet); + + if sheet.band(tr("Text"), false, None, None).open { + text_rows(app, sheet); + } +} + +/// The slot showing the alpha in use; a click opens the picker of shapes, library alphas and images, × goes back to the Round shape +fn alpha_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let ctx = sheet.ui.ctx().clone(); + let current = current_choice(&app.session); + let brush = &app.session.tool.brush; + let hardness = brush.hardness; + let (name, source, texture) = match ¤t { + AlphaChoice::Image(name) => { + let texture = app.session.images.get(name).map(|image| app.thumbs.image(&ctx, name, image)); + (name.clone(), tr("Imported image"), texture) + } + AlphaChoice::Library(id) => { + let alpha = alphas::find(id); + let texture = alpha.and_then(|alpha| app.thumbs.alpha(&ctx, alpha)); + (alpha.map_or_else(|| (*id).to_owned(), |alpha| tr(&alpha.label).to_owned()), tr("Library alpha"), texture) + } + AlphaChoice::Shape(_) | AlphaChoice::Import => (tr(brush.alpha.label()).to_owned(), tr("Built-in shape"), None), + }; + let shape = brush.alpha; + let thumbnail = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, Color32::BLACK); + match &texture { + Some(texture) => { + painter.image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + None => crate::thumbs::paint_alpha(painter, rect, shape, hardness), + } + }; + + // The default Round shape has nothing to clear back to + let clearable = current != AlphaChoice::Shape(BrushAlpha::default()); + let slot = sheet.slot(&thumbnail, &name, source, None, clearable, false); + + let popup = sheet.ui.make_persistent_id("brush_alpha_source"); + if slot.pick.clicked() { + resource_picker::toggle(&ctx, popup); + } + let tabs = || alpha_tabs(&app.session, hardness); + match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), true, tabs) { + Some(AlphaChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(choice) if choice != current => { + app.run("tool.brush", json!({ "alpha": alpha_value(&choice) })); + } + _ => {} + } + if slot.clear { + app.run("tool.brush", json!({ "alpha": BrushAlpha::default().label() })); + } + + // An alpha from the Assets panel, or an image, dropped on the slot becomes the alpha + crate::shelf::drop_target(app, sheet.ui, &slot.pick, crate::shelf::DropZone::Brush); + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + app.run("tool.brush", json!({ "alpha": { "image": name } })); + } + sheet.close_card(); +} + +/// The picker's choice the brush's alpha is +fn current_choice(session: &Session) -> AlphaChoice { + let brush = &session.tool.brush; + match (&brush.alpha_image, brush.alpha_library.as_deref().and_then(alphas::find)) { + (Some(name), _) => AlphaChoice::Image(name.clone()), + (None, Some(alpha)) => AlphaChoice::Library(alpha.id.as_str()), + (None, None) => AlphaChoice::Shape(brush.alpha), + } +} + +/// What `tool.brush` takes as `alpha` for `choice` +fn alpha_value(choice: &AlphaChoice) -> Value { + match choice { + AlphaChoice::Shape(shape) => json!(shape.label()), + AlphaChoice::Library(id) => json!({ "library": id }), + AlphaChoice::Image(name) => json!({ "image": name }), + AlphaChoice::Import => Value::Null, + } +} + +/// The picker's one tab: the built-in Shapes at the brush's `hardness`, the library's Alphas in their shelf groups, then Textures with Import... first +fn alpha_tabs(session: &Session, hardness: f32) -> Vec> { + let shapes = BrushAlpha::ALL + .into_iter() + .map(|shape| ResourcePickerItem { + id: AlphaChoice::Shape(shape), + label: tr(shape.label()).to_owned(), + caption: None, + picture: TilePicture::Shape(shape, hardness), + }) + .collect(); + let library = alphas::library() + .iter() + .map(|alpha| ResourcePickerItem { + id: AlphaChoice::Library(alpha.id.as_str()), + label: tr(&alpha.label).to_owned(), + caption: Some(tr(alpha.category)), + picture: TilePicture::Alpha(alpha), + }) + .collect(); + let textures = ResourcePickerItem::textures(session, AlphaChoice::Import, |name| AlphaChoice::Image(name.to_owned())); + let groups = [(n_("Shapes"), shapes), (n_("Alphas"), library), (n_("Textures"), textures)] + .into_iter() + .map(|(header, items)| PickerGroup { header: Some(tr(header)), items }) + .collect(); + vec![PickerTab { icon: ic::CIRCLE_HALF, name: tr("Alphas"), groups }] +} + +/// Hardness and the parameters every alpha shares beside the shape they make; the band's reset puts them all back +fn parameters_band(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let tokens = Tokens::get(sheet.ui.ctx()); + let image = app.session.tool.brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)).cloned(); + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); + let fields = |settings: &BrushSettings| (settings.hardness, settings.alpha_params); + let band = sheet.band(tr("Parameters"), true, Some(fields(brush) != fields(&defaults)), None); + if band.reset { + (brush.hardness, brush.alpha_params) = fields(&defaults); + } + if !band.open { + return; + } + + let shown = brush.clone(); + let ctx = sheet.ui.ctx().clone(); + let tint = tokens.text.to_array(); + let picture = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + BrushStrokePreview::paint_picture(&ctx, painter, rect, "brush_alpha_picture", (&shown, image.as_ref()), |_| [tint[0], tint[1], tint[2]], alpha_image); + }; + + // Only the procedural Round shape has a roundness + let round = brush.alpha == BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none(); + let before = [brush.hardness, brush.alpha_params.roundness, brush.alpha_params.size_x, brush.alpha_params.size_y].map(|fraction| fraction * 100.0); + let [mut hardness, mut roundness, mut size_x, mut size_y] = before; + let percent = |label: &'static str, value, range: RangeInclusive| StackSlider { + label: tr(label), + value, + range: range.clone(), + typed: range, + decimals: 0, + suffix: "", + dial: false, + }; + if round { + sheet.picture_sliders( + &picture, + &mut [ + percent(n_("Hardness"), &mut hardness, HARDNESS_PERCENT_RANGE), + percent(n_("Roundness"), &mut roundness, ROUNDNESS_PERCENT_RANGE), + percent(n_("Size X"), &mut size_x, ALPHA_SIZE_PERCENT_RANGE), + percent(n_("Size Y"), &mut size_y, ALPHA_SIZE_PERCENT_RANGE), + ], + ); + } else { + sheet.picture_sliders( + &picture, + &mut [ + percent(n_("Hardness"), &mut hardness, HARDNESS_PERCENT_RANGE), + percent(n_("Size X"), &mut size_x, ALPHA_SIZE_PERCENT_RANGE), + percent(n_("Size Y"), &mut size_y, ALPHA_SIZE_PERCENT_RANGE), + ], + ); + } + + // Only what moved is written back, so an untouched value keeps its exact fraction + for (after, was, fraction) in [ + (hardness, before[0], &mut brush.hardness), + (roundness, before[1], &mut brush.alpha_params.roundness), + (size_x, before[2], &mut brush.alpha_params.size_x), + (size_y, before[3], &mut brush.alpha_params.size_y), + ] { + if after != was { + *fraction = after / 100.0; + } + } + sheet.slider(tr("Contrast"), &mut brush.alpha_params.contrast, 1.0..=MAX_ALPHA_CONTRAST, 2); + sheet.toggle(tr("Invert"), &mut brush.alpha_params.invert); + *brush = brush.sanitized(); +} + +/// Text drawn in a font, as the brush alpha or a decal (`resource.text`) +fn text_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + if app.ui.text.fonts.is_empty() + && let Some(fonts) = app.run("text.fonts", Value::Null) + { + let installed = fonts["installed"].as_array().into_iter().flatten().map(|font| { + let styles = font["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + (font["family"].as_str().unwrap_or_default().to_string(), styles) + }); + let built_in = fonts["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|name| (name.to_string(), Vec::new())); + app.ui.text.fonts = installed.chain(built_in).collect(); + } + + // A decal shows the text in the tool's base color; an alpha must stay white + let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]); + let tokens = Tokens::get(sheet.ui.ctx()); + let text = &mut app.ui.text; + sheet.embed(|ui: &mut Ui| { + let frame = egui::Frame::NONE + .fill(tokens.field) + .stroke(Stroke::new(TEXT_BOX_OUTLINE_WIDTH, tokens.field_border)) + .corner_radius(CornerRadius::same(TEXT_BOX_ROUNDING)) + .inner_margin(egui::Margin::same(TEXT_BOX_MARGIN)); + frame.show(ui, |ui| { + let edit = + egui::TextEdit::multiline(&mut text.text).frame(egui::Frame::NONE).desired_rows(TEXT_ROWS).desired_width(f32::INFINITY).hint_text(tr("Text")); + ui.add(edit); + }); + }); + + // Index 0 is the default font, then the families in the order `text.fonts` lists them + let family = text.fonts.iter().position(|(family, _)| *family == text.font).map_or(0, |index| index + 1); + let family_name = |index: usize| if index == 0 { tr("Default").to_owned() } else { text.fonts[index - 1].0.clone() }; + let (picked, _) = sheet.dropdown_built(tr("Font"), family, || 0..=text.fonts.len(), family_name, None); + if let Some(index) = picked { + text.font = if index == 0 { String::new() } else { text.fonts[index - 1].0.clone() }; + text.style = String::new(); + } + + let styles = text.fonts.iter().find(|(family, _)| *family == text.font).map(|(_, styles)| styles.clone()).unwrap_or_default(); + if styles.len() > 1 { + let style = styles.iter().position(|style| *style == text.style).map_or(0, |index| index + 1); + let style_name = |index: usize| if index == 0 { tr("Default").to_owned() } else { styles[index - 1].clone() }; + let (picked, _) = sheet.dropdown_built(tr("Style"), style, || 0..=styles.len(), style_name, None); + if let Some(index) = picked { + text.style = if index == 0 { String::new() } else { styles[index - 1].clone() }; + } + } + + let mut params = + json!({"text": text.text, "font": (!text.font.is_empty()).then_some(&text.font), "style": (!text.style.is_empty()).then_some(&text.style)}); + let ready = !text.text.trim().is_empty(); + let alpha = sheet.button_enabled(ic::CIRCLE_HALF, tr("Use as brush alpha"), false, ready).clicked(); + let decal = sheet.button_enabled(ic::STAMP, tr("Place as decal"), false, ready).clicked(); + if decal { + params["color"] = json!(color); + } + if (alpha || decal) + && let Some(name) = app.run("resource.text", params).and_then(|result| result["name"].as_str().map(str::to_string)) + { + if alpha { + app.run("tool.brush", json!({"alpha": {"image": name}})); + } else { + app.run("layer.add.decal", json!({"image": name})); + } + } +} diff --git a/crates/ui-egui/src/brush_pictures.rs b/crates/ui-egui/src/brush_pictures.rs new file mode 100644 index 00000000..a4f09487 --- /dev/null +++ b/crates/ui-egui/src/brush_pictures.rs @@ -0,0 +1,154 @@ +//! Pictures of what the brush settings do: the brush's stamp turned to its Angle, a strip of jittered dabs and the alignment modes + +use egui::{ColorImage, Painter, Pos2, Rect, Shape, Stroke, pos2}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::paint::{Alignment, BrushSettings}; + +use crate::preview_image::stroke_strip; +use crate::theme::Tokens; + +/// The stamp's radius in the Orientation picture, as a share of half its side: room for the dial's ring around it +const STAMP_RADIUS_SHARE: f32 = 0.62; + +/// The dial's ring radius, as a share of half the picture's side +const RING_RADIUS_SHARE: f32 = 0.86; + +/// How far the Angle tick reaches in and out of the ring, in points +const TICK_REACH: f32 = 3.0; + +/// The ring's and the tick's line widths, in points +const RING_WIDTH: f32 = 1.0; +const TICK_WIDTH: f32 = 2.0; + +/// How far a dab may reach from the strip's centre line, as a share of half its height +const STRIP_REACH_SHARE: f32 = 0.85; + +/// The least spacing between the strip's dabs, in stamp diameters, so each dab reads on its own +const STRIP_DAB_SPACING: f32 = 1.4; + +/// The brush's own stamp turned to its Angle, alone in a `size` square: jitter, flow and opacity left out so only the shape and its turn show +pub(crate) fn stamp_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], _pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + let still = BrushSettings { + jitter_size: 0.0, + jitter_angle: 0.0, + jitter_flow: 0.0, + jitter_position: 0.0, + follow_path: false, + flow: 1.0, + opacity: 1.0, + ..brush.clone() + }; + let center = (size[0] as f32 * 0.5, size[1] as f32 * 0.5); + let radius = center.0.min(center.1) * STAMP_RADIUS_SHARE; + + // A curve that stays put lays exactly one stamp + stroke_strip(&still, image, size, |_| radius, |_| center, |x| column_tint(tints, x)) +} + +/// The brush's alpha as its Parameters shape it, upright: the Alpha section's Parameters picture +pub(crate) fn alpha_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + stamp_image(&BrushSettings { angle: 0.0, ..brush.clone() }, image, size, pixels_per_point, tints) +} + +/// A row of the brush's dabs across a `size` strip, scattered by its four jitters; dabs shrink as Position Jitter grows so the scatter stays inside +pub(crate) fn jitter_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], _pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + let spaced = BrushSettings { spacing: brush.spacing.max(STRIP_DAB_SPACING), follow_path: false, flow: 1.0, opacity: 1.0, ..brush.clone() }; + let (width, middle) = (size[0] as f32, size[1] as f32 * 0.5); + + // A dab lands up to Position Jitter radii from the line, so its radius and that reach together fill the strip's half height + let radius = middle * STRIP_REACH_SHARE / (1.0 + brush.jitter_position.max(0.0)); + let curve = |t: f32| (radius + t * (width - 2.0 * radius), middle); + stroke_strip(&spaced, image, size, |_| radius, curve, |x| column_tint(tints, x)) +} + +fn column_tint(tints: &[[u8; 3]], x: usize) -> [u8; 3] { + tints.get(x).copied().unwrap_or([u8::MAX; 3]) +} + +/// The dial around the Orientation picture's stamp: a ring and an accent tick at `degrees` (counter-clockwise from the right, as the stamp turns) +pub(crate) fn dial_ring(painter: &Painter, rect: Rect, degrees: f32, tokens: &Tokens) { + let center = rect.center(); + let ring = rect.width().min(rect.height()) * 0.5 * RING_RADIUS_SHARE; + painter.circle_stroke(center, ring, Stroke::new(RING_WIDTH, tokens.button_border)); + + let (sin, cos) = degrees.to_radians().sin_cos(); + let at = |reach: f32| pos2(center.x + reach * cos, center.y - reach * sin); + painter.line_segment([at(ring - TICK_REACH), at(ring + TICK_REACH)], Stroke::new(TICK_WIDTH, tokens.accent)); +} + +/// Points along the Alignment picture's surface +const SURFACE_POINTS: usize = 16; + +/// The surface's bulge and the stamp's height above it, as shares of the picture's height +const SURFACE_BULGE_SHARE: f32 = 0.45; +const STAMP_LIFT_SHARE: f32 = 0.12; + +/// Margin inside the Alignment picture, in points +const ALIGNMENT_INSET: f32 = 2.0; + +/// The middle share of the surface the stamp covers +const STAMP_SPAN_SHARE: f32 = 0.6; + +/// How an Alignment lays the stamp on a curved surface: bent along it (Tangent | Wrap) or flat towards the view (Camera) +pub(crate) fn alignment_picture(painter: &Painter, rect: Rect, alignment: Alignment, tokens: &Tokens) { + let rect = rect.shrink(ALIGNMENT_INSET); + let bulge = rect.height() * SURFACE_BULGE_SHARE; + let surface_y = |across: f32| rect.bottom() - bulge * (1.0 - across * across); + let point = |across: f32, lift: f32| pos2(rect.center().x + across * rect.width() * 0.5, surface_y(across) - lift); + let line = |from: f32, to: f32, lift: f32| -> Vec { + (0..=SURFACE_POINTS).map(|step| point(from + (to - from) * step as f32 / SURFACE_POINTS as f32, lift)).collect() + }; + painter.add(Shape::line(line(-1.0, 1.0, 0.0), Stroke::new(RING_WIDTH, tokens.text_dim))); + + let lift = rect.height() * STAMP_LIFT_SHARE; + let stamp = match alignment { + Alignment::Tangent => line(-STAMP_SPAN_SHARE, STAMP_SPAN_SHARE, lift), + Alignment::Camera => { + let top = surface_y(0.0) - lift; + vec![pos2(point(-STAMP_SPAN_SHARE, 0.0).x, top), pos2(point(STAMP_SPAN_SHARE, 0.0).x, top)] + } + }; + painter.add(Shape::line(stamp, Stroke::new(TICK_WIDTH, tokens.accent))); +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::paint::BrushAlpha; + + use super::*; + + const STAMP_SIZE: [usize; 2] = [48, 48]; + const STRIP_SIZE: [usize; 2] = [240, 40]; + + fn white(width: usize) -> Vec<[u8; 3]> { + vec![[u8::MAX; 3]; width] + } + + #[test] + fn the_stamp_turns_with_angle() { + let upright = BrushSettings { alpha: BrushAlpha::Streaks, angle: 0.0, ..BrushSettings::default() }; + let turned = BrushSettings { angle: 45.0, ..upright.clone() }; + + let picture = |brush: &BrushSettings| stamp_image(brush, None, STAMP_SIZE, 1.0, &white(STAMP_SIZE[0])).pixels; + + assert!(picture(&upright).iter().any(|pixel| pixel.a() > 0), "the stamp shows"); + assert_ne!(picture(&upright), picture(&turned)); + } + + #[test] + fn each_jitter_changes_the_strip() { + let steady = BrushSettings { hardness: 1.0, ..BrushSettings::default() }; + let strip = |brush: &BrushSettings| jitter_image(brush, None, STRIP_SIZE, 1.0, &white(STRIP_SIZE[0])).pixels; + let jittered = [ + BrushSettings { jitter_size: 0.8, ..steady.clone() }, + BrushSettings { jitter_flow: 0.8, ..steady.clone() }, + BrushSettings { jitter_angle: 0.8, alpha: BrushAlpha::Streaks, ..steady.clone() }, + BrushSettings { jitter_position: 1.0, ..steady.clone() }, + ]; + + for brush in &jittered { + let unjittered = BrushSettings { jitter_size: 0.0, jitter_flow: 0.0, jitter_angle: 0.0, jitter_position: 0.0, ..brush.clone() }; + assert_ne!(strip(brush), strip(&unjittered), "{brush:?}"); + } + } +} diff --git a/crates/ui-egui/src/brush_sheet.rs b/crates/ui-egui/src/brush_sheet.rs new file mode 100644 index 00000000..cf4a7022 --- /dev/null +++ b/crates/ui-egui/src/brush_sheet.rs @@ -0,0 +1,265 @@ +//! The Brush section of a paint tool's Properties: the Size, Opacity, Orientation, Jitter and Projection bands, grouped and named as the reference groups them + +use std::ops::RangeInclusive; +use std::sync::Arc; + +use egui::{Painter, Rect, Response, Sense, Stroke, StrokeKind, Ui, vec2}; +use serde_json::json; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::paint::{Alignment, BrushSettings}; + +use crate::TextureCraftApp; +use crate::brush_pictures::{alignment_picture, dial_ring, jitter_image, stamp_image}; +use crate::brush_stroke_preview::BrushStrokePreview; +use crate::fill_pictures::backface_picture; +use crate::i18n::tr; +use crate::property_sheet::{PropertySheet, RowLead, StackSlider}; +use crate::theme::{Tokens, caption}; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; + +/// Height of the Jitter band's strip of dabs, in points +const JITTER_STRIP_HEIGHT: f32 = 40.0; + +/// Corner radius of the Jitter strip's frame +const JITTER_STRIP_ROUNDING: f32 = 2.0; + +/// Width of the Jitter strip's frame, in points; the dabs are drawn inside it +const JITTER_STRIP_OUTLINE_WIDTH: f32 = 1.0; + +/// What Angle and each Angle fade may be, in degrees +const ANGLE_RANGE: RangeInclusive = -180.0..=180.0; +const ANGLE_FADE_RANGE: RangeInclusive = 0.0..=90.0; + +/// Size's slider, in percent of the largest brush +const SIZE_PERCENT_RANGE: RangeInclusive = 0.05..=100.0; + +/// Spacing's slider, in percent of the stamp's width +const SPACING_PERCENT_RANGE: RangeInclusive = 1.0..=1000.0; + +/// Position Jitter's slider, in percent of the stamp's radius +const POSITION_JITTER_PERCENT_RANGE: RangeInclusive = 0.0..=400.0; + +const PERCENT_RANGE: RangeInclusive = 0.0..=100.0; + +/// The ranges of Stamp depth, Gravity, particles per stamp, and a particle's lifetime in steps +const STAMP_DEPTH_RANGE: RangeInclusive = 0.05..=4.0; +const GRAVITY_RANGE: RangeInclusive = 0.0..=2.0; +const PARTICLE_COUNT_RANGE: RangeInclusive = 1.0..=16.0; +const PARTICLE_LIFETIME_RANGE: RangeInclusive = 1.0..=128.0; + +/// Width of the brush presets list +const PRESETS_WIDTH: f32 = 230.0; + +/// Height the presets list scrolls past +const PRESETS_MAX_HEIGHT: f32 = 380.0; + +/// The Brush section under its caption, whose ≡ button `menu` opens the brush presets +pub(crate) fn brush_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, menu: Option) { + if let Some(menu) = menu { + brush_presets_popover(app, sheet.ui, menu); + } + + let tokens = Tokens::get(sheet.ui.ctx()); + let image = app.session.tool.brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)).cloned(); + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); + + // Each band's reset puts back only the fields it shows + let size_fields = |settings: &BrushSettings| (settings.size, settings.size_pressure, settings.min_size, settings.spacing); + let band = sheet.band(tr("Size"), true, Some(size_fields(brush) != size_fields(&defaults)), None); + if band.reset { + (brush.size, brush.size_pressure, brush.min_size, brush.spacing) = size_fields(&defaults); + } + if band.open { + // Every row keeps the pen button's slot, so the three values line up + let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; + if sheet.pen_slider(tr("Size"), &mut size_percent, SIZE_PERCENT_RANGE, 1, Some(&mut brush.size_pressure)).0.is_some() { + brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + } + let pressure = brush.size_pressure; + sheet.greyed(pressure, Some(tr("Applies only while pen pressure on Size is on")), |sheet| { + pen_percent_slider(sheet, tr("Minimum Size (%)"), &mut brush.min_size, PERCENT_RANGE); + }); + pen_percent_slider(sheet, tr("Spacing"), &mut brush.spacing, SPACING_PERCENT_RANGE); + } + + let opacity_fields = |settings: &BrushSettings| (settings.flow, settings.opacity); + let band = sheet.band(tr("Opacity"), true, Some(opacity_fields(brush) != opacity_fields(&defaults)), None); + if band.reset { + (brush.flow, brush.opacity) = opacity_fields(&defaults); + } + if band.open { + percent_slider(sheet, tr("Flow"), &mut brush.flow, PERCENT_RANGE); + percent_slider(sheet, tr("Stroke opacity"), &mut brush.opacity, PERCENT_RANGE); + } + + let orientation_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); + let band = sheet.band(tr("Orientation"), true, Some(orientation_fields(brush) != orientation_fields(&defaults)), None); + if band.reset { + (brush.angle, brush.follow_path) = orientation_fields(&defaults); + } + if band.open { + let shown = brush.clone(); + let ctx = sheet.ui.ctx().clone(); + let tint = tokens.text.to_array(); + let dial = |painter: &Painter, rect: Rect| { + BrushStrokePreview::paint_picture( + &ctx, + painter, + rect, + "brush_stamp_picture", + (&shown, image.as_ref()), + |_| [tint[0], tint[1], tint[2]], + stamp_image, + ); + dial_ring(painter, rect, shown.angle, &tokens); + }; + let angle = StackSlider { label: tr("Angle"), value: &mut brush.angle, range: ANGLE_RANGE, typed: ANGLE_RANGE, decimals: 0, suffix: "°", dial: false }; + sheet.picture_sliders(&dial, &mut [angle]); + sheet.toggle(tr("Follow Path"), &mut brush.follow_path); + } + + let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_flow, settings.jitter_angle, settings.jitter_position); + let band = sheet.band(tr("Jitter"), true, Some(jitter_fields(brush) != jitter_fields(&defaults)), None); + if band.reset { + (brush.jitter_size, brush.jitter_flow, brush.jitter_angle, brush.jitter_position) = jitter_fields(&defaults); + } + if band.open { + jitter_strip(sheet, brush, image.as_ref(), &tokens); + percent_slider(sheet, tr("Size Jitter"), &mut brush.jitter_size, PERCENT_RANGE); + percent_slider(sheet, tr("Flow Jitter"), &mut brush.jitter_flow, PERCENT_RANGE); + percent_slider(sheet, tr("Angle Jitter"), &mut brush.jitter_angle, PERCENT_RANGE); + percent_slider(sheet, tr("Position Jitter"), &mut brush.jitter_position, POSITION_JITTER_PERCENT_RANGE); + } + + let projection_fields = + |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.screen_space, settings.depth); + let band = sheet.band(tr("Projection"), true, Some(projection_fields(brush) != projection_fields(&defaults)), None); + if band.reset { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.screen_space, brush.depth) = projection_fields(&defaults); + } + if band.open { + projection_rows(sheet, brush, &tokens); + } + + let particles = &mut brush.particles; + let band = sheet.band(tr("Particles"), false, Some(*particles != defaults.particles), None); + if band.reset { + *particles = defaults.particles; + } + if band.open { + sheet.info(tr("Paint slides down the surface")); + sheet.toggle(tr("Particle brush"), &mut particles.enabled); + whole_slider(sheet, tr("Count per stamp"), &mut particles.count, PARTICLE_COUNT_RANGE); + whole_slider(sheet, tr("Lifetime (steps)"), &mut particles.lifetime, PARTICLE_LIFETIME_RANGE); + sheet.slider(tr("Gravity"), &mut particles.gravity, GRAVITY_RANGE, 2); + } + + *brush = brush.sanitized(); +} + +/// Alignment, Backface culling with its Angle fade under it, Size Space and Stamp depth +fn projection_rows(sheet: &mut PropertySheet<'_>, brush: &mut BrushSettings, tokens: &Tokens) { + let alignment_name = |alignment: Alignment| { + match alignment { + Alignment::Tangent => tr("Tangent | Wrap"), + Alignment::Camera => tr("Camera"), + } + .to_owned() + }; + let picture = |painter: &Painter, rect: Rect, alignment: Alignment| alignment_picture(painter, rect, alignment, tokens); + let (picked, _) = sheet.dropdown(tr("Alignment"), brush.alignment, &[Alignment::Tangent, Alignment::Camera], alignment_name, Some(&picture)); + if let Some(alignment) = picked { + brush.alignment = alignment; + } + + let culled = brush.backface_culling; + let picture = |painter: &Painter, rect: Rect| backface_picture(painter, rect, culled, tokens); + sheet.picture_toggle(&picture, tr("Backface culling"), &mut brush.backface_culling); + + // Faces only fade towards their edge while backfaces are culled + sheet.greyed(brush.backface_culling, Some(tr("Fades only while Backface culling is on")), |sheet| { + sheet.angle_led(RowLead::Child(tr("Angle fade from")), &mut brush.angle_fade.0, ANGLE_FADE_RANGE); + sheet.angle_led(RowLead::Child(tr("Angle fade to")), &mut brush.angle_fade.1, ANGLE_FADE_RANGE); + }); + + if let Some(space) = sheet.switch(tr("Size Space"), &[tr("Object"), tr("Viewport")], usize::from(brush.screen_space)) { + brush.screen_space = space == 1; + } + sheet.slider(tr("Stamp depth"), &mut brush.depth, STAMP_DEPTH_RANGE, 2); +} + +/// The brush's dabs scattered by its jitters, across the panel above the Jitter sliders +fn jitter_strip(sheet: &mut PropertySheet<'_>, brush: &BrushSettings, image: Option<&Arc>, tokens: &Tokens) { + let tint = tokens.text.to_array(); + sheet.embed(|ui: &mut Ui| { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), JITTER_STRIP_HEIGHT), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Jitter preview"))); + + let painter = ui.painter(); + painter.rect_filled(rect, JITTER_STRIP_ROUNDING, tokens.field); + painter.rect_stroke(rect, JITTER_STRIP_ROUNDING, Stroke::new(JITTER_STRIP_OUTLINE_WIDTH, tokens.field_border), StrokeKind::Inside); + BrushStrokePreview::paint_picture( + ui.ctx(), + painter, + rect.shrink(JITTER_STRIP_OUTLINE_WIDTH), + "brush_jitter_picture", + (brush, image), + |_| [tint[0], tint[1], tint[2]], + jitter_image, + ); + }); +} + +/// A 0..1 setting shown and typed in whole percent +fn percent_slider(sheet: &mut PropertySheet<'_>, label: &str, fraction: &mut f32, percent: RangeInclusive) { + let mut shown = *fraction * 100.0; + if sheet.slider(label, &mut shown, percent, 0).is_some() { + *fraction = shown / 100.0; + } +} + +/// [`percent_slider`] in a band whose rows keep the pen button's slot +fn pen_percent_slider(sheet: &mut PropertySheet<'_>, label: &str, fraction: &mut f32, percent: RangeInclusive) { + let mut shown = *fraction * 100.0; + if sheet.pen_slider(label, &mut shown, percent, 0, None).0.is_some() { + *fraction = shown / 100.0; + } +} + +/// A count on a slider of whole numbers +fn whole_slider(sheet: &mut PropertySheet<'_>, label: &str, count: &mut u32, range: RangeInclusive) { + let mut shown = *count as f32; + if sheet.slider(label, &mut shown, range, 0).is_some() { + *count = shown.round() as u32; + } +} + +/// The brush presets, listed under the Brush caption's ≡ button +fn brush_presets_popover(app: &mut TextureCraftApp, ui: &Ui, menu: Response) { + menu.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Brush presets"))); + let menu = menu.on_hover_text(tr("Brush presets")); + let popup_id = ui.make_persistent_id("brush_presets_popup"); + if menu.clicked() { + egui::Popup::toggle_id(ui.ctx(), popup_id); + } + + egui::Popup::from_response(&menu).id(popup_id).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_min_width(PRESETS_WIDTH); + egui::ScrollArea::vertical().max_height(PRESETS_MAX_HEIGHT).show(ui, |ui| { + let mut category = ""; + for preset in texturecraft_engine::paint::presets::PRESETS.iter() { + if preset.category != category { + category = preset.category; + ui.label(caption(category)); + } + if ui.selectable_label(false, preset.label).on_hover_text(tr("Use this brush (keeps its size)")).clicked() { + app.run("brush.preset.apply", json!({"preset": preset.id})); + } + } + + ui.separator(); + crate::shelf::user_brushes(app, ui, ""); + }); + }); +} diff --git a/crates/ui-egui/src/brush_stroke_preview.rs b/crates/ui-egui/src/brush_stroke_preview.rs new file mode 100644 index 00000000..88af53c3 --- /dev/null +++ b/crates/ui-egui/src/brush_stroke_preview.rs @@ -0,0 +1,237 @@ +//! The live stroke at the top of the paint tool's properties: the current brush's own stamps along a hand-drawn gesture + +use std::sync::{Arc, Weak}; + +use egui::{Color32, ColorImage, Context, Id, Painter, Rect, TextureHandle, TextureOptions, pos2, vec2}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::paint::BrushSettings; + +use crate::preview_image::stroke_strip; + +/// The stroke's margin from the edges of its half of the preview, in points +const STROKE_MARGIN: f32 = 6.0; + +/// The gesture the stroke follows, as fractions of its box: a small hook, a dip, a tall arch and a long tail down +const STROKE_PATH: [[f32; 2]; 5] = [[0.0, 0.6], [0.18, 0.3], [0.4, 0.8], [0.65, 0.0], [1.0, 1.0]]; + +/// The gesture's widest width for its height, so a wide preview centres it instead of flattening its arch +const STROKE_ASPECT: f32 = 1.4; + +/// The pen pressure the stroke is drawn with, from its start to its end: it presses harder as it goes, as a hand does +const STROKE_PRESSURE: std::ops::RangeInclusive = 0.35..=1.0; + +/// The stroke's width: [`STROKE_WIDTH_PER_ROOT_SIZE`] points times the root of the brush size, kept inside [`STROKE_WIDTH`]; the root lets small brushes read and big ones still grow +const STROKE_WIDTH_PER_ROOT_SIZE: f32 = 70.0; +const STROKE_WIDTH: std::ops::RangeInclusive = 2.0..=32.0; + +/// The rendered stroke and what it was rendered from, kept in egui's memory behind an `Arc` so a frame with the same brush reuses it without copying it +pub(crate) struct BrushStrokePreview { + brush: BrushSettings, + // A hidden picture keeps its texture without owning the decoded alpha + image: Option>, + tints: Vec<[u8; 3]>, + size: [usize; 2], + pixels_per_point: f32, + texture: TextureHandle, +} + +impl BrushStrokePreview { + /// Paint the brush's stroke across `rect`, each pixel column coloured by `tint` of its position 0..1; it renders again only on a new brush, alpha image, colour or size + pub(crate) fn paint(ctx: &Context, painter: &Painter, rect: Rect, brush: &BrushSettings, image: Option<&Arc>, tint: impl Fn(f32) -> [u8; 3]) { + Self::paint_picture(ctx, painter, rect, "brush_stroke_preview", (brush, image), tint, stroke_image); + } + + /// Paint `render`'s picture of the brush across `rect`, kept under `key` until the brush, alpha image, colour or size change + pub(crate) fn paint_picture( + ctx: &Context, + painter: &Painter, + rect: Rect, + key: &'static str, + (brush, image): (&BrushSettings, Option<&Arc>), + tint: impl Fn(f32) -> [u8; 3], + render: impl FnOnce(&BrushSettings, Option<&ImageRes>, [usize; 2], f32, &[[u8; 3]]) -> ColorImage, + ) { + let pixels_per_point = ctx.pixels_per_point(); + let size = [(rect.width() * pixels_per_point).round().max(1.0) as usize, (rect.height() * pixels_per_point).round().max(1.0) as usize]; + let column_tint = |x: usize| tint((x as f32 + 0.5) / size[0] as f32); + + // The docked panel and the right-click popup draw the same picture at their own widths: one cache each + let id = Id::unique(key).with(painter.layer_id()); + let cached = ctx.data(|data| data.get_temp::>(id)).filter(|preview| { + preview.brush == *brush + && preview.size == size + && preview.pixels_per_point == pixels_per_point + && preview.image.as_ref().map(Weak::as_ptr) == image.map(Arc::as_ptr) + && preview.tints.iter().enumerate().all(|(x, shown)| *shown == column_tint(x)) + }); + + let texture = match cached { + Some(preview) => preview.texture.id(), + None => { + let tints: Vec<[u8; 3]> = (0..size[0]).map(column_tint).collect(); + let picture = render(brush, image.map(|image| &**image), size, pixels_per_point, &tints); + let texture = ctx.load_texture(key, picture, TextureOptions::LINEAR); + let texture_id = texture.id(); + let preview = BrushStrokePreview { brush: brush.clone(), image: image.map(Arc::downgrade), tints, size, pixels_per_point, texture }; + ctx.data_mut(|data| data.insert_temp(id, Arc::new(preview))); + texture_id + } + }; + painter.image(texture, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } +} + +/// The brush's stroke as a `size` image at `pixels_per_point`: a hand-drawn gesture as wide as the brush size, narrowed towards Minimum Size at its light start; column `x` in `tints[x]` +pub(crate) fn stroke_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + let (width, height) = (size[0] as f32 / pixels_per_point, size[1] as f32 / pixels_per_point); + let stroke_width = (brush.size.max(0.0).sqrt() * STROKE_WIDTH_PER_ROOT_SIZE).clamp(*STROKE_WIDTH.start(), *STROKE_WIDTH.end()); + let inset = STROKE_MARGIN + stroke_width * 0.5; + let span_y = (height - 2.0 * inset).max(0.0); + let span = vec2((width - 2.0 * inset).clamp(0.0, span_y * STROKE_ASPECT), span_y); + let left = (width - span.x) * 0.5; + let curve = |t: f32| { + let [x, y] = path_point(t); + ((left + x * span.x) * pixels_per_point, (inset + y * span.y) * pixels_per_point) + }; + let radius = |t: f32| { + let pressure = STROKE_PRESSURE.start() + (STROKE_PRESSURE.end() - STROKE_PRESSURE.start()) * t * (2.0 - t); + stroke_width * 0.5 * pixels_per_point * brush.uv_stamp_radius(pressure) / brush.uv_stamp_radius(1.0).max(f32::MIN_POSITIVE) + }; + let tint = |x: usize| tints.get(x).copied().unwrap_or([u8::MAX; 3]); + stroke_strip(brush, image, size, radius, curve, tint) +} + +/// The point at `t` (0..1) along [`STROKE_PATH`], a Catmull-Rom spline through its points +fn path_point(t: f32) -> [f32; 2] { + let last = STROKE_PATH.len() - 1; + let at = t.clamp(0.0, 1.0) * last as f32; + let segment = (at as usize).min(last - 1); + let u = at - segment as f32; + let point = |index: isize| STROKE_PATH[index.clamp(0, last as isize) as usize]; + let [p0, p1, p2, p3] = [-1, 0, 1, 2].map(|offset| point(segment as isize + offset)); + let blend = |axis: usize| { + let (a, b, c, d) = (p0[axis], p1[axis], p2[axis], p3[axis]); + 0.5 * (2.0 * b + (c - a) * u + (2.0 * a - 5.0 * b + 4.0 * c - d) * u * u + (3.0 * b - a - 3.0 * c + d) * u * u * u) + }; + [blend(0), blend(1)] +} + +#[cfg(test)] +mod tests { + use super::*; + + const SIZE: [usize; 2] = [160, 88]; + + fn paint(brush: &BrushSettings) -> ColorImage { + stroke_image(brush, None, SIZE, 1.0, &[[u8::MAX; 3]; SIZE[0]]) + } + + fn painted_pixels(picture: &ColorImage) -> usize { + picture.pixels.iter().filter(|pixel| pixel.a() > 0).count() + } + + fn total_paint(picture: &ColorImage) -> u64 { + picture.pixels.iter().map(|pixel| u64::from(pixel.a())).sum() + } + + #[test] + fn wider_spacing_leaves_gaps_between_dabs() { + let dense = BrushSettings { hardness: 1.0, spacing: 0.1, ..BrushSettings::default() }; + let sparse = BrushSettings { spacing: 3.0, ..dense.clone() }; + + assert!(painted_pixels(&paint(&sparse)) < painted_pixels(&paint(&dense))); + } + + #[test] + fn a_softer_brush_lays_down_less_paint() { + let hard = BrushSettings { hardness: 1.0, ..BrushSettings::default() }; + let soft = BrushSettings { hardness: 0.0, ..hard.clone() }; + + assert!(total_paint(&paint(&soft)) < total_paint(&paint(&hard))); + } + + #[test] + fn a_bigger_brush_paints_a_wider_stroke() { + let small = BrushSettings { size: 0.02, ..BrushSettings::default() }; + let big = BrushSettings { size: 0.1, ..small.clone() }; + + assert!(painted_pixels(&paint(&small)) < painted_pixels(&paint(&big))); + } + + /// Paint in the first and last quarter of the columns the stroke covers + fn paint_at_ends(picture: &ColorImage) -> (u64, u64) { + let [width, _] = picture.size; + let painted = |index: &usize| picture.pixels.iter().skip(*index).step_by(width).any(|pixel| pixel.a() > 0); + let (first, last) = ((0..width).find(painted).unwrap_or(0), (0..width).rfind(painted).unwrap_or(width)); + let quarter = (last - first) / 4; + let paint_in = |columns: std::ops::Range| { + picture.pixels.iter().enumerate().filter(|(index, _)| columns.contains(&(index % width))).map(|(_, pixel)| u64::from(pixel.a())).sum() + }; + (paint_in(first..first + quarter), paint_in(last - quarter..last + 1)) + } + + #[test] + fn the_stroke_starts_light_and_a_lower_minimum_size_thins_its_start() { + let brush = BrushSettings { hardness: 1.0, min_size: 0.05, ..BrushSettings::default() }; + let full = BrushSettings { min_size: 1.0, ..brush.clone() }; + let (start, end) = paint_at_ends(&paint(&brush)); + let (full_start, _) = paint_at_ends(&paint(&full)); + + assert!(start < end, "the stroke widens as the pen presses harder"); + assert!(start < full_start, "Minimum Size bounds how thin the light start gets"); + } + + #[test] + fn without_size_pressure_the_stroke_keeps_its_width() { + let brush = BrushSettings { hardness: 1.0, min_size: 0.05, size_pressure: false, ..BrushSettings::default() }; + let full = BrushSettings { min_size: 1.0, size_pressure: true, ..brush.clone() }; + + assert!(paint(&brush) == paint(&full), "a mouse brush draws no taper"); + } + + #[test] + fn changing_display_scale_redraws_a_stroke_at_the_same_pixel_size() { + let ctx = Context::default(); + let brush = BrushSettings::default(); + let draw = |scale: f32| { + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(scale); + let rect = Rect::from_min_size(egui::Pos2::ZERO, vec2(SIZE[0] as f32, SIZE[1] as f32) / scale); + let mut frame = ctx.run_ui(input, |ui| BrushStrokePreview::paint(&ctx, ui.painter(), rect, &brush, None, |_| [255; 3])); + let upload = frame.textures_delta.set.values().flatten().find(|delta| delta.image.size() == SIZE).map(|delta| delta.image.clone()); + frame.textures_delta.clear(); + upload + }; + + let first = draw(1.0).expect("first picture"); + let scaled = draw(2.0).expect("redrawn picture"); + let reused = draw(2.0); + + let (egui::ImageData::Color(first), egui::ImageData::Color(scaled)) = (first, scaled); + assert_ne!(first.pixels, scaled.pixels, "stroke width and margins follow the display scale"); + assert!(reused.is_none(), "an unchanged display reuses the picture"); + } + + #[test] + fn cached_pictures_release_each_decoded_alpha_when_its_owner_drops_it() { + const ALPHA_SIDE_PX: u32 = 1024; + let ctx = Context::default(); + let brush = BrushSettings::default(); + let rect = Rect::from_min_size(egui::Pos2::ZERO, vec2(48.0, 32.0)); + let mut former_alphas = Vec::new(); + + for (layer_name, gray) in [("docked", 0.25), ("popup", 0.75)] { + let pixels = vec![[gray, gray, gray, 1.0]; (ALPHA_SIDE_PX * ALPHA_SIDE_PX) as usize]; + let alpha = Arc::new(ImageRes::new(ALPHA_SIDE_PX, ALPHA_SIDE_PX, pixels, false)); + let layer = egui::LayerId::new(egui::Order::Middle, Id::unique(layer_name)); + let painter = ctx.layer_painter(layer); + + BrushStrokePreview::paint(&ctx, &painter, rect, &brush, Some(&alpha), |_| [255; 3]); + former_alphas.push(Arc::downgrade(&alpha)); + } + + let retained_bytes: usize = former_alphas.iter().filter_map(|alpha| alpha.upgrade()).map(|alpha| std::mem::size_of_val(alpha.rgba.as_slice())).sum(); + eprintln!("cached pictures retain {retained_bytes} decoded alpha bytes"); + assert_eq!(retained_bytes, 0, "pictures must not own decoded alpha pixels"); + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 57c15011..3df1804c 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -8,21 +8,21 @@ use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Project, Projection, Sampling, Source, }; -use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; -use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; +use texturecraft_engine::texel::linear_to_srgb; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; +use crate::brush_stroke_preview::BrushStrokePreview; use crate::i18n::{n_, tr, trf}; use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; +use crate::paint_section::PaintSection; use crate::past_end::PastEnd; use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; use crate::source_choice::SourceChoice; -use crate::state::PropsTab; +use crate::tabbed_page::TabbedPage; use crate::theme::{Tokens, caption}; -use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -1895,9 +1895,10 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { // A floating scroll bar would cover the right-aligned slider values and section reset icons ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); let scope = SectionScope::Docked; - if let Some(tabs) = properties_fill_tabs(app) { + if let Some(tabs) = properties_tabs(app) { crate::property_sheet::section_tabs(ui, scope, 0, &tabs); } + pinned_brush_preview(app, ui); let selection = properties_selection(app); crate::property_sheet::in_scope(ui, scope, |ui| { @@ -1936,20 +1937,42 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: output.state.clamped_offset().y } -/// The tabs over the panel when it shows a fill layer's or a mask fill effect's sections, which they jump between -pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 3]> { - if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { +/// The tabs over the panel when it shows a fill layer's, a mask fill effect's or a paint tool's sections, which they jump between +pub(crate) fn properties_tabs(app: &TextureCraftApp) -> Option> { + Some(match tabbed_page(app)? { + TabbedPage::Fill { mask } => crate::fill_panel::fill_tabs(mask).to_vec(), + TabbedPage::Tool => tool_sections(app).into_iter().map(|section| (section.icon(), section.title())).collect(), + }) +} + +/// The page under the panel's jump tabs, if it shows one +fn tabbed_page(app: &TextureCraftApp) -> Option { + if !app.session.project_open || app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; } let project = &app.session.doc.project; - match app.session.target { - StackTarget::Content => { - let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; - matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(|| crate::fill_panel::fill_tabs(false)) + let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id)); + let tool_shown = match (layer, app.session.target) { + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => { + return matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then_some(TabbedPage::Fill { mask: false }); } - StackTarget::Effect(effect) => mask_fill_of(project, effect).map(|_| crate::fill_panel::fill_tabs(true)), - _ => None, + (Some(_), StackTarget::Effect(effect)) => match project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Paint | EffectKind::Path(_)) => true, + _ => return mask_fill_of(project, effect).map(|_| TabbedPage::Fill { mask: true }), + }, + (Some(layer), StackTarget::Content) => !layer.is_group() && layer.instance_source().is_none(), + _ => true, + }; + + // Everything else shows the tool's sections where the tool can paint + (tool_shown && app.session.tool_usable(app.session.tool.tool)).then_some(TabbedPage::Tool) +} + +/// The brush preview under the tool's jump tabs: it stays in view while the sections scroll under it +pub(crate) fn pinned_brush_preview(app: &TextureCraftApp, ui: &mut Ui) { + if tabbed_page(app) == Some(TabbedPage::Tool) { + legacy_body(ui, |ui| brush_preview(app, ui)); } } @@ -1991,10 +2014,6 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { (Some(layer), StackTarget::Effect(effect)) => { let snapshot = layer.clone(); effect_properties(app, ui, &snapshot, effect); - let painted = app.session.doc.project.effect(effect).is_some_and(|(_, effect)| matches!(effect.kind, EffectKind::Paint | EffectKind::Path(_))); - if painted && grayscale_tab_open(app) { - crate::mask_paint_panel::grayscale_sheet(app, ui); - } } (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => { let snapshot = layer.clone(); @@ -2007,35 +2026,27 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { } (Some(layer), StackTarget::Mask) => { let layer_id = layer.id; - legacy_body(ui, |ui| { - // Saved height masks can still be turned off here - let height_shown = app.session.doc.project.content_layer(layer_id).is_some_and(|content| content.height_mask.enabled); - if height_shown { + + // Saved height masks can still be turned off here + if app.session.doc.project.content_layer(layer_id).is_some_and(|content| content.height_mask.enabled) { + legacy_body(ui, |ui| { height_mask_section(app, ui, layer_id); - } - if tool_usable { - if height_shown { + if tool_usable { ui.separator(); } - tool_properties(app, ui); - } - }); - if tool_usable && grayscale_tab_open(app) { - crate::mask_paint_panel::grayscale_sheet(app, ui); + }); + } + if tool_usable { + tool_properties(app, ui); } } (None, _) if !tool_usable => legacy_body(ui, |ui| { ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); }), - _ => legacy_body(ui, |ui| tool_properties(app, ui)), + _ => tool_properties(app, ui), } } -/// Whether the tool panel's third tab is open while a mask is painted: its Grayscale tab, drawn under the tool's rows -fn grayscale_tab_open(app: &TextureCraftApp) -> bool { - app.ui.props_tab == PropsTab::Material && !targets_content(app) -} - /// Mask with height: the layer's height shapes its mask transitions. fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId) { let height_mask = app.session.project().content_layer(layer).map(|source| source.height_mask).unwrap_or_default(); @@ -2066,97 +2077,69 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId) { const BRUSH_PREVIEW_HEIGHT: f32 = 88.0; const BRUSH_PREVIEW_CORNER_RADIUS: f32 = 2.0; -/// The preview stroke: its segments, its margin from the preview's left (each side of its half), its wave's phase span in radians and its swing -const PREVIEW_STROKE_STEPS: usize = 40; -const PREVIEW_STROKE_MARGIN: f32 = 14.0; -const PREVIEW_STROKE_WAVE: f32 = 9.0; -const PREVIEW_STROKE_SWING: f32 = 18.0; - -/// The preview stroke's width: [`PREVIEW_STROKE_WIDTH_SCALE`] points for each [`PREVIEW_SIZE_UNIT`] of brush size, kept inside [`PREVIEW_STROKE_WIDTH`] -const PREVIEW_SIZE_UNIT: f32 = 0.25; -const PREVIEW_STROKE_WIDTH_SCALE: f32 = 60.0; -const PREVIEW_STROKE_WIDTH: std::ops::RangeInclusive = 2.0..=30.0; - -/// Faintest the preview stroke draws, so a low flow or opacity still shows -const PREVIEW_STROKE_MIN_ALPHA: u8 = 30; - -/// Radius of the preview's material sphere, and the colour it shows when the tool has no base colour +/// Radius of the preview's material sphere, and the material it shows for channels the tool doesn't paint const PREVIEW_SPHERE_RADIUS: f32 = 36.0; const PREVIEW_FALLBACK_BASE_COLOR: [f32; 3] = [0.8; 3]; -/// Gap between the brush preview and the tab buttons +/// Samples an image-backed mask's gray is read at across the preview stroke +const STROKE_GRAY_SAMPLES: u32 = 64; + +/// Gap under the brush preview const BRUSH_PREVIEW_GAP: f32 = 4.0; -fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The brush's stroke in its target's tint, with a material sphere for content targets +fn brush_preview(app: &TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let content = targets_content(app); - - // Brush preview: a stroke and a sphere with the tool's material - let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Brush preview"))); let painter = ui.painter(); painter.rect_filled(rect, BRUSH_PREVIEW_CORNER_RADIUS, tokens.viewport); let half_width = rect.width() * 0.5; - let brush = &app.session.tool.brush; - let mut points = Vec::new(); - for step in 0..=PREVIEW_STROKE_STEPS { - let fraction = step as f32 / PREVIEW_STROKE_STEPS as f32; - let x = rect.left() + PREVIEW_STROKE_MARGIN + fraction * (half_width - 2.0 * PREVIEW_STROKE_MARGIN); - points.push(pos2(x, rect.center().y + (fraction * PREVIEW_STROKE_WAVE).sin() * PREVIEW_STROKE_SWING)); + let stroke_rect = Rect::from_min_size(rect.min, vec2(half_width, rect.height())); + let tool = &app.session.tool; + let brush = &tool.brush; + let image = brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)); + + let channel_value = |channel| if tool.enabled.contains(&channel) { tool.values.get(&channel).copied() } else { None }; + let base_color = content.then(|| channel_value(Channel::BaseColor).unwrap_or(PREVIEW_FALLBACK_BASE_COLOR)); + + if app.session.quick_mask.editing { + // The quick mask stores coverage independently of the tool's material and mask gray + BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, |_| [u8::MAX; 3]); + } else if let Some(base_color) = base_color { + let srgb = base_color.map(|linear| (linear_to_srgb(linear) * 255.0 + 0.5) as u8); + BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, |_| srgb); + } else { + // A mask paints gray: an image-backed one is read across the stroke + let gray = app.session.mask_gray(); + let mask_tint = |across: f32| { + let gray = (gray.at((across * STROKE_GRAY_SAMPLES as f32) as u32, 0, (STROKE_GRAY_SAMPLES, 1)) * 255.0).round() as u8; + [gray; 3] + }; + BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, mask_tint); } - let stroke_width = (brush.size / PREVIEW_SIZE_UNIT * PREVIEW_STROKE_WIDTH_SCALE).clamp(*PREVIEW_STROKE_WIDTH.start(), *PREVIEW_STROKE_WIDTH.end()); - let alpha = (brush.flow * brush.opacity * 255.0) as u8; - - let preview_stroke = |gray: f32| { - let gray = (gray.clamp(0.0, 1.0) * 255.0).round() as u8; - Stroke::new(stroke_width, Color32::from_rgba_unmultiplied(gray, gray, gray, alpha.max(PREVIEW_STROKE_MIN_ALPHA))) - }; - - // Sample image-backed masks along the preview stroke - let gray = if content { texturecraft_engine::compose::MaskGray::Value(1.0) } else { app.session.mask_gray() }; - match gray { - texturecraft_engine::compose::MaskGray::Value(value) => { - painter.add(egui::Shape::line(points, preview_stroke(value))); - } - texturecraft_engine::compose::MaskGray::Image { .. } => { - let size = PREVIEW_STROKE_STEPS as u32; - for (index, segment) in points.windows(2).enumerate() { - let value = gray.at(index as u32, size / 2, (size, size)); - painter.line_segment([segment[0], segment[1]], preview_stroke(value)); - } - } - } - - if content { - let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); - + if let Some(base_color) = base_color { // The sphere sits in the middle of the preview's right half - crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); + let metallic = channel_value(Channel::Metallic).map_or(crate::thumbs::SPHERE_DEFAULT_METALLIC, |metallic| metallic[0]); + let roughness = channel_value(Channel::Roughness).map_or(crate::thumbs::SPHERE_DEFAULT_ROUGHNESS, |roughness| roughness[0]); + let center = pos2(rect.left() + half_width * 1.5, rect.center().y); + crate::thumbs::paint_material_sphere(painter, center, PREVIEW_SPHERE_RADIUS, base_color, metallic, roughness); } + ui.add_space(BRUSH_PREVIEW_GAP); +} - ui.horizontal(|ui| { - let button_size = ui.spacing().interact_size.y; - - // Painting a mask, the material tab becomes the Grayscale tab - let material = if content { (ic::SPHERE, tr("Material")) } else { (ic::SQUARE_HALF, tr("Grayscale")) }; - for (tab, icon, tip) in - [(PropsTab::Brush, ic::PAINT_BRUSH, tr("Brush")), (PropsTab::Alpha, ic::CIRCLE_HALF, tr("Alpha")), (PropsTab::Material, material.0, material.1)] - { - if icon_button(ui, icon, tip, app.ui.props_tab == tab, button_size).clicked() { - app.ui.props_tab = tab; - } - } - }); - ui.separator(); - +/// What only this tool has, above the sections every brush tool shares +fn tool_header(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); if app.session.quick_mask.editing { ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tokens.text_dim)); ui.separator(); } let tool_section: Option = match app.session.tool.tool { - Tool::Projection => Some(stencil_section), Tool::Clone => Some(clone_section), Tool::Smudge => Some(smudge_section), Tool::Path => Some(path_section), @@ -2167,75 +2150,32 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { section(app, ui); ui.separator(); } - - match app.ui.props_tab { - PropsTab::Brush => brush_section(app, ui), - PropsTab::Alpha => alpha_section(app, ui), - PropsTab::Material if content => material_section(app, ui), - // A mask's Grayscale tab is a property sheet, drawn by the caller past this panel's margins - PropsTab::Material => {} - } } -/// How far the Position sliders move the stencil's center from the middle of the view (NDC; -1..1 is the view) -const STENCIL_POSITION_RANGE: f32 = 2.0; - -fn stencil_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Stencil"))); - let names: Vec = app.session.doc.resources.keys().cloned().collect(); - let current = app.session.tool.stencil.as_ref().map(|s| s.image.clone()).unwrap_or_else(|| tr("None").into()); - let row = ui.horizontal(|ui| { - egui::ComboBox::from_id_salt("stencil_img").width(170.0).selected_text(current.clone()).show_ui(ui, |ui| { - if ui.selectable_label(app.session.tool.stencil.is_none(), tr("None")).clicked() { - app.run("tool.stencil", json!({"clear": true})); +/// The tool's sections, one page under the panel's jump tabs +fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { + legacy_body(ui, |ui| tool_header(app, ui)); + PropertySheet::show(ui, "tool_sheet", |sheet| { + for section in tool_sections(app) { + // The Stencil caption carries its own reset + let menu = if section == PaintSection::Stencil { None } else { sheet.section(section.title(), section == PaintSection::Brush) }; + match section { + PaintSection::Brush => crate::brush_sheet::brush_section(app, sheet, menu), + PaintSection::Alpha => crate::alpha_sheet::alpha_section(app, sheet), + PaintSection::Stencil => crate::stencil_sheet::stencil_section(app, sheet), + PaintSection::Material => crate::material_sheet::material_section(app, sheet), + PaintSection::Grayscale => crate::mask_paint_panel::grayscale_section(app, sheet), } - for n in &names { - if ui.selectable_label(*n == current, n).clicked() { - app.run("tool.stencil", json!({"image": n})); - } - } - }); - import_button(app, ui); - }); - - // An image from the Assets panel dropped on the row becomes the stencil - let row_response = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as the stencil")); - if let Some(name) = image_drop(ui, &row_response) { - app.run("tool.stencil", json!({"image": name})); - } - if names.is_empty() { - ui.label(RichText::new(tr("Import an image (File > Import resources) to project it onto the mesh.")).color(tk.text_dim)); - return; - } - - if let Some(st) = app.session.tool.stencil.as_mut() { - slider(ui, tr("Scale"), &mut st.scale, 0.05..=4.0, 2); - slider(ui, tr("Rotation"), &mut st.rotation, 0.0..=360.0, 0); - slider(ui, tr("Position X"), &mut st.center[0], -STENCIL_POSITION_RANGE..=STENCIL_POSITION_RANGE, 2); - slider(ui, tr("Position Y"), &mut st.center[1], -STENCIL_POSITION_RANGE..=STENCIL_POSITION_RANGE, 2); - if ui.button(tr("Reset stencil")).on_hover_text(tr("Put the stencil back in the middle of the view at its starting size and rotation")).clicked() { - st.reset_placement(); } - slider(ui, tr("Overlay opacity"), &mut st.opacity, 0.0..=1.0, 2); - ui.checkbox(&mut st.tile, tr("Tile")); - ui.label( - RichText::new(tr("S + left-drag rotates (with Shift in 15° steps), S + right-drag scales, S + middle-drag moves; or use Position X / Y.")) - .size(10.5) - .color(tk.text_dim), - ); - } + }); } -fn import_button(app: &mut TextureCraftApp, ui: &mut Ui) { - if ui.small_button(tr("Import...")).clicked() { - let ctx = ui.ctx().clone(); - crate::menus::invoke(app, &ctx, "resource.import"); - } +/// The sections of [`tool_properties`]: Stencil for the brush tools it shapes, except while they paint the quick mask +fn tool_sections(app: &TextureCraftApp) -> Vec { + PaintSection::page(crate::viewport::stencil_applies(app), targets_content(app)) } fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Clone"))); ui.horizontal(|ui| { ui.label(tr("Copy from")); @@ -2248,6 +2188,7 @@ fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { } } }); + let mut aligned = app.session.tool.clone_aligned; if ui .checkbox(&mut aligned, tr("Aligned")) @@ -2256,39 +2197,47 @@ fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { { app.run("tool.brush", json!({"cloneAligned": aligned})); } - let Some(src) = app.session.tool.clone_source else { - ui.label(RichText::new(tr("Hold V and click the mesh to set the source, then paint elsewhere to copy it.")).color(tk.text_dim)); + + let Some(source) = app.session.tool.clone_source else { + ui.label(tr("Source: none")).on_hover_text(tr("Hold V and click the mesh to set the source, then paint elsewhere to copy it.")); return; }; - ui.horizontal(|ui| { - ui.label(trf("Source U {u} V {v}", &[("u", &format!("{:.3}", src.uv[0])), ("v", &format!("{:.3}", src.uv[1]))])); - if ui.small_button(tr("Clear")).clicked() { - app.run("tool.cloneSource", json!({"clear": true})); - } - }); let hint = if !app.session.tool.clone_aligned { tr("Not aligned: every stroke starts at the source. V + click sets a new source.") - } else if src.offset.is_some() { + } else if source.offset.is_some() { tr("Aligned: the offset set by the first stroke is kept. V + click sets a new source.") } else { tr("The first stroke sets the offset from the source.") }; - ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); + ui.horizontal(|ui| { + ui.label(trf("Source U {u} V {v}", &[("u", &format!("{:.3}", source.uv[0])), ("v", &format!("{:.3}", source.uv[1]))])).on_hover_text(hint); + if ui.small_button(tr("Clear")).clicked() { + app.run("tool.cloneSource", json!({"clear": true})); + } + }); } +/// Space between the smudge strength and the channels it drags +const SMUDGE_CHANNELS_GAP: f32 = 4.0; + +/// Full value of the smudge strength slider, the 0..100 scale `tool.brush` takes +const SMUDGE_STRENGTH_PERCENT: f32 = 100.0; + fn smudge_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Smudge"))); - let mut v = app.session.tool.smudge_strength * 100.0; - if slider(ui, tr("Strength"), &mut v, 0.0..=100.0, 0).changed() { - app.session.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0); + + let mut strength_percent = app.session.tool.smudge_strength * SMUDGE_STRENGTH_PERCENT; + let strength = slider(ui, tr("Strength"), &mut strength_percent, 0.0..=SMUDGE_STRENGTH_PERCENT, 0); + if strength.on_hover_text(tr("Drags the layer stack's values along the stroke into the selected layer.")).changed() { + app.run("tool.brush", json!({"smudgeStrength": strength_percent})); } - ui.label(RichText::new(tr("Drags the layer stack's values along the stroke into the selected layer.")).size(10.5).color(tk.text_dim)); - ui.add_space(4.0); - ui.label(tr("Channels dragged")); + + ui.add_space(SMUDGE_CHANNELS_GAP); + ui.label(tr("Channels dragged")).on_hover_text(tr( + "These are the brush's material channels, the same ones Paint writes and the Material tab shows. A channel the selected layer does not have is skipped.", + )); material_channel_chips(app, ui); - ui.label(RichText::new(tr("These are the brush's material channels, the same ones Paint writes and the Material tab shows. A channel the selected layer does not have is skipped.")).size(10.5).color(tk.text_dim)); } fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { @@ -2303,34 +2252,6 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); } -/// Popover for built-in and saved brush presets -fn brush_presets_popover(app: &mut TextureCraftApp, ui: &mut Ui) { - let response = ui.button(format!("{} {}", ic::PAINT_BRUSH_BROAD, tr("Brush presets"))); - let popup_id = ui.make_persistent_id("brush_presets_popup"); - if response.clicked() { - egui::Popup::toggle_id(ui.ctx(), popup_id); - } - - egui::Popup::from_response(&response).id(popup_id).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.set_min_width(230.0); - egui::ScrollArea::vertical().max_height(380.0).show(ui, |ui| { - let mut category = ""; - for preset in texturecraft_engine::paint::presets::PRESETS.iter() { - if preset.category != category { - category = preset.category; - ui.label(caption(category)); - } - if ui.selectable_label(false, preset.label).on_hover_text(tr("Use this brush (keeps its size)")).clicked() { - app.run("brush.preset.apply", json!({"preset": preset.id})); - } - } - - ui.separator(); - crate::shelf::user_brushes(app, ui, ""); - }); - }); -} - /// Width of the label column in polygon fill's properties const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0; @@ -2429,298 +2350,16 @@ fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { } } -/// Font size of the dim hint line under the Brush caption -const HINT_TEXT_SIZE: f32 = 10.5; - -fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - ui.label(caption(tr("Brush"))); - brush_presets_popover(app, ui); - }); - - let brush = &mut app.session.tool.brush; - let defaults = BrushSettings::default(); - let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); - ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); - ui.label(RichText::new(tr("Ctrl+Shift+right-drag: size and hardness in fine steps.")).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); - - // Each section's reset puts back only the fields it shows - let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.screen_space); - if section_with_reset(ui, "sec_size", tr("Size"), true, size_fields(brush) == size_fields(&defaults), |ui| { - let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; - if slider(ui, tr("Size"), &mut size_percent, 0.05..=100.0, 1).changed() { - brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); - } - - let mut min_size_percent = brush.min_size * 100.0; - if slider(ui, tr("Minimum size (%)"), &mut min_size_percent, 0.0..=100.0, 0).changed() { - brush.min_size = min_size_percent / 100.0; - } - - ui.checkbox(&mut brush.screen_space, tr("Size in screen space")); - }) { - (brush.size, brush.min_size, brush.screen_space) = size_fields(&defaults); - } - - let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing); - if section_with_reset(ui, "sec_flow", tr("Flow and opacity"), true, flow_fields(brush) == flow_fields(&defaults), |ui| { - let mut flow_percent = brush.flow * 100.0; - if slider(ui, tr("Flow"), &mut flow_percent, 0.0..=100.0, 0).changed() { - brush.flow = flow_percent / 100.0; - } - - let mut opacity_percent = brush.opacity * 100.0; - if slider(ui, tr("Stroke opacity"), &mut opacity_percent, 0.0..=100.0, 0).changed() { - brush.opacity = opacity_percent / 100.0; - } - - let mut spacing_percent = brush.spacing * 100.0; - if slider(ui, tr("Spacing"), &mut spacing_percent, 1.0..=1000.0, 0).changed() { - brush.spacing = spacing_percent / 100.0; - } - }) { - (brush.flow, brush.opacity, brush.spacing) = flow_fields(&defaults); - } - - let angle_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); - if section_with_reset(ui, "sec_angle", tr("Angle"), false, angle_fields(brush) == angle_fields(&defaults), |ui| { - slider(ui, tr("Angle"), &mut brush.angle, -180.0..=180.0, 0); - ui.checkbox(&mut brush.follow_path, tr("Follow path")); - }) { - (brush.angle, brush.follow_path) = angle_fields(&defaults); - } - - let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_angle, settings.jitter_flow, settings.jitter_position); - if section_with_reset(ui, "sec_jitter", tr("Jitters"), false, jitter_fields(brush) == jitter_fields(&defaults), |ui| { - let jitters = [(tr("Size jitter"), &mut brush.jitter_size), (tr("Angle jitter"), &mut brush.jitter_angle), (tr("Flow jitter"), &mut brush.jitter_flow)]; - for (label, jitter) in jitters { - let mut jitter_percent = *jitter * 100.0; - if slider(ui, label, &mut jitter_percent, 0.0..=100.0, 0).changed() { - *jitter = jitter_percent / 100.0; - } - } - - let mut position_jitter_percent = brush.jitter_position * 100.0; - if slider(ui, tr("Position jitter"), &mut position_jitter_percent, 0.0..=400.0, 0).changed() { - brush.jitter_position = position_jitter_percent / 100.0; - } - }) { - (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = jitter_fields(&defaults); - } - - let alignment_fields = |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.depth); - if section_with_reset(ui, "sec_align", tr("Alignment and culling"), false, alignment_fields(brush) == alignment_fields(&defaults), |ui| { - use texturecraft_engine::paint::Alignment; - let alignments = [(Alignment::Tangent, tr("Tangent | Wrap")), (Alignment::Camera, tr("Camera"))]; - let shown = alignments.iter().find(|(alignment, _)| *alignment == brush.alignment).map_or("", |(_, label)| label); - combo(ui, tr("Alignment"), shown, |ui| { - for (alignment, label) in alignments { - ui.selectable_value(&mut brush.alignment, alignment, label); - } - }); - - ui.checkbox(&mut brush.backface_culling, tr("Backface culling")); - slider(ui, tr("Angle fade from"), &mut brush.angle_fade.0, 0.0..=90.0, 0); - slider(ui, tr("Angle fade to"), &mut brush.angle_fade.1, 0.0..=90.0, 0); - slider(ui, tr("Stamp depth"), &mut brush.depth, 0.05..=4.0, 2); - }) { - (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = alignment_fields(&defaults); - } - - if section_with_reset(ui, "sec_particles", tr("Particles"), false, brush.particles == defaults.particles, |ui| { - let particles = &mut brush.particles; - ui.checkbox(&mut particles.enabled, tr("Particle brush (slides down the surface)")); - - let mut count = particles.count as f32; - if slider(ui, tr("Count per stamp"), &mut count, 1.0..=16.0, 0).changed() { - particles.count = count as u32; - } - - let mut lifetime_steps = particles.lifetime as f32; - if slider(ui, tr("Lifetime (steps)"), &mut lifetime_steps, 1.0..=128.0, 0).changed() { - particles.lifetime = lifetime_steps as u32; - } - - slider(ui, tr("Gravity"), &mut particles.gravity, 0.0..=2.0, 2); - }) { - brush.particles = defaults.particles; - } - - if section_with_reset(ui, "sec_lazy", tr("Lazy mouse"), false, brush.lazy == defaults.lazy, |ui| { - slider(ui, tr("Lazy mouse distance"), &mut brush.lazy, 0.0..=200.0, 0); - }) { - brush.lazy = defaults.lazy; - } - - *brush = brush.sanitized(); -} - -/// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. -fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Painter, Rect)) -> egui::Response { - let tk = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(vec2(52.0, 64.0), Sense::click()); - let p = ui.painter(); - p.rect_filled(rect, 3.0, tk.viewport); - if on { - p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - } - paint(p, Rect::from_center_size(rect.center() - vec2(0.0, 7.0), vec2(40.0, 40.0))); - let name = elided(p, label, 9.5, tk.viewport_text, rect.width() - 4.0); - p.galley(rect.center_bottom() - vec2(name.size().x * 0.5, 6.0 + name.size().y * 0.5), name, tk.viewport_text); - resp.on_hover_text(label) -} - -fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(caption(tr("Alpha"))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| import_button(app, ui)); - }); - let brush = &app.session.tool.brush; - let (current, image, hardness) = (brush.alpha, brush.alpha_image.clone(), brush.hardness); - let library = if image.is_none() { brush.alpha_library.as_deref().and_then(alphas::find) } else { None }; - let mut pick = None; - let zone = ui.horizontal_wrapped(|ui| { - for a in BrushAlpha::ALL { - let on = image.is_none() && library.is_none() && current == a; - if alpha_tile(ui, on, tr(a.label()), |p, r| crate::thumbs::paint_alpha(p, r, a, hardness)).clicked() { - pick = Some(json!(a.label())); - } - } - - // The library alpha in use (picked from the shelf's Alphas tab) - if let Some(a) = library { - let tex = app.thumbs.alpha(ui.ctx(), a); - alpha_tile(ui, true, &a.label, |p, r| { - if let Some(t) = tex { - p.image(t.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - } - }); - } - - // Imported images, sampled as grayscale - for name in app.session.doc.resources.keys() { - let Some(img) = app.session.images.get(name) else { continue }; - let tex = app.thumbs.image(ui.ctx(), name, img); - let on = image.as_deref() == Some(name.as_str()); - if alpha_tile(ui, on, name, |p, r| { - p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - }) - .clicked() - { - pick = Some(json!({ "image": name })); - } - } - }); - if let Some(alpha) = pick { - app.run("tool.brush", json!({ "alpha": alpha })); - } - ui.label(RichText::new(tr("More in Assets > Alphas: click one, or drag it here")).size(10.0).color(tk.text_dim)); - crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush); - alpha_parameters(&mut app.session.tool.brush, ui); - section(ui, "sec_text", tr("Text"), true, |ui| text_section(app, ui)); -} - -/// Hardness and the parameters every alpha shares, under a header whose reset puts them back -fn alpha_parameters(brush: &mut BrushSettings, ui: &mut Ui) { - let defaults = BrushSettings::default(); - let at_defaults = brush.hardness == defaults.hardness && brush.alpha_params == defaults.alpha_params; - let round = brush.alpha == BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none(); - let percent_slider = |ui: &mut Ui, label: &str, value: &mut f32, min: f32, max: f32| { - let mut percent = *value * 100.0; - if slider(ui, label, &mut percent, min..=max, 0).changed() { - *value = percent / 100.0; - } - }; - - let reset = section_with_reset(ui, "sec_alpha_params", tr("Parameters"), true, at_defaults, |ui| { - percent_slider(ui, tr("Hardness"), &mut brush.hardness, 0.0, 99.9); - percent_slider(ui, tr("Size X"), &mut brush.alpha_params.size_x, 5.0, 100.0); - percent_slider(ui, tr("Size Y"), &mut brush.alpha_params.size_y, 5.0, 100.0); - - // Only the procedural Round shape has a roundness - ui.add_enabled_ui(round, |ui| percent_slider(ui, tr("Roundness"), &mut brush.alpha_params.roundness, 0.0, 100.0)); - slider(ui, tr("Contrast"), &mut brush.alpha_params.contrast, 1.0..=MAX_ALPHA_CONTRAST, 2); - ui.checkbox(&mut brush.alpha_params.invert, tr("Invert")); - }); - if reset { - (brush.hardness, brush.alpha_params) = (defaults.hardness, defaults.alpha_params); - } - *brush = brush.sanitized(); -} - -/// Text drawn in a font, as the brush alpha or a decal (`resource.text`). -fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { - if app.ui.text.fonts.is_empty() - && let Some(f) = app.run("text.fonts", Value::Null) - { - let installed = f["installed"].as_array().into_iter().flatten().map(|v| { - let styles = v["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); - (v["family"].as_str().unwrap_or_default().to_string(), styles) - }); - let built_in = f["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), Vec::new())); - app.ui.text.fonts = installed.chain(built_in).collect(); - } - // A decal shows the text in the tool's base color; an alpha must stay white. - let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]); - let t = &mut app.ui.text; - ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(2).desired_width(f32::INFINITY).hint_text(tr("Text"))); - let shown = if t.font.is_empty() { tr("Default").to_string() } else { t.font.clone() }; - combo(ui, tr("Font"), shown, |ui| { - if ui.selectable_label(t.font.is_empty(), tr("Default")).clicked() { - (t.font, t.style) = (String::new(), String::new()); - } - for (family, _) in &t.fonts { - if ui.selectable_label(t.font == *family, family).clicked() { - (t.font, t.style) = (family.clone(), String::new()); - } - } - }); - let styles = t.fonts.iter().find(|(f, _)| *f == t.font).map(|(_, s)| s.clone()).unwrap_or_default(); - if styles.len() > 1 { - let shown = if t.style.is_empty() { tr("Default").to_string() } else { t.style.clone() }; - combo(ui, tr("Style"), shown, |ui| { - for s in styles { - ui.selectable_value(&mut t.style, s.clone(), s); - } - }); - } - let mut params = json!({"text": t.text, "font": (!t.font.is_empty()).then_some(&t.font), "style": (!t.style.is_empty()).then_some(&t.style)}); - let ready = !t.text.trim().is_empty(); - ui.horizontal_wrapped(|ui| { - let alpha = ui.add_enabled(ready, egui::Button::new(tr("Use as brush alpha"))).clicked(); - let decal = ui.add_enabled(ready, egui::Button::new(tr("Place as decal"))).clicked(); - if decal { - params["color"] = json!(color); - } - if (alpha || decal) - && let Some(name) = app.run("resource.text", params).and_then(|r| r["name"].as_str().map(str::to_string)) - { - match alpha { - true => app.run("tool.brush", json!({"alpha": {"image": name}})), - false => app.run("layer.add.decal", json!({"image": name})), - }; - } - }); -} - /// Tooltip of the material channel chips. pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; -/// The tool's material under a "Material" heading -fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(caption(tr("Material"))); - material_controls(app, ui); -} - /// Space between the tool's channel chips and the first channel value const CHIPS_GAP: f32 = 4.0; /// Room right of the tool's colour swatch, like a linked material's const TOOL_SWATCH_RIGHT_MARGIN: f32 = LINK_SWATCH_RIGHT_MARGIN; -/// One chip per channel of the texture set, on while the tool's material has it enabled; returns the channels. -/// The Material tab and the Smudge panel both draw these, so they share one set of flags. +/// One chip per channel of the texture set, on while the tool's material has it enabled (the flags the Material section's pills show); returns the channels fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec { let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { @@ -2735,7 +2374,7 @@ fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec crate::anchor_properties::anchor_properties(app, ui, effect_id, &effect.name), - EffectKind::Paint => legacy_body(ui, |ui| { - let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { - tr("Paint on the mesh to edit the layer content.") - } else { - tr("Paint on the mesh to edit this mask.") - }; - ui.label(RichText::new(hint).color(tokens.text_dim)); + EffectKind::Paint => { + legacy_body(ui, |ui| { + let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { + tr("Paint on the mesh to edit the layer content.") + } else { + tr("Paint on the mesh to edit this mask.") + }; + ui.label(RichText::new(hint).color(tokens.text_dim)); + }); if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } - }), - EffectKind::Path(paths) => legacy_body(ui, |ui| { - ui.label( + } + EffectKind::Path(paths) => { + legacy_body(ui, |ui| { + ui.label( RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) .color(tokens.text_dim), ); - let editing = app.session.tool.path.editing; - for index in 0..paths.len() { - ui.horizontal(|ui| { - let selected = editing == Some((effect_id, index)); - if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { - if selected { - app.run("tool.path", json!({"clear": true})); - } else { - app.run("path.edit", json!({"effect": id, "index": index})); + let editing = app.session.tool.path.editing; + for index in 0..paths.len() { + ui.horizontal(|ui| { + let selected = editing == Some((effect_id, index)); + if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { + if selected { + app.run("tool.path", json!({"clear": true})); + } else { + app.run("path.edit", json!({"effect": id, "index": index})); + } } - } - if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { - app.run("path.remove", json!({"effect": id, "index": index})); - } - }); - } + if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { + app.run("path.remove", json!({"effect": id, "index": index})); + } + }); + } + }); if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } - }), + } EffectKind::Filter(filter) => crate::filter_properties::filter_properties(app, ui, effect_id, filter), EffectKind::ColorSelection(selection) => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, selection), EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index aa7f223d..e528e7b3 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -889,15 +889,13 @@ pub fn save_library(app: &TextureCraftApp, storage: &mut dyn eframe::Storage) { fn outputs(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32) { let look = ExportLook::get(ui.ctx()); let tokens = Tokens::get(ui.ctx()); - let (mut preset, editable) = match (&app.ui.export.draft, selected(app)) { - (Some(d), _) => (d.clone(), true), - (None, Some(b)) => (b, false), - (None, None) => { - MapPreviewCache::clear(ui.ctx()); - drawn::label_at(ui, column.left(), top + CURRENT_PRESET_Y, tr("Select an output template"), look.text_dim, false); - return; - } + let editable = app.ui.export.draft.is_some(); + let Some(mut preset) = app.ui.export.draft.clone().or_else(|| selected(app)) else { + MapPreviewCache::clear(ui.ctx()); + drawn::label_at(ui, column.left(), top + CURRENT_PRESET_Y, tr("Select an output template"), look.text_dim, false); + return; }; + let params = plan_params(app, &preset); let preview = match ¶ms { Ok(params) => MapPreviewCache::plan(app, ui.ctx(), params), @@ -1043,9 +1041,10 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32) { if acted { pending = None; } - let e = &mut app.ui.export; - e.draft_split = split; - e.pending_drop = pending; + + app.ui.export.draft_split = split; + app.ui.export.pending_drop = pending; + if acted || changed { commit(app, preset, origin); } @@ -1782,7 +1781,8 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ /// The maps the selected template's outputs read, with their colours, for the panes' markers fn marked_sources(app: &TextureCraftApp) -> Vec<(SourceRef, Color32)> { - let Some(preset) = app.ui.export.draft.clone().or_else(|| selected(app)) else { return Vec::new() }; + let draft = app.ui.export.draft.as_ref().map(std::borrow::Cow::Borrowed); + let Some(preset) = draft.or_else(|| selected(app).map(std::borrow::Cow::Owned)) else { return Vec::new() }; let sources = preset.maps.iter().flat_map(|map| map.channels.iter().map(|(_, source)| source)); sources.filter_map(|source| source_color(source).map(|color| (source.clone(), color))).collect() diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index c346d033..2b18c5fb 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -448,22 +448,22 @@ fn start_export(app: &mut TextureCraftApp) { texturecraft_engine::formats::export::validate_export_paths(paths).err().map(|error| trf("Export stopped: {error}", &[("error", &error)])) }); - let e = &mut app.ui.export; - e.tab = 2; - e.console = vec![ConsoleLine::Step(tr("Preparing texture export").into())]; + let export = &mut app.ui.export; + export.tab = 2; + export.console = vec![ConsoleLine::Step(tr("Preparing texture export").into())]; if let Some(error) = error { - e.console.push(ConsoleLine::Step(error.clone())); + export.console.push(ConsoleLine::Step(error.clone())); app.toast(error, true); return; } - e.job = Some(crate::state::ExportJob { + export.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, - usd_asset: e.usd_asset, - shader_parameters: e.shader_parameters, + usd_asset: export.usd_asset, + shader_parameters: export.shader_parameters, ..Default::default() }); } @@ -1340,9 +1340,9 @@ fn success(tk: &Tokens) -> egui::Color32 { } /// The LIST OF EXPORTS tab in `body`: the file tree with each file's path as tooltip, the fold strip and the console -fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { +fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect, idle_plans: Option<&[ExportSetPlan]>) { let look = ExportLook::get(ui.ctx()); - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let hidden = app.ui.export.console_hidden; // The console keeps at least its least width, the tree at least its own @@ -1353,7 +1353,7 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { let tree = egui::Rect::from_min_max(egui::pos2(body.left(), body.top() + 1.0), egui::pos2(strip.left() - STRIP_GAP, body.bottom())); ui.painter().rect_filled(tree, 0.0, look.chrome); ui.scope_builder(egui::UiBuilder::new().max_rect(tree), |ui| { - egui::ScrollArea::both().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); + egui::ScrollArea::both().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tokens, idle_plans)); }); // The strip at the console's left edge: a click hides or shows the console, a drag resizes it @@ -1391,8 +1391,8 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { for (index, line) in app.ui.export.console.iter().enumerate() { let response = match line { ConsoleLine::Step(text) => ui.label(text), - ConsoleLine::Done(text) => ui.label(RichText::new(text).color(success(&tk))), - ConsoleLine::Set(name) => ui.label(set_line(ui, name, &tk)), + ConsoleLine::Done(text) => ui.label(RichText::new(text).color(success(&tokens))), + ConsoleLine::Set(name) => ui.label(set_line(ui, name, &tokens)), }; if index + 1 == app.ui.export.console.len() { @@ -1417,19 +1417,30 @@ fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { } /// One foldable node per ticked texture set, a row per file; the columns start after the longest file name -fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { - let (sets, directory): (Vec<(usize, ExportSetPlan)>, String) = match &app.ui.export.job { - Some(job) if !job.preview.is_empty() => (job.preview.iter().cloned().enumerate().collect(), job.directory.clone()), +fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens, idle_plans: Option<&[ExportSetPlan]>) { + let planned: Vec; + let (sets, directory) = match (&app.ui.export.job, idle_plans) { + (Some(job), _) if !job.preview.is_empty() => (job.preview.as_slice(), job.directory.as_str()), + (_, Some(plans)) => (plans, app.ui.export.dir.as_str()), _ => { - let planned = export_selection(app).into_iter().filter_map(|ts| { - let params = set_params(app, ts); - plan_set(app, ts, ¶ms).map(|set| (ts, set)) - }); - (planned.collect(), app.ui.export.dir.clone()) + planned = selected_plans(app); + (planned.as_slice(), app.ui.export.dir.as_str()) } }; - let rows: Vec> = sets.iter().map(|(_, set)| tree_files(set, &directory)).collect(); - let longest = |text: fn(&TreeFile) -> &str| rows.iter().flatten().map(|file| drawn::text_width(ui, text(file), false)).fold(0.0, f32::max); + + let rows: Vec> = sets.iter().map(|set| tree_files(set, directory)).collect(); + let longest = |column: fn(&TreeFile) -> &str| { + let mut widest = 0.0_f32; + let mut previous = None; + for value in rows.iter().flatten().map(column) { + if previous != Some(value) { + widest = widest.max(drawn::text_width(ui, value, false)); + previous = Some(value); + } + } + + widest + }; let columns = { let size = TREE_FILE_INDENT + longest(|f| &f.name) + TREE_COLUMN_GAP; let format = size + longest(|f| &f.size) + TREE_COLUMN_GAP; @@ -1437,27 +1448,38 @@ fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { }; // Each set takes its header row, its files when open and a blank row - let open: Vec = sets.iter().map(|(index, _)| ui.data(|d| d.get_temp::(tree_id(ui, *index))).unwrap_or(true)).collect(); + let disclosure: Vec<_> = sets + .iter() + .enumerate() + .map(|(row, set)| { + let id = match set.index { + Some(index) => ui.scope_id().with(("exp_tree", index)), + None => ui.scope_id().with(("removed_export_set", row)), + }; + let open = ui.data(|data| data.get_temp::(id)).unwrap_or(true); + (id, open) + }) + .collect(); let row_count: usize = sets .iter() .zip(&rows) - .zip(&open) - .map(|(((_, set), files), open)| 1 + 1 + if *open { files.len().max(usize::from(set.files.is_err())) } else { 0 }) + .zip(&disclosure) + .map(|((set, files), (_, open))| 2 + if *open { files.len().max(usize::from(set.files.is_err())) } else { 0 }) .sum(); let width = ui.available_width().max(columns[2] + longest(|file| &file.bits) + TREE_BITS_GAP); let height = TREE_TOP_PADDING + row_count as f32 * TREE_ROW_HEIGHT; let (area, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); let mut y = area.top() + TREE_TOP_PADDING; - for (((index, set), files), open) in sets.iter().zip(&rows).zip(open) { + for ((set, files), (id, open)) in sets.iter().zip(&rows).zip(disclosure) { let header = egui::Rect::from_min_max(egui::pos2(area.left(), y), egui::pos2(area.right(), y + TREE_ROW_HEIGHT)); - if tree_header(ui, header, &set.name, open, tree_id(ui, *index)) { - ui.data_mut(|d| d.insert_temp(tree_id(ui, *index), !open)); + if tree_header(ui, header, &set.name, open, id) { + ui.data_mut(|data| data.insert_temp(id, !open)); } y += TREE_ROW_HEIGHT; if open { if let Err(error) = &set.files { - drawn::label_at(ui, area.left() + TREE_FILE_INDENT, y + TREE_ROW_HEIGHT / 2.0, error, tk.danger, false); + drawn::label_at(ui, area.left() + TREE_FILE_INDENT, y + TREE_ROW_HEIGHT / 2.0, error, tokens.danger, false); y += TREE_ROW_HEIGHT; } for file in files { @@ -1469,6 +1491,16 @@ fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { } } +fn selected_plans(app: &mut TextureCraftApp) -> Vec { + export_selection(app) + .into_iter() + .filter_map(|index| { + let params = set_params(app, index); + plan_set(app, index, ¶ms) + }) + .collect() +} + fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) -> Option { let set = app.session.doc.project.texture_sets.get(index)?; let name = set.name.clone(); @@ -1477,11 +1509,6 @@ fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) Some(ExportSetPlan { index: Some(index), name, files }) } -/// Where a texture set's node keeps whether it is open -fn tree_id(ui: &Ui, index: usize) -> egui::Id { - ui.scope_id().with(("exp_tree", index)) -} - /// The texts of each file `set` plans: name, size, file type, bit depth and its whole path fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { let Ok(files) = &set.files else { return Vec::new() }; @@ -1511,6 +1538,7 @@ fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui:: // Expose the hand-drawn header as a disclosure control response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, true, name)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(open)); let y = rect.center().y; let chevron = if open { @@ -1734,7 +1762,7 @@ pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { } /// The bottom bar: Export, Save settings, Cancel and the texture count, Reset all on SETTINGS; while exporting, progress -fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do_export: &mut bool, canceled: &mut bool) { +fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do_export: &mut bool, canceled: &mut bool) -> Option> { let slot = |k: f32| { let right = window.right() - RIGHT_MARGIN - k * (FOOTER_BUTTON_WIDTH + FOOTER_BUTTON_GAP); drawn::control_rect(right - FOOTER_BUTTON_WIDTH, right, y) @@ -1749,7 +1777,7 @@ fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do let look = ExportLook::get(ui.ctx()); let response = ui.put(bar, egui::ProgressBar::new(progress).fill(look.outline).text(format!("{:.0}%", progress * 100.0))); ui.ctx().accesskit_node_builder(response.id, |node| node.set_live(egui::accesskit::Live::Polite)); - return; + return None; } // OUTPUT TEMPLATES shows no count; a template edit that does not validate holds Save and Export @@ -1770,9 +1798,20 @@ fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do if cancel.on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { *canceled = true; } + let list_plans = (app.ui.export.tab == 2).then(|| selected_plans(app)); if !templates_tab { + let texture_count = match &list_plans { + Some(plans) => plans + .iter() + .try_fold(0, |count, set| { + let files = set.files.as_ref().ok()?; + Some(count + files.as_array().map_or(0, Vec::len)) + }) + .unwrap_or(0), + None => selected_texture_count(app), + }; let look = ExportLook::get(ui.ctx()); - let count = trf("{n} textures selected for export", &[("n", &selected_texture_count(app))]); + let count = trf("{n} textures selected for export", &[("n", &texture_count)]); let left = slot(2.0).left() - COUNT_GAP - drawn::text_width(ui, &count, false); drawn::label_at(ui, left, y, &count, look.text_dim, false); } @@ -1782,10 +1821,12 @@ fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do && drawn::button(ui, reset_rect, tr("Reset all"), false, true).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() { // Keep ownership so Cancel can restore the opening settings - let e = &mut app.ui.export; - let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); + let export = &mut app.ui.export; + let (opened_with, owner, owner_id) = (export.opened_with.take(), std::mem::take(&mut export.owner), export.owner_id); app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; } + + list_plans } /// The SETTINGS tab in `body`: the texture set list, a divider, then the selected page @@ -1826,13 +1867,13 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::export_templates::clear_map_previews(ctx); // The window opens on SETTINGS again; an export stops with it - let e = &mut app.ui.export; - e.job = None; - e.ask = None; - e.pending_drop = None; - e.opened_with = None; - e.tab = 0; - e.page = None; + let export = &mut app.ui.export; + export.job = None; + export.ask = None; + export.pending_drop = None; + export.opened_with = None; + export.tab = 0; + export.page = None; return; } @@ -1921,7 +1962,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let footer_y = window.bottom() - FOOTER_MIDDLE_FROM_BOTTOM; drawn::divider(ui, egui::Rect::from_min_max(body.left_bottom(), body.right_bottom() + vec2(0.0, 1.0))); - footer(app, ui, window, footer_y, &mut do_export, &mut canceled); + let list_plans = footer(app, ui, window, footer_y, &mut do_export, &mut canceled); // The tabs lay out from the body; a child clips what an overflow would draw past it let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body)); @@ -1929,7 +1970,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let ui = &mut body_ui; match app.ui.export.tab { 1 => crate::export_templates::tab(app, ui, body, presets), - 2 => list_tab(app, ui, body), + 2 => list_tab(app, ui, body, list_plans.as_deref()), _ => settings_tab(app, ui, body, presets), } }); diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs index 22c87109..7a08c986 100644 --- a/crates/ui-egui/src/framework.rs +++ b/crates/ui-egui/src/framework.rs @@ -122,6 +122,10 @@ impl TextureCraftApp { Brightness::Dark | Brightness::MediumDark => craft_theme::Mode::Dark, }; let mut root = RootEnv::new().mode(mode).scale(Scale::new(scale)); + if let Some(theme) = crate::library_theme::library_theme(ctx, &crate::theme::Tokens::get(ctx)) { + root = root.library_theme(theme); + } + // Hide UI on another key leaves Tab to focus traversal and the shortcuts root.tab_toggles_chrome = crate::keymap::shortcut_of(&self.ui.keymap, "ui.hideUi") == Some("Tab"); let app_modal = crate::docking::input_blocked(self, ctx).then_some(ViewportId::ROOT); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 7d9be266..cdf46547 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -698,9 +698,9 @@ pub fn fixed_gestures() -> Vec<(String, String)> { (tr("Ctrl + RMB drag").into(), tr("Brush size (left/right) and hardness (up/down)").into()), (tr("Ctrl + LMB drag").into(), tr("Brush flow (left/right) and angle (up/down)").into()), (tr("Ctrl + Shift + RMB drag").into(), tr("Brush size and hardness in fine steps").into()), - (keyed("{key} + LMB drag"), tr("Projection: rotate the stencil").into()), - (keyed("{key} + RMB drag"), tr("Projection: scale the stencil").into()), - (keyed("{key} + MMB drag"), tr("Projection: move the stencil").into()), + (keyed("{key} + LMB drag"), tr("Rotate the stencil").into()), + (keyed("{key} + RMB drag"), tr("Scale the stencil").into()), + (keyed("{key} + MMB drag"), tr("Move the stencil").into()), (trf("{key} + LMB", &[("key", &clone)]), tr("Clone: pick the point to copy from").into()), (tr("Click (Path tool)").into(), tr("Path: add a point; on the curve it inserts one").into()), (tr("LMB drag on a point (Path tool)").into(), tr("Path: move the point").into()), @@ -733,7 +733,7 @@ mod tests { let rows = fixed_gestures(); let has = |gesture: &str, what: &str| rows.iter().any(|(g, w)| g == gesture && w.contains(what)); let (s, v) = (crate::viewport::STENCIL_KEY.name(), crate::viewport::CLONE_SOURCE_KEY.name()); - assert!(has(&format!("{s} + LMB drag"), "rotate") && has(&format!("{s} + RMB drag"), "scale") && has(&format!("{s} + MMB drag"), "move")); + assert!(has(&format!("{s} + LMB drag"), "Rotate") && has(&format!("{s} + RMB drag"), "Scale") && has(&format!("{s} + MMB drag"), "Move")); assert!(has(&format!("{v} + LMB"), "Clone")); for (gesture, what) in [ ("Shift + LMB", "straight line"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ebb68f4e..32462eed 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,6 +7,8 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod alpha_choice; +mod alpha_sheet; mod anchor_properties; mod angle_dial; mod ask; @@ -20,6 +22,9 @@ pub mod bake_presets; mod bake_report; mod bake_scene; pub mod baking_log; +mod brush_pictures; +mod brush_sheet; +mod brush_stroke_preview; mod color_management; mod color_picker; mod color_selection_editor; @@ -79,6 +84,7 @@ mod levels_display; mod levels_editor; mod levels_handle; mod levels_properties; +mod library_theme; mod line_snap; mod list_action; pub mod log_panel; @@ -90,6 +96,7 @@ mod mask_preview_image; mod mask_source_choice; mod material_orb; mod material_preview_image; +mod material_sheet; pub mod menus; mod mesh_export_options; #[cfg(not(target_arch = "wasm32"))] @@ -109,6 +116,7 @@ pub mod orb_previews; mod orb_shape; /// The channel's OS identity (app id, window and app names) — see its module docs. pub mod os_window; +mod paint_section; mod pane_split; pub mod parity; mod past_end; @@ -185,8 +193,11 @@ mod soft_box; mod source_choice; mod source_slot; pub mod state; +mod stencil_choice; +mod stencil_sheet; mod surface_paint_point; pub mod symmetry; +mod tabbed_page; pub mod theme; pub mod thumbs; mod tile_edits; diff --git a/crates/ui-egui/src/library_theme.rs b/crates/ui-egui/src/library_theme.rs new file mode 100644 index 00000000..38f24b65 --- /dev/null +++ b/crates/ui-egui/src/library_theme.rs @@ -0,0 +1,52 @@ +//! TextureCraft's colours handed to craft-ui, so the dock's frames, tab strips and splitters draw in our theme instead of the suite's default grey + +use std::sync::Arc; + +use craft_theme::{ColorToken, ModePins, Pins, Rgba, SUITE_DEFAULT, ThemeDef, ThemeId, builtins}; +use egui::{Color32, Context, Id}; + +use crate::theme::Tokens; + +/// The id of TextureCraft's theme, apart from every built-in one +const THEME_ID: &str = "texturecraft.app"; + +/// The theme craft-ui resolves its tokens from (`RootEnv::library_theme`), kept while the tokens stay the same so it resolves once per theme change +pub(crate) fn library_theme(ctx: &Context, tokens: &Tokens) -> Option> { + let pins = app_pins(tokens); + let memory_id = Id::unique(THEME_ID); + let kept: Option> = ctx.data(|data| data.get_temp(memory_id)); + if let Some(def) = kept.filter(|def| def.pins.dark == pins) { + return Some(def); + } + + let def = Arc::new(app_def(pins)?); + ctx.data_mut(|data| data.insert_temp(memory_id, Arc::clone(&def))); + Some(def) +} + +/// The suite default with TextureCraft's colours pinned in both modes (the root's mode picks one); `None` if the suite default is missing +fn app_def(pins: Pins) -> Option { + let mut def = builtins().iter().find(|theme| theme.id.as_str() == SUITE_DEFAULT)?.clone(); + def.id = ThemeId::parse(THEME_ID).ok()?; + def.pins = ModePins { light: pins.clone(), dark: pins }; + Some(def) +} + +fn app_pins(tokens: &Tokens) -> Pins { + [ + (ColorToken::SurfaceBackground, rgba(tokens.chrome)), + (ColorToken::SurfacePanel, rgba(tokens.panel)), + (ColorToken::LineBorder, rgba(tokens.separator)), + (ColorToken::AccentSolid, rgba(tokens.accent)), + // The shown tab's name is brighter than the others, as on the panel headers + (ColorToken::TextNormal, rgba(tokens.text_strong)), + (ColorToken::TextMuted, rgba(tokens.text_dim)), + ] + .into_iter() + .collect() +} + +fn rgba(color: Color32) -> Rgba { + let [r, g, b, a] = color.to_srgba_unmultiplied(); + Rgba([r, g, b, a]) +} diff --git a/crates/ui-egui/src/mask_paint_panel.rs b/crates/ui-egui/src/mask_paint_panel.rs index cf12f191..7ecdfba4 100644 --- a/crates/ui-egui/src/mask_paint_panel.rs +++ b/crates/ui-egui/src/mask_paint_panel.rs @@ -1,6 +1,5 @@ -//! The paint tools' Grayscale tab while a mask is painted: the GRAYSCALE section with the slot of the gray a stroke lays down +//! The paint tools' Grayscale section while a mask is painted: the slot of the gray a stroke lays down -use egui::Ui; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::Session; @@ -20,58 +19,55 @@ use crate::theme::Tokens; use crate::tile_picture::TilePicture; /// The GRAYSCALE section: a slot card for one gray (with its ramp and invert) or an image whose gray is painted -pub(crate) fn grayscale_sheet(app: &mut TextureCraftApp, ui: &mut Ui) { - PropertySheet::show(ui, "mask_paint_sheet", |sheet| { - sheet.section(tr("Grayscale"), false); - let gray = app.session.tool.mask_value; - let source = match &app.session.tool.mask_image { - Some(name) => Source::Image { name: name.clone(), normal_format: NormalFormat::default() }, - None => Source::Uniform([gray; 3]), - }; - let tokens = Tokens::get(sheet.ui.ctx()); - let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source); - let line = source_line(app, &source); - let image = app.session.tool.mask_image.is_some(); - let slot = sheet.slot(&|painter, rect| paint_thumbnail(painter, rect, &picture, &tokens), tr("Grayscale"), &line, None, image, false); +pub(crate) fn grayscale_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let gray = app.session.tool.mask_value; + let source = match &app.session.tool.mask_image { + Some(name) => Source::Image { name: name.clone(), normal_format: NormalFormat::default() }, + None => Source::Uniform([gray; 3]), + }; + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source); + let line = source_line(app, &source); + let image = app.session.tool.mask_image.is_some(); + let slot = sheet.slot(&|painter, rect| paint_thumbnail(painter, rect, &picture, &tokens), tr("Grayscale"), &line, None, image, false); - let popup = sheet.ui.make_persistent_id("mask_paint_source"); - if slot.pick.clicked() { - resource_picker::toggle(sheet.ui.ctx(), popup); - } - let current = match &app.session.tool.mask_image { - Some(name) => MaskSourceChoice::Image(name.clone()), - None => MaskSourceChoice::Uniform, - }; - let ctx = sheet.ui.ctx().clone(); - let tabs = || source_tabs(&app.session, shown_color([gray; 3])); - match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), image, tabs) { - Some(MaskSourceChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), - Some(MaskSourceChoice::Image(name)) if app.session.tool.mask_image.as_deref() != Some(name.as_str()) => { - app.run("tool.material", json!({"maskImage": name})); - } - Some(MaskSourceChoice::Uniform) if image => { - app.run("tool.material", json!({"maskImage": null})); - } - _ => {} - } - if slot.clear { - app.run("tool.material", json!({"maskImage": null})); - } - if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + let popup = sheet.ui.make_persistent_id("mask_paint_source"); + if slot.pick.clicked() { + resource_picker::toggle(sheet.ui.ctx(), popup); + } + let current = match &app.session.tool.mask_image { + Some(name) => MaskSourceChoice::Image(name.clone()), + None => MaskSourceChoice::Uniform, + }; + let ctx = sheet.ui.ctx().clone(); + let tabs = || source_tabs(&app.session, shown_color([gray; 3])); + match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), image, tabs) { + Some(MaskSourceChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(MaskSourceChoice::Image(name)) if app.session.tool.mask_image.as_deref() != Some(name.as_str()) => { app.run("tool.material", json!({"maskImage": name})); } - - if !image { - let mut value = gray; - let edit = sheet.ramp(tr("Grayscale"), &mut value, 0.0..=1.0); - if edit.invert { - app.run("tool.material", json!({"maskValue": 1.0 - gray})); - } else if edit.changed.is_some() { - app.run("tool.material", json!({"maskValue": value})); - } + Some(MaskSourceChoice::Uniform) if image => { + app.run("tool.material", json!({"maskImage": null})); } - sheet.close_card(); - }); + _ => {} + } + if slot.clear { + app.run("tool.material", json!({"maskImage": null})); + } + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + app.run("tool.material", json!({"maskImage": name})); + } + + if !image { + let mut value = gray; + let edit = sheet.ramp(tr("Grayscale"), &mut value, 0.0..=1.0); + if edit.invert { + app.run("tool.material", json!({"maskValue": 1.0 - gray})); + } else if edit.changed.is_some() { + app.run("tool.material", json!({"maskValue": value})); + } + } + sheet.close_card(); } /// The picker's one Resources tab: Textures (Import... first, then the project's images) and Uniform diff --git a/crates/ui-egui/src/material_sheet.rs b/crates/ui-egui/src/material_sheet.rs new file mode 100644 index 00000000..6ff7c5d4 --- /dev/null +++ b/crates/ui-egui/src/material_sheet.rs @@ -0,0 +1,71 @@ +//! The Material section of a brush tool's Properties: the channel strip, then one card per channel that is on with the value the brush paints there + +use serde_json::json; +use texturecraft_engine::Tool; +use texturecraft_engine::core::{Channel, ChannelKind, Source}; + +use crate::TextureCraftApp; +use crate::fill_material_panel::{pill_name, take_color_pick}; +use crate::i18n::tr; +use crate::property_sheet::PropertySheet; +use crate::slot_thumbnail::{paint_thumbnail, thumbnail}; +use crate::source_slot::SourceSlot; +use crate::theme::Tokens; + +/// The channel strip (the fill layer's pills), then a card per channel that is on; the eraser only picks channels +pub(crate) fn material_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); + let names: Vec<&str> = channels.iter().map(|channel| tr(pill_name(*channel))).collect(); + let enabled: Vec = channels.iter().map(|channel| app.session.tool.enabled.contains(channel)).collect(); + if let Some((index, solo)) = sheet.channel_pills(&names, &enabled) + && let Some(channel) = channels.get(index) + { + let enable = solo || !enabled.get(index).copied().unwrap_or(false); + app.run("tool.material", json!({"channel": channel.id(), "enabled": enable, "solo": solo})); + } + if app.session.tool.tool == Tool::Eraser { + return; + } + + let shown: Vec = channels.into_iter().filter(|channel| app.session.tool.enabled.contains(channel)).collect(); + for channel in shown { + channel_card(app, sheet, channel); + } +} + +/// One channel's card: its swatch, name and source, the ⟲ back to the channel's default, then its colour bar or gray ramp (a normal paints flat and has none) +fn channel_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, channel: Channel) { + let slot_of = SourceSlot::Channel(channel); + let kind = channel.kind(); + let default = channel.default_value(); + let value = if kind == ChannelKind::NormalMap { default } else { app.session.tool.values.get(&channel).copied().unwrap_or(default) }; + + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = thumbnail(app, &sheet.ui.ctx().clone(), &Source::Uniform(value)); + let thumb = |painter: &egui::Painter, rect: egui::Rect| paint_thumbnail(painter, rect, &picture, &tokens); + let line = if kind == ChannelKind::NormalMap { tr("Flat") } else { tr("Uniform") }; + if sheet.slot_fixed(&thumb, slot_of.name(), line, value != default).reset { + app.run("tool.material", json!({"channel": channel.id(), "value": default})); + } + + match kind { + ChannelKind::Color => { + let pick = sheet.color_bar(slot_of.name(), value, app.picking_color, &app.session.doc.project.swatches); + if let Some(color) = take_color_pick(app, pick) { + app.run("tool.material", json!({"channel": channel.id(), "color": color})); + } + } + ChannelKind::Scalar | ChannelKind::Signed => { + let mut gray = value[0]; + let edit = sheet.ramp(slot_of.name(), &mut gray, slot_of.range()); + if edit.invert { + let inverted = if kind == ChannelKind::Signed { -gray } else { 1.0 - gray }; + app.run("tool.material", json!({"channel": channel.id(), "value": inverted})); + } else if edit.changed.is_some() { + app.run("tool.material", json!({"channel": channel.id(), "value": gray})); + } + } + ChannelKind::NormalMap => {} + } + sheet.close_card(); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 5e5ced92..1504e0b0 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -468,8 +468,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - // A plain Escape or Enter while no widget of TextureCraft's has the keyboard is the window's cancel or submit: back - // in egui's input, it runs the Escape and Enter handlers below, the shortcuts and the Path tool's keys + // Route unhandled window actions back through the shortcuts and Path tool for (key, taken) in [(Key::Escape, crate::framework::take_window_cancel(ctx)), (Key::Enter, crate::framework::take_window_submit(ctx))] { if taken { let escape = craft_ui::runtime::keys::escape_mods(ctx).filter(|_| key == Key::Escape); @@ -496,7 +495,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { }); // Let the innermost popup consume Escape before cancelling the active tool - // (the drop popup of the Output templates tab is open without registering with egui, and reads Escape itself) + // The Output templates drop popup handles Escape outside egui's popup registry let popup_open = egui::Popup::is_any_open(ctx) || app.ui.export.pending_drop.is_some(); let point_pick_armed = crate::generator_point_pick::armed(ctx).is_some(); let mut cancel_point_pick = false; diff --git a/crates/ui-egui/src/paint_section.rs b/crates/ui-egui/src/paint_section.rs new file mode 100644 index 00000000..4648658f --- /dev/null +++ b/crates/ui-egui/src/paint_section.rs @@ -0,0 +1,50 @@ +//! The sections of a paint tool's Properties, each with its jump tab + +use egui_phosphor::regular as ic; + +use crate::i18n::tr; + +/// One section of a paint tool's Properties page +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PaintSection { + Brush, + Alpha, + Stencil, + Material, + /// The Material section's place while a mask is painted + Grayscale, +} + +impl PaintSection { + /// The sections in page order: Stencil only for a tool that `uses_stencil`, Grayscale instead of Material unless `content` is painted + pub(crate) fn page(uses_stencil: bool, content: bool) -> Vec { + let mut sections = vec![PaintSection::Brush, PaintSection::Alpha]; + if uses_stencil { + sections.push(PaintSection::Stencil); + } + sections.push(if content { PaintSection::Material } else { PaintSection::Grayscale }); + sections + } + + /// The section's caption and tab name + pub(crate) fn title(self) -> &'static str { + match self { + PaintSection::Brush => tr("Brush"), + PaintSection::Alpha => tr("Alpha"), + PaintSection::Stencil => tr("Stencil"), + PaintSection::Material => tr("Material"), + PaintSection::Grayscale => tr("Grayscale"), + } + } + + /// The tab's icon + pub(crate) fn icon(self) -> &'static str { + match self { + PaintSection::Brush => ic::PAINT_BRUSH, + PaintSection::Alpha => ic::CIRCLE_HALF, + PaintSection::Stencil => ic::FRAME_CORNERS, + PaintSection::Material => ic::SPHERE, + PaintSection::Grayscale => ic::SQUARE_HALF, + } + } +} diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/parity.rs index 2ad606b1..c452c978 100644 --- a/crates/ui-egui/src/parity.rs +++ b/crates/ui-egui/src/parity.rs @@ -51,12 +51,15 @@ pub fn headless_of(id: &str, in_engine: bool) -> (&'static str, Option<&'static if in_engine { return ("yes", None, ""); } + if let Some(m) = HEADLESS.iter().find(|m| m.0 == id) { return (m.1, Some(m.2), m.3); } + if WINDOW_PREFIXES.iter().any(|p| id.starts_with(p)) { return ("no", Some("window"), "a desktop panel or toolbar"); } + ("unknown", None, "") } diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index b078e520..b1a8a9f7 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -158,19 +158,12 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { /// Preview the brush along an S curve in a `size_px` square pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&ImageRes>) -> ColorImage { - // Leave room around the S curve and cap work for a single preview + // Leave room around the S curve const STROKE_RADIUS_FRACTION: f32 = 0.11; - const CURVE_SAMPLE_STEP: f32 = 0.002; - const MIN_STAMP_SPACING_PX: f32 = 0.5; - const MAX_STAMPS: u32 = 2000; const CURVE_HORIZONTAL_INSET: f32 = 0.15; const CURVE_HORIZONTAL_SPAN: f32 = 0.7; const CURVE_WAVE_AMPLITUDE: f32 = 0.22; - let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = size_px as f32 * STROKE_RADIUS_FRACTION; - let shape = Shape { alpha: brush.alpha, image, library, params: brush.alpha_params, level: 0 }.at_radius(radius); - // The horizontal inset and vertical wave keep the S curve inside the swatch let curve = |t: f32| { ( @@ -178,48 +171,90 @@ pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&Imag size_px as f32 * (0.5 - CURVE_WAVE_AMPLITUDE * (t * std::f32::consts::TAU).sin()), ) }; - let mut cover = vec![0f32; size_px * size_px]; + let cover = stamp_coverage(brush, image, [size_px, size_px], |_| size_px as f32 * STROKE_RADIUS_FRACTION, curve); + ColorImage::new([size_px, size_px], cover.into_iter().map(|coverage| Color32::from_gray((coverage * brush.opacity * 255.0 + 0.5) as u8)).collect()) +} + +/// The brush's stroke along `curve` (0..1 to pixels) in a `size` strip, stamps `radius` (0..1 to pixels) wide, columns in `tint`'s colour; missed pixels stay transparent +pub fn stroke_strip( + brush: &BrushSettings, + image: Option<&ImageRes>, + size: [usize; 2], + radius: impl Fn(f32) -> f32, + curve: impl Fn(f32) -> (f32, f32), + tint: impl Fn(usize) -> [u8; 3], +) -> ColorImage { + let cover = stamp_coverage(brush, image, size, radius, curve); + let pixels = cover + .into_iter() + .enumerate() + .map(|(index, coverage)| { + let [r, g, b] = tint(index % size[0]); + Color32::from_rgba_unmultiplied(r, g, b, (coverage * brush.opacity * 255.0 + 0.5) as u8) + }) + .collect(); + ColorImage::new(size, pixels) +} + +/// Paint coverage 0..1 of the brush's stamps (`radius` 0..1 to pixels, its alpha, hardness, spacing, flow, angle and jitters) along `curve` in a `width` × `height` image +fn stamp_coverage( + brush: &BrushSettings, + image: Option<&ImageRes>, + [width, height]: [usize; 2], + radius: impl Fn(f32) -> f32, + curve: impl Fn(f32) -> (f32, f32), +) -> Vec { + // Cap work for a single preview + const CURVE_SAMPLE_STEP: f32 = 0.002; + const MIN_STAMP_SPACING_PX: f32 = 0.5; + const MAX_STAMPS: u32 = 2000; + + let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let shape = Shape { alpha: brush.alpha, image, library, params: brush.alpha_params, level: 0 }.at_radius(radius(1.0)); + let mut cover = vec![0f32; width * height]; // Odd multipliers decorrelate reproducible jitter across stamps and channels let jitter_sample = |stamp_index: u32, channel: u32| { (stamp_index.wrapping_mul(0x9E37_79B9) ^ channel.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32 }; - let step = (brush.spacing * 2.0 * radius).max(MIN_STAMP_SPACING_PX); - let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); + + // Spacing follows the stamp's own radius, as on the model + let step = |t: f32| (brush.spacing * 2.0 * radius(t)).max(MIN_STAMP_SPACING_PX); + let (mut t, mut travelled, mut stamp_index) = (0.0f32, step(0.0), 0u32); let mut last = curve(0.0); - while t <= 1.0 && i < MAX_STAMPS { - let p = curve(t); - travelled += (p.0 - last.0).hypot(p.1 - last.1); - last = p; + while t <= 1.0 && stamp_index < MAX_STAMPS { + let point = curve(t); + travelled += (point.0 - last.0).hypot(point.1 - last.1); + last = point; t += CURVE_SAMPLE_STEP; - if travelled < step { + if travelled < step(t) { continue; } travelled = 0.0; - i += 1; - let stamp_radius = radius * (1.0 - brush.jitter_size * jitter_sample(i, 1)); - let tangent = if brush.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(i, 2); - let (cx, cy) = ( - p.0 + brush.jitter_position * radius * (jitter_sample(i, 3) * 2.0 - 1.0), - p.1 + brush.jitter_position * radius * (jitter_sample(i, 4) * 2.0 - 1.0), + stamp_index += 1; + let stamp_radius = radius(t) * (1.0 - brush.jitter_size * jitter_sample(stamp_index, 1)); + let tangent = if brush.follow_path { (curve(t).1 - point.1).atan2(curve(t).0 - point.0) } else { 0.0 }; + let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(stamp_index, 2); + let (center_x, center_y) = ( + point.0 + brush.jitter_position * radius(t) * (jitter_sample(stamp_index, 3) * 2.0 - 1.0), + point.1 + brush.jitter_position * radius(t) * (jitter_sample(stamp_index, 4) * 2.0 - 1.0), ); - let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(i, 5)); + let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(stamp_index, 5)); let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - stamp_radius).floor().max(0.0) as usize, ((cx + stamp_radius).ceil() as usize).min(size_px)); - let (y0, y1) = ((cy - stamp_radius).floor().max(0.0) as usize, ((cy + stamp_radius).ceil() as usize).min(size_px)); + let (x0, x1) = ((center_x - stamp_radius).floor().max(0.0) as usize, ((center_x + stamp_radius).ceil() as usize).min(width)); + let (y0, y1) = ((center_y - stamp_radius).floor().max(0.0) as usize, ((center_y + stamp_radius).ceil() as usize).min(height)); for y in y0..y1 { for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / stamp_radius, (cy - y as f32 - 0.5) / stamp_radius); - let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, i) * flow; - let coverage = &mut cover[y * size_px + x]; + let (dx, dy) = ((x as f32 + 0.5 - center_x) / stamp_radius, (center_y - y as f32 - 0.5) / stamp_radius); + let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, stamp_index) * flow; + let coverage = &mut cover[y * width + x]; *coverage = 1.0 - (1.0 - *coverage) * (1.0 - alpha.clamp(0.0, 1.0)); } } } - ColorImage::new([size_px, size_px], cover.into_iter().map(|v| Color32::from_gray((v * brush.opacity * 255.0 + 0.5) as u8)).collect()) + cover } /// Environment `name`'s panorama across a `size²` swatch, transparent above and below diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 291d50d9..1d59fdc1 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -85,9 +85,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // The docked panel's jump tabs on the top edge stay put while the sections scroll under them let scope = SectionScope::Popup; - if let Some(tabs) = crate::dock::properties_fill_tabs(app) { + if let Some(tabs) = crate::dock::properties_tabs(app) { crate::property_sheet::section_tabs(ui, scope, ui.style().visuals.menu_corner_radius.nw, &tabs); } + crate::dock::pinned_brush_preview(app, ui); crate::property_sheet::in_scope(ui, scope, |ui| { // A popup that fits its rows keeps its size; one that scrolls goes on until its last section's top let area = egui::ScrollArea::vertical().id_salt("properties_popup_scroll"); diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index c534afc3..c74a956a 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -2,7 +2,7 @@ use std::ops::RangeInclusive; -use egui::{Align2, Color32, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::row::SECTION_CAPTION_CENTER; use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS}; @@ -45,6 +45,9 @@ const PICTURE_TOP: f32 = 4.0; const PICTURE_SHORTER: f32 = 10.0; const PICTURE_TO_COLUMN: f32 = 6.0; +/// Width of the line around the picture +const PICTURE_OUTLINE_WIDTH: f32 = 1.0; + impl PropertySheet<'_> { /// A section caption with its on/off switch at the right edge pub(crate) fn section_switch(&mut self, title: &str, on: bool) -> Response { @@ -135,32 +138,35 @@ impl PropertySheet<'_> { Self::apply_typed(value, typed, dragged) } - /// Draw a picture beside captioned sliders and report the edit on each slider. + /// Draw a picture beside captioned sliders and report the edit on each slider pub(crate) fn picture_sliders(&mut self, picture: &dyn Fn(&Painter, Rect), sliders: &mut [StackSlider<'_>; N]) -> [Option; N] { let count = sliders.len().max(1) as f32; let height = count * (STACK_CAPTION_LINE + STACK_PART_LINE) + (count - 1.0) * STACK_GAP; self.space(BLOCK_MARGIN); let block = self.take(height); - let x0 = self.column(); - let side = (height - PICTURE_SHORTER).min(x0 - self.left - PICTURE_TO_COLUMN).max(1.0); + + let column_x = self.column(); + let side = (height - PICTURE_SHORTER).min(column_x - self.left - PICTURE_TO_COLUMN).max(1.0); let square = Rect::from_min_size(pos2(self.left, block.top() + PICTURE_TOP), vec2(side, side)); picture(self.ui.painter(), square); - self.ui.painter().rect_stroke(square, 0, Stroke::new(1.0, self.tokens.field_border), StrokeKind::Inside); + self.ui.painter().rect_stroke(square, CornerRadius::ZERO, Stroke::new(PICTURE_OUTLINE_WIDTH, self.tokens.field_border), StrokeKind::Inside); + let caption_color = self.tokens.text_dim; let mut edits = [None; N]; let mut y = block.top(); for (edit, slider) in edits.iter_mut().zip(sliders) { - let dim = self.tokens.text_dim; - let caption = pos2(x0, y + STACK_CAPTION_LINE / 2.0); - self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), dim); + let caption = pos2(column_x, y + STACK_CAPTION_LINE / 2.0); + self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), caption_color); + let center_y = y + STACK_CAPTION_LINE + STACK_PART_LINE / 2.0; let id = self.next_id(); let dial_x = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - DIAL_AIR - DIAL_RADIUS; let end = if slider.dial { dial_x - DIAL_RADIUS - DIAL_AIR } else { self.track_end() }; - let track = Track { start: x0 + KNOB_RADIUS, end, center_y, zero: None, ramp: false }; + let track = Track { start: column_x + KNOB_RADIUS, end, center_y, zero: (*slider.range.start() < 0.0).then_some(0.0), ramp: false }; if slider.dial { self.paint_dial(pos2(dial_x, center_y), *slider.value); } + let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); *edit = Self::apply_typed(slider.value, typed, dragged); diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index acd1f2dd..3a0b341d 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -29,6 +29,7 @@ mod material_rows; mod name_field; mod number_field; mod open_card; +mod pen_slider; mod preview_block; mod preview_edit; mod preview_lower; @@ -46,6 +47,7 @@ mod size_columns; mod size_columns_response; mod slider; mod slot; +mod slot_ends; mod slot_response; mod source_card; mod stack_slider; diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 36c484ad..11ed89fd 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -8,7 +8,7 @@ use crate::theme::semibold; const FIELD_GAP: f32 = 4.0; /// Room kept at the row's end for the link button, on every row of a group that has one -const LINK_SLOT: f32 = 26.0; +pub(super) const LINK_SLOT: f32 = 26.0; /// Size of the link button pub(super) const LINK_SIZE: f32 = 18.0; diff --git a/crates/ui-egui/src/property_sheet/pen_slider.rs b/crates/ui-egui/src/property_sheet/pen_slider.rs new file mode 100644 index 00000000..23ce262b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/pen_slider.rs @@ -0,0 +1,57 @@ +//! A slider that keeps the link slot at its end, for a pen-pressure button: the Size band's rows + +use std::ops::RangeInclusive; + +use egui::{Align2, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, vec2}; +use egui_phosphor::regular as ic; + +use super::number_field::{LINK_SIZE, LINK_SLOT}; +use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, ROW_HEIGHT, RowLead}; +use crate::i18n::{tr, trf}; + +/// Width of the pen button's outline, in points +const PEN_BUTTON_OUTLINE_WIDTH: f32 = 1.0; + +impl PropertySheet<'_> { + /// [`Self::slider`] ending one link slot early so a band's rows line up, with the `pen` button in that slot; returns the edit and whether the pen was clicked (it flips `pen`) + pub(crate) fn pen_slider( + &mut self, + label: &str, + value: &mut f32, + range: RangeInclusive, + decimals: usize, + pen: Option<&mut bool>, + ) -> (Option, bool) { + let right = self.right; + self.right -= LINK_SLOT; + let edit = self.slider_led(RowLead::label(label), value, range, decimals, ""); + self.right = right; + let center = Pos2::new(right - LINK_SIZE / 2.0, self.cursor_y() - ROW_HEIGHT / 2.0); + let clicked = pen.is_some_and(|pressed| self.pen_button(center, label, pressed)); + (edit, clicked) + } + + /// The pen button: lit while pen pressure drives row `label`'s value + fn pen_button(&mut self, center: Pos2, label: &str, pressed: &mut bool) -> bool { + let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); + let id = self.named_id("pen_pressure", label); + let response = self.ui.interact(rect, id, Sense::click()); + + let name = trf("{name} pen pressure", &[("name", &label)]); + let enabled = self.ui.is_enabled(); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, enabled, *pressed, &name)); + let response = self.tip(response, tr("Pen pressure")); + if response.clicked() { + *pressed = !*pressed; + } + + let tokens = self.tokens; + let (fill, border) = if *pressed { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + let painter = self.ui.painter(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(PEN_BUTTON_OUTLINE_WIDTH, border), StrokeKind::Inside); + painter.text(rect.center(), Align2::CENTER_CENTER, ic::PEN, FontId::proportional(ICON_SIZE), tokens.text); + self.paint_control_focus(&response); + + response.clicked() + } +} diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 90d2111b..623b6126 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -1,6 +1,7 @@ use egui::{Align2, CornerRadius, FontId, Painter, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; use egui_phosphor::regular as ic; +use super::slot_ends::SlotEnds; use super::switch_control::PILL_SIZE; use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, SlotResponse, TEXT_SIZE}; use crate::theme::semibold; @@ -14,6 +15,9 @@ const SLOT_HEIGHT: f32 = 36.0; /// Size of a slot's thumbnail pub(super) const THUMB_SIZE: f32 = 26.0; +/// Width of the thumbnail's frame, lit while the row is hovered, in points +const THUMB_OUTLINE_WIDTH: f32 = 1.0; + /// Air between the thumbnail and the slot's name const THUMB_TO_NAME: f32 = 10.0; @@ -73,31 +77,32 @@ impl PropertySheet<'_> { self.open_card(); self.scope = self.named_id("slot", name); self.space(SLOT_CARD_TOP); - self.slot_row(thumbnail, name, source, on, clear, reset.then_some(true)) + self.slot_row(thumbnail, name, source, SlotEnds { on, clear, reset: reset.then_some(true), pickable: true }) } /// [`Self::slot`] whose ⟲ always shows beside the ×, faint and inert while what it restores is at its defaults (`changed` false) pub(crate) fn slot_restorable(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, changed: bool) -> SlotResponse { self.open_card(); self.space(SLOT_CARD_TOP); - self.slot_row(thumbnail, name, source, None, true, Some(changed)) + self.slot_row(thumbnail, name, source, SlotEnds { on: None, clear: true, reset: Some(changed), pickable: true }) + } + + /// A slot card whose one source can't be swapped (a brush's uniform channel): the row picks nothing, its ⟲ is faint and inert while at the defaults (`changed` false) + pub(crate) fn slot_fixed(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, changed: bool) -> SlotResponse { + self.open_card(); + self.scope = self.named_id("slot", name); + self.space(SLOT_CARD_TOP); + self.slot_row(thumbnail, name, source, SlotEnds { on: None, clear: false, reset: Some(changed), pickable: false }) } /// [`Self::slot`]'s row inside the card open now (an input a mode adds, under that mode), not a card of its own pub(crate) fn slot_in_card(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, clear: bool) -> SlotResponse { - self.slot_row(thumbnail, name, source, None, clear, None) + self.slot_row(thumbnail, name, source, SlotEnds { on: None, clear, reset: None, pickable: true }) } - /// A slot row: thumbnail, name over source, then ⟲ (`Some(changed)`), × and the toggle on the right; the row opens the source list - fn slot_row( - &mut self, - thumbnail: &dyn Fn(&Painter, Rect), - name: &str, - source: &str, - on: Option<&mut bool>, - clear: bool, - reset: Option, - ) -> SlotResponse { + /// A slot row: thumbnail, name over source, then ⟲ (`Some(changed)`), × and the toggle on the right; the row opens the source list when `pickable` + fn slot_row(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, ends: SlotEnds<'_>) -> SlotResponse { + let SlotEnds { on, clear, reset, pickable } = ends; let rect = self.take(SLOT_HEIGHT); let center_y = rect.top() + SLOT_HEIGHT / 2.0; let enabled = on.as_deref().copied().unwrap_or(true); @@ -109,8 +114,16 @@ impl PropertySheet<'_> { // The picker spans the card while the trailing glyphs keep their own hit areas let row = self.bled_row(rect); let pick_id = self.next_id(); - let pick = self.ui.interact(row, pick_id, Sense::click()); - pick.widget_info(|| egui::WidgetInfo { current_text_value: Some(source.to_owned()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name) }); + let pick = self.ui.interact(row, pick_id, if pickable { Sense::click() } else { Sense::hover() }); + if pickable { + pick.widget_info(|| egui::WidgetInfo { + current_text_value: Some(source.to_owned()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name) + }); + } else { + // A label's words are its value, so the name and source read as one + pick.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{name}: {source}"))); + } let mut result = SlotResponse { pick, clear: false, reset: false, toggled: false }; let tokens = self.tokens; @@ -119,15 +132,16 @@ impl PropertySheet<'_> { painter.rect_stroke( thumb, CornerRadius::ZERO, - Stroke::new(1.0, if result.pick.hovered() { tokens.accent } else { tokens.field_border }), + Stroke::new(THUMB_OUTLINE_WIDTH, if pickable && result.pick.hovered() { tokens.accent } else { tokens.field_border }), StrokeKind::Inside, ); let text_x = thumb.right() + THUMB_TO_NAME; + let (name_font, name_color) = if enabled { (semibold(TEXT_SIZE), tokens.text) } else { (FontId::proportional(TEXT_SIZE), tokens.text_dim) }; painter.text(pos2(text_x, center_y - NAME_ABOVE_CENTER), Align2::LEFT_CENTER, name, name_font, name_color); painter.text(pos2(text_x, center_y + SOURCE_BELOW_CENTER), Align2::LEFT_CENTER, source, FontId::proportional(SOURCE_TEXT_SIZE), tokens.text_dim); - for (shown, live, x, glyph, tip, slot) in [ + for (shown, live, x, glyph, tip, clicked) in [ (clear, true, clear_x, ic::X, crate::i18n::n_("Clear"), &mut result.clear), (reset.is_some(), reset.unwrap_or(false), reset_x, ic::CLOCK_COUNTER_CLOCKWISE, crate::i18n::n_("Restore defaults"), &mut result.reset), ] { @@ -138,14 +152,15 @@ impl PropertySheet<'_> { let glyph_rect = Rect::from_center_size(pos2(x, center_y), Vec2::splat(SLOT_GLYPH_BOX)); let id = self.next_id(); - // At the defaults the ⟲ is faint and inert, as on a band: a click there picks the source like the rest of the row + // At the defaults the ⟲ is faint and inert, as on a band: on a pickable row a click there picks the source like the rest of the row let response = if live { self.tip(self.ui.interact(glyph_rect, id, Sense::click()), crate::i18n::tr(tip)) } else { self.ui.interact(glyph_rect, id, Sense::hover()) }; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, live, crate::i18n::tr(tip))); - *slot = live && response.clicked(); + *clicked = live && response.clicked(); + let color = self.reset_glyph_color(live, response.hovered(), tokens.text); painter.text(glyph_rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(SLOT_ICON_SIZE), color); } @@ -161,6 +176,7 @@ impl PropertySheet<'_> { response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, *on, name)); self.pill(pill.center(), *on, true); } + self.drawn(thumb.bottom()); result } diff --git a/crates/ui-egui/src/property_sheet/slot_ends.rs b/crates/ui-egui/src/property_sheet/slot_ends.rs new file mode 100644 index 00000000..cfc42cda --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slot_ends.rs @@ -0,0 +1,16 @@ +//! What a slot row offers besides its picture and words + +/// A slot row's toggle, ×, ⟲ and whether the row opens the source list +pub(super) struct SlotEnds<'a> { + /// The on/off pill at the right end, when the slot has one + pub(super) on: Option<&'a mut bool>, + + /// The × back to a uniform source shows + pub(super) clear: bool, + + /// The ⟲ shows: `Some(changed)`, faint and inert while unchanged + pub(super) reset: Option, + + /// A click on the row opens the source list + pub(super) pickable: bool, +} diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs index 8c970158..85e34e5e 100644 --- a/crates/ui-egui/src/resource_picker.rs +++ b/crates/ui-egui/src/resource_picker.rs @@ -395,7 +395,7 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz TilePicture::Image(name, image) => Some(thumbs.image(ui.ctx(), name, image)), TilePicture::Procedural(kind) => thumbs.procedural(ui.ctx(), *kind), TilePicture::Generator(kind) => thumbs.generator(ui.ctx(), *kind), - TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None, + TilePicture::Shape(..) | TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None, }; match (&item.picture, texture) { @@ -419,6 +419,10 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz tokens.text_dim.gamma_multiply(LOADING_GLYPH_OPACITY), ); } + (TilePicture::Shape(alpha, hardness), None) => { + painter.rect_filled(picture, rounding, Color32::BLACK); + crate::thumbs::paint_alpha(painter, picture, *alpha, *hardness); + } (TilePicture::Swatch(color), None) => { painter.rect_filled(picture, rounding, *color); } diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 830a10ff..a79c1c44 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -270,24 +270,36 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let folder = app.ui.shelf_path.clone(); let picked_tab = app.ui.shelf_tab; - let mut matching: Vec = all_entries.into_iter().filter(|entry| entry.matches(&filter)).collect(); - if app.ui.shelf_favorites_only { - matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some()); - } + let mut matching: Vec<_> = { + // A duplicated preference keeps the first rank it had on disk + let mut ranks = std::collections::HashMap::with_capacity(app.ui.shelf_favorites.len()); + for (rank, favorite) in app.ui.shelf_favorites.iter().enumerate() { + ranks.entry((favorite.kind.as_str(), favorite.id.as_str())).or_insert(rank); + } + + all_entries + .into_iter() + .filter(|entry| entry.matches(&filter)) + .filter_map(|entry| { + let rank = if ranks.is_empty() { None } else { ranks.get(&entry.identity()).copied() }; + (!app.ui.shelf_favorites_only || rank.is_some()).then_some((entry, rank)) + }) + .collect() + }; let path_pane_open = app.ui.shelf_panes.filter_by_path; let mut applicable = if path_pane_open { - crate::shelf_folders::paths(matching.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))) + crate::shelf_folders::paths(matching.iter().map(|(entry, _)| entry).filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))) } else { Vec::new() }; // All libraries includes every result without constructing an asset path if !folder.is_empty() { - matching.retain(|entry| entry.in_folder(&folder)); + matching.retain(|(entry, _)| entry.in_folder(&folder)); } - let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|(entry, _)| entry.tab() == *tab).count()).collect(); // Saved smart materials and masks count toward their tabs even without tiles; they can't be favorites yet let favorites_only = app.ui.shelf_favorites_only; @@ -314,10 +326,10 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { && crate::shelf_tabs::shows(tab, Tab::Brushes) && folder.len() <= 2 && folder.iter().zip([crate::shelf_entry::USER, "Brushes"]).all(|(selected, part)| selected == part); - let mut entries: Vec = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect(); + let mut entries: Vec<_> = matching.into_iter().filter(|(entry, _)| crate::shelf_tabs::shows(tab, entry.tab())).collect(); + // Favorites first, the most recently added first, then by name - let favorites = &app.ui.shelf_favorites; - entries.sort_by_cached_key(|entry| (crate::shelf_favorite::rank(favorites, entry).unwrap_or(usize::MAX), entry.label().to_lowercase())); + entries.sort_by_cached_key(|(entry, rank)| (rank.unwrap_or(usize::MAX), entry.label().to_lowercase())); // The toolbar has its own strip at the panel's bottom, so nothing above it can push it out let area = ui.available_rect_before_wrap(); @@ -342,7 +354,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } /// The tiles of `entries` in a scroll area `height` high, then user brushes, saved smart materials and saved smart masks when selected -fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: f32, saved: [bool; 2], show_user_brushes: bool, filter: &str) { +fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[(ShelfEntry, Option)], height: f32, saved: [bool; 2], show_user_brushes: bool, filter: &str) { let ctx = ui.ctx().clone(); let view = app.ui.shelf_view; let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE))); @@ -354,9 +366,9 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: .show(ui, |ui| { ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { tiles(ui, |ui| { - for entry in entries { + for (entry, rank) in entries { let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str())); - entry_tile(app, ui, &ctx, entry, view, is_selected); + entry_tile(app, ui, &ctx, entry, view, is_selected, rank.is_some()); } }); if show_user_brushes { @@ -515,7 +527,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) { fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str, _: bool) {} /// The tile of `entry`, outlined when `selected`: a click applies it, a right-click opens its menu -fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) { +fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool, favorite: bool) { // An image removed this frame has nothing to show if let ShelfEntry::Image(name) = entry && !app.session.images.contains_key(name) @@ -523,15 +535,13 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry return; } - // A picture the user picked replaces the thumbnail, unless its file is gone; it is read only once its tile shows - let thumbnail = entry.thumbnail(app, ctx); let custom_file = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry); let asset = entry.asset(); let session = &app.session; let response = tile_in_view( ui, &mut app.thumbs, - |ui, thumbs| custom_file.and_then(|file| thumbs.custom_preview(ui.ctx(), file)).or(thumbnail), + |ui, thumbs| custom_file.and_then(|file| thumbs.custom_preview(ui.ctx(), file)).or_else(|| entry.thumbnail(thumbs, session, ui.ctx())), |thumbs| match entry { ShelfEntry::SavedBrush { path: Some(path), .. } => Some(thumbs.saved_brush_preview(path, &session.images)), _ => entry.preview(session), @@ -550,7 +560,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry if entry.includes_randomness() { randomness_badge(ui.painter(), view.thumbnail_rect(response.rect)); } - if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { + if favorite { crate::shelf_favorite::star(ui.painter(), view.thumbnail_rect(response.rect), Tokens::get(ctx).warning); ctx.accesskit_node_builder(response.id, |node| node.set_description(tr("Favorite"))); } diff --git a/crates/ui-egui/src/shelf_custom_preview.rs b/crates/ui-egui/src/shelf_custom_preview.rs index 6fbe2ca1..c25ec3d1 100644 --- a/crates/ui-egui/src/shelf_custom_preview.rs +++ b/crates/ui-egui/src/shelf_custom_preview.rs @@ -43,10 +43,20 @@ pub(crate) fn remove(previews: &mut Vec, entry: &ShelfEntry) /// The largest centred square of `image`, scaled to [`CUSTOM_PREVIEW_PX`] (smaller images keep their size) pub(crate) fn square(image: &image::DynamicImage) -> image::RgbaImage { + use image::{DynamicImage, GenericImageView, imageops}; + let side = image.width().min(image.height()); - let cropped = image.crop_imm((image.width() - side) / 2, (image.height() - side) / 2, side, side); + let left = (image.width() - side) / 2; + let top = (image.height() - side) / 2; let size = side.min(CUSTOM_PREVIEW_PX); - cropped.resize_exact(size, size, image::imageops::FilterType::Triangle).to_rgba8() + let filter = imageops::FilterType::Triangle; + + // Sample common thumbnail formats directly from the decoded pixels + match image { + DynamicImage::ImageRgba8(pixels) => imageops::resize(&*pixels.view(left, top, side, side), size, size, filter), + DynamicImage::ImageRgb8(pixels) => DynamicImage::ImageRgb8(imageops::resize(&*pixels.view(left, top, side, side), size, size, filter)).into_rgba8(), + other => other.crop_imm(left, top, side, side).resize_exact(size, size, filter).into_rgba8(), + } } #[cfg(test)] diff --git a/crates/ui-egui/src/shelf_drag_ghost.rs b/crates/ui-egui/src/shelf_drag_ghost.rs index 2c11a2a1..7ffd7e43 100644 --- a/crates/ui-egui/src/shelf_drag_ghost.rs +++ b/crates/ui-egui/src/shelf_drag_ghost.rs @@ -87,9 +87,11 @@ fn dragged(ctx: &Context) -> Option<(Option, String)> { if let Some(drag) = egui::DragAndDrop::payload::(ctx) { return Some((drag.thumb.as_ref().map(egui::TextureHandle::id), drag.label.clone())); } + if !egui::DragAndDrop::has_payload_of_type::(ctx) { return None; } + ctx.data(|data| data.get_temp::(Id::unique(LAYER))).map(|label| (None, label)) } diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index 32669e7f..9c3f6f6c 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -16,6 +16,7 @@ use crate::TextureCraftApp; use crate::i18n::{n_, tr}; use crate::shelf::{Asset, Tab, apply}; use crate::shelf_preview::ShelfPreview; +use crate::thumbs::Thumbs; /// Probes per side of the grid that compares a procedural under two seeds, off the pattern's grid lines const SEED_PROBES: usize = 4; @@ -171,23 +172,23 @@ impl ShelfEntry { } /// The thumbnail, or None while it renders - pub(crate) fn thumbnail(&self, app: &mut TextureCraftApp, ctx: &egui::Context) -> Option { + pub(crate) fn thumbnail(&self, thumbs: &mut Thumbs, session: &Session, ctx: &egui::Context) -> Option { match self { - ShelfEntry::Material(material) => app.thumbs.material(ctx, material.id), - ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), - ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), - ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), - ShelfEntry::SavedBrush { path: Some(path), .. } => app.thumbs.saved_brush(ctx, path, &app.session.images), + ShelfEntry::Material(material) => thumbs.material(ctx, material.id), + ShelfEntry::SmartMask(mask) => thumbs.smart_mask(ctx, mask.id), + ShelfEntry::Filter(filter) => thumbs.filter(ctx, filter.id), + ShelfEntry::Brush(preset) => thumbs.brush_preset(ctx, preset), + ShelfEntry::SavedBrush { path: Some(path), .. } => thumbs.saved_brush(ctx, path, &session.images), ShelfEntry::SavedBrush { path: None, name, index } => { - let brush = &app.session.brush_presets.list.get(*index)?.brush; - app.thumbs.session_brush(ctx, name, brush, &app.session.images) + let brush = &session.brush_presets.list.get(*index)?.brush; + thumbs.session_brush(ctx, name, brush, &session.images) } - ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), - ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), - ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), + ShelfEntry::Alpha(alpha) => thumbs.alpha(ctx, alpha), + ShelfEntry::Procedural(kind) => thumbs.procedural(ctx, *kind), + ShelfEntry::Environment(name) => thumbs.environment(ctx, name), ShelfEntry::Image(name) => { - let image = app.session.images.get(name).cloned()?; - Some(app.thumbs.image(ctx, name, &image)) + let image = session.images.get(name)?; + Some(thumbs.image(ctx, name, image)) } } } diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index e098ef5f..07d8847b 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -222,6 +222,7 @@ fn custom_preview_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry && row(ui, width, tr("Remove custom preview"), true, tokens).clicked() { crate::shelf_custom_preview::remove(&mut app.ui.shelf_custom_previews, entry); + app.thumbs.retain_custom_previews(&app.ui.shelf_custom_previews); ui.close(); } } @@ -243,6 +244,7 @@ fn pick_custom_preview(app: &mut TextureCraftApp, entry: &ShelfEntry) { app.thumbs.forget_custom_preview(&file); crate::shelf_custom_preview::set(&mut app.ui.shelf_custom_previews, kind, id, file); + app.thumbs.retain_custom_previews(&app.ui.shelf_custom_previews); }); } diff --git a/crates/ui-egui/src/shelf_updates.rs b/crates/ui-egui/src/shelf_updates.rs index 5a53fd27..a010bcd2 100644 --- a/crates/ui-egui/src/shelf_updates.rs +++ b/crates/ui-egui/src/shelf_updates.rs @@ -58,6 +58,15 @@ fn last_run_id() -> Id { /// Runs the automatic updates once their minutes have passed since the last run, and wakes the app for the next one pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &Context) { + let failures_id = Id::unique("shelf_updates_reported_failures"); + ctx.data_mut(|data| { + let owner = data.get_temp_mut_or(failures_id, app.session.project_id); + if *owner != app.session.project_id { + *owner = app.session.project_id; + data.remove::>(failures_id); + } + }); + let updates = app.ui.shelf_updates; if !updates.assets && !updates.resources { ctx.data_mut(|data| data.remove::(last_run_id())); @@ -83,7 +92,7 @@ pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &Context) { refresh_assets(app); } if updates.resources { - update_resources(app, ctx); + update_resources(app, ctx, failures_id); } ctx.request_repaint_after(std::time::Duration::from_secs_f64(every)); } @@ -101,19 +110,17 @@ pub(crate) fn refresh_assets(app: &mut TextureCraftApp) { } /// Reads the project's changed image files again; a file that is gone or can't be read says why once, until it reads again -fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { +fn update_resources(app: &mut TextureCraftApp, ctx: &Context, failures_id: Id) { let Some(status) = app.run("resource.status", json!({})) else { return }; - let rows = status["resources"].as_array().cloned().unwrap_or_default(); - let mut failures: Vec<(String, String)> = - rows.iter().filter(|row| row["status"] == "missing").map(|row| (text(&row["name"]), text(&row["error"]))).collect(); + let rows = status["resources"].as_array().into_iter().flatten(); + let mut failures: Vec<(String, String)> = rows.filter(|row| row["status"] == "missing").map(|row| (text(&row["name"]), text(&row["error"]))).collect(); if status["outdated"].as_u64().is_some_and(|outdated| outdated > 0) && let Some(result) = app.run("resource.update", json!({})) { failures.extend(result["failed"].as_array().into_iter().flatten().map(|failure| (text(&failure["name"]), text(&failure["error"])))); } - let reported_id = reported_failures_id(app.session.project_id); - let mut reported: Vec = ctx.data(|data| data.get_temp(reported_id)).unwrap_or_default(); + let mut reported: Vec = ctx.data_mut(|data| data.remove_temp(failures_id)).unwrap_or_default(); reported.retain(|name| failures.iter().any(|(failed, _)| failed == name)); for (name, error) in failures { if !reported.contains(&name) { @@ -121,7 +128,9 @@ fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { reported.push(name); } } - ctx.data_mut(|data| data.insert_temp(reported_id, reported)); + if !reported.is_empty() { + ctx.data_mut(|data| data.insert_temp(failures_id, reported)); + } } /// Reads the files of `names` (every changed image when None) again through the Resources Updater, which says what happened @@ -141,11 +150,6 @@ fn text(value: &serde_json::Value) -> String { value.as_str().unwrap_or_default().to_owned() } -/// The files of project `project_id` whose failure to read was already shown (ctx temp data) -fn reported_failures_id(project_id: u64) -> Id { - Id::unique(("shelf_updates_reported_failures", project_id)) -} - /// The refresh button with its popup of update settings, opening upward from the toolbar `panel` with its left edge on the panel's pub(crate) fn button(app: &mut TextureCraftApp, ui: &mut Ui, size: f32, panel: egui::Rect) { let label = tr("Refresh"); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 1ea83ab4..6f222279 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -85,14 +85,6 @@ pub enum ViewLayout { Only2D, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum PropsTab { - #[default] - Brush, - Alpha, - Material, -} - #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct Windows { pub export: bool, @@ -666,7 +658,6 @@ pub struct UiState { /// The share of the Assets panel's width the filter panes take #[serde(default = "default_shelf_panes_share", deserialize_with = "deserialize_shelf_panes_share")] pub shelf_panes_share: f32, - pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, /// Layer being renamed and the edit buffer. @@ -883,7 +874,6 @@ impl Default for UiState { shelf_updates: crate::shelf_updates::ShelfUpdates::default(), shelf_panes_split: default_shelf_panes_split(), shelf_panes_share: default_shelf_panes_share(), - props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, new_project: NewProject::default(), diff --git a/crates/ui-egui/src/stencil_choice.rs b/crates/ui-egui/src/stencil_choice.rs new file mode 100644 index 00000000..1414f08e --- /dev/null +++ b/crates/ui-egui/src/stencil_choice.rs @@ -0,0 +1,8 @@ +//! What the Stencil slot's picker offers + +/// One tile of the Stencil slot's picker: an image resource, or importing one +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum StencilChoice { + Image(String), + Import, +} diff --git a/crates/ui-egui/src/stencil_sheet.rs b/crates/ui-egui/src/stencil_sheet.rs new file mode 100644 index 00000000..2946de01 --- /dev/null +++ b/crates/ui-egui/src/stencil_sheet.rs @@ -0,0 +1,260 @@ +//! The Stencil section of a brush tool's Properties: the stencil's slot with its picker, its Tiling mode, and its placement beside a picture of where it sits in the view + +use std::ops::RangeInclusive; + +use egui::{Color32, CornerRadius, Painter, Pos2, Rect, Stroke, StrokeKind, TextureId, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::session::StencilState; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::stencil_choice::StencilChoice; +use crate::theme::Tokens; + +/// Scale = the image's height as a fraction of the view's +const SCALE_RANGE: RangeInclusive = 0.05..=4.0; + +/// How far the Position sliders move the stencil's center from the middle of the view (NDC; -1..1 is the view) +const POSITION_RANGE: RangeInclusive = -2.0..=2.0; + +/// The Rotation dial's range in degrees +const ROTATION_RANGE: RangeInclusive = 0.0..=360.0; + +/// The view's outline in the placement picture +const VIEW_OUTLINE_WIDTH: f32 = 1.0; + +/// Air between the placement picture's edge and the view drawn in it +const VIEW_INSET: f32 = 6.0; + +/// A Tiling mode picture's cell: its share of the picture and the air between two cells +const TILE_CELL_FRACTION: f32 = 0.42; +const TILE_CELL_GAP: f32 = 2.0; + +/// The Stencil section under its caption, whose reset puts the stencil back in the middle of the view +pub(crate) fn stencil_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let moved = app.session.tool.stencil.as_ref().is_some_and(|stencil| placement(stencil) != placement(&StencilState::new(&stencil.image))); + if sheet.section_reset(tr("Stencil"), moved) + && let Some(stencil) = &app.session.tool.stencil + { + let start = StencilState::new(&stencil.image); + app.run("tool.stencil", json!({"center": start.center, "scale": start.scale, "rotation": start.rotation})); + } + + stencil_slot(app, sheet); + let Some(stencil) = app.session.tool.stencil.clone() else { return }; + + let tile_name = |tile: bool| if tile { tr("H and V Tiling") } else { tr("No Tiling") }.to_owned(); + let text = Tokens::get(sheet.ui.ctx()).text; + let tile_picture = |painter: &Painter, rect: Rect, tile: bool| paint_tiling(painter, rect, tile, text); + let (picked, _) = sheet.dropdown(tr("Tiling mode"), stencil.tile, &[false, true], tile_name, Some(&tile_picture)); + if let Some(tile) = picked { + app.run("tool.stencil", json!({ "tile": tile })); + } + + placement_rows(app, sheet, &stencil); + + let mut opacity = stencil.opacity; + if sheet.slider(tr("Overlay opacity"), &mut opacity, 0.0..=1.0, 2).is_some() { + app.run("tool.stencil", json!({ "opacity": opacity })); + } +} + +/// What the section's reset puts back: where the stencil sits, its size and its turn +fn placement(stencil: &StencilState) -> ([f32; 2], f32, f32) { + (stencil.center, stencil.scale, stencil.rotation) +} + +/// The slot showing the stencil's image; a click opens the picker of images, × takes the stencil away +fn stencil_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let ctx = sheet.ui.ctx().clone(); + let current = app.session.tool.stencil.as_ref().map(|stencil| StencilChoice::Image(stencil.image.clone())); + let texture = match ¤t { + Some(StencilChoice::Image(name)) => app.session.images.get(name).map(|image| app.thumbs.image(&ctx, name, image)), + _ => None, + }; + let (name, source) = match ¤t { + Some(StencilChoice::Image(name)) => (name.clone(), tr("Imported image")), + _ => (tr("None").to_owned(), tr("Pick an image to paint through")), + }; + let tokens = Tokens::get(&ctx); + let thumbnail = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + if let Some(texture) = &texture { + painter.image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + }; + let slot = sheet.slot(&thumbnail, &name, source, None, current.is_some(), false); + let slot_pick = + slot.pick.clone().on_hover_text(tr("S + left-drag rotates (with Shift in 15° steps), S + right-drag scales, S + middle-drag moves the stencil")); + + let popup = sheet.ui.make_persistent_id("brush_stencil_source"); + if slot_pick.clicked() { + resource_picker::toggle(&ctx, popup); + } + let tabs = || { + let textures = ResourcePickerItem::textures(&app.session, StencilChoice::Import, |name| StencilChoice::Image(name.to_owned())); + vec![PickerTab { icon: ic::FRAME_CORNERS, name: tr("Stencils"), groups: vec![PickerGroup { header: None, items: textures }] }] + }; + match resource_picker::show(&slot_pick, popup, &mut app.thumbs, current.as_ref(), true, tabs) { + Some(StencilChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(choice) if Some(&choice) != current.as_ref() => { + if let StencilChoice::Image(name) = choice { + app.run("tool.stencil", json!({ "image": name })); + } + } + _ => {} + } + if slot.clear { + app.run("tool.stencil", json!({"clear": true})); + } + + // An image from the Assets panel dropped on the slot becomes the stencil + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot_pick) { + app.run("tool.stencil", json!({ "image": name })); + } + sheet.close_card(); +} + +/// Scale, Rotation and Position X / Y beside a picture of the view with the stencil placed in it +fn placement_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, stencil: &StencilState) { + let ctx = sheet.ui.ctx().clone(); + let tokens = Tokens::get(&ctx); + let image = app.session.images.get(&stencil.image).cloned(); + let texture = image.as_ref().map(|image| app.thumbs.stencil(&ctx, &stencil.image, image)); + let view_aspect = app.session.viewport.x.max(1.0) / app.session.viewport.y.max(1.0); + let image_aspect = image.as_ref().map_or(1.0, |image| image.width as f32 / image.height.max(1) as f32); + let picture = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + let view = fit(rect.shrink(VIEW_INSET), view_aspect); + painter.rect_filled(view, CornerRadius::ZERO, tokens.panel); + if let Some(texture) = &texture { + paint_stencil(&painter.with_clip_rect(view), view, texture.id(), stencil, image_aspect, Color32::WHITE, stencil.tile); + } + painter.rect_stroke(view, CornerRadius::ZERO, Stroke::new(VIEW_OUTLINE_WIDTH, tokens.text_dim), StrokeKind::Inside); + }; + + let (mut scale, mut rotation, [mut x, mut y]) = (stencil.scale, stencil.rotation, stencil.center); + let edits = sheet.picture_sliders( + &picture, + &mut [ + StackSlider { label: tr("Scale"), value: &mut scale, range: SCALE_RANGE, typed: SCALE_RANGE, decimals: 2, suffix: "", dial: false }, + StackSlider { label: tr("Rotation"), value: &mut rotation, range: ROTATION_RANGE, typed: ROTATION_RANGE, decimals: 0, suffix: "°", dial: true }, + StackSlider { label: tr("Position X"), value: &mut x, range: POSITION_RANGE, typed: POSITION_RANGE, decimals: 2, suffix: "", dial: false }, + StackSlider { label: tr("Position Y"), value: &mut y, range: POSITION_RANGE, typed: POSITION_RANGE, decimals: 2, suffix: "", dial: false }, + ], + ); + let [scale_edit, rotation_edit, x_edit, y_edit] = edits.map(|edit| edit.is_some()); + let mut params = serde_json::Map::new(); + if scale_edit { + params.insert("scale".into(), json!(scale)); + } + if rotation_edit { + params.insert("rotation".into(), json!(rotation)); + } + if x_edit || y_edit { + params.insert("center".into(), json!([x, y])); + } + if !params.is_empty() { + app.run("tool.stencil", Value::Object(params)); + } +} + +/// The largest rect of `aspect` (width / height) centred in `outer` +fn fit(outer: Rect, aspect: f32) -> Rect { + let width = outer.width().min(outer.height() * aspect); + Rect::from_center_size(outer.center(), vec2(width, width / aspect.max(f32::EPSILON))) +} + +/// Paints the stencil's image where it sits in the view `rect`, `tint`ed: one copy, or every copy that reaches the view when `tiled`; returns the middle copy's corners (top left, top right, bottom right, bottom left) +pub(crate) fn paint_stencil( + painter: &Painter, + rect: Rect, + texture: TextureId, + stencil: &StencilState, + image_aspect: f32, + tint: Color32, + tiled: bool, +) -> [Pos2; 4] { + let aspect = rect.width() / rect.height().max(1.0); + let (center, half_size, rotation) = stencil.placement(image_aspect, aspect); + let to_screen = |x: f32, y: f32| pos2(rect.left() + (x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - y * 0.5) * rect.height()); + let (sine, cosine) = rotation.sin_cos(); + + let square = [(-1.0, 1.0), (1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)]; + let corners = square.map(|(x, y)| { + let (x, y) = (x * half_size[0], y * half_size[1]); + to_screen(center[0] + x * cosine - y * sine, center[1] + x * sine + y * cosine) + }); + + let mut mesh = egui::Mesh::with_texture(texture); + for ((x, y), corner) in square.into_iter().zip(corners) { + let (position, local_x, local_y) = if tiled { + // Map view corners back into stencil space so the sampler repeats at any scale + let (dx, dy) = (x - center[0], y - center[1]); + (to_screen(x, y), (dx * cosine + dy * sine) / half_size[0].max(f32::EPSILON), (dy * cosine - dx * sine) / half_size[1].max(f32::EPSILON)) + } else { + (corner, x, y) + }; + let uv = pos2(0.5 + local_x * 0.5, 0.5 - local_y * 0.5); + mesh.vertices.push(egui::epaint::Vertex { pos: position, uv, color: tint }); + } + + mesh.indices.extend([0, 1, 2, 0, 2, 3]); + painter.add(egui::Shape::mesh(mesh)); + corners +} + +/// A Tiling mode's picture: one square for No Tiling, four for H and V Tiling +fn paint_tiling(painter: &Painter, rect: Rect, tile: bool, color: Color32) { + let cell = rect.width() * TILE_CELL_FRACTION; + if !tile { + painter.rect_filled(Rect::from_center_size(rect.center(), vec2(cell, cell)), CornerRadius::ZERO, color); + return; + } + + let half_step = (cell + TILE_CELL_GAP) / 2.0; + for (direction_x, direction_y) in [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)] { + let center = rect.center() + vec2(direction_x * half_step, direction_y * half_step); + painter.rect_filled(Rect::from_center_size(center, vec2(cell, cell)), CornerRadius::ZERO, color); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_tiny_offset_tiled_stencil_repeats_across_the_placement_picture() { + let ctx = egui::Context::default(); + let view = Rect::from_min_size(pos2(0.0, 0.0), vec2(200.0, 200.0)); + let image = std::sync::Arc::new(texturecraft_engine::compose::ImageRes::new(2, 8, vec![[1.0; 4]; 16], false)); + let stencil = StencilState { center: [2.0, 2.0], scale: 0.05, rotation: 90.0, tile: true, ..StencilState::new("offset") }; + let texture = crate::thumbs::Thumbs::default().stencil(&ctx, "offset", &image); + + let mut frame = ctx.run_ui(egui::RawInput::default(), |ui| { + paint_stencil(ui.painter(), view, texture.id(), &stencil, 0.25, Color32::WHITE, true); + }); + let options = frame.textures_delta.set[&texture.id()][0].options; + frame.textures_delta.clear(); + let mesh = frame + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Mesh(mesh) if mesh.texture_id == texture.id() => Some(mesh), + _ => None, + }) + .expect("the stencil picture"); + println!("Tile geometry: {} vertices, {} indices", mesh.vertices.len(), mesh.indices.len()); + + assert!(mesh.calc_bounds().contains_rect(view), "the rotated tiles reach the entire view"); + if mesh.vertices.iter().any(|vertex| !(0.0..=1.0).contains(&vertex.uv.x) || !(0.0..=1.0).contains(&vertex.uv.y)) { + assert_eq!(options.wrap_mode, egui::TextureWrapMode::Repeat, "the image repeats outside its first tile"); + } + } +} diff --git a/crates/ui-egui/src/tabbed_page.rs b/crates/ui-egui/src/tabbed_page.rs new file mode 100644 index 00000000..815af5eb --- /dev/null +++ b/crates/ui-egui/src/tabbed_page.rs @@ -0,0 +1,8 @@ +//! Which page under jump tabs the Properties panel shows + +/// A fill's sections (`mask` for a mask fill effect) or the paint tool's +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum TabbedPage { + Fill { mask: bool }, + Tool, +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 66925033..b0814b39 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -36,6 +36,8 @@ const GENERATOR_SET_KEY_PREFIX: &str = "generator-set:"; const SAVED_FILE_KEY_PREFIX: &str = "saved-"; /// Largest stencil preview dimension in pixels const STENCIL_MAX_SIZE_PX: f32 = 1024.0; +/// The texture name prefix of a stencil preview +const STENCIL_KEY_PREFIX: &str = "stencil:"; /// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; @@ -53,6 +55,8 @@ pub struct Thumbs { saved_files_epoch: u64, images: HashMap, TextureHandle)>, images_revision: Option, + /// The large preview of the selected stencil, shared by Properties and the viewport + stencil: Option<(Weak, TextureHandle)>, preview_session: Option<(u64, u64)>, /// Weak identities for images read by configured generator previews generator_images: HashMap>, @@ -79,13 +83,15 @@ pub struct Thumbs { impl Thumbs { /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px) pub fn stencil(&mut self, ctx: &egui::Context, name: &str, image: &Arc) -> TextureHandle { - let key = format!("stencil:{name}"); - if let Some((cached_image, texture)) = self.images.get(&key) - && cached_image.ptr_eq(&Arc::downgrade(image)) + if let Some((cached_image, texture)) = &self.stencil + && std::ptr::eq(cached_image.as_ptr(), Arc::as_ptr(image)) { return texture.clone(); } + // Release the previous overlay before allocating its replacement + self.stencil = None; + let scale = (STENCIL_MAX_SIZE_PX / image.width.max(image.height).max(1) as f32).min(1.0); let (w, h) = (((image.width as f32 * scale) as usize).max(1), ((image.height as f32 * scale) as usize).max(1)); let mut color_image = ColorImage::filled([w, h], Color32::TRANSPARENT); @@ -100,8 +106,8 @@ impl Thumbs { } } - let texture = ctx.load_texture(key.clone(), color_image, TextureOptions::LINEAR); - self.images.insert(key, (Arc::downgrade(image), texture.clone())); + let texture = ctx.load_texture(format!("{STENCIL_KEY_PREFIX}{name}"), color_image, TextureOptions::LINEAR_REPEAT); + self.stencil = Some((Arc::downgrade(image), texture.clone())); texture } @@ -149,14 +155,19 @@ impl Thumbs { } self.images_revision = Some(revision); - self.images.retain(|key, (cached_image, _)| { - let name = key.strip_prefix("stencil:").unwrap_or(key); - images.get(name).is_some_and(|image| cached_image.ptr_eq(&Arc::downgrade(image))) - }); + self.images.retain(|name, (cached_image, _)| images.get(name).is_some_and(|image| std::ptr::eq(cached_image.as_ptr(), Arc::as_ptr(image)))); } /// Keep project previews only while they refer to current resources or bake maps. pub(crate) fn sync_project_previews(&mut self, session: &Session) -> bool { + // Clearing the stencil does not advance the session revision + if let Some((shown, _)) = &self.stencil { + let current = session.tool.stencil.as_ref().and_then(|stencil| session.images.get(&stencil.image)); + if !current.is_some_and(|image| std::ptr::eq(shown.as_ptr(), Arc::as_ptr(image))) { + self.stencil = None; + } + } + let current = (session.project_id, session.revision); let previous = self.preview_session.replace(current); if previous == Some(current) { @@ -319,6 +330,12 @@ impl Thumbs { self.custom_previews.clear(); } + /// Release custom textures after their last tile stops using the file + pub(crate) fn retain_custom_previews(&mut self, previews: &[crate::shelf_custom_preview::ShelfCustomPreview]) { + let in_use: std::collections::HashSet<_> = previews.iter().map(|preview| preview.file.as_path()).collect(); + self.custom_previews.retain(|file, _| in_use.contains(file.as_path())); + } + /// Load the picture at `file` again next time: the user picked it anew, maybe after changing it #[cfg(not(target_arch = "wasm32"))] pub(crate) fn forget_custom_preview(&mut self, file: &Path) { @@ -501,41 +518,60 @@ impl Thumbs { } } -/// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). -pub fn paint_sphere(p: &Painter, c: Pos2, r: f32, base: [f32; 3]) { - let mut mesh = egui::Mesh::default(); - let rings = 10; - let segs = 28; +/// Metallic and roughness of a sphere drawn without a material's own values +pub(crate) const SPHERE_DEFAULT_METALLIC: f32 = 0.0; +pub(crate) const SPHERE_DEFAULT_ROUGHNESS: f32 = 0.5; + +/// Rings and segments per ring of a drawn sphere's mesh +const SPHERE_RINGS: usize = 10; +const SPHERE_SEGMENTS: usize = 28; + +/// Exposure applied to a drawn sphere's shading before tone mapping +const SPHERE_EXPOSURE: f32 = 1.4; + +/// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews) +pub fn paint_sphere(painter: &Painter, center: Pos2, radius: f32, base: [f32; 3]) { + paint_material_sphere(painter, center, radius, base, SPHERE_DEFAULT_METALLIC, SPHERE_DEFAULT_ROUGHNESS); +} + +/// [`paint_sphere`] with the material's `metallic` and `roughness` (0..1) +pub fn paint_material_sphere(painter: &Painter, center: Pos2, radius: f32, base: [f32; 3], metallic: f32, roughness: f32) { let color = |dx: f32, dy: f32| { - let d2 = (dx * dx + dy * dy).min(1.0); - let n = [dx, dy, (1.0 - d2).sqrt()]; - let s = shade(n, base, 0.0, 0.5).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0) as u8); - Color32::from_rgb(s[0], s[1], s[2]) + let distance_squared = (dx * dx + dy * dy).min(1.0); + let normal = [dx, dy, (1.0 - distance_squared).sqrt()]; + let srgb = shade(normal, base, metallic, roughness).map(|linear| (linear_to_srgb(aces(linear * SPHERE_EXPOSURE)) * 255.0) as u8); + Color32::from_rgb(srgb[0], srgb[1], srgb[2]) }; - mesh.colored_vertex(c, color(0.0, 0.0)); - for i in 1..=rings { - let rr = i as f32 / rings as f32; - for j in 0..segs { - let a = j as f32 / segs as f32 * std::f32::consts::TAU; - let (dx, dy) = (a.cos() * rr, a.sin() * rr); - mesh.colored_vertex(Pos2::new(c.x + dx * r, c.y - dy * r), color(dx, dy)); + + // A center vertex, then each ring's vertices outwards + let mut mesh = egui::Mesh::default(); + mesh.colored_vertex(center, color(0.0, 0.0)); + for ring in 1..=SPHERE_RINGS { + let ring_radius = ring as f32 / SPHERE_RINGS as f32; + for segment in 0..SPHERE_SEGMENTS { + let angle = segment as f32 / SPHERE_SEGMENTS as f32 * std::f32::consts::TAU; + let (dx, dy) = (angle.cos() * ring_radius, angle.sin() * ring_radius); + mesh.colored_vertex(Pos2::new(center.x + dx * radius, center.y - dy * radius), color(dx, dy)); } } - for j in 0..segs { - let (a, b) = (1 + j, 1 + (j + 1) % segs); - mesh.add_triangle(0, a as u32, b as u32); + + // A fan from the center to the first ring, then quads between neighbouring rings + for segment in 0..SPHERE_SEGMENTS { + let (first, next) = (1 + segment, 1 + (segment + 1) % SPHERE_SEGMENTS); + mesh.add_triangle(0, first as u32, next as u32); } - for i in 1..rings { - let r0 = 1 + (i - 1) * segs; - let r1 = 1 + i * segs; - for j in 0..segs { - let (a, b) = (r0 + j, r0 + (j + 1) % segs); - let (c2, d) = (r1 + j, r1 + (j + 1) % segs); - mesh.add_triangle(a as u32, c2 as u32, d as u32); - mesh.add_triangle(a as u32, d as u32, b as u32); + for ring in 1..SPHERE_RINGS { + let inner_start = 1 + (ring - 1) * SPHERE_SEGMENTS; + let outer_start = 1 + ring * SPHERE_SEGMENTS; + for segment in 0..SPHERE_SEGMENTS { + let next_segment = (segment + 1) % SPHERE_SEGMENTS; + let (inner, inner_next) = (inner_start + segment, inner_start + next_segment); + let (outer, outer_next) = (outer_start + segment, outer_start + next_segment); + mesh.add_triangle(inner as u32, outer as u32, outer_next as u32); + mesh.add_triangle(inner as u32, outer_next as u32, inner_next as u32); } } - p.add(egui::Shape::mesh(mesh)); + painter.add(egui::Shape::mesh(mesh)); } /// Brush alpha preview drawn as small cells (cheap, no texture). diff --git a/crates/ui-egui/src/tile_picture.rs b/crates/ui-egui/src/tile_picture.rs index d031e666..3a0f955e 100644 --- a/crates/ui-egui/src/tile_picture.rs +++ b/crates/ui-egui/src/tile_picture.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use egui::Color32; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::{GeneratorKind, ProceduralKind}; +use texturecraft_engine::paint::BrushAlpha; use texturecraft_engine::paint::alphas::LibraryAlpha; /// A tile's picture source. Previews are requested only when its tile is drawn. @@ -12,6 +13,8 @@ pub(crate) enum TilePicture { Material(&'static str), Filter(&'static str), Alpha(&'static LibraryAlpha), + /// A built-in brush shape at a hardness, drawn as the shape tiles of the old alpha grid were + Shape(BrushAlpha, f32), Image(String, Arc), Procedural(ProceduralKind), /// A mask generator at its defaults on the smart masks' orb, a die in its corner when a seed changes its result diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 59f56357..72cbf52d 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -283,7 +283,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) const SIZE_PERCENT_RANGE: std::ops::RangeInclusive = 0.05..=100.0; /// Spacing's track, in percent of the brush's diameter - const SPACING_PERCENT_RANGE: std::ops::RangeInclusive = 1.0..=200.0; + const SPACING_PERCENT_RANGE: std::ops::RangeInclusive = 1.0..=1000.0; /// Lazy mouse Distance's track, in pixels const LAZY_DISTANCE_RANGE_PX: std::ops::RangeInclusive = 1.0..=200.0; diff --git a/crates/ui-egui/src/view_mode_picker.rs b/crates/ui-egui/src/view_mode_picker.rs index 332f136b..734a8a8d 100644 --- a/crates/ui-egui/src/view_mode_picker.rs +++ b/crates/ui-egui/src/view_mode_picker.rs @@ -76,7 +76,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, child: &mut Ui, id_salt: &str, wid // The picker stays greyed without project maps let combo = child .add_enabled_ui(project_open, |child| { - egui::ComboBox::from_id_salt(id_salt).width(width).height(LIST_HEIGHT).selected_text(label).show_ui(child, |ui| { + egui::ComboBox::from_id_salt(id_salt).width(width).height(LIST_HEIGHT).selected_text(label.as_str()).show_ui(child, |ui| { // Bake mode keeps its own list: the material, then the mesh maps, without titles if !baking { section(ui, "Lighting"); @@ -135,6 +135,11 @@ pub(crate) fn show(app: &mut TextureCraftApp, child: &mut Ui, id_salt: &str, wid }) .inner; + // The box shows only the mode's name: it is named for what it picks + combo.response.widget_info(|| egui::WidgetInfo { + current_text_value: Some(label.clone()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, project_open, tr("View mode")) + }); image_picker(app, &combo.response, popup_id); } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4c1fe3c7..37c61484 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -23,7 +23,7 @@ use crate::state::ViewLayout; use crate::theme::Tokens; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; -/// Hold this key with the Projection tool to rotate, scale or move the stencil with the mouse +/// Hold this key with a brush tool to rotate, scale or move the stencil with the mouse pub const STENCIL_KEY: egui::Key = egui::Key::S; /// Hold this key with the Clone tool and click to set the source pub const CLONE_SOURCE_KEY: egui::Key = egui::Key::V; @@ -305,7 +305,7 @@ const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; const BAKE_PAINT_CURSOR_STROKE: f32 = 1.0; const BAKE_PAINT_CURSOR_ALPHA: u8 = 200; -/// The projection stencil's dashed outline: width, white alpha, dash and gap, in points +/// The stencil's dashed outline: width, white alpha, dash and gap, in points const STENCIL_OUTLINE_STROKE: f32 = 1.0; const STENCIL_OUTLINE_ALPHA: u8 = 120; const STENCIL_OUTLINE_DASH: f32 = 5.0; @@ -572,7 +572,7 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { let names: Vec = app.session.doc.project.cameras.iter().map(|camera| camera.name.clone()).collect(); let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str); if project_open { - egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { + let picker = egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { app.run("camera.select", json!({})); } @@ -586,6 +586,13 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { app.run("camera.add", json!({})); } }); + + // The box shows only the camera's name: it is named for what it picks + let enabled = child.is_enabled(); + picker.response.widget_info(|| egui::WidgetInfo { + current_text_value: Some(shown.to_owned()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, enabled, tr("View camera")) + }); } // The 2D view of a UV tile project: a checkable button left of the view mode, with no tooltip, that shows or hides the tile numbers and the hover label @@ -779,13 +786,13 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let holding = crate::move_on_model::holding(app, ui.ctx()); let navigating = !adjusting && !holding && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); - // Navigation; S + drag moves the projection stencil instead, below + // Navigation; S + drag moves the stencil instead, below let delta = ui.input(|input| input.pointer.delta()); let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !crate::framework::widget_has_keyboard(ui.ctx()); - // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise - let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; + // Only an equipped brush tool that can act moves the stencil: it isn't drawn otherwise + let stencil_moves = tool_acts(app) && stencil_applies(app); let stencil_drag = s_held && stencil_moves && app.session.tool.stencil.is_some(); if stencil_drag || adjusting || holding { // The stencil, the brush or the held Move on model button changes instead of the camera @@ -918,8 +925,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Depth of field focus pick: a click focuses there instead of painting - let focus_pick = focus_picking(ui.ctx()) || point_pick.is_some(); - if focus_picking(ui.ctx()) { + let picking_focus_distance = focus_picking(ui.ctx()); + let focus_pick = picking_focus_distance || point_pick.is_some(); + if picking_focus_distance { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt && response.clicked_by(PointerButton::Primary) @@ -1011,7 +1019,6 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let gizmo_handle = gizmo_free && !app.session.stroke_active() && began_on_handle; - // Painting let painting = tool_acts(app) && !popup && !alt @@ -1182,35 +1189,24 @@ fn bake_visualization(app: &TextureCraftApp) -> Option bool { + app.session.tool.tool.uses_stencil() && !app.session.quick_mask.editing +} + /// Whether the active tool can act on the selection now: a greyed tool ignores clicks, keys and drags in the views fn tool_acts(app: &TextureCraftApp) -> bool { app.ui.mode == crate::state::Mode::Painting && app.session.tool_usable(app.session.tool.tool) diff --git a/crates/ui-egui/tests/i18n_build.rs b/crates/ui-egui/tests/i18n_build.rs index d2d690de..b8f61a03 100644 --- a/crates/ui-egui/tests/i18n_build.rs +++ b/crates/ui-egui/tests/i18n_build.rs @@ -1,6 +1,7 @@ //! Optional catalog embedding must work without network or application dependencies. #[path = "../i18n_build.rs"] -#[allow(dead_code)] // The production build entry point is not invoked by these pure-input tests. +// The tests call catalog collection directly +#[allow(dead_code)] mod i18n_build; /// The catalogs' Rust includes alone, which is what these tests assert on; the build itself asks @@ -36,6 +37,7 @@ fn no_input_is_english_but_required_input_errors() { #[test] fn invalid_and_relative_checkouts_are_rejected() { let fixture = Fixture::new(); + assert!(generate(Some(&fixture.0.join("missing")), false).is_err()); assert!(generate(Some(std::path::Path::new("relative")), false).is_err()); } @@ -44,6 +46,7 @@ fn invalid_and_relative_checkouts_are_rejected() { fn shared_only_locale_is_not_offered_and_required_needs_app_catalog() { let fixture = Fixture::new(); std::fs::write(fixture.0.join("locales/es/common.tsv"), "\tSave\tGuardar\n").unwrap(); + assert!(!generate(Some(&fixture.0), false).unwrap().contains("include_str!")); assert!(generate(Some(&fixture.0), true).is_err()); } @@ -53,11 +56,15 @@ fn app_catalog_is_embedded_with_optional_shared_catalog() { let fixture = Fixture::new(); let app = fixture.0.join("locales/es/texturecraft.tsv"); std::fs::write(&app, "\tLayers\tCapas\n").unwrap(); + let source = generate(Some(&fixture.0), true).unwrap(); + assert!(source.contains("texturecraft.tsv")); assert!(source.contains("(\"es\", \"\",")); + let common = fixture.0.join("locales/es/common.tsv"); std::fs::write(&common, "\tSave\tGuardar\n").unwrap(); + assert!(generate(Some(&fixture.0), true).unwrap().contains("common.tsv")); } @@ -65,20 +72,36 @@ fn app_catalog_is_embedded_with_optional_shared_catalog() { fn unreadable_catalog_fails_before_generating_rust_source() { let fixture = Fixture::new(); std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), [0xff, 0xfe]).unwrap(); + assert!(generate(Some(&fixture.0), true).is_err()); } #[test] -fn generated_paths_compile_and_embed_the_catalog_contents() { +fn generated_catalogs_are_readable_through_the_runtime_accessor() { let fixture = Fixture::new(); - std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap(); - let generated = generate(Some(&fixture.0), true).unwrap(); + let app = "\tLayers\tCapas\n"; + std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), app).unwrap(); + + let populated = generate(Some(&fixture.0), true).unwrap(); + let empty = generate(None, false).unwrap(); let program = format!( - "extern crate self as craft_i18n;\npub type Embedded = [(&'static str, &'static str, &'static str)];\n{generated}\nfn main() {{ assert_eq!(CRAFT_I18N[0].2, \"\\tLayers\\tCapas\\n\"); }}" + r#" +extern crate self as craft_i18n; +pub type Embedded = [(&'static str, &'static str, &'static str)]; + +mod populated {{ {populated} }} +mod empty {{ {empty} }} + +fn main() {{ + assert_eq!(populated::craft_i18n_catalogs(), &[("es", "", {app:?})]); + assert!(empty::craft_i18n_catalogs().is_empty()); +}} +"# ); let source = fixture.0.join("check.rs"); let binary = fixture.0.join(format!("check{}", std::env::consts::EXE_SUFFIX)); std::fs::write(&source, program).unwrap(); + assert!(std::process::Command::new("rustc").arg(&source).arg("-o").arg(&binary).status().unwrap().success()); assert!(std::process::Command::new(binary).status().unwrap().success()); } @@ -98,6 +121,7 @@ fn malformed_utf8_catalogs_and_invalid_rows_fail_during_generation() { let fixture = Fixture::new(); std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap(); std::fs::write(fixture.0.join("locales/es").join(file), invalid).unwrap(); + for required in [false, true] { assert!(generate(Some(&fixture.0), required).is_err(), "accepted {file}: {invalid:?}"); } @@ -112,11 +136,13 @@ fn the_catalog_characters_are_the_ones_the_web_font_keeps() { std::fs::write(fixture.0.join("locales/es/common.tsv"), "\tSave\tGuardar\n").unwrap(); std::fs::create_dir_all(fixture.0.join("locales/ja")).unwrap(); std::fs::write(fixture.0.join("locales/ja/texturecraft.tsv"), "\tLayers\t\u{30ec}\u{30a4}\u{30e4}\u{30fc}\n").unwrap(); - // A shared-only locale contributes no characters: its catalog is not embedded. + + // Shared-only locales have no embedded catalog std::fs::create_dir_all(fixture.0.join("locales/de")).unwrap(); std::fs::write(fixture.0.join("locales/de/common.tsv"), "\tSave\tSpeichern \u{fc}\n").unwrap(); let (source, characters) = i18n_build::collect(Some(&fixture.0), true).unwrap(); + assert!(source.contains("texturecraft.tsv")); for used in ['L', 'a', 'y', 'e', 'r', 's', 'C', 'p', 'G', 'u', 'd', '\u{30ec}', '\u{30a4}', '\u{30e4}', '\u{30fc}'] { assert!(characters.contains(&used), "missing {used:?}"); @@ -127,7 +153,7 @@ fn the_catalog_characters_are_the_ones_the_web_font_keeps() { sorted.dedup(); assert_eq!(sorted, characters, "sorted and distinct"); - // Nothing to cut with no checkout: the web build then keeps the faces whole. + // With no catalog checkout the web build keeps the full font assert_eq!(i18n_build::collect(None, false).unwrap().1, Vec::::new()); assert!(i18n_build::collect(None, true).is_err()); } diff --git a/crates/ui-egui/tests/it/alpha_parameters.rs b/crates/ui-egui/tests/it/alpha_parameters.rs index acbd588f..394a135d 100644 --- a/crates/ui-egui/tests/it/alpha_parameters.rs +++ b/crates/ui-egui/tests/it/alpha_parameters.rs @@ -4,7 +4,6 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::paint::{AlphaParams, BrushAlpha, BrushSettings}; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::PropsTab; const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); const STARTUP_FRAMES: usize = 4; @@ -23,13 +22,19 @@ fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().session.tool.brush = brush; - harness.state_mut().ui.props_tab = PropsTab::Alpha; harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(egui::Role::Tab, "Alpha").click(); + harness.run_steps(SETTLE_FRAMES); harness } +/// The reset on the Parameters band's row fn restore_defaults<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'tree> { - harness.get_by_role_and_label(egui::Role::Button, "Parameters: Reset to defaults") + let band = harness.get_by_role_and_label(egui::Role::Button, "Parameters").rect(); + harness + .query_all_by_role_and_label(egui::Role::Button, "Restore defaults") + .find(|node| node.rect().y_range().intersects(band.y_range())) + .unwrap_or_else(|| panic!("no reset on the Parameters band")) } fn invert_checkbox<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> Option> { @@ -86,10 +91,11 @@ fn the_invert_checkbox_sets_the_brush_parameter() { #[test] fn hardness_left_the_brush_tab_and_its_reset() { - let mut harness = app_with_brush(BrushSettings::default()); - harness.state_mut().ui.props_tab = PropsTab::Brush; - harness.run_steps(SETTLE_FRAMES); + let harness = app_with_brush(BrushSettings::default()); - assert!(harness.query_by_label("Hardness").is_none(), "Hardness is in the Alpha tab now"); - assert!(harness.query_by_label("Flow").is_some()); + // One page: the Brush section comes first, Hardness only in the Alpha section under it + let hardness: Vec<_> = harness.query_all_by_role_and_label(egui::Role::Slider, "Hardness").map(|node| node.rect().top()).collect(); + let flow = harness.get_by_role_and_label(egui::Role::Slider, "Flow").rect().top(); + assert_eq!(hardness.len(), 1, "Hardness is in the Alpha section alone"); + assert!(hardness[0] > flow, "the Alpha section follows the Brush section's Flow"); } diff --git a/crates/ui-egui/tests/it/alpha_slot.rs b/crates/ui-egui/tests/it/alpha_slot.rs new file mode 100644 index 00000000..0093e077 --- /dev/null +++ b/crates/ui-egui/tests/it/alpha_slot.rs @@ -0,0 +1,107 @@ +//! The Alpha section's slot: its picker sets the brush alpha, × goes back to the Round shape, and Roundness shows only for the Round shape + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_widget}; + +/// Window the Alpha section tests run in +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Frames after a click in the slot, more than the crate's SETTLE_FRAMES to leave the alpha picker's popup time to open or close +const SLOT_CLICK_FRAMES: usize = 6; + +/// Frames for the jump tab's animated scroll to settle +const SCROLL_FRAMES: usize = 60; + +/// The app showing the Alpha section of Properties, with `brush` +fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().session.tool.brush = brush; + harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(Role::Tab, "Alpha").click(); + harness.run_steps(SCROLL_FRAMES); + harness +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + click_widget(harness, role, label); + harness.run_steps(SLOT_CLICK_FRAMES); +} + +/// The × of the slot showing `slot`: the Clear button on its row +fn click_clear(harness: &mut Harness<'_, TextureCraftApp>, slot: &str) { + let row = harness.get_by_role_and_label(Role::ComboBox, slot).rect(); + let clear = harness + .query_all_by_role_and_label(Role::Button, "Clear") + .find(|node| node.rect().y_range().intersects(row.y_range())) + .unwrap_or_else(|| panic!("no Clear on the {slot} slot")) + .rect(); + super::click_at(harness, clear.center()); + harness.run_steps(SLOT_CLICK_FRAMES); +} + +/// Clicks the built-in shape `label`: the Shapes come first, above a library alpha of the same name +fn click_shape(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + let tile = harness + .query_all_by_role_and_label(Role::ListBoxOption, label) + .map(|node| node.rect()) + .min_by(|a, b| a.top().total_cmp(&b.top())) + .unwrap_or_else(|| panic!("no {label} tile")); + super::click_at(harness, tile.center()); + harness.run_steps(SLOT_CLICK_FRAMES); +} + +#[test] +fn the_slot_picks_a_shape_and_its_clear_goes_back_to_round() { + let mut harness = app_with_brush(BrushSettings::default()); + let row = harness.get_by_role_and_label(Role::ComboBox, "Round").rect(); + assert!( + !harness.query_all_by_role_and_label(Role::Button, "Clear").any(|node| node.rect().y_range().intersects(row.y_range())), + "the Round shape has nothing to clear back to" + ); + + click(&mut harness, Role::ComboBox, "Round"); + click_shape(&mut harness, "Star"); + assert_eq!(harness.state().session.tool.brush.alpha, BrushAlpha::Star); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Star").is_some(), "the slot shows the picked shape"); + + click_clear(&mut harness, "Star"); + assert_eq!(harness.state().session.tool.brush.alpha, BrushAlpha::Round); +} + +#[test] +fn the_picker_offers_the_library_alphas() { + // Any library alpha + let alpha = &alphas::library()[0]; + let mut harness = app_with_brush(BrushSettings::default()); + + click(&mut harness, Role::ComboBox, "Round"); + harness.event(egui::Event::Text(alpha.label.clone())); + harness.run_steps(SLOT_CLICK_FRAMES); + click(&mut harness, Role::ListBoxOption, &alpha.label); + + let brush = &harness.state().session.tool.brush; + assert_eq!(brush.alpha_library.as_deref(), Some(alpha.id.as_str())); + assert!(harness.query_by_role_and_label(Role::ComboBox, &alpha.label).is_some(), "the slot shows the library alpha"); +} + +#[test] +fn roundness_shows_only_for_the_round_shape() { + let roundness = |harness: &Harness<'_, TextureCraftApp>| harness.query_all_by_role_and_label(Role::Slider, "Roundness").count(); + + let round = app_with_brush(BrushSettings::default()); + assert_eq!(roundness(&round), 1, "the Round shape has a roundness"); + + let star = app_with_brush(BrushSettings { alpha: BrushAlpha::Star, ..BrushSettings::default() }); + assert_eq!(roundness(&star), 0, "other alphas have none"); + assert_eq!(star.query_all_by_role_and_label(Role::Slider, "Hardness").count(), 1, "the rest of the Parameters stay"); +} diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs index 16270401..19dd4b0c 100644 --- a/crates/ui-egui/tests/it/brush_section_reset.rs +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -1,11 +1,11 @@ -//! Each brush section header has a reset icon that puts only that section's settings back to their defaults +//! Each band of the Brush section has a reset that puts back only that band's settings, grouped as the reference groups them use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::paint::{Alignment, BrushAlpha, BrushSettings, Particles, Symmetry}; use texturecraft_ui_egui::TextureCraftApp; -/// The default window; Properties shows only the top of the brush there, so lower headers are scrolled to +/// The default window; Properties shows only the top of the brush there, so lower bands are scrolled to const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); /// Frames for the first layout and fonts to settle @@ -17,25 +17,22 @@ const SETTLE_FRAMES: usize = 3; /// Puts one section's fields of the first brush back to the second's values type SectionReset = fn(&mut BrushSettings, &BrushSettings); -/// Each brush section's title, a label shown only while it is open, whether it starts open, and its reset -const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ - ("Size", "Minimum size (%)", true, |brush, defaults| { - (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space) +/// Each band's title, a label shown only while it is open, whether it starts open, and its reset +const SECTIONS: [(&str, &str, bool, SectionReset); 6] = [ + ("Size", "Minimum Size (%)", true, |brush, defaults| { + (brush.size, brush.size_pressure, brush.min_size, brush.spacing) = (defaults.size, defaults.size_pressure, defaults.min_size, defaults.spacing) }), - ("Flow and opacity", "Stroke opacity", true, |brush, defaults| { - (brush.flow, brush.opacity, brush.spacing) = (defaults.flow, defaults.opacity, defaults.spacing) - }), - ("Angle", "Follow path", false, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), - ("Jitters", "Size jitter", false, |brush, defaults| { + ("Opacity", "Stroke opacity", true, |brush, defaults| (brush.flow, brush.opacity) = (defaults.flow, defaults.opacity)), + ("Orientation", "Follow Path", true, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), + ("Jitter", "Size Jitter", true, |brush, defaults| { (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) }), - ("Alignment and culling", "Backface culling", false, |brush, defaults| { - (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = - (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) + ("Projection", "Backface culling", true, |brush, defaults| { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.screen_space, brush.depth) = + (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.screen_space, defaults.depth) }), ("Particles", "Gravity", false, |brush, defaults| brush.particles = defaults.particles), - ("Lazy mouse", "Lazy mouse distance", false, |brush, defaults| brush.lazy = defaults.lazy), ]; /// A valid brush with every section field changed and a custom alpha that resets must preserve @@ -43,6 +40,7 @@ fn changed_brush() -> BrushSettings { BrushSettings { size: 0.1, min_size: 0.5, + size_pressure: false, screen_space: true, flow: 0.5, opacity: 0.6, @@ -82,24 +80,40 @@ fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { harness } -/// The reset icon on the header row titled `title` -fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { - let label = format!("{title}: Reset to defaults"); +/// The band titled `title` in Properties: the rightmost, as the top bar has a Size too +fn band<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { harness .query_all_by_role(egui::Role::Button) - .find(|node| node.accesskit_node().label().as_deref() == Some(label.as_str())) - .unwrap_or_else(|| panic!("no reset icon on the {title} header")) + .filter(|node| node.accesskit_node().label().as_deref() == Some(title)) + .max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())) + .unwrap_or_else(|| panic!("no {title} band")) } -/// Scrolls the header titled `title` into view and clicks its reset icon +/// The reset on the band titled `title` +fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { + let band = band(harness, title).rect(); + harness + .query_all_by_role(egui::Role::Button) + .find(|node| node.accesskit_node().label().as_deref() == Some("Restore defaults") && node.rect().y_range().intersects(band.y_range())) + .unwrap_or_else(|| panic!("no reset on the {title} band")) +} + +/// Scrolls the band titled `title` into view and clicks its reset fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { - reset_icon(harness, title).scroll_to_me(); + band(harness, title).scroll_to_me(); harness.run_steps(SETTLE_FRAMES); reset_icon(harness, title).click(); harness.run_steps(SETTLE_FRAMES); } +#[test] +fn the_lazy_mouse_is_set_only_in_the_top_bar() { + let harness = app_with_brush(BrushSettings::default()); + + assert_eq!(harness.query_all_by_label("Lazy mouse").count(), 1, "the top bar's button, no band in Properties"); +} + #[test] fn each_reset_puts_back_only_its_own_section() { let defaults = BrushSettings::default(); @@ -118,13 +132,12 @@ fn each_reset_puts_back_only_its_own_section() { } } -/// Scrolls the header titled `title` into view and clicks the header itself, folding or unfolding it +/// Scrolls the band titled `title` into view and clicks it, folding or unfolding it fn click_header(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { - reset_icon(harness, title).scroll_to_me(); + band(harness, title).scroll_to_me(); harness.run_steps(SETTLE_FRAMES); - let icon = reset_icon(harness, title).rect(); - harness.query_all_by_label(title).find(|label| label.rect().y_range().intersects(icon.y_range())).unwrap_or_else(|| panic!("no {title} header")).click(); + band(harness, title).click(); harness.run_steps(SETTLE_FRAMES); } @@ -157,7 +170,7 @@ fn at_the_defaults_the_reset_icons_are_inert() { click_reset(&mut harness, title); - assert_eq!(harness.query_by_label(body_label).is_some(), starts_open, "the click doesn't reach the {title} header"); + assert_eq!(harness.query_by_label(body_label).is_some(), !starts_open, "an inert reset folds the {title} band like the rest of it"); assert_eq!(harness.state().session.tool.brush, BrushSettings::default(), "the {title} reset is inert"); } } @@ -168,6 +181,7 @@ fn enter_and_space_on_the_focused_reset_icon_reset_only_its_section() { let mut harness = app_with_brush(changed_brush()); reset_icon(&harness, "Size").focus(); harness.run_steps(SETTLE_FRAMES); + assert!(reset_icon(&harness, "Size").is_focused()); harness.key_press(key); @@ -175,7 +189,8 @@ fn enter_and_space_on_the_focused_reset_icon_reset_only_its_section() { let defaults = BrushSettings::default(); let mut expected = changed_brush(); - (expected.size, expected.min_size, expected.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space); + (expected.size, expected.size_pressure, expected.min_size, expected.spacing) = + (defaults.size, defaults.size_pressure, defaults.min_size, defaults.spacing); assert_eq!(harness.state().session.tool.brush, expected, "resetting Size with {key:?}"); } } diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index d2edee62..4997545b 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -143,16 +143,16 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { let rows = plan(&mut h).len(); h.get_all_by_label_contains("Enable override for ").nth(4).unwrap().click(); h.run_steps(4); - let m = maps(&h); - let (_, first) = m.iter().next().unwrap(); + let map_overrides = maps(&h); + let (_, first) = map_overrides.iter().next().unwrap(); - assert!(first.file_type.is_some(), "{m:?}"); + assert!(first.file_type.is_some(), "{map_overrides:?}"); assert!(h.query_by_label("*").is_some(), "the set is marked"); click(&mut h, "Output maps menu"); click(&mut h, "Override every item"); - assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows); + assert_eq!(maps(&h).values().filter(|map_overrides| map_overrides.file_type.is_some()).count(), rows); click(&mut h, "Output maps menu"); click(&mut h, "Clear all overrides"); @@ -165,12 +165,12 @@ fn export_writes_a_map_with_its_own_file_type() { let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize; let dir = TempDir::new("export-map-overrides"); let template = h.state().ui.export.preset.clone(); - let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }), size: None }); - let e = &mut h.state_mut().ui.export; - e.dir = dir.display().to_string(); - e.sets.insert(0, o); - e.skip = (1..32).collect(); + let mut overrides = SetExport { maps_template: template, ..SetExport::default() }; + overrides.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }), size: None }); + let export = &mut h.state_mut().ui.export; + export.dir = dir.display().to_string(); + export.sets.insert(0, overrides); + export.skip = (1..32).collect(); h.run_steps(3); click(&mut h, "Export"); @@ -193,9 +193,9 @@ fn a_map_the_template_no_longer_has_is_ignored() { let mut h = harness(); let before = selected(&h); let template = h.state().ui.export.preset.clone(); - let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(999, MapExport { enabled: false, file_type: None, size: None }); - h.state_mut().ui.export.sets.insert(0, o); + let mut overrides = SetExport { maps_template: template, ..SetExport::default() }; + overrides.maps.insert(999, MapExport { enabled: false, file_type: None, size: None }); + h.state_mut().ui.export.sets.insert(0, overrides); h.run_steps(3); assert_eq!(selected(&h), before, "the export still plans every file"); @@ -285,11 +285,13 @@ fn rows_with_a_one_depth_file_type_each_have_their_own_bit_depth_list() { let mut h = harness(); let rows: Vec = plan(&mut h).iter().take(2).map(|file| file["map"].as_u64().unwrap() as usize).collect(); let template = h.state().ui.export.preset.clone(); - let mut o = SetExport { maps_template: template, ..SetExport::default() }; + let mut overrides = SetExport { maps_template: template, ..SetExport::default() }; for map in &rows { - o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "hdr".into(), bit_depth: 32, dithering: false }), size: None }); + overrides + .maps + .insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "hdr".into(), bit_depth: 32, dithering: false }), size: None }); } - h.state_mut().ui.export.sets.insert(0, o); + h.state_mut().ui.export.sets.insert(0, overrides); h.run_steps(4); let greyed: Vec<_> = diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index ec4bf518..c6046193 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -50,6 +50,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { click(&mut h, "Export"); assert_eq!(h.state().ui.export.tab, 2, "Export switches to LIST OF EXPORTS"); h.run_steps(1); + assert!(h.query_by_label("Cancel Export").is_some()); assert_eq!(h.get_by_role(egui::Role::ProgressIndicator).accesskit_node().live(), egui::accesskit::Live::Polite); assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons"); @@ -63,6 +64,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { h.run_steps(1); } h.run_steps(2); + assert!(h.state().ui.windows.export, "the window stays open"); assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Cancel Export").is_none()); let lines = console(&h); @@ -176,6 +178,7 @@ fn long_filenames_leave_the_export_details_reachable_by_scrolling() { assert!(!bits_fit(&h), "the bit-depth column starts beyond the viewport"); h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).focus(); h.run_steps(3); + assert!(h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).is_focused()); for _ in 0..12 { @@ -379,3 +382,30 @@ fn a_texture_set_that_leaves_the_export_leaves_its_count() { assert_eq!(job.total - job.pending.len(), exports(&h), "the bar counts the writes done"); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn a_folded_set_stays_folded_while_a_selection_is_exported() { + let (mut harness, _) = harness("folded-selection"); + let directory = super::temp_dir::TempDir::new("folded-export-selection"); + harness.state_mut().ui.export.dir = directory.display().to_string(); + harness.state_mut().ui.export.skip = vec![0]; + harness.state_mut().ui.export.tab = 2; + harness.run_steps(3); + let set = harness.state().session.doc.project.texture_sets[1].name.clone(); + let preset = harness.state().ui.export.preset.clone(); + let plan = texturecraft_engine::execute(&mut harness.state_mut().session, "export.plan", &json!({"preset": preset, "ts": 1})).unwrap(); + let file = plan[0]["file"].as_str().unwrap(); + assert!(harness.query_by_label(file).is_some()); + + harness.get_by_role_and_label(egui::Role::DisclosureTriangle, &set).click(); + harness.run_steps(2); + + assert!(harness.query_by_label(file).is_none()); + + click(&mut harness, "Export"); + harness.run_steps(1); + + assert!(harness.query_by_label("Cancel Export").is_some(), "the selection is being written"); + assert!(harness.query_by_label(file).is_none(), "starting the export keeps the selected set folded"); + assert_eq!(harness.get_by_role_and_label(egui::Role::DisclosureTriangle, &set).accesskit_node().data().is_expanded(), Some(false)); +} diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index d3309e43..bc2b230a 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -198,8 +198,9 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { assert!(h.query_by_label("Dilation (pixels)").is_some()); - // A click on the slider sets the width and leaves the menu open - h.get_by_role(egui::Role::Slider).click(); + // A click on the slider sets the width and leaves the menu open; Properties has sliders too, so take the one under the menu's label + let label = h.get_by_label("Dilation (pixels)").rect().left_bottom(); + h.query_all_by_role(egui::Role::Slider).min_by(|a, b| a.rect().left_top().distance(label).total_cmp(&b.rect().left_top().distance(label))).unwrap().click(); h.run_steps(4); assert_ne!(h.state().ui.export.dilation, 16); diff --git a/crates/ui-egui/tests/it/library_theme.rs b/crates/ui-egui/tests/it/library_theme.rs new file mode 100644 index 00000000..3afe5219 --- /dev/null +++ b/crates/ui-egui/tests/it/library_theme.rs @@ -0,0 +1,38 @@ +//! craft-ui's parts (the dock's frames and tab strips) draw in TextureCraft's colours, not the suite's default grey + +use craft_ui::style::StyleCx; +use egui::Color32; +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::theme::{Brightness, Tokens}; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, TEXTURE_RESOLUTION}; + +/// A window wide enough for the dock's groups, strips and splitters +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1200.0, 800.0); + +fn srgba(color: craft_theme::Rgba) -> Color32 { + let [r, g, b, a] = color.0; + Color32::from_rgba_unmultiplied(r, g, b, a) +} + +#[test] +fn the_dock_strips_and_panel_bodies_take_the_app_theme_colours() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + for brightness in [Brightness::Dark, Brightness::MediumDark, Brightness::MediumLight, Brightness::Light] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(SETTLE_FRAMES); + let tokens = Tokens::get(&harness.ctx); + let (strip, body, frame) = StyleCx::with_root(&harness.ctx, |cx| { + let color = &cx.tokens.color; + (color.surface.background, color.surface.panel, color.line.border) + }); + assert_eq!(srgba(strip), tokens.chrome, "{brightness:?}: the tab strips lie on the window chrome"); + assert_eq!(srgba(body), tokens.panel, "{brightness:?}: the shown tab and the panel body are the panel card"); + assert_eq!(srgba(frame), tokens.separator, "{brightness:?}: the group frames are the cards' hairline"); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 1c805d02..1b0167ac 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. mod alpha_parameters; +mod alpha_slot; mod anchor_point; mod auto_rebake; mod bake_job_mesh; @@ -62,6 +63,7 @@ mod layer_rename; mod layer_toolbar; mod layers_panel; mod levels_editor; +mod library_theme; mod log_panel_680; mod mask_export; mod mask_fill_rows; @@ -72,6 +74,8 @@ mod nav_buttons; mod new_project_baked_maps; mod new_project_window; mod output_templates; +mod paint_hint_lines; +mod paint_tool_tabs; mod panel_header; mod path_in_view; mod path_list; @@ -103,6 +107,7 @@ mod shift_lines_3d; mod shortcut_keys; mod shortcut_list; mod side_panels; +mod size_pressure; mod skew_paint; mod smudge_channels; mod snapped_lines; @@ -112,6 +117,7 @@ mod temp_dir; mod template_invert; mod templates_681; mod tool_availability; +mod tool_material; mod tool_settings_saved; mod toolbar; mod user_smart_mask; diff --git a/crates/ui-egui/tests/it/mask_paint_grayscale.rs b/crates/ui-egui/tests/it/mask_paint_grayscale.rs index 059beb4f..b619ea48 100644 --- a/crates/ui-egui/tests/it/mask_paint_grayscale.rs +++ b/crates/ui-egui/tests/it/mask_paint_grayscale.rs @@ -7,7 +7,6 @@ use serde_json::json; use texturecraft_engine::core::LayerId; use texturecraft_engine::execute; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::PropsTab; use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION}; @@ -32,8 +31,9 @@ fn folder_mask_harness() -> (Harness<'static, TextureCraftApp>, String) { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.props_tab = PropsTab::Material; harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(Role::Tab, "Grayscale").click(); + harness.run_steps(SETTLE_FRAMES); (harness, image) } diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index edb10bfe..1a8b7ed0 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -213,10 +213,10 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { two.maps.truncate(2); h.state_mut().run("export.preset.save", json!({ "preset": two })).unwrap(); let own = "Unreal Engine (Packed)".to_string(); - let mut o = texturecraft_ui_egui::state::SetExport { preset: Some(own.clone()), maps_template: own, ..Default::default() }; - o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); + let mut overrides = texturecraft_ui_egui::state::SetExport { preset: Some(own.clone()), maps_template: own, ..Default::default() }; + overrides.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); let ts = h.state().session.ts(); - h.state_mut().ui.export.sets.insert(ts, o); + h.state_mut().ui.export.sets.insert(ts, overrides); h.state_mut().ui.export.preset = "Two".into(); h.run_steps(4); @@ -235,13 +235,13 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { let library = TemplateLibrary::new("follow"); let mut h = harness(&library); - let mut o = texturecraft_ui_egui::state::SetExport { preset: Some("Mine".into()), maps_template: "Mine".into(), ..Default::default() }; - o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); + let mut overrides = texturecraft_ui_egui::state::SetExport { preset: Some("Mine".into()), maps_template: "Mine".into(), ..Default::default() }; + overrides.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); // The override is there when the window opens h.state_mut().ui.windows.export = false; h.run_steps(2); - h.state_mut().ui.export.sets.insert(0, o); + h.state_mut().ui.export.sets.insert(0, overrides); let ui = &mut h.state_mut().ui; ui.windows.export = true; ui.export.tab = 1; @@ -256,10 +256,10 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { h.run_steps(4); assert_eq!(h.state().ui.export.preset, "Yours"); - let o = h.state().ui.export.sets[&0].clone(); + let overrides = h.state().ui.export.sets[&0].clone(); - assert_eq!((o.preset.as_deref(), o.maps_template.as_str()), (Some("Yours"), "Yours"), "the set keeps its template and map ticks"); - assert_eq!(o.maps.len(), 1); + assert_eq!((overrides.preset.as_deref(), overrides.maps_template.as_str()), (Some("Yours"), "Yours"), "the set keeps its template and map ticks"); + assert_eq!(overrides.maps.len(), 1); right_click(&mut h, "Yours"); click(&mut h, "Remove"); @@ -271,7 +271,7 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { // Cancel goes back to the settings the window opened with, minus the removed template click(&mut h, "Cancel"); - assert!(h.state().ui.export.sets.values().all(|o| o.preset.as_deref() != Some("Yours") && o.preset.as_deref() != Some("Mine"))); + assert!(h.state().ui.export.sets.values().all(|overrides| overrides.preset.as_deref() != Some("Yours") && overrides.preset.as_deref() != Some("Mine"))); } #[test] @@ -786,5 +786,6 @@ fn feedback_template_preview_counts_overrides_only_for_its_own_maps() { assert!(h.query_by_label(&format!("{} output maps will be exported", initial - 1)).is_some()); h.state_mut().ui.export.sets.get_mut(&ts).unwrap().preset = Some("Separate maps".into()); h.run_steps(4); + assert!(h.query_by_label(&format!("{initial} output maps will be exported")).is_some()); } diff --git a/crates/ui-egui/tests/it/paint_hint_lines.rs b/crates/ui-egui/tests/it/paint_hint_lines.rs new file mode 100644 index 00000000..c4759186 --- /dev/null +++ b/crates/ui-egui/tests/it/paint_hint_lines.rs @@ -0,0 +1,53 @@ +//! A brush tool's Properties explain themselves in tooltips: no line of instructions under the controls + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +fn with_tool(tool: &str) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// The words of every label in the app +fn labels(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.query_all_by_role(Role::Label).filter_map(|node| node.accesskit_node().value().map(|value| value.to_string())).collect() +} + +#[test] +fn the_brush_section_has_no_shortcut_lines() { + let harness = with_tool("paint"); + assert!(harness.query_by_role_and_label(Role::Slider, "Size").is_some(), "the Brush section is on screen"); + let labels = labels(&harness); + let shortcut = labels.iter().find(|label| label.contains("drag")); + assert!(shortcut.is_none(), "the view shortcuts are in the keymap, not under the brush: {shortcut:?}"); +} + +#[test] +fn the_smudge_section_has_no_explanation_lines() { + let labels = labels(&with_tool("smudge")); + assert!(labels.iter().any(|label| label == "Channels dragged"), "the Smudge section is on screen"); + let sentence = labels.iter().find(|label| label.ends_with('.')); + assert!(sentence.is_none(), "what Smudge does is in its tooltips: {sentence:?}"); +} + +#[test] +fn the_clone_section_shows_its_source_state_without_instructions() { + let labels = labels(&with_tool("clone")); + assert!(labels.iter().any(|label| label == "Source: none"), "no source set yet reads as state"); + let sentence = labels.iter().find(|label| label.ends_with('.')); + assert!(sentence.is_none(), "how to set the source is in the tooltip: {sentence:?}"); +} diff --git a/crates/ui-egui/tests/it/paint_tool_tabs.rs b/crates/ui-egui/tests/it/paint_tool_tabs.rs new file mode 100644 index 00000000..ca7ee50c --- /dev/null +++ b/crates/ui-egui/tests/it/paint_tool_tabs.rs @@ -0,0 +1,174 @@ +//! A paint tool's Properties: one page of sections under jump tabs, Brush · Alpha · (Stencil) · Material, below a brush preview that stays put + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// Short enough that the tool's sections scroll +const WINDOW: egui::Vec2 = egui::vec2(1400.0, 800.0); + +/// A second at 60 frames: a jump scrolls with egui's scroll animation +const SCROLL_FRAMES: usize = 60; + +fn paint_harness(tool: &str) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// egui reports a tab's selection as its toggled state +fn tab_selected(harness: &Harness<'_, TextureCraftApp>, tab: &str) -> bool { + harness.get_by_role_and_label(Role::Tab, tab).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn the_tabs_jump_within_one_page_of_the_tools_sections() { + let mut harness = paint_harness("paint"); + for tab in ["Brush", "Alpha", "Stencil", "Material"] { + assert!(harness.query_by_role_and_label(Role::Tab, tab).is_some(), "the {tab} tab"); + } + assert!(tab_selected(&harness, "Brush"), "the page opens on its first section"); + let flow_before = harness.get_by_label("Flow").rect().top(); + + harness.get_by_role_and_label(Role::Tab, "Material").click(); + harness.run_steps(SCROLL_FRAMES); + + assert!(tab_selected(&harness, "Material"), "the clicked section is the one in view"); + assert!(!tab_selected(&harness, "Brush")); + assert!(harness.get_by_label("Flow").rect().top() < flow_before, "the Brush rows scrolled up out of the way, still on the page"); +} + +#[test] +fn every_brush_tool_has_a_stencil_tab_and_polygon_fill_none() { + for tool in ["paint", "eraser", "projection", "smudge", "clone"] { + let harness = paint_harness(tool); + + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_some(), "{tool}"); + } + + let harness = paint_harness("polygonFill"); + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_none(), "polygon fill paints no strokes"); +} + +#[test] +fn the_brush_preview_stays_under_the_tabs_while_the_sections_scroll() { + let mut harness = paint_harness("paint"); + let preview_before = harness.get_by_label("Brush preview").rect(); + let flow_before = harness.get_by_label("Flow").rect().top(); + + harness.get_by_role_and_label(Role::Tab, "Material").click(); + harness.run_steps(SCROLL_FRAMES); + + assert!(harness.get_by_label("Flow").rect().top() < flow_before, "the sections scrolled"); + assert_eq!(harness.get_by_label("Brush preview").rect(), preview_before, "the preview stayed where it was"); + assert!(preview_before.top() >= harness.get_by_role_and_label(Role::Tab, "Material").rect().bottom(), "under the tabs"); +} + +#[test] +fn the_brush_preview_keeps_its_picture_until_the_paint_colour_changes() { + let mut harness = paint_harness("paint"); + let pictures = |harness: &Harness<'_, TextureCraftApp>| -> Vec { + harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name == "brush_stroke_preview").map(|(id, _)| *id).collect() + }; + let first = pictures(&harness); + + harness.run_steps(SCROLL_FRAMES); + + assert_eq!(pictures(&harness), first, "an unchanged brush reuses its picture"); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + harness.run_steps(SCROLL_FRAMES); + let recoloured = pictures(&harness); + assert_eq!(recoloured.len(), 1, "the old picture is released"); + assert_ne!(recoloured, first, "a new colour draws a new picture"); +} + +#[test] +fn the_brush_preview_ignores_values_of_disabled_channels() { + let mut harness = paint_harness("paint"); + let preview_meshes = |harness: &Harness<'_, TextureCraftApp>| { + let preview = harness.get_by_role_and_label(Role::Image, "Brush preview").rect(); + let mut meshes = harness.output().shapes.iter().filter_map(|clipped| match &clipped.shape { + egui::Shape::Mesh(mesh) if preview.contains_rect(mesh.calc_bounds()) => Some(mesh), + _ => None, + }); + let stroke = meshes.find(|mesh| mesh.calc_bounds().right() <= preview.center().x).unwrap(); + let sphere = meshes.find(|mesh| mesh.calc_bounds().left() >= preview.center().x).unwrap(); + (stroke.texture_id, sphere.vertices.iter().map(|vertex| vertex.color).collect::>()) + }; + + for (channel, material) in [ + ("baseColor", json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})), + ("metallic", json!({"channel": "metallic", "value": 1.0})), + ("roughness", json!({"channel": "roughness", "value": 0.0})), + ] { + execute(&mut harness.state_mut().session, "tool.material", &material).unwrap(); + harness.run_steps(1); + let enabled = preview_meshes(&harness); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": channel, "enabled": false})).unwrap(); + harness.run_steps(1); + let disabled = preview_meshes(&harness); + + assert!(disabled.1 != enabled.1, "disabling {channel} changes the sphere shading"); + if channel == "baseColor" { + assert_ne!(disabled.0, enabled.0, "disabling base color redraws the tinted stroke"); + } + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": channel, "enabled": true})).unwrap(); + harness.run_steps(1); + + assert!(preview_meshes(&harness).1 == enabled.1, "re-enabling {channel} restores its stored value in the sphere"); + } +} + +#[test] +fn the_brush_preview_uses_neutral_coverage_while_editing_the_quick_mask() { + let mut harness = paint_harness("paint"); + let stroke_texture = |harness: &Harness<'_, TextureCraftApp>| { + let preview = harness.get_by_role_and_label(Role::Image, "Brush preview").rect(); + harness + .output() + .shapes + .iter() + .find_map(|clipped| match &clipped.shape { + egui::Shape::Mesh(mesh) if preview.contains_rect(mesh.calc_bounds()) && mesh.calc_bounds().right() <= preview.center().x => { + Some(mesh.texture_id) + } + _ => None, + }) + .unwrap() + }; + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + harness.step(); + let blue = stroke_texture(&harness); + + execute(&mut harness.state_mut().session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + harness.step(); + + let coverage = stroke_texture(&harness); + assert_ne!(coverage, blue, "editing the quick mask redraws the blue stroke as coverage"); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 1.0, 1.0]})).unwrap(); + harness.step(); + + assert_eq!(stroke_texture(&harness), coverage, "material changes do not tint the quick mask stroke"); + + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); + harness.step(); + + assert_eq!(stroke_texture(&harness), coverage, "the quick mask preview uses the same neutral stroke as white paint"); +} diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index 72605f64..42393fa3 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -1,4 +1,4 @@ -//! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the tool's colour, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart +//! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the brush presets, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart use eframe::App as _; use egui::accesskit::Role; @@ -18,9 +18,6 @@ const DRAG_MOVES: usize = 6; /// A short stroke on the model const STROKE: Vec2 = vec2(-60.0, 40.0); -/// From the tool's Base color label to inside its swatch -const LABEL_TO_SWATCH: f32 = 60.0; - /// The app started on `storage` (its saved arrangement, if any) with the paint tool's Properties showing fn app(storage: &MemoryStorage) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); @@ -91,23 +88,17 @@ fn stroke_on_model(harness: &mut Harness<'_, TextureCraftApp>, modifiers: Modifi drag(harness, view.center(), STROKE, modifiers); } -/// Opens the paint tool's Base color swatch from its Properties' Material tab -fn open_tool_color(harness: &mut Harness<'_, TextureCraftApp>) { - let header = harness.get_by_role_and_label(egui::Role::Tab, "Properties - Paint").rect(); - let in_properties = |rect: egui::Rect| header.x_range().contains(rect.center().x) && rect.top() > header.top(); - let material = harness.get_all_by_label("Material").find(|node| in_properties(node.rect())).unwrap(); - material.click(); - harness.run_steps(SETTLE_FRAMES); - - let label = harness.get_all_by_value("Base color").find(|node| in_properties(node.rect())).unwrap().rect(); - click(harness, label.right_center() + vec2(LABEL_TO_SWATCH, 0.0)); - assert!(egui::Popup::is_any_open(&harness.ctx), "the swatch opens its colour popup"); +/// Opens the brush presets from the ≡ on the paint tool's Brush caption +fn open_brush_presets(harness: &mut Harness<'_, TextureCraftApp>) { + let menu = harness.get_by_role_and_label(Role::Button, "Brush presets").rect(); + click(harness, menu.center()); + assert!(egui::Popup::is_any_open(&harness.ctx), "the ≡ opens the brush presets"); } #[test] -fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_restored_rearranged_layout() { +fn a_stroke_on_the_model_closes_the_brush_presets_in_the_default_and_a_restored_rearranged_layout() { let check_stroke = |mut harness: Harness<'_, TextureCraftApp>, layout: &str| { - open_tool_color(&mut harness); + open_brush_presets(&mut harness); let history = harness.state().session.history_labels().len(); stroke_on_model(&mut harness, Modifiers::NONE); @@ -121,9 +112,9 @@ fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_resto } #[test] -fn an_alt_orbit_keeps_the_tool_colour_popup_open() { +fn an_alt_orbit_keeps_the_brush_presets_open() { let mut harness = app(&MemoryStorage::default()); - open_tool_color(&mut harness); + open_brush_presets(&mut harness); stroke_on_model(&mut harness, Modifiers::ALT); @@ -147,7 +138,7 @@ fn a_stroke_on_the_model_closes_the_add_effect_menu() { fn outside_drag_dismissal_handles_motion_batched_with_release() { for (modifiers, stays_open) in [(Modifiers::ALT, true), (Modifiers::NONE, false)] { let mut harness = app(&MemoryStorage::default()); - open_tool_color(&mut harness); + open_brush_presets(&mut harness); let origin = harness.state().viewport_rect.center(); harness.event(Event::ModifiersChanged(modifiers)); harness.hover_at(origin); diff --git a/crates/ui-egui/tests/it/properties_lists.rs b/crates/ui-egui/tests/it/properties_lists.rs index 3486b719..cb2501c2 100644 --- a/crates/ui-egui/tests/it/properties_lists.rs +++ b/crates/ui-egui/tests/it/properties_lists.rs @@ -22,6 +22,9 @@ const GESTURE: Vec2 = vec2(-60.0, 40.0); /// Where in the view the gestures start, as a share of its width from its left edge const GESTURE_SHARE: f32 = 0.3; +/// Frames for a scroll to a list to finish its animation +const SCROLL_FRAMES: usize = 30; + /// Escapes between lists, so one that stays open can't leave its popup over the next const ESCAPES_TO_CLEAR: usize = 2; @@ -242,6 +245,17 @@ fn every_list_opens_leaves_the_view_its_camera_and_closes_on_escape_a_click_and_ continue; }; + // A list low in a long panel sits below its visible part until scrolled to + let same_before = lists(&harness).iter().take(index).filter(|(_, other)| *other == shown).count(); + if let Some(node) = harness.query_all_by_role(Role::ComboBox).find(|node| node.rect() == button) { + node.scroll_to_me(); + } + harness.run_steps(SCROLL_FRAMES); + let Some((button, _)) = lists(&harness).into_iter().filter(|(_, other)| *other == shown).nth(same_before) else { + problems.push(format!("{screen}: {shown} is gone after scrolling to it")); + continue; + }; + problems.extend(check_list(&mut harness, button, &format!("{screen}: {shown}"))); for _ in 0..ESCAPES_TO_CLEAR { harness.key_press(egui::Key::Escape); diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 19de942d..0453378a 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -9,7 +9,7 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; use texturecraft_ui_egui::state::{Mode, ViewLayout}; -use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION}; /// A common laptop window const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); @@ -35,6 +35,9 @@ const SCROLL_FRAMES: usize = 25; /// How far left of the popup a click lands on the model const MODEL_LEFT_OF_POPUP: f32 = 60.0; +/// How far in from the popup's right edge a slider drag ends, still over the slider's band +const DROP_LEFT_OF_POPUP_EDGE: f32 = 30.0; + fn harness() -> Harness<'static, TextureCraftApp> { harness_sized(WINDOW_SIZE) } @@ -156,21 +159,23 @@ fn dragging_its_size_slider_changes_the_brush() { click(&mut harness, PointerButton::Secondary, center); let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); - // The Size section's header sits above its slider of the same name - let slider_label = harness - .query_all_by_label("Size") + // The Size band holds a slider of the same name, its track right of the label + let slider = harness + .query_all_by_role(egui::Role::Slider) + .filter(|node| node.accesskit_node().label().as_deref() == Some("Size")) .map(|node| node.rect()) - .filter(|rect| popup.contains_rect(*rect)) - .max_by(|first, second| first.top().total_cmp(&second.top())) + .find(|rect| popup.contains_rect(*rect)) .unwrap(); - let track_y = slider_label.bottom() + 10.0; + let track_y = slider.center().y; let size = harness.state().session.tool.brush.size; - harness.drag_at(egui::pos2(slider_label.left() + 20.0, track_y)); - harness.run_steps(2); - harness.hover_at(egui::pos2(popup.right() - 30.0, track_y)); - harness.run_steps(2); - harness.drop_at(egui::pos2(popup.right() - 30.0, track_y)); - harness.run_steps(3); + let drop = egui::pos2(popup.right() - DROP_LEFT_OF_POPUP_EDGE, track_y); + harness.drag_at(egui::pos2(slider.left() + SLIDER_END_INSET, track_y)); + harness.run_steps(DRAG_STEP_FRAMES); + harness.hover_at(drop); + harness.run_steps(DRAG_STEP_FRAMES); + harness.drop_at(drop); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().session.tool.brush.size > size, "{size} -> {}", harness.state().session.tool.brush.size); assert!(is_open(&harness), "editing it keeps it open"); } @@ -194,7 +199,28 @@ fn it_shows_what_the_properties_panel_shows() { let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); let in_popup = |label: &str| harness.query_all_by_label(label).any(|node| popup.contains_rect(node.rect())); assert!(in_popup("UV projection"), "a selected fill shows its fill settings"); - assert!(!in_popup("Minimum size (%)"), "not the brush's"); + assert!(!in_popup("Minimum Size (%)"), "not the brush's"); +} + +#[test] +fn its_brush_pictures_and_the_docked_panels_keep_their_own_textures() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + + assert!(is_open(&harness)); + + let previews = |harness: &Harness<'_, TextureCraftApp>| { + let mut ids: Vec<_> = + harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name == "brush_stroke_preview").map(|(id, _)| *id).collect(); + ids.sort_unstable_by_key(|id| format!("{id:?}")); + ids + }; + let before = previews(&harness); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(before.len(), 2, "one stroke preview for the docked panel and one for the popup"); + assert_eq!(previews(&harness), before, "neither is drawn again while the brush stays the same"); } /// Whether the jump tab `name` inside `area` is the lit one diff --git a/crates/ui-egui/tests/it/shelf_drag_ghost.rs b/crates/ui-egui/tests/it/shelf_drag_ghost.rs index eb5525ba..56f72830 100644 --- a/crates/ui-egui/tests/it/shelf_drag_ghost.rs +++ b/crates/ui-egui/tests/it/shelf_drag_ghost.rs @@ -64,6 +64,7 @@ fn the_badge_says_whether_the_place_under_the_pointer_takes_the_asset_without_co harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); } @@ -96,5 +97,6 @@ fn a_layer_dragged_in_the_layer_stack_gets_the_same_ghost_and_badge() { harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); } diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index c2809684..dcb99d5e 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -39,14 +39,14 @@ fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static (harness, unique) } -/// Largest drawn texture in pixels, excluding fonts and images below `min_width` points -fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { +/// Largest drawn texture in pixels, excluding fonts and images below `min_side` points on either side (a wide strip is not a big preview) +fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_side: f32) -> Option<[usize; 2]> { let textures = h.ctx.tex_manager(); let textures = textures.read(); h.output() .shapes .iter() - .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().width() >= min_width) + .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().size().min_elem() >= min_side) .filter_map(|clipped| textures.meta(clipped.shape.texture_id()).map(|meta| meta.size)) .max() } diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 261b72ac..dbc70547 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -51,6 +51,7 @@ fn a_built_in_tile_menu_says_what_the_asset_is_and_where_it_lives() { harness.get_by_label("Close").click(); harness.run_steps(3); + assert!(harness.query_by_label("Usages material").is_none(), "Close closes the menu"); } @@ -88,8 +89,11 @@ fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { #[test] fn a_saved_brush_menu_renames_replaces_and_deletes_it() { - // A name that sorts before every built-in brush, so its tile is in view + let dir = super::temp_dir::TempDir::new("shelf-rename-brush"); let mut harness = shelf(BRUSHES_TYPE); + harness.state_mut().session.brush_presets.dir = Some(dir.to_path_buf()); + + // Keep the saved brush in view at the beginning of the sorted grid texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap(); harness.run_steps(3); @@ -97,23 +101,27 @@ fn a_saved_brush_menu_renames_replaces_and_deletes_it() { type_name(&mut harness, "Never applied"); harness.key_press(Key::Escape); harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa ink"], "Escape keeps the name"); right_click(&mut harness, "Aa ink"); type_name(&mut harness, "Aa pen"); harness.key_press(Key::Enter); harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa pen"], "Enter renames the brush"); texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({"size": 77})).unwrap(); right_click(&mut harness, "Aa pen"); harness.get_by_label("Replace with the current brush").click(); harness.run_steps(3); + assert_eq!(harness.state().session.brush_presets.list[0].brush, harness.state().session.tool.brush, "the preset holds the current brush"); right_click(&mut harness, "Aa pen"); harness.get_by_label("Delete").click(); harness.run_steps(3); + assert!(preset_names(&harness).is_empty(), "Delete removes the brush"); } @@ -188,14 +196,17 @@ fn shift_f10_opens_the_menu_of_the_focused_tile_on_its_first_row_and_escape_retu harness.get_all_by_label(&name).next().unwrap().focus(); harness.run_steps(2); + assert!(harness.get_all_by_label(&name).next().unwrap().is_focused(), "the tile takes the focus"); harness.key_press_modifiers(Modifiers::SHIFT, Key::F10); harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_some(), "Shift+F10 opens the menu"); assert!(harness.get_by_label("Delete").is_focused(), "the first row that can be picked takes the focus (Reload can't: no file)"); harness.key_press(Key::Escape); harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_none(), "Escape closes it"); assert!(harness.get_all_by_label(&name).next().unwrap().accesskit_node().is_focused(), "the focus is back on the tile"); } @@ -266,3 +277,76 @@ fn set_custom_preview_shows_a_picked_picture_until_removed() { right_click(&mut harness, material.label); assert!(harness.query_by_label("Remove custom preview").is_none(), "only a tile with a custom preview offers to remove it"); } + +#[test] +fn custom_preview_textures_live_until_their_last_tile_releases_them() { + let mut materials: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + materials.sort_by_key(|material| material.label.to_lowercase()); + let (first, second) = (materials[0].label, materials[1].label); + let mut harness = shelf(MATERIALS_TYPE); + let directory = super::temp_dir::TempDir::new("shared-shelf-preview"); + let shared = directory.join("shared.png"); + let replacement = directory.join("replacement.png"); + let last = directory.join("last.png"); + for path in [&shared, &replacement, &last] { + image::RgbaImage::from_pixel(164, 164, image::Rgba([40, 160, 90, 255])).save(path).unwrap(); + } + let mut answers = vec![shared.clone(), shared, replacement, last].into_iter(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answers.next().unwrap()])))); + + let allocated = |harness: &Harness<'_, TextureCraftApp>| { + harness + .ctx + .tex_manager() + .read() + .allocated() + .filter(|(_, texture)| texture.name.starts_with("custom_preview_")) + .fold((0, 0), |(count, bytes), (_, texture)| (count + 1, bytes + texture.size[0] * texture.size[1] * texture.bytes_per_pixel)) + }; + + pick_from_menu(&mut harness, first, "Set custom preview..."); + pick_from_menu(&mut harness, second, "Set custom preview..."); + let shared = allocated(&harness); + pick_from_menu(&mut harness, first, "Set custom preview..."); + let separate = allocated(&harness); + pick_from_menu(&mut harness, second, "Remove custom preview"); + let remaining = allocated(&harness); + pick_from_menu(&mut harness, first, "Set custom preview..."); + let replaced_last = allocated(&harness); + pick_from_menu(&mut harness, first, "Remove custom preview"); + let cleared = allocated(&harness); + + println!( + "Custom preview (textures, bytes): shared {shared:?}, replaced {separate:?}, removed {remaining:?}, replaced last {replaced_last:?}, cleared {cleared:?}" + ); + assert_eq!(shared.0, 1); + assert!(shared.1 > 0); + assert_eq!(separate, (2, 2 * shared.1)); + assert_eq!(remaining, shared); + assert_eq!(replaced_last, shared); + assert_eq!(cleared, (0, 0)); +} + +#[test] +fn the_shelf_uploads_only_the_project_thumbnails_in_view() { + const RESOURCE_COUNT: usize = 100; + let mut harness = shelf(TEXTURES_TYPE); + harness.state_mut().ui.shelf_filter = "visible-tile".into(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(64, 64, image::Rgba([80, 140, 40, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + for index in 0..RESOURCE_COUNT { + harness.state_mut().session.import_resource_bytes(&format!("visible-tile-{index:03}.png"), png.clone()).unwrap(); + } + + harness.run_steps(3); + + let allocated = harness + .ctx + .tex_manager() + .read() + .allocated() + .filter(|(_, texture)| texture.name.starts_with("res_visible-tile-")) + .fold((0, 0), |(count, bytes), (_, texture)| (count + 1, bytes + texture.size[0] * texture.size[1] * texture.bytes_per_pixel)); + println!("Shelf of {RESOURCE_COUNT} textures: {} uploads retained, {} bytes", allocated.0, allocated.1); + assert!(allocated.0 > 0 && allocated.0 < RESOURCE_COUNT); +} diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 5c3c9275..45b8a657 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -237,6 +237,7 @@ fn a_long_saved_search_list_can_select_the_last_query() { }) .collect(); harness.run_steps(3); + assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows"); harness.get_by_label("search 0").hover(); diff --git a/crates/ui-egui/tests/it/shelf_second.rs b/crates/ui-egui/tests/it/shelf_second.rs index ef3413db..aac41b23 100644 --- a/crates/ui-egui/tests/it/shelf_second.rs +++ b/crates/ui-egui/tests/it/shelf_second.rs @@ -33,6 +33,7 @@ fn the_folder_button_opens_a_second_assets_panel_that_searches_on_its_own() { harness.get_by_label("New Assets panel").click(); harness.run_steps(3); + assert!(harness.state().ui.dock.is_visible(Panel::AssetsSecond), "the folder button shows a second Assets panel"); search_shown_panel(&mut harness, "brick"); diff --git a/crates/ui-egui/tests/it/shelf_updates.rs b/crates/ui-egui/tests/it/shelf_updates.rs index 717a6d4a..7e6ab880 100644 --- a/crates/ui-egui/tests/it/shelf_updates.rs +++ b/crates/ui-egui/tests/it/shelf_updates.rs @@ -113,13 +113,14 @@ fn a_file_that_fails_to_read_is_reported_again_in_the_next_project() { harness.run_steps(2); let mut reported = Vec::new(); - for project in ["first", "second"] { - if project == "second" { + let mut retained = Vec::new(); + for project in ["first", "second", "third"] { + if project != "first" { harness.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); } let folder = std::env::temp_dir().join(format!("texturecraft-failed-read-{project}-{}", std::process::id())); std::fs::create_dir_all(&folder).unwrap(); - let path = folder.join("photo.png"); + let path = folder.join("missing-update-photo.png"); std::fs::write(&path, grey_png(0.2)).unwrap(); let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); std::fs::remove_dir_all(&folder).unwrap(); @@ -127,8 +128,17 @@ fn a_file_that_fails_to_read_is_reported_again_in_the_next_project() { pass_a_minute(&mut harness); + let allocations = harness.ctx.data(|data| { + data.iter_temp_by_type::>().filter(|names| names.contains(&name)).fold((0, 0), |(count, bytes), names| { + (count + 1, bytes + names.capacity() * size_of::() + names.iter().map(String::capacity).sum::()) + }) + }); + retained.push(allocations); reported.push(harness.state().toasts.iter().any(|toast| toast.error && toast.text.starts_with(&format!("{name}:")))); } - assert_eq!(reported, [true, true], "each project says once that its file can't be read"); + println!("Cached missing-file reports (lists, bytes) for successive projects: {retained:?}"); + assert_eq!(retained[0].0, 1, "the active project remembers the report"); + assert_eq!(retained, [retained[0]; 3], "each replacement releases the previous project's failure list"); + assert_eq!(reported, [true; 3], "each project says once that its file can't be read"); } diff --git a/crates/ui-egui/tests/it/size_pressure.rs b/crates/ui-egui/tests/it/size_pressure.rs new file mode 100644 index 00000000..9d6013c3 --- /dev/null +++ b/crates/ui-egui/tests/it/size_pressure.rs @@ -0,0 +1,47 @@ +//! The pen button on the paint tool's Size row turns pen pressure on Size on and off; Minimum Size only applies while it is on + +use egui::accesskit::{Role, Toggled}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// Tall enough that the Size band shows without scrolling +const WINDOW: egui::Vec2 = egui::vec2(1600.0, 960.0); + +fn paint_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +fn pen_toggled(harness: &Harness<'_, TextureCraftApp>) -> Option { + harness.get_by_role_and_label(Role::CheckBox, "Size pen pressure").accesskit_node().toggled() +} + +/// Whether every Minimum Size slider node is greyed +fn minimum_size_greyed(harness: &Harness<'_, TextureCraftApp>) -> bool { + let sliders: Vec<_> = harness.get_all_by_label("Minimum Size (%)").filter(|node| node.accesskit_node().role() == Role::Slider).collect(); + assert!(!sliders.is_empty(), "Minimum Size has a slider"); + sliders.iter().all(|node| node.accesskit_node().is_disabled()) +} + +#[test] +fn the_pen_button_turns_size_pressure_off_and_greys_minimum_size() { + let mut harness = paint_harness(); + assert_eq!(pen_toggled(&harness), Some(Toggled::True), "a new brush follows the pen"); + assert!(!minimum_size_greyed(&harness)); + + harness.get_by_role_and_label(Role::CheckBox, "Size pen pressure").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(!harness.state().session.tool.brush.size_pressure, "the click reached the brush"); + assert_eq!(pen_toggled(&harness), Some(Toggled::False)); + assert!(minimum_size_greyed(&harness), "Minimum Size does nothing without pen pressure"); +} diff --git a/crates/ui-egui/tests/it/smudge_channels.rs b/crates/ui-egui/tests/it/smudge_channels.rs index 024377d6..414ea372 100644 --- a/crates/ui-egui/tests/it/smudge_channels.rs +++ b/crates/ui-egui/tests/it/smudge_channels.rs @@ -8,7 +8,9 @@ use texturecraft_engine::core::Channel; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, Tool, execute}; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::PropsTab; + +/// Frames egui's scroll animation takes to bring a row into view +const SCROLL_FRAMES: usize = 30; fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); @@ -26,11 +28,13 @@ fn run(harness: &mut Harness<'_, TextureCraftApp>, command: &str, params: Value) harness.run_steps(4); } -/// The channel chips drawn in the open Properties panel +/// The Smudge panel's chip for `channel` (the Material section's pill below it is a checkbox) +fn smudge_chip<'a>(harness: &'a Harness<'_, TextureCraftApp>, channel: Channel) -> egui_kittest::Node<'a> { + harness.get_by_role_and_label(Role::Button, channel.short()) +} + fn chip_is_on(harness: &Harness<'_, TextureCraftApp>, channel: Channel) -> bool { - let chips: Vec<_> = harness.get_all_by_role_and_label(Role::Button, channel.short()).collect(); - assert_eq!(chips.len(), 1, "one {} chip is drawn", channel.short()); - chips[0].accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) + smudge_chip(harness, channel).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) } /// Channels whose chip is on, in the order of `Channel::ALL` @@ -67,13 +71,15 @@ fn smudge_panel_shows_the_channels_the_material_has_on() { fn clicking_a_channel_in_the_smudge_panel_turns_it_off_and_on_for_the_material() { let mut harness = harness(); - harness.get_by_role_and_label(Role::Button, Channel::Metallic.short()).click(); + smudge_chip(&harness, Channel::Metallic).click(); harness.run_steps(4); + assert!(!harness.state().session.tool.enabled.contains(&Channel::Metallic)); assert!(!chip_is_on(&harness, Channel::Metallic)); - harness.get_by_role_and_label(Role::Button, Channel::Metallic.short()).click(); + smudge_chip(&harness, Channel::Metallic).click(); harness.run_steps(4); + assert!(harness.state().session.tool.enabled.contains(&Channel::Metallic)); assert!(chip_is_on(&harness, Channel::Metallic)); } @@ -81,19 +87,23 @@ fn clicking_a_channel_in_the_smudge_panel_turns_it_off_and_on_for_the_material() #[test] fn material_tab_and_smudge_panel_stay_in_sync() { let mut harness = harness(); - harness.state_mut().ui.props_tab = PropsTab::Material; - harness.run_steps(4); - // Both the Smudge panel and the Material tab draw a chip per channel - let chips = harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()).count(); - assert_eq!(chips, 2, "Smudge panel and Material tab"); - - let first = harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()).next().unwrap(); - first.click(); + // The Smudge panel draws a chip per channel, the Material section a pill + harness.get_by_role_and_label(Role::CheckBox, "Height").scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + harness.get_by_role_and_label(Role::CheckBox, "Height").click(); harness.run_steps(4); assert!(!harness.state().session.tool.enabled.contains(&Channel::Height)); - for chip in harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()) { - assert_ne!(chip.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "both chips show height off"); - } + assert!(!chip_is_on(&harness, Channel::Height), "the Smudge panel's chip shows height off"); + let pill = harness.get_by_role_and_label(Role::CheckBox, "Height"); + assert_ne!(pill.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "so does the Material section's pill"); + + smudge_chip(&harness, Channel::Height).scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + smudge_chip(&harness, Channel::Height).click(); + harness.run_steps(4); + + let pill = harness.get_by_role_and_label(Role::CheckBox, "Height"); + assert_eq!(pill.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "the chip turns the pill back on") } diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index fc72b047..74543239 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -1,5 +1,4 @@ -//! The Projection tool's stencil: an Assets image dropped on its slot, position fields and a reset in the tool panel, -//! S + Shift + left-drag to turn it in snapped steps, and the 2D view saying that projection paints in the 3D view +//! The brush tools' stencil: an Assets image dropped on its slot, position fields, Tiling mode and the section reset in the tool panel, S + Shift + left-drag to turn it in snapped steps, the 2D view saying that projection paints in the 3D view, and no stencil while the quick mask is painted use egui::accesskit::Role; use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; @@ -11,30 +10,50 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; use texturecraft_ui_egui::state::ViewLayout; +use crate::{BAKE_RESOLUTION, REDRAW_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + /// The sample project with the Projection tool equipped, and an imported image's resource name fn projection_app() -> (Harness<'static, TextureCraftApp>, String) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + tool_app(Tool::Projection) +} + +/// Window the stencil tests run in +const WINDOW_SIZE: egui::Vec2 = vec2(1600.0, 960.0); + +/// Side of the plain white image imported for the stencil +const IMAGE_SIZE: u32 = 4; + +/// The sample project with `tool` equipped and its Stencil section in view, and an imported image's resource name +fn tool_app(tool: Tool) -> (Harness<'static, TextureCraftApp>, String) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let white = image::RgbaImage::from_pixel(IMAGE_SIZE, IMAGE_SIZE, image::Rgba([255, 255, 255, 255])); + white.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let name = session.import_resource_bytes("logo.png", png).unwrap(); - session.tool.tool = Tool::Projection; + session.tool.tool = tool; + let mut harness = Harness::builder() - .with_size(egui::vec2(1600.0, 960.0)) + .with_size(WINDOW_SIZE) .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(4); + harness.run_steps(STARTUP_FRAMES); + + harness.get_by_role_and_label(Role::Tab, "Stencil").click(); + harness.run_steps(REDRAW_FRAMES); (harness, name) } -/// The number field beside a uniquely labelled slider +/// The number field a click on a slider's value opens, on the slider's line fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = harness.get_by_label(label).rect().center().y; + let row = harness.get_by_role_and_label(Role::Slider, label).rect().center().y; harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } -/// Type a complete value in the number field beside a uniquely labelled slider +/// Type a complete value in the number field of a uniquely labelled slider fn set_number(harness: &mut Harness<'_, TextureCraftApp>, label: &str, value: &str) { + harness.get_by_label(&format!("{label} value")).click(); + harness.run_steps(2); let length = number_field(harness, label).value().unwrap().len(); number_field(harness, label).focus(); harness.run_steps(2); @@ -87,7 +106,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { let (mut harness, name) = projection_app(); assert!(harness.state().session.tool.stencil.is_none()); - let slot = harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).unwrap().rect().center(); + let slot = harness.get_by_role_and_label(Role::ComboBox, "None").rect().center(); egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None }); harness.hover_at(slot); harness.run_steps(2); @@ -98,7 +117,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { } #[test] -fn the_position_fields_move_the_stencil_and_reset_puts_it_back() { +fn the_position_fields_move_the_stencil_and_the_section_reset_puts_it_back() { let (mut harness, name) = projection_app(); texturecraft_engine::execute( &mut harness.state_mut().session, @@ -112,20 +131,35 @@ fn the_position_fields_move_the_stencil_and_reset_puts_it_back() { set_number(&mut harness, "Position X", "-0.75"); let moved = harness.state().session.tool.stencil.clone().unwrap(); assert_eq!(moved.center, [-0.75, -0.25], "only X changed"); - harness.get_by_label("Position Y"); + harness.get_by_role_and_label(Role::Slider, "Position Y"); - harness.get_by_label("Reset stencil").scroll_to_me(); + harness.get_by_label("Stencil: Reset to defaults").scroll_to_me(); harness.run_steps(3); - harness.get_by_label("Reset stencil").click(); + harness.get_by_label("Stencil: Reset to defaults").click(); harness.run_steps(3); let reset = harness.state().session.tool.stencil.clone().unwrap(); assert_eq!((reset.center, reset.scale, reset.rotation), ([0.0, 0.0], 0.8, 0.0)); assert_eq!((reset.image.as_str(), reset.opacity, reset.tile), (name.as_str(), 0.3, true), "image, opacity and tiling stay"); } +#[test] +fn the_tiling_mode_list_tiles_the_stencil() { + let (mut harness, name) = tool_app(Tool::Paint); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); + harness.run_steps(3); + + harness.get_by_role_and_label(Role::ComboBox, "No Tiling").click(); + harness.run_steps(3); + harness.get_by_label("H and V Tiling").click(); + harness.run_steps(3); + + assert!(harness.state().session.tool.stencil.as_ref().is_some_and(|stencil| stencil.tile)); +} + +/// The Paint tool's stencil turns like the Projection tool's #[test] fn s_shift_left_drag_turns_the_stencil_in_snapped_steps_without_painting() { - let (mut harness, name) = projection_app(); + let (mut harness, name) = tool_app(Tool::Paint); texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); harness.run_steps(2); let from = harness.state().viewport_rect.center(); @@ -148,6 +182,26 @@ fn s_shift_left_drag_turns_the_stencil_in_snapped_steps_without_painting() { assert_eq!(history(&harness), steps); } +#[test] +fn the_stencil_hides_and_stays_put_while_the_quick_mask_is_painted() { + let (mut harness, name) = tool_app(Tool::Paint); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + harness.run_steps(REDRAW_FRAMES); + let from = harness.state().viewport_rect.center(); + let before = harness.state().session.tool.stencil.clone().unwrap(); + + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_none(), "quick mask strokes skip the stencil, so it has no tab"); + drag_holding(&mut harness, &[Key::S], Modifiers::SHIFT, from, vec2(100.0, -40.0)); + assert_eq!(harness.state().session.tool.stencil.clone().unwrap().rotation, before.rotation, "S + drag leaves it alone"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); + harness.run_steps(REDRAW_FRAMES); + + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_some(), "back when the quick mask is done"); +} + #[test] fn the_2d_view_says_projection_paints_in_3d_and_paints_nothing() { let (mut harness, name) = projection_app(); @@ -175,3 +229,39 @@ fn the_2d_view_says_projection_paints_in_3d_and_paints_nothing() { drag_holding(&mut harness, &[], Modifiers::NONE, from, vec2(60.0, 0.0)); assert!(history(&harness) > steps, "the paint tool paints there"); } + +#[test] +fn picking_another_stencil_releases_the_last_ones_overlay_texture() { + const OVERLAY_SIDE_PX: u32 = 1024; + let (mut harness, _) = tool_app(Tool::Paint); + let stencil_textures = |harness: &Harness<'_, TextureCraftApp>| { + harness + .ctx + .tex_manager() + .read() + .allocated() + .filter(|(_, texture)| texture.name.starts_with("stencil:")) + .fold((0, 0), |(count, bytes), (_, texture)| (count + 1, bytes + texture.size[0] * texture.size[1] * texture.bytes_per_pixel)) + }; + + // Switch among three full-size overlays + for gray in [64, 128, 192] { + let mut png = Vec::new(); + let image = image::RgbaImage::from_pixel(OVERLAY_SIDE_PX, OVERLAY_SIDE_PX, image::Rgba([gray, gray, gray, 255])); + image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes(&format!("stencil_{gray}.png"), png).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({ "image": name })).unwrap(); + harness.run_steps(REDRAW_FRAMES); + } + + let (count, bytes) = stencil_textures(&harness); + eprintln!("selected stencil retains {count} texture(s) and {bytes} texture bytes"); + assert_eq!(count, 1, "only the current stencil keeps its big texture"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"clear": true})).unwrap(); + harness.run_steps(REDRAW_FRAMES); + + let (count, bytes) = stencil_textures(&harness); + eprintln!("cleared stencil retains {count} texture(s) and {bytes} texture bytes"); + assert_eq!(count, 0, "clearing the stencil releases its overlay"); +} diff --git a/crates/ui-egui/tests/it/tool_material.rs b/crates/ui-egui/tests/it/tool_material.rs new file mode 100644 index 00000000..691edec0 --- /dev/null +++ b/crates/ui-egui/tests/it/tool_material.rs @@ -0,0 +1,100 @@ +//! A brush tool's Material section: the fill layer's channel pills, then a card per channel that is on with the value the brush paints + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::drag; +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, click_widget}; + +/// A second at 60 frames: the Material tab's jump scrolls with egui's scroll animation +const SCROLL_FRAMES: usize = 60; + +/// `tool`'s Properties scrolled to its Material section +fn material_section(tool: &str) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + click_widget(&mut harness, Role::Tab, "Material"); + harness.run_steps(SCROLL_FRAMES); + harness +} + +fn tool_value(harness: &Harness<'_, TextureCraftApp>, channel: Channel) -> [f32; 3] { + harness.state().session.tool.values.get(&channel).copied().unwrap_or(channel.default_value()) +} + +/// The top row of the card named `card` ("Metallic: Uniform"), if it shows +fn card_row(harness: &Harness<'_, TextureCraftApp>, card: &str) -> Option { + let named = |node: &egui_kittest::Node<'_>| node.accesskit_node().value().is_some_and(|value| value.starts_with(&format!("{card}: "))); + harness.query_all_by_role(Role::Label).find(named).map(|node| node.rect()) +} + +/// Clicks the widget with `role` and `label` on the top row of the card named `card` +fn click_in_card(harness: &mut Harness<'_, TextureCraftApp>, card: &str, role: Role, label: &str) { + let row = card_row(harness, card).unwrap(); + let at = harness.get_all_by_role_and_label(role, label).map(|node| node.rect().center()).find(|at| row.contains(*at)).unwrap(); + click_at(harness, at); +} + +#[test] +fn each_channel_that_is_on_gets_a_card_whose_reset_returns_the_channels_default() { + let mut harness = material_section("paint"); + assert!(harness.query_by_role_and_label(Role::Button, "Base color").is_some(), "Base color is a colour bar"); + for gray in ["Metallic", "Roughness", "Height"] { + assert!(harness.query_by_role_and_label(Role::Slider, gray).is_some(), "{gray} is a gray ramp"); + } + assert!(card_row(&harness, "Normal").is_some(), "Normal has a card"); + assert!(harness.query_by_role_and_label(Role::Slider, "Normal").is_none(), "the normal paints flat: no value to set"); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "metallic", "value": 0.8})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + click_in_card(&mut harness, "Metallic", Role::Button, "Restore defaults"); + + assert_eq!(tool_value(&harness, Channel::Metallic), Channel::Metallic.default_value(), "⟲ goes back to the channel's default"); + + click_widget(&mut harness, Role::CheckBox, "Metal"); + + assert!(!harness.state().session.tool.enabled.contains(&Channel::Metallic), "off in the strip, the brush stops painting Metallic"); + assert!(card_row(&harness, "Metallic").is_none(), "a channel that is off has no card"); +} + +#[test] +fn a_click_on_a_ramp_sets_the_value_the_brush_paints() { + let mut harness = material_section("paint"); + let before = tool_value(&harness, Channel::Roughness); + harness.get_by_role_and_label(Role::Slider, "Roughness").scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + let track = harness.get_by_role_and_label(Role::Slider, "Roughness").rect(); + + drag(&mut harness, track.center(), egui::pos2(track.right() - SLIDER_END_INSET, track.center().y)); + + assert!(tool_value(&harness, Channel::Roughness)[0] > before[0], "dragged toward the ramp's white end the brush paints rougher"); +} + +#[test] +fn the_eraser_picks_its_channels_without_value_cards() { + let harness = material_section("eraser"); + assert!(harness.query_by_role_and_label(Role::CheckBox, "Color").is_some(), "the channel strip"); + assert!(harness.query_by_role_and_label(Role::Button, "Base color").is_none(), "the eraser paints no colour"); + assert!(harness.query_by_role_and_label(Role::Slider, "Roughness").is_none()); +} + +#[test] +fn a_channel_cards_name_is_not_read_as_unavailable() { + let harness = material_section("paint"); + let named = |node: &egui_kittest::Node<'_>| node.accesskit_node().value().is_some_and(|value| value.starts_with("Metallic: ")); + let card = harness.query_all_by_role(Role::Label).find(named).unwrap(); + + assert!(!card.accesskit_node().is_disabled(), "the card's reset and value row answer, so its name must not read as unavailable"); +} diff --git a/crates/ui-egui/tests/it/toolbar.rs b/crates/ui-egui/tests/it/toolbar.rs index c9271888..9c1b1adf 100644 --- a/crates/ui-egui/tests/it/toolbar.rs +++ b/crates/ui-egui/tests/it/toolbar.rs @@ -6,6 +6,8 @@ use texturecraft_engine::{Session, Tool}; use texturecraft_ui_egui::state::{Mode, ViewLayout}; use texturecraft_ui_egui::{TextureCraftApp, theme, toolbar}; +use crate::DRAG_STEP_FRAMES; + fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> { let session = Session::new_project("Toolbar", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); let context = eframe::CreationContext::_new_kittest(egui::Context::default()); @@ -24,12 +26,17 @@ fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> } fn size_label(harness: &Harness<'_, TextureCraftApp>) -> (egui::Pos2, egui::Rect) { + bar_label(harness, "Size") +} + +/// Where the top bar paints the slider label `label`, and that text's clip +fn bar_label(harness: &Harness<'_, TextureCraftApp>, label: &str) -> (egui::Pos2, egui::Rect) { harness .output() .shapes .iter() .find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == "Size" => Some((text.pos, shape.clip_rect)), + egui::Shape::Text(text) if text.galley.text() == label => Some((text.pos, shape.clip_rect)), _ => None, }) .unwrap() @@ -88,6 +95,34 @@ fn arrows_and_wheel_scroll_without_changing_the_brush() { assert_eq!(harness.state().session.tool.brush, brush); } +#[test] +fn the_spacing_slider_reaches_as_far_as_the_properties_one() { + // Wide enough that the bar shows Spacing without scrolling + const BAR_WIDTH: f32 = 1600.0; + // From the label's top left onto its text, which drags the value + const LABEL_GRAB_OFFSET: egui::Vec2 = egui::vec2(4.0, 8.0); + // Far enough right to pass the slider's end + const DRAG_PAST_END: f32 = 400.0; + // The top bar's old Spacing limit: 200 % of the diameter + const OLD_SPACING_LIMIT: f32 = 2.0; + + let mut harness = toolbar_harness(BAR_WIDTH, Tool::Paint); + let (label, _) = bar_label(&harness, "Spacing"); + let from = label + LABEL_GRAB_OFFSET; + let past_the_end = from + egui::vec2(DRAG_PAST_END, 0.0); + + harness.hover_at(from); + harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(DRAG_STEP_FRAMES); + harness.hover_at(past_the_end); + harness.run_steps(DRAG_STEP_FRAMES); + harness.event(egui::Event::PointerButton { pos: past_the_end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(DRAG_STEP_FRAMES); + + // Properties' Spacing goes to 1000 % of the diameter + assert!(harness.state().session.tool.brush.spacing > OLD_SPACING_LIMIT, "past the 200 % the top bar used to stop at"); +} + #[test] fn shorter_tools_and_wider_windows_remove_the_arrows() { let mut harness = toolbar_harness(700.0, Tool::Path); diff --git a/crates/ui-egui/tests/it/user_smart_mask.rs b/crates/ui-egui/tests/it/user_smart_mask.rs index 7547e74c..83f15b96 100644 --- a/crates/ui-egui/tests/it/user_smart_mask.rs +++ b/crates/ui-egui/tests/it/user_smart_mask.rs @@ -65,8 +65,8 @@ fn a_saved_smart_mask_is_listed_with_the_smart_masks_and_applies_to_the_selected let source = add_layer(&mut saved, "Source", true); let dir = std::env::temp_dir().join(format!("tc-ui-smart-mask-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("Stencil.tcmask"); - std::fs::write(&file, saved.smart_mask_bytes(source, "Stencil").unwrap()).unwrap(); + let file = dir.join("Zebra Saved.tcmask"); + std::fs::write(&file, saved.smart_mask_bytes(source, "Zebra Saved").unwrap()).unwrap(); let mut harness = harness(|_| {}); let target = harness.state().session.selected_layer().unwrap(); @@ -75,11 +75,12 @@ fn a_saved_smart_mask_is_listed_with_the_smart_masks_and_applies_to_the_selected harness.state_mut().ui.shelf_path = vec!["user".into()]; harness.state_mut().ui.shelf_tab = SMART_MATERIALS_TYPE; harness.run_steps(3); - assert!(harness.query_by_label_contains("Stencil").is_none(), "it is not a smart material"); + + assert!(harness.query_by_label_contains("Zebra Saved").is_none(), "it is not a smart material"); harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE; harness.run_steps(3); - harness.get_by_label_contains("Stencil").click(); + harness.get_by_label_contains("Zebra Saved").click(); harness.run_steps(3); std::fs::remove_dir_all(&dir).unwrap(); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index ae1e7c83..af529908 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -801,6 +801,7 @@ fn assets_pass_two_snapshots() { .with_pixels_per_point(1.0) // The system draws the pointer, not the app .with_render_cursor(false) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .wgpu() .build_eframe(|context| TextureCraftApp::new(context, session)); let app = harness.state_mut(); @@ -822,6 +823,7 @@ fn assets_pass_two_snapshots() { if MATERIALS.iter().filter(|material| material.smart).all(|material| thumbnails.material(&context, material.id).is_some()) { break; } + assert!(started.elapsed() < std::time::Duration::from_secs(120), "smart material thumbnails did not arrive"); std::thread::sleep(std::time::Duration::from_millis(20)); } @@ -864,6 +866,7 @@ fn assets_pass_two_snapshots() { // 05: the drag ghost over the layer stack (takes a material) and over Properties (doesn't) let viewport_right = harness.state().viewport_rect.max.x; let layer = harness.get_all_by_role(Role::ListItem).find(|row| row.rect().min.x > viewport_right).expect("a layer row").rect().center(); + // Properties fills the right column under the layer stack, in the window's lower part let properties = egui::pos2(layer.x, harness.ctx.content_rect().height() * PROPERTIES_HEIGHT_SHARE); let tile = harness.get_all_by_label("Gold Dirty").next().unwrap().rect().center(); @@ -2404,7 +2407,8 @@ fn folder_mask_snapshots() { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.props_tab = texturecraft_ui_egui::state::PropsTab::Material; + harness.run_steps(6); + harness.get_by_role_and_label(egui::Role::Tab, "Grayscale").click(); harness.run_steps(6); save(&mut harness, &output_dir, "foldermask-white"); if std::env::var_os("TC_UI_THEMES").is_some() { @@ -3446,6 +3450,188 @@ fn sheet_scroll_end_snapshots() { save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); } +/// The paint tool's Properties: the Brush tab with every section open and scrolled down, its presets, pen button and Alignment list mid-use, the Alpha tab with its picker open, the Material tab with a pill hovered, a stencil on the Projection tool, a mask's Grayscale tab, the right-click popup, and the Clone and Eraser tools' tabs; `TC_UI_THEMES` set adds the dark and light themes +#[test] +#[ignore] +fn paint_tool_properties_snapshots() { + use egui::{Event, Modifiers, PointerButton}; + use serde_json::json; + use texturecraft_engine::core::Channel; + use texturecraft_engine::execute; + use texturecraft_engine::paint::{BrushAlpha, BrushSettings}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let stripes = image::RgbaImage::from_fn(64, 64, |x, _| { + let value = if (x / 8) % 2 == 0 { 230 } else { 40 }; + image::Rgba([value, value, value, 255]) + }); + let mut bytes = Vec::new(); + stripes.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let image = session.import_resource_bytes("stripes.png", bytes).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "paint"})).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.set_render_cursor(false); + harness.run_steps(6); + save(&mut harness, &output_dir, "paint-brush"); + + // The top preview follows the brush and the paint: one picture per brush + let default_brush = harness.state().session.tool.brush.clone(); + let default_values = harness.state().session.tool.values.clone(); + let brushes = [ + ("dotted-red", BrushSettings { size: 0.06, hardness: 1.0, spacing: 1.6, ..default_brush.clone() }, [0.8, 0.05, 0.04], 0.0, 0.5), + ("soft-blue-metal", BrushSettings { size: 0.12, hardness: 0.0, flow: 0.35, ..default_brush.clone() }, [0.1, 0.3, 0.9], 1.0, 0.2), + ( + "star-jitter-green", + BrushSettings { + size: 0.08, + alpha: BrushAlpha::Star, + spacing: 0.9, + follow_path: true, + jitter_size: 0.5, + jitter_angle: 0.3, + jitter_position: 0.6, + ..default_brush.clone() + }, + [0.1, 0.6, 0.15], + 0.0, + 0.8, + ), + ]; + for (name, brush, base_color, metallic, roughness) in brushes { + let tool = &mut harness.state_mut().session.tool; + tool.brush = brush; + tool.values.insert(Channel::BaseColor, base_color); + tool.values.insert(Channel::Metallic, [metallic; 3]); + tool.values.insert(Channel::Roughness, [roughness; 3]); + save(&mut harness, &output_dir, &format!("paint-preview-{name}")); + } + let tool = &mut harness.state_mut().session.tool; + tool.brush = default_brush; + tool.values = default_values; + + // The top bar has labels of the same names: Properties is the rightmost + let in_properties = |harness: &Harness<'_, TextureCraftApp>, label: &str| { + harness.get_all_by_label(label).map(|node| node.rect().center()).max_by(|a, b| a.x.total_cmp(&b.x)).unwrap() + }; + + harness.get_all_by_label("Particles").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); + harness.run_steps(3); + let at = in_properties(&harness, "Particles"); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + + let themes = std::env::var_os("TC_UI_THEMES").is_some(); + let shoot = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { + save(harness, &output_dir, name); + if themes { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(harness, &output_dir, &format!("{name}-{theme}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + }; + let hover = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + let at = harness.get_by_role_and_label(role, label).rect().center(); + harness.hover_at(at); + harness.run_steps(40); + }; + let open = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + harness.get_by_role_and_label(role, label).scroll_to_me(); + harness.run_steps(6); + harness.get_by_role_and_label(role, label).click(); + harness.run_steps(6); + }; + let close = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + }; + harness.get_by_label_contains("Brush presets").scroll_to_me(); + harness.run_steps(3); + shoot(&mut harness, "paint-brush-open"); + open(&mut harness, egui::Role::Button, "Brush presets"); + shoot(&mut harness, "paint-presets-open"); + close(&mut harness); + hover(&mut harness, egui::Role::CheckBox, "Size pen pressure"); + shoot(&mut harness, "paint-size-pen-hover"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Size pen pressure").click(); + harness.run_steps(6); + shoot(&mut harness, "paint-size-pen-off"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Size pen pressure").click(); + harness.run_steps(4); + open(&mut harness, egui::Role::ComboBox, "Tangent | Wrap"); + shoot(&mut harness, "paint-alignment-open"); + close(&mut harness); + harness.get_all_by_label("Particles").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); + harness.run_steps(6); + shoot(&mut harness, "paint-brush-scrolled"); + + let tab = |harness: &mut Harness<'_, TextureCraftApp>, tab: &str, name: &str| { + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::Tab, tab).click(); + harness.run_steps(6); + shoot(harness, name); + }; + tab(&mut harness, "Brush", "paint-brush-top"); + tab(&mut harness, "Alpha", "paint-alpha"); + open(&mut harness, egui::Role::ComboBox, "Round"); + let star = + harness.query_all_by_role_and_label(egui::Role::ListBoxOption, "Star").map(|node| node.rect()).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap(); + harness.hover_at(star.center()); + harness.run_steps(6); + shoot(&mut harness, "paint-alpha-picker"); + close(&mut harness); + tab(&mut harness, "Material", "paint-material"); + hover(&mut harness, egui::Role::CheckBox, "Height"); + shoot(&mut harness, "paint-material-pill-hover"); + + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "eraser"})).unwrap(); + tab(&mut harness, "Material", "eraser-material"); + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "clone"})).unwrap(); + tab(&mut harness, "Brush", "clone-brush"); + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "projection"})).unwrap(); + execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": image})).unwrap(); + tab(&mut harness, "Stencil", "projection-stencil"); + execute(&mut harness.state_mut().session, "tool.stencil", &json!({"rotation": 15.0, "center": [0.1, -0.05]})).unwrap(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::ComboBox, "No Tiling").click(); + harness.run_steps(4); + shoot(&mut harness, "projection-stencil-tiling-open"); + harness.get_by_label("H and V Tiling").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "projection-stencil-tiled"); + execute(&mut harness.state_mut().session, "tool.stencil", &json!({"clear": true})).unwrap(); + + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "paint"})).unwrap(); + let layer = harness.state().session.selected_layer().map(|id| id.0); + execute(&mut harness.state_mut().session, "mask.add.black", &json!({"layer": layer})).unwrap(); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap(); + tab(&mut harness, "Grayscale", "mask-grayscale"); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": "content"})).unwrap(); + + harness.get_by_role_and_label(egui::Role::Tab, "Brush").click(); + harness.run_steps(4); + let at = harness.state().viewport_rect.center() - egui::vec2(150.0, 250.0); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + harness.run_steps(6); + shoot(&mut harness, "paint-popup"); +} + /// The Export textures window on each tab at its mocks' size; TC_SNAPSHOT_THEME=medium (default), dark or light #[test] #[ignore] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8233c5a7..9c65e129 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -170,7 +170,13 @@ sampling at the source point. Changing `cloneAligned` forgets the offset of earl procedural Round alpha: 100 is a circle, 0 a square), `alphaContrast` (1..8, 1 leaves the values alone) and `alphaInvert` (swaps paint and no paint inside the stamp square). They apply to procedural, library and imported alphas alike and are returned by `tool.brush` with the other -values. The alpha's rotation is the brush `angle`. +values. The alpha's rotation is the brush `angle`. The Projection settings of the Brush section go +through `tool.brush` too and come back with it: `angleFade` (`[from, to]` in degrees, 0..90: with +`backfaceCulling` on, faces turned further than `from` from the view fade out until `to`), +`screenSpace` (Size Space Viewport: the size follows the view instead of the object) and +`stampDepth` (0.05..4). `sizePressure` (default `true`) lets pen pressure shrink the size towards +`minSize`. Setting `sizePressure` to `false` removes pen-pressure scaling. In 3D, `jitterSize` +still varies stamp size independently. Bake mode applies an edit in Common Settings or Mesh Map Settings to the texture sets sharing that group's settings: Common Settings, and each map's settings, are shared by any set of texture sets @@ -813,7 +819,7 @@ operation returns a busy error and can be retried. | `material.link.saveSource` | `{layer?, path}`: the original linked source with its `.mcmat`, `.mcraft` or `.sbs` extension | For a 1024-pixel texture set, TextureCraft requests `materialcraft-cli export source.mcmat maps --profile maps --size 1024x1024` with repeated `--set` and `--input` arguments. It discovers the published image inputs through `info` when the texture set supplies mesh maps. The desktop worker decodes the returned maps before installing the fill at its original drop target. The executable is resolved from -`$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH` +`$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else in a `MaterialCraft` folder beside TextureCraft's own folder (the launcher's layout), else on `PATH` (the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`, `worldNormal`, `normal`, `height`, `id`, `bentNormal`, `opacity`, `colorMap`, `worldDirection`; @@ -854,7 +860,10 @@ steps or an object with an optional input and output (paths relative to the curr } ``` -The CLI is a console program and never opens a window; `render` needs a GPU or software adapter. +The CLI is a console program and never opens a window; `render` needs a GPU or software adapter, unless it path +traces (`--samples`). Like the desktop app, it takes the high-performance GPU; `WGPU_ADAPTER_NAME` +(part of the adapter's name or backend) or `WGPU_POWER_PREF` (`high`, `low` or `none`) picks another. +`WGPU_BACKEND` narrows the list first, so a name on a backend it leaves out matches nothing. `texturecraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md) (command-line conventions); `texturecraft-cli --help` and ` --help` are the reference for every flag. diff --git a/docs/features.md b/docs/features.md index e112294e..f5ad6061 100644 --- a/docs/features.md +++ b/docs/features.md @@ -16,8 +16,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **18 brush presets** (basic, wear and grunge, details) in the shelf's Brushes tab set the stroke and keep the size. The Brush section's **Brush presets** popover (and the shelf) also keeps your own: save the current brush, click to use it, rename, replace or delete it. -- **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the - stencil), polygon fill (triangle, UV island or the whole mesh), **path** (Shift+click places a corner point for hard edges) and **lasso fill**, a +- **Tools:** paint, eraser, **projection** (paints an image's colors), a **stencil** every brush tool + paints through (its gray masks the stroke; hold S to move, turn and scale it; painting the quick mask, + or in the 2D UV view with any tool but projection, ignores the stencil), polygon fill (triangle, UV island or the whole mesh), **path** (Shift+click places a corner point for hard edges) and **lasso fill**, a **particle brush**, **smudge**, **clone** (V + click sets the source, marked in the 3D and 2D views; an Aligned option keeps or restarts the offset per stroke), material picker, Shift+click straight lines (Ctrl+Shift+click snaps them to 15 degree steps), and painting directly in the **2D UV view**. diff --git a/docs/nightly-signing-policy.example.json b/docs/nightly-signing-policy.example.json index 99924a91..1e4070e7 100644 --- a/docs/nightly-signing-policy.example.json +++ b/docs/nightly-signing-policy.example.json @@ -42,7 +42,15 @@ "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", "trust": { "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" - } + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] }, "macos-aarch64": { "unsigned_artifact_name": "nightly-unsigned-macos-aarch64",