From 2eeadf2d71fe7c1110f1263762a08897c761d038 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:59 +0000 Subject: [PATCH 1/6] Filters: the filter library and its maths (blur, bevel, glow, drop shadow, baked lighting, gradients, shape filters) --- crates/compose/src/distance_envelope.rs | 64 + crates/compose/src/environment_sh.rs | 194 +++ crates/compose/src/environment_sky.rs | 164 +++ crates/compose/src/soft_box.rs | 30 + crates/compose/src/warp_source_sample.rs | 59 + crates/compose/src/warp_texel.rs | 76 ++ crates/core/src/color_match.rs | 116 ++ crates/core/src/ramp_curve.rs | 38 + crates/core/src/source_warp.rs | 135 ++ crates/core/src/stylized_shading.rs | 193 +++ crates/core/src/unit_value.rs | 33 + crates/core/src/warp_source.rs | 64 + crates/engine/src/filter_lib.rs | 1131 ++++++++++++++--- crates/engine/src/stylized_lighting_params.rs | 99 ++ crates/engine/tests/it/filter_stylize.rs | 242 ++++ crates/engine/tests/it/filter_support.rs | 47 + 16 files changed, 2529 insertions(+), 156 deletions(-) create mode 100644 crates/compose/src/distance_envelope.rs create mode 100644 crates/compose/src/environment_sh.rs create mode 100644 crates/compose/src/environment_sky.rs create mode 100644 crates/compose/src/soft_box.rs create mode 100644 crates/compose/src/warp_source_sample.rs create mode 100644 crates/compose/src/warp_texel.rs create mode 100644 crates/core/src/color_match.rs create mode 100644 crates/core/src/ramp_curve.rs create mode 100644 crates/core/src/source_warp.rs create mode 100644 crates/core/src/stylized_shading.rs create mode 100644 crates/core/src/unit_value.rs create mode 100644 crates/core/src/warp_source.rs create mode 100644 crates/engine/src/stylized_lighting_params.rs create mode 100644 crates/engine/tests/it/filter_stylize.rs diff --git a/crates/compose/src/distance_envelope.rs b/crates/compose/src/distance_envelope.rs new file mode 100644 index 00000000..d78ea341 --- /dev/null +++ b/crates/compose/src/distance_envelope.rs @@ -0,0 +1,64 @@ +//! The lower envelope of parabolas that turns a line of squared distances into each place's squared distance to the nearest feature + +/// The lower envelope of the parabolas over a line of squared distances, which gives each place's squared distance to the nearest feature along it and the line before +#[derive(Default)] +pub(crate) struct DistanceEnvelope { + /// The parabolas still lowest somewhere: their vertex and where their stretch begins + parabolas: Vec<(usize, f64)>, + /// The line as it was + heights: Vec, +} + +impl DistanceEnvelope { + /// Replace `line` with each place's squared distance to the nearest feature + pub(crate) fn lower(&mut self, line: &mut [f32]) { + self.heights.clear(); + self.heights.extend_from_slice(line); + self.parabolas.clear(); + let heights = &self.heights; + + // In f64, where squared places and their sums stay exact past 4096 texels and a wide line cannot overflow a 32-bit usize + let lifted = |at: usize| f64::from(heights.get(at).copied().unwrap_or(f32::MAX)) + at as f64 * at as f64; + for at in 0..heights.len() { + let mut start = f64::NEG_INFINITY; + while let Some(&(vertex, from)) = self.parabolas.last() { + let crossing = (lifted(at) - lifted(vertex)) / (2.0 * (at - vertex) as f64); + if crossing <= from { + self.parabolas.pop(); + } else { + start = crossing; + break; + } + } + self.parabolas.push((at, start)); + } + + let mut current = 0; + for (at, out) in line.iter_mut().enumerate() { + while self.parabolas.get(current + 1).is_some_and(|(_, from)| *from < at as f64) { + current += 1; + } + if let Some(&(vertex, _)) = self.parabolas.get(current) { + *out = (at as f32 - vertex as f32).powi(2) + heights.get(vertex).copied().unwrap_or(f32::MAX); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Past 4096 texels a squared place is no longer exact in f32: two close features at the end of a wide line still each read 0 + #[test] + fn close_features_far_along_a_wide_line_stay_exact() { + const FAR: f32 = 4.0e8; + let mut line = vec![FAR; 10_000]; + line[9_950] = 1.0; + line[9_951] = 0.0; + + DistanceEnvelope::default().lower(&mut line); + + assert_eq!(line[9_949..9_954], [2.0, 1.0, 0.0, 1.0, 4.0]); + } +} diff --git a/crates/compose/src/environment_sh.rs b/crates/compose/src/environment_sh.rs new file mode 100644 index 00000000..30a2d847 --- /dev/null +++ b/crates/compose/src/environment_sh.rs @@ -0,0 +1,194 @@ +//! The viewport environment's diffuse light as spherical harmonics, worked out once per environment, and Baked Lighting Environment's shading with it + +use std::sync::{Arc, Mutex}; + +use texturecraft_core::project::DisplaySettings; +use texturecraft_core::{Channel, DIELECTRIC_REFLECTANCE, finite_unit, mix3}; +use texturecraft_geom::glam::Vec3; + +use crate::environment_sky::{VIEWPORT_WIDTH, dir_of, environment_linear, radiance, sh_basis, sh9_averaged}; +use crate::store::{ImageRes, ImageStore}; + +/// The diffuse light of the viewport environment and the turn the viewport gives it +pub struct EnvironmentSh { + coefficients: [[f32; 3]; 9], + /// The viewport's environment rotation (radians) + rotation: f32, +} + +/// The environment the last coefficients were worked out for: a built-in by name, or an imported image (held, so it is not a different image at the same address) +type CacheEntry = (String, Option>, Arc<[[f32; 3]; 9]>); + +static CACHE: Mutex> = Mutex::new(None); + +impl EnvironmentSh { + /// The diffuse light of the environment `display` shows (an imported image from `images`), worked out once per environment + pub fn of(display: &DisplaySettings, images: &ImageStore) -> EnvironmentSh { + let image = display.environment_resource().and_then(|name| images.get(name)).cloned(); + let same = |entry: &CacheEntry| match (&entry.1, &image) { + (Some(held), Some(image)) => Arc::ptr_eq(held, image), + (None, None) => entry.0 == display.environment, + _ => false, + }; + let rotation = display.env_rotation.to_radians(); + + let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2.clone()); + if let Some(coefficients) = cached { + return EnvironmentSh { coefficients: *coefficients, rotation }; + } + + // Worked out with the cache unlocked: the averaging runs on the thread pool, where a worker holding the lock could take another tile's task that waits for it + let coefficients = match &image { + Some(image) => image_sh(image), + None => built_in_sh(&display.environment), + }; + *CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image, Arc::new(coefficients))); + EnvironmentSh { coefficients, rotation } + } + + /// The diffuse light reaching a surface facing world direction `normal` with the environment turned `horizontal` and tilted `vertical` (radians) past the viewport's turn + pub fn irradiance(&self, normal: Vec3, horizontal: f32, vertical: f32) -> Vec3 { + let (sin_tilt, cos_tilt) = vertical.sin_cos(); + let tilted = Vec3::new(normal.x, cos_tilt * normal.y - sin_tilt * normal.z, sin_tilt * normal.y + cos_tilt * normal.z); + + // Turned as the viewport turns its environment + let (sin_turn, cos_turn) = (self.rotation + horizontal).sin_cos(); + let direction = Vec3::new(cos_turn * tilted.x - sin_turn * tilted.z, tilted.y, sin_turn * tilted.x + cos_turn * tilted.z); + let light = sh_basis(direction).iter().zip(&self.coefficients).fold(Vec3::ZERO, |sum, (basis, coefficient)| sum + Vec3::from(*coefficient) * *basis); + light.max(Vec3::ZERO) + } + + /// Baked Lighting Environment's lit base color: linear `albedo`, its metal read from `channels` (straight values by [`Channel::index`]), in `light` (the environment's diffuse light at the surface, exposure applied), darkened by ambient occlusion `ao` by `[diffuse, specular]` occlusion. The viewer looks straight at the surface, so what it reflects is the light around the normal + pub fn shade(albedo: [f32; 3], light: Vec3, ao: f32, [diffuse_occlusion, specular_occlusion]: [f32; 2], channels: &[[f32; 3]]) -> [f32; 3] { + let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 }; + let metal = finite_unit(channels.get(Channel::Metallic.index()).map_or(0.0, |m| m[0])); + let f0 = mix3([DIELECTRIC_REFLECTANCE; 3], albedo, metal); + let diffuse = 1.0 + (ao - 1.0) * finite_unit(diffuse_occlusion); + let specular = 1.0 + (ao - 1.0) * finite_unit(specular_occlusion); + let incoming = light.to_array(); + std::array::from_fn(|k| finite_unit(albedo[k] * (1.0 - metal) * incoming[k] * diffuse + f0[k] * incoming[k] * specular)) + } +} + +/// The coefficients of built-in environment `name` as the viewport works them out: drawn at its width, then averaged +fn built_in_sh(name: &str) -> [[f32; 3]; 9] { + let (width, height) = (VIEWPORT_WIDTH, VIEWPORT_WIDTH / 2); + sh9_averaged(width, height, |x, y| radiance(name, dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32))) +} + +/// The coefficients of an imported equirect image, every texel averaged in as the viewport does +fn image_sh(image: &ImageRes) -> [[f32; 3]; 9] { + let linear = |v: f32| environment_linear(v, image.srgb); + sh9_averaged(image.width, image.height, |x, y| { + let texel = image.rgba.get((y as usize) * image.width as usize + x as usize).copied().unwrap_or([0.0; 4]); + Vec3::new(linear(texel[0]), linear(texel[1]), linear(texel[2])) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A uniform environment lights every direction alike, whatever the turn; brighter skies light more + #[test] + fn a_uniform_image_lights_every_way_alike() { + let image = |v: f32| ImageRes { width: 32, height: 16, rgba: vec![[v, v, v, 1.0]; 32 * 16], srgb: false, mips: Default::default() }; + let sh = EnvironmentSh { coefficients: image_sh(&image(0.5)), rotation: 1.0 }; + for normal in [Vec3::Y, Vec3::X, Vec3::NEG_Y, Vec3::new(0.6, 0.0, 0.8)] { + let light = sh.irradiance(normal, 0.3, 0.7); + assert!((light - Vec3::splat(0.5)).abs().max_element() < 0.02, "{normal}: {light}"); + } + } + + /// The studio's key light is up and to one side: a surface facing up gets more light than one facing down, and turning the environment moves the light around + #[test] + fn a_built_in_lights_by_where_the_surface_faces_and_turns() { + let display = DisplaySettings { environment: "Studio Soft".into(), ..DisplaySettings::default() }; + let sh = EnvironmentSh::of(&display, &ImageStore::default()); + assert!(sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum() > 2.0 * sh.irradiance(Vec3::NEG_Y, 0.0, 0.0).element_sum()); + let side = Vec3::new(0.7, 0.0, 0.7).normalize(); + let (here, turned) = (sh.irradiance(side, 0.0, 0.0), sh.irradiance(side, std::f32::consts::PI, 0.0)); + assert!((here - turned).abs().max_element() > 0.05, "{here} vs {turned}"); + let night = EnvironmentSh::of(&DisplaySettings { environment: "Night".into(), ..DisplaySettings::default() }, &ImageStore::default()); + assert!(night.irradiance(Vec3::Y, 0.0, 0.0).element_sum() < sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum(), "the cache follows the environment"); + } + + /// Tiles on the thread pool that ask for a new light finish: the light is worked out with the cache unlocked, so a worker that steals another tile while it waits for its share of the averaging never waits for its own lock + #[test] + fn tiles_asking_for_a_new_light_on_the_thread_pool_finish() { + use rayon::prelude::*; + + const WORKERS: usize = 8; + const TILES: usize = 1024; + // One tile in so many asks for the light; the rest finish at once, so their workers are free to steal the averaging's work + const LIT_EVERY: usize = 128; + const ROUNDS: usize = 20; + const PATIENCE: std::time::Duration = std::time::Duration::from_secs(60); + + let (done, finished) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let Ok(pool) = rayon::ThreadPoolBuilder::new().num_threads(WORKERS).build() else { return }; + pool.install(|| { + for round in 0..ROUNDS { + // Each round shows another environment, so its first tile misses the cache + let environment = if round % 2 == 0 { "Sunset" } else { "Night" }; + let display = DisplaySettings { environment: environment.into(), ..DisplaySettings::default() }; + (0..TILES).into_par_iter().filter(|tile| tile % LIT_EVERY == 0).for_each(|_| { + EnvironmentSh::of(&display, &ImageStore::default()); + }); + } + }); + let _ = done.send(()); + }); + assert!(finished.recv_timeout(PATIENCE).is_ok(), "the tiles deadlocked on the cache"); + } + + /// Diffuse occlusion darkens non-metals by the ambient occlusion; metals take their light from the reflections, which only specular occlusion darkens + #[test] + fn occlusion_darkens_the_diffuse_and_the_reflections_apart() { + let mut channels: Vec<[f32; 3]> = Channel::ALL.iter().map(|c| c.default_value()).collect(); + let light = Vec3::splat(1.0); + let dielectric = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0]; + assert!(dielectric([1.0, 0.0]) < dielectric([0.0, 0.0]) * 0.5); + channels[Channel::Metallic.index()] = [1.0; 3]; + let metal = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0]; + assert_eq!(metal([1.0, 0.0]), metal([0.0, 0.0])); + assert!(metal([0.0, 1.0]) < metal([0.0, 0.0]) * 0.5); + } + + /// The coefficients of `radiance` read at every place of a fine grid, the integral the averaged ones must match + fn fine_sh(width: u32, radiance: impl Fn(Vec3) -> Vec3) -> [[f32; 3]; 9] { + let height = width / 2; + crate::environment_sky::sh9(width, height, |x, y| radiance(dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32))) + } + + /// Sunset's sun is smaller than a texel of a coarse grid: averaging the viewport's drawing keeps its light, as the viewport does + #[test] + fn a_small_sun_lights_as_the_viewport_shows_it() { + let display = DisplaySettings { environment: "Sunset".into(), ..DisplaySettings::default() }; + + let baked = EnvironmentSh::of(&display, &ImageStore::default()).coefficients; + let fine = fine_sh(1024, |direction| radiance("Sunset", direction)); + + for (baked, fine) in baked.iter().zip(&fine) { + for (baked, fine) in baked.iter().zip(fine) { + assert!((baked - fine).abs() < 0.02, "{baked} vs {fine}"); + } + } + } + + /// An imported image's small bright patch counts though it falls between the texels a coarse read would take + #[test] + fn a_small_bright_patch_of_an_image_counts() { + const BRIGHT: f32 = 500.0; + let (width, height) = (1024u32, 512u32); + let patch = |x: u32, y: u32| (97..101).contains(&x) && (193..197).contains(&y); + let rgba = (0..width * height).map(|i| if patch(i % width, i / width) { [BRIGHT, BRIGHT, BRIGHT, 1.0] } else { [0.0, 0.0, 0.0, 1.0] }).collect(); + let image = ImageRes { width, height, rgba, srgb: false, mips: Default::default() }; + + let averaged = image_sh(&image)[0][0]; + let exact = crate::environment_sky::sh9(width, height, |x, y| if patch(x, y) { Vec3::splat(BRIGHT) } else { Vec3::ZERO })[0][0]; + + assert!(exact > 0.01 && (averaged - exact).abs() < exact * 0.05, "{averaged} vs {exact}"); + } +} diff --git a/crates/compose/src/environment_sky.rs b/crates/compose/src/environment_sky.rs new file mode 100644 index 00000000..0c37ccd2 --- /dev/null +++ b/crates/compose/src/environment_sky.rs @@ -0,0 +1,164 @@ +//! The built-in environments (drawn in code, no image assets) and their diffuse light as spherical harmonics, for the viewport and Baked Lighting Environment + +use std::f32::consts::{PI, TAU}; + +use rayon::prelude::*; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::soft_box::SoftBox; + +/// The width the viewport draws a built-in environment at (half as tall) +pub const VIEWPORT_WIDTH: u32 = 512; + +/// The width an environment is box-averaged down to before its diffuse light is worked out: averaging keeps a sun smaller than a texel +const SH_WIDTH: u32 = 128; + +/// The brightest radiance the viewport keeps of an imported environment (it stores half floats) +const HALF_FLOAT_MAX: f32 = 65_000.0; + +/// The irradiance convolution factor of each SH band (the cosine lobe's π, 2π/3 and π/4), one per coefficient +const COSINE_LOBE_BANDS: [f32; 9] = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0]; + +/// The linear radiance of a component `v` of an imported environment's texel (sRGB-encoded when `srgb`): not a number is 0, capped at the half-float range, sRGB at 1 +pub fn environment_linear(v: f32, srgb: bool) -> f32 { + let v = if v.is_finite() { v.clamp(0.0, HALF_FLOAT_MAX) } else { 0.0 }; + if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v } +} + +/// The direction at equirect place `u = φ / 2π`, `v = θ / π`: `(sin θ cos φ, cos θ, sin θ sin φ)`, row 0 straight up +pub fn dir_of(u: f32, v: f32) -> Vec3 { + let (theta, phi) = (v * PI, u * TAU); + Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin()) +} + +/// The equirect place of direction `d` +pub fn uv_of(d: Vec3) -> Vec2 { + let phi = d.z.atan2(d.x); + Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI) +} + +/// Smoothstep of `t` over 0..1 +pub(crate) fn smooth(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// How fast a sky turns from its horizon to its zenith and to its ground (powers of the height; under 1 turns early) +const ZENITH_FALLOFF: f32 = 0.6; +const GROUND_FALLOFF: f32 = 0.25; + +/// A sky blending `horizon` up to `zenith` and down to `ground` +fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 { + if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(ZENITH_FALLOFF)) } else { horizon.lerp(ground, (-d.y).powf(GROUND_FALLOFF)) } +} + +/// The Sunset sun's disc: the cosine of its edge from the centre, the width of its soft rim, and its brightness +const SUN_EDGE_COS: f32 = 0.9985; +const SUN_EDGE_WIDTH: f32 = 0.0012; +const SUN_RADIANCE: f32 = 120.0; + +/// The light a built-in environment `name` sends from direction `d` (unknown names give the default studio) +pub fn radiance(name: &str, d: Vec3) -> Vec3 { + match name { + "Studio Contrast" => { + let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01)); + base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(d) + + SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(d) + } + "Overcast" => { + let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15)); + base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(d) + } + "Sunset" => { + let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05)); + let sun_dir = dir_of(0.12, 0.47); + let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE; + base + Vec3::new(1.0, 0.6, 0.3) * sun + } + "Warehouse" => { + let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06)); + for k in 0..6 { + c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }.eval(d); + } + c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(d) + } + "Night" => { + let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005)); + base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(d) + + SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(d) + } + + // "Studio Soft" (default) + _ => { + let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07)); + base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(d) + + SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(d) + + SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(d) + } + } +} + +/// The 9 real spherical-harmonics basis functions at unit direction `d` (the standard band 0..2 constants) +pub fn sh_basis(d: Vec3) -> [f32; 9] { + let (x, y, z) = (d.x, d.y, d.z); + [ + 0.282_095, + 0.488_603 * y, + 0.488_603 * z, + 0.488_603 * x, + 1.092_548 * x * y, + 1.092_548 * y * z, + 0.315_392 * (3.0 * z * z - 1.0), + 1.092_548 * x * z, + 0.546_274 * (x * x - y * y), + ] +} + +/// Diffuse irradiance as 9 SH coefficients of the equirect image `width` x `height` whose texels `radiance` gives (already convolved with the cosine lobe and divided by π, so `Σ c·Y(n)` times albedo is the diffuse radiance) +pub fn sh9(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3) -> [[f32; 3]; 9] { + let (w, h) = (width.max(1), height.max(1)); + let mut sums = [Vec3::ZERO; 9]; + for y in 0..h { + let theta = PI * (y as f32 + 0.5) / h as f32; + let solid_angle = (TAU / w as f32) * (PI / h as f32) * theta.sin(); + for x in 0..w { + let direction = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32); + + // No firefly clamp: the projection integrates, so a bright sun lights diffuse fully + let weighted = radiance(x, y) * solid_angle; + for (sum, basis) in sums.iter_mut().zip(sh_basis(direction)) { + *sum += weighted * basis; + } + } + } + std::array::from_fn(|k| (sums[k] * COSINE_LOBE_BANDS[k] / PI).to_array()) +} + +/// [`sh9`] of the equirect image `width` x `height` whose texels `radiance` gives, box-halved while wider than [`SH_WIDTH`] (an odd last row or column is dropped, as the viewport drops it) +pub fn sh9_averaged(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3 + Sync) -> [[f32; 3]; 9] { + if width <= SH_WIDTH { + return sh9(width, height, radiance); + } + + let mut image = half(width, height, radiance); + while image.0 > SH_WIDTH { + let (w, h, data) = ℑ + image = half(*w, *h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO)); + } + let (w, h, data) = image; + sh9(w, h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO)) +} + +/// The equirect image `width` x `height` whose texels `texel` gives, box-downsampled by 2 (wrapping around, clamped at the poles): its width, height and texels +pub fn half(width: u32, height: u32, texel: impl Fn(u32, u32) -> Vec3 + Sync) -> (u32, u32, Vec) { + let (w, h) = ((width / 2).max(1), (height / 2).max(1)); + let get = |x: u32, y: u32| texel(x % width.max(1), y.min(height.saturating_sub(1))); + let mut data = vec![Vec3::ZERO; (w * h) as usize]; + data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| { + for (x, texel) in row.iter_mut().enumerate() { + let (sx, sy) = (x as u32 * 2, y as u32 * 2); + *texel = (get(sx, sy) + get(sx + 1, sy) + get(sx, sy + 1) + get(sx + 1, sy + 1)) * 0.25; + } + }); + (w, h, data) +} diff --git a/crates/compose/src/soft_box.rs b/crates/compose/src/soft_box.rs new file mode 100644 index 00000000..b1fba4f7 --- /dev/null +++ b/crates/compose/src/soft_box.rs @@ -0,0 +1,30 @@ +//! A soft rectangular light of the built-in environments + +use texturecraft_geom::glam::Vec3; + +/// A soft rectangular light: azimuth/elevation center (degrees), half sizes (degrees) +pub(crate) struct SoftBox { + pub azimuth: f32, + pub elevation: f32, + pub half_width: f32, + pub half_height: f32, + pub color: Vec3, +} + +/// Where the light starts to fade, as a share of its half size, and over how much of it +const EDGE_FADE_START: f32 = 0.8; +const EDGE_FADE_WIDTH: f32 = 0.4; + +impl SoftBox { + /// The light the box sends along direction `d` + pub fn eval(&self, d: Vec3) -> Vec3 { + let elevation = d.y.clamp(-1.0, 1.0).asin().to_degrees(); + let azimuth = d.z.atan2(d.x).to_degrees(); + + // The azimuth difference wrapped to -180..180 degrees + let azimuth_step = ((azimuth - self.azimuth + 540.0).rem_euclid(360.0)) - 180.0; + let (x, y) = (azimuth_step.abs() / self.half_width, (elevation - self.elevation).abs() / self.half_height); + let edge = |t: f32| 1.0 - crate::environment_sky::smooth((t - EDGE_FADE_START) / EDGE_FADE_WIDTH); + self.color * edge(x) * edge(y) + } +} diff --git a/crates/compose/src/warp_source_sample.rs b/crates/compose/src/warp_source_sample.rs new file mode 100644 index 00000000..9ab36aad --- /dev/null +++ b/crates/compose/src/warp_source_sample.rs @@ -0,0 +1,59 @@ +//! A warp's or slope blur's source as read around one texel + +use texturecraft_core::{WarpSource, WarpSourceMode, lum}; + +use crate::eval::{MIN_ALPHA, texel_noise}; +use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample}; + +/// A warp's or slope blur's source at one texel's neighbourhood +pub(crate) struct WarpSourceSample<'a> { + source: &'a WarpSource, + /// The default noise's seed + seed: u32, + res: u32, + comps: usize, + sample: Sample<'a>, + input: Input<'a>, + /// Half the texels the source is blurred across, worked out once per texel + half_blur: f32, +} + +impl<'a> WarpSourceSample<'a> { + /// `source` (default noise seeded `seed`) at `res` texels across a UV tile, reading `comps` values a texel through `sample`, or Custom Input through `input` + pub(crate) fn new(source: &'a WarpSource, seed: u32, (res, comps): (u32, usize), (sample, input): (Sample<'a>, Input<'a>)) -> Self { + WarpSourceSample { source, seed, res, comps, sample, input, half_blur: source.blur_texels(res) / 2.0 } + } + + /// The source at texel position `(x, y)` after its blur, Balance and Contrast + pub(crate) fn at(&self, x: f32, y: f32) -> f32 { + let half = self.half_blur; + let value = if half > 0.0 { + let corners = [(-half, -half), (half, -half), (-half, half), (half, half)]; + let (sum, count) = corners.iter().filter_map(|(dx, dy)| self.raw(x + dx, y + dy)).fold((0.0f32, 0u8), |(sum, count), read| (sum + read, count + 1)); + if count == 0 { WarpSource::MID_GRAY } else { sum / f32::from(count) } + } else { + self.raw(x, y).unwrap_or(WarpSource::MID_GRAY) + }; + self.source.shape(value) + } + + /// The source at texel position `(x, y)` before it is shaped; None where the values it filters cover nothing + fn raw(&self, x: f32, y: f32) -> Option { + match self.source.mode { + WarpSourceMode::DefaultNoise => Some(WarpSource::stretch_noise(texel_noise(x, y, [0.0; 2], self.res, self.source.noise_scale(), self.seed))), + WarpSourceMode::PreviousInput => { + let mut read = [0.0f32; 5]; + (self.sample)(x, y, &mut read); + match (self.comps, read) { + // Content stays premultiplied by its own coverage + (4, [r, g, b, alpha, _]) if alpha > MIN_ALPHA => Some(lum([r / alpha, g / alpha, b / alpha])), + (1, [value, .., weight]) if weight > MIN_READ_WEIGHT => Some(value / weight), + _ => None, + } + } + + // Mid gray (its default) moves nothing + WarpSourceMode::CustomNoise => (self.input)(x, y), + } + } +} diff --git a/crates/compose/src/warp_texel.rs b/crates/compose/src/warp_texel.rs new file mode 100644 index 00000000..0866e9ed --- /dev/null +++ b/crates/compose/src/warp_texel.rs @@ -0,0 +1,76 @@ +//! What a Warp filter reads for one texel: its source, then the moves its mode makes + +use texturecraft_core::{SourceWarp, WarpBlending, WarpMode}; + +use crate::eval::direction; +use crate::warp_source_sample::WarpSourceSample; + +/// Bilinear sample at an absolute texel position into an accumulator (components, then weight), as [`crate::eval`]'s gather reads +pub(crate) type Sample<'a> = &'a dyn Fn(f32, f32, &mut [f32; 5]); + +/// The filter's Custom Noise image input at an absolute texel position; None where the values it filters cover nothing +pub(crate) type Input<'a> = &'a dyn Fn(f32, f32) -> Option; + +/// A read weighing less than this covers nothing +pub(crate) const MIN_READ_WEIGHT: f32 = 1e-6; + +/// Warp `warp` at texel `(x, y)` (`res` texels across a UV tile, `comps` values a texel) into `acc`: where its source sends it, or those reads blended +pub(crate) fn warp_texel(warp: &SourceWarp, (x, y): (f32, f32), (res, comps): (u32, usize), acc: &mut [f32; 5], (sample, input): (Sample<'_>, Input<'_>)) { + let source = WarpSourceSample::new(&warp.source, warp.seed, (res, comps), (sample, input)); + let reach = warp.move_texels(res); + if warp.mode == WarpMode::Warp { + let probe = SourceWarp::probe_texels(res); + let rise = [source.at(x + probe, y) - source.at(x - probe, y), source.at(x, y + probe) - source.at(x, y - probe)]; + let [dx, dy] = warp.slope_move(rise, res); + sample(x + dx, y + dy, acc); + return; + } + + let directions = warp.angles().map(direction); + let moved = |(at_x, at_y): (f32, f32), [dx, dy]: [f32; 2]| { + let along = SourceWarp::amount(source.at(at_x, at_y)) * reach; + (at_x + dx * along, at_y + dy * along) + }; + match (warp.mode, warp.blending) { + (WarpMode::MultiDirectional, WarpBlending::Chain) => { + let (end_x, end_y) = directions.fold((x, y), moved); + sample(end_x, end_y, acc); + } + (WarpMode::MultiDirectional, WarpBlending::Max | WarpBlending::Min) => { + let reads = directions.map(|direction| moved((x, y), direction)); + keep_extreme_read(reads, warp.blending == WarpBlending::Max, comps, acc, sample); + } + + // One direction, or the average of several: the reads add up in `acc` + _ => { + for direction in directions { + let (at_x, at_y) = moved((x, y), direction); + sample(at_x, at_y, acc); + } + } + } +} + +/// Keeps in `acc` the largest (or smallest) of the reads at `positions`, component by component; reads that cover nothing are skipped +pub(crate) fn keep_extreme_read(positions: impl Iterator, larger: bool, comps: usize, acc: &mut [f32; 5], sample: Sample<'_>) { + let mut picked: Option<[f32; 5]> = None; + for (at_x, at_y) in positions { + let mut read = [0.0f32; 5]; + sample(at_x, at_y, &mut read); + if read[4] <= MIN_READ_WEIGHT { + continue; + } + + let read = read.map(|component| component / read[4]); + picked = Some(match picked { + Some(so_far) => std::array::from_fn(|k| if larger { so_far[k].max(read[k]) } else { so_far[k].min(read[k]) }), + None => read, + }); + } + + if let Some(picked) = picked { + let kept = comps.min(4); + acc[..kept].copy_from_slice(&picked[..kept]); + acc[4] = 1.0; + } +} diff --git a/crates/core/src/color_match.rs b/crates/core/src/color_match.rs new file mode 100644 index 00000000..c945bf72 --- /dev/null +++ b/crates/core/src/color_match.rs @@ -0,0 +1,116 @@ +//! Color Match's settings: the colors moved so a source color lands on a target color + +use serde::{Deserialize, Serialize}; + +use crate::{SourceColorMode, TargetColorMode, oklab}; + +/// A Color Match filter: every color moved, in OKLab, by the step from its source color to its target color +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ColorMatch { + /// Source Color Mode: the color moved from + pub source_mode: SourceColorMode, + /// Source Color (linear), read in Source Color Mode Parameter + pub source_color: [f32; 3], + /// Target Color Mode: the color moved to + pub target_mode: TargetColorMode, + /// Target Color (linear), read in Target Color Mode Parameter + pub target_color: [f32; 3], + /// Custom Color Variation: the colors keep at most Hue, Chroma and Luma of their difference from the source + pub custom_variation: bool, + /// Hue (degrees): how far a hue may stay from the target's + pub hue: f32, + /// Chroma: how far a chroma may stay from the target's + pub chroma: f32, + /// Luma: how far a lightness may stay from the target's + pub luma: f32, +} + +impl ColorMatch { + /// Mid gray (128 sRGB) in linear + const GRAY: [f32; 3] = [0.215_860_5; 3]; + + /// The most Hue keeps (degrees): two hues are at most half a turn apart + pub const MAX_HUE_DEGREES: f32 = 180.0; + /// The most Chroma keeps (OKLab chroma) + pub const MAX_CHROMA: f32 = 1.0; + /// The most Luma keeps (OKLab lightness, 0..1) + pub const MAX_LUMA: f32 = 1.0; + + /// A new Color Match: the texture's mean moves to the target and every texel keeps all of its difference from the mean (Color Variation at its widest), so the layer keeps its pattern until a variation is lowered + pub const LIBRARY: ColorMatch = ColorMatch { + source_mode: SourceColorMode::Average, + source_color: Self::GRAY, + target_mode: TargetColorMode::Parameter, + target_color: Self::GRAY, + custom_variation: true, + hue: Self::MAX_HUE_DEGREES, + chroma: Self::MAX_CHROMA, + luma: Self::MAX_LUMA, + }; + + /// Linear `color` moved by the step from `source` to `target`; without Custom Color Variation it keeps all of its difference from the source, with it at most Hue, Chroma and Luma of it (all 0: the target color itself). Hostile values give the color back + pub fn apply(&self, color: [f32; 3], source: [f32; 3], target: [f32; 3]) -> [f32; 3] { + let [lightness, a, b] = oklab::from_linear(color.map(|v| v.max(0.0))); + let [source_lightness, source_a, source_b] = oklab::from_linear(source.map(|v| v.max(0.0))); + let [target_lightness, target_a, target_b] = oklab::from_linear(target.map(|v| v.max(0.0))); + + let moved = if self.custom_variation { + let limit = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 }; + let keep = |difference: f32, max: f32| difference.clamp(-max, max); + let (chroma, hue) = (a.hypot(b), b.atan2(a)); + let (source_chroma, source_hue) = (source_a.hypot(source_b), source_b.atan2(source_a)); + let (target_chroma, target_hue) = (target_a.hypot(target_b), target_b.atan2(target_a)); + let turn = (hue - source_hue + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI; + let out_lightness = target_lightness + keep(lightness - source_lightness, limit(self.luma, Self::MAX_LUMA)); + let out_chroma = (target_chroma + keep(chroma - source_chroma, limit(self.chroma, Self::MAX_CHROMA))).max(0.0); + let out_hue = target_hue + keep(turn, limit(self.hue, Self::MAX_HUE_DEGREES).to_radians()); + [out_lightness, out_chroma * out_hue.cos(), out_chroma * out_hue.sin()] + } else { + [target_lightness + lightness - source_lightness, target_a + a - source_a, target_b + b - source_b] + }; + + let out = oklab::to_linear(moved); + if out.iter().all(|v| v.is_finite()) { out.map(|v| v.clamp(0.0, 1.0)) } else { color } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn near(a: [f32; 3], b: [f32; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3) + } + + #[test] + fn the_source_color_lands_on_the_target_and_variation_is_kept_as_asked() { + let red = [0.6, 0.1, 0.05]; + let blue = [0.05, 0.1, 0.6]; + let lighter_red = [0.8, 0.2, 0.1]; + let lightness = |color: [f32; 3]| oklab::from_linear(color)[0]; + + // Without Custom Color Variation every difference from the source is kept + let keep_all = ColorMatch { custom_variation: false, ..ColorMatch::LIBRARY }; + let moved = keep_all.apply(lighter_red, red, blue); + assert!(near(keep_all.apply(red, red, blue), blue), "the source itself becomes the target"); + assert!(lightness(moved) > lightness(blue) + 0.05, "a lighter texel stays lighter than the target"); + assert!(moved[2] > moved[0], "and turns blue"); + + // Custom Color Variation at 0: every color is the target + let flat = ColorMatch { luma: 0.0, chroma: 0.0, hue: 0.0, ..ColorMatch::LIBRARY }; + assert!(near(flat.apply(lighter_red, red, blue), blue)); + + // A new Color Match's widest limits keep the lightness difference again + let library = ColorMatch::LIBRARY; + assert!(lightness(library.apply(lighter_red, red, blue)) > lightness(blue) + 0.05, "a new Color Match keeps the variation"); + + // Luma alone: the lightness difference kept up to it + let luma_only = ColorMatch { luma: 0.02, ..flat }; + let limited = lightness(luma_only.apply(lighter_red, red, blue)) - lightness(blue); + assert!((limited - 0.02).abs() < 1e-3, "lightness kept up to Luma: {limited}"); + + let hostile = ColorMatch { hue: f32::NAN, chroma: f32::INFINITY, luma: -1.0, ..flat }; + assert!(hostile.apply([f32::NAN, 0.5, 0.5], red, blue).iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))); + } +} diff --git a/crates/core/src/ramp_curve.rs b/crates/core/src/ramp_curve.rs new file mode 100644 index 00000000..101a90ed --- /dev/null +++ b/crates/core/src/ramp_curve.rs @@ -0,0 +1,38 @@ +//! The bend Bevel Smooth's ramp and Mask Outline's fade take, sanitised once per filter + +/// A Curve Shape of 1 raises a ramp to the power ¼ and −1 to the power 4, 0 leaves it straight +const CURVE_SHAPE_BASE: f32 = 4.0; + +/// A 0..1 ramp moved by an offset, then raised to a power: below 0 the shape rises later, above 0 sooner +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RampCurve { + offset: f32, + exponent: f32, +} + +impl RampCurve { + /// The curve moving a ramp by `offset` and bending it by `shape` (each −1..1, 0 when not finite) + pub fn new(offset: f32, shape: f32) -> RampCurve { + let bounded = |x: f32| if x.is_finite() { x.clamp(-1.0, 1.0) } else { 0.0 }; + RampCurve { offset: bounded(offset), exponent: CURVE_SHAPE_BASE.powf(-bounded(shape)) } + } + + /// Ramp value `along` (0..1) moved and bent + pub fn apply(self, along: f32) -> f32 { + (along + self.offset).clamp(0.0, 1.0).powf(self.exponent) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_shape_bends_and_the_offset_moves() { + assert_eq!(RampCurve::new(0.0, 0.0).apply(0.3), 0.3, "straight"); + assert_eq!(RampCurve::new(0.0, 1.0).apply(0.0625), 0.5, "the power ¼ rises sooner"); + assert_eq!(RampCurve::new(0.0, -1.0).apply(0.5), 0.0625, "the power 4 rises later"); + assert_eq!(RampCurve::new(0.25, 0.0).apply(0.5), 0.75); + assert_eq!(RampCurve::new(f32::NAN, f32::INFINITY), RampCurve::new(0.0, 0.0), "hostile settings leave it straight"); + } +} diff --git a/crates/core/src/source_warp.rs b/crates/core/src/source_warp.rs new file mode 100644 index 00000000..4891f752 --- /dev/null +++ b/crates/core/src/source_warp.rs @@ -0,0 +1,135 @@ +//! The Warp filter's settings and the moves it makes + +use serde::{Deserialize, Serialize}; + +use crate::{WarpBlending, WarpMode, WarpSource, WarpSourceMode, finite_unit}; + +/// Texels read from where a source sends them: along its slope, along one direction, or along several blended +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceWarp { + /// The default noise's seed + pub seed: u32, + pub mode: WarpMode, + /// How far a texel moves at most, a share of the UV tile before the divider (0..1) + pub intensity: f32, + /// Divides `intensity` (1, 10, 100 or 1000) for fine moves + pub divider: u16, + /// The direction (degrees) of the directional modes, the first of several in Multi Directional Warp + pub angle: f32, + /// How many directions a Multi Directional Warp spreads evenly around the circle (1, 2 or 4) + pub directions: u8, + pub blending: WarpBlending, + pub source: WarpSource, +} + +impl SourceWarp { + /// The Warp filter as the library adds it + pub const LIBRARY: SourceWarp = SourceWarp { + seed: 0, + mode: WarpMode::Warp, + intensity: 0.1, + divider: 10, + angle: 0.0, + directions: 4, + blending: WarpBlending::Average, + source: WarpSource::LIBRARY, + }; + + /// The direction counts a Multi Directional Warp takes + pub const DIRECTIONS: [u8; 3] = [1, 2, 4]; + + /// The share of the UV tile the source's slope is measured across, on each side of a texel + pub const PROBE_SHARE: f32 = 1.0 / 256.0; + + /// The source's slope (rise per UV tile) that moves a texel the whole way in Warp mode + pub const FULL_SLOPE: f32 = 4.0; + + /// How many texels a texel moves at most at `res` texels across a UV tile + pub fn move_texels(&self, res: u32) -> f32 { + move_texels(self.intensity, self.divider, res) + } + + /// How many texels each side of a texel Warp mode measures the source's slope across + pub fn probe_texels(res: u32) -> f32 { + (res as f32 * Self::PROBE_SHARE).max(1.0) + } + + /// The directions (degrees) texels move along: none in Warp mode (the slope decides), the Angle, or Directions spread from it + pub fn angles(&self) -> impl Iterator + Clone + use<> { + let angle = if self.angle.is_finite() { self.angle } else { 0.0 }; + let count = match self.mode { + WarpMode::Warp => 0, + WarpMode::Directional => 1, + WarpMode::MultiDirectional if Self::DIRECTIONS.contains(&self.directions) => self.directions, + WarpMode::MultiDirectional => 1, + }; + (0..count).map(move |index| angle + 360.0 * f32::from(index) / f32::from(count)) + } + + /// How many texels around a texel the warp reads at `res` texels across a UV tile: its moves (chained ones add up) and where it reads its source + pub fn reach(&self, res: u32) -> f32 { + let chained = self.mode == WarpMode::MultiDirectional && self.blending == WarpBlending::Chain; + let moves = self.move_texels(res) * if chained { self.angles().count().max(1) as f32 } else { 1.0 }; + if self.source.mode != WarpSourceMode::PreviousInput { + return moves; + } + + let probe = if self.mode == WarpMode::Warp { Self::probe_texels(res) } else { 0.0 }; + moves + probe + self.source.blur_texels(res) * std::f32::consts::FRAC_1_SQRT_2 + } + + /// How far (−1..1 of the move) a source value moves a texel along a direction: backwards below mid gray, forwards above + pub fn amount(value: f32) -> f32 { + if value.is_finite() { (2.0 * value - 1.0).clamp(-1.0, 1.0) } else { 0.0 } + } + + /// Warp mode's move (texels) from how much the source rises across [`SourceWarp::probe_texels`] each side of a texel along x and y + pub fn slope_move(&self, rise: [f32; 2], res: u32) -> [f32; 2] { + let across = 2.0 * Self::probe_texels(res) / res.max(1) as f32; + let [x, y] = rise.map(|rise| if rise.is_finite() { rise / across / Self::FULL_SLOPE } else { 0.0 }); + let length = x.hypot(y); + let fit = if length > 1.0 { 1.0 / length } else { 1.0 }; + let reach = self.move_texels(res); + [x * fit * reach, y * fit * reach] + } +} + +/// How many texels Intensity over Divider moves at `res` texels across a UV tile (Warp's and Blur Slope's) +pub(crate) fn move_texels(intensity: f32, divider: u16, res: u32) -> f32 { + finite_unit(intensity) / f32::from(divider.max(1)) * res as f32 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn moves_follow_intensity_mode_and_directions() { + let warp = SourceWarp::LIBRARY; + assert!((warp.move_texels(2048) - 20.48).abs() < 1e-3, "0.1 ÷ 10 of the tile"); + assert_eq!(warp.angles().count(), 0); + let directional = SourceWarp { mode: WarpMode::Directional, angle: 30.0, ..warp }; + assert_eq!(directional.angles().collect::>(), vec![30.0]); + let multi = SourceWarp { mode: WarpMode::MultiDirectional, angle: 10.0, ..warp }; + assert_eq!(multi.angles().collect::>(), vec![10.0, 100.0, 190.0, 280.0]); + let chained = SourceWarp { blending: WarpBlending::Chain, ..multi }; + assert!((chained.reach(2048) - 4.0 * 20.48).abs() < 1e-3, "four moves one after the other"); + let input = SourceWarp { source: WarpSource { mode: WarpSourceMode::PreviousInput, ..WarpSource::LIBRARY }, ..warp }; + assert!((input.reach(2048) - (20.48 + 8.0)).abs() < 1e-3, "plus where it measures the slope"); + assert_eq!((SourceWarp::amount(0.0), SourceWarp::amount(0.5), SourceWarp::amount(1.0)), (-1.0, 0.0, 1.0)); + } + + #[test] + fn slope_moves_saturate_and_hostile_settings_stay_in_range() { + let warp = SourceWarp::LIBRARY; + let gentle = warp.slope_move([0.01, 0.0], 2048); + assert!(gentle[0] > 0.0 && gentle[0] < warp.move_texels(2048), "{gentle:?}"); + let steep = warp.slope_move([1.0, 1.0], 2048); + assert!((steep[0].hypot(steep[1]) - warp.move_texels(2048)).abs() < 1e-3, "a cliff moves the whole way, no further: {steep:?}"); + let hostile = SourceWarp { intensity: f32::NAN, angle: f32::INFINITY, directions: 9, divider: 0, mode: WarpMode::MultiDirectional, ..warp }; + assert_eq!((hostile.move_texels(2048), hostile.angles().collect::>()), (0.0, vec![0.0])); + assert_eq!(hostile.slope_move([f32::NAN, 1.0], 2048)[0], 0.0); + assert_eq!(SourceWarp { intensity: 9.0, divider: 1, ..warp }.move_texels(1024), 1024.0); + } +} diff --git a/crates/core/src/stylized_shading.rs b/crates/core/src/stylized_shading.rs new file mode 100644 index 00000000..57d4d5ca --- /dev/null +++ b/crates/core/src/stylized_shading.rs @@ -0,0 +1,193 @@ +//! Baked Lighting Stylized's settings worked out once per filter, and the shading of each texel with them + +use std::f32::consts::PI; + +use crate::lighting_output::LightingOutput; +use crate::stylized_lighting::StylizedLighting; +use crate::sun_and_sky::SunAndSky; +use crate::{Channel, finite_unit, mix3}; + +/// The curvature map's value on a flat surface (below it concave, above convex) +pub const FLAT_CURVATURE: f32 = 0.5; + +/// The scale that takes either side of [`FLAT_CURVATURE`] to 0..1 +const CURVATURE_SIDE_SCALE: f32 = 2.0; + +/// The Cook-Torrance denominator 4·(n·l)·(n·v) with the viewer straight on (n·v = 1), n·l cancelled by the light's own facing +const COOK_TORRANCE_DENOMINATOR: f32 = 4.0; + +/// The roughness highlights never go below (a mirror would be a single texel of infinite light) +const MIN_ROUGHNESS: f32 = 0.08; + +/// The smoothness below which cavity and edges switch on as a step +const MIN_SMOOTHNESS: f32 = 1e-3; + +/// A [`StylizedLighting`] under its [`SunAndSky`], with every value that depends only on the settings worked out once +#[derive(Clone, Debug, PartialEq)] +pub struct StylizedShading { + /// The sun, Light 1 and Light 2: the unit direction toward each, its intensity and its color + lights: [([f32; 3], f32, [f32; 3]); 3], + sky_intensity: f32, + sky_color: [f32; 3], + horizon_color: [f32; 3], + ground_color: [f32; 3], + /// Diffuse AO, Specular AO, Diffuse Cavity, Specular Cavity and Edges Intensity, each 0..1 + diffuse_ao: f32, + specular_ao: f32, + diffuse_cavity: f32, + specular_cavity: f32, + edges_intensity: f32, + cavity_smoothness: f32, + edges_smoothness: f32, + specular_glossiness: bool, + output: LightingOutput, + /// The reflectance of non-metals at normal incidence, 0..1 + dielectric_reflectance: f32, + /// The relief the baked height gives the lit normals; None lights the mesh's own normals + relief: Option, +} + +impl StylizedShading { + /// `settings` lit by `light` + pub fn new(settings: &StylizedLighting, light: SunAndSky) -> StylizedShading { + let sun = (light.sun.direction(), light.sun.intensity, settings.sun_color); + let [first, second] = settings.lights.map(|extra| (extra.direction(), extra.intensity, extra.color)); + StylizedShading { + lights: [sun, first, second], + sky_intensity: light.sky_intensity, + sky_color: settings.sky_color, + horizon_color: settings.horizon_color, + ground_color: settings.ground_color, + diffuse_ao: finite_unit(light.diffuse_ao), + specular_ao: finite_unit(settings.specular_ao), + diffuse_cavity: finite_unit(settings.diffuse_cavity), + specular_cavity: finite_unit(settings.specular_cavity), + edges_intensity: finite_unit(settings.edges_intensity), + cavity_smoothness: settings.cavity_smoothness, + edges_smoothness: settings.edges_smoothness, + specular_glossiness: settings.specular_glossiness, + output: settings.output, + dielectric_reflectance: finite_unit(settings.dielectric_reflectance), + relief: (!settings.mesh_only).then_some(settings.height_to_normal), + } + } + + /// The relief the baked height gives the normals it lights (Height to Normal Intensity); None lights the mesh's own normals + pub fn relief(&self) -> Option { + self.relief + } + + /// The ambient light reaching a surface facing `normal` from the sky, horizon and ground + fn ambient(&self, normal: [f32; 3]) -> [f32; 3] { + let up = normal[1].clamp(-1.0, 1.0); + if up >= 0.0 { mix3(self.horizon_color, self.sky_color, up) } else { mix3(self.horizon_color, self.ground_color, -up) } + } + + /// The lit base color of linear `albedo` facing `normal` (world space, unit) with baked ambient occlusion `ao` and curvature `curvature` ([`FLAT_CURVATURE`] flat), its material read from `channels` (straight values by [`Channel::index`]); the viewer looks straight at the surface + pub fn shade(&self, albedo: [f32; 3], normal: [f32; 3], [ao, curvature]: [f32; 2], channels: &[[f32; 3]]) -> [f32; 3] { + let channel = |channel: Channel| channels.get(channel.index()).copied().unwrap_or_else(|| channel.default_value()); + let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 }; + let curvature = if curvature.is_finite() { curvature } else { FLAT_CURVATURE }; + let cavity = fade_in((FLAT_CURVATURE - curvature) * CURVATURE_SIDE_SCALE, self.cavity_smoothness); + let edge = fade_in((curvature - FLAT_CURVATURE) * CURVATURE_SIDE_SCALE, self.edges_smoothness); + + let (roughness, f0, diffuse_albedo) = if self.specular_glossiness { + (1.0 - finite_unit(channel(Channel::Glossiness)[0]), channel(Channel::Specular).map(finite_unit), albedo) + } else { + let metal = finite_unit(channel(Channel::Metallic)[0]); + let f0 = mix3([self.dielectric_reflectance; 3], albedo, metal); + + // Without highlights the whole base color is lit, as Baked Lighting did + let kept = if self.output.specular() { 1.0 - metal } else { 1.0 }; + (finite_unit(channel(Channel::Roughness)[0]), f0, albedo.map(|x| x * kept)) + }; + let roughness = roughness.max(MIN_ROUGHNESS); + let sky = self.ambient(normal); + + let diffuse_ao = 1.0 + (ao - 1.0) * self.diffuse_ao; + let specular_ao = 1.0 + (ao - 1.0) * self.specular_ao; + let diffuse_cavity = 1.0 - cavity * self.diffuse_cavity; + let specular_cavity = 1.0 - cavity * self.specular_cavity; + + let mut diffuse = sky.map(|sky_light| sky_light * self.sky_intensity * diffuse_ao * diffuse_cavity); + let mut specular = [0.0f32; 3]; + for &(direction, intensity, color) in &self.lights { + let facing = dot(normal, direction); + if facing <= 0.0 || intensity <= 0.0 { + continue; + } + + let half = normalize([normal[0] + direction[0], normal[1] + direction[1], normal[2] + direction[2]]); + let normal_dot_half = dot(normal, half).max(0.0); + let highlight = ggx(normal_dot_half, roughness) / COOK_TORRANCE_DENOMINATOR * facing * specular_cavity; + for (((diffuse, specular), color), f0) in diffuse.iter_mut().zip(&mut specular).zip(color).zip(f0) { + *diffuse += color * intensity * facing * diffuse_cavity; + *specular += color * intensity * highlight * schlick(f0, normal_dot_half); + } + } + for ((specular, f0), sky_light) in specular.iter_mut().zip(f0).zip(sky) { + *specular += f0 * sky_light * self.sky_intensity * specular_ao * specular_cavity; + } + + std::array::from_fn(|k| { + let lit = if self.output.diffuse() { diffuse_albedo[k] * diffuse[k] } else { 0.0 }; + let shine = if self.output.specular() { specular[k] } else { 0.0 }; + let shaded = finite_unit(lit + shine); + finite_unit(shaded + (1.0 - shaded) * edge * self.edges_intensity) + }) + } +} + +/// `amount` (clamped 0..1) reaching full over `smoothness`: a step when it is about 0 or not a number +fn fade_in(amount: f32, smoothness: f32) -> f32 { + let amount = amount.clamp(0.0, 1.0); + if smoothness.is_nan() || smoothness <= MIN_SMOOTHNESS { + return if amount > 0.0 { 1.0 } else { 0.0 }; + } + + (amount / smoothness).min(1.0) +} + +/// The GGX distribution of microfacets facing `normal_dot_half` (the cosine between the normal and the half vector) at `roughness` +fn ggx(normal_dot_half: f32, roughness: f32) -> f32 { + let alpha_squared = (roughness * roughness).powi(2); + let denominator = normal_dot_half * normal_dot_half * (alpha_squared - 1.0) + 1.0; + alpha_squared / (PI * denominator * denominator) +} + +/// Schlick's Fresnel of reflectance `f0` at cosine `cos` +fn schlick(f0: f32, cos: f32) -> f32 { + f0 + (1.0 - f0) * (1.0 - cos.clamp(0.0, 1.0)).powi(5) +} + +fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// `v` at unit length; a vector too short to have a direction points up +fn normalize(v: [f32; 3]) -> [f32; 3] { + const MIN_LENGTH: f32 = 1e-6; + + let length = dot(v, v).sqrt(); + if length > MIN_LENGTH { v.map(|x| x / length) } else { [0.0, 1.0, 0.0] } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A smoothness that is not a number switches cavity and edges on as a step: a flat surface stays untouched + #[test] + fn a_nan_smoothness_fades_in_as_a_step() { + assert_eq!((fade_in(0.0, f32::NAN), fade_in(0.3, f32::NAN)), (0.0, 1.0)); + } + + /// The relief is the Height to Normal Intensity, unless the filter lights the mesh's own normals + #[test] + fn the_relief_follows_mesh_only() { + let light = SunAndSky { sun: StylizedLighting::PLAIN.lights[0], sky_intensity: 1.0, diffuse_ao: 0.0 }; + assert_eq!(StylizedShading::new(&StylizedLighting::PLAIN, light).relief(), None); + let detailed = StylizedLighting { mesh_only: false, height_to_normal: 0.7, ..StylizedLighting::PLAIN }; + assert_eq!(StylizedShading::new(&detailed, light).relief(), Some(0.7)); + } +} diff --git a/crates/core/src/unit_value.rs b/crates/core/src/unit_value.rs new file mode 100644 index 00000000..aed6e18e --- /dev/null +++ b/crates/core/src/unit_value.rs @@ -0,0 +1,33 @@ +//! Settings and values sanitised to the 0..1 range filters read them in + +/// A value at its threshold still counts when float rounding left it a step below (a white read back as 0.99999994) +const THRESHOLD_TOLERANCE: f32 = f32::EPSILON; + +/// `x` clamped to 0..1, 0 when not finite +pub fn finite_unit(x: f32) -> f32 { + if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 } +} + +/// Whether `value` reaches `threshold` (clamped to 0..1, `fallback` when not finite) +pub fn at_or_above_threshold(value: f32, threshold: f32, fallback: f32) -> bool { + let threshold = if threshold.is_finite() { threshold.clamp(0.0, 1.0) } else { fallback }; + value >= threshold - THRESHOLD_TOLERANCE +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn values_land_in_the_unit_range() { + assert_eq!([finite_unit(-2.0), finite_unit(0.25), finite_unit(7.0), finite_unit(f32::NAN), finite_unit(f32::INFINITY)], [0.0, 0.25, 1.0, 0.0, 0.0]); + } + + #[test] + fn a_threshold_counts_a_value_rounded_just_below_it() { + assert!(at_or_above_threshold(1.0 - f32::EPSILON / 2.0, 1.0, 0.5)); + assert!(!at_or_above_threshold(0.49, 0.5, 0.5)); + assert!(at_or_above_threshold(0.5, f32::NAN, 0.5), "a hostile threshold falls back"); + assert!(at_or_above_threshold(1.0, 9.0, 0.5), "a threshold past 1 is 1"); + } +} diff --git a/crates/core/src/warp_source.rs b/crates/core/src/warp_source.rs new file mode 100644 index 00000000..80ff4914 --- /dev/null +++ b/crates/core/src/warp_source.rs @@ -0,0 +1,64 @@ +//! The values a Warp's moves follow and how they are shaped first + +use serde::{Deserialize, Serialize}; + +use crate::WarpSourceMode; +use crate::gradient_input::{NEUTRAL_BALANCE, shape_gray}; + +/// A Warp's source: noise, the values it filters or an image, blurred, balanced and contrasted +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WarpSource { + pub mode: WarpSourceMode, + /// How widely the source is averaged first (0..1, up to [`WarpSource::BLUR_SHARE`] of the UV tile) + pub blur: f32, + /// Added to the source around 0.5 (0..1) + pub balance: f32, + /// Steepens the source around mid gray (0..1) + pub contrast: f32, + /// How many times the default noise repeats across a UV tile (0.01..16) + pub tiling: f32, +} + +impl WarpSource { + /// The source as the library's Warp starts with it + pub const LIBRARY: WarpSource = WarpSource { mode: WarpSourceMode::DefaultNoise, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, tiling: 1.0 }; + + /// Noise features across a UV tile at Source Tiling 1 + pub const NOISE_FEATURES: f32 = 4.0; + + /// The share of the UV tile a Source Blur of 1 averages over + pub const BLUR_SHARE: f32 = 1.0 / 16.0; + + /// Mid gray: the source value that moves nothing, and the noise's middle + pub const MID_GRAY: f32 = 0.5; + + /// How far noise is stretched from mid gray so it spans black to white + pub const NOISE_STRETCH: f32 = 1.5; + + /// The Tiling range + pub const TILING_MIN: f32 = 0.01; + pub const TILING_MAX: f32 = 16.0; + + /// Noise features per UV tile + pub fn noise_scale(&self) -> f32 { + let tiling = if self.tiling.is_finite() { self.tiling.clamp(Self::TILING_MIN, Self::TILING_MAX) } else { 1.0 }; + Self::NOISE_FEATURES * tiling + } + + /// How many texels across the source is averaged over at `res` texels across a UV tile + pub fn blur_texels(&self, res: u32) -> f32 { + let blur = if self.blur.is_finite() { self.blur.clamp(0.0, 1.0) } else { 0.0 }; + blur * Self::BLUR_SHARE * res as f32 + } + + /// Fractal noise `noise` (around mid gray) stretched to span 0..1 + pub fn stretch_noise(noise: f32) -> f32 { + if noise.is_finite() { (Self::MID_GRAY + (noise - Self::MID_GRAY) * Self::NOISE_STRETCH).clamp(0.0, 1.0) } else { Self::MID_GRAY } + } + + /// Source value `value` after Balance and Contrast + pub fn shape(&self, value: f32) -> f32 { + shape_gray(value, self.balance, self.contrast, false) + } +} diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index c424f839..b4a72c26 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -3,10 +3,18 @@ //! by id; `filter.list` lists them with their default parameters. use serde_json::{Value, json}; -use texturecraft_core::{Channel, EffectKind, Fill, Filter, Levels, Procedural, ProceduralKind, Projection, Source}; +use texturecraft_core::{ + AnisotropicKuwahara, Bevel, BevelBlur, BevelCorner, BevelDirection, BevelSmooth, Channel, ColorMatch, ConversionMode, CurvePreset, DirectionalDistance, + Effect, EffectKind, Fill, Filter, GradientInput, GrayscaleConversion, GrayscaleMode, HeightToNormal, HighpassSpace, LayerId, Levels, MaskOutline, Mirror, + MirrorCorner, MirrorMode, OutlinePosition, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PbrValidate, Procedural, ProceduralKind, Projection, SlopeBlending, + Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedLighting, TargetColorMode, ThresholdMode, TileTransform, ValidationMode, WarpBlending, + WarpMode, WarpSource, WarpSourceMode, +}; -use crate::commands::{CommandSpec, always, bad, color_of, color_param, f32p, u64p}; -use crate::{Result, cmd}; +use crate::commands::{CommandSpec, always, bad, boolp, color_of, color_param, f32p, has_layer, strp, u64p}; +use crate::filter_about::FilterAbout; +use crate::layer_cmds::FULL_TURN_DEGREES; +use crate::{Result, Session, cmd}; /// A filter of the library. #[derive(Clone, Copy, Debug)] @@ -20,6 +28,11 @@ pub struct FilterDef { } impl FilterDef { + /// What it does and the words it is found by (its Attributes) + pub fn about(&self) -> Option { + crate::filter_about::of(self.id) + } + /// Whether it builds a filter effect (levels and material finishes are effect types of their own) pub fn is_filter_effect(&self) -> bool { matches!(build(self.id, &Value::Null), Ok(EffectKind::Filter(_))) @@ -40,31 +53,47 @@ const fn def(id: &'static str, label: &'static str, group: &'static str, mask: b pub const FILTERS: &[FilterDef] = &[ def("hsl", "HSL Perceptive", "Adjustments", true), def("levels", "Levels", "Adjustments", true), - def("contrastLuminosity", "Contrast/Luminosity", "Adjustments", true), + def("contrastLuminosity", "Contrast Luminosity", "Adjustments", true), def("colorBalance", "Color Balance", "Adjustments", true), - def("gradientMap", "Gradient Map", "Adjustments", true), + def("colorCorrect", "Color Correct", "Adjustments", true), + def("gradientMap", "Gradient", "Adjustments", true), + def("gradientCurve", "Gradient Curve", "Adjustments", true), + def("gradientDynamic", "Gradient Dynamic", "Adjustments", true), def("posterize", "Posterize", "Adjustments", true), def("clamp", "Clamp", "Adjustments", true), + def("smoothstep", "Smoothstep", "Adjustments", true), + def("heightAdjust", "Height Adjust", "Adjustments", true), def("histogramScan", "Histogram Scan", "Adjustments", true), def("histogramRange", "Histogram Range", "Adjustments", true), def("histogramShift", "Histogram Shift", "Adjustments", true), def("invert", "Invert", "Adjustments", true), def("threshold", "Threshold", "Adjustments", true), - def("grayscale", "Grayscale", "Adjustments", false), + def("grayscale", "Grayscale Conversion", "Adjustments", true), def("edgeDetect", "Edge Detect", "Adjustments", true), def("normalInvert", "Normal Invert", "Adjustments", false), - def("bakedLighting", "Baked Lighting", "Adjustments", false), + def("bakedLighting", "Baked Lighting Stylized", "Adjustments", false), + def("bakedLightingEnvironment", "Baked Lighting Environment", "Adjustments", false), def("replaceColor", "Replace Color", "Adjustments", false), + def("pbrValidate", "PBR Validate (Metallic Roughness)", "Adjustments", false), + def("heightToNormal", "Height To Normal", "Adjustments", false), + def("colorMatch", "Color Match", "Adjustments", false), def("blur", "Blur", "Blur and sharpen", true), def("blurDirectional", "Blur Directional", "Blur and sharpen", true), - def("slopeBlur", "Slope Blur", "Blur and sharpen", true), + def("slopeBlur", "Blur Slope", "Blur and sharpen", true), def("sharpen", "Sharpen", "Blur and sharpen", true), - def("highPass", "High Pass", "Blur and sharpen", true), + def("highPass", "Highpass", "Blur and sharpen", true), + def("fxaa", "FXAA (Anti-aliasing)", "Blur and sharpen", true), + def("anisotropicKuwahara", "Anisotropic Kuwahara", "Blur and sharpen", true), def("bevel", "Bevel", "Blur and sharpen", true), + def("bevelSmooth", "Bevel Smooth", "Blur and sharpen", true), + def("directionalDistance", "Directional Distance", "Blur and sharpen", true), def("glow", "Glow", "Blur and sharpen", true), + def("dropShadow", "Drop Shadow", "Blur and sharpen", true), + def("maskOutline", "Mask Outline", "Blur and sharpen", true), def("warp", "Warp", "Distort", true), - def("warpDirectional", "Warp Directional", "Distort", true), - def("mosaic", "Mosaic", "Distort", true), + def("mosaic", "Pixelate", "Distort", true), + def("mirror", "Mirror", "Distort", true), + def("transform", "Transform", "Distort", true), def("matFinishGrind", "MatFinish Grind", "Material finish", false), def("matFinishRaw", "MatFinish Raw", "Material finish", false), def("matFinishSanded", "MatFinish Sanded", "Material finish", false), @@ -75,69 +104,264 @@ fn norm(s: &str) -> String { s.to_ascii_lowercase().replace([' ', '_', '-', '/'], "") } -/// The library filter `id` (case and separators ignored; labels work too). +/// The library filter `id` (case and separators ignored; labels work too). Directional Warp's former id and labels find Warp, whose mode it is now pub fn find(id: &str) -> Option<&'static FilterDef> { - let n = norm(id); - FILTERS.iter().find(|f| norm(f.id) == n || norm(f.label) == n) + let wanted = if is_directional_warp(id) { norm("warp") } else { norm(id) }; + FILTERS.iter().find(|def| norm(def.id) == wanted || norm(def.label) == wanted) +} + +/// Whether `id` names Directional Warp, a filter of its own before the warp modes (`warpDirectional`, "Warp Directional", "Directional Warp") +fn is_directional_warp(id: &str) -> bool { + matches!(norm(id).as_str(), "warpdirectional" | "directionalwarp") } pub fn specs() -> Vec { - vec![cmd!( - "filter.list", - "List filters", - [], - None, - "{} — the filter library: id, label, group, whether masks take it, default parameters", - always, - |_, _| Ok(Value::Array( - FILTERS - .iter() - .map(|f| json!({"id": f.id, "label": f.label, "group": f.group, "mask": f.mask, "defaults": build(f.id, &Value::Null).ok()})) - .collect() - )) - )] + vec![ + cmd!( + "effect.filter.restoreDefaults", + "Restore defaults", + [], + None, + "{effect?: filter effect id, default the selected effect} — its filter's parameters back to their defaults (name, channels and blending stay; a filter saved before its library replacement becomes that replacement, as the library adds it) in one undo step; no step when they are already; returns {changed}", + has_layer, + restore_defaults + ), + cmd!( + "filter.list", + "List filters", + [], + None, + "{} — the filter library: id, label, group, whether masks take it, default parameters, what it does (description) and its tags", + always, + |_, _| Ok(Value::Array(FILTERS.iter().map(listed).collect())) + ), + ] } -/// The effect for library filter `id` with its defaults, then the parameters in `p`. +/// `filter.list`'s entry for `def` +fn listed(def: &FilterDef) -> Value { + let about = def.about(); + json!({ + "id": def.id, + "label": def.label, + "group": def.group, + "mask": def.mask, + "defaults": build(def.id, &Value::Null).ok(), + "description": about.map(|about| about.description), + "tags": about.map(|about| about.tags), + }) +} + +/// The filter `effect.filter.restoreDefaults` works on: its id and the library defaults of the filter it is (None: an empty filter) +fn filter_defaults(s: &Session, p: &Value) -> Result<(LayerId, Option)> { + const CMD: &str = "effect.filter.restoreDefaults"; + let effect = crate::mask_cmds::effect_id(s, p, CMD)?; + let filter = match s.doc.project.effect(effect) { + Some((_, Effect { kind: EffectKind::Filter(filter), .. })) => filter, + Some(_) => return Err(bad(CMD, format!("effect {} is not a filter", effect.0))), + None => return Err(bad(CMD, format!("no effect {}", effect.0))), + }; + let defaults = match build(filter.label(), &Value::Null) { + Ok(EffectKind::Filter(defaults)) => Some(defaults), + _ => None, + }; + Ok((effect, defaults)) +} + +/// Puts a filter effect's parameters back to their library defaults in one undo step +fn restore_defaults(s: &mut Session, p: &Value) -> Result { + let (effect, defaults) = filter_defaults(s, p)?; + let current = s.doc.project.effect(effect).map(|(_, found)| &found.kind); + let Some(defaults) = defaults.filter(|defaults| !matches!(current, Some(EffectKind::Filter(filter)) if filter == defaults)) else { + return Ok(json!({"changed": false})); + }; + + s.edit("Restore defaults", |s| { + if let Some(edited) = s.doc.project.effect_mut(effect) { + edited.kind = EffectKind::Filter(defaults); + } + Ok(()) + })?; + Ok(json!({"changed": true})) +} + +/// A Color Correct tone that changes nothing: no contrast, no luminosity, saturation as it is +const NEUTRAL_TONE: [f32; 3] = [0.0, 0.0, 0.5]; + +/// Mid gray as a color picker shows it (sRGB 0.5), in linear RGB +pub const MID_GRAY: f32 = 0.214; + +/// The two Channel Input and Extract Direction choices: the channel the filter sits on, or its image input +const CURRENT_CHANNEL: &str = "currentChannel"; +const CUSTOM_INPUT: &str = "customInput"; + +/// A new glow's warm light, in linear RGB +const GLOW_COLOR: [f32; 3] = [0.871, 0.578, 0.188]; + +/// The Glow filter as the library adds it: a soft warm halo outside the shapes +pub const LIBRARY_GLOW: Filter = Filter::HaloGlow { on_mask: false, precise: false, width: 0.15, spread: 0.0, opacity: 1.0, color: GLOW_COLOR }; + +/// The Drop Shadow filter as the library adds it: a half-opaque black shadow cast downward +pub const LIBRARY_DROP_SHADOW: Filter = Filter::DropShadow { angle: 90.0, distance: 0.1, size: 0.2, spread: 0.0, opacity: 0.5, color: [0.0; 3] }; + +/// The Gradient Curve filter as the library adds it +pub const LIBRARY_GRADIENT_CURVE: Filter = Filter::GradientCurve { preset: CurvePreset::Round, invert: false, balance: 0.5, contrast: 0.0 }; + +/// The Gradient Dynamic filter as the library adds it: a horizontal ramp from a light gray +pub const LIBRARY_GRADIENT_DYNAMIC: Filter = Filter::GradientDynamic { vertical: false, position: 0.0, color: [0.6; 3] }; + +/// The Baked Lighting Environment filter as the library adds it: the environment as it stands, full ambient occlusion +pub const LIBRARY_ENVIRONMENT_LIGHTING: Filter = + Filter::EnvironmentLighting { horizontal: 0.0, vertical: 0.0, exposure: 0.0, height_intensity: 4.0, ambient_occlusion: 1.0, specular_occlusion: 0.0 }; + +pub use crate::stylized_lighting_params::{MAX_CAVITY_SMOOTHNESS, MAX_DIELECTRIC_REFLECTANCE, MAX_HEIGHT_TO_NORMAL, MAX_LIGHT_INTENSITY}; + +/// A Seed slider's end; any seed can be typed +const SEED_SLIDER_MAX: f32 = 999.0; + +/// The Tiling range of a warp's or slope blur's source +pub const SOURCE_TILING_MIN: f32 = WarpSource::TILING_MIN; +pub const SOURCE_TILING_MAX: f32 = WarpSource::TILING_MAX; + +/// The Source Tiling slider range of a noise-driven warp or blur +const NOISE_TILING_MIN: f32 = 0.5; +const NOISE_TILING_MAX: f32 = 64.0; + +/// A blur Intensity slider's end, in the reference workflow's unit (see [`Filter::BLUR_INTENSITY`]) +pub const BLUR_INTENSITY_SLIDER_MAX: f32 = 16.0; + +/// The widest radius or width a filter takes, in texels at 2K; its slider ends at [`TEXELS_SLIDER_MAX`] +const TEXELS_MAX: f32 = 256.0; +const TEXELS_SLIDER_MAX: f32 = 128.0; + +/// Slider ends where a larger value can still be typed +const SHARPEN_SLIDER_MAX: f32 = 4.0; +const GLOW_AMOUNT_SLIDER_MAX: f32 = 5.0; +pub const SKY_INTENSITY_SLIDER_MAX: f32 = 2.0; +const EDGE_WIDTH_SLIDER_MAX: f32 = 64.0; +const MOSAIC_PIXELS_SLIDER_MAX: f32 = 128.0; + +/// The largest values that can be typed past those slider ends +const SHARPEN_AMOUNT_MAX: f32 = 10.0; +const GLOW_AMOUNT_MAX: f32 = 10.0; +const SKY_INTENSITY_MAX: f32 = 10.0; + +/// The largest mosaic cell, in pixels +const MOSAIC_SIZE_MAX: f32 = 2048.0; + +/// Height Adjust's largest Multiply +const HEIGHT_MULTIPLY_MAX: f32 = 10.0; + +/// Height Adjust's Offset reaches this far either way, as the reference's does +const HEIGHT_OFFSET_MAX: f32 = 10.0; + +/// Distance Bevel's largest Smoothing +pub const DISTANCE_BEVEL_SMOOTHING_MAX: f32 = Bevel::SMOOTHING_MAX; + +/// Bevel Smooth's and Directional Distance's largest Distance, as a share of the texture +pub const SMOOTH_DISTANCE_MAX: f32 = 0.3; + +/// Bevel Smooth's largest Smoothing +pub const BEVEL_SMOOTHING_MAX: f32 = BevelSmooth::SMOOTHING_MAX; + +/// The most colors `colors` takes at once +const GRADIENT_COLORS_GIVEN_MAX: usize = 16; + +/// The fewest colors a gradient's Color Quantity uses +pub const GRADIENT_QUANTITY_MIN: u8 = 2; + +/// Stylized lighting's Sun Intensity end +pub const SUN_INTENSITY_MAX: f32 = 10.0; +/// Environment lighting's Height Intensity end +const HEIGHT_INTENSITY_MAX: f32 = 8.0; + +/// The Gradient filter as the library adds it: black, mid gray and white at 0, 0.5 and 1 (the other seven colors wait white at 1) +fn library_gradient() -> Filter { + let quantity = 3; + let mut colors = vec![[0.0; 3], [MID_GRAY; 3]]; + colors.resize(usize::from(Filter::MAX_GRADIENT_COLORS), [1.0; 3]); + let mut positions = vec![0.0, 0.5]; + positions.resize(colors.len(), 1.0); + Filter::GradientMap { colors, positions, quantity: Some(quantity), input: GradientInput::LIBRARY, linear: true, debug: false } +} + +/// The Baked Lighting Stylized filter as the library adds it: a sun 45° up in front, full sky light, no diffuse AO +pub fn library_baked_lighting() -> Filter { + Filter::BakedLighting { azimuth: 0.0, elevation: 45.0, light: 1.0, ambient: 1.0, occlusion: 0.0, stylized: Some(Box::new(StylizedLighting::library())) } +} + +/// The effect for library filter `id` with its defaults, then the parameters in `p` pub fn build(id: &str, p: &Value) -> Result { - let cmd = "effect.add.filter"; - let d = find(id).ok_or_else(|| bad(cmd, format!("unknown filter `{id}` (see filter.list)")))?; - let mut f = match d.id { + build_for("effect.add.filter", id, p) +} + +/// The effect for library filter `id` with its defaults, then the parameters in `p`; errors name `cmd` (`effect.set` swaps a filter with it) +pub(crate) fn build_for(cmd: &str, id: &str, p: &Value) -> Result { + let def = find(id).ok_or_else(|| bad(cmd, format!("unknown filter `{id}` (see filter.list)")))?; + let mut filter = match def.id { "invert" => Filter::Invert, - "threshold" => Filter::Threshold { level: 0.5 }, - "blur" => Filter::Blur { radius: 2.0 }, + "threshold" => Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater }, + "blur" => Filter::Blur { radius: 0.3 * Filter::BLUR_INTENSITY, wrap: false }, "sharpen" => Filter::Sharpen { amount: 1.0 }, - "hsl" => Filter::Hsl { hue: 0.0, saturation: 0.0, lightness: 0.0 }, - "contrastLuminosity" => Filter::ContrastLuminosity { contrast: 0.3, luminosity: 0.0 }, + "hsl" => Filter::Hsl { hue: 0.0, saturation: 0.0, lightness: 0.0, perceptive: true }, + "contrastLuminosity" => Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.0 }, + "colorCorrect" => Filter::ColorCorrect { shadows: NEUTRAL_TONE, midtones: NEUTRAL_TONE, highlights: NEUTRAL_TONE }, "colorBalance" => Filter::ColorBalance { shadows: [0.0; 3], midtones: [0.0; 3], highlights: [0.0; 3] }, - "gradientMap" => Filter::GradientMap { colors: vec![[0.02, 0.02, 0.04], [0.45, 0.16, 0.05], [1.0, 0.85, 0.55]] }, - "posterize" => Filter::Posterize { levels: 4.0 }, - "clamp" => Filter::Clamp { min: 0.2, max: 0.8 }, - "histogramScan" => Filter::HistogramScan { position: 0.5, contrast: 0.5 }, + "gradientMap" => library_gradient(), + "gradientCurve" => LIBRARY_GRADIENT_CURVE, + "gradientDynamic" => LIBRARY_GRADIENT_DYNAMIC, + "posterize" => Filter::Posterize { levels: 8.0, alpha: false }, + "clamp" => Filter::Clamp { min: 0.0, max: 1.0 }, + "smoothstep" => Filter::Smoothstep { min: 0.0, max: 1.0 }, + "heightAdjust" => Filter::HeightAdjust { invert: false, offset: 0.0, multiply: 1.0 }, + "histogramScan" => Filter::HistogramScan { position: 0.5, contrast: 0.0, invert_position: false }, "histogramRange" => Filter::HistogramRange { range: 0.5, position: 0.5 }, - "histogramShift" => Filter::HistogramShift { offset: 0.25 }, - "warp" => Filter::Warp { intensity: 16.0, scale: 4.0, seed: 1 }, + "histogramShift" => Filter::HistogramShift { offset: 0.0 }, + "warp" => Filter::SourceWarp(SourceWarp::LIBRARY), "blurDirectional" => Filter::DirectionalBlur { radius: 16.0, angle: 0.0 }, - "slopeBlur" => Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1 }, - "highPass" => Filter::HighPass { radius: 8.0 }, + "slopeBlur" => Filter::SourceSlopeBlur(SourceSlopeBlur::LIBRARY), + "highPass" => Filter::HighPass { radius: 3.0 * Filter::BLUR_INTENSITY, space: HighpassSpace::Working, alpha: false }, "edgeDetect" => Filter::EdgeDetect { width: 2.0 }, - "warpDirectional" => Filter::DirectionalWarp { intensity: 16.0, angle: 0.0, scale: 4.0, seed: 1 }, - "grayscale" => Filter::Grayscale, + "grayscale" => Filter::GrayscaleConversion(GrayscaleConversion::LIBRARY), "normalInvert" => Filter::NormalInvert, - "bevel" => Filter::Bevel { width: 16.0 }, - "mosaic" => Filter::Mosaic { size: 32.0 }, - "glow" => Filter::Glow { radius: 16.0, amount: 1.0 }, + "bevel" => Filter::DistanceBevel(Bevel::LIBRARY), + "bevelSmooth" => Filter::BevelSmooth(BevelSmooth::LIBRARY), + "directionalDistance" => Filter::DirectionalDistance(DirectionalDistance::LIBRARY), + "mosaic" => Filter::Mosaic { size: Filter::pixel_size(32.0), alpha: true }, + "fxaa" => Filter::Fxaa { alpha: false }, + "anisotropicKuwahara" => Filter::AnisotropicKuwahara(AnisotropicKuwahara::LIBRARY), + "pbrValidate" => Filter::PbrValidate(PbrValidate::LIBRARY), + "heightToNormal" => Filter::HeightToNormal(HeightToNormal::LIBRARY), + "colorMatch" => Filter::ColorMatch(ColorMatch::LIBRARY), + "mirror" => Filter::Mirror(Mirror::LIBRARY), + "transform" => Filter::Transform(TileTransform::LIBRARY), + "maskOutline" => Filter::MaskOutline(MaskOutline::LIBRARY), + "glow" => LIBRARY_GLOW, + "dropShadow" => LIBRARY_DROP_SHADOW, "replaceColor" => Filter::ReplaceColor { from: [0.5, 0.05, 0.05], to: [0.05, 0.15, 0.5], tolerance: 0.2, softness: 0.15 }, - "bakedLighting" => Filter::BakedLighting { azimuth: 45.0, elevation: 45.0, light: 0.8, ambient: 0.4, occlusion: 1.0 }, + "bakedLighting" => library_baked_lighting(), + "bakedLightingEnvironment" => LIBRARY_ENVIRONMENT_LIGHTING, "levels" => { - let mut l = Levels::default(); crate::mask_cmds::levels_from(cmd, p, &mut l)?; - return Ok(EffectKind::Levels(l)); + let mut levels = Levels::default(); + crate::mask_cmds::levels_from(cmd, p, &mut levels)?; + return Ok(EffectKind::Levels(levels)); } finish => return mat_finish(finish).map(EffectKind::Material).ok_or_else(|| bad(cmd, format!("unknown filter `{id}`"))), }; - apply(p, &mut f, cmd)?; - Ok(EffectKind::Filter(f)) + + // A new gradient given its colors ramps through all of them, or the `quantity` given, evenly unless places are given too + if let Filter::GradientMap { positions, quantity, .. } = &mut filter + && p.get("colors").is_some() + { + *quantity = None; + if p.get("positions").is_none() { + positions.clear(); + } + } + + apply_named(Some(id), p, &mut filter, cmd)?; + Ok(EffectKind::Filter(filter)) } /// A material finish: procedural roughness and height (tri-planar, so it is seamless). @@ -157,93 +381,508 @@ fn mat_finish(id: &str) -> Option { Some(fill) } -/// Scalar parameters of a filter for editors: (param key, label, value, min, max). Colors -/// (color balance, gradient map) and the HSL hue have their own editors. -pub fn scalar_params(f: &Filter) -> Vec<(&'static str, &'static str, f32, f32, f32)> { - match f { - Filter::Blur { radius } => vec![("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0)], - Filter::Sharpen { amount } => vec![("amount", "Amount", *amount, 0.0, 5.0)], - Filter::Threshold { level } => vec![("level", "Level", *level, 0.0, 1.0)], +/// Scalar parameters of a filter for editors: (param key, label, value, min, max); colors (color balance, gradient map) and the HSL hue have their own editors +pub fn scalar_params(filter: &Filter) -> Vec<(&'static str, &'static str, f32, f32, f32)> { + match filter { + Filter::Blur { radius, .. } => vec![("intensity", "Blur Intensity", *radius / Filter::BLUR_INTENSITY, 0.0, BLUR_INTENSITY_SLIDER_MAX)], + Filter::Sharpen { amount } => vec![("amount", "Sharpen Intensity", *amount, 0.0, SHARPEN_SLIDER_MAX)], + Filter::Threshold { level, .. } => vec![("level", "Threshold", *level, 0.0, 1.0)], Filter::Hsl { saturation, lightness, .. } => { vec![("saturation", "Saturation", *saturation, -1.0, 1.0), ("lightness", "Lightness", *lightness, -1.0, 1.0)] } Filter::ContrastLuminosity { contrast, luminosity } => { vec![("contrast", "Contrast", *contrast, -1.0, 1.0), ("luminosity", "Luminosity", *luminosity, -1.0, 1.0)] } - Filter::Posterize { levels } => vec![("levels", "Steps", *levels, 2.0, 64.0)], - Filter::Clamp { min, max } => vec![("min", "Minimum", *min, 0.0, 1.0), ("max", "Maximum", *max, 0.0, 1.0)], - Filter::HistogramScan { position, contrast } => vec![("position", "Position", *position, 0.0, 1.0), ("contrast", "Contrast", *contrast, 0.0, 1.0)], + Filter::Posterize { levels, .. } => vec![("levels", "Colors Amount", *levels, POSTERIZE_LEVELS_MIN, POSTERIZE_LEVELS_MAX)], + Filter::Clamp { min, max } => vec![("min", "Min", *min, 0.0, 1.0), ("max", "Max", *max, 0.0, 1.0)], + Filter::Smoothstep { min, max } => vec![("min", "Minimum", *min, 0.0, 1.0), ("max", "Maximum", *max, 0.0, 1.0)], + Filter::HeightAdjust { offset, multiply, .. } => { + vec![("offset", "Offset", *offset, -HEIGHT_OFFSET_MAX, HEIGHT_OFFSET_MAX), ("multiply", "Multiply", *multiply, 0.0, HEIGHT_MULTIPLY_MAX)] + } + Filter::HistogramScan { position, contrast, .. } => vec![("position", "Position", *position, 0.0, 1.0), ("contrast", "Contrast", *contrast, 0.0, 1.0)], Filter::HistogramRange { range, position } => vec![("range", "Range", *range, 0.0, 1.0), ("position", "Position", *position, 0.0, 1.0)], - Filter::HistogramShift { offset } => vec![("offset", "Offset", *offset, -1.0, 1.0)], - Filter::Warp { intensity, scale, seed } => { + Filter::HistogramShift { offset } => vec![("position", "Position", Filter::shift_position(*offset), 0.0, 1.0)], + Filter::Warp { intensity, scale, seed, .. } => { vec![ - ("intensity", "Intensity (texels at 2K)", *intensity, 0.0, 128.0), - ("scale", "Noise scale", *scale, 0.5, 64.0), - ("seed", "Seed", *seed as f32, 0.0, 999.0), + ("intensity", "Intensity", *intensity, 0.0, TEXELS_SLIDER_MAX), + ("scale", "Source Tiling", *scale, NOISE_TILING_MIN, NOISE_TILING_MAX), + ("seed", "Seed", *seed as f32, 0.0, SEED_SLIDER_MAX), ] } Filter::DirectionalBlur { radius, angle } => { - vec![("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0), ("angle", "Angle (degrees)", *angle, 0.0, 360.0)] - } - Filter::SlopeBlur { radius, scale, seed } => { vec![ - ("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0), - ("scale", "Slope scale", *scale, 0.5, 64.0), - ("seed", "Seed", *seed as f32, 0.0, 999.0), + ("intensity", "Intensity", *radius / Filter::BLUR_INTENSITY, 0.0, BLUR_INTENSITY_SLIDER_MAX), + ("angle", "Angle", *angle, 0.0, FULL_TURN_DEGREES), ] } - Filter::HighPass { radius } => vec![("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0)], - Filter::EdgeDetect { width } => vec![("width", "Width (texels at 2K)", *width, 0.0, 64.0)], - Filter::DirectionalWarp { intensity, angle, scale, seed } => { + Filter::SlopeBlur { radius, scale, seed, .. } => { vec![ - ("intensity", "Intensity (texels at 2K)", *intensity, 0.0, 128.0), - ("angle", "Angle (degrees)", *angle, 0.0, 360.0), - ("scale", "Noise scale", *scale, 0.5, 64.0), - ("seed", "Seed", *seed as f32, 0.0, 999.0), + ("radius", "Intensity", *radius, 0.0, TEXELS_SLIDER_MAX), + ("scale", "Source Tiling", *scale, NOISE_TILING_MIN, NOISE_TILING_MAX), + ("seed", "Seed", *seed as f32, 0.0, SEED_SLIDER_MAX), ] } - Filter::Bevel { width } => vec![("width", "Width (texels at 2K)", *width, 0.0, 128.0)], - Filter::Mosaic { size } => vec![("size", "Cell size (texels at 2K)", *size, 1.0, 256.0)], + Filter::HighPass { radius, .. } => vec![("intensity", "Radius", *radius / Filter::BLUR_INTENSITY, 0.0, BLUR_INTENSITY_SLIDER_MAX)], + Filter::GrayscaleConversion(conversion) => conversion_params(conversion), + Filter::AnisotropicKuwahara(kuwahara) => vec![ + ("radius", "Radius", kuwahara.radius, 0.0, AnisotropicKuwahara::MAX_RADIUS), + ("smoothness", "Smoothness", kuwahara.smoothness, 0.0, 1.0), + ("sharpness", "Sharpness", kuwahara.sharpness, AnisotropicKuwahara::MIN_SHARPNESS, 1.0), + ("tensorSmoothness", "Tensor Smoothness", kuwahara.tensor_smoothness, 0.0, 1.0), + ("anisotropy", "Anisotropy", kuwahara.anisotropy, 0.0, 1.0), + ("angle", "Anisotropy Angle", kuwahara.angle, 0.0, FULL_TURN_DEGREES), + ], + Filter::Grayscale => conversion_params(&GrayscaleConversion::of_luminance()), + Filter::HeightToNormal(converter) if converter.world_units => vec![ + ("surfaceSize", "Surface Size (cm)", converter.surface_size, HeightToNormal::MIN_SURFACE_SIZE, HeightToNormal::MAX_SURFACE_SIZE), + ("heightDepth", "Height Depth (cm)", converter.height_depth, 0.0, HeightToNormal::MAX_HEIGHT_DEPTH), + ], + Filter::HeightToNormal(converter) => vec![("normalIntensity", "Normal Intensity", converter.intensity, 0.0, HeightToNormal::MAX_INTENSITY)], + Filter::ColorMatch(matcher) => { + vec![ + ("hue", "Hue", matcher.hue, 0.0, FULL_TURN_DEGREES), + ("chroma", "Chroma", matcher.chroma, 0.0, ColorMatch::MAX_CHROMA), + ("luma", "Luma", matcher.luma, 0.0, ColorMatch::MAX_LUMA), + ] + } + Filter::EdgeDetect { width } => vec![("width", "Width", *width, 0.0, EDGE_WIDTH_SLIDER_MAX)], + Filter::DirectionalWarp { intensity, angle, scale, seed, .. } => { + vec![ + ("intensity", "Intensity", *intensity, 0.0, TEXELS_SLIDER_MAX), + ("angle", "Angle", *angle, 0.0, FULL_TURN_DEGREES), + ("scale", "Source Tiling", *scale, NOISE_TILING_MIN, NOISE_TILING_MAX), + ("seed", "Seed", *seed as f32, 0.0, SEED_SLIDER_MAX), + ] + } + Filter::Bevel { width, .. } => vec![("width", "Distance", *width, 0.0, TEXELS_SLIDER_MAX)], + Filter::Mosaic { size, .. } => vec![("pixelsAmount", "Pixels Amount", Filter::pixels_amount(*size), 1.0, MOSAIC_PIXELS_SLIDER_MAX)], + Filter::DistanceBevel(bevel) => { + vec![("distance", "Distance", bevel.distance, -1.0, 1.0), ("smoothing", "Smoothing", bevel.smoothing, 0.0, DISTANCE_BEVEL_SMOOTHING_MAX)] + } + Filter::SourceWarp(warp) => { + let mut params = vec![("seed", "Seed", warp.seed as f32, 0.0, SEED_SLIDER_MAX), ("intensity", "Intensity", warp.intensity, 0.0, 1.0)]; + if warp.mode != WarpMode::Warp { + params.push(("angle", "Angle", warp.angle, 0.0, FULL_TURN_DEGREES)); + } + params.extend([ + ("sourceBlur", "Source Blur", warp.source.blur, 0.0, 1.0), + ("sourceBalance", "Source Balance", warp.source.balance, 0.0, 1.0), + ("sourceContrast", "Source Contrast", warp.source.contrast, 0.0, 1.0), + ("sourceTiling", "Source Tiling", warp.source.tiling, SOURCE_TILING_MIN, SOURCE_TILING_MAX), + ]); + params + } + Filter::SourceSlopeBlur(slope) => vec![ + ("seed", "Seed", slope.seed as f32, 0.0, SEED_SLIDER_MAX), + ("intensity", "Intensity", slope.intensity, 0.0, 1.0), + ("quality", "Quality", slope.quality, 0.0, 1.0), + ("sourceBlur", "Blur", slope.source.blur, 0.0, 1.0), + ("sourceBalance", "Position", slope.source.balance, 0.0, 1.0), + ("sourceContrast", "Contrast", slope.source.contrast, 0.0, 1.0), + ("sourceTiling", "Source Tiling", slope.source.tiling, SOURCE_TILING_MIN, SOURCE_TILING_MAX), + ], + Filter::BevelSmooth(smooth) => vec![ + ("distance", "Distance", smooth.distance, 0.0, SMOOTH_DISTANCE_MAX), + ("smoothing", "Smoothing", smooth.smoothing, 0.0, BEVEL_SMOOTHING_MAX), + ("curveOffset", "Curve Offset", smooth.curve_offset, -1.0, 1.0), + ("curveShape", "Curve Shape", smooth.curve_shape, -1.0, 1.0), + ("maskThreshold", "Mask Threshold", smooth.threshold, 0.0, 1.0), + ("distanceMapMultiplier", "Distance Map Multiplier", smooth.multiplier, 0.0, 1.0), + ], + Filter::DirectionalDistance(trail) => vec![ + ("distance", "Distance", trail.distance, 0.0, SMOOTH_DISTANCE_MAX), + ("angle", "Angle", trail.angle, 0.0, FULL_TURN_DEGREES), + ("contrast", "Contrast", trail.contrast, 0.0, 1.0), + ("distanceMapMultiplier", "Distance Map Multiplier", trail.multiplier, 0.0, 1.0), + ], + // Only the offset of the axis the mode mirrors across shows + Filter::Mirror(mirror) => match mirror.mode { + MirrorMode::AxisX => vec![("axisXOffset", "Axis X Offset", mirror.offset[0], 0.0, 1.0)], + MirrorMode::AxisY => vec![("axisYOffset", "Axis Y Offset", mirror.offset[1], 0.0, 1.0)], + MirrorMode::Corner => Vec::new(), + }, + Filter::MaskOutline(outline) => vec![ + ("threshold", "Threshold", outline.threshold, 0.0, 1.0), + ("width", "Width", outline.width, 0.0, 1.0), + ("blur", "Blur", outline.blur, 0.0, 1.0), + ("curveShape", "Curve Shape", outline.curve, -1.0, 1.0), + ], Filter::Glow { radius, amount } => { - vec![("radius", "Radius (texels at 2K)", *radius, 0.0, 128.0), ("amount", "Amount", *amount, 0.0, 5.0)] + vec![("radius", "Width", *radius, 0.0, TEXELS_SLIDER_MAX), ("amount", "Amount", *amount, 0.0, GLOW_AMOUNT_SLIDER_MAX)] } - Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion } => vec![ - ("azimuth", "Light azimuth (degrees)", *azimuth, 0.0, 360.0), - ("elevation", "Light elevation (degrees)", *elevation, -90.0, 90.0), - ("light", "Light intensity", *light, 0.0, 4.0), - ("ambient", "Ambient", *ambient, 0.0, 2.0), - ("occlusion", "Ambient occlusion", *occlusion, 0.0, 1.0), + Filter::HaloGlow { width, spread, opacity, .. } => { + vec![("width", "Width", *width, -1.0, 1.0), ("spread", "Spread", *spread, 0.0, 1.0), ("opacity", "Opacity", *opacity, 0.0, 1.0)] + } + Filter::DropShadow { angle, distance, size, spread, opacity, .. } => vec![ + ("angle", "Angle", *angle, 0.0, FULL_TURN_DEGREES), + ("distance", "Distance", *distance, -Filter::SHADOW_DISTANCE_MAX, Filter::SHADOW_DISTANCE_MAX), + ("size", "Size", *size, 0.0, 1.0), + ("spread", "Spread", *spread, 0.0, 1.0), + ("opacity", "Opacity", *opacity, 0.0, 1.0), + ], + Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, .. } => vec![ + ("light", "Sun Intensity", *light, 0.0, SUN_INTENSITY_MAX), + ("azimuth", "Horizontal Angle", *azimuth, 0.0, FULL_TURN_DEGREES), + ("elevation", "Vertical Angle", *elevation, 0.0, FULL_TURN_DEGREES), + ("ambient", "Sky Intensity", *ambient, 0.0, SKY_INTENSITY_SLIDER_MAX), + ("occlusion", "Diffuse AO", *occlusion, 0.0, 1.0), + ], + Filter::EnvironmentLighting { horizontal, vertical, exposure, height_intensity, ambient_occlusion, specular_occlusion } => vec![ + ("horizontalRotation", "Horizontal Rotation", *horizontal, 0.0, FULL_TURN_DEGREES), + ("verticalRotation", "Vertical Rotation", *vertical, 0.0, FULL_TURN_DEGREES), + ("exposure", "Exposure", *exposure, -Filter::ENVIRONMENT_EXPOSURE_STOPS, Filter::ENVIRONMENT_EXPOSURE_STOPS), + ("heightIntensity", "Height Intensity", *height_intensity, 0.0, HEIGHT_INTENSITY_MAX), + ("ambientOcclusion", "Ambient Occlusion Intensity", *ambient_occlusion, 0.0, 1.0), + ("specularOcclusion", "Specular Occlusion Intensity", *specular_occlusion, 0.0, 1.0), ], Filter::ReplaceColor { tolerance, softness, .. } => { vec![("tolerance", "Tolerance", *tolerance, 0.0, 1.0), ("softness", "Softness", *softness, 0.0, 1.0)] } - Filter::Invert | Filter::ColorBalance { .. } | Filter::GradientMap { .. } | Filter::Grayscale | Filter::NormalInvert => Vec::new(), + Filter::GradientMap { input, .. } => vec![ + ("blur", "Blur Intensity", input.blur, 0.0, BLUR_INTENSITY_SLIDER_MAX), + ("balance", "Balance", input.balance, 0.0, 1.0), + ("contrast", "Contrast", input.contrast, 0.0, 1.0), + ], + Filter::GradientCurve { balance, contrast, .. } => vec![("balance", "Balance", *balance, 0.0, 1.0), ("contrast", "Contrast", *contrast, 0.0, 1.0)], + Filter::GradientDynamic { position, .. } => vec![("position", "Gradient Input Position", *position, 0.0, 1.0)], + Filter::Invert + | Filter::InvertOff + | Filter::ColorBalance { .. } + | Filter::ColorCorrect { .. } + | Filter::NormalInvert + | Filter::Fxaa { .. } + | Filter::PbrValidate(_) + | Filter::Transform(_) + | Filter::Empty => Vec::new(), } } -/// Set the parameters of `f` given in `p` (clamped to their ranges); `effect.set` uses it too. -pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { - let set = |slot: &mut f32, key: &str, lo: f32, hi: f32| { - if let Some(v) = f32p(p, key) { - *slot = v.clamp(lo, hi); +/// Grayscale Conversion's sliders: Balance and Contrast, then the Channels Weights' Red, Green, Blue and Alpha in that mode +fn conversion_params(conversion: &GrayscaleConversion) -> Vec<(&'static str, &'static str, f32, f32, f32)> { + let mut params = vec![("balance", "Balance", conversion.balance, 0.0, 1.0), ("contrast", "Contrast", conversion.contrast, 0.0, 1.0)]; + if conversion.mode == ConversionMode::ChannelsWeights { + let [red, green, blue, alpha] = conversion.weights; + params.extend([ + ("red", "Red", red, 0.0, 1.0), + ("green", "Green", green, 0.0, 1.0), + ("blue", "Blue", blue, 0.0, 1.0), + ("alpha", "Alpha", alpha, 0.0, 1.0), + ]); + } + params +} + +/// The keys `effect.set` takes for Grayscale Conversion +const CONVERSION_KEYS: [&str; 9] = ["channelInput", "invert", "balance", "contrast", "mode", "red", "green", "blue", "alpha"]; + +/// Set the Grayscale Conversion settings given in `p`: channelInput (currentChannel or customInput), invert, balance, contrast, mode and the red, green, blue and alpha weights +fn apply_conversion(p: &Value, conversion: &mut GrayscaleConversion, cmd: &str) -> Result<()> { + conversion.custom_input = two_way(p, "channelInput", CURRENT_CHANNEL, CUSTOM_INPUT, cmd)?.unwrap_or(conversion.custom_input); + set_bool(p, "invert", &mut conversion.invert, cmd)?; + conversion.mode = choice(p, "mode", &ConversionMode::ALL, ConversionMode::id, cmd)?.unwrap_or(conversion.mode); + + let [red, green, blue, alpha] = &mut conversion.weights; + for (key, slot) in + [("balance", &mut conversion.balance), ("contrast", &mut conversion.contrast), ("red", red), ("green", green), ("blue", blue), ("alpha", alpha)] + { + if let Some(value) = f32p(p, key) { + *slot = value.clamp(0.0, 1.0); + } + } + Ok(()) +} + +/// Make a gradient use its first `wanted` colors: an evenly spaced ramp keeps its places from now on, and each added color starts at 1 as the ramp's color there +fn set_quantity(colors: &mut Vec<[f32; 3]>, positions: &mut Vec, quantity: &mut Option, wanted: u8) { + let used = quantity.map_or(colors.len(), usize::from).min(colors.len()); + + // The used colors without a place keep the even place the ramp gave them + let last = used.saturating_sub(1).max(1) as f32; + for index in positions.len()..used { + positions.push(index as f32 / last); + } + + let wanted_len = usize::from(wanted); + + // At 1 the blend space does not matter: only the rightmost stop counts, which need not be the last in the list + let used_colors = colors.get(..used).unwrap_or_default(); + let fill = texturecraft_core::gradient_input::ramp(used_colors, positions, true, 1.0).unwrap_or([1.0; 3]); + if colors.len() < wanted_len { + colors.resize(wanted_len, fill); + } + if positions.len() < wanted_len { + positions.resize(wanted_len, 1.0); + } + *quantity = Some(wanted); +} + +/// Set the Mirror settings given in `p`: displayDebug, mode, axisXOffset, axisYOffset, invertAxisX, invertAxisY and cornerType +fn apply_mirror(p: &Value, mirror: &mut Mirror, cmd: &str) -> Result<()> { + mirror.mode = choice(p, "mode", &MirrorMode::ALL, MirrorMode::id, cmd)?.unwrap_or(mirror.mode); + mirror.corner = choice(p, "cornerType", &MirrorCorner::ALL, MirrorCorner::id, cmd)?.unwrap_or(mirror.corner); + + let [offset_x, offset_y] = &mut mirror.offset; + for (key, slot) in [("axisXOffset", offset_x), ("axisYOffset", offset_y)] { + if let Some(offset) = f32p(p, key) { + *slot = offset.clamp(0.0, 1.0); + } + } + + let [invert_x, invert_y] = &mut mirror.invert; + for (key, slot) in [("displayDebug", &mut mirror.debug), ("invertAxisX", invert_x), ("invertAxisY", invert_y)] { + set_bool(p, key, slot, cmd)?; + } + Ok(()) +} + +/// The choice among `all` whose id (`id`) `p` gives under `key`, if it gives one; an unknown id is refused +pub(crate) fn choice(p: &Value, key: &str, all: &[T], id: fn(T) -> &'static str, cmd: &str) -> Result> { + if p.get(key).is_none() { + return Ok(None); + } + + let given = strp(p, key).unwrap_or_default(); + let found = all.iter().copied().find(|choice| id(*choice) == given); + found.map(Some).ok_or_else(|| { + let ids: Vec<&str> = all.iter().map(|choice| id(*choice)).collect(); + bad(cmd, format!("`{key}` must be {}", one_of(&ids))) + }) +} + +/// Which of two ids `p` gives under `key` (true: `on_id`), if it gives one; any other value is refused +pub(crate) fn two_way(p: &Value, key: &str, off_id: &str, on_id: &str, cmd: &str) -> Result> { + if p.get(key).is_none() { + return Ok(None); + } + + match strp(p, key) { + Some(id) if id == off_id => Ok(Some(false)), + Some(id) if id == on_id => Ok(Some(true)), + _ => Err(bad(cmd, format!("`{key}` must be {off_id} or {on_id}"))), + } +} + +/// Set `slot` to the true or false `p` gives under `key`, if it gives one; any other value is refused +pub(crate) fn set_bool(p: &Value, key: &str, slot: &mut bool, cmd: &str) -> Result<()> { + if p.get(key).is_some() { + *slot = boolp(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be true or false")))?; + } + Ok(()) +} + +/// Set `slot` to the color `p` gives under `key` (clamped to 0..1), if it gives one; any other value, null too, is refused +pub(crate) fn set_color(p: &Value, key: &str, slot: &mut [f32; 3], cmd: &str) -> Result<()> { + if p.get(key).is_some() { + let rgb = color_param(cmd, p, key)?.ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")")))?; + *slot = rgb.map(|x| x.clamp(0.0, 1.0)); + } + Ok(()) +} + +/// An array of exactly three finite numbers +fn three_numbers(given: &Value) -> Option<[f32; 3]> { + let [first, second, third] = given.as_array()?.as_slice() else { return None }; + let number = |value: &Value| value.as_f64().map(|x| x as f32).filter(|x| x.is_finite()); + Some([number(first)?, number(second)?, number(third)?]) +} + +/// The allowed values of a setting as its error message lists them: "a, b or c" +fn one_of(allowed: &[T]) -> String { + let words: Vec = allowed.iter().map(ToString::to_string).collect(); + match words.split_last() { + Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")), + _ => words.concat(), + } +} + +/// Whether `p` asks `filter`, a warp saved before the warp modes, for a mode it can't hold: Directional Warp's former id on a Warp, or a `warpMode` it is not +pub(crate) fn changes_saved_warp_mode(named: &str, p: &Value, filter: &Filter) -> bool { + let saved_mode = match filter { + Filter::Warp { .. } => WarpMode::Warp, + Filter::DirectionalWarp { .. } => WarpMode::Directional, + _ => return false, + }; + match p.get("warpMode") { + Some(mode) => mode.as_str() != Some(saved_mode.id()), + None => is_directional_warp(named) && saved_mode != WarpMode::Directional, + } +} + +/// [`apply`] for the filter id `named`, if one is given: Directional Warp's former id turns a Warp to Directional mode unless `warpMode` is given +pub(crate) fn apply_named(named: Option<&str>, p: &Value, filter: &mut Filter, cmd: &str) -> Result<()> { + apply(p, filter, cmd)?; + + if let Filter::SourceWarp(warp) = filter + && named.is_some_and(is_directional_warp) + && p.get("warpMode").is_none() + { + warp.mode = WarpMode::Directional; + } + Ok(()) +} + +/// Set the parameters of `filter` given in `p` (clamped to their ranges); `effect.set` uses it too +pub(crate) fn apply(p: &Value, filter: &mut Filter, cmd: &str) -> Result<()> { + let set = |slot: &mut f32, key: &str, low: f32, high: f32| { + if let Some(value) = f32p(p, key) { + *slot = value.clamp(low, high); } }; let seed = |slot: &mut u32| { - if let Some(v) = u64p(p, "seed") { - *slot = u32::try_from(v).unwrap_or(u32::MAX); + if let Some(value) = u64p(p, "seed") { + *slot = u32::try_from(value).unwrap_or(u32::MAX); } }; + let divider = |slot: &mut u16| -> Result<()> { + if p.get("divider").is_some() { + let value = u64p(p, "divider").and_then(|value| u16::try_from(value).ok()).filter(|value| Filter::DIVIDERS.contains(value)); + *slot = value.ok_or_else(|| bad(cmd, format!("`divider` must be {}", one_of(&Filter::DIVIDERS))))?; + } + Ok(()) + }; + + // A blur's Intensity in the reference workflow's unit (radius in texels at 2K ÷ Filter::BLUR_INTENSITY) + let blur_intensity = |radius: &mut f32| { + if let Some(intensity) = f32p(p, "intensity") { + *radius = (intensity * Filter::BLUR_INTENSITY).clamp(0.0, TEXELS_MAX); + } + }; + let switch = |slot: &mut bool, key: &str| set_bool(p, key, slot, cmd); + let shade = |slot: &mut [f32; 3]| set_color(p, "color", slot, cmd); let angle = |slot: &mut f32| { - if let Some(v) = f32p(p, "angle") { - *slot = v.rem_euclid(360.0); + if let Some(degrees) = f32p(p, "angle") { + *slot = degrees.rem_euclid(FULL_TURN_DEGREES); } }; - match f { - Filter::Invert | Filter::Grayscale | Filter::NormalInvert => {} - Filter::Threshold { level } => set(level, "level", 0.0, 1.0), - Filter::Blur { radius } => set(radius, "radius", 0.0, 256.0), - Filter::Sharpen { amount } => set(amount, "amount", 0.0, 10.0), - Filter::Hsl { hue, saturation, lightness } => { + + match filter { + Filter::Invert | Filter::InvertOff => { + let mut on = matches!(filter, Filter::Invert); + switch(&mut on, "invert")?; + *filter = if on { Filter::Invert } else { Filter::InvertOff }; + } + Filter::NormalInvert | Filter::Empty => {} + // A Grayscale saved before the settings takes its luminance weights on its first edit, so it looks the same + Filter::Grayscale => { + if CONVERSION_KEYS.iter().any(|key| p.get(key).is_some()) { + let mut conversion = GrayscaleConversion::of_luminance(); + apply_conversion(p, &mut conversion, cmd)?; + *filter = Filter::GrayscaleConversion(conversion); + } + } + Filter::GrayscaleConversion(conversion) => apply_conversion(p, conversion, cmd)?, + Filter::AnisotropicKuwahara(kuwahara) => { + kuwahara.custom_input = two_way(p, "extractDirection", CURRENT_CHANNEL, CUSTOM_INPUT, cmd)?.unwrap_or(kuwahara.custom_input); + set(&mut kuwahara.radius, "radius", 0.0, AnisotropicKuwahara::MAX_RADIUS); + set(&mut kuwahara.smoothness, "smoothness", 0.0, 1.0); + set(&mut kuwahara.sharpness, "sharpness", AnisotropicKuwahara::MIN_SHARPNESS, 1.0); + set(&mut kuwahara.tensor_smoothness, "tensorSmoothness", 0.0, 1.0); + set(&mut kuwahara.anisotropy, "anisotropy", 0.0, 1.0); + angle(&mut kuwahara.angle); + } + Filter::PbrValidate(validate) => { + validate.mode = choice(p, "validationMode", &ValidationMode::ALL, ValidationMode::id, cmd)?.unwrap_or(validate.mode); + for (key, slot, allowed) in [ + ("albedoDarkRangeThreshold", &mut validate.albedo_dark, PbrValidate::ALBEDO_DARK), + ("metalReflectanceRange", &mut validate.metal_low, PbrValidate::METAL_LOW), + ] { + if p.get(key).is_some() { + let value = u64p(p, key).and_then(|value| u8::try_from(value).ok()).filter(|value| allowed.contains(value)); + *slot = value.ok_or_else(|| bad(cmd, format!("`{key}` must be {}", one_of(&allowed))))?; + } + } + } + Filter::HeightToNormal(converter) => { + switch(&mut converter.overwrite, "overwriteExistingNormal")?; + switch(&mut converter.world_units, "useWorldUnits")?; + set(&mut converter.surface_size, "surfaceSize", HeightToNormal::MIN_SURFACE_SIZE, HeightToNormal::MAX_SURFACE_SIZE); + set(&mut converter.height_depth, "heightDepth", 0.0, HeightToNormal::MAX_HEIGHT_DEPTH); + set(&mut converter.intensity, "normalIntensity", 0.0, HeightToNormal::MAX_INTENSITY); + } + Filter::ColorMatch(matcher) => { + matcher.source_mode = choice(p, "sourceColorMode", &SourceColorMode::ALL, SourceColorMode::id, cmd)?.unwrap_or(matcher.source_mode); + matcher.target_mode = choice(p, "targetColorMode", &TargetColorMode::ALL, TargetColorMode::id, cmd)?.unwrap_or(matcher.target_mode); + set_color(p, "sourceColor", &mut matcher.source_color, cmd)?; + set_color(p, "targetColor", &mut matcher.target_color, cmd)?; + switch(&mut matcher.custom_variation, "customColorVariation")?; + set(&mut matcher.hue, "hue", 0.0, FULL_TURN_DEGREES); + set(&mut matcher.chroma, "chroma", 0.0, ColorMatch::MAX_CHROMA); + set(&mut matcher.luma, "luma", 0.0, ColorMatch::MAX_LUMA); + } + Filter::Threshold { level, mode } => { + set(level, "level", 0.0, 1.0); + *mode = choice(p, "mode", &ThresholdMode::ALL, ThresholdMode::id, cmd)?.unwrap_or(*mode); + } + Filter::Mirror(mirror) => apply_mirror(p, mirror, cmd)?, + Filter::Transform(transform) => crate::tile_transform_params::apply(p, transform, cmd)?, + Filter::SourceWarp(warp) => { + seed(&mut warp.seed); + warp.mode = choice(p, "warpMode", &WarpMode::ALL, WarpMode::id, cmd)?.unwrap_or(warp.mode); + set(&mut warp.intensity, "intensity", 0.0, 1.0); + divider(&mut warp.divider)?; + angle(&mut warp.angle); + if p.get("directions").is_some() { + let count = u64p(p, "directions").and_then(|count| u8::try_from(count).ok()).filter(|count| SourceWarp::DIRECTIONS.contains(count)); + warp.directions = count.ok_or_else(|| bad(cmd, format!("`directions` must be {}", one_of(&SourceWarp::DIRECTIONS))))?; + } + warp.blending = choice(p, "blendingMode", &WarpBlending::ALL, WarpBlending::id, cmd)?.unwrap_or(warp.blending); + warp.source.mode = choice(p, "sourceMode", &WarpSourceMode::ALL, WarpSourceMode::id, cmd)?.unwrap_or(warp.source.mode); + set(&mut warp.source.blur, "sourceBlur", 0.0, 1.0); + set(&mut warp.source.balance, "sourceBalance", 0.0, 1.0); + set(&mut warp.source.contrast, "sourceContrast", 0.0, 1.0); + set(&mut warp.source.tiling, "sourceTiling", SOURCE_TILING_MIN, SOURCE_TILING_MAX); + } + Filter::SourceSlopeBlur(slope) => { + seed(&mut slope.seed); + set(&mut slope.intensity, "intensity", 0.0, 1.0); + divider(&mut slope.divider)?; + slope.blending = choice(p, "blendingMode", &SlopeBlending::ALL, SlopeBlending::id, cmd)?.unwrap_or(slope.blending); + set(&mut slope.quality, "quality", 0.0, 1.0); + slope.source.mode = choice(p, "sourceMode", &WarpSourceMode::ALL, WarpSourceMode::id, cmd)?.unwrap_or(slope.source.mode); + set(&mut slope.source.blur, "sourceBlur", 0.0, 1.0); + set(&mut slope.source.balance, "sourceBalance", 0.0, 1.0); + set(&mut slope.source.contrast, "sourceContrast", 0.0, 1.0); + set(&mut slope.source.tiling, "sourceTiling", SOURCE_TILING_MIN, SOURCE_TILING_MAX); + } + Filter::DistanceBevel(bevel) => { + set(&mut bevel.distance, "distance", -1.0, 1.0); + set(&mut bevel.smoothing, "smoothing", 0.0, DISTANCE_BEVEL_SMOOTHING_MAX); + bevel.corner = choice(p, "cornerType", &BevelCorner::ALL, BevelCorner::id, cmd)?.unwrap_or(bevel.corner); + bevel.blur = choice(p, "blurMode", &BevelBlur::ALL, BevelBlur::id, cmd)?.unwrap_or(bevel.blur); + switch(&mut bevel.wrap, "wrap")?; + } + Filter::BevelSmooth(smooth) => { + smooth.direction = choice(p, "direction", &BevelDirection::ALL, BevelDirection::id, cmd)?.unwrap_or(smooth.direction); + set(&mut smooth.distance, "distance", 0.0, SMOOTH_DISTANCE_MAX); + set(&mut smooth.smoothing, "smoothing", 0.0, BEVEL_SMOOTHING_MAX); + set(&mut smooth.curve_offset, "curveOffset", -1.0, 1.0); + set(&mut smooth.curve_shape, "curveShape", -1.0, 1.0); + set(&mut smooth.threshold, "maskThreshold", 0.0, 1.0); + set(&mut smooth.multiplier, "distanceMapMultiplier", 0.0, 1.0); + switch(&mut smooth.wrap, "wrap")?; + } + Filter::DirectionalDistance(trail) => { + set(&mut trail.distance, "distance", 0.0, SMOOTH_DISTANCE_MAX); + angle(&mut trail.angle); + set(&mut trail.contrast, "contrast", 0.0, 1.0); + set(&mut trail.multiplier, "distanceMapMultiplier", 0.0, 1.0); + } + Filter::MaskOutline(outline) => { + outline.position = choice(p, "maskPosition", &OutlinePosition::ALL, OutlinePosition::id, cmd)?.unwrap_or(outline.position); + switch(&mut outline.from_black, "startFromBlack")?; + set(&mut outline.threshold, "threshold", 0.0, 1.0); + set(&mut outline.width, "width", 0.0, 1.0); + set(&mut outline.blur, "blur", 0.0, 1.0); + set(&mut outline.curve, "curveShape", -1.0, 1.0); + } + Filter::Blur { radius, wrap: wraps } => { + set(radius, "radius", 0.0, TEXELS_MAX); + blur_intensity(radius); + switch(wraps, "wrap")?; + } + Filter::Sharpen { amount } => set(amount, "amount", 0.0, SHARPEN_AMOUNT_MAX), + Filter::Hsl { hue, saturation, lightness, perceptive } => { + *perceptive = two_way(p, "mode", "regular", "perceptive", cmd)?.unwrap_or(*perceptive); set(hue, "hue", -1.0, 1.0); set(saturation, "saturation", -1.0, 1.0); set(lightness, "lightness", -1.0, 1.0); @@ -252,81 +891,195 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { set(contrast, "contrast", -1.0, 1.0); set(luminosity, "luminosity", -1.0, 1.0); } + Filter::ColorCorrect { shadows, midtones, highlights } => { + for (key, slot) in [("shadows", shadows), ("midtones", midtones), ("highlights", highlights)] { + if let Some(given) = p.get(key) { + let [contrast, luminosity, saturation] = + three_numbers(given).ok_or_else(|| bad(cmd, format!("`{key}` must be [contrast, luminosity, saturation]")))?; + *slot = [contrast.clamp(-1.0, 1.0), luminosity.clamp(-1.0, 1.0), saturation.clamp(0.0, 1.0)]; + } + } + } Filter::ColorBalance { shadows, midtones, highlights } => { for (key, slot) in [("shadows", shadows), ("midtones", midtones), ("highlights", highlights)] { - if let Some(val) = p.get(key).filter(|v| !v.is_null()) { - let v = color_of(val).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; - *slot = v.map(|x| x.clamp(-1.0, 1.0)); + if let Some(given) = p.get(key).filter(|given| !given.is_null()) { + let offsets = color_of(given).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; + *slot = offsets.map(|x| x.clamp(-1.0, 1.0)); } } } - Filter::GradientMap { colors } => { + Filter::GradientMap { colors, positions, quantity, input, linear, debug } => { if let Some(list) = p.get("colors") { - let parsed: Option> = list.as_array().and_then(|a| a.iter().map(|c| color_of(c).map(|v| v.map(|x| x.clamp(0.0, 1.0)))).collect()); + let parsed: Option> = + list.as_array().and_then(|given| given.iter().map(|color| color_of(color).map(|rgb| rgb.map(|x| x.clamp(0.0, 1.0)))).collect()); match parsed { - Some(c) if (1..=16).contains(&c.len()) => *colors = c, - _ => return Err(bad(cmd, "`colors` must be 1 to 16 colors ([r, g, b] linear or \"#rrggbb\" sRGB)")), + Some(parsed) if (1..=GRADIENT_COLORS_GIVEN_MAX).contains(&parsed.len()) => *colors = parsed, + _ => return Err(bad(cmd, format!("`colors` must be 1 to {GRADIENT_COLORS_GIVEN_MAX} colors ([r, g, b] linear or \"#rrggbb\" sRGB)"))), } } + if let Some(list) = p.get("positions") { + let parsed: Option> = + list.as_array().and_then(|given| given.iter().map(|place| place.as_f64().map(|place| (place as f32).clamp(0.0, 1.0))).collect()); + match parsed { + Some(parsed) if parsed.len() <= colors.len() => *positions = parsed, + _ => return Err(bad(cmd, "`positions` must be numbers in 0..1, at most one per color")), + } + } + if p.get("quantity").is_some() { + let wanted = u64p(p, "quantity") + .and_then(|count| u8::try_from(count).ok()) + .filter(|count| (GRADIENT_QUANTITY_MIN..=Filter::MAX_GRADIENT_COLORS).contains(count)); + let wanted = wanted + .ok_or_else(|| bad(cmd, format!("`quantity` must be a whole number from {GRADIENT_QUANTITY_MIN} to {}", Filter::MAX_GRADIENT_COLORS)))?; + set_quantity(colors, positions, quantity, wanted); + } + input.mode = choice(p, "grayscaleMode", &GrayscaleMode::ALL, GrayscaleMode::id, cmd)?.unwrap_or(input.mode); + set(&mut input.blur, "blur", 0.0, BLUR_INTENSITY_SLIDER_MAX); + set(&mut input.balance, "balance", 0.0, 1.0); + set(&mut input.contrast, "contrast", 0.0, 1.0); + for (key, slot) in [("invert", &mut input.invert), ("linear", linear), ("debug", debug)] { + switch(slot, key)?; + } } - Filter::Posterize { levels } => set(levels, "levels", 2.0, 64.0), - Filter::Clamp { min, max } => { + Filter::GradientCurve { preset, invert, balance, contrast } => { + *preset = choice(p, "preset", &CurvePreset::ALL, CurvePreset::id, cmd)?.unwrap_or(*preset); + switch(invert, "invert")?; + set(balance, "balance", 0.0, 1.0); + set(contrast, "contrast", 0.0, 1.0); + } + Filter::GradientDynamic { vertical, position, color } => { + *vertical = two_way(p, "orientation", "horizontal", "vertical", cmd)?.unwrap_or(*vertical); + set(position, "position", 0.0, 1.0); + shade(color)?; + } + Filter::Posterize { levels, alpha } => { + set(levels, "levels", POSTERIZE_LEVELS_MIN, POSTERIZE_LEVELS_MAX); + switch(alpha, "applyToAlpha")?; + } + Filter::Clamp { min, max } | Filter::Smoothstep { min, max } => { set(min, "min", 0.0, 1.0); set(max, "max", 0.0, 1.0); } - Filter::HistogramScan { position, contrast } => { + Filter::HeightAdjust { invert, offset, multiply } => { + switch(invert, "invert")?; + set(offset, "offset", -HEIGHT_OFFSET_MAX, HEIGHT_OFFSET_MAX); + set(multiply, "multiply", 0.0, HEIGHT_MULTIPLY_MAX); + } + Filter::HistogramScan { position, contrast, invert_position } => { set(position, "position", 0.0, 1.0); set(contrast, "contrast", 0.0, 1.0); + switch(invert_position, "invertPosition")?; } Filter::HistogramRange { range, position } => { set(range, "range", 0.0, 1.0); set(position, "position", 0.0, 1.0); } - Filter::HistogramShift { offset } => set(offset, "offset", -1.0, 1.0), - Filter::Warp { intensity, scale, seed: s } => { - set(intensity, "intensity", 0.0, 256.0); - set(scale, "scale", 0.01, 1000.0); - seed(s); + Filter::HistogramShift { offset } => { + set(offset, "offset", -1.0, 1.0); + if let Some(position) = f32p(p, "position") { + *offset = Filter::shift_offset(position); + } } - Filter::DirectionalBlur { radius, angle: a } => { - set(radius, "radius", 0.0, 256.0); - angle(a); + Filter::Warp { intensity, scale, seed: noise_seed, divider: intensity_divider } => { + set(intensity, "intensity", 0.0, TEXELS_MAX); + set(scale, "scale", Filter::NOISE_SCALE_MIN, Filter::NOISE_SCALE_MAX); + seed(noise_seed); + divider(intensity_divider)?; } - Filter::SlopeBlur { radius, scale, seed: s } => { - set(radius, "radius", 0.0, 256.0); - set(scale, "scale", 0.01, 1000.0); - seed(s); + Filter::DirectionalBlur { radius, angle: direction } => { + set(radius, "radius", 0.0, TEXELS_MAX); + blur_intensity(radius); + angle(direction); } - Filter::HighPass { radius } => set(radius, "radius", 0.0, 256.0), - Filter::EdgeDetect { width } | Filter::Bevel { width } => set(width, "width", 0.0, 256.0), - Filter::Mosaic { size } => set(size, "size", 1.0, 512.0), + Filter::SlopeBlur { radius, scale, seed: noise_seed, divider: intensity_divider } => { + set(radius, "radius", 0.0, TEXELS_MAX); + set(scale, "scale", Filter::NOISE_SCALE_MIN, Filter::NOISE_SCALE_MAX); + seed(noise_seed); + divider(intensity_divider)?; + } + Filter::HighPass { radius, space, alpha } => { + set(radius, "radius", 0.0, TEXELS_MAX); + blur_intensity(radius); + *space = choice(p, "colorSpace", &HighpassSpace::ALL, HighpassSpace::id, cmd)?.unwrap_or(*space); + switch(alpha, "applyToAlpha")?; + } + Filter::EdgeDetect { width } => set(width, "width", 0.0, TEXELS_MAX), + Filter::Bevel { width, wrap: wraps } => { + set(width, "width", 0.0, TEXELS_MAX); + switch(wraps, "wrap")?; + } + Filter::Mosaic { size, alpha } => { + set(size, "size", 1.0, MOSAIC_SIZE_MAX); + if let Some(amount) = f32p(p, "pixelsAmount") { + *size = Filter::pixel_size(amount.round()); + } + switch(alpha, "applyToAlpha")?; + } + Filter::Fxaa { alpha } => switch(alpha, "affectAlphaChannel")?, Filter::Glow { radius, amount } => { - set(radius, "radius", 0.0, 256.0); - set(amount, "amount", 0.0, 10.0); + set(radius, "radius", 0.0, TEXELS_MAX); + set(amount, "amount", 0.0, GLOW_AMOUNT_MAX); + } + Filter::HaloGlow { on_mask, precise, width, spread, opacity, color } => { + switch(on_mask, "usedOnMask")?; + *precise = two_way(p, "mode", "soft", "precise", cmd)?.unwrap_or(*precise); + set(width, "width", -1.0, 1.0); + set(spread, "spread", 0.0, 1.0); + set(opacity, "opacity", 0.0, 1.0); + shade(color)?; + } + Filter::DropShadow { angle: direction, distance, size, spread, opacity, color } => { + angle(direction); + set(distance, "distance", -Filter::SHADOW_DISTANCE_MAX, Filter::SHADOW_DISTANCE_MAX); + set(size, "size", 0.0, 1.0); + set(spread, "spread", 0.0, 1.0); + set(opacity, "opacity", 0.0, 1.0); + shade(color)?; } Filter::ReplaceColor { from, to, tolerance, softness } => { for (key, slot) in [("from", from), ("to", to)] { - if let Some(v) = color_param(cmd, p, key)? { - *slot = v.map(|x| x.clamp(0.0, 1.0)); + if let Some(rgb) = color_param(cmd, p, key)? { + *slot = rgb.map(|x| x.clamp(0.0, 1.0)); } } set(tolerance, "tolerance", 0.0, 1.0); set(softness, "softness", 0.0, 1.0); } - Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion } => { - if let Some(v) = f32p(p, "azimuth") { - *azimuth = v.rem_euclid(360.0); + Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, stylized } => { + if let Some(degrees) = f32p(p, "azimuth") { + *azimuth = degrees.rem_euclid(FULL_TURN_DEGREES); } - set(elevation, "elevation", -90.0, 90.0); - set(light, "light", 0.0, 10.0); - set(ambient, "ambient", 0.0, 10.0); + + // A light past the zenith comes from the far side: the angle wraps like the horizontal one + if let Some(degrees) = f32p(p, "elevation") { + *elevation = degrees.rem_euclid(FULL_TURN_DEGREES); + } + set(light, "light", 0.0, SUN_INTENSITY_MAX); + set(ambient, "ambient", 0.0, SKY_INTENSITY_MAX); set(occlusion, "occlusion", 0.0, 1.0); + + // A Baked Lighting saved before the stylized settings takes them lit as it was + if crate::stylized_lighting_params::sets_any(p) { + crate::stylized_lighting_params::apply(p, stylized.get_or_insert_with(|| Box::new(StylizedLighting::PLAIN)), cmd)?; + } } - Filter::DirectionalWarp { intensity, angle: a, scale, seed: s } => { - set(intensity, "intensity", 0.0, 256.0); - angle(a); - set(scale, "scale", 0.01, 1000.0); - seed(s); + Filter::EnvironmentLighting { horizontal, vertical, exposure, height_intensity, ambient_occlusion, specular_occlusion } => { + for (key, slot) in [("horizontalRotation", horizontal), ("verticalRotation", vertical)] { + if let Some(degrees) = f32p(p, key) { + *slot = degrees.rem_euclid(FULL_TURN_DEGREES); + } + } + set(exposure, "exposure", -Filter::ENVIRONMENT_EXPOSURE_STOPS, Filter::ENVIRONMENT_EXPOSURE_STOPS); + set(height_intensity, "heightIntensity", 0.0, HEIGHT_INTENSITY_MAX); + set(ambient_occlusion, "ambientOcclusion", 0.0, 1.0); + set(specular_occlusion, "specularOcclusion", 0.0, 1.0); + } + Filter::DirectionalWarp { intensity, angle: direction, scale, seed: noise_seed, divider: intensity_divider } => { + set(intensity, "intensity", 0.0, TEXELS_MAX); + angle(direction); + set(scale, "scale", Filter::NOISE_SCALE_MIN, Filter::NOISE_SCALE_MAX); + seed(noise_seed); + divider(intensity_divider)?; } } Ok(()) @@ -338,19 +1091,85 @@ mod tests { #[test] fn every_filter_builds_and_finds_by_id_or_label() { - for f in FILTERS { - let kind = build(f.id, &Value::Null).unwrap_or_else(|e| panic!("{}: {e}", f.id)); - // Material finishes are content only; other filters also run on masks, where some - // (grayscale, normal invert) change nothing and are not offered. - assert_eq!(kind.content_only().is_none(), f.mask || matches!(kind, EffectKind::Filter(_)), "{}", f.id); - assert_eq!(find(f.label).map(|d| d.id), Some(f.id)); + for def in FILTERS { + let kind = build(def.id, &Value::Null).unwrap_or_else(|err| panic!("{}: {err}", def.id)); + + // Material finishes are content only; other filters also run on masks, where some (normal invert) change nothing and are not offered + assert_eq!(kind.content_only().is_none(), def.mask || matches!(kind, EffectKind::Filter(_)), "{}", def.id); + assert_eq!(find(def.label).map(|found| found.id), Some(def.id)); } + + let EffectKind::Filter(Filter::Posterize { levels, .. }) = build("posterize", &json!({"levels": 1000})).unwrap() else { panic!() }; + assert_eq!(levels, POSTERIZE_LEVELS_MAX); + assert!(build("nope", &Value::Null).is_err()); - let EffectKind::Filter(Filter::Posterize { levels }) = build("posterize", &json!({"levels": 1000})).unwrap() else { panic!() }; - assert_eq!(levels, 64.0); assert!(build("gradientMap", &json!({"colors": []})).is_err()); assert!(build("colorBalance", &json!({"shadows": "x"})).is_err()); - let EffectKind::Filter(Filter::GradientMap { colors }) = build("gradientMap", &json!({"colors": [[0, 0, 0], "#ffffff"]})).unwrap() else { panic!() }; + + let EffectKind::Filter(Filter::GradientMap { colors, .. }) = build("gradientMap", &json!({"colors": [[0, 0, 0], "#ffffff"]})).unwrap() else { + panic!() + }; + assert_eq!(colors.len(), 2); } + + #[test] + fn a_new_gradient_given_colors_and_a_quantity_spaces_them_evenly() { + let five = [[0.0; 3], [0.25; 3], [0.5; 3], [0.75; 3], [1.0; 3]]; + for (given, quantity, expected) in [(&five[..2], 2, vec![0.0, 1.0]), (&five[..], 5, vec![0.0, 0.25, 0.5, 0.75, 1.0])] { + let params = json!({"colors": given, "quantity": quantity}); + + let EffectKind::Filter(Filter::GradientMap { positions, quantity: used, .. }) = build("gradientMap", ¶ms).unwrap() else { panic!() }; + + assert_eq!(positions, expected, "{params}"); + assert_eq!(used, Some(quantity)); + } + } + + /// A gradient given its colors and their places ramps through all of them, not the library's three + #[test] + fn a_new_gradient_given_colors_and_places_uses_every_color() { + let five = [[0.0; 3], [0.25; 3], [0.5; 3], [0.75; 3], [1.0; 3]]; + let places = [0.0, 0.1, 0.2, 0.3, 1.0]; + + let EffectKind::Filter(filter) = build("gradientMap", &json!({"colors": five, "positions": places})).unwrap() else { panic!() }; + + assert_eq!(filter.ramp_colors().len(), five.len()); + assert!(matches!(&filter, Filter::GradientMap { positions, .. } if positions[..] == places)); + } + + /// Raising Color Quantity leaves the colors the gradient had where they were, placed or not + #[test] + fn raising_the_quantity_keeps_colors_without_a_place_where_they_were() { + let three = json!({"colors": [[0, 0, 0], [1, 0, 0], [1, 1, 1]], "positions": [0.0]}); + let EffectKind::Filter(mut filter) = build("gradientMap", &three).unwrap() else { panic!() }; + let middle = filter.ramp_at(0.5); + + apply(&json!({"quantity": 4}), &mut filter, "effect.set").unwrap(); + + assert_eq!(filter.ramp_at(0.5), middle); + assert!(matches!(&filter, Filter::GradientMap { positions, .. } if positions[..] == [0.0, 0.5, 1.0, 1.0]), "{filter:?}"); + } + + #[test] + fn every_filter_row_reads_a_reference_name_without_an_internal_unit() { + let old_saves = [ + Filter::Warp { intensity: 8.0, scale: 4.0, seed: 1, divider: 1 }, + Filter::SlopeBlur { radius: 8.0, scale: 4.0, seed: 1, divider: 1 }, + Filter::DirectionalWarp { intensity: 8.0, angle: 0.0, scale: 4.0, seed: 1, divider: 1 }, + Filter::EdgeDetect { width: 2.0 }, + Filter::Bevel { width: 8.0, wrap: false }, + Filter::Glow { radius: 16.0, amount: 1.0 }, + ]; + let library = FILTERS.iter().filter_map(|def| match build(def.id, &Value::Null) { + Ok(EffectKind::Filter(filter)) => Some(filter), + _ => None, + }); + for filter in old_saves.into_iter().chain(library) { + for (key, label, ..) in scalar_params(&filter) { + let title_case = label.split([' ', '/']).filter(|word| !word.is_empty()).all(|word| word.starts_with(|c: char| !c.is_lowercase())); + assert!(title_case && !label.contains("texels") && !label.contains("degrees"), "{key}: {label}"); + } + } + } } diff --git a/crates/engine/src/stylized_lighting_params.rs b/crates/engine/src/stylized_lighting_params.rs new file mode 100644 index 00000000..6a6b6b78 --- /dev/null +++ b/crates/engine/src/stylized_lighting_params.rs @@ -0,0 +1,99 @@ +//! `effect.set` keys of Baked Lighting Stylized past Baked Lighting's sun and ambient + +use serde_json::Value; +use texturecraft_core::{DirectionalLight, LightingOutput, StylizedLighting}; + +use crate::Result; +use crate::commands::{bad, f32p}; +use crate::filter_lib::{choice, set_color, two_way}; +use crate::layer_cmds::FULL_TURN_DEGREES; + +/// The keys that give a Baked Lighting saved before them its stylized settings +pub(crate) const KEYS: [&str; 17] = [ + "sunColor", + "skyColor", + "horizonColor", + "groundColor", + "light1", + "light2", + "diffuseCavity", + "specularAo", + "specularCavity", + "cavitySmoothness", + "edgesIntensity", + "edgesSmoothness", + "input", + "output", + "dielectricReflectance", + "normalDetails", + "heightToNormal", +]; + +/// The highest Dielectric Reflectance, Cavity Smoothness and Height to Normal Intensity +pub const MAX_DIELECTRIC_REFLECTANCE: f32 = 0.16; +pub const MAX_CAVITY_SMOOTHNESS: f32 = 4.0; +pub const MAX_HEIGHT_TO_NORMAL: f32 = 3.0; + +/// The highest intensity of Light 1 and Light 2 +pub const MAX_LIGHT_INTENSITY: f32 = 2.0; + +/// Whether `p` sets any stylized setting +pub(crate) fn sets_any(p: &Value) -> bool { + KEYS.iter().any(|key| p.get(*key).is_some()) +} + +/// Set the stylized settings `p` names on `lighting`, clamped; a bad color or choice is refused +pub(crate) fn apply(p: &Value, lighting: &mut StylizedLighting, cmd: &str) -> Result<()> { + let set = |slot: &mut f32, key: &str, high: f32| { + if let Some(value) = f32p(p, key) { + *slot = value.clamp(0.0, high); + } + }; + + for (key, slot) in [ + ("sunColor", &mut lighting.sun_color), + ("skyColor", &mut lighting.sky_color), + ("horizonColor", &mut lighting.horizon_color), + ("groundColor", &mut lighting.ground_color), + ] { + set_color(p, key, slot, cmd)?; + } + + for (key, light) in ["light1", "light2"].into_iter().zip(lighting.lights.iter_mut()) { + if let Some(params) = p.get(key) { + set_light(params, light, key, cmd)?; + } + } + + set(&mut lighting.diffuse_cavity, "diffuseCavity", 1.0); + set(&mut lighting.specular_ao, "specularAo", 1.0); + set(&mut lighting.specular_cavity, "specularCavity", 1.0); + set(&mut lighting.cavity_smoothness, "cavitySmoothness", MAX_CAVITY_SMOOTHNESS); + set(&mut lighting.edges_intensity, "edgesIntensity", 1.0); + set(&mut lighting.edges_smoothness, "edgesSmoothness", 1.0); + set(&mut lighting.dielectric_reflectance, "dielectricReflectance", MAX_DIELECTRIC_REFLECTANCE); + set(&mut lighting.height_to_normal, "heightToNormal", MAX_HEIGHT_TO_NORMAL); + + lighting.specular_glossiness = two_way(p, "input", "metalRoughness", "specularGlossiness", cmd)?.unwrap_or(lighting.specular_glossiness); + lighting.output = choice(p, "output", &LightingOutput::ALL, LightingOutput::id, cmd)?.unwrap_or(lighting.output); + lighting.mesh_only = two_way(p, "normalDetails", "meshHeightNormal", "mesh", cmd)?.unwrap_or(lighting.mesh_only); + Ok(()) +} + +/// Light 1 or Light 2 from `{azimuth, elevation, intensity, color}` (any of them) +fn set_light(p: &Value, light: &mut DirectionalLight, key: &str, cmd: &str) -> Result<()> { + if !p.is_object() { + return Err(bad(cmd, format!("`{key}` must be an object {{azimuth, elevation, intensity, color}}"))); + } + + if let Some(degrees) = f32p(p, "azimuth") { + light.azimuth = degrees.rem_euclid(FULL_TURN_DEGREES); + } + if let Some(degrees) = f32p(p, "elevation") { + light.elevation = degrees.rem_euclid(FULL_TURN_DEGREES); + } + if let Some(intensity) = f32p(p, "intensity") { + light.intensity = intensity.clamp(0.0, MAX_LIGHT_INTENSITY); + } + set_color(p, "color", &mut light.color, cmd) +} diff --git a/crates/engine/tests/it/filter_stylize.rs b/crates/engine/tests/it/filter_stylize.rs new file mode 100644 index 00000000..13b28c90 --- /dev/null +++ b/crates/engine/tests/it/filter_stylize.rs @@ -0,0 +1,242 @@ +//! Anisotropic Kuwahara, PBR Validate (Metallic Roughness), Height To Normal and Color Match + +use serde_json::json; +use texturecraft_engine::core::{ + AnisotropicKuwahara, Channel, ColorMatch, Filter, HeightToNormal, PbrValidate, SourceColorMode, TargetColorMode, ValidationMode, +}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, filter_of, refused, session, set, sized_session}; + +/// The composited base color at texel `(x, y)` +fn base_color(s: &mut Session, (x, y): (u32, u32)) -> [f32; 3] { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, x, y) +} + +/// Texels across a set fine enough for filters measured in texels at 2K (Kuwahara's radius, a height's slope) +const FINE_SET_SIZE: u32 = 512; + +/// A new Anisotropic Kuwahara starts where the reference does, takes every setting (one undo step) and smooths a noisy fill +#[test] +fn anisotropic_kuwahara_takes_its_settings_and_smooths() { + let mut s = sized_session(FINE_SET_SIZE); + let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap()["layer"].as_u64().unwrap(); + let pattern = json!({"layer": fill, "channel": "baseColor", "procedural": "Clouds", "scale": 64, "low": [0, 0, 0], "high": [1, 1, 1]}); + execute(&mut s, "layer.fill.set", &pattern).unwrap(); + let texels: Vec<(u32, u32)> = (0..32).map(|k| (FINE_SET_SIZE / 4 + k, FINE_SET_SIZE / 2)).collect(); + let before: Vec = texels.iter().map(|t| base_color(&mut s, *t)[0]).collect(); + + let effect = add_filter(&mut s, json!({"filter": "Anisotropic Kuwahara"})); + assert_eq!(filter_of(&s, effect), Filter::AnisotropicKuwahara(AnisotropicKuwahara::LIBRARY)); + + set(&mut s, effect, json!({"radius": AnisotropicKuwahara::MAX_RADIUS})); + let after: Vec = texels.iter().map(|t| base_color(&mut s, *t)[0]).collect(); + let steps = |v: &[f32]| v.windows(2).map(|w| (w[1] - w[0]).abs()).sum::(); + assert!(steps(&after) < steps(&before) * 0.9, "smoother: {} vs {}", steps(&after), steps(&before)); + + let all = json!({"extractDirection": "customInput", "radius": 20.0, "smoothness": 0.5, "sharpness": 0.1, + "tensorSmoothness": 0.3, "anisotropy": 0.4, "angle": 390.0}); + set(&mut s, effect, all); + let expected = AnisotropicKuwahara { + custom_input: true, + radius: AnisotropicKuwahara::MAX_RADIUS, + smoothness: 0.5, + sharpness: 0.25, + tensor_smoothness: 0.3, + anisotropy: 0.4, + angle: 30.0, + }; + assert_eq!(filter_of(&s, effect), Filter::AnisotropicKuwahara(expected), "clamped, the angle wrapped"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "extractDirection": "luma"})).is_err()); + + let read = base_color(&mut s, texels[0]); + assert!(read.iter().all(|v| v.is_finite()), "a flat Custom Input reads no direction: {read:?}"); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + let Filter::AnisotropicKuwahara(undone) = filter_of(&s, effect) else { panic!("still Kuwahara") }; + assert_eq!(undone, AnisotropicKuwahara { radius: AnisotropicKuwahara::MAX_RADIUS, ..AnisotropicKuwahara::LIBRARY }, "one undo step"); + + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Anisotropic Kuwahara")); +} + +/// PBR Validate starts with the Color and Metal pills on, shows a too dark non-metal base color in red, leaves the metal as it is and takes its three switches +#[test] +fn pbr_validate_marks_implausible_base_colors() { + let mut s = session(); + let texel = (SIZE / 4, SIZE / 2); + + // sRGB 20: darker than both dark thresholds + let dark = 0.007; + execute(&mut s, "layer.add.fill", &json!({"color": [dark, dark, dark], "metallic": 0.0})).unwrap(); + let effect = add_filter(&mut s, json!({"filter": "pbrValidate"})); + assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate::LIBRARY)); + + let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Metallic) && off.contains(&Channel::Roughness), "{off:?}"); + assert_eq!(base_color(&mut s, texel), PbrValidate::INVALID, "too dark"); + assert_eq!(s.caches[0].composite.value(Channel::Metallic, texel.0, texel.1)[0], 0.0, "the metal is left as it is"); + + set(&mut s, effect, json!({"validationMode": "metal"})); + let shown = base_color(&mut s, texel); + assert!((shown[0] - dark).abs() < 1e-3, "Metal leaves non-metal colors unchecked: {shown:?}"); + + set(&mut s, effect, json!({"validationMode": "albedo", "albedoDarkRangeThreshold": 50, "metalReflectanceRange": 70})); + assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate { mode: ValidationMode::Albedo, albedo_dark: 50, metal_low: 70 })); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "albedoDarkRangeThreshold": 40})).is_err()); + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "validationMode": "all"})).is_err()); +} + +/// The composited packed normal at texel `(x, y)` +fn normal(s: &mut Session, (x, y): (u32, u32)) -> [f32; 3] { + s.update(); + s.caches[0].composite.value(Channel::Normal, x, y) +} + +/// How far the packed normals of `texels` tilt from flat, summed +fn tilt(s: &mut Session, texels: &[(u32, u32)]) -> f32 { + texels.iter().map(|texel| normal(s, *texel)).map(|[x, y, _]| (x - 0.5).abs() + (y - 0.5).abs()).sum() +} + +/// Height To Normal starts with the Normal pill only, turns the layer's height into its normal, overwrites or overlays it, one undo step +#[test] +fn height_to_normal_turns_the_height_into_the_normal() { + let mut s = sized_session(FINE_SET_SIZE); + let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap()["layer"].as_u64().unwrap(); + let bumps = json!({"layer": fill, "channel": "height", "procedural": "Clouds", "scale": 16, "low": [-0.05, -0.05, -0.05], "high": [0.05, 0.05, 0.05]}); + execute(&mut s, "layer.fill.set", &bumps).unwrap(); + let texels: Vec<(u32, u32)> = (0..32).map(|k| (FINE_SET_SIZE / 4 + k, FINE_SET_SIZE / 2)).collect(); + assert!(tilt(&mut s, &texels) < 1e-3, "a fill's own normal is flat"); + + let color = base_color(&mut s, texels[0]); + + let effect = add_filter(&mut s, json!({"filter": "heightToNormal"})); + assert_eq!(filter_of(&s, effect), Filter::HeightToNormal(HeightToNormal::LIBRARY)); + + let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::Normal) && off.contains(&Channel::BaseColor) && off.contains(&Channel::Height), "{off:?}"); + + let made = tilt(&mut s, &texels); + assert!(made > 0.01, "the bumps tilt the normal: {made}"); + assert_eq!(base_color(&mut s, texels[0]), color, "the base color is left as it is"); + + set(&mut s, effect, json!({"heightDepth": 64.0})); + assert!(tilt(&mut s, &texels) > made * 1.5, "deeper heights tilt more"); + + set(&mut s, effect, json!({"useWorldUnits": false, "normalIntensity": 0.0})); + assert!(tilt(&mut s, &texels) < 1e-3, "no intensity: flat"); + + execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "normal", "value": [0.7, 0.5, 0.95]})).unwrap(); + assert!(tilt(&mut s, &texels) < 1e-3, "Overwrite Existing Normal replaces the fill's normal"); + + set(&mut s, effect, json!({"overwriteExistingNormal": false})); + assert!((normal(&mut s, texels[0])[0] - 0.7).abs() < 0.02, "laid over the fill's normal: {:?}", normal(&mut s, texels[0])); + + let all = json!({"overwriteExistingNormal": true, "useWorldUnits": true, "surfaceSize": 0.0, "heightDepth": 500.0, + "normalIntensity": 70.0}); + set(&mut s, effect, all); + let expected = HeightToNormal { + surface_size: 1.0, + height_depth: HeightToNormal::MAX_HEIGHT_DEPTH, + intensity: HeightToNormal::MAX_INTENSITY, + ..HeightToNormal::LIBRARY + }; + assert_eq!(filter_of(&s, effect), Filter::HeightToNormal(expected), "clamped"); + assert!(normal(&mut s, texels[0]).iter().all(|v| v.is_finite())); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + let Filter::HeightToNormal(undone) = filter_of(&s, effect) else { panic!("still Height To Normal") }; + assert!(!undone.overwrite && undone.surface_size == 300.0, "one undo step: {undone:?}"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "useWorldUnits": "yes"})).is_err()); + + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Height To Normal")); +} + +/// Color Match starts with the Color pill only and moves the colors to its target keeping their pattern, all of them at the Color Variation's 0, keeping each texel's difference from the whole texture's mean without Custom Color Variation; Parameter and Image Input modes read their colors +#[test] +fn color_match_moves_the_colors_to_the_target() { + let mut s = session(); + let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap()["layer"].as_u64().unwrap(); + let reds = json!({"layer": fill, "channel": "baseColor", "procedural": "Clouds", "scale": 8, "low": [0.3, 0.02, 0.02], "high": [0.9, 0.1, 0.1]}); + execute(&mut s, "layer.fill.set", &reds).unwrap(); + let texels: Vec<(u32, u32)> = (0..24).map(|k| (SIZE / 4 + k * 2, SIZE / 2)).collect(); + let before: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + let spread = |colors: &[[f32; 3]]| colors.iter().map(|c| c[0]).fold(f32::MIN, f32::max) - colors.iter().map(|c| c[0]).fold(f32::MAX, f32::min); + assert!(spread(&before) > 0.05, "the clouds vary: {before:?}"); + + let effect = add_filter(&mut s, json!({"filter": "Color Match"})); + assert_eq!(filter_of(&s, effect), Filter::ColorMatch(ColorMatch::LIBRARY)); + + let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness), "{off:?}"); + + let new: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + assert!(spread(&new) > 0.02, "a new Color Match keeps the pattern: {new:?}"); + + let redness = new.iter().map(|c| c[0] - c[2]).sum::() / new.len() as f32; + assert!(redness.abs() < 0.05, "around the gray target: {redness} {new:?}"); + + // Color Variation at 0: every texel is the target itself + set(&mut s, effect, json!({"hue": 0.0, "chroma": 0.0, "luma": 0.0})); + let gray = ColorMatch::LIBRARY.target_color; + for texel in &texels { + let color = base_color(&mut s, *texel); + assert!(color.iter().zip(gray).all(|(v, g)| (v - g).abs() < 2e-3), "Color Variation 0: the target itself, {color:?}"); + } + + // Without Custom Color Variation the texels keep their differences from the mean, now around the target + set(&mut s, effect, json!({"customColorVariation": false})); + let kept: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + assert!(spread(&kept) > 0.02, "variation kept: {kept:?}"); + + let redness = kept.iter().map(|c| c[0] - c[2]).sum::() / kept.len() as f32; + assert!(redness.abs() < 0.05, "the reds are gray on average now: {redness} {kept:?}"); + + let brighter = |colors: &[[f32; 3]], a: usize, b: usize| colors[a][0] + colors[a][1] > colors[b][0] + colors[b][1]; + let (lightest, darkest) = + (0..texels.len()).fold((0, 0), |(hi, lo), k| (if before[k][0] > before[hi][0] { k } else { hi }, if before[k][0] < before[lo][0] { k } else { lo })); + assert!(brighter(&kept, lightest, darkest), "the lightest red stays the lightest"); + + // Source Color Parameter: the texels of that color land on the target + let source = before[lightest]; + set(&mut s, effect, json!({"sourceColorMode": "parameter", "sourceColor": source, "targetColor": [0.05, 0.1, 0.6]})); + let landed = base_color(&mut s, texels[lightest]); + assert!((landed[2] - 0.6).abs() < 0.01 && (landed[0] - 0.05).abs() < 0.01, "{landed:?}"); + + // Image Input: mid gray until a source is set + let all = json!({"sourceColorMode": "input", "targetColorMode": "imageInput", "customColorVariation": true, "hue": 400.0, + "chroma": 2.0, "luma": -1.0}); + set(&mut s, effect, all); + let expected = ColorMatch { + source_mode: SourceColorMode::Input, + source_color: source, + target_mode: TargetColorMode::ImageInput, + target_color: [0.05, 0.1, 0.6], + custom_variation: true, + hue: 360.0, + chroma: 1.0, + luma: 0.0, + }; + assert_eq!(filter_of(&s, effect), Filter::ColorMatch(expected), "clamped"); + + set(&mut s, effect, json!({"chroma": 0.0, "hue": 0.0})); + let image = base_color(&mut s, texels[0]); + assert!(image.iter().all(|v| (v - 0.5).abs() < 2e-3), "the Image Input's mid gray: {image:?}"); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + let Filter::ColorMatch(undone) = filter_of(&s, effect) else { panic!("still Color Match") }; + assert_eq!((undone.hue, undone.chroma), (360.0, 1.0), "one undo step: {undone:?}"); + + refused( + &mut s, + effect, + &[json!({"sourceColorMode": "median"}), json!({"targetColorMode": "input"}), json!({"customColorVariation": 1}), json!({"targetColor": "red"})], + ); + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Color Match")); +} diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs index df495231..e37b8e79 100644 --- a/crates/engine/tests/it/filter_support.rs +++ b/crates/engine/tests/it/filter_support.rs @@ -1,9 +1,13 @@ //! What the filter tests share: their sessions and reading the composite +//! What the filter tests share: their sessions, adding, setting and refusing a filter, and reading the composite use texturecraft_engine::Session; use texturecraft_engine::core::Channel; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; /// The texture set side the filter tests paint on pub(crate) const SIZE: u32 = 128; @@ -45,3 +49,46 @@ pub(crate) fn center(s: &mut Session, channel: Channel) -> [f32; 3] { let uv = center_uv(s); s.caches[0].composite.value(channel, (uv.x * SIZE as f32) as u32, (uv.y * SIZE as f32) as u32) } + +/// The composited roughness at texel `(x, y)` +pub(crate) fn roughness(s: &mut Session, (x, y): (u32, u32)) -> f32 { + s.update(); + s.caches[0].composite.value(Channel::Roughness, x, y)[0] +} + +/// Content filter `params` on the selected layer: the effect +pub(crate) fn add_filter(s: &mut Session, params: Value) -> LayerId { + let mut params = params; + params["target"] = json!("content"); + LayerId(execute(s, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) +} + +/// A fill layer of base color `color` and roughness 0.3 under content filter `params`: the effect +pub(crate) fn filtered(s: &mut Session, color: [f32; 3], params: Value) -> LayerId { + execute(s, "layer.add.fill", &json!({"color": color, "roughness": 0.3})).unwrap(); + add_filter(s, params) +} + +/// The filter `effect` holds +pub(crate) fn filter_of(s: &Session, effect: LayerId) -> Filter { + match &s.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Filter(filter) => filter.clone(), + other => panic!("not a filter: {other:?}"), + } +} + +/// `effect.set` on `effect` with `params`, which must succeed +pub(crate) fn set(s: &mut Session, effect: LayerId, params: Value) { + let mut params = params; + params["effect"] = json!(effect.0); + execute(s, "effect.set", ¶ms).unwrap(); +} + +/// Each of `bad` is refused by `effect.set` on `effect` +pub(crate) fn refused(s: &mut Session, effect: LayerId, bad: &[Value]) { + for bad in bad { + let mut params = bad.clone(); + params["effect"] = json!(effect.0); + assert!(execute(s, "effect.set", ¶ms).is_err(), "{bad}"); + } +} From 73ac56a987ee4e467fc3d37e964180e3ed10ea1a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:30:00 +0000 Subject: [PATCH 2/6] Filters: the FILTER panel, its card, picker and parameters --- crates/ui-egui/src/filter_properties.rs | 1160 +++++++++++++++++ crates/ui-egui/src/filter_slot.rs | 97 +- crates/ui-egui/src/filter_transform_rows.rs | 91 ++ .../src/property_sheet/attribute_rows.rs | 60 + .../src/property_sheet/gradient_rows.rs | 120 ++ crates/ui-egui/tests/it/filter_card.rs | 105 ++ crates/ui-egui/tests/it/filter_gradient.rs | 163 +++ crates/ui-egui/tests/it/filter_inputs.rs | 114 ++ crates/ui-egui/tests/it/filter_picker.rs | 73 +- crates/ui-egui/tests/it/filter_support.rs | 68 + 10 files changed, 1947 insertions(+), 104 deletions(-) create mode 100644 crates/ui-egui/src/filter_properties.rs create mode 100644 crates/ui-egui/src/filter_transform_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/attribute_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/gradient_rows.rs create mode 100644 crates/ui-egui/tests/it/filter_card.rs create mode 100644 crates/ui-egui/tests/it/filter_gradient.rs create mode 100644 crates/ui-egui/tests/it/filter_inputs.rs diff --git a/crates/ui-egui/src/filter_properties.rs b/crates/ui-egui/src/filter_properties.rs new file mode 100644 index 00000000..028af176 --- /dev/null +++ b/crates/ui-egui/src/filter_properties.rs @@ -0,0 +1,1160 @@ +//! The Filter effect's properties: FILTER over the channel pills (content), the filter card holding its parameters and Attributes, then its image inputs' cards + +use std::ops::RangeInclusive; + +use egui::{Painter, Rect, Stroke, StrokeKind, Ui}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + AnisotropicKuwahara, Bevel, BevelBlur, BevelCorner, BevelDirection, BevelSmooth, Channel, ColorMatch, ConversionMode, CurvePreset, DirectionalLight, + EffectKind, Filter, GrayscaleConversion, GrayscaleMode, HeightToNormal, HighpassSpace, ImageInput, LayerId, LightingOutput, MaskOutline, Mirror, + MirrorCorner, MirrorMode, OutlinePosition, PbrValidate, SlopeBlending, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedLighting, TargetColorMode, + ThresholdMode, ValidationMode, WarpBlending, WarpMode, WarpSourceMode, +}; +use texturecraft_engine::filter_lib::{ + BEVEL_SMOOTHING_MAX, BLUR_INTENSITY_SLIDER_MAX, DISTANCE_BEVEL_SMOOTHING_MAX, FilterDef, GRADIENT_QUANTITY_MIN, MAX_CAVITY_SMOOTHNESS, + MAX_DIELECTRIC_REFLECTANCE, MAX_HEIGHT_TO_NORMAL, MAX_LIGHT_INTENSITY, SKY_INTENSITY_SLIDER_MAX, SMOOTH_DISTANCE_MAX, SOURCE_TILING_MAX, SOURCE_TILING_MIN, + SUN_INTENSITY_MAX, build, find, scalar_params, +}; +use texturecraft_engine::paint::FULL_TURN_DEGREES; + +use crate::TextureCraftApp; +use crate::fill_material_panel::pill_name; +use crate::i18n::{tr, trf}; +use crate::property_sheet::PropertySheet; +use crate::theme::{AXIS_COLORS, OPPOSITE_COLORS, Tokens}; + +/// Where TextureCraft's filters come from: the repository, without its scheme +const AUTHOR_URL: &str = "github.com/storytold/texturecraft"; + +/// What a filter's angle rows span, in degrees: one full turn of their dial +pub(crate) const DIAL_DEGREES: RangeInclusive = 0.0..=FULL_TURN_DEGREES; + +/// The decimals Height To Normal's Normal Intensity shows +const INTENSITY_DECIMALS: usize = 2; + +/// The widest Divider chip text: the chip keeps one width whatever it shows +const WIDEST_DIVIDER: &str = "÷1000"; + +/// The properties of filter effect `effect` (`filter`), with its channel pills when it sits on the layer content +pub(crate) fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect: LayerId, filter: &Filter) { + let on_mask = crate::filter_slot::is_on_mask(app, effect.0); + PropertySheet::show(ui, ("filter_sheet", effect.0), |sheet| { + sheet.section(tr("Filter"), false); + if !on_mask { + let off: Vec = app.session.doc.project.effect(effect).map(|(_, found)| found.off_channels.iter().copied().collect()).unwrap_or_default(); + channel_pills(app, sheet, effect, &off); + } + let def = find(filter.label()); + let defaults = def.and_then(defaults_of); + let changed = defaults.as_ref().is_some_and(|defaults| defaults != filter); + if filter_card(app, sheet, effect, filter, def, changed) { + app.run("effect.filter.restoreDefaults", json!({"effect": effect.0})); + } + if *filter == Filter::Empty { + return; + } + + // The card holds the filter's settings, as a material channel's card does: sub-groups are captions in it, Attributes its last folded row + sheet.slot_rule(); + sheet.hold_card(); + parameters(app, sheet, effect.0, filter); + if sheet.closing_fold(tr("Attributes")) { + attributes(app, sheet, def); + } + sheet.release_card(); + + // Inputs every mode reads: their own slot cards after the filter's + for input in ImageInput::of(filter).into_iter().filter(|input| !input.by_mode) { + input_slot(app, sheet, effect, input, false); + } + if let Filter::GradientDynamic { color, .. } = filter { + gradient_source(app, sheet, effect.0, *color); + } + }); +} + +/// The filter's read-only Attributes (library entry `def`): what it does, who made it, the words it is found by and the size it works at +fn attributes(app: &TextureCraftApp, sheet: &mut PropertySheet<'_>, def: Option<&FilterDef>) { + let about = def.and_then(|def| def.about()); + if let Some(about) = about { + sheet.attribute_text(tr("Description"), tr(about.description)); + } + sheet.attribute(tr("Category"), tr("Filter")); + sheet.attribute(tr("Author"), "TextureCraft"); + sheet.attribute(tr("Author URL"), AUTHOR_URL); + if let Some(about) = about { + sheet.attribute(tr("Tags"), &about.tags.iter().map(|tag| tr(tag)).collect::>().join(", ")); + } + if let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) { + sheet.attribute(tr("Size"), &format!("{0} × {0}", texture_set.resolution)); + } +} + +/// The slot card of image input `input` of filter effect `effect` (its row only, inside the card open now, when `in_card`): the source it reads, picked like a mask fill's +fn input_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, effect: LayerId, input: ImageInput, in_card: bool) { + let Some((reader, source)) = app.session.doc.project.effect(effect).map(|(owner, found)| (owner, found.input(&input))) else { return }; + crate::fill_material_panel::source_card(app, sheet, source, &json!({"effect": effect.0}), crate::source_slot::SourceSlot::Input(input), reader, in_card); +} + +/// The library defaults of filter `def` +fn defaults_of(def: &FilterDef) -> Option { + match build(def.id, &Value::Null) { + Ok(EffectKind::Filter(defaults)) => Some(defaults), + _ => None, + } +} + +/// One pill per texture set channel, lit where the filter works; Alt+click keeps only the clicked one +fn channel_pills(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, effect: LayerId, off: &[Channel]) { + 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 on: Vec = channels.iter().map(|channel| !off.contains(channel)).collect(); + let Some((index, solo)) = sheet.channel_pills(&names, &on) else { return }; + let Some(clicked) = channels.get(index) else { return }; + + let switched: serde_json::Map = if solo { + channels.iter().map(|channel| (channel.id().to_string(), json!(channel == clicked))).collect() + } else { + std::iter::once((clicked.id().to_string(), json!(!on.get(index).copied().unwrap_or(true)))).collect() + }; + app.run("effect.set", json!({"effect": effect.0, "channels": switched})); +} + +/// How soon a filter card whose picture is still rendering looks for it again +const THUMBNAIL_POLL: std::time::Duration = std::time::Duration::from_millis(100); + +/// The hourglass size on a slot whose picture is still rendering +const WAITING_GLYPH_SIZE: f32 = 12.0; + +/// How round a filter card's picture and a swatch's corners are, in points +const SWATCH_CORNER_RADIUS: u8 = 3; + +/// The width of a picture's outline, in points +const OUTLINE_WIDTH: f32 = 1.0; + +/// The card naming the filter (or None; `def` its library entry): a click opens the filter picker under it, × empties it; returns whether its ⟲ (live while `changed`) was clicked +fn filter_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, effect: LayerId, filter: &Filter, def: Option<&FilterDef>, changed: bool) -> bool { + let ctx = sheet.ui.ctx().clone(); + let empty = *filter == Filter::Empty; + let thumbnail = def.and_then(|def| app.thumbs.filter(&ctx, def.id)); + let tokens = Tokens::get(&ctx); + let picture = |painter: &Painter, rect: Rect| match &thumbnail { + Some(texture) => { + painter.image(texture.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } + + // A picked filter whose picture is still rendering: a filled square, so it never reads as the empty card's outline + None if !empty => { + painter.rect_filled(rect.shrink(OUTLINE_WIDTH), SWATCH_CORNER_RADIUS, tokens.button); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::HOURGLASS_MEDIUM, + egui::FontId::proportional(WAITING_GLYPH_SIZE), + tokens.text_dim, + ); + ctx.request_repaint_after(THUMBNAIL_POLL); + } + None => { + painter.rect_stroke(rect.shrink(OUTLINE_WIDTH), SWATCH_CORNER_RADIUS, Stroke::new(OUTLINE_WIDTH, tokens.text_dim), StrokeKind::Inside); + } + }; + let (name, source) = if empty { (tr("Filter"), tr("None")) } else { (tr(filter.label()), tr("Filter")) }; + let slot = if empty { sheet.slot(&picture, name, source, None, false, false) } else { sheet.slot_restorable(&picture, name, source, changed) }; + if slot.clear { + app.run("effect.set", json!({"effect": effect.0, "filter": texturecraft_engine::mask_cmds::EMPTY_FILTER})); + } + crate::filter_slot::picker(app, &slot.pick, effect.0, def.map(|def| def.id)); + slot.reset +} + +/// The seed of a legacy seeded filter as stored ([`scalar_params`] hands it over as an f32, which rounds seeds past 2^24) +fn legacy_seed(filter: &Filter) -> Option { + match filter { + Filter::Warp { seed, .. } | Filter::DirectionalWarp { seed, .. } | Filter::SlopeBlur { seed, .. } => Some(*seed), + _ => None, + } +} + +/// The filter's own rows: Seed first, Intensity with its Divider chip, angles with their dial, then the color editors +fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter) { + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + let mut params = json!({ "effect": id, "merge": merge }); + params[key] = value; + app.run("effect.set", params); + }; + match filter { + Filter::ColorBalance { shadows, midtones, highlights } => return color_balance(app, sheet, id, [highlights, midtones, shadows]), + Filter::ColorCorrect { shadows, midtones, highlights } => return color_correct(app, sheet, id, [shadows, midtones, highlights]), + Filter::Hsl { hue, saturation, lightness, perceptive } => return hsl(app, sheet, id, [*hue, *saturation, *lightness], *perceptive), + Filter::GradientMap { .. } => return gradient(app, sheet, id, filter), + Filter::GradientCurve { preset, invert, balance, contrast } => return gradient_curve(app, sheet, id, *preset, *invert, [*balance, *contrast]), + Filter::GradientDynamic { vertical, position, .. } => return gradient_dynamic(app, sheet, id, *vertical, *position), + Filter::HaloGlow { on_mask, precise, color, .. } => return glow(app, sheet, id, filter, (*on_mask, *precise), *color), + Filter::DropShadow { color, .. } => return drop_shadow(app, sheet, id, filter, *color), + Filter::BakedLighting { .. } => return baked_lighting_stylized(app, sheet, id, filter), + Filter::Threshold { level, mode } => return threshold(app, sheet, id, *level, *mode), + Filter::Mirror(mirror) => return mirror_rows(app, sheet, id, mirror), + Filter::Transform(transform) => return crate::filter_transform_rows::transform_rows(app, sheet, id, transform), + Filter::MaskOutline(outline) => return mask_outline(app, sheet, id, outline), + Filter::DistanceBevel(bevel) => return bevel_rows(app, sheet, id, bevel), + Filter::BevelSmooth(smooth) => return bevel_smooth(app, sheet, id, smooth), + Filter::SourceWarp(warp) => return source_warp(app, sheet, id, warp), + Filter::SourceSlopeBlur(slope) => return slope_blur(app, sheet, id, slope), + Filter::HighPass { radius, space, alpha } => return highpass(app, sheet, id, *radius, *space, *alpha), + Filter::GrayscaleConversion(conversion) => return grayscale_conversion(app, sheet, id, conversion), + Filter::Grayscale => return grayscale_conversion(app, sheet, id, &GrayscaleConversion::of_luminance()), + Filter::AnisotropicKuwahara(kuwahara) => return anisotropic_kuwahara(app, sheet, id, kuwahara), + Filter::PbrValidate(validate) => return pbr_validate(app, sheet, id, validate), + Filter::HeightToNormal(filter) => return height_to_normal(app, sheet, id, filter), + Filter::ColorMatch(matcher) => return color_match(app, sheet, id, matcher), + _ => {} + } + let params = scalar_params(filter); + + // Invert leads its filter's rows (Invert, Height Adjust) + let leading = match filter { + Filter::Invert | Filter::InvertOff => Some(*filter == Filter::Invert), + Filter::HeightAdjust { invert, .. } => Some(*invert), + _ => None, + }; + if let Some(mut on) = leading + && sheet.toggle(tr("Invert"), &mut on) + { + set(app, "invert", json!(on), false); + } + if let Some(&(_, label, ..)) = params.iter().find(|(key, ..)| *key == "seed") + && let Some(mut seed) = legacy_seed(filter) + && sheet.seed(tr(label), &mut seed) + { + set(app, "seed", json!(seed), false); + } + let divided = divided_key(filter); + for (key, label, mut value, min, max) in params.into_iter().filter(|(key, ..)| *key != "seed") { + let edit = match divided { + Some((divided_param, divider)) if divided_param == key => intensity_row(app, sheet, id, &mut value, min..=max, divider), + _ if matches!(key, "angle" | "azimuth" | "horizontalRotation" | "verticalRotation") => sheet.angle(tr(label), &mut value, min..=max), + _ => range_slider(sheet, tr(label), &mut value, min..=max, decimals(key, min, max)), + }; + if let Some(merge) = edit { + set(app, key, json!(value), merge); + } + } + + // Switches under the sliders: Blur and Bevel reading past the texture's edges, Posterize, Pixelate and FXAA changing the coverage, Histogram Scan's direction + let trailing = match filter { + Filter::Blur { wrap, .. } => Some(("wrap", tr("Blur Wrap"), *wrap)), + Filter::Bevel { wrap, .. } => Some(("wrap", tr("Bevel Wrap"), *wrap)), + Filter::Posterize { alpha, .. } => Some(("applyToAlpha", tr("Apply to Alpha"), *alpha)), + Filter::Mosaic { alpha, .. } => Some(("applyToAlpha", tr("Apply To Alpha"), *alpha)), + Filter::Fxaa { alpha } => Some(("affectAlphaChannel", tr("Affect Alpha Channel"), *alpha)), + Filter::HistogramScan { invert_position, .. } => Some(("invertPosition", tr("Invert Position"), *invert_position)), + _ => None, + }; + if let Some((key, label, mut on)) = trailing + && sheet.toggle(label, &mut on) + { + set(app, key, json!(on), false); + } + + if let Filter::ReplaceColor { from, to, .. } = filter { + replace_colors(app, sheet, id, *from, *to); + } +} + +/// Highpass: Color Space, Radius (in Blur Intensity's unit) and Apply To Alpha +fn highpass(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, radius: f32, space: HighpassSpace, alpha: bool) { + if let (Some(picked), _) = sheet.dropdown(tr("Color Space"), space, &HighpassSpace::ALL, |space| tr(space.label()).to_owned(), None) { + app.run("effect.set", json!({"effect": id, "colorSpace": picked.id()})); + } + slider_rows(app, sheet, id, &[("intensity", tr("Radius"), radius / Filter::BLUR_INTENSITY, 0.0..=BLUR_INTENSITY_SLIDER_MAX)]); + let mut alpha = alpha; + if sheet.toggle(tr("Apply To Alpha"), &mut alpha) { + app.run("effect.set", json!({"effect": id, "applyToAlpha": alpha})); + } +} + +/// Grayscale Conversion: Channel Input (its Custom Input right under it), Invert, Balance, Contrast, Mode and the Channels Weights +fn grayscale_conversion(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, conversion: &GrayscaleConversion) { + let inputs = [tr("Current Channel"), tr("Custom Input")]; + if let Some(picked) = sheet.switch(tr("Channel Input"), &inputs, usize::from(conversion.custom_input)) { + app.run("effect.set", json!({"effect": id, "channelInput": if picked == 1 { "customInput" } else { "currentChannel" }})); + } + if conversion.custom_input { + input_slot(app, sheet, LayerId(id), ImageInput::CUSTOM_INPUT, true); + } + let mut invert = conversion.invert; + if sheet.toggle(tr("Invert"), &mut invert) { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + slider_rows(app, sheet, id, &[("balance", tr("Balance"), conversion.balance, 0.0..=1.0), ("contrast", tr("Contrast"), conversion.contrast, 0.0..=1.0)]); + if let (Some(picked), _) = sheet.dropdown(tr("Mode"), conversion.mode, &ConversionMode::ALL, |mode| tr(mode.label()).to_owned(), None) { + app.run("effect.set", json!({"effect": id, "mode": picked.id()})); + } + if conversion.mode == ConversionMode::ChannelsWeights { + let [red, green, blue, alpha] = conversion.weights; + let rows = [ + ("red", tr("Red"), red, 0.0..=1.0), + ("green", tr("Green"), green, 0.0..=1.0), + ("blue", tr("Blue"), blue, 0.0..=1.0), + ("alpha", tr("Alpha"), alpha, 0.0..=1.0), + ]; + slider_rows(app, sheet, id, &rows); + } +} + +/// Anisotropic Kuwahara: Extract Direction (its Custom Input right under it), Radius, Smoothness, Sharpness, Tensor Smoothness, Anisotropy and its Angle +fn anisotropic_kuwahara(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, kuwahara: &AnisotropicKuwahara) { + let inputs = [tr("Current Channel"), tr("Custom Input")]; + if let Some(picked) = sheet.switch(tr("Extract Direction"), &inputs, usize::from(kuwahara.custom_input)) { + app.run("effect.set", json!({"effect": id, "extractDirection": if picked == 1 { "customInput" } else { "currentChannel" }})); + } + if kuwahara.custom_input { + input_slot(app, sheet, LayerId(id), ImageInput::CUSTOM_INPUT, true); + } + let rows = [ + ("radius", tr("Radius"), kuwahara.radius, 0.0..=AnisotropicKuwahara::MAX_RADIUS), + ("smoothness", tr("Smoothness"), kuwahara.smoothness, 0.0..=1.0), + ("sharpness", tr("Sharpness"), kuwahara.sharpness, AnisotropicKuwahara::MIN_SHARPNESS..=1.0), + ("tensorSmoothness", tr("Tensor Smoothness"), kuwahara.tensor_smoothness, 0.0..=1.0), + ("anisotropy", tr("Anisotropy"), kuwahara.anisotropy, 0.0..=1.0), + ]; + slider_rows(app, sheet, id, &rows); + let mut angle = kuwahara.angle; + if let Some(merge) = sheet.angle(tr("Anisotropy Angle"), &mut angle, DIAL_DEGREES) { + app.run("effect.set", json!({"effect": id, "angle": angle, "merge": merge})); + } +} + +/// PBR Validate (Metallic Roughness): Validation Mode, Albedo Dark Range Threshold and Metal Reflectance Range, each label above its switch +fn pbr_validate(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, validate: &PbrValidate) { + let modes: Vec<&str> = ValidationMode::ALL.iter().map(|mode| tr(mode.label())).collect(); + let mode = ValidationMode::ALL.iter().position(|mode| *mode == validate.mode).unwrap_or_default(); + if let Some(picked) = sheet.stacked_switch(tr("Validation Mode"), &modes, mode).and_then(|index| ValidationMode::ALL.get(index)) { + app.run("effect.set", json!({"effect": id, "validationMode": picked.id()})); + } + let dark = PbrValidate::ALBEDO_DARK.iter().position(|value| *value == validate.albedo_dark).unwrap_or_default(); + if let Some(picked) = sheet.stacked_switch(tr("Albedo Dark Range Threshold"), &[tr("50 sRGB"), tr("30 sRGB")], dark) { + app.run("effect.set", json!({"effect": id, "albedoDarkRangeThreshold": PbrValidate::ALBEDO_DARK.get(picked)})); + } + let low = PbrValidate::METAL_LOW.iter().position(|value| *value == validate.metal_low).unwrap_or_default(); + if let Some(picked) = sheet.stacked_switch(tr("Metal Reflectance Range"), &[tr("70-100% Reflective"), tr("60-100% Reflective")], low) { + app.run("effect.set", json!({"effect": id, "metalReflectanceRange": PbrValidate::METAL_LOW.get(picked)})); + } +} + +/// Height To Normal: Overwrite Existing Normal, Use World Units, then Surface Size and Height Depth (whole cm) or Normal Intensity +fn height_to_normal(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &HeightToNormal) { + for (key, label, on) in + [("overwriteExistingNormal", tr("Overwrite Existing Normal"), filter.overwrite), ("useWorldUnits", tr("Use World Units"), filter.world_units)] + { + let mut on = on; + if sheet.toggle(label, &mut on) { + app.run("effect.set", json!({"effect": id, key: on})); + } + } + let rows = if filter.world_units { + vec![ + ("surfaceSize", tr("Surface Size (cm)"), filter.surface_size, HeightToNormal::MIN_SURFACE_SIZE..=HeightToNormal::MAX_SURFACE_SIZE, true), + ("heightDepth", tr("Height Depth (cm)"), filter.height_depth, 0.0..=HeightToNormal::MAX_HEIGHT_DEPTH, true), + ] + } else { + vec![("normalIntensity", tr("Normal Intensity"), filter.intensity, 0.0..=HeightToNormal::MAX_INTENSITY, false)] + }; + for (key, label, stored, range, whole_centimetres) in rows { + let mut value = stored; + let decimals = if whole_centimetres { 0 } else { INTENSITY_DECIMALS }; + let slid = sheet.slider(label, &mut value, range, decimals); + if !whole_centimetres { + if let Some(merge) = slid { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + continue; + } + + // Whole centimetres: a press's first whole-number change starts its undo step, changes that round to the stored value apply nothing + let value = value.round(); + let press = sheet.ui.make_persistent_id(("height_to_normal_press", id, key)); + if let Some(merge) = crate::widgets::press_edit(sheet.ui, press, slid.is_some() && value != stored) { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } +} + +/// Color Match: each Color Mode with its color or image slot right under it, Custom Color Variation and, while it is on, the Color Variation card (Hue with its dial, Chroma, Luma) +fn color_match(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, matcher: &ColorMatch) { + let color = |app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, key: &str, label: &str, linear: [f32; 3]| { + let pick = sheet.color_bar_led(label, linear, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + app.run("effect.set", json!({"effect": id, key: picked, "merge": pick.merge})); + } + }; + if let (Some(picked), _) = sheet.dropdown(tr("Source Color Mode"), matcher.source_mode, &SourceColorMode::ALL, |mode| tr(mode.label()).to_owned(), None) { + app.run("effect.set", json!({"effect": id, "sourceColorMode": picked.id()})); + } + match matcher.source_mode { + SourceColorMode::Parameter => color(app, sheet, "sourceColor", tr("Source Color"), matcher.source_color), + SourceColorMode::Input => input_slot(app, sheet, LayerId(id), ImageInput::SOURCE_INPUT, true), + SourceColorMode::Average => {} + } + let targets: Vec<&str> = TargetColorMode::ALL.iter().map(|mode| tr(mode.label())).collect(); + let target = usize::from(matcher.target_mode == TargetColorMode::ImageInput); + if let Some(picked) = sheet.switch(tr("Target Color Mode"), &targets, target).and_then(|index| TargetColorMode::ALL.get(index)) { + app.run("effect.set", json!({"effect": id, "targetColorMode": picked.id()})); + } + match matcher.target_mode { + TargetColorMode::Parameter => color(app, sheet, "targetColor", tr("Target Color"), matcher.target_color), + TargetColorMode::ImageInput => input_slot(app, sheet, LayerId(id), ImageInput::TARGET_INPUT, true), + } + let mut custom = matcher.custom_variation; + if sheet.toggle(tr("Custom Color Variation"), &mut custom) { + app.run("effect.set", json!({"effect": id, "customColorVariation": custom})); + } + if !matcher.custom_variation { + return; + } + + if sheet.card(tr("Color Variation"), Some(true)) { + let mut hue = matcher.hue; + if let Some(merge) = sheet.angle(tr("Hue"), &mut hue, DIAL_DEGREES) { + app.run("effect.set", json!({"effect": id, "hue": hue, "merge": merge})); + } + slider_rows(app, sheet, id, &[("chroma", tr("Chroma"), matcher.chroma, 0.0..=1.0), ("luma", tr("Luma"), matcher.luma, 0.0..=1.0)]); + } + sheet.close_card(); +} + +/// Threshold: its level, then the Mode comparing a value with it (>, ≥, <, ≤) +fn threshold(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, level: f32, mode: ThresholdMode) { + let mut level = level; + if let Some(merge) = sheet.slider(tr("Threshold"), &mut level, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "level": level, "merge": merge})); + } + let signs = ThresholdMode::ALL.map(ThresholdMode::sign); + let current = ThresholdMode::ALL.iter().position(|candidate| *candidate == mode).unwrap_or_default(); + if let Some(picked) = sheet.switch(tr("Mode"), &signs, current).and_then(|index| ThresholdMode::ALL.get(index)) { + app.run("effect.set", json!({"effect": id, "mode": picked.id()})); + } +} + +/// Mirror: Display Debug and Mode, then the axis's offset and Invert switch, or the Corner Type of a corner mirror +fn mirror_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, mirror: &Mirror) { + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + }; + let mut debug = mirror.debug; + if sheet.toggle(tr("Display Debug"), &mut debug) { + set(app, "displayDebug", json!(debug), false); + } + if let (Some(picked), _) = sheet.dropdown(tr("Mode"), mirror.mode, &MirrorMode::ALL, |mode| tr(mode.label()).to_owned(), None) { + set(app, "mode", json!(picked.id()), false); + } + let ([x_offset, y_offset], [x_invert, y_invert]) = (mirror.offset, mirror.invert); + let (offset_key, offset_label, mut offset, invert_key, invert_label, mut invert) = match mirror.mode { + MirrorMode::AxisX => ("axisXOffset", tr("Axis X Offset"), x_offset, "invertAxisX", tr("Invert Axis X"), x_invert), + MirrorMode::AxisY => ("axisYOffset", tr("Axis Y Offset"), y_offset, "invertAxisY", tr("Invert Axis Y"), y_invert), + MirrorMode::Corner => { + let name = |corner: MirrorCorner| tr(corner.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Corner Type"), mirror.corner, &MirrorCorner::ALL, name, None) { + set(app, "cornerType", json!(picked.id()), false); + } + return; + } + }; + if let Some(merge) = sheet.slider(offset_label, &mut offset, 0.0..=1.0, 2) { + set(app, offset_key, json!(offset), merge); + } + if sheet.toggle(invert_label, &mut invert) { + set(app, invert_key, json!(invert), false); + } +} + +/// Mask Outline: Mask Position and Start From Black, then the band's Threshold, Width, Blur and Curve Shape +fn mask_outline(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, outline: &MaskOutline) { + let names = OutlinePosition::ALL.map(|position| tr(position.label())); + let current = OutlinePosition::ALL.iter().position(|position| *position == outline.position).unwrap_or_default(); + if let Some(picked) = sheet.switch(tr("Mask Position"), &names, current).and_then(|index| OutlinePosition::ALL.get(index)) { + app.run("effect.set", json!({"effect": id, "maskPosition": picked.id()})); + } + let mut from_black = outline.from_black; + if sheet.toggle(tr("Start From Black"), &mut from_black) { + app.run("effect.set", json!({"effect": id, "startFromBlack": from_black})); + } + for (key, label, value) in [("threshold", tr("Threshold"), outline.threshold), ("width", tr("Width"), outline.width), ("blur", tr("Blur"), outline.blur)] { + let mut value = value; + if let Some(merge) = sheet.slider(label, &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } + let mut curve = outline.curve; + if let Some(merge) = sheet.signed_slider(tr("Curve Shape"), &mut curve, -1.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "curveShape": curve, "merge": merge})); + } +} + +/// A choice's shown name and the id the command takes for it +type ChoiceNames = (fn(T) -> &'static str, fn(T) -> &'static str); + +/// A switch among `all` (named by `label`) setting `key` to the picked one's `id` +fn choice_switch( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + (label, key): (&str, &str), + all: &[T], + current: T, + (name, id_of): ChoiceNames, +) { + let names: Vec<&str> = all.iter().map(|choice| tr(name(*choice))).collect(); + let current_index = all.iter().position(|choice| *choice == current).unwrap_or_default(); + if let Some(picked) = sheet.switch(label, &names, current_index).and_then(|index| all.get(index)) { + app.run("effect.set", json!({"effect": id, key: id_of(*picked)})); + } +} + +/// Sliders setting `effect.set` keys: (key, label, value, range), signed ranges filling from their middle +fn slider_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, rows: &[(&str, &str, f32, std::ops::RangeInclusive)]) { + for (key, label, value, range) in rows { + let mut value = *value; + if let Some(merge) = range_slider(sheet, label, &mut value, range.clone(), 2) { + app.run("effect.set", json!({"effect": id, *key: value, "merge": merge})); + } + } +} + +/// A slider over `range`, filling from its middle when the range is signed +fn range_slider(sheet: &mut PropertySheet<'_>, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> Option { + if *range.start() < 0.0 { sheet.signed_slider(label, value, range, decimals) } else { sheet.slider(label, value, range, decimals) } +} + +/// The Bevel Wrap switch of a bevel +fn bevel_wrap(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, wrap: bool) { + let mut wrap = wrap; + if sheet.toggle(tr("Bevel Wrap"), &mut wrap) { + app.run("effect.set", json!({"effect": id, "wrap": wrap})); + } +} + +/// Bevel: Bevel Wrap, the signed Distance (inwards below 0), Corner Type, Smoothing and Blur Mode +fn bevel_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, bevel: &Bevel) { + bevel_wrap(app, sheet, id, bevel.wrap); + slider_rows(app, sheet, id, &[("distance", tr("Distance"), bevel.distance, -1.0..=1.0)]); + choice_switch(app, sheet, id, (tr("Corner Type"), "cornerType"), &BevelCorner::ALL, bevel.corner, (BevelCorner::label, BevelCorner::id)); + slider_rows(app, sheet, id, &[("smoothing", tr("Smoothing"), bevel.smoothing, 0.0..=DISTANCE_BEVEL_SMOOTHING_MAX)]); + choice_switch(app, sheet, id, (tr("Blur Mode"), "blurMode"), &BevelBlur::ALL, bevel.blur, (BevelBlur::label, BevelBlur::id)); +} + +/// Bevel Smooth: Direction, the ramp's Distance, Smoothing, Curve Offset and Shape, Mask Threshold, Distance Map Multiplier and Bevel Wrap +fn bevel_smooth(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, smooth: &BevelSmooth) { + choice_switch(app, sheet, id, (tr("Direction"), "direction"), &BevelDirection::ALL, smooth.direction, (BevelDirection::label, BevelDirection::id)); + slider_rows( + app, + sheet, + id, + &[ + ("distance", tr("Distance"), smooth.distance, 0.0..=SMOOTH_DISTANCE_MAX), + ("smoothing", tr("Smoothing"), smooth.smoothing, 0.0..=BEVEL_SMOOTHING_MAX), + ("curveOffset", tr("Curve Offset"), smooth.curve_offset, -1.0..=1.0), + ("curveShape", tr("Curve Shape"), smooth.curve_shape, -1.0..=1.0), + ("maskThreshold", tr("Mask Threshold"), smooth.threshold, 0.0..=1.0), + ("distanceMapMultiplier", tr("Distance Map Multiplier"), smooth.multiplier, 0.0..=1.0), + ], + ); + bevel_wrap(app, sheet, id, smooth.wrap); +} + +/// Warp: Seed, Warp Mode, Intensity with its Divider, the directional modes' Angle (Multi Directional's Directions, Blending Mode), then Source Parameters +fn source_warp(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, warp: &SourceWarp) { + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + }; + let mut seed = warp.seed; + if sheet.seed(tr("Seed"), &mut seed) { + set(app, "seed", json!(seed), false); + } + if let (Some(picked), _) = sheet.dropdown(tr("Warp Mode"), warp.mode, &WarpMode::ALL, |mode| tr(mode.label()).to_owned(), None) { + set(app, "warpMode", json!(picked.id()), false); + } + let mut intensity = warp.intensity; + if let Some(merge) = intensity_row(app, sheet, id, &mut intensity, 0.0..=1.0, warp.divider) { + set(app, "intensity", json!(intensity), merge); + } + if warp.mode != WarpMode::Warp { + let mut angle = warp.angle; + if let Some(merge) = sheet.angle(tr("Angle"), &mut angle, DIAL_DEGREES) { + set(app, "angle", json!(angle), merge); + } + } + if warp.mode == WarpMode::MultiDirectional { + let counts = SourceWarp::DIRECTIONS.map(|count| count.to_string()); + let names: Vec<&str> = counts.iter().map(String::as_str).collect(); + let current_index = SourceWarp::DIRECTIONS.iter().position(|count| *count == warp.directions).unwrap_or_default(); + if let Some(picked) = sheet.switch(tr("Directions"), &names, current_index).and_then(|index| SourceWarp::DIRECTIONS.get(index)) { + set(app, "directions", json!(picked), false); + } + let name = |blending: WarpBlending| tr(blending.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Blending Mode"), warp.blending, &WarpBlending::ALL, name, None) { + set(app, "blendingMode", json!(picked.id()), false); + } + } + if sheet.card(tr("Source Parameters"), Some(true)) { + let source = &warp.source; + let name = |mode: WarpSourceMode| tr(mode.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Source Mode"), source.mode, &WarpSourceMode::ALL, name, None) { + set(app, "sourceMode", json!(picked.id()), false); + } + if source.mode == WarpSourceMode::CustomNoise { + input_slot(app, sheet, LayerId(id), ImageInput::CUSTOM_NOISE, true); + } + slider_rows( + app, + sheet, + id, + &[ + ("sourceBlur", tr("Source Blur"), source.blur, 0.0..=1.0), + ("sourceBalance", tr("Source Balance"), source.balance, 0.0..=1.0), + ("sourceContrast", tr("Source Contrast"), source.contrast, 0.0..=1.0), + ("sourceTiling", tr("Source Tiling"), source.tiling, SOURCE_TILING_MIN..=SOURCE_TILING_MAX), + ], + ); + } + sheet.close_card(); +} + +/// Blur Slope: Seed, Intensity with its Divider, Blending Mode (each drawn as what it does to a bar), Quality, then Source Parameters +fn slope_blur(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, slope: &SourceSlopeBlur) { + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + }; + let mut seed = slope.seed; + if sheet.seed(tr("Seed"), &mut seed) { + set(app, "seed", json!(seed), false); + } + let mut intensity = slope.intensity; + if let Some(merge) = intensity_row(app, sheet, id, &mut intensity, 0.0..=1.0, slope.divider) { + set(app, "intensity", json!(intensity), merge); + } + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = |painter: &Painter, rect: Rect, blending: SlopeBlending| slope_blending_picture(painter, rect, blending, &tokens); + let name = |blending: SlopeBlending| tr(blending.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Blending Mode"), slope.blending, &SlopeBlending::ALL, name, Some(&picture)) { + set(app, "blendingMode", json!(picked.id()), false); + } + slider_rows(app, sheet, id, &[("quality", tr("Quality"), slope.quality, 0.0..=1.0)]); + if sheet.card(tr("Source Parameters"), Some(true)) { + let source = &slope.source; + let name = |mode: WarpSourceMode| tr(mode.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Source Type"), source.mode, &WarpSourceMode::ALL, name, None) { + set(app, "sourceMode", json!(picked.id()), false); + } + if source.mode == WarpSourceMode::CustomNoise { + input_slot(app, sheet, LayerId(id), ImageInput::CUSTOM_NOISE, true); + } + let mut shown_blur = source.blur * SLOPE_SOURCE_BLUR_DISPLAY_MAX; + if let Some(merge) = sheet.slider(tr("Blur"), &mut shown_blur, 0.0..=SLOPE_SOURCE_BLUR_DISPLAY_MAX, 2) { + set(app, "sourceBlur", json!(shown_blur / SLOPE_SOURCE_BLUR_DISPLAY_MAX), merge); + } + slider_rows( + app, + sheet, + id, + &[ + ("sourceBalance", tr("Position"), source.balance, 0.0..=1.0), + ("sourceContrast", tr("Contrast"), source.contrast, 0.0..=1.0), + ("sourceTiling", tr("Source Tiling"), source.tiling, SOURCE_TILING_MIN..=SOURCE_TILING_MAX), + ], + ); + } + sheet.close_card(); +} + +/// The reference shows this blur on 0..20; stored on Warp's shared 0..1 source scale +const SLOPE_SOURCE_BLUR_DISPLAY_MAX: f32 = 20.0; + +/// A light bar on the field after the slope pass: smeared (Blur), eaten away (Min) or grown (Max) +fn slope_blending_picture(painter: &Painter, rect: Rect, blending: SlopeBlending, tokens: &Tokens) { + painter.rect_filled(rect, 0, tokens.field); + let bar = |left: f32, right: f32| { + let (top, bottom) = (rect.top() + rect.height() * SLOPE_BAR_TOP, rect.top() + rect.height() * (1.0 - SLOPE_BAR_TOP)); + Rect::from_min_max(egui::pos2(rect.left() + rect.width() * left, top), egui::pos2(rect.left() + rect.width() * right, bottom)) + }; + match blending { + SlopeBlending::Blur => { + for (step, spread) in SLOPE_BLUR_SPREADS.iter().enumerate() { + let share = (step + 1) as f32 / SLOPE_BLUR_SPREADS.len() as f32; + let tint = tokens.text.gamma_multiply(share * SLOPE_BLUR_LAYER_ALPHA); + painter.rect_filled( + bar(BLUR_BAR.0 - spread, BLUR_BAR.1 + spread).expand2(egui::vec2(0.0, spread * rect.height() * SLOPE_BLUR_VERTICAL_SHARE)), + SLOPE_BLUR_LAYER_ROUNDING, + tint, + ); + } + } + SlopeBlending::Min => { + painter.rect_filled(bar(MIN_BAR.0, MIN_BAR.1), 0, tokens.text); + } + SlopeBlending::Max => { + painter.rect_filled(bar(MAX_BAR.0, MAX_BAR.1), 0, tokens.text); + } + } + painter.rect_stroke(rect, 0, Stroke::new(OUTLINE_WIDTH, tokens.field_border), StrokeKind::Inside); +} + +/// Where a blending picture's bar starts down its square (and ends as far from the bottom) +const SLOPE_BAR_TOP: f32 = 0.25; + +/// How far each soft layer of the Blur picture's bar spreads past the bar (shares of the square), widest first +const SLOPE_BLUR_SPREADS: [f32; 4] = [0.12, 0.08, 0.04, 0.0]; + +/// How opaque the Blur picture's soft layers stack up to +const SLOPE_BLUR_LAYER_ALPHA: f32 = 0.45; + +/// How much of a Blur layer's sideways spread it also grows up and down: half, so the smear reads wider than tall +const SLOPE_BLUR_VERTICAL_SHARE: f32 = 0.5; + +/// How round a Blur layer's corners are, in points: soft, where the Min and Max bars are square +const SLOPE_BLUR_LAYER_ROUNDING: u8 = 1; + +/// The left and right ends of each slope blur mode's bar, as shares of the pictogram's width +const BLUR_BAR: (f32, f32) = (0.3, 0.62); +const MIN_BAR: (f32, f32) = (0.42, 0.58); +const MAX_BAR: (f32, f32) = (0.18, 0.82); + +/// The tone groups' names and the `effect.set` keys they edit, in the order a panel shows them +const SHADOWS: (&str, &str) = ("Shadows", "shadows"); +const MIDTONES: (&str, &str) = ("Midtones", "midtones"); +const HIGHLIGHTS: (&str, &str) = ("Highlights", "highlights"); + +/// Color Balance: a card per tone (Highlights, Midtones, Shadows), each with Cyan ↔ Red, Magenta ↔ Green and Yellow ↔ Blue +fn color_balance(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, tones: [&[f32; 3]; 3]) { + let ends = [(tr("Cyan"), tr("Red")), (tr("Magenta"), tr("Green")), (tr("Yellow"), tr("Blue"))]; + let rights = ends.map(|(_, right)| right); + for ((name, key), values) in [HIGHLIGHTS, MIDTONES, SHADOWS].into_iter().zip(tones) { + if !sheet.card(tr(name), Some(true)) { + sheet.close_card(); + continue; + } + + let mut balance = *values; + let mut edit = None; + for (component, (value, (left, right))) in balance.iter_mut().zip(ends).enumerate() { + let (left_tint, right_tint) = + (OPPOSITE_COLORS.get(component).copied().unwrap_or_default(), AXIS_COLORS.get(component).copied().unwrap_or_default()); + edit = edit.or(sheet.tinted_slider((left, left_tint), (right, right_tint), &rights, value)); + } + sheet.close_card(); + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, key: balance, "merge": merge})); + } + } +} + +/// Color Correct: a card per tone (Shadows, Midtones, Highlights), each with Contrast, Luminosity and Saturation +fn color_correct(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, tones: [&[f32; 3]; 3]) { + for ((name, key), values) in [SHADOWS, MIDTONES, HIGHLIGHTS].into_iter().zip(tones) { + if !sheet.card(tr(name), Some(true)) { + sheet.close_card(); + continue; + } + + let [mut contrast, mut luminosity, mut saturation] = *values; + let edit = sheet + .signed_slider(tr("Contrast"), &mut contrast, -1.0..=1.0, 2) + .or(sheet.signed_slider(tr("Luminosity"), &mut luminosity, -1.0..=1.0, 2)) + .or(sheet.slider(tr("Saturation"), &mut saturation, 0.0..=1.0, 2)); + sheet.close_card(); + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, key: [contrast, luminosity, saturation], "merge": merge})); + } + } +} + +/// HSL Perceptive: Mode (Regular | Perceptive), then Hue, Saturation and Lightness on 0..1 with 0.5 leaving them as they are +fn hsl(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, [hue, saturation, lightness]: [f32; 3], perceptive: bool) { + if let Some(mode) = sheet.switch(tr("Mode"), &[tr("Regular"), tr("Perceptive")], usize::from(perceptive)) { + app.run("effect.set", json!({"effect": id, "mode": if mode == 1 { "perceptive" } else { "regular" }})); + } + + // Shown around 0.5: the hue as half a turn either way (a stored turn past half wraps round), saturation and lightness as −1..1 halved + let rows = [ + ("hue", tr("Hue"), (hue + 0.5).rem_euclid(1.0), 1.0), + ("saturation", tr("Saturation"), 0.5 + saturation / 2.0, 2.0), + ("lightness", tr("Lightness"), 0.5 + lightness / 2.0, 2.0), + ]; + for (key, label, shown, scale) in rows { + let mut value = shown.clamp(0.0, 1.0); + if let Some(merge) = sheet.centered_slider(label, &mut value, 0.0..=1.0, 0.5, 2) { + app.run("effect.set", json!({"effect": id, key: (value - 0.5) * scale, "merge": merge})); + } + } +} + +/// Gradient: Display Gradient (Debug), the Input Transformation card, then the Colors card (the ramp, Color Quantity, Blend Color in Linear and a row per color) +fn gradient(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter) { + let Filter::GradientMap { colors, positions, input, linear, debug, .. } = filter else { return }; + let set = |app: &mut TextureCraftApp, params: Value| { + let mut params = params; + params["effect"] = json!(id); + app.run("effect.set", params); + }; + let mut shown = *debug; + if sheet.toggle(tr("Display Gradient (Debug)"), &mut shown) { + set(app, json!({"debug": shown})); + } + + if sheet.card(tr("Input Transformation"), Some(true)) { + let name = |mode: GrayscaleMode| tr(mode.label()).to_owned(); + if let (Some(mode), _) = sheet.dropdown(tr("Grayscale Mode"), input.mode, &GrayscaleMode::ALL, name, None) { + set(app, json!({"grayscaleMode": mode.id()})); + } + for (key, label, value) in + [("blur", tr("Blur Intensity"), input.blur), ("balance", tr("Balance"), input.balance), ("contrast", tr("Contrast"), input.contrast)] + { + let mut value = value; + let range = if key == "blur" { 0.0..=BLUR_INTENSITY_SLIDER_MAX } else { 0.0..=1.0 }; + if let Some(merge) = sheet.slider(label, &mut value, range, 2) { + set(app, json!({key: value, "merge": merge})); + } + } + let mut invert = input.invert; + if sheet.toggle(tr("Invert"), &mut invert) { + set(app, json!({"invert": invert})); + } + } + sheet.close_card(); + + if sheet.card(tr("Colors"), Some(true)) { + let used = filter.ramp_colors(); + + // An evenly spaced ramp (projects saved before) shows its places, and keeps them once one moves + let last = used.len().saturating_sub(1).max(1) as f32; + let mut places: Vec = (0..colors.len()).map(|index| positions.get(index).copied().unwrap_or(index as f32 / last)).collect(); + if let Some(drag) = sheet.gradient_ramp(used, &places, &|t| filter.ramp_at(t).unwrap_or([0.0; 3])) { + if let Some(place) = places.get_mut(drag.index) { + *place = drag.position; + } + set(app, json!({"positions": places, "merge": drag.merge})); + } + let mut quantity = used.len() as f32; + let slid = sheet.slider(tr("Color Quantity"), &mut quantity, f32::from(GRADIENT_QUANTITY_MIN)..=f32::from(Filter::MAX_GRADIENT_COLORS), 0).is_some(); + let quantity = quantity.round(); + + // A press's first whole-number change starts its undo step: changes that round to the count it has apply nothing + let press = sheet.ui.make_persistent_id(("color_quantity_press", id)); + if let Some(merge) = crate::widgets::press_edit(sheet.ui, press, slid && quantity as usize != used.len()) { + set(app, json!({"quantity": quantity, "merge": merge})); + } + let mut in_linear = *linear; + if sheet.toggle(tr("Blend Color in Linear"), &mut in_linear) { + set(app, json!({"linear": in_linear})); + } + for (index, color) in used.iter().enumerate() { + let label = trf("Color {number}", &[("number", &(index + 1))]); + let mut place = places.get(index).copied().unwrap_or(0.0); + let (pick, moved) = sheet.color_stop(&label, *color, &mut place, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + let mut recolored = colors.clone(); + if let Some(slot) = recolored.get_mut(index) { + *slot = picked; + } + set(app, json!({"colors": recolored, "merge": pick.merge})); + } + if let Some(merge) = moved { + if let Some(slot) = places.get_mut(index) { + *slot = place; + } + set(app, json!({"positions": places, "merge": merge})); + } + } + } + sheet.close_card(); +} + +/// Gradient Curve: Preset (each drawn as its curve), Invert, Balance and Contrast +fn gradient_curve(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, preset: CurvePreset, invert: bool, [balance, contrast]: [f32; 2]) { + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = |painter: &Painter, rect: Rect, preset: CurvePreset| curve_picture(painter, rect, preset, &tokens); + let name = |preset: CurvePreset| tr(preset.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Preset"), preset, &CurvePreset::ALL, name, Some(&picture)) { + app.run("effect.set", json!({"effect": id, "preset": picked.id()})); + } + let mut inverted = invert; + if sheet.toggle(tr("Invert"), &mut inverted) { + app.run("effect.set", json!({"effect": id, "invert": inverted})); + } + for (key, label, value) in [("balance", tr("Balance"), balance), ("contrast", tr("Contrast"), contrast)] { + let mut value = value; + if let Some(merge) = sheet.slider(label, &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } +} + +/// A curve preset's shape over a dark square +fn curve_picture(painter: &Painter, rect: Rect, preset: CurvePreset, tokens: &Tokens) { + painter.rect_filled(rect, CURVE_PICTURE_ROUNDING, tokens.field); + let inner = rect.shrink(CURVE_PICTURE_INSET); + let points: Vec = (0..=CURVE_PICTURE_STEPS) + .map(|step| { + let t = step as f32 / CURVE_PICTURE_STEPS as f32; + egui::pos2(inner.left() + inner.width() * t, inner.bottom() - inner.height() * preset.at(t)) + }) + .collect(); + painter.add(egui::Shape::line(points, Stroke::new(CURVE_PICTURE_STROKE, tokens.accent))); +} + +/// A curve picture's inset in its square, in points +const CURVE_PICTURE_INSET: f32 = 2.0; + +/// How round a curve picture's square is, in points +const CURVE_PICTURE_ROUNDING: u8 = 2; + +/// How many straight pieces a curve picture's line is drawn with +const CURVE_PICTURE_STEPS: usize = 30; + +/// The width of a curve picture's line, in points +const CURVE_PICTURE_STROKE: f32 = 1.5; + +/// Gradient Dynamic: Gradient Orientation and Gradient Input Position (its Gradient Source is a card after the filter's) +fn gradient_dynamic(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, vertical: bool, position: f32) { + if let Some(picked) = sheet.switch(tr("Gradient Orientation"), &[tr("Horizontal"), tr("Vertical")], usize::from(vertical)) { + app.run("effect.set", json!({"effect": id, "orientation": if picked == 1 { "vertical" } else { "horizontal" }})); + } + let mut value = position; + if let Some(merge) = sheet.slider(tr("Gradient Input Position"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "position": value, "merge": merge})); + } +} + +/// Gradient Dynamic's Gradient Source: its own slot card after the filter's, a uniform color whose bar opens the picker +fn gradient_source(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, color: [f32; 3]) { + let swatch = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, SWATCH_CORNER_RADIUS, crate::fill_material_panel::shown_color(color)); + }; + + // The card's row opens the picker of the colour bar under it: its source is a uniform color only + let card = sheet.slot(&swatch, tr("Gradient Source"), tr("Uniform"), None, false, false); + let pick = sheet.color_bar(tr("Gradient Source"), color, app.picking_color, &app.session.doc.project.swatches); + if card.pick.clicked() { + sheet.open_color_picker(pick.id, color); + } + sheet.close_card(); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + app.run("effect.set", json!({"effect": id, "color": picked, "merge": pick.merge})); + } +} + +/// Glow: Used on a Mask, Mode (Soft | Precise), Width (inner below 0), Spread, Opacity and its Color +fn glow(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter, (on_mask, precise): (bool, bool), color: [f32; 3]) { + let mut used = on_mask; + if sheet.toggle(tr("Used on a Mask"), &mut used) { + app.run("effect.set", json!({"effect": id, "usedOnMask": used})); + } + if let Some(mode) = sheet.switch(tr("Mode"), &[tr("Soft"), tr("Precise")], usize::from(precise)) { + app.run("effect.set", json!({"effect": id, "mode": if mode == 1 { "precise" } else { "soft" }})); + } + for (key, label, mut value, min, max) in scalar_params(filter) { + if let Some(merge) = range_slider(sheet, tr(label), &mut value, min..=max, 2) { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } + color_row(app, sheet, id, color); +} + +/// Drop Shadow: Angle with its dial, Distance (either way), Size, Spread, Opacity and its Color +fn drop_shadow(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter, color: [f32; 3]) { + for (key, label, mut value, min, max) in scalar_params(filter) { + let edit = if key == "angle" { sheet.angle(tr(label), &mut value, min..=max) } else { range_slider(sheet, tr(label), &mut value, min..=max, 2) }; + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } + color_row(app, sheet, id, color); +} + +/// Baked Lighting Stylized: a card each for the Sun, the Sky, Light 1 and 2, Occlusion and cavity, the Material and Normal details (one saved before shows its plain settings) +fn baked_lighting_stylized(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter) { + let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, stylized } = filter else { return }; + let lighting = stylized.as_deref().unwrap_or(&StylizedLighting::PLAIN); + let set = |app: &mut TextureCraftApp, params: Value| { + let mut params = params; + params["effect"] = json!(id); + app.run("effect.set", params); + }; + + if sheet.card(tr("Sun"), Some(true)) { + let mut value = *light; + if let Some(merge) = sheet.slider(tr("Sun Intensity"), &mut value, 0.0..=SUN_INTENSITY_MAX, 2) { + set(app, json!({"light": value, "merge": merge})); + } + for (key, label, value) in + [("azimuth", tr("Sun Horizontal Angle"), *azimuth), ("elevation", tr("Sun Vertical Angle"), elevation.rem_euclid(FULL_TURN_DEGREES))] + { + let mut value = value; + if let Some(merge) = sheet.angle(label, &mut value, DIAL_DEGREES) { + set(app, json!({key: value, "merge": merge})); + } + } + let pick = sheet.color_bar_led(tr("Sun Color"), lighting.sun_color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + set(app, json!({"sunColor": picked, "merge": pick.merge})); + } + } + sheet.close_card(); + + if sheet.card(tr("Sky"), Some(true)) { + let mut value = *ambient; + if let Some(merge) = sheet.slider(tr("Sky Intensity"), &mut value, 0.0..=SKY_INTENSITY_SLIDER_MAX, 2) { + set(app, json!({"ambient": value, "merge": merge})); + } + for (key, label, color) in [ + ("skyColor", tr("Sky Color"), lighting.sky_color), + ("horizonColor", tr("Horizon Color"), lighting.horizon_color), + ("groundColor", tr("Ground Color"), lighting.ground_color), + ] { + let pick = sheet.color_bar_led(label, color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + set(app, json!({key: picked, "merge": pick.merge})); + } + } + } + sheet.close_card(); + + for (key, title, extra) in [("light1", tr("Light 1"), lighting.lights[0]), ("light2", tr("Light 2"), lighting.lights[1])] { + if sheet.card(title, Some(true)) { + extra_light(app, sheet, id, key, extra); + } + sheet.close_card(); + } + + if sheet.card(tr("Occlusion and cavity"), Some(true)) { + let rows = [ + ("occlusion", tr("Diffuse AO"), *occlusion, 1.0), + ("diffuseCavity", tr("Diffuse Cavity"), lighting.diffuse_cavity, 1.0), + ("specularAo", tr("Specular AO"), lighting.specular_ao, 1.0), + ("specularCavity", tr("Specular Cavity"), lighting.specular_cavity, 1.0), + ("cavitySmoothness", tr("Cavity Smoothness"), lighting.cavity_smoothness, MAX_CAVITY_SMOOTHNESS), + ("edgesIntensity", tr("Edges Intensity"), lighting.edges_intensity, 1.0), + ("edgesSmoothness", tr("Edges Smoothness"), lighting.edges_smoothness, 1.0), + ]; + for (key, label, value, max) in rows { + let mut value = value; + if let Some(merge) = sheet.slider(label, &mut value, 0.0..=max, 2) { + set(app, json!({key: value, "merge": merge})); + } + } + } + sheet.close_card(); + + if sheet.card(tr("Material"), Some(true)) { + let input = |glossiness: bool| tr(if glossiness { "Specular / Glossiness" } else { "Metal / Roughness" }).to_owned(); + if let (Some(glossiness), _) = sheet.dropdown(tr("Input"), lighting.specular_glossiness, &[false, true], input, None) { + set(app, json!({"input": if glossiness { "specularGlossiness" } else { "metalRoughness" }})); + } + let output = |output: LightingOutput| tr(output.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Output"), lighting.output, &LightingOutput::ALL, output, None) { + set(app, json!({"output": picked.id()})); + } + let mut value = lighting.dielectric_reflectance; + if let Some(merge) = sheet.slider(tr("Dielectric Reflectance"), &mut value, 0.0..=MAX_DIELECTRIC_REFLECTANCE, 2) { + set(app, json!({"dielectricReflectance": value, "merge": merge})); + } + } + sheet.close_card(); + + if sheet.card(tr("Normal details"), Some(true)) { + let details = |mesh_only: bool| tr(if mesh_only { "Mesh only" } else { "Mesh + Height + Normal" }).to_owned(); + if let (Some(mesh_only), _) = sheet.dropdown(tr("Normal Details Type"), lighting.mesh_only, &[true, false], details, None) { + set(app, json!({"normalDetails": if mesh_only { "mesh" } else { "meshHeightNormal" }})); + } + let mut value = lighting.height_to_normal; + if let Some(merge) = sheet.slider(tr("Height to Normal Intensity"), &mut value, 0.0..=MAX_HEIGHT_TO_NORMAL, 2) { + set(app, json!({"heightToNormal": value, "merge": merge})); + } + } + sheet.close_card(); +} + +/// Light 1 or 2's rows (`key` names it to `effect.set`): Horizontal and Vertical Angle with their dials, Intensity and Color +fn extra_light(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, key: &str, light: DirectionalLight) { + let set = |app: &mut TextureCraftApp, part: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: part, "merge": merge})); + }; + for (part, label, value) in + [("azimuth", tr("Horizontal Angle"), light.azimuth), ("elevation", tr("Vertical Angle"), light.elevation.rem_euclid(FULL_TURN_DEGREES))] + { + let mut value = value; + if let Some(merge) = sheet.angle(label, &mut value, DIAL_DEGREES) { + set(app, json!({part: value}), merge); + } + } + let mut intensity = light.intensity; + if let Some(merge) = sheet.slider(tr("Intensity"), &mut intensity, 0.0..=MAX_LIGHT_INTENSITY, 2) { + set(app, json!({"intensity": intensity}), merge); + } + let pick = sheet.color_bar_led(tr("Color"), light.color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + set(app, json!({"color": picked}), pick.merge); + } +} + +/// A light or shadow filter's Color: its bar opens the colour picker, the eyedropper picks from the screen +fn color_row(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, color: [f32; 3]) { + let pick = sheet.color_bar_led(tr("Color"), color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + app.run("effect.set", json!({"effect": id, "color": picked, "merge": pick.merge})); + } +} + +/// The parameter a filter's Divider divides and the divider it has +fn divided_key(filter: &Filter) -> Option<(&'static str, u16)> { + match filter { + Filter::Warp { divider, .. } | Filter::DirectionalWarp { divider, .. } => Some(("intensity", *divider)), + Filter::SlopeBlur { divider, .. } => Some(("radius", *divider)), + _ => None, + } +} + +/// Intensity with its "÷10" Divider chip before the value; the chip's list picks 1, 10, 100 or 1000 +fn intensity_row( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + value: &mut f32, + range: std::ops::RangeInclusive, + divider: u16, +) -> Option { + let shown = |divider: u16| format!("÷{divider}"); + let (edit, chip) = sheet.slider_with_chip(tr("Intensity"), value, range, 2, &shown(divider), WIDEST_DIVIDER); + let (picked, _) = sheet.hanging_list(&chip, divider, &Filter::DIVIDERS, &shown, None); + if let Some(divider) = picked { + app.run("effect.set", json!({"effect": id, "divider": divider})); + } + edit +} + +/// A range wider than this shows one decimal +const WIDE_RANGE: f32 = 10.0; + +/// Decimals a parameter's value shows: whole numbers for counts, two for blur intensities, one for wide ranges +fn decimals(key: &str, min: f32, max: f32) -> usize { + if matches!(key, "levels" | "pixelsAmount") { + 0 + } else if key == "intensity" { + 2 + } else if max - min > WIDE_RANGE { + 1 + } else { + 2 + } +} + +/// Replace Color's two colors: each bar opens the colour picker, its eyedropper picks from the screen +fn replace_colors(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, from: [f32; 3], to: [f32; 3]) { + for (key, label, linear) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { + let pick = sheet.color_bar_led(label, linear, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + app.run("effect.set", json!({"effect": id, key: picked, "merge": pick.merge})); + } + } +} diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index de81ca34..daa99d27 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -1,10 +1,9 @@ -//! The filter slot atop a filter's properties: thumbnail and name, opening a picker that swaps it +//! The filter picker hanging from the filter card: a grid of the library's filters that swaps the effect's filter -use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::core::{Filter, LayerId}; -use texturecraft_engine::filter_lib::{filter_effects, find}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::filter_lib::filter_effects; use crate::TextureCraftApp; use crate::i18n::tr; @@ -12,46 +11,19 @@ use crate::picker_group::PickerGroup; use crate::picker_tab::PickerTab; use crate::resource_picker; use crate::resource_picker_item::ResourcePickerItem; -use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::tile_picture::TilePicture; -use crate::widgets::elided; -pub(crate) const SLOT_HEIGHT: f32 = 52.0; -const SLOT_ROUNDING: f32 = 3.0; -const BORDER_WIDTH: f32 = 1.0; -const THUMBNAIL_SIZE: f32 = 40.0; -const THUMBNAIL_INSET: f32 = 6.0; -const CAPTION_FONT_SIZE: f32 = 11.0; -const NAME_FONT_SIZE: f32 = 13.0; -/// Gap between the caption's and the name's centers -const LINE_GAP: f32 = 15.0; -const CARET_INSET: f32 = 14.0; -const CARET_FONT_SIZE: f32 = 14.0; -/// Gap between the slot and its keyboard focus outline -const FOCUS_MARGIN: f32 = 2.0; - -/// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters -pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) { - let ctx = ui.ctx().clone(); +/// The filter picker of filter effect `effect` (library filter `current` now), hanging from its card's row `pick`: a pick runs `effect.set {filter}`, masks offer only mask filters +pub(crate) fn picker(app: &mut TextureCraftApp, pick: &egui::Response, effect: u64, current: Option<&'static str>) { + let ctx = pick.ctx.clone(); let on_mask = is_on_mask(app, effect); - let current = find(filter.label()).map(|def| def.id); - let thumbnail = current.and_then(|id| app.thumbs.filter(&ctx, id)); - let name = tr(filter.label()); - - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); - - let popup = ui.make_persistent_id(("filter_picker", effect)); + let popup = pick.id.with(("filter_picker", effect)); let open_requested = take_open_request(&ctx, effect); - - if response.clicked() || (open_requested && !egui::Popup::is_id_open(&ctx, popup)) { + if pick.clicked() || (open_requested && !egui::Popup::is_id_open(&ctx, popup)) { resource_picker::toggle(&ctx, popup); } - let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); - paint(ui, rect, (highlighted, response.has_focus()), thumbnail.as_ref().map(egui::TextureHandle::id), (tr("Filter"), name)); - let tabs = |thumbs: &mut Thumbs| { let mut items: Vec> = filter_effects() .iter() @@ -69,6 +41,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: vec![PickerTab { icon: ic::FUNNEL, name: tr("Filters"), groups: vec![PickerGroup { header: None, items }] }] }; let picked = resource_picker::show(&response, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); + let picked = resource_picker::show(pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); if let Some(id) = picked.filter(|id| Some(*id) != current) { app.run("effect.set", json!({"effect": effect, "filter": id})); } @@ -80,13 +53,20 @@ pub(crate) fn open_picker_when_shown(ctx: &egui::Context, effect: u64) { ctx.data_mut(|data| data.insert_temp(open_request_id(), (effect, frame))); } -/// Whether an open request for `effect`'s slot is waiting, removing it; a request older than a frame lapses +/// Whether an open request for `effect`'s slot is waiting, removing it; a request for another effect stays for that effect's slot, one older than a frame lapses fn take_open_request(ctx: &egui::Context, effect: u64) -> bool { let frame = ctx.cumulative_frame_nr(); - let request = ctx.data_mut(|data| data.remove_temp::<(u64, u64)>(open_request_id())); + ctx.data_mut(|data| { + let Some((requested_effect, requested_frame)) = data.get_temp::<(u64, u64)>(open_request_id()) else { return false }; - // Properties can draw before or after the menu that asked, so a request lives for this frame and the next - request.is_some_and(|(requested_effect, requested_frame)| requested_effect == effect && frame <= requested_frame + 1) + // Properties can draw before or after the menu that asked, so a request lives for this frame and the next + let lapsed = frame > requested_frame.saturating_add(1); + let for_this_slot = requested_effect == effect; + if lapsed || for_this_slot { + data.remove_temp::<(u64, u64)>(open_request_id()); + } + for_this_slot && !lapsed + }) } /// Where the effect whose slot should open its picker waits @@ -95,37 +75,24 @@ fn open_request_id() -> egui::Id { } /// Whether filter effect `effect` sits in a mask rather than the layer content -fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { +pub(crate) fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { let project = &app.session.doc.project; let owner = project.effect(LayerId(effect)).and_then(|(owner, _)| project.layers.get(&owner)); owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) } -/// A slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, `caption` over `name`, caret (fill source slots share it) -pub(crate) fn paint(ui: &Ui, rect: Rect, (highlighted, focused): (bool, bool), thumbnail: Option, (caption, name): (&str, &str)) { - let tokens = Tokens::get(ui.ctx()); - let painter = ui.painter(); - let (fill, border) = if highlighted { (tokens.row_hover, tokens.button_border) } else { (tokens.field, tokens.field_border) }; - painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside); - if focused { - painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); - } +#[cfg(test)] +mod tests { + use super::*; - if let Some(texture) = thumbnail { - let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); - painter.image(texture, image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); - } + /// Two filter sheets drawn in one frame: the one for another effect leaves the request to the slot it is for + #[test] + fn an_open_request_waits_for_its_own_slot() { + let ctx = egui::Context::default(); + open_picker_when_shown(&ctx, 2); - // Long names are cut short rather than run under the thumbnail or the caret - let text_left = rect.left() + THUMBNAIL_INSET * 2.0 + THUMBNAIL_SIZE; - let text_right = rect.right() - CARET_INSET * 2.0; - let text_center_x = (text_left + text_right) * 0.5; - let lines = [(caption, CAPTION_FONT_SIZE, tokens.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tokens.text_strong, LINE_GAP * 0.5)]; - for (text, size, color, offset) in lines { - let galley = elided(painter, text, size, color, text_right - text_left); - painter.galley(pos2(text_center_x, rect.center().y + offset) - galley.size() * 0.5, galley, color); + assert!(!take_open_request(&ctx, 1), "not the requested slot"); + assert!(take_open_request(&ctx, 2), "the requested slot still finds it"); + assert!(!take_open_request(&ctx, 2), "taken once"); } - - let caret_color = if highlighted { tokens.text } else { tokens.text_dim }; - painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); } diff --git a/crates/ui-egui/src/filter_transform_rows.rs b/crates/ui-egui/src/filter_transform_rows.rs new file mode 100644 index 00000000..68bdb4bd --- /dev/null +++ b/crates/ui-egui/src/filter_transform_rows.rs @@ -0,0 +1,91 @@ +//! The Transform filter's rows: Scaling and Offset beside a preview of the moved tile, Tile Safe Rotation, Rotation, Repeat mode and Flip mode + +use std::ops::RangeInclusive; + +use egui::{Painter, Rect, pos2}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{FlipMode, RepeatMode, TileTransform, UvWrap}; + +use crate::TextureCraftApp; +use crate::fill_pictures::{lattice_preview, wrap_picture}; +use crate::filter_properties::DIAL_DEGREES; +use crate::i18n::tr; +use crate::property_sheet::{PreviewLower, PreviewSize, PropertySheet}; +use crate::theme::Tokens; + +/// What the Scaling track spans (a fill's Tiling track); typing reaches the filter's whole range +const SCALING_TRACK: RangeInclusive = 0.01..=5.0; + +/// What the Offset track spans, in tiles: one tile either way covers every position of a repeating tile +const OFFSET_TRACK: RangeInclusive = -1.0..=1.0; + +/// The rows in the reference's order: Scaling (linked) and Offset beside the preview, Tile Safe Rotation, Rotation, Repeat mode, Flip mode +pub(crate) fn transform_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, transform: &TileTransform) { + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + }; + let tokens = Tokens::get(sheet.ui.ctx()); + + let link_id = sheet.ui.make_persistent_id(("transform_scaling_link", id)); + let mut linked = sheet.ui.data(|data| data.get_temp::(link_id)).unwrap_or(transform.scaling[0] == transform.scaling[1]); + let was_linked = linked; + let (low, high) = TileTransform::SCALING; + let mut scaling = transform.scaling; + let size = PreviewSize { label: tr("Scaling"), values: &mut scaling, range: SCALING_TRACK, typed: low..=high, decimals: 2, linked: &mut linked }; + let mut offset = transform.offset; + let reach = TileTransform::MAX_OFFSET; + let lower = PreviewLower::Offset { values: &mut offset, range: OFFSET_TRACK, typed: -reach..=reach }; + let (map, repeat) = (transform.affine(), transform.repeat == RepeatMode::HorizontallyAndVertically); + let picture = |painter: &Painter, rect: Rect| lattice_preview(painter, rect, map, repeat, &tokens); + let edit = sheet.preview_block(&picture, size, lower); + if linked != was_linked { + sheet.ui.data_mut(|data| data.insert_temp(link_id, linked)); + } + if let Some(merge) = edit.size + && scaling != transform.scaling + { + set(app, "scaling", json!(scaling), merge); + } + if let Some(merge) = edit.lower + && offset != transform.offset + { + set(app, "offset", json!(offset), merge); + } + + let mut tile_safe = transform.tile_safe; + if sheet.toggle(tr("Tile Safe Rotation"), &mut tile_safe) { + set(app, "tileSafeRotation", json!(tile_safe), false); + } + let mut degrees = transform.rotation; + if let Some(merge) = sheet.angle(tr("Rotation"), &mut degrees, DIAL_DEGREES) { + set(app, "rotation", json!(degrees), merge); + } + + let repeat_picture = |painter: &Painter, rect: Rect, mode: RepeatMode| { + let wrap = if mode == RepeatMode::None { UvWrap::None } else { UvWrap::Repeat }; + wrap_picture(painter, rect, wrap, &tokens); + }; + let name = |mode: RepeatMode| tr(mode.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Repeat mode"), transform.repeat, &RepeatMode::ALL, name, Some(&repeat_picture)) { + set(app, "repeatMode", json!(picked.id()), false); + } + let flip_picture = |painter: &Painter, rect: Rect, mode: FlipMode| flip_picture(painter, rect, mode, &tokens); + let name = |mode: FlipMode| tr(mode.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Flip mode"), transform.flip, &FlipMode::ALL, name, Some(&flip_picture)) { + set(app, "flipMode", json!(picked.id()), false); + } +} + +/// An L, turned over the way the flip mode turns the tile (no letters, so it reads in any language) +fn flip_picture(painter: &Painter, rect: Rect, mode: FlipMode, tokens: &Tokens) { + const L_SHAPE: [[f32; 2]; 6] = [[0.3, 0.2], [0.45, 0.2], [0.45, 0.65], [0.75, 0.65], [0.75, 0.8], [0.3, 0.8]]; + let [across, down] = mode.sides(); + + // An L is not convex: two rectangles draw it + let [top, _, joint, _, far, bottom] = L_SHAPE.map(|[u, v]| { + let (u, v) = (if across { 1.0 - u } else { u }, if down { 1.0 - v } else { v }); + pos2(rect.left() + u * rect.width(), rect.top() + v * rect.height()) + }); + painter.rect_filled(Rect::from_two_pos(top, pos2(joint.x, bottom.y)), 0, tokens.accent); + painter.rect_filled(Rect::from_two_pos(joint, far), 0, tokens.accent); +} diff --git a/crates/ui-egui/src/property_sheet/attribute_rows.rs b/crates/ui-egui/src/property_sheet/attribute_rows.rs new file mode 100644 index 00000000..82255146 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/attribute_rows.rs @@ -0,0 +1,60 @@ +//! Read-only rows (an asset's Attributes): a label and its value as dim text, nothing to edit + +use egui::text::{LayoutJob, TextFormat, TextWrapping}; +use egui::{FontId, Galley, Sense, pos2}; +use std::sync::Arc; + +use super::{PropertySheet, TEXT_SIZE}; + +/// Height of the label line above a wrapped text +const TEXT_LABEL_LINE: f32 = 18.0; + +/// From the label line's top to the label's centre +const TEXT_LABEL_CENTER: f32 = 8.0; + +/// Air above a wrapped text's label +const TEXT_LABEL_AIR: f32 = 4.0; + +/// Height of a wrapped text's lines +const TEXT_LINE_HEIGHT: f32 = 18.0; + +/// Air under a wrapped text's last line +const TEXT_AIR_BELOW: f32 = 6.0; + +impl PropertySheet<'_> { + /// `label` beside its value as dim text, cut with "…" where it would pass the right edge (the whole value then shows on hover) + pub(crate) fn attribute(&mut self, label: &str, value: &str) { + let (rect, center_y) = self.row(label); + let galley = self.dim_text(value, rect.width(), Some(1)); + let cut = galley.elided; + self.ui.painter().galley(pos2(rect.left(), center_y - galley.size().y / 2.0), galley, self.tokens.text_dim); + let response = self.ui.interact(rect, self.id.with(("attribute", label)), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{label}: {value}"))); + if cut { + self.tip(response, value); + } + } + + /// `label` on its own line, then `text` wrapped across the panel in dim lines + pub(crate) fn attribute_text(&mut self, label: &str, text: &str) { + self.space(TEXT_LABEL_AIR); + let line = self.take(TEXT_LABEL_LINE); + let color = self.tokens.text; + self.ui.painter().text(pos2(self.left, line.top() + TEXT_LABEL_CENTER), egui::Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), color); + let galley = self.dim_text(text, self.right - self.left, None); + let body = self.take(galley.size().y.max(TEXT_LINE_HEIGHT) + TEXT_AIR_BELOW); + let response = self.ui.interact(body, self.id.with(("attribute", label)), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{label}: {text}"))); + self.ui.painter().galley(pos2(self.left, body.top()), galley, self.tokens.text_dim); + self.drawn(body.bottom() - TEXT_AIR_BELOW); + } + + /// `text` laid out dim in `width`, wrapped on lines [`TEXT_LINE_HEIGHT`] apart, at most `rows` of them (the last cut with "…") + fn dim_text(&self, text: &str, width: f32, rows: Option) -> Arc { + let format = + TextFormat { font_id: FontId::proportional(TEXT_SIZE), color: self.tokens.text_dim, line_height: Some(TEXT_LINE_HEIGHT), ..Default::default() }; + let mut job = LayoutJob::single_section(text.to_owned(), format); + job.wrap = TextWrapping { max_width: width, max_rows: rows.unwrap_or(usize::MAX), break_anywhere: rows.is_some(), overflow_character: Some('…') }; + self.ui.painter().layout_job(job) + } +} diff --git a/crates/ui-egui/src/property_sheet/gradient_rows.rs b/crates/ui-egui/src/property_sheet/gradient_rows.rs new file mode 100644 index 00000000..a99a4cb2 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/gradient_rows.rs @@ -0,0 +1,120 @@ +//! A gradient's ramp with a marker per color, and a color's row with its place on the ramp + +use std::ops::RangeInclusive; + +use egui::{CornerRadius, Id, Mesh, Rect, Sense, Shape, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use super::PropertySheet; +use super::marker_drag::MarkerDrag; +use super::slider::KNOB_RADIUS; +use super::track::Track; +use crate::color_picker::ColorPick; +use crate::fill_material_panel::shown_color; + +/// The ramp's inset from the rows' edges, so the end markers stay inside them +const RAMP_INSET: f32 = 5.0; + +/// Height of the ramp, the air under it, and a marker's height and half width +const RAMP_HEIGHT: f32 = 16.0; +const MARKER_AIR: f32 = 2.0; +const MARKER_HEIGHT: f32 = 12.0; +const MARKER_HALF: f32 = 5.0; + +/// How far beyond a marker's sides it still answers a drag +const MARKER_HIT_MARGIN: f32 = 1.0; + +/// From the marker's tip to where its sides turn straight down +const MARKER_SHOULDER: f32 = 6.0; + +/// The whole ramp block: ramp, markers and the air under them +const RAMP_BLOCK: f32 = 40.0; + +/// Slices the ramp is drawn in (colors blend between them) +const RAMP_SLICES: usize = 64; + +/// Width of a color row's swatch and its height +const SWATCH_WIDTH: f32 = 44.0; +const SWATCH_HEIGHT: f32 = 18.0; + +/// From the controls column to the eyedropper's centre and to the position track +const EYEDROPPER_X: f32 = 56.0; +const STOP_TRACK_X: f32 = 72.0; + +impl PropertySheet<'_> { + /// The ramp as `at` (linear colors along 0..1) draws it, with a marker under it for each of `colors` at its place in `positions`; a marker drags along it + pub(crate) fn gradient_ramp(&mut self, colors: &[[f32; 3]], positions: &[f32], at: &dyn Fn(f32) -> [f32; 3]) -> Option { + let block = self.take(RAMP_BLOCK); + let (x0, x1) = (self.left + RAMP_INSET, self.right - RAMP_INSET); + let ramp = Rect::from_min_max(pos2(x0, block.top()), pos2(x1, block.top() + RAMP_HEIGHT)); + let tokens = self.tokens; + let mut mesh = Mesh::default(); + for slice in 0..=RAMP_SLICES { + let share = slice as f32 / RAMP_SLICES as f32; + let x = x0 + (x1 - x0) * share; + let color = shown_color(at(share)); + mesh.colored_vertex(pos2(x, ramp.top()), color); + mesh.colored_vertex(pos2(x, ramp.bottom()), color); + if slice > 0 { + let base = (slice as u32) * 2; + mesh.add_triangle(base - 2, base - 1, base); + mesh.add_triangle(base - 1, base, base + 1); + } + } + let painter = self.ui.painter().clone(); + painter.add(Shape::mesh(mesh)); + painter.rect_stroke(ramp, CornerRadius::ZERO, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + + let mut drag = None; + for (index, color) in colors.iter().enumerate() { + let position = positions.get(index).copied().unwrap_or(0.0).clamp(0.0, 1.0); + let x = x0 + (x1 - x0) * position; + let top = ramp.bottom() + MARKER_AIR; + let hit = Rect::from_min_max(pos2(x - MARKER_HALF - MARKER_HIT_MARGIN, top), pos2(x + MARKER_HALF + MARKER_HIT_MARGIN, top + MARKER_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::drag()); + response.widget_info(|| WidgetInfo::slider(true, f64::from(position), crate::i18n::trf("Color {number}", &[("number", &(index + 1))]))); + let moved_to = response + .interact_pointer_pos() + .filter(|_| response.dragged()) + .map(|pointer| ((pointer.x - x0) / (x1 - x0).max(1.0)).clamp(0.0, 1.0)) + .filter(|picked| *picked != position); + if let Some(merge) = crate::widgets::press_edit(self.ui, response.id, moved_to.is_some()) + && let Some(moved_to) = moved_to + { + drag = Some(MarkerDrag { index, position: moved_to, merge }); + } + let outline = if response.hovered() || response.dragged() { tokens.accent } else { tokens.text_dim }; + let points = vec![ + pos2(x, top), + pos2(x + MARKER_HALF, top + MARKER_SHOULDER), + pos2(x + MARKER_HALF, top + MARKER_HEIGHT), + pos2(x - MARKER_HALF, top + MARKER_HEIGHT), + pos2(x - MARKER_HALF, top + MARKER_SHOULDER), + ]; + painter.add(Shape::convex_polygon(points, shown_color(*color), Stroke::new(1.0, outline))); + } + self.drawn(ramp.bottom() + MARKER_AIR + MARKER_HEIGHT); + drag + } + + /// Color N: its swatch (a click opens the picker) and eyedropper, then its place on the ramp; returns the pick and the place's edit + pub(crate) fn color_stop( + &mut self, + label: &str, + linear: [f32; 3], + position: &mut f32, + eyedropping: Option, + swatches: &[[f32; 3]], + ) -> (ColorPick, Option) { + let (control, center_y) = self.row(label); + let swatch = Rect::from_min_size(pos2(control.left(), center_y - SWATCH_HEIGHT / 2.0), vec2(SWATCH_WIDTH, SWATCH_HEIGHT)); + let pick = self.color_bar_at(swatch, control.left() + EYEDROPPER_X, label, linear, eyedropping, swatches); + + let id = self.next_id(); + let range: RangeInclusive = 0.0..=1.0; + let track = Track { start: control.left() + STOP_TRACK_X + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dragged = self.track(id, label, &track, position, &range); + let typed = self.value_field(id, label, center_y, *position, &range, 2, ""); + (pick, Self::apply_typed(position, typed, dragged)) + } +} diff --git a/crates/ui-egui/tests/it/filter_card.rs b/crates/ui-egui/tests/it/filter_card.rs new file mode 100644 index 00000000..6c78e409 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_card.rs @@ -0,0 +1,105 @@ +//! The Filter effect card in Properties: channel pills, Intensity's Divider chip, the card holding the parameters with its ⟲ beside × and Attributes as its last row + +use crate::filter_support::{WINDOW_HEIGHT, app_with, click_at, filter_of}; +use egui::accesskit::Role; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{Channel, Filter, SourceWarp}; + +#[test] +fn a_pill_switches_its_channel_and_the_chip_picks_the_divider() { + let (mut harness, effect) = app_with("warp", "content", WINDOW_HEIGHT); + let rough = harness.get_by_role_and_label(Role::CheckBox, "Rough").rect(); + + click_at(&mut harness, rough.center()); + + assert!(harness.state().session.doc.project.effect(effect).unwrap().1.off_channels.contains(&Channel::Roughness)); + + let chip = harness.get_by_role_and_label(Role::ComboBox, "÷10").rect(); + click_at(&mut harness, chip.center()); + assert!(egui::Popup::is_any_open(&harness.ctx), "the chip opens its list"); + + let hundred = harness.get_by_role_and_label(Role::ListBoxOption, "÷100").rect(); + click_at(&mut harness, hundred.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::SourceWarp(SourceWarp { divider: 100, .. })), "{:?}", filter_of(&harness, effect)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "picking closes the list"); +} + +#[test] +fn restore_defaults_and_clear_on_the_card() { + let (mut harness, effect) = app_with("blur", "content", WINDOW_HEIGHT); + let defaults = filter_of(&harness, effect); + + let restore = harness.get_by_role_and_label(Role::Button, "Restore defaults"); + assert!(restore.accesskit_node().is_disabled(), "inert at the defaults"); + let restore = restore.rect(); + let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect(); + assert!((restore.center().y - clear.center().y).abs() < 0.5 && restore.right() < clear.left(), "⟲ beside × on the card"); + + harness.state_mut().run("effect.set", json!({"effect": effect.0, "radius": 40.0})); + harness.run_steps(3); + let restore = harness.get_by_role_and_label(Role::Button, "Restore defaults").rect(); + click_at(&mut harness, restore.center()); + + assert_eq!(filter_of(&harness, effect), defaults); + + let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect(); + click_at(&mut harness, clear.center()); + + assert_eq!(filter_of(&harness, effect), Filter::Empty); + assert!(harness.query_by_label("Attributes").is_none(), "an empty filter has no settings"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Filter").is_some(), "the card reads Filter over None"); +} + +/// How far a card reaches past its rows on each side (the panel style's card bleed) +const CARD_BLEED: f32 = 6.0; + +/// The filter's card holds its rows: no Parameters band, every row and the Attributes row inside the card's edges, Attributes last +#[test] +fn the_filter_card_holds_its_parameters() { + let (harness, _) = app_with("slopeBlur", "content", WINDOW_HEIGHT); + assert!(harness.query_by_label("Parameters").is_none(), "no Parameters band"); + + let card = harness.get_by_role_and_label(Role::ComboBox, "Blur Slope").rect(); + let attributes = harness.get_by_role_and_label(Role::Button, "Attributes").rect(); + let sub_group = harness.get_by_role_and_label(Role::Button, "Source Parameters").rect(); + + // A row inside the card keeps the card's bleed on both sides; a band would span the panel + assert_eq!(attributes.left(), card.left() + CARD_BLEED, "{attributes:?} {card:?}"); + assert_eq!(sub_group.left(), attributes.left(), "a sub-group is a caption in the card, not a card of its own"); + for slider in harness.query_all_by_role(Role::Slider) { + assert!(slider.rect().bottom() <= attributes.top(), "Attributes is the card's last row: {:?}", slider.rect()); + } +} + +/// Air between the bottom of slider `last` and the top of the Attributes row under it, with library filter `filter` shown +fn air_under(filter: &str, last: &str) -> f32 { + let (harness, _) = app_with(filter, "content", WINDOW_HEIGHT); + let slider = harness.get_by_role_and_label(Role::Slider, last).rect(); + harness.get_by_role_and_label(Role::Button, "Attributes").rect().top() - slider.bottom() +} + +#[test] +fn a_generic_filter_ends_its_parameters_like_a_dedicated_one() { + // Sharpen's rows come from the library's parameters, Mask Outline's from its own rows; both end on a slider + assert_eq!(air_under("sharpen", "Sharpen Intensity"), air_under("maskOutline", "Curve Shape")); +} + +#[test] +fn replace_colors_two_colors_are_colour_bars_with_their_eyedroppers() { + let (mut harness, effect) = app_with("replaceColor", "content", WINDOW_HEIGHT); + assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Pick color").count(), 2, "an eyedropper beside each color"); + + let bar = harness.get_by_role_and_label(Role::Button, "Replacement color").rect(); + click_at(&mut harness, bar.center()); + let hex = harness.get_by_role_and_label(Role::TextInput, "Hex color").rect(); + click_at(&mut harness, hex.center()); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text("FF0000".into())); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + let Filter::ReplaceColor { to, .. } = filter_of(&harness, effect) else { panic!("a Replace Color filter") }; + assert_eq!(to, [1.0, 0.0, 0.0], "the bar's picker sets the replacement color"); +} diff --git a/crates/ui-egui/tests/it/filter_gradient.rs b/crates/ui-egui/tests/it/filter_gradient.rs new file mode 100644 index 00000000..9a485c56 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_gradient.rs @@ -0,0 +1,163 @@ +//! The gradient filters in Properties: Gradient Map's rows (the ramp's markers, Color Quantity, Input Transformation, the color rows), Gradient Curve's +//! Preset list, Invert and Balance, and Gradient Dynamic's orientation and Gradient Input Position + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, drag, drag_through, filter_of, lowest, topmost, undo, undo_depth}; +use egui::accesskit::Role; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{CurvePreset, Filter, GrayscaleMode}; +use texturecraft_engine::filter_lib::GRADIENT_QUANTITY_MIN; + +/// Dragging Color 2's marker along the ramp moves its place, and one undo puts it back +#[test] +fn a_gradient_marker_drags_its_color_along_the_ramp() { + let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); + + // Color 2's row has a place track named Color 2 too: the ramp's marker is the topmost + let marker = topmost(&harness, Role::Slider, "Color 2"); + drag(&mut harness, marker.center(), marker.center() + egui::vec2(60.0, 0.0)); + + let Filter::GradientMap { positions, .. } = filter_of(&harness, effect) else { panic!() }; + let moved = positions.get(1).copied().unwrap(); + assert!(moved > 0.6, "dragged right: {positions:?}"); + + undo(&mut harness); + + let Filter::GradientMap { positions, .. } = filter_of(&harness, effect) else { panic!() }; + assert_eq!(positions.get(1), Some(&0.5), "one undo step for the drag"); +} + +/// Color Quantity at its right end shows ten color rows +#[test] +fn color_quantity_adds_color_rows() { + let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); + assert!(harness.query_by_label("Color 4").is_none()); + + let track = harness.get_by_role_and_label(Role::Slider, "Color Quantity").rect(); + click_at(&mut harness, along(track, 1.0)); + + assert_eq!(filter_of(&harness, effect).ramp_colors().len(), 10); + assert!(harness.query_all_by_label("Color 10").next().is_some(), "the tenth color has its row"); +} + +/// egui's click distance (`InputOptions::max_click_dist`): a press whose pointer travels further is a drag +const DRAG_THRESHOLD: f32 = 6.0; + +/// A Color Quantity drag whose first change rounds to the count it had starts its own undo step: undo leaves the edit before it alone +#[test] +fn a_color_quantity_drag_is_its_own_undo_step() { + let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); + let linear = harness.get_by_role_and_label(Role::CheckBox, "Blend Color in Linear").rect(); + click_at(&mut harness, linear.center()); + assert!(matches!(filter_of(&harness, effect), Filter::GradientMap { linear: false, .. })); + let depth = undo_depth(&harness); + + // From 2.6 colors to 3.2 (both round to the 3 it has), then to 4.2 + let track = harness.get_by_role_and_label(Role::Slider, "Color Quantity").rect(); + let (least, most) = (f32::from(GRADIENT_QUANTITY_MIN), f32::from(Filter::MAX_GRADIENT_COLORS)); + let at = |colors: f32| along(track, (colors - least) / (most - least)); + assert!(at(3.2).x - at(2.6).x > DRAG_THRESHOLD, "the first move already drags: {track:?}"); + + drag_through(&mut harness, at(2.6), &[at(3.2), at(4.2)]); + + assert_eq!(filter_of(&harness, effect).ramp_colors().len(), 4); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); + + undo(&mut harness); + let filter = filter_of(&harness, effect); + assert_eq!(filter.ramp_colors().len(), 3, "the drag undone"); + assert!(matches!(filter, Filter::GradientMap { linear: false, .. }), "Blend Color in Linear stays off: {filter:?}"); +} + +/// Input Transformation's Grayscale Mode list, Blur Intensity and Invert, Display Gradient (Debug), Blend Color in Linear and a color row's place track each set their own setting +#[test] +fn gradient_map_rows_set_their_own_setting() { + let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); + + let list = harness.get_by_role_and_label(Role::ComboBox, "Average").rect(); + click_at(&mut harness, list.center()); + let max = harness.get_by_label("Max").rect(); + click_at(&mut harness, max.center()); + let blur = harness.get_by_role_and_label(Role::Slider, "Blur Intensity").rect(); + click_at(&mut harness, along(blur, 0.5)); + for toggle in ["Invert", "Display Gradient (Debug)", "Blend Color in Linear"] { + let rect = harness.get_by_role_and_label(Role::CheckBox, toggle).rect(); + click_at(&mut harness, rect.center()); + } + + // Color 2's row is the lower of the two Color 2 tracks (the ramp's marker is the upper) + let row = lowest(&harness, Role::Slider, "Color 2"); + click_at(&mut harness, along(row, 1.0)); + + let Filter::GradientMap { input, debug, linear, positions, .. } = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert_eq!((input.mode, input.invert, debug, linear), (GrayscaleMode::Max, true, true, false)); + assert!((input.blur - 8.0).abs() < 0.05, "the middle of 0..16: {}", input.blur); + assert_eq!(positions.get(1), Some(&1.0), "Color 2 moved to the end: {positions:?}"); + assert_eq!((input.balance, input.contrast), (0.5, 0.0), "the others stay"); +} + +/// Gradient Curve's Preset list picks a curve +#[test] +fn gradient_curve_preset_list_picks_a_curve() { + let (mut harness, effect) = app_with("gradientCurve", "content", WINDOW_HEIGHT); + let list = harness.get_by_role_and_label(Role::ComboBox, "Round").rect(); + click_at(&mut harness, list.center()); + let bump = harness.get_by_label("Bump").rect(); + + click_at(&mut harness, bump.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::GradientCurve { preset: CurvePreset::Bump, .. }), "{:?}", filter_of(&harness, effect)); +} + +/// Gradient Curve's Invert and Balance set their own setting +#[test] +fn gradient_curve_invert_and_balance() { + let (mut harness, effect) = app_with("gradientCurve", "content", WINDOW_HEIGHT); + + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + click_at(&mut harness, invert.center()); + let balance = harness.get_by_role_and_label(Role::Slider, "Balance").rect(); + click_at(&mut harness, along(balance, 1.0)); + + let Filter::GradientCurve { invert, balance, contrast, .. } = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!(invert && balance > 0.99 && contrast == 0.0, "{invert} {balance} {contrast}"); +} + +/// Gradient Dynamic's Gradient Input Position follows its track +#[test] +fn gradient_dynamic_input_position_follows_its_track() { + let (mut harness, effect) = app_with("gradientDynamic", "content", WINDOW_HEIGHT); + let position = harness.get_by_role_and_label(Role::Slider, "Gradient Input Position").rect(); + + click_at(&mut harness, along(position, 0.5)); + + assert!( + matches!(filter_of(&harness, effect), Filter::GradientDynamic { position, .. } if (position - 0.5).abs() < 0.01), + "{:?}", + filter_of(&harness, effect) + ); +} + +/// Gradient Dynamic's orientation turns vertical: a boxed switch at the panel's width, Vertical one click away +#[test] +fn gradient_dynamic_orientation_turns_vertical() { + let (mut harness, effect) = app_with("gradientDynamic", "content", WINDOW_HEIGHT); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Horizontal").is_none(), "both choices fit side by side"); + + let vertical = harness.get_by_label("Vertical").rect(); + click_at(&mut harness, vertical.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::GradientDynamic { vertical: true, .. }), "{:?}", filter_of(&harness, effect)); +} + +#[test] +fn gradient_dynamic_source_card_opens_the_color_picker() { + let (mut harness, _) = app_with("gradientDynamic", "content", WINDOW_HEIGHT); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Gradient Source").is_none(), "no picker yet"); + + // Through the pointer, on the card's name: the card's whole row picks its source + let card = harness.get_by_role_and_label(Role::ComboBox, "Gradient Source").rect(); + click_at(&mut harness, card.center()); + harness.run_steps(4); + + assert!(harness.query_by_role_and_label(Role::TitleBar, "Gradient Source").is_some(), "the card opens the colour picker of its bar"); +} diff --git a/crates/ui-egui/tests/it/filter_inputs.rs b/crates/ui-egui/tests/it/filter_inputs.rs new file mode 100644 index 00000000..b3ff2d4f --- /dev/null +++ b/crates/ui-egui/tests/it/filter_inputs.rs @@ -0,0 +1,114 @@ +//! Filter image inputs and Attributes in Properties: Bevel Smooth's Distance Map card after the filter's, Warp's Custom Noise slot under its Source Mode, the read-only Attributes row ending the filter card + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{LayerId, ProceduralKind, Source}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, lowest, pick, topmost}; + +/// The source effect `effect` holds in its input `id` +fn input(harness: &Harness<'_, TextureCraftApp>, effect: LayerId, id: &str) -> Option { + harness.state().session.doc.project.effect(effect).unwrap().1.inputs.get(id).cloned() +} + +/// A click on the control of `role` named `label` (the lowest, where a list above shows the same name) +fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + let at = lowest(harness, role, label).center(); + click_at(harness, at); +} + +/// The Distance Map slot picks a pattern from the source picker, × puts it back to white, its ramp sets a gray +#[test] +fn the_distance_map_slot_picks_its_source() { + let (mut harness, effect) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); + assert!(harness.query_by_label("Image inputs").is_none(), "an input every mode reads is a card of its own, no band"); + assert!(lowest(&harness, Role::ComboBox, "Distance Map").top() > topmost(&harness, Role::Button, "Attributes").bottom(), "after the filter card"); + + click(&mut harness, Role::ComboBox, "Distance Map"); + assert!(harness.query_by_role_and_label(Role::Tab, "Anchor points").is_some(), "the slot opens the source picker"); + click(&mut harness, Role::ListBoxOption, "Clouds"); + + let Some(Source::Procedural { pattern, low, high, .. }) = input(&harness, effect, "distanceMap") else { panic!("a procedural") }; + assert_eq!((pattern.kind, low, high), (ProceduralKind::Clouds, [0.0; 3], [1.0; 3])); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); + + // The filter card has its own ×: the slot's is the lower one + click(&mut harness, Role::Button, "Clear"); + assert_eq!(input(&harness, effect, "distanceMap"), None, "back to its default white"); + + let ramp = harness.get_by_role_and_label(Role::Slider, "Distance Map").rect(); + click_at(&mut harness, along(ramp, 0.0)); + + let Some(Source::Uniform([gray, ..])) = input(&harness, effect, "distanceMap") else { panic!("a gray") }; + assert!(gray < 0.05, "{gray}"); +} + +/// Warp shows its Custom Noise slot right under Source Mode only in that mode, above the source's sliders; a pattern picked there shows its Scale and Contrast +#[test] +fn the_custom_noise_slot_follows_the_source_mode() { + let (mut harness, effect) = app_with("warp", "mask", WINDOW_HEIGHT); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Custom Noise").is_none()); + + pick(&mut harness, "Default Noise", "Custom Noise"); + + let slot = lowest(&harness, Role::ComboBox, "Custom Noise"); + let blur = harness.get_by_role_and_label(Role::Slider, "Source Blur").rect(); + assert!(slot.bottom() <= blur.top(), "the slot sits above Source Blur"); + + click_at(&mut harness, slot.center()); + click(&mut harness, Role::ListBoxOption, "Clouds"); + + let Some(Source::Procedural { pattern, .. }) = input(&harness, effect, "customNoise") else { panic!("a procedural custom noise") }; + assert!(harness.query_by_label("Image inputs").is_none(), "a mode's input is not under Image inputs"); + + // The picked pattern's Scale and Contrast show inside the mode's card, like every slot's, and set the pattern + let scale = harness.get_by_role_and_label(Role::Slider, "Scale").rect(); + assert!(scale.top() >= slot.bottom() && harness.query_by_role_and_label(Role::Slider, "Contrast").is_some()); + + click_at(&mut harness, along(scale, 0.0)); + + let Some(Source::Procedural { pattern: scaled, .. }) = input(&harness, effect, "customNoise") else { panic!("still a procedural") }; + assert!(scaled.scale < pattern.scale, "{} -> {}", pattern.scale, scaled.scale); +} + +/// Attributes is closed at first; a click on the filter card's last row shows the filter's read-only rows in the card, above the input cards; another hides them +#[test] +fn the_attributes_row_opens_on_a_click() { + let (mut harness, _) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); + let category = "Category: Filter"; + assert!(harness.query_by_label(category).is_none(), "closed by default"); + let band = topmost(&harness, Role::Button, "Attributes"); + assert!(band.bottom() < lowest(&harness, Role::ComboBox, "Distance Map").top(), "above the input's card"); + + click_at(&mut harness, band.center()); + + assert!(harness.query_by_label(category).is_some()); + assert!(harness.query_by_label("Description: Draws a smooth ramp from the edge of the shapes.").is_some()); + assert!(harness.query_by_label("Tags: bevel, edge, ramp").is_some()); + assert!(harness.query_by_label("Size: 256 × 256").is_some(), "the texture set's size"); + assert!(harness.get_by_label(category).rect().top() > band.bottom(), "the rows hang under the row"); + assert!(harness.get_by_label(category).rect().bottom() < lowest(&harness, Role::ComboBox, "Distance Map").top(), "inside the filter card"); + + click_at(&mut harness, band.center()); + + assert!(harness.query_by_label(category).is_none()); +} + +/// An open section that makes the panel scroll keeps its rows in place from frame to frame (the scroll bar refits no row) +#[test] +fn the_sheet_keeps_its_layout_when_the_scroll_bar_comes_in() { + let (mut harness, _) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); + let attributes = topmost(&harness, Role::Button, "Attributes").center(); + click_at(&mut harness, attributes); + let layout = |harness: &Harness<'_, TextureCraftApp>| -> Vec { + harness.query_all_by_role(Role::ComboBox).chain(harness.query_all_by_role(Role::Button)).map(|node| node.rect()).collect() + }; + let first = layout(&harness); + + for frame in 0..3 { + harness.run_steps(1); + assert_eq!(layout(&harness), first, "frame {frame}"); + } +} diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index dfb895a8..2dcee134 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -4,33 +4,21 @@ use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::{Value, json}; -use texturecraft_engine::core::{EffectKind, Filter, LayerId}; +use texturecraft_engine::core::{Filter, LayerId}; use texturecraft_engine::{StackTarget, execute}; use texturecraft_ui_egui::TextureCraftApp; +use crate::filter_support::{WINDOW_HEIGHT, WINDOW_WIDTH, app_with, click_at, filter_of}; + /// The app with an Invert filter on a fill layer's content, selected so Properties shows its slot fn app_with_invert() -> (Harness<'static, TextureCraftApp>, LayerId) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); - let effect = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); - let effect = LayerId(effect["effect"].as_u64().unwrap()); - execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); - session.target = StackTarget::Effect(effect); - - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - harness.run_steps(4); - (harness, effect) -} - -/// The kind of effect `effect` now -fn kind(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> EffectKind { - harness.state().session.doc.project.effect(effect).unwrap().1.kind.clone() + app_with("invert", "content", WINDOW_HEIGHT) } /// Clicks the Invert slot, which opens its picker fn open_picker(harness: &mut Harness<'_, TextureCraftApp>) { - harness.get_by_role_and_label(Role::ComboBox, "Invert").click(); - harness.run_steps(3); + let at = harness.get_by_role_and_label(Role::ComboBox, "Invert").rect().center(); + click_at(harness, at); assert!(egui::Popup::is_any_open(&harness.ctx), "clicking the slot opens the picker"); } @@ -44,10 +32,10 @@ fn picking_from_the_slot_swaps_the_filter() { harness.run_steps(3); assert_eq!(harness.query_all_by_label("Blur").count(), 0, "the search hides filters that don't match"); - harness.get_by_label("Sharpen").click(); - harness.run_steps(3); + let at = harness.get_by_label("Sharpen").rect().center(); + click_at(&mut harness, at); - assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, effect)); + assert!(matches!(filter_of(&harness, effect), Filter::Sharpen { .. }), "{:?}", filter_of(&harness, effect)); assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); } @@ -63,16 +51,18 @@ fn escape_closes_the_picker_without_changes() { harness.run_steps(3); assert!(!egui::Popup::is_any_open(&harness.ctx)); - assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); + assert!(matches!(filter_of(&harness, effect), Filter::Invert)); } /// Opens the wand's Add effect menu and clicks Filter fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { harness.get_by_role_and_label(Role::Button, "Add effect").click(); - harness.run_steps(3); + let at = harness.get_by_role_and_label(Role::Button, "Add effect").rect().center(); + click_at(harness, at); harness.get_by_role_and_label(Role::Button, "Filter").click(); - harness.run_steps(3); + let at = harness.get_by_role_and_label(Role::Button, "Filter").rect().center(); + click_at(harness, at); } #[test] @@ -81,20 +71,20 @@ fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { add_filter_from_the_wand(&mut harness); let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; - assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); - assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot"); + assert!(matches!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&harness, added)); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Filter").is_some(), "Properties shows the new filter's slot"); assert!(egui::Popup::is_any_open(&harness.ctx), "the new filter's picker is open to choose the real filter"); // The search field has the focus, and a search brings Sharpen into view harness.event(egui::Event::Text("sharp".into())); harness.run_steps(3); - harness.get_by_label("Sharpen").click(); - harness.run_steps(3); - assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, added)); + let at = harness.get_by_label("Sharpen").rect().center(); + click_at(&mut harness, at); + assert!(matches!(filter_of(&harness, added), Filter::Sharpen { .. }), "{:?}", filter_of(&harness, added)); } #[test] -fn escape_after_add_filter_keeps_the_neutral_filter() { +fn escape_after_add_filter_keeps_the_empty_filter() { let (mut harness, _) = app_with_invert(); add_filter_from_the_wand(&mut harness); assert!(harness.query_by_label("Sharpen").is_some(), "Add filter opened the picker"); @@ -104,16 +94,17 @@ fn escape_after_add_filter_keeps_the_neutral_filter() { let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter stays selected") }; assert!(!egui::Popup::is_any_open(&harness.ctx)); - assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(matches!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&harness, added)); harness.state_mut().run("edit.undo", Value::Null); - assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the neutral filter"); + assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the empty filter"); } #[test] fn add_filter_on_a_mask_adds_it_to_the_mask() { let (mut harness, _) = app_with_invert(); let layer = harness.state().session.selected_layer().unwrap(); + // A new mask becomes the selected target, so the wand adds to it harness.state_mut().run("mask.add.white", json!({"layer": layer.0})); harness.run_steps(3); @@ -123,9 +114,10 @@ fn add_filter_on_a_mask_adds_it_to_the_mask() { let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; let mask = harness.state().session.doc.project.layer(layer).unwrap().mask.clone().unwrap(); assert!(mask.effects.iter().any(|effect| effect.id == added), "the filter went on the mask"); - assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(matches!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&harness, added)); assert!(harness.query_by_label("Sharpen").is_some(), "the mask filter's picker is open"); - assert!(harness.query_by_label("Grayscale").is_none(), "the picker leaves out content-only filters"); + assert!(harness.query_by_label("Normal Invert").is_none(), "the picker leaves out content-only filters"); + assert!(harness.query_by_label("Grayscale Conversion").is_some(), "masks take Grayscale Conversion"); } #[test] @@ -137,7 +129,7 @@ fn add_filter_reopens_closed_properties_to_show_its_picker() { add_filter_from_the_wand(&mut harness); - assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Add filter reveals Properties"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Filter").is_some(), "Add filter reveals Properties"); assert!(harness.query_by_label("Sharpen").is_some(), "the picker opens immediately"); } @@ -158,10 +150,13 @@ fn keyboard_opens_the_slot_and_outside_click_closes_it() { } harness.run_steps(3); assert!(!egui::Popup::is_any_open(&harness.ctx)); - assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); + assert!(matches!(filter_of(&harness, effect), Filter::Invert)); } } +/// The snapshots' window height: a usual desktop window, the picker opening over the views +const SNAPSHOT_HEIGHT: f32 = 960.0; + #[test] #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] fn filter_picker_snapshots_and_frame_timings() { @@ -170,7 +165,7 @@ fn filter_picker_snapshots_and_frame_timings() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|cc| { + let mut harness = Harness::builder().with_size(egui::vec2(WINDOW_WIDTH, SNAPSHOT_HEIGHT)).wgpu().build_eframe(|cc| { eprintln!("selected graphics adapter: {:?}", cc.wgpu_render_state.as_ref().unwrap().adapter.get_info()); TextureCraftApp::new(cc, session) }); @@ -193,7 +188,7 @@ fn filter_picker_snapshots_and_frame_timings() { harness.event(egui::Event::Text("sharp".into())); harness.run_steps(3); harness.render().unwrap().save(output.join("filter-picker-search.png")).unwrap(); - harness.get_by_label("Sharpen").click(); - harness.run_steps(3); + let at = harness.get_by_label("Sharpen").rect().center(); + click_at(&mut harness, at); harness.render().unwrap().save(output.join("filter-picker-selected.png")).unwrap(); } diff --git a/crates/ui-egui/tests/it/filter_support.rs b/crates/ui-egui/tests/it/filter_support.rs index 912e2017..cd8a750e 100644 --- a/crates/ui-egui/tests/it/filter_support.rs +++ b/crates/ui-egui/tests/it/filter_support.rs @@ -1,8 +1,48 @@ //! Helpers the filter panel tests share +use egui::accesskit::Role; use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Filter, LayerId}; +use texturecraft_engine::{StackTarget, execute}; use texturecraft_ui_egui::TextureCraftApp; +/// The test window's width: the dock at its usual size beside the views +pub(crate) const WINDOW_WIDTH: f32 = 1600.0; + +/// A window tall enough for a filter's rows and its Attributes in the docked Properties panel +pub(crate) const WINDOW_HEIGHT: f32 = 1400.0; + +/// A window tall enough for the filters with many cards (Baked Lighting Stylized, Color Match) to show every row unscrolled +pub(crate) const TALL_WINDOW_HEIGHT: f32 = 2400.0; + +/// The app `height` tall with library filter `filter` on a fill layer's `target` ("content" or "mask", a white mask added), selected so Properties shows it +pub(crate) fn app_with(filter: &str, target: &str, height: f32) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + if target == "mask" { + execute(&mut session, "mask.add.white", &json!({"layer": layer["layer"]})).unwrap(); + } + let effect = execute(&mut session, "effect.add.filter", &json!({"target": target, "filter": filter})).unwrap(); + let effect = LayerId(effect["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); + session.target = StackTarget::Effect(effect); + + let mut harness = Harness::builder().with_size(egui::vec2(WINDOW_WIDTH, height)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + (harness, effect) +} + +/// The filter effect `effect` holds now +pub(crate) fn filter_of(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Filter { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Filter(filter) => filter.clone(), + other => panic!("not a filter: {other:?}"), + } +} + /// A real pointer click at `pos`: move there, press, one frame, release, then frames for the edit to show pub(crate) fn click_at(harness: &mut Harness<'_, TextureCraftApp>, pos: egui::Pos2) { let modifiers = egui::Modifiers::NONE; @@ -13,6 +53,18 @@ pub(crate) fn click_at(harness: &mut Harness<'_, TextureCraftApp>, pos: egui::Po harness.run_steps(3); } +/// Pick `option` of a setting shown as a boxed switch where its words fit, or as a dropdown showing `current` where they don't +pub(crate) fn pick(harness: &mut Harness<'_, TextureCraftApp>, current: &str, option: &str) { + if let Some(segment) = harness.query_by_role_and_label(Role::RadioButton, option).map(|node| node.rect()) { + click_at(harness, segment.center()); + } else { + let list = harness.get_by_role_and_label(Role::ComboBox, current).rect(); + click_at(harness, list.center()); + let choice = harness.get_by_label(option).rect(); + click_at(harness, choice.center()); + } +} + /// A press at `from`, a drag to `to` in steps and a release, as the pointer does it pub(crate) fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, to: egui::Pos2) { let steps: Vec = (1..=DRAG_STEPS).map(|step| from + (to - from) * (step as f32 / DRAG_STEPS as f32)).collect(); @@ -42,6 +94,16 @@ pub(crate) fn along(track: egui::Rect, share: f32) -> egui::Pos2 { egui::pos2(track.left() + SLIDER_TRACK_INSET + (track.width() - 2.0 * SLIDER_TRACK_INSET) * share, track.center().y) } +/// The rect of the topmost of the widgets with `role` and `label` (a name a later row repeats) +pub(crate) fn topmost(harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> egui::Rect { + harness.get_all_by_role_and_label(role, label).map(|node| node.rect()).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap() +} + +/// The rect of the lowest of the widgets with `role` and `label` +pub(crate) fn lowest(harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> egui::Rect { + harness.get_all_by_role_and_label(role, label).map(|node| node.rect()).max_by(|a, b| a.top().total_cmp(&b.top())).unwrap() +} + /// Moves a drag makes on its way, one frame each, so a press makes several changes const DRAG_STEPS: usize = 4; @@ -49,3 +111,9 @@ const DRAG_STEPS: usize = 4; pub(crate) fn undo_depth(harness: &Harness<'_, TextureCraftApp>) -> usize { harness.state().session.history_labels().len() } + +/// Undoes the last step, then frames for the panel to show it +pub(crate) fn undo(harness: &mut Harness<'_, TextureCraftApp>) { + harness.state_mut().session.undo().unwrap(); + harness.run_steps(2); +} From b4d810ddcf39854c4533d099129f0a2725edfd04 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:30:01 +0000 Subject: [PATCH 3/6] Filters: engine evaluation, commands, docs and the remaining tests --- crates/compose/src/below.rs | 27 +- crates/compose/src/eval.rs | 1783 +++++++++++++++-- crates/compose/src/eval/evaluation_inputs.rs | 23 - crates/compose/src/lib.rs | 9 +- crates/compose/src/shape_distance.rs | 386 ++++ crates/compose/src/slope_texel.rs | 45 + crates/compose/tests/cache_and_instances.rs | 61 +- crates/core/src/anisotropic_kuwahara.rs | 92 + crates/core/src/bevel.rs | 98 + crates/core/src/bevel_blur.rs | 35 + crates/core/src/bevel_corner.rs | 35 + crates/core/src/bevel_direction.rs | 39 + crates/core/src/bevel_smooth.rs | 117 ++ crates/core/src/conversion_mode.rs | 63 + crates/core/src/curve_preset.rs | 142 ++ crates/core/src/directional_distance.rs | 59 + crates/core/src/directional_light.rs | 31 + crates/core/src/gradient_input.rs | 151 ++ crates/core/src/grayscale_conversion.rs | 90 + crates/core/src/grayscale_mode.rs | 58 + crates/core/src/height_to_normal.rs | 80 + crates/core/src/highpass_space.rs | 84 + crates/core/src/image_input.rs | 88 + crates/core/src/layer.rs | 661 +++++- crates/core/src/lib.rs | 86 + crates/core/src/lighting_output.rs | 49 + crates/core/src/mask_outline.rs | 92 + crates/core/src/mirror.rs | 99 + crates/core/src/mirror_corner.rs | 49 + crates/core/src/mirror_mode.rs | 39 + crates/core/src/oklab.rs | 40 + crates/core/src/outline_position.rs | 48 + crates/core/src/pbr_validate.rs | 78 + crates/core/src/project.rs | 3 +- crates/core/src/slope_blending.rs | 39 + crates/core/src/source_color_mode.rs | 36 + crates/core/src/source_slope_blur.rs | 65 + crates/core/src/stylized_lighting.rs | 157 ++ crates/core/src/sun_and_sky.rs | 11 + crates/core/src/target_color_mode.rs | 33 + crates/core/src/threshold_mode.rs | 90 + crates/core/src/tile_transform.rs | 225 +++ crates/core/src/tile_transform/flip_mode.rs | 49 + crates/core/src/tile_transform/repeat_mode.rs | 33 + crates/core/src/validation_mode.rs | 46 + crates/core/src/warp_blending.rs | 42 + crates/core/src/warp_mode.rs | 39 + crates/core/src/warp_source_mode.rs | 39 + crates/engine/src/filter_about.rs | 85 + crates/engine/src/folder_cmds.rs | 6 + crates/engine/src/inspect.rs | 10 +- crates/engine/src/layer_cmds.rs | 44 +- crates/engine/src/lib.rs | 3 + crates/engine/src/mask_cmds.rs | 76 +- crates/engine/src/material_lib.rs | 4 +- crates/engine/src/preview.rs | 49 +- crates/engine/src/session.rs | 43 +- crates/engine/src/tile_transform_params.rs | 52 + crates/engine/src/view_cmds.rs | 20 +- crates/engine/tests/it/content_effects.rs | 23 +- crates/engine/tests/it/filter_card.rs | 140 ++ crates/engine/tests/it/filter_colour.rs | 100 + crates/engine/tests/it/filter_gradient.rs | 168 ++ crates/engine/tests/it/filter_inputs.rs | 109 + crates/engine/tests/it/filter_light.rs | 204 ++ crates/engine/tests/it/filter_shape.rs | 364 ++++ crates/engine/tests/it/filter_simple.rs | 319 +++ crates/engine/tests/it/filter_swap.rs | 156 +- crates/engine/tests/it/filter_transform.rs | 78 + crates/engine/tests/it/folder_contents.rs | 1 + crates/engine/tests/it/main.rs | 9 + crates/engine/tests/it/painter_gaps.rs | 24 +- crates/engine/tests/it/resources_used.rs | 17 + crates/engine/tests/session.rs | 174 ++ crates/render/src/ibl.rs | 152 +- crates/render/src/renderer.rs | 2 +- crates/ui-egui/src/anchor_properties.rs | 22 + crates/ui-egui/src/dock.rs | 109 +- crates/ui-egui/src/fill_material_panel.rs | 1 + crates/ui-egui/src/fill_pictures.rs | 35 + crates/ui-egui/src/i18n.rs | 4 + crates/ui-egui/src/layer_toolbar.rs | 2 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/material_orb.rs | 2 + .../ui-egui/src/property_sheet/color_bar.rs | 11 + crates/ui-egui/src/property_sheet/group.rs | 89 + .../ui-egui/src/property_sheet/marker_drag.rs | 8 + crates/ui-egui/src/property_sheet/mod.rs | 3 + crates/ui-egui/src/property_sheet/row.rs | 5 +- crates/ui-egui/src/property_sheet/row_lead.rs | 4 + crates/ui-egui/src/property_sheet/slider.rs | 69 + crates/ui-egui/src/property_sheet/slot.rs | 7 + .../src/property_sheet/switch_control.rs | 13 +- crates/ui-egui/src/property_sheet/tests.rs | 44 +- .../src/property_sheet/tests/gallery.rs | 4 + crates/ui-egui/src/source_slot.rs | 10 + crates/ui-egui/src/theme.rs | 63 +- crates/ui-egui/tests/it/filter_colour.rs | 85 + crates/ui-egui/tests/it/filter_light.rs | 118 ++ crates/ui-egui/tests/it/filter_shape.rs | 307 +++ crates/ui-egui/tests/it/filter_simple.rs | 240 +++ crates/ui-egui/tests/it/filter_stylize.rs | 178 ++ crates/ui-egui/tests/it/filter_transform.rs | 86 + crates/ui-egui/tests/it/main.rs | 12 +- crates/ui-egui/tests/it/properties_lists.rs | 265 +++ crates/ui-egui/tests/ui_snapshots.rs | 642 ++++++ docs/control-protocol.md | 5 +- 107 files changed, 9956 insertions(+), 665 deletions(-) delete mode 100644 crates/compose/src/eval/evaluation_inputs.rs create mode 100644 crates/compose/src/shape_distance.rs create mode 100644 crates/compose/src/slope_texel.rs create mode 100644 crates/core/src/anisotropic_kuwahara.rs create mode 100644 crates/core/src/bevel.rs create mode 100644 crates/core/src/bevel_blur.rs create mode 100644 crates/core/src/bevel_corner.rs create mode 100644 crates/core/src/bevel_direction.rs create mode 100644 crates/core/src/bevel_smooth.rs create mode 100644 crates/core/src/conversion_mode.rs create mode 100644 crates/core/src/curve_preset.rs create mode 100644 crates/core/src/directional_distance.rs create mode 100644 crates/core/src/directional_light.rs create mode 100644 crates/core/src/gradient_input.rs create mode 100644 crates/core/src/grayscale_conversion.rs create mode 100644 crates/core/src/grayscale_mode.rs create mode 100644 crates/core/src/height_to_normal.rs create mode 100644 crates/core/src/highpass_space.rs create mode 100644 crates/core/src/image_input.rs create mode 100644 crates/core/src/lighting_output.rs create mode 100644 crates/core/src/mask_outline.rs create mode 100644 crates/core/src/mirror.rs create mode 100644 crates/core/src/mirror_corner.rs create mode 100644 crates/core/src/mirror_mode.rs create mode 100644 crates/core/src/oklab.rs create mode 100644 crates/core/src/outline_position.rs create mode 100644 crates/core/src/pbr_validate.rs create mode 100644 crates/core/src/slope_blending.rs create mode 100644 crates/core/src/source_color_mode.rs create mode 100644 crates/core/src/source_slope_blur.rs create mode 100644 crates/core/src/stylized_lighting.rs create mode 100644 crates/core/src/sun_and_sky.rs create mode 100644 crates/core/src/target_color_mode.rs create mode 100644 crates/core/src/threshold_mode.rs create mode 100644 crates/core/src/tile_transform.rs create mode 100644 crates/core/src/tile_transform/flip_mode.rs create mode 100644 crates/core/src/tile_transform/repeat_mode.rs create mode 100644 crates/core/src/validation_mode.rs create mode 100644 crates/core/src/warp_blending.rs create mode 100644 crates/core/src/warp_mode.rs create mode 100644 crates/core/src/warp_source_mode.rs create mode 100644 crates/engine/src/filter_about.rs create mode 100644 crates/engine/src/tile_transform_params.rs create mode 100644 crates/engine/tests/it/filter_card.rs create mode 100644 crates/engine/tests/it/filter_colour.rs create mode 100644 crates/engine/tests/it/filter_gradient.rs create mode 100644 crates/engine/tests/it/filter_inputs.rs create mode 100644 crates/engine/tests/it/filter_light.rs create mode 100644 crates/engine/tests/it/filter_shape.rs create mode 100644 crates/engine/tests/it/filter_simple.rs create mode 100644 crates/engine/tests/it/filter_transform.rs create mode 100644 crates/ui-egui/src/property_sheet/marker_drag.rs create mode 100644 crates/ui-egui/tests/it/filter_colour.rs create mode 100644 crates/ui-egui/tests/it/filter_light.rs create mode 100644 crates/ui-egui/tests/it/filter_shape.rs create mode 100644 crates/ui-egui/tests/it/filter_simple.rs create mode 100644 crates/ui-egui/tests/it/filter_stylize.rs create mode 100644 crates/ui-egui/tests/it/filter_transform.rs create mode 100644 crates/ui-egui/tests/it/properties_lists.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 05d1cafc..4d8f01c1 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -10,7 +10,7 @@ use std::collections::{BTreeSet, HashMap, VecDeque}; use std::sync::Arc; use texturecraft_core::project::MAX_DEPTH; -use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{BakedMap, Channel, EffectKind, Filter, Layer, LayerId, LayerKind, Project, Source, TextureSet}; use texturecraft_texel::TileImage; use crate::eval::{Inputs, PaintTarget}; @@ -98,6 +98,8 @@ pub struct StackKey { pixels: Vec<(LayerId, Option, Shared)>, baked: (u32, Vec<(BakedMap, usize)>), images: Vec<(String, ImageIdentity)>, + /// The viewport environment, its rotation (bits) and its image when it is an imported one, where Baked Lighting Environment lights with them + environment: Option<(String, u32, Option)>, } impl StackKey { @@ -152,6 +154,8 @@ impl StackKey { fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name); } for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { + // A filter's image inputs, also one its mode leaves unread: that only empties the cache more often + effect.inputs.values().flat_map(Source::images).for_each(&mut record_image_name); match &effect.kind { EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), @@ -166,6 +170,16 @@ impl StackKey { let image_identities = referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect(); + let lit = render_tree + .iter() + .filter_map(|id| project.layers.get(id)) + .flat_map(|layer| layer.content_effects.iter()) + .any(|effect| matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. }))); + let environment = lit.then(|| { + let image = project.display.environment_resource().and_then(|name| images.get(name)).map(ImageIdentity::new); + (project.display.environment.clone(), project.display.env_rotation.to_bits(), image) + }); + Some(StackKey { set, roots, @@ -173,6 +187,7 @@ impl StackKey { pixels: pixel_handles, baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()), images: image_identities, + environment, }) } } @@ -182,14 +197,18 @@ impl StackKey { /// changed (same set, roots, layers, baked maps and images; the same images by id, channel /// and size). None when anything else differs: the caller recomposites everything. pub fn changed_tiles(&self, other: &StackKey) -> Option> { - if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images { + if self.set != other.set + || self.roots != other.roots + || self.layers != other.layers + || self.baked != other.baked + || self.images != other.images + || self.environment != other.environment + { return None; } - if self.pixels.len() != other.pixels.len() { return None; } - let size = self.set.size(); let mut changed = BTreeSet::new(); for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index d0cdb0f2..ffe4a3d3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -14,15 +14,20 @@ use texturecraft_core::{ BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Sampling, ShapeCrop, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, + CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, + HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, Project, Projection, + RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, + TileTransform, blend1, blend3, lum, mix3, per_unit, posterize, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; -use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::effect_histogram::EffectHistogram; +use crate::environment_sh::EnvironmentSh; use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_place::FillPlace; @@ -32,8 +37,10 @@ use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, procedur use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; use crate::projector_depth::ProjectorDepth; +use crate::shape_distance::distance_filter; +use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; -use evaluation_inputs::EvaluationInputs; +use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; const NCH: usize = Channel::ALL.len(); @@ -46,6 +53,12 @@ const SEAM_JUMP_SHARE: f32 = 0.25; /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; +/// 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; + +/// The Height Intensity of Baked Lighting Environment that tilts the normals as Baked Lighting Stylized's Height to Normal Intensity 1 does (its default) +const ENVIRONMENT_HEIGHT_UNIT: f32 = 4.0; + /// What a live stroke paints into. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PaintTarget { @@ -260,6 +273,12 @@ struct EffectPlan<'a> { depth: Option>, /// Whether a fill or material effect covers every texel (see [`covers_every_texel`]), so no texel asks covers_all: bool, + /// The viewport environment's light, for Baked Lighting Environment + environment: Option, + /// Baked Lighting Stylized's settings worked out once for every texel it shades + stylized: Option, + /// The source a point filter's image input reads (Grayscale Conversion's Custom Input) + input: Option, } struct MaskPlan<'a> { @@ -317,36 +336,63 @@ impl FieldKey { pub type Fields = HashMap; -/// How a neighbourhood filter reads around a texel. +/// How a neighbourhood filter reads around a texel #[derive(Clone, Copy)] enum Op { - /// Box blurs (≈ Gaussian), sharpening by the amount when given. + /// Box blurs (≈ Gaussian), sharpening by the amount when given Blur(Option), - /// The value minus its box blur, around the channel's mid value. - HighPass, - /// Values ramped down towards their shape's edge, from the box blur. + /// The value minus its box blur, around the channel's mid value: colors in `space`, the coverage too when `alpha` + HighPass { space: HighpassSpace, alpha: bool }, + /// Values ramped down towards their shape's edge, from the box blur Bevel, - /// The value plus its box blur times the amount. + /// The value plus its box blur times the amount Glow(f32), - /// The value at the center of its cell (`r` texels across). - Mosaic, - /// Average along a direction (unit vector in texels). + /// The value at the center of its cell (`r` texels across); the texel's own coverage kept unless `alpha` + Mosaic { alpha: bool }, + /// Stair-stepped edges blended across (FXAA); the texel's own coverage kept unless `alpha` + Fxaa { alpha: bool }, + /// The mean of the calmest sector of an ellipse along the local direction (see [`kuwahara_texel`]) + Kuwahara(AnisotropicKuwahara), + /// Average along a direction (unit vector in texels) Line([f32; 2]), - /// Read at an offset given by a noise vector field, or by noise along a direction. + /// Read at an offset given by a noise vector field, or by noise along a direction Warp { scale: f32, seed: u32, dir: Option<[f32; 2]> }, - /// Gradient magnitude from central differences. + /// Gradient magnitude from central differences Edge, - /// Average downhill along a noise height field. + /// Average downhill along a noise height field Slope { scale: f32, seed: u32 }, + /// Box blurs, then the effect's own point filter on the blurred value (a gradient's Blur Intensity) + PreBlur, + /// A halo from the box blur of the shapes, laid around (or inside) them + Halo, + /// The shapes moved by `offset` (whole texels), box blurred and laid under them + Shadow { offset: [i32; 2] }, + /// Each UV tile's texels read from where `mirror` sends them in their tile (`block` texels across the set's atlas blocks) + Mirror { mirror: Mirror, block: u32 }, + /// Each UV tile's texels read from where `transform` sends them (its `affine`, worked out once), repeating round the tile or empty past it + Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]), block: u32 }, + /// A band along the edge of the shapes past a threshold, from the box blur of the shapes + Outline(MaskOutline), + /// Drawn from the distance to the shapes' edge (see [`distance_filter`]) + Distance, + /// Read from where a warp's source sends each texel (see [`warp_texel`]) + SourceWarp(SourceWarp), + /// The values downhill of each texel along a source's slope, blended (see [`slope_texel`]) + SourceSlopeBlur(SourceSlopeBlur), + /// The normal of the slopes of the layer's Height (see [`height_to_normal_texel`]) + HeightToNormal(HeightToNormal), + /// Colors moved from a source color to a target color; the source the whole set's mean in Source Color Mode Average (see [`color_match`]) + ColorMatch(ColorMatch), } -/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]). +/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]) fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { neighbourhood_filters(effects, res).last() } -/// Below this a coverage weight counts as no coverage at all. -const MIN_COVERAGE_WEIGHT: f32 = 1e-6; +/// Below this squared length an unpacked baked normal is no direction (an unbaked texel) +const MIN_NORMAL_LENGTH_SQUARED: f32 = 1e-6; + /// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. const FILTER_SIZE_RESOLUTION: f32 = 2048.0; /// The smallest radius a filter runs at, in texels. @@ -359,29 +405,70 @@ const MIN_SHARPEN_RADIUS: f32 = 0.75; fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator + '_ { let texels = move |size: f32| (size * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind { - EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), + EffectKind::Filter(Filter::Blur { radius, .. }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), EffectKind::Filter(Filter::Sharpen { amount }) => { Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), Op::Blur(Some(*amount)))) } EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))), - EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { - Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) + EffectKind::Filter(Filter::Warp { intensity, scale, seed, divider }) if *intensity > 0.0 => { + Some((index, texels(divided(*intensity, *divider)), Op::Warp { scale: *scale, seed: *seed, dir: None })) } - EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => { - Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) + EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed, divider }) if *intensity > 0.0 => { + Some((index, texels(divided(*intensity, *divider)), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) } - EffectKind::Filter(Filter::HighPass { radius }) => Some((index, texels(*radius), Op::HighPass)), + EffectKind::Filter(Filter::SourceWarp(warp)) if warp.move_texels(res) > 0.0 => Some((index, warp.reach(res).max(0.5), Op::SourceWarp(*warp))), + EffectKind::Filter(Filter::SourceSlopeBlur(slope)) if slope.move_texels(res) > 0.0 => { + Some((index, slope.reach(res).max(0.5), Op::SourceSlopeBlur(*slope))) + } + EffectKind::Filter(Filter::HighPass { radius, space, alpha }) => Some((index, texels(*radius), Op::HighPass { space: *space, alpha: *alpha })), EffectKind::Filter(Filter::EdgeDetect { width }) => Some((index, texels(*width), Op::Edge)), // Three box passes ramp an edge over about twice their radius - EffectKind::Filter(Filter::Bevel { width }) => Some((index, texels(*width * 0.5), Op::Bevel)), + EffectKind::Filter(Filter::Bevel { width, .. }) => Some((index, texels(*width * 0.5), Op::Bevel)), EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), - EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)), - // Use reference-resolution reach so all callers classify the same filters as stages + EffectKind::Filter(Filter::Mosaic { size, alpha }) => Some((index, texels(*size), Op::Mosaic { alpha: *alpha })), + EffectKind::Filter(Filter::Fxaa { alpha }) => Some((index, FXAA_SEARCH as f32 + 1.0, Op::Fxaa { alpha: *alpha })), + // The ellipse reaches up to twice the radius along a clear direction, and the direction is read around its reach + EffectKind::Filter(Filter::AnisotropicKuwahara(kuwahara)) if kuwahara.radius > 0.0 => { + Some((index, texels(kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS)) * (2.0 + kuwahara.tensor_reach()) + 1.0, Op::Kuwahara(*kuwahara))) + } + + // The slopes come from the heights right around a texel + EffectKind::Filter(Filter::HeightToNormal(filter)) => Some((index, 1.0, Op::HeightToNormal(*filter))), + // Average reads the mean color of the whole set; the other modes read the texel alone + EffectKind::Filter(Filter::ColorMatch(matcher)) => { + Some((index, if matcher.source_mode == SourceColorMode::Average { WHOLE_SET } else { 1.0 }, Op::ColorMatch(*matcher))) + } + // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) } - EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { - Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) + // A mirror reads anywhere in its UV tile + EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror, block: res })), + // A transform reads anywhere in its UV tile; one that changes nothing is skipped + EffectKind::Filter(Filter::Transform(transform)) if !transform.is_identity() => { + Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine(), block: res })) + } + + // Three box passes reach the band's width + EffectKind::Filter(Filter::MaskOutline(outline)) => { + Some((index, (outline.width * res as f32 / BLUR_BOX_PASSES as f32).max(MIN_FILTER_RADIUS), Op::Outline(*outline))) + } + + // Three box passes' reach covers the distance and its smoothing + EffectKind::Filter(filter @ (Filter::DistanceBevel(_) | Filter::BevelSmooth(_) | Filter::DirectionalDistance(_))) => { + Some((index, distance_reach(filter, res) / BLUR_BOX_PASSES as f32 + 1.0, Op::Distance)) + } + EffectKind::Filter(Filter::HaloGlow { width, .. }) => Some((index, texels(width.abs() * Filter::HALO_REACH), Op::Halo)), + EffectKind::Filter(Filter::DropShadow { angle, distance, size, .. }) => { + // Cast away from the light: `distance` of a UV tile, against the light's direction + let [dx, dy] = direction(*angle); + let reach = distance.clamp(-Filter::SHADOW_DISTANCE_MAX, Filter::SHADOW_DISTANCE_MAX) * res as f32; + let offset = [(-dx * reach).round() as i32, (-dy * reach).round() as i32]; + Some((index, texels(size * Filter::HALO_REACH), Op::Shadow { offset })) + } + EffectKind::Filter(Filter::GradientMap { input, debug: false, .. }) if input.blur > 0.0 => Some((index, texels(input.blur), Op::PreBlur)), + EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed, divider }) if *radius > 0.0 => { + Some((index, texels(divided(*radius, *divider)), Op::Slope { scale: *scale, seed: *seed })) } _ => None, }) @@ -403,9 +490,27 @@ pub fn stack_reads_neighbours(project: &Project, texture_set_index: usize) -> bo }) } +/// A neighbourhood radius that reaches the whole set ([`filter_extent`] caps it at the set's longest side) +const WHOLE_SET: f32 = 65_536.0; + +/// How many texels around a texel distance filter `filter` reads at `res` texels across a UV tile: its reach and its smoothing's three box passes +fn distance_reach(filter: &Filter, res: u32) -> f32 { + match filter { + Filter::DistanceBevel(bevel) => bevel.reach(res) + BLUR_BOX_PASSES as f32 * bevel.smoothing_texels(res), + Filter::BevelSmooth(smooth) => smooth.reach(res) + BLUR_BOX_PASSES as f32 * smooth.smoothing_texels(res), + Filter::DirectionalDistance(trail) => trail.reach(res), + _ => 0.0, + } +} + +/// `size` over its intensity divider (a divider of 0 from a hostile file counts as 1) +fn divided(size: f32, divider: u16) -> f32 { + size / f32::from(divider.max(1)) +} + /// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn /// counterclockwise on screen. -fn direction(angle: f32) -> [f32; 2] { +pub(crate) fn direction(angle: f32) -> [f32; 2] { let (sn, cs) = angle.to_radians().sin_cos(); [cs, -sn] } @@ -417,36 +522,79 @@ const MAP_GAIN: f32 = 2.0; const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2; /// Samples along a directional or slope blur at most (beyond, samples spread out). -const LINE_SAMPLES: i32 = 24; +pub(crate) const LINE_SAMPLES: i32 = 24; /// Fractal noise over texel position `(x, y)` (`res` texels per UV unit, `scale` features per /// UV unit), shifted by `d` in noise space. -fn texel_noise(x: f32, y: f32, d: [f32; 2], res: u32, scale: f32, seed: u32) -> f32 { - let k = if scale.is_finite() { scale.clamp(0.01, 1000.0) } else { 1.0 } / res.max(1) as f32; - noise::fbm([x * k + d[0], y * k + d[1], 0.0], 3, seed, noise::perlin) +pub(crate) fn texel_noise(x: f32, y: f32, d: [f32; 2], res: u32, scale: f32, seed: u32) -> f32 { + let per_texel = if scale.is_finite() { scale.clamp(Filter::NOISE_SCALE_MIN, Filter::NOISE_SCALE_MAX) } else { 1.0 } / res.max(1) as f32; + noise::fbm([x * per_texel + d[0], y * per_texel + d[1], 0.0], 3, seed, noise::perlin) } -/// The neighbourhood filters that gather samples (directional and slope blur, warp) over a -/// field region `(x0, y0, w, h)` of premultiplied `orig` texels (`comps` each) and their -/// `cover`: bilinear samples weighted by coverage, so uncovered texels don't bleed in. -/// Positions are absolute texel coordinates, so a texel's result does not depend on the region. +/// Gain on a noise warp's value around mid gray: values a third away from it already move the whole radius, as the noise seldom strays further +const WARP_NOISE_GAIN: f32 = 3.0; + +/// Mixed into a noise warp's seed for its vertical move, so it differs from the horizontal one (any odd constant does) +const WARP_Y_SALT: u32 = 0x5BD1_E995; + +/// How far apart, in noise space, a slope blur measures its noise's slope +const SLOPE_NOISE_PROBE: f32 = 0.01; + +/// The neighbourhood filters that gather samples (directional and slope blur, warp) over a field region `(x0, y0, w, h)` of premultiplied `orig` texels (`comps` each) and their `cover`: bilinear samples weighted by coverage, so uncovered texels don't bleed in; positions are absolute texel coordinates, so a texel's result does not depend on the region #[allow(clippy::too_many_arguments)] -fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u32, u32, u32, u32), r: f32, res: u32, opacity: f32) -> Vec { +fn gather( + op: Op, + (orig, cover, grays): (&[f32], &[f32], &[f32]), + comps: usize, + (x0, y0, w, h): (u32, u32, u32, u32), + r: f32, + res: u32, + opacity: f32, +) -> Vec { let mut data = orig.to_vec(); - let (wu, hu) = (w as usize, h as usize); - // Bilinear sample at absolute texel position (fx, fy) into `acc` (components, then weight). + let (width, height) = (w as usize, h as usize); + + // The filter's image input at absolute texel position (fx, fy), bilinear over the covered texels; None off them + let input = |fx: f32, fy: f32| -> Option { + if !(fx.is_finite() && fy.is_finite()) { + return None; + } + + let (bx, by) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - bx, fy - by); + let (mut sum, mut weight) = (0.0f32, 0.0f32); + for (dx, dy, k) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] { + let (cx, cy) = (bx as i64 + dx - i64::from(x0), by as i64 + dy - i64::from(y0)); + if k <= 0.0 || cx < 0 || cy < 0 || cx >= width as i64 || cy >= height as i64 { + continue; + } + + let i = cy as usize * width + cx as usize; + if let (Some(covered), Some(gray)) = (cover.get(i), grays.get(i)) + && *covered > 0.0 + { + sum += gray * k; + weight += k; + } + } + (weight > MIN_READ_WEIGHT).then(|| sum / weight) + }; + + // Bilinear sample at absolute texel position (fx, fy) into `acc` (components, then weight) let sample = |fx: f32, fy: f32, acc: &mut [f32; 5]| { if !(fx.is_finite() && fy.is_finite()) { return; } + let (bx, by) = (fx.floor(), fy.floor()); let (tx, ty) = (fx - bx, fy - by); for (dx, dy, k) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] { let (cx, cy) = (bx as i64 + dx - i64::from(x0), by as i64 + dy - i64::from(y0)); - if k <= 0.0 || cx < 0 || cy < 0 || cx >= wu as i64 || cy >= hu as i64 { + if k <= 0.0 || cx < 0 || cy < 0 || cx >= width as i64 || cy >= height as i64 { continue; } - let i = cy as usize * wu + cx as usize; + + let i = cy as usize * width + cx as usize; let (Some(c), Some(px)) = (cover.get(i), orig.get(i * comps..(i + 1) * comps)) else { continue }; for (a, v) in acc.iter_mut().zip(px) { *a += v * k; @@ -454,11 +602,12 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 acc[4] += c * k; } }; - data.par_chunks_mut((comps * wu).max(1)).enumerate().for_each(|(row, line)| { - for col in 0..wu { - if cover.get(row * wu + col).is_none_or(|c| *c <= 0.0) { + data.par_chunks_mut((comps * width).max(1)).enumerate().for_each(|(row, line)| { + for col in 0..width { + if cover.get(row * width + col).is_none_or(|c| *c <= 0.0) { continue; } + let (x, y) = ((x0 as usize + col) as f32, (y0 as usize + row) as f32); let mut acc = [0.0f32; 5]; let n = (r.ceil() as i32).clamp(1, LINE_SAMPLES); @@ -471,53 +620,92 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 } } Op::Warp { scale, seed, dir } => { - let off = |salt: u32| ((texel_noise(x, y, [0.0; 2], res, scale, seed ^ salt) - 0.5) * 3.0).clamp(-1.0, 1.0) * r; + let noise_offset = |salt: u32| ((texel_noise(x, y, [0.0; 2], res, scale, seed ^ salt) - 0.5) * WARP_NOISE_GAIN).clamp(-1.0, 1.0) * r; match dir { Some(d) => { - let t = off(0); + let t = noise_offset(0); sample(x + d[0] * t, y + d[1] * t, &mut acc); } - None => sample(x + off(0), y + off(0x5BD1_E995), &mut acc), + None => sample(x + noise_offset(0), y + noise_offset(WARP_Y_SALT), &mut acc), } } Op::Edge => { - let center = orig.get((row * wu + col) * comps..(row * wu + col + 1) * comps).unwrap_or(&[]); + let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); let at = |dx: f32, dy: f32| { - let mut a = [0.0f32; 5]; - sample(x + dx, y + dy, &mut a); - a + let mut read = [0.0f32; 5]; + sample(x + dx, y + dy, &mut read); + read }; - let (l, rt, u, d) = (at(-r, 0.0), at(r, 0.0), at(0.0, -r), at(0.0, r)); - // A side outside the UV island reads the texel itself: seams are not edges. - let val = |a: &[f32; 5], k: usize| if a[4] > 1e-6 { a[k] / a[4] } else { center.get(k).copied().unwrap_or(0.0) }; - let mag = |k: usize| (val(&rt, k) - val(&l, k)).hypot(val(&d, k) - val(&u, k)).min(1.0); - // Content stays premultiplied by its own coverage; masks are one value. - let cov = if comps == 4 { center.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - for (k, a) in acc.iter_mut().enumerate().take(comps.min(3)) { - *a = mag(k) * cov; + let (left, right, up, down) = (at(-r, 0.0), at(r, 0.0), at(0.0, -r), at(0.0, r)); + + // A side outside the UV island reads the texel itself: seams are not edges + let component = |read: &[f32; 5], k: usize| { + if read[4] > MIN_READ_WEIGHT { read[k] / read[4] } else { center.get(k).copied().unwrap_or(0.0) } + }; + let magnitude = |k: usize| (component(&right, k) - component(&left, k)).hypot(component(&down, k) - component(&up, k)).min(1.0); + + // Content stays premultiplied by its own coverage; masks are one value + let coverage = if comps == 4 { center.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + for (k, slot) in acc.iter_mut().enumerate().take(comps.min(3)) { + *slot = magnitude(k) * coverage; } if comps == 4 { - acc[3] = cov; + acc[3] = coverage; } acc[4] = 1.0; } Op::Slope { scale, seed } => { - let e = 0.01; - let hgt = |dx: f32, dy: f32| texel_noise(x, y, [dx, dy], res, scale, seed); - // Downhill; a flat spot keeps its value. - let d = Vec2::new(hgt(-e, 0.0) - hgt(e, 0.0), hgt(0.0, -e) - hgt(0.0, e)).try_normalize().unwrap_or(Vec2::ZERO); + let noise_height = |dx: f32, dy: f32| texel_noise(x, y, [dx, dy], res, scale, seed); + let probe = SLOPE_NOISE_PROBE; + + // Downhill; a flat spot keeps its value + let downhill = Vec2::new(noise_height(-probe, 0.0) - noise_height(probe, 0.0), noise_height(0.0, -probe) - noise_height(0.0, probe)); + let d = downhill.try_normalize().unwrap_or(Vec2::ZERO); for s in 0..=n { let t = s as f32 * step; sample(x + d.x * t, y + d.y * t, &mut acc); } } - Op::Mosaic => { + Op::Mosaic { alpha } => { let center = |v: f32| ((v / r).floor() + 0.5) * r - 0.5; sample(center(x), center(y), &mut acc); + if !alpha { + keep_coverage(&mut acc, comps, orig.get((row * width + col) * comps + 3)); + } } - Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_) => {} + Op::Fxaa { alpha } => { + let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); + fxaa_texel((x, y), comps, center, &mut acc, &sample); + if !alpha { + keep_coverage(&mut acc, comps, center.get(3)); + } + } + Op::Mirror { mirror, block } => { + mirror_texel(&mirror, (x, y), (block, res), comps, orig.get((row * width + col) * comps + comps - 1), &mut acc, &sample) + } + Op::Transform { transform, affine, block } => transform_texel(&transform, affine, (x, y), (block, res), &mut acc, &sample), + Op::SourceWarp(warp) => warp_texel(&warp, (x, y), (res, comps), &mut acc, (&sample, &input)), + Op::SourceSlopeBlur(slope) => slope_texel(&slope, (x, y), (res, comps), &mut acc, (&sample, &input)), + Op::HeightToNormal(filter) => { + let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); + height_to_normal_texel(&filter, (x, y), (res, center), &mut acc, &input); + } + Op::Kuwahara(kuwahara) => { + let radius = (kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS) * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); + kuwahara_texel(&kuwahara, (x, y), (radius, comps), &mut acc, (&sample, &input)); + } + Op::ColorMatch(_) + | Op::Blur(_) + | Op::HighPass { .. } + | Op::Bevel + | Op::Glow(_) + | Op::PreBlur + | Op::Halo + | Op::Shadow { .. } + | Op::Outline(_) + | Op::Distance => {} } - if acc[4] > 1e-6 + if acc[4] > MIN_READ_WEIGHT && let Some(px) = line.get_mut(col * comps..(col + 1) * comps) { for (slot, a) in px.iter_mut().zip(acc) { @@ -529,6 +717,411 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 data } +/// The linear colors `source` gives over texel region `(x0, y0, w, h)` (its tiles `tiles`), row by row +fn input_colors(inp: &Inputs, source: &Source, tiles: &[(u32, u32)], (x0, y0, w, h): (u32, u32, u32, u32)) -> Vec<[f32; 3]> { + let parts: Vec> = tiles + .par_iter() + .map(|&(tx, ty)| { + let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); + tile_texels(inp.gbuf, tx, ty) + .map(|(x, y, offset)| { + let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); + (x, y, texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color)) + }) + .collect() + }) + .collect(); + let mut colors = vec![[0.0f32; 3]; (w * h) as usize]; + for &(x, y, color) in parts.iter().flatten() { + if let (Some(dx), Some(dy)) = (x.checked_sub(x0), y.checked_sub(y0)) + && let Some(slot) = colors.get_mut((dy * w + dx) as usize) + { + *slot = color; + } + } + colors +} + +/// Color Match's per-texel source or target colors (None: one color for the whole region) +type MatchColors = Option>; + +/// Color Match over premultiplied `data` (`comps` values a texel): each covered color moved from its source (the region's mean or its Input color) to its target (Target Color or its Image Input color), mixed in by `opacity` +fn color_match(data: &mut [f32], comps: usize, matcher: &ColorMatch, (sources, targets): (&MatchColors, &MatchColors), opacity: f32) { + if comps != 4 || opacity <= 0.0 { + return; + } + + // The mean of the covered colors (premultiplied, so a texel counts by its coverage) + let (sum, covered) = data + .par_chunks(4) + .fold( + || ([0.0f64; 3], 0.0f64), + |(mut sum, mut covered), px| { + if let [r, g, b, a] = *px + && a > 0.0 + && a.is_finite() + { + for (slot, v) in sum.iter_mut().zip([r, g, b]) { + *slot += f64::from(v); + } + covered += f64::from(a); + } + (sum, covered) + }, + ) + .reduce(|| ([0.0; 3], 0.0), |(a, ca), (b, cb)| ([a[0] + b[0], a[1] + b[1], a[2] + b[2]], ca + cb)); + let mean = if covered > 0.0 { sum.map(|v| (v / covered) as f32) } else { matcher.target_color }; + data.par_chunks_mut(4).enumerate().for_each(|(i, px)| { + let [r, g, b, a] = *px else { return }; + if a <= 0.0 || !a.is_finite() { + return; + } + + let source = match matcher.source_mode { + SourceColorMode::Average => mean, + SourceColorMode::Parameter => matcher.source_color, + SourceColorMode::Input => sources.as_ref().and_then(|colors| colors.get(i)).copied().unwrap_or(matcher.source_color), + }; + let target = match matcher.target_mode { + TargetColorMode::Parameter => matcher.target_color, + TargetColorMode::ImageInput => targets.as_ref().and_then(|colors| colors.get(i)).copied().unwrap_or(matcher.target_color), + }; + let moved = matcher.apply([r, g, b].map(|v| v / a), source, target); + for (slot, v) in px.iter_mut().zip(moved) { + *slot += (v * a - *slot) * opacity; + } + }); +} + +/// Height To Normal at texel `(x, y)` into `acc`: the 3×3 Sobel normal of the heights `height` reads, laid over normal `center` unless it overwrites it +fn height_to_normal_texel( + filter: &HeightToNormal, + (x, y): (f32, f32), + (res, center): (u32, &[f32]), + acc: &mut [f32; 5], + height: &dyn Fn(f32, f32) -> Option, +) { + let (Some(own), [red, green, blue, cov]) = (height(x, y), center) else { return }; + if *cov <= 0.0 { + return; + } + + let at = |dx: f32, dy: f32| height(x + dx, y + dy).unwrap_or(own); + + // Sobel gradients over the kernel's weight sum + let gx = (at(1.0, -1.0) + 2.0 * at(1.0, 0.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(-1.0, 0.0) - at(-1.0, 1.0)) / 8.0; + let gy = (at(-1.0, 1.0) + 2.0 * at(0.0, 1.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(0.0, -1.0) - at(1.0, -1.0)) / 8.0; + let made = filter.normal([gx, gy], res).map(|v| v * 0.5 + 0.5); + let packed = if filter.overwrite { made } else { texturecraft_core::blend::rnm([red, green, blue].map(|v| v / cov), made) }; + for (slot, value) in acc.iter_mut().zip(packed) { + *slot = value * cov; + } + acc[3] = *cov; + acc[4] = 1.0; +} + +/// Gathered sample `acc` (premultiplied, then weight) recoloured over the texel's own coverage `own` (content only; a sample with no coverage leaves it) +fn keep_coverage(acc: &mut [f32; 5], comps: usize, own: Option<&f32>) { + let Some(&own) = own.filter(|_| comps == 4) else { return }; + if acc[3] <= MIN_READ_WEIGHT { + acc[4] = 0.0; + return; + } + + let scale = own * acc[4] / acc[3]; + for component in acc.iter_mut().take(3) { + *component *= scale; + } + acc[3] = own * acc[4]; +} + +/// Sample rows (and columns) on each side of the middle Anisotropic Kuwahara reads its ellipse with at most +const KUWAHARA_STEPS: i32 = 6; + +/// Below this, a structure tensor has no direction +const MIN_TENSOR: f32 = 1e-12; + +/// How fast a Kuwahara sample's gaussian weight falls with its squared distance across the ellipse (e^-2 at the rim) +const KUWAHARA_FALLOFF: f32 = 2.0; + +/// A spread of one in a sector, in 8-bit steps: what Anisotropic Kuwahara's sector weights are measured in +const KUWAHARA_SPREAD_SCALE: f32 = 255.0; + +/// Anisotropic Kuwahara at texel `(x, y)` (`radius` texels, `comps` components) into `acc`: an ellipse along the gray's direction, its sectors' means weighed by their calm +fn kuwahara_texel( + kuwahara: &AnisotropicKuwahara, + (x, y): (f32, f32), + (radius, comps): (f32, usize), + acc: &mut [f32; 5], + (sample, input): (Sample<'_>, Input<'_>), +) { + // A straight value at an offset; None off the UV island + let read = |fx: f32, fy: f32| -> Option<[f32; 4]> { + let mut sum = [0.0f32; 5]; + sample(fx, fy, &mut sum); + (sum[4] > MIN_READ_WEIGHT).then(|| std::array::from_fn(|k| if k < comps.min(4) { sum[k] / sum[4] } else { 0.0 })) + }; + let gray = |fx: f32, fy: f32| if kuwahara.custom_input { input(fx, fy) } else { read(fx, fy).map(|px| fxaa_luma(&px[..comps.min(4)])) }; + + // Structure tensor: the gray's gradients over a 3×3 grid spread by Tensor Smoothness, the middle weighing most + let spread = kuwahara.tensor_reach() * radius; + let (mut xx, mut xy, mut yy) = (0.0f32, 0.0f32, 0.0f32); + for gy in -1i32..=1 { + for gx in -1i32..=1 { + let (px, py) = (x + gx as f32 * spread, y + gy as f32 * spread); + let own = gray(px, py); + let at = |dx: f32, dy: f32| gray(px + dx, py + dy).or(own); + let (Some(left), Some(right), Some(up), Some(down)) = (at(-1.0, 0.0), at(1.0, 0.0), at(0.0, -1.0), at(0.0, 1.0)) else { continue }; + // Central differences over two texels + let (dx, dy) = ((right - left) * 0.5, (down - up) * 0.5); + + // A 1-2-1 binomial kernel in each direction: the middle 4, the sides 2, the corners 1 + let weight = (4 >> (gx.abs() + gy.abs())) as f32; + xx += weight * dx * dx; + xy += weight * dx * dy; + yy += weight * dy * dy; + } + } + let root = ((xx - yy).powi(2) + 4.0 * xy * xy).sqrt(); + let clear = if xx + yy > MIN_TENSOR { root / (xx + yy) } else { 0.0 }; + + // Strokes run across the steepest change; Anisotropy Angle turns the ellipse counterclockwise on screen + let along = 0.5 * (2.0 * xy).atan2(xx - yy) + std::f32::consts::FRAC_PI_2 - kuwahara.angle.to_radians(); + let (sin, cos) = if along.is_finite() { along.sin_cos() } else { (0.0, 1.0) }; + let (major, minor) = kuwahara.axes(radius, if clear.is_finite() { clear } else { 0.0 }); + + // Each sector's weighted sum, squared sum and weight + let mut sums = [[0.0f32; 5]; AnisotropicKuwahara::SECTORS]; + let mut squares = [0.0f32; AnisotropicKuwahara::SECTORS]; + let steps = (major.ceil() as i32).clamp(1, KUWAHARA_STEPS); + let exponent = kuwahara.sector_exponent(); + let colors = comps.min(3); + for j in -steps..=steps { + for i in -steps..=steps { + let (u, v) = (i as f32 / steps as f32, j as f32 / steps as f32); + let distance = u * u + v * v; + if distance > 1.0 { + continue; + } + + let (ox, oy) = (u * major, v * minor); + let Some(px) = read(x + ox * cos - oy * sin, y + ox * sin + oy * cos) else { continue }; + let falloff = (-KUWAHARA_FALLOFF * distance).exp(); + let heading = v.atan2(u); + for (k, (sum, square)) in sums.iter_mut().zip(&mut squares).enumerate() { + // The middle texel belongs to every sector; the others to the sectors they face, fading towards their sides + let facing = (heading - k as f32 * std::f32::consts::TAU / AnisotropicKuwahara::SECTORS as f32).cos(); + let weight = if distance <= 0.0 { + falloff + } else if facing > 0.0 { + falloff * facing.powf(exponent) + } else { + continue; + }; + for (slot, value) in sum.iter_mut().zip(&px) { + *slot += weight * value; + } + sum[4] += weight; + *square += weight * px.iter().take(colors).map(|value| value * value).sum::(); + } + } + } + + // Calmer sectors weigh more, sharper the higher the Sharpness (in logs, so the powers can't overflow) + let sharpness = kuwahara.sharpness_exponent(); + let logs: [Option; AnisotropicKuwahara::SECTORS] = std::array::from_fn(|sector| { + let (sum, square) = (sums.get(sector)?, squares.get(sector)?); + (sum[4] > MIN_READ_WEIGHT).then(|| { + let mean = sum.iter().take(colors).map(|value| (value / sum[4]).powi(2)).sum::(); + let spread = (square / sum[4] - mean).max(0.0).sqrt(); + -sharpness * (1.0 + KUWAHARA_SPREAD_SCALE * spread).ln() + }) + }); + let Some(top) = logs.iter().flatten().copied().reduce(f32::max) else { return }; + let mut total = [0.0f32; 5]; + for (sum, log) in sums.iter().zip(&logs) { + let Some(log) = log else { continue }; + let weight = (log - top).exp(); + for (slot, value) in total.iter_mut().zip(sum.iter().take(4)) { + *slot += weight * value / sum[4]; + } + total[4] += weight; + } + *acc = total; +} + +/// Texels an FXAA edge search walks each way along an edge at most +const FXAA_SEARCH: i32 = 8; + +/// The least luma contrast around a texel FXAA smooths +const FXAA_EDGE_MIN: f32 = 0.0312; + +/// The least luma contrast around a texel FXAA smooths, as a share of its brightest neighbour +const FXAA_EDGE_RELATIVE: f32 = 0.125; + +/// How much a lone texel (subpixel aliasing) is blended into its neighbours at most +const FXAA_SUBPIXEL: f32 = 0.75; + +/// Luma of premultiplied texel components (a mask's value) +fn fxaa_luma(px: &[f32]) -> f32 { + match px { + [value] => *value, + [r, g, b, ..] => lum([*r, *g, *b]), + _ => 0.0, + } +} + +/// FXAA (the public luma-edge method) at texel `(x, y)` with components `center` into `acc`: read across its edge by how near the edge's end is +fn fxaa_texel((x, y): (f32, f32), comps: usize, center: &[f32], acc: &mut [f32; 5], sample: &dyn Fn(f32, f32, &mut [f32; 5])) { + let own = fxaa_luma(center); + + // Luma at an offset from the texel; off the UV island the texel's own, so seams are not edges + let luma = |dx: f32, dy: f32| { + let mut read = [0.0f32; 5]; + sample(x + dx, y + dy, &mut read); + if read[4] <= MIN_READ_WEIGHT { + return own; + } + + let mut px = [0.0f32; 4]; + for (slot, v) in px.iter_mut().zip(&read).take(comps.min(4)) { + *slot = v / read[4]; + } + fxaa_luma(&px[..comps.min(4)]) + }; + let (n, s, w, e) = (luma(0.0, -1.0), luma(0.0, 1.0), luma(-1.0, 0.0), luma(1.0, 0.0)); + let (hi, lo) = (own.max(n).max(s).max(w).max(e), own.min(n).min(s).min(w).min(e)); + let range = hi - lo; + if !range.is_finite() || range < FXAA_EDGE_MIN.max(hi * FXAA_EDGE_RELATIVE) { + return; + } + + let (nw, ne, sw, se) = (luma(-1.0, -1.0), luma(1.0, -1.0), luma(-1.0, 1.0), luma(1.0, 1.0)); + + // An edge running across (values changing down the rows) or down (values changing along them) + let across = 2.0 * (n - 2.0 * own + s).abs() + (nw - 2.0 * w + sw).abs() + (ne - 2.0 * e + se).abs(); + let down = 2.0 * (w - 2.0 * own + e).abs() + (nw - 2.0 * n + ne).abs() + (sw - 2.0 * s + se).abs(); + let horizontal = across >= down; + let (before, after) = if horizontal { (n, s) } else { (w, e) }; + let (sign, side) = if (before - own).abs() >= (after - own).abs() { (-1.0, before) } else { (1.0, after) }; + let (perp, along) = if horizontal { ([0.0, sign], [1.0, 0.0]) } else { ([sign, 0.0], [0.0, 1.0]) }; + + // Walk the edge's midline both ways until its luma leaves the edge's + let edge = 0.5 * (own + side); + let enough = 0.25 * (side - own).abs(); + let walk = |way: f32| { + let mut end = (FXAA_SEARCH as f32, 0.0); + for step in 1..=FXAA_SEARCH { + let t = step as f32 * way; + let delta = luma(perp[0] * 0.5 + along[0] * t, perp[1] * 0.5 + along[1] * t) - edge; + end = (step as f32, delta); + if delta.abs() >= enough { + break; + } + } + end + }; + let ((back, back_delta), (ahead, ahead_delta)) = (walk(-1.0), walk(1.0)); + let (nearest, delta) = if back < ahead { (back, back_delta) } else { (ahead, ahead_delta) }; + let edge_blend = if (delta < 0.0) != (own < edge) { 0.5 - nearest / (back + ahead) } else { 0.0 }; + + // A texel unlike all its neighbours blends in by its own contrast (sides weigh twice the corners) + let average = (2.0 * (n + s + w + e) + nw + ne + sw + se) / 12.0; + let contrast = ((average - own).abs() / range).clamp(0.0, 1.0); + let eased = crate::organic::smoothstep(0.0, 1.0, contrast); + let blend = edge_blend.max(eased * eased * FXAA_SUBPIXEL); + if blend > 0.0 { + sample(x + perp[0] * blend, y + perp[1] * blend, acc); + } +} + +/// Mirror `mirror` at texel `(x, y)` into `acc`: the texel it reads in its UV tile (`res` texels from its `block`'s top left), or white on a debug axis +fn mirror_texel( + mirror: &Mirror, + (x, y): (f32, f32), + (block, res): (u32, u32), + comps: usize, + alpha: Option<&f32>, + acc: &mut [f32; 5], + sample: &dyn Fn(f32, f32, &mut [f32; 5]), +) { + let (block, size) = (block.max(1) as f32, res.max(1) as f32); + let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); + let (local_x, local_y) = (x - origin_x, y - origin_y); + if local_x >= size || local_y >= size { + return; + } + + let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; + let line = (Mirror::DEBUG_HALF_WIDTH * size / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size; + if mirror.debug && mirror.on_axis(uv, line) { + // Content stays premultiplied by its own coverage; masks are one value + let cover = if comps == 4 { alpha.copied().unwrap_or(0.0) } else { 1.0 }; + for slot in acc.iter_mut().take(comps) { + *slot = cover; + } + acc[4] = 1.0; + return; + } + + let [u, v] = mirror.source(uv); + + // Whole texels, so an even mirror copies texels exactly + let at = |origin: f32, along: f32| origin + (along * size - 0.5).round().clamp(0.0, size - 1.0); + sample(at(origin_x, u), at(origin_y, v), acc); +} + +/// Transform `transform` (whose read is `affine`) at texel `(x, y)` into `acc`: bilinear between the four texels round where it reads in its UV tile (`res` texels from its `block`'s top left), each wrapped round the tile; where it does not repeat, a read past the tile counts as empty +fn transform_texel( + transform: &TileTransform, + (columns, shift): ([[f32; 2]; 2], [f32; 2]), + (x, y): (f32, f32), + (block, res): (u32, u32), + acc: &mut [f32; 5], + sample: &dyn Fn(f32, f32, &mut [f32; 5]), +) { + let (block, size) = (block.max(1) as f32, res.max(1) as f32); + let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); + let (local_x, local_y) = (x - origin_x, y - origin_y); + if local_x >= size || local_y >= size { + return; + } + + let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; + + // Texel space of the tile, centres at whole numbers + let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size - 0.5); + if !at.iter().all(|a| a.is_finite()) { + return; + } + + let (base_x, base_y) = (at[0].floor(), at[1].floor()); + let (tx, ty) = (at[0] - base_x, at[1] - base_y); + let repeat = transform.repeat == RepeatMode::HorizontallyAndVertically; + let mut total = [0.0f32; 5]; + for (dx, dy, k) in [(0.0, 0.0, (1.0 - tx) * (1.0 - ty)), (1.0, 0.0, tx * (1.0 - ty)), (0.0, 1.0, (1.0 - tx) * ty), (1.0, 1.0, tx * ty)] { + if k <= 0.0 { + continue; + } + + let (cx, cy) = (base_x + dx, base_y + dy); + let inside = (0.0..size).contains(&cx) && (0.0..size).contains(&cy); + if !repeat && !inside { + // Empty: no value, full weight + total[4] += k; + continue; + } + + // One whole texel: the sample's own weights, so this matches its bilinear read + let mut one = [0.0f32; 5]; + sample(origin_x + cx.rem_euclid(size), origin_y + cy.rem_euclid(size), &mut one); + for (slot, value) in total.iter_mut().zip(one) { + *slot += value * k; + } + } + *acc = total; +} + /// Fixed-point scale of the blur. Integer running sums make a texel's result independent of /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; @@ -635,6 +1228,17 @@ fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel] plan(inp, &set.stack, &planned, tx, ty, 0, fields) } +/// [`anchor_plan`], or the plain set stack when `lit` (a layer lit by its material reads the stack below it too) +fn below_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], (tx, ty): (u32, u32), fields: Option<&'a Fields>, lit: bool) -> Vec> { + let anchors = anchor_plan(inp, id, channels, tx, ty, fields); + if !anchors.is_empty() || !lit { + return anchors; + } + + let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() }; + plan(inp, &set.stack, channels, tx, ty, 0, fields) +} + /// `channels` with every channel the Compare effects among `effects` compare added once fn compared_channels<'e>(effects: impl IntoIterator, mut channels: Vec) -> Vec { for effect in effects { @@ -700,12 +1304,20 @@ fn field( margins[index] += margins[index + 1]; } + // A wrapping filter reads across the set's edges, so it and every filter under it cover the whole set along an axis it crosses + let own_wraps: Vec = filters.iter().map(|filter| wraps(effects, filter.0)).collect(); + let mut wrapping = own_wraps.clone(); + for index in (0..wrapping.len().saturating_sub(1)).rev() { + wrapping[index] |= wrapping[index + 1]; + } + let mut previous: Option<(usize, Field)> = None; let mut anchor_stages = Vec::new(); - for (&filter, &margin) in filters.iter().zip(&margins) { - let region = region_around(inp, tiles, margin)?; + for (((&filter, &margin), &wrap), &own_wrap) in filters.iter().zip(&margins).zip(&wrapping).zip(&own_wraps) { + let region = region_around(inp, tiles, margin, wrap)?; let start = previous.as_ref().map(|(index, field)| (*index, field)); let filtered = filter_region(inp, channels, below, (id, around), job, effects, filter, region, start)?; + let filtered = filter_region(inp, channels, below, (id, around), job, effects, filter, own_wrap, region, start)?; // Preserve only stages with anchors before the next filter overwrites their value if let Some((previous_index, previous_field)) = previous.take() @@ -728,32 +1340,84 @@ fn field( }) } -/// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set. -fn region_around(inp: &Inputs, tiles: &[(u32, u32)], margin: u32) -> Option<(u32, u32, u32, u32)> { +/// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set; with `wrap`, an axis the margin crosses an edge of spans the whole set (the filter reads the far side there) +fn region_around(inp: &Inputs, tiles: &[(u32, u32)], margin: u32, wrap: bool) -> Option<(u32, u32, u32, u32)> { let (first_x, first_y) = tiles.iter().fold((u32::MAX, u32::MAX), |(min_x, min_y), tile| (min_x.min(tile.0), min_y.min(tile.1))); let (last_x, last_y) = tiles.iter().fold((0, 0), |(max_x, max_y), tile| (max_x.max(tile.0), max_y.max(tile.1))); - let (x0, y0) = (first_x.saturating_sub(margin) * TILE, first_y.saturating_sub(margin) * TILE); - let (x1, y1) = (((last_x + 1 + margin) * TILE).min(inp.gbuf.width), ((last_y + 1 + margin) * TILE).min(inp.gbuf.height)); + let axis = |first: u32, last: u32, size: u32| { + let end = last.saturating_add(1).saturating_add(margin).saturating_mul(TILE); + if wrap && (first < margin || end > size) { + return (0, size); + } + + (first.saturating_sub(margin).saturating_mul(TILE), end.min(size)) + }; + let ((x0, x1), (y0, y1)) = (axis(first_x, last_x, inp.gbuf.width), axis(first_y, last_y, inp.gbuf.height)); let (w, h) = (x1.saturating_sub(x0), y1.saturating_sub(y0)); (w > 0 && h > 0).then_some((x0, y0, w, h)) } -/// A neighbourhood filter's radius in whole texels and how many texels around a texel it reads. +/// Whether the neighbourhood filter at `index` among the visible effects reads past the set's edges from the far side +fn wraps(effects: &[Effect], index: usize) -> bool { + matches!( + effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| &effect.kind), + Some(EffectKind::Filter( + Filter::Blur { wrap: true, .. } + | Filter::Bevel { wrap: true, .. } + | Filter::DistanceBevel(Bevel { wrap: true, .. }) + | Filter::BevelSmooth(BevelSmooth { wrap: true, .. }) + )) + ) +} + +/// `data` (`w` × `h` texels of `comps` values) with `pad_x` and `pad_y` texels added around it, read from the opposite side +fn wrap_pad(data: &[f32], comps: usize, (w, h): (usize, usize), (pad_x, pad_y): (usize, usize)) -> Vec { + let (padded_w, padded_h) = (w + 2 * pad_x, h + 2 * pad_y); + let mut out = vec![0.0f32; padded_w * padded_h * comps]; + out.par_chunks_mut(padded_w * comps).enumerate().for_each(|(y, row)| { + let source_y = (y + h * pad_y.div_ceil(h.max(1)) - pad_y) % h.max(1); + for (x, pixel) in row.chunks_mut(comps).enumerate() { + let source_x = (x + w * pad_x.div_ceil(w.max(1)) - pad_x) % w.max(1); + let at = (source_y * w + source_x) * comps; + if let Some(source) = data.get(at..at + comps) { + pixel.copy_from_slice(source); + } + } + }); + out +} + +/// The `w` × `h` texels inside [`wrap_pad`]'s border +fn unpad(data: &[f32], comps: usize, (w, h): (usize, usize), (pad_x, pad_y): (usize, usize)) -> Vec { + let padded_w = w + 2 * pad_x; + (pad_y..pad_y + h).flat_map(|y| data.get((y * padded_w + pad_x) * comps..(y * padded_w + pad_x + w) * comps).unwrap_or_default()).copied().collect() +} + +/// A neighbourhood filter's radius in whole texels and how many texels around a texel it reads fn filter_extent(radius: f32, op: Op, longest_side: u32) -> (u32, u32) { // Clamped so a hostile radius can't overflow the region arithmetic let radius_texels = radius.round().clamp(1.0, longest_side as f32) as u32; // Three box passes reach three radii; the gathering filters one radius plus a bilinear texel let reach = if is_box_blur(op) { 3 * radius_texels } else { radius_texels + 1 }; - (radius_texels, reach) + + // A shadow also reads the shapes it was moved from + let moved = match op { + Op::Shadow { offset: [dx, dy] } => dx.unsigned_abs().max(dy.unsigned_abs()).min(longest_side), + _ => 0, + }; + (radius_texels, reach + moved) } -/// Whether neighbourhood filter `op` is computed from box blurs (the others gather samples). +/// One evaluated texel of a filter's region: its position, its premultiplied value and the gray its image input reads there +type RegionTexel = (u32, u32, [f32; 4], f32); + +/// Whether neighbourhood filter `op` is computed from box blurs (the others gather samples) fn is_box_blur(op: Op) -> bool { - matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_)) + matches!(op, Op::Blur(_) | Op::HighPass { .. } | Op::Bevel | Op::Glow(_) | Op::PreBlur | Op::Halo | Op::Shadow { .. } | Op::Outline(_) | Op::Distance) } -/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given. +/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given; `wrap` when the filter reads past the set's edges from the far side #[allow(clippy::too_many_arguments)] fn filter_region( inputs: &EvaluationInputs, @@ -763,6 +1427,7 @@ fn filter_region( job: Job, effects: &[Effect], (index, radius, op): (usize, f32, Op), + wrap: bool, (region_x, region_y, width, height): (u32, u32, u32, u32), start: Option<(usize, &Field)>, ) -> Option { @@ -773,7 +1438,19 @@ fn filter_region( let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); let opacity = filter_effect.map(|effect| effect.blend_of(channel).opacity.clamp(0.0, 1.0)).unwrap_or(1.0); - let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); + let filter = filter_effect.and_then(|effect| match &effect.kind { + EffectKind::Filter(filter) => Some(filter), + _ => None, + }); + let opacity = filter_effect.map(|effect| effect.applied_blend(channel).opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + + // Height To Normal makes the Normal only (and reads the layer's Height as its gray); other channels pass + let heights = matches!(op, Op::HeightToNormal(_)) && channel == Some(Channel::Normal); + let opacity = if matches!(op, Op::HeightToNormal(_)) && !heights { 0.0 } else { opacity }; + + // Color Match moves colors only; other channels pass + let opacity = if matches!(op, Op::ColorMatch(_)) && channel.map(Channel::kind) != Some(ChannelKind::Color) { 0.0 } else { opacity }; + let (radius_texels, reach) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); // Generator stages keep their ramp beside the mask stack below let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) { @@ -786,15 +1463,24 @@ fn filter_region( Job::Content(_) => 4, }; - // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) + // The gray the filter's image input reads (its first; the filters that read one have one) + let input = filter_effect.zip(filter).and_then(|(effect, filter)| ImageInput::of(filter).first().map(|input| effect.input(input))); + + let lit_prefix = + channel == Some(Channel::BaseColor) && effects.iter().filter(|effect| effect.visible).take(index).any(|effect| lights_material(&effect.kind)); + + // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage), and its image input let (region_right, region_bottom) = (region_x + width, region_y + height); let region_tiles: Vec<(u32, u32)> = (region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.div_ceil(TILE)).map(move |x| (x, y))).collect(); - let parts: Vec> = region_tiles + let parts: Vec> = region_tiles .par_iter() .map(|&(tile_x, tile_y)| { - let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below)); + // A base colour lit by its material below the filter lights it as the full render does + let lit_layer = if lit_prefix { plan(inputs, &[id], channels, tile_x, tile_y, 0, Some(below)).into_iter().find(|node| node.lights) } else { None }; + let anchor_nodes = below_plan(inputs, id, channels, (tile_x, tile_y), Some(below), lit_layer.is_some()); let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); + let height_nodes = if heights { plan(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below)) } else { Vec::new() }; let mut mask = None; let mut nodes = Vec::new(); let mut generator_sizes = None; @@ -824,6 +1510,9 @@ fn filter_region( if !anchor_nodes.is_empty() { texel.anchors_below(&anchor_nodes, id); } + if let Some(layer) = &lit_layer { + texel.light(layer); + } let value = match (&mask, nodes.first()) { (Some(mask_stack), _) => { @@ -836,7 +1525,22 @@ fn filter_region( }, (None, None) => [0.0; 4], }; - (x, y, value) + let gray = match height_nodes.first() { + // Heights are signed and premultiplied by their coverage, so an edge slopes down to 0 + Some(node) => { + let mut height = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchor_nodes.is_empty() { + height.anchors_below(&anchor_nodes, id); + } + node.chans.first().and_then(|chan| height.content(&node.content, chan)).map_or(0.0, |(value, cov)| value[0] * cov) + } + None => { + let gray = + input.as_ref().map_or(1.0, |source| texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Scalar)[0]); + gray.clamp(0.0, 1.0) + } + }; + (x, y, value, gray) }) .collect() }) @@ -846,27 +1550,60 @@ fn filter_region( let texel_count = (width * height) as usize; let mut stack_values = vec![0.0f32; texel_count * components]; let mut cover = vec![0.0f32; texel_count]; + let mut grays = vec![0.0f32; texel_count]; let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize; let band = (TILE * width) as usize; - stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| { - for &(x, y, value) in row.iter().flatten() { - let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize; - if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) { - *covered = 1.0; - pixel.copy_from_slice(&value[..components]); + stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(grays.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each( + |(((stack_values, cover), grays), row)| { + for &(x, y, value, gray) in row.iter().flatten() { + let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize; + if let (Some(covered), Some(read), Some(pixel)) = + (cover.get_mut(texel), grays.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) + { + *covered = 1.0; + *read = gray; + pixel.copy_from_slice(&value[..components]); + } } - } - }); + }, + ); // Release tile scatter data before allocating filter buffers drop(parts); + // Color Match's Input and Image Input colors over the region, when its modes read them + let match_inputs = match (op, filter_effect) { + (Op::ColorMatch(matcher), Some(effect)) if opacity > 0.0 => { + let read = + |on: bool, input: ImageInput| on.then(|| input_colors(inputs, &effect.input(&input), ®ion_tiles, (region_x, region_y, width, height))); + [ + read(matcher.source_mode == SourceColorMode::Input, ImageInput::SOURCE_INPUT), + read(matcher.target_mode == TargetColorMode::ImageInput, ImageInput::TARGET_INPUT), + ] + } + _ => [None, None], + }; + // High pass centers on the channel's middle value (0 for signed channels like height) let middle = match job { Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0, _ => 0.5, }; + // A Highpass in sRGB filters its colors encoded (decoded again below); one with Apply To Alpha keeps the colors on the new coverage + let (space, highpass_alpha) = match (op, job) { + (Op::HighPass { space, alpha }, Job::Content(channel)) if components == 4 => { + (if channel.kind() == ChannelKind::Color { space } else { HighpassSpace::Working }, alpha) + } + _ => (HighpassSpace::Working, false), + }; + let covered = highpass_alpha.then(|| stack_values.clone()); + recode(&mut stack_values, components, |rgb| space.encode(rgb)); + + // A wrapped axis pads by the reach up to one period (past it the far side repeats), so a set pads to 3x its size at most + let pad_x = if wrap && region_x == 0 && width == inputs.gbuf.width { reach.min(width) } else { 0 }; + let pad_y = if wrap && region_y == 0 && height == inputs.gbuf.height { reach.min(height) } else { 0 }; + // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let filtered = |scale: f32| -> Vec { let tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1); @@ -875,43 +1612,92 @@ fn filter_region( return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set)); } - let scaled_radius = neighbourhood_filters(effects, tile_resolution) - .find(|filter| filter.0 == index) - .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); - if !is_box_blur(op) { - return gather(op, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity); + let scaled = neighbourhood_filters(effects, tile_resolution).find(|filter| filter.0 == index); + let scaled_radius = scaled.map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); + if let Op::ColorMatch(matcher) = op { + let mut matched = stack_values.clone(); + color_match(&mut matched, components, &matcher, (&match_inputs[0], &match_inputs[1]), opacity); + return matched; } - // Weighted so uncovered texels don't bleed in - let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize); - let mut weights = cover.clone(); + if !is_box_blur(op) { + return gather( + op, + (&stack_values, &cover, &grays), + components, + (region_x, region_y, width, height), + scaled_radius as f32, + tile_resolution, + opacity, + ); + } + + // Weighted so uncovered texels don't bleed in; a wrapping filter reads a border copied from the far side + let pad = (pad_x as usize, pad_y as usize); + let unpadded = (width as usize, height as usize); + let (stack_values, cover, grays) = if pad == (0, 0) { + (Cow::Borrowed(&stack_values), Cow::Borrowed(&cover), Cow::Borrowed(&grays)) + } else { + let padded = |values: &[f32], components: usize| Cow::Owned(wrap_pad(values, components, unpadded, pad)); + (padded(&stack_values, components), padded(&cover, 1), padded(&grays, 1)) + }; + let (columns, rows, blur_radius) = (unpadded.0 + 2 * pad.0, unpadded.1 + 2 * pad.1, scaled_radius as usize); + if let (Some((_, _, scaled_op @ (Op::Halo | Op::Shadow { .. }))), Some(filter)) = (scaled, filter) { + let kind = channel.map_or(ChannelKind::Scalar, Channel::kind); + let mut lit_values = stack_values.to_vec(); + halo(&mut lit_values, &cover, components, (columns, rows, blur_radius), (scaled_op, filter, kind), opacity); + return if pad == (0, 0) { lit_values } else { unpad(&lit_values, components, unpadded, pad) }; + } + + if let (Some((_, _, Op::Distance)), Some(filter)) = (scaled, filter) { + let mut distance_values = stack_values.to_vec(); + distance_filter(&mut distance_values, (&cover, &grays), components, (columns, rows), filter, tile_resolution, opacity); + return if pad == (0, 0) { distance_values } else { unpad(&distance_values, components, unpadded, pad) }; + } + + if let Some((_, _, Op::Outline(outline))) = scaled { + let mut outline_values = stack_values.to_vec(); + mask_outline(&mut outline_values, &cover, components, (columns, rows, blur_radius), &outline, opacity); + return if pad == (0, 0) { outline_values } else { unpad(&outline_values, components, unpadded, pad) }; + } + + // A pre-blur takes the blur whole; the effect's opacity mixes its mapped result below + let blurred_opacity = if matches!(op, Op::PreBlur) { 1.0 } else { opacity }; + let mut weights = cover.to_vec(); blur(&mut weights, columns, rows, blur_radius); - let mut filtered_values = stack_values.clone(); + let mut filtered_values = stack_values.to_vec(); for component in 0..components { let mut sums: Vec = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); blur(&mut sums, columns, rows, blur_radius); filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { // Content is premultiplied, so the middle value is too (coverage itself is kept) let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *weight > MIN_COVERAGE_WEIGHT + if *weight > MIN_READ_WEIGHT && let Some(slot) = pixel.get_mut(component) { let (original, blurred) = (*slot, sum / weight); let result = match op { Op::Blur(Some(amount)) => original + amount * (original - blurred), - Op::HighPass if component < 3 => original - blurred + middle * coverage, + Op::HighPass { .. } if component < 3 => original - blurred + middle * coverage, + Op::HighPass { alpha: true, .. } => (original - blurred + 0.5).clamp(0.0, 1.0), // Away from 0 by at most the value itself: 0 at the edge, full inside Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)), Op::Glow(amount) if component < 3 => original + amount * blurred, - Op::HighPass | Op::Bevel | Op::Glow(_) => original, + Op::HighPass { .. } | Op::Bevel | Op::Glow(_) => original, _ => blurred, }; - *slot = original + (result - original) * opacity; + *slot = original + (result - original) * blurred_opacity; } }); } - filtered_values + if matches!(op, Op::PreBlur) + && let Some(filter) = filter + { + let kind = channel.map_or(ChannelKind::Scalar, Channel::kind); + map_blurred(&mut filtered_values, &stack_values, components, filter, kind, opacity); + } + if pad == (0, 0) { filtered_values } else { unpad(&filtered_values, components, unpadded, pad) } }; // Each block keeps the result at its tile's scale (blocks are TILE aligned) @@ -940,6 +1726,11 @@ fn filter_region( }); } + // Laid on the new coverage first, so the decode divides by the alpha the colours now carry + if let Some(before) = covered { + recover(&mut result, &before, middle); + } + recode(&mut result, field_components, |rgb| space.decode(rgb)); unpremultiply(&mut result, field_components); Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } @@ -970,7 +1761,7 @@ fn generator_region( let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); blur(&mut sums, columns, rows, blur_radius); ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { - if *weight > MIN_COVERAGE_WEIGHT { + if *weight > MIN_READ_WEIGHT { *ramp = sum / weight; } }); @@ -1012,7 +1803,7 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, } } } - sums.into_iter().map(|(sum, weight)| (weight > MIN_COVERAGE_WEIGHT).then(|| sum / weight)) + sums.into_iter().map(|(sum, weight)| (weight > MIN_READ_WEIGHT).then(|| sum / weight)) }) .collect(); let average = |column: isize, row: isize| -> Option { @@ -1042,7 +1833,7 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, Some(value) => (sum + value * corner_weight, weight + corner_weight), None => (sum, weight), }); - if weight > MIN_COVERAGE_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } + if weight > MIN_READ_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } }) .collect() } @@ -1055,6 +1846,175 @@ fn finish_generator(generator: &Generator, ramp: f32) -> f32 { (value + offset).clamp(0.0, 1.0) } +/// Straight colours a colour space map must leave alone to be the identity +const IDENTITY_PROBE: [f32; 3] = [0.25, 0.5, 0.75]; + +/// Premultiplied content `data` (four components a texel) with each straight color mapped by `map` (nothing for masks or an identity space) +fn recode(data: &mut [f32], comps: usize, map: impl Fn([f32; 3]) -> [f32; 3] + Sync) { + if comps != 4 || map(IDENTITY_PROBE) == IDENTITY_PROBE { + return; + } + + data.par_chunks_mut(4).for_each(|pixel| { + if let [r, g, b, a] = pixel + && *a > MIN_READ_WEIGHT + { + let mapped = map([*r / *a, *g / *a, *b / *a]); + [*r, *g, *b] = mapped.map(|component| component * *a); + } + }); +} + +/// Premultiplied content `data` whose coverage a Highpass changed: its colors laid on the new coverage (mid gray where there was none, as `before`) +fn recover(data: &mut [f32], before: &[f32], mid: f32) { + data.par_chunks_mut(4).zip(before.par_chunks(4)).for_each(|(pixel, old)| { + let (Some(&own), Some(&new)) = (old.get(3), pixel.get(3)) else { return }; + let scale = if own > MIN_READ_WEIGHT { new / own } else { 0.0 }; + for component in pixel.iter_mut().take(3) { + *component = if own > MIN_READ_WEIGHT { *component * scale } else { mid * new }; + } + }); +} + +/// Below this cover a texel is empty and has no straight colour +pub(crate) const MIN_ALPHA: f32 = 1e-5; + +/// The blurred value a precise halo is solid from +const PRECISE_EDGE: f32 = 0.5; + +/// How soft a full spread leaves a halo: its least hardness +const HALO_SOFTEST: f32 = 0.01; + +/// The shapes' blurred share at their edge +const OUTLINE_EDGE_SHARE: f32 = 0.5; + +/// Lay halo glow or drop shadow `filter` (`op` its move) over premultiplied `data` in the tint of a channel of `kind`, mixed in by `opacity` +fn halo( + data: &mut [f32], + cover: &[f32], + comps: usize, + (width, height, radius): (usize, usize, usize), + (op, filter, kind): (Op, &Filter, ChannelKind), + opacity: f32, +) { + let (inner, precise, spread, strength, color, mask_white) = match *filter { + Filter::HaloGlow { on_mask, precise, width, spread, opacity, color } => (width < 0.0, precise, spread, opacity, color, on_mask), + Filter::DropShadow { spread, opacity, color, .. } => (false, false, spread, opacity, color, true), + _ => return, + }; + + // Rec. 709 luminance, unlike `lum`'s weights on purpose + let luminance = 0.2126 * color[0] + 0.7152 * color[1] + 0.0722 * color[2]; + let tint = match (comps, kind) { + (4, ChannelKind::Color) => color, + (4, _) => [luminance; 3], + _ if mask_white => [1.0; 3], + _ => [luminance; 3], + }; + + // The shapes: the content's coverage or the mask's value (the outside of them for an inner glow) + let shape = |texel: usize| { + let value = data.get(texel * comps + comps - 1).copied().unwrap_or(0.0); + let value = if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; + if inner { 1.0 - value } else { value } + }; + let offset = match op { + Op::Shadow { offset } => offset, + _ => [0, 0], + }; + let moved = |texel: usize| -> Option { + let (x, y) = ((texel % width.max(1)) as i64 - i64::from(offset[0]), (texel / width.max(1)) as i64 - i64::from(offset[1])); + (x >= 0 && y >= 0 && (x as usize) < width && (y as usize) < height).then(|| y as usize * width + x as usize) + }; + let texels = width * height; + let mut weights: Vec = (0..texels).map(|texel| moved(texel).and_then(|from| cover.get(from).copied()).unwrap_or(0.0)).collect(); + let mut sums: Vec = (0..texels).map(|texel| moved(texel).map_or(0.0, |from| shape(from) * cover.get(from).copied().unwrap_or(0.0))).collect(); + blur(&mut weights, width, height, radius); + blur(&mut sums, width, height, radius); + + let hardness = (1.0 - spread.clamp(0.0, 1.0)).max(HALO_SOFTEST); + let strength = strength.clamp(0.0, 1.0); + data.par_chunks_mut(comps).zip(sums.par_iter().zip(weights.par_iter())).for_each(|(pixel, (sum, weight))| { + let blurred = if *weight > MIN_READ_WEIGHT { (sum / weight).clamp(0.0, 1.0) } else { 0.0 }; + let shaped = if precise { crate::organic::smoothstep(0.0, PRECISE_EDGE, blurred) } else { blurred }; + let glow = (shaped / hardness).min(1.0) * strength; + let cov = pixel.last().copied().unwrap_or(0.0).clamp(0.0, 1.0); + let mut before = [0.0f32; 4]; + for (was, value) in before.iter_mut().zip(pixel.iter()) { + *was = *value; + } + if inner { + // Inside the shapes, towards the tint (content premultiplied by its coverage) + let weight = if comps == 4 { glow } else { glow * cov }; + for (slot, tint) in pixel.iter_mut().zip(tint).take(comps.min(3)) { + let target = if comps == 4 { tint * cov } else { tint }; + *slot += (target - *slot) * weight; + } + } else { + // Under the shapes: it shows where they leave room + let under = glow * (1.0 - cov); + for (slot, tint) in pixel.iter_mut().zip(tint).take(comps.min(3)) { + *slot += tint * under; + } + if comps == 4 + && let Some(alpha) = pixel.get_mut(3) + { + *alpha += under; + } + } + for (slot, was) in pixel.iter_mut().zip(before) { + *slot = was + (*slot - was) * opacity; + } + }); +} + +/// Lay Mask Outline `outline` over premultiplied `data` (shapes of content from its luminance), mixed in by `opacity` +fn mask_outline(data: &mut [f32], cover: &[f32], comps: usize, (width, height, radius): (usize, usize, usize), outline: &MaskOutline, opacity: f32) { + let value = |pixel: &[f32]| match pixel { + [r, g, b, alpha] if *alpha > MIN_ALPHA => lum([r / alpha, g / alpha, b / alpha]), + [value] => *value, + _ => 0.0, + }; + let inside: Vec = data.par_chunks(comps).zip(cover.par_iter()).map(|(pixel, covered)| *covered > 0.0 && outline.inside(value(pixel))).collect(); + let fade_curve = outline.fade_curve(); + let mut weights = cover.to_vec(); + let mut sums: Vec = inside.par_iter().zip(cover.par_iter()).map(|(inside, covered)| if *inside { *covered } else { 0.0 }).collect(); + blur(&mut weights, width, height, radius); + blur(&mut sums, width, height, radius); + data.par_chunks_mut(comps).zip(inside.par_iter()).zip(sums.par_iter().zip(weights.par_iter())).for_each(|((pixel, inside), (sum, weight))| { + // The shapes' share around a texel is a half at their edge and none (outside) or all (inside) past the band + let share = if *weight > MIN_READ_WEIGHT { (sum / weight).clamp(0.0, 1.0) } else { 0.0 }; + let closeness = if *inside { (1.0 - share) / OUTLINE_EDGE_SHARE } else { share / OUTLINE_EDGE_SHARE }; + let band = outline.band(fade_curve, *inside, closeness); + + // Content is premultiplied by its coverage, which stays + let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + for slot in pixel.iter_mut().take(comps.min(3)) { + let before = if comps == 4 { if cov > MIN_ALPHA { *slot / cov } else { 0.0 } } else { *slot }; + let result = outline.apply(before, band); + *slot = (before + (result - before) * opacity) * cov; + } + }); +} + +/// Run point filter `filter` on blurred texels `data` (premultiplied content or masks) and mix the result over the unblurred `orig` by `opacity` +fn map_blurred(data: &mut [f32], orig: &[f32], comps: usize, filter: &Filter, kind: ChannelKind, opacity: f32) { + let straight = |value: f32, cover: f32| if cover > MIN_ALPHA { value / cover } else { 0.0 }; + data.par_chunks_mut(comps).zip(orig.par_chunks(comps)).for_each(|(pixel, original)| match (pixel, original) { + ([value], [before]) => { + let mapped = filter.point(kind, [*value; 3]).map_or(*value, |gray| gray[0]); + *value = before + (mapped - before) * opacity; + } + ([r, g, b, cover], [r0, g0, b0, cover0]) => { + let before = [straight(*r0, *cover0), straight(*g0, *cover0), straight(*b0, *cover0)]; + let blurred = [straight(*r, *cover), straight(*g, *cover), straight(*b, *cover)]; + let mixed = mix3(before, filter.point(kind, blurred).unwrap_or(before), opacity); + [*r, *g, *b, *cover] = [mixed[0] * cover0, mixed[1] * cover0, mixed[2] * cover0, *cover0]; + } + _ => {} + }); +} + /// Clamp filtered masks to 0..1, and turn filtered content back into straight values. fn unpremultiply(data: &mut [f32], comps: usize) { // Avoid amplifying rounding error near transparent texels @@ -1176,6 +2136,8 @@ struct Node<'a> { anchors: Vec<(LayerId, Option)>, /// The node or one of its children records an anchor has_anchor: bool, + /// Its base colour has an effect lit by the layer's material (see [`lights_material`]) + lights: bool, height_mask: HeightMask, /// Geometry mask: whether the layer shows on each mesh submesh (None: everywhere). parts: Option>, @@ -1210,6 +2172,15 @@ fn effect_plans<'a>( _ => (None, false), }; let blend = effect.blend_of(channel); + let environment = match &effect.kind { + EffectKind::Filter(Filter::EnvironmentLighting { .. }) => Some(EnvironmentSh::of(&inp.project.display, inp.images)), + _ => None, + }; + let stylized = match &effect.kind { + EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => filter.stylized_lighting().map(|(settings, light)| settings.shading(light)), + _ => None, + }; + let blend = effect.applied_blend(channel); EffectPlan { id: effect.id, kind: offset_effect(&effect.kind, around), @@ -1221,6 +2192,12 @@ fn effect_plans<'a>( filtered_mask: None, depth, covers_all, + environment, + stylized, + input: match &effect.kind { + EffectKind::Filter(filter) if !filter.is_neighbourhood() => ImageInput::of(filter).first().map(|input| effect.input(input)), + _ => None, + }, } }) .collect() @@ -1370,10 +2347,21 @@ fn plan_node<'a>( let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); let anchors = if fx { anchor_cuts(&layer.content_effects) } else { Vec::new() }; let has_anchor = !anchors.is_empty() || mask_anchor || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor)); + let base = Channel::BaseColor.index(); + let lights = chans.iter().any(|chan_plan| chan_plan.ch == base && chan_plan.effects.iter().any(|effect| lights_material(&effect.kind))); // The geometry mask is the layer's own (an instance in another set has other parts) let parts = own.geometry_mask.as_ref().map(|names| inp.mesh.submeshes.iter().map(|s| names.contains(&s.name)).collect()); - Some(Node { id, content, chans, mask, anchors, has_anchor, height_mask: layer.height_mask, parts }) + Some(Node { id, content, chans, mask, anchors, has_anchor, lights, height_mask: layer.height_mask, parts }) +} + +/// Whether a base colour effect reads the layer's other channels as its material: Baked Lighting Stylized's highlights, Environment Lighting, PBR Validate's metal +fn lights_material(kind: &EffectKind) -> bool { + match kind { + EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => filter.stylized_lighting().is_some_and(|(stylized, _)| stylized.output.specular()), + EffectKind::Filter(Filter::EnvironmentLighting { .. } | Filter::PbrValidate(_)) => true, + _ => false, + } } /// The content of `layer` (layer `id`'s own, or its instance source's; None for an unfollowed instance) and its plan per drawn channel of `channels`, its fills under the Scale and Rotation `around` of the folders holding `id`; a folder's children are planned when `kids` @@ -1525,6 +2513,8 @@ struct Texel<'a, 'b> { anchors: Vec<(LayerId, Acc, bool)>, /// The stack below the layer whose mask compares its channels (recorded by `eval` there, or where it stops) below: Option, + /// The material Baked Lighting Stylized reads its highlights from: the stack with the layer it lights (its other channels) laid on + lit: Option, /// Where `eval` takes layer masks and content from. tape: Tape<'b>, /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip @@ -1559,9 +2549,13 @@ impl<'t> Tape<'t> { } } +/// Each channel's content (value and coverage) where the layer has one +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, 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 } } /// Run `f` with `tape` as this texel's tape. @@ -1751,6 +2745,41 @@ impl<'a, 'b> Texel<'a, 'b> { (value.map(|v| v / cover), cover) } + /// The normal Baked Lighting Stylized lights: the mesh's (no `relief`), or (Mesh + Height + Normal) its [`Texel::detail_normal`] at `relief` + fn lit_normal(&mut self, relief: Option) -> [f32; 3] { + match relief { + Some(relief) => self.detail_normal(relief), + None => self.coords().nrm.to_array(), + } + } + + /// The baked world normal (the mesh's without one) tilted by the baked height's slope times `relief` + fn detail_normal(&mut self, relief: f32) -> [f32; 3] { + let mesh = self.coords().nrm; + let detail = self + .baked_color(BakedMap::WorldNormal) + .map(|packed| Vec3::from(packed) * 2.0 - Vec3::ONE) + .filter(|n| n.length_squared() > MIN_NORMAL_LENGTH_SQUARED); + let nrm = detail.map_or(mesh, Vec3::normalize); + let i = (self.y * self.inp.gbuf.width + self.x) as usize; + let (Some(surface), Some(slope)) = (self.surface(i), self.height_slope()) else { return nrm.to_array() }; + let tangent = surface.tangent.truncate(); + let bitangent = nrm.cross(tangent) * surface.tangent.w; + let tilted = nrm - (tangent * slope[0] + bitangent * slope[1]) * HEIGHT_RELIEF * relief; + tilted.try_normalize().unwrap_or(nrm).to_array() + } + + /// The baked height's change per UV unit along U and V at this texel (central differences); None without a height bake + fn height_slope(&self) -> Option<[f32; 2]> { + let (width, height) = (self.res, self.inp.gbuf.height); + let at = |x: u32, y: u32| self.inp.baked.sample_working(BakedMap::Height, x, y, (width, height), &self.inp.block_scales).map(|h| h[0]); + let (left, right) = (self.x.saturating_sub(1), (self.x + 1).min(width.saturating_sub(1))); + let (up, down) = (self.y.saturating_sub(1), (self.y + 1).min(height.saturating_sub(1))); + let du = (at(right, self.y)? - at(left, self.y)?) / (right - left).max(1) as f32 * width as f32; + let dv = (at(self.x, down)? - at(self.x, up)?) / (down - up).max(1) as f32 * height as f32; + Some([du, dv]).filter(|slope| slope.iter().all(|s| s.is_finite())) + } + fn baked(&self, m: BakedMap) -> Option { self.baked_color(m).map(|value| value[0]) } @@ -2131,6 +3160,17 @@ impl<'a, 'b> Texel<'a, 'b> { value += (blend1(effect.blend, value, generated) - value) * opacity; } EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, + EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { + let ramp = filter.ramp_at(self.coords().uv.x.rem_euclid(1.0)).map_or(value, lum); + value += (ramp - value) * opacity; + } + EffectKind::Filter(Filter::GrayscaleConversion(conversion)) => { + let read = match &effect.input { + Some(source) => self.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color), + None => [value; 3], + }; + value += (conversion.gray(read, 1.0) - value) * opacity; + } EffectKind::Filter(filter) => { // A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start` let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); @@ -2209,13 +3249,19 @@ impl<'a, 'b> Texel<'a, 'b> { } Content::Fill { .. } | Content::Paint { .. } if mask > 0.0 => { let before = if node.anchors.iter().any(|(_, cut)| cut.is_some()) { Some(*acc) } else { None }; - for chan_plan in &node.chans { - if let Some((value, coverage)) = self.tape_content(&node.content, chan_plan) { - apply(acc, chan_plan, value, coverage, mask); + // A layer lit by its material evaluates its other channels first (see `Texel::lit_content`) + if node.lights { + self.lit_content(node, acc, mask); + } else { + self.lit = None; + for chan_plan in &node.chans { + if let Some((value, coverage)) = self.tape_content(&node.content, chan_plan) { + apply(acc, chan_plan, value, coverage, mask); + } } } - // Anchors inside the content stack read the stack cut at that point + // Anchors inside the content stack read the stack cut at that point, lit by the same material for (anchor, cut) in &node.anchors { let recorded = match (cut, before) { (Some(cut), Some(mut cut_acc)) => { @@ -2230,6 +3276,7 @@ impl<'a, 'b> Texel<'a, 'b> { }; self.anchors.push((*anchor, recorded, false)); } + self.lit = None; continue; } _ => {} @@ -2241,6 +3288,48 @@ impl<'a, 'b> Texel<'a, 'b> { false } + /// Lay a layer lit by its material over `acc` under `mask`: its other channels go first, each evaluated once, and `self.lit` holds them over the stack below for its base colour's lighting + #[inline(never)] + fn lit_content(&mut self, node: &Node, acc: &mut Acc, mask: f32) { + let base = Channel::BaseColor.index(); + let (material, others) = self.material(node, *acc, mask); + self.lit = Some(material); + + for chan_plan in &node.chans { + let content = match others.get(chan_plan.ch) { + Some(other) if chan_plan.ch != base => *other, + _ => self.tape_content(&node.content, chan_plan), + }; + if let Some((value, coverage)) = content { + apply(acc, chan_plan, value, coverage, mask); + } + } + } + + /// Layer `node`'s other channels than its base colour laid over `below` under `mask`, and each one's content + fn material(&mut self, node: &Node, below: Acc, mask: f32) -> (Acc, ChannelContents) { + let base = Channel::BaseColor.index(); + let mut others = [None; NCH]; + let mut material = below; + for chan_plan in node.chans.iter().filter(|chan_plan| chan_plan.ch != base) { + let content = self.tape_content(&node.content, chan_plan); + if let Some((value, coverage)) = content { + apply(&mut material, chan_plan, value, coverage, mask); + } + if let Some(slot) = others.get_mut(chan_plan.ch) { + *slot = content; + } + } + (material, others) + } + + /// Light layer `node`'s base colour as the full render does, after [`Texel::anchors_below`] recorded the stack below it + fn light(&mut self, node: &Node) { + let below = self.below.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + let mask = self.node_mask(node); + self.lit = Some(self.material(node, below, mask).0); + } + /// [`Texel::eval`] of the whole stack over `acc`, split along the path to the hot layer /// (`levels`, top level first). Cold (`warm` false) it evaluates everything, leaving in /// `accs` the stack before the path layer of each level and recording on `tape` the masks @@ -2458,11 +3547,69 @@ impl<'a, 'b> Texel<'a, 'b> { EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); - let factor = filter.baked_light(self.coords().nrm.to_array(), ao).unwrap_or(1.0); (mix3(value, value.map(|x| (x * factor).clamp(0.0, 1.0)), opacity), coverage) + let lit = match &effect.stylized { + Some(stylized) => { + let nrm = self.lit_normal(stylized.relief()); + let curvature = self.baked(BakedMap::Curvature).unwrap_or(FLAT_CURVATURE); + let material = self.lit.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + stylized.shade(value, nrm, [ao, curvature], &material) + } + None => { + let factor = filter.baked_light(self.coords().nrm.to_array(), ao).unwrap_or(1.0); + value.map(|x| (x * factor).clamp(0.0, 1.0)) + } + }; + (mix3(value, lit, opacity), coverage) } _ => (value, coverage), }, + // Environment lighting reads the texel's normal, occlusion and metal, and lights the base color only + EffectKind::Filter(Filter::EnvironmentLighting { horizontal, vertical, exposure, height_intensity, ambient_occlusion, specular_occlusion }) => { + match (Channel::ALL.get(chan_plan.ch), &effect.environment) { + (Some(Channel::BaseColor), Some(environment)) => { + let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); + let nrm = Vec3::from(self.detail_normal(height_intensity / ENVIRONMENT_HEIGHT_UNIT)); + let light = environment.irradiance(nrm, horizontal.to_radians(), vertical.to_radians()) + * exposure.clamp(-Filter::ENVIRONMENT_EXPOSURE_STOPS, Filter::ENVIRONMENT_EXPOSURE_STOPS).exp2(); + let material = self.lit.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + let lit = EnvironmentSh::shade(value, light, ao, [*ambient_occlusion, *specular_occlusion], &material); + (mix3(value, lit, opacity), coverage) + } + _ => (value, coverage), + } + } + + // PBR Validate checks the base color against the layer's metal and leaves the other channels as they are + EffectKind::Filter(Filter::PbrValidate(validate)) => match Channel::ALL.get(chan_plan.ch) { + Some(Channel::BaseColor) => { + let metal = self.lit.and_then(|material| material.get(Channel::Metallic.index()).map(|metal| metal[0])).unwrap_or(0.0); + (mix3(value, validate.check(value, metal), opacity), coverage) + } + _ => (value, coverage), + }, + // A gradient's debug view shows its ramp left to right across each UV tile + EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { + let ramp = + filter.ramp_at(self.coords().uv.x.rem_euclid(1.0)).map(|color| if chan_plan.kind == ChannelKind::Color { color } else { [lum(color); 3] }); + (ramp.map_or(value, |ramp| mix3(value, ramp, opacity)), coverage) + } + + // Posterize with Apply to Alpha steps the content's coverage too + EffectKind::Filter(filter @ Filter::Posterize { levels, alpha: true }) => { + let stepped = coverage + (posterize(coverage, *levels) - coverage) * opacity; + (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), stepped) + } + + // Grayscale Conversion weighs the coverage as Alpha, or reads its Custom Input + EffectKind::Filter(Filter::GrayscaleConversion(conversion)) => { + let (custom_input, alpha) = match &effect.input { + Some(source) => (Some(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color)), 1.0), + None => (None, coverage), + }; + (mix3(value, conversion.channel_value(chan_plan.kind, value, custom_input, alpha), opacity), coverage) + } + // Neighbourhood filters come precomputed through `ChanPlan::start` EffectKind::Filter(filter) => (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), // Anchors are recorded by `eval`; mask-only effects leave content as it is @@ -3410,7 +4557,7 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti .map(|&(tx, ty)| { let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); let Some(n) = nodes.first() else { return Vec::new() }; - let full = anchor_plan(&visible_inputs, id, &channels, tx, ty, Some(&fields)); + let full = below_plan(&visible_inputs, id, &channels, (tx, ty), Some(&fields), n.lights); let mut buffers: Vec<(Channel, Vec, bool)> = n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect(); for (ch, buffer, _) in &mut buffers { @@ -3426,6 +4573,9 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti if !full.is_empty() { tex.anchors_below(&full, id); } + if n.lights { + tex.light(n); + } let m = tex.node_mask(n); for (c, (ch, buffer, any)) in n.chans.iter().zip(buffers.iter_mut()) { let Some((v, cov)) = tex.content(&n.content, c) else { continue }; @@ -3457,6 +4607,9 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti mod tests { use super::*; use texturecraft_core::{ChannelBlend, CompareOp, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; + use texturecraft_core::{ + ChannelBlend, CompareOp, Effect, Layer, OutputResolution, PbrValidate, Procedural, ProceduralKind, ResolutionMode, StylizedLighting, TextureSet, + }; use texturecraft_geom::primitives; struct Fixture { @@ -3611,7 +4764,7 @@ mod tests { let layer = fill_layer(&mut fixture.project, [color; 3], 0.5); let mut mask = Mask::new(MaskBackground::White); for radius in [8.0, 4.0, 2.0] { - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius }))); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius, wrap: false }))); if record_anchors && radius != 2.0 { mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Anchor)); } @@ -3922,10 +5075,9 @@ mod tests { fixture.project.layer_mut(upper).unwrap().mask = Some(mask.clone()); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let original = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); - assert!(original.iter().any(|value| *value > 0.99) && original.iter().any(|value| *value < 0.01), "the anchor supplies the checker"); - for filter in [Filter::Blur { radius: 64.0 }, Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }] { + for filter in [Filter::Blur { radius: 64.0, wrap: false }, Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 }] { let mut filtered = mask.clone(); filtered.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter))); fixture.project.layer_mut(upper).unwrap().mask = Some(filtered); @@ -3942,7 +5094,7 @@ mod tests { fixture.project.texture_sets[0].resolution = 128; let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; - let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 }; let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let mut masked = |filters: &[Filter]| { let mut mask = Mask::new(MaskBackground::Black); @@ -3958,7 +5110,7 @@ mod tests { }; let warped = masked(std::slice::from_ref(&warp)); - let blurred_then_warped = masked(&[Filter::Blur { radius: 64.0 }, warp]); + let blurred_then_warped = masked(&[Filter::Blur { radius: 64.0, wrap: false }, warp]); assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); assert!(blurred_then_warped.iter().any(|value| *value > 0.05 && *value < 0.95), "the blur softens the checker before the warp moves it"); } @@ -3973,7 +5125,7 @@ mod tests { Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, ); - let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 }; let warp_effect = content_fx(&mut fixture, layer, EffectKind::Filter(warp)); let row = |fixture: &Fixture| -> Vec { let composite = run(fixture, None); @@ -3981,7 +5133,7 @@ mod tests { }; let warped = row(&fixture); - content_fx(&mut fixture, layer, EffectKind::Filter(Filter::Blur { radius: 64.0 })); + content_fx(&mut fixture, layer, EffectKind::Filter(Filter::Blur { radius: 64.0, wrap: false })); let effects = &mut fixture.project.layer_mut(layer).unwrap().content_effects; let warp_index = effects.iter().position(|effect| effect.id == warp_effect).unwrap(); let warp_on_top = effects.remove(warp_index); @@ -4199,20 +5351,14 @@ mod tests { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0; 3], 1.0); assert!(!stack_reads_neighbours(&f.project, 0)); - let mut mask = Mask::new(MaskBackground::White); let eid = f.project.alloc_id(); - mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0 }))); + mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); - assert!(stack_reads_neighbours(&f.project, 0)); - f.project.layer_mut(id).unwrap().mask = None; - assert!(!stack_reads_neighbours(&f.project, 0)); - - content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0 })); - + content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0, alpha: true })); assert!(stack_reads_neighbours(&f.project, 0)); } @@ -4233,7 +5379,7 @@ mod tests { )); f.project.layer_mut(id).unwrap().mask = Some(mask.clone()); let hard: Vec = (0..64).map(|x| run(&f, None).value(Channel::BaseColor, x, 20)[0]).collect(); - mask.effects.push(Effect::new(e2, EffectKind::Filter(Filter::Blur { radius: 64.0 }))); + mask.effects.push(Effect::new(e2, EffectKind::Filter(Filter::Blur { radius: 64.0, wrap: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); let soft_img = run(&f, None); let soft: Vec = (0..64).map(|x| soft_img.value(Channel::BaseColor, x, 20)[0]).collect(); @@ -4288,7 +5434,7 @@ soft {soft:?}" fn content_filters_hsl_and_opacity_change_layer_values() { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); - content_fx(&mut f, id, EffectKind::Filter(Filter::Hsl { hue: 1.0 / 3.0, saturation: 0.0, lightness: 0.0 })); + content_fx(&mut f, id, EffectKind::Filter(Filter::Hsl { hue: 1.0 / 3.0, saturation: 0.0, lightness: 0.0, perceptive: false })); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 5, 5), [0.0, 1.0, 0.0]), "{:?}", out.value(Channel::BaseColor, 5, 5)); assert!(close(out.value(Channel::Roughness, 5, 5), [0.2; 3]), "a hue shift leaves scalars alone"); @@ -4307,14 +5453,85 @@ soft {soft:?}" assert!(close(out.value(Channel::Roughness, 5, 5), [0.5; 3])); } + /// Posterize steps a paint layer's coverage only with Apply to Alpha + #[test] + fn posterize_steps_the_coverage_when_it_applies_to_alpha() { + let mut f = fixture(); + let id = f.project.alloc_id(); + let l = Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]); + f.project.insert_layer(0, l, None, false).unwrap(); + + // Half-covered red over the default mid gray + f.pixels.layer_mut(id, Channel::BaseColor, (64, 64)).set(3, 3, &[to_u16(0.5), 0, 0, to_u16(0.5)]); + let posterize = content_fx(&mut f, id, EffectKind::Filter(Filter::Posterize { levels: 2.0, alpha: false })); + assert!(close(run(&f, None).value(Channel::BaseColor, 3, 3), [0.75, 0.25, 0.25]), "the coverage stays as it is"); + f.project.effect_mut(posterize).unwrap().kind = EffectKind::Filter(Filter::Posterize { levels: 2.0, alpha: true }); + assert!(close(run(&f, None).value(Channel::BaseColor, 3, 3), [1.0, 0.0, 0.0]), "half coverage rounds up to whole"); + } + + /// A paint layer with base color texels set by `paint` (x, y -> Some(linear color, coverage)) + fn painted(f: &mut Fixture, paint: impl Fn(u32, u32) -> Option<([f32; 3], f32)>) -> LayerId { + let id = f.project.alloc_id(); + let l = Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]); + f.project.insert_layer(0, l, None, false).unwrap(); + let tile = f.pixels.layer_mut(id, Channel::BaseColor, (64, 64)); + for (x, y) in (0..64).flat_map(|y| (0..64).map(move |x| (x, y))) { + if let Some((color, cover)) = paint(x, y) { + tile.set(x, y, &[to_u16(color[0] * cover), to_u16(color[1] * cover), to_u16(color[2] * cover), to_u16(cover)]); + } + } + id + } + + /// Pixelate steps the coverage into its cells only with Apply To Alpha; off, each texel keeps its own + #[test] + fn pixelate_keeps_each_texels_coverage_without_apply_to_alpha() { + let mut f = fixture(); + + // One red texel in a cell of 4 × 4 texels (128 texels at 2K at 64 across), whose center reads it a quarter + let id = painted(&mut f, |x, y| ((x, y) == (1, 1)).then_some(([1.0, 0.0, 0.0], 1.0))); + let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 128.0, alpha: true })); + let out = run(&f, None); + assert!(close(out.value(Channel::BaseColor, 1, 1), [0.625, 0.375, 0.375]), "the cell's coverage: {:?}", out.value(Channel::BaseColor, 1, 1)); + assert!(close(out.value(Channel::BaseColor, 2, 2), [0.625, 0.375, 0.375]), "spread over the cell"); + f.project.effect_mut(fx).unwrap().kind = EffectKind::Filter(Filter::Mosaic { size: 128.0, alpha: false }); + let out = run(&f, None); + assert!(close(out.value(Channel::BaseColor, 1, 1), [1.0, 0.0, 0.0]), "the texel keeps its whole coverage"); + assert!(close(out.value(Channel::BaseColor, 2, 2), [0.5; 3]), "an uncovered texel stays uncovered"); + } + + /// FXAA blends a stair-stepped edge and leaves flat areas; the coverage only with Affect Alpha Channel + #[test] + fn fxaa_smooths_stair_steps() { + let stairs = |x: u32, y: u32| x >= 20 + y / 4; + let mids = |out: &Composite| (0..64 * 64).filter(|i| (0.05..0.95).contains(&out.value(Channel::BaseColor, i % 64, i / 64)[0])).count(); + + // Black and white, both covered: the edge gets in-between values + let mut f = fixture(); + let id = painted(&mut f, |x, y| Some((if stairs(x, y) { [1.0; 3] } else { [0.0; 3] }, 1.0))); + assert_eq!(mids(&run(&f, None)), 0); + content_fx(&mut f, id, EffectKind::Filter(Filter::Fxaa { alpha: false })); + let out = run(&f, None); + assert!(mids(&out) > 16, "{} texels blended", mids(&out)); + assert!(close(out.value(Channel::BaseColor, 2, 30), [0.0; 3]) && close(out.value(Channel::BaseColor, 60, 30), [1.0; 3]), "flat areas stay"); + + // White shapes on nothing: the coverage changes only with Affect Alpha Channel + let mut f = fixture(); + let id = painted(&mut f, |x, y| stairs(x, y).then_some(([1.0; 3], 1.0))); + let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Fxaa { alpha: false })); + let plain = |out: &Composite| (0..64 * 64).all(|i| [0.5, 1.0].iter().any(|v| (out.value(Channel::BaseColor, i % 64, i / 64)[0] - v).abs() < 2e-4)); + assert!(plain(&run(&f, None)), "each texel keeps its coverage"); + f.project.effect_mut(fx).unwrap().kind = EffectKind::Filter(Filter::Fxaa { alpha: true }); + assert!(!plain(&run(&f, None)), "the coverage is smoothed"); + } + #[test] fn hsl_on_a_mask_changes_its_lightness() { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0; 3], 1.0); let mut mask = Mask::new(MaskBackground::White); - mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Hsl { hue: 0.3, saturation: 1.0, lightness: -0.5 }))); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Hsl { hue: 0.3, saturation: 1.0, lightness: -0.5, perceptive: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); - assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.75; 3])); } @@ -4333,19 +5550,142 @@ soft {soft:?}" (0..64).map(|x| out.value(Channel::Roughness, x, 20)[0]).collect::>() }; let hard = row(&f); - content_fx(&mut f, id, EffectKind::Filter(Filter::Blur { radius: 64.0 })); + content_fx(&mut f, id, EffectKind::Filter(Filter::Blur { radius: 64.0, wrap: false })); let soft = row(&f); let mids = |v: &[f32]| v.iter().filter(|x| **x > 0.05 && **x < 0.95).count(); assert!(mids(&soft) > mids(&hard) + 4, "hard {hard:?}\nsoft {soft:?}"); assert!(soft.iter().all(|v| (0.0..=1.0).contains(v))); } + /// A fill layer of a black and white checker on Roughness, under `filter` when given + fn checker_roughness(fixture: &mut Fixture, filter: Option) { + let id = fixture.project.alloc_id(); + let mut fill = Fill::default(); + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; + fill.sources.insert(Channel::Roughness, checker); + fixture.project.insert_layer(0, Layer::new(id, "F", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap(); + if let Some(filter) = filter { + content_fx(fixture, id, EffectKind::Filter(filter)); + } + } + + #[test] + fn a_wrapping_blur_reads_the_far_side_of_the_texture() { + let row = |wrap: Option| { + let mut f = fixture(); + checker_roughness(&mut f, wrap.map(|wrap| Filter::Blur { radius: 96.0, wrap })); + let out = run(&f, None); + (0..64).map(|x| out.value(Channel::Roughness, x, 20)[0]).collect::>() + }; + + // The checker tiles: its period P repeats across the whole row + let hard = row(None); + let period = (1..64).find(|&p| (0..64 - p).all(|x| (hard[x] - hard[x + p]).abs() < 1e-3)).unwrap(); + assert!(period <= 32, "{hard:?}"); + + // Wrapped, the blur at the texture's edge sees the far side, so the result keeps tiling; clipped, the edge differs + let wrapped = row(Some(true)); + assert!((0..64 - period).all(|x| (wrapped[x] - wrapped[x + period]).abs() < 0.02), "{wrapped:?}"); + let clipped = row(Some(false)); + assert!((clipped[0] - clipped[period]).abs() > 0.05, "{clipped:?}"); + assert!((12..52).all(|x| (clipped[x] - wrapped[x]).abs() < 0.02), "away from the edges, wrap changes nothing"); + } + + /// A set several tiles wide: a tile at its edge composited alone reads the far side as the whole set does, so the result keeps tiling across the edge + #[test] + fn a_wrapping_filter_reads_the_far_side_of_a_set_several_tiles_wide() { + const WIDTH: u32 = 256; + const HEIGHT: u32 = 64; + let row_of = |out: &Composite| (0..WIDTH).map(|x| out.value(Channel::Roughness, x, 20)[0]).collect::>(); + let composite = |filter: Option<&Filter>, tiles: &[(u32, u32)]| { + let mut f = fixture(); + f.gbuf = UvGBuffer::new(&f.mesh, 0, WIDTH, HEIGHT); + f.project.texture_sets[0].resolution = WIDTH; + checker_roughness(&mut f, filter.cloned()); + let images = ImageStore::default(); + let mut out = Composite::with_size(&f.project.texture_sets[0].channel_list(), WIDTH, HEIGHT); + composite_tiles(&inputs(&f, &images, None), &mut out, tiles); + row_of(&out) + }; + let hard = composite(None, &all_tiles(WIDTH, HEIGHT)); + let period = (1..WIDTH as usize).find(|&p| (0..WIDTH as usize - p).all(|x| (hard[x] - hard[x + p]).abs() < 1e-3)).unwrap(); + assert!(period <= WIDTH as usize / 2, "the checker tiles across the set: {hard:?}"); + + let wrapping = [ + Filter::Blur { radius: 96.0, wrap: true }, + Filter::DistanceBevel(Bevel { wrap: true, ..Bevel::LIBRARY }), + Filter::BevelSmooth(BevelSmooth { wrap: true, ..BevelSmooth::LIBRARY }), + ]; + for filter in wrapping { + let whole = composite(Some(&filter), &all_tiles(WIDTH, HEIGHT)); + let edge_tile = composite(Some(&filter), &[(0, 0)]); + + let label = filter.label(); + assert!((0..TILE as usize).all(|x| (edge_tile[x] - whole[x]).abs() < 1e-3), "{label}: the edge tile alone\n{edge_tile:?}\nwhole\n{whole:?}"); + assert!((0..WIDTH as usize - period).all(|x| (whole[x] - whole[x + period]).abs() < 0.02), "{label} keeps tiling: {whole:?}"); + } + } + + #[test] + fn a_gradients_blur_intensity_blurs_what_it_looks_up() { + let row = |filter: Option| { + let mut f = fixture(); + checker_roughness(&mut f, filter); + let out = run(&f, None); + (16..48).map(|x| out.value(Channel::Roughness, x, 20)[0]).collect::>() + }; + let mut gradient = Filter::even_gradient(vec![[0.0; 3], [1.0; 3]]); + let hard = row(Some(gradient.clone())); + assert!(hard.iter().zip(row(None)).all(|(a, b)| (a - b).abs() < 1e-3), "a black to white ramp keeps a scalar as it is"); + + // Blurred first, then looked up: the same as a blur of that size + if let Filter::GradientMap { input, .. } = &mut gradient { + input.blur = 8.0; + } + let blurred = row(Some(gradient)); + let reference = row(Some(Filter::Blur { radius: 8.0, wrap: false })); + assert!(blurred.iter().zip(&reference).all(|(a, b)| (a - b).abs() < 0.02), "{blurred:?} vs {reference:?}"); + assert!(blurred.iter().zip(&hard).any(|(a, b)| (a - b).abs() > 0.1), "{blurred:?}"); + } + + #[test] + fn highpass_works_in_its_color_space_and_applies_to_alpha() { + // Uniform content has no detail: mid gray in the working space, sRGB mid gray (linear 0.214) in sRGB + let mut f = fixture(); + let below = fill_layer(&mut f.project, [0.0; 3], 0.0); + let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); + assert_ne!(below, id); + let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::SrgbFromLinear, alpha: false })); + let out = run(&f, None); + assert!(close(out.value(Channel::BaseColor, 30, 30), [texturecraft_texel::srgb_to_linear(0.5); 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); + assert!(close(out.value(Channel::Roughness, 30, 30), [0.5; 3]), "scalar channels stay in the working space"); + + // Apply To Alpha: full coverage minus its blur, around 0.5, lays the layer at half over the black one below + f.project.effect_mut(hp).unwrap().kind = EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::Working, alpha: true }); + let out = run(&f, None); + assert!(close(out.value(Channel::Roughness, 30, 30), [0.25; 3]), "{:?}", out.value(Channel::Roughness, 30, 30)); + } + + #[test] + fn highpass_in_srgb_applied_to_alpha_decodes_on_the_new_coverage() { + let mut f = fixture(); + fill_layer(&mut f.project, [0.0; 3], 0.0); + let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); + content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::SrgbFromLinear, alpha: true })); + + let out = run(&f, None); + + // sRGB mid gray (linear 0.214) at half coverage over the black layer below + let expected = texturecraft_texel::srgb_to_linear(0.5) * 0.5; + assert!(close(out.value(Channel::BaseColor, 30, 30), [expected; 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); + } + #[test] fn high_pass_edge_detect_directional_warp_grayscale_and_normal_invert() { // Uniform content gives mid gray high pass and black edge detection let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); - let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0 })); + let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::Working, alpha: false })); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 30, 30), [0.5; 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); assert!(close(out.value(Channel::Roughness, 30, 30), [0.5; 3])); @@ -4368,15 +5708,12 @@ soft {soft:?}" let edges = content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 32.0 })); let out = run(&f, None); let vals: Vec = (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).map(|(x, y)| out.value(Channel::Roughness, x, y)[0]).collect(); - assert!(vals.iter().all(|v| (0.0..=1.0).contains(v))); assert!(vals.iter().filter(|v| **v > 0.5).count() > 64 && vals.iter().filter(|v| **v < 0.01).count() > 64, "{vals:?}"); - f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != edges); - content_fx(&mut f, id, EffectKind::Filter(Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 })); + content_fx(&mut f, id, EffectKind::Filter(Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 })); let warped = run(&f, None); let differs = (0..64).any(|y| (0..64).any(|x| (warped.value(Channel::Roughness, x, y)[0] - plain.value(Channel::Roughness, x, y)[0]).abs() > 0.2)); - assert!(differs, "the warp moves the checker"); // Point filters @@ -4396,6 +5733,59 @@ soft {soft:?}" assert_eq!(rc.point(ChannelKind::Scalar, [0.8; 3]), Some([0.8; 3])); } + #[test] + fn a_halo_glow_lights_around_a_masks_shapes_and_a_drop_shadow_lands_under_them_away_from_the_light() { + let row_of = |filter: Option| { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0; 3], 1.0); + let mut mask = Mask::new(MaskBackground::Black); + let fill = EffectKind::Fill { + source: Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::default(), + }; + mask.effects.push(Effect::new(f.project.alloc_id(), fill)); + if let Some(filter) = filter { + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(filter))); + } + f.project.layer_mut(id).unwrap().mask = Some(mask); + let out = run(&f, None); + (0..64 * 64).map(|i| out.value(Channel::BaseColor, i % 64, i / 64)[0]).collect::>() + }; + let plain = row_of(None); + let (low, high) = plain.iter().fold((f32::MAX, f32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + let dark = |v: f32| v < low + 0.01; + + // A glow only adds, and lights the dark texels beside the shapes + let glow = Filter::HaloGlow { on_mask: true, precise: false, width: 1.0, spread: 0.0, opacity: 1.0, color: [1.0; 3] }; + let glowing = row_of(Some(glow)); + assert!(glowing.iter().zip(&plain).all(|(g, p)| *g >= p - 1e-4), "a glow only adds"); + let lit = (0..64 * 64).filter(|&i| dark(plain[i]) && glowing[i] > low + 0.1 * (high - low)).count(); + assert!(lit > 64, "{lit} dark texels lit"); + + // A shadow from a light above lands below the shapes: dark texels under a shape take it, those above one do not + let shadow = Filter::DropShadow { angle: 90.0, distance: 0.1, size: 0.0, spread: 0.0, opacity: 0.5, color: [0.0; 3] }; + let shadowed = row_of(Some(shadow)); + assert!(shadowed.iter().zip(&plain).all(|(s, p)| *s >= p - 1e-4), "a shadow only goes under the shapes"); + let reach = 6; + let at = |x: usize, y: usize| plain[y * 64 + x]; + let (mut below, mut above) = (Vec::new(), Vec::new()); + for y in 8..56 { + for x in 0..64 { + if dark(at(x, y)) && !dark(at(x, y - reach)) && (y - 2..=y).all(|row| dark(at(x, row))) { + below.push(shadowed[y * 64 + x] - at(x, y)); + } + if dark(at(x, y)) && !dark(at(x, y + reach)) && dark(at(x, y - reach)) && (y..=y + 2).all(|row| dark(at(x, row))) { + above.push(shadowed[y * 64 + x] - at(x, y)); + } + } + } + assert!(!below.is_empty() && !above.is_empty()); + let mean = |v: &[f32]| v.iter().sum::() / v.len() as f32; + assert!(mean(&below) > 0.2 * (high - low), "under: {below:?}"); + assert!(mean(&above) < 0.05 * (high - low), "above: {above:?}"); + } + #[test] fn bevel_glow_and_mosaic() { let checker = |f: &mut Fixture| { @@ -4417,7 +5807,7 @@ soft {soft:?}" let plain = values(&f); // Bevel stays below the shape and turns edges into ramps - let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Bevel { width: 128.0 })); + let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Bevel { width: 128.0, wrap: false })); let bevel = values(&f); let mids = |v: &[f32]| v.iter().filter(|x| **x > 0.05 && **x < 0.95).count(); assert!(bevel.iter().zip(&plain).all(|(b, p)| *b <= p + 1e-4 && *b >= 0.0), "a bevel only lowers values"); @@ -4425,7 +5815,7 @@ soft {soft:?}" // Mosaic reduces changes between adjacent texels f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != fx); - let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 768.0 })); + let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 768.0, alpha: true })); let mosaic = values(&f); let steps = |v: &[f32]| v.windows(2).filter(|w| (w[0] - w[1]).abs() > 0.01).count(); assert!(steps(&mosaic) < steps(&plain), "{} vs {}", steps(&mosaic), steps(&plain)); @@ -4445,7 +5835,7 @@ soft {soft:?}" let lit = |elevation: f32| { let mut f = fixture(); let id = fill_layer(&mut f.project, [0.5; 3], 0.3); - let fx = Filter::BakedLighting { azimuth: 0.0, elevation, light: 0.6, ambient: 0.4, occlusion: 1.0 }; + let fx = Filter::BakedLighting { azimuth: 0.0, elevation, light: 0.6, ambient: 0.4, occlusion: 1.0, stylized: None }; content_fx(&mut f, id, EffectKind::Filter(fx)); let out = run(&f, None); (out.value(Channel::BaseColor, 30, 30), out.value(Channel::Roughness, 30, 30)) @@ -4455,15 +5845,30 @@ soft {soft:?}" // Facing the light adds illumination; facing away keeps ambient only let (toward, rough) = lit(if n.y > 0.0 { 90.0 } else { -90.0 }); assert!(close(toward, [0.5; 3]) && close(rough, [0.3; 3]), "{toward:?} {rough:?}"); - let (away, _) = lit(if n.y > 0.0 { -90.0 } else { 90.0 }); assert!(close(away, [0.2; 3]), "{away:?}"); - - let f = Filter::BakedLighting { azimuth: 0.0, elevation: 0.0, light: 0.0, ambient: 1.0, occlusion: 0.5 }; + let f = Filter::BakedLighting { azimuth: 0.0, elevation: 0.0, light: 0.0, ambient: 1.0, occlusion: 0.5, stylized: None }; assert_eq!(f.baked_light([0.0, 1.0, 0.0], 0.2), Some(0.6), "half the occlusion"); assert_eq!(Filter::Invert.baked_light([0.0; 3], 1.0), None); } + /// Baked Lighting Stylized's highlights read the roughness of the layer it lights: a smooth layer shines brighter than a rough one under the same sun + #[test] + fn stylized_baked_lighting_highlights_read_the_layers_roughness() { + let lit = |rough: f32| { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [0.2; 3], rough); + let n = primitives::plane(2.0, 2).normals[0]; + let stylized = Some(Box::new(StylizedLighting { lights: [texturecraft_core::DirectionalLight::off(0.0); 2], ..StylizedLighting::library() })); + let elevation = if n.y > 0.0 { 90.0 } else { -90.0 }; + let fx = Filter::BakedLighting { azimuth: 0.0, elevation, light: 1.0, ambient: 0.0, occlusion: 0.0, stylized }; + content_fx(&mut f, id, EffectKind::Filter(fx)); + run(&f, None).value(Channel::BaseColor, 30, 30) + }; + let (smooth, rough) = (lit(0.15), lit(0.9)); + assert!(smooth[0] > rough[0] + 0.05, "smooth {smooth:?} rough {rough:?}"); + } + #[test] fn a_compares_histogram_reads_the_compares_under_it_against_the_stack() { let mut f = fixture(); @@ -4490,10 +5895,24 @@ soft {soft:?}" // The roughness below (0.8) passes the first compare everywhere: the mask so far is white let white = *mask_so_far.last().unwrap(); - assert!(white > 0 && mask_so_far.iter().sum::() == white, "{mask_so_far:?}"); } + #[test] + fn a_histogram_shares_one_field_of_a_stage_reading_the_whole_set() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [0.5; 3], 0.5); + let matcher = ColorMatch { source_mode: SourceColorMode::Average, ..ColorMatch::LIBRARY }; + content_fx(&mut f, id, EffectKind::Filter(Filter::ColorMatch(matcher))); + let images = ImageStore::default(); + let inp = inputs(&f, &images, None); + let channels = f.project.texture_set(0).unwrap().channel_list(); + + let shared = shared_histogram_fields(&inp, &channels, &all_tiles(64, 64)); + + assert!(shared.is_some_and(|fields| fields.contains_key(&FieldKey::Content(id, Channel::BaseColor))), "every sampled tile reads one field"); + } + #[test] fn a_filtered_mask_compares_the_layers_filtered_content() { let mut f = fixture(); @@ -4512,6 +5931,7 @@ soft {soft:?}" let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(f.project.alloc_id(), compare)); mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 2.0 }))); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 2.0, wrap: true }))); f.project.layer_mut(top).unwrap().mask = Some(mask); let color = run(&f, None).value(Channel::BaseColor, 30, 30); @@ -4616,18 +6036,15 @@ soft {soft:?}" let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })); f.project.layer_mut(top).unwrap().mask = Some(mask.clone()); - assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // The field pre-pass reads anchors under blur, preserving flat height - mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false }))); f.project.layer_mut(top).unwrap().mask = Some(mask); - assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // An anchor above its reader is not evaluated yet, so it reads the channel default f.project.move_layer(low, 1).unwrap(); - assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3])); } @@ -4660,16 +6077,14 @@ soft {soft:?}" assert!(close(run(&fixture, None).value(Channel::BaseColor, 5, 5), [0.4; 3])); // Under a blur precomputed over the region the anchor still records its own place - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false }))); fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); - assert!(close(color, [0.4; 3]), "{color:?}"); // An empty paint layer still records its mask anchor for the layer above fixture.project.layer_mut(low).unwrap().kind = LayerKind::Paint; let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); - assert!(close(color, [0.7; 3]), "{color:?}"); } @@ -4686,22 +6101,74 @@ soft {soft:?}" fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default(), sampling: Default::default() }, )); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 64.0 }))); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 64.0, wrap: false }))); mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); fixture.project.layer_mut(lower).unwrap().mask = Some(mask.clone()); let reader = anchor_reader(&mut fixture, anchor); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let expected = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); - assert!(expected.iter().any(|value| *value > 0.1 && *value < 0.9), "the anchor records a softened checker"); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 128.0 }))); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 128.0, wrap: false }))); fixture.project.layer_mut(lower).unwrap().mask = Some(mask); let actual = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); assert_eq!(actual, expected, "a filter above the anchor must not change its recorded value"); } + #[test] + fn an_anchor_between_content_effects_keeps_the_layers_own_lighting() { + let mut fixture = fixture(); + let low = fixture.project.alloc_id(); + let mut fill = Fill::default(); + + // A gray (sRGB 140) dim for a metal but valid for a dielectric: PBR Validate turns it red only with the layer's own metal + let dim_metal = [0.26; 3]; + fill.sources.insert(Channel::BaseColor, Source::Uniform(dim_metal)); + fill.sources.insert(Channel::Metallic, Source::Uniform([1.0; 3])); + let layer = Layer::new(low, "Metal", LayerKind::Fill(fill), &[Channel::BaseColor, Channel::Metallic]); + fixture.project.insert_layer(0, layer, None, false).unwrap(); + content_fx(&mut fixture, low, EffectKind::Filter(Filter::PbrValidate(PbrValidate::LIBRARY))); + let anchor = content_fx(&mut fixture, low, EffectKind::Anchor); + let reader = fixture.project.alloc_id(); + let mut read = Fill::default(); + read.sources.insert(Channel::BaseColor, Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }); + let layer = Layer::new(reader, "Reader", LayerKind::Fill(read), &[Channel::BaseColor]); + fixture.project.insert_layer(0, layer, None, false).unwrap(); + let uncut = run(&fixture, None).value(Channel::BaseColor, 5, 5); + + // An effect above the anchor cuts the content stack there: the cut is checked against the same metal + content_fx(&mut fixture, low, EffectKind::Levels(Default::default())); + let cut = run(&fixture, None).value(Channel::BaseColor, 5, 5); + + assert!(close(uncut, PbrValidate::INVALID), "{uncut:?}"); + assert!(close(cut, uncut), "{cut:?}"); + } + + #[test] + fn a_filter_and_a_flatten_above_pbr_validate_keep_the_layers_own_metal() { + let mut fixture = fixture(); + let id = fixture.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([0.26; 3])); + fill.sources.insert(Channel::Metallic, Source::Uniform([1.0; 3])); + let layer = Layer::new(id, "Metal", LayerKind::Fill(fill), &[Channel::BaseColor, Channel::Metallic]); + fixture.project.insert_layer(0, layer, None, false).unwrap(); + content_fx(&mut fixture, id, EffectKind::Filter(Filter::PbrValidate(PbrValidate::LIBRARY))); + let images = ImageStore::default(); + let flat = flatten_layer(&inputs(&fixture, &images, None), id, &all_tiles(64, 64)).unwrap(); + content_fx(&mut fixture, id, EffectKind::Filter(Filter::Blur { radius: 4.0, wrap: false })); + + let blurred = run(&fixture, None).value(Channel::BaseColor, 30, 30); + + // A dim gray is valid for a dielectric only: the layer's metal makes it red in the filter's prepass and in the flattened layer + assert!(close(blurred, PbrValidate::INVALID), "{blurred:?}"); + let (_, _, data) = flat.iter().find(|(channel, tile, _)| *channel == Channel::BaseColor && *tile == (0, 0)).unwrap(); + let texel = (30 * TILE as usize + 30) * 4; + let flattened: [f32; 3] = std::array::from_fn(|i| from_u16(data[texel + i])); + assert!(flattened.iter().zip(PbrValidate::INVALID).all(|(value, invalid)| (value - invalid).abs() < 1e-3), "{flattened:?}"); + } + #[test] fn generator_micro_detail_follows_the_anchor_height() { let mut fixture = fixture(); diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs deleted file mode 100644 index 6f50f143..00000000 --- a/crates/compose/src/eval/evaluation_inputs.rs +++ /dev/null @@ -1,23 +0,0 @@ -use std::ops::Deref; - -use super::Inputs; -use crate::ProjectorDepthCache; - -pub(super) struct EvaluationInputs<'a> { - inputs: &'a Inputs<'a>, - pub(super) projectors: &'a ProjectorDepthCache, -} - -impl<'a> EvaluationInputs<'a> { - pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self { - Self { inputs, projectors } - } -} - -impl<'a> Deref for EvaluationInputs<'a> { - type Target = Inputs<'a>; - - fn deref(&self) -> &Self::Target { - self.inputs - } -} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index c0369fd2..65cf4271 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -13,7 +13,10 @@ pub mod below; mod curvature_size_level; pub mod curvature_sizes; pub mod display; +mod distance_envelope; mod effect_histogram; +pub mod environment_sh; +pub mod environment_sky; pub mod eval; mod fabric; pub mod fill_copies; @@ -30,8 +33,10 @@ pub mod pattern; mod pattern_context; pub mod projector_cover; pub mod projector_depth; -mod projector_depth_cache; pub mod projector_view; +mod shape_distance; +mod slope_texel; +mod soft_box; pub mod solo; pub mod store; pub mod thumb; @@ -40,6 +45,8 @@ mod tile_pattern; mod tile_random_stream; mod timber; pub mod warp; +mod warp_source_sample; +mod warp_texel; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; diff --git a/crates/compose/src/shape_distance.rs b/crates/compose/src/shape_distance.rs new file mode 100644 index 00000000..0f3df3a7 --- /dev/null +++ b/crates/compose/src/shape_distance.rs @@ -0,0 +1,386 @@ +//! Filters drawn from the distance to the shapes' edge: Bevel, Bevel Smooth and Directional Distance + +use rayon::prelude::*; +use texturecraft_core::{Bevel, BevelBlur, BevelCorner, DirectionalDistance, Filter, lum}; + +use crate::distance_envelope::DistanceEnvelope; +use crate::eval::{MIN_ALPHA, blur}; + +/// From a texel's centre to the edge between it and the nearest texel across: half a texel short of their centres' distance +const EDGE_OFFSET: f32 = 0.5; + +/// Components of a texel with color and coverage (red, green, blue, alpha) +const RGBA_COMPONENTS: usize = 4; + +/// Color components of a texel, before its alpha +const COLOR_COMPONENTS: usize = 3; + +/// Where a texel's alpha sits among its components +const ALPHA_INDEX: usize = 3; + +/// What a texel becomes from its index, whether it is inside the shapes and its own value +type TexelResult<'a> = dyn Fn(usize, bool, f32) -> f32 + Sync + 'a; + +/// Lay distance filter `filter` over premultiplied `data` (`width` × `height` texels of `components`; content's shapes from its luminance), `tile_resolution` texels across a UV tile, mixed in by `opacity`; its Distance Map `grays` (0..1 a texel) scales the distance texel by texel +pub(crate) fn distance_filter( + data: &mut [f32], + (cover, grays): (&[f32], &[f32]), + components: usize, + (width, height): (usize, usize), + filter: &Filter, + tile_resolution: u32, + opacity: f32, +) { + let map = |texel: usize| grays.get(texel).copied().unwrap_or(1.0); + let value = |pixel: &[f32]| match pixel { + [r, g, b, alpha] if *alpha > MIN_ALPHA => lum([r / alpha, g / alpha, b / alpha]), + [value] => *value, + _ => 0.0, + }; + let values: Vec = data.par_chunks(components).map(value).collect(); + let shapes = |inside: &(dyn Fn(f32) -> bool + Sync)| -> Vec { + values.par_iter().zip(cover.par_iter()).map(|(value, covered)| *covered > 0.0 && inside(*value)).collect() + }; + let smoothed = |field: &mut [f32], texels: f32| { + let radius = texels.round() as usize; + if radius > 0 { + blur(field, width, height, radius); + } + }; + + // Per texel: whether it is inside the shapes, and what it becomes from its own value + let (inside, result): (Vec, Box>) = match filter { + Filter::DistanceBevel(bevel) => { + let inside = shapes(&|value| value >= Bevel::EDGE); + let edge = edge_distances(&inside, (width, height), bevel.corner == BevelCorner::Angular); + let reach = bevel.reach(tile_resolution); + let mut slope: Vec = inside.par_iter().zip(edge.par_iter()).map(|(inside, edge)| bevel.slope(*inside, *edge, reach)).collect(); + let mut blurred = slope.clone(); + smoothed(&mut blurred, bevel.smoothing_texels(tile_resolution)); + slope.par_iter_mut().zip(blurred.par_iter()).for_each(|(sharp, blurred)| { + *sharp = match bevel.blur { + BevelBlur::Uniform => *blurred, + // Sharp at the slope's foot, as blurred as Uniform at its top + BevelBlur::NonUniform => *sharp + (blurred - *sharp) * *sharp, + }; + }); + let bevel = *bevel; + (inside, Box::new(move |texel, inside, value| bevel.apply(inside, value, slope.get(texel).copied().unwrap_or(1.0)))) + } + Filter::BevelSmooth(smooth) => { + let inside = shapes(&|value| smooth.inside(value)); + let edge = edge_distances(&inside, (width, height), false); + let (reach, curve) = (smooth.reach(tile_resolution), smooth.curve()); + let mut ramp: Vec = inside + .par_iter() + .zip(edge.par_iter()) + .enumerate() + .map(|(texel, (inside, edge))| smooth.value(curve, *inside, *edge, reach * map(texel))) + .collect(); + smoothed(&mut ramp, smooth.smoothing_texels(tile_resolution)); + (inside, Box::new(move |texel, _, value| ramp.get(texel).copied().unwrap_or(value))) + } + Filter::DirectionalDistance(trail) => { + let inside = shapes(&|value| value >= DirectionalDistance::EDGE); + let along = trail_distances(&inside, (width, height), crate::eval::direction(trail.angle), trail.reach(tile_resolution)); + let trail = *trail; + + // A share of the full reach is a larger share of a texel's shorter one; no trail where the map is black, the shapes stay + let shortened = move |texel: usize| { + along.get(texel).copied().flatten().and_then(|along| match map(texel) { + _ if along <= 0.0 => Some(0.0), + gray if gray > 0.0 => Some(along / gray), + _ => None, + }) + }; + (inside, Box::new(move |texel, _, _| trail.value(shortened(texel).filter(|along| *along <= 1.0)))) + } + _ => return, + }; + + let has_alpha = components == RGBA_COMPONENTS; + data.par_chunks_mut(components).zip(inside.par_iter()).zip(cover.par_iter()).enumerate().for_each(|(texel, ((pixel, inside), covered))| { + if *covered <= 0.0 { + return; + } + + // Content is premultiplied by its coverage, which stays + let coverage = if has_alpha { pixel.get(ALPHA_INDEX).copied().unwrap_or(0.0) } else { 1.0 }; + for slot in pixel.iter_mut().take(components.min(COLOR_COMPONENTS)) { + let before = if has_alpha { if coverage > MIN_ALPHA { *slot / coverage } else { 0.0 } } else { *slot }; + let after = result(texel, *inside, before); + *slot = (before + (after - before) * opacity) * coverage; + } + }); +} + +/// Every texel's distance (texels) to the edge between it and the nearest texel on the other side of the shapes `inside`: straight-line, or the larger axis distance when `angular` +fn edge_distances(inside: &[bool], (width, height): (usize, usize), angular: bool) -> Vec { + let outside: Vec = inside.iter().map(|inside| !inside).collect(); + let (to_inside, to_outside) = if angular { + (chessboard_distances(inside, (width, height)), chessboard_distances(&outside, (width, height))) + } else { + (straight_distances(inside, (width, height)), straight_distances(&outside, (width, height))) + }; + inside + .par_iter() + .zip(to_inside.par_iter().zip(to_outside.par_iter())) + .map(|(inside, (to_inside, to_outside))| (if *inside { *to_outside } else { *to_inside } - EDGE_OFFSET).max(0.0)) + .collect() +} + +/// Every texel's straight-line distance (texels) to the nearest texel where `feature` holds; farther than the region when none does +fn straight_distances(feature: &[bool], (width, height): (usize, usize)) -> Vec { + // Squared distances, separable: along the rows, then along the columns of those + let far = ((width + height) as f32).powi(2); + let mut rows: Vec = feature.iter().map(|feature| if *feature { 0.0 } else { far }).collect(); + rows.par_chunks_mut(width.max(1)).for_each_init(DistanceEnvelope::default, |envelope, row| envelope.lower(row)); + let mut columns: Vec = (0..width * height).map(|at| rows.get((at % height.max(1)) * width + at / height.max(1)).copied().unwrap_or(far)).collect(); + columns.par_chunks_mut(height.max(1)).for_each_init(DistanceEnvelope::default, |envelope, column| envelope.lower(column)); + (0..width * height).map(|at| columns.get((at % width.max(1)) * height + at / width.max(1)).copied().unwrap_or(far).sqrt()).collect() +} + +/// Every texel's distance (texels, the larger of across and down) to the nearest texel where `feature` holds; farther than the region when none does +fn chessboard_distances(feature: &[bool], (width, height): (usize, usize)) -> Vec { + let far = (width + height) as f32; + let mut distances: Vec = feature.iter().map(|feature| if *feature { 0.0 } else { far }).collect(); + + // One pass down from the texels above and left, one up from those below and right + let step = |distances: &mut [f32], (x, y): (usize, usize), neighbours: [(isize, isize); 4]| { + let nearest = neighbours + .iter() + .filter_map(|(dx, dy)| { + let (neighbour_x, neighbour_y) = (x.checked_add_signed(*dx)?, y.checked_add_signed(*dy)?); + (neighbour_x < width && neighbour_y < height).then(|| distances.get(neighbour_y * width + neighbour_x).copied()).flatten() + }) + .fold(f32::MAX, f32::min); + if let Some(slot) = distances.get_mut(y * width + x) { + *slot = slot.min(nearest + 1.0); + } + }; + for y in 0..height { + for x in 0..width { + step(&mut distances, (x, y), [(-1, 0), (-1, -1), (0, -1), (1, -1)]); + } + } + for y in (0..height).rev() { + for x in (0..width).rev() { + step(&mut distances, (x, y), [(1, 0), (1, 1), (0, 1), (-1, 1)]); + } + } + distances +} + +/// For every texel, how far (a share of `reach` texels) the nearest texel of the shapes `inside` lies behind it against `direction`, if one is in reach +fn trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec> { + let steps = trail_steps((width, height), direction, reach); + + // Each row of shapes as bits, a row without one as no words: steps landing on it find nothing + let shapes: Vec> = inside.par_chunks(width.max(1)).map(row_bits).collect(); + + let mut distances = vec![None; width * height]; + distances.par_chunks_mut(width.max(1)).enumerate().for_each(|(y, row)| trail_row(row, y, &shapes, &steps)); + distances +} + +/// The texel steps back along a trail against `direction`, nearest first, each with its share of `reach`: texel coordinates are whole, so every texel takes the same steps +fn trail_steps((width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<(isize, isize, f32)> { + // Steps of one texel along the direction's longer axis visit every column (or row) the trail crosses, so no thin shape is stepped over + let longer_axis = direction[0].abs().max(direction[1].abs()); + let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 }; + let step = if samples > 0 { reach / samples as f32 } else { 0.0 }; + + let mut steps: Vec<(isize, isize, f32)> = Vec::new(); + for sample in 0..=samples { + let back = sample as f32 * step; + + // Rounded half up, so a whole texel coordinate added to it rounds the same; a NaN direction lands nowhere + let (across, down) = ((0.5 - direction[0] * back).floor(), (0.5 - direction[1] * back).floor()); + if !(across.is_finite() && down.is_finite()) { + break; + } + + // A step as long as the region leaves it from every texel, and never comes back in + let (across, down) = (across as isize, down as isize); + if across.unsigned_abs() >= width || down.unsigned_abs() >= height { + break; + } + + // Rounding puts several samples on one texel: the nearest counts + if steps.last().is_some_and(|(last_across, last_down, _)| (*last_across, *last_down) == (across, down)) { + continue; + } + steps.push((across, down, if reach > 0.0 { back / reach } else { 0.0 })); + } + steps +} + +/// A row of shapes as bits, [`u64::BITS`] texels a word; no words when it has none +fn row_bits(row: &[bool]) -> Vec { + if !row.contains(&true) { + return Vec::new(); + } + + let mut words = vec![0u64; row.len().div_ceil(WORD_BITS)]; + for (word, texels) in words.iter_mut().zip(row.chunks(WORD_BITS)) { + *word = texels.iter().enumerate().filter(|(_, inside)| **inside).fold(0, |bits, (bit, _)| bits | 1 << bit); + } + words +} + +/// Texels in a word of a row's bits +const WORD_BITS: usize = u64::BITS as usize; + +/// Row `y`'s trail distances into `row`: a step at a time, every texel the step brings onto a shape takes its share, unless an earlier step did +fn trail_row(row: &mut [Option], y: usize, shapes: &[Vec], steps: &[(isize, isize, f32)]) { + let width = row.len(); + let mut found = vec![0u64; width.div_ceil(WORD_BITS)]; + let mut unfound = width; + + // The last word's bits past the row's end are no texels + let last_word = found.len().saturating_sub(1); + let tail = width % WORD_BITS; + let last_word_texels = if tail > 0 { (1u64 << tail) - 1 } else { u64::MAX }; + + for (across, down, share) in steps { + // A step past the region's top or bottom leaves it for good + let Some(source) = y.checked_add_signed(*down).and_then(|source_y| shapes.get(source_y)) else { break }; + if source.is_empty() { + continue; + } + + for (word, found_word) in found.iter_mut().enumerate() { + let in_row = if word == last_word { last_word_texels } else { u64::MAX }; + let landed = bits_from(source, (word * WORD_BITS) as isize + across) & !*found_word & in_row; + *found_word |= landed; + + let mut remaining = landed; + while remaining != 0 { + let bit = remaining.trailing_zeros() as usize; + remaining &= remaining - 1; + if let Some(slot) = row.get_mut(word * WORD_BITS + bit) { + *slot = Some(*share); + } + unfound = unfound.saturating_sub(1); + } + } + + if unfound == 0 { + break; + } + } +} + +/// The [`WORD_BITS`] bits of row bits `source` from texel `start` on, none past either end +fn bits_from(source: &[u64], start: isize) -> u64 { + let bits = WORD_BITS as isize; + let (word, shift) = (start.div_euclid(bits), start.rem_euclid(bits) as u32); + let at = |index: isize| usize::try_from(index).ok().and_then(|index| source.get(index)).copied().unwrap_or(0); + let low = at(word) >> shift; + if shift == 0 { low } else { low | at(word + 1) << (u64::BITS - shift) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn distances_are_straight_or_chessboard() { + // One feature texel in the middle of a 5 × 5 region + let mut feature = vec![false; 25]; + feature[12] = true; + let straight = straight_distances(&feature, (5, 5)); + let chessboard = chessboard_distances(&feature, (5, 5)); + assert_eq!((straight[12], straight[13], chessboard[13]), (0.0, 1.0, 1.0)); + assert!((straight[0] - 8f32.sqrt()).abs() < 1e-5, "{}", straight[0]); + assert_eq!(chessboard[0], 2.0, "a corner is as far as its larger axis"); + let none = straight_distances(&[false; 4], (2, 2)); + assert!(none.iter().all(|distance| *distance >= 4.0), "no feature is beyond the region"); + } + + #[test] + fn distances_keep_rows_and_columns_apart_in_a_region_wider_than_tall() { + // One feature texel at column 1, row 0 of a 7 × 3 region + let (width, height) = (7, 3); + let mut feature = vec![false; width * height]; + feature[1] = true; + let straight = straight_distances(&feature, (width, height)); + let chessboard = chessboard_distances(&feature, (width, height)); + + let at = |x: usize, y: usize| y * width + x; + assert_eq!((straight[at(1, 0)], straight[at(6, 0)], straight[at(1, 2)]), (0.0, 5.0, 2.0)); + assert!((straight[at(6, 2)] - 29f32.sqrt()).abs() < 1e-5, "{}", straight[at(6, 2)]); + assert_eq!((chessboard[at(6, 0)], chessboard[at(0, 2)], chessboard[at(6, 2)]), (5.0, 2.0, 5.0)); + } + + #[test] + fn a_trail_finds_the_nearest_shape_behind_a_texel_as_a_share_of_its_reach() { + // A shape at column 0 of a 5 × 2 region; the trail runs towards +x, so a texel looks back towards -x + let (width, height) = (5, 2); + let inside: Vec = (0..width * height).map(|texel| texel % width == 0).collect(); + let trail = trail_distances(&inside, (width, height), [1.0, 0.0], 4.0); + + assert_eq!(trail[0], Some(0.0), "on the shape"); + assert_eq!(trail[2], Some(0.5), "two texels behind, half the reach"); + assert_eq!(trail[width + 4], Some(1.0), "at the reach's end"); + } + + #[test] + fn a_long_trail_steps_over_no_thin_shape() { + // A one-texel shape at column 0 of an 8 × 1 region, with a reach far longer than the region + let (width, height) = (8, 1); + let inside: Vec = (0..width * height).map(|texel| texel == 0).collect(); + let reach = 128.0; + + let trail = trail_distances(&inside, (width, height), [1.0, 0.0], reach); + + assert_eq!(trail[3], Some(3.0 / reach), "three texels behind"); + assert!(trail.iter().all(Option::is_some), "every texel behind the shape is in its trail: {trail:?}"); + } + + /// The trail as every texel walks it on its own, one sample at a time: what the shared steps must match + fn walked_trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec> { + let longer_axis = direction[0].abs().max(direction[1].abs()); + let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 }; + let step = if samples > 0 { reach / samples as f32 } else { 0.0 }; + (0..width * height) + .into_par_iter() + .map(|texel| { + let (x, y) = ((texel % width) as f32, (texel / width) as f32); + (0..=samples) + .map(|sample| { + let back = sample as f32 * step; + (back, (x - direction[0] * back).round(), (y - direction[1] * back).round()) + }) + .take_while(|(_, sample_x, sample_y)| *sample_x >= 0.0 && *sample_y >= 0.0 && (*sample_x as usize) < width && (*sample_y as usize) < height) + .find_map(|(back, sample_x, sample_y)| inside[sample_y as usize * width + sample_x as usize].then(|| back / reach)) + }) + .collect() + } + + #[test] + fn shared_trail_steps_find_what_each_texel_walking_its_own_finds() { + // About one texel in fifty a shape, in a region whose rows end part way through a word + // Small enough that the walk's float sums round as exactly as the shared steps (thousands of texels across, a near tie can round a texel over) + let (width, height) = (150, 97); + let mut seed = 12345u32; + let inside: Vec = (0..width * height) + .map(|_| { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + (seed >> 16) % 97 < 2 + }) + .collect(); + + for angle in [0.0, 17.0, 45.0, 90.0, 135.0, 200.0, 290.0, 333.0] { + for reach in [9.3, 60.0, 400.0] { + let direction = crate::eval::direction(angle); + + let shared = trail_distances(&inside, (width, height), direction, reach); + + let walked = walked_trail_distances(&inside, (width, height), direction, reach); + assert!(walked.iter().any(Option::is_some) && walked.iter().any(Option::is_none), "{angle}° {reach}: a field with texels in and out of reach"); + assert_eq!(shared, walked, "{angle}° reach {reach}"); + } + } + } +} diff --git a/crates/compose/src/slope_texel.rs b/crates/compose/src/slope_texel.rs new file mode 100644 index 00000000..0cbdd957 --- /dev/null +++ b/crates/compose/src/slope_texel.rs @@ -0,0 +1,45 @@ +//! What a Blur Slope filter reads for one texel: its source's slope, then the values downhill of it + +use texturecraft_core::{SlopeBlending, SourceSlopeBlur, SourceWarp}; + +use crate::eval::LINE_SAMPLES; +use crate::warp_source_sample::WarpSourceSample; +use crate::warp_texel::{Input, Sample, keep_extreme_read}; + +/// A source rising less than this across a texel is flat +const FLAT_STEEPNESS: f32 = 1e-6; + +/// Blur Slope `slope` at texel `(x, y)` (`res` texels across a UV tile, `comps` values a texel) into `acc`: the reads downhill of it, blended +pub(crate) fn slope_texel( + slope: &SourceSlopeBlur, + (x, y): (f32, f32), + (res, comps): (u32, usize), + acc: &mut [f32; 5], + (sample, input): (Sample<'_>, Input<'_>), +) { + let source = WarpSourceSample::new(&slope.source, slope.seed, (res, comps), (sample, input)); + let probe = SourceWarp::probe_texels(res); + let downhill = [source.at(x - probe, y) - source.at(x + probe, y), source.at(x, y - probe) - source.at(x, y + probe)]; + let steepness = downhill[0].hypot(downhill[1]); + + // A flat spot keeps its value + if steepness.is_nan() || steepness <= FLAT_STEEPNESS { + sample(x, y, acc); + return; + } + + let [dx, dy] = downhill.map(|rise| rise / steepness); + let reach = slope.move_texels(res); + let read_count = slope.samples((reach.ceil() as u32).clamp(1, LINE_SAMPLES.unsigned_abs())); + let step = reach / read_count as f32; + let along = (0..=read_count).map(|read| read as f32 * step); + if slope.blending == SlopeBlending::Blur { + for t in along { + sample(x + dx * t, y + dy * t, acc); + } + return; + } + + let reads = along.map(|t| (x + dx * t, y + dy * t)); + keep_extreme_read(reads, slope.blending == SlopeBlending::Max, comps, acc, sample); +} diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 29fd7115..dea9f8d6 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -7,9 +7,12 @@ use std::collections::BTreeMap; use texturecraft_compose::{ BelowCache, Composite, Inputs, MaskGray, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, }; +use texturecraft_core::project::ENV_RESOURCE_PREFIX; use texturecraft_core::{ BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, ContentsOffset, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet, + GrayscaleConversion, HeightMask, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, + TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; use texturecraft_texel::{TILE, TileImage, to_u16}; @@ -69,7 +72,7 @@ fn heavy_stack(f: &mut Fixture) -> LayerId { ); let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(effect(f, EffectKind::Generator(Generator::new(GeneratorKind::Position)))); - mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); + mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false }))); add(f, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(mask)); let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None); for b in f.project.layer_mut(group).unwrap().channels.values_mut() { @@ -83,7 +86,7 @@ fn heavy_stack(f: &mut Fixture) -> LayerId { f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, )); - blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0 }))); + blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0, wrap: false }))); let top = add(f, 0, LayerKind::Paint, Some(blurred)); let img = f.pixels.layer_mut(top, Channel::BaseColor, (RES, RES)); for y in 40..200 { @@ -248,7 +251,7 @@ fn generator_mask(f: &mut Fixture, kind: GeneratorKind, blur: Option) -> Ma let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(effect(f, EffectKind::Generator(g))); if let Some(radius) = blur { - mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius }))); + mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius, wrap: false }))); } mask } @@ -312,8 +315,8 @@ fn nested_stack(f: &mut Fixture) -> Nested { blend(f, g2_above, BlendMode::Overlay, 0.7); put(f, 0, Some(g2), LayerKind::Instance { source: base }, Some(Mask::new(MaskBackground::White))); let g1_above = put(f, 0, Some(g1), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Wood, 0.2, 0.8))]), None); - let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0 })); - let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0 })); + let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0, perceptive: false })); + let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0, wrap: false })); f.project.layer_mut(g1_above).unwrap().content_effects.extend([hsl, blur]); blend(f, g1_above, BlendMode::Screen, 0.5); let mask = generator_mask(f, GeneratorKind::Position, Some(30.0)); @@ -544,7 +547,7 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() { assert!(check_cached(&f, 0, top).is_empty(), "anchor readers evaluate everything"); // Behind a blur the cut reads the filtered field; before it, the unfiltered content - let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0 })); + let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0, wrap: false })); f.project.layer_mut(low).unwrap().content_effects.insert(0, blur); let blurred = reference(&f, 0); assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat"); @@ -572,12 +575,12 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { &mut f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, )); - slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 }))); + slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1, divider: 1 }))); let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope)); let top = add(&mut f, 0, LayerKind::Paint, None); paint_rect(&mut f, top, (30, 40), (150, 100), 0.4); let plain = reference(&f, 0); - let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3 })); + let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3, divider: 1 })); f.project.layer_mut(base).unwrap().content_effects.push(warp); let line = effect(&mut f, EffectKind::Filter(Filter::DirectionalBlur { radius: 40.0, angle: 30.0 })); f.project.layer_mut(streaks).unwrap().content_effects.push(line); @@ -671,6 +674,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap(); blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); + blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0, wrap: false }); let (images, baked) = (Default::default(), Default::default()); cache.ahead = Vec::new(); composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache)); @@ -709,7 +713,7 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { &mut fixture, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, )); - blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); + blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false }))); add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred)); // Keep the blurred layer visible under the hot layer @@ -958,22 +962,58 @@ fn flat_image(value: f32) -> std::sync::Arc { #[test] fn id_map_image_changes_invalidate_stack_key() { +fn filter_input_and_id_map_image_changes_invalidate_stack_key() { let mut fixture = fixture(); heavy_stack(&mut fixture); let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let conversion = GrayscaleConversion { custom_input: true, ..GrayscaleConversion::LIBRARY }; + let mut filter = effect(&mut fixture, EffectKind::Filter(Filter::GrayscaleConversion(conversion))); + filter.inputs.insert(ImageInput::CUSTOM_INPUT.id.into(), Source::image("input")); let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1); selection.id_map = Some("id".into()); let selection = effect(&mut fixture, EffectKind::ColorSelection(selection)); let layer = fixture.project.layer_mut(bottom_layer).unwrap(); + layer.content_effects.push(filter); layer.mask = Some(Mask::new(MaskBackground::White)); layer.mask.as_mut().unwrap().effects.push(selection); let mut images = texturecraft_compose::ImageStore::default(); + images.insert("input".into(), flat_image(0.1)); images.insert("id".into(), flat_image(0.1)); - let original = stack_key(&fixture, &images); images.insert("id".into(), flat_image(0.9)); + for name in ["input", "id"] { + let original = stack_key(&fixture, &images); + images.insert(name.into(), flat_image(0.9)); + assert!(stack_key(&fixture, &images) != original, "replacing the {name} image must invalidate the cache"); + } +} assert!(stack_key(&fixture, &images) != original, "replacing the id image must invalidate the cache"); +#[test] +fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() { + let mut fixture = fixture(); + heavy_stack(&mut fixture); + let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let mut images = texturecraft_compose::ImageStore::default(); + images.insert("sky".into(), flat_image(0.5)); + fixture.project.display.environment = format!("{ENV_RESOURCE_PREFIX}sky"); + let unlit = stack_key(&fixture, &images); + + fixture.project.display.env_rotation += 90.0; + assert_eq!(stack_key(&fixture, &images), unlit, "without Baked Lighting Environment the turn changes nothing"); + + let lighting = + Filter::EnvironmentLighting { horizontal: 0.0, vertical: 0.0, exposure: 0.0, height_intensity: 0.0, ambient_occlusion: 0.0, specular_occlusion: 0.0 }; + let lighting = effect(&mut fixture, EffectKind::Filter(lighting)); + fixture.project.layer_mut(bottom_layer).unwrap().content_effects.push(lighting); + let lit = stack_key(&fixture, &images); + fixture.project.display.env_rotation += 90.0; + let turned = stack_key(&fixture, &images); + assert!(turned != lit, "turning the environment invalidates the cache"); + assert_eq!(lit.changed_tiles(&turned), None, "and recomposites every tile"); + + images.insert("sky".into(), flat_image(0.9)); + assert!(stack_key(&fixture, &images) != turned, "replacing the environment image invalidates the cache"); } /// Where a blur lies on the layer inside the instanced folder @@ -988,6 +1028,7 @@ fn folder_of_blurred_clouds(f: &mut Fixture, ts: usize, folder: Option, let held = put(f, ts, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None); let clouds = put(f, ts, Some(held), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None); let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0 })); + let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false })); match blur_on { BlurOn::Content => f.project.layer_mut(clouds).unwrap().content_effects.push(blur), BlurOn::Mask => { diff --git a/crates/core/src/anisotropic_kuwahara.rs b/crates/core/src/anisotropic_kuwahara.rs new file mode 100644 index 00000000..6989a99a --- /dev/null +++ b/crates/core/src/anisotropic_kuwahara.rs @@ -0,0 +1,92 @@ +//! Anisotropic Kuwahara's settings: a painterly smoothing that follows the direction of the strokes + +use serde::{Deserialize, Serialize}; + +/// An Anisotropic Kuwahara filter: each texel takes the mean of the calmest sector of an ellipse turned along the local direction +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AnisotropicKuwahara { + /// Extract Direction Custom Input: the direction comes from the filter's Custom Input instead of the channel + pub custom_input: bool, + /// Texels at 2K the ellipse reaches (0..10) + pub radius: f32, + /// How much neighbouring sectors overlap (0 = hard sector edges) + pub smoothness: f32, + /// How strongly the calmest sector wins over the others (0.25..1) + pub sharpness: f32, + /// How far around a texel its direction is averaged, as a share of the radius + pub tensor_smoothness: f32, + /// How much the ellipse stretches along the direction where the direction is clear (0 = a circle) + pub anisotropy: f32, + /// Degrees the ellipse turns from the extracted direction + pub angle: f32, +} + +impl AnisotropicKuwahara { + /// A new Anisotropic Kuwahara + pub const LIBRARY: AnisotropicKuwahara = + AnisotropicKuwahara { custom_input: false, radius: 5.0, smoothness: 0.25, sharpness: 0.25, tensor_smoothness: 0.1, anisotropy: 1.0, angle: 0.0 }; + + /// The largest Radius, in texels at 2K + pub const MAX_RADIUS: f32 = 10.0; + + /// The least Sharpness + pub const MIN_SHARPNESS: f32 = 0.25; + + /// Sectors the ellipse is split into + pub const SECTORS: usize = 8; + + /// The sector weighing exponent at a Sharpness of 0 and of 1 (Sharpness stops at [`Self::MIN_SHARPNESS`], so the least it weighs with is 5.5) + const SHARPNESS_EXPONENT_MIN: f32 = 2.0; + const SHARPNESS_EXPONENT_MAX: f32 = 16.0; + + /// The sample falloff exponent at no Smoothness (1 at full Smoothness) + const SECTOR_EXPONENT_MAX: f32 = 16.0; + + /// How far around a texel its direction is read, as a share of the radius (Tensor Smoothness, 0..1) + pub fn tensor_reach(&self) -> f32 { + if self.tensor_smoothness.is_finite() { self.tensor_smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.tensor_smoothness } + } + + /// The exponent a sector's spread is weighed with: higher picks the calmest sector more sharply + pub fn sharpness_exponent(&self) -> f32 { + let sharpness = if self.sharpness.is_finite() { self.sharpness.clamp(Self::MIN_SHARPNESS, 1.0) } else { Self::LIBRARY.sharpness }; + Self::SHARPNESS_EXPONENT_MIN + sharpness * (Self::SHARPNESS_EXPONENT_MAX - Self::SHARPNESS_EXPONENT_MIN) + } + + /// How sharply a sample's weight falls off away from a sector's middle: smoother sectors overlap more + pub fn sector_exponent(&self) -> f32 { + let smoothness = if self.smoothness.is_finite() { self.smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.smoothness }; + 1.0 + (1.0 - smoothness) * (Self::SECTOR_EXPONENT_MAX - 1.0) + } + + /// The ellipse's semi-axes (along, across the direction) for `radius` texels where the direction is `clear` (0..1) + pub fn axes(&self, radius: f32, clear: f32) -> (f32, f32) { + let stretch = if self.anisotropy.is_finite() { self.anisotropy.clamp(0.0, 1.0) } else { Self::LIBRARY.anisotropy } * clear.clamp(0.0, 1.0); + (radius * (1.0 + stretch), radius / (1.0 + stretch)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_clear_direction_stretches_the_ellipse() { + let filter = AnisotropicKuwahara::LIBRARY; + assert_eq!(filter.axes(4.0, 0.0), (4.0, 4.0)); + assert_eq!(filter.axes(4.0, 1.0), (8.0, 2.0)); + assert_eq!(AnisotropicKuwahara { anisotropy: 0.0, ..filter }.axes(4.0, 1.0), (4.0, 4.0)); + assert!(AnisotropicKuwahara { sharpness: 1.0, ..filter }.sharpness_exponent() > filter.sharpness_exponent()); + assert!(AnisotropicKuwahara { smoothness: 1.0, ..filter }.sector_exponent() < filter.sector_exponent()); + } + + #[test] + fn sharpness_weighs_on_a_line_from_its_exponent_at_0_to_its_exponent_at_1() { + let at = |sharpness: f32| AnisotropicKuwahara { sharpness, ..AnisotropicKuwahara::LIBRARY }.sharpness_exponent(); + + assert_eq!(at(AnisotropicKuwahara::MIN_SHARPNESS), 5.5, "the least Sharpness, a quarter of the way along"); + assert_eq!(at(0.0), 5.5, "below the least, the least"); + assert_eq!(at(1.0), 16.0, "the most Sharpness weighs with the most exponent"); + } +} diff --git a/crates/core/src/bevel.rs b/crates/core/src/bevel.rs new file mode 100644 index 00000000..740a918c --- /dev/null +++ b/crates/core/src/bevel.rs @@ -0,0 +1,98 @@ +//! The Bevel filter's settings and the slope it gives a shape's edge + +use serde::{Deserialize, Serialize}; + +use crate::{BevelBlur, BevelCorner, SIZE_REFERENCE_RES}; + +/// Shapes (values at or above [`Bevel::EDGE`]) sloped at their edge: inwards for a negative distance, outwards for a positive one +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Bevel { + /// Reads past the texture's edges from the far side (Bevel Wrap) + pub wrap: bool, + /// How far the slope reaches from the edge, a fraction of the UV tile: inwards below 0, outwards above (−1..1) + pub distance: f32, + pub corner: BevelCorner, + /// How much the slope is blurred (0..5, [`Bevel::SMOOTHING_TEXELS`] texels at 2K each) + pub smoothing: f32, + pub blur: BevelBlur, +} + +impl Bevel { + /// The Bevel filter as the library adds it + pub const LIBRARY: Bevel = Bevel { wrap: false, distance: -0.1, corner: BevelCorner::Round, smoothing: 0.0, blur: BevelBlur::NonUniform }; + + /// Values at or above it are inside the shapes + pub const EDGE: f32 = 0.5; + + /// Texels at 2K a unit of Smoothing blurs over + pub const SMOOTHING_TEXELS: f32 = 4.0; + + /// The largest Smoothing + pub const SMOOTHING_MAX: f32 = 5.0; + + /// Whether the slope lies inside the shapes + pub fn inward(&self) -> bool { + self.distance <= 0.0 || self.distance.is_nan() + } + + /// How many texels the slope reaches at `res` texels across a UV tile + pub fn reach(&self, res: u32) -> f32 { + let distance = if self.distance.is_finite() { self.distance.abs().min(1.0) } else { 0.0 }; + distance * res as f32 + } + + /// How many texels the slope is blurred over at `res` texels across a UV tile + pub fn smoothing_texels(&self, res: u32) -> f32 { + let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 }; + smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES + } + + /// The slope (0..1) at a texel `edge` texels from the shapes' edge, inside them or not, rising from 0 at its foot to 1 at its top + pub fn slope(&self, inside: bool, edge: f32, reach: f32) -> f32 { + let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 }; + match (self.inward(), inside) { + (true, true) => along, + (false, false) => 1.0 - along, + (true, false) => 0.0, + (false, true) => 1.0, + } + } + + /// The result at a texel of `value`, inside the shapes or not, on `slope`: an inward slope scales the shapes, an outward one rises around them + pub fn apply(&self, inside: bool, value: f32, slope: f32) -> f32 { + match (self.inward(), inside) { + (true, true) => value * slope, + (false, false) => value.max(slope), + _ => value, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_negative_distance_slopes_inwards_and_a_positive_one_outwards() { + let inward = Bevel::LIBRARY; + assert_eq!(inward.reach(2048), 204.8); + assert_eq!((inward.slope(true, 0.0, 10.0), inward.slope(true, 5.0, 10.0), inward.slope(true, 20.0, 10.0)), (0.0, 0.5, 1.0)); + assert_eq!(inward.apply(true, 0.8, 0.5), 0.4, "inside, scaled down towards the edge"); + assert_eq!(inward.apply(false, 0.3, 0.0), 0.3, "outside untouched"); + let outward = Bevel { distance: 0.1, ..inward }; + assert_eq!((outward.slope(false, 0.0, 10.0), outward.slope(false, 5.0, 10.0), outward.slope(false, 20.0, 10.0)), (1.0, 0.5, 0.0)); + assert_eq!(outward.apply(false, 0.2, 0.5), 0.5, "rises around the shapes"); + assert_eq!(outward.apply(true, 0.7, 1.0), 0.7, "inside untouched"); + } + + #[test] + fn hostile_settings_stay_in_range() { + let bevel = Bevel { distance: f32::NAN, smoothing: f32::INFINITY, ..Bevel::LIBRARY }; + assert_eq!((bevel.reach(2048), bevel.smoothing_texels(2048)), (0.0, 0.0)); + assert_eq!(bevel.slope(true, 3.0, 0.0), 1.0, "no reach leaves the shapes whole"); + let excessive = Bevel { distance: -9.0, smoothing: 9.0, ..bevel }; + assert_eq!(excessive.reach(1024), 1024.0); + assert_eq!(excessive.smoothing_texels(2048), Bevel::SMOOTHING_MAX * Bevel::SMOOTHING_TEXELS, "smoothing stops at its largest"); + } +} diff --git a/crates/core/src/bevel_blur.rs b/crates/core/src/bevel_blur.rs new file mode 100644 index 00000000..7d5e9cf3 --- /dev/null +++ b/crates/core/src/bevel_blur.rs @@ -0,0 +1,35 @@ +//! How a Bevel's Smoothing spreads over its slope + +use serde::{Deserialize, Serialize}; + +/// Where a Bevel's Smoothing blurs its slope +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BevelBlur { + /// Sharp at the slope's foot, smoother towards its top + #[default] + NonUniform, + /// The same blur over the whole slope + Uniform, +} + +impl BevelBlur { + /// Every blur mode, in the order a switch shows them + pub const ALL: [BevelBlur; 2] = [BevelBlur::NonUniform, BevelBlur::Uniform]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + BevelBlur::NonUniform => "Non-Uniform", + BevelBlur::Uniform => "Uniform", + } + } + + /// The id `effect.set {blurMode}` takes + pub fn id(self) -> &'static str { + match self { + BevelBlur::NonUniform => "nonUniform", + BevelBlur::Uniform => "uniform", + } + } +} diff --git a/crates/core/src/bevel_corner.rs b/crates/core/src/bevel_corner.rs new file mode 100644 index 00000000..fb26e355 --- /dev/null +++ b/crates/core/src/bevel_corner.rs @@ -0,0 +1,35 @@ +//! The shape a Bevel gives the corners it rounds off + +use serde::{Deserialize, Serialize}; + +/// How a Bevel measures the distance from a shape's edge, which shows at its corners +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BevelCorner { + /// Straight-line distance: corners the bevel goes around come out round + #[default] + Round, + /// The larger of the horizontal and vertical distance: corners stay square + Angular, +} + +impl BevelCorner { + /// Every corner type, in the order a switch shows them + pub const ALL: [BevelCorner; 2] = [BevelCorner::Round, BevelCorner::Angular]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + BevelCorner::Round => "Round", + BevelCorner::Angular => "Angular", + } + } + + /// The id `effect.set {cornerType}` takes + pub fn id(self) -> &'static str { + match self { + BevelCorner::Round => "round", + BevelCorner::Angular => "angular", + } + } +} diff --git a/crates/core/src/bevel_direction.rs b/crates/core/src/bevel_direction.rs new file mode 100644 index 00000000..013e4c7b --- /dev/null +++ b/crates/core/src/bevel_direction.rs @@ -0,0 +1,39 @@ +//! Which side of a shape's edge a Bevel Smooth ramps on + +use serde::{Deserialize, Serialize}; + +/// The side of the edge a Bevel Smooth's ramp lies on +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BevelDirection { + /// From the edge outwards, the shapes staying white + #[default] + Out, + /// From the edge inwards, around the shapes staying black + In, + /// Across the edge, mid gray on it + InOut, +} + +impl BevelDirection { + /// Every direction, in the order a switch shows them + pub const ALL: [BevelDirection; 3] = [BevelDirection::Out, BevelDirection::In, BevelDirection::InOut]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + BevelDirection::Out => "Out", + BevelDirection::In => "In", + BevelDirection::InOut => "In/Out", + } + } + + /// The id `effect.set {direction}` takes + pub fn id(self) -> &'static str { + match self { + BevelDirection::Out => "out", + BevelDirection::In => "in", + BevelDirection::InOut => "inOut", + } + } +} diff --git a/crates/core/src/bevel_smooth.rs b/crates/core/src/bevel_smooth.rs new file mode 100644 index 00000000..6bf665f3 --- /dev/null +++ b/crates/core/src/bevel_smooth.rs @@ -0,0 +1,117 @@ +//! The Bevel Smooth filter's settings and the ramp it draws from a shape's edge + +use serde::{Deserialize, Serialize}; + +use crate::{BevelDirection, RampCurve, SIZE_REFERENCE_RES, at_or_above_threshold, finite_unit}; + +/// A smooth ramp from the edge of the shapes (values at or above `threshold`), outwards, inwards or across it +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BevelSmooth { + pub direction: BevelDirection, + /// How far the ramp reaches from the edge, a fraction of the UV tile (0..0.3) + pub distance: f32, + /// How much the ramp is blurred (0..10, [`BevelSmooth::SMOOTHING_TEXELS`] texels at 2K each) + pub smoothing: f32, + /// Moves the ramp up or down before its curve (−1..1) + pub curve_offset: f32, + /// Bends the ramp: below 0 it rises later, above 0 sooner (−1..1) + pub curve_shape: f32, + /// Values at or above it are inside the shapes (Mask Threshold, 0..1) + pub threshold: f32, + /// Scales the distance (Distance Map Multiplier, 0..1) + pub multiplier: f32, + /// Reads past the texture's edges from the far side (Bevel Wrap) + pub wrap: bool, +} + +impl BevelSmooth { + /// The Bevel Smooth filter as the library adds it + pub const LIBRARY: BevelSmooth = BevelSmooth { + direction: BevelDirection::Out, + distance: 0.1, + smoothing: 1.0, + curve_offset: 0.0, + curve_shape: 0.0, + threshold: 0.5, + multiplier: 1.0, + wrap: false, + }; + + /// Texels at 2K a unit of Smoothing blurs over + pub const SMOOTHING_TEXELS: f32 = 2.0; + + /// The largest Smoothing + pub const SMOOTHING_MAX: f32 = 10.0; + + /// Whether `value` is inside the shapes + pub fn inside(&self, value: f32) -> bool { + at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold) + } + + /// How many texels the ramp reaches at `res` texels across a UV tile + pub fn reach(&self, res: u32) -> f32 { + finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32 + } + + /// How many texels the ramp is blurred over at `res` texels across a UV tile + pub fn smoothing_texels(&self, res: u32) -> f32 { + let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 }; + smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES + } + + /// The curve the ramp takes (Curve Offset and Curve Shape), worked out once per filter + pub fn curve(&self) -> RampCurve { + RampCurve::new(self.curve_offset, self.curve_shape) + } + + /// The ramp at a texel `edge` texels from the shapes' edge, inside them or not, bent by [`BevelSmooth::curve`] + pub fn value(&self, curve: RampCurve, inside: bool, edge: f32, reach: f32) -> f32 { + let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 }; + let curved = curve.apply(along); + match (self.direction, inside) { + (BevelDirection::Out, true) => 1.0, + (BevelDirection::Out, false) => 1.0 - curved, + (BevelDirection::In, true) => curved, + (BevelDirection::In, false) => 0.0, + (BevelDirection::InOut, true) => 0.5 + 0.5 * curved, + (BevelDirection::InOut, false) => 0.5 - 0.5 * curved, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The ramp with the curve worked out as the filter does + fn ramp(filter: BevelSmooth, inside: bool, edge: f32, reach: f32) -> f32 { + filter.value(filter.curve(), inside, edge, reach) + } + + #[test] + fn the_ramp_lies_on_its_direction_side() { + let out = BevelSmooth::LIBRARY; + assert_eq!(out.reach(2048), 204.8); + assert!(out.inside(0.5) && !out.inside(0.49)); + assert_eq!((ramp(out, true, 3.0, 10.0), ramp(out, false, 0.0, 10.0), ramp(out, false, 5.0, 10.0), ramp(out, false, 20.0, 10.0)), (1.0, 1.0, 0.5, 0.0)); + let inward = BevelSmooth { direction: BevelDirection::In, ..out }; + assert_eq!((ramp(inward, false, 3.0, 10.0), ramp(inward, true, 5.0, 10.0), ramp(inward, true, 20.0, 10.0)), (0.0, 0.5, 1.0)); + let both = BevelSmooth { direction: BevelDirection::InOut, ..out }; + assert_eq!( + (ramp(both, true, 0.0, 10.0), ramp(both, false, 0.0, 10.0), ramp(both, true, 10.0, 10.0), ramp(both, false, 10.0, 10.0)), + (0.5, 0.5, 1.0, 0.0) + ); + } + + #[test] + fn curve_offset_and_shape_bend_the_ramp() { + let inward = BevelSmooth { direction: BevelDirection::In, ..BevelSmooth::LIBRARY }; + assert_eq!(ramp(BevelSmooth { curve_offset: 0.25, ..inward }, true, 5.0, 10.0), 0.75); + assert!(ramp(BevelSmooth { curve_shape: 0.5, ..inward }, true, 5.0, 10.0) > 0.5, "rises sooner"); + assert!(ramp(BevelSmooth { curve_shape: -0.5, ..inward }, true, 5.0, 10.0) < 0.5, "rises later"); + assert_eq!(BevelSmooth { multiplier: 0.5, ..inward }.reach(2048), 102.4); + let hostile = BevelSmooth { distance: f32::NAN, curve_offset: f32::NAN, curve_shape: f32::INFINITY, threshold: f32::NAN, ..inward }; + assert_eq!((hostile.reach(2048), ramp(hostile, true, 1.0, 0.0)), (0.0, 1.0)); + } +} diff --git a/crates/core/src/conversion_mode.rs b/crates/core/src/conversion_mode.rs new file mode 100644 index 00000000..5817373c --- /dev/null +++ b/crates/core/src/conversion_mode.rs @@ -0,0 +1,63 @@ +//! How Grayscale Conversion turns a color into gray + +use serde::{Deserialize, Serialize}; + +use crate::GrayscaleMode; + +/// The gray Grayscale Conversion reads from a color: a [`GrayscaleMode`], or its own weights per component +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ConversionMode { + /// Halfway between the lightest and darkest component + Desaturation, + /// Red, Green, Blue and Alpha times their weights, summed + #[default] + ChannelsWeights, + /// The components' mean + Average, + /// The lightest component + Max, + /// The darkest component + Min, +} + +impl ConversionMode { + /// Every mode, in the order a list shows them + pub const ALL: [ConversionMode; 5] = + [ConversionMode::Desaturation, ConversionMode::ChannelsWeights, ConversionMode::Average, ConversionMode::Max, ConversionMode::Min]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + ConversionMode::ChannelsWeights => "Channels Weights", + other => other.mode().map_or("", GrayscaleMode::label), + } + } + + /// The id `effect.set {mode}` takes + pub fn id(self) -> &'static str { + match self { + ConversionMode::ChannelsWeights => "channelsWeights", + other => other.mode().map_or("", GrayscaleMode::id), + } + } + + /// The gray of straight color `rgb` with coverage `alpha`, `weights` for Red, Green, Blue and Alpha + pub fn gray(self, rgb: [f32; 3], alpha: f32, weights: [f32; 4]) -> f32 { + match self.mode() { + Some(mode) => mode.gray(rgb), + None => rgb[0] * weights[0] + rgb[1] * weights[1] + rgb[2] * weights[2] + alpha * weights[3], + } + } + + /// The gradient's grayscale mode this one matches (None for Channels Weights) + fn mode(self) -> Option { + match self { + ConversionMode::Desaturation => Some(GrayscaleMode::Desaturation), + ConversionMode::ChannelsWeights => None, + ConversionMode::Average => Some(GrayscaleMode::Average), + ConversionMode::Max => Some(GrayscaleMode::Max), + ConversionMode::Min => Some(GrayscaleMode::Min), + } + } +} diff --git a/crates/core/src/curve_preset.rs b/crates/core/src/curve_preset.rs new file mode 100644 index 00000000..97d843c4 --- /dev/null +++ b/crates/core/src/curve_preset.rs @@ -0,0 +1,142 @@ +//! The shapes Gradient Curve remaps values through + +use serde::{Deserialize, Serialize}; + +use crate::layer::smoothstep; + +/// Stairs climbs in this many flat steps +const STAIRS_STEPS: f32 = 4.0; + +/// Triangular rises and falls this many times +const TRIANGULAR_TEETH: f32 = 2.0; + +/// A remap curve from 0..1 onto 0..1 +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CurvePreset { + /// A quarter circle: rises fast, then flattens + #[default] + Round, + /// A quarter circle the other way: flat, then rises fast + Pinch, + /// Four flat steps + Stairs, + EaseOut, + Ease, + EaseIn, + /// Up to the middle and back down, rounded at the top + PeakOut, + /// Up to the middle and back down in straight lines + Peak, + /// Up to the middle and back down, pointed at the top + PeakIn, + /// Half a sine wave + Bump, + /// Two humps + DoubleBump, + /// Two straight teeth + Triangular, +} + +impl CurvePreset { + /// Every preset, in the order the Preset list shows them + pub const ALL: [CurvePreset; 12] = [ + CurvePreset::Round, + CurvePreset::Pinch, + CurvePreset::Stairs, + CurvePreset::EaseOut, + CurvePreset::Ease, + CurvePreset::EaseIn, + CurvePreset::PeakOut, + CurvePreset::Peak, + CurvePreset::PeakIn, + CurvePreset::Bump, + CurvePreset::DoubleBump, + CurvePreset::Triangular, + ]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + CurvePreset::Round => "Round", + CurvePreset::Pinch => "Pinch", + CurvePreset::Stairs => "Stairs", + CurvePreset::EaseOut => "Ease Out", + CurvePreset::Ease => "Ease", + CurvePreset::EaseIn => "Ease In", + CurvePreset::PeakOut => "Peak Out", + CurvePreset::Peak => "Peak", + CurvePreset::PeakIn => "Peak In", + CurvePreset::Bump => "Bump", + CurvePreset::DoubleBump => "Double Bump", + CurvePreset::Triangular => "Triangular", + } + } + + /// The id `effect.set {preset}` takes + pub fn id(self) -> &'static str { + match self { + CurvePreset::Round => "round", + CurvePreset::Pinch => "pinch", + CurvePreset::Stairs => "stairs", + CurvePreset::EaseOut => "easeOut", + CurvePreset::Ease => "ease", + CurvePreset::EaseIn => "easeIn", + CurvePreset::PeakOut => "peakOut", + CurvePreset::Peak => "peak", + CurvePreset::PeakIn => "peakIn", + CurvePreset::Bump => "bump", + CurvePreset::DoubleBump => "doubleBump", + CurvePreset::Triangular => "triangular", + } + } + + /// The curve at `t` (clamped to 0..1; a non-finite `t` reads 0) + pub fn at(self, t: f32) -> f32 { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + let peak = 1.0 - (2.0 * t - 1.0).abs(); + let y = match self { + CurvePreset::Round => (1.0 - (1.0 - t) * (1.0 - t)).sqrt(), + CurvePreset::Pinch => 1.0 - (1.0 - t * t).sqrt(), + CurvePreset::Stairs => ((t * STAIRS_STEPS).floor() / (STAIRS_STEPS - 1.0)).min(1.0), + CurvePreset::EaseOut => 1.0 - (1.0 - t) * (1.0 - t), + CurvePreset::Ease => smoothstep(0.0, 1.0, t), + CurvePreset::EaseIn => t * t, + CurvePreset::PeakOut => peak.sqrt(), + CurvePreset::Peak => peak, + CurvePreset::PeakIn => peak * peak, + CurvePreset::Bump => (std::f32::consts::PI * t).sin(), + CurvePreset::DoubleBump => (2.0 * std::f32::consts::PI * t).sin().abs(), + CurvePreset::Triangular => 1.0 - ((2.0 * TRIANGULAR_TEETH * t) % 2.0 - 1.0).abs(), + }; + y.clamp(0.0, 1.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Samples across 0..1 that every curve is read at + const SAMPLES: usize = 64; + + #[test] + fn every_preset_stays_in_range_and_reads_a_non_finite_t_as_0() { + for preset in CurvePreset::ALL { + let values: Vec = (0..=SAMPLES).map(|i| preset.at(i as f32 / SAMPLES as f32)).collect(); + assert!(values.iter().all(|value| (0.0..=1.0).contains(value)), "{}", preset.id()); + assert_eq!(preset.at(f32::NAN), preset.at(0.0), "{}", preset.id()); + assert_eq!(preset.at(f32::INFINITY), preset.at(0.0), "{}", preset.id()); + } + } + + #[test] + fn stairs_has_four_levels_and_triangular_two_teeth() { + let mut levels: Vec = (0..=SAMPLES).map(|i| CurvePreset::Stairs.at(i as f32 / SAMPLES as f32)).collect(); + levels.dedup(); + assert_eq!(levels, [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]); + + let triangular = |t: f32| CurvePreset::Triangular.at(t); + assert_eq!([triangular(0.0), triangular(0.25), triangular(0.5), triangular(0.75), triangular(1.0)], [0.0, 1.0, 0.0, 1.0, 0.0]); + } +} diff --git a/crates/core/src/directional_distance.rs b/crates/core/src/directional_distance.rs new file mode 100644 index 00000000..0099a483 --- /dev/null +++ b/crates/core/src/directional_distance.rs @@ -0,0 +1,59 @@ +//! The Directional Distance filter's settings and the trail it draws from the shapes + +use serde::{Deserialize, Serialize}; + +use crate::finite_unit; + +/// A trail fading away from the shapes (values at or above [`DirectionalDistance::EDGE`]) towards `angle` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DirectionalDistance { + /// How far the trail reaches, a fraction of the UV tile (0..0.3) + pub distance: f32, + /// Where the trail runs to, in degrees counterclockwise from the right (270 runs down) + pub angle: f32, + /// Hardens the trail's fade (0..1) + pub contrast: f32, + /// Scales the distance (Distance Map Multiplier, 0..1) + pub multiplier: f32, +} + +impl DirectionalDistance { + /// The Directional Distance filter as the library adds it + pub const LIBRARY: DirectionalDistance = DirectionalDistance { distance: 0.1, angle: 270.0, contrast: 0.0, multiplier: 1.0 }; + + /// Values at or above it are inside the shapes + pub const EDGE: f32 = 0.5; + + /// The most contrast reaches: a hard step, kept off a division by zero + const HARDEST: f32 = 0.99; + + /// How many texels the trail reaches at `res` texels across a UV tile + pub fn reach(&self, res: u32) -> f32 { + finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32 + } + + /// The trail where the nearest shape behind a texel is `along` of the reach away (0 on a shape), or none is in reach + pub fn value(&self, along: Option) -> f32 { + let Some(along) = along.filter(|along| along.is_finite()) else { return 0.0 }; + let fade = 1.0 - along.clamp(0.0, 1.0); + let contrast = if self.contrast.is_finite() { self.contrast.clamp(0.0, Self::HARDEST) } else { 0.0 }; + (0.5 + (fade - 0.5) / (1.0 - contrast)).clamp(0.0, 1.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_trail_fades_with_distance_and_contrast_hardens_it() { + let trail = DirectionalDistance::LIBRARY; + assert_eq!(trail.reach(2048), 204.8); + assert_eq!((trail.value(Some(0.0)), trail.value(Some(0.25)), trail.value(None)), (1.0, 0.75, 0.0)); + let hard = DirectionalDistance { contrast: 0.5, ..trail }; + assert_eq!((hard.value(Some(0.25)), hard.value(Some(0.8))), (1.0, 0.0)); + let hostile = DirectionalDistance { distance: f32::NAN, contrast: f32::INFINITY, multiplier: -1.0, ..trail }; + assert_eq!((hostile.reach(2048), hostile.value(Some(f32::NAN))), (0.0, 0.0)); + } +} diff --git a/crates/core/src/directional_light.rs b/crates/core/src/directional_light.rs new file mode 100644 index 00000000..429a78b7 --- /dev/null +++ b/crates/core/src/directional_light.rs @@ -0,0 +1,31 @@ +//! One of Baked Lighting Stylized's extra lights + +use serde::{Deserialize, Serialize}; + +/// A light from `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees), of strength `intensity` in `color` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct DirectionalLight { + pub azimuth: f32, + pub elevation: f32, + pub intensity: f32, + pub color: [f32; 3], +} + +impl DirectionalLight { + /// An unlit white light from `azimuth`, 45 degrees up + pub const fn off(azimuth: f32) -> DirectionalLight { + DirectionalLight { azimuth, elevation: 45.0, intensity: 0.0, color: [1.0; 3] } + } + + /// The unit direction toward the light + pub fn direction(&self) -> [f32; 3] { + toward(self.azimuth, self.elevation) + } +} + +/// The unit direction toward a light at `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees) +fn toward(azimuth: f32, elevation: f32) -> [f32; 3] { + let (sin_azimuth, cos_azimuth) = azimuth.to_radians().sin_cos(); + let (sin_elevation, cos_elevation) = elevation.to_radians().sin_cos(); + [cos_elevation * sin_azimuth, sin_elevation, cos_elevation * cos_azimuth] +} diff --git a/crates/core/src/gradient_input.rs b/crates/core/src/gradient_input.rs new file mode 100644 index 00000000..12f99b20 --- /dev/null +++ b/crates/core/src/gradient_input.rs @@ -0,0 +1,151 @@ +//! Gradient's Input Transformation: how a texel becomes the position it reads on the ramp + +use serde::{Deserialize, Serialize}; + +use crate::finite_unit; +use crate::grayscale_mode::GrayscaleMode; + +/// Full contrast stays a finite step instead of a division by zero +const MIN_STEEPNESS: f32 = 1e-3; + +/// The balance that leaves the gray as it is +pub(crate) const NEUTRAL_BALANCE: f32 = 0.5; + +/// The gray, blurred, balanced, contrasted and maybe inverted value a gradient looks up +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct GradientInput { + /// How a color becomes gray (masks and scalar channels are gray already) + pub mode: GrayscaleMode, + /// Blurs the gray before the lookup, in texels at 2K (0..16) + pub blur: f32, + /// Shifts the gray: above 0.5 lighter, below darker + pub balance: f32, + /// Steepens the gray around its middle: 1 is a hard step + pub contrast: f32, + pub invert: bool, +} + +impl Default for GradientInput { + /// What gradients read in projects saved before the Input Transformation: luma, untouched + fn default() -> Self { + GradientInput { mode: GrayscaleMode::Luma, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false } + } +} + +impl GradientInput { + /// The library's starting transformation: the average of the components, untouched + pub const LIBRARY: GradientInput = GradientInput { mode: GrayscaleMode::Average, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false }; + + /// Whether it reads gradients as projects saved before it did (skipped when saving) + pub fn is_unchanged(&self) -> bool { + *self == GradientInput::default() + } + + /// The ramp position of gray `x` + pub fn shape(&self, x: f32) -> f32 { + // Left as it is, the gray reaches the ramp bit for bit as projects saved before read it (the ramp clamps it) + if self.balance == NEUTRAL_BALANCE && self.contrast == 0.0 && !self.invert { + return x; + } + + shape_gray(x, self.balance, self.contrast, self.invert) + } +} + +/// Gray `x` balanced (0.5 keeps it), contrasted around mid gray (0 keeps it, 1 is a step at 0.5) and maybe inverted, in 0..1 +pub fn shape_gray(x: f32, balance: f32, contrast: f32, invert: bool) -> f32 { + let balanced = finite_unit(x) + finite_unit(balance) - NEUTRAL_BALANCE; + let steep = (1.0 - finite_unit(contrast)).max(MIN_STEEPNESS); + let shaped = finite_unit((balanced - 0.5) / steep + 0.5); + if invert { 1.0 - shaped } else { shaped } +} + +/// A ramp stop's place and color +type Stop = (f32, [f32; 3]); + +/// The color at `t` on a ramp of `colors` placed at `positions` (each 0..1, evenly spaced where missing), blended in linear or sRGB +pub fn ramp(colors: &[[f32; 3]], positions: &[f32], linear: bool, t: f32) -> Option<[f32; 3]> { + let last = colors.len().checked_sub(1)?; + let even = |index: usize| if last == 0 { 0.0 } else { index as f32 / last as f32 }; + let stops = colors + .iter() + .enumerate() + .map(|(index, color)| (positions.get(index).copied().filter(|p| p.is_finite()).unwrap_or_else(|| even(index)).clamp(0.0, 1.0), *color)); + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + + // The stops each side of `t` without sorting them, per texel: the last placed at or before it and the first placed after it + let (mut before, mut after): (Option, Option) = (None, None); + for (position, color) in stops { + if position <= t { + if before.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_ge()) { + before = Some((position, color)); + } + } else if after.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_lt()) { + after = Some((position, color)); + } + } + let ((before_place, before_color), (after_place, after_color)) = match (before, after) { + (Some(before), Some(after)) => (before, after), + (Some(only), None) | (None, Some(only)) => (only, only), + (None, None) => return None, + }; + + let share = if after_place > before_place { ((t - before_place) / (after_place - before_place)).clamp(0.0, 1.0) } else { 0.0 }; + Some(if linear { + std::array::from_fn(|k| before_color[k] + (after_color[k] - before_color[k]) * share) + } else { + std::array::from_fn(|k| { + let (before, after) = (linear_to_srgb(before_color[k]), linear_to_srgb(after_color[k])); + srgb_to_linear(before + (after - before) * share) + }) + }) +} + +// A copy of texturecraft_texel's: texel and core are both layer 0, so core cannot use it + +/// sRGB transfer of a linear component +pub(crate) fn linear_to_srgb(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +/// Linear value of an sRGB component +pub(crate) fn srgb_to_linear(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_ramp_reads_its_stops_in_place_order_whatever_their_list_order() { + let (black, gray, white) = ([0.0; 3], [0.5; 3], [1.0; 3]); + let colors = [white, black, gray]; + let positions = [1.0, 0.0, 0.5]; + + let quarter = ramp(&colors, &positions, true, 0.25); + let ends = (ramp(&colors, &positions, true, 0.0), ramp(&colors, &positions, true, 1.0)); + let past_one_stop = ramp(&[gray, white], &[0.5, 0.5], true, 0.25); + + assert_eq!(quarter, Some([0.25; 3])); + assert_eq!(ends, (Some(black), Some(white))); + assert_eq!(past_one_stop, Some(gray), "before the first stop, its color"); + assert_eq!(ramp(&[], &[], true, 0.5), None); + } + + #[test] + fn an_untouched_input_passes_every_gray_on_bit_for_bit() { + const SAMPLES: u16 = 1000; + let untouched = [GradientInput::default(), GradientInput::LIBRARY]; + let grays = (0..=SAMPLES).map(|step| f32::from(step) / f32::from(SAMPLES)).chain([-0.25, 1.5]); + + for input in untouched { + for gray in grays.clone() { + assert_eq!(input.shape(gray).to_bits(), gray.to_bits(), "{input:?} at {gray}"); + } + } + } +} diff --git a/crates/core/src/grayscale_conversion.rs b/crates/core/src/grayscale_conversion.rs new file mode 100644 index 00000000..3f186a7d --- /dev/null +++ b/crates/core/src/grayscale_conversion.rs @@ -0,0 +1,90 @@ +//! Grayscale Conversion's settings: which gray it reads and how it shapes it + +use serde::{Deserialize, Serialize}; + +use crate::blend::lum; +use crate::gradient_input::{NEUTRAL_BALANCE, shape_gray}; +use crate::layer::per_unit; +use crate::{ChannelKind, ConversionMode}; + +/// A Grayscale Conversion filter: the gray of the current channel (or of its Custom Input), balanced, contrasted and maybe inverted +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GrayscaleConversion { + /// Channel Input Custom Input: the gray of the filter's Custom Input instead of the channel's + pub custom_input: bool, + pub invert: bool, + pub balance: f32, + pub contrast: f32, + pub mode: ConversionMode, + /// Channels Weights' Red, Green, Blue and Alpha + pub weights: [f32; 4], +} + +impl GrayscaleConversion { + /// A new Grayscale Conversion: a third of each color component, alpha left out + pub const LIBRARY: GrayscaleConversion = GrayscaleConversion { + custom_input: false, + invert: false, + balance: NEUTRAL_BALANCE, + contrast: 0.0, + mode: ConversionMode::ChannelsWeights, + weights: [0.33, 0.33, 0.33, 0.0], + }; + + /// The settings a Grayscale filter saved before them takes on its first edit: its luminance weights, so it looks the same + pub fn of_luminance() -> GrayscaleConversion { + let [red, green, blue] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]].map(lum); + GrayscaleConversion { weights: [red, green, blue, 0.0], ..Self::LIBRARY } + } + + /// The shaped gray of straight color `rgb` with coverage `alpha` + pub fn gray(&self, rgb: [f32; 3], alpha: f32) -> f32 { + shape_gray(self.mode.gray(rgb, alpha, self.weights), self.balance, self.contrast, self.invert) + } + + /// `v` of a `kind` channel (coverage `alpha`) or `custom_input` turned gray: colors gray, scalar and signed in their range, normals as they are + pub fn channel_value(&self, kind: ChannelKind, v: [f32; 3], custom_input: Option<[f32; 3]>, alpha: f32) -> [f32; 3] { + match (kind, custom_input) { + (ChannelKind::NormalMap, _) => v, + (ChannelKind::Color, None) => [self.gray(v, alpha); 3], + (ChannelKind::Color, Some(input)) => [self.gray(input, alpha); 3], + (_, None) => per_unit(kind, v, |x| self.gray([x; 3], alpha)), + (_, Some(input)) => per_unit(kind, v, |_| self.gray(input, alpha)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_saved_grayscale_keeps_its_luminance() { + let color = [0.8, 0.3, 0.1]; + assert!((GrayscaleConversion::of_luminance().gray(color, 1.0) - lum(color)).abs() < 1e-5); + } + + #[test] + fn weights_balance_contrast_and_invert_shape_the_gray() { + let only_red = GrayscaleConversion { weights: [1.0, 0.0, 0.0, 0.0], ..GrayscaleConversion::LIBRARY }; + assert!((only_red.gray([0.6, 1.0, 1.0], 1.0) - 0.6).abs() < 1e-6); + let alpha = GrayscaleConversion { weights: [0.0, 0.0, 0.0, 1.0], ..GrayscaleConversion::LIBRARY }; + assert!((alpha.gray([1.0; 3], 0.25) - 0.25).abs() < 1e-6, "Alpha weighs the coverage"); + let inverted = GrayscaleConversion { invert: true, mode: ConversionMode::Max, ..GrayscaleConversion::LIBRARY }; + assert!((inverted.gray([0.2, 0.7, 0.1], 1.0) - 0.3).abs() < 1e-6); + let contrasted = GrayscaleConversion { contrast: 1.0, mode: ConversionMode::Average, ..GrayscaleConversion::LIBRARY }; + assert_eq!(contrasted.gray([0.6; 3], 1.0), 1.0); + } + + #[test] + fn only_colors_turn_gray() { + let conversion = GrayscaleConversion::LIBRARY; + + let height = conversion.channel_value(ChannelKind::Signed, [-0.6; 3], None, 1.0); + let normal = conversion.channel_value(ChannelKind::NormalMap, [0.2, 0.7, 0.9], None, 1.0); + + assert!(height.iter().all(|x| (x + 0.6).abs() < 0.02), "a signed height keeps its sign: {height:?}"); + assert_eq!(normal, [0.2, 0.7, 0.9]); + } +} diff --git a/crates/core/src/grayscale_mode.rs b/crates/core/src/grayscale_mode.rs new file mode 100644 index 00000000..53d06ec6 --- /dev/null +++ b/crates/core/src/grayscale_mode.rs @@ -0,0 +1,58 @@ +//! How a color becomes the gray a gradient looks up + +use serde::{Deserialize, Serialize}; + +/// The gray a color reads as, before a gradient maps it +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GrayscaleMode { + /// Halfway between the lightest and darkest component + Desaturation, + /// Weighted by how bright each component looks (what gradients read in projects saved before the modes) + #[default] + Luma, + /// The components' mean + Average, + /// The lightest component + Max, + /// The darkest component + Min, +} + +impl GrayscaleMode { + /// Every mode, in the order a list shows them + pub const ALL: [GrayscaleMode; 5] = [GrayscaleMode::Desaturation, GrayscaleMode::Luma, GrayscaleMode::Average, GrayscaleMode::Max, GrayscaleMode::Min]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + GrayscaleMode::Desaturation => "Desaturation", + GrayscaleMode::Luma => "Luma", + GrayscaleMode::Average => "Average", + GrayscaleMode::Max => "Max", + GrayscaleMode::Min => "Min", + } + } + + /// The id `effect.set {grayscaleMode}` takes + pub fn id(self) -> &'static str { + match self { + GrayscaleMode::Desaturation => "desaturation", + GrayscaleMode::Luma => "luma", + GrayscaleMode::Average => "average", + GrayscaleMode::Max => "max", + GrayscaleMode::Min => "min", + } + } + + /// The gray of linear color `[r, g, b]` + pub fn gray(self, [r, g, b]: [f32; 3]) -> f32 { + match self { + GrayscaleMode::Desaturation => (r.max(g).max(b) + r.min(g).min(b)) / 2.0, + GrayscaleMode::Luma => crate::blend::lum([r, g, b]), + GrayscaleMode::Average => (r + g + b) / 3.0, + GrayscaleMode::Max => r.max(g).max(b), + GrayscaleMode::Min => r.min(g).min(b), + } + } +} diff --git a/crates/core/src/height_to_normal.rs b/crates/core/src/height_to_normal.rs new file mode 100644 index 00000000..4f72ae16 --- /dev/null +++ b/crates/core/src/height_to_normal.rs @@ -0,0 +1,80 @@ +//! Height To Normal's settings: the layer's Height turned into its Normal + +use serde::{Deserialize, Serialize}; + +/// A Height To Normal filter: the normal of the slopes of the layer's Height, over or in place of its Normal +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeightToNormal { + /// Overwrite Existing Normal: the made normal replaces the Normal below instead of being laid over it + pub overwrite: bool, + /// Use World Units: the slope comes from Surface Size and Height Depth instead of Normal Intensity + pub world_units: bool, + /// Surface Size (cm): how wide a UV tile is on the model + pub surface_size: f32, + /// Height Depth (cm): how deep a height of 1 is + pub height_depth: f32, + /// Normal Intensity: how strongly the slopes tilt the normal without world units + pub intensity: f32, +} + +impl HeightToNormal { + /// A new Height To Normal + pub const LIBRARY: HeightToNormal = HeightToNormal { overwrite: true, world_units: true, surface_size: 300.0, height_depth: 16.0, intensity: 10.0 }; + + /// The smallest Surface Size: whole cm, so the reference's 0.1 rounds up to 1 + pub const MIN_SURFACE_SIZE: f32 = 1.0; + + /// The largest Surface Size (cm) + pub const MAX_SURFACE_SIZE: f32 = 1000.0; + + /// The largest Height Depth (cm) + pub const MAX_HEIGHT_DEPTH: f32 = 100.0; + + /// The largest Normal Intensity + pub const MAX_INTENSITY: f32 = 50.0; + + /// Height Depth over Surface Size a Normal Intensity of 1 tilts like (so the default 10 matches the default 16 cm over 300 cm) + const INTENSITY_UNIT: f32 = Self::LIBRARY.height_depth / Self::LIBRARY.surface_size / Self::LIBRARY.intensity; + + /// How much a change of height per texel tilts the normal at `res` texels across a UV tile (0 for hostile values) + pub fn strength(&self, res: u32) -> f32 { + let finite = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 }; + let per_tile = if self.world_units { + finite(self.height_depth, Self::MAX_HEIGHT_DEPTH) / finite(self.surface_size, Self::MAX_SURFACE_SIZE).max(Self::MIN_SURFACE_SIZE) + } else { + finite(self.intensity, Self::MAX_INTENSITY) * Self::INTENSITY_UNIT + }; + per_tile * res as f32 + } + + /// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down + pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] { + let strength = self.strength(res); + let (x, y) = (-gx * strength, gy * strength); + let length = (x * x + y * y + 1.0).sqrt(); + if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn world_units_and_normal_intensity_tilt_the_normal_up_the_slope() { + let filter = HeightToNormal::LIBRARY; + assert_eq!(filter.normal([0.0, 0.0], 2048), [0.0, 0.0, 1.0], "a flat height"); + let [x, y, z] = filter.normal([0.01, 0.0], 2048); + assert!(x < 0.0 && y == 0.0 && z > 0.0, "rising to the right faces left"); + let expected = 0.01 * 16.0 / 300.0 * 2048.0; + assert!((-x / z - expected).abs() < 1e-4, "16 cm over 300 cm"); + let intensity = HeightToNormal { world_units: false, ..filter }; + assert!((intensity.strength(2048) - filter.strength(2048)).abs() < 1e-3, "Normal Intensity 10 matches the world default"); + assert!(HeightToNormal { intensity: 20.0, ..intensity }.strength(2048) > intensity.strength(2048)); + assert!(HeightToNormal { height_depth: 32.0, ..filter }.strength(2048) > filter.strength(2048)); + assert_eq!(filter.normal([0.0, 0.01], 2048)[1].signum(), 1.0, "rising down the image faces up"); + let hostile = HeightToNormal { surface_size: f32::NAN, height_depth: f32::INFINITY, ..filter }; + assert!(hostile.normal([1.0, 1.0], 2048).iter().all(|v| v.is_finite())); + } +} diff --git a/crates/core/src/highpass_space.rs b/crates/core/src/highpass_space.rs new file mode 100644 index 00000000..7faa4f94 --- /dev/null +++ b/crates/core/src/highpass_space.rs @@ -0,0 +1,84 @@ +//! The color space a Highpass filter works in + +use serde::{Deserialize, Serialize}; + +use crate::gradient_input::{linear_to_srgb, srgb_to_linear}; + +/// ACEScg (AP1) to linear sRGB (Rec. 709) primaries, white point adapted (the published ACES matrix) +const AP1_TO_REC709: [[f32; 3]; 3] = [[1.705_05, -0.621_79, -0.083_26], [-0.130_26, 1.140_80, -0.010_55], [-0.024_00, -0.128_97, 1.152_97]]; + +/// Linear sRGB (Rec. 709) to ACEScg (AP1) primaries: the inverse of [`AP1_TO_REC709`] +const REC709_TO_AP1: [[f32; 3]; 3] = [[0.613_10, 0.339_52, 0.047_37], [0.070_19, 0.916_35, 0.013_45], [0.020_62, 0.109_57, 0.869_81]]; + +/// Where a Highpass takes its detail: in the working space (masks always), or in sRGB from linear sRGB or ACEScg colors +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum HighpassSpace { + /// The values as they are (what a Highpass did in projects saved before the Color Space) + #[default] + Working, + /// Colors read as linear sRGB, filtered sRGB encoded + SrgbFromLinear, + /// Colors read as ACEScg, filtered sRGB encoded + SrgbFromAcescg, +} + +impl HighpassSpace { + /// Every space, in the order a list shows them + pub const ALL: [HighpassSpace; 3] = [HighpassSpace::Working, HighpassSpace::SrgbFromLinear, HighpassSpace::SrgbFromAcescg]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + HighpassSpace::Working => "Working space / Mask", + HighpassSpace::SrgbFromLinear => "sRGB (from Linear sRGB)", + HighpassSpace::SrgbFromAcescg => "sRGB (from ACEScg)", + } + } + + /// The id `effect.set {colorSpace}` takes + pub fn id(self) -> &'static str { + match self { + HighpassSpace::Working => "working", + HighpassSpace::SrgbFromLinear => "srgbFromLinear", + HighpassSpace::SrgbFromAcescg => "srgbFromAcescg", + } + } + + /// Straight color `rgb` in this space + pub fn encode(self, rgb: [f32; 3]) -> [f32; 3] { + match self { + HighpassSpace::Working => rgb, + HighpassSpace::SrgbFromLinear => rgb.map(linear_to_srgb), + HighpassSpace::SrgbFromAcescg => times(&AP1_TO_REC709, rgb).map(linear_to_srgb), + } + } + + /// Straight color `rgb` of this space back in the working space + pub fn decode(self, rgb: [f32; 3]) -> [f32; 3] { + match self { + HighpassSpace::Working => rgb, + HighpassSpace::SrgbFromLinear => rgb.map(srgb_to_linear), + HighpassSpace::SrgbFromAcescg => times(&REC709_TO_AP1, rgb.map(srgb_to_linear)), + } + } +} + +/// Matrix `m` times column `v` +fn times(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] { + m.map(|row| row[0] * v[0] + row[1] * v[1] + row[2] * v[2]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_space_round_trips_a_color_in_its_gamut() { + for space in HighpassSpace::ALL { + let back = space.decode(space.encode([0.5, 0.4, 0.3])); + assert!(back.iter().zip([0.5, 0.4, 0.3]).all(|(a, b)| (a - b).abs() < 2e-3), "{space:?}: {back:?}"); + } + assert!((HighpassSpace::SrgbFromLinear.encode([0.214; 3])[0] - 0.5).abs() < 1e-2, "linear mid gray is sRGB 0.5"); + } +} diff --git a/crates/core/src/image_input.rs b/crates/core/src/image_input.rs new file mode 100644 index 00000000..d935074f --- /dev/null +++ b/crates/core/src/image_input.rs @@ -0,0 +1,88 @@ +//! An image a filter reads besides the stack it filters (its image inputs), as a source on the filter's effect + +use crate::{Filter, Source, SourceColorMode, TargetColorMode, WarpSourceMode}; + +/// One image input of a filter: the key its source is stored under on the effect, its name and the gray it reads until a source is set +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ImageInput { + pub id: &'static str, + pub label: &'static str, + /// The gray the input reads while no source is set (what the filter did before it had the input) + pub default: f32, + /// Added by a mode of the filter (shown under that mode), not one of its Image inputs + pub by_mode: bool, +} + +impl ImageInput { + /// Bevel Smooth's and Directional Distance's Distance Map: scales the distance per texel + pub const DISTANCE_MAP: ImageInput = ImageInput { id: "distanceMap", label: "Distance Map", default: 1.0, by_mode: false }; + + /// Warp's and Blur Slope's Custom Noise (Source Type Custom Noise): the source its texels move or read along; mid gray moves nothing + pub const CUSTOM_NOISE: ImageInput = ImageInput { id: "customNoise", label: "Custom Noise", default: 0.5, by_mode: true }; + + /// The Custom Input of Grayscale Conversion (the color it reads instead of the channel) and Anisotropic Kuwahara (its direction's gray); mid gray until set + pub const CUSTOM_INPUT: ImageInput = ImageInput { id: "customInput", label: "Custom Input", default: 0.5, by_mode: true }; + + /// Color Match's Input (Source Color Mode Input): the color each texel moves from; mid gray until set + pub const SOURCE_INPUT: ImageInput = ImageInput { id: "input", label: "Input", default: 0.5, by_mode: true }; + + /// Color Match's Image Input (Target Color Mode Image Input): the color each texel moves to; mid gray until set + pub const TARGET_INPUT: ImageInput = ImageInput { id: "imageInput", label: "Image Input", default: 0.5, by_mode: true }; + + /// The image inputs `filter` reads now (a mode's input only while that mode is on) + pub fn of(filter: &Filter) -> Vec { + Self::all(filter).iter().copied().filter(|input| input.is_on(filter)).collect() + } + + /// The input of `filter` stored under `id`, also while its mode is off + pub fn named(filter: &Filter, id: &str) -> Option { + Self::all(filter).iter().find(|input| input.id == id).copied() + } + + /// Every image input `filter` has, its modes' inputs also while those modes are off + fn all(filter: &Filter) -> &'static [ImageInput] { + match filter { + Filter::BevelSmooth(_) | Filter::DirectionalDistance(_) => &[Self::DISTANCE_MAP], + Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_) => &[Self::CUSTOM_NOISE], + Filter::GrayscaleConversion(_) | Filter::AnisotropicKuwahara(_) => &[Self::CUSTOM_INPUT], + Filter::ColorMatch(_) => &[Self::SOURCE_INPUT, Self::TARGET_INPUT], + _ => &[], + } + } + + /// Whether `filter` reads this input now: an input a mode adds only while that mode is on + fn is_on(&self, filter: &Filter) -> bool { + match filter { + Filter::SourceWarp(warp) => warp.source.mode == WarpSourceMode::CustomNoise, + Filter::SourceSlopeBlur(slope) => slope.source.mode == WarpSourceMode::CustomNoise, + Filter::GrayscaleConversion(conversion) => conversion.custom_input, + Filter::AnisotropicKuwahara(kuwahara) => kuwahara.custom_input, + Filter::ColorMatch(matcher) if *self == Self::SOURCE_INPUT => matcher.source_mode == SourceColorMode::Input, + Filter::ColorMatch(matcher) => matcher.target_mode == TargetColorMode::ImageInput, + _ => true, + } + } + + /// The source the input reads while none is set + pub fn default_source(&self) -> Source { + Source::Uniform([self.default; 3]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{BevelSmooth, SourceWarp, WarpSource}; + + #[test] + fn a_warp_has_its_custom_noise_only_in_that_source_mode() { + let warp = SourceWarp::LIBRARY; + assert!(ImageInput::of(&Filter::SourceWarp(warp)).is_empty()); + let custom = SourceWarp { source: WarpSource { mode: WarpSourceMode::CustomNoise, ..warp.source }, ..warp }; + assert_eq!(ImageInput::of(&Filter::SourceWarp(custom)), vec![ImageInput::CUSTOM_NOISE]); + assert_eq!(ImageInput::named(&Filter::SourceWarp(warp), "customNoise"), Some(ImageInput::CUSTOM_NOISE), "kept while the mode is off"); + assert_eq!(ImageInput::of(&Filter::BevelSmooth(BevelSmooth::LIBRARY)), vec![ImageInput::DISTANCE_MAP]); + assert_eq!(ImageInput::named(&Filter::BevelSmooth(BevelSmooth::LIBRARY), "customNoise"), None); + assert_eq!(ImageInput::DISTANCE_MAP.default_source(), Source::Uniform([1.0; 3])); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 9d318149..aee8f43d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1,50 +1,47 @@ //! Layers, masks, effects and fill sources. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, CompareSource, ContentsOffset, DepthCulling, Projector, RandomizedSeed, ShapeCrop, lum}; +use crate::curve_preset::CurvePreset; +use crate::gradient_input::{GradientInput, ramp, shape_gray}; +use crate::{ + AnisotropicKuwahara, Backface, BakedMap, Bevel, BevelSmooth, BlendMode, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, DepthCulling, + DirectionalDistance, DirectionalLight, FillSymmetry, GrayscaleConversion, HeightToNormal, HighpassSpace, MaskOutline, Mirror, PbrValidate, Projector, + RandomizedSeed, ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, +}; mod curvature_detail; mod curvature_mode; mod decal_flip; mod decal_symmetry; -mod filtering; mod generator_global; mod micro_detail; mod output_resolution; mod resolution_mode; -mod sampling; -mod scale_mode; mod tile_blending; mod tile_generator; mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; -mod uv_transform; -mod uv_wrap; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; -pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; -pub use sampling::Sampling; -pub use scale_mode::ScaleMode; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; -pub use uv_transform::UvTransform; -pub use uv_wrap::UvWrap; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -1049,13 +1046,21 @@ impl Generator { pub enum Filter { Blur { radius: f32, + /// Reads past the texture's edges from its opposite side, so tiling textures stay seamless; off in projects saved before it + #[serde(default, skip_serializing_if = "is_false")] + wrap: bool, }, Sharpen { amount: f32, }, Invert, + /// Invert switched off: changes nothing until it is switched back on ([`Filter::Invert`]) + InvertOff, Threshold { level: f32, + /// Which side of `level` turns white; at or above it in projects saved before the modes + #[serde(default, skip_serializing_if = "ThresholdMode::is_default")] + mode: ThresholdMode, }, /// Hue/saturation/lightness shift (color channels; lightness only on grays and masks). /// `hue` is in turns, `saturation` and `lightness` in −1..1; all zero = unchanged. @@ -1063,25 +1068,76 @@ pub enum Filter { hue: f32, saturation: f32, lightness: f32, + /// Shifts in a perceptual color space (OKLCh), so a hue turn keeps the colors' lightness; plain HSL in projects saved before it + #[serde(default, skip_serializing_if = "is_false")] + perceptive: bool, }, /// Contrast around mid gray and a luminosity shift, both −1..1 (0 = unchanged). ContrastLuminosity { contrast: f32, luminosity: f32, }, + /// Contrast, luminosity (both −1..1, 0 = unchanged) and saturation (0..1, 0.5 = unchanged) for the shadows, midtones and highlights, each `[contrast, luminosity, saturation]`, weighted by the texel's lightness as [`Filter::ColorBalance`] + ColorCorrect { + shadows: [f32; 3], + midtones: [f32; 3], + highlights: [f32; 3], + }, /// Color offsets (−1..1 per component) weighted towards the shadows, midtones and highlights. ColorBalance { shadows: [f32; 3], midtones: [f32; 3], highlights: [f32; 3], }, - /// Luminance mapped through evenly spaced colors (linear RGB; scalars read their gray). + /// The texel's gray (after `input`) mapped through a ramp of colors (scalars read the ramp's gray) GradientMap { colors: Vec<[f32; 3]>, + /// Where each color sits on the ramp (0..1); evenly spaced in projects saved before + #[serde(default, skip_serializing_if = "Vec::is_empty")] + positions: Vec, + /// How many of `colors` the ramp uses (2..10), the rest kept for later; all of them in projects saved before + #[serde(default, skip_serializing_if = "Option::is_none")] + quantity: Option, + /// How a texel becomes the position it reads; luma, untouched, in projects saved before + #[serde(default, skip_serializing_if = "GradientInput::is_unchanged")] + input: GradientInput, + /// Blends neighbouring colors in linear RGB (off: in sRGB, as a color picker shows them); on in projects saved before + #[serde(default = "yes", skip_serializing_if = "is_true")] + linear: bool, + /// Shows the ramp itself across the texture (left to right) in place of the mapped values + #[serde(default, skip_serializing_if = "is_false")] + debug: bool, + }, + /// Values remapped through a preset curve, after balance, contrast and invert like a gradient's input + GradientCurve { + preset: CurvePreset, + invert: bool, + balance: f32, + contrast: f32, + }, + /// A color read off a gradient source at `position` across it (`vertical`: down it); the source is a uniform color + GradientDynamic { + vertical: bool, + position: f32, + color: [f32; 3], }, /// Quantize to `levels` steps (2..64). Posterize { levels: f32, + /// Steps the content's coverage too (Apply to Alpha); off in projects saved before it + #[serde(default, skip_serializing_if = "is_false")] + alpha: bool, + }, + /// The values between `min` and `max` eased from black to white (smoothstep); outside them black or white + Smoothstep { + min: f32, + max: f32, + }, + /// Heights flipped (`invert`), scaled by `multiply` and raised by `offset` around mid gray + HeightAdjust { + invert: bool, + offset: f32, + multiply: f32, }, /// Keep values within `min..max`. Clamp { @@ -1093,6 +1149,9 @@ pub enum Filter { HistogramScan { position: f32, contrast: f32, + /// Scans from the other end: the position read as 1 − position (Invert Position); off in projects saved before it + #[serde(default, skip_serializing_if = "is_false")] + invert_position: bool, }, /// The values squeezed towards `position`: `range` 1 keeps them, 0 sets them all to it. HistogramRange { @@ -1103,68 +1162,147 @@ pub enum Filter { HistogramShift { offset: f32, }, - /// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K, - /// `scale` noise features per UV unit. + /// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K, `scale` noise features per UV unit (projects saved before the warp modes; new ones are [`Filter::SourceWarp`]) Warp { intensity: f32, scale: f32, seed: u32, + /// Divides `intensity` (1, 10, 100 or 1000) for fine displacements; 1 in projects saved before it + #[serde(default = "unit_divider", skip_serializing_if = "is_unit_divider")] + divider: u16, }, /// Blur along one direction: `radius` in texels at 2K, `angle` in degrees. DirectionalBlur { radius: f32, angle: f32, }, - /// Smear values downhill along a noise height field ("slope blur"): `radius` in texels at - /// 2K, `scale` noise features per UV unit. + /// Values smeared downhill along a noise height field: `radius` in texels at 2K, `scale` noise features per UV unit (projects saved before its source settings) SlopeBlur { radius: f32, scale: f32, seed: u32, + /// Divides `radius` like [`Filter::Warp`]'s divider + #[serde(default = "unit_divider", skip_serializing_if = "is_unit_divider")] + divider: u16, }, /// The detail finer than `radius` (texels at 2K) around mid gray: the value minus its blur. HighPass { radius: f32, + /// Color Space: colors filtered in sRGB from linear sRGB or ACEScg + #[serde(default, skip_serializing_if = "is_working_space")] + space: HighpassSpace, + /// Apply To Alpha: the content's coverage takes its detail too + #[serde(default, skip_serializing_if = "is_false")] + alpha: bool, }, /// Gradient magnitude across `width` texels at 2K: edges light, flat areas black. EdgeDetect { width: f32, }, - /// Like [`Filter::Warp`], but every texel moves along one direction (`angle` in degrees). + /// Like [`Filter::Warp`], but every texel moves along one direction (`angle` in degrees; projects saved before the warp modes) DirectionalWarp { intensity: f32, angle: f32, scale: f32, seed: u32, + /// Divides `intensity` like [`Filter::Warp`]'s divider + #[serde(default = "unit_divider", skip_serializing_if = "is_unit_divider")] + divider: u16, }, - /// Colors to their luminance (scalars and masks unchanged). + /// Colors to their luminance (scalars and masks unchanged): projects saved before Grayscale Conversion's settings Grayscale, + /// The gray of every channel (or of its Custom Input) by its mode and weights, balanced, contrasted and maybe inverted + GrayscaleConversion(GrayscaleConversion), /// Flip the green component of normal maps (OpenGL ↔ DirectX); other channels unchanged. NormalInvert, /// Shapes rounded off at their edges: values ramp up from 0 at a shape's edge to their own /// level over about `width` texels at 2K (a mask's or height's bevel). Bevel { width: f32, + /// Reads past the texture's edges like [`Filter::Blur`]'s wrap + #[serde(default, skip_serializing_if = "is_false")] + wrap: bool, }, - /// Square cells `size` texels at 2K across, each the value at its center. + /// Shapes sloped at their edge, inwards or outwards over a share of the UV tile (projects saved before keep [`Filter::Bevel`]) + DistanceBevel(Bevel), + /// Texels read from where a source sends them, in one of the warp modes (projects saved before keep [`Filter::Warp`] and [`Filter::DirectionalWarp`]) + SourceWarp(SourceWarp), + /// Values read downhill along a source's slope, blended (projects saved before keep [`Filter::SlopeBlur`]) + SourceSlopeBlur(SourceSlopeBlur), + /// A smooth ramp from the shapes' edge, outwards, inwards or across it + BevelSmooth(BevelSmooth), + /// A trail fading away from the shapes in one direction + DirectionalDistance(DirectionalDistance), + /// One side of an axis (or one quarter) of each UV tile copied over the rest + Mirror(Mirror), + /// Each UV tile's content scaled, turned, moved and flipped, repeating or not + Transform(TileTransform), + /// A band along the edge where values cross a threshold + MaskOutline(MaskOutline), + /// Square cells `size` texels at 2K across, each the value at its center (Pixelate; see [`Filter::pixels_amount`]) Mosaic { size: f32, + /// Steps the content's coverage into the cells too (Apply To Alpha); on in projects saved before the switch + #[serde(default = "yes", skip_serializing_if = "is_true")] + alpha: bool, }, - /// Adds a blur of the values (`radius` texels at 2K) times `amount`: light bleeds around - /// bright areas. + /// Painterly smoothing along the strokes' direction: each texel the mean of the calmest sector around it + AnisotropicKuwahara(AnisotropicKuwahara), + /// Base colors outside the physically plausible ranges shown in red (reads the layer's metal) + PbrValidate(PbrValidate), + /// Height To Normal: the layer's Height turned into its Normal + HeightToNormal(HeightToNormal), + /// Color Match: the colors moved so a source color (the texture's mean by default) lands on a target color + ColorMatch(ColorMatch), + /// Stair-stepped edges smoothed by blending across them (FXAA) + Fxaa { + /// Smooths the content's coverage too (Affect Alpha Channel) + #[serde(default, skip_serializing_if = "is_false")] + alpha: bool, + }, + /// Adds a blur of the values (`radius` texels at 2K) times `amount`: light bleeds around bright areas (projects saved before the halo glow below) Glow { radius: f32, amount: f32, }, - /// Lighting painted into the base color: `ambient` (times the baked ambient occlusion by - /// `occlusion`) plus a directional light of strength `light` from `azimuth` around +Y - /// (degrees from +Z) and `elevation` above the horizon (degrees), on the mesh's normals. + /// A halo in `color` around the shapes (content coverage, mask values), inside them below 0 `width`; see [`Filter::HALO_REACH`] + HaloGlow { + /// Laid on a mask as white rather than the color's luminance (Used on a Mask) + on_mask: bool, + /// Ends sharper (Mode Precise) instead of fading out (Soft) + precise: bool, + width: f32, + spread: f32, + opacity: f32, + color: [f32; 3], + }, + /// The shapes in `color` laid under them, moved `distance` of a UV tile away from a light at `angle` and blurred over `size` + DropShadow { + angle: f32, + distance: f32, + size: f32, + spread: f32, + opacity: f32, + color: [f32; 3], + }, + /// Lighting painted into the base color: `ambient` (times the baked ambient occlusion by `occlusion`) plus a directional light of strength `light` from `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees), on the mesh's normals. `stylized` adds sky colors, more lights, cavity, edges and highlights (Baked Lighting Stylized); projects saved before have none and light as they did BakedLighting { azimuth: f32, elevation: f32, light: f32, ambient: f32, occlusion: f32, + #[serde(default, skip_serializing_if = "Option::is_none")] + stylized: Option>, + }, + /// The base color lit by the viewport environment (its diffuse light), turned `horizontal` and tilted `vertical` degrees, brighter by 2^`exposure`, on the mesh's normals tilted by the baked height (`height_intensity`) and darkened by the baked ambient occlusion (`ambient_occlusion` on the diffuse light, `specular_occlusion` on the reflections) + EnvironmentLighting { + horizontal: f32, + vertical: f32, + exposure: f32, + height_intensity: f32, + ambient_occlusion: f32, + specular_occlusion: f32, }, /// Colors near `from` (within `tolerance`, fading out over `softness`, as RGB distance /// 0..1) shifted by `to − from`, so their shading and texture stay (linear RGB). @@ -1174,13 +1312,78 @@ pub enum Filter { tolerance: f32, softness: f32, }, + /// No filter picked yet: changes nothing + Empty, +} + +/// The divider of projects saved before intensities had one +fn unit_divider() -> u16 { + 1 } /// Whether a switch is on, its default where it defaults to on (not saved then) +/// Serde default of a switch that was on in projects saved before it existed +fn yes() -> bool { + true +} + +/// Whether a switch is on, its default where it defaults to [`yes`] (not saved then) fn is_true(on: &bool) -> bool { *on } +/// Whether a high pass runs in the working color space, its default (not saved then) +fn is_working_space(space: &HighpassSpace) -> bool { + *space == HighpassSpace::Working +} + +/// Whether a switch is off, its default (not saved then) +fn is_false(on: &bool) -> bool { + !*on +} + +/// Whether `divider` leaves its intensity as it is (not saved then) +fn is_unit_divider(divider: &u16) -> bool { + *divider == 1 +} + +/// The fewest and most steps a posterize keeps +pub const POSTERIZE_LEVELS_MIN: f32 = 2.0; +pub const POSTERIZE_LEVELS_MAX: f32 = 64.0; + +/// Filter sizes are given in texels at 2K, as in the reference workflow +pub const SIZE_REFERENCE_RES: f32 = 2048.0; + +/// `x` (0..1) rounded to `levels` steps (2..64) from black to white +pub fn posterize(x: f32, levels: f32) -> f32 { + let steps = (levels.clamp(POSTERIZE_LEVELS_MIN, POSTERIZE_LEVELS_MAX).round() - 1.0).max(1.0); + let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 }; + (x * steps).round() / steps +} + +/// Bounds of a smoothstep closer than this are a step: easing over a narrower span would divide by almost nothing +const MIN_SMOOTHSTEP_SPAN: f32 = 1e-6; + +/// 0 at or below `min`, 1 at or above `max`, eased between them (swapped bounds are read in order; equal bounds are a step) +pub(crate) fn smoothstep(min: f32, max: f32, x: f32) -> f32 { + let (low, high) = (finite_or(min.min(max), 0.0), finite_or(min.max(max), 1.0)); + if !x.is_finite() { + return 0.0; + } + + if high - low <= MIN_SMOOTHSTEP_SPAN { + return if x >= high { 1.0 } else { 0.0 }; + } + + let t = ((x - low) / (high - low)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// `v`, or `fallback` where it is not a number +fn finite_or(v: f32, fallback: f32) -> f32 { + if v.is_finite() { v } else { fallback } +} + /// Push `x` (0..1) towards 1 (`amount` > 0) or 0 (`amount` < 0); `amount` in −1..1. fn shift_unit(x: f32, amount: f32) -> f32 { let a = amount.clamp(-1.0, 1.0); @@ -1229,6 +1432,22 @@ pub fn hsl_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [ [hue_to_rgb(p, q, h + 1.0 / 3.0), hue_to_rgb(p, q, h), hue_to_rgb(p, q, h - 1.0 / 3.0)] } +/// Smooth weights of the shadows, midtones and highlights at lightness `l` (0..1), summing to 1: shadows fade out and highlights in with lightness +fn tone_weights(l: f32) -> (f32, f32, f32) { + ((1.0 - l) * (1.0 - l), 2.0 * l * (1.0 - l), l * l) +} + +/// [`hsl_adjust`] in OKLCh: the hue turns and the chroma scales (`saturation` −1 = gray, 1 = twice as vivid) at the color's own perceived lightness, which `lightness` then pushes towards white or black (linear 0..1 colors) +pub fn perceptive_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [f32; 3] { + let clean = |x: f32| if x.is_finite() { x } else { 0.0 }; + let [l, a, b] = crate::oklab::from_linear(rgb.map(|v| clean(v).clamp(0.0, 1.0))); + let (sin, cos) = (clean(hue) * std::f32::consts::TAU).sin_cos(); + let chroma = 1.0 + clean(saturation).clamp(-1.0, 1.0); + let (a, b) = ((a * cos - b * sin) * chroma, (a * sin + b * cos) * chroma); + let l = shift_unit(l.clamp(0.0, 1.0), clean(lightness)); + crate::oklab::to_linear([l, a, b]).map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }) +} + /// Apply a 0..1 function to each component of a channel value: signed values map through /// 0..1, normals are left alone. pub fn per_unit(kind: ChannelKind, v: [f32; 3], f: impl Fn(f32) -> f32) -> [f32; 3] { @@ -1252,6 +1471,72 @@ pub fn gradient(colors: &[[f32; 3]], t: f32) -> Option<[f32; 3]> { } impl Filter { + /// The most Baked Lighting Environment's Exposure brightens or darkens, in stops + pub const ENVIRONMENT_EXPOSURE_STOPS: f32 = 5.0; + + /// The choices of an intensity's divider + pub const DIVIDERS: [u16; 4] = [1, 10, 100, 1000]; + + /// The most colors a gradient's Color Quantity uses + pub const MAX_GRADIENT_COLORS: u8 = 10; + + /// Texels at 2K a Blur Intensity (Blur, Blur Directional) of 1 reaches + pub const BLUR_INTENSITY: f32 = 16.0; + + /// Texels at 2K a halo glow's Width or a drop shadow's Size of 1 reaches + pub const HALO_REACH: f32 = 128.0; + + /// A drop shadow is cast at most this share of a UV tile away, either way + pub const SHADOW_DISTANCE_MAX: f32 = 0.5; + + /// The noise features per UV unit a noise-driven warp or slope blur reads, at least and at most + pub const NOISE_SCALE_MIN: f32 = 0.01; + pub const NOISE_SCALE_MAX: f32 = 1000.0; + + /// A gradient as projects saved before the Input Transformation read it: `colors` evenly spaced, luma, linear blending + pub fn even_gradient(colors: Vec<[f32; 3]>) -> Filter { + Filter::GradientMap { colors, positions: Vec::new(), quantity: None, input: GradientInput::default(), linear: true, debug: false } + } + + /// Histogram Shift's Position (0..1) for its `offset`: a shift back by 1 − position, so 1 shifts nothing (offsets above 0 saved before the Position read as themselves, the same shift but for white and black) + pub fn shift_position(offset: f32) -> f32 { + let offset = if offset.is_finite() { offset.clamp(-1.0, 1.0) } else { 0.0 }; + if offset <= 0.0 { offset + 1.0 } else { offset } + } + + /// The Histogram Shift offset a Position (0..1) sets (see [`Filter::shift_position`]) + pub fn shift_offset(position: f32) -> f32 { + let position = if position.is_finite() { position.clamp(0.0, 1.0) } else { 1.0 }; + position - 1.0 + } + + /// Pixelate's Pixels Amount (cells across a UV tile) for a cell `size` in texels at 2K + pub fn pixels_amount(size: f32) -> f32 { + SIZE_REFERENCE_RES / if size.is_finite() { size.max(1.0) } else { SIZE_REFERENCE_RES } + } + + /// The cell size in texels at 2K that a Pixels Amount (cells across a UV tile) sets + pub fn pixel_size(amount: f32) -> f32 { + SIZE_REFERENCE_RES / if amount.is_finite() { amount.clamp(1.0, SIZE_REFERENCE_RES) } else { 1.0 } + } + + /// The colors a gradient's ramp uses: the first Color Quantity of them (all of them where it has none) + pub fn ramp_colors(&self) -> &[[f32; 3]] { + match self { + Filter::GradientMap { colors, quantity, .. } => colors.get(..quantity.map_or(colors.len(), usize::from).min(colors.len())).unwrap_or(colors), + _ => &[], + } + } + + /// A gradient's color at ramp position `t` (None for other filters and an empty ramp) + pub fn ramp_at(&self, t: f32) -> Option<[f32; 3]> { + let Filter::GradientMap { positions, linear, .. } = self else { return None }; + let colors = self.ramp_colors(); + + // Evenly spaced linear ramps take the path projects saved before took, so they render bit for bit as before + if positions.is_empty() && *linear { gradient(colors, t) } else { ramp(colors, positions, *linear, t) } + } + /// Whether the filter reads neighbouring texels (the compositor runs it over a region). pub fn is_neighbourhood(&self) -> bool { matches!( @@ -1266,66 +1551,118 @@ impl Filter { | Filter::DirectionalWarp { .. } | Filter::Bevel { .. } | Filter::Mosaic { .. } + | Filter::Fxaa { .. } + | Filter::AnisotropicKuwahara(_) + | Filter::HeightToNormal(_) + | Filter::ColorMatch(_) + | Filter::DistanceBevel(_) + | Filter::SourceWarp(_) + | Filter::SourceSlopeBlur(_) + | Filter::BevelSmooth(_) + | Filter::DirectionalDistance(_) + | Filter::Mirror(_) + | Filter::Transform(_) + | Filter::MaskOutline(_) | Filter::Glow { .. } + | Filter::HaloGlow { .. } + | Filter::DropShadow { .. } ) } /// The filter applied to one value of a channel of `kind` (masks are scalars). None for /// neighbourhood filters and where it changes nothing (an empty gradient). pub fn point(&self, kind: ChannelKind, v: [f32; 3]) -> Option<[f32; 3]> { - let unit = |x: f32| if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 }; + // Histogram Scan's narrowest soft cut, so near full contrast stays a finite slope + const SCAN_MIN_WIDTH: f32 = 1e-3; + + // Replace Color's least softness, so a hard edge divides by no zero + const REPLACE_MIN_SOFTNESS: f32 = 1e-6; + Some(match self { Filter::Invert => per_unit(kind, v, |x| 1.0 - x), - Filter::Threshold { level } => per_unit(kind, v, |x| if x >= *level { 1.0 } else { 0.0 }), - Filter::Hsl { hue, saturation, lightness } => match kind { + Filter::Threshold { level, mode } => per_unit(kind, v, |x| if mode.passes(x, *level) { 1.0 } else { 0.0 }), + Filter::Hsl { hue, saturation, lightness, perceptive } => match kind { + ChannelKind::Color if *perceptive => perceptive_adjust(v, *hue, *saturation, *lightness), ChannelKind::Color => hsl_adjust(v, *hue, *saturation, *lightness), _ => per_unit(kind, v, |x| hsl_adjust([x; 3], 0.0, 0.0, *lightness)[0]), }, Filter::ContrastLuminosity { contrast, luminosity } => { - let k = 1.0 + contrast.clamp(-1.0, 1.0); - per_unit(kind, v, |x| unit((x - 0.5) * k + 0.5 + luminosity)) + let slope = 1.0 + contrast.clamp(-1.0, 1.0); + per_unit(kind, v, |x| finite_unit((x - 0.5) * slope + 0.5 + luminosity)) + } + Filter::ColorCorrect { shadows, midtones, highlights } => { + // [contrast, luminosity, saturation] at the texel's lightness, weighted as color balance + let at = |lightness: f32| -> [f32; 3] { + let (in_shadows, in_midtones, in_highlights) = tone_weights(finite_unit(lightness)); + std::array::from_fn(|k| shadows[k] * in_shadows + midtones[k] * in_midtones + highlights[k] * in_highlights) + }; + let correct = |x: f32, [contrast, luminosity, _]: [f32; 3]| (x - 0.5) * (1.0 + contrast.clamp(-1.0, 1.0)) + 0.5 + luminosity.clamp(-1.0, 1.0); + match kind { + ChannelKind::Color => { + let tone = at(lum(v)); + let corrected = v.map(|x| correct(x, tone)); + let gray = lum(corrected); + let gain = 2.0 * tone[2].clamp(0.0, 1.0); + corrected.map(|x| finite_unit(gray + (x - gray) * gain)) + } + _ => per_unit(kind, v, |x| finite_unit(correct(x, at(x)))), + } } Filter::ColorBalance { shadows, midtones, highlights } => { - // Smooth weights summing to 1: shadows fade out and highlights in with lightness. - let weights = |l: f32| { - let l = unit(l); - ((1.0 - l) * (1.0 - l), 2.0 * l * (1.0 - l), l * l) - }; - let shift = |k: usize, l: f32| { - let (s, m, h) = weights(l); - shadows.get(k).copied().unwrap_or(0.0) * s + midtones.get(k).copied().unwrap_or(0.0) * m + highlights.get(k).copied().unwrap_or(0.0) * h + let shift = |component: usize, lightness: f32| { + let (in_shadows, in_midtones, in_highlights) = tone_weights(finite_unit(lightness)); + shadows.get(component).copied().unwrap_or(0.0) * in_shadows + + midtones.get(component).copied().unwrap_or(0.0) * in_midtones + + highlights.get(component).copied().unwrap_or(0.0) * in_highlights }; match kind { ChannelKind::Color => { - let l = lum(v); - std::array::from_fn(|k| unit(v[k] + shift(k, l))) + let lightness = lum(v); + std::array::from_fn(|k| finite_unit(v[k] + shift(k, lightness))) } - _ => per_unit(kind, v, |x| unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)), + _ => per_unit(kind, v, |x| finite_unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)), } } - Filter::GradientMap { colors } => match kind { - ChannelKind::Color => gradient(colors, lum(v))?, - _ => per_unit(kind, v, |x| gradient(colors, x).map_or(x, lum)), + Filter::GradientMap { input, .. } => match kind { + ChannelKind::Color => self.ramp_at(input.shape(input.mode.gray(v)))?, + // A height reads the ramp at its 0..1 place, as projects saved before did + _ => per_unit(kind, v, |x| self.ramp_at(input.shape(x)).map_or(x, lum)), }, - Filter::Posterize { levels } => { - let steps = (levels.clamp(2.0, 64.0).round() - 1.0).max(1.0); - per_unit(kind, v, |x| (unit(x) * steps).round() / steps) + Filter::GradientCurve { preset, invert, balance, contrast } => per_unit(kind, v, |x| preset.at(shape_gray(x, *balance, *contrast, *invert))), + Filter::GradientDynamic { color, .. } => match kind { + ChannelKind::Color => color.map(finite_unit), + _ => per_unit(kind, v, |_| finite_unit(lum(*color))), + }, + Filter::Posterize { levels, .. } => per_unit(kind, v, |x| posterize(x, *levels)), + Filter::Smoothstep { min, max } => per_unit(kind, v, |x| smoothstep(*min, *max, x)), + Filter::HeightAdjust { invert, offset, multiply } => { + let (offset, multiply) = (finite_or(*offset, 0.0), finite_or(*multiply, 1.0)); + per_unit(kind, v, |x| { + let x = if *invert { 1.0 - x } else { x }; + finite_unit((x - 0.5) * multiply + 0.5 + offset) + }) } + Filter::InvertOff => v, Filter::Clamp { min, max } => { - let (lo, hi) = (min.min(*max), min.max(*max)); - per_unit(kind, v, |x| x.max(lo).min(hi)) + let (low, high) = (min.min(*max), min.max(*max)); + per_unit(kind, v, |x| x.max(low).min(high)) } - // Full contrast is a threshold: the position itself goes to white. - Filter::HistogramScan { position, contrast } if *contrast >= 1.0 => per_unit(kind, v, |x| if x >= *position { 1.0 } else { 0.0 }), - Filter::HistogramScan { position, contrast } => { - let width = (1.0 - contrast.clamp(0.0, 1.0)).max(1e-3); - per_unit(kind, v, |x| unit((x - position) / width + 0.5)) + + // Full contrast is a threshold: the position itself goes to white + Filter::HistogramScan { position, contrast, invert_position } => { + let position = if *invert_position { 1.0 - position } else { *position }; + if *contrast >= 1.0 { + per_unit(kind, v, |x| if x >= position { 1.0 } else { 0.0 }) + } else { + let width = (1.0 - contrast.clamp(0.0, 1.0)).max(SCAN_MIN_WIDTH); + per_unit(kind, v, |x| finite_unit((x - position) / width + 0.5)) + } } - Filter::HistogramRange { range, position } => per_unit(kind, v, |x| unit(position + (x - position) * range)), + Filter::HistogramRange { range, position } => per_unit(kind, v, |x| finite_unit(position + (x - position) * range)), Filter::HistogramShift { offset } => per_unit(kind, v, |x| { - // Wrapped by hand: `rem_euclid` would also send white (1 + 0) to black. - let y = unit(x) + offset.clamp(-1.0, 1.0); - unit(if y > 1.0 { + // Wrapped by hand: `rem_euclid` would also send white (1 + 0) to black + let y = finite_unit(x) + offset.clamp(-1.0, 1.0); + finite_unit(if y > 1.0 { y - 1.0 } else if y < 0.0 { y + 1.0 @@ -1337,23 +1674,26 @@ impl Filter { ChannelKind::Color => [lum(v); 3], _ => v, }, + // Read opaque here: the compositor passes the content's coverage (and a Custom Input) through `GrayscaleConversion::channel_value` + Filter::GrayscaleConversion(conversion) => conversion.channel_value(kind, v, None, 1.0), Filter::NormalInvert => match kind { ChannelKind::NormalMap => [v[0], 1.0 - v[1], v[2]], _ => v, }, Filter::ReplaceColor { from, to, tolerance, softness } => match kind { ChannelKind::Color => { - let d = ((v[0] - from[0]).powi(2) + (v[1] - from[1]).powi(2) + (v[2] - from[2]).powi(2)).sqrt() / 3f32.sqrt(); - let (t, s) = (tolerance.clamp(0.0, 1.0), softness.clamp(0.0, 1.0)); - let w = if d <= t { + // How far the color is from `from`, 1 across the whole cube + let distance = ((v[0] - from[0]).powi(2) + (v[1] - from[1]).powi(2) + (v[2] - from[2]).powi(2)).sqrt() / 3f32.sqrt(); + let (tolerance, softness) = (tolerance.clamp(0.0, 1.0), softness.clamp(0.0, 1.0)); + let weight = if distance <= tolerance { 1.0 - } else if d >= t + s { + } else if distance >= tolerance + softness { 0.0 } else { - let x = 1.0 - (d - t) / s.max(1e-6); - x * x * (3.0 - 2.0 * x) + let closeness = 1.0 - (distance - tolerance) / softness.max(REPLACE_MIN_SOFTNESS); + closeness * closeness * (3.0 - 2.0 * closeness) }; - std::array::from_fn(|k| unit(v[k] + (to[k] - from[k]) * w)) + std::array::from_fn(|k| finite_unit(v[k] + (to[k] - from[k]) * weight)) } _ => v, }, @@ -1367,8 +1707,25 @@ impl Filter { | Filter::DirectionalWarp { .. } | Filter::Bevel { .. } | Filter::Mosaic { .. } + | Filter::Fxaa { .. } + | Filter::AnisotropicKuwahara(_) + | Filter::PbrValidate(_) + | Filter::HeightToNormal(_) + | Filter::ColorMatch(_) + | Filter::DistanceBevel(_) + | Filter::SourceWarp(_) + | Filter::SourceSlopeBlur(_) + | Filter::BevelSmooth(_) + | Filter::DirectionalDistance(_) + | Filter::Mirror(_) + | Filter::Transform(_) + | Filter::MaskOutline(_) | Filter::Glow { .. } - | Filter::BakedLighting { .. } => return None, + | Filter::HaloGlow { .. } + | Filter::DropShadow { .. } + | Filter::BakedLighting { .. } + | Filter::EnvironmentLighting { .. } + | Filter::Empty => return None, }) } @@ -1376,43 +1733,97 @@ impl Filter { match self { Filter::Blur { .. } => "Blur", Filter::Sharpen { .. } => "Sharpen", - Filter::Invert => "Invert", + Filter::Invert | Filter::InvertOff => "Invert", Filter::Threshold { .. } => "Threshold", Filter::Hsl { .. } => "HSL Perceptive", - Filter::ContrastLuminosity { .. } => "Contrast/Luminosity", + Filter::ContrastLuminosity { .. } => "Contrast Luminosity", Filter::ColorBalance { .. } => "Color Balance", - Filter::GradientMap { .. } => "Gradient Map", + Filter::ColorCorrect { .. } => "Color Correct", + Filter::GradientMap { .. } => "Gradient", + Filter::GradientCurve { .. } => "Gradient Curve", + Filter::GradientDynamic { .. } => "Gradient Dynamic", Filter::Posterize { .. } => "Posterize", + Filter::Smoothstep { .. } => "Smoothstep", + Filter::HeightAdjust { .. } => "Height Adjust", Filter::Clamp { .. } => "Clamp", Filter::HistogramScan { .. } => "Histogram Scan", Filter::HistogramRange { .. } => "Histogram Range", Filter::HistogramShift { .. } => "Histogram Shift", Filter::Warp { .. } => "Warp", Filter::DirectionalBlur { .. } => "Blur Directional", - Filter::SlopeBlur { .. } => "Slope Blur", - Filter::HighPass { .. } => "High Pass", + Filter::SlopeBlur { .. } => "Blur Slope", + Filter::HighPass { .. } => "Highpass", Filter::EdgeDetect { .. } => "Edge Detect", Filter::DirectionalWarp { .. } => "Warp Directional", - Filter::Grayscale => "Grayscale", + Filter::Grayscale | Filter::GrayscaleConversion(_) => "Grayscale Conversion", Filter::NormalInvert => "Normal Invert", Filter::Bevel { .. } => "Bevel", - Filter::Mosaic { .. } => "Mosaic", - Filter::Glow { .. } => "Glow", - Filter::BakedLighting { .. } => "Baked Lighting", + Filter::Mosaic { .. } => "Pixelate", + Filter::Fxaa { .. } => "FXAA (Anti-aliasing)", + Filter::AnisotropicKuwahara(_) => "Anisotropic Kuwahara", + Filter::PbrValidate(_) => "PBR Validate (Metallic Roughness)", + Filter::HeightToNormal(_) => "Height To Normal", + Filter::ColorMatch(_) => "Color Match", + Filter::DistanceBevel(_) => "Bevel", + Filter::SourceWarp(_) => "Warp", + Filter::SourceSlopeBlur(_) => "Blur Slope", + Filter::BevelSmooth(_) => "Bevel Smooth", + Filter::DirectionalDistance(_) => "Directional Distance", + Filter::Mirror(_) => "Mirror", + Filter::Transform(_) => "Transform", + Filter::MaskOutline(_) => "Mask Outline", + Filter::Glow { .. } | Filter::HaloGlow { .. } => "Glow", + Filter::DropShadow { .. } => "Drop Shadow", + Filter::BakedLighting { .. } => "Baked Lighting Stylized", + Filter::EnvironmentLighting { .. } => "Baked Lighting Environment", Filter::ReplaceColor { .. } => "Replace Color", + Filter::Empty => "Filter (empty)", } } - /// Baked lighting's factor on the base color of a surface facing `nrm` (world space) with + /// The label this filter had before it took the reference workflow's name: effects named after it still follow a swap + pub fn former_label(&self) -> Option<&'static str> { + match self { + Filter::ContrastLuminosity { .. } => Some("Contrast/Luminosity"), + Filter::SlopeBlur { .. } | Filter::SourceSlopeBlur(_) => Some("Slope Blur"), + Filter::HighPass { .. } => Some("High Pass"), + Filter::Mosaic { .. } => Some("Mosaic"), + Filter::Grayscale => Some("Grayscale"), + Filter::GradientMap { .. } => Some("Gradient Map"), + Filter::BakedLighting { .. } => Some("Baked Lighting"), + _ => None, + } + } + + /// Baked lighting's factor on the base color of a surface facing `normal` (world space) with /// ambient occlusion `ao` (None for other filters). - pub fn baked_light(&self, nrm: [f32; 3], ao: f32) -> Option { - let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion } = self else { return None }; - let (sa, ca) = azimuth.to_radians().sin_cos(); - let (se, ce) = elevation.to_radians().sin_cos(); - let facing = (nrm[0] * ce * sa + nrm[1] * se + nrm[2] * ce * ca).max(0.0); + pub fn baked_light(&self, normal: [f32; 3], ao: f32) -> Option { + let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, .. } = self else { return None }; + let (sin_azimuth, cos_azimuth) = azimuth.to_radians().sin_cos(); + let (sin_elevation, cos_elevation) = elevation.to_radians().sin_cos(); + + // Multiplied in this order so saved projects light exactly as before + let facing = (normal[0] * cos_elevation * sin_azimuth + normal[1] * sin_elevation + normal[2] * cos_elevation * cos_azimuth).max(0.0); let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 }; - let k = ambient * (1.0 + (ao - 1.0) * occlusion.clamp(0.0, 1.0)) + light * facing; - Some(if k.is_finite() { k.max(0.0) } else { 1.0 }) + let factor = ambient * (1.0 + (ao - 1.0) * occlusion.clamp(0.0, 1.0)) + light * facing; + Some(if factor.is_finite() { factor.max(0.0) } else { 1.0 }) + } + + /// The channels a new content effect of the filter starts with on (None: all of them) + pub fn starts_on(&self) -> Option<&'static [Channel]> { + match self { + // PBR Validate reads the metal but changes only the base color, so its Metal pill would do nothing + Filter::BakedLighting { .. } | Filter::EnvironmentLighting { .. } | Filter::ColorMatch(_) | Filter::PbrValidate(_) => Some(&[Channel::BaseColor]), + Filter::HeightToNormal(_) => Some(&[Channel::Normal]), + _ => None, + } + } + + /// Baked Lighting Stylized's settings with its sun and sky (None for other filters and a Baked Lighting saved before them) + pub fn stylized_lighting(&self) -> Option<(&StylizedLighting, SunAndSky)> { + let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, stylized: Some(stylized) } = self else { return None }; + let sun = DirectionalLight { azimuth: *azimuth, elevation: *elevation, intensity: *light, color: stylized.sun_color }; + Some((stylized, SunAndSky { sun, sky_intensity: *ambient, diffuse_ao: *occlusion })) } } @@ -1647,6 +2058,7 @@ impl Layer { _ => false, }; fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.kind.reads(None)) + fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.reads(None)) } /// Whether the layer's result depends on the stack below it: it reads an anchor point, or its mask compares channels of the stack @@ -1666,12 +2078,44 @@ pub struct Effect { /// A content effect's channels that blend apart from `blend` and `opacity` (none in projects saved before they existed) #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub channel_blends: BTreeMap, + /// A content effect's channels it leaves as they are (none in projects saved before they could be switched off) + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub off_channels: BTreeSet, + /// A filter effect's image inputs set to a source, by [`crate::ImageInput`] id (the others read their default gray) + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub inputs: BTreeMap, } impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { // Generators and fills that build a mask usually add on top of the background Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0, channel_blends: BTreeMap::new() } + Effect { + id, + name: kind.name().to_string(), + visible: true, + kind, + blend: BlendMode::Normal, + opacity: 1.0, + channel_blends: BTreeMap::new(), + off_channels: BTreeSet::new(), + inputs: BTreeMap::new(), + } + } + + /// The image resources the effect reads: its kind's ([`EffectKind::images_read`]) and its filter image inputs' + pub fn images_read(&self) -> impl Iterator { + self.kind.images_read().chain(self.inputs.values().flat_map(Source::images)) + } + + /// Whether a source of the effect, or one of its image inputs, reads anchor point `anchor` (any anchor point when None) + pub fn reads(&self, anchor: Option) -> bool { + self.kind.reads(anchor) || self.inputs.values().any(|source| source.reads_anchor(anchor)) + } + + /// The source image input `input` reads: the one set on the effect, else its default gray + pub fn input(&self, input: &crate::ImageInput) -> Source { + self.inputs.get(input.id).cloned().unwrap_or_else(|| input.default_source()) } /// How the effect blends on `channel` of its layer's content, or on its mask (`None`) @@ -1679,6 +2123,15 @@ impl Effect { let shared = ChannelBlend { mode: self.blend, opacity: self.opacity }; channel.and_then(|channel| self.channel_blends.get(&channel).copied()).unwrap_or(shared) } + + /// How the effect lays onto `channel` when composited: [`Self::blend_of`], at no opacity on a channel it is switched off for + pub fn applied_blend(&self, channel: Option) -> ChannelBlend { + let blend = self.blend_of(channel); + match channel { + Some(channel) if self.off_channels.contains(&channel) => ChannelBlend { opacity: 0.0, ..blend }, + _ => blend, + } + } } #[cfg(test)] @@ -1717,11 +2170,15 @@ mod tests { #[test] fn a_colour_selection_id_map_is_reported_as_used() { + fn a_colour_selection_id_map_and_a_filter_image_input_are_reported_as_used() { let mut selection = crate::ColorSelection::new(Vec::new(), 0.0); selection.id_map = Some("id.png".into()); let effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection)); + let mut effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection)); + effect.inputs.insert("mask".into(), Source::image("input.png")); assert_eq!(effect.kind.images_read().collect::>(), vec!["id.png"]); + assert_eq!(effect.images_read().collect::>(), vec!["id.png", "input.png"]); } #[test] @@ -1908,6 +2365,20 @@ mod tests { assert!(hsl_adjust([f32::NAN, 2.0, -1.0], f32::NAN, 5.0, -5.0).iter().all(|v| v.is_finite())); } + #[test] + fn an_untransformed_gradient_maps_bit_for_bit_as_projects_saved_before_did() { + let colors = vec![[1.0, 0.2, 0.0], [0.1, 0.4, 0.9], [0.0, 0.0, 1.0]]; + let gm = Filter::even_gradient(colors.clone()); + for step in 0..=1000 { + let x = step as f32 / 1000.0; + let color = [x, 0.5 * x, 1.0 - x]; + assert_eq!(gm.point(ChannelKind::Color, color), gradient(&colors, lum(color)), "color {color:?}"); + let height = 2.0 * x - 1.0; + let saved_before = per_unit(ChannelKind::Signed, [height; 3], |t| gradient(&colors, t).map_or(t, lum)); + assert_eq!(gm.point(ChannelKind::Signed, [height; 3]), Some(saved_before), "height {height}"); + } + } + #[test] fn point_filters_map_values_and_skip_neighbourhood_filters() { let c = ChannelKind::Color; @@ -1915,38 +2386,34 @@ mod tests { let cl = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 }; assert!(close(cl.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0])); assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3])); - - let gm = Filter::GradientMap { colors: vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] }; + let gm = Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]); assert!(close(gm.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0])); assert!(close(gm.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0])); - assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing"); - - assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); + assert_eq!(Filter::even_gradient(vec![]).point(c, [0.3; 3]), None, "an empty gradient changes nothing"); + let gray_ramp = Filter::even_gradient(vec![[0.0; 3], [1.0; 3]]); + assert!(close(gray_ramp.point(ChannelKind::Signed, [-0.6; 3]).unwrap(), [-0.6; 3]), "a height reads the ramp at its 0..1 place"); + assert!(close(Filter::Posterize { levels: 2.0, alpha: false }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic"); - - let scan = |position, contrast| Filter::HistogramScan { position, contrast }.point(c, [0.2, 0.5, 0.9]).unwrap(); - + let scan = |position, contrast| Filter::HistogramScan { position, contrast, invert_position: false }.point(c, [0.2, 0.5, 0.9]).unwrap(); assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values"); assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white"); assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9])); - let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap(); - assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3])); assert!(close(range(0.5, 0.5), [0.35, 0.5, 0.7])); - let shift = |offset| Filter::HistogramShift { offset }.point(c, [0.0, 0.5, 1.0]).unwrap(); - assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white"); assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75])); - let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] }; assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99); assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3])); assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0])); - - for f in [Filter::Blur { radius: 1.0 }, Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0 }, Filter::DirectionalBlur { radius: 1.0, angle: 0.0 }] { + for f in [ + Filter::Blur { radius: 1.0, wrap: false }, + Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0, divider: 1 }, + Filter::DirectionalBlur { radius: 1.0, angle: 0.0 }, + ] { assert!(f.is_neighbourhood() && f.point(c, [0.5; 3]).is_none()); } let nan = Filter::ContrastLuminosity { contrast: f32::NAN, luminosity: f32::NAN }; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c1fc86f6..ea2c1805 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -7,32 +7,75 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod anisotropic_kuwahara; pub mod backface; pub mod bake; +pub mod bevel; +pub mod bevel_blur; +pub mod bevel_corner; +pub mod bevel_direction; +pub mod bevel_smooth; pub mod blend; mod block_scales; pub mod channel; +pub mod color_match; pub mod color_selection; pub mod compare_source; pub mod contents_offset; +pub mod conversion_mode; pub mod cook_resolution; +pub mod curve_preset; pub mod depth_culling; +pub mod directional_distance; +pub mod directional_light; mod env_alignment; pub mod fill_symmetry; +pub mod gradient_input; +pub mod grayscale_conversion; +pub mod grayscale_mode; +pub mod height_to_normal; +pub mod highpass_space; +pub mod image_input; pub mod layer; +pub mod lighting_output; +pub mod mask_outline; +pub mod mirror; +pub mod mirror_corner; +pub mod mirror_mode; +pub mod oklab; +pub mod outline_position; +pub mod pbr_validate; pub mod project; pub mod projector; +pub mod ramp_curve; pub mod randomized_seed; mod saved_decal; mod saved_projection; pub mod selection_background; mod shadow_mode; pub mod shape_crop; +pub mod slope_blending; +pub mod source_color_mode; +pub mod source_slope_blur; +pub mod source_warp; +pub mod stylized_lighting; +pub mod stylized_shading; +pub mod sun_and_sky; pub mod symmetry_kind; +pub mod target_color_mode; +pub mod threshold_mode; +pub mod tile_transform; +pub mod unit_value; +pub mod validation_mode; +pub mod warp_blending; +pub mod warp_mode; +pub mod warp_source; +pub mod warp_source_mode; /// A full turn, in degrees pub const FULL_TURN_DEGREES: f32 = 360.0; +pub use anisotropic_kuwahara::AnisotropicKuwahara; pub use backface::Backface; pub use bake::{ AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap, @@ -41,29 +84,72 @@ pub use bake::{ NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, }; +pub use bevel::Bevel; +pub use bevel_blur::BevelBlur; +pub use bevel_corner::BevelCorner; +pub use bevel_direction::BevelDirection; +pub use bevel_smooth::BevelSmooth; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use color_match::ColorMatch; pub use color_selection::ColorSelection; pub use compare_source::CompareSource; pub use contents_offset::ContentsOffset; +pub use conversion_mode::ConversionMode; pub use cook_resolution::CookResolution; +pub use curve_preset::CurvePreset; pub use depth_culling::DepthCulling; +pub use directional_distance::DirectionalDistance; +pub use directional_light::DirectionalLight; pub use fill_symmetry::FillSymmetry; +pub use gradient_input::GradientInput; +pub use grayscale_conversion::GrayscaleConversion; +pub use grayscale_mode::GrayscaleMode; +pub use height_to_normal::HeightToNormal; +pub use highpass_space::HighpassSpace; +pub use image_input::ImageInput; pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, + OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, + Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, + hsl_adjust, per_unit, posterize, }; +pub use lighting_output::LightingOutput; +pub use mask_outline::MaskOutline; +pub use mirror::Mirror; +pub use mirror_corner::MirrorCorner; +pub use mirror_mode::MirrorMode; +pub use outline_position::OutlinePosition; +pub use pbr_validate::PbrValidate; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MAX_SWATCHES, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, }; pub use projector::Projector; +pub use ramp_curve::RampCurve; pub use randomized_seed::RandomizedSeed; pub use selection_background::SelectionBackground; pub use shape_crop::ShapeCrop; +pub use slope_blending::SlopeBlending; +pub use source_color_mode::SourceColorMode; +pub use source_slope_blur::SourceSlopeBlur; +pub use source_warp::SourceWarp; +pub use stylized_lighting::{DIELECTRIC_REFLECTANCE, StylizedLighting}; +pub use stylized_shading::{FLAT_CURVATURE, StylizedShading}; +pub use sun_and_sky::SunAndSky; pub use symmetry_kind::SymmetryKind; +pub use target_color_mode::TargetColorMode; +pub use threshold_mode::ThresholdMode; +pub use tile_transform::{FlipMode, RepeatMode, TileTransform}; +pub use unit_value::{at_or_above_threshold, finite_unit}; +pub use validation_mode::ValidationMode; +pub use warp_blending::WarpBlending; +pub use warp_mode::WarpMode; +pub use warp_source::WarpSource; +pub use warp_source_mode::WarpSourceMode; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum CoreError { diff --git a/crates/core/src/lighting_output.rs b/crates/core/src/lighting_output.rs new file mode 100644 index 00000000..43054a39 --- /dev/null +++ b/crates/core/src/lighting_output.rs @@ -0,0 +1,49 @@ +//! What Baked Lighting Stylized paints into the base color + +use serde::{Deserialize, Serialize}; + +/// The lit parts Baked Lighting Stylized keeps +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LightingOutput { + /// The lit surface and its highlights + #[default] + DiffuseSpecular, + /// The lit surface only (what Baked Lighting painted before it had highlights) + Diffuse, + /// The highlights only + Specular, +} + +impl LightingOutput { + /// Every output, in the order a list shows them + pub const ALL: [LightingOutput; 3] = [LightingOutput::DiffuseSpecular, LightingOutput::Diffuse, LightingOutput::Specular]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + LightingOutput::DiffuseSpecular => "Diffuse + Specular", + LightingOutput::Diffuse => "Diffuse only", + LightingOutput::Specular => "Specular only", + } + } + + /// The id `effect.set {output}` takes + pub fn id(self) -> &'static str { + match self { + LightingOutput::DiffuseSpecular => "diffuseSpecular", + LightingOutput::Diffuse => "diffuse", + LightingOutput::Specular => "specular", + } + } + + /// Whether the lit surface is kept + pub fn diffuse(self) -> bool { + self != LightingOutput::Specular + } + + /// Whether the highlights are kept + pub fn specular(self) -> bool { + self != LightingOutput::Diffuse + } +} diff --git a/crates/core/src/mask_outline.rs b/crates/core/src/mask_outline.rs new file mode 100644 index 00000000..cbd17456 --- /dev/null +++ b/crates/core/src/mask_outline.rs @@ -0,0 +1,92 @@ +//! The Mask Outline filter's settings and the band it draws + +use serde::{Deserialize, Serialize}; + +use crate::{OutlinePosition, RampCurve, at_or_above_threshold}; + +/// A band along the edge where values cross a threshold, outside, inside or on both sides of the shapes +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MaskOutline { + pub position: OutlinePosition, + /// The band on black; otherwise it is laid over the values below + pub from_black: bool, + /// Values at or above it are inside the shapes (0..1) + pub threshold: f32, + /// How far the band reaches from the edge, a fraction of the UV tile (0..1) + pub width: f32, + /// How much of the band fades out towards its far side (0..1) + pub blur: f32, + /// Bends that fade: below 0 it falls off sooner, above 0 later (−1..1) + pub curve: f32, +} + +impl MaskOutline { + /// The Mask Outline filter as the library adds it + pub const LIBRARY: MaskOutline = MaskOutline { position: OutlinePosition::Outside, from_black: true, threshold: 1.0, width: 0.05, blur: 0.0, curve: 0.0 }; + + /// Whether `value` is inside the shapes + pub fn inside(&self, value: f32) -> bool { + at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold) + } + + /// The curve the band's fade takes (Curve), worked out once per filter + pub fn fade_curve(&self) -> RampCurve { + RampCurve::new(0.0, self.curve) + } + + /// The band at a texel inside the shapes or not, `closeness` to the edge going from 1 at it to 0 at the band's reach, its fade bent by [`MaskOutline::fade_curve`] + pub fn band(&self, fade_curve: RampCurve, inside: bool, closeness: f32) -> f32 { + let closeness = if closeness.is_finite() { closeness.clamp(0.0, 1.0) } else { 0.0 }; + if !self.position.covers(inside) || closeness <= 0.0 || !self.width.is_finite() || self.width <= 0.0 { + return 0.0; + } + + let blur = if self.blur.is_finite() { self.blur.clamp(0.0, 1.0) } else { 0.0 }; + if blur <= 0.0 { + return 1.0; + } + + fade_curve.apply(closeness / blur) + } + + /// The result at a texel of value `value`: the band on black, or over the value + pub fn apply(&self, value: f32, band: f32) -> f32 { + if self.from_black { band } else { value.max(band) } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The band with the curve worked out as the filter does + fn band(filter: MaskOutline, inside: bool, closeness: f32) -> f32 { + filter.band(filter.fade_curve(), inside, closeness) + } + + #[test] + fn the_band_lies_on_its_side_of_the_edge() { + let outline = MaskOutline::LIBRARY; + assert!(outline.inside(1.0) && !outline.inside(0.99)); + assert_eq!(band(outline, false, 0.3), 1.0, "a hard band outside"); + assert_eq!(band(outline, true, 0.3), 0.0, "nothing inside an outside band"); + assert_eq!(band(outline, false, 0.0), 0.0, "nothing past its reach"); + let inside = MaskOutline { position: OutlinePosition::Inside, ..outline }; + assert_eq!((band(inside, true, 0.3), band(inside, false, 0.3)), (1.0, 0.0)); + let both = MaskOutline { position: OutlinePosition::Both, ..outline }; + assert_eq!((band(both, true, 0.3), band(both, false, 0.3)), (1.0, 1.0)); + assert_eq!(outline.apply(0.4, 0.0), 0.0, "from black"); + assert_eq!(MaskOutline { from_black: false, ..outline }.apply(0.4, 0.0), 0.4, "over the values"); + } + + #[test] + fn blur_fades_the_band_and_curve_shape_bends_the_fade() { + let soft = MaskOutline { blur: 1.0, ..MaskOutline::LIBRARY }; + assert!((band(soft, false, 0.5) - 0.5).abs() < 1e-6, "a linear fade"); + assert!(band(MaskOutline { curve: 0.5, ..soft }, false, 0.5) > 0.5, "falls off later"); + assert!(band(MaskOutline { curve: -0.5, ..soft }, false, 0.5) < 0.5, "falls off sooner"); + assert_eq!(band(MaskOutline { blur: 0.5, ..soft }, false, 0.6), 1.0, "only the far part fades"); + assert_eq!(band(MaskOutline { width: f32::NAN, threshold: f32::NAN, ..soft }, false, 0.5), 0.0); + } +} diff --git a/crates/core/src/mirror.rs b/crates/core/src/mirror.rs new file mode 100644 index 00000000..44831b81 --- /dev/null +++ b/crates/core/src/mirror.rs @@ -0,0 +1,99 @@ +//! The Mirror filter's settings and where it reads each texel from + +use serde::{Deserialize, Serialize}; + +use crate::{MirrorCorner, MirrorMode}; + +/// A mirror filter: one side of an axis (or one quarter) of each UV tile copied over the rest +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Mirror { + /// Draws the mirror's axes over the result (Display Debug) + pub debug: bool, + pub mode: MirrorMode, + /// Where the X and Y axes sit across the tile (0..1) + pub offset: [f32; 2], + /// Copies the right (X) or bottom (Y) side instead of the left or top one + pub invert: [bool; 2], + pub corner: MirrorCorner, +} + +impl Mirror { + /// The Mirror filter as the library adds it: left onto right across the middle + pub const LIBRARY: Mirror = Mirror { debug: false, mode: MirrorMode::AxisX, offset: [0.5, 0.5], invert: [false, false], corner: MirrorCorner::TopLeft }; + + /// Half the width of a debug axis line, in texels at 2K + pub const DEBUG_HALF_WIDTH: f32 = 2.0; + + /// Where in its tile (0..1 across, 0..1 down) the texel at `uv` reads from; a copy that reaches past an edge folds back at it + pub fn source(&self, [u, v]: [f32; 2]) -> [f32; 2] { + let across = |at: f32, axis: f32, keep_after: bool| { + let copied = if keep_after { at < axis } else { at > axis }; + fold(if copied { 2.0 * axis - at } else { at }) + }; + match self.mode { + MirrorMode::AxisX => [across(u, self.axis(0), self.invert[0]), v], + MirrorMode::AxisY => [u, across(v, self.axis(1), self.invert[1])], + MirrorMode::Corner => { + let (right, bottom) = self.corner.sides(); + [across(u, 0.5, right), across(v, 0.5, bottom)] + } + } + } + + /// Whether `uv` lies within `half_width` (a fraction of the tile) of one of the mirror's axes + pub fn on_axis(&self, [u, v]: [f32; 2], half_width: f32) -> bool { + let near = |at: f32, axis: f32| (at - axis).abs() <= half_width; + match self.mode { + MirrorMode::AxisX => near(u, self.axis(0)), + MirrorMode::AxisY => near(v, self.axis(1)), + MirrorMode::Corner => near(u, 0.5) || near(v, 0.5), + } + } + + /// The axis position along `axis` (0 = X, 1 = Y), within the tile even from a hostile file + fn axis(&self, axis: usize) -> f32 { + let at = self.offset.get(axis).copied().unwrap_or(0.5); + if at.is_finite() { at.clamp(0.0, 1.0) } else { 0.5 } + } +} + +/// `at` folded back into 0..1 at the tile's edges, as a mirror reflects +fn fold(at: f32) -> f32 { + let wrapped = at.rem_euclid(2.0); + if wrapped > 1.0 { 2.0 - wrapped } else { wrapped } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_mode_reads_the_kept_side() { + let mut mirror = Mirror::LIBRARY; + assert_eq!(mirror.source([0.25, 0.4]), [0.25, 0.4], "the left side stays"); + assert_eq!(mirror.source([0.75, 0.4]), [0.25, 0.4], "the right side reads the left"); + mirror.invert[0] = true; + assert_eq!(mirror.source([0.25, 0.4]), [0.75, 0.4], "inverted, the left side reads the right"); + + mirror.offset[0] = 0.25; + mirror.invert[0] = false; + assert_eq!(mirror.source([0.75, 0.0]), [0.25, 0.0], "a copy past the left edge folds back at it"); + + mirror.mode = MirrorMode::AxisY; + assert_eq!(mirror.source([0.9, 0.75]), [0.9, 0.25], "Axis Y reads the top for the bottom"); + + mirror.mode = MirrorMode::Corner; + mirror.corner = MirrorCorner::BottomRight; + assert_eq!(mirror.source([0.25, 0.25]), [0.75, 0.75], "every quarter reads the kept one"); + assert_eq!(mirror.source([0.75, 0.75]), [0.75, 0.75]); + assert!(mirror.on_axis([0.5, 0.1], 0.01) && mirror.on_axis([0.1, 0.5], 0.01) && !mirror.on_axis([0.1, 0.1], 0.01)); + } + + #[test] + fn a_hostile_offset_stays_in_the_tile() { + let mirror = Mirror { offset: [f32::NAN, f32::INFINITY], ..Mirror::LIBRARY }; + let [u, v] = mirror.source([0.9, 0.9]); + assert!((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)); + } +} diff --git a/crates/core/src/mirror_corner.rs b/crates/core/src/mirror_corner.rs new file mode 100644 index 00000000..43061423 --- /dev/null +++ b/crates/core/src/mirror_corner.rs @@ -0,0 +1,49 @@ +//! The quarter a corner mirror copies + +use serde::{Deserialize, Serialize}; + +/// The quarter of each UV tile a corner mirror keeps and copies over the other three +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MirrorCorner { + #[default] + TopLeft, + TopRight, + BottomLeft, + BottomRight, +} + +impl MirrorCorner { + /// Every corner, in the order a list shows them + pub const ALL: [MirrorCorner; 4] = [MirrorCorner::TopLeft, MirrorCorner::TopRight, MirrorCorner::BottomLeft, MirrorCorner::BottomRight]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + MirrorCorner::TopLeft => "Top Left", + MirrorCorner::TopRight => "Top Right", + MirrorCorner::BottomLeft => "Bottom Left", + MirrorCorner::BottomRight => "Bottom Right", + } + } + + /// The id `effect.set {cornerType}` takes + pub fn id(self) -> &'static str { + match self { + MirrorCorner::TopLeft => "topLeft", + MirrorCorner::TopRight => "topRight", + MirrorCorner::BottomLeft => "bottomLeft", + MirrorCorner::BottomRight => "bottomRight", + } + } + + /// Whether the kept quarter is on the right half and on the bottom half + pub fn sides(self) -> (bool, bool) { + match self { + MirrorCorner::TopLeft => (false, false), + MirrorCorner::TopRight => (true, false), + MirrorCorner::BottomLeft => (false, true), + MirrorCorner::BottomRight => (true, true), + } + } +} diff --git a/crates/core/src/mirror_mode.rs b/crates/core/src/mirror_mode.rs new file mode 100644 index 00000000..6ec9acca --- /dev/null +++ b/crates/core/src/mirror_mode.rs @@ -0,0 +1,39 @@ +//! Which way a mirror filter copies a texture + +use serde::{Deserialize, Serialize}; + +/// The side of an axis, or the corner, a mirror filter copies over the rest of each UV tile +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MirrorMode { + /// Across a vertical axis, left onto right + #[default] + AxisX, + /// Across a horizontal axis, top onto bottom + AxisY, + /// One quarter onto the other three + Corner, +} + +impl MirrorMode { + /// Every mode, in the order a list shows them + pub const ALL: [MirrorMode; 3] = [MirrorMode::AxisX, MirrorMode::AxisY, MirrorMode::Corner]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + MirrorMode::AxisX => "Mirror Axis X", + MirrorMode::AxisY => "Mirror Axis Y", + MirrorMode::Corner => "Mirror Corner", + } + } + + /// The id `effect.set {mode}` takes + pub fn id(self) -> &'static str { + match self { + MirrorMode::AxisX => "axisX", + MirrorMode::AxisY => "axisY", + MirrorMode::Corner => "corner", + } + } +} diff --git a/crates/core/src/oklab.rs b/crates/core/src/oklab.rs new file mode 100644 index 00000000..022f3964 --- /dev/null +++ b/crates/core/src/oklab.rs @@ -0,0 +1,40 @@ +//! The OKLab perceptual color space (Björn Ottosson's public construction): hue, chroma and lightness shifts that keep perceived lightness + +/// Linear sRGB to OKLab `[L, a, b]` +pub fn from_linear([r, g, b]: [f32; 3]) -> [f32; 3] { + let l = (0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt(); + let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt(); + let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt(); + [ + 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s, + 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s, + 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s, + ] +} + +/// OKLab `[L, a, b]` back to linear sRGB (unclamped) +pub fn to_linear([lightness, a, b]: [f32; 3]) -> [f32; 3] { + let l = (lightness + 0.396_337_78 * a + 0.215_803_76 * b).powi(3); + let m = (lightness - 0.105_561_346 * a - 0.063_854_17 * b).powi(3); + let s = (lightness - 0.089_484_18 * a - 1.291_485_5 * b).powi(3); + [ + 4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s, + -1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s, + -0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s, + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn colors_round_trip_and_white_has_lightness_one() { + let white = from_linear([1.0; 3]); + assert!((white[0] - 1.0).abs() < 1e-3 && white[1].abs() < 1e-3 && white[2].abs() < 1e-3, "{white:?}"); + for color in [[0.8, 0.2, 0.1], [0.05, 0.5, 0.9], [0.3, 0.3, 0.3]] { + let back = to_linear(from_linear(color)); + assert!(color.iter().zip(back).all(|(a, b)| (a - b).abs() < 1e-3), "{color:?} -> {back:?}"); + } + } +} diff --git a/crates/core/src/outline_position.rs b/crates/core/src/outline_position.rs new file mode 100644 index 00000000..8e62d6d1 --- /dev/null +++ b/crates/core/src/outline_position.rs @@ -0,0 +1,48 @@ +//! Which side of a mask's edge a Mask Outline draws on + +use serde::{Deserialize, Serialize}; + +/// The side of the threshold edge a Mask Outline's band lies on +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum OutlinePosition { + /// Around the shapes, outside them + #[default] + Outside, + /// Inside the shapes, along their edge + Inside, + /// On both sides of the edge + Both, +} + +impl OutlinePosition { + /// Every position, in the order a switch shows them + pub const ALL: [OutlinePosition; 3] = [OutlinePosition::Outside, OutlinePosition::Inside, OutlinePosition::Both]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + OutlinePosition::Outside => "Outside", + OutlinePosition::Inside => "Inside", + OutlinePosition::Both => "Both", + } + } + + /// The id `effect.set {maskPosition}` takes + pub fn id(self) -> &'static str { + match self { + OutlinePosition::Outside => "outside", + OutlinePosition::Inside => "inside", + OutlinePosition::Both => "both", + } + } + + /// Whether the band covers a texel inside the shapes (`inside`) + pub fn covers(self, inside: bool) -> bool { + match self { + OutlinePosition::Outside => !inside, + OutlinePosition::Inside => inside, + OutlinePosition::Both => true, + } + } +} diff --git a/crates/core/src/pbr_validate.rs b/crates/core/src/pbr_validate.rs new file mode 100644 index 00000000..0690ada2 --- /dev/null +++ b/crates/core/src/pbr_validate.rs @@ -0,0 +1,78 @@ +//! PBR Validate (Metallic Roughness): base colors outside the physically plausible ranges shown in red + +use serde::{Deserialize, Serialize}; + +use crate::ValidationMode; +use crate::blend::lum; +use crate::gradient_input::linear_to_srgb; + +/// A PBR Validate filter: which texels it checks and the ranges it checks them against +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PbrValidate { + pub mode: ValidationMode, + /// Albedo Dark Range Threshold: the darkest valid non-metal base color, in sRGB steps of 255 (30 or 50) + pub albedo_dark: u8, + /// Metal Reflectance Range: the dimmest valid metal base color, in percent of sRGB white (60 or 70) + pub metal_low: u8, +} + +impl PbrValidate { + /// A new PBR Validate: both kinds of texel, the tolerant ranges + pub const LIBRARY: PbrValidate = PbrValidate { mode: ValidationMode::Combined, albedo_dark: 30, metal_low: 60 }; + + /// Albedo Dark Range Threshold's choices + pub const ALBEDO_DARK: [u8; 2] = [50, 30]; + + /// Metal Reflectance Range's choices + pub const METAL_LOW: [u8; 2] = [70, 60]; + + /// The brightest valid non-metal base color, in sRGB steps of 255 + const ALBEDO_BRIGHT: f32 = 240.0; + + /// Metal from this value up counts as metal + const METAL_THRESHOLD: f32 = 0.5; + + /// Metal Reflectance Range's choices are percent of sRGB white + const PERCENT: f32 = 100.0; + + /// Base Color Range's choices are sRGB steps of 255 + const SRGB_STEPS: f32 = 255.0; + + /// The color of a texel outside its range + pub const INVALID: [f32; 3] = [1.0, 0.0, 0.0]; + + /// Straight linear base color `color` of a texel with metal `metal`: its own color when valid or not checked, red when not + pub fn check(&self, color: [f32; 3], metal: f32) -> [f32; 3] { + let srgb = linear_to_srgb(lum(color).clamp(0.0, 1.0)); + let valid = if metal >= Self::METAL_THRESHOLD { + !self.mode.checks_metal() || srgb >= f32::from(self.metal_low) / Self::PERCENT + } else { + !self.mode.checks_albedo() || (f32::from(self.albedo_dark) / Self::SRGB_STEPS..=Self::ALBEDO_BRIGHT / Self::SRGB_STEPS).contains(&srgb) + }; + if valid { color } else { Self::INVALID } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gradient_input::srgb_to_linear; + + #[test] + fn colors_outside_their_range_turn_red() { + let gray = |srgb: f32| [srgb_to_linear(srgb / 255.0); 3]; + let filter = PbrValidate::LIBRARY; + assert_eq!(filter.check(gray(40.0), 0.0), gray(40.0), "above 30 sRGB"); + assert_eq!(filter.check(gray(20.0), 0.0), PbrValidate::INVALID, "too dark"); + assert_eq!(filter.check(gray(250.0), 0.0), PbrValidate::INVALID, "too bright"); + assert_eq!(PbrValidate { albedo_dark: 50, ..filter }.check(gray(40.0), 0.0), PbrValidate::INVALID); + assert_eq!(filter.check(gray(140.0), 1.0), PbrValidate::INVALID, "a dim metal"); + assert_eq!(filter.check(gray(170.0), 1.0), gray(170.0), "60% reflective"); + assert_eq!(PbrValidate { metal_low: 70, ..filter }.check(gray(170.0), 1.0), PbrValidate::INVALID); + let albedo = PbrValidate { mode: ValidationMode::Albedo, ..filter }; + assert_eq!(albedo.check(gray(140.0), 1.0), gray(140.0), "Albedo leaves metal unchecked"); + let metal = PbrValidate { mode: ValidationMode::Metal, ..filter }; + assert_eq!(metal.check(gray(20.0), 0.0), gray(20.0), "Metal leaves non-metal unchecked"); + } +} diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index b182682d..97d35be8 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -653,6 +653,7 @@ impl Project { } let effects = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()); out.extend(effects.filter(|e| e.kind.reads(Some(anchor))).map(|e| (layer.id, Some(e.id)))); + out.extend(effects.filter(|e| e.reads(Some(anchor))).map(|e| (layer.id, Some(e.id)))); } out } @@ -868,7 +869,7 @@ mod tests { material.sources.insert(Channel::Roughness, Source::Uniform([0.2; 3])); l.content_effects = vec![ Effect::new(fill, EffectKind::Material(material)), - Effect::new(hsl, EffectKind::Filter(Filter::Hsl { hue: 0.25, saturation: -0.5, lightness: 0.1 })), + Effect::new(hsl, EffectKind::Filter(Filter::Hsl { hue: 0.25, saturation: -0.5, lightness: 0.1, perceptive: false })), Effect::new(anchor, EffectKind::Anchor), ]; let id = p.insert_layer(0, l, None, false).unwrap(); diff --git a/crates/core/src/slope_blending.rs b/crates/core/src/slope_blending.rs new file mode 100644 index 00000000..766016b9 --- /dev/null +++ b/crates/core/src/slope_blending.rs @@ -0,0 +1,39 @@ +//! How a Blur Slope combines what it reads downhill + +use serde::{Deserialize, Serialize}; + +/// What a Blur Slope keeps of the values it reads along the slope +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SlopeBlending { + /// Their average: the values smeared downhill + #[default] + Blur, + /// The smallest of them, per component: light shapes eaten away downhill + Min, + /// The largest of them, per component: light shapes grown downhill + Max, +} + +impl SlopeBlending { + /// Every choice, in the order a panel lists them + pub const ALL: [SlopeBlending; 3] = [SlopeBlending::Blur, SlopeBlending::Min, SlopeBlending::Max]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + SlopeBlending::Blur => "Blur", + SlopeBlending::Min => "Min", + SlopeBlending::Max => "Max", + } + } + + /// The id `effect.set` takes + pub fn id(self) -> &'static str { + match self { + SlopeBlending::Blur => "blur", + SlopeBlending::Min => "min", + SlopeBlending::Max => "max", + } + } +} diff --git a/crates/core/src/source_color_mode.rs b/crates/core/src/source_color_mode.rs new file mode 100644 index 00000000..08b3da42 --- /dev/null +++ b/crates/core/src/source_color_mode.rs @@ -0,0 +1,36 @@ +//! Where Color Match takes the color it moves from + +use serde::{Deserialize, Serialize}; + +/// Color Match's Source Color Mode: the mean color of the whole texture, its Source Color, or its Input image +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SourceColorMode { + #[default] + Average, + Parameter, + Input, +} + +impl SourceColorMode { + /// Every mode, in the order a panel shows them + pub const ALL: [SourceColorMode; 3] = [SourceColorMode::Average, SourceColorMode::Parameter, SourceColorMode::Input]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + SourceColorMode::Average => "Average", + SourceColorMode::Parameter => "Parameter", + SourceColorMode::Input => "Input", + } + } + + /// The id `effect.set {sourceColorMode}` takes + pub fn id(self) -> &'static str { + match self { + SourceColorMode::Average => "average", + SourceColorMode::Parameter => "parameter", + SourceColorMode::Input => "input", + } + } +} diff --git a/crates/core/src/source_slope_blur.rs b/crates/core/src/source_slope_blur.rs new file mode 100644 index 00000000..27aeacff --- /dev/null +++ b/crates/core/src/source_slope_blur.rs @@ -0,0 +1,65 @@ +//! The Blur Slope filter's settings and how far it reads + +use serde::{Deserialize, Serialize}; + +use crate::{SlopeBlending, SourceWarp, WarpSource, WarpSourceMode, source_warp}; + +/// Values read downhill along a source's slope, averaged or kept at their smallest or largest +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceSlopeBlur { + /// The default noise's seed + pub seed: u32, + /// How far downhill a texel reads, a share of the UV tile before the divider (0..1) + pub intensity: f32, + /// Divides `intensity` (1, 10, 100 or 1000) for short smears + pub divider: u16, + pub blending: SlopeBlending, + /// The share of the reads taken along the way (0..1): fewer is faster and grainier + pub quality: f32, + pub source: WarpSource, +} + +impl SourceSlopeBlur { + /// The Blur Slope filter as the library adds it + pub const LIBRARY: SourceSlopeBlur = + SourceSlopeBlur { seed: 0, intensity: 0.3, divider: 10, blending: SlopeBlending::Blur, quality: 1.0, source: WarpSource::LIBRARY }; + + /// How many texels downhill a texel reads at most at `res` texels across a UV tile + pub fn move_texels(&self, res: u32) -> f32 { + source_warp::move_texels(self.intensity, self.divider, res) + } + + /// How many of `most` reads along the way Quality keeps (at least one past the texel itself) + pub fn samples(&self, most: u32) -> u32 { + let quality = if self.quality.is_finite() { self.quality.clamp(0.0, 1.0) } else { 1.0 }; + ((most as f32 * quality).round() as u32).clamp(1, most.max(1)) + } + + /// How many texels around a texel the filter reads at `res` texels across a UV tile: downhill, and where it measures its source's slope + pub fn reach(&self, res: u32) -> f32 { + let moves = self.move_texels(res); + if self.source.mode != WarpSourceMode::PreviousInput { + return moves; + } + + moves + SourceWarp::probe_texels(res) + self.source.blur_texels(res) * std::f32::consts::FRAC_1_SQRT_2 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_follow_intensity_quality_and_source() { + let slope = SourceSlopeBlur::LIBRARY; + assert!((slope.move_texels(2048) - 61.44).abs() < 1e-3, "0.3 ÷ 10 of the tile"); + assert_eq!((slope.samples(24), SourceSlopeBlur { quality: 0.5, ..slope }.samples(24)), (24, 12)); + assert_eq!(SourceSlopeBlur { quality: 0.0, ..slope }.samples(24), 1, "always one read downhill"); + assert_eq!(SourceSlopeBlur { quality: f32::NAN, ..slope }.samples(24), 24); + let input = SourceSlopeBlur { source: WarpSource { mode: WarpSourceMode::PreviousInput, ..WarpSource::LIBRARY }, ..slope }; + assert!((input.reach(2048) - (61.44 + 8.0)).abs() < 1e-3, "plus where it measures the slope"); + assert_eq!(SourceSlopeBlur { intensity: f32::INFINITY, ..slope }.move_texels(2048), 0.0); + } +} diff --git a/crates/core/src/stylized_lighting.rs b/crates/core/src/stylized_lighting.rs new file mode 100644 index 00000000..3c5289d8 --- /dev/null +++ b/crates/core/src/stylized_lighting.rs @@ -0,0 +1,157 @@ +//! What Baked Lighting Stylized adds to Baked Lighting's sun and ambient: sky colors, two more lights, cavity, edges and highlights + +use serde::{Deserialize, Serialize}; + +use crate::directional_light::DirectionalLight; +use crate::lighting_output::LightingOutput; +use crate::stylized_shading::StylizedShading; +use crate::sun_and_sky::SunAndSky; + +/// Baked Lighting Stylized's settings past the sun's direction and strength, the sky's strength and Diffuse AO (kept on the filter, as Baked Lighting saved them) +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StylizedLighting { + pub sun_color: [f32; 3], + /// The ambient light from straight above, at the horizon and from below; normals between blend them + pub sky_color: [f32; 3], + pub horizon_color: [f32; 3], + pub ground_color: [f32; 3], + /// Light 1 and Light 2 + pub lights: [DirectionalLight; 2], + /// How much the cavities (concave curvature) darken the lit surface and its highlights + pub diffuse_cavity: f32, + pub specular_cavity: f32, + /// How much the baked ambient occlusion darkens the highlights + pub specular_ao: f32, + /// The concavity (and convexity, for edges) over which cavity and edges fade in: 0 is a hard step + pub cavity_smoothness: f32, + /// How much the edges (convex curvature) lighten toward white + pub edges_intensity: f32, + pub edges_smoothness: f32, + /// Reads the Specular and Glossiness channels instead of Metallic and Roughness (Input) + pub specular_glossiness: bool, + pub output: LightingOutput, + /// The reflectance of non-metals at normal incidence + pub dielectric_reflectance: f32, + /// Lights the mesh's own normals, without the baked normal and height detail (Normal Details Type Mesh only) + pub mesh_only: bool, + pub height_to_normal: f32, +} + +/// The reflectance of non-metals at normal incidence +pub const DIELECTRIC_REFLECTANCE: f32 = 0.04; + +impl StylizedLighting { + /// The settings that light exactly as Baked Lighting did: white light and sky, no extra lights, cavity, edges or highlights, the mesh's own normals + pub const PLAIN: StylizedLighting = StylizedLighting { + sun_color: [1.0; 3], + sky_color: [1.0; 3], + horizon_color: [1.0; 3], + ground_color: [1.0; 3], + lights: [DirectionalLight::off(90.0), DirectionalLight::off(180.0)], + diffuse_cavity: 0.0, + specular_cavity: 0.0, + specular_ao: 0.0, + cavity_smoothness: 0.25, + edges_intensity: 0.0, + edges_smoothness: 0.0, + specular_glossiness: false, + output: LightingOutput::Diffuse, + dielectric_reflectance: DIELECTRIC_REFLECTANCE, + mesh_only: true, + height_to_normal: 1.0, + }; + + /// A new Baked Lighting Stylized: a warm sun, a blue sky over a brown ground, highlights, and the baked normal and height detail + pub fn library() -> StylizedLighting { + StylizedLighting { + sun_color: [1.0, 0.905, 0.716], + sky_color: [0.305, 0.456, 0.791], + horizon_color: [0.644, 0.644, 0.61], + ground_color: [0.102, 0.08, 0.061], + output: LightingOutput::DiffuseSpecular, + mesh_only: false, + ..StylizedLighting::PLAIN + } + } + + /// These settings lit by `light`, worked out once for the shading of every texel + pub fn shading(&self, light: SunAndSky) -> StylizedShading { + StylizedShading::new(self, light) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Channel, Filter}; + + const UP: [f32; 3] = [0.0, 1.0, 0.0]; + + fn material(roughness: f32) -> Vec<[f32; 3]> { + let mut channels: Vec<[f32; 3]> = Channel::ALL.iter().map(|c| c.default_value()).collect(); + channels[Channel::Roughness.index()] = [roughness; 3]; + channels + } + + fn light(elevation: f32, intensity: f32, sky_intensity: f32) -> SunAndSky { + SunAndSky { sun: DirectionalLight { azimuth: 0.0, elevation, intensity, color: [1.0; 3] }, sky_intensity, diffuse_ao: 0.5 } + } + + /// The plain settings light as Baked Lighting did: the base color times sun facing plus occluded ambient + #[test] + fn plain_settings_light_as_baked_lighting_did() { + let legacy = Filter::BakedLighting { azimuth: 0.0, elevation: 30.0, light: 0.6, ambient: 0.4, occlusion: 0.5, stylized: None }; + for (nrm, ao) in [(UP, 1.0), ([0.6, 0.8, 0.0], 0.3), ([0.0, -1.0, 0.0], 0.7)] { + let k = legacy.baked_light(nrm, ao).unwrap_or(f32::NAN); + let shaded = StylizedLighting::PLAIN.shading(light(30.0, 0.6, 0.4)).shade([0.5, 0.25, 1.0], nrm, [ao, 0.5], &material(0.5)); + let expected = [0.5f32, 0.25, 1.0].map(|x| (x * k).clamp(0.0, 1.0)); + assert!(shaded.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-5), "{nrm:?}: {shaded:?} vs {expected:?}"); + } + } + + /// The sky, horizon and ground colors light a surface by where it faces; Light 1 adds its color + #[test] + fn sky_colors_and_extra_lights() { + let colors = StylizedLighting { sky_color: [0.0, 0.0, 1.0], horizon_color: [0.0, 1.0, 0.0], ground_color: [1.0, 0.0, 0.0], ..StylizedLighting::PLAIN }; + let sky = light(45.0, 0.0, 1.0); + let white = [1.0; 3]; + assert_eq!(colors.shading(sky).shade(white, UP, [1.0, 0.5], &material(0.5)), [0.0, 0.0, 1.0]); + assert_eq!(colors.shading(sky).shade(white, [1.0, 0.0, 0.0], [1.0, 0.5], &material(0.5)), [0.0, 1.0, 0.0]); + assert_eq!(colors.shading(sky).shade(white, [0.0, -1.0, 0.0], [1.0, 0.5], &material(0.5)), [1.0, 0.0, 0.0]); + + let mut extra = StylizedLighting::PLAIN; + extra.lights[0] = DirectionalLight { azimuth: 0.0, elevation: 90.0, intensity: 0.5, color: [1.0, 0.0, 0.0] }; + let dark = light(45.0, 0.0, 0.0); + let lit = extra.shading(dark).shade(white, UP, [1.0, 0.5], &material(0.5)); + assert!((lit[0] - 0.5).abs() < 1e-5 && lit[1] == 0.0, "{lit:?}"); + } + + /// Highlights: a smooth surface shines brighter than a rough one; Specular only keeps them alone, Diffuse only drops them + #[test] + fn highlights_follow_roughness_and_the_output() { + let sun = light(90.0, 1.0, 0.0); + let shiny = StylizedLighting { output: LightingOutput::Specular, ..StylizedLighting::library() }; + let albedo = [0.0; 3]; + let smooth = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2)); + let rough = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.9)); + assert!(smooth[0] > rough[0] + 0.1 && rough[0] > 0.0, "{smooth:?} {rough:?}"); + let diffuse = StylizedLighting { output: LightingOutput::Diffuse, ..StylizedLighting::library() }; + assert_eq!(diffuse.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2)), [0.0; 3]); + } + + /// Cavities darken the lit surface by Diffuse Cavity; edges lighten toward white by Edges Intensity + #[test] + fn cavities_darken_and_edges_lighten() { + let sky = light(45.0, 0.0, 1.0); + let gray = [0.5; 3]; + let cavities = StylizedLighting { diffuse_cavity: 1.0, ..StylizedLighting::PLAIN }; + assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat: no cavity"); + assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity"); + let sun = light(90.0, 1.0, 0.0); + assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat in the sun: no cavity"); + assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity in the sun"); + let edges = StylizedLighting { edges_intensity: 1.0, ..StylizedLighting::PLAIN }; + assert_eq!(edges.shading(sky).shade(gray, UP, [1.0, 0.9], &material(0.5)), [1.0; 3], "a sharp edge"); + } +} diff --git a/crates/core/src/sun_and_sky.rs b/crates/core/src/sun_and_sky.rs new file mode 100644 index 00000000..e24245da --- /dev/null +++ b/crates/core/src/sun_and_sky.rs @@ -0,0 +1,11 @@ +//! The sun and sky Baked Lighting Stylized shades with + +use crate::directional_light::DirectionalLight; + +/// The sun and sky a [`StylizedLighting`](crate::StylizedLighting) shades with, kept on the filter as Baked Lighting saved them +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SunAndSky { + pub sun: DirectionalLight, + pub sky_intensity: f32, + pub diffuse_ao: f32, +} diff --git a/crates/core/src/target_color_mode.rs b/crates/core/src/target_color_mode.rs new file mode 100644 index 00000000..ffcafdab --- /dev/null +++ b/crates/core/src/target_color_mode.rs @@ -0,0 +1,33 @@ +//! Where Color Match takes the color it moves to + +use serde::{Deserialize, Serialize}; + +/// Color Match's Target Color Mode: its Target Color or its Image Input +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TargetColorMode { + #[default] + Parameter, + ImageInput, +} + +impl TargetColorMode { + /// Every mode, in the order a panel shows them + pub const ALL: [TargetColorMode; 2] = [TargetColorMode::Parameter, TargetColorMode::ImageInput]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + TargetColorMode::Parameter => "Parameter", + TargetColorMode::ImageInput => "Image Input", + } + } + + /// The id `effect.set {targetColorMode}` takes + pub fn id(self) -> &'static str { + match self { + TargetColorMode::Parameter => "parameter", + TargetColorMode::ImageInput => "imageInput", + } + } +} diff --git a/crates/core/src/threshold_mode.rs b/crates/core/src/threshold_mode.rs new file mode 100644 index 00000000..3dc3b05b --- /dev/null +++ b/crates/core/src/threshold_mode.rs @@ -0,0 +1,90 @@ +//! How a threshold compares a value with its level + +use serde::{Deserialize, Serialize}; + +/// Which values a threshold turns white: those above its level, at or above it, below it, or at or below it +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ThresholdMode { + Greater, + /// What thresholds did in projects saved before the modes + #[default] + GreaterOrEqual, + Lower, + LowerOrEqual, +} + +impl ThresholdMode { + /// Every mode, in the order a panel shows them + pub const ALL: [ThresholdMode; 4] = [ThresholdMode::Greater, ThresholdMode::GreaterOrEqual, ThresholdMode::Lower, ThresholdMode::LowerOrEqual]; + + /// The comparison sign a panel shows + pub fn sign(self) -> &'static str { + match self { + ThresholdMode::Greater => ">", + ThresholdMode::GreaterOrEqual => "≥", + ThresholdMode::Lower => "<", + ThresholdMode::LowerOrEqual => "≤", + } + } + + /// The name a tooltip shows + pub fn label(self) -> &'static str { + match self { + ThresholdMode::Greater => "Greater", + ThresholdMode::GreaterOrEqual => "Greater or equal", + ThresholdMode::Lower => "Lower", + ThresholdMode::LowerOrEqual => "Lower or equal", + } + } + + /// The id `effect.set {mode}` takes + pub fn id(self) -> &'static str { + match self { + ThresholdMode::Greater => "greater", + ThresholdMode::GreaterOrEqual => "greaterOrEqual", + ThresholdMode::Lower => "lower", + ThresholdMode::LowerOrEqual => "lowerOrEqual", + } + } + + /// Whether `value` turns white against `level` + pub fn passes(self, value: f32, level: f32) -> bool { + match self { + ThresholdMode::Greater => value > level, + ThresholdMode::GreaterOrEqual => value >= level, + ThresholdMode::Lower => value < level, + ThresholdMode::LowerOrEqual => value <= level, + } + } + + /// Whether it is the mode projects saved before the modes read as (it is then left out of a saved file) + pub fn is_default(&self) -> bool { + *self == ThresholdMode::default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ChannelKind, Filter}; + + #[test] + fn a_threshold_saved_before_the_modes_reads_and_saves_as_before() { + let saved = r#"{"Threshold":{"level":0.5}}"#; + let filter: Filter = serde_json::from_str(saved).unwrap(); + assert_eq!(filter, Filter::Threshold { level: 0.5, mode: ThresholdMode::GreaterOrEqual }); + assert_eq!(serde_json::to_string(&filter).unwrap(), saved); + assert_eq!(filter.point(ChannelKind::Scalar, [0.5; 3]), Some([1.0; 3]), "a value at the level turns white as before"); + } + + #[test] + fn each_mode_compares_its_way() { + let at = |mode: ThresholdMode, value: f32| Filter::Threshold { level: 0.5, mode }.point(ChannelKind::Scalar, [value; 3]).map(|v| v[0]); + assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Greater, value)), [Some(0.0), Some(0.0), Some(1.0)]); + assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Lower, value)), [Some(1.0), Some(0.0), Some(0.0)]); + assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::LowerOrEqual, value)), [Some(1.0), Some(1.0), Some(0.0)]); + let saved = serde_json::to_string(&Filter::Threshold { level: 0.01, mode: ThresholdMode::LowerOrEqual }).unwrap(); + assert!(saved.contains(r#""mode":"lowerOrEqual""#), "{saved}"); + } +} diff --git a/crates/core/src/tile_transform.rs b/crates/core/src/tile_transform.rs new file mode 100644 index 00000000..a834f7c8 --- /dev/null +++ b/crates/core/src/tile_transform.rs @@ -0,0 +1,225 @@ +//! The Transform filter's settings and where it reads each texel from + +use serde::{Deserialize, Serialize}; + +mod flip_mode; +mod repeat_mode; + +pub use flip_mode::FlipMode; +pub use repeat_mode::RepeatMode; + +/// A turn this close to a whole number of quarter turns (in quarter turns) keeps the tile's edges meeting as it is +const SQUARE_TURN_TOLERANCE: f32 = 1e-4; + +/// A shift or step this small (a share of the tile) moves no texel +const IDENTITY_TOLERANCE: f32 = 1e-6; + +/// Degrees in a quarter turn +const QUARTER_TURN_DEGREES: f32 = 90.0; + +/// A Transform filter: each UV tile's content scaled, turned and moved about the tile's centre, then flipped +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TileTransform { + pub repeat: RepeatMode, + pub flip: FlipMode, + /// How many times the content fits across and down the tile (2 = twice, half as big), as a fill's Tiling + pub scaling: [f32; 2], + /// How far the content moves, in tiles; positive reads further right and down, as a fill's Offset + pub offset: [f32; 2], + /// Turns only by angles that keep the tile's edges meeting, so a repeating result stays seamless + pub tile_safe: bool, + /// Degrees + pub rotation: f32, +} + +impl TileTransform { + /// The Transform filter as the library adds it: no change, repeating, tile safe + pub const LIBRARY: TileTransform = TileTransform { + repeat: RepeatMode::HorizontallyAndVertically, + flip: FlipMode::None, + scaling: [1.0, 1.0], + offset: [0.0, 0.0], + tile_safe: true, + rotation: 0.0, + }; + + /// The smallest and largest Scaling it renders (a hostile file's values come back within) + pub const SCALING: (f32, f32) = (0.01, 64.0); + + /// The farthest Offset it renders, in tiles + pub const MAX_OFFSET: f32 = 64.0; + + /// Where in the tile (0..1 across and down, before any repeat) the texel at `uv` reads from, as `linear · uv + shift`; the columns of `linear` are what one step across and one step down the result move in the source + pub fn affine(&self) -> ([[f32; 2]; 2], [f32; 2]) { + let finite = |value: f32, fallback: f32| if value.is_finite() { value } else { fallback }; + let (low, high) = Self::SCALING; + let scaling = self.scaling.map(|scale| finite(scale, 1.0).clamp(low, high)); + let rotation = finite(self.rotation, 0.0); + let (sin, cos) = rotation.to_radians().sin_cos(); + + // Turn, then scale (a fill's Tiling convention): one step across moves (cos, sin) scaled + let mut columns = [[cos * scaling[0], sin * scaling[1]], [-sin * scaling[0], cos * scaling[1]]]; + let quarter_turns = rotation / QUARTER_TURN_DEGREES; + let square = (quarter_turns - quarter_turns.round()).abs() < SQUARE_TURN_TOLERANCE; + + if self.tile_safe && !square { + let exact = columns; + + // Whole steps of the source per tile edge keep the edges meeting; a step can never vanish + for column in &mut columns { + let rounded = column.map(f32::round); + *column = if rounded == [0.0, 0.0] { + if column[0].abs() >= column[1].abs() { [column[0].signum(), 0.0] } else { [0.0, column[1].signum()] } + } else { + rounded + }; + } + + // Steps rounded onto one line would read a single line of the source: the one rounded further takes the nearest whole step that turns as the exact pair does + if determinant(columns) <= 0.0 { + let [across, down] = columns; + let across_further = squared_distance(across, exact[0]) >= squared_distance(down, exact[1]); + columns = if across_further { + turning_step(exact[0], |step| [step, down]).map_or(columns, |step| [step, down]) + } else { + turning_step(exact[1], |step| [across, step]).map_or(columns, |step| [across, step]) + }; + } + } + + let [flip_x, flip_y] = self.flip.sides(); + if flip_x { + columns[0] = columns[0].map(|v| -v); + } + if flip_y { + columns[1] = columns[1].map(|v| -v); + } + + let offset = self.offset.map(|along| finite(along, 0.0).clamp(-Self::MAX_OFFSET, Self::MAX_OFFSET)); + + // About the tile's centre: the centre reads the centre moved by the offset + let shift = [0, 1].map(|axis| 0.5 + offset[axis] - 0.5 * (columns[0][axis] + columns[1][axis])); + (columns, shift) + } + + /// Whether it changes nothing (a turn a hair short of a whole one included) + pub fn is_identity(&self) -> bool { + let (columns, shift) = self.affine(); + let steps = [columns[0][0] - 1.0, columns[0][1], columns[1][0], columns[1][1] - 1.0]; + steps.iter().chain(&shift).all(|along| along.abs() < IDENTITY_TOLERANCE) + } +} + +/// How the second column turns from the first: positive anticlockwise, as every exact turn and scale does, 0 when they lie on one line +fn determinant([across, down]: [[f32; 2]; 2]) -> f32 { + across[0] * down[1] - across[1] * down[0] +} + +fn squared_distance(a: [f32; 2], b: [f32; 2]) -> f32 { + (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) +} + +/// The whole step nearest `exact` (a corner of the cell it lies in) whose columns from `pair` turn as an exact pair does; a corner usually does; otherwise the rounded pair stays +fn turning_step(exact: [f32; 2], pair: impl Fn([f32; 2]) -> [[f32; 2]; 2]) -> Option<[f32; 2]> { + let [x, y] = exact.map(f32::floor); + [[x, y], [x + 1.0, y], [x, y + 1.0], [x + 1.0, y + 1.0]] + .into_iter() + .filter(|corner| determinant(pair(*corner)) > 0.0) + .min_by(|a, b| squared_distance(*a, exact).total_cmp(&squared_distance(*b, exact))) +} + +#[cfg(test)] +mod tests { + use super::*; + + impl TileTransform { + /// Where the texel at `uv` reads from in its tile (0..1), or None where the content does not repeat and no longer reaches (the renderer's read, without its bilinear corners) + fn source(&self, [u, v]: [f32; 2]) -> Option<[f32; 2]> { + let (columns, shift) = self.affine(); + let at = [0, 1].map(|axis| columns[0][axis] * u + columns[1][axis] * v + shift[axis]); + match self.repeat { + RepeatMode::HorizontallyAndVertically => Some(at.map(|along| along.rem_euclid(1.0))), + RepeatMode::None => at.iter().all(|along| (0.0..=1.0).contains(along)).then_some(at), + } + } + } + + fn near(a: [f32; 2], b: [f32; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-4 && (a[1] - b[1]).abs() < 1e-4 + } + + #[test] + fn the_library_transform_reads_each_texel_from_itself() { + let transform = TileTransform::LIBRARY; + assert!(transform.is_identity()); + assert!(near(transform.source([0.3, 0.7]).unwrap_or_default(), [0.3, 0.7])); + } + + #[test] + fn scaling_offset_and_flip_move_the_reads_about_the_centre() { + let mut transform = TileTransform { scaling: [2.0, 2.0], ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.5, 0.5]), "the centre stays"); + assert!(near(transform.source([0.75, 0.5]).unwrap_or_default(), [0.0, 0.5]), "twice the content: a quarter tile reads half a tile on"); + transform.repeat = RepeatMode::None; + assert_eq!(transform.source([0.9, 0.5]), None, "past the content reads nothing without repeat"); + transform = TileTransform { offset: [0.25, 0.0], ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.75, 0.5])); + assert!(near(transform.source([0.9, 0.5]).unwrap_or_default(), [0.15, 0.5]), "the read wraps round the tile"); + transform = TileTransform { flip: FlipMode::Horizontally, ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.8, 0.3])); + transform.flip = FlipMode::Vertically; + assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.2, 0.7])); + } + + #[test] + fn a_tile_safe_turn_moves_whole_tiles_per_edge() { + let transform = TileTransform { scaling: [2.0, 2.0], rotation: 30.0, ..TileTransform::LIBRARY }; + let (columns, _) = transform.affine(); + assert_eq!(columns, [[2.0, 1.0], [-1.0, 2.0]], "the turn snaps to whole steps, about 26.6°"); + + // A small turn of the plain tile snaps back to no turn, never to nothing + let small = TileTransform { rotation: 10.0, ..TileTransform::LIBRARY }; + assert_eq!(small.affine().0, [[1.0, 0.0], [0.0, 1.0]]); + let tiny = TileTransform { scaling: [0.1, 0.1], rotation: 45.0, ..TileTransform::LIBRARY }; + assert!(tiny.affine().0.iter().all(|column| column != &[0.0, 0.0])); + + // Unsafe, the turn is exact + let free = TileTransform { tile_safe: false, ..transform }; + assert!((free.affine().0[0][1] - 2.0 * 30f32.to_radians().sin()).abs() < 1e-5); + + // A square turn keeps its scaling + let square = TileTransform { scaling: [1.5, 1.5], rotation: 90.0, ..TileTransform::LIBRARY }; + assert!((square.affine().0[1][0] + 1.5).abs() < 1e-5); + + // A turn just short of a whole one is square too (a tiny negative turn is stored that way) + let nearly_whole = TileTransform { scaling: [1.5, 1.5], rotation: 359.99995, ..TileTransform::LIBRARY }; + assert!((nearly_whole.affine().0[0][0] - 1.5).abs() < 1e-5, "{:?}", nearly_whole.affine().0); + } + + #[test] + fn a_tile_safe_turn_never_rounds_both_steps_onto_one_line() { + // Narrow and tall, turned half a quarter: both steps round straight down, so one moves off that line + let narrow = TileTransform { scaling: [0.1, 2.0], rotation: 45.0, ..TileTransform::LIBRARY }; + + let (columns, _) = narrow.affine(); + + assert!(determinant(columns) > 0.0, "the source is read in two directions: {columns:?}"); + } + + #[test] + fn a_turn_a_hair_short_of_a_whole_one_changes_nothing() { + for tile_safe in [true, false] { + let transform = TileTransform { rotation: 359.99998, tile_safe, ..TileTransform::LIBRARY }; + assert!(transform.is_identity(), "tile safe {tile_safe}: {:?}", transform.affine()); + } + assert!(!TileTransform { rotation: 359.9, tile_safe: false, ..TileTransform::LIBRARY }.is_identity()); + } + + #[test] + fn hostile_values_stay_in_the_tile() { + let transform = TileTransform { scaling: [f32::NAN, f32::INFINITY], offset: [f32::NAN, -1e30], rotation: f32::INFINITY, ..TileTransform::LIBRARY }; + let [u, v] = transform.source([0.9, 0.9]).unwrap_or_default(); + assert!((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)); + } +} diff --git a/crates/core/src/tile_transform/flip_mode.rs b/crates/core/src/tile_transform/flip_mode.rs new file mode 100644 index 00000000..fc008c48 --- /dev/null +++ b/crates/core/src/tile_transform/flip_mode.rs @@ -0,0 +1,49 @@ +use serde::{Deserialize, Serialize}; + +/// Which way the Transform filter turns its result over +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FlipMode { + #[default] + None, + /// Left and right swap + Horizontally, + /// Top and bottom swap + Vertically, + HorizontallyAndVertically, +} + +impl FlipMode { + /// Every mode, in the order a list shows them + pub const ALL: [FlipMode; 4] = [FlipMode::None, FlipMode::Horizontally, FlipMode::Vertically, FlipMode::HorizontallyAndVertically]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + FlipMode::None => "None", + FlipMode::Horizontally => "Horizontally", + FlipMode::Vertically => "Vertically", + FlipMode::HorizontallyAndVertically => "Horizontally & Vertically", + } + } + + /// The id `effect.set {flipMode}` takes + pub fn id(self) -> &'static str { + match self { + FlipMode::None => "none", + FlipMode::Horizontally => "horizontally", + FlipMode::Vertically => "vertically", + FlipMode::HorizontallyAndVertically => "horizontallyAndVertically", + } + } + + /// Whether it swaps across (left and right) and down (top and bottom) + pub fn sides(self) -> [bool; 2] { + match self { + FlipMode::None => [false, false], + FlipMode::Horizontally => [true, false], + FlipMode::Vertically => [false, true], + FlipMode::HorizontallyAndVertically => [true, true], + } + } +} diff --git a/crates/core/src/tile_transform/repeat_mode.rs b/crates/core/src/tile_transform/repeat_mode.rs new file mode 100644 index 00000000..adc7be88 --- /dev/null +++ b/crates/core/src/tile_transform/repeat_mode.rs @@ -0,0 +1,33 @@ +use serde::{Deserialize, Serialize}; + +/// Whether a moved texture repeats across its UV tile or leaves empty where it no longer reaches +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum RepeatMode { + /// Past the tile's edge reads empty + None, + /// The tile repeats both ways, so the result stays seamless + #[default] + HorizontallyAndVertically, +} + +impl RepeatMode { + /// Every mode, in the order a list shows them + pub const ALL: [RepeatMode; 2] = [RepeatMode::None, RepeatMode::HorizontallyAndVertically]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + RepeatMode::None => "None", + RepeatMode::HorizontallyAndVertically => "Horizontally & Vertically", + } + } + + /// The id `effect.set {repeatMode}` takes + pub fn id(self) -> &'static str { + match self { + RepeatMode::None => "none", + RepeatMode::HorizontallyAndVertically => "horizontallyAndVertically", + } + } +} diff --git a/crates/core/src/validation_mode.rs b/crates/core/src/validation_mode.rs new file mode 100644 index 00000000..b46ac99a --- /dev/null +++ b/crates/core/src/validation_mode.rs @@ -0,0 +1,46 @@ +//! Which texels PBR Validate checks + +use serde::{Deserialize, Serialize}; + +/// PBR Validate's Validation Mode: the non-metal base colors, the metal ones, or both +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ValidationMode { + Albedo, + Metal, + #[default] + Combined, +} + +impl ValidationMode { + /// Every mode, in the order a switch shows them + pub const ALL: [ValidationMode; 3] = [ValidationMode::Albedo, ValidationMode::Metal, ValidationMode::Combined]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + ValidationMode::Albedo => "Albedo", + ValidationMode::Metal => "Metal", + ValidationMode::Combined => "Combined", + } + } + + /// The id `effect.set {validationMode}` takes + pub fn id(self) -> &'static str { + match self { + ValidationMode::Albedo => "albedo", + ValidationMode::Metal => "metal", + ValidationMode::Combined => "combined", + } + } + + /// Whether non-metal base colors are checked + pub fn checks_albedo(self) -> bool { + self != ValidationMode::Metal + } + + /// Whether metal base colors are checked + pub fn checks_metal(self) -> bool { + self != ValidationMode::Albedo + } +} diff --git a/crates/core/src/warp_blending.rs b/crates/core/src/warp_blending.rs new file mode 100644 index 00000000..f5e2d0bd --- /dev/null +++ b/crates/core/src/warp_blending.rs @@ -0,0 +1,42 @@ +//! How a Multi Directional Warp combines its directions + +use serde::{Deserialize, Serialize}; + +/// How the reads of a Multi Directional Warp's directions combine +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WarpBlending { + #[default] + Average, + /// The largest of them, per component + Max, + /// The smallest of them, per component + Min, + /// One move after the other, each from where the last one landed + Chain, +} + +impl WarpBlending { + /// Every choice, in the order a panel lists them + pub const ALL: [WarpBlending; 4] = [WarpBlending::Average, WarpBlending::Max, WarpBlending::Min, WarpBlending::Chain]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + WarpBlending::Average => "Average", + WarpBlending::Max => "Max", + WarpBlending::Min => "Min", + WarpBlending::Chain => "Chain", + } + } + + /// The id `effect.set` takes + pub fn id(self) -> &'static str { + match self { + WarpBlending::Average => "average", + WarpBlending::Max => "max", + WarpBlending::Min => "min", + WarpBlending::Chain => "chain", + } + } +} diff --git a/crates/core/src/warp_mode.rs b/crates/core/src/warp_mode.rs new file mode 100644 index 00000000..95fe042b --- /dev/null +++ b/crates/core/src/warp_mode.rs @@ -0,0 +1,39 @@ +//! How a Warp moves the texels it reads + +use serde::{Deserialize, Serialize}; + +/// Which way a Warp moves texels: along its source's slope, along one direction, or along several +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WarpMode { + /// Along the source's slope, each texel its own way + #[default] + Warp, + /// Along the Angle, forwards or backwards by the source + Directional, + /// Along Directions spread evenly from the Angle, blended + MultiDirectional, +} + +impl WarpMode { + /// Every choice, in the order a panel lists them + pub const ALL: [WarpMode; 3] = [WarpMode::Warp, WarpMode::Directional, WarpMode::MultiDirectional]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + WarpMode::Warp => "Warp", + WarpMode::Directional => "Directional Warp", + WarpMode::MultiDirectional => "Multi Directional Warp", + } + } + + /// The id `effect.set` takes + pub fn id(self) -> &'static str { + match self { + WarpMode::Warp => "warp", + WarpMode::Directional => "directional", + WarpMode::MultiDirectional => "multiDirectional", + } + } +} diff --git a/crates/core/src/warp_source_mode.rs b/crates/core/src/warp_source_mode.rs new file mode 100644 index 00000000..8452f627 --- /dev/null +++ b/crates/core/src/warp_source_mode.rs @@ -0,0 +1,39 @@ +//! What drives a Warp + +use serde::{Deserialize, Serialize}; + +/// The values a Warp's moves follow +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WarpSourceMode { + /// Fractal noise of the Warp's seed + #[default] + DefaultNoise, + /// The values the Warp filters (their luminance) + PreviousInput, + /// An image input (until one is linked: flat, so nothing moves) + CustomNoise, +} + +impl WarpSourceMode { + /// Every choice, in the order a panel lists them + pub const ALL: [WarpSourceMode; 3] = [WarpSourceMode::DefaultNoise, WarpSourceMode::PreviousInput, WarpSourceMode::CustomNoise]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + WarpSourceMode::DefaultNoise => "Default Noise", + WarpSourceMode::PreviousInput => "Previous Input", + WarpSourceMode::CustomNoise => "Custom Noise", + } + } + + /// The id `effect.set` takes + pub fn id(self) -> &'static str { + match self { + WarpSourceMode::DefaultNoise => "defaultNoise", + WarpSourceMode::PreviousInput => "previousInput", + WarpSourceMode::CustomNoise => "customNoise", + } + } +} diff --git a/crates/engine/src/filter_about.rs b/crates/engine/src/filter_about.rs new file mode 100644 index 00000000..b27bcc26 --- /dev/null +++ b/crates/engine/src/filter_about.rs @@ -0,0 +1,85 @@ +//! What each library filter does, in one sentence, and the words it is found by: the Attributes of its properties + +/// A library filter's description and tags +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FilterAbout { + pub description: &'static str, + pub tags: &'static [&'static str], +} + +const fn about(description: &'static str, tags: &'static [&'static str]) -> FilterAbout { + FilterAbout { description, tags } +} + +/// One entry per library filter id, found by its id +const ABOUT: &[(&str, FilterAbout)] = &[ + ("hsl", about("Shifts the hue and changes the saturation and lightness of the colors.", &["color", "hue", "saturation", "lightness"])), + ("levels", about("Remaps the values between new black and white points, with a midtone gamma.", &["levels", "contrast", "remap"])), + ("contrastLuminosity", about("Raises or lowers the contrast and the overall brightness.", &["contrast", "brightness"])), + ("colorBalance", about("Tints the shadows, midtones and highlights each towards a color.", &["color", "tint", "balance"])), + ( + "colorCorrect", + about("Corrects the contrast, luminosity and saturation of the shadows, midtones and highlights.", &["color", "correction", "saturation"]), + ), + ("gradientMap", about("Replaces each value by the color at its place on a gradient.", &["gradient", "color", "remap"])), + ("gradientCurve", about("Bends the values through a curve preset.", &["gradient", "curve", "remap"])), + ("gradientDynamic", about("Reads the colors along a gradient source at each value's position.", &["gradient", "color", "dynamic"])), + ("posterize", about("Rounds the values to a few steps.", &["steps", "quantize", "flat"])), + ("clamp", about("Keeps the values between a minimum and a maximum.", &["clamp", "range", "limit"])), + ("smoothstep", about("Eases the values between a minimum and a maximum from black to white.", &["smoothstep", "range", "ease"])), + ("heightAdjust", about("Flips, scales and raises heights around mid gray.", &["height", "offset", "multiply"])), + ("histogramScan", about("Turns the values into a sharp or soft cut at a chosen position.", &["histogram", "contrast", "cut"])), + ("histogramRange", about("Squeezes the values into a narrower range around a position.", &["histogram", "range"])), + ("histogramShift", about("Slides the values along and wraps them around.", &["histogram", "shift", "wrap"])), + ("invert", about("Turns dark into light and light into dark.", &["invert", "negative"])), + ("threshold", about("Makes every value white past the threshold and black below it.", &["threshold", "black and white", "cut"])), + ("grayscale", about("Turns the colors into grays.", &["grayscale", "desaturate"])), + ("edgeDetect", about("Draws lines where the values change sharply.", &["edges", "outline", "lines"])), + ("normalInvert", about("Flips the green component of a normal map.", &["normal", "invert", "green"])), + ("bakedLighting", about("Paints sun, sky and light shading into the base color from the baked mesh maps.", &["lighting", "stylized", "shading"])), + ("bakedLightingEnvironment", about("Lights the base color with the viewport environment.", &["lighting", "environment", "shading"])), + ("replaceColor", about("Swaps one color for another, keeping the shading.", &["color", "replace", "swap"])), + ("blur", about("Softens the input: each texel spreads into its neighbours.", &["blur", "soften"])), + ("blurDirectional", about("Smears the input along one direction.", &["blur", "motion", "direction"])), + ("slopeBlur", about("Smears the values downhill along a noise height field.", &["blur", "slope", "flow"])), + ("sharpen", about("Makes the details crisper.", &["sharpen", "detail"])), + ("highPass", about("Keeps the fine details and drops the broad shapes.", &["detail", "high pass", "frequency"])), + ("bevel", about("Slopes the shapes down to their edge, or raises a slope around them.", &["bevel", "edge", "slope"])), + ("bevelSmooth", about("Draws a smooth ramp from the edge of the shapes.", &["bevel", "edge", "ramp"])), + ("directionalDistance", about("Draws a trail fading away from the shapes towards an angle.", &["distance", "trail", "leak"])), + ("glow", about("Lays a soft halo of color around the shapes.", &["glow", "halo", "light"])), + ("dropShadow", about("Lays a blurred, offset shadow of the shapes under them.", &["shadow", "drop shadow"])), + ("maskOutline", about("Draws a band along the edge of the shapes.", &["outline", "edge", "stroke"])), + ("warp", about("Moves the texels by a noise or another source.", &["warp", "distort", "noise"])), + ("mosaic", about("Breaks the input into square pixels, a set number across the UV tile.", &["pixelate", "mosaic", "cells"])), + ("fxaa", about("Smooths stair-stepped edges by blending across them.", &["anti-aliasing", "edges", "smooth"])), + ("anisotropicKuwahara", about("Smooths the input into painterly strokes that follow its direction.", &["painterly", "smooth", "stylize"])), + ("pbrValidate", about("Shows in red the base colors outside the physically plausible ranges.", &["pbr", "validate", "albedo", "metal"])), + ("colorMatch", about("Moves the colors so a source color, the texture's mean by default, lands on a target color.", &["color", "match", "recolor"])), + ("heightToNormal", about("Turns the layer's height into its normal.", &["height", "normal", "convert"])), + ("mirror", about("Copies one side of each UV tile over the other.", &["mirror", "symmetry", "flip"])), + ("transform", about("Scales, turns, moves and flips the content of each UV tile.", &["transform", "scale", "rotate", "offset", "flip"])), + ("matFinishGrind", about("Gives the material a ground finish: fine brushed lines in its roughness.", &["material", "metal", "scratches"])), + ("matFinishRaw", about("Gives the material a raw finish: uneven, cloudy roughness.", &["material", "raw", "rough"])), + ("matFinishSanded", about("Gives the material a sanded finish: a fine, even grain in its roughness.", &["material", "sanded", "rough"])), + ("matFinishHammered", about("Gives the material a hammered finish: round dents in its roughness.", &["material", "metal", "hammered"])), +]; + +/// The description and tags of library filter `id` (its exact id) +pub fn of(id: &str) -> Option { + ABOUT.iter().find(|(entry, _)| *entry == id).map(|(_, about)| *about) +} + +#[cfg(test)] +mod tests { + use super::of; + use crate::filter_lib::FILTERS; + + #[test] + fn every_library_filter_is_described_and_tagged() { + for def in FILTERS { + let about = of(def.id).unwrap_or_else(|| panic!("{} has no description", def.id)); + assert!(about.description.ends_with('.') && !about.tags.is_empty(), "{}", def.id); + } + } +} diff --git a/crates/engine/src/folder_cmds.rs b/crates/engine/src/folder_cmds.rs index dbf9f8f7..5b22cf50 100644 --- a/crates/engine/src/folder_cmds.rs +++ b/crates/engine/src/folder_cmds.rs @@ -217,6 +217,8 @@ fn layer_seeds(layer: &mut Layer) -> Vec<&mut u32> { EffectKind::Material(fill) => seeds.extend(fill.sources.values_mut().filter_map(source_seed)), EffectKind::Generator(generator) => seeds.push(&mut generator.seed), EffectKind::Filter(Filter::Warp { seed, .. } | Filter::SlopeBlur { seed, .. } | Filter::DirectionalWarp { seed, .. }) => seeds.push(seed), + EffectKind::Filter(Filter::SourceWarp(warp)) => seeds.push(&mut warp.seed), + EffectKind::Filter(Filter::SourceSlopeBlur(slope)) => seeds.push(&mut slope.seed), _ => {} } } @@ -236,6 +238,10 @@ fn seed_count(layer: &Layer) -> usize { EffectKind::Fill { source, .. } => usize::from(matches!(source, Source::Procedural { .. })), EffectKind::Material(fill) => fill_seeds(fill), EffectKind::Generator(_) | EffectKind::Filter(Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. }) => 1, + EffectKind::Generator(_) + | EffectKind::Filter( + Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. } | Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_), + ) => 1, _ => 0, }) .sum(); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 87ccb68e..09cdaecb 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -74,6 +74,12 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { effect.channel_blends.iter().map(|(channel, blend)| (channel.id().to_string(), json!({ "blend": blend.mode.label(), "opacity": blend.opacity }))); out["channelBlends"] = Value::Object(channels.collect()); } + if !effect.off_channels.is_empty() { + out["offChannels"] = json!(effect.off_channels.iter().map(|channel| channel.id()).collect::>()); + } + if !effect.inputs.is_empty() { + out["inputs"] = Value::Object(effect.inputs.iter().map(|(id, source)| (id.clone(), source_json(source))).collect()); + } let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count()); let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::(); @@ -119,8 +125,8 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { EffectKind::Filter(filter) => { out["filter"] = json!(filter); match filter { - Filter::Hsl { hue, saturation, lightness } => out["hsl"] = json!([hue, saturation, lightness]), - Filter::Blur { radius } => out["radius"] = json!(radius), + Filter::Hsl { hue, saturation, lightness, .. } => out["hsl"] = json!([hue, saturation, lightness]), + Filter::Blur { radius, .. } => out["radius"] = json!(radius), _ => {} } } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 1a36ef38..61d2611e 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -5,6 +5,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, + Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, ImageInput, Layer, LayerId, LayerKind, + NormalFormat, Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; use texturecraft_paint::alphas::{self, LibraryAlpha}; @@ -122,6 +124,7 @@ pub fn specs() -> Vec { [], None, "{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", + "{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)} | {effect: filter effect id, input: image input id (distanceMap, customNoise), value?|procedural?|image?|alpha?|anchor? as a mask fill's source, or clear: true (back to its default gray)}", has_layer, fill_set ), @@ -566,11 +569,13 @@ fn mask_source_mut(s: &mut Session, effect: LayerId) -> Result<&mut Source> { } fn fill_set(session: &mut Session, params: &Value) -> Result { + if let Some(input) = strp(params, "input") { + return input_set(session, params, input); + } let target = fill_target(session, params, FILL_SET)?; if let FillTarget::Mask(effect) = target { return mask_fill_set(session, params, effect); } - let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; // `solo`: this channel on, every other one off @@ -683,6 +688,43 @@ fn mask_fill_set(s: &mut Session, p: &Value, effect: LayerId) -> Result { Ok(Value::Null) } +/// `layer.fill.set {effect, input}`: the source of a filter effect's image input `id`, or its default gray back (`clear`) +fn input_set(s: &mut Session, p: &Value, id: &str) -> Result { + let effect = u64p(p, "effect").map(LayerId).ok_or_else(|| bad(FILL_SET, "`input` goes with a filter `effect`"))?; + let found = s.doc.project.effect(effect).map(|(_, found)| found).ok_or_else(|| bad(FILL_SET, format!("no effect {}", effect.0)))?; + let EffectKind::Filter(filter) = &found.kind else { return Err(bad(FILL_SET, format!("{} is not a filter effect", effect.0))) }; + let input = ImageInput::named(filter, id).ok_or_else(|| bad(FILL_SET, format!("the {} filter has no image input `{id}`", filter.label())))?; + refuse_gray_keys(p, "an image input")?; + + let (source, library_alpha) = if p.get("clear").and_then(Value::as_bool) == Some(true) { + (None, None) + } else { + let (source, alpha) = gray_source(s, p, effect, found.input(&input))?; + (Some(source), alpha) + }; + + // Its default gray is not stored, so a project that never set the input saves as before + let stored = source.filter(|source| *source != input.default_source()); + + // Setting what the input already reads adds no undo step + if found.inputs.get(input.id) == stored.as_ref() && library_alpha_present(s, library_alpha) { + return Ok(Value::Null); + } + + s.edit("Set image input", |s| { + if let Some(alpha) = library_alpha { + s.add_library_alpha(alpha)?; + } + let found = s.doc.project.effect_mut(effect).ok_or_else(|| bad(FILL_SET, "the effect is gone"))?; + match stored { + Some(source) => found.inputs.insert(input.id.to_string(), source), + None => found.inputs.remove(input.id), + }; + Ok(()) + })?; + Ok(Value::Null) +} + /// Refuses the [`GRAY_REFUSED_KEYS`] for `subject`, a fill with one grayscale source fn refuse_gray_keys(p: &Value, subject: &str) -> Result<()> { if GRAY_REFUSED_KEYS.iter().any(|key| p.get(key).is_some()) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 53c87e71..23c6b489 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -24,6 +24,7 @@ pub mod fill_hit_test; pub mod fill_material_cmds; pub mod fill_mode; pub mod fill_reset_cmds; +pub mod filter_about; pub mod filter_lib; pub mod folder_cmds; mod frame_target; @@ -73,10 +74,12 @@ mod session_log; pub mod set_cmds; pub mod smart_masks; mod solo; +mod stylized_lighting_params; pub mod swatch_cmds; pub mod template_cmds; pub mod text_cmds; pub mod thumbs; +mod tile_transform_params; mod tool_availability; pub mod tool_cmds; pub mod tool_settings; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 93c25a02..899f71cb 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -12,6 +12,9 @@ use crate::mask_owner::MaskOwner; use crate::session::StackTarget; use crate::{EngineError, Result, Session, cmd}; +/// The `filter` id of a filter effect with no filter picked +pub const EMPTY_FILTER: &str = "none"; + pub fn specs() -> Vec { vec![ cmd!("mask.add.white", "Add white mask", ["Layers", "Mask"], None, "{layer?}", has_layer, |s, p| add_mask(s, p, MaskBackground::White)), @@ -68,7 +71,7 @@ pub fn specs() -> Vec { "Add filter", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b] linear or \"#rrggbb\" sRGB, ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content", + "{layer?, target?: mask|content, name?, filter?: any id or label from filter.list (warpDirectional adds Warp in its Directional mode) or \"none\" for an empty filter that changes nothing, level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b] linear or \"#rrggbb\" sRGB, ...], positions?: [0..1, ...], quantity?: 2..10, grayscaleMode?: desaturation|luma|average|max|min, blur?, balance?, invert?, linear?, debug?, preset?: round|pinch|stairs|easeOut|ease|easeIn|peakOut|peak|peakIn|bump|doubleBump|triangular, orientation?: horizontal|vertical, color?, levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content", has_layer, add_filter ), @@ -96,6 +99,7 @@ pub fn specs() -> Vec { [], None, "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -293,6 +297,14 @@ fn push_effect_in( if let Some(name) = name_param(p) { effect.name = name.to_string(); } + + // A filter that changes only some channels (lighting, validation) starts with the other channels' pills off + if content + && let EffectKind::Filter(filter) = &effect.kind + && let Some(on) = filter.starts_on() + { + effect.off_channels = Channel::ALL.into_iter().filter(|channel| !on.contains(channel)).collect(); + } if !content { layer.mask.get_or_insert_with(|| Mask::new(background)).effects.push(effect); } else if layer.is_group() { @@ -586,7 +598,9 @@ fn add_levels(s: &mut Session, p: &Value) -> Result { fn add_filter(s: &mut Session, p: &Value) -> Result { let id = strp(p, "filter").unwrap_or("invert"); - let kind = crate::filter_lib::build(id, p)?; + + // An empty filter changes nothing until one is picked into it + let kind = if id == EMPTY_FILTER { EffectKind::Filter(Filter::Empty) } else { crate::filter_lib::build(id, p)? }; // Library filters are named after their shelf entry (material finishes are fill effects) let mut p = p.clone(); @@ -718,6 +732,11 @@ fn set(session: &mut Session, params: &Value) -> Result { return Err(bad(CMD, "a mask's levels remap its one value: leave out `affects`")); } + let switched = switched_channels(params)?; + if !switched.is_empty() && on_mask { + return Err(bad(CMD, "a mask effect has one value: leave out `channels`")); + } + // `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one let anchor = match session.doc.project.effect(effect) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { @@ -755,9 +774,15 @@ fn set(session: &mut Session, params: &Value) -> Result { _ => None, }; - // Naming the filter the effect already is edits its parameters like a plain effect.set + // Naming the filter the effect already is edits its parameters like a plain effect.set (Directional Warp's former id also sets its mode); a warp saved before the warp modes has no mode to set, so another mode replaces it as a swap does + let changes_saved_warp_mode = |filter: &str| matches!(session.doc.project.effect(effect), Some((_, Effect { kind: EffectKind::Filter(saved), .. })) if crate::filter_lib::changes_saved_warp_mode(filter, params, saved)); let swapped = match strp(params, "filter") { - Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None, + Some(EMPTY_FILTER) => Some(emptied_filter(session, effect)?), + Some(filter) + if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) && !changes_saved_warp_mode(filter) => + { + None + } Some(filter) => Some(swapped_filter(session, effect, filter, params)?), None => None, }; @@ -769,7 +794,7 @@ fn set(session: &mut Session, params: &Value) -> Result { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; if let Some((kind, label)) = swapped { if let EffectKind::Filter(old) = &edited.kind - && edited.name == old.label() + && (edited.name == old.label() || Some(edited.name.as_str()) == old.former_label()) { edited.name = label.to_string(); } @@ -779,6 +804,13 @@ fn set(session: &mut Session, params: &Value) -> Result { if let Some(visible) = boolp(params, "visible") { edited.visible = visible; } + for (channel, on) in &switched { + if *on { + edited.off_channels.remove(channel); + } else { + edited.off_channels.insert(*channel); + } + } crate::effect_blending_cmds::set_blending(edited, channel, blend, f32p(params, "opacity")); if let Some(name) = name_param(params) { edited.name = name.to_string(); @@ -813,7 +845,7 @@ fn set(session: &mut Session, params: &Value) -> Result { // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} - EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?, + EffectKind::Filter(filter) => crate::filter_lib::apply_named(strp(params, "filter"), params, filter, CMD)?, EffectKind::Fill { source, projection, .. } => { // `uniform` picks the source, so it outranks settings that would edit the current pattern let uniform = f32p(params, "uniform").filter(|_| strp(params, "procedural").is_none()); @@ -883,6 +915,30 @@ fn fill_pattern(command: &str, params: &Value, current: &Source) -> Result Result> { + const CMD: &str = "effect.set"; + let Some(given) = params.get("channels") else { return Ok(Vec::new()) }; + let given = given.as_object().ok_or_else(|| bad(CMD, "`channels` must be an object of channel ids to true (on) or false (off)"))?; + given + .iter() + .map(|(id, on)| { + let channel = Channel::parse(id).ok_or_else(|| bad(CMD, format!("unknown channel `{id}`")))?; + let on = on.as_bool().ok_or_else(|| bad(CMD, format!("`channels.{id}` must be true or false")))?; + Ok((channel, on)) + }) + .collect() +} + +/// An empty filter and its label, to replace filter effect `effect`'s +fn emptied_filter(s: &Session, effect: LayerId) -> Result<(EffectKind, &'static str)> { + match s.doc.project.effect(effect) { + Some((_, Effect { kind: EffectKind::Filter(_), .. })) => Ok((EffectKind::Filter(Filter::Empty), Filter::Empty.label())), + Some((_, other)) => Err(bad("effect.set", format!("`filter` changes filter effects only, not {}", other.kind.name().to_ascii_lowercase()))), + None => Err(bad("effect.set", format!("no effect {}", effect.0))), + } +} + /// The library id of the filter effect `effect` is, if it is one fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> { match &s.doc.project.effect(effect)?.1.kind { @@ -900,10 +956,9 @@ fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<( } let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?; - let mut kind = crate::filter_lib::build(def.id, &Value::Null)?; - let EffectKind::Filter(filter) = &mut kind else { + if !def.is_filter_effect() { return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label))); - }; + } let mask = s.doc.project.layer(owner)?.mask.as_ref(); let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect)); @@ -911,7 +966,8 @@ fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<( return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label))); } - crate::filter_lib::apply(p, filter, CMD)?; + // Built as effect.add.filter builds it, from the id given, so a former id such as `warpDirectional` sets the same mode it adds with + let kind = crate::filter_lib::build_for(CMD, id, p)?; Ok((kind, def.label)) } diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index e3638c2f..4a27474f 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -51,12 +51,10 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, out.extend(link.outputs.values().cloned()); } } - for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { - out.extend(effect.kind.images_read().map(str::to_string)); + out.extend(effect.images_read().map(str::to_string)); out.extend(crate::path_tool::path_images(&effect.kind)); } - for child in layer.children() { images_used(project, *child, out, depth + 1); } diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 15d8c072..a0e6d366 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -2,7 +2,10 @@ use rayon::prelude::*; use texturecraft_compose::pattern::{Coords, procedural}; -use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet}; +use texturecraft_core::{ + Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, SIZE_REFERENCE_RES, Source, TextureSet, + TileTransform, +}; use texturecraft_geom::glam::{Vec2, Vec3}; use crate::materials::{Builder, build}; @@ -88,16 +91,16 @@ pub fn material(id: &str, size: usize) -> Option>> { /// `f` with its reach in texels multiplied by `k` (previews show at a fraction of 2K). fn magnified(f: Filter, k: f32) -> Filter { match f { - Filter::Blur { radius } => Filter::Blur { radius: radius * k }, + Filter::Blur { radius, wrap } => Filter::Blur { radius: radius * k, wrap }, Filter::DirectionalBlur { radius, angle } => Filter::DirectionalBlur { radius: radius * k, angle }, - Filter::SlopeBlur { radius, scale, seed } => Filter::SlopeBlur { radius: radius * k, scale, seed }, - Filter::Warp { intensity, scale, seed } => Filter::Warp { intensity: intensity * k, scale, seed }, - Filter::HighPass { radius } => Filter::HighPass { radius: radius * k }, + Filter::SlopeBlur { radius, scale, seed, divider } => Filter::SlopeBlur { radius: radius * k, scale, seed, divider }, + Filter::Warp { intensity, scale, seed, divider } => Filter::Warp { intensity: intensity * k, scale, seed, divider }, + Filter::HighPass { radius, space, alpha } => Filter::HighPass { radius: radius * k, space, alpha }, Filter::EdgeDetect { width } => Filter::EdgeDetect { width: width * k }, - Filter::Bevel { width } => Filter::Bevel { width: width * k }, - Filter::Mosaic { size } => Filter::Mosaic { size: size * k }, + Filter::Bevel { width, wrap } => Filter::Bevel { width: width * k, wrap }, + Filter::Mosaic { size, alpha } => Filter::Mosaic { size: size * k, alpha }, Filter::Glow { radius, amount } => Filter::Glow { radius: radius * k, amount }, - Filter::DirectionalWarp { intensity, angle, scale, seed } => Filter::DirectionalWarp { intensity: intensity * k, angle, scale, seed }, + Filter::DirectionalWarp { intensity, angle, scale, seed, divider } => Filter::DirectionalWarp { intensity: intensity * k, angle, scale, seed, divider }, f => f, } } @@ -108,9 +111,16 @@ fn magnified(f: Filter, k: f32) -> Filter { pub fn filter(id: &str, size: usize) -> Option>> { let res = u32::try_from(size).ok()?.max(1); let kind = match crate::filter_lib::build(id, &serde_json::Value::Null).ok()? { - EffectKind::Filter(f) => EffectKind::Filter(magnified(f, 2048.0 / res as f32)), + // Transform changes nothing as the library adds it: its picture shows it scaled and turned + EffectKind::Filter(Filter::Transform(transform)) => { + EffectKind::Filter(Filter::Transform(TileTransform { scaling: [2.0, 2.0], rotation: 30.0, ..transform })) + } + EffectKind::Filter(f) => EffectKind::Filter(magnified(f, SIZE_REFERENCE_RES / res as f32)), k => k, }; + + // The filters that shape a mask's edge read where values cross 0.5: they get black and white shapes, where the clouds would leave them black + let shapes = matches!(kind, EffectKind::Filter(Filter::BevelSmooth(_) | Filter::DirectionalDistance(_))); let mesh = texturecraft_geom::primitives::plane(2.0, 2); let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res); let mut p = Project::new("preview", ""); @@ -118,7 +128,12 @@ pub fn filter(id: &str, size: usize) -> Option>> { let procedural = |kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high, ramp: Vec::new() }; let mut fill = Fill::default(); - fill.sources.insert(Channel::BaseColor, procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1])); + let base = if shapes { + procedural(ProceduralKind::Checker, 3.0, [0.0; 3], [1.0; 3]) + } else { + procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1]) + }; + fill.sources.insert(Channel::BaseColor, base); fill.sources.insert(Channel::Roughness, procedural(ProceduralKind::Checker, 4.0, [0.25; 3], [0.7; 3])); fill.sources.insert(Channel::Height, procedural(ProceduralKind::Cells, 3.0, [-0.12; 3], [0.12; 3])); let mut layer = Layer::new(p.alloc_id(), "sample", LayerKind::Fill(fill), &CHANNELS); @@ -192,4 +207,18 @@ mod tests { let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap()); assert!(plain != warped, "the warp shows in its preview"); } + + #[test] + fn the_edge_shaping_filters_show_their_shapes_not_black() { + let size = 32; + // A neutral filter shows the checker as it is; an edge filter must change it + let checker = filter("levels", size).unwrap(); + for id in ["bevelSmooth", "directionalDistance"] { + let pixels = filter(id, size).unwrap(); + assert!(pixels != checker, "{id}: the preview shows the unchanged checker"); + let lit: Vec = pixels.into_iter().flatten().map(|sample| sample.base.iter().sum::() / 3.0).collect(); + let bright = lit.iter().filter(|value| **value > 0.25).count(); + assert!(bright * 5 > lit.len(), "{id}: {bright} of {} texels lit", lit.len()); + } + } } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index fbb0b9f3..2f5ad634 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -757,41 +757,38 @@ impl Session { (Some(previous), Some(current)) => !Arc::ptr_eq(previous, current), (previous, current) => previous.is_some() != current.is_some(), }; - if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(resource_changed)) { + if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(|name| resource_changed(&name))) { self.path_cache = None; } // Removed or replaced resources may change any set's rendered content let removed_or_replaced_resource = previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); - if removed_or_replaced_resource { - for cache in &mut self.caches { - cache.invalidate_all(); - } - - return; - } - let added_resource_names: BTreeSet<&str> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect(); - let is_added = |name: &str| added_resource_names.contains(name); let uses_added_resource = |texture_set_index: usize| { - use texturecraft_core::{EffectKind, Fill}; - - let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package)); - let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill); - let project = &self.doc.project; - !added_resource_names.is_empty() - && project.texture_sets.get(texture_set_index).is_some_and(|set| { - project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { - matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) - || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| { effect.kind.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill)) - }) - }) + let uses_added_resource = |texture_set_index: usize| { + use texturecraft_core::{EffectKind, Fill}; + + let is_added = |name: &str| added_resource_names.contains(name); + let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package)); + let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill); + let project = &self.doc.project; + !added_resource_names.is_empty() + && project.texture_sets.get(texture_set_index).is_some_and(|set| { + project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { + matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) + || layer + .mask + .iter() + .flat_map(|mask| &mask.effects) + .chain(&layer.content_effects) + .any(|effect| effect.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill))) }) - }; + }) + }; let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default()); let stack_key = |document: &Document, texture_set_index: usize| { let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default(); diff --git a/crates/engine/src/tile_transform_params.rs b/crates/engine/src/tile_transform_params.rs new file mode 100644 index 00000000..86a0f807 --- /dev/null +++ b/crates/engine/src/tile_transform_params.rs @@ -0,0 +1,52 @@ +//! `effect.set` on a Transform filter: repeatMode, flipMode, scaling, offset, tileSafeRotation and rotation + +use serde_json::Value; +use texturecraft_core::{FlipMode, RepeatMode, TileTransform}; + +use crate::Result; +use crate::commands::{bad, boolp, f32p, strp}; +use crate::layer_cmds::FULL_TURN_DEGREES; + +/// Set the Transform settings given in `p`; a value of the wrong kind is refused and changes nothing +pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Result<()> { + let mut edited = *transform; + if p.get("repeatMode").is_some() { + let id = strp(p, "repeatMode").unwrap_or_default(); + edited.repeat = + RepeatMode::ALL.into_iter().find(|mode| mode.id() == id).ok_or_else(|| bad(cmd, "`repeatMode` must be none or horizontallyAndVertically"))?; + } + if p.get("flipMode").is_some() { + let id = strp(p, "flipMode").unwrap_or_default(); + edited.flip = FlipMode::ALL + .into_iter() + .find(|mode| mode.id() == id) + .ok_or_else(|| bad(cmd, "`flipMode` must be none, horizontally, vertically or horizontallyAndVertically"))?; + } + let (low, high) = TileTransform::SCALING; + if let Some(scaling) = pair(p, "scaling", cmd)? { + edited.scaling = scaling.map(|scale| scale.clamp(low, high)); + } + if let Some(offset) = pair(p, "offset", cmd)? { + edited.offset = offset.map(|along| along.clamp(-TileTransform::MAX_OFFSET, TileTransform::MAX_OFFSET)); + } + if p.get("tileSafeRotation").is_some() { + edited.tile_safe = boolp(p, "tileSafeRotation").ok_or_else(|| bad(cmd, "`tileSafeRotation` must be true or false"))?; + } + if p.get("rotation").is_some() { + let degrees = f32p(p, "rotation").ok_or_else(|| bad(cmd, "`rotation` must be a number of degrees"))?; + edited.rotation = degrees.rem_euclid(FULL_TURN_DEGREES); + } + *transform = edited; + Ok(()) +} + +/// `[x, y]` (or one number for both) under `key`, if given; anything else is refused +fn pair(p: &Value, key: &str, cmd: &str) -> Result> { + let Some(value) = p.get(key) else { return Ok(None) }; + let number = |item: &Value| item.as_f64().map(|value| value as f32).filter(|value| value.is_finite()); + let parsed = match value { + Value::Array(items) if items.len() == 2 => items.first().and_then(number).zip(items.get(1).and_then(number)).map(|(x, y)| [x, y]), + other => number(other).map(|both| [both, both]), + }; + parsed.map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y] or one number"))) +} diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 6d77ebf5..e02220c9 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use texturecraft_core::project::ENVIRONMENTS; -use texturecraft_core::{BakedMap, Channel, EnvAlignment, ShadowMode, ToneMapping}; +use texturecraft_core::{BakedMap, Channel, EffectKind, EnvAlignment, Filter, Project, ShadowMode, ToneMapping}; use texturecraft_geom::glam::Vec3; use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p}; @@ -301,6 +301,7 @@ fn display(s: &mut Session, p: &Value) -> Result { } let scatter_color = color_param("display.set", p, "scatterColor")?; + let (environment_before, rotation_before) = (s.doc.project.display.environment.clone(), s.doc.project.display.env_rotation); let settings = &mut s.doc.project.display; if let Some(picked) = environment { settings.environment = picked; @@ -368,10 +369,27 @@ fn display(s: &mut Session, p: &Value) -> Result { if f32p(p, "fov").is_some() { s.camera.fov = s.doc.project.display.fov; } + + // Baked Lighting Environment lights with the viewport environment: the layers it lights composite again when that turns or changes + let display = &s.doc.project.display; + if (display.environment.as_str(), display.env_rotation) != (environment_before.as_str(), rotation_before) && lit_by_environment(&s.doc.project) { + for cache in &mut s.caches { + cache.invalidate_all(); + } + } s.revision = s.revision.wrapping_add(1); Ok(serde_json::to_value(&s.doc.project.display).unwrap_or(Value::Null)) } +/// Whether a layer's content has a Baked Lighting Environment +fn lit_by_environment(project: &Project) -> bool { + project + .layers + .values() + .flat_map(|layer| layer.content_effects.iter()) + .any(|effect| matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. }))) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index 8274f5d8..f1414b05 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -33,54 +33,39 @@ fn id(reply: Value, key: &str) -> u64 { fn content_effects_commands_inspect_and_round_trip() { let mut s = session(); let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0], "roughness": 0.2})).unwrap(), "layer"); - let hsl = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "hsl", "hue": 1.0 / 3.0})).unwrap(), "effect"); - + let hsl = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "hsl", "mode": "regular", "hue": 1.0 / 3.0})).unwrap(), "effect"); assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor)); assert!(s.doc.project.layer(LayerId(layer)).unwrap().mask.is_none(), "content effects don't create a mask"); assert_eq!(s.target, StackTarget::Effect(LayerId(hsl))); - // Mask-only effects refuse the content, unknown targets are errors + // Mask-only effects refuse the content, unknown targets are errors. assert!(execute(&mut s, "effect.add.generator", &json!({"target": "content"})).is_err()); assert!(execute(&mut s, "effect.add.filter", &json!({"target": "nope"})).is_err()); - execute(&mut s, "effect.set", &json!({"effect": hsl, "hue": 0.0, "lightness": -1.0})).unwrap(); - assert!(close(center(&mut s, Channel::BaseColor), [0.0; 3])); - execute(&mut s, "effect.set", &json!({"effect": hsl, "visible": false})).unwrap(); - // A content fill effect, edited through layer.fill.set + // A content fill effect, edited through layer.fill.set. let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap(), "effect"); - assert!(close(center(&mut s, Channel::Roughness), [0.7; 3])); assert!(close(center(&mut s, Channel::BaseColor), [1.0, 0.0, 0.0]), "channels without a source stay"); - execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "value": 0.9})).unwrap(); - assert!(close(center(&mut s, Channel::Roughness), [0.9; 3])); - execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "enabled": false})).unwrap(); - assert!(close(center(&mut s, Channel::Roughness), [0.2; 3])); assert!(execute(&mut s, "layer.fill.set", &json!({"effect": hsl, "channel": "roughness", "value": 0.5})).is_err(), "not a fill effect"); - // Inspect shows the content stack; the project survives a save/load round trip + // Inspect shows the content stack; the project survives a save/load round trip. let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); let kinds: Vec<&str> = row["contentEffects"].as_array().unwrap().iter().map(|effect| effect["kind"].as_str().unwrap()).collect(); - assert_eq!(kinds, ["HSL Perceptive", "Fill"], "{row}"); - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.doc.project, s.doc.project); execute(&mut s, "layer.select", &json!({"layer": layer, "target": fill})).unwrap(); execute(&mut s, "effect.remove", &json!({"effect": fill})).unwrap(); - assert_eq!(s.target, StackTarget::Content); - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert_eq!(s.doc.project.layer(LayerId(layer)).unwrap().content_effects.len(), 2); } diff --git a/crates/engine/tests/it/filter_card.rs b/crates/engine/tests/it/filter_card.rs new file mode 100644 index 00000000..ee9c25af --- /dev/null +++ b/crates/engine/tests/it/filter_card.rs @@ -0,0 +1,140 @@ +//! The Filter effect card: an empty filter, its content channels switched on and off, Intensity's divider, Restore defaults and the Attributes it lists + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, Filter, LayerId, SourceSlopeBlur, SourceWarp}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, center, facing_session as session, filter_of, set}; + +fn assert_close(actual: [f32; 3], expected: [f32; 3], what: &str) { + assert!((0..3).all(|i| (actual[i] - expected[i]).abs() < 4e-3), "{what}: {actual:?}, expected {expected:?}"); +} + +/// A fill layer of base color 0.2 and roughness 0.3 under content filter `params`: (layer, effect) +fn filtered_layer(s: &mut Session, params: Value) -> (u64, LayerId) { + let layer = execute(s, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2], "roughness": 0.3})).unwrap()["layer"].as_u64().unwrap(); + (layer, add_filter(s, params)) +} + +/// An empty filter changes nothing and is named for it; picking a filter names it after the filter, × empties it again +#[test] +fn an_empty_filter_renders_nothing_until_one_is_picked() { + let mut s = session(); + let (_, effect) = filtered_layer(&mut s, json!({"filter": "none"})); + + assert_eq!(filter_of(&s, effect), Filter::Empty); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Filter (empty)"); + assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "an empty filter leaves the color"); + + set(&mut s, effect, json!({"filter": "invert"})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Invert"); + assert_close(center(&mut s, Channel::BaseColor), [0.8; 3], "the picked filter works"); + + set(&mut s, effect, json!({"filter": "none"})); + assert_eq!(filter_of(&s, effect), Filter::Empty); + assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "emptied again"); +} + +/// A content filter switched off for a channel leaves that channel; inspect lists it; masks refuse `channels` +#[test] +fn a_content_filter_leaves_the_channels_switched_off() { + let mut s = session(); + let (layer, effect) = filtered_layer(&mut s, json!({"filter": "invert"})); + + assert_close(center(&mut s, Channel::Roughness), [0.7; 3], "every channel at first"); + + set(&mut s, effect, json!({"channels": {"roughness": false}})); + assert_close(center(&mut s, Channel::Roughness), [0.3; 3], "roughness switched off"); + assert_close(center(&mut s, Channel::BaseColor), [0.8; 3], "the color still inverted"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); + let filter_row = row["contentEffects"].as_array().unwrap().iter().find(|filter_row| filter_row["id"] == effect.0).unwrap(); + assert_eq!(filter_row["offChannels"], json!(["roughness"])); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.7; 3], "one undo step"); + + set(&mut s, effect, json!({"channels": {"roughness": false}})); + set(&mut s, effect, json!({"channels": {"roughness": true}})); + assert!(s.doc.project.effect(effect).unwrap().1.off_channels.is_empty()); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channels": {"nope": false}})).is_err()); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channels": {"roughness": 1}})).is_err()); + + let masked = execute(&mut s, "effect.add.filter", &json!({"filter": "invert", "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + + assert!(execute(&mut s, "effect.set", &json!({"effect": masked, "channels": {"roughness": false}})).is_err()); +} + +/// Intensity ÷ Divider: warp 0.5 ÷ 10 renders as warp 0.05; only 1, 10, 100 and 1000 are taken; a divider of 1 is not saved +#[test] +fn the_divider_divides_the_intensity() { + let warp = |intensity: f32, divider: u16| { + let mut s = session(); + execute(&mut s, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "checker", "scale": 8.0})).unwrap(); + let params = json!({"filter": "warp", "target": "content", "intensity": intensity, "seed": 5}); + let effect = execute(&mut s, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": effect, "divider": divider})).unwrap(); + s.update(); + (0..SIZE).step_by(7).map(|x| s.caches[0].composite.value(Channel::BaseColor, x, SIZE / 2)[0]).collect::>() + }; + let divided = warp(0.5, 10); + assert_eq!(divided, warp(0.05, 1), "0.5 ÷ 10 = 0.05"); + assert_ne!(divided, warp(0.5, 1), "the divider changes the warp"); + + let mut s = session(); + let (_, effect) = filtered_layer(&mut s, json!({"filter": "slopeBlur"})); + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "divider": 7})).is_err()); + + set(&mut s, effect, json!({"divider": 100})); + assert!(matches!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur { divider: 100, .. }))); + + let saved = serde_json::to_value(Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 }).unwrap(); + assert_eq!(saved, json!({"Warp": {"intensity": 1.0, "scale": 2.0, "seed": 3}}), "saved as before dividers"); + + let loaded: Filter = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded, Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 }); +} + +/// Restore defaults puts the parameters back in one undo step, keeping the name and switched-off channels; none at defaults +#[test] +fn restore_defaults_puts_the_filters_parameters_back() { + let mut s = session(); + let (_, effect) = filtered_layer(&mut s, json!({"filter": "warp", "name": "Wobble"})); + let defaults = filter_of(&s, effect); + let steps = s.history_labels().len(); + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(), json!({"changed": false})); + assert_eq!(s.history_labels().len(), steps, "no step at defaults"); + + set(&mut s, effect, json!({"intensity": 0.5, "seed": 9, "divider": 100, "channels": {"height": false}})); + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(), json!({"changed": true})); + assert_eq!(filter_of(&s, effect), defaults); + + let restored = s.doc.project.effect(effect).unwrap().1.clone(); + assert_eq!(restored.name, "Wobble"); + assert!(restored.off_channels.contains(&Channel::Height)); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(matches!(filter_of(&s, effect), Filter::SourceWarp(SourceWarp { divider: 100, seed: 9, .. })), "one undo step"); + + let empty = filtered_layer(&mut s, json!({"filter": "none"})).1; + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": empty.0})).unwrap(), json!({"changed": false})); + + let fill = execute(&mut s, "effect.add.fill", &json!({"target": "content"})).unwrap()["effect"].as_u64().unwrap(); + assert!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": fill})).is_err()); +} + +#[test] +fn filter_list_describes_and_tags_every_filter() { + let mut s = session(); + let listed = execute(&mut s, "filter.list", &Value::Null).unwrap(); + for def in listed.as_array().unwrap() { + assert!(def["description"].as_str().is_some_and(|text| !text.is_empty()), "{def}"); + assert!(def["tags"].as_array().is_some_and(|tags| !tags.is_empty()), "{def}"); + } + let blur = listed.as_array().unwrap().iter().find(|def| def["id"] == "blur").unwrap(); + assert_eq!(blur["tags"], json!(["blur", "soften"])); +} diff --git a/crates/engine/tests/it/filter_colour.rs b/crates/engine/tests/it/filter_colour.rs new file mode 100644 index 00000000..f0bc3561 --- /dev/null +++ b/crates/engine/tests/it/filter_colour.rs @@ -0,0 +1,100 @@ +//! The colour filters (Color Balance, Color Correct, HSL Perceptive, Contrast Luminosity) and the shared edge wrap of Blur and Bevel + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Bevel, Channel, Filter}; +use texturecraft_engine::execute; + +use crate::filter_support::{center, facing_session as session, filter_of, filtered, set}; + +fn distance(a: [f32; 3], b: [f32; 3]) -> f32 { + (0..3).map(|i| (a[i] - b[i]).abs()).fold(0.0, f32::max) +} + +/// Color Correct: neutral by default, then each tone's contrast, luminosity and saturation; one undo step per edit +#[test] +fn color_correct_changes_nothing_until_its_tones_move() { + let mut s = session(); + let color = [0.6, 0.3, 0.2]; + let effect = filtered(&mut s, color, json!({"filter": "colorCorrect"})); + let neutral = filter_of(&s, effect); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Color Correct"); + assert!(distance(center(&mut s, Channel::BaseColor), color) < 4e-3, "the defaults change nothing"); + + set(&mut s, effect, json!({"shadows": [0.0, 0.0, 0.0], "midtones": [0.0, 0.0, 0.0], "highlights": [0.0, 0.0, 0.0]})); + let gray = center(&mut s, Channel::BaseColor); + assert!((gray[0] - gray[1]).abs() < 4e-3 && (gray[1] - gray[2]).abs() < 4e-3, "saturation 0 everywhere is gray: {gray:?}"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(filter_of(&s, effect), neutral, "one undo step takes back all three tones"); + + set(&mut s, effect, json!({"midtones": [0.0, 0.3, 0.5], "shadows": [0.0, 0.3, 0.5], "highlights": [0.0, 0.3, 0.5]})); + let lighter = center(&mut s, Channel::BaseColor); + assert!((0..3).all(|i| lighter[i] > color[i] + 0.1), "luminosity lifts every tone: {lighter:?}"); + + let roughness = center(&mut s, Channel::Roughness); + assert!(roughness[0] > 0.4, "scalars take contrast and luminosity: {roughness:?}"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "midtones": "x"})).is_err()); + + let Filter::ColorCorrect { midtones, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!(midtones, [0.0, 0.3, 0.5], "a refused edit changes nothing"); + + set(&mut s, effect, json!({"midtones": [5.0, -5.0, 5.0]})); + let Filter::ColorCorrect { midtones, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!(midtones, [1.0, -1.0, 1.0], "clamped to the ranges"); +} + +/// HSL Perceptive: a new filter is Perceptive, projects saved before stay Regular; a perceptive hue turn keeps lightness better +#[test] +fn hsl_perceptive_turns_the_hue_at_the_same_lightness() { + let mut s = session(); + let yellow = [0.8, 0.7, 0.05]; + let effect = filtered(&mut s, yellow, json!({"filter": "hsl", "hue": 0.5})); + assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: true, .. }), "new filters are perceptive"); + + let perceptive = center(&mut s, Channel::BaseColor); + set(&mut s, effect, json!({"mode": "regular"})); + assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: false, .. })); + + let regular = center(&mut s, Channel::BaseColor); + // Rec. 709 luminance weights + let relative_luminance = |c: [f32; 3]| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; + let drift = |color: [f32; 3]| (relative_luminance(color) - relative_luminance(yellow)).abs(); + assert!(drift(perceptive) < drift(regular), "perceptive {perceptive:?} regular {regular:?}"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "vivid"})).is_err()); + + // Saved before the mode: Regular, and saved again without the field + let old: Filter = serde_json::from_value(json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}})).unwrap(); + assert_eq!(old, Filter::Hsl { hue: 0.5, saturation: 0.0, lightness: 0.0, perceptive: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}})); +} + +/// Contrast Luminosity starts neutral (contrast 0) like the other colour filters +#[test] +fn contrast_luminosity_starts_neutral() { + let mut s = session(); + let effect = filtered(&mut s, [0.2; 3], json!({"filter": "contrastLuminosity"})); + assert_eq!(filter_of(&s, effect), Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.0 }); + assert!(distance(center(&mut s, Channel::BaseColor), [0.2; 3]) < 4e-3); +} + +/// Blur and Bevel take the shared edge wrap: effect.set {wrap}, saved only when on, old projects load with it off +#[test] +fn blur_and_bevel_take_the_edge_wrap() { + let mut s = session(); + let blur = filtered(&mut s, [0.2; 3], json!({"filter": "blur"})); + assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: false, .. })); + + set(&mut s, blur, json!({"wrap": true})); + assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: true, .. })); + + assert!(execute(&mut s, "effect.set", &json!({"effect": blur.0, "wrap": "yes"})).is_err()); + + let bevel = filtered(&mut s, [0.2; 3], json!({"filter": "bevel", "wrap": true})); + assert!(matches!(filter_of(&s, bevel), Filter::DistanceBevel(Bevel { wrap: true, .. }))); + + let old: Filter = serde_json::from_value(json!({"Blur": {"radius": 4.0}})).unwrap(); + assert_eq!(old, Filter::Blur { radius: 4.0, wrap: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Blur": {"radius": 4.0}}), "off is not saved"); +} diff --git a/crates/engine/tests/it/filter_gradient.rs b/crates/engine/tests/it/filter_gradient.rs new file mode 100644 index 00000000..738c5390 --- /dev/null +++ b/crates/engine/tests/it/filter_gradient.rs @@ -0,0 +1,168 @@ +//! The gradient filters: Gradient (positions, quantity, input transformation, linear blending, debug), Gradient Curve and Gradient Dynamic + +use serde_json::json; +use texturecraft_engine::core::{Channel, EffectKind, Filter, GrayscaleMode, layer::gradient}; +use texturecraft_engine::execute; +use texturecraft_engine::filter_lib::{LIBRARY_GRADIENT_CURVE, LIBRARY_GRADIENT_DYNAMIC, MID_GRAY}; + +use crate::filter_support::{add_filter, center, center_uv, facing_session as session, filter_of, filtered, refused, set}; + +fn near(a: f32, b: f32) -> bool { + (a - b).abs() < 6e-3 +} + +/// Projects saved before read a gradient as evenly spaced colors from the texel's luma, blended in linear, and save it as before +#[test] +fn a_gradient_saved_before_reads_and_saves_as_before() { + let saved = json!({"GradientMap": {"colors": [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]}}); + let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(filter, Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]])); + assert_eq!(serde_json::to_value(&filter).unwrap(), saved, "nothing new is saved"); + + let Filter::GradientMap { colors, input, .. } = &filter else { panic!() }; + assert_eq!(input.mode, GrayscaleMode::Luma); + + for t in [0.0, 0.2, 0.37, 0.5, 0.81, 1.0] { + assert_eq!(filter.ramp_at(t), gradient(colors, t), "bit for bit as before at {t}"); + } +} + +/// The library's Gradient: black, mid gray and white at 0, 0.5 and 1; places, quantity, invert, balance and linear blending move what a texel reads +#[test] +fn gradient_places_quantity_and_input_transformation() { + let mut s = session(); + let effect = filtered(&mut s, [0.25; 3], json!({"filter": "gradientMap"})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Gradient"); + + let Filter::GradientMap { quantity, input, linear, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!((quantity, input.mode, linear), (Some(3), GrayscaleMode::Average, true)); + + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY / 2.0), "halfway from black to mid gray"); + + set(&mut s, effect, json!({"positions": [0.0, 0.25, 1.0]})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY), "mid gray moved to 0.25"); + + set(&mut s, effect, json!({"invert": true})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.5 / 0.75)), "inverted, it reads 0.75"); + + set(&mut s, effect, json!({"invert": false, "balance": 0.75})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.25 / 0.75)), "balance 0.75 lifts it to 0.5"); + + set(&mut s, effect, json!({"balance": 0.5, "positions": [0.0, 0.5, 1.0], "linear": false})); + let srgb = center(&mut s, Channel::BaseColor)[0]; + assert!(near(srgb, 0.0508), "blended in sRGB, halfway from black to mid gray is sRGB 0.25: {srgb}"); + + set(&mut s, effect, json!({"quantity": 4})); + assert_eq!(filter_of(&s, effect).ramp_colors().len(), 4); + + refused( + &mut s, + effect, + &[ + json!({"quantity": 11}), + json!({"quantity": 1}), + json!({"grayscaleMode": "x"}), + json!({"positions": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]}), + json!({"debug": 3}), + ], + ); + + set(&mut s, effect, json!({"grayscaleMode": "max"})); + let Filter::GradientMap { input, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!(input.mode, GrayscaleMode::Max); +} + +/// A new gradient given its colors alone ramps evenly through every one of them +#[test] +fn a_gradient_given_colors_alone_ramps_evenly_through_all_of_them() { + let mut s = session(); + + let two = filtered(&mut s, [0.5; 3], json!({"filter": "gradientMap", "colors": [[0, 0, 0], [1, 1, 1]]})); + let mid = center(&mut s, Channel::BaseColor)[0]; + assert!(near(mid, 0.5), "black to white reads mid gray halfway: {mid}"); + + execute(&mut s, "effect.remove", &json!({"effect": two.0})).unwrap(); + let five = add_filter(&mut s, json!({"filter": "gradientMap", "colors": [[0, 0, 0], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75], [1, 1, 1]]})); + assert_eq!(filter_of(&s, five).ramp_colors().len(), 5, "every color is used"); +} + +/// Display Gradient (Debug) shows the ramp left to right across the texture +#[test] +fn display_gradient_shows_the_ramp_across_the_texture() { + let mut s = session(); + let effect = filtered(&mut s, [0.9; 3], json!({"filter": "gradientMap", "debug": true})); + let (value, uv) = (center(&mut s, Channel::BaseColor), center_uv(&mut s)); + let ramp = filter_of(&s, effect).ramp_at(uv.x).unwrap(); + assert!((0..3).all(|k| (value[k] - ramp[k]).abs() < 0.03), "{value:?} vs {ramp:?} at u {}", uv.x); +} + +/// An old gradient that gains a quantity keeps its colors' places and adds the new one at 1 +#[test] +fn a_saved_gradient_keeps_its_places_when_it_gains_a_color() { + let mut s = session(); + let effect = filtered(&mut s, [0.5; 3], json!({"filter": "gradientMap"})); + if let Some(found) = s.doc.project.effect_mut(effect) { + found.kind = EffectKind::Filter(Filter::even_gradient(vec![[0.0; 3], [1.0, 0.0, 0.0], [1.0; 3]])); + } + set(&mut s, effect, json!({"quantity": 4})); + let Filter::GradientMap { colors, positions, quantity, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!((positions, quantity), (vec![0.0, 0.5, 1.0, 1.0], Some(4))); + assert_eq!(colors.last(), Some(&[1.0; 3]), "the new color starts as the last one"); +} + +/// A color added at 1 starts as the ramp's color there: its rightmost stop's, not the last one listed +#[test] +fn an_added_color_keeps_the_ramps_end() { + let mut s = session(); + let effect = filtered(&mut s, [0.5; 3], json!({"filter": "gradientMap", "colors": [[1, 1, 1], [0, 0, 0]]})); + set(&mut s, effect, json!({"positions": [0.8, 0.2]})); + let before = filter_of(&s, effect).ramp_at(0.9); + + set(&mut s, effect, json!({"quantity": 3})); + + assert_eq!(before, Some([1.0; 3]), "white past its stop at 0.8"); + assert_eq!(filter_of(&s, effect).ramp_at(0.9), before, "the added color at 1 keeps the end white"); +} + +/// Gradient Curve: values remapped through the preset after balance, contrast and invert +#[test] +fn gradient_curve_remaps_through_its_preset() { + let mut s = session(); + let effect = filtered(&mut s, [0.25; 3], json!({"filter": "gradientCurve"})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Gradient Curve"); + assert_eq!(filter_of(&s, effect), LIBRARY_GRADIENT_CURVE, "the workflow's defaults"); + + let round = (1.0f32 - 0.75 * 0.75).sqrt(); + assert!(near(center(&mut s, Channel::BaseColor)[0], round), "Round at 0.25"); + + set(&mut s, effect, json!({"preset": "easeIn"})); + assert!(near(center(&mut s, Channel::BaseColor)[0], 0.0625), "Ease In at 0.25"); + + set(&mut s, effect, json!({"invert": true})); + assert!(near(center(&mut s, Channel::BaseColor)[0], 0.5625), "Ease In at 0.75"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "preset": "spiral"})).is_err()); + + let Filter::GradientCurve { preset, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!(preset.id(), "easeIn", "a refused preset changes nothing"); +} + +/// Gradient Dynamic with a uniform Gradient Source: every texel reads that color (scalars its gray) +#[test] +fn gradient_dynamic_reads_its_uniform_source() { + let mut s = session(); + let effect = filtered(&mut s, [0.9, 0.1, 0.1], json!({"filter": "gradientDynamic", "color": [0.2, 0.4, 0.6]})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Gradient Dynamic"); + + let Filter::GradientDynamic { vertical, position, .. } = LIBRARY_GRADIENT_DYNAMIC else { panic!() }; + assert_eq!(filter_of(&s, effect), Filter::GradientDynamic { vertical, position, color: [0.2, 0.4, 0.6] }, "the workflow's defaults, the color given"); + + let color = center(&mut s, Channel::BaseColor); + assert!(near(color[0], 0.2) && near(color[1], 0.4) && near(color[2], 0.6), "{color:?}"); + + set(&mut s, effect, json!({"orientation": "vertical", "position": 0.7})); + let Filter::GradientDynamic { vertical, position, .. } = filter_of(&s, effect) else { panic!() }; + assert!(vertical && position == 0.7); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "orientation": "diagonal"})).is_err()); +} diff --git a/crates/engine/tests/it/filter_inputs.rs b/crates/engine/tests/it/filter_inputs.rs new file mode 100644 index 00000000..423eab27 --- /dev/null +++ b/crates/engine/tests/it/filter_inputs.rs @@ -0,0 +1,109 @@ +//! Filter image inputs: Bevel Smooth's and Directional Distance's Distance Map and Warp's Custom Noise read a source set on the effect + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Effect, LayerId, Source}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_shape::shape_edge; +use crate::filter_support::{SIZE, add_filter, roughness, session, set}; + +/// `layer.fill.set` on image input `params` of `effect`: its result, the error as text +fn input(s: &mut Session, effect: LayerId, params: Value) -> Result { + let mut params = params; + params["effect"] = json!(effect.0); + execute(s, "layer.fill.set", ¶ms).map_err(|error| error.to_string()) +} + +/// The image inputs `effect` holds, by input id +fn inputs(s: &Session, effect: LayerId) -> Vec<(String, Source)> { + let (_, found) = s.doc.project.effect(effect).unwrap(); + found.inputs.iter().map(|(id, source)| (id.clone(), source.clone())).collect() +} + +/// Bevel Smooth's Distance Map scales its distance texel by texel: a gray, an anchor's gray, back to white; its default is not stored; one undo step +#[test] +fn a_distance_map_scales_the_bevel_smooth_distance() { + let mut s = session(); + + // A layer below records a roughness of 0.5 at an anchor point + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.5})).unwrap(); + let anchor = LayerId(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap()["effect"].as_u64().unwrap()); + let (at, _, _) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "bevelSmooth"})); + + set(&mut s, effect, json!({"smoothing": 0.0})); + let full = roughness(&mut s, at(4)); + assert!(full > 0.0 && full < 1.0, "on the ramp: {full}"); + + input(&mut s, effect, json!({"input": "distanceMap", "value": 0.5})).unwrap(); + let half = roughness(&mut s, at(4)); + assert!(half < full - 0.05, "half the distance fades sooner: {half} vs {full}"); + assert_eq!(inputs(&s, effect), vec![("distanceMap".to_string(), Source::Uniform([0.5; 3]))]); + + let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"inputs\":{\"distanceMap\""), "inspect shows the input"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(inputs(&s, effect).is_empty(), "one undo step"); + assert_eq!(roughness(&mut s, at(4)), full); + + input(&mut s, effect, json!({"input": "distanceMap", "anchor": anchor.0, "anchorChannel": "roughness"})).unwrap(); + assert!((roughness(&mut s, at(4)) - half).abs() < 1e-3, "the anchor's 0.5 reads as the uniform 0.5"); + + input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap(); + assert!(inputs(&s, effect).is_empty() && roughness(&mut s, at(4)) == full, "cleared: white, as before"); + + let steps = s.history_labels().len(); + input(&mut s, effect, json!({"input": "distanceMap", "value": 1.0})).unwrap(); + input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap(); + assert!(inputs(&s, effect).is_empty(), "the default gray is not stored"); + assert_eq!(s.history_labels().len(), steps, "setting what the input already reads adds no undo step"); + + for bad in [json!({"input": "nope", "value": 0.5}), json!({"input": "distanceMap", "channel": "roughness", "value": 0.5}), json!({"input": "distanceMap"})] + { + assert!(input(&mut s, effect, bad.clone()).is_err(), "{bad}"); + } + assert!(input(&mut s, anchor, json!({"input": "distanceMap", "value": 0.5})).is_err(), "not a filter"); +} + +/// Directional Distance: a black Distance Map leaves no trail +#[test] +fn a_black_distance_map_leaves_no_trail() { + let mut s = session(); + let (at, _, outward) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "directionalDistance"})); + + set(&mut s, effect, json!({"angle": if outward > 0 { 0.0 } else { 180.0 }, "distance": 0.05})); + assert!(roughness(&mut s, at(1)) > 0.0, "a trail"); + + input(&mut s, effect, json!({"input": "distanceMap", "value": 0.0})).unwrap(); + assert_eq!((roughness(&mut s, at(1)), roughness(&mut s, at(-2))), (0.0, 1.0), "no trail, the shapes stay"); +} + +/// Warp's Custom Noise moves texels by its source; projects saved before image inputs load with none and save without them +#[test] +fn a_custom_noise_moves_the_warp() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); + let row = SIZE / 2; + let before: Vec = (0..SIZE).map(|x| roughness(&mut s, (x, row))).collect(); + let moved = |s: &mut Session| (0..SIZE).map(|x| (roughness(s, (x, row)) - before[x as usize]).abs()).fold(0.0f32, f32::max); + + let effect = add_filter(&mut s, json!({"filter": "warp"})); + set(&mut s, effect, json!({"intensity": 0.05, "divider": 1, "warpMode": "directional", "sourceMode": "customNoise"})); + assert!(moved(&mut s) < 2e-3, "its default mid gray moves nothing"); + + input(&mut s, effect, json!({"input": "customNoise", "procedural": "gradient"})).unwrap(); + assert!(moved(&mut s) > 0.01, "a source moves texels: {}", moved(&mut s)); + + set(&mut s, effect, json!({"sourceMode": "defaultNoise"})); + assert_eq!(inputs(&s, effect).len(), 1, "kept while another source mode is on"); + + let (_, found) = s.doc.project.effect(effect).unwrap(); + let saved = serde_json::to_value(Effect { inputs: Default::default(), ..found.clone() }).unwrap(); + assert!(saved.get("inputs").is_none(), "no inputs, no key: saves as before"); + + let loaded: Effect = serde_json::from_value(saved).unwrap(); + assert!(loaded.inputs.is_empty(), "an effect saved before loads with none"); +} diff --git a/crates/engine/tests/it/filter_light.rs b/crates/engine/tests/it/filter_light.rs new file mode 100644 index 00000000..5fccb750 --- /dev/null +++ b/crates/engine/tests/it/filter_light.rs @@ -0,0 +1,204 @@ +//! The light filters: Glow, Drop Shadow, Baked Lighting Stylized and Baked Lighting Environment + +use serde_json::json; +use texturecraft_engine::core::{Channel, DirectionalLight, EffectKind, Filter, LayerId, LightingOutput}; +use texturecraft_engine::filter_lib::{LIBRARY_DROP_SHADOW, LIBRARY_ENVIRONMENT_LIGHTING, LIBRARY_GLOW, library_baked_lighting}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, filter_of, refused, set}; + +/// A plane, so every texel faces the same way +fn session() -> Session { + Session::new_project("t", primitives::plane(2.0, 2), "builtin:plane", None, SIZE).unwrap() +} + +/// A fill layer with library filter `id` in its mask: the effect +fn masked(s: &mut Session, id: &str) -> LayerId { + execute(s, "layer.add.fill", &json!({})).unwrap(); + execute(s, "mask.add.black", &json!({})).unwrap(); + LayerId(execute(s, "effect.add.filter", &json!({"filter": id, "target": "mask"})).unwrap()["effect"].as_u64().unwrap()) +} + +/// Projects saved before keep their additive glow, read and saved as they were; a new Glow is the halo, named the same +#[test] +fn a_glow_saved_before_stays_additive_and_a_new_glow_is_the_halo() { + let saved = json!({"Glow": {"radius": 16.0, "amount": 1.0}}); + let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(filter, Filter::Glow { radius: 16.0, amount: 1.0 }); + assert_eq!(serde_json::to_value(&filter).unwrap(), saved); + + let mut s = session(); + let effect = masked(&mut s, "glow"); + assert_eq!(filter_of(&s, effect), LIBRARY_GLOW, "the workflow's defaults"); + assert_eq!(filter_of(&s, effect).label(), "Glow"); + assert_eq!(filter.label(), "Glow"); +} + +/// Glow's Used on a Mask, Mode, Width (inner glow below 0), Spread, Opacity and Color set and clamp; bad values are refused +#[test] +fn glow_settings_set_clamp_and_refuse() { + let mut s = session(); + let effect = masked(&mut s, "glow"); + + set(&mut s, effect, json!({"usedOnMask": true, "mode": "precise", "width": -3.0, "spread": 0.4, "opacity": 0.6, "color": [0.2, 0.4, 0.6]})); + let glow = Filter::HaloGlow { on_mask: true, precise: true, width: -1.0, spread: 0.4, opacity: 0.6, color: [0.2, 0.4, 0.6] }; + assert_eq!(filter_of(&s, effect), glow); + + refused(&mut s, effect, &[json!({"mode": "hard"}), json!({"usedOnMask": 1}), json!({"color": "red"})]); + + assert_eq!(filter_of(&s, effect), glow); + + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true)); + assert_eq!(filter_of(&s, effect), LIBRARY_GLOW); +} + +/// Drop Shadow: the workflow's defaults, then Angle wrapping, Distance both ways, Size, Spread, Opacity and Color +#[test] +fn drop_shadow_defaults_and_settings() { + let mut s = session(); + let effect = masked(&mut s, "Drop Shadow"); + assert_eq!(filter_of(&s, effect), LIBRARY_DROP_SHADOW, "the workflow's defaults"); + + set(&mut s, effect, json!({"angle": 450.0, "distance": -0.9, "size": 2.0, "spread": 0.3, "opacity": 0.25, "color": "#ffffff"})); + assert_eq!(filter_of(&s, effect), Filter::DropShadow { angle: 90.0, distance: -0.5, size: 1.0, spread: 0.3, opacity: 0.25, color: [1.0; 3] }); + + refused(&mut s, effect, &[json!({"color": [1.0]})]); + + let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "dropShadow" && f["mask"] == true)); +} + +/// A content fill layer with library filter `id` on its content: the effect +fn on_content(s: &mut Session, id: &str) -> LayerId { + execute(s, "layer.add.fill", &json!({})).unwrap(); + add_filter(s, json!({"filter": id})) +} + +/// Projects saved before keep their Baked Lighting, read and saved as they were and named Baked Lighting Stylized; a new one takes the workflow's defaults +#[test] +fn a_baked_lighting_saved_before_stays_and_a_new_one_is_stylized() { + let saved = json!({"BakedLighting": {"azimuth": 45.0, "elevation": 45.0, "light": 0.75, "ambient": 0.5, "occlusion": 1.0}}); + let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert!(filter.stylized_lighting().is_none(), "lights as before"); + assert_eq!(serde_json::to_value(&filter).unwrap(), saved); + assert_eq!(filter.label(), "Baked Lighting Stylized"); + assert_eq!(filter.former_label(), Some("Baked Lighting")); + + let mut s = session(); + let effect = on_content(&mut s, "Baked Lighting"); + let made = filter_of(&s, effect); + assert_eq!(made, library_baked_lighting(), "the workflow's sun, sky and lights"); + + let (stylized, _) = made.stylized_lighting().unwrap(); + assert_eq!( + (stylized.output, stylized.mesh_only, stylized.dielectric_reflectance, stylized.cavity_smoothness), + (LightingOutput::DiffuseSpecular, false, 0.04, 0.25) + ); + assert_eq!((stylized.lights[0].azimuth, stylized.lights[1].azimuth, stylized.lights[0].intensity), (90.0, 180.0, 0.0)); + + let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLighting" && f["mask"] == false && f["label"] == "Baked Lighting Stylized")); +} + +/// The stylized settings set and clamp; one set on a Baked Lighting saved before gives it the rest lit as it was; bad choices are refused +#[test] +fn stylized_lighting_settings_set_clamp_and_refuse() { + let mut s = session(); + let effect = on_content(&mut s, "bakedLighting"); + let old = Filter::BakedLighting { azimuth: 45.0, elevation: 45.0, light: 0.8, ambient: 0.4, occlusion: 1.0, stylized: None }; + s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(old); + + set( + &mut s, + effect, + json!({ + "skyColor": [0.1, 0.2, 0.3], "light1": {"azimuth": 450.0, "elevation": -30.0, "intensity": 5.0, "color": "#ff0000"}, + "diffuseCavity": 0.5, "cavitySmoothness": 9.0, "dielectricReflectance": 1.0, "heightToNormal": 2.0, + "input": "specularGlossiness", "output": "specular", "normalDetails": "meshHeightNormal" + }), + ); + let filter = filter_of(&s, effect); + let (stylized, light) = filter.stylized_lighting().unwrap(); + assert_eq!((light.sun.intensity, light.sky_intensity, stylized.sun_color), (0.8, 0.4, [1.0; 3]), "the rest as it lit"); + + assert_eq!(stylized.sky_color, [0.1, 0.2, 0.3]); + assert_eq!(stylized.lights[0], DirectionalLight { azimuth: 90.0, elevation: 330.0, intensity: 2.0, color: [1.0, 0.0, 0.0] }); + assert_eq!((stylized.diffuse_cavity, stylized.cavity_smoothness, stylized.dielectric_reflectance, stylized.height_to_normal), (0.5, 4.0, 0.16, 2.0)); + assert!(stylized.specular_glossiness && !stylized.mesh_only && stylized.output == LightingOutput::Specular); + + refused( + &mut s, + effect, + &[json!({"output": "both"}), json!({"input": 1}), json!({"normalDetails": "height"}), json!({"light2": 3}), json!({"groundColor": "dirt"})], + ); + assert_eq!(filter_of(&s, effect), filter, "refusals change nothing"); + + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true)); + assert_eq!(filter_of(&s, effect).stylized_lighting().unwrap().0.output, LightingOutput::DiffuseSpecular); +} + +/// Baked Lighting Environment: the workflow's defaults, only the Color pill lit, rotations wrapping and the rest clamped, Restore defaults +#[test] +fn environment_lighting_defaults_and_settings() { + let mut s = session(); + let effect = on_content(&mut s, "bakedLightingEnvironment"); + let made = filter_of(&s, effect); + assert_eq!(made, LIBRARY_ENVIRONMENT_LIGHTING, "the workflow's defaults"); + assert_eq!((made.label(), s.doc.project.effect(effect).unwrap().1.name.as_str()), ("Baked Lighting Environment", "Baked Lighting Environment")); + + let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness) && off.contains(&Channel::Height), "only the Color pill is lit: {off:?}"); + + let stylized = on_content(&mut s, "bakedLighting"); + assert!(s.doc.project.effect(stylized).unwrap().1.off_channels.contains(&Channel::Metallic), "Baked Lighting Stylized lights the Color pill only too"); + + let blur = on_content(&mut s, "blur"); + assert!(s.doc.project.effect(blur).unwrap().1.off_channels.is_empty(), "other filters work on every channel"); + + set( + &mut s, + effect, + json!({"horizontalRotation": 370.0, "verticalRotation": -90.0, "exposure": 9.0, "heightIntensity": -1.0, "ambientOcclusion": 0.5, "specularOcclusion": 2.0}), + ); + assert_eq!( + filter_of(&s, effect), + Filter::EnvironmentLighting { + horizontal: 10.0, + vertical: 270.0, + exposure: 5.0, + height_intensity: 0.0, + ambient_occlusion: 0.5, + specular_occlusion: 1.0 + } + ); + + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true)); + assert_eq!(filter_of(&s, effect), made); + + let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLightingEnvironment" && f["mask"] == false)); +} + +/// Baked Lighting Environment lights the base color with the viewport environment: another environment relights it, Exposure brightens it +#[test] +fn environment_lighting_follows_the_viewport_environment() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap(); + let center = |s: &mut Session| { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, SIZE / 2, SIZE / 2) + }; + let unlit = center(&mut s); + + let effect = add_filter(&mut s, json!({"filter": "bakedLightingEnvironment"})); + let studio = center(&mut s); + assert_ne!(studio, unlit, "the studio lights the base color"); + + execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap(); + let night = center(&mut s); + assert!(night[0] < studio[0] * 0.5, "the night lights it less: {night:?} vs {studio:?}"); + + set(&mut s, effect, json!({"exposure": 3.0})); + assert!(center(&mut s)[0] > night[0], "exposure brightens it"); +} diff --git a/crates/engine/tests/it/filter_shape.rs b/crates/engine/tests/it/filter_shape.rs new file mode 100644 index 00000000..73dc6521 --- /dev/null +++ b/crates/engine/tests/it/filter_shape.rs @@ -0,0 +1,364 @@ +//! The shape filters: Threshold's modes, Mirror, Mask Outline, Bevel, Bevel Smooth, Directional Distance, Warp's modes and Blur Slope's source + +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + Bevel, BevelBlur, BevelCorner, BevelDirection, BevelSmooth, DirectionalDistance, EffectKind, Filter, MaskOutline, Mirror, MirrorCorner, MirrorMode, + OutlinePosition, SlopeBlending, SourceSlopeBlur, SourceWarp, ThresholdMode, WarpBlending, WarpMode, WarpSource, WarpSourceMode, +}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, filter_of, refused, roughness, session, set}; + +/// Threshold: a new one is Greater than 0.01; each mode compares its way; one saved before keeps Greater or equal +#[test] +fn threshold_modes_compare_their_way() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + let effect = add_filter(&mut s, json!({"filter": "threshold"})); + assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater }, "the library defaults"); + + let texel = (SIZE / 4, SIZE / 2); + assert_eq!(roughness(&mut s, texel), 1.0); + + set(&mut s, effect, json!({"level": 0.25})); + assert_eq!(roughness(&mut s, texel), 0.0, "a value at the level is not greater"); + + for (mode, white) in [("greaterOrEqual", 1.0), ("lower", 0.0), ("lowerOrEqual", 1.0)] { + set(&mut s, effect, json!({"mode": mode})); + assert_eq!(roughness(&mut s, texel), white, "{mode}"); + } + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "sideways"})).is_err()); + assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.25, mode: ThresholdMode::LowerOrEqual }, "a refused mode changes nothing"); + + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater }); +} + +/// Mirror: the left half of each UV tile copied onto the right (inverted the other way, or a corner onto the rest), its axis white in Display Debug +#[test] +fn mirror_copies_one_side_over_the_other() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); + let row = SIZE / 2; + let (left, right) = ((20, row), (SIZE - 1 - 20, row)); + let (left_before, right_before) = (roughness(&mut s, left), roughness(&mut s, right)); + assert!((left_before - right_before).abs() > 0.05, "the gradient differs across: {left_before} {right_before}"); + + let effect = add_filter(&mut s, json!({"filter": "mirror"})); + assert_eq!(filter_of(&s, effect), Filter::Mirror(Mirror::LIBRARY)); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Mirror"); + assert!((roughness(&mut s, left) - left_before).abs() < 2e-3, "the left side stays"); + assert!((roughness(&mut s, right) - left_before).abs() < 2e-3, "the right side reads the left"); + + set(&mut s, effect, json!({"invertAxisX": true})); + assert!((roughness(&mut s, left) - right_before).abs() < 2e-3, "inverted, the left side reads the right"); + + set(&mut s, effect, json!({"mode": "corner", "cornerType": "topRight"})); + assert!((roughness(&mut s, (20, 20)) - roughness(&mut s, (SIZE - 1 - 20, 20))).abs() < 2e-3, "a corner mirrors across too"); + + let Filter::Mirror(mirror) = filter_of(&s, effect) else { panic!() }; + assert_eq!((mirror.mode, mirror.corner), (MirrorMode::Corner, MirrorCorner::TopRight)); + + set(&mut s, effect, json!({"mode": "axisX", "displayDebug": true})); + assert_eq!(roughness(&mut s, (SIZE / 2, row)), 1.0, "Display Debug draws the axis white"); + + refused(&mut s, effect, &[json!({"mode": "diagonal"}), json!({"cornerType": "middle"}), json!({"invertAxisY": "yes"})]); + + set(&mut s, effect, json!({"axisYOffset": 3.0})); + let Filter::Mirror(mirror) = filter_of(&s, effect) else { panic!() }; + assert_eq!(mirror.offset, [0.5, 1.0], "offsets clamp to the tile"); +} + +/// Mask Outline: a band along the edge where the gradient crosses its Threshold, outside, inside or on both sides, on black or over the values +#[test] +fn mask_outline_draws_a_band_along_the_threshold_edge() { + let mut s = session(); + let (at, values, _) = shape_edge(&mut s); + + let effect = add_filter(&mut s, json!({"filter": "maskOutline"})); + assert_eq!(filter_of(&s, effect), Filter::MaskOutline(MaskOutline::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Mask Outline"); + + set(&mut s, effect, json!({"threshold": 0.5, "width": 0.03})); + assert_eq!(roughness(&mut s, at(2)), 1.0, "outside, next to the edge"); + assert_eq!(roughness(&mut s, at(8)), 0.0, "past the band"); + assert_eq!(roughness(&mut s, at(-2)), 0.0, "inside the shapes"); + + set(&mut s, effect, json!({"maskPosition": "inside"})); + assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 0.0), "inside"); + + set(&mut s, effect, json!({"maskPosition": "both"})); + assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 1.0), "both sides"); + + set(&mut s, effect, json!({"startFromBlack": false})); + let far = at(8); + assert!((roughness(&mut s, far) - values[far.0 as usize]).abs() < 2e-3, "over the values"); + + set(&mut s, effect, json!({"startFromBlack": true, "maskPosition": "outside", "blur": 1.0})); + let (near, further) = (roughness(&mut s, at(1)), roughness(&mut s, at(2))); + assert!(near > further && further > 0.0 && near < 1.0, "a blurred band fades out: {near} {further}"); + + refused(&mut s, effect, &[json!({"maskPosition": "around"}), json!({"startFromBlack": 1})]); + + set(&mut s, effect, json!({"width": 4.0, "curveShape": -3.0})); + let Filter::MaskOutline(outline) = filter_of(&s, effect) else { panic!() }; + assert_eq!((outline.position, outline.width, outline.curve), (OutlinePosition::Outside, 1.0, -1.0), "values clamp"); + + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::MaskOutline(MaskOutline::LIBRARY)); +} + +/// A fill whose roughness is a repeating gradient: the middle row's values +fn gradient_row(s: &mut Session) -> Vec { + execute(s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + execute(s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); + middle_row(s) +} + +/// The composited roughness along the middle row +fn middle_row(s: &mut Session) -> Vec { + (0..SIZE).map(|x| roughness(s, (x, SIZE / 2))).collect() +} + +/// A roughness gradient crossing 0.5 away from the tile's sides along the middle row: texel `steps` outward of the shapes' first texel at its edge (inward below 0), the values before any filter, and the outward direction along x +pub(crate) fn shape_edge(s: &mut Session) -> (impl Fn(i64) -> (u32, u32) + use<>, Vec, i64) { + let row = SIZE / 2; + let values = gradient_row(s); + let edge = (SIZE / 4..SIZE * 3 / 4).find(|x| (values[*x as usize] >= 0.5) != (values[*x as usize - 1] >= 0.5)).unwrap(); + let (inner, outward): (u32, i64) = if values[edge as usize] >= 0.5 { (edge, -1) } else { (edge - 1, 1) }; + (move |steps: i64| ((inner as i64 + steps * outward) as u32, row), values, outward) +} + +/// Bevel: a negative Distance slopes the shapes down to their edge, a positive one rises around them; Smoothing, Corner Type, Blur Mode and Wrap set; one saved before keeps its width bevel +#[test] +fn bevel_slopes_inwards_or_outwards() { + let mut s = session(); + let (at, values, _) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "bevel"})); + assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(Bevel::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Bevel"); + + let value = |at: (u32, u32)| values[at.0 as usize]; + + // Inwards over a tenth of the tile (12.8 texels here) + let (edge, outside) = (roughness(&mut s, at(0)), roughness(&mut s, at(3))); + assert!(edge < value(at(0)) * 0.2, "down at the edge: {edge} vs {}", value(at(0))); + assert!((outside - value(at(3))).abs() < 2e-3, "outside untouched"); + + set(&mut s, effect, json!({"distance": 0.1})); + let (near, further) = (roughness(&mut s, at(1)), roughness(&mut s, at(6))); + assert!(near > 0.8 && further > value(at(6)) && near > further, "rises around the shapes: {near} {further}"); + assert!((roughness(&mut s, at(-2)) - value(at(-2))).abs() < 2e-3, "inside untouched"); + + set(&mut s, effect, json!({"smoothing": 2.0, "blurMode": "uniform"})); + let smoothed = roughness(&mut s, at(1)); + assert!((smoothed - near).abs() > 1e-3, "smoothing blurs the slope: {smoothed} vs {near}"); + + set(&mut s, effect, json!({"cornerType": "angular", "wrap": true})); + refused(&mut s, effect, &[json!({"cornerType": "square"}), json!({"blurMode": "even"}), json!({"wrap": 1})]); + + set(&mut s, effect, json!({"distance": -3.0, "smoothing": 9.0})); + let expected = Bevel { wrap: true, distance: -1.0, corner: BevelCorner::Angular, smoothing: 5.0, blur: BevelBlur::Uniform }; + assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(expected), "values clamp"); + + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(Bevel::LIBRARY)); + + let old: Filter = serde_json::from_value(json!({"Bevel": {"width": 16.0}})).unwrap(); + assert_eq!(old, Filter::Bevel { width: 16.0, wrap: false }, "a bevel saved before keeps its width"); +} + +/// Bevel Smooth: a ramp from the edge outwards (shapes white), inwards (around them black) or across it (mid gray on it) +#[test] +fn bevel_smooth_ramps_from_the_edge() { + let mut s = session(); + let (at, _, _) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "bevelSmooth"})); + assert_eq!(filter_of(&s, effect), Filter::BevelSmooth(BevelSmooth::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Bevel Smooth"); + + set(&mut s, effect, json!({"smoothing": 0.0})); + + let (inside, near, further) = (roughness(&mut s, at(-3)), roughness(&mut s, at(1)), roughness(&mut s, at(6))); + assert_eq!(inside, 1.0, "out: the shapes stay white"); + assert!(near > further && further > 0.0 && near < 1.0, "fades outwards: {near} {further}"); + + set(&mut s, effect, json!({"direction": "in"})); + let (outside, inner) = (roughness(&mut s, at(3)), roughness(&mut s, at(-3))); + assert!(outside == 0.0 && inner > 0.0 && inner < 1.0, "in: rises inwards: {outside} {inner}"); + + set(&mut s, effect, json!({"direction": "inOut"})); + let (edge_in, edge_out) = (roughness(&mut s, at(0)), roughness(&mut s, at(1))); + assert!(edge_in > 0.5 && edge_out < 0.5 && edge_in - edge_out < 0.2, "across: mid gray at the edge: {edge_in} {edge_out}"); + + set(&mut s, effect, json!({"curveOffset": 0.5})); + assert!(roughness(&mut s, at(0)) > edge_in, "the offset raises the ramp"); + + refused(&mut s, effect, &[json!({"direction": "up"}), json!({"wrap": "yes"})]); + + set(&mut s, effect, json!({"distance": 2.0, "smoothing": 20.0, "maskThreshold": -1.0, "distanceMapMultiplier": 4.0, "curveShape": 5.0})); + let Filter::BevelSmooth(smooth) = filter_of(&s, effect) else { panic!() }; + assert_eq!( + (smooth.direction, smooth.distance, smooth.smoothing, smooth.threshold, smooth.multiplier, smooth.curve_shape), + (BevelDirection::InOut, 0.3, 10.0, 0.0, 1.0, 1.0), + "values clamp" + ); +} + +/// Directional Distance: a trail fading away from the shapes towards its Angle, none against it +#[test] +fn directional_distance_trails_one_way() { + let mut s = session(); + let (at, _, outward) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "directionalDistance"})); + assert_eq!(filter_of(&s, effect), Filter::DirectionalDistance(DirectionalDistance::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Directional Distance"); + + // Along the row, away from the shapes + let away = if outward > 0 { 0.0 } else { 180.0 }; + set(&mut s, effect, json!({"angle": away, "distance": 0.05})); + let (inside, near, further) = (roughness(&mut s, at(-2)), roughness(&mut s, at(1)), roughness(&mut s, at(4))); + assert_eq!(inside, 1.0, "the shapes are white"); + assert!(near > further && further > 0.0, "fades away from them: {near} {further}"); + + set(&mut s, effect, json!({"contrast": 0.5})); + assert_eq!(roughness(&mut s, at(1)), 1.0, "contrast hardens the near trail"); + + set(&mut s, effect, json!({"angle": away + 180.0, "contrast": 0.0})); + assert!(roughness(&mut s, at(1)) < near, "against the angle the edge gets less trail"); + + set(&mut s, effect, json!({"distance": 1.0, "angle": -90.0, "contrast": 3.0, "distanceMapMultiplier": -1.0})); + let expected = DirectionalDistance { distance: 0.3, angle: 270.0, contrast: 1.0, multiplier: 0.0 }; + assert_eq!(filter_of(&s, effect), Filter::DirectionalDistance(expected), "values clamp, the angle wraps"); +} + +/// Texels either side of a texel that must all rise (or fall) for the warp and slope tests to read it as on a slope +const SLOPE_WINDOW: usize = 8; + +/// Warp: library defaults, the former Directional Warp id, Previous Input moving texels by their values, blended directions, old saves +#[test] +fn warp_modes_move_texels_their_way() { + let mut s = session(); + let before = gradient_row(&mut s); + let after = middle_row; + let moved = |values: &[f32]| values.iter().zip(&before).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + + let effect = add_filter(&mut s, json!({"filter": "warp"})); + assert_eq!(filter_of(&s, effect), Filter::SourceWarp(SourceWarp::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Warp"); + + set(&mut s, effect, json!({"intensity": 0.05, "divider": 1})); + let warped = after(&mut s); + assert!(moved(&warped) > 0.01 && warped.iter().all(|v| v.is_finite()), "the noise moves texels: {}", moved(&warped)); + + set(&mut s, effect, json!({"intensity": 0.0})); + assert!(moved(&after(&mut s)) < 2e-3, "no intensity, no move"); + + // Along the gradient where it rises: a texel above mid gray reads further up it, so it gets lighter + let rising = |x: usize| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] > before[k]); + let falling = |x: usize| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] < before[k]); + let light = |x: &usize| (0.6..0.85).contains(&before[*x]); + let (texel, angle) = match (SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| light(x) && rising(*x)) { + Some(x) => (x, 0.0), + None => ((SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| light(x) && falling(*x)).unwrap(), 180.0), + }; + set(&mut s, effect, json!({"intensity": 0.05, "warpMode": "directional", "angle": angle, "sourceMode": "previousInput"})); + let directional = after(&mut s); + assert!(directional[texel] > before[texel] + 0.01, "{} -> {}", before[texel], directional[texel]); + + set(&mut s, effect, json!({"sourceMode": "customNoise"})); + assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing moves"); + + set(&mut s, effect, json!({"warpMode": "multiDirectional", "sourceMode": "defaultNoise", "directions": 2, "blendingMode": "max"})); + let max = after(&mut s); + set(&mut s, effect, json!({"blendingMode": "min"})); + let min = after(&mut s); + set(&mut s, effect, json!({"blendingMode": "average"})); + let average = after(&mut s); + assert!(max.iter().zip(&min).all(|(max, min)| max + 1e-4 >= *min) && max.iter().zip(&min).any(|(max, min)| max - min > 0.01), "Max over Min"); + assert!(average.iter().zip(max.iter().zip(&min)).all(|(average, (max, min))| *average <= max + 2e-3 && *average >= min - 2e-3), "the average between"); + + set(&mut s, effect, json!({"blendingMode": "chain", "directions": 4})); + assert!(after(&mut s).iter().all(|v| v.is_finite())); + + refused(&mut s, effect, &[json!({"warpMode": "spiral"}), json!({"directions": 3}), json!({"blendingMode": "sum"}), json!({"sourceMode": "image"})]); + + set(&mut s, effect, json!({"intensity": 5.0, "angle": -90.0, "sourceTiling": 99.0, "sourceBlur": -1.0, "seed": 7})); + let Filter::SourceWarp(warp) = filter_of(&s, effect) else { panic!() }; + assert_eq!((warp.intensity, warp.angle, warp.source.tiling, warp.source.blur, warp.seed), (1.0, 270.0, 16.0, 0.0, 7), "values clamp, the angle wraps"); + assert_eq!((warp.mode, warp.blending, warp.directions), (WarpMode::MultiDirectional, WarpBlending::Chain, 4)); + + let former = add_filter(&mut s, json!({"filter": "warpDirectional"})); + let directional = SourceWarp { mode: WarpMode::Directional, ..SourceWarp::LIBRARY }; + assert_eq!(filter_of(&s, former), Filter::SourceWarp(directional), "the former id adds a Directional Warp"); + + // Saved before the modes: loads as it was, and Restore defaults gives the warp of its mode + let saved = json!({"DirectionalWarp": {"intensity": 8.0, "angle": 30.0, "scale": 4.0, "seed": 3}}); + let old: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(old, Filter::DirectionalWarp { intensity: 8.0, angle: 30.0, scale: 4.0, seed: 3, divider: 1 }); + assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before"); + + s.doc.project.effect_mut(former).unwrap().kind = EffectKind::Filter(old); + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": former.0})).unwrap(); + assert_eq!(filter_of(&s, former), Filter::SourceWarp(directional)); +} + +/// Blur Slope: library defaults, Min under Blur under Max, reading downhill of its Previous Input, Quality, one undo, old saves +#[test] +fn slope_blur_reads_downhill_of_its_source() { + let mut s = session(); + let before = gradient_row(&mut s); + let after = middle_row; + let moved = |values: &[f32]| values.iter().zip(&before).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + + let effect = add_filter(&mut s, json!({"filter": "slopeBlur"})); + assert_eq!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Blur Slope"); + + set(&mut s, effect, json!({"intensity": 0.05, "divider": 1})); + let blur = after(&mut s); + assert!(moved(&blur) > 0.005 && blur.iter().all(|v| v.is_finite()), "the noise's slope smears: {}", moved(&blur)); + + set(&mut s, effect, json!({"blendingMode": "min"})); + let min = after(&mut s); + set(&mut s, effect, json!({"blendingMode": "max"})); + let max = after(&mut s); + assert!(max.iter().zip(&min).all(|(max, min)| max + 1e-4 >= *min) && max.iter().zip(&min).any(|(max, min)| max - min > 0.01), "Max over Min"); + assert!(blur.iter().zip(max.iter().zip(&min)).all(|(blur, (max, min))| *blur <= max + 2e-3 && *blur >= min - 2e-3), "Blur between"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + let Filter::SourceSlopeBlur(slope) = filter_of(&s, effect) else { panic!() }; + assert_eq!(slope.blending, SlopeBlending::Min, "one undo step"); + + // Read downhill of the gradient itself: every texel where it rises reads darker values + set(&mut s, effect, json!({"blendingMode": "blur", "sourceMode": "previousInput"})); + let downhill = after(&mut s); + let rising = (SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] > before[k] + 1e-4)).unwrap(); + assert!(downhill[rising] < before[rising] - 0.005, "{} -> {}", before[rising], downhill[rising]); + + set(&mut s, effect, json!({"quality": 0.0})); + let coarse = after(&mut s); + assert!(coarse.iter().all(|v| v.is_finite()) && coarse != downhill, "fewer reads, another smear"); + + set(&mut s, effect, json!({"sourceMode": "customNoise"})); + assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing smears"); + + refused(&mut s, effect, &[json!({"blendingMode": "average"}), json!({"sourceMode": "image"}), json!({"divider": 7})]); + + set(&mut s, effect, json!({"intensity": 5.0, "quality": -1.0, "sourceTiling": 99.0, "sourceBlur": 2.0, "sourceBalance": 0.25, "seed": 7})); + let Filter::SourceSlopeBlur(slope) = filter_of(&s, effect) else { panic!() }; + let source = WarpSource { mode: WarpSourceMode::CustomNoise, blur: 1.0, balance: 0.25, contrast: 0.0, tiling: 16.0 }; + assert_eq!((slope.intensity, slope.quality, slope.source, slope.seed), (1.0, 0.0, source, 7), "values clamp"); + + // Saved before its source settings: loads and saves as it was, and Restore defaults gives today's Blur Slope + let saved = json!({"SlopeBlur": {"radius": 16.0, "scale": 4.0, "seed": 1}}); + let old: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(old, Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1, divider: 1 }); + assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before"); + + s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(old); + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur::LIBRARY)); +} diff --git a/crates/engine/tests/it/filter_simple.rs b/crates/engine/tests/it/filter_simple.rs new file mode 100644 index 00000000..8b6bdaaa --- /dev/null +++ b/crates/engine/tests/it/filter_simple.rs @@ -0,0 +1,319 @@ +//! The simple adjustment filters, the blurs, Highpass and Grayscale Conversion + +use serde_json::json; +use texturecraft_engine::core::{Channel, ConversionMode, EffectKind, Filter, GrayscaleConversion, HighpassSpace, lum}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, filter_of, roughness, session, set}; + +/// A session with one roughness `value` fill +fn fill(value: f32) -> Session { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": value})).unwrap(); + s +} + +const TEXEL: (u32, u32) = (SIZE / 4, SIZE / 2); + +fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 2e-3 +} + +/// The library defaults leave the values as they are (Posterize steps them, Invert inverts) +#[test] +fn new_simple_filters_start_where_the_reference_does() { + let cases = [ + ("clamp", Filter::Clamp { min: 0.0, max: 1.0 }), + ("smoothstep", Filter::Smoothstep { min: 0.0, max: 1.0 }), + ("heightAdjust", Filter::HeightAdjust { invert: false, offset: 0.0, multiply: 1.0 }), + ("histogramScan", Filter::HistogramScan { position: 0.5, contrast: 0.0, invert_position: false }), + ("histogramShift", Filter::HistogramShift { offset: 0.0 }), + ("posterize", Filter::Posterize { levels: 8.0, alpha: false }), + ("invert", Filter::Invert), + ]; + for (id, defaults) in cases { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": id})); + assert_eq!(filter_of(&s, effect), defaults, "{id}"); + } + let mut s = fill(0.25); + add_filter(&mut s, json!({"filter": "clamp"})); + add_filter(&mut s, json!({"filter": "heightAdjust"})); + add_filter(&mut s, json!({"filter": "histogramScan"})); + add_filter(&mut s, json!({"filter": "histogramShift"})); + assert!(close(roughness(&mut s, TEXEL), 0.25), "Clamp, Height Adjust, Histogram Scan and Shift at their defaults change nothing"); +} + +/// Smoothstep eases between its bounds; Clamp keeps within them +#[test] +fn smoothstep_eases_between_minimum_and_maximum() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "smoothstep"})); + assert!(close(roughness(&mut s, TEXEL), 0.15625), "0.25 eased: 3t² − 2t³"); + + set(&mut s, effect, json!({"min": 0.25, "max": 0.75})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "at the minimum"); + + set(&mut s, effect, json!({"min": 0.0, "max": 0.2})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "past the maximum"); + + set(&mut s, effect, json!({"min": 0.25, "max": 0.25})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "equal bounds are a step, the bound itself white"); +} + +/// Invert's switch turns it off and on in one undo step each; restore defaults turns it back on +#[test] +fn invert_switches_off_and_on() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "invert"})); + assert!(close(roughness(&mut s, TEXEL), 0.75)); + + set(&mut s, effect, json!({"invert": false})); + assert_eq!(filter_of(&s, effect), Filter::InvertOff); + assert!(close(roughness(&mut s, TEXEL), 0.25), "off changes nothing"); + assert_eq!(filter_of(&s, effect).label(), "Invert", "still named Invert"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "invert": "yes"})).is_err()); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Invert, "one undo step"); + + set(&mut s, effect, json!({"invert": false})); + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Invert); + + // An old project's Invert still reads as before + let old: Filter = serde_json::from_value(json!("Invert")).unwrap(); + assert_eq!(old, Filter::Invert); +} + +/// Height Adjust flips, scales and raises around mid gray +#[test] +fn height_adjust_flips_scales_and_raises() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "heightAdjust"})); + + set(&mut s, effect, json!({"multiply": 2.0})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "(0.25 − 0.5) × 2 + 0.5"); + + set(&mut s, effect, json!({"invert": true, "offset": 0.1})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "flipped to 0.75, (0.75 − 0.5) × 2 + 0.5 + 0.1 clamped"); + + set(&mut s, effect, json!({"multiply": 1.0, "offset": -0.2})); + assert!(close(roughness(&mut s, TEXEL), 0.55)); + + set(&mut s, effect, json!({"multiply": 50.0})); + assert_eq!(filter_of(&s, effect), Filter::HeightAdjust { invert: true, offset: -0.2, multiply: 10.0 }, "Multiply caps at 10"); +} + +/// Height Adjust's Offset reaches -10..10 as the reference's does +#[test] +fn height_adjust_offset_reaches_ten_either_way() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "heightAdjust"})); + + set(&mut s, effect, json!({"offset": 5.0})); + let kept = filter_of(&s, effect); + set(&mut s, effect, json!({"offset": -50.0})); + + assert_eq!(kept, Filter::HeightAdjust { invert: false, offset: 5.0, multiply: 1.0 }, "an offset of 5 is kept"); + assert_eq!(filter_of(&s, effect), Filter::HeightAdjust { invert: false, offset: -10.0, multiply: 1.0 }, "Offset stops at -10"); +} + +/// Histogram Scan's Invert Position reads the position from the other end; old saves have none +#[test] +fn histogram_scan_inverts_its_position() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "histogramScan"})); + + set(&mut s, effect, json!({"position": 0.2, "contrast": 1.0})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "0.25 is above 0.2"); + + set(&mut s, effect, json!({"invertPosition": true})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "0.25 is below 1 − 0.2"); + + let old: Filter = serde_json::from_value(json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}})).unwrap(); + assert_eq!(old, Filter::HistogramScan { position: 0.5, contrast: 0.5, invert_position: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}}), "saved as before"); +} + +/// Histogram Shift's Position: 1 shifts nothing, lower shifts back by 1 − position; offsets saved before read as themselves +#[test] +fn histogram_shift_takes_a_position() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "histogramShift"})); + + set(&mut s, effect, json!({"position": 0.5})); + assert_eq!(filter_of(&s, effect), Filter::HistogramShift { offset: -0.5 }); + assert!(close(roughness(&mut s, TEXEL), 0.75), "0.25 − 0.5 wraps to 0.75"); + + assert_eq!(Filter::shift_position(-0.5), 0.5); + assert_eq!(Filter::shift_position(0.25), 0.25, "an old positive offset shows as itself"); + assert_eq!(Filter::shift_position(0.0), 1.0); +} + +/// Posterize steps to its Colors Amount and takes Apply to Alpha; old saves read without it and save as before +#[test] +fn posterize_takes_apply_to_alpha() { + let mut s = fill(0.3); + let effect = add_filter(&mut s, json!({"filter": "posterize"})); + + set(&mut s, effect, json!({"levels": 2, "applyToAlpha": true})); + assert_eq!(filter_of(&s, effect), Filter::Posterize { levels: 2.0, alpha: true }); + assert!(close(roughness(&mut s, TEXEL), 0.0)); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": 1})).is_err()); + + let old: Filter = serde_json::from_value(json!({"Posterize": {"levels": 4.0}})).unwrap(); + assert_eq!(old, Filter::Posterize { levels: 4.0, alpha: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Posterize": {"levels": 4.0}}), "saved as before"); +} + +/// Pixelate takes Pixels Amount (cells across the UV tile) and Apply To Alpha; Mosaics saved before load and save as before +#[test] +fn pixelate_takes_pixels_amount_and_apply_to_alpha() { + let mut s = fill(0.3); + let effect = add_filter(&mut s, json!({"filter": "pixelate"})); + assert_eq!(filter_of(&s, effect), Filter::Mosaic { size: 64.0, alpha: true }, "32 pixels across, coverage stepped"); + + set(&mut s, effect, json!({"pixelsAmount": 7.6, "applyToAlpha": false})); + let Filter::Mosaic { size, alpha } = filter_of(&s, effect) else { panic!() }; + assert!(close(Filter::pixels_amount(size), 8.0) && !alpha, "a whole Pixels Amount: {size}"); + assert!(close(roughness(&mut s, TEXEL), 0.3), "a uniform fill stays"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "no"})).is_err()); + + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Pixelate"), "named after the reference workflow"); + + let old: Filter = serde_json::from_value(json!({"Mosaic": {"size": 32.0}})).unwrap(); + assert_eq!(old, Filter::Mosaic { size: 32.0, alpha: true }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Mosaic": {"size": 32.0}}), "saved as before"); +} + +/// FXAA (Anti-aliasing) takes Affect Alpha Channel (off for a new one) and leaves flat values as they are +#[test] +fn fxaa_takes_affect_alpha_channel() { + let mut s = fill(0.3); + let effect = add_filter(&mut s, json!({"filter": "FXAA (Anti-aliasing)"})); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false }); + + set(&mut s, effect, json!({"affectAlphaChannel": true})); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: true }); + assert!(close(roughness(&mut s, TEXEL), 0.3), "nothing to smooth on a flat fill"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "affectAlphaChannel": 2})).is_err()); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false }, "one undo step"); +} + +/// Blur and Blur Directional take Intensity in the reference workflow's unit (16 texels at 2K each); radius still works +#[test] +fn blurs_take_intensity() { + let mut s = fill(0.3); + let blur = add_filter(&mut s, json!({"filter": "blur"})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 4.8, wrap: false }, "a new Blur starts at Blur Intensity 0.30"); + + set(&mut s, blur, json!({"intensity": 2.0})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 32.0, wrap: false }); + + set(&mut s, blur, json!({"intensity": 1000.0})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 256.0, wrap: false }, "capped as radius is"); + + let directional = add_filter(&mut s, json!({"filter": "blurDirectional"})); + + set(&mut s, directional, json!({"intensity": 0.5, "angle": 90})); + assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 8.0, angle: 90.0 }); + + set(&mut s, directional, json!({"radius": 4.0})); + assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 4.0, angle: 90.0 }, "radius in texels at 2K still sets it"); +} + +/// Highpass takes Radius in Blur Intensity's unit (a new one 3), Color Space and Apply To Alpha; a Highpass saved before loads and saves as before +#[test] +fn highpass_takes_radius_color_space_and_apply_to_alpha() { + let mut s = fill(0.3); + let effect = add_filter(&mut s, json!({"filter": "Highpass"})); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::Working, alpha: false }); + assert!(close(roughness(&mut s, TEXEL), 0.5), "a flat fill has no detail: mid gray"); + + set(&mut s, effect, json!({"intensity": 0.5, "colorSpace": "srgbFromAcescg", "applyToAlpha": true})); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 8.0, space: HighpassSpace::SrgbFromAcescg, alpha: true }); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "colorSpace": "rec2020"})).is_err()); + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "yes"})).is_err()); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::Working, alpha: false }, "one undo step"); + + let old: Filter = serde_json::from_value(json!({"HighPass": {"radius": 8.0}})).unwrap(); + assert_eq!(old, Filter::HighPass { radius: 8.0, space: HighpassSpace::Working, alpha: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HighPass": {"radius": 8.0}}), "saved as before"); +} + +/// The composited base color at the test texel +fn base_color(s: &mut Session) -> [f32; 3] { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, TEXEL.0, TEXEL.1) +} + +/// A new Grayscale Conversion weighs a third of each component; a Grayscale saved before keeps its luminance, also after its first edit +#[test] +fn grayscale_conversion_takes_its_settings_and_keeps_saved_grayscales() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1]})).unwrap(); + let effect = add_filter(&mut s, json!({"filter": "Grayscale Conversion"})); + assert_eq!(filter_of(&s, effect), Filter::GrayscaleConversion(GrayscaleConversion::LIBRARY)); + + s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(Filter::Grayscale); + let saved = base_color(&mut s); + assert!(saved.iter().all(|v| close(*v, saved[0])) && close(saved[0], lum([0.8, 0.2, 0.1])), "{saved:?}"); + + set(&mut s, effect, json!({"balance": 0.5})); + assert_eq!(filter_of(&s, effect), Filter::GrayscaleConversion(GrayscaleConversion::of_luminance()), "the luminance weights"); + assert!(close(base_color(&mut s)[0], saved[0]), "looks the same after its first edit"); + + set(&mut s, effect, json!({"red": 1.0, "green": 0.0, "blue": 0.0, "invert": true})); + assert!(close(base_color(&mut s)[0], 1.0 - 0.8), "Red only, inverted"); + + set(&mut s, effect, json!({"mode": "min", "invert": false})); + assert!(close(base_color(&mut s)[0], 0.1), "the darkest component"); + + set(&mut s, effect, json!({"channelInput": "customInput", "mode": "max"})); + assert!(close(base_color(&mut s)[0], 0.5), "the Custom Input reads mid gray until set"); + + let Filter::GrayscaleConversion(conversion) = filter_of(&s, effect) else { panic!("converted") }; + assert!(conversion.custom_input && conversion.mode == ConversionMode::Max); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channelInput": "image"})).is_err()); + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "luma"})).is_err(), "Luma is the gradients' mode"); + + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Grayscale Conversion")); + assert_eq!(serde_json::to_value(Filter::Grayscale).unwrap(), json!("Grayscale"), "saved as before"); +} + +/// Grayscale Conversion turns only colors gray: a signed height keeps its sign and a normal map is left alone +#[test] +fn grayscale_conversion_keeps_heights_signed_and_normals_as_they_are() { + let mut s = session(); + let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1]})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "height", "value": -0.6})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "normal", "value": [0.7, 0.5, 0.95]})).unwrap(); + s.update(); + let height_before = s.caches[0].composite.value(Channel::Height, TEXEL.0, TEXEL.1)[0]; + let normal_before = s.caches[0].composite.value(Channel::Normal, TEXEL.0, TEXEL.1); + + add_filter(&mut s, json!({"filter": "grayscale"})); + s.update(); + let height = s.caches[0].composite.value(Channel::Height, TEXEL.0, TEXEL.1)[0]; + let normal = s.caches[0].composite.value(Channel::Normal, TEXEL.0, TEXEL.1); + + assert!(height_before < -0.5, "the fill's height is negative: {height_before}"); + assert!((height - height_before).abs() < 0.02, "a signed height keeps its sign: {height} from {height_before}"); + assert!(normal.iter().zip(normal_before).all(|(after, before)| close(*after, before)), "the normal is untouched: {normal:?}"); + + let gray = base_color(&mut s); + assert!(close(gray[0], gray[2]), "the color turns gray: {gray:?}"); +} diff --git a/crates/engine/tests/it/filter_swap.rs b/crates/engine/tests/it/filter_swap.rs index 0bfa03f4..c8502ad8 100644 --- a/crates/engine/tests/it/filter_swap.rs +++ b/crates/engine/tests/it/filter_swap.rs @@ -1,10 +1,12 @@ //! Swapping a filter effect's type in place through `effect.set {filter}` use serde_json::{Value, json}; -use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId}; +use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId, WarpMode}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, StackTarget, execute}; +use crate::filter_support::set; + /// A sphere project with its default layer selected fn session() -> Session { Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap() @@ -35,12 +37,12 @@ fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() { let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"})); - execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap(); + set(&mut s, swapped, json!({"blend": "Multiply", "opacity": 0.4, "visible": false})); - execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap(); + set(&mut s, swapped, json!({"filter": "blur", "radius": 5.0})); let blur = effect(&s, swapped); - assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius, .. }) if radius == 5.0), "{:?}", blur.kind); assert_eq!(blur.name, "Blur", "a default name follows the new filter"); assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false)); assert_eq!(content_order(&s), vec![below, swapped, above]); @@ -51,21 +53,114 @@ fn swapping_a_filter_keeps_a_name_the_user_chose() { let mut s = session(); let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"})); - execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap(); + set(&mut s, id, json!({"filter": "threshold"})); assert_eq!(effect(&s, id).name, "Flip"); } +#[test] +fn swapping_to_the_former_directional_warp_id_sets_directional_mode() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + set(&mut s, id, json!({"filter": "warpDirectional"})); + + let swapped = effect(&s, id).kind; + assert!(matches!(swapped, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Directional), "{swapped:?}"); +} + +#[test] +fn naming_the_former_directional_warp_id_on_a_warp_sets_directional_mode() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "warp", "target": "content", "seed": 7})); + + set(&mut s, id, json!({"filter": "warpDirectional"})); + + let edited = effect(&s, id).kind; + assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Directional && warp.seed == 7), "{edited:?}"); +} + +#[test] +fn a_warp_mode_given_with_the_former_directional_warp_id_wins() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "warp", "target": "content"})); + + set(&mut s, id, json!({"filter": "warpDirectional", "warpMode": "warp"})); + + let edited = effect(&s, id).kind; + assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Warp), "{edited:?}"); +} + +/// A content warp effect saved before the warp modes, as `filter` +fn saved_warp(s: &mut Session, filter: Filter) -> LayerId { + let id = add(s, "effect.add.filter", json!({"filter": "warp", "target": "content"})); + s.doc.project.effect_mut(id).unwrap().kind = EffectKind::Filter(filter); + id +} + +#[test] +fn asking_a_saved_warp_for_another_mode_replaces_it_with_a_warp_in_that_mode() { + let mut s = session(); + let warp = saved_warp(&mut s, Filter::Warp { intensity: 8.0, scale: 4.0, seed: 1, divider: 1 }); + let directional = saved_warp(&mut s, Filter::DirectionalWarp { intensity: 8.0, angle: 0.0, scale: 4.0, seed: 1, divider: 1 }); + + set(&mut s, warp, json!({"filter": "warpDirectional", "angle": 90.0})); + set(&mut s, directional, json!({"filter": "warp", "warpMode": "multiDirectional"})); + + let edited = effect(&s, warp).kind; + assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Directional && warp.angle == 90.0), "{edited:?}"); + let edited = effect(&s, directional).kind; + assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::MultiDirectional), "{edited:?}"); +} + +#[test] +fn editing_a_saved_warp_in_its_own_mode_keeps_it() { + let mut s = session(); + let warp = saved_warp(&mut s, Filter::Warp { intensity: 8.0, scale: 4.0, seed: 1, divider: 1 }); + let directional = saved_warp(&mut s, Filter::DirectionalWarp { intensity: 8.0, angle: 0.0, scale: 4.0, seed: 1, divider: 1 }); + + set(&mut s, warp, json!({"filter": "warp", "warpMode": "warp", "seed": 3})); + set(&mut s, directional, json!({"filter": "warpDirectional", "angle": 45.0})); + + assert_eq!(effect(&s, warp).kind, EffectKind::Filter(Filter::Warp { intensity: 8.0, scale: 4.0, seed: 3, divider: 1 })); + assert_eq!(effect(&s, directional).kind, EffectKind::Filter(Filter::DirectionalWarp { intensity: 8.0, angle: 45.0, scale: 4.0, seed: 1, divider: 1 })); +} + +#[test] +fn swapping_to_a_gradient_given_colors_ramps_evenly_through_them() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + set(&mut s, id, json!({"filter": "gradientMap", "colors": [[0, 0, 0], [1, 1, 1]]})); + + let EffectKind::Filter(gradient) = effect(&s, id).kind else { panic!("still a filter") }; + let halfway = gradient.ramp_at(0.5).unwrap(); + assert!((halfway[0] - 0.5).abs() < 1e-3, "black to white is mid gray halfway: {halfway:?}"); +} + +/// A swap to a gradient given five colors and their places ramps through all five, not the library's three +#[test] +fn swapping_to_a_gradient_given_colors_and_places_uses_every_color() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let colors = [[0.0; 3], [0.25; 3], [0.5; 3], [0.75; 3], [1.0; 3]]; + + set(&mut s, id, json!({"filter": "gradientMap", "colors": colors, "positions": [0.0, 0.1, 0.2, 0.3, 1.0]})); + + let EffectKind::Filter(gradient) = effect(&s, id).kind else { panic!("still a filter") }; + assert_eq!(gradient.ramp_colors(), colors); +} + #[test] fn one_undo_restores_the_old_filter() { let mut s = session(); let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3})); - execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap(); + set(&mut s, id, json!({"filter": "sharpen"})); execute(&mut s, "edit.undo", &Value::Null).unwrap(); let restored = effect(&s, id); - assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind); + assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level, .. }) if level == 0.3), "{:?}", restored.kind); assert_eq!(restored.name, "Threshold"); } @@ -74,7 +169,7 @@ fn a_mask_refuses_a_content_only_filter() { let mut s = session(); let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); - let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err(); + let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "normalInvert"})).unwrap_err(); assert!(err.to_string().contains("not on masks"), "{err}"); assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); @@ -86,9 +181,9 @@ fn a_mask_filter_swaps_in_place_on_the_mask() { let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); let above = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); - execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4})).unwrap(); + set(&mut s, swapped, json!({"blend": "Multiply", "opacity": 0.4})); - execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap(); + set(&mut s, swapped, json!({"filter": "blur"})); let blur = effect(&s, swapped); assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind); @@ -103,11 +198,11 @@ fn naming_the_current_filter_edits_it_in_place() { let mut s = session(); let id = add(&mut s, "effect.add.filter", json!({"filter": "blur", "target": "content", "radius": 5.0})); - execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur", "radius": 9.0})).unwrap(); - execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).unwrap(); + set(&mut s, id, json!({"filter": "blur", "radius": 9.0})); + set(&mut s, id, json!({"filter": "blur"})); let blur = effect(&s, id); - assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius, .. }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind); } #[test] @@ -115,7 +210,7 @@ fn a_name_given_with_the_swap_wins() { let mut s = session(); let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); - execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold", "name": "Edges"})).unwrap(); + set(&mut s, id, json!({"filter": "threshold", "name": "Edges"})); let swapped = effect(&s, id); assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind); @@ -126,11 +221,11 @@ fn a_name_given_with_the_swap_wins() { fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { let mut s = session(); let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); - execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap(); + set(&mut s, id, json!({"blend": "Multiply", "opacity": 0.4, "name": "Flip"})); let before = effect(&s, id); for refused in [ - json!({"effect": id.0, "filter": "grayscale"}), + json!({"effect": id.0, "filter": "normalInvert"}), json!({"effect": id.0, "filter": "nope"}), json!({"effect": id.0, "filter": "levels"}), json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}), @@ -153,6 +248,7 @@ fn only_filter_effects_swap_and_only_to_filters() { assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect"); assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "nope"})).is_err(), "an unknown filter on levels"); assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err()); assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert))); } @@ -170,3 +266,31 @@ fn invalid_swap_parameters_report_effect_set_and_preserve_history() { assert_eq!(effect(&s, id), before); assert_eq!(s.history_labels(), history); } + +#[test] +fn a_mask_takes_grayscale_conversion() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + + set(&mut s, id, json!({"filter": "grayscale"})); + + let swapped = effect(&s, id); + assert!(matches!(swapped.kind, EffectKind::Filter(Filter::GrayscaleConversion(_))), "{:?}", swapped.kind); + assert_eq!(swapped.name, "Grayscale Conversion"); +} + +#[test] +fn filters_carry_the_workflows_names_and_former_names_still_follow_a_swap() { + let mut s = session(); + let slope = add(&mut s, "effect.add.filter", json!({"filter": "slopeBlur", "target": "content"})); + assert_eq!(effect(&s, slope).name, "Blur Slope"); + let names: Vec = execute(&mut s, "filter.list", &Value::Null).unwrap().as_array().unwrap().iter().map(|def| def["label"].clone()).collect(); + for name in ["Contrast Luminosity", "Blur Slope", "Highpass", "Grayscale Conversion"] { + assert!(names.contains(&json!(name)), "{name} in {names:?}"); + } + + // A project saved before the rename holds the former name: a swap still renames it, and the former name still finds the filter + let old = add(&mut s, "effect.add.filter", json!({"filter": "Slope Blur", "target": "content", "name": "Slope Blur"})); + set(&mut s, old, json!({"filter": "blur"})); + assert_eq!(effect(&s, old).name, "Blur"); +} diff --git a/crates/engine/tests/it/filter_transform.rs b/crates/engine/tests/it/filter_transform.rs new file mode 100644 index 00000000..704c2c87 --- /dev/null +++ b/crates/engine/tests/it/filter_transform.rs @@ -0,0 +1,78 @@ +//! The Transform filter: each UV tile's content scaled, turned, moved and flipped, repeating round the tile or empty past it + +use serde_json::json; +use texturecraft_engine::core::{EffectKind, Filter, FlipMode, LayerId, RepeatMode, TileTransform}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, refused, roughness, session, set}; + +fn transform_of(s: &Session, effect: LayerId) -> TileTransform { + match &s.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Filter(Filter::Transform(transform)) => *transform, + other => panic!("not a transform: {other:?}"), + } +} + +/// A new Transform changes nothing; Offset moves the content round the tile, Repeat mode None leaves empty past it, Flip mode turns it over +#[test] +fn transform_moves_scales_and_flips_each_tile() { + let mut s = session(); + let row = SIZE / 2; + let empty = roughness(&mut s, (8, row)); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); + let before: Vec = (0..SIZE).map(|x| roughness(&mut s, (x, row))).collect(); + let was = |x: u32| before[(x % SIZE) as usize]; + + let effect = add_filter(&mut s, json!({"filter": "transform"})); + assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Transform"); + + for x in [20, 64, 100] { + assert!((roughness(&mut s, (x, row)) - was(x)).abs() < 1e-4, "a new Transform changes nothing at {x}"); + } + + // A quarter tile on: each texel reads 32 texels further right, the last ones round from the left + set(&mut s, effect, json!({"offset": [0.25, 0.0]})); + for x in [20, 50, 110] { + assert!((roughness(&mut s, (x, row)) - was(x + SIZE / 4)).abs() < 2e-3, "offset at {x}"); + } + + set(&mut s, effect, json!({"offset": 0.0, "flipMode": "horizontally"})); + assert!((roughness(&mut s, (20, row)) - was(SIZE - 1 - 20)).abs() < 2e-3, "flipped, the left reads the right"); + + // Twice across about the centre: the centre stays; without repeat the edges read empty (the layer's content is clear there) + set(&mut s, effect, json!({"flipMode": "none", "scaling": [2.0, 2.0], "repeatMode": "none"})); + assert!((roughness(&mut s, (SIZE / 2, row)) - was(SIZE / 2)).abs() < 2e-2, "the centre stays"); + assert!((roughness(&mut s, (8, row)) - empty).abs() < 1e-4, "past the content reads empty"); + + // Repeating, texel 8 reads 2 · 8.5 / 128 − 0.5 of a tile on: between texels 80 and 81 + set(&mut s, effect, json!({"repeatMode": "horizontallyAndVertically"})); + assert!((roughness(&mut s, (8, row)) - (was(80) + was(81)) / 2.0).abs() < 2e-3, "the tile comes round again"); + + let edited = transform_of(&s, effect); + assert_eq!((edited.repeat, edited.flip, edited.scaling), (RepeatMode::HorizontallyAndVertically, FlipMode::None, [2.0, 2.0])); + + set(&mut s, effect, json!({"rotation": -30.0, "tileSafeRotation": false})); + let turned = transform_of(&s, effect); + assert_eq!((turned.rotation, turned.tile_safe), (330.0, false), "a turn reads 0..360"); + + refused( + &mut s, + effect, + &[ + json!({"repeatMode": "sideways"}), + json!({"flipMode": "diagonal"}), + json!({"scaling": [1.0]}), + json!({"offset": "far"}), + json!({"tileSafeRotation": 1}), + ], + ); + assert_eq!(transform_of(&s, effect), turned, "a refused value changes nothing"); + + set(&mut s, effect, json!({"scaling": [1e9, -5.0]})); + assert_eq!(transform_of(&s, effect).scaling, [TileTransform::SCALING.1, TileTransform::SCALING.0], "scaling clamps"); + + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY); +} diff --git a/crates/engine/tests/it/folder_contents.rs b/crates/engine/tests/it/folder_contents.rs index 11ca86e9..b517deea 100644 --- a/crates/engine/tests/it/folder_contents.rs +++ b/crates/engine/tests/it/folder_contents.rs @@ -139,6 +139,7 @@ fn fill_seeds(s: &Session, id: LayerId) -> (u32, u32, u32) { }; let warp = layer.mask.as_ref().unwrap().effects.iter().find_map(|effect| match effect.kind { EffectKind::Filter(Filter::Warp { seed, .. }) => Some(seed), + EffectKind::Filter(Filter::SourceWarp(warp)) => Some(warp.seed), _ => None, }); (pattern(Channel::BaseColor), pattern(Channel::Roughness), warp.unwrap()) diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f45226e8..c38e850b 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -21,8 +21,17 @@ mod fill_patterns; mod fill_projections; mod fill_sampling; mod fill_whole_material; +mod filter_card; +mod filter_colour; +mod filter_gradient; +mod filter_inputs; +mod filter_light; +mod filter_shape; +mod filter_simple; +mod filter_stylize; mod filter_support; mod filter_swap; +mod filter_transform; mod filters; mod folder_contents; mod frame_selection; diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 26fcb753..d423c852 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -63,7 +63,6 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { "matFinishGrind", "highPass", "edgeDetect", - "warpDirectional", "grayscale", "normalInvert", "bevel", @@ -80,47 +79,36 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { let fid = f["id"].as_str().unwrap(); let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect"); let (owner, e) = s.doc.project.effect(eid).unwrap(); - assert_eq!(owner, layer); assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry"); assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid)); - execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); } - // A gradient map recolors the content; effect.set edits it and inspect shows it + // A gradient map recolors the content; effect.set edits it and inspect shows it. let gm = id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect"); let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}"); - execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap(); - assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95); assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err()); - let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); - assert!(inspect.contains("GradientMap"), "inspect shows filter parameters"); - execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap(); - // Posterize on the mask; its steps are clamped + // Posterize on the mask; its steps are clamped. let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect"); execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap(); - assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post))); - assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0)); - - // Material finishes fill the content's roughness and height + assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels, .. }) if levels == 64.0)); + // Material finishes fill the content's roughness and height. let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect"); - assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin)); assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height))); assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err()); - - // A directional blur, slope blur and warp composite without trouble on a sphere + // A directional blur, slope blur and warp composite without trouble on a sphere. for (fid, extra) in [ ("blurDirectional", json!({"radius": 40, "angle": 45})), - ("slopeBlur", json!({"radius": 30})), + ("slopeBlur", json!({"intensity": 0.5, "divider": 1})), ("warp", json!({"intensity": 50})), ("warpDirectional", json!({"intensity": 50, "angle": 30})), ("highPass", json!({"radius": 20})), diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs index 8889b7ae..5cb945c0 100644 --- a/crates/engine/tests/it/resources_used.rs +++ b/crates/engine/tests/it/resources_used.rs @@ -1,4 +1,5 @@ //! The images a project reads beyond fill sources: a colour selection's ID map, the mask brush and its paths +//! The images a project reads beyond fill sources: a colour selection's ID map, a filter's image input, the mask brush and its paths use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, LayerId}; @@ -27,11 +28,23 @@ fn selecting_layer(session: &mut Session, id_map: &str) -> LayerId { layer } +/// [`selecting_layer`] with a Bevel Smooth that reads `input` as its Distance Map +fn layer_reading(session: &mut Session, id_map: &str, input: &str) -> LayerId { + let layer = selecting_layer(session, id_map); + let filter = execute(session, "effect.add.filter", &json!({"filter": "bevelSmooth", "target": "content"})).unwrap()["effect"].as_u64().unwrap(); + execute(session, "layer.fill.set", &json!({"effect": filter, "input": "distanceMap", "image": input})).unwrap(); + layer +} + #[test] fn removing_unused_resources_keeps_the_images_a_selection_the_mask_brush_and_a_path_read() { +fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mask_brush_and_a_path_read() { let mut session = session(); let [id_map, path, brush, unused] = ["id.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap()); let layer = selecting_layer(&mut session, &id_map); + let [id_map, input, path, brush, unused] = + ["id.png", "input.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap()); + let layer = layer_reading(&mut session, &id_map, &input); // A path on the mask is painted with one image, then the brush moves on to another execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); @@ -46,15 +59,19 @@ fn removing_unused_resources_keeps_the_images_a_selection_the_mask_brush_and_a_p #[test] fn a_smart_material_carries_the_image_its_selection_reads() { +fn a_smart_material_carries_the_images_its_selection_and_filter_input_read() { let mut session = session(); let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); let layer = selecting_layer(&mut session, &id_map); + let input = session.import_resource_bytes("input.png", white_png()).unwrap(); + let layer = layer_reading(&mut session, &id_map, &input); let bytes = session.smart_material_bytes(layer, "Parts").unwrap(); let mut other = self::session(); other.add_smart_material_bytes(&bytes).unwrap(); assert!(other.doc.resources.contains_key(&id_map), "the ID map comes along"); + assert!(other.doc.resources.contains_key(&input), "the filter input comes along"); } #[test] diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index b5ae16f0..2802448b 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -268,6 +268,8 @@ fn panic_hunt() { s.update(); } } + + hunt_filters(&hostile); } /// A 4 × 4 gray PNG, the image the hunted decals project @@ -278,8 +280,10 @@ fn gray_png() -> Vec { } /// Frame edits and frame and Fill section resets on the fills they act on (a planar, a warp and a decal mask) meet hostile values without panicking; a refused edit changes nothing and adds no undo step +/// Frame edits, frame and Fill section resets and Transform filter settings on the fills they act on (a planar, a warp, a decal mask and a Transform filter) meet hostile values without panicking; a refused edit changes nothing and adds no undo step #[test] fn panic_hunt_frames() { +fn panic_hunt_frames_and_transforms() { let mut s = session(); let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); let planar = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); @@ -288,6 +292,7 @@ fn panic_hunt_frames() { execute(&mut s, "layer.fill.projection", &json!({"layer": warp, "projection": "warp"})).unwrap(); let decal = execute(&mut s, "layer.add.decal", &json!({"image": image, "channel": "mask", "position": [0, 0, 1], "normal": [0, 0, 1]})).unwrap(); let mask_effect = decal["maskEffect"].as_u64().unwrap(); + let transform = execute(&mut s, "effect.add.filter", &json!({"filter": "transform", "target": "content"})).unwrap()["effect"].as_u64().unwrap(); s.update(); let hostile_values = @@ -310,6 +315,15 @@ fn panic_hunt_frames() { s.update(); } } + + let transform_keys = ["repeatMode", "flipMode", "scaling", "offset", "rotation", "tileSafeRotation"]; + for key in transform_keys { + for value in &hostile_values { + let mut params = json!({"effect": transform}); + params[key] = value.clone(); + hunt_refused_changes_nothing(&mut s, "effect.set", ¶ms); + } + } } /// Run `command` with `params` and render; refused, it must leave the project and the undo history as they were @@ -321,6 +335,166 @@ fn hunt_refused_changes_nothing(s: &mut Session, command: &str, params: &Value) s.update(); } +/// The number parameters library filters read, all set at once to one hostile value +const FILTER_NUMBER_KEYS: &[&str] = &[ + "radius", + "intensity", + "amount", + "level", + "hue", + "saturation", + "lightness", + "contrast", + "luminosity", + "levels", + "min", + "max", + "position", + "range", + "offset", + "multiply", + "scale", + "angle", + "width", + "distance", + "smoothing", + "size", + "spread", + "opacity", + "blur", + "balance", + "quality", + "sourceBlur", + "sourceBalance", + "sourceContrast", + "sourceTiling", + "tolerance", + "softness", + "light", + "ambient", + "occlusion", + "azimuth", + "elevation", + "horizontalRotation", + "verticalRotation", + "exposure", + "heightIntensity", + "ambientOcclusion", + "specularOcclusion", + "pixelsAmount", + "curveOffset", + "curveShape", + "maskThreshold", + "distanceMapMultiplier", + "threshold", + "axisXOffset", + "axisYOffset", + "surfaceSize", + "heightDepth", + "normalIntensity", + "chroma", + "luma", + "red", + "green", + "blue", + "alpha", + "tensorSmoothness", + "anisotropy", + "sharpness", + "smoothness", + "rotation", + "scaling", + "diffuseCavity", + "specularAo", + "specularCavity", + "cavitySmoothness", + "edgesIntensity", + "edgesSmoothness", + "dielectricReflectance", + "heightToNormal", +]; + +/// The objects library filters read numbers from (Baked Lighting Stylized's two lights) +const FILTER_LIGHT_KEYS: &[&str] = &["light1", "light2"]; + +/// Every filter number parameter set to `number`, with seeds, switches and choices at their ends +fn filter_extreme(number: f64) -> Value { + let mut params = json!({"seed": u64::MAX, "wrap": true, "applyToAlpha": true, "invert": true, "directions": 4, "divider": 1000}); + for key in FILTER_NUMBER_KEYS { + params[*key] = json!(number); + } + for key in FILTER_LIGHT_KEYS { + params[*key] = json!({"azimuth": number, "elevation": number, "intensity": number}); + } + params +} + +/// Every library filter added on the content and on a mask with `hostile` and extreme parameters, edited to extremes, and rendered; then swapped to the same way +fn hunt_filters(hostile: &[Value]) { + let extremes: Vec = [3.0e38, -3.0e38, 0.0].into_iter().map(filter_extreme).collect(); + + for def in texturecraft_engine::filter_lib::FILTERS { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1], "roughness": 0.4})).unwrap(); + for target in ["content", "mask"] { + if target == "mask" { + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + } + + for given in hostile.iter().chain(&extremes) { + let mut params = if given.is_object() { given.clone() } else { json!({}) }; + params["filter"] = json!(def.id); + params["target"] = json!(target); + let added = execute(&mut s, "effect.add.filter", ¶ms).ok().and_then(|reply| reply["effect"].as_u64()); + s.update(); + + // Extreme values are clamped, not refused, so every filter meets them on the content + if target == "content" && extremes.contains(given) { + assert!(added.is_some(), "{} takes extreme values: {params}", def.id); + } + if let Some(effect) = added { + for edit in &extremes { + let mut edit = edit.clone(); + edit["effect"] = json!(effect); + // Each accepted value reaches the compositor before the next edit replaces it + if execute(&mut s, "effect.set", &edit).is_ok() { + s.update(); + } + } + } + } + } + } + + hunt_filter_swaps(hostile, &extremes); +} + +/// An empty filter effect on the content and on a mask swapped through `effect.set` to every library filter with each of `hostile` and `extremes`, and rendered +fn hunt_filter_swaps(hostile: &[Value], extremes: &[Value]) { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1], "roughness": 0.4})).unwrap(); + for target in ["content", "mask"] { + if target == "mask" { + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + } + let added = execute(&mut s, "effect.add.filter", &json!({"filter": "none", "target": target})).unwrap(); + let effect = added["effect"].as_u64().unwrap(); + + for def in texturecraft_engine::filter_lib::FILTERS { + for given in hostile.iter().chain(extremes) { + let mut params = if given.is_object() { given.clone() } else { json!({}) }; + params["effect"] = json!(effect); + params["filter"] = json!(def.id); + + // Emptied first, so each swap builds the filter anew rather than editing it in place + execute(&mut s, "effect.set", &json!({"effect": effect, "filter": "none"})).unwrap(); + let _ = execute(&mut s, "effect.set", ¶ms); + s.update(); + } + } + } +} + /// A colour param is `[r, g, b]` in linear 0..1 or `"#rrggbb"` in sRGB, and the same digits differ /// between the two, so every command that takes a colour says which form is which. #[test] diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index 11635fcc..57e5f87e 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -8,6 +8,7 @@ use std::f32::consts::{PI, TAU}; use rayon::prelude::*; +use texturecraft_compose::environment_sky; use texturecraft_geom::glam::{Vec2, Vec3}; /// An equirect HDR image (linear RGB). @@ -18,86 +19,9 @@ pub struct EnvImage { pub data: Vec<[f32; 3]>, } +pub use texturecraft_compose::environment_sky::{dir_of, radiance, sh_basis, uv_of}; pub use texturecraft_core::project::ENVIRONMENTS; -pub fn dir_of(u: f32, v: f32) -> Vec3 { - let (theta, phi) = (v * PI, u * TAU); - Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin()) -} - -pub fn uv_of(d: Vec3) -> Vec2 { - let phi = d.z.atan2(d.x); - Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI) -} - -/// A soft rectangular light: azimuth/elevation center (degrees), half sizes (degrees). -struct SoftBox { - az: f32, - el: f32, - hw: f32, - hh: f32, - color: Vec3, -} - -impl SoftBox { - fn eval(&self, d: Vec3) -> Vec3 { - let el = d.y.clamp(-1.0, 1.0).asin().to_degrees(); - let az = d.z.atan2(d.x).to_degrees(); - let daz = ((az - self.az + 540.0).rem_euclid(360.0)) - 180.0; - let (x, y) = (daz.abs() / self.hw, (el - self.el).abs() / self.hh); - let e = |t: f32| 1.0 - smooth((t - 0.8) / 0.4); - self.color * e(x) * e(y) - } -} - -fn smooth(t: f32) -> f32 { - let t = t.clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 { - if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(0.6)) } else { horizon.lerp(ground, (-d.y).powf(0.25)) } -} - -fn radiance(name: &str, d: Vec3) -> Vec3 { - match name { - "Studio Contrast" => { - let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01)); - base + SoftBox { az: 35.0, el: 30.0, hw: 22.0, hh: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(d) - + SoftBox { az: -150.0, el: 40.0, hw: 6.0, hh: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(d) - } - "Overcast" => { - let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15)); - base + SoftBox { az: 60.0, el: 55.0, hw: 40.0, hh: 25.0, color: Vec3::splat(0.6) }.eval(d) - } - "Sunset" => { - let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05)); - let sun_dir = dir_of(0.12, 0.47); - let sun = smooth((d.dot(sun_dir) - 0.9985) / 0.0012) * 120.0; - base + Vec3::new(1.0, 0.6, 0.3) * sun - } - "Warehouse" => { - let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06)); - for k in 0..6 { - c += SoftBox { az: -150.0 + k as f32 * 60.0, el: 50.0, hw: 6.0, hh: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }.eval(d); - } - c + SoftBox { az: 90.0, el: 5.0, hw: 30.0, hh: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(d) - } - "Night" => { - let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005)); - base + SoftBox { az: 20.0, el: 15.0, hw: 10.0, hh: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(d) - + SoftBox { az: -110.0, el: 10.0, hw: 12.0, hh: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(d) - } - // "Studio Soft" (default) - _ => { - let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07)); - base + SoftBox { az: 40.0, el: 35.0, hw: 28.0, hh: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(d) - + SoftBox { az: -125.0, el: 20.0, hw: 35.0, hh: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(d) - + SoftBox { az: 175.0, el: 55.0, hw: 8.0, hh: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(d) - } - } -} - /// Render a built-in environment (unknown names give the default studio). pub fn environment(name: &str, width: u32) -> EnvImage { let w = width.clamp(16, 4096); @@ -132,16 +56,8 @@ impl EnvImage { /// Box-downsample by 2. pub fn half(&self) -> EnvImage { - let (w, h) = ((self.width / 2).max(1), (self.height / 2).max(1)); - let mut data = vec![[0.0f32; 3]; (w * h) as usize]; - data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| { - for (x, px) in row.iter_mut().enumerate() { - let (sx, sy) = (x as i64 * 2, y as i64 * 2); - let s = (self.get(sx, sy) + self.get(sx + 1, sy) + self.get(sx, sy + 1) + self.get(sx + 1, sy + 1)) * 0.25; - *px = s.to_array(); - } - }); - EnvImage { width: w, height: h, data } + let (width, height, data) = environment_sky::half(self.width, self.height, |x, y| self.get(x as i64, y as i64)); + EnvImage { width, height, data: data.iter().map(Vec3::to_array).collect() } } /// An imported equirect image (`rgba` row-major, top row first, sRGB-encoded when `srgb`) as @@ -149,23 +65,12 @@ impl EnvImage { /// range, and images larger than [`MAX_IMPORT_WIDTH`] are box-downsampled. None when the /// pixel count does not match the size. pub fn from_rgba(width: u32, height: u32, rgba: &[[f32; 4]], srgb: bool) -> Option { - Self::from_pixels(width, height, rgba, srgb) - } - - /// An imported linear RGB equirect image, with the same validation and size limits as [Self::from_rgba]. - pub fn from_linear_rgb(width: u32, height: u32, rgb: &[[f32; 3]]) -> Option { - Self::from_pixels(width, height, rgb, false) - } - - fn from_pixels(width: u32, height: u32, pixels: &[[f32; COMPONENTS]], srgb: bool) -> Option { - if width == 0 || height == 0 || pixels.len() as u64 != width as u64 * height as u64 { + if width == 0 || height == 0 || rgba.len() as u64 != width as u64 * height as u64 { return None; } - let lin = |v: f32| { - let v = if v.is_finite() { v.clamp(0.0, 65_000.0) } else { 0.0 }; - if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v } - }; let data = pixels.par_iter().map(|p| [lin(p[0]), lin(p[1]), lin(p[2])]).collect(); + let linear = |v: f32| environment_sky::environment_linear(v, srgb); + let data = rgba.par_iter().map(|p| [linear(p[0]), linear(p[1]), linear(p[2])]).collect(); let mut img = EnvImage { width, height, data }; while img.width > MAX_IMPORT_WIDTH || img.height > MAX_IMPORT_WIDTH { img = img.half(); @@ -247,48 +152,9 @@ pub fn prefilter(env: &EnvImage, levels: u32) -> Vec { out } -/// Diffuse irradiance as 9 SH coefficients (already convolved with the cosine lobe and divided -/// by π, so `Σ c·Y(n)` times albedo is the diffuse radiance). +/// Diffuse irradiance as 9 SH coefficients, convolved with the cosine lobe and divided by π, so `Σ c·Y(n)` times albedo is the diffuse radiance pub fn sh9(env: &EnvImage) -> [[f32; 3]; 9] { - let mut src = env.clone(); - while src.width > 128 { - src = src.half(); - } - let (w, h) = (src.width, src.height); - let mut c = [Vec3::ZERO; 9]; - for y in 0..h { - let theta = PI * (y as f32 + 0.5) / h as f32; - let dw = (TAU / w as f32) * (PI / h as f32) * theta.sin(); - for x in 0..w { - let d = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32); - // No firefly clamp: the projection integrates, so a bright sun lights diffuse fully. - let l = src.get(x as i64, y as i64) * dw; - for (k, ylm) in sh_basis(d).iter().enumerate() { - c[k] += l * *ylm; - } - } - } - let a = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0]; - let mut out = [[0.0; 3]; 9]; - for k in 0..9 { - out[k] = (c[k] * a[k] / PI).to_array(); - } - out -} - -pub fn sh_basis(d: Vec3) -> [f32; 9] { - let (x, y, z) = (d.x, d.y, d.z); - [ - 0.282_095, - 0.488_603 * y, - 0.488_603 * z, - 0.488_603 * x, - 1.092_548 * x * y, - 1.092_548 * y * z, - 0.315_392 * (3.0 * z * z - 1.0), - 1.092_548 * x * z, - 0.546_274 * (x * x - y * y), - ] + environment_sky::sh9_averaged(env.width, env.height, |x, y| env.get(x as i64, y as i64)) } #[cfg(test)] diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 5e0561af..481cb6d4 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -1319,7 +1319,7 @@ impl Renderer { let img = match imported { Some(img) => img, None if !self.env_is_imported && self.env_name == name => return, - None => ibl::environment(name, 512), + None => ibl::environment(name, texturecraft_compose::environment_sky::VIEWPORT_WIDTH), }; let levels = ibl::prefilter(&img, ENV_LEVELS); diff --git a/crates/ui-egui/src/anchor_properties.rs b/crates/ui-egui/src/anchor_properties.rs index 360bef5b..e3fb0313 100644 --- a/crates/ui-egui/src/anchor_properties.rs +++ b/crates/ui-egui/src/anchor_properties.rs @@ -78,3 +78,25 @@ fn reader_glyph(kind: &EffectKind) -> &'static str { EffectKind::Fill { .. } | EffectKind::Material(_) => ic::PAINT_BUCKET, } } + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::execute; + + use super::*; + + #[test] + fn a_reference_shows_the_icon_of_what_reads_the_anchor() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"roughness": 0.5})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &Value::Null).unwrap()["effect"].as_u64().unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let filter = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "bevelSmooth"})).unwrap()["effect"].clone(); + execute(&mut session, "layer.fill.set", &json!({"effect": filter, "input": "distanceMap", "anchor": anchor})).unwrap(); + + let glyphs: Vec<&str> = references(&session.doc.project, LayerId(anchor)).iter().map(|reference| reference.glyph).collect(); + assert_eq!(glyphs, [ic::FUNNEL], "a filter reading the anchor shows the filter icon, not a fill's"); + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 0dc5bc7f..5248b0fb 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -7,8 +7,8 @@ use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Filter, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, + BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, }; -use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; @@ -24,11 +24,6 @@ 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}; -const FILTER_SWATCH_WIDTH: f32 = 36.0; -const FILTER_HINT_SIZE: f32 = 10.5; -/// The most colors `effect.set {colors}` takes for a gradient map -const MAX_GRADIENT_STOPS: usize = 16; - const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), Color32::from_rgb(0xd0, 0x80, 0x30), @@ -3029,28 +3024,6 @@ fn axis_combo(ui: &mut Ui, axis: u8) -> Option { picked } -/// Swatches for gradient map stops (dark to light) with Add color and Remove last; true when -/// they changed. -fn gradient_stops(ui: &mut Ui, salt: &str, stops: &mut Vec<[f32; 3]>) -> bool { - let mut changed = false; - ui.horizontal_wrapped(|ui| { - for (i, stop) in stops.iter_mut().enumerate() { - changed |= color_swatch(ui, &format!("{salt}_{i}"), stop, FILTER_SWATCH_WIDTH); - } - }); - ui.horizontal(|ui| { - if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { - stops.push(stops.last().copied().unwrap_or([1.0; 3])); - changed = true; - } - if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { - stops.pop(); - changed = true; - } - }); - changed -} - /// The properties of effect `effect_id` of `layer`: each kind's own settings. fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { let tokens = Tokens::get(ui.ctx()); @@ -3166,6 +3139,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe } }), EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)), + 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 } => { let settings = crate::compare_settings::CompareSettings { @@ -3182,85 +3156,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe } } -/// The filter slot and the parameters of filter effect `id` -fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { - let tk = Tokens::get(ui.ctx()); - let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { - let mut params = json!({ "effect": id, "merge": merge }); - params[key] = value; - app.run("effect.set", params); - }; - crate::filter_slot::show(app, ui, id, filter); - - if let Filter::Hsl { hue, .. } = filter { - let mut degrees = hue * 360.0; - if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut degrees, -180.0..=180.0, 0) { - set(app, "hue", json!(degrees / 360.0), merge); - } - } - - for (key, label, mut value, min, max) in scalar_params(filter) { - let decimals = if matches!(key, "seed" | "levels") { - 0 - } else if max - min > 10.0 { - 1 - } else { - 2 - }; - if let Some(merge) = slider_edit(ui, tr(label), &mut value, min..=max, decimals) { - set(app, key, json!(value), merge); - } - } - - match filter { - Filter::ColorBalance { shadows, midtones, highlights } => { - for (key, label, rgb) in [("shadows", tr("Shadows"), shadows), ("midtones", tr("Midtones"), midtones), ("highlights", tr("Highlights"), highlights)] - { - ui.label(RichText::new(label).strong()); - let mut balance = *rgb; - let mut edit = None; - for (component, name) in balance.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { - edit = edit.or(slider_edit(ui, name, component, -1.0..=1.0, 2)); - } - if let Some(merge) = edit { - set(app, key, json!(balance), merge); - } - } - } - Filter::ReplaceColor { from, to, .. } => { - for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { - let mut color = *rgb; - ui.horizontal(|ui| { - if color_swatch(ui, &format!("replace_{key}_{id}"), &mut color, FILTER_SWATCH_WIDTH) { - set(app, key, json!(color), false); - } - ui.label(label); - }); - } - ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); - } - Filter::GradientMap { colors } => { - let mut stops = colors.clone(); - if gradient_stops(ui, &format!("gradient_{id}"), &mut stops) { - set(app, "colors", json!(stops), false); - } - ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); - } - Filter::Warp { .. } - | Filter::DirectionalBlur { .. } - | Filter::SlopeBlur { .. } - | Filter::DirectionalWarp { .. } - | Filter::HighPass { .. } - | Filter::EdgeDetect { .. } - | Filter::Bevel { .. } - | Filter::Mosaic { .. } - | Filter::Glow { .. } => { - ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); - } - _ => {} - } -} - #[cfg(test)] mod layer_layout_tests { use super::*; diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index 7efd7a14..24a62cd4 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -428,6 +428,7 @@ fn procedural_rows( // A grayscale's card (a mask fill's, a filter input's) shows its Balance and Seed with Scale and Contrast; a material channel's keeps them in Attributes let gray = matches!(slot_of, SourceSlot::Grayscale); + let gray = matches!(slot_of, SourceSlot::Grayscale | SourceSlot::Input(_)); if gray { edit = edit.or(balance_and_seed(sheet, &mut edited)); } diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs index 5a9fa0d7..2f7d7358 100644 --- a/crates/ui-egui/src/fill_pictures.rs +++ b/crates/ui-egui/src/fill_pictures.rs @@ -370,6 +370,41 @@ mod tests { use super::*; + /// A repeating map far denser than the tiles drawn (Scaling 64 turned 45°) still fills the whole window, its far corner too + #[test] + fn a_dense_repeating_preview_leaves_no_bare_field() { + use texturecraft_engine::core::TileTransform; + + let tokens = Tokens::for_brightness(crate::theme::Brightness::MediumDark); + let transform = TileTransform { scaling: [64.0, 64.0], rotation: 45.0, ..TileTransform::LIBRARY }; + let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 100.0)); + let ctx = egui::Context::default(); + let output = ctx.run_ui(egui::RawInput::default(), |ui| lattice_preview(ui.painter(), rect, transform.affine(), true, &tokens)); + + // Whether a filled shape other than the bare field covers `point` + let covered = |point: Pos2| { + output.shapes.iter().any(|clipped| match &clipped.shape { + Shape::Rect(shape) => shape.fill != tokens.field && shape.fill != Color32::TRANSPARENT && shape.rect.contains(point), + Shape::Path(path) if path.fill != Color32::TRANSPARENT => { + let corners = &path.points; + let side = |index: usize| { + let (from, to) = (corners[index], corners[(index + 1) % corners.len()]); + (to - from).x * (point - from).y - (to - from).y * (point - from).x + }; + let sides: Vec = (0..corners.len()).map(side).collect(); + sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) + } + _ => false, + }) + }; + for corner in [pos2(1.0, 1.0), pos2(99.0, 1.0), pos2(1.0, 99.0), pos2(99.0, 99.0)] { + assert!(covered(corner), "the preview fills {corner:?}"); + } + + // No renderer takes the uploads here + output.drop_without_applying_deltas(); + } + /// A hand-edited span past a full turn spaces the ring's dots as the engine spaces the copies: six copies 60° apart, none on top of another #[test] fn the_ring_spaces_its_copies_as_the_engine_does() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2e663682..d1d19dc1 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -249,6 +249,10 @@ mod tests { keys.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, label)| *label)); for filter in FILTERS { keys.extend([filter.label, filter.group]); + if let Some(about) = filter.about() { + keys.push(about.description); + keys.extend(about.tags); + } if let Ok(EffectKind::Filter(effect)) = build(filter.id, &serde_json::Value::Null) { keys.push(effect.label()); keys.extend(scalar_params(&effect).into_iter().map(|parameter| parameter.1)); diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index b8274f79..922eacd2 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -91,6 +91,8 @@ const BLACK_SWATCH: u8 = 10; /// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it pub(crate) const NEW_FILTER: &str = "hsl"; +/// The filter Add filter adds: an empty one, which changes nothing until its slot's picker swaps a filter into it +pub(crate) const NEW_FILTER: &str = texturecraft_engine::mask_cmds::EMPTY_FILTER; /// The Layers panel's top row and what its menus open pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a3671aee..11cbf1f2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -38,7 +38,9 @@ mod fill_material_panel; mod fill_panel; mod fill_pictures; mod fill_symmetry_panel; +mod filter_properties; mod filter_slot; +mod filter_transform_rows; mod folder_properties; pub mod fonts; mod frame_gizmo; diff --git a/crates/ui-egui/src/material_orb.rs b/crates/ui-egui/src/material_orb.rs index b34aa1d1..5b7e4a11 100644 --- a/crates/ui-egui/src/material_orb.rs +++ b/crates/ui-egui/src/material_orb.rs @@ -5,6 +5,7 @@ use egui::{Color32, ColorImage, Painter, Rect, pos2}; use rayon::prelude::*; use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{Channel, DIELECTRIC_REFLECTANCE}; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::texel::linear_to_srgb; @@ -125,6 +126,7 @@ fn shade(material: &OrbMaterial, env: &OrbEnvironment, direction: Vec3, pixel: f for (channel, value) in out.iter_mut().enumerate() { let base = sample.base[channel].clamp(0.0, 1.0); let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * metallic; + let f0 = DIELECTRIC_REFLECTANCE + (base - DIELECTRIC_REFLECTANCE) * metallic; let specular = f0 * scale + bias; *value = diffuse_light[channel] * base * (1.0 - metallic) * (1.0 - specular) + specular_light[channel] * specular + sample.emissive[channel].max(0.0); } diff --git a/crates/ui-egui/src/property_sheet/color_bar.rs b/crates/ui-egui/src/property_sheet/color_bar.rs index b9239dc0..d120ce3f 100644 --- a/crates/ui-egui/src/property_sheet/color_bar.rs +++ b/crates/ui-egui/src/property_sheet/color_bar.rs @@ -86,6 +86,17 @@ fn open_picker(ctx: &egui::Context, state_id: Id, state: &mut PickerState, linea } impl PropertySheet<'_> { + /// Opens the picker of the colour bar `bar` (its [`ColorPick::id`]) on `linear` from the next frame, as a click on the bar does + pub(crate) fn open_color_picker(&self, bar: Id, linear: [f32; 3]) { + let ctx = self.ui.ctx(); + let state_id = bar.with("picker"); + let mut state = picker_state(ctx, state_id); + if !state.open { + open_picker(ctx, &mut state, linear); + ctx.data_mut(|data| data.insert_temp(state_id, state)); + } + } + /// A uniform colour (linear): a bar across the card that opens the picker (with the project's `swatches`), and the eyedropper; `eyedropping` is the bar whose pick waits for its click pub(crate) fn color_bar(&mut self, label: &str, linear: [f32; 3], eyedropping: Option, swatches: &[[f32; 3]]) -> ColorPick { let center_y = self.take(super::ROW_HEIGHT).center().y; diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs index b4eb8182..30b16b1c 100644 --- a/crates/ui-egui/src/property_sheet/group.rs +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -20,6 +20,26 @@ pub(super) const CARD_BLEED: f32 = 6.0; /// Corner radius of a card pub(super) const CARD_RADIUS: u8 = 6; +/// From a card's top to its name's centre +const CARD_NAME_CENTER: f32 = CARD_PADDING + 6.0; + +/// Air above a sub-group's name inside a held card, and the name row under it +const INNER_CAPTION_AIR: f32 = 6.0; +const INNER_CAPTION_ROW: f32 = 22.0; + +/// From an inner caption's row top to its name's centre +const INNER_CAPTION_CENTER: f32 = 10.0; + +/// Air between an inner caption's name and its hairline, and from the hairline's end to the right edge +const INNER_RULE_AIR: f32 = 8.0; +const INNER_RULE_END: f32 = 16.0; + +/// Air above the folded row that ends a held card +const CLOSING_FOLD_AIR: f32 = 2.0; + +/// The room a rule under a card's slot takes: the hairline 1 px down, then air (the next row starts 6 under the slot) +const SLOT_RULE_ROOM: f32 = 6.0; + /// From the right edge to the centre of a band's reset button const BAND_RESET_INSET: f32 = 26.0; @@ -33,6 +53,9 @@ const BAND_PICTURE_AIR: f32 = 8.0; /// A band's reset button click square const BAND_RESET_TARGET: f32 = 20.0; +/// How far above and below a foldable card's name a click folds it +const CARD_HIT_HALF_HEIGHT: f32 = 12.0; + /// How far a title's text reaches below its centre const TITLE_HALF_LINE: f32 = 7.0; @@ -117,6 +140,53 @@ impl PropertySheet<'_> { BandResponse { open, reset: reset_clicked } } + /// A folded group inside a card: bold name, its value (dim) and a caret; returns whether it is open + pub(crate) fn card(&mut self, title: &str, foldable: Option) -> bool { + if self.held && self.card.is_some() { + return self.inner_caption(title, foldable); + } + + self.open_card(); + let id = self.named_id("card", title); + self.scope = id; + let rect = self.take(CARD_NAME_CENTER + ROW_HEIGHT / 2.0); + let center_y = rect.top() + CARD_NAME_CENTER; + let open = foldable.is_none_or(|default_open| { + let hit = Rect::from_x_y_ranges(self.left..=self.right, (center_y - CARD_HIT_HALF_HEIGHT)..=(center_y + CARD_HIT_HALF_HEIGHT)); + self.fold_toggle(id, hit, title, default_open) + }); + + let tokens = self.tokens; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + if foldable.is_some() { + self.caret(pos2(self.right - EDGE_GLYPH_INSET, center_y), open, tokens.text_dim); + } + self.drawn(center_y + TITLE_HALF_LINE); + open + } + + /// A sub-group inside the held card: its bold name on a hairline (no card in a card), a caret when it folds + fn inner_caption(&mut self, title: &str, foldable: Option) -> bool { + self.space(INNER_CAPTION_AIR); + let id = self.named_id("caption", title); + let rect = self.take(INNER_CAPTION_ROW); + let center_y = rect.top() + INNER_CAPTION_CENTER; + let open = foldable.is_none_or(|default_open| self.fold_toggle(id, Rect::from_x_y_ranges(self.left..=self.right, rect.y_range()), title, default_open)); + + let tokens = self.tokens; + let painter = self.ui.painter(); + let name = painter.text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + let rule_end = self.right - INNER_RULE_END; + if name.right() + INNER_RULE_AIR < rule_end { + painter.line_segment([pos2(name.right() + INNER_RULE_AIR, center_y), pos2(rule_end, center_y)], Stroke::new(1.0, tokens.separator)); + } + if foldable.is_some() { + self.caret(pos2(self.right - EDGE_GLYPH_INSET, center_y), open, tokens.text_dim); + } + self.drawn(center_y + TITLE_HALF_LINE); + open + } + /// A group's fold state kept under `id`, flipped by a click on `hit` (answering as `title`); returns whether it is open fn fold_toggle(&mut self, id: egui::Id, hit: Rect, title: &str, default_open: bool) -> bool { let mut open = self.ui.data(|data| data.get_temp::(id)).unwrap_or(default_open); @@ -134,12 +204,25 @@ impl PropertySheet<'_> { Rect::from_min_max(pos2(self.left - CARD_BLEED, rect.top()), pos2(self.right + CARD_BLEED, rect.bottom())) } + /// Keeps the card open now open through what follows: groups inside it become inner captions, and slots and cards join it, until [`Self::release_card`] + pub(crate) fn hold_card(&mut self) { + self.held = self.card.is_some(); + } + /// Ends [`Self::hold_card`] and closes the held card pub(crate) fn release_card(&mut self) { self.held = false; self.close_card(); } + /// A hairline across the open card under its slot row, then air before its settings + pub(crate) fn slot_rule(&mut self) { + let rect = self.take(SLOT_RULE_ROOM); + let y = rect.top() + 1.0; + self.ui.painter().line_segment([pos2(self.left, y), pos2(self.right, y)], Stroke::new(1.0, self.tokens.separator)); + self.drawn(y); + } + /// Starts a card with no name row: a slot card, whose slot is its top row; inside a held card it joins that card pub(crate) fn open_card(&mut self) { if self.held && self.card.is_some() { @@ -178,6 +261,12 @@ impl PropertySheet<'_> { open } + /// The folded row that ends a held card (its Attributes), [`CLOSING_FOLD_AIR`] under the rows before it; returns whether it is open + pub(crate) fn closing_fold(&mut self, title: &str) -> bool { + self.space(CLOSING_FOLD_AIR); + self.fold(title, None, false) + } + /// Ends the open card (not a held one: [`Self::release_card`] ends that): its face reaches [`CARD_PADDING`] below what its rows painted pub(crate) fn close_card(&mut self) { if self.held { diff --git a/crates/ui-egui/src/property_sheet/marker_drag.rs b/crates/ui-egui/src/property_sheet/marker_drag.rs new file mode 100644 index 00000000..8faaa6dc --- /dev/null +++ b/crates/ui-egui/src/property_sheet/marker_drag.rs @@ -0,0 +1,8 @@ +//! Where a gradient's dragged marker moved + +/// A marker that was dragged: which color, its new place and whether it continues the drag's undo step +pub(crate) struct MarkerDrag { + pub(crate) index: usize, + pub(crate) position: f32, + pub(crate) merge: bool, +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index fe8a47dd..fdef2d7b 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -2,6 +2,7 @@ mod action_row; mod action_row_response; +mod attribute_rows; mod axis_rows; mod band_response; mod button_icon; @@ -12,11 +13,13 @@ mod compare_row; mod compare_row_response; mod eye_toggle; mod factor_slider; +mod gradient_rows; mod group; mod hold_pad; mod id_color_row; mod id_color_row_response; mod info_icon; +mod marker_drag; mod material_rows; mod name_field; mod number_field; diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs index f517175d..f44b8045 100644 --- a/crates/ui-egui/src/property_sheet/row.rs +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -170,6 +170,9 @@ impl PropertySheet<'_> { let label_x = self.left + shift + ROW_PICTURE_SIZE + ROW_PICTURE_AIR; let (label, stack) = match lead { RowLead::Label { text, stack } => (text, stack), + let (label, stack, text_color) = match lead { + RowLead::Label { text, stack } => (text, stack, self.tokens.text), + RowLead::Tinted { text, color } => (text, false, color), RowLead::Loose(text) if shift + self.text_width(text, font.clone()) <= self.column() - self.left - LOOSE_LABEL_AIR => { self.paint_info(center_y); self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text); @@ -195,10 +198,10 @@ impl PropertySheet<'_> { self.seen.label_width = self.seen.label_width.max(width); } - let text = self.tokens.text; if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { self.paint_info(center_y); self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text); + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); return self.column(); } diff --git a/crates/ui-egui/src/property_sheet/row_lead.rs b/crates/ui-egui/src/property_sheet/row_lead.rs index 36d82d8a..84fc568d 100644 --- a/crates/ui-egui/src/property_sheet/row_lead.rs +++ b/crates/ui-egui/src/property_sheet/row_lead.rs @@ -14,6 +14,9 @@ pub(crate) enum RowLead<'a> { /// A setting of the row above, dim, its label on the label column like its parent's Child(&'a str), + + /// A label beside the controls column in a color of its own (Color Balance's color names) + Tinted { text: &'a str, color: egui::Color32 }, } impl<'a> RowLead<'a> { @@ -26,6 +29,7 @@ impl<'a> RowLead<'a> { pub(crate) fn text(self) -> &'a str { match self { RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) => text, + RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) | RowLead::Tinted { text, .. } => text, } } } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 14b8d740..aa8dde9c 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -1,11 +1,14 @@ use std::ops::RangeInclusive; use egui::{Align2, Id, Rect, Sense, Stroke, WidgetInfo, pos2}; +use egui::{Align2, Color32, CornerRadius, FontId, Id, Rect, Response, Sense, Stroke, StrokeKind, WidgetInfo, pos2}; +use egui_phosphor::regular as ic; use super::number_field::shown_number; use super::track::Track; use super::value_text::ValueText; use super::{PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, TEXT_SIZE}; +use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; /// Radius of a slider's knob @@ -29,6 +32,22 @@ const DIAL_ZERO_DEGREES: f32 = 90.0; /// Air between the dial and the value, and between the track's end and the dial const DIAL_AIR: f32 = 6.0; +/// Air between a tinted slider's track end and its right-hand color name +const TINT_WORD_AIR: f32 = 8.0; + +/// Half the height of Intensity's divider chip +const CHIP_HALF_HEIGHT: f32 = 10.0; + +/// The chip's room around its number: the caret and the air on both sides +const CHIP_PADDING: f32 = 24.0; + +/// Air between the chip and the value, beyond the panel's value column +const CHIP_TO_VALUE: f32 = 18.0; + +/// Where a slider's unit chip draws its caret and its text, from the chip's right end +const CHIP_CARET_INSET: f32 = 9.0; +const CHIP_TEXT_INSET: f32 = 18.0; + impl PropertySheet<'_> { /// A bounded number; `Some(merge)` when `value` changed, `merge` true for a drag's later steps pub(crate) fn slider(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { @@ -65,6 +84,22 @@ impl PropertySheet<'_> { Self::apply_typed(value, typed, dragged) } + /// A −1..1 balance between two tinted color names, left as the label and right after the track (`rights`: the group's right names) + pub(crate) fn tinted_slider(&mut self, left: (&str, Color32), right: (&str, Color32), rights: &[&str], value: &mut f32) -> Option { + let tokens = self.tokens; + let readable = |tint: Color32| crate::theme::legible_tint(tint, tokens.row, tokens.text); + let (control, center_y) = self.row_with(RowLead::Tinted { text: left.0, color: readable(left.1) }); + let id = self.next_id(); + let widest = rights.iter().map(|name| self.text_width(name, FontId::proportional(TEXT_SIZE))).fold(0.0, f32::max); + let word_x = self.track_end() - widest; + let track = Track { start: control.left() + KNOB_RADIUS, end: word_x - TINT_WORD_AIR, center_y, zero: Some(0.0), ramp: false }; + let range = -1.0..=1.0; + let dragged = self.track(id, left.0, &track, value, &range); + self.ui.painter().text(pos2(word_x, center_y), Align2::LEFT_CENTER, right.0, FontId::proportional(TEXT_SIZE), readable(right.1)); + let typed = self.value_field(id, left.0, center_y, *value, &range, 2, ""); + Self::apply_typed(value, typed, dragged) + } + /// An angle in degrees: the track, then a small dial just before the value pub(crate) fn angle(&mut self, label: &str, degrees: &mut f32, range: RangeInclusive) -> Option { self.angle_led(RowLead::label(label), degrees, range) @@ -107,6 +142,40 @@ impl PropertySheet<'_> { Self::apply_typed(degrees, typed, dragged) } + /// A slider with a small dropdown chip before its value (Intensity's divider); returns the edit and the chip + pub(crate) fn slider_with_chip( + &mut self, + label: &str, + value: &mut f32, + range: RangeInclusive, + decimals: usize, + chip: &str, + widest_chip: &str, + ) -> (Option, Response) { + let (control, center_y) = self.row(label); + let id = self.next_id(); + let chip_end = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - CHIP_TO_VALUE; + let chip_width = self.text_width(widest_chip, FontId::proportional(TEXT_SIZE)) + CHIP_PADDING; + let chip_rect = Rect::from_min_max(pos2(chip_end - chip_width, center_y - CHIP_HALF_HEIGHT), pos2(chip_end, center_y + CHIP_HALF_HEIGHT)); + let chip_response = self.ui.interact(chip_rect, id.with("chip"), Sense::click()); + chip_response.widget_info(|| WidgetInfo::labeled(egui::Role::ComboBox, true, chip)); + + let tokens = self.tokens; + let open = egui::Popup::is_id_open(self.ui.ctx(), egui::Popup::default_response_id(&chip_response)); + let painter = self.ui.painter(); + painter.rect_filled(chip_rect, CornerRadius::same(CONTROL_RADIUS), if chip_response.hovered() { tokens.row_hover } else { tokens.button }); + if open { + painter.rect_stroke(chip_rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } + painter.text(pos2(chip_end - CHIP_CARET_INSET, center_y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(ICON_SIZE), tokens.text); + painter.text(pos2(chip_end - CHIP_TEXT_INSET, center_y), Align2::RIGHT_CENTER, chip, semibold(SMALL_TEXT_SIZE), tokens.text); + + let track = Track { start: control.left() + KNOB_RADIUS, end: chip_rect.left() - DIAL_AIR - KNOB_RADIUS, center_y, zero: None, ramp: false }; + let dragged = self.track(id, label, &track, value, &range); + let typed = self.value_field(id, label, center_y, *value, &range, decimals, ""); + (Self::apply_typed(value, typed, dragged), chip_response) + } + /// A typed value wins over a drag in the same frame and starts its own undo step pub(super) fn apply_typed(value: &mut f32, typed: Option, dragged: Option) -> Option { match typed { diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 3c144770..edee6c7a 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -75,6 +75,13 @@ impl PropertySheet<'_> { self.slot_row(thumbnail, name, source, on, clear, reset.then_some(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`]'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) diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 98b278e1..f0316e7d 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,6 +1,7 @@ -use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, SMALL_TEXT_SIZE, TEXT_SIZE}; +use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; /// Draws a picture row's picture into its square @@ -93,6 +94,16 @@ impl PropertySheet<'_> { self.segments(control, options, selected, runs, None) } + /// [`Self::switch`] with its label always above it, the switch across the whole panel (long choices in a set of such switches); returns the picked index + pub(crate) fn stacked_switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { + if !self.switch_fits(options, self.left) { + return self.switch_dropdown(label, options, selected); + } + + let (control, _) = self.row_with(RowLead::Label { text: label, stack: true }); + self.segments(control, options, selected, untinted, None) + } + /// Whether every option's word fits its share of a switch from `left` to the panel's right edge fn switch_fits(&self, options: &[&str], left: f32) -> bool { let segment = (self.right - left) / options.len().max(1) as f32; diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index fc155266..adaeb900 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -99,7 +99,7 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { } } - if sheet.fold("Edges", None, true) { + if sheet.card("Edges", Some(true)) { sheet.toggle("Wrap", &mut state.wrap); sheet.toggle("Shape Crop", &mut state.crop); sheet.info(DEPTH_CULLING_TIP); @@ -115,6 +115,11 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { { *on = !*on; } + let (_, chip) = sheet.slider_with_chip("Intensity", &mut state.intensity, 0.0..=1.0, 2, &format!("÷{}", state.divider), "÷1000"); + let dividers = ["1", "10", "100", "1000"]; + if let Some(picked) = sheet.hanging_list(&chip, state.divider, ÷rs, &|divider: &str| format!("÷{divider}"), None).0 { + state.divider = picked; + } let band = sheet.band("Parameters", true, None, Some("3")); if band.open { sheet.caption("Offset"); @@ -325,6 +330,7 @@ fn card_under_caption(ui: &mut egui::Ui, state: &mut (bool, std::cell::Cell)) { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "ramp", |sheet| { + if let Some(drag) = sheet.gradient_ramp(&[[1.0, 0.0, 0.0]], &[state.0], &|_| [0.5; 3]) { + state.0 = drag.position; + state.1.push(drag.merge); + } + }); +} + +/// A marker pressed past the ramp's end changes nothing at first; its first move inward still starts its own undo step +#[test] +fn a_gradient_marker_pressed_past_the_ramps_end_starts_an_undo_step_with_its_first_change() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui_state(one_marker_ramp, (1.0, Vec::new())); + harness.run_steps(2); + let marker = harness.get_by_label("Color 1").rect(); + let past_end = marker.right_center() - egui::vec2(1.0, 0.0); + harness.drag_at(past_end); + harness.run(); + harness.hover_at(past_end + egui::vec2(20.0, 0.0)); + harness.run(); + harness.hover_at(past_end - egui::vec2(40.0, 0.0)); + harness.run(); + harness.hover_at(past_end - egui::vec2(60.0, 0.0)); + harness.run(); + harness.drop_at(past_end - egui::vec2(60.0, 0.0)); + harness.run(); + + let merges = &harness.state().1; + assert!(merges.len() >= 2, "the drag changes the value more than once: {merges:?}"); + assert_eq!(merges.first(), Some(&false), "the first real change starts an undo step: {merges:?}"); + assert!(merges.iter().skip(1).all(|merge| *merge), "later changes continue it: {merges:?}"); +} + #[test] fn the_label_column_fits_the_widest_short_label_and_long_labels_stack() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs index 4f81abb1..8fc9ebc0 100644 --- a/crates/ui-egui/src/property_sheet/tests/gallery.rs +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -20,6 +20,8 @@ pub(super) struct Gallery { pub(super) channel_on: bool, pub(super) channels: [bool; 5], pub(super) channel_value: f32, + pub(super) intensity: f32, + pub(super) divider: &'static str, pub(super) seed: u32, pub(super) randomized: u32, pub(super) long_choice: usize, @@ -44,6 +46,8 @@ impl Default for Gallery { channel_on: true, channels: [true, true, true, false, true], channel_value: 0.8, + intensity: 0.5, + divider: "1", seed: 1234, randomized: 0, long_choice: 0, diff --git a/crates/ui-egui/src/source_slot.rs b/crates/ui-egui/src/source_slot.rs index 454ff93b..e7474eec 100644 --- a/crates/ui-egui/src/source_slot.rs +++ b/crates/ui-egui/src/source_slot.rs @@ -1,7 +1,9 @@ //! What a source slot card edits: one channel of a fill's material, or a mask fill's one grayscale source +//! What a source slot card edits: one channel of a fill's material, a mask fill's one grayscale source, or a filter's image input use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, ChannelKind}; +use texturecraft_engine::core::{Channel, ChannelKind, ImageInput}; use crate::i18n::tr; @@ -11,6 +13,8 @@ pub(crate) enum SourceSlot { Channel(Channel), /// A mask fill's source, read as gray 0..1 Grayscale, + /// A filter's image input, read as gray 0..1 + Input(ImageInput), } impl SourceSlot { @@ -19,6 +23,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => tr(channel.label()), SourceSlot::Grayscale => tr("Grayscale"), + SourceSlot::Input(input) => tr(input.label), } } @@ -27,6 +32,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => channel.kind(), SourceSlot::Grayscale => ChannelKind::Scalar, + SourceSlot::Grayscale | SourceSlot::Input(_) => ChannelKind::Scalar, } } @@ -35,6 +41,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => channel.default_value(), SourceSlot::Grayscale => [1.0; 3], + SourceSlot::Input(input) => [input.default; 3], } } @@ -56,6 +63,7 @@ impl SourceSlot { match self { SourceSlot::Grayscale => ([0.0; 3], [1.0; 3]), + SourceSlot::Grayscale | SourceSlot::Input(_) => ([0.0; 3], [1.0; 3]), SourceSlot::Channel(Channel::BaseColor) => BASE_COLOR_ENDS, SourceSlot::Channel(Channel::Height) => HEIGHT_ENDS, SourceSlot::Channel(_) => CHANNEL_ENDS, @@ -67,6 +75,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => json!({"channel": channel.id()}), SourceSlot::Grayscale => json!({}), + SourceSlot::Input(input) => json!({"input": input.id}), } } @@ -75,6 +84,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => channel.id(), SourceSlot::Grayscale => "grayscale", + SourceSlot::Input(input) => input.id, } } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 05b2eb8f..33f94c62 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -397,12 +397,45 @@ pub const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; /// The axes' letters, as the Axis switches and the 3D fields' tags show them pub const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; +/// Cyan, magenta and yellow: the opposites of [`AXIS_COLORS`] at the same brightness (Color Balance's color names) +pub const OPPOSITE_COLORS: [Color32; 3] = [Color32::from_rgb(0x52, 0xb8, 0xc4), Color32::from_rgb(0xc4, 0x6a, 0xc8), Color32::from_rgb(0xd2, 0xb8, 0x52)]; + /// `from` moved `amount` of the way to `to` in gamma space, opaque pub(crate) fn lerp_color(from: Color32, to: Color32, amount: f32) -> Color32 { let mix = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount).round().clamp(0.0, 255.0) as u8; Color32::from_rgb(mix(from.r(), to.r()), mix(from.g(), to.g()), mix(from.b(), to.b())) } +/// Least contrast a tinted color name keeps against its background (the WCAG ratio for normal text: the names are regular 12 pt lettering) +const TINT_MIN_CONTRAST: f32 = 4.5; + +/// How finely [`legible_tint`] walks from the tint to the text colour: a tenth of the way at a time keeps as much of the tint as reads +const TINT_STEPS: u8 = 10; + +/// `tint` moved toward `text` just enough to read on `background` (Color Balance's yellow and cyan names on a light card); a tint that already reads stays as it is +pub fn legible_tint(tint: Color32, background: Color32, text: Color32) -> Color32 { + (0..=TINT_STEPS) + .map(|step| tint.lerp_to_gamma(text, f32::from(step) / f32::from(TINT_STEPS))) + .find(|color| contrast_ratio(*color, background) >= TINT_MIN_CONTRAST) + .unwrap_or(text) +} + +/// WCAG's flare term, added to both luminances so black still has a ratio +const WCAG_FLARE: f32 = 0.05; + +/// The WCAG contrast ratio of two opaque colors (1..21) +fn contrast_ratio(a: Color32, b: Color32) -> f32 { + let luminance = |color: Color32| { + let linear = egui::Rgba::from(color); + + // Rec. 709 luminance + 0.2126 * linear.r() + 0.7152 * linear.g() + 0.0722 * linear.b() + }; + let (first, second) = (luminance(a), luminance(b)); + let (high, low) = (first.max(second), first.min(second)); + (high + WCAG_FLARE) / (low + WCAG_FLARE) +} + /// A section caption inside a panel: semibold in the strong colour, as written (no capitals). pub fn caption(text: &str) -> egui::RichText { egui::RichText::new(text).font(semibold(12.5)).strong() @@ -412,6 +445,23 @@ pub fn caption(text: &str) -> egui::RichText { mod tests { use super::*; + #[test] + fn tint_names_reach_normal_text_contrast_and_a_tint_that_already_reads_stays_as_it_is() { + for theme in [Brightness::Light, Brightness::MediumLight, Brightness::MediumDark, Brightness::Dark] { + let tokens = Tokens::for_brightness(theme); + for tint in OPPOSITE_COLORS.into_iter().chain(AXIS_COLORS) { + let shown = legible_tint(tint, tokens.row, tokens.text); + assert!(contrast_ratio(shown, tokens.row) >= TINT_MIN_CONTRAST, "{theme:?} {tint:?} -> {shown:?}"); + if contrast_ratio(tint, tokens.row) >= TINT_MIN_CONTRAST { + assert_eq!(shown, tint, "{theme:?}: a tint that already reads stays as it is"); + } + } + } + + let light = Tokens::for_brightness(Brightness::Light); + assert_ne!(legible_tint(OPPOSITE_COLORS[2], light.row, light.text), OPPOSITE_COLORS[2], "yellow darkens on a light card"); + } + #[test] fn settings_round_trip_and_unknown_values_load_the_defaults() { for b in Brightness::ALL { @@ -429,18 +479,7 @@ mod tests { #[test] fn every_brightness_and_accent_reads() { - // Relative luminance (WCAG) and contrast ratio. - let lum = |c: Color32| { - let ch = |v: u8| { - let v = f32::from(v) / 255.0; - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } - }; - 0.2126 * ch(c.r()) + 0.7152 * ch(c.g()) + 0.0722 * ch(c.b()) - }; - let contrast = |a: Color32, b: Color32| { - let (x, y) = (lum(a), lum(b)); - (x.max(y) + 0.05) / (x.min(y) + 0.05) - }; + let contrast = contrast_ratio; for b in Brightness::ALL { for a in Accent::ALL { let t = Tokens::for_brightness(b).with_accent(a); diff --git a/crates/ui-egui/tests/it/filter_colour.rs b/crates/ui-egui/tests/it/filter_colour.rs new file mode 100644 index 00000000..92d57879 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_colour.rs @@ -0,0 +1,85 @@ +//! The colour filters in Properties: HSL Perceptive's Mode switch and centred sliders, the tone cards of Color Balance and +//! Color Correct, and Blur's Wrap toggle + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, filter_of, topmost}; +use egui::accesskit::Role; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::Filter; + +#[test] +fn hsl_mode_switches_and_its_sliders_sit_at_the_middle() { + let (mut harness, effect) = app_with("hsl", "content", WINDOW_HEIGHT); + for label in ["Hue", "Saturation", "Lightness"] { + let value = harness.get_by_role_and_label(Role::Slider, label).accesskit_node().numeric_value(); + assert_eq!(value, Some(0.5), "{label} unchanged reads 0.50"); + } + + let regular = harness.get_by_role_and_label(Role::RadioButton, "Regular").rect(); + click_at(&mut harness, regular.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::Hsl { perceptive: false, .. }), "{:?}", filter_of(&harness, effect)); + + // A click at the right end of Saturation doubles it (stored 1) + let track = harness.get_by_role_and_label(Role::Slider, "Saturation").rect(); + click_at(&mut harness, along(track, 1.0)); + + assert!(matches!(filter_of(&harness, effect), Filter::Hsl { saturation, .. } if saturation > 0.95), "{:?}", filter_of(&harness, effect)); +} + +/// A stored hue past half a turn (0.75, the same hue as -0.25) shows wrapped round on the centred Hue slider, not pinned at its right end +#[test] +fn hsl_hue_past_half_a_turn_shows_wrapped_round() { + let (mut harness, effect) = app_with("hsl", "content", WINDOW_HEIGHT); + harness.state_mut().run("effect.set", serde_json::json!({"effect": effect.0, "hue": 0.75})); + harness.run_steps(2); + + let shown = harness.get_by_role_and_label(Role::Slider, "Hue").accesskit_node().numeric_value().unwrap(); + + assert!((shown - 0.25).abs() < 1e-3, "a quarter turn back shows a quarter left of the middle: {shown}"); +} + +/// Color Balance's tone cards fold one at a time, and a row edits only its own card's tone +#[test] +fn color_balance_tone_cards_fold_and_edit_their_own_tone() { + let (mut harness, effect) = app_with("colorBalance", "content", WINDOW_HEIGHT); + assert_eq!(harness.query_all_by_role_and_label(Role::Slider, "Cyan").count(), 3, "a Cyan row per tone"); + + let midtones = harness.get_by_role_and_label(Role::Button, "Midtones").rect(); + click_at(&mut harness, midtones.center()); + + assert_eq!(harness.query_all_by_role_and_label(Role::Slider, "Cyan").count(), 2, "Midtones folds"); + + // Highlights comes first: its Yellow row's left end pushes the highlights to yellow + let track = topmost(&harness, Role::Slider, "Yellow"); + click_at(&mut harness, along(track, 0.0)); + + let Filter::ColorBalance { highlights, shadows, midtones } = filter_of(&harness, effect) else { panic!() }; + assert!(highlights[2] < -0.9 && shadows == [0.0; 3] && midtones == [0.0; 3], "{highlights:?} {midtones:?} {shadows:?}"); +} + +/// Color Correct's Midtones card sits between its header and the Highlights card's, and its Saturation row edits the midtones only +#[test] +fn color_correct_midtones_card_edits_its_own_tone() { + let (mut harness, effect) = app_with("colorCorrect", "content", WINDOW_HEIGHT); + let midtones = harness.get_by_role_and_label(Role::Button, "Midtones").rect(); + let highlights = harness.get_by_role_and_label(Role::Button, "Highlights").rect(); + let track = harness + .get_all_by_role_and_label(Role::Slider, "Saturation") + .map(|node| node.rect()) + .find(|rect| rect.top() > midtones.bottom() && rect.bottom() < highlights.top()) + .unwrap(); + click_at(&mut harness, along(track, 0.0)); + + let Filter::ColorCorrect { shadows, midtones, .. } = filter_of(&harness, effect) else { panic!() }; + assert!(midtones[2] < 0.05 && shadows[2] == 0.5, "the Midtones card's Saturation: {midtones:?} {shadows:?}"); +} + +#[test] +fn blur_wrap_switches_the_edge_wrap() { + let (mut harness, effect) = app_with("blur", "content", WINDOW_HEIGHT); + let wrap = harness.get_by_role_and_label(Role::CheckBox, "Blur Wrap").rect(); + + click_at(&mut harness, wrap.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::Blur { wrap: true, .. })); +} diff --git a/crates/ui-egui/tests/it/filter_light.rs b/crates/ui-egui/tests/it/filter_light.rs new file mode 100644 index 00000000..d93268ba --- /dev/null +++ b/crates/ui-egui/tests/it/filter_light.rs @@ -0,0 +1,118 @@ +//! The light and shadow filters in Properties: Glow's Used on a Mask, Mode and signed Width, Drop Shadow's Angle and Distance, the Baked Lighting cards and rows (the Sun's angle names) + +use crate::filter_support::{TALL_WINDOW_HEIGHT, WINDOW_HEIGHT, along, app_with, click_at, drag, filter_of, topmost, undo, undo_depth}; +use egui::accesskit::Role; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{Filter, LightingOutput}; + +/// Clicks on Used on a Mask, Precise and the left end of Width turn the glow into a precise inner glow laid as white on the mask +#[test] +fn glow_rows_set_used_on_a_mask_precise_and_an_inner_width() { + let (mut harness, effect) = app_with("glow", "mask", WINDOW_HEIGHT); + + let toggle = harness.get_by_role_and_label(Role::CheckBox, "Used on a Mask").rect(); + click_at(&mut harness, toggle.center()); + let precise = harness.get_by_role_and_label(Role::RadioButton, "Precise").rect(); + click_at(&mut harness, precise.center()); + let width = harness.get_by_role_and_label(Role::Slider, "Width").rect(); + click_at(&mut harness, along(width, 0.0)); + + let Filter::HaloGlow { on_mask, precise, width, .. } = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!(on_mask && precise, "{on_mask} {precise}"); + assert!(width < -0.9, "inner glow: {width}"); +} + +/// Drop Shadow's Distance reaches both ways and its Angle row carries a dial +#[test] +fn drop_shadow_distance_goes_both_ways() { + let (mut harness, effect) = app_with("dropShadow", "mask", WINDOW_HEIGHT); + let distance = harness.get_by_role_and_label(Role::Slider, "Distance").rect(); + + click_at(&mut harness, along(distance, 0.0)); + + let Filter::DropShadow { distance, angle, .. } = filter_of(&harness, effect) else { panic!() }; + assert!(distance < -0.45, "towards the light: {distance}"); + assert_eq!(angle, 90.0); + + // The dial sits between the Angle track and its value, so the track ends short of Distance's + let angle_track = harness.get_by_role_and_label(Role::Slider, "Angle").rect(); + let distance_track = harness.get_by_role_and_label(Role::Slider, "Distance").rect(); + assert!(angle_track.right() < distance_track.right() - DIAL_ROOM, "{angle_track:?} {distance_track:?}"); +} + +/// How much shorter than a plain slider's track an angle row's track is at least: room for its dial +const DIAL_ROOM: f32 = 10.0; + +/// Drop Shadow's Angle dial row: a drag turns it in one undo step, undo turns it back +#[test] +fn drop_shadow_angle_drag_is_one_undo_step() { + let (mut harness, effect) = app_with("dropShadow", "mask", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + let angle = harness.get_by_role_and_label(Role::Slider, "Angle").rect(); + + drag(&mut harness, along(angle, 0.5), along(angle, 0.0)); + + let Filter::DropShadow { angle, .. } = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!(angle < 0.5, "turned to 0: {angle}"); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); + + undo(&mut harness); + assert!(matches!(filter_of(&harness, effect), Filter::DropShadow { angle, .. } if angle == 90.0), "{:?}", filter_of(&harness, effect)); +} + +/// The Sun card's angles read Sun Horizontal Angle and Sun Vertical Angle; Light 1 and 2 keep Horizontal Angle and Vertical Angle +#[test] +fn baked_lighting_stylized_sun_angles_take_the_sun_names() { + let (harness, _) = app_with("bakedLighting", "content", TALL_WINDOW_HEIGHT); + + for label in ["Sun Horizontal Angle", "Sun Vertical Angle"] { + assert_eq!(harness.query_all_by_role_and_label(Role::Slider, label).count(), 1, "{label}"); + } + for label in ["Horizontal Angle", "Vertical Angle"] { + assert_eq!(harness.query_all_by_role_and_label(Role::Slider, label).count(), 2, "{label}: Light 1 and 2"); + } +} + +/// Baked Lighting Stylized's cards edit their own settings: Sun Intensity's right end, Light 1's Intensity and Output's Specular only +#[test] +fn baked_lighting_stylized_cards_set_the_sun_a_light_and_the_output() { + let (mut harness, effect) = app_with("bakedLighting", "content", TALL_WINDOW_HEIGHT); + + let sun = harness.get_by_role_and_label(Role::Slider, "Sun Intensity").rect(); + click_at(&mut harness, along(sun, 1.0)); + + // Light 1's card comes before Light 2's + let light_1 = topmost(&harness, Role::Slider, "Intensity"); + click_at(&mut harness, along(light_1, 1.0)); + let output = harness.get_by_role_and_label(Role::ComboBox, "Diffuse + Specular").rect(); + click_at(&mut harness, output.center()); + let specular = harness.get_by_label("Specular only").rect(); + click_at(&mut harness, specular.center()); + + let filter = filter_of(&harness, effect); + let (stylized, light) = filter.stylized_lighting().unwrap(); + assert!(light.sun.intensity > 9.5, "{}", light.sun.intensity); + assert!(stylized.lights[0].intensity > 1.9 && stylized.lights[1].intensity == 0.0, "{:?}", stylized.lights); + assert_eq!(stylized.output, LightingOutput::Specular); +} + +/// Baked Lighting Environment's rows: Horizontal Rotation with its dial, a signed Exposure, and the stacked Specular Occlusion Intensity under its label +#[test] +fn baked_lighting_environment_rows_set_rotation_exposure_and_occlusion() { + let (mut harness, effect) = app_with("bakedLightingEnvironment", "content", TALL_WINDOW_HEIGHT); + + let rotation = harness.get_by_role_and_label(Role::Slider, "Horizontal Rotation").rect(); + click_at(&mut harness, rotation.center()); + let exposure = harness.get_by_role_and_label(Role::Slider, "Exposure").rect(); + click_at(&mut harness, along(exposure, 0.0)); + let specular = harness.get_by_role_and_label(Role::Slider, "Specular Occlusion Intensity").rect(); + click_at(&mut harness, along(specular, 1.0)); + + let Filter::EnvironmentLighting { horizontal, exposure, specular_occlusion, ambient_occlusion, .. } = filter_of(&harness, effect) else { + panic!("{:?}", filter_of(&harness, effect)) + }; + + assert!((150.0..210.0).contains(&horizontal), "half way round: {horizontal}"); + assert!(exposure < -4.5, "darker: {exposure}"); + assert!(specular_occlusion > 0.95 && ambient_occlusion == 1.0, "{specular_occlusion} {ambient_occlusion}"); +} diff --git a/crates/ui-egui/tests/it/filter_shape.rs b/crates/ui-egui/tests/it/filter_shape.rs new file mode 100644 index 00000000..50358d2b --- /dev/null +++ b/crates/ui-egui/tests/it/filter_shape.rs @@ -0,0 +1,307 @@ +//! The shape filters in Properties: Threshold's Mode switch, Mirror's mode-dependent rows, Mask Outline's, Bevel's, Bevel Smooth's, Directional Distance's, Warp's (its Directional mode and Angle) and Blur Slope's rows (its ÷ chip, Seed and Source Parameters' Blur) + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, drag, filter_of, lowest, pick, topmost, undo, undo_depth}; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::{ + BevelBlur, BevelCorner, BevelDirection, EffectKind, Filter, MirrorCorner, MirrorMode, OutlinePosition, SlopeBlending, ThresholdMode, WarpBlending, + WarpMode, WarpSourceMode, +}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Threshold's slider is named Threshold and its ≤ segment sets Lower or equal +#[test] +fn threshold_mode_switch_sets_the_comparison() { + let (mut harness, effect) = app_with("threshold", "mask", WINDOW_HEIGHT); + + let level = harness.get_by_role_and_label(Role::Slider, "Threshold").rect(); + click_at(&mut harness, along(level, 1.0)); + let lower = harness.get_by_role_and_label(Role::RadioButton, "≤").rect(); + click_at(&mut harness, lower.center()); + + let Filter::Threshold { level, mode } = filter_of(&harness, effect) else { panic!() }; + assert!(level > 0.95, "{level}"); + assert_eq!(mode, ThresholdMode::LowerOrEqual); +} + +/// Mirror shows Axis X Offset and Invert Axis X, swaps them for Axis Y's, and a corner mirror shows only its Corner Type +#[test] +fn mirror_rows_follow_the_mode() { + let (mut harness, effect) = app_with("mirror", "mask", WINDOW_HEIGHT); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert Axis X").rect(); + + click_at(&mut harness, invert.center()); + + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!() }; + assert_eq!(mirror.invert, [true, false]); + + let mode = harness.get_by_role_and_label(Role::ComboBox, "Mirror Axis X").rect(); + click_at(&mut harness, mode.center()); + let axis_y = harness.get_by_label("Mirror Axis Y").rect(); + click_at(&mut harness, axis_y.center()); + + assert!(harness.query_by_label("Axis Y Offset").is_some() && harness.query_by_label("Axis X Offset").is_none()); + + let mode = harness.get_by_role_and_label(Role::ComboBox, "Mirror Axis Y").rect(); + click_at(&mut harness, mode.center()); + let corner = harness.get_by_label("Mirror Corner").rect(); + click_at(&mut harness, corner.center()); + let corner_type = harness.get_by_role_and_label(Role::ComboBox, "Top Left").rect(); + click_at(&mut harness, corner_type.center()); + let bottom_right = harness.get_by_label("Bottom Right").rect(); + click_at(&mut harness, bottom_right.center()); + + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((mirror.mode, mirror.corner), (MirrorMode::Corner, MirrorCorner::BottomRight)); + assert!(harness.query_by_label("Axis Y Offset").is_none()); +} + +/// Mirror's mode list pick is one undo step, and undo puts Axis X back +#[test] +fn mirror_mode_pick_is_one_undo_step() { + let (mut harness, effect) = app_with("mirror", "mask", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + + pick(&mut harness, "Mirror Axis X", "Mirror Axis Y"); + + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!() }; + assert_eq!(mirror.mode, MirrorMode::AxisY); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the pick"); + + undo(&mut harness); + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!() }; + assert_eq!(mirror.mode, MirrorMode::AxisX); +} + +/// Mask Outline's Both segment, Start From Black toggle, Width and the signed Curve Shape each set their own setting +#[test] +fn mask_outline_rows_set_the_band() { + let (mut harness, effect) = app_with("maskOutline", "mask", WINDOW_HEIGHT); + + pick(&mut harness, "Outside", "Both"); + let from_black = harness.get_by_role_and_label(Role::CheckBox, "Start From Black").rect(); + click_at(&mut harness, from_black.center()); + let width = harness.get_by_role_and_label(Role::Slider, "Width").rect(); + click_at(&mut harness, along(width, 1.0)); + let curve = harness.get_by_role_and_label(Role::Slider, "Curve Shape").rect(); + click_at(&mut harness, along(curve, 0.0)); + + let Filter::MaskOutline(outline) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((outline.position, outline.from_black), (OutlinePosition::Both, false)); + assert!(outline.width > 0.95 && outline.curve < -0.95, "{outline:?}"); + assert_eq!((outline.threshold, outline.blur), (1.0, 0.0), "the others stay"); +} + +/// Bevel's Bevel Wrap, signed Distance, Corner Type, Smoothing and Blur Mode each set their own setting +#[test] +fn bevel_rows_set_the_slope() { + let (mut harness, effect) = app_with("bevel", "mask", WINDOW_HEIGHT); + + let wrap = harness.get_by_role_and_label(Role::CheckBox, "Bevel Wrap").rect(); + click_at(&mut harness, wrap.center()); + let distance = harness.get_by_role_and_label(Role::Slider, "Distance").rect(); + click_at(&mut harness, along(distance, 1.0)); + pick(&mut harness, "Round", "Angular"); + let smoothing = harness.get_by_role_and_label(Role::Slider, "Smoothing").rect(); + click_at(&mut harness, along(smoothing, 1.0)); + pick(&mut harness, "Non-Uniform", "Uniform"); + + let Filter::DistanceBevel(bevel) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((bevel.wrap, bevel.corner, bevel.blur), (true, BevelCorner::Angular, BevelBlur::Uniform)); + assert!(bevel.distance > 0.95 && bevel.smoothing > 4.9, "{bevel:?}"); +} + +/// Bevel's Distance drag is one undo step, and undo puts the distance back +#[test] +fn bevel_distance_drag_is_one_undo_step() { + let (mut harness, effect) = app_with("bevel", "mask", WINDOW_HEIGHT); + let Filter::DistanceBevel(before) = filter_of(&harness, effect) else { panic!() }; + let depth = undo_depth(&harness); + let distance = harness.get_by_role_and_label(Role::Slider, "Distance").rect(); + + drag(&mut harness, along(distance, 0.5), along(distance, 1.0)); + + let Filter::DistanceBevel(bevel) = filter_of(&harness, effect) else { panic!() }; + assert!(bevel.distance > 0.95, "{bevel:?}"); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); + + undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::DistanceBevel(before)); +} + +/// Bevel Smooth's Direction, Curve Offset and Bevel Wrap set their own setting +#[test] +fn bevel_smooth_rows() { + let (mut harness, effect) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); + + pick(&mut harness, "Out", "In/Out"); + let offset = harness.get_by_role_and_label(Role::Slider, "Curve Offset").rect(); + click_at(&mut harness, along(offset, 0.0)); + let wrap = harness.get_by_role_and_label(Role::CheckBox, "Bevel Wrap").rect(); + click_at(&mut harness, wrap.center()); + + let Filter::BevelSmooth(smooth) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((smooth.direction, smooth.wrap), (BevelDirection::InOut, true)); + assert!(smooth.curve_offset < -0.95 && smooth.distance == 0.1, "{smooth:?}"); +} + +/// Directional Distance's Angle row turns its trail and leaves the distance alone +#[test] +fn directional_distance_angle_row() { + let (mut harness, effect) = app_with("directionalDistance", "mask", WINDOW_HEIGHT); + let angle = harness.get_by_role_and_label(Role::Slider, "Angle").rect(); + + click_at(&mut harness, along(angle, 0.0)); + + let Filter::DirectionalDistance(trail) = filter_of(&harness, effect) else { panic!() }; + assert!(trail.angle < 5.0 && trail.distance == 0.1, "{trail:?}"); +} + +/// Warp shows the Angle only in the directional modes; Directions, Blending Mode, Source Mode, Source Tiling and Intensity set their own setting +#[test] +fn warp_rows_follow_the_mode() { + let (mut harness, effect) = app_with("warp", "mask", WINDOW_HEIGHT); + assert!(harness.query_by_label("Angle").is_none() && harness.query_by_label("Source Parameters").is_some()); + + // The filter card is named Warp too: the Warp Mode list is the lower one + let mode = lowest(&harness, Role::ComboBox, "Warp"); + click_at(&mut harness, mode.center()); + let multi = harness.get_by_label("Multi Directional Warp").rect(); + click_at(&mut harness, multi.center()); + + assert!(harness.query_by_role_and_label(Role::Slider, "Angle").is_some(), "a directional mode turns by its Angle"); + + let two = harness.get_by_role_and_label(Role::RadioButton, "2").rect(); + click_at(&mut harness, two.center()); + pick(&mut harness, "Average", "Chain"); + pick(&mut harness, "Default Noise", "Previous Input"); + let tiling = harness.get_by_role_and_label(Role::Slider, "Source Tiling").rect(); + click_at(&mut harness, along(tiling, 1.0)); + let intensity = harness.get_by_role_and_label(Role::Slider, "Intensity").rect(); + click_at(&mut harness, along(intensity, 1.0)); + + let Filter::SourceWarp(warp) = filter_of(&harness, effect) else { panic!() }; + assert_eq!( + (warp.mode, warp.directions, warp.blending, warp.source.mode), + (WarpMode::MultiDirectional, 2, WarpBlending::Chain, WarpSourceMode::PreviousInput) + ); + assert!(warp.source.tiling > 15.9 && warp.intensity > 0.95, "{warp:?}"); + assert_eq!((warp.seed, warp.divider, warp.source.balance), (0, 10, 0.5), "the others stay"); +} + +/// Blur Slope shows the reference's rows in order (no Slope scale); Blending Mode, Source Type and Quality set their own setting +#[test] +fn slope_blur_rows_set_the_smear() { + let (mut harness, effect) = app_with("slopeBlur", "mask", WINDOW_HEIGHT); + assert!(harness.query_by_label("Slope scale").is_none()); + let top = |harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str| harness.get_by_role_and_label(role, label).rect().top(); + let order = [ + top(&harness, Role::Slider, "Intensity"), + top(&harness, Role::ComboBox, "Blur"), + top(&harness, Role::Slider, "Quality"), + harness.get_by_label("Source Parameters").rect().top(), + top(&harness, Role::ComboBox, "Default Noise"), + top(&harness, Role::Slider, "Blur"), + top(&harness, Role::Slider, "Position"), + top(&harness, Role::Slider, "Contrast"), + top(&harness, Role::Slider, "Source Tiling"), + ]; + assert!(order.windows(2).all(|pair| pair[0] < pair[1]), "{order:?}"); + + pick(&mut harness, "Blur", "Max"); + pick(&mut harness, "Default Noise", "Custom Noise"); + let quality = harness.get_by_role_and_label(Role::Slider, "Quality").rect(); + click_at(&mut harness, along(quality, 0.0)); + + let Filter::SourceSlopeBlur(slope) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((slope.blending, slope.source.mode), (SlopeBlending::Max, WarpSourceMode::CustomNoise)); + assert!(slope.quality < 0.05, "{slope:?}"); + assert_eq!((slope.seed, slope.divider, slope.source.balance), (0, 10, 0.5), "the others stay"); + + // Source Type's list reads Custom Noise too: the input's slot is the lower, between it and Blur + let source_type = topmost(&harness, Role::ComboBox, "Custom Noise"); + let slot = lowest(&harness, Role::ComboBox, "Custom Noise"); + let blur = harness.get_by_role_and_label(Role::Slider, "Blur").rect(); + assert!(source_type.bottom() <= slot.top() && slot.bottom() <= blur.top(), "the Custom Noise input under Source Type: {source_type:?} {slot:?} {blur:?}"); +} + +/// Warp's Directional Warp (a list pick) shows its Angle, whose track turns it; the list pick is one undo step +#[test] +fn warp_directional_mode_and_its_angle() { + let (mut harness, effect) = app_with("warp", "mask", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + + // The filter card is named Warp too: the Warp Mode list is the lower one + let mode = lowest(&harness, Role::ComboBox, "Warp"); + click_at(&mut harness, mode.center()); + let directional = harness.get_by_label("Directional Warp").rect(); + click_at(&mut harness, directional.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::SourceWarp(warp) if warp.mode == WarpMode::Directional)); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the pick"); + + let angle = harness.get_by_role_and_label(Role::Slider, "Angle").rect(); + click_at(&mut harness, along(angle, 0.5)); + + let Filter::SourceWarp(warp) = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!((warp.angle - 180.0).abs() < 0.5, "half way round: {}", warp.angle); + + undo(&mut harness); + undo(&mut harness); + + assert!(matches!(filter_of(&harness, effect), Filter::SourceWarp(warp) if warp.mode == WarpMode::Warp), "{:?}", filter_of(&harness, effect)); +} + +/// A legacy Warp's seed past 2^24 opens in the Seed field exactly as stored (it read through an f32, one less) +#[test] +fn legacy_warp_seed_past_two_to_the_24_opens_as_stored() { + const LARGE_SEED: u32 = 16_777_217; + let (mut harness, effect) = app_with("warp", "mask", WINDOW_HEIGHT); + let project = &mut harness.state_mut().session.doc.project; + project.effect_mut(effect).unwrap().kind = EffectKind::Filter(Filter::Warp { intensity: 8.0, scale: 4.0, seed: LARGE_SEED, divider: 1 }); + harness.run_steps(2); + + let field = harness.get_by_role_and_label(Role::Label, "Seed value").rect(); + click_at(&mut harness, field.center()); + + let typed = harness.get_all_by_role(Role::TextInput).filter(|node| node.rect().intersects(field)).find_map(|node| node.accesskit_node().value()); + assert_eq!(typed, Some(LARGE_SEED.to_string())); +} + +/// Blur Slope's ÷ chip picks the divider, the dice picks a new Seed, and Source Parameters' Blur shows 0..20 over the stored 0..1 +#[test] +fn slope_blur_divider_seed_and_source_blur() { + let (mut harness, effect) = app_with("slopeBlur", "mask", WINDOW_HEIGHT); + + let chip = harness.get_by_role_and_label(Role::ComboBox, "÷10").rect(); + click_at(&mut harness, chip.center()); + let thousand = harness.get_by_role_and_label(Role::ListBoxOption, "÷1000").rect(); + click_at(&mut harness, thousand.center()); + let dice = harness.get_by_role_and_label(Role::Button, "Random").rect(); + click_at(&mut harness, dice.center()); + let blur = harness.get_by_role_and_label(Role::Slider, "Blur").rect(); + click_at(&mut harness, along(blur, 0.5)); + + let Filter::SourceSlopeBlur(slope) = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert_eq!(slope.divider, 1000); + assert_ne!(slope.seed, 0, "a new seed"); + assert!((slope.source.blur - 0.5).abs() < 0.01, "stored on 0..1: {}", slope.source.blur); + let shown = harness.get_by_role_and_label(Role::Slider, "Blur").accesskit_node().numeric_value().unwrap(); + assert!((shown - 10.0).abs() < 0.2, "shown on 0..20: {shown}"); +} + +/// Mirror's Display Debug switch and its axis offset track set their own setting +#[test] +fn mirror_debug_and_offset() { + let (mut harness, effect) = app_with("mirror", "mask", WINDOW_HEIGHT); + + let debug = harness.get_by_role_and_label(Role::CheckBox, "Display Debug").rect(); + click_at(&mut harness, debug.center()); + let offset = harness.get_by_role_and_label(Role::Slider, "Axis X Offset").rect(); + click_at(&mut harness, along(offset, 1.0)); + + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!(mirror.debug); + assert_eq!(mirror.offset, [1.0, 0.5], "Axis X's offset only"); +} diff --git a/crates/ui-egui/tests/it/filter_simple.rs b/crates/ui-egui/tests/it/filter_simple.rs new file mode 100644 index 00000000..52e04446 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_simple.rs @@ -0,0 +1,240 @@ +//! The simple adjustment filters in Properties: Invert's switch, Height Adjust's Invert above its sliders, Histogram Scan's +//! Invert Position and Posterize's Apply to Alpha under theirs, Pixelate and FXAA (Anti-aliasing)'s switches, and the reference's names on +//! Clamp, Smoothstep, Histogram Shift, Sharpen, Blur and Blur Directional; Highpass's and Grayscale Conversion's rows; the simple sliders +//! (Contrast Luminosity, Clamp, Smoothstep, Sharpen, Histogram Range, Edge Detect, Replace Color) setting their own setting, a drag as one undo step + +use egui::accesskit::Role; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::{ConversionMode, Filter, HighpassSpace}; + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, drag, filter_of, lowest, pick, undo, undo_depth}; + +/// Invert's only row is its switch: a click turns it off, another back on +#[test] +fn invert_switch_turns_it_off_and_on() { + let (mut harness, effect) = app_with("invert", "mask", WINDOW_HEIGHT); + let switch = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + + click_at(&mut harness, switch.center()); + assert_eq!(filter_of(&harness, effect), Filter::InvertOff); + + let switch = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + click_at(&mut harness, switch.center()); + assert_eq!(filter_of(&harness, effect), Filter::Invert); +} + +/// Height Adjust: Invert above Offset and Multiply; the switch flips it and Multiply's track sets it +#[test] +fn height_adjust_rows() { + let (mut harness, effect) = app_with("heightAdjust", "mask", WINDOW_HEIGHT); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + let offset = harness.get_by_role_and_label(Role::Slider, "Offset").rect(); + let multiply = harness.get_by_role_and_label(Role::Slider, "Multiply").rect(); + assert!(invert.center().y < offset.center().y && offset.center().y < multiply.center().y, "Invert, Offset, Multiply"); + + click_at(&mut harness, invert.center()); + click_at(&mut harness, along(multiply, 1.0)); + + let Filter::HeightAdjust { invert, offset, multiply } = filter_of(&harness, effect) else { panic!() }; + assert!(invert && offset == 0.0 && multiply > 9.5, "{invert} {offset} {multiply}"); +} + +/// Histogram Scan's Invert Position sits under Position and Contrast +#[test] +fn histogram_scan_switch_under_its_sliders() { + let (mut harness, effect) = app_with("histogramScan", "mask", WINDOW_HEIGHT); + let contrast = harness.get_by_role_and_label(Role::Slider, "Contrast").rect(); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert Position").rect(); + assert!(invert.center().y > contrast.center().y); + + click_at(&mut harness, invert.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::HistogramScan { invert_position: true, .. })); +} + +/// Posterize's Apply to Alpha sits under Colors Amount +#[test] +fn posterize_switch_under_its_slider() { + let (mut harness, effect) = app_with("posterize", "mask", WINDOW_HEIGHT); + let amount = harness.get_by_role_and_label(Role::Slider, "Colors Amount").rect(); + let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply to Alpha").rect(); + assert!(alpha.center().y > amount.center().y); + + click_at(&mut harness, alpha.center()); + + assert_eq!(filter_of(&harness, effect), Filter::Posterize { levels: 8.0, alpha: true }); +} + +/// Clamp's Min and Max, Smoothstep's Minimum and Maximum and Sharpen Intensity +#[test] +fn reference_names_on_the_sliders() { + for (filter, labels) in [("clamp", &["Min", "Max"][..]), ("smoothstep", &["Minimum", "Maximum"]), ("sharpen", &["Sharpen Intensity"])] { + let (harness, _) = app_with(filter, "mask", WINDOW_HEIGHT); + for label in labels { + assert!(harness.query_by_role_and_label(Role::Slider, label).is_some(), "{filter}: {label}"); + } + } +} + +/// Histogram Shift's Position: a click on its middle shifts by a half turn back +#[test] +fn histogram_shift_position_middle_is_a_half_turn_back() { + let (mut harness, effect) = app_with("histogramShift", "mask", WINDOW_HEIGHT); + let position = harness.get_by_role_and_label(Role::Slider, "Position").rect(); + + click_at(&mut harness, position.center()); + + let Filter::HistogramShift { offset } = filter_of(&harness, effect) else { panic!() }; + assert!((offset + 0.5).abs() < 0.05, "the middle is a half turn back: {offset}"); +} + +/// The setting slider case `label` of a filter sets, read back from the filter +type ReadSetting = fn(&Filter) -> Option; + +/// One slider per case, clicked at `share` of its track: (library filter, slider, share, the setting it sets, the value expected) +const SLIDER_CASES: [(&str, &str, f32, ReadSetting, f32); 12] = [ + ("contrastLuminosity", "Contrast", 1.0, |filter| if let Filter::ContrastLuminosity { contrast, .. } = filter { Some(*contrast) } else { None }, 1.0), + ("contrastLuminosity", "Luminosity", 0.0, |filter| if let Filter::ContrastLuminosity { luminosity, .. } = filter { Some(*luminosity) } else { None }, -1.0), + ("clamp", "Min", 0.5, |filter| if let Filter::Clamp { min, .. } = filter { Some(*min) } else { None }, 0.5), + ("clamp", "Max", 0.5, |filter| if let Filter::Clamp { max, .. } = filter { Some(*max) } else { None }, 0.5), + ("smoothstep", "Minimum", 0.5, |filter| if let Filter::Smoothstep { min, .. } = filter { Some(*min) } else { None }, 0.5), + ("smoothstep", "Maximum", 0.5, |filter| if let Filter::Smoothstep { max, .. } = filter { Some(*max) } else { None }, 0.5), + ("sharpen", "Sharpen Intensity", 1.0, |filter| if let Filter::Sharpen { amount } = filter { Some(*amount) } else { None }, 4.0), + ("histogramRange", "Range", 1.0, |filter| if let Filter::HistogramRange { range, .. } = filter { Some(*range) } else { None }, 1.0), + ("histogramRange", "Position", 0.0, |filter| if let Filter::HistogramRange { position, .. } = filter { Some(*position) } else { None }, 0.0), + ("edgeDetect", "Width", 0.5, |filter| if let Filter::EdgeDetect { width } = filter { Some(*width) } else { None }, 32.0), + ("replaceColor", "Tolerance", 1.0, |filter| if let Filter::ReplaceColor { tolerance, .. } = filter { Some(*tolerance) } else { None }, 1.0), + ("replaceColor", "Softness", 1.0, |filter| if let Filter::ReplaceColor { softness, .. } = filter { Some(*softness) } else { None }, 1.0), +]; + +/// How near a clicked slider's setting must land to the value expected +const SLIDER_TOLERANCE: f32 = 0.01; + +/// Each simple filter's sliders set their own setting through the pointer +#[test] +fn simple_sliders_set_their_own_setting() { + for (filter, label, share, read, expected) in SLIDER_CASES { + let (mut harness, effect) = app_with(filter, "content", WINDOW_HEIGHT); + let before = filter_of(&harness, effect); + let track = harness.get_by_role_and_label(Role::Slider, label).rect(); + + click_at(&mut harness, along(track, share)); + + let after = filter_of(&harness, effect); + let value = read(&after).unwrap(); + assert!((value - expected).abs() < SLIDER_TOLERANCE, "{filter} {label}: {value}, expected {expected}"); + assert_ne!(read(&before), read(&after), "{filter} {label} changed"); + } +} + +/// A slider drag is one undo step, and undo puts the value back +#[test] +fn a_slider_drag_is_one_undo_step() { + let (mut harness, effect) = app_with("sharpen", "content", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + let track = harness.get_by_role_and_label(Role::Slider, "Sharpen Intensity").rect(); + + drag(&mut harness, along(track, 0.5), along(track, 1.0)); + + assert!(matches!(filter_of(&harness, effect), Filter::Sharpen { amount } if amount > 3.9), "{:?}", filter_of(&harness, effect)); + assert_eq!(undo_depth(&harness), depth + 1); + + undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::Sharpen { amount: 1.0 }); +} + +/// Pixelate: Pixels Amount (32) with Apply To Alpha under it +#[test] +fn pixelate_rows() { + let (mut harness, effect) = app_with("pixelate", "mask", WINDOW_HEIGHT); + let amount = harness.get_by_role_and_label(Role::Slider, "Pixels Amount"); + assert_eq!(amount.accesskit_node().numeric_value().map(f64::round), Some(32.0)); + let amount = amount.rect(); + let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply To Alpha").rect(); + assert!(alpha.center().y > amount.center().y); + + click_at(&mut harness, alpha.center()); + assert!(matches!(filter_of(&harness, effect), Filter::Mosaic { alpha: false, .. })); + + click_at(&mut harness, along(amount, 1.0)); + let Filter::Mosaic { size, .. } = filter_of(&harness, effect) else { panic!() }; + assert!((Filter::pixels_amount(size) - 128.0).abs() < 0.5, "the right end is 128 across: {size}"); +} + +/// FXAA (Anti-aliasing): only its Affect Alpha Channel switch +#[test] +fn fxaa_rows() { + let (mut harness, effect) = app_with("fxaa", "mask", WINDOW_HEIGHT); + let affect = harness.get_by_role_and_label(Role::CheckBox, "Affect Alpha Channel").rect(); + + click_at(&mut harness, affect.center()); + + assert_eq!(filter_of(&harness, effect), Filter::Fxaa { alpha: true }); +} + +/// Blur's Blur Intensity takes the reference's name and starts at 0.30 +#[test] +fn blur_intensity_takes_the_reference_name() { + let (harness, _) = app_with("blur", "mask", WINDOW_HEIGHT); + let intensity = harness.get_by_role_and_label(Role::Slider, "Blur Intensity"); + assert_eq!(intensity.accesskit_node().numeric_value().map(|value| (value * 100.0).round()), Some(30.0)); +} + +/// Blur Directional's Intensity and Angle take the reference's names, and Intensity's right end is the widest blur +#[test] +fn blur_directional_rows_take_the_reference_names() { + let (mut harness, effect) = app_with("blurDirectional", "mask", WINDOW_HEIGHT); + let intensity = harness.get_by_role_and_label(Role::Slider, "Intensity").rect(); + assert!(harness.query_by_role_and_label(Role::Slider, "Angle").is_some()); + + click_at(&mut harness, along(intensity, 1.0)); + + assert!(matches!(filter_of(&harness, effect), Filter::DirectionalBlur { radius, .. } if radius > 250.0)); +} + +/// Highpass: Color Space, Radius and Apply To Alpha, each setting its own value +#[test] +fn highpass_rows() { + let (mut harness, effect) = app_with("highPass", "mask", WINDOW_HEIGHT); + let radius = harness.get_by_role_and_label(Role::Slider, "Radius"); + assert_eq!(radius.accesskit_node().numeric_value().map(|value| (value * 100.0).round()), Some(300.0)); + let radius = radius.rect(); + let space = harness.get_by_role_and_label(Role::ComboBox, "Working space / Mask").rect(); + let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply To Alpha").rect(); + assert!(space.center().y < radius.center().y && radius.center().y < alpha.center().y, "the reference's order"); + + pick(&mut harness, "Working space / Mask", "sRGB (from ACEScg)"); + click_at(&mut harness, alpha.center()); + assert_eq!(filter_of(&harness, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::SrgbFromAcescg, alpha: true }); + + click_at(&mut harness, along(radius, 1.0)); + assert!(matches!(filter_of(&harness, effect), Filter::HighPass { radius, .. } if radius > 250.0), "Radius 16 = 256 texels at 2K"); +} + +/// Grayscale Conversion: Channel Input (Custom Input shows its slot right under it), Invert, Balance, Contrast, Mode and the weights in Channels Weights only +#[test] +fn grayscale_conversion_rows() { + let (mut harness, effect) = app_with("grayscale", "mask", WINDOW_HEIGHT); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect().center().y; + let sliders = ["Balance", "Contrast", "Red", "Green", "Blue", "Alpha"].map(|label| harness.get_by_role_and_label(Role::Slider, label).rect().center().y); + let rows: Vec = std::iter::once(invert).chain(sliders).collect(); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Custom Input").is_none(), "no slot for the current channel"); + + pick(&mut harness, "Current Channel", "Custom Input"); + + let Filter::GrayscaleConversion(conversion) = filter_of(&harness, effect) else { panic!() }; + assert!(conversion.custom_input); + + // The lowest: Channel Input shows the same name where its words don't fit a switch + let slot = lowest(&harness, Role::ComboBox, "Custom Input"); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + assert!(slot.center().y < invert.center().y, "its slot right under Channel Input"); + + click_at(&mut harness, invert.center()); + pick(&mut harness, "Channels Weights", "Max"); + + let Filter::GrayscaleConversion(conversion) = filter_of(&harness, effect) else { panic!() }; + assert!(conversion.invert && conversion.mode == ConversionMode::Max); + assert!(harness.query_by_label("Red").is_none(), "no weights outside Channels Weights"); +} diff --git a/crates/ui-egui/tests/it/filter_stylize.rs b/crates/ui-egui/tests/it/filter_stylize.rs new file mode 100644 index 00000000..b285db69 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_stylize.rs @@ -0,0 +1,178 @@ +//! Anisotropic Kuwahara's, PBR Validate (Metallic Roughness)'s, Height To Normal's and Color Match's rows in Properties + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{ + AnisotropicKuwahara, ColorMatch, Filter, HeightToNormal, LayerId, PbrValidate, SourceColorMode, TargetColorMode, ValidationMode, +}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::{TALL_WINDOW_HEIGHT, WINDOW_HEIGHT, along, app_with, click_at, filter_of, lowest, pick, undo_depth}; + +/// Anisotropic Kuwahara: Extract Direction (its Custom Input slot right under it), then Radius … Anisotropy and the Anisotropy Angle dial, in the reference's order +#[test] +fn anisotropic_kuwahara_rows() { + let (mut harness, effect) = app_with("anisotropicKuwahara", "mask", WINDOW_HEIGHT); + let rows = ["Radius", "Smoothness", "Sharpness", "Tensor Smoothness", "Anisotropy", "Anisotropy Angle"] + .map(|label| harness.get_by_role_and_label(Role::Slider, label).rect().center().y); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Custom Input").is_none(), "no slot for the current channel"); + + pick(&mut harness, "Current Channel", "Custom Input"); + + let Filter::AnisotropicKuwahara(kuwahara) = filter_of(&harness, effect) else { panic!("still Kuwahara") }; + assert!(kuwahara.custom_input); + let slot = lowest(&harness, Role::ComboBox, "Custom Input"); + let radius = harness.get_by_role_and_label(Role::Slider, "Radius").rect(); + assert!(slot.center().y < radius.center().y, "its slot right under Extract Direction"); + + // A click at the left end of Sharpness's track reaches its least value, the library's + let sharpness = harness.get_by_role_and_label(Role::Slider, "Sharpness").rect(); + click_at(&mut harness, along(sharpness, 0.0)); + + let Filter::AnisotropicKuwahara(kuwahara) = filter_of(&harness, effect) else { panic!("still Kuwahara") }; + assert!((kuwahara.sharpness - AnisotropicKuwahara::LIBRARY.sharpness).abs() < 0.02, "{}", kuwahara.sharpness); +} + +/// The height of the label line a stacked setting shows above its control (the panel style's stack rhythm) +const STACK_LABEL_LINE: f32 = 18.0; + +/// PBR Validate: three switches, each label above its switch across the panel; each click sets its own setting +#[test] +fn pbr_validate_rows() { + let (mut harness, effect) = app_with("pbrValidate", "content", TALL_WINDOW_HEIGHT); + let firsts = ["Albedo", "50 sRGB", "70-100% Reflective"].map(|option| harness.get_by_role_and_label(Role::RadioButton, option).rect()); + for pair in firsts.windows(2) { + assert!((pair[0].left() - pair[1].left()).abs() < 1.0, "every switch starts at the panel's edge: {pair:?}"); + assert!(pair[1].top() - pair[0].bottom() >= STACK_LABEL_LINE, "a label line between the switches: {pair:?}"); + } + let last = harness.get_by_role_and_label(Role::RadioButton, "60-100% Reflective").rect(); + let combined = harness.get_by_role_and_label(Role::RadioButton, "Combined").rect(); + assert!((last.right() - combined.right()).abs() < 1.0, "all as wide: {last:?} {combined:?}"); + + for option in ["Albedo", "50 sRGB", "70-100% Reflective"] { + let segment = harness.get_by_role_and_label(Role::RadioButton, option).rect(); + click_at(&mut harness, segment.center()); + } + + assert_eq!(filter_of(&harness, effect), Filter::PbrValidate(PbrValidate { mode: ValidationMode::Albedo, albedo_dark: 50, metal_low: 70 })); +} + +/// Where along Surface Size's track the click lands: away from the default and between whole centimetres, so rounding shows +const OFF_DEFAULT_SHARE: f32 = 0.37; + +/// A click on Surface Size that rounds to the centimetres it holds changes nothing, so it adds no undo step +#[test] +fn height_to_normal_click_rounding_to_the_stored_size_adds_no_step() { + let (mut harness, effect) = app_with("heightToNormal", "mask", WINDOW_HEIGHT); + let size = harness.get_by_role_and_label(Role::Slider, "Surface Size (cm)").rect(); + click_at(&mut harness, along(size, OFF_DEFAULT_SHARE)); + let (depth, after_first) = (undo_depth(&harness), filter_of(&harness, effect)); + + click_at(&mut harness, along(size, OFF_DEFAULT_SHARE)); + + assert_eq!(filter_of(&harness, effect), after_first); + assert_eq!(undo_depth(&harness), depth, "the same whole centimetres again: no new step"); +} + +/// Height To Normal: its two switches, then whole Surface Size (cm) and Height Depth (cm), or Normal Intensity without world units +#[test] +fn height_to_normal_rows() { + let (mut harness, effect) = app_with("heightToNormal", "mask", WINDOW_HEIGHT); + let rows = [ + (Role::CheckBox, "Overwrite Existing Normal"), + (Role::CheckBox, "Use World Units"), + (Role::Slider, "Surface Size (cm)"), + (Role::Slider, "Height Depth (cm)"), + ] + .map(|(role, label)| harness.get_by_role_and_label(role, label).rect().center().y); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); + + // A click on Surface Size's track sets whole centimetres + let size = harness.get_by_role_and_label(Role::Slider, "Surface Size (cm)").rect(); + click_at(&mut harness, along(size, OFF_DEFAULT_SHARE)); + + let Filter::HeightToNormal(filter) = filter_of(&harness, effect) else { panic!("still Height To Normal") }; + assert!(filter.surface_size != 300.0 && filter.surface_size.fract() == 0.0, "{}", filter.surface_size); + assert!(harness.query_by_role_and_label(Role::Slider, "Normal Intensity").is_none()); + + let overwrite = harness.get_by_role_and_label(Role::CheckBox, "Overwrite Existing Normal").rect(); + click_at(&mut harness, overwrite.center()); + let world = harness.get_by_role_and_label(Role::CheckBox, "Use World Units").rect(); + click_at(&mut harness, world.center()); + + let Filter::HeightToNormal(filter) = filter_of(&harness, effect) else { panic!("still Height To Normal") }; + assert_eq!((filter.overwrite, filter.world_units, filter.intensity), (false, false, HeightToNormal::LIBRARY.intensity)); + assert!(harness.query_by_role_and_label(Role::Slider, "Surface Size (cm)").is_none()); + + // A click at the left end of Normal Intensity's track reaches 0 + let intensity = harness.get_by_role_and_label(Role::Slider, "Normal Intensity").rect(); + click_at(&mut harness, along(intensity, 0.0)); + + let Filter::HeightToNormal(filter) = filter_of(&harness, effect) else { panic!("still Height To Normal") }; + assert!(filter.intensity < 0.5, "{}", filter.intensity); +} + +/// The Color Match settings effect `effect` holds now +fn color_match_of(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> ColorMatch { + let Filter::ColorMatch(matcher) = filter_of(harness, effect) else { panic!("still Color Match") }; + matcher +} + +/// Color Match: Source Color Mode (a list: its three words don't fit a switch), Target Color Mode (a switch, a list where its words don't fit), Target Color, Custom Color Variation and its Color Variation card; each mode's color or image slot right under it, clicked through the pointer +#[test] +fn color_match_rows() { + let (mut harness, effect) = app_with("colorMatch", "content", TALL_WINDOW_HEIGHT); + + // Target Color Mode's control: its switch's segment, or its list where the words don't fit + let target_mode = |harness: &Harness<'_, TextureCraftApp>, shown: &str| { + harness + .query_all_by(|node| matches!(node.role(), Role::RadioButton | Role::ComboBox) && node.label().as_deref() == Some(shown)) + .map(|node| node.rect()) + .min_by(|a, b| a.top().total_cmp(&b.top())) + .unwrap() + }; + let rows = [ + harness.get_by_role_and_label(Role::ComboBox, "Average").rect(), + target_mode(&harness, "Parameter"), + harness.get_by_role_and_label(Role::Button, "Target Color").rect(), + harness.get_by_role_and_label(Role::CheckBox, "Custom Color Variation").rect(), + harness.get_by_role_and_label(Role::Slider, "Hue").rect(), + harness.get_by_role_and_label(Role::Slider, "Chroma").rect(), + harness.get_by_role_and_label(Role::Slider, "Luma").rect(), + ] + .map(|rect| rect.center().y); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); + assert!(harness.query_by_role_and_label(Role::Button, "Source Color").is_none(), "Average shows no Source Color"); + + pick(&mut harness, "Parameter", "Image Input"); + + assert_eq!(color_match_of(&harness, effect).target_mode, TargetColorMode::ImageInput); + assert!(harness.query_by_role_and_label(Role::Button, "Target Color").is_none(), "the Image Input slot replaces Target Color"); + let shown = harness.query_all_by_label("Image Input").count(); + assert!(shown >= 2, "the mode and its slot: {shown}"); + + // The source list's own Parameter row (not a control showing Parameter) + let list = harness.get_by_role_and_label(Role::ComboBox, "Average").rect(); + click_at(&mut harness, list.center()); + let row = harness + .query_all_by(|node| !matches!(node.role(), Role::RadioButton | Role::ComboBox) && node.label().as_deref() == Some("Parameter")) + .map(|node| node.rect()) + .find(|rect| rect.top() >= list.bottom() - 1.0) + .unwrap(); + click_at(&mut harness, row.center()); + + assert_eq!(color_match_of(&harness, effect).source_mode, SourceColorMode::Parameter); + let source = harness.get_by_role_and_label(Role::Button, "Source Color").rect(); + assert!(source.center().y < target_mode(&harness, "Image Input").center().y, "Source Color right under its mode"); + + let luma = harness.get_by_role_and_label(Role::Slider, "Luma").rect(); + click_at(&mut harness, along(luma, 1.0)); + assert!(color_match_of(&harness, effect).luma > 0.95, "{}", color_match_of(&harness, effect).luma); + + let custom = harness.get_by_role_and_label(Role::CheckBox, "Custom Color Variation").rect(); + click_at(&mut harness, custom.center()); + assert!(!color_match_of(&harness, effect).custom_variation); + assert!(harness.query_by_role_and_label(Role::Slider, "Hue").is_none(), "the Color Variation card goes with its switch"); +} diff --git a/crates/ui-egui/tests/it/filter_transform.rs b/crates/ui-egui/tests/it/filter_transform.rs new file mode 100644 index 00000000..38af6e79 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_transform.rs @@ -0,0 +1,86 @@ +//! The Transform filter in Properties: Scaling and Offset beside its preview, Tile Safe Rotation, Rotation, Repeat mode and Flip mode + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{Filter, FlipMode, RepeatMode, TileTransform}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, drag, filter_of, undo, undo_depth}; + +/// Every row sets its own setting through the pointer, in the reference's order +#[test] +fn transform_rows_set_the_transform() { + let (mut harness, effect) = app_with("transform", "mask", WINDOW_HEIGHT); + let transform = |harness: &Harness<'_, TextureCraftApp>| match filter_of(harness, effect) { + Filter::Transform(transform) => transform, + other => panic!("not a transform: {other:?}"), + }; + assert_eq!(transform(&harness), TileTransform::LIBRARY); + + let top = |harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str| harness.get_by_role_and_label(role, label).rect().top(); + let order = [ + top(&harness, Role::Slider, "Scaling"), + top(&harness, Role::Slider, "Offset"), + top(&harness, Role::CheckBox, "Tile Safe Rotation"), + top(&harness, Role::Slider, "Rotation"), + top(&harness, Role::ComboBox, "Horizontally & Vertically"), + top(&harness, Role::ComboBox, "None"), + ]; + assert!(order.windows(2).all(|pair| pair[0] < pair[1]), "Scaling, Offset, Tile Safe Rotation, Rotation, Repeat mode, Flip mode: {order:?}"); + + // Linked, the Scaling track sets both directions + let scaling = harness.get_by_role_and_label(Role::Slider, "Scaling").rect(); + click_at(&mut harness, along(scaling, 1.0)); + + let scaled = transform(&harness).scaling; + assert!(scaled[0] > 4.5 && scaled[0] == scaled[1], "{scaled:?}"); + + let offset = harness.get_by_role_and_label(Role::Slider, "Offset").rect(); + click_at(&mut harness, along(offset, 1.0)); + + let moved = transform(&harness).offset; + assert!(moved[0] > 0.95 && moved[1] == 0.0, "the first Offset slider moves across: {moved:?}"); + + let tile_safe = harness.get_by_role_and_label(Role::CheckBox, "Tile Safe Rotation").rect(); + click_at(&mut harness, tile_safe.center()); + + assert!(!transform(&harness).tile_safe); + + let rotation = harness.get_by_role_and_label(Role::Slider, "Rotation").rect(); + click_at(&mut harness, rotation.center()); + + let degrees = transform(&harness).rotation; + assert!((150.0..210.0).contains(°rees), "{degrees}"); + + let flip = harness.get_by_role_and_label(Role::ComboBox, "None").rect(); + click_at(&mut harness, flip.center()); + let vertically = harness.get_by_label("Vertically").rect(); + click_at(&mut harness, vertically.center()); + + assert_eq!(transform(&harness).flip, FlipMode::Vertically); + + let repeat = harness.get_by_role_and_label(Role::ComboBox, "Horizontally & Vertically").rect(); + click_at(&mut harness, repeat.center()); + let none = harness.get_by_label("None").rect(); + click_at(&mut harness, none.center()); + + assert_eq!(transform(&harness).repeat, RepeatMode::None); +} + +/// A Rotation drag is one undo step, and undo turns the tile back +#[test] +fn rotation_drag_is_one_undo_step() { + let (mut harness, effect) = app_with("transform", "mask", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + let rotation = harness.get_by_role_and_label(Role::Slider, "Rotation").rect(); + + drag(&mut harness, along(rotation, 0.0), along(rotation, 0.5)); + + let Filter::Transform(turned) = filter_of(&harness, effect) else { panic!() }; + assert!((150.0..210.0).contains(&turned.rotation), "{turned:?}"); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); + + undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::Transform(TileTransform::LIBRARY)); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 3e9a0d64..6cf3242b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -33,7 +33,6 @@ mod fill_projection_rows; mod fill_support; mod fill_symmetry_rows; mod filter_picker; -mod filter_support; mod folder_properties; mod frame_selection; mod generator_panel; @@ -66,6 +65,7 @@ mod pen_pressure; mod polygon_fill; mod popup_press_close; mod project_config; +mod properties_lists; mod properties_min_width; mod properties_popup; mod properties_scroll; @@ -101,6 +101,16 @@ mod view2d_tiles; mod view_mode_picker; mod window_menu_684; +mod filter_card; +mod filter_colour; +mod filter_gradient; +mod filter_inputs; +mod filter_light; +mod filter_shape; +mod filter_simple; +mod filter_stylize; +mod filter_support; +mod filter_transform; mod stencil; mod symmetry; mod symmetry_2d; diff --git a/crates/ui-egui/tests/it/properties_lists.rs b/crates/ui-egui/tests/it/properties_lists.rs new file mode 100644 index 00000000..ef3bcb47 --- /dev/null +++ b/crates/ui-egui/tests/it/properties_lists.rs @@ -0,0 +1,265 @@ +//! Every list in each Properties screen, through real pointer input: a click opens it; with it open the view still zooms on the wheel, pans on a middle drag and orbits on an Alt drag; Escape, a click outside and a stroke on the model close it + +use egui::accesskit::Role; +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, Vec2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{Session, StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::fill_support::{click_node, fill_app}; +use crate::filter_support::click_at; +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, PROPERTIES_WINDOW, REDRAW_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, WHEEL_NOTCH}; + +/// Moves of a drag in the view, each a few points, so it is a drag well before its release +const DRAG_MOVES: usize = 6; + +/// A drag in the view: long enough to move the camera, short enough to stay in the view +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; + +/// Escapes between lists, so one that stays open can't leave its popup over the next +const ESCAPES_TO_CLEAR: usize = 2; + +/// The Properties screen a `setup` leaves selected in the sample session +fn screen(setup: impl FnOnce(&mut Session)) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + setup(&mut session); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_accessibility_check(false).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// A new fill layer with a white mask, `command` adding an effect with `params` to its `target` stack, and that effect selected +fn with_effect(session: &mut Session, target: &str, command: &str, params: Value) { + let layer = execute(session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(session, "mask.add.white", &json!({"layer": layer})).unwrap(); + let mut params = params; + params["layer"] = json!(layer); + params["target"] = json!(target); + let effect = execute(session, command, ¶ms).unwrap()["effect"].as_u64().unwrap(); + execute(session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(LayerId(effect)); +} + +/// The screens with lists in Properties, each named for the failure messages +fn screens() -> Vec<(&'static str, Harness<'static, TextureCraftApp>)> { + vec![ + ("paint tool", screen(|_| {})), + ( + "fill layer", + screen(|session| { + execute(session, "layer.add.fill", &json!({})).unwrap(); + }), + ), + ( + "folder", + screen(|session| { + let folder = execute(session, "layer.add.group", &json!({})).unwrap()["layer"].clone(); + execute(session, "layer.select", &json!({"layer": folder, "target": "content"})).unwrap(); + }), + ), + ("mask fill", screen(|session| with_effect(session, "mask", "effect.add.fill", json!({})))), + ("mask paint", screen(|session| with_effect(session, "mask", "effect.add.paint", json!({})))), + ("colour selection", screen(|session| with_effect(session, "mask", "effect.add.colorSelection", json!({})))), + ("compare mask", screen(|session| with_effect(session, "mask", "effect.add.compare", json!({})))), + ("levels", screen(|session| with_effect(session, "content", "effect.add.levels", json!({})))), + ("generator", screen(|session| with_effect(session, "mask", "effect.add.generator", json!({"generator": "curvature"})))), + ("blur filter", screen(|session| with_effect(session, "content", "effect.add.filter", json!({"filter": "blur"})))), + ("gradient filter", screen(|session| with_effect(session, "content", "effect.add.filter", json!({"filter": "gradient"})))), + ("warp filter", screen(|session| with_effect(session, "mask", "effect.add.filter", json!({"filter": "warp"})))), + ] +} + +/// The lists right of the view (the docked panels), top to bottom, each as its rect and what it shows +fn lists(harness: &Harness<'_, TextureCraftApp>) -> Vec<(Rect, String)> { + let view = harness.state().viewport_rect; + let window = Rect::from_min_size(Pos2::ZERO, PROPERTIES_WINDOW); + let mut lists: Vec<(Rect, String)> = harness + .query_all_by_role(Role::ComboBox) + .filter(|node| node.rect().left() >= view.right() && window.contains_rect(node.rect())) + .map(|node| (node.rect(), format!("{:?} = {:?}", node.accesskit_node().label(), node.value()))) + .collect(); + lists.sort_by(|(a, _), (b, _)| a.top().total_cmp(&b.top()).then(a.left().total_cmp(&b.left()))); + lists +} + +/// A `button` press at `from` dragged by `by` in small moves, then released, with `modifiers` held +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, by: Vec2, button: PointerButton, modifiers: Modifiers) { + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button, pressed: true, modifiers }); + harness.run_steps(DRAG_STEP_FRAMES); + for step in 1..=DRAG_MOVES { + harness.hover_at(from + by * (step as f32 / DRAG_MOVES as f32)); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers }); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(SETTLE_FRAMES); +} + +/// One wheel notch at `at` +fn wheel(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, WHEEL_NOTCH), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }); + harness.run_steps(REDRAW_FRAMES); +} + +/// Whether one wheel notch at `at` zooms the camera +fn zooms(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) -> bool { + let distance = harness.state().session.camera.distance; + wheel(harness, at); + harness.state().session.camera.distance != distance +} + +/// Whether a middle drag from `from` pans the camera +fn pans(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2) -> bool { + let target = harness.state().session.camera.target; + drag(harness, from, GESTURE, PointerButton::Middle, Modifiers::NONE); + harness.state().session.camera.target != target +} + +/// Whether an Alt drag from `from` orbits the camera +fn orbits(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2) -> bool { + let yaw = harness.state().session.camera.yaw; + drag(harness, from, GESTURE, PointerButton::Primary, Modifiers::ALT); + harness.state().session.camera.yaw != yaw +} + +/// Where the gestures start in the view: clear of the lists, which open beside Properties +fn gesture_start(harness: &Harness<'_, TextureCraftApp>) -> Pos2 { + let view = harness.state().viewport_rect; + view.left_center() + vec2(view.width() * GESTURE_SHARE, 0.0) +} + +fn is_open(harness: &Harness<'_, TextureCraftApp>) -> bool { + egui::Popup::is_any_open(&harness.ctx) +} + +/// Opens the list at `button` with a click; false when it did not open +fn open(harness: &mut Harness<'_, TextureCraftApp>, button: Rect) -> bool { + click_at(harness, button.center()); + harness.run_steps(SETTLE_FRAMES); + is_open(harness) +} + +/// What goes wrong with the list at `button`, each a line naming it +fn check_list(harness: &mut Harness<'_, TextureCraftApp>, button: Rect, name: &str) -> Vec { + let mut problems = Vec::new(); + let gesture_start = gesture_start(harness); + if !open(harness, button) { + return vec![format!("{name}: a click does not open it")]; + } + + if !zooms(harness, gesture_start) { + problems.push(format!("{name}: the wheel over the view does not zoom while it is open")); + } + + // Each gesture starts with the list open, whatever the one before did to it + if !is_open(harness) && !open(harness, button) { + return [problems, vec![format!("{name}: it does not open again after the wheel")]].concat(); + } + if !pans(harness, gesture_start) { + problems.push(format!("{name}: a middle drag in the view does not pan while it is open")); + } + + // A middle drag may close it, as a click outside does; the orbit is checked with it open again + if !is_open(harness) && !open(harness, button) { + return [problems, vec![format!("{name}: a second click does not open it")]].concat(); + } + if !orbits(harness, gesture_start) { + problems.push(format!("{name}: an Alt drag in the view does not orbit while it is open")); + } + + if !is_open(harness) && !open(harness, button) { + return [problems, vec![format!("{name}: it does not open again")]].concat(); + } + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + if is_open(harness) { + problems.push(format!("{name}: Escape does not close it")); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + } + + if open(harness, button) { + click_at(harness, gesture_start); + if is_open(harness) { + problems.push(format!("{name}: a click in the view does not close it")); + } + } + + if !is_open(harness) && open(harness, button) { + drag(harness, gesture_start, GESTURE, PointerButton::Primary, Modifiers::NONE); + if is_open(harness) { + problems.push(format!("{name}: a stroke on the model does not close it")); + } + } + problems +} + +#[test] +fn every_list_opens_leaves_the_view_its_camera_and_closes_on_escape_a_click_and_a_stroke_outside() { + let mut problems = Vec::new(); + for (screen, mut harness) in screens() { + let count = lists(&harness).len(); + assert!(count > 0, "{screen}: lists show"); + for index in 0..count { + // Looked up again each time: a closed list or a stroke may move the rows below + let Some((button, shown)) = lists(&harness).get(index).cloned() else { + problems.push(format!("{screen}: list {index} of {count} is gone")); + continue; + }; + + problems.extend(check_list(&mut harness, button, &format!("{screen}: {shown}"))); + for _ in 0..ESCAPES_TO_CLEAR { + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + } + } + } + assert!(problems.is_empty(), "{}", problems.join("\n")); +} + +#[test] +fn the_colour_picker_window_and_the_symmetry_settings_leave_the_view_its_wheel_middle_drag_and_alt_orbit() { + let (mut harness, _) = fill_app(json!({"color": [0.2, 0.2, 0.2]}), None, Some("Material"), PROPERTIES_WINDOW); + click_node(&mut harness, Role::Button, "Base color"); + let start = gesture_start(&harness); + let picker_open = |harness: &Harness<'_, TextureCraftApp>| harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(); + assert!(picker_open(&harness), "the colour bar opens its picker"); + assert!(zooms(&mut harness, start), "the wheel over the view zooms with the picker open"); + assert!(pans(&mut harness, start), "a middle drag pans with the picker open"); + assert!(orbits(&mut harness, start), "an Alt drag orbits with the picker open"); + assert!(picker_open(&harness), "the picker stays open through the camera moves, as a window beside the panel"); + + let mut harness = screen(|_| {}); + + // The paint controls overflow the bar at this width; its arrow brings the Symmetry buttons into view + harness.get_by_label("Scroll right").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(SETTLE_FRAMES); + let settings_open = |harness: &Harness<'_, TextureCraftApp>| harness.query_by_label("Radial symmetry").is_some(); + assert!(settings_open(&harness), "the settings open"); + let start = gesture_start(&harness); + assert!(zooms(&mut harness, start), "the wheel over the view zooms with the symmetry settings open"); + assert!(settings_open(&harness), "the wheel leaves the settings open"); + assert!(pans(&mut harness, start), "a middle drag pans with the symmetry settings open"); + assert!(orbits(&mut harness, start), "an Alt drag orbits with the symmetry settings open"); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 9d45eed0..f733e8a7 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -2208,6 +2208,68 @@ fn layer_toolbar_snapshots() { } } +/// Screen 12: the Filter effect: empty, Blur on a mask, Slope Blur on the content (pills, Seed, Intensity's chip), its Divider list open, Restore defaults hovered +#[test] +#[ignore] +fn filter_card_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + 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 layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let add = |session: &mut texturecraft_engine::Session, params: serde_json::Value| { + LayerId(execute(session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let empty = add(&mut session, json!({"layer": layer, "target": "content", "filter": "none"})); + let blur = add(&mut session, json!({"layer": layer, "target": "mask", "filter": "blur"})); + let slope = add(&mut session, json!({"layer": layer, "target": "content", "filter": "slopeBlur", "seed": 12})); + execute(&mut session, "effect.set", &json!({"effect": slope.0, "divider": 10, "channels": {"metallic": false, "normal": false}})).unwrap(); + let invert = add(&mut session, json!({"layer": layer, "target": "content", "filter": "invert"})); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(empty); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + + // Add filter opens the picker; a filter selected from its row does not + save(&mut harness, &output_dir, "filter-empty"); + harness.state_mut().session.target = StackTarget::Effect(blur); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-blur-mask"); + harness.state_mut().session.target = StackTarget::Effect(invert); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-invert-content"); + harness.state_mut().session.target = StackTarget::Effect(slope); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-slope"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-slope-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + harness.get_by_role_and_label(egui::Role::ComboBox, "Blur").click(); + harness.run_steps(3); + let option = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Max").rect().center(); + harness.hover_at(option); + save(&mut harness, &output_dir, "filter-slope-blending-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + let reset = harness.get_by_role_and_label(egui::Role::Button, "Restore defaults").rect().center(); + harness.hover_at(reset); + save(&mut harness, &output_dir, "filter-reset-hovered"); + harness.get_by_role_and_label(egui::Role::ComboBox, "÷10").click(); + harness.run_steps(3); + let option = harness.get_by_role_and_label(egui::Role::ListBoxOption, "÷100").rect().center(); + harness.hover_at(option); + save(&mut harness, &output_dir, "filter-divider-open"); +} + #[test] #[ignore = "writes the material picker (Material mode) to TC_UI_SNAPSHOTS; run with --ignored"] /// A whole-material fill's card opens the material picker: grouped under its categories, Copper chosen and Brass hovered, then a search @@ -2250,6 +2312,585 @@ fn material_picker_snapshots() { } } +#[test] +#[ignore = "writes the colour filters (screen 18) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 18: Color Balance, Color Correct, HSL Perceptive and Contrast Luminosity with the mock's values, one knob hovered +fn colour_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + 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 layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let mut add = |params: serde_json::Value| { + let mut params = params; + params["layer"] = layer.clone(); + params["target"] = json!("content"); + LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let effects = [ + ("colour-balance", add(json!({"filter": "colorBalance", "highlights": [0.0, 0.0, -0.2], "midtones": [0.25, 0.0, 0.0], "shadows": [0.0, -0.1, 0.0]}))), + ("colour-correct", add(json!({"filter": "colorCorrect", "shadows": [0.0, 0.1, 0.5], "midtones": [0.2, 0.0, 0.6], "highlights": [0.0, -0.1, 0.5]}))), + ("hsl", add(json!({"filter": "hsl", "hue": 0.12, "saturation": 0.0, "lightness": -0.1}))), + ("contrast-luminosity", add(json!({"filter": "contrastLuminosity", "contrast": 0.3}))), + ]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(4); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + harness.state_mut().session.target = StackTarget::Effect(effects[2].1); + harness.run_steps(4); + let hue = harness.get_by_role_and_label(egui::Role::Slider, "Hue").rect(); + harness.hover_at(egui::pos2(hue.left() + hue.width() * 0.62, hue.center().y)); + save(&mut harness, &output_dir, "filter-hsl-hovered"); + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-colour-balance-{theme}")); + } + } +} + +#[test] +#[ignore = "writes the gradient filters (screen 19) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 19: Gradient, Gradient Curve (and its Preset list open, Bump hovered) and Gradient Dynamic +fn gradient_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + 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 layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |params: serde_json::Value| { + let mut params = params; + params["layer"] = layer.clone(); + params["target"] = json!("mask"); + LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let stops = json!([[0.009, 0.008, 0.013], [0.55, 0.105, 0.021], [0.87, 0.67, 0.35]]); + let effects = [ + ("gradient", add(json!({"filter": "gradientMap", "colors": stops, "positions": [0.0, 0.45, 1.0]}))), + ("gradient-curve", add(json!({"filter": "gradientCurve"}))), + ("gradient-dynamic", add(json!({"filter": "gradientDynamic", "color": [0.578, 0.578, 0.578]}))), + ]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(4); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + harness.state_mut().session.target = StackTarget::Effect(effects[1].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Round").click(); + harness.run_steps(3); + let bump = harness.get_by_label("Bump").rect(); + harness.hover_at(bump.center()); + save(&mut harness, &output_dir, "filter-gradient-curve-presets"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + let marker = harness.get_all_by_role_and_label(egui::Role::Slider, "Color 2").next().unwrap().rect(); + harness.hover_at(marker.center()); + save(&mut harness, &output_dir, "filter-gradient-marker-hovered"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-gradient-{theme}")); + } + } +} + +#[test] +#[ignore = "writes the light and shadow filters (screen 20) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 20: Glow (and its Width hovered) and Drop Shadow +fn light_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + 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 layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |filter: &str| { + let params = json!({"layer": layer.clone(), "target": "mask", "filter": filter}); + LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let effects = [("glow", add("glow")), ("drop-shadow", add("dropShadow"))]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + let distance = harness.get_by_role_and_label(egui::Role::Slider, "Distance").rect(); + harness.hover_at(distance.center()); + save(&mut harness, &output_dir, "filter-drop-shadow-hovered"); + harness.get_by_role_and_label(egui::Role::Button, "Color").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-drop-shadow-color-picker"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-glow-{theme}")); + } + } + + // Baked Lighting Stylized on content, in a window tall enough for all its cards, then its Output list open + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let params = json!({"layer": layer.clone(), "target": "content", "filter": "bakedLighting"}); + let lighting = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); + let params = json!({"layer": layer.clone(), "target": "content", "filter": "bakedLightingEnvironment"}); + let environment = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(lighting); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 2600.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(8); + save(&mut harness, &output_dir, "filter-baked-lighting-stylized"); + let output = harness.get_by_role_and_label(egui::Role::ComboBox, "Diffuse + Specular").rect(); + harness.hover_at(output.center()); + harness.get_by_role_and_label(egui::Role::ComboBox, "Diffuse + Specular").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-baked-lighting-stylized-output-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-baked-lighting-stylized-{theme}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + + // Baked Lighting Environment, then hovering its stacked Specular Occlusion Intensity + harness.state_mut().session.target = StackTarget::Effect(environment); + harness.run_steps(8); + save(&mut harness, &output_dir, "filter-baked-lighting-environment"); + let specular = harness.get_by_role_and_label(egui::Role::Slider, "Specular Occlusion Intensity").rect(); + harness.hover_at(specular.center()); + save(&mut harness, &output_dir, "filter-baked-lighting-environment-hovered"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-baked-lighting-environment-{theme}")); + } + } +} + +#[test] +#[ignore = "writes the shape filters (screen 21) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 21: Mirror in each mode (its Mode list open), Mask Outline, Threshold (its Mode hovered) +fn shape_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + 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 layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |filter: &str, settings: serde_json::Value| { + let params = json!({"layer": layer.clone(), "target": "mask", "filter": filter}); + let effect = execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap(); + let mut settings = settings; + settings["effect"] = json!(effect); + execute(&mut session, "effect.set", &settings).unwrap(); + LayerId(effect) + }; + let effects = [ + ("mirror-axis-x", add("mirror", json!({}))), + ("mirror-axis-y", add("mirror", json!({"mode": "axisY"}))), + ("mirror-corner", add("mirror", json!({"mode": "corner"}))), + ("mask-outline", add("maskOutline", json!({}))), + ("bevel", add("bevel", json!({}))), + ("bevel-smooth", add("bevelSmooth", json!({}))), + ("directional-distance", add("directionalDistance", json!({}))), + ("threshold", add("threshold", json!({}))), + ("warp", add("warp", json!({}))), + ("warp-directional", add("warp", json!({"warpMode": "directional"}))), + ("warp-multi-directional", add("warp", json!({"warpMode": "multiDirectional"}))), + ("transform", add("transform", json!({"scaling": [2.0, 2.0], "offset": [0.25, 0.0], "rotation": 30.0}))), + ("transform-plain", add("transform", json!({"repeatMode": "none", "scaling": [1.5, 1.5], "tileSafeRotation": false, "rotation": 20.0}))), + ]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + let shown = |name: &str| effects.iter().find(|(shown, _)| *shown == name).map(|(_, effect)| *effect).unwrap(); + harness.state_mut().session.target = StackTarget::Effect(shown("threshold")); + harness.run_steps(4); + let mode = harness.get_by_role_and_label(egui::Role::RadioButton, "≥").rect(); + harness.hover_at(mode.center()); + save(&mut harness, &output_dir, "filter-threshold-hovered"); + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Mirror Axis X").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-mirror-mode-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + + // Warp's mode list (under the filter card, also named Warp) and Multi Directional Warp's Blending Mode list, open + harness.state_mut().session.target = StackTarget::Effect(shown("warp")); + harness.run_steps(4); + let lists = harness.query_all_by_role_and_label(egui::Role::ComboBox, "Warp"); + lists.max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-warp-mode-list"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(shown("warp-multi-directional")); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Average").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-warp-blending-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + + // Transform's Flip mode and Repeat mode lists, open with a choice hovered + harness.state_mut().session.target = StackTarget::Effect(shown("transform")); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "None").click(); + harness.run_steps(4); + harness.hover_at(harness.get_by_label("Vertically").rect().center()); + harness.run_steps(2); + save(&mut harness, &output_dir, "filter-transform-flip-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Horizontally & Vertically").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-transform-repeat-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + for name in ["mirror-axis-x", "mask-outline", "bevel", "bevel-smooth", "warp-multi-directional", "transform"] { + harness.state_mut().session.target = StackTarget::Effect(shown(name)); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}-{theme}")); + } + } + } +} + +#[test] +#[ignore = "writes the simple filters (screen 23) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 23: Clamp, Smoothstep, Invert, Height Adjust, Histogram Scan, Histogram Shift, Sharpen and Posterize, one hovered switch +fn simple_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + 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 layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |filter: &str| { + let params = json!({"layer": layer.clone(), "target": "mask", "filter": filter}); + LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let effects = [ + "clamp", + "smoothstep", + "invert", + "heightAdjust", + "histogramScan", + "histogramShift", + "sharpen", + "posterize", + "pixelate", + "fxaa", + "blur", + "blurDirectional", + "highPass", + "grayscale", + "anisotropicKuwahara", + ] + .map(|id| (id, add(id))); + + // PBR Validate goes on the layer content (its Color and Metal pills) + let params = json!({"layer": layer.clone(), "target": "content", "filter": "pbrValidate"}); + let pbr = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); + + // Height To Normal too (its Normal pill), once with world units and once without + let params = json!({"layer": layer.clone(), "target": "content", "filter": "heightToNormal"}); + let normals = [(); 2].map(|_| LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap())); + execute(&mut session, "effect.set", &json!({"effect": normals[1].0, "useWorldUnits": false})).unwrap(); + + // Color Match too (its Color pill): a new one, and one reading its Input and Image Input + let params = json!({"layer": layer.clone(), "target": "content", "filter": "colorMatch"}); + let matches = [(); 2].map(|_| LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap())); + execute(&mut session, "effect.set", &json!({"effect": matches[1].0, "sourceColorMode": "input", "targetColorMode": "imageInput"})).unwrap(); + + // Replace Color too (its two colour bars) + let params = json!({"layer": layer.clone(), "target": "content", "filter": "replaceColor"}); + let replace = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + let shown = |name: &str| effects.iter().find(|(shown, _)| *shown == name).map(|(_, effect)| *effect).unwrap(); + harness.state_mut().session.target = StackTarget::Effect(shown("posterize")); + harness.run_steps(4); + let alpha = harness.get_by_role_and_label(egui::Role::CheckBox, "Apply to Alpha").rect(); + harness.hover_at(alpha.center()); + save(&mut harness, &output_dir, "filter-posterize-hovered"); + harness.state_mut().session.target = StackTarget::Effect(shown("highPass")); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Working space / Mask").click(); + harness.run_steps(2); + harness.get_by_label("sRGB (from ACEScg)").hover(); + save(&mut harness, &output_dir, "filter-highPass-open"); + harness.key_press(egui::Key::Escape); + let custom = json!({"effect": shown("grayscale").0, "channelInput": "customInput"}); + execute(&mut harness.state_mut().session, "effect.set", &custom).unwrap(); + harness.state_mut().session.target = StackTarget::Effect(shown("grayscale")); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-grayscale-custom"); + let custom = json!({"effect": shown("anisotropicKuwahara").0, "extractDirection": "customInput"}); + execute(&mut harness.state_mut().session, "effect.set", &custom).unwrap(); + harness.state_mut().session.target = StackTarget::Effect(shown("anisotropicKuwahara")); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-anisotropicKuwahara-custom"); + harness.state_mut().session.target = StackTarget::Effect(pbr); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-pbrValidate"); + let metal = harness.get_by_role_and_label(egui::Role::RadioButton, "70-100% Reflective").rect(); + harness.hover_at(metal.center()); + save(&mut harness, &output_dir, "filter-pbrValidate-hovered"); + for (effect, name) in normals.into_iter().zip(["heightToNormal", "heightToNormal-intensity"]) { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + let world = harness.get_by_role_and_label(egui::Role::CheckBox, "Use World Units").rect(); + harness.hover_at(world.center()); + save(&mut harness, &output_dir, "filter-heightToNormal-hovered"); + for (effect, name) in matches.into_iter().zip(["colorMatch", "colorMatch-inputs"]) { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + harness.state_mut().session.target = StackTarget::Effect(matches[0]); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Average").click(); + harness.run_steps(2); + harness.get_by_label("Input").hover(); + save(&mut harness, &output_dir, "filter-colorMatch-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.state_mut().session.target = StackTarget::Effect(replace); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-replaceColor"); + harness.get_by_role_and_label(egui::Role::Button, "Replacement color").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-replaceColor-picker"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + for name in ["heightAdjust", "histogramScan", "pixelate", "blurDirectional", "highPass", "grayscale", "anisotropicKuwahara"] { + harness.state_mut().session.target = StackTarget::Effect(shown(name)); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}-{theme}")); + } + harness.state_mut().session.target = StackTarget::Effect(pbr); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-pbrValidate-{theme}")); + harness.state_mut().session.target = StackTarget::Effect(normals[0]); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-heightToNormal-{theme}")); + harness.state_mut().session.target = StackTarget::Effect(matches[0]); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-colorMatch-{theme}")); + } + } +} + +#[test] +#[ignore = "writes the filter image inputs (screen 22) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 22: Bevel Smooth's Distance Map uniform, read from an anchor point and its picker open; Warp's Custom Noise from a pattern +fn image_input_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + 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(); + execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"name": "Cavity Dirt mask"})).unwrap()["effect"].clone(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |filter: &str, settings: serde_json::Value, input: serde_json::Value| { + let params = json!({"layer": layer.clone(), "target": "mask", "filter": filter}); + let effect = execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap(); + let mut settings = settings; + settings["effect"] = json!(effect); + execute(&mut session, "effect.set", &settings).unwrap(); + if !input.is_null() { + let mut input = input; + input["effect"] = json!(effect); + execute(&mut session, "layer.fill.set", &input).unwrap(); + } + LayerId(effect) + }; + let effects = [ + ("bevel-smooth-uniform", add("bevelSmooth", json!({}), serde_json::Value::Null)), + ("bevel-smooth-anchor", add("bevelSmooth", json!({}), json!({"input": "distanceMap", "anchor": anchor}))), + ("warp-custom-noise", add("warp", json!({"sourceMode": "customNoise"}), json!({"input": "customNoise", "procedural": "clouds"}))), + ("blur-changed", add("blur", json!({"radius": 12.0, "wrap": true}), serde_json::Value::Null)), + ]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 2200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Distance Map").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-distance-map-picker"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + + // Blur with Attributes open, then its Parameters reset hovered (Restore defaults named over it) + harness.state_mut().session.target = StackTarget::Effect(effects[3].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Button, "Attributes").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-attributes-open"); + harness.get_by_role_and_label(egui::Role::Button, "Attributes").click(); + harness.run_steps(4); + let reset = harness.get_by_role_and_label(egui::Role::Button, "Restore defaults").rect().center(); + harness.set_render_cursor(false); + harness.hover_at(reset); + harness.run_steps(60); + save(&mut harness, &output_dir, "filter-restore-defaults-hover"); + harness.set_render_cursor(true); + harness.hover_at(egui::pos2(1.0, 1.0)); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.state_mut().session.target = StackTarget::Effect(effects[3].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Button, "Attributes").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-attributes-open-{theme}")); + harness.get_by_role_and_label(egui::Role::Button, "Attributes").click(); + harness.run_steps(4); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}-{theme}")); + } + } + } +} + +#[test] +#[ignore = "writes the filter picker states (screen 13) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 13: the filter picker opened from an empty card, swapping (current outlined), searching, and in a mask +fn filter_picker_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + 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 layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let add = |session: &mut texturecraft_engine::Session, params: serde_json::Value| { + LayerId(execute(session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let empty = add(&mut session, json!({"layer": layer, "target": "content", "filter": "none"})); + let slope = add(&mut session, json!({"layer": layer, "target": "content", "filter": "slopeBlur"})); + execute(&mut session, "effect.set", &json!({"effect": slope.0, "channels": {"metallic": false, "normal": false}})).unwrap(); + let masked = add(&mut session, json!({"layer": layer, "target": "mask", "filter": "none"})); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(empty); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + let open = |harness: &mut Harness<'_, TextureCraftApp>, card: &str, hover: &str| { + harness.get_by_role_and_label(egui::Role::ComboBox, card).click(); + settle_thumbnails(harness); + let tile = harness.get_by_role_and_label(egui::Role::ListBoxOption, hover).rect().center(); + harness.hover_at(tile); + }; + open(&mut harness, "Filter", "Blur"); + save(&mut harness, &output_dir, "filter-picker-new"); + harness.event(egui::Event::Text("blur".into())); + harness.hover_at(egui::pos2(1.0, 1.0)); + save(&mut harness, &output_dir, "filter-picker-search"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(slope); + harness.run_steps(4); + open(&mut harness, "Blur Slope", "Clamp"); + save(&mut harness, &output_dir, "filter-picker-swapping"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(masked); + harness.run_steps(4); + open(&mut harness, "Filter", "Bevel"); + save(&mut harness, &output_dir, "filter-picker-mask"); +} + /// The Properties panel at its minimum width (the right column dragged as narrow as it goes), on the Fill tab's widest row (3D projection settings) and on a filter #[test] #[ignore] @@ -2280,6 +2921,7 @@ fn properties_min_width_snapshot() { } harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "hsl"})).unwrap(); + execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "colorMatch"})).unwrap(); save(&mut harness, &output_dir, "properties-min-width-filter"); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9b88b0f8..bc2cc695 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -589,13 +589,16 @@ with `material.apply` instead. The fill remembers the material (`Fill.material`, - `effect.blending.modeToEveryChannel`, `opacityToEveryChannel` and `bothToEveryChannel {effect?, channel?}` give every channel of a content effect one channel's blend mode, opacity or both; `effect.blending.copy` and `effect.blending.paste {effect?}` carry every channel's blending between effects (a mask effect takes - the shared one). `effect.set {effect, channel, blend?, opacity?}` sets one channel's blending. + the shared one). `effect.set {effect, channel, blend?, opacity?}` sets one channel's blending and + `effect.set {effect, channels: {roughness: false}}` switches a content effect's channels on or off. - `mask.add.bitmap {layer?, image | alpha, projection?}` adds a mask fill reading an image's gray; `effect.set {effect, idMap: image resource | null}` gives a colour selection its own ID map in place of the baked one; `tool.material {maskImage: image resource | null}` paints an image's gray into masks. - `effect.add.colorSelection {layer?, color?, tolerance?}` and `mask.add.heightCombination {layer?}` add a colour selection or a compare mask (this layer's height against the layers below) to a layer's mask, making the mask first when it has none; both return `{effect}`. +- `effect.filter.restoreDefaults {effect?}` puts a filter's parameters back to its defaults (name, + channels and blending stay) and returns `{changed}`. - `layer.fill.resetProjection {layer? | effect?}` puts the Fill section back to a new fill's (same projection kind; a placed frame, the symmetry and the sources stay); `layer.fill.resetFrame` puts a warp's frame back around the mesh with its corners unpulled. Each is one undo step, or none when From 7d8cbb658a681625702f1495d554053fbe3d5a39 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:30:01 +0000 Subject: [PATCH 4/6] Filters: the stand-ins parts 2-4 kept for the filter panel and the effect blend lookups go --- crates/compose/src/eval.rs | 10 ---------- crates/compose/tests/cache_and_instances.rs | 6 ------ crates/core/src/layer.rs | 7 ------- crates/core/src/lib.rs | 2 -- crates/core/src/project.rs | 1 - crates/engine/src/filter_lib.rs | 1 - crates/engine/src/folder_cmds.rs | 1 - crates/engine/src/layer_cmds.rs | 3 --- crates/engine/src/mask_cmds.rs | 1 - crates/engine/src/session.rs | 3 --- crates/engine/tests/it/filter_support.rs | 3 --- crates/engine/tests/it/folder_contents.rs | 1 - crates/engine/tests/it/resources_used.rs | 6 ------ crates/engine/tests/session.rs | 2 -- crates/render/src/ibl.rs | 1 - crates/ui-egui/src/dock.rs | 2 -- crates/ui-egui/src/fill_material_panel.rs | 1 - crates/ui-egui/src/filter_slot.rs | 1 - crates/ui-egui/src/layer_toolbar.rs | 2 -- crates/ui-egui/src/material_orb.rs | 5 ----- crates/ui-egui/src/property_sheet/row.rs | 3 --- crates/ui-egui/src/property_sheet/row_lead.rs | 1 - crates/ui-egui/src/property_sheet/slider.rs | 2 -- crates/ui-egui/src/property_sheet/switch_control.rs | 1 - crates/ui-egui/src/property_sheet/tests.rs | 1 - crates/ui-egui/src/source_slot.rs | 4 ---- crates/ui-egui/tests/it/filter_picker.rs | 2 -- crates/ui-egui/tests/ui_snapshots.rs | 1 - 28 files changed, 74 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index ffe4a3d3..6e7fb298 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -11,9 +11,6 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, - Filtering, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Sampling, - ShapeCrop, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, Project, Projection, @@ -1316,7 +1313,6 @@ fn field( for (((&filter, &margin), &wrap), &own_wrap) in filters.iter().zip(&margins).zip(&wrapping).zip(&own_wraps) { let region = region_around(inp, tiles, margin, wrap)?; let start = previous.as_ref().map(|(index, field)| (*index, field)); - let filtered = filter_region(inp, channels, below, (id, around), job, effects, filter, region, start)?; let filtered = filter_region(inp, channels, below, (id, around), job, effects, filter, own_wrap, region, start)?; // Preserve only stages with anchors before the next filter overwrites their value @@ -1437,7 +1433,6 @@ fn filter_region( }; let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); - let opacity = filter_effect.map(|effect| effect.blend_of(channel).opacity.clamp(0.0, 1.0)).unwrap_or(1.0); let filter = filter_effect.and_then(|effect| match &effect.kind { EffectKind::Filter(filter) => Some(filter), _ => None, @@ -2171,7 +2166,6 @@ fn effect_plans<'a>( } _ => (None, false), }; - let blend = effect.blend_of(channel); let environment = match &effect.kind { EffectKind::Filter(Filter::EnvironmentLighting { .. }) => Some(EnvironmentSh::of(&inp.project.display, inp.images)), _ => None, @@ -2554,7 +2548,6 @@ 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, 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 } } @@ -3547,7 +3540,6 @@ impl<'a, 'b> Texel<'a, 'b> { EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); - (mix3(value, value.map(|x| (x * factor).clamp(0.0, 1.0)), opacity), coverage) let lit = match &effect.stylized { Some(stylized) => { let nrm = self.lit_normal(stylized.relief()); @@ -4606,7 +4598,6 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti #[cfg(test)] mod tests { use super::*; - use texturecraft_core::{ChannelBlend, CompareOp, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; use texturecraft_core::{ ChannelBlend, CompareOp, Effect, Layer, OutputResolution, PbrValidate, Procedural, ProceduralKind, ResolutionMode, StylizedLighting, TextureSet, }; @@ -5930,7 +5921,6 @@ soft {soft:?}" }; let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(f.project.alloc_id(), compare)); - mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 2.0 }))); mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 2.0, wrap: true }))); f.project.layer_mut(top).unwrap().mask = Some(mask); diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index dea9f8d6..423b6975 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -10,7 +10,6 @@ use texturecraft_compose::{ use texturecraft_core::project::ENV_RESOURCE_PREFIX; use texturecraft_core::{ BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, ContentsOffset, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, - HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet, GrayscaleConversion, HeightMask, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet, }; @@ -673,7 +672,6 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { // Changing the hot mask must invalidate the retained fields let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap(); - blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0, wrap: false }); let (images, baked) = (Default::default(), Default::default()); cache.ahead = Vec::new(); @@ -961,7 +959,6 @@ fn flat_image(value: f32) -> std::sync::Arc { } #[test] -fn id_map_image_changes_invalidate_stack_key() { fn filter_input_and_id_map_image_changes_invalidate_stack_key() { let mut fixture = fixture(); heavy_stack(&mut fixture); @@ -980,7 +977,6 @@ fn filter_input_and_id_map_image_changes_invalidate_stack_key() { images.insert("input".into(), flat_image(0.1)); images.insert("id".into(), flat_image(0.1)); - images.insert("id".into(), flat_image(0.9)); for name in ["input", "id"] { let original = stack_key(&fixture, &images); images.insert(name.into(), flat_image(0.9)); @@ -988,7 +984,6 @@ fn filter_input_and_id_map_image_changes_invalidate_stack_key() { } } - assert!(stack_key(&fixture, &images) != original, "replacing the id image must invalidate the cache"); #[test] fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() { let mut fixture = fixture(); @@ -1027,7 +1022,6 @@ enum BlurOn { fn folder_of_blurred_clouds(f: &mut Fixture, ts: usize, folder: Option, blur_on: BlurOn) -> (LayerId, LayerId) { let held = put(f, ts, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None); let clouds = put(f, ts, Some(held), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None); - let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0 })); let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false })); match blur_on { BlurOn::Content => f.project.layer_mut(clouds).unwrap().content_effects.push(blur), diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index aee8f43d..1ff4e0fc 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -4,7 +4,6 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, CompareSource, ContentsOffset, DepthCulling, Projector, RandomizedSeed, ShapeCrop, lum}; use crate::curve_preset::CurvePreset; use crate::gradient_input::{GradientInput, ramp, shape_gray}; use crate::{ @@ -1321,7 +1320,6 @@ fn unit_divider() -> u16 { 1 } -/// Whether a switch is on, its default where it defaults to on (not saved then) /// Serde default of a switch that was on in projects saved before it existed fn yes() -> bool { true @@ -2057,7 +2055,6 @@ impl Layer { LayerKind::Fill(fill) => fill.sources.values().any(|source| source.reads_anchor(None)), _ => false, }; - fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.kind.reads(None)) fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.reads(None)) } @@ -2089,7 +2086,6 @@ pub struct Effect { impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { // Generators and fills that build a mask usually add on top of the background - Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0, channel_blends: BTreeMap::new() } Effect { id, name: kind.name().to_string(), @@ -2169,15 +2165,12 @@ mod tests { } #[test] - fn a_colour_selection_id_map_is_reported_as_used() { fn a_colour_selection_id_map_and_a_filter_image_input_are_reported_as_used() { let mut selection = crate::ColorSelection::new(Vec::new(), 0.0); selection.id_map = Some("id.png".into()); - let effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection)); let mut effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection)); effect.inputs.insert("mask".into(), Source::image("input.png")); - assert_eq!(effect.kind.images_read().collect::>(), vec!["id.png"]); assert_eq!(effect.images_read().collect::>(), vec!["id.png", "input.png"]); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ea2c1805..b05c708b 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,8 +111,6 @@ pub use image_input::ImageInput; pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, - OutputResolution, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Sampling, ScaleMode, Source, TileBlending, TileGenerator, - TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, posterize, diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 97d35be8..7dfcefca 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -652,7 +652,6 @@ impl Project { out.push((layer.id, None)); } let effects = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()); - out.extend(effects.filter(|e| e.kind.reads(Some(anchor))).map(|e| (layer.id, Some(e.id)))); out.extend(effects.filter(|e| e.reads(Some(anchor))).map(|e| (layer.id, Some(e.id)))); } out diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index b4a72c26..2cab1ad0 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -342,7 +342,6 @@ pub(crate) fn build_for(cmd: &str, id: &str, p: &Value) -> Result { "bakedLighting" => library_baked_lighting(), "bakedLightingEnvironment" => LIBRARY_ENVIRONMENT_LIGHTING, "levels" => { - crate::mask_cmds::levels_from(cmd, p, &mut l)?; let mut levels = Levels::default(); crate::mask_cmds::levels_from(cmd, p, &mut levels)?; return Ok(EffectKind::Levels(levels)); diff --git a/crates/engine/src/folder_cmds.rs b/crates/engine/src/folder_cmds.rs index 5b22cf50..4b0ce043 100644 --- a/crates/engine/src/folder_cmds.rs +++ b/crates/engine/src/folder_cmds.rs @@ -237,7 +237,6 @@ fn seed_count(layer: &Layer) -> usize { .map(|effect| match &effect.kind { EffectKind::Fill { source, .. } => usize::from(matches!(source, Source::Procedural { .. })), EffectKind::Material(fill) => fill_seeds(fill), - EffectKind::Generator(_) | EffectKind::Filter(Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. }) => 1, EffectKind::Generator(_) | EffectKind::Filter( Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. } | Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_), diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 61d2611e..1de76b29 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -3,8 +3,6 @@ use serde_json::{Value, json}; use texturecraft_core::{ - Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat, - Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, ImageInput, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; @@ -123,7 +121,6 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", "{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)} | {effect: filter effect id, input: image input id (distanceMap, customNoise), value?|procedural?|image?|alpha?|anchor? as a mask fill's source, or clear: true (back to its default gray)}", has_layer, fill_set diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 899f71cb..403459b5 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -98,7 +98,6 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 2f5ad634..241b5717 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -766,9 +766,6 @@ impl Session { previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); let added_resource_names: BTreeSet<&str> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect(); - let uses_added_resource = - |texture_set_index: usize| { - effect.kind.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill)) let uses_added_resource = |texture_set_index: usize| { use texturecraft_core::{EffectKind, Fill}; diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs index e37b8e79..16e2e0a0 100644 --- a/crates/engine/tests/it/filter_support.rs +++ b/crates/engine/tests/it/filter_support.rs @@ -1,8 +1,5 @@ -//! What the filter tests share: their sessions and reading the composite //! What the filter tests share: their sessions, adding, setting and refusing a filter, and reading the composite -use texturecraft_engine::Session; -use texturecraft_engine::core::Channel; use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId}; use texturecraft_engine::geom::glam::Vec2; diff --git a/crates/engine/tests/it/folder_contents.rs b/crates/engine/tests/it/folder_contents.rs index b517deea..f9c7d961 100644 --- a/crates/engine/tests/it/folder_contents.rs +++ b/crates/engine/tests/it/folder_contents.rs @@ -138,7 +138,6 @@ fn fill_seeds(s: &Session, id: LayerId) -> (u32, u32, u32) { other => panic!("not a pattern: {other:?}"), }; let warp = layer.mask.as_ref().unwrap().effects.iter().find_map(|effect| match effect.kind { - EffectKind::Filter(Filter::Warp { seed, .. }) => Some(seed), EffectKind::Filter(Filter::SourceWarp(warp)) => Some(warp.seed), _ => None, }); diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs index 5cb945c0..bd89ee77 100644 --- a/crates/engine/tests/it/resources_used.rs +++ b/crates/engine/tests/it/resources_used.rs @@ -1,4 +1,3 @@ -//! The images a project reads beyond fill sources: a colour selection's ID map, the mask brush and its paths //! The images a project reads beyond fill sources: a colour selection's ID map, a filter's image input, the mask brush and its paths use serde_json::{Value, json}; @@ -37,11 +36,8 @@ fn layer_reading(session: &mut Session, id_map: &str, input: &str) -> LayerId { } #[test] -fn removing_unused_resources_keeps_the_images_a_selection_the_mask_brush_and_a_path_read() { fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mask_brush_and_a_path_read() { let mut session = session(); - let [id_map, path, brush, unused] = ["id.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap()); - let layer = selecting_layer(&mut session, &id_map); let [id_map, input, path, brush, unused] = ["id.png", "input.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap()); let layer = layer_reading(&mut session, &id_map, &input); @@ -58,11 +54,9 @@ fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mas } #[test] -fn a_smart_material_carries_the_image_its_selection_reads() { fn a_smart_material_carries_the_images_its_selection_and_filter_input_read() { let mut session = session(); let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); - let layer = selecting_layer(&mut session, &id_map); let input = session.import_resource_bytes("input.png", white_png()).unwrap(); let layer = layer_reading(&mut session, &id_map, &input); let bytes = session.smart_material_bytes(layer, "Parts").unwrap(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 2802448b..62d4f7cd 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -279,10 +279,8 @@ fn gray_png() -> Vec { out } -/// Frame edits and frame and Fill section resets on the fills they act on (a planar, a warp and a decal mask) meet hostile values without panicking; a refused edit changes nothing and adds no undo step /// Frame edits, frame and Fill section resets and Transform filter settings on the fills they act on (a planar, a warp, a decal mask and a Transform filter) meet hostile values without panicking; a refused edit changes nothing and adds no undo step #[test] -fn panic_hunt_frames() { fn panic_hunt_frames_and_transforms() { let mut s = session(); let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index 57e5f87e..43c8f56c 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -68,7 +68,6 @@ impl EnvImage { if width == 0 || height == 0 || rgba.len() as u64 != width as u64 * height as u64 { return None; } - let data = pixels.par_iter().map(|p| [lin(p[0]), lin(p[1]), lin(p[2])]).collect(); let linear = |v: f32| environment_sky::environment_linear(v, srgb); let data = rgba.par_iter().map(|p| [linear(p[0]), linear(p[1]), linear(p[2])]).collect(); let mut img = EnvImage { width, height, data }; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 5248b0fb..89a6f43a 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,7 +6,6 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Filter, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, }; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; @@ -3138,7 +3137,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe tool_properties(app, ui); } }), - EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)), 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/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index 24a62cd4..f99000c2 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -427,7 +427,6 @@ fn procedural_rows( let mut edit = scale_and_contrast(sheet, &mut edited); // A grayscale's card (a mask fill's, a filter input's) shows its Balance and Seed with Scale and Contrast; a material channel's keeps them in Attributes - let gray = matches!(slot_of, SourceSlot::Grayscale); let gray = matches!(slot_of, SourceSlot::Grayscale | SourceSlot::Input(_)); if gray { edit = edit.or(balance_and_seed(sheet, &mut edited)); diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index daa99d27..8f4ea87e 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -40,7 +40,6 @@ pub(crate) fn picker(app: &mut TextureCraftApp, pick: &egui::Response, effect: u items.sort_by_cached_key(|item| item.label.to_lowercase()); vec![PickerTab { icon: ic::FUNNEL, name: tr("Filters"), groups: vec![PickerGroup { header: None, items }] }] }; - let picked = resource_picker::show(&response, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); let picked = resource_picker::show(pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); if let Some(id) = picked.filter(|id| Some(*id) != current) { app.run("effect.set", json!({"effect": effect, "filter": id})); diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 922eacd2..31716da3 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -89,8 +89,6 @@ const SHADOW_OFFSET: [i8; 2] = [3, 4]; const WHITE_SWATCH: u8 = 235; const BLACK_SWATCH: u8 = 10; -/// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it -pub(crate) const NEW_FILTER: &str = "hsl"; /// The filter Add filter adds: an empty one, which changes nothing until its slot's picker swaps a filter into it pub(crate) const NEW_FILTER: &str = texturecraft_engine::mask_cmds::EMPTY_FILTER; diff --git a/crates/ui-egui/src/material_orb.rs b/crates/ui-egui/src/material_orb.rs index 5b7e4a11..3e19aadd 100644 --- a/crates/ui-egui/src/material_orb.rs +++ b/crates/ui-egui/src/material_orb.rs @@ -4,7 +4,6 @@ use egui::{Color32, ColorImage, Painter, Rect, pos2}; use rayon::prelude::*; -use texturecraft_engine::core::Channel; use texturecraft_engine::core::{Channel, DIELECTRIC_REFLECTANCE}; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::texel::linear_to_srgb; @@ -21,9 +20,6 @@ const MAX_SIDE_PX: usize = 512; /// The sphere's radius in halves of the square const SPHERE_RADIUS: f32 = 0.84; -/// Reflectance of a non-metal seen face on -const DIELECTRIC_F0: f32 = 0.04; - /// The lowest roughness shaded (a perfect mirror aliases at orb sizes) const MIN_ROUGHNESS: f32 = 0.03; @@ -125,7 +121,6 @@ fn shade(material: &OrbMaterial, env: &OrbEnvironment, direction: Vec3, pixel: f let mut out = [0.0; 3]; for (channel, value) in out.iter_mut().enumerate() { let base = sample.base[channel].clamp(0.0, 1.0); - let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * metallic; let f0 = DIELECTRIC_REFLECTANCE + (base - DIELECTRIC_REFLECTANCE) * metallic; let specular = f0 * scale + bias; *value = diffuse_light[channel] * base * (1.0 - metallic) * (1.0 - specular) + specular_light[channel] * specular + sample.emissive[channel].max(0.0); diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs index f44b8045..ca9af0e1 100644 --- a/crates/ui-egui/src/property_sheet/row.rs +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -168,8 +168,6 @@ impl PropertySheet<'_> { let center_y = self.cursor_y() + ROW_HEIGHT / 2.0; let shift = self.lead_shift(); let label_x = self.left + shift + ROW_PICTURE_SIZE + ROW_PICTURE_AIR; - let (label, stack) = match lead { - RowLead::Label { text, stack } => (text, stack), let (label, stack, text_color) = match lead { RowLead::Label { text, stack } => (text, stack, self.tokens.text), RowLead::Tinted { text, color } => (text, false, color), @@ -200,7 +198,6 @@ impl PropertySheet<'_> { if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { self.paint_info(center_y); - self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text); self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); return self.column(); } diff --git a/crates/ui-egui/src/property_sheet/row_lead.rs b/crates/ui-egui/src/property_sheet/row_lead.rs index 84fc568d..4cfaaa77 100644 --- a/crates/ui-egui/src/property_sheet/row_lead.rs +++ b/crates/ui-egui/src/property_sheet/row_lead.rs @@ -28,7 +28,6 @@ impl<'a> RowLead<'a> { /// The row's name, as assistive tech reads it pub(crate) fn text(self) -> &'a str { match self { - RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) => text, RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) | RowLead::Tinted { text, .. } => text, } } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index aa8dde9c..a94831bc 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -1,13 +1,11 @@ use std::ops::RangeInclusive; -use egui::{Align2, Id, Rect, Sense, Stroke, WidgetInfo, pos2}; use egui::{Align2, Color32, CornerRadius, FontId, Id, Rect, Response, Sense, Stroke, StrokeKind, WidgetInfo, pos2}; use egui_phosphor::regular as ic; use super::number_field::shown_number; use super::track::Track; use super::value_text::ValueText; -use super::{PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, TEXT_SIZE}; use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index f0316e7d..f975c19d 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,6 +1,5 @@ use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; -use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, SMALL_TEXT_SIZE, TEXT_SIZE}; use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index adaeb900..a8727f95 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -329,7 +329,6 @@ fn card_under_caption(ui: &mut egui::Ui, state: &mut (bool, std::cell::Cell ChannelKind { match self { SourceSlot::Channel(channel) => channel.kind(), - SourceSlot::Grayscale => ChannelKind::Scalar, SourceSlot::Grayscale | SourceSlot::Input(_) => ChannelKind::Scalar, } } @@ -62,7 +59,6 @@ impl SourceSlot { const CHANNEL_ENDS: ([f32; 3], [f32; 3]) = ([0.2; 3], [0.8; 3]); match self { - SourceSlot::Grayscale => ([0.0; 3], [1.0; 3]), SourceSlot::Grayscale | SourceSlot::Input(_) => ([0.0; 3], [1.0; 3]), SourceSlot::Channel(Channel::BaseColor) => BASE_COLOR_ENDS, SourceSlot::Channel(Channel::Height) => HEIGHT_ENDS, diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 2dcee134..69244a47 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -56,11 +56,9 @@ fn escape_closes_the_picker_without_changes() { /// Opens the wand's Add effect menu and clicks Filter fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { - harness.get_by_role_and_label(Role::Button, "Add effect").click(); let at = harness.get_by_role_and_label(Role::Button, "Add effect").rect().center(); click_at(harness, at); - harness.get_by_role_and_label(Role::Button, "Filter").click(); let at = harness.get_by_role_and_label(Role::Button, "Filter").rect().center(); click_at(harness, at); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index f733e8a7..abe99bf3 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -2920,7 +2920,6 @@ fn properties_min_width_snapshot() { save(&mut harness, &output_dir, &format!("properties-min-width-planar-{name}")); } harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; - execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "hsl"})).unwrap(); execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "colorMatch"})).unwrap(); save(&mut harness, &output_dir, "properties-min-width-filter"); } From a99c37392c42e7ade7ade629556064812f2956b5 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 05:30:01 +0000 Subject: [PATCH 5/6] Filters: review repairs from #698 Chasse's repairs to this part's code, carried over from the #698 head (5644b7d3). --- crates/compose/src/below.rs | 2 + crates/compose/src/environment_sh.rs | 38 ++- crates/compose/src/environment_sky.rs | 35 +- crates/compose/src/eval.rs | 305 +++++++++++++----- crates/compose/src/eval/evaluation_inputs.rs | 45 +++ crates/compose/src/lib.rs | 1 + crates/compose/src/shape_distance.rs | 90 +++--- crates/compose/src/soft_box.rs | 13 +- crates/compose/tests/cache_and_instances.rs | 3 + crates/core/src/color_match.rs | 46 ++- crates/core/src/curve_preset.rs | 2 + crates/core/src/gradient_input.rs | 47 ++- crates/core/src/grayscale_conversion.rs | 3 + crates/core/src/image_input.rs | 1 + crates/core/src/layer.rs | 32 +- crates/core/src/lib.rs | 4 + crates/core/src/mask_outline.rs | 2 + crates/core/src/mirror.rs | 5 + crates/core/src/prepared_color_match.rs | 35 ++ crates/core/src/prepared_gradient.rs | 35 ++ crates/core/src/source_warp.rs | 6 + crates/core/src/stylized_lighting.rs | 3 + crates/core/src/stylized_shading.rs | 34 +- crates/core/src/threshold_mode.rs | 3 + crates/core/src/tile_transform.rs | 10 + crates/engine/src/layer_cmds.rs | 2 + crates/engine/src/mask_cmds.rs | 4 +- crates/engine/src/material_lib.rs | 2 + crates/engine/src/preview.rs | 12 +- crates/engine/src/session.rs | 26 +- crates/engine/src/tile_transform_params.rs | 5 + crates/engine/tests/it/content_effects.rs | 21 +- crates/engine/tests/it/filter_card.rs | 15 + crates/engine/tests/it/filter_colour.rs | 13 + crates/engine/tests/it/filter_gradient.rs | 8 + crates/engine/tests/it/filter_inputs.rs | 13 + crates/engine/tests/it/filter_light.rs | 42 +++ crates/engine/tests/it/filter_shape.rs | 24 ++ crates/engine/tests/it/filter_simple.rs | 34 ++ crates/engine/tests/it/filter_stylize.rs | 16 + crates/engine/tests/it/filter_support.rs | 3 + crates/engine/tests/it/filter_swap.rs | 8 + crates/engine/tests/it/filter_transform.rs | 11 + crates/engine/tests/it/painter_gaps.rs | 19 +- crates/render/src/ibl.rs | 34 +- .../ui-egui/src/property_sheet/color_bar.rs | 4 +- .../src/property_sheet/switch_control.rs | 2 +- crates/ui-egui/tests/it/filter_card.rs | 3 + crates/ui-egui/tests/it/filter_gradient.rs | 3 + crates/ui-egui/tests/it/filter_inputs.rs | 5 + crates/ui-egui/tests/it/filter_light.rs | 2 + crates/ui-egui/tests/it/filter_picker.rs | 8 + crates/ui-egui/tests/it/filter_shape.rs | 5 + crates/ui-egui/tests/it/filter_simple.rs | 10 + crates/ui-egui/tests/it/filter_stylize.rs | 5 + crates/ui-egui/tests/it/filter_transform.rs | 1 + crates/ui-egui/tests/it/properties_lists.rs | 6 + 57 files changed, 937 insertions(+), 229 deletions(-) create mode 100644 crates/compose/src/eval/evaluation_inputs.rs create mode 100644 crates/core/src/prepared_color_match.rs create mode 100644 crates/core/src/prepared_gradient.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 4d8f01c1..cfb5edb2 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -206,9 +206,11 @@ impl StackKey { { return None; } + if self.pixels.len() != other.pixels.len() { return None; } + let size = self.set.size(); let mut changed = BTreeSet::new(); for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) { diff --git a/crates/compose/src/environment_sh.rs b/crates/compose/src/environment_sh.rs index 30a2d847..390928bf 100644 --- a/crates/compose/src/environment_sh.rs +++ b/crates/compose/src/environment_sh.rs @@ -1,6 +1,6 @@ //! The viewport environment's diffuse light as spherical harmonics, worked out once per environment, and Baked Lighting Environment's shading with it -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, Weak}; use texturecraft_core::project::DisplaySettings; use texturecraft_core::{Channel, DIELECTRIC_REFLECTANCE, finite_unit, mix3}; @@ -16,33 +16,33 @@ pub struct EnvironmentSh { rotation: f32, } -/// The environment the last coefficients were worked out for: a built-in by name, or an imported image (held, so it is not a different image at the same address) -type CacheEntry = (String, Option>, Arc<[[f32; 3]; 9]>); +/// The last coefficients, keyed by a built-in name or the identity of an imported image +type CacheEntry = (String, Option>, [[f32; 3]; 9]); static CACHE: Mutex> = Mutex::new(None); impl EnvironmentSh { /// The diffuse light of the environment `display` shows (an imported image from `images`), worked out once per environment pub fn of(display: &DisplaySettings, images: &ImageStore) -> EnvironmentSh { - let image = display.environment_resource().and_then(|name| images.get(name)).cloned(); + let image = display.environment_resource().and_then(|name| images.get(name)); let same = |entry: &CacheEntry| match (&entry.1, &image) { - (Some(held), Some(image)) => Arc::ptr_eq(held, image), + (Some(identity), Some(image)) => std::ptr::eq(identity.as_ptr(), Arc::as_ptr(image)), (None, None) => entry.0 == display.environment, _ => false, }; let rotation = display.env_rotation.to_radians(); - let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2.clone()); + let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2); if let Some(coefficients) = cached { - return EnvironmentSh { coefficients: *coefficients, rotation }; + return EnvironmentSh { coefficients, rotation }; } - // Worked out with the cache unlocked: the averaging runs on the thread pool, where a worker holding the lock could take another tile's task that waits for it - let coefficients = match &image { + // Average outside the lock so a Rayon worker can take another tile that needs the cache + let coefficients = match image { Some(image) => image_sh(image), None => built_in_sh(&display.environment), }; - *CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image, Arc::new(coefficients))); + *CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image.map(Arc::downgrade), coefficients)); EnvironmentSh { coefficients, rotation } } @@ -113,6 +113,24 @@ mod tests { assert!(night.irradiance(Vec3::Y, 0.0, 0.0).element_sum() < sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum(), "the cache follows the environment"); } + #[test] + fn replacing_an_imported_environment_releases_its_image() { + let display = DisplaySettings { environment: "resource:lighting".into(), ..DisplaySettings::default() }; + + for color in [[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]] { + let image = Arc::new(ImageRes::new(32, 16, vec![color; 32 * 16], false)); + let image_identity = Arc::downgrade(&image); + let images = ImageStore::from([("lighting".into(), image)]); + + let lighting = EnvironmentSh::of(&display, &images); + drop(images); + let irradiance = lighting.irradiance(Vec3::Y, 0.0, 0.0); + + assert!(irradiance.distance(Vec3::new(color[0], color[1], color[2])) < 0.02); + assert!(image_identity.upgrade().is_none(), "lighting should release the decoded image with its store"); + } + } + /// Tiles on the thread pool that ask for a new light finish: the light is worked out with the cache unlocked, so a worker that steals another tile while it waits for its share of the averaging never waits for its own lock #[test] fn tiles_asking_for_a_new_light_on_the_thread_pool_finish() { diff --git a/crates/compose/src/environment_sky.rs b/crates/compose/src/environment_sky.rs index 0c37ccd2..ec911b88 100644 --- a/crates/compose/src/environment_sky.rs +++ b/crates/compose/src/environment_sky.rs @@ -59,41 +59,44 @@ const SUN_RADIANCE: f32 = 120.0; /// The light a built-in environment `name` sends from direction `d` (unknown names give the default studio) pub fn radiance(name: &str, d: Vec3) -> Vec3 { + if name == "Sunset" { + let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05)); + let sun_dir = dir_of(0.12, 0.47); + let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE; + return base + Vec3::new(1.0, 0.6, 0.3) * sun; + } + + let (azimuth, elevation) = SoftBox::angles(d); match name { "Studio Contrast" => { let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01)); - base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(d) - + SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(d) + base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(azimuth, elevation) + + SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(azimuth, elevation) } "Overcast" => { let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15)); - base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(d) - } - "Sunset" => { - let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05)); - let sun_dir = dir_of(0.12, 0.47); - let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE; - base + Vec3::new(1.0, 0.6, 0.3) * sun + base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(azimuth, elevation) } "Warehouse" => { let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06)); for k in 0..6 { - c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }.eval(d); + c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) } + .eval(azimuth, elevation); } - c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(d) + c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(azimuth, elevation) } "Night" => { let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005)); - base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(d) - + SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(d) + base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(azimuth, elevation) + + SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(azimuth, elevation) } // "Studio Soft" (default) _ => { let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07)); - base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(d) - + SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(d) - + SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(d) + base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(azimuth, elevation) + + SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(azimuth, elevation) + + SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(azimuth, elevation) } } } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6e7fb298..7b0ef05b 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -13,14 +13,15 @@ use rayon::prelude::*; use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, - HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, Project, Projection, - RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, - TileTransform, blend1, blend3, lum, mix3, per_unit, posterize, + HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, + PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, + TargetColorMode, TextureSet, TileGrid, TileTransform, blend1, blend3, lum, mix3, per_unit, posterize, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; +use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::effect_histogram::EffectHistogram; @@ -38,6 +39,7 @@ use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; +use evaluation_inputs::EvaluationInputs; const NCH: usize = Channel::ALL.len(); @@ -276,6 +278,24 @@ struct EffectPlan<'a> { stylized: Option, /// The source a point filter's image input reads (Grayscale Conversion's Custom Input) input: Option, + /// Custom stops shared across tile plans and channels + gradient: Option>, +} + +impl EffectPlan<'_> { + fn point(&self, filter: &Filter, kind: ChannelKind, value: [f32; 3]) -> Option<[f32; 3]> { + match &self.gradient { + Some(gradient) => gradient.point(kind, value), + None => filter.point(kind, value), + } + } + + fn ramp_at(&self, filter: &Filter, position: f32) -> Option<[f32; 3]> { + match &self.gradient { + Some(gradient) => gradient.at(position), + None => filter.ramp_at(position), + } + } } struct MaskPlan<'a> { @@ -424,7 +444,7 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator Some((index, texels(*radius), Op::Glow(*amount))), EffectKind::Filter(Filter::Mosaic { size, alpha }) => Some((index, texels(*size), Op::Mosaic { alpha: *alpha })), EffectKind::Filter(Filter::Fxaa { alpha }) => Some((index, FXAA_SEARCH as f32 + 1.0, Op::Fxaa { alpha: *alpha })), - // The ellipse reaches up to twice the radius along a clear direction, and the direction is read around its reach + // Both the direction search and the ellipse can reach twice the radius EffectKind::Filter(Filter::AnisotropicKuwahara(kuwahara)) if kuwahara.radius > 0.0 => { Some((index, texels(kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS)) * (2.0 + kuwahara.tensor_reach()) + 1.0, Op::Kuwahara(*kuwahara))) } @@ -435,7 +455,7 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator { Some((index, if matcher.source_mode == SourceColorMode::Average { WHOLE_SET } else { 1.0 }, Op::ColorMatch(*matcher))) } - // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them + // Use reference-resolution reach so all callers classify the same filters as stages EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) } @@ -714,28 +734,43 @@ fn gather( data } -/// The linear colors `source` gives over texel region `(x0, y0, w, h)` (its tiles `tiles`), row by row -fn input_colors(inp: &Inputs, source: &Source, tiles: &[(u32, u32)], (x0, y0, w, h): (u32, u32, u32, u32)) -> Vec<[f32; 3]> { - let parts: Vec> = tiles - .par_iter() - .map(|&(tx, ty)| { - let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); - tile_texels(inp.gbuf, tx, ty) - .map(|(x, y, offset)| { - let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); - (x, y, texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color)) - }) - .collect() - }) - .collect(); - let mut colors = vec![[0.0f32; 3]; (w * h) as usize]; - for &(x, y, color) in parts.iter().flatten() { - if let (Some(dx), Some(dy)) = (x.checked_sub(x0), y.checked_sub(y0)) - && let Some(slot) = colors.get_mut((dy * w + dx) as usize) - { - *slot = color; - } +/// The linear colors a filter input gives over the tile-aligned texel region, row by row +fn input_colors( + inputs: &EvaluationInputs, + source: &Source, + (layer, channels, below): (LayerId, &[Channel], &Fields), + (left, top, width, height): (u32, u32, u32, u32), +) -> Vec<[f32; 3]> { + if width == 0 || height == 0 { + return Vec::new(); } + + let mut colors = vec![[0.0; 3]; (width * height) as usize]; + let horizontal_tiles = left / TILE..(left + width).div_ceil(TILE); + colors.par_chunks_mut((TILE * width) as usize).enumerate().for_each(|(band, colors)| { + let tile_y = top / TILE + band as u32; + let band_top = tile_y * TILE; + for tile_x in horizontal_tiles.clone() { + let anchors = if matches!(source, Source::Anchor { .. }) { anchor_plan(inputs, layer, channels, tile_x, tile_y, Some(below)) } else { Vec::new() }; + let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); + + for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) { + if x < left || x - left >= width { + continue; + } + + let index = ((y - band_top) * width + (x - left)) as usize; + let Some(pixel) = colors.get_mut(index) else { continue }; + let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchors.is_empty() { + texel.anchors_below(&anchors, layer); + } + + *pixel = texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color); + } + } + }); + colors } @@ -748,48 +783,65 @@ fn color_match(data: &mut [f32], comps: usize, matcher: &ColorMatch, (sources, t return; } - // The mean of the covered colors (premultiplied, so a texel counts by its coverage) - let (sum, covered) = data - .par_chunks(4) - .fold( - || ([0.0f64; 3], 0.0f64), - |(mut sum, mut covered), px| { - if let [r, g, b, a] = *px - && a > 0.0 - && a.is_finite() - { - for (slot, v) in sum.iter_mut().zip([r, g, b]) { - *slot += f64::from(v); - } - covered += f64::from(a); - } - (sum, covered) - }, - ) - .reduce(|| ([0.0; 3], 0.0), |(a, ca), (b, cb)| ([a[0] + b[0], a[1] + b[1], a[2] + b[2]], ca + cb)); - let mean = if covered > 0.0 { sum.map(|v| (v / covered) as f32) } else { matcher.target_color }; - data.par_chunks_mut(4).enumerate().for_each(|(i, px)| { - let [r, g, b, a] = *px else { return }; - if a <= 0.0 || !a.is_finite() { + let source_color = if matcher.source_mode == SourceColorMode::Average { mean_region_color(data, matcher.target_color) } else { matcher.source_color }; + let source_pixels = if matcher.source_mode == SourceColorMode::Input { sources.as_deref() } else { None }; + let target_pixels = if matcher.target_mode == TargetColorMode::ImageInput { targets.as_deref() } else { None }; + + if source_pixels.is_none() && target_pixels.is_none() { + let prepared = PreparedColorMatch::new(*matcher, source_color, matcher.target_color); + match_pixels(data, opacity, |_, color| prepared.apply(color)); + } else { + match_pixels(data, opacity, |index, color| { + let source = source_pixels.and_then(|pixels| pixels.get(index)).copied().unwrap_or(source_color); + let target = target_pixels.and_then(|pixels| pixels.get(index)).copied().unwrap_or(matcher.target_color); + matcher.apply(color, source, target) + }); + } +} + +fn match_pixels(data: &mut [f32], opacity: f32, remap: impl Fn(usize, [f32; 3]) -> [f32; 3] + Sync) { + data.par_chunks_mut(4).enumerate().for_each(|(index, pixel)| { + let [red, green, blue, alpha] = *pixel else { return }; + if alpha <= 0.0 || !alpha.is_finite() { return; } - let source = match matcher.source_mode { - SourceColorMode::Average => mean, - SourceColorMode::Parameter => matcher.source_color, - SourceColorMode::Input => sources.as_ref().and_then(|colors| colors.get(i)).copied().unwrap_or(matcher.source_color), - }; - let target = match matcher.target_mode { - TargetColorMode::Parameter => matcher.target_color, - TargetColorMode::ImageInput => targets.as_ref().and_then(|colors| colors.get(i)).copied().unwrap_or(matcher.target_color), - }; - let moved = matcher.apply([r, g, b].map(|v| v / a), source, target); - for (slot, v) in px.iter_mut().zip(moved) { - *slot += (v * a - *slot) * opacity; + let moved = remap(index, [red, green, blue].map(|component| component / alpha)); + for (slot, value) in pixel.iter_mut().zip(moved) { + *slot += (value * alpha - *slot) * opacity; } }); } +/// The mean of a premultiplied color region, or the fallback when no texel is covered +fn mean_region_color(data: &[f32], fallback: [f32; 3]) -> [f32; 3] { + // Premultiplication weights the color by coverage + let (color_sum, coverage_sum) = data + .par_chunks(4) + .fold( + || ([0.0f64; 3], 0.0f64), + |(mut colors, mut coverage), pixel| { + if let [red, green, blue, alpha] = *pixel + && alpha > 0.0 + && alpha.is_finite() + { + for (sum, component) in colors.iter_mut().zip([red, green, blue]) { + *sum += f64::from(component); + } + coverage += f64::from(alpha); + } + + (colors, coverage) + }, + ) + .reduce( + || ([0.0; 3], 0.0), + |(left, left_coverage), (right, right_coverage)| ([left[0] + right[0], left[1] + right[1], left[2] + right[2]], left_coverage + right_coverage), + ); + + if coverage_sum > 0.0 { color_sum.map(|component| (component / coverage_sum) as f32) } else { fallback } +} + /// Height To Normal at texel `(x, y)` into `acc`: the 3×3 Sobel normal of the heights `height` reads, laid over normal `center` unless it overwrites it fn height_to_normal_texel( filter: &HeightToNormal, @@ -906,7 +958,7 @@ fn kuwahara_texel( let falloff = (-KUWAHARA_FALLOFF * distance).exp(); let heading = v.atan2(u); for (k, (sum, square)) in sums.iter_mut().zip(&mut squares).enumerate() { - // The middle texel belongs to every sector; the others to the sectors they face, fading towards their sides + // The center contributes to every sector while other weights taper at sector boundaries let facing = (heading - k as f32 * std::f32::consts::TAU / AnisotropicKuwahara::SECTORS as f32).cos(); let weight = if distance <= 0.0 { falloff @@ -915,6 +967,7 @@ fn kuwahara_texel( } else { continue; }; + for (slot, value) in sum.iter_mut().zip(&px) { *slot += weight * value; } @@ -924,7 +977,7 @@ fn kuwahara_texel( } } - // Calmer sectors weigh more, sharper the higher the Sharpness (in logs, so the powers can't overflow) + // Weight low-variance sectors more and use logarithms to avoid overflow let sharpness = kuwahara.sharpness_exponent(); let logs: [Option; AnisotropicKuwahara::SECTORS] = std::array::from_fn(|sector| { let (sum, square) = (sums.get(sector)?, squares.get(sector)?); @@ -1226,7 +1279,7 @@ fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel] } /// [`anchor_plan`], or the plain set stack when `lit` (a layer lit by its material reads the stack below it too) -fn below_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], (tx, ty): (u32, u32), fields: Option<&'a Fields>, lit: bool) -> Vec> { +fn below_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], (tx, ty): (u32, u32), fields: Option<&'a Fields>, lit: bool) -> Vec> { let anchors = anchor_plan(inp, id, channels, tx, ty, fields); if !anchors.is_empty() || !lit { return anchors; @@ -1301,7 +1354,7 @@ fn field( margins[index] += margins[index + 1]; } - // A wrapping filter reads across the set's edges, so it and every filter under it cover the whole set along an axis it crosses + // A wrapped dependency expands all lower stages across any crossed axis let own_wraps: Vec = filters.iter().map(|filter| wraps(effects, filter.0)).collect(); let mut wrapping = own_wraps.clone(); for index in (0..wrapping.len().saturating_sub(1)).rev() { @@ -1459,7 +1512,14 @@ fn filter_region( }; // The gray the filter's image input reads (its first; the filters that read one have one) - let input = filter_effect.zip(filter).and_then(|(effect, filter)| ImageInput::of(filter).first().map(|input| effect.input(input))); + let input = filter_effect.zip(filter).and_then(|(effect, filter)| { + // Color Match reads each input as linear color separately + if matches!(filter, Filter::ColorMatch(_)) { + return None; + } + + ImageInput::of(filter).first().map(|input| effect.input(input)) + }); let lit_prefix = channel == Some(Channel::BaseColor) && effects.iter().filter(|effect| effect.visible).take(index).any(|effect| lights_material(&effect.kind)); @@ -1569,8 +1629,9 @@ fn filter_region( // Color Match's Input and Image Input colors over the region, when its modes read them let match_inputs = match (op, filter_effect) { (Op::ColorMatch(matcher), Some(effect)) if opacity > 0.0 => { - let read = - |on: bool, input: ImageInput| on.then(|| input_colors(inputs, &effect.input(&input), ®ion_tiles, (region_x, region_y, width, height))); + let read = |on: bool, input: ImageInput| { + on.then(|| input_colors(inputs, &effect.input(&input), (id, channels, below), (region_x, region_y, width, height))) + }; [ read(matcher.source_mode == SourceColorMode::Input, ImageInput::SOURCE_INPUT), read(matcher.target_mode == TargetColorMode::ImageInput, ImageInput::TARGET_INPUT), @@ -1585,7 +1646,7 @@ fn filter_region( _ => 0.5, }; - // A Highpass in sRGB filters its colors encoded (decoded again below); one with Apply To Alpha keeps the colors on the new coverage + // Filter High Pass in its working space and preserve color when only coverage changes let (space, highpass_alpha) = match (op, job) { (Op::HighPass { space, alpha }, Job::Content(channel)) if components == 4 => { (if channel.kind() == ChannelKind::Color { space } else { HighpassSpace::Working }, alpha) @@ -1595,7 +1656,7 @@ fn filter_region( let covered = highpass_alpha.then(|| stack_values.clone()); recode(&mut stack_values, components, |rgb| space.encode(rgb)); - // A wrapped axis pads by the reach up to one period (past it the far side repeats), so a set pads to 3x its size at most + // Pad by at most one sampling period on either side because farther reads repeat let pad_x = if wrap && region_x == 0 && width == inputs.gbuf.width { reach.min(width) } else { 0 }; let pad_y = if wrap && region_y == 0 && height == inputs.gbuf.height { reach.min(height) } else { 0 }; @@ -1690,7 +1751,7 @@ fn filter_region( && let Some(filter) = filter { let kind = channel.map_or(ChannelKind::Scalar, Channel::kind); - map_blurred(&mut filtered_values, &stack_values, components, filter, kind, opacity); + map_blurred(&mut filtered_values, &stack_values, components, filter, inputs.gradient(filter).as_deref(), kind, opacity); } if pad == (0, 0) { filtered_values } else { unpad(&filtered_values, components, unpadded, pad) } }; @@ -1993,17 +2054,22 @@ fn mask_outline(data: &mut [f32], cover: &[f32], comps: usize, (width, height, r } /// Run point filter `filter` on blurred texels `data` (premultiplied content or masks) and mix the result over the unblurred `orig` by `opacity` -fn map_blurred(data: &mut [f32], orig: &[f32], comps: usize, filter: &Filter, kind: ChannelKind, opacity: f32) { +fn map_blurred(data: &mut [f32], orig: &[f32], comps: usize, filter: &Filter, gradient: Option<&PreparedGradient>, kind: ChannelKind, opacity: f32) { + let point = |value| match gradient { + Some(gradient) => gradient.point(kind, value), + None => filter.point(kind, value), + }; let straight = |value: f32, cover: f32| if cover > MIN_ALPHA { value / cover } else { 0.0 }; + data.par_chunks_mut(comps).zip(orig.par_chunks(comps)).for_each(|(pixel, original)| match (pixel, original) { ([value], [before]) => { - let mapped = filter.point(kind, [*value; 3]).map_or(*value, |gray| gray[0]); + let mapped = point([*value; 3]).map_or(*value, |gray| gray[0]); *value = before + (mapped - before) * opacity; } ([r, g, b, cover], [r0, g0, b0, cover0]) => { let before = [straight(*r0, *cover0), straight(*g0, *cover0), straight(*b0, *cover0)]; let blurred = [straight(*r, *cover), straight(*g, *cover), straight(*b, *cover)]; - let mixed = mix3(before, filter.point(kind, blurred).unwrap_or(before), opacity); + let mixed = mix3(before, point(blurred).unwrap_or(before), opacity); [*r, *g, *b, *cover] = [mixed[0] * cover0, mixed[1] * cover0, mixed[2] * cover0, *cover0]; } _ => {} @@ -2192,6 +2258,10 @@ fn effect_plans<'a>( EffectKind::Filter(filter) if !filter.is_neighbourhood() => ImageInput::of(filter).first().map(|input| effect.input(input)), _ => None, }, + gradient: match &effect.kind { + EffectKind::Filter(filter) => inp.gradient(filter), + _ => None, + }, } }) .collect() @@ -3154,7 +3224,7 @@ impl<'a, 'b> Texel<'a, 'b> { } EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { - let ramp = filter.ramp_at(self.coords().uv.x.rem_euclid(1.0)).map_or(value, lum); + let ramp = effect.ramp_at(filter, self.coords().uv.x.rem_euclid(1.0)).map_or(value, lum); value += (ramp - value) * opacity; } EffectKind::Filter(Filter::GrayscaleConversion(conversion)) => { @@ -3166,7 +3236,7 @@ impl<'a, 'b> Texel<'a, 'b> { } EffectKind::Filter(filter) => { // A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start` - let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); + let filtered = effect.point(filter, ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); value += (filtered - value) * opacity; } EffectKind::ColorSelection(selection) => { @@ -3582,8 +3652,9 @@ impl<'a, 'b> Texel<'a, 'b> { }, // A gradient's debug view shows its ramp left to right across each UV tile EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { - let ramp = - filter.ramp_at(self.coords().uv.x.rem_euclid(1.0)).map(|color| if chan_plan.kind == ChannelKind::Color { color } else { [lum(color); 3] }); + let ramp = effect + .ramp_at(filter, self.coords().uv.x.rem_euclid(1.0)) + .map(|color| if chan_plan.kind == ChannelKind::Color { color } else { [lum(color); 3] }); (ramp.map_or(value, |ramp| mix3(value, ramp, opacity)), coverage) } @@ -3603,7 +3674,7 @@ impl<'a, 'b> Texel<'a, 'b> { } // Neighbourhood filters come precomputed through `ChanPlan::start` - EffectKind::Filter(filter) => (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), + EffectKind::Filter(filter) => (effect.point(filter, chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), // Anchors are recorded by `eval`; mask-only effects leave content as it is EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection(_) | EffectKind::Compare { .. } => { (value, coverage) @@ -5066,6 +5137,7 @@ mod tests { fixture.project.layer_mut(upper).unwrap().mask = Some(mask.clone()); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let original = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); + assert!(original.iter().any(|value| *value > 0.99) && original.iter().any(|value| *value < 0.01), "the anchor supplies the checker"); for filter in [Filter::Blur { radius: 64.0, wrap: false }, Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 }] { @@ -5342,14 +5414,20 @@ mod tests { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0; 3], 1.0); assert!(!stack_reads_neighbours(&f.project, 0)); + let mut mask = Mask::new(MaskBackground::White); let eid = f.project.alloc_id(); mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); + assert!(stack_reads_neighbours(&f.project, 0)); + f.project.layer_mut(id).unwrap().mask = None; + assert!(!stack_reads_neighbours(&f.project, 0)); + content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0, alpha: true })); + assert!(stack_reads_neighbours(&f.project, 0)); } @@ -5456,7 +5534,9 @@ soft {soft:?}" f.pixels.layer_mut(id, Channel::BaseColor, (64, 64)).set(3, 3, &[to_u16(0.5), 0, 0, to_u16(0.5)]); let posterize = content_fx(&mut f, id, EffectKind::Filter(Filter::Posterize { levels: 2.0, alpha: false })); assert!(close(run(&f, None).value(Channel::BaseColor, 3, 3), [0.75, 0.25, 0.25]), "the coverage stays as it is"); + f.project.effect_mut(posterize).unwrap().kind = EffectKind::Filter(Filter::Posterize { levels: 2.0, alpha: true }); + assert!(close(run(&f, None).value(Channel::BaseColor, 3, 3), [1.0, 0.0, 0.0]), "half coverage rounds up to whole"); } @@ -5485,6 +5565,7 @@ soft {soft:?}" let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 1, 1), [0.625, 0.375, 0.375]), "the cell's coverage: {:?}", out.value(Channel::BaseColor, 1, 1)); assert!(close(out.value(Channel::BaseColor, 2, 2), [0.625, 0.375, 0.375]), "spread over the cell"); + f.project.effect_mut(fx).unwrap().kind = EffectKind::Filter(Filter::Mosaic { size: 128.0, alpha: false }); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 1, 1), [1.0, 0.0, 0.0]), "the texel keeps its whole coverage"); @@ -5501,6 +5582,7 @@ soft {soft:?}" let mut f = fixture(); let id = painted(&mut f, |x, y| Some((if stairs(x, y) { [1.0; 3] } else { [0.0; 3] }, 1.0))); assert_eq!(mids(&run(&f, None)), 0); + content_fx(&mut f, id, EffectKind::Filter(Filter::Fxaa { alpha: false })); let out = run(&f, None); assert!(mids(&out) > 16, "{} texels blended", mids(&out)); @@ -5511,8 +5593,11 @@ soft {soft:?}" let id = painted(&mut f, |x, y| stairs(x, y).then_some(([1.0; 3], 1.0))); let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Fxaa { alpha: false })); let plain = |out: &Composite| (0..64 * 64).all(|i| [0.5, 1.0].iter().any(|v| (out.value(Channel::BaseColor, i % 64, i / 64)[0] - v).abs() < 2e-4)); + assert!(plain(&run(&f, None)), "each texel keeps its coverage"); + f.project.effect_mut(fx).unwrap().kind = EffectKind::Filter(Filter::Fxaa { alpha: true }); + assert!(!plain(&run(&f, None)), "the coverage is smoothed"); } @@ -5523,6 +5608,7 @@ soft {soft:?}" let mut mask = Mask::new(MaskBackground::White); mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Hsl { hue: 0.3, saturation: 1.0, lightness: -0.5, perceptive: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.75; 3])); } @@ -5572,11 +5658,13 @@ soft {soft:?}" // The checker tiles: its period P repeats across the whole row let hard = row(None); let period = (1..64).find(|&p| (0..64 - p).all(|x| (hard[x] - hard[x + p]).abs() < 1e-3)).unwrap(); + assert!(period <= 32, "{hard:?}"); // Wrapped, the blur at the texture's edge sees the far side, so the result keeps tiling; clipped, the edge differs let wrapped = row(Some(true)); assert!((0..64 - period).all(|x| (wrapped[x] - wrapped[x + period]).abs() < 0.02), "{wrapped:?}"); + let clipped = row(Some(false)); assert!((clipped[0] - clipped[period]).abs() > 0.05, "{clipped:?}"); assert!((12..52).all(|x| (clipped[x] - wrapped[x]).abs() < 0.02), "away from the edges, wrap changes nothing"); @@ -5600,6 +5688,7 @@ soft {soft:?}" }; let hard = composite(None, &all_tiles(WIDTH, HEIGHT)); let period = (1..WIDTH as usize).find(|&p| (0..WIDTH as usize - p).all(|x| (hard[x] - hard[x + p]).abs() < 1e-3)).unwrap(); + assert!(period <= WIDTH as usize / 2, "the checker tiles across the set: {hard:?}"); let wrapping = [ @@ -5627,6 +5716,7 @@ soft {soft:?}" }; let mut gradient = Filter::even_gradient(vec![[0.0; 3], [1.0; 3]]); let hard = row(Some(gradient.clone())); + assert!(hard.iter().zip(row(None)).all(|(a, b)| (a - b).abs() < 1e-3), "a black to white ramp keeps a scalar as it is"); // Blurred first, then looked up: the same as a blur of that size @@ -5646,6 +5736,7 @@ soft {soft:?}" let below = fill_layer(&mut f.project, [0.0; 3], 0.0); let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); assert_ne!(below, id); + let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::SrgbFromLinear, alpha: false })); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 30, 30), [texturecraft_texel::srgb_to_linear(0.5); 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); @@ -5699,12 +5790,15 @@ soft {soft:?}" let edges = content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 32.0 })); let out = run(&f, None); let vals: Vec = (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).map(|(x, y)| out.value(Channel::Roughness, x, y)[0]).collect(); + assert!(vals.iter().all(|v| (0.0..=1.0).contains(v))); assert!(vals.iter().filter(|v| **v > 0.5).count() > 64 && vals.iter().filter(|v| **v < 0.01).count() > 64, "{vals:?}"); + f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != edges); content_fx(&mut f, id, EffectKind::Filter(Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 })); let warped = run(&f, None); let differs = (0..64).any(|y| (0..64).any(|x| (warped.value(Channel::Roughness, x, y)[0] - plain.value(Channel::Roughness, x, y)[0]).abs() > 0.2)); + assert!(differs, "the warp moves the checker"); // Point filters @@ -5751,6 +5845,7 @@ soft {soft:?}" let glow = Filter::HaloGlow { on_mask: true, precise: false, width: 1.0, spread: 0.0, opacity: 1.0, color: [1.0; 3] }; let glowing = row_of(Some(glow)); assert!(glowing.iter().zip(&plain).all(|(g, p)| *g >= p - 1e-4), "a glow only adds"); + let lit = (0..64 * 64).filter(|&i| dark(plain[i]) && glowing[i] > low + 0.1 * (high - low)).count(); assert!(lit > 64, "{lit} dark texels lit"); @@ -5758,6 +5853,7 @@ soft {soft:?}" let shadow = Filter::DropShadow { angle: 90.0, distance: 0.1, size: 0.0, spread: 0.0, opacity: 0.5, color: [0.0; 3] }; let shadowed = row_of(Some(shadow)); assert!(shadowed.iter().zip(&plain).all(|(s, p)| *s >= p - 1e-4), "a shadow only goes under the shapes"); + let reach = 6; let at = |x: usize, y: usize| plain[y * 64 + x]; let (mut below, mut above) = (Vec::new(), Vec::new()); @@ -5771,7 +5867,9 @@ soft {soft:?}" } } } + assert!(!below.is_empty() && !above.is_empty()); + let mean = |v: &[f32]| v.iter().sum::() / v.len() as f32; assert!(mean(&below) > 0.2 * (high - low), "under: {below:?}"); assert!(mean(&above) < 0.05 * (high - low), "above: {above:?}"); @@ -5836,8 +5934,10 @@ soft {soft:?}" // Facing the light adds illumination; facing away keeps ambient only let (toward, rough) = lit(if n.y > 0.0 { 90.0 } else { -90.0 }); assert!(close(toward, [0.5; 3]) && close(rough, [0.3; 3]), "{toward:?} {rough:?}"); + let (away, _) = lit(if n.y > 0.0 { -90.0 } else { 90.0 }); assert!(close(away, [0.2; 3]), "{away:?}"); + let f = Filter::BakedLighting { azimuth: 0.0, elevation: 0.0, light: 0.0, ambient: 1.0, occlusion: 0.5, stylized: None }; assert_eq!(f.baked_light([0.0, 1.0, 0.0], 0.2), Some(0.6), "half the occlusion"); assert_eq!(Filter::Invert.baked_light([0.0; 3], 1.0), None); @@ -5886,9 +5986,44 @@ soft {soft:?}" // The roughness below (0.8) passes the first compare everywhere: the mask so far is white let white = *mask_so_far.last().unwrap(); + assert!(white > 0 && mask_so_far.iter().sum::() == white, "{mask_so_far:?}"); } + #[test] + fn color_match_reads_the_anchor_in_either_image_input() { + let mut fixture = fixture(); + let original_color = [0.6, 0.19, 0.09]; + let target_color = [0.1, 0.3, 0.8]; + let lower = fill_layer(&mut fixture.project, original_color, 0.5); + let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); + let upper = fill_layer(&mut fixture.project, original_color, 0.5); + let source = Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }; + + let matcher = ColorMatch { source_mode: SourceColorMode::Input, target_color, custom_variation: false, ..ColorMatch::LIBRARY }; + let effect_id = content_fx(&mut fixture, upper, EffectKind::Filter(Filter::ColorMatch(matcher))); + let effect = fixture.project.effect_mut(effect_id).unwrap(); + effect.inputs.insert(ImageInput::SOURCE_INPUT.id.to_owned(), source.clone()); + + let from_anchor = run(&fixture, None).value(Channel::BaseColor, 30, 30); + + assert!(close(from_anchor, target_color), "{from_anchor:?}"); + + let effect = fixture.project.effect_mut(effect_id).unwrap(); + effect.kind = EffectKind::Filter(Filter::ColorMatch(ColorMatch { + source_mode: SourceColorMode::Parameter, + source_color: original_color, + target_mode: TargetColorMode::ImageInput, + ..matcher + })); + effect.inputs.clear(); + effect.inputs.insert(ImageInput::TARGET_INPUT.id.to_owned(), source); + + let to_anchor = run(&fixture, None).value(Channel::BaseColor, 30, 30); + + assert!(close(to_anchor, original_color), "{to_anchor:?}"); + } + #[test] fn a_histogram_shares_one_field_of_a_stage_reading_the_whole_set() { let mut f = fixture(); @@ -5899,7 +6034,10 @@ soft {soft:?}" let inp = inputs(&f, &images, None); let channels = f.project.texture_set(0).unwrap().channel_list(); - let shared = shared_histogram_fields(&inp, &channels, &all_tiles(64, 64)); + let projectors = ProjectorDepthCache::default(); + let inputs = EvaluationInputs::new(&inp, &projectors); + + let shared = shared_histogram_fields(&inputs, &channels, &all_tiles(64, 64)); assert!(shared.is_some_and(|fields| fields.contains_key(&FieldKey::Content(id, Channel::BaseColor))), "every sampled tile reads one field"); } @@ -6026,15 +6164,18 @@ soft {soft:?}" let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })); f.project.layer_mut(top).unwrap().mask = Some(mask.clone()); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // The field pre-pass reads anchors under blur, preserving flat height mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false }))); f.project.layer_mut(top).unwrap().mask = Some(mask); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // An anchor above its reader is not evaluated yet, so it reads the channel default f.project.move_layer(low, 1).unwrap(); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3])); } @@ -6070,11 +6211,13 @@ soft {soft:?}" mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false }))); fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.4; 3]), "{color:?}"); // An empty paint layer still records its mask anchor for the layer above fixture.project.layer_mut(low).unwrap().kind = LayerKind::Paint; let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.7; 3]), "{color:?}"); } @@ -6097,6 +6240,7 @@ soft {soft:?}" let reader = anchor_reader(&mut fixture, anchor); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let expected = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); + assert!(expected.iter().any(|value| *value > 0.1 && *value < 0.9), "the anchor records a softened checker"); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 128.0, wrap: false }))); @@ -6153,6 +6297,7 @@ soft {soft:?}" // A dim gray is valid for a dielectric only: the layer's metal makes it red in the filter's prepass and in the flattened layer assert!(close(blurred, PbrValidate::INVALID), "{blurred:?}"); + let (_, _, data) = flat.iter().find(|(channel, tile, _)| *channel == Channel::BaseColor && *tile == (0, 0)).unwrap(); let texel = (30 * TILE as usize + 30) * 4; let flattened: [f32; 3] = std::array::from_fn(|i| from_u16(data[texel + i])); diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs new file mode 100644 index 00000000..a895001a --- /dev/null +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -0,0 +1,45 @@ +use std::collections::HashMap; +use std::ops::Deref; +use std::sync::{Arc, Mutex, PoisonError}; + +use texturecraft_core::{Filter, PreparedGradient}; + +use super::Inputs; +use crate::ProjectorDepthCache; + +pub(super) struct EvaluationInputs<'a> { + inputs: &'a Inputs<'a>, + pub(super) projectors: &'a ProjectorDepthCache, + gradients: Mutex>>, +} + +impl<'a> EvaluationInputs<'a> { + pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self { + Self { inputs, projectors, gradients: Mutex::default() } + } + + pub(super) fn gradient(&self, filter: &'a Filter) -> Option> { + if !matches!(filter, Filter::GradientMap { linear: false, .. }) { + return None; + } + + // The borrowed project keeps filter addresses stable for this evaluation + let key = std::ptr::from_ref(filter) as usize; + let mut gradients = self.gradients.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(prepared) = gradients.get(&key) { + return Some(Arc::clone(prepared)); + } + + let prepared = Arc::new(PreparedGradient::of(filter)?); + gradients.insert(key, Arc::clone(&prepared)); + Some(prepared) + } +} + +impl<'a> Deref for EvaluationInputs<'a> { + type Target = Inputs<'a>; + + fn deref(&self) -> &Self::Target { + self.inputs + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 65cf4271..852127e0 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -33,6 +33,7 @@ pub mod pattern; mod pattern_context; pub mod projector_cover; pub mod projector_depth; +mod projector_depth_cache; pub mod projector_view; mod shape_distance; mod slope_texel; diff --git a/crates/compose/src/shape_distance.rs b/crates/compose/src/shape_distance.rs index 0f3df3a7..60fd130c 100644 --- a/crates/compose/src/shape_distance.rs +++ b/crates/compose/src/shape_distance.rs @@ -37,9 +37,8 @@ pub(crate) fn distance_filter( [value] => *value, _ => 0.0, }; - let values: Vec = data.par_chunks(components).map(value).collect(); let shapes = |inside: &(dyn Fn(f32) -> bool + Sync)| -> Vec { - values.par_iter().zip(cover.par_iter()).map(|(value, covered)| *covered > 0.0 && inside(*value)).collect() + data.par_chunks(components).zip(cover.par_iter()).map(|(pixel, covered)| *covered > 0.0 && inside(value(pixel))).collect() }; let smoothed = |field: &mut [f32], texels: f32| { let radius = texels.round() as usize; @@ -55,15 +54,22 @@ pub(crate) fn distance_filter( let edge = edge_distances(&inside, (width, height), bevel.corner == BevelCorner::Angular); let reach = bevel.reach(tile_resolution); let mut slope: Vec = inside.par_iter().zip(edge.par_iter()).map(|(inside, edge)| bevel.slope(*inside, *edge, reach)).collect(); - let mut blurred = slope.clone(); - smoothed(&mut blurred, bevel.smoothing_texels(tile_resolution)); - slope.par_iter_mut().zip(blurred.par_iter()).for_each(|(sharp, blurred)| { - *sharp = match bevel.blur { - BevelBlur::Uniform => *blurred, - // Sharp at the slope's foot, as blurred as Uniform at its top - BevelBlur::NonUniform => *sharp + (blurred - *sharp) * *sharp, - }; - }); + drop(edge); + + let smoothing_radius = bevel.smoothing_texels(tile_resolution).round() as usize; + if smoothing_radius > 0 { + match bevel.blur { + BevelBlur::Uniform => blur(&mut slope, width, height, smoothing_radius), + BevelBlur::NonUniform => { + let mut blurred = slope.clone(); + blur(&mut blurred, width, height, smoothing_radius); + + // Keep the foot sharp and blur the top at full strength + slope.par_iter_mut().zip(blurred).for_each(|(sharp, blurred)| *sharp += (blurred - *sharp) * *sharp); + } + } + } + let bevel = *bevel; (inside, Box::new(move |texel, inside, value| bevel.apply(inside, value, slope.get(texel).copied().unwrap_or(1.0)))) } @@ -77,6 +83,7 @@ pub(crate) fn distance_filter( .enumerate() .map(|(texel, (inside, edge))| smooth.value(curve, *inside, *edge, reach * map(texel))) .collect(); + drop(edge); smoothed(&mut ramp, smooth.smoothing_texels(tile_resolution)); (inside, Box::new(move |texel, _, value| ramp.get(texel).copied().unwrap_or(value))) } @@ -116,34 +123,42 @@ pub(crate) fn distance_filter( /// Every texel's distance (texels) to the edge between it and the nearest texel on the other side of the shapes `inside`: straight-line, or the larger axis distance when `angular` fn edge_distances(inside: &[bool], (width, height): (usize, usize), angular: bool) -> Vec { - let outside: Vec = inside.iter().map(|inside| !inside).collect(); - let (to_inside, to_outside) = if angular { - (chessboard_distances(inside, (width, height)), chessboard_distances(&outside, (width, height))) - } else { - (straight_distances(inside, (width, height)), straight_distances(&outside, (width, height))) - }; - inside - .par_iter() - .zip(to_inside.par_iter().zip(to_outside.par_iter())) - .map(|(inside, (to_inside, to_outside))| (if *inside { *to_outside } else { *to_inside } - EDGE_OFFSET).max(0.0)) - .collect() + let distances = if angular { chessboard_distances } else { straight_distances }; + let mut to_inside = distances(inside, (width, height), true); + let to_outside = distances(inside, (width, height), false); + + to_inside + .par_iter_mut() + .zip(to_outside) + .zip(inside) + .for_each(|((to_inside, to_outside), inside)| *to_inside = (if *inside { to_outside } else { *to_inside } - EDGE_OFFSET).max(0.0)); + + to_inside } -/// Every texel's straight-line distance (texels) to the nearest texel where `feature` holds; farther than the region when none does -fn straight_distances(feature: &[bool], (width, height): (usize, usize)) -> Vec { - // Squared distances, separable: along the rows, then along the columns of those +/// Each texel's straight-line distance to the nearest texel on the requested side. +fn straight_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec { + // Start beyond the region so a line without a feature stays out of reach let far = ((width + height) as f32).powi(2); - let mut rows: Vec = feature.iter().map(|feature| if *feature { 0.0 } else { far }).collect(); + let mut rows: Vec = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect(); rows.par_chunks_mut(width.max(1)).for_each_init(DistanceEnvelope::default, |envelope, row| envelope.lower(row)); + let mut columns: Vec = (0..width * height).map(|at| rows.get((at % height.max(1)) * width + at / height.max(1)).copied().unwrap_or(far)).collect(); columns.par_chunks_mut(height.max(1)).for_each_init(DistanceEnvelope::default, |envelope, column| envelope.lower(column)); - (0..width * height).map(|at| columns.get((at % width.max(1)) * height + at / width.max(1)).copied().unwrap_or(far).sqrt()).collect() + + // Reuse the row buffer for the final distances in row-major order + rows.resize(width * height, far); + for (index, distance) in rows.iter_mut().enumerate() { + *distance = columns.get((index % width.max(1)) * height + index / width.max(1)).copied().unwrap_or(far).sqrt(); + } + + rows } -/// Every texel's distance (texels, the larger of across and down) to the nearest texel where `feature` holds; farther than the region when none does -fn chessboard_distances(feature: &[bool], (width, height): (usize, usize)) -> Vec { +/// Each texel's distance to the nearest texel on the requested side, measured along the larger axis. +fn chessboard_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec { let far = (width + height) as f32; - let mut distances: Vec = feature.iter().map(|feature| if *feature { 0.0 } else { far }).collect(); + let mut distances: Vec = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect(); // One pass down from the texels above and left, one up from those below and right let step = |distances: &mut [f32], (x, y): (usize, usize), neighbours: [(isize, isize); 4]| { @@ -210,6 +225,7 @@ fn trail_steps((width, height): (usize, usize), direction: [f32; 2], reach: f32) if steps.last().is_some_and(|(last_across, last_down, _)| (*last_across, *last_down) == (across, down)) { continue; } + steps.push((across, down, if reach > 0.0 { back / reach } else { 0.0 })); } steps @@ -289,12 +305,12 @@ mod tests { // One feature texel in the middle of a 5 × 5 region let mut feature = vec![false; 25]; feature[12] = true; - let straight = straight_distances(&feature, (5, 5)); - let chessboard = chessboard_distances(&feature, (5, 5)); + let straight = straight_distances(&feature, (5, 5), true); + let chessboard = chessboard_distances(&feature, (5, 5), true); assert_eq!((straight[12], straight[13], chessboard[13]), (0.0, 1.0, 1.0)); assert!((straight[0] - 8f32.sqrt()).abs() < 1e-5, "{}", straight[0]); assert_eq!(chessboard[0], 2.0, "a corner is as far as its larger axis"); - let none = straight_distances(&[false; 4], (2, 2)); + let none = straight_distances(&[false; 4], (2, 2), true); assert!(none.iter().all(|distance| *distance >= 4.0), "no feature is beyond the region"); } @@ -304,8 +320,8 @@ mod tests { let (width, height) = (7, 3); let mut feature = vec![false; width * height]; feature[1] = true; - let straight = straight_distances(&feature, (width, height)); - let chessboard = chessboard_distances(&feature, (width, height)); + let straight = straight_distances(&feature, (width, height), true); + let chessboard = chessboard_distances(&feature, (width, height), true); let at = |x: usize, y: usize| y * width + x; assert_eq!((straight[at(1, 0)], straight[at(6, 0)], straight[at(1, 2)]), (0.0, 5.0, 2.0)); @@ -360,8 +376,8 @@ mod tests { #[test] fn shared_trail_steps_find_what_each_texel_walking_its_own_finds() { - // About one texel in fifty a shape, in a region whose rows end part way through a word - // Small enough that the walk's float sums round as exactly as the shared steps (thousands of texels across, a near tie can round a texel over) + // Sparse rows end partway through a word + // Keep the region small enough to avoid rounding nearly tied rays into different texels let (width, height) = (150, 97); let mut seed = 12345u32; let inside: Vec = (0..width * height) diff --git a/crates/compose/src/soft_box.rs b/crates/compose/src/soft_box.rs index b1fba4f7..7145148b 100644 --- a/crates/compose/src/soft_box.rs +++ b/crates/compose/src/soft_box.rs @@ -16,11 +16,16 @@ const EDGE_FADE_START: f32 = 0.8; const EDGE_FADE_WIDTH: f32 = 0.4; impl SoftBox { - /// The light the box sends along direction `d` - pub fn eval(&self, d: Vec3) -> Vec3 { - let elevation = d.y.clamp(-1.0, 1.0).asin().to_degrees(); - let azimuth = d.z.atan2(d.x).to_degrees(); + /// Convert the sampled direction to degrees once for all the lights + pub fn angles(direction: Vec3) -> (f32, f32) { + let elevation = direction.y.clamp(-1.0, 1.0).asin().to_degrees(); + let azimuth = direction.z.atan2(direction.x).to_degrees(); + (azimuth, elevation) + } + + /// The light the box sends along the sampled azimuth and elevation + pub fn eval(&self, azimuth: f32, elevation: f32) -> Vec3 { // The azimuth difference wrapped to -180..180 degrees let azimuth_step = ((azimuth - self.azimuth + 540.0).rem_euclid(360.0)) - 180.0; let (x, y) = (azimuth_step.abs() / self.half_width, (elevation - self.elevation).abs() / self.half_height); diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 423b6975..014e9ec5 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -980,6 +980,7 @@ fn filter_input_and_id_map_image_changes_invalidate_stack_key() { for name in ["input", "id"] { let original = stack_key(&fixture, &images); images.insert(name.into(), flat_image(0.9)); + assert!(stack_key(&fixture, &images) != original, "replacing the {name} image must invalidate the cache"); } } @@ -995,6 +996,7 @@ fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() { let unlit = stack_key(&fixture, &images); fixture.project.display.env_rotation += 90.0; + assert_eq!(stack_key(&fixture, &images), unlit, "without Baked Lighting Environment the turn changes nothing"); let lighting = @@ -1008,6 +1010,7 @@ fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() { assert_eq!(lit.changed_tiles(&turned), None, "and recomposites every tile"); images.insert("sky".into(), flat_image(0.9)); + assert!(stack_key(&fixture, &images) != turned, "replacing the environment image invalidates the cache"); } diff --git a/crates/core/src/color_match.rs b/crates/core/src/color_match.rs index c945bf72..8b25ee85 100644 --- a/crates/core/src/color_match.rs +++ b/crates/core/src/color_match.rs @@ -51,28 +51,44 @@ impl ColorMatch { /// Linear `color` moved by the step from `source` to `target`; without Custom Color Variation it keeps all of its difference from the source, with it at most Hue, Chroma and Luma of it (all 0: the target color itself). Hostile values give the color back pub fn apply(&self, color: [f32; 3], source: [f32; 3], target: [f32; 3]) -> [f32; 3] { - let [lightness, a, b] = oklab::from_linear(color.map(|v| v.max(0.0))); - let [source_lightness, source_a, source_b] = oklab::from_linear(source.map(|v| v.max(0.0))); - let [target_lightness, target_a, target_b] = oklab::from_linear(target.map(|v| v.max(0.0))); + let lab = |color: [f32; 3]| oklab::from_linear(color.map(|component| component.max(0.0))); + let [lightness, a, b] = lab(color); + let [source_lightness, source_a, source_b] = lab(source); + let [target_lightness, target_a, target_b] = lab(target); let moved = if self.custom_variation { - let limit = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 }; - let keep = |difference: f32, max: f32| difference.clamp(-max, max); - let (chroma, hue) = (a.hypot(b), b.atan2(a)); - let (source_chroma, source_hue) = (source_a.hypot(source_b), source_b.atan2(source_a)); - let (target_chroma, target_hue) = (target_a.hypot(target_b), target_b.atan2(target_a)); - let turn = (hue - source_hue + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI; - let out_lightness = target_lightness + keep(lightness - source_lightness, limit(self.luma, Self::MAX_LUMA)); - let out_chroma = (target_chroma + keep(chroma - source_chroma, limit(self.chroma, Self::MAX_CHROMA))).max(0.0); - let out_hue = target_hue + keep(turn, limit(self.hue, Self::MAX_HUE_DEGREES).to_radians()); - [out_lightness, out_chroma * out_hue.cos(), out_chroma * out_hue.sin()] + self.move_polar(polar([lightness, a, b]), polar([source_lightness, source_a, source_b]), polar([target_lightness, target_a, target_b])) } else { [target_lightness + lightness - source_lightness, target_a + a - source_a, target_b + b - source_b] }; - let out = oklab::to_linear(moved); - if out.iter().all(|v| v.is_finite()) { out.map(|v| v.clamp(0.0, 1.0)) } else { color } + matched_linear(color, moved) } + + #[inline] + pub(super) fn move_polar( + &self, + [lightness, chroma, hue]: [f32; 3], + [source_lightness, source_chroma, source_hue]: [f32; 3], + [target_lightness, target_chroma, target_hue]: [f32; 3], + ) -> [f32; 3] { + let limit = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 }; + let keep = |difference: f32, max: f32| difference.clamp(-max, max); + let turn = (hue - source_hue + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI; + let out_lightness = target_lightness + keep(lightness - source_lightness, limit(self.luma, Self::MAX_LUMA)); + let out_chroma = (target_chroma + keep(chroma - source_chroma, limit(self.chroma, Self::MAX_CHROMA))).max(0.0); + let out_hue = target_hue + keep(turn, limit(self.hue, Self::MAX_HUE_DEGREES).to_radians()); + [out_lightness, out_chroma * out_hue.cos(), out_chroma * out_hue.sin()] + } +} + +pub(super) fn polar([lightness, a, b]: [f32; 3]) -> [f32; 3] { + [lightness, a.hypot(b), b.atan2(a)] +} + +pub(super) fn matched_linear(original: [f32; 3], lab: [f32; 3]) -> [f32; 3] { + let out = oklab::to_linear(lab); + if out.iter().all(|value| value.is_finite()) { out.map(|value| value.clamp(0.0, 1.0)) } else { original } } #[cfg(test)] diff --git a/crates/core/src/curve_preset.rs b/crates/core/src/curve_preset.rs index 97d843c4..fe586794 100644 --- a/crates/core/src/curve_preset.rs +++ b/crates/core/src/curve_preset.rs @@ -124,6 +124,7 @@ mod tests { fn every_preset_stays_in_range_and_reads_a_non_finite_t_as_0() { for preset in CurvePreset::ALL { let values: Vec = (0..=SAMPLES).map(|i| preset.at(i as f32 / SAMPLES as f32)).collect(); + assert!(values.iter().all(|value| (0.0..=1.0).contains(value)), "{}", preset.id()); assert_eq!(preset.at(f32::NAN), preset.at(0.0), "{}", preset.id()); assert_eq!(preset.at(f32::INFINITY), preset.at(0.0), "{}", preset.id()); @@ -134,6 +135,7 @@ mod tests { fn stairs_has_four_levels_and_triangular_two_teeth() { let mut levels: Vec = (0..=SAMPLES).map(|i| CurvePreset::Stairs.at(i as f32 / SAMPLES as f32)).collect(); levels.dedup(); + assert_eq!(levels, [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]); let triangular = |t: f32| CurvePreset::Triangular.at(t); diff --git a/crates/core/src/gradient_input.rs b/crates/core/src/gradient_input.rs index 12f99b20..042b59dd 100644 --- a/crates/core/src/gradient_input.rs +++ b/crates/core/src/gradient_input.rs @@ -2,8 +2,8 @@ use serde::{Deserialize, Serialize}; -use crate::finite_unit; use crate::grayscale_mode::GrayscaleMode; +use crate::{ChannelKind, finite_unit, lum, per_unit}; /// Full contrast stays a finite step instead of a division by zero const MIN_STEEPNESS: f32 = 1e-3; @@ -44,13 +44,23 @@ impl GradientInput { /// The ramp position of gray `x` pub fn shape(&self, x: f32) -> f32 { - // Left as it is, the gray reaches the ramp bit for bit as projects saved before read it (the ramp clamps it) + // Preserve the exact input when the transformation is neutral if self.balance == NEUTRAL_BALANCE && self.contrast == 0.0 && !self.invert { return x; } shape_gray(x, self.balance, self.contrast, self.invert) } + + /// Apply a gradient to a channel using its ramp sampler + pub fn map(&self, kind: ChannelKind, value: [f32; 3], sample: impl Fn(f32) -> Option<[f32; 3]>) -> Option<[f32; 3]> { + if kind == ChannelKind::Color { + return sample(self.shape(self.mode.gray(value))); + } + + // Preserve the signed-channel mapping and leave normals alone + Some(per_unit(kind, value, |gray| sample(self.shape(gray)).map_or(gray, lum))) + } } /// Gray `x` balanced (0.5 keeps it), contrasted around mid gray (0 keeps it, 1 is a step at 0.5) and maybe inverted, in 0..1 @@ -64,17 +74,21 @@ pub fn shape_gray(x: f32, balance: f32, contrast: f32, invert: bool) -> f32 { /// A ramp stop's place and color type Stop = (f32, [f32; 3]); +pub(crate) fn ramp_stops<'a>(colors: &'a [[f32; 3]], positions: &'a [f32]) -> impl ExactSizeIterator + 'a { + let last = colors.len().saturating_sub(1); + colors.iter().copied().enumerate().map(move |(index, color)| { + let even_position = || if last == 0 { 0.0 } else { index as f32 / last as f32 }; + let position = positions.get(index).copied().filter(|position| position.is_finite()).unwrap_or_else(even_position); + (position.clamp(0.0, 1.0), color) + }) +} + /// The color at `t` on a ramp of `colors` placed at `positions` (each 0..1, evenly spaced where missing), blended in linear or sRGB pub fn ramp(colors: &[[f32; 3]], positions: &[f32], linear: bool, t: f32) -> Option<[f32; 3]> { - let last = colors.len().checked_sub(1)?; - let even = |index: usize| if last == 0 { 0.0 } else { index as f32 / last as f32 }; - let stops = colors - .iter() - .enumerate() - .map(|(index, color)| (positions.get(index).copied().filter(|p| p.is_finite()).unwrap_or_else(|| even(index)).clamp(0.0, 1.0), *color)); + let stops = ramp_stops(colors, positions); let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; - // The stops each side of `t` without sorting them, per texel: the last placed at or before it and the first placed after it + // Keep the last stop at or before the sample and the first stop after it let (mut before, mut after): (Option, Option) = (None, None); for (position, color) in stops { if position <= t { @@ -91,15 +105,14 @@ pub fn ramp(colors: &[[f32; 3]], positions: &[f32], linear: bool, t: f32) -> Opt (None, None) => return None, }; + let encode = |color: [f32; 3]| if linear { color } else { color.map(linear_to_srgb) }; + Some(interpolate((before_place, encode(before_color)), (after_place, encode(after_color)), linear, t)) +} + +pub(crate) fn interpolate((before_place, before_color): Stop, (after_place, after_color): Stop, linear: bool, t: f32) -> [f32; 3] { let share = if after_place > before_place { ((t - before_place) / (after_place - before_place)).clamp(0.0, 1.0) } else { 0.0 }; - Some(if linear { - std::array::from_fn(|k| before_color[k] + (after_color[k] - before_color[k]) * share) - } else { - std::array::from_fn(|k| { - let (before, after) = (linear_to_srgb(before_color[k]), linear_to_srgb(after_color[k])); - srgb_to_linear(before + (after - before) * share) - }) - }) + let color = std::array::from_fn(|component| before_color[component] + (after_color[component] - before_color[component]) * share); + if linear { color } else { color.map(srgb_to_linear) } } // A copy of texturecraft_texel's: texel and core are both layer 0, so core cannot use it diff --git a/crates/core/src/grayscale_conversion.rs b/crates/core/src/grayscale_conversion.rs index 3f186a7d..126b9b3b 100644 --- a/crates/core/src/grayscale_conversion.rs +++ b/crates/core/src/grayscale_conversion.rs @@ -69,10 +69,13 @@ mod tests { fn weights_balance_contrast_and_invert_shape_the_gray() { let only_red = GrayscaleConversion { weights: [1.0, 0.0, 0.0, 0.0], ..GrayscaleConversion::LIBRARY }; assert!((only_red.gray([0.6, 1.0, 1.0], 1.0) - 0.6).abs() < 1e-6); + let alpha = GrayscaleConversion { weights: [0.0, 0.0, 0.0, 1.0], ..GrayscaleConversion::LIBRARY }; assert!((alpha.gray([1.0; 3], 0.25) - 0.25).abs() < 1e-6, "Alpha weighs the coverage"); + let inverted = GrayscaleConversion { invert: true, mode: ConversionMode::Max, ..GrayscaleConversion::LIBRARY }; assert!((inverted.gray([0.2, 0.7, 0.1], 1.0) - 0.3).abs() < 1e-6); + let contrasted = GrayscaleConversion { contrast: 1.0, mode: ConversionMode::Average, ..GrayscaleConversion::LIBRARY }; assert_eq!(contrasted.gray([0.6; 3], 1.0), 1.0); } diff --git a/crates/core/src/image_input.rs b/crates/core/src/image_input.rs index d935074f..751911c3 100644 --- a/crates/core/src/image_input.rs +++ b/crates/core/src/image_input.rs @@ -78,6 +78,7 @@ mod tests { fn a_warp_has_its_custom_noise_only_in_that_source_mode() { let warp = SourceWarp::LIBRARY; assert!(ImageInput::of(&Filter::SourceWarp(warp)).is_empty()); + let custom = SourceWarp { source: WarpSource { mode: WarpSourceMode::CustomNoise, ..warp.source }, ..warp }; assert_eq!(ImageInput::of(&Filter::SourceWarp(custom)), vec![ImageInput::CUSTOM_NOISE]); assert_eq!(ImageInput::named(&Filter::SourceWarp(warp), "customNoise"), Some(ImageInput::CUSTOM_NOISE), "kept while the mode is off"); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 1ff4e0fc..c819446b 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -8,39 +8,49 @@ use crate::curve_preset::CurvePreset; use crate::gradient_input::{GradientInput, ramp, shape_gray}; use crate::{ AnisotropicKuwahara, Backface, BakedMap, Bevel, BevelSmooth, BlendMode, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, DepthCulling, - DirectionalDistance, DirectionalLight, FillSymmetry, GrayscaleConversion, HeightToNormal, HighpassSpace, MaskOutline, Mirror, PbrValidate, Projector, - RandomizedSeed, ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, + DirectionalDistance, DirectionalLight, GrayscaleConversion, HeightToNormal, HighpassSpace, MaskOutline, Mirror, PbrValidate, Projector, RandomizedSeed, + ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, }; mod curvature_detail; mod curvature_mode; mod decal_flip; mod decal_symmetry; +mod filtering; mod generator_global; mod micro_detail; mod output_resolution; mod resolution_mode; +mod sampling; +mod scale_mode; mod tile_blending; mod tile_generator; mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; +mod uv_transform; +mod uv_wrap; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; +pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; +pub use sampling::Sampling; +pub use scale_mode::ScaleMode; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; +pub use uv_transform::UvTransform; +pub use uv_wrap::UvWrap; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -1425,6 +1435,7 @@ pub fn hsl_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [ if s <= 0.0 { return [l; 3]; } + let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; let p = 2.0 * l - q; [hue_to_rgb(p, q, h + 1.0 / 3.0), hue_to_rgb(p, q, h), hue_to_rgb(p, q, h - 1.0 / 3.0)] @@ -1621,11 +1632,7 @@ impl Filter { _ => per_unit(kind, v, |x| finite_unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)), } } - Filter::GradientMap { input, .. } => match kind { - ChannelKind::Color => self.ramp_at(input.shape(input.mode.gray(v)))?, - // A height reads the ramp at its 0..1 place, as projects saved before did - _ => per_unit(kind, v, |x| self.ramp_at(input.shape(x)).map_or(x, lum)), - }, + Filter::GradientMap { input, .. } => input.map(kind, v, |position| self.ramp_at(position))?, Filter::GradientCurve { preset, invert, balance, contrast } => per_unit(kind, v, |x| preset.at(shape_gray(x, *balance, *contrast, *invert))), Filter::GradientDynamic { color, .. } => match kind { ChannelKind::Color => color.map(finite_unit), @@ -2366,6 +2373,7 @@ mod tests { let x = step as f32 / 1000.0; let color = [x, 0.5 * x, 1.0 - x]; assert_eq!(gm.point(ChannelKind::Color, color), gradient(&colors, lum(color)), "color {color:?}"); + let height = 2.0 * x - 1.0; let saved_before = per_unit(ChannelKind::Signed, [height; 3], |t| gradient(&colors, t).map_or(t, lum)); assert_eq!(gm.point(ChannelKind::Signed, [height; 3]), Some(saved_before), "height {height}"); @@ -2379,29 +2387,39 @@ mod tests { let cl = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 }; assert!(close(cl.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0])); assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3])); + let gm = Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]); assert!(close(gm.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0])); assert!(close(gm.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0])); assert_eq!(Filter::even_gradient(vec![]).point(c, [0.3; 3]), None, "an empty gradient changes nothing"); + let gray_ramp = Filter::even_gradient(vec![[0.0; 3], [1.0; 3]]); assert!(close(gray_ramp.point(ChannelKind::Signed, [-0.6; 3]).unwrap(), [-0.6; 3]), "a height reads the ramp at its 0..1 place"); assert!(close(Filter::Posterize { levels: 2.0, alpha: false }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic"); + let scan = |position, contrast| Filter::HistogramScan { position, contrast, invert_position: false }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values"); assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white"); assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9])); + let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3])); assert!(close(range(0.5, 0.5), [0.35, 0.5, 0.7])); + let shift = |offset| Filter::HistogramShift { offset }.point(c, [0.0, 0.5, 1.0]).unwrap(); + assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white"); assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75])); + let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] }; assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99); assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3])); assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0])); + for f in [ Filter::Blur { radius: 1.0, wrap: false }, Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0, divider: 1 }, diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index b05c708b..88ee96d1 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -45,6 +45,8 @@ pub mod mirror_mode; pub mod oklab; pub mod outline_position; pub mod pbr_validate; +mod prepared_color_match; +mod prepared_gradient; pub mod project; pub mod projector; pub mod ramp_curve; @@ -122,6 +124,8 @@ pub use mirror_corner::MirrorCorner; pub use mirror_mode::MirrorMode; pub use outline_position::OutlinePosition; pub use pbr_validate::PbrValidate; +pub use prepared_color_match::PreparedColorMatch; +pub use prepared_gradient::PreparedGradient; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MAX_SWATCHES, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, diff --git a/crates/core/src/mask_outline.rs b/crates/core/src/mask_outline.rs index cbd17456..de70f808 100644 --- a/crates/core/src/mask_outline.rs +++ b/crates/core/src/mask_outline.rs @@ -72,8 +72,10 @@ mod tests { assert_eq!(band(outline, false, 0.3), 1.0, "a hard band outside"); assert_eq!(band(outline, true, 0.3), 0.0, "nothing inside an outside band"); assert_eq!(band(outline, false, 0.0), 0.0, "nothing past its reach"); + let inside = MaskOutline { position: OutlinePosition::Inside, ..outline }; assert_eq!((band(inside, true, 0.3), band(inside, false, 0.3)), (1.0, 0.0)); + let both = MaskOutline { position: OutlinePosition::Both, ..outline }; assert_eq!((band(both, true, 0.3), band(both, false, 0.3)), (1.0, 1.0)); assert_eq!(outline.apply(0.4, 0.0), 0.0, "from black"); diff --git a/crates/core/src/mirror.rs b/crates/core/src/mirror.rs index 44831b81..9a2bd491 100644 --- a/crates/core/src/mirror.rs +++ b/crates/core/src/mirror.rs @@ -73,18 +73,23 @@ mod tests { let mut mirror = Mirror::LIBRARY; assert_eq!(mirror.source([0.25, 0.4]), [0.25, 0.4], "the left side stays"); assert_eq!(mirror.source([0.75, 0.4]), [0.25, 0.4], "the right side reads the left"); + mirror.invert[0] = true; + assert_eq!(mirror.source([0.25, 0.4]), [0.75, 0.4], "inverted, the left side reads the right"); mirror.offset[0] = 0.25; mirror.invert[0] = false; + assert_eq!(mirror.source([0.75, 0.0]), [0.25, 0.0], "a copy past the left edge folds back at it"); mirror.mode = MirrorMode::AxisY; + assert_eq!(mirror.source([0.9, 0.75]), [0.9, 0.25], "Axis Y reads the top for the bottom"); mirror.mode = MirrorMode::Corner; mirror.corner = MirrorCorner::BottomRight; + assert_eq!(mirror.source([0.25, 0.25]), [0.75, 0.75], "every quarter reads the kept one"); assert_eq!(mirror.source([0.75, 0.75]), [0.75, 0.75]); assert!(mirror.on_axis([0.5, 0.1], 0.01) && mirror.on_axis([0.1, 0.5], 0.01) && !mirror.on_axis([0.1, 0.1], 0.01)); diff --git a/crates/core/src/prepared_color_match.rs b/crates/core/src/prepared_color_match.rs new file mode 100644 index 00000000..0c97fa57 --- /dev/null +++ b/crates/core/src/prepared_color_match.rs @@ -0,0 +1,35 @@ +//! Reusable OKLab references for moving a region of colors + +use crate::color_match::{matched_linear, polar}; +use crate::{ColorMatch, oklab}; + +/// The settings and converted references for a region with constant source and target colors +#[derive(Clone, Copy, Debug)] +pub struct PreparedColorMatch { + settings: ColorMatch, + source: [f32; 3], + target: [f32; 3], +} + +impl PreparedColorMatch { + /// Prepare the fixed reference pair once for the region + pub fn new(settings: ColorMatch, source: [f32; 3], target: [f32; 3]) -> Self { + let reference = |color: [f32; 3]| { + let lab = oklab::from_linear(color.map(|component| component.max(0.0))); + if settings.custom_variation { polar(lab) } else { lab } + }; + Self { settings, source: reference(source), target: reference(target) } + } + + /// Move a texel using the prepared reference pair + pub fn apply(&self, color: [f32; 3]) -> [f32; 3] { + let lab = oklab::from_linear(color.map(|component| component.max(0.0))); + let moved = if self.settings.custom_variation { + self.settings.move_polar(polar(lab), self.source, self.target) + } else { + std::array::from_fn(|index| self.target[index] + lab[index] - self.source[index]) + }; + + matched_linear(color, moved) + } +} diff --git a/crates/core/src/prepared_gradient.rs b/crates/core/src/prepared_gradient.rs new file mode 100644 index 00000000..4e5fa307 --- /dev/null +++ b/crates/core/src/prepared_gradient.rs @@ -0,0 +1,35 @@ +use crate::gradient_input::{interpolate, linear_to_srgb, ramp_stops}; +use crate::{ChannelKind, Filter, GradientInput}; + +/// An sRGB gradient prepared for repeated sampling +pub struct PreparedGradient { + stops: Vec<(f32, [f32; 3])>, + input: GradientInput, +} + +impl PreparedGradient { + /// Prepare an sRGB ramp by converting its endpoints once + pub fn of(filter: &Filter) -> Option { + let Filter::GradientMap { positions, linear: false, input, .. } = filter else { return None }; + + let mut stops: Vec<_> = ramp_stops(filter.ramp_colors(), positions).map(|(position, color)| (position, color.map(linear_to_srgb))).collect(); + + // Stable order preserves which stop wins at shared positions + stops.sort_by(|left, right| left.0.total_cmp(&right.0)); + Some(Self { stops, input: *input }) + } + + /// Sample the prepared ramp at a normalized position + pub fn at(&self, position: f32) -> Option<[f32; 3]> { + let position = if position.is_finite() { position.clamp(0.0, 1.0) } else { 0.0 }; + let split = self.stops.partition_point(|stop| stop.0 <= position); + let before = split.checked_sub(1).and_then(|index| self.stops.get(index)).copied(); + let after = self.stops.get(split).copied(); + Some(interpolate(before.or(after)?, after.or(before)?, false, position)) + } + + /// Apply the prepared gradient to one value + pub fn point(&self, kind: ChannelKind, value: [f32; 3]) -> Option<[f32; 3]> { + self.input.map(kind, value, |position| self.at(position)) + } +} diff --git a/crates/core/src/source_warp.rs b/crates/core/src/source_warp.rs index 4891f752..f4b5b76a 100644 --- a/crates/core/src/source_warp.rs +++ b/crates/core/src/source_warp.rs @@ -109,12 +109,16 @@ mod tests { let warp = SourceWarp::LIBRARY; assert!((warp.move_texels(2048) - 20.48).abs() < 1e-3, "0.1 ÷ 10 of the tile"); assert_eq!(warp.angles().count(), 0); + let directional = SourceWarp { mode: WarpMode::Directional, angle: 30.0, ..warp }; assert_eq!(directional.angles().collect::>(), vec![30.0]); + let multi = SourceWarp { mode: WarpMode::MultiDirectional, angle: 10.0, ..warp }; assert_eq!(multi.angles().collect::>(), vec![10.0, 100.0, 190.0, 280.0]); + let chained = SourceWarp { blending: WarpBlending::Chain, ..multi }; assert!((chained.reach(2048) - 4.0 * 20.48).abs() < 1e-3, "four moves one after the other"); + let input = SourceWarp { source: WarpSource { mode: WarpSourceMode::PreviousInput, ..WarpSource::LIBRARY }, ..warp }; assert!((input.reach(2048) - (20.48 + 8.0)).abs() < 1e-3, "plus where it measures the slope"); assert_eq!((SourceWarp::amount(0.0), SourceWarp::amount(0.5), SourceWarp::amount(1.0)), (-1.0, 0.0, 1.0)); @@ -125,8 +129,10 @@ mod tests { let warp = SourceWarp::LIBRARY; let gentle = warp.slope_move([0.01, 0.0], 2048); assert!(gentle[0] > 0.0 && gentle[0] < warp.move_texels(2048), "{gentle:?}"); + let steep = warp.slope_move([1.0, 1.0], 2048); assert!((steep[0].hypot(steep[1]) - warp.move_texels(2048)).abs() < 1e-3, "a cliff moves the whole way, no further: {steep:?}"); + let hostile = SourceWarp { intensity: f32::NAN, angle: f32::INFINITY, directions: 9, divider: 0, mode: WarpMode::MultiDirectional, ..warp }; assert_eq!((hostile.move_texels(2048), hostile.angles().collect::>()), (0.0, vec![0.0])); assert_eq!(hostile.slope_move([f32::NAN, 1.0], 2048)[0], 0.0); diff --git a/crates/core/src/stylized_lighting.rs b/crates/core/src/stylized_lighting.rs index 3c5289d8..3aa0801b 100644 --- a/crates/core/src/stylized_lighting.rs +++ b/crates/core/src/stylized_lighting.rs @@ -136,6 +136,7 @@ mod tests { let smooth = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2)); let rough = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.9)); assert!(smooth[0] > rough[0] + 0.1 && rough[0] > 0.0, "{smooth:?} {rough:?}"); + let diffuse = StylizedLighting { output: LightingOutput::Diffuse, ..StylizedLighting::library() }; assert_eq!(diffuse.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2)), [0.0; 3]); } @@ -148,9 +149,11 @@ mod tests { let cavities = StylizedLighting { diffuse_cavity: 1.0, ..StylizedLighting::PLAIN }; assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat: no cavity"); assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity"); + let sun = light(90.0, 1.0, 0.0); assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat in the sun: no cavity"); assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity in the sun"); + let edges = StylizedLighting { edges_intensity: 1.0, ..StylizedLighting::PLAIN }; assert_eq!(edges.shading(sky).shade(gray, UP, [1.0, 0.9], &material(0.5)), [1.0; 3], "a sharp edge"); } diff --git a/crates/core/src/stylized_shading.rs b/crates/core/src/stylized_shading.rs index 57d4d5ca..24bcdda8 100644 --- a/crates/core/src/stylized_shading.rs +++ b/crates/core/src/stylized_shading.rs @@ -101,6 +101,8 @@ impl StylizedShading { let kept = if self.output.specular() { 1.0 - metal } else { 1.0 }; (finite_unit(channel(Channel::Roughness)[0]), f0, albedo.map(|x| x * kept)) }; + let compute_diffuse = self.output.diffuse(); + let compute_specular = self.output.specular(); let roughness = roughness.max(MIN_ROUGHNESS); let sky = self.ambient(normal); @@ -109,7 +111,7 @@ impl StylizedShading { let diffuse_cavity = 1.0 - cavity * self.diffuse_cavity; let specular_cavity = 1.0 - cavity * self.specular_cavity; - let mut diffuse = sky.map(|sky_light| sky_light * self.sky_intensity * diffuse_ao * diffuse_cavity); + let mut diffuse = if compute_diffuse { sky.map(|sky_light| sky_light * self.sky_intensity * diffuse_ao * diffuse_cavity) } else { [0.0; 3] }; let mut specular = [0.0f32; 3]; for &(direction, intensity, color) in &self.lights { let facing = dot(normal, direction); @@ -117,21 +119,29 @@ impl StylizedShading { continue; } - let half = normalize([normal[0] + direction[0], normal[1] + direction[1], normal[2] + direction[2]]); - let normal_dot_half = dot(normal, half).max(0.0); - let highlight = ggx(normal_dot_half, roughness) / COOK_TORRANCE_DENOMINATOR * facing * specular_cavity; - for (((diffuse, specular), color), f0) in diffuse.iter_mut().zip(&mut specular).zip(color).zip(f0) { - *diffuse += color * intensity * facing * diffuse_cavity; - *specular += color * intensity * highlight * schlick(f0, normal_dot_half); + if compute_diffuse { + for (diffuse, color) in diffuse.iter_mut().zip(color) { + *diffuse += color * intensity * facing * diffuse_cavity; + } + } + if compute_specular { + let half = normalize([normal[0] + direction[0], normal[1] + direction[1], normal[2] + direction[2]]); + let normal_dot_half = dot(normal, half).max(0.0); + let highlight = ggx(normal_dot_half, roughness) / COOK_TORRANCE_DENOMINATOR * facing * specular_cavity; + for ((specular, color), f0) in specular.iter_mut().zip(color).zip(f0) { + *specular += color * intensity * highlight * schlick(f0, normal_dot_half); + } } } - for ((specular, f0), sky_light) in specular.iter_mut().zip(f0).zip(sky) { - *specular += f0 * sky_light * self.sky_intensity * specular_ao * specular_cavity; + if compute_specular { + for ((specular, f0), sky_light) in specular.iter_mut().zip(f0).zip(sky) { + *specular += f0 * sky_light * self.sky_intensity * specular_ao * specular_cavity; + } } - std::array::from_fn(|k| { - let lit = if self.output.diffuse() { diffuse_albedo[k] * diffuse[k] } else { 0.0 }; - let shine = if self.output.specular() { specular[k] } else { 0.0 }; + std::array::from_fn(|channel| { + let lit = if compute_diffuse { diffuse_albedo[channel] * diffuse[channel] } else { 0.0 }; + let shine = specular[channel]; let shaded = finite_unit(lit + shine); finite_unit(shaded + (1.0 - shaded) * edge * self.edges_intensity) }) diff --git a/crates/core/src/threshold_mode.rs b/crates/core/src/threshold_mode.rs index 3dc3b05b..953b649d 100644 --- a/crates/core/src/threshold_mode.rs +++ b/crates/core/src/threshold_mode.rs @@ -73,6 +73,7 @@ mod tests { fn a_threshold_saved_before_the_modes_reads_and_saves_as_before() { let saved = r#"{"Threshold":{"level":0.5}}"#; let filter: Filter = serde_json::from_str(saved).unwrap(); + assert_eq!(filter, Filter::Threshold { level: 0.5, mode: ThresholdMode::GreaterOrEqual }); assert_eq!(serde_json::to_string(&filter).unwrap(), saved); assert_eq!(filter.point(ChannelKind::Scalar, [0.5; 3]), Some([1.0; 3]), "a value at the level turns white as before"); @@ -84,7 +85,9 @@ mod tests { assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Greater, value)), [Some(0.0), Some(0.0), Some(1.0)]); assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Lower, value)), [Some(1.0), Some(0.0), Some(0.0)]); assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::LowerOrEqual, value)), [Some(1.0), Some(1.0), Some(0.0)]); + let saved = serde_json::to_string(&Filter::Threshold { level: 0.01, mode: ThresholdMode::LowerOrEqual }).unwrap(); + assert!(saved.contains(r#""mode":"lowerOrEqual""#), "{saved}"); } } diff --git a/crates/core/src/tile_transform.rs b/crates/core/src/tile_transform.rs index a834f7c8..2807b801 100644 --- a/crates/core/src/tile_transform.rs +++ b/crates/core/src/tile_transform.rs @@ -161,14 +161,22 @@ mod tests { let mut transform = TileTransform { scaling: [2.0, 2.0], ..TileTransform::LIBRARY }; assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.5, 0.5]), "the centre stays"); assert!(near(transform.source([0.75, 0.5]).unwrap_or_default(), [0.0, 0.5]), "twice the content: a quarter tile reads half a tile on"); + transform.repeat = RepeatMode::None; + assert_eq!(transform.source([0.9, 0.5]), None, "past the content reads nothing without repeat"); + transform = TileTransform { offset: [0.25, 0.0], ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.75, 0.5])); assert!(near(transform.source([0.9, 0.5]).unwrap_or_default(), [0.15, 0.5]), "the read wraps round the tile"); + transform = TileTransform { flip: FlipMode::Horizontally, ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.8, 0.3])); + transform.flip = FlipMode::Vertically; + assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.2, 0.7])); } @@ -181,6 +189,7 @@ mod tests { // A small turn of the plain tile snaps back to no turn, never to nothing let small = TileTransform { rotation: 10.0, ..TileTransform::LIBRARY }; assert_eq!(small.affine().0, [[1.0, 0.0], [0.0, 1.0]]); + let tiny = TileTransform { scaling: [0.1, 0.1], rotation: 45.0, ..TileTransform::LIBRARY }; assert!(tiny.affine().0.iter().all(|column| column != &[0.0, 0.0])); @@ -213,6 +222,7 @@ mod tests { let transform = TileTransform { rotation: 359.99998, tile_safe, ..TileTransform::LIBRARY }; assert!(transform.is_identity(), "tile safe {tile_safe}: {:?}", transform.affine()); } + assert!(!TileTransform { rotation: 359.9, tile_safe: false, ..TileTransform::LIBRARY }.is_identity()); } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 1de76b29..bea50e17 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -569,10 +569,12 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { if let Some(input) = strp(params, "input") { return input_set(session, params, input); } + let target = fill_target(session, params, FILL_SET)?; if let FillTarget::Mask(effect) = target { return mask_fill_set(session, params, effect); } + let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; // `solo`: this channel on, every other one off diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 403459b5..4264b338 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -773,7 +773,7 @@ fn set(session: &mut Session, params: &Value) -> Result { _ => None, }; - // Naming the filter the effect already is edits its parameters like a plain effect.set (Directional Warp's former id also sets its mode); a warp saved before the warp modes has no mode to set, so another mode replaces it as a swap does + // Update matching filter variants in place and rebuild when the legacy filter lacks the requested mode let changes_saved_warp_mode = |filter: &str| matches!(session.doc.project.effect(effect), Some((_, Effect { kind: EffectKind::Filter(saved), .. })) if crate::filter_lib::changes_saved_warp_mode(filter, params, saved)); let swapped = match strp(params, "filter") { Some(EMPTY_FILTER) => Some(emptied_filter(session, effect)?), @@ -965,7 +965,7 @@ fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<( return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label))); } - // Built as effect.add.filter builds it, from the id given, so a former id such as `warpDirectional` sets the same mode it adds with + // Resolve legacy IDs the same way as effect.add.filter to preserve their modes let kind = crate::filter_lib::build_for(CMD, id, p)?; Ok((kind, def.label)) } diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 4a27474f..678d7bb7 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -51,10 +51,12 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, out.extend(link.outputs.values().cloned()); } } + for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { out.extend(effect.images_read().map(str::to_string)); out.extend(crate::path_tool::path_images(&effect.kind)); } + for child in layer.children() { images_used(project, *child, out, depth + 1); } diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index a0e6d366..c44dce36 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -121,6 +121,10 @@ pub fn filter(id: &str, size: usize) -> Option>> { // The filters that shape a mask's edge read where values cross 0.5: they get black and white shapes, where the clouds would leave them black let shapes = matches!(kind, EffectKind::Filter(Filter::BevelSmooth(_) | Filter::DirectionalDistance(_))); + render_filter_preview(kind, size, res, shapes) +} + +fn render_filter_preview(kind: EffectKind, size: usize, res: u32, shapes: bool) -> Option>> { let mesh = texturecraft_geom::primitives::plane(2.0, 2); let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res); let mut p = Project::new("preview", ""); @@ -210,9 +214,11 @@ mod tests { #[test] fn the_edge_shaping_filters_show_their_shapes_not_black() { - let size = 32; - // A neutral filter shows the checker as it is; an edge filter must change it - let checker = filter("levels", size).unwrap(); + const SIDE_PX: u32 = 32; + let size = SIDE_PX as usize; + + // Use the same checker input with an inactive filter + let checker = render_filter_preview(EffectKind::Filter(Filter::InvertOff), size, SIDE_PX, true).unwrap(); for id in ["bevelSmooth", "directionalDistance"] { let pixels = filter(id, size).unwrap(); assert!(pixels != checker, "{id}: the preview shows the unchanged checker"); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 241b5717..4fd5983e 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -757,19 +757,28 @@ impl Session { (Some(previous), Some(current)) => !Arc::ptr_eq(previous, current), (previous, current) => previous.is_some() != current.is_some(), }; - if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(|name| resource_changed(&name))) { + if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(resource_changed)) { self.path_cache = None; } // Removed or replaced resources may change any set's rendered content let removed_or_replaced_resource = previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); + if removed_or_replaced_resource { + for cache in &mut self.caches { + cache.invalidate_all(); + } + + return; + } + let added_resource_names: BTreeSet<&str> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect(); + let is_added = |name: &str| added_resource_names.contains(name); + let added_environment = self.doc.project.display.environment_resource().is_some_and(is_added); let uses_added_resource = |texture_set_index: usize| { - use texturecraft_core::{EffectKind, Fill}; + use texturecraft_core::{EffectKind, Fill, Filter}; - let is_added = |name: &str| added_resource_names.contains(name); let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package)); let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill); let project = &self.doc.project; @@ -777,12 +786,11 @@ impl Session { && project.texture_sets.get(texture_set_index).is_some_and(|set| { project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) - || layer - .mask - .iter() - .flat_map(|mask| &mask.effects) - .chain(&layer.content_effects) - .any(|effect| effect.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill))) + || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| { + effect.images_read().any(is_added) + || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill)) + || (added_environment && matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. }))) + }) }) }) }; diff --git a/crates/engine/src/tile_transform_params.rs b/crates/engine/src/tile_transform_params.rs index 86a0f807..bde8fdf4 100644 --- a/crates/engine/src/tile_transform_params.rs +++ b/crates/engine/src/tile_transform_params.rs @@ -10,6 +10,7 @@ use crate::layer_cmds::FULL_TURN_DEGREES; /// Set the Transform settings given in `p`; a value of the wrong kind is refused and changes nothing pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Result<()> { let mut edited = *transform; + if p.get("repeatMode").is_some() { let id = strp(p, "repeatMode").unwrap_or_default(); edited.repeat = @@ -22,6 +23,7 @@ pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Resu .find(|mode| mode.id() == id) .ok_or_else(|| bad(cmd, "`flipMode` must be none, horizontally, vertically or horizontallyAndVertically"))?; } + let (low, high) = TileTransform::SCALING; if let Some(scaling) = pair(p, "scaling", cmd)? { edited.scaling = scaling.map(|scale| scale.clamp(low, high)); @@ -29,6 +31,7 @@ pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Resu if let Some(offset) = pair(p, "offset", cmd)? { edited.offset = offset.map(|along| along.clamp(-TileTransform::MAX_OFFSET, TileTransform::MAX_OFFSET)); } + if p.get("tileSafeRotation").is_some() { edited.tile_safe = boolp(p, "tileSafeRotation").ok_or_else(|| bad(cmd, "`tileSafeRotation` must be true or false"))?; } @@ -36,6 +39,7 @@ pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Resu let degrees = f32p(p, "rotation").ok_or_else(|| bad(cmd, "`rotation` must be a number of degrees"))?; edited.rotation = degrees.rem_euclid(FULL_TURN_DEGREES); } + *transform = edited; Ok(()) } @@ -48,5 +52,6 @@ fn pair(p: &Value, key: &str, cmd: &str) -> Result> { Value::Array(items) if items.len() == 2 => items.first().and_then(number).zip(items.get(1).and_then(number)).map(|(x, y)| [x, y]), other => number(other).map(|both| [both, both]), }; + parsed.map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y] or one number"))) } diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index f1414b05..d9fbed69 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -34,38 +34,53 @@ fn content_effects_commands_inspect_and_round_trip() { let mut s = session(); let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0], "roughness": 0.2})).unwrap(), "layer"); let hsl = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "hsl", "mode": "regular", "hue": 1.0 / 3.0})).unwrap(), "effect"); + assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor)); assert!(s.doc.project.layer(LayerId(layer)).unwrap().mask.is_none(), "content effects don't create a mask"); assert_eq!(s.target, StackTarget::Effect(LayerId(hsl))); - // Mask-only effects refuse the content, unknown targets are errors. + // Mask-only effects refuse the content, unknown targets are errors assert!(execute(&mut s, "effect.add.generator", &json!({"target": "content"})).is_err()); assert!(execute(&mut s, "effect.add.filter", &json!({"target": "nope"})).is_err()); + execute(&mut s, "effect.set", &json!({"effect": hsl, "hue": 0.0, "lightness": -1.0})).unwrap(); + assert!(close(center(&mut s, Channel::BaseColor), [0.0; 3])); + execute(&mut s, "effect.set", &json!({"effect": hsl, "visible": false})).unwrap(); - // A content fill effect, edited through layer.fill.set. + // A content fill effect, edited through layer.fill.set let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap(), "effect"); + assert!(close(center(&mut s, Channel::Roughness), [0.7; 3])); assert!(close(center(&mut s, Channel::BaseColor), [1.0, 0.0, 0.0]), "channels without a source stay"); + execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "value": 0.9})).unwrap(); + assert!(close(center(&mut s, Channel::Roughness), [0.9; 3])); + execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "enabled": false})).unwrap(); + assert!(close(center(&mut s, Channel::Roughness), [0.2; 3])); assert!(execute(&mut s, "layer.fill.set", &json!({"effect": hsl, "channel": "roughness", "value": 0.5})).is_err(), "not a fill effect"); - // Inspect shows the content stack; the project survives a save/load round trip. + // Inspect shows the content stack; the project survives a save/load round trip let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); let kinds: Vec<&str> = row["contentEffects"].as_array().unwrap().iter().map(|effect| effect["kind"].as_str().unwrap()).collect(); + assert_eq!(kinds, ["HSL Perceptive", "Fill"], "{row}"); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); execute(&mut s, "layer.select", &json!({"layer": layer, "target": fill})).unwrap(); execute(&mut s, "effect.remove", &json!({"effect": fill})).unwrap(); + assert_eq!(s.target, StackTarget::Content); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layer(LayerId(layer)).unwrap().content_effects.len(), 2); } diff --git a/crates/engine/tests/it/filter_card.rs b/crates/engine/tests/it/filter_card.rs index ee9c25af..51c88f67 100644 --- a/crates/engine/tests/it/filter_card.rs +++ b/crates/engine/tests/it/filter_card.rs @@ -24,14 +24,19 @@ fn an_empty_filter_renders_nothing_until_one_is_picked() { assert_eq!(filter_of(&s, effect), Filter::Empty); assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Filter (empty)"); + assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "an empty filter leaves the color"); set(&mut s, effect, json!({"filter": "invert"})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Invert"); + assert_close(center(&mut s, Channel::BaseColor), [0.8; 3], "the picked filter works"); set(&mut s, effect, json!({"filter": "none"})); + assert_eq!(filter_of(&s, effect), Filter::Empty); + assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "emptied again"); } @@ -50,6 +55,7 @@ fn a_content_filter_leaves_the_channels_switched_off() { let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); let filter_row = row["contentEffects"].as_array().unwrap().iter().find(|filter_row| filter_row["id"] == effect.0).unwrap(); + assert_eq!(filter_row["offChannels"], json!(["roughness"])); execute(&mut s, "edit.undo", &Value::Null).unwrap(); @@ -57,6 +63,7 @@ fn a_content_filter_leaves_the_channels_switched_off() { set(&mut s, effect, json!({"channels": {"roughness": false}})); set(&mut s, effect, json!({"channels": {"roughness": true}})); + assert!(s.doc.project.effect(effect).unwrap().1.off_channels.is_empty()); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channels": {"nope": false}})).is_err()); @@ -90,12 +97,15 @@ fn the_divider_divides_the_intensity() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "divider": 7})).is_err()); set(&mut s, effect, json!({"divider": 100})); + assert!(matches!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur { divider: 100, .. }))); let saved = serde_json::to_value(Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 }).unwrap(); + assert_eq!(saved, json!({"Warp": {"intensity": 1.0, "scale": 2.0, "seed": 3}}), "saved as before dividers"); let loaded: Filter = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded, Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 }); } @@ -110,20 +120,24 @@ fn restore_defaults_puts_the_filters_parameters_back() { assert_eq!(s.history_labels().len(), steps, "no step at defaults"); set(&mut s, effect, json!({"intensity": 0.5, "seed": 9, "divider": 100, "channels": {"height": false}})); + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(), json!({"changed": true})); assert_eq!(filter_of(&s, effect), defaults); let restored = s.doc.project.effect(effect).unwrap().1.clone(); + assert_eq!(restored.name, "Wobble"); assert!(restored.off_channels.contains(&Channel::Height)); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(matches!(filter_of(&s, effect), Filter::SourceWarp(SourceWarp { divider: 100, seed: 9, .. })), "one undo step"); let empty = filtered_layer(&mut s, json!({"filter": "none"})).1; assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": empty.0})).unwrap(), json!({"changed": false})); let fill = execute(&mut s, "effect.add.fill", &json!({"target": "content"})).unwrap()["effect"].as_u64().unwrap(); + assert!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": fill})).is_err()); } @@ -136,5 +150,6 @@ fn filter_list_describes_and_tags_every_filter() { assert!(def["tags"].as_array().is_some_and(|tags| !tags.is_empty()), "{def}"); } let blur = listed.as_array().unwrap().iter().find(|def| def["id"] == "blur").unwrap(); + assert_eq!(blur["tags"], json!(["blur", "soften"])); } diff --git a/crates/engine/tests/it/filter_colour.rs b/crates/engine/tests/it/filter_colour.rs index f0bc3561..6106ba99 100644 --- a/crates/engine/tests/it/filter_colour.rs +++ b/crates/engine/tests/it/filter_colour.rs @@ -16,18 +16,22 @@ fn color_correct_changes_nothing_until_its_tones_move() { let mut s = session(); let color = [0.6, 0.3, 0.2]; let effect = filtered(&mut s, color, json!({"filter": "colorCorrect"})); + let neutral = filter_of(&s, effect); assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Color Correct"); assert!(distance(center(&mut s, Channel::BaseColor), color) < 4e-3, "the defaults change nothing"); set(&mut s, effect, json!({"shadows": [0.0, 0.0, 0.0], "midtones": [0.0, 0.0, 0.0], "highlights": [0.0, 0.0, 0.0]})); + let gray = center(&mut s, Channel::BaseColor); assert!((gray[0] - gray[1]).abs() < 4e-3 && (gray[1] - gray[2]).abs() < 4e-3, "saturation 0 everywhere is gray: {gray:?}"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(filter_of(&s, effect), neutral, "one undo step takes back all three tones"); set(&mut s, effect, json!({"midtones": [0.0, 0.3, 0.5], "shadows": [0.0, 0.3, 0.5], "highlights": [0.0, 0.3, 0.5]})); + let lighter = center(&mut s, Channel::BaseColor); assert!((0..3).all(|i| lighter[i] > color[i] + 0.1), "luminosity lifts every tone: {lighter:?}"); @@ -50,13 +54,16 @@ fn hsl_perceptive_turns_the_hue_at_the_same_lightness() { let mut s = session(); let yellow = [0.8, 0.7, 0.05]; let effect = filtered(&mut s, yellow, json!({"filter": "hsl", "hue": 0.5})); + assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: true, .. }), "new filters are perceptive"); let perceptive = center(&mut s, Channel::BaseColor); set(&mut s, effect, json!({"mode": "regular"})); + assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: false, .. })); let regular = center(&mut s, Channel::BaseColor); + // Rec. 709 luminance weights let relative_luminance = |c: [f32; 3]| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; let drift = |color: [f32; 3]| (relative_luminance(color) - relative_luminance(yellow)).abs(); @@ -66,6 +73,7 @@ fn hsl_perceptive_turns_the_hue_at_the_same_lightness() { // Saved before the mode: Regular, and saved again without the field let old: Filter = serde_json::from_value(json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}})).unwrap(); + assert_eq!(old, Filter::Hsl { hue: 0.5, saturation: 0.0, lightness: 0.0, perceptive: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}})); } @@ -75,6 +83,7 @@ fn hsl_perceptive_turns_the_hue_at_the_same_lightness() { fn contrast_luminosity_starts_neutral() { let mut s = session(); let effect = filtered(&mut s, [0.2; 3], json!({"filter": "contrastLuminosity"})); + assert_eq!(filter_of(&s, effect), Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.0 }); assert!(distance(center(&mut s, Channel::BaseColor), [0.2; 3]) < 4e-3); } @@ -84,17 +93,21 @@ fn contrast_luminosity_starts_neutral() { fn blur_and_bevel_take_the_edge_wrap() { let mut s = session(); let blur = filtered(&mut s, [0.2; 3], json!({"filter": "blur"})); + assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: false, .. })); set(&mut s, blur, json!({"wrap": true})); + assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: true, .. })); assert!(execute(&mut s, "effect.set", &json!({"effect": blur.0, "wrap": "yes"})).is_err()); let bevel = filtered(&mut s, [0.2; 3], json!({"filter": "bevel", "wrap": true})); + assert!(matches!(filter_of(&s, bevel), Filter::DistanceBevel(Bevel { wrap: true, .. }))); let old: Filter = serde_json::from_value(json!({"Blur": {"radius": 4.0}})).unwrap(); + assert_eq!(old, Filter::Blur { radius: 4.0, wrap: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Blur": {"radius": 4.0}}), "off is not saved"); } diff --git a/crates/engine/tests/it/filter_gradient.rs b/crates/engine/tests/it/filter_gradient.rs index 738c5390..d73e2913 100644 --- a/crates/engine/tests/it/filter_gradient.rs +++ b/crates/engine/tests/it/filter_gradient.rs @@ -16,6 +16,7 @@ fn near(a: f32, b: f32) -> bool { fn a_gradient_saved_before_reads_and_saves_as_before() { let saved = json!({"GradientMap": {"colors": [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]}}); let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(filter, Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]])); assert_eq!(serde_json::to_value(&filter).unwrap(), saved, "nothing new is saved"); @@ -40,12 +41,15 @@ fn gradient_places_quantity_and_input_transformation() { assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY / 2.0), "halfway from black to mid gray"); set(&mut s, effect, json!({"positions": [0.0, 0.25, 1.0]})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY), "mid gray moved to 0.25"); set(&mut s, effect, json!({"invert": true})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.5 / 0.75)), "inverted, it reads 0.75"); set(&mut s, effect, json!({"invert": false, "balance": 0.75})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.25 / 0.75)), "balance 0.75 lifts it to 0.5"); set(&mut s, effect, json!({"balance": 0.5, "positions": [0.0, 0.5, 1.0], "linear": false})); @@ -53,6 +57,7 @@ fn gradient_places_quantity_and_input_transformation() { assert!(near(srgb, 0.0508), "blended in sRGB, halfway from black to mid gray is sRGB 0.25: {srgb}"); set(&mut s, effect, json!({"quantity": 4})); + assert_eq!(filter_of(&s, effect).ramp_colors().len(), 4); refused( @@ -93,6 +98,7 @@ fn display_gradient_shows_the_ramp_across_the_texture() { let effect = filtered(&mut s, [0.9; 3], json!({"filter": "gradientMap", "debug": true})); let (value, uv) = (center(&mut s, Channel::BaseColor), center_uv(&mut s)); let ramp = filter_of(&s, effect).ramp_at(uv.x).unwrap(); + assert!((0..3).all(|k| (value[k] - ramp[k]).abs() < 0.03), "{value:?} vs {ramp:?} at u {}", uv.x); } @@ -136,9 +142,11 @@ fn gradient_curve_remaps_through_its_preset() { assert!(near(center(&mut s, Channel::BaseColor)[0], round), "Round at 0.25"); set(&mut s, effect, json!({"preset": "easeIn"})); + assert!(near(center(&mut s, Channel::BaseColor)[0], 0.0625), "Ease In at 0.25"); set(&mut s, effect, json!({"invert": true})); + assert!(near(center(&mut s, Channel::BaseColor)[0], 0.5625), "Ease In at 0.75"); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "preset": "spiral"})).is_err()); diff --git a/crates/engine/tests/it/filter_inputs.rs b/crates/engine/tests/it/filter_inputs.rs index 423eab27..23611860 100644 --- a/crates/engine/tests/it/filter_inputs.rs +++ b/crates/engine/tests/it/filter_inputs.rs @@ -41,21 +41,26 @@ fn a_distance_map_scales_the_bevel_smooth_distance() { assert_eq!(inputs(&s, effect), vec![("distanceMap".to_string(), Source::Uniform([0.5; 3]))]); let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"inputs\":{\"distanceMap\""), "inspect shows the input"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(inputs(&s, effect).is_empty(), "one undo step"); assert_eq!(roughness(&mut s, at(4)), full); input(&mut s, effect, json!({"input": "distanceMap", "anchor": anchor.0, "anchorChannel": "roughness"})).unwrap(); + assert!((roughness(&mut s, at(4)) - half).abs() < 1e-3, "the anchor's 0.5 reads as the uniform 0.5"); input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap(); + assert!(inputs(&s, effect).is_empty() && roughness(&mut s, at(4)) == full, "cleared: white, as before"); let steps = s.history_labels().len(); input(&mut s, effect, json!({"input": "distanceMap", "value": 1.0})).unwrap(); input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap(); + assert!(inputs(&s, effect).is_empty(), "the default gray is not stored"); assert_eq!(s.history_labels().len(), steps, "setting what the input already reads adds no undo step"); @@ -63,6 +68,7 @@ fn a_distance_map_scales_the_bevel_smooth_distance() { { assert!(input(&mut s, effect, bad.clone()).is_err(), "{bad}"); } + assert!(input(&mut s, anchor, json!({"input": "distanceMap", "value": 0.5})).is_err(), "not a filter"); } @@ -74,9 +80,11 @@ fn a_black_distance_map_leaves_no_trail() { let effect = add_filter(&mut s, json!({"filter": "directionalDistance"})); set(&mut s, effect, json!({"angle": if outward > 0 { 0.0 } else { 180.0 }, "distance": 0.05})); + assert!(roughness(&mut s, at(1)) > 0.0, "a trail"); input(&mut s, effect, json!({"input": "distanceMap", "value": 0.0})).unwrap(); + assert_eq!((roughness(&mut s, at(1)), roughness(&mut s, at(-2))), (0.0, 1.0), "no trail, the shapes stay"); } @@ -92,18 +100,23 @@ fn a_custom_noise_moves_the_warp() { let effect = add_filter(&mut s, json!({"filter": "warp"})); set(&mut s, effect, json!({"intensity": 0.05, "divider": 1, "warpMode": "directional", "sourceMode": "customNoise"})); + assert!(moved(&mut s) < 2e-3, "its default mid gray moves nothing"); input(&mut s, effect, json!({"input": "customNoise", "procedural": "gradient"})).unwrap(); + assert!(moved(&mut s) > 0.01, "a source moves texels: {}", moved(&mut s)); set(&mut s, effect, json!({"sourceMode": "defaultNoise"})); + assert_eq!(inputs(&s, effect).len(), 1, "kept while another source mode is on"); let (_, found) = s.doc.project.effect(effect).unwrap(); let saved = serde_json::to_value(Effect { inputs: Default::default(), ..found.clone() }).unwrap(); + assert!(saved.get("inputs").is_none(), "no inputs, no key: saves as before"); let loaded: Effect = serde_json::from_value(saved).unwrap(); + assert!(loaded.inputs.is_empty(), "an effect saved before loads with none"); } diff --git a/crates/engine/tests/it/filter_light.rs b/crates/engine/tests/it/filter_light.rs index 5fccb750..770d57e3 100644 --- a/crates/engine/tests/it/filter_light.rs +++ b/crates/engine/tests/it/filter_light.rs @@ -25,6 +25,7 @@ fn masked(s: &mut Session, id: &str) -> LayerId { fn a_glow_saved_before_stays_additive_and_a_new_glow_is_the_halo() { let saved = json!({"Glow": {"radius": 16.0, "amount": 1.0}}); let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(filter, Filter::Glow { radius: 16.0, amount: 1.0 }); assert_eq!(serde_json::to_value(&filter).unwrap(), saved); @@ -61,11 +62,13 @@ fn drop_shadow_defaults_and_settings() { assert_eq!(filter_of(&s, effect), LIBRARY_DROP_SHADOW, "the workflow's defaults"); set(&mut s, effect, json!({"angle": 450.0, "distance": -0.9, "size": 2.0, "spread": 0.3, "opacity": 0.25, "color": "#ffffff"})); + assert_eq!(filter_of(&s, effect), Filter::DropShadow { angle: 90.0, distance: -0.5, size: 1.0, spread: 0.3, opacity: 0.25, color: [1.0; 3] }); refused(&mut s, effect, &[json!({"color": [1.0]})]); let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "dropShadow" && f["mask"] == true)); } @@ -80,6 +83,7 @@ fn on_content(s: &mut Session, id: &str) -> LayerId { fn a_baked_lighting_saved_before_stays_and_a_new_one_is_stylized() { let saved = json!({"BakedLighting": {"azimuth": 45.0, "elevation": 45.0, "light": 0.75, "ambient": 0.5, "occlusion": 1.0}}); let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert!(filter.stylized_lighting().is_none(), "lights as before"); assert_eq!(serde_json::to_value(&filter).unwrap(), saved); assert_eq!(filter.label(), "Baked Lighting Stylized"); @@ -91,6 +95,7 @@ fn a_baked_lighting_saved_before_stays_and_a_new_one_is_stylized() { assert_eq!(made, library_baked_lighting(), "the workflow's sun, sky and lights"); let (stylized, _) = made.stylized_lighting().unwrap(); + assert_eq!( (stylized.output, stylized.mesh_only, stylized.dielectric_reflectance, stylized.cavity_smoothness), (LightingOutput::DiffuseSpecular, false, 0.04, 0.25) @@ -98,6 +103,7 @@ fn a_baked_lighting_saved_before_stays_and_a_new_one_is_stylized() { assert_eq!((stylized.lights[0].azimuth, stylized.lights[1].azimuth, stylized.lights[0].intensity), (90.0, 180.0, 0.0)); let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLighting" && f["mask"] == false && f["label"] == "Baked Lighting Stylized")); } @@ -120,6 +126,7 @@ fn stylized_lighting_settings_set_clamp_and_refuse() { ); let filter = filter_of(&s, effect); let (stylized, light) = filter.stylized_lighting().unwrap(); + assert_eq!((light.sun.intensity, light.sky_intensity, stylized.sun_color), (0.8, 0.4, [1.0; 3]), "the rest as it lit"); assert_eq!(stylized.sky_color, [0.1, 0.2, 0.3]); @@ -132,6 +139,7 @@ fn stylized_lighting_settings_set_clamp_and_refuse() { effect, &[json!({"output": "both"}), json!({"input": 1}), json!({"normalDetails": "height"}), json!({"light2": 3}), json!({"groundColor": "dirt"})], ); + assert_eq!(filter_of(&s, effect), filter, "refusals change nothing"); assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true)); @@ -148,6 +156,7 @@ fn environment_lighting_defaults_and_settings() { assert_eq!((made.label(), s.doc.project.effect(effect).unwrap().1.name.as_str()), ("Baked Lighting Environment", "Baked Lighting Environment")); let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness) && off.contains(&Channel::Height), "only the Color pill is lit: {off:?}"); let stylized = on_content(&mut s, "bakedLighting"); @@ -161,6 +170,7 @@ fn environment_lighting_defaults_and_settings() { effect, json!({"horizontalRotation": 370.0, "verticalRotation": -90.0, "exposure": 9.0, "heightIntensity": -1.0, "ambientOcclusion": 0.5, "specularOcclusion": 2.0}), ); + assert_eq!( filter_of(&s, effect), Filter::EnvironmentLighting { @@ -177,6 +187,7 @@ fn environment_lighting_defaults_and_settings() { assert_eq!(filter_of(&s, effect), made); let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLightingEnvironment" && f["mask"] == false)); } @@ -200,5 +211,36 @@ fn environment_lighting_follows_the_viewport_environment() { assert!(night[0] < studio[0] * 0.5, "the night lights it less: {night:?} vs {studio:?}"); set(&mut s, effect, json!({"exposure": 3.0})); + assert!(center(&mut s)[0] > night[0], "exposure brightens it"); } + +#[test] +fn reimporting_the_selected_environment_relights_the_composite() { + let mut session = session(); + let image_bytes = |rgb: [u8; 3]| { + let image = image::RgbImage::from_pixel(8, 4, image::Rgb(rgb)); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write_to(&mut bytes, image::ImageFormat::Png).unwrap(); + bytes.into_inner() + }; + let sample = |session: &mut Session| { + session.update(); + session.caches[0].composite.value(Channel::BaseColor, SIZE / 2, SIZE / 2) + }; + execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap(); + add_filter(&mut session, json!({"filter": "bakedLightingEnvironment"})); + let name = session.import_resource_bytes("lighting.png", image_bytes([255, 0, 0])).unwrap(); + execute(&mut session, "display.set", &json!({"environment": format!("resource:{name}")})).unwrap(); + let red = sample(&mut session); + assert!(red[0] > red[1], "the selected resource lights the base color"); + + execute(&mut session, "resource.remove", &json!({"name": name})).unwrap(); + let fallback = sample(&mut session); + let replacement = session.import_resource_bytes("lighting.png", image_bytes([0, 255, 0])).unwrap(); + let green = sample(&mut session); + + assert_eq!(replacement, name); + assert_ne!(fallback, red); + assert!(green[1] > green[0] && green != fallback, "reimporting the referenced image relights the material: {green:?}"); +} diff --git a/crates/engine/tests/it/filter_shape.rs b/crates/engine/tests/it/filter_shape.rs index 73dc6521..5ffd623c 100644 --- a/crates/engine/tests/it/filter_shape.rs +++ b/crates/engine/tests/it/filter_shape.rs @@ -21,10 +21,12 @@ fn threshold_modes_compare_their_way() { assert_eq!(roughness(&mut s, texel), 1.0); set(&mut s, effect, json!({"level": 0.25})); + assert_eq!(roughness(&mut s, texel), 0.0, "a value at the level is not greater"); for (mode, white) in [("greaterOrEqual", 1.0), ("lower", 0.0), ("lowerOrEqual", 1.0)] { set(&mut s, effect, json!({"mode": mode})); + assert_eq!(roughness(&mut s, texel), white, "{mode}"); } @@ -32,6 +34,7 @@ fn threshold_modes_compare_their_way() { assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.25, mode: ThresholdMode::LowerOrEqual }, "a refused mode changes nothing"); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater }); } @@ -53,15 +56,18 @@ fn mirror_copies_one_side_over_the_other() { assert!((roughness(&mut s, right) - left_before).abs() < 2e-3, "the right side reads the left"); set(&mut s, effect, json!({"invertAxisX": true})); + assert!((roughness(&mut s, left) - right_before).abs() < 2e-3, "inverted, the left side reads the right"); set(&mut s, effect, json!({"mode": "corner", "cornerType": "topRight"})); + assert!((roughness(&mut s, (20, 20)) - roughness(&mut s, (SIZE - 1 - 20, 20))).abs() < 2e-3, "a corner mirrors across too"); let Filter::Mirror(mirror) = filter_of(&s, effect) else { panic!() }; assert_eq!((mirror.mode, mirror.corner), (MirrorMode::Corner, MirrorCorner::TopRight)); set(&mut s, effect, json!({"mode": "axisX", "displayDebug": true})); + assert_eq!(roughness(&mut s, (SIZE / 2, row)), 1.0, "Display Debug draws the axis white"); refused(&mut s, effect, &[json!({"mode": "diagonal"}), json!({"cornerType": "middle"}), json!({"invertAxisY": "yes"})]); @@ -82,14 +88,17 @@ fn mask_outline_draws_a_band_along_the_threshold_edge() { assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Mask Outline"); set(&mut s, effect, json!({"threshold": 0.5, "width": 0.03})); + assert_eq!(roughness(&mut s, at(2)), 1.0, "outside, next to the edge"); assert_eq!(roughness(&mut s, at(8)), 0.0, "past the band"); assert_eq!(roughness(&mut s, at(-2)), 0.0, "inside the shapes"); set(&mut s, effect, json!({"maskPosition": "inside"})); + assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 0.0), "inside"); set(&mut s, effect, json!({"maskPosition": "both"})); + assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 1.0), "both sides"); set(&mut s, effect, json!({"startFromBlack": false})); @@ -107,6 +116,7 @@ fn mask_outline_draws_a_band_along_the_threshold_edge() { assert_eq!((outline.position, outline.width, outline.curve), (OutlinePosition::Outside, 1.0, -1.0), "values clamp"); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::MaskOutline(MaskOutline::LIBRARY)); } @@ -164,9 +174,11 @@ fn bevel_slopes_inwards_or_outwards() { assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(expected), "values clamp"); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(Bevel::LIBRARY)); let old: Filter = serde_json::from_value(json!({"Bevel": {"width": 16.0}})).unwrap(); + assert_eq!(old, Filter::Bevel { width: 16.0, wrap: false }, "a bevel saved before keeps its width"); } @@ -194,6 +206,7 @@ fn bevel_smooth_ramps_from_the_edge() { assert!(edge_in > 0.5 && edge_out < 0.5 && edge_in - edge_out < 0.2, "across: mid gray at the edge: {edge_in} {edge_out}"); set(&mut s, effect, json!({"curveOffset": 0.5})); + assert!(roughness(&mut s, at(0)) > edge_in, "the offset raises the ramp"); refused(&mut s, effect, &[json!({"direction": "up"}), json!({"wrap": "yes"})]); @@ -224,9 +237,11 @@ fn directional_distance_trails_one_way() { assert!(near > further && further > 0.0, "fades away from them: {near} {further}"); set(&mut s, effect, json!({"contrast": 0.5})); + assert_eq!(roughness(&mut s, at(1)), 1.0, "contrast hardens the near trail"); set(&mut s, effect, json!({"angle": away + 180.0, "contrast": 0.0})); + assert!(roughness(&mut s, at(1)) < near, "against the angle the edge gets less trail"); set(&mut s, effect, json!({"distance": 1.0, "angle": -90.0, "contrast": 3.0, "distanceMapMultiplier": -1.0})); @@ -254,6 +269,7 @@ fn warp_modes_move_texels_their_way() { assert!(moved(&warped) > 0.01 && warped.iter().all(|v| v.is_finite()), "the noise moves texels: {}", moved(&warped)); set(&mut s, effect, json!({"intensity": 0.0})); + assert!(moved(&after(&mut s)) < 2e-3, "no intensity, no move"); // Along the gradient where it rises: a texel above mid gray reads further up it, so it gets lighter @@ -269,6 +285,7 @@ fn warp_modes_move_texels_their_way() { assert!(directional[texel] > before[texel] + 0.01, "{} -> {}", before[texel], directional[texel]); set(&mut s, effect, json!({"sourceMode": "customNoise"})); + assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing moves"); set(&mut s, effect, json!({"warpMode": "multiDirectional", "sourceMode": "defaultNoise", "directions": 2, "blendingMode": "max"})); @@ -281,6 +298,7 @@ fn warp_modes_move_texels_their_way() { assert!(average.iter().zip(max.iter().zip(&min)).all(|(average, (max, min))| *average <= max + 2e-3 && *average >= min - 2e-3), "the average between"); set(&mut s, effect, json!({"blendingMode": "chain", "directions": 4})); + assert!(after(&mut s).iter().all(|v| v.is_finite())); refused(&mut s, effect, &[json!({"warpMode": "spiral"}), json!({"directions": 3}), json!({"blendingMode": "sum"}), json!({"sourceMode": "image"})]); @@ -297,11 +315,13 @@ fn warp_modes_move_texels_their_way() { // Saved before the modes: loads as it was, and Restore defaults gives the warp of its mode let saved = json!({"DirectionalWarp": {"intensity": 8.0, "angle": 30.0, "scale": 4.0, "seed": 3}}); let old: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(old, Filter::DirectionalWarp { intensity: 8.0, angle: 30.0, scale: 4.0, seed: 3, divider: 1 }); assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before"); s.doc.project.effect_mut(former).unwrap().kind = EffectKind::Filter(old); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": former.0})).unwrap(); + assert_eq!(filter_of(&s, former), Filter::SourceWarp(directional)); } @@ -336,6 +356,7 @@ fn slope_blur_reads_downhill_of_its_source() { set(&mut s, effect, json!({"blendingMode": "blur", "sourceMode": "previousInput"})); let downhill = after(&mut s); let rising = (SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] > before[k] + 1e-4)).unwrap(); + assert!(downhill[rising] < before[rising] - 0.005, "{} -> {}", before[rising], downhill[rising]); set(&mut s, effect, json!({"quality": 0.0})); @@ -343,6 +364,7 @@ fn slope_blur_reads_downhill_of_its_source() { assert!(coarse.iter().all(|v| v.is_finite()) && coarse != downhill, "fewer reads, another smear"); set(&mut s, effect, json!({"sourceMode": "customNoise"})); + assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing smears"); refused(&mut s, effect, &[json!({"blendingMode": "average"}), json!({"sourceMode": "image"}), json!({"divider": 7})]); @@ -355,10 +377,12 @@ fn slope_blur_reads_downhill_of_its_source() { // Saved before its source settings: loads and saves as it was, and Restore defaults gives today's Blur Slope let saved = json!({"SlopeBlur": {"radius": 16.0, "scale": 4.0, "seed": 1}}); let old: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(old, Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1, divider: 1 }); assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before"); s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(old); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur::LIBRARY)); } diff --git a/crates/engine/tests/it/filter_simple.rs b/crates/engine/tests/it/filter_simple.rs index 8b6bdaaa..225e6911 100644 --- a/crates/engine/tests/it/filter_simple.rs +++ b/crates/engine/tests/it/filter_simple.rs @@ -41,6 +41,7 @@ fn new_simple_filters_start_where_the_reference_does() { add_filter(&mut s, json!({"filter": "heightAdjust"})); add_filter(&mut s, json!({"filter": "histogramScan"})); add_filter(&mut s, json!({"filter": "histogramShift"})); + assert!(close(roughness(&mut s, TEXEL), 0.25), "Clamp, Height Adjust, Histogram Scan and Shift at their defaults change nothing"); } @@ -52,12 +53,15 @@ fn smoothstep_eases_between_minimum_and_maximum() { assert!(close(roughness(&mut s, TEXEL), 0.15625), "0.25 eased: 3t² − 2t³"); set(&mut s, effect, json!({"min": 0.25, "max": 0.75})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "at the minimum"); set(&mut s, effect, json!({"min": 0.0, "max": 0.2})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "past the maximum"); set(&mut s, effect, json!({"min": 0.25, "max": 0.25})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "equal bounds are a step, the bound itself white"); } @@ -69,6 +73,7 @@ fn invert_switches_off_and_on() { assert!(close(roughness(&mut s, TEXEL), 0.75)); set(&mut s, effect, json!({"invert": false})); + assert_eq!(filter_of(&s, effect), Filter::InvertOff); assert!(close(roughness(&mut s, TEXEL), 0.25), "off changes nothing"); assert_eq!(filter_of(&s, effect).label(), "Invert", "still named Invert"); @@ -76,14 +81,17 @@ fn invert_switches_off_and_on() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "invert": "yes"})).is_err()); execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Invert, "one undo step"); set(&mut s, effect, json!({"invert": false})); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Invert); // An old project's Invert still reads as before let old: Filter = serde_json::from_value(json!("Invert")).unwrap(); + assert_eq!(old, Filter::Invert); } @@ -94,15 +102,19 @@ fn height_adjust_flips_scales_and_raises() { let effect = add_filter(&mut s, json!({"filter": "heightAdjust"})); set(&mut s, effect, json!({"multiply": 2.0})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "(0.25 − 0.5) × 2 + 0.5"); set(&mut s, effect, json!({"invert": true, "offset": 0.1})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "flipped to 0.75, (0.75 − 0.5) × 2 + 0.5 + 0.1 clamped"); set(&mut s, effect, json!({"multiply": 1.0, "offset": -0.2})); + assert!(close(roughness(&mut s, TEXEL), 0.55)); set(&mut s, effect, json!({"multiply": 50.0})); + assert_eq!(filter_of(&s, effect), Filter::HeightAdjust { invert: true, offset: -0.2, multiply: 10.0 }, "Multiply caps at 10"); } @@ -127,12 +139,15 @@ fn histogram_scan_inverts_its_position() { let effect = add_filter(&mut s, json!({"filter": "histogramScan"})); set(&mut s, effect, json!({"position": 0.2, "contrast": 1.0})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "0.25 is above 0.2"); set(&mut s, effect, json!({"invertPosition": true})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "0.25 is below 1 − 0.2"); let old: Filter = serde_json::from_value(json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}})).unwrap(); + assert_eq!(old, Filter::HistogramScan { position: 0.5, contrast: 0.5, invert_position: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}}), "saved as before"); } @@ -144,6 +159,7 @@ fn histogram_shift_takes_a_position() { let effect = add_filter(&mut s, json!({"filter": "histogramShift"})); set(&mut s, effect, json!({"position": 0.5})); + assert_eq!(filter_of(&s, effect), Filter::HistogramShift { offset: -0.5 }); assert!(close(roughness(&mut s, TEXEL), 0.75), "0.25 − 0.5 wraps to 0.75"); @@ -159,12 +175,14 @@ fn posterize_takes_apply_to_alpha() { let effect = add_filter(&mut s, json!({"filter": "posterize"})); set(&mut s, effect, json!({"levels": 2, "applyToAlpha": true})); + assert_eq!(filter_of(&s, effect), Filter::Posterize { levels: 2.0, alpha: true }); assert!(close(roughness(&mut s, TEXEL), 0.0)); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": 1})).is_err()); let old: Filter = serde_json::from_value(json!({"Posterize": {"levels": 4.0}})).unwrap(); + assert_eq!(old, Filter::Posterize { levels: 4.0, alpha: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Posterize": {"levels": 4.0}}), "saved as before"); } @@ -184,9 +202,11 @@ fn pixelate_takes_pixels_amount_and_apply_to_alpha() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "no"})).is_err()); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Pixelate"), "named after the reference workflow"); let old: Filter = serde_json::from_value(json!({"Mosaic": {"size": 32.0}})).unwrap(); + assert_eq!(old, Filter::Mosaic { size: 32.0, alpha: true }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Mosaic": {"size": 32.0}}), "saved as before"); } @@ -199,12 +219,14 @@ fn fxaa_takes_affect_alpha_channel() { assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false }); set(&mut s, effect, json!({"affectAlphaChannel": true})); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: true }); assert!(close(roughness(&mut s, TEXEL), 0.3), "nothing to smooth on a flat fill"); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "affectAlphaChannel": 2})).is_err()); execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false }, "one undo step"); } @@ -216,17 +238,21 @@ fn blurs_take_intensity() { assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 4.8, wrap: false }, "a new Blur starts at Blur Intensity 0.30"); set(&mut s, blur, json!({"intensity": 2.0})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 32.0, wrap: false }); set(&mut s, blur, json!({"intensity": 1000.0})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 256.0, wrap: false }, "capped as radius is"); let directional = add_filter(&mut s, json!({"filter": "blurDirectional"})); set(&mut s, directional, json!({"intensity": 0.5, "angle": 90})); + assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 8.0, angle: 90.0 }); set(&mut s, directional, json!({"radius": 4.0})); + assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 4.0, angle: 90.0 }, "radius in texels at 2K still sets it"); } @@ -239,15 +265,18 @@ fn highpass_takes_radius_color_space_and_apply_to_alpha() { assert!(close(roughness(&mut s, TEXEL), 0.5), "a flat fill has no detail: mid gray"); set(&mut s, effect, json!({"intensity": 0.5, "colorSpace": "srgbFromAcescg", "applyToAlpha": true})); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 8.0, space: HighpassSpace::SrgbFromAcescg, alpha: true }); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "colorSpace": "rec2020"})).is_err()); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "yes"})).is_err()); execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::Working, alpha: false }, "one undo step"); let old: Filter = serde_json::from_value(json!({"HighPass": {"radius": 8.0}})).unwrap(); + assert_eq!(old, Filter::HighPass { radius: 8.0, space: HighpassSpace::Working, alpha: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HighPass": {"radius": 8.0}}), "saved as before"); } @@ -271,16 +300,20 @@ fn grayscale_conversion_takes_its_settings_and_keeps_saved_grayscales() { assert!(saved.iter().all(|v| close(*v, saved[0])) && close(saved[0], lum([0.8, 0.2, 0.1])), "{saved:?}"); set(&mut s, effect, json!({"balance": 0.5})); + assert_eq!(filter_of(&s, effect), Filter::GrayscaleConversion(GrayscaleConversion::of_luminance()), "the luminance weights"); assert!(close(base_color(&mut s)[0], saved[0]), "looks the same after its first edit"); set(&mut s, effect, json!({"red": 1.0, "green": 0.0, "blue": 0.0, "invert": true})); + assert!(close(base_color(&mut s)[0], 1.0 - 0.8), "Red only, inverted"); set(&mut s, effect, json!({"mode": "min", "invert": false})); + assert!(close(base_color(&mut s)[0], 0.1), "the darkest component"); set(&mut s, effect, json!({"channelInput": "customInput", "mode": "max"})); + assert!(close(base_color(&mut s)[0], 0.5), "the Custom Input reads mid gray until set"); let Filter::GrayscaleConversion(conversion) = filter_of(&s, effect) else { panic!("converted") }; @@ -290,6 +323,7 @@ fn grayscale_conversion_takes_its_settings_and_keeps_saved_grayscales() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "luma"})).is_err(), "Luma is the gradients' mode"); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Grayscale Conversion")); assert_eq!(serde_json::to_value(Filter::Grayscale).unwrap(), json!("Grayscale"), "saved as before"); } diff --git a/crates/engine/tests/it/filter_stylize.rs b/crates/engine/tests/it/filter_stylize.rs index 13b28c90..512a405c 100644 --- a/crates/engine/tests/it/filter_stylize.rs +++ b/crates/engine/tests/it/filter_stylize.rs @@ -59,6 +59,7 @@ fn anisotropic_kuwahara_takes_its_settings_and_smooths() { assert_eq!(undone, AnisotropicKuwahara { radius: AnisotropicKuwahara::MAX_RADIUS, ..AnisotropicKuwahara::LIBRARY }, "one undo step"); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Anisotropic Kuwahara")); } @@ -75,6 +76,7 @@ fn pbr_validate_marks_implausible_base_colors() { assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate::LIBRARY)); let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Metallic) && off.contains(&Channel::Roughness), "{off:?}"); assert_eq!(base_color(&mut s, texel), PbrValidate::INVALID, "too dark"); assert_eq!(s.caches[0].composite.value(Channel::Metallic, texel.0, texel.1)[0], 0.0, "the metal is left as it is"); @@ -84,6 +86,7 @@ fn pbr_validate_marks_implausible_base_colors() { assert!((shown[0] - dark).abs() < 1e-3, "Metal leaves non-metal colors unchecked: {shown:?}"); set(&mut s, effect, json!({"validationMode": "albedo", "albedoDarkRangeThreshold": 50, "metalReflectanceRange": 70})); + assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate { mode: ValidationMode::Albedo, albedo_dark: 50, metal_low: 70 })); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "albedoDarkRangeThreshold": 40})).is_err()); @@ -109,6 +112,7 @@ fn height_to_normal_turns_the_height_into_the_normal() { let bumps = json!({"layer": fill, "channel": "height", "procedural": "Clouds", "scale": 16, "low": [-0.05, -0.05, -0.05], "high": [0.05, 0.05, 0.05]}); execute(&mut s, "layer.fill.set", &bumps).unwrap(); let texels: Vec<(u32, u32)> = (0..32).map(|k| (FINE_SET_SIZE / 4 + k, FINE_SET_SIZE / 2)).collect(); + assert!(tilt(&mut s, &texels) < 1e-3, "a fill's own normal is flat"); let color = base_color(&mut s, texels[0]); @@ -117,6 +121,7 @@ fn height_to_normal_turns_the_height_into_the_normal() { assert_eq!(filter_of(&s, effect), Filter::HeightToNormal(HeightToNormal::LIBRARY)); let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::Normal) && off.contains(&Channel::BaseColor) && off.contains(&Channel::Height), "{off:?}"); let made = tilt(&mut s, &texels); @@ -124,15 +129,19 @@ fn height_to_normal_turns_the_height_into_the_normal() { assert_eq!(base_color(&mut s, texels[0]), color, "the base color is left as it is"); set(&mut s, effect, json!({"heightDepth": 64.0})); + assert!(tilt(&mut s, &texels) > made * 1.5, "deeper heights tilt more"); set(&mut s, effect, json!({"useWorldUnits": false, "normalIntensity": 0.0})); + assert!(tilt(&mut s, &texels) < 1e-3, "no intensity: flat"); execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "normal", "value": [0.7, 0.5, 0.95]})).unwrap(); + assert!(tilt(&mut s, &texels) < 1e-3, "Overwrite Existing Normal replaces the fill's normal"); set(&mut s, effect, json!({"overwriteExistingNormal": false})); + assert!((normal(&mut s, texels[0])[0] - 0.7).abs() < 0.02, "laid over the fill's normal: {:?}", normal(&mut s, texels[0])); let all = json!({"overwriteExistingNormal": true, "useWorldUnits": true, "surfaceSize": 0.0, "heightDepth": 500.0, @@ -154,6 +163,7 @@ fn height_to_normal_turns_the_height_into_the_normal() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "useWorldUnits": "yes"})).is_err()); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Height To Normal")); } @@ -167,15 +177,18 @@ fn color_match_moves_the_colors_to_the_target() { let texels: Vec<(u32, u32)> = (0..24).map(|k| (SIZE / 4 + k * 2, SIZE / 2)).collect(); let before: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); let spread = |colors: &[[f32; 3]]| colors.iter().map(|c| c[0]).fold(f32::MIN, f32::max) - colors.iter().map(|c| c[0]).fold(f32::MAX, f32::min); + assert!(spread(&before) > 0.05, "the clouds vary: {before:?}"); let effect = add_filter(&mut s, json!({"filter": "Color Match"})); assert_eq!(filter_of(&s, effect), Filter::ColorMatch(ColorMatch::LIBRARY)); let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness), "{off:?}"); let new: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + assert!(spread(&new) > 0.02, "a new Color Match keeps the pattern: {new:?}"); let redness = new.iter().map(|c| c[0] - c[2]).sum::() / new.len() as f32; @@ -192,6 +205,7 @@ fn color_match_moves_the_colors_to_the_target() { // Without Custom Color Variation the texels keep their differences from the mean, now around the target set(&mut s, effect, json!({"customColorVariation": false})); let kept: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + assert!(spread(&kept) > 0.02, "variation kept: {kept:?}"); let redness = kept.iter().map(|c| c[0] - c[2]).sum::() / kept.len() as f32; @@ -200,6 +214,7 @@ fn color_match_moves_the_colors_to_the_target() { let brighter = |colors: &[[f32; 3]], a: usize, b: usize| colors[a][0] + colors[a][1] > colors[b][0] + colors[b][1]; let (lightest, darkest) = (0..texels.len()).fold((0, 0), |(hi, lo), k| (if before[k][0] > before[hi][0] { k } else { hi }, if before[k][0] < before[lo][0] { k } else { lo })); + assert!(brighter(&kept, lightest, darkest), "the lightest red stays the lightest"); // Source Color Parameter: the texels of that color land on the target @@ -238,5 +253,6 @@ fn color_match_moves_the_colors_to_the_target() { &[json!({"sourceColorMode": "median"}), json!({"targetColorMode": "input"}), json!({"customColorVariation": 1}), json!({"targetColor": "red"})], ); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Color Match")); } diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs index 16e2e0a0..796396c2 100644 --- a/crates/engine/tests/it/filter_support.rs +++ b/crates/engine/tests/it/filter_support.rs @@ -57,6 +57,7 @@ pub(crate) fn roughness(s: &mut Session, (x, y): (u32, u32)) -> f32 { pub(crate) fn add_filter(s: &mut Session, params: Value) -> LayerId { let mut params = params; params["target"] = json!("content"); + LayerId(execute(s, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) } @@ -78,6 +79,7 @@ pub(crate) fn filter_of(s: &Session, effect: LayerId) -> Filter { pub(crate) fn set(s: &mut Session, effect: LayerId, params: Value) { let mut params = params; params["effect"] = json!(effect.0); + execute(s, "effect.set", ¶ms).unwrap(); } @@ -86,6 +88,7 @@ pub(crate) fn refused(s: &mut Session, effect: LayerId, bad: &[Value]) { for bad in bad { let mut params = bad.clone(); params["effect"] = json!(effect.0); + assert!(execute(s, "effect.set", ¶ms).is_err(), "{bad}"); } } diff --git a/crates/engine/tests/it/filter_swap.rs b/crates/engine/tests/it/filter_swap.rs index c8502ad8..5c41ea01 100644 --- a/crates/engine/tests/it/filter_swap.rs +++ b/crates/engine/tests/it/filter_swap.rs @@ -109,6 +109,7 @@ fn asking_a_saved_warp_for_another_mode_replaces_it_with_a_warp_in_that_mode() { let edited = effect(&s, warp).kind; assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Directional && warp.angle == 90.0), "{edited:?}"); + let edited = effect(&s, directional).kind; assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::MultiDirectional), "{edited:?}"); } @@ -135,6 +136,7 @@ fn swapping_to_a_gradient_given_colors_ramps_evenly_through_them() { let EffectKind::Filter(gradient) = effect(&s, id).kind else { panic!("still a filter") }; let halfway = gradient.ramp_at(0.5).unwrap(); + assert!((halfway[0] - 0.5).abs() < 1e-3, "black to white is mid gray halfway: {halfway:?}"); } @@ -188,8 +190,10 @@ fn a_mask_filter_swaps_in_place_on_the_mask() { let blur = effect(&s, swapped); assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind); assert_eq!((blur.name.as_str(), blur.blend, blur.opacity), ("Blur", BlendMode::Multiply, 0.4)); + let layer = s.selected_layer().unwrap(); let mask_order: Vec = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(mask_order, vec![below, swapped, above]); } @@ -234,8 +238,10 @@ fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { } assert_eq!(effect(&s, id), before); + // The last step is still the blend, opacity and name edit execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(effect(&s, id).name, "Invert"); } @@ -284,6 +290,7 @@ fn filters_carry_the_workflows_names_and_former_names_still_follow_a_swap() { let mut s = session(); let slope = add(&mut s, "effect.add.filter", json!({"filter": "slopeBlur", "target": "content"})); assert_eq!(effect(&s, slope).name, "Blur Slope"); + let names: Vec = execute(&mut s, "filter.list", &Value::Null).unwrap().as_array().unwrap().iter().map(|def| def["label"].clone()).collect(); for name in ["Contrast Luminosity", "Blur Slope", "Highpass", "Grayscale Conversion"] { assert!(names.contains(&json!(name)), "{name} in {names:?}"); @@ -292,5 +299,6 @@ fn filters_carry_the_workflows_names_and_former_names_still_follow_a_swap() { // A project saved before the rename holds the former name: a swap still renames it, and the former name still finds the filter let old = add(&mut s, "effect.add.filter", json!({"filter": "Slope Blur", "target": "content", "name": "Slope Blur"})); set(&mut s, old, json!({"filter": "blur"})); + assert_eq!(effect(&s, old).name, "Blur"); } diff --git a/crates/engine/tests/it/filter_transform.rs b/crates/engine/tests/it/filter_transform.rs index 704c2c87..d5e7b9a6 100644 --- a/crates/engine/tests/it/filter_transform.rs +++ b/crates/engine/tests/it/filter_transform.rs @@ -19,12 +19,14 @@ fn transform_moves_scales_and_flips_each_tile() { let mut s = session(); let row = SIZE / 2; let empty = roughness(&mut s, (8, row)); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); let before: Vec = (0..SIZE).map(|x| roughness(&mut s, (x, row))).collect(); let was = |x: u32| before[(x % SIZE) as usize]; let effect = add_filter(&mut s, json!({"filter": "transform"})); + assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY); assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Transform"); @@ -34,26 +36,32 @@ fn transform_moves_scales_and_flips_each_tile() { // A quarter tile on: each texel reads 32 texels further right, the last ones round from the left set(&mut s, effect, json!({"offset": [0.25, 0.0]})); + for x in [20, 50, 110] { assert!((roughness(&mut s, (x, row)) - was(x + SIZE / 4)).abs() < 2e-3, "offset at {x}"); } set(&mut s, effect, json!({"offset": 0.0, "flipMode": "horizontally"})); + assert!((roughness(&mut s, (20, row)) - was(SIZE - 1 - 20)).abs() < 2e-3, "flipped, the left reads the right"); // Twice across about the centre: the centre stays; without repeat the edges read empty (the layer's content is clear there) set(&mut s, effect, json!({"flipMode": "none", "scaling": [2.0, 2.0], "repeatMode": "none"})); + assert!((roughness(&mut s, (SIZE / 2, row)) - was(SIZE / 2)).abs() < 2e-2, "the centre stays"); assert!((roughness(&mut s, (8, row)) - empty).abs() < 1e-4, "past the content reads empty"); // Repeating, texel 8 reads 2 · 8.5 / 128 − 0.5 of a tile on: between texels 80 and 81 set(&mut s, effect, json!({"repeatMode": "horizontallyAndVertically"})); + assert!((roughness(&mut s, (8, row)) - (was(80) + was(81)) / 2.0).abs() < 2e-3, "the tile comes round again"); let edited = transform_of(&s, effect); + assert_eq!((edited.repeat, edited.flip, edited.scaling), (RepeatMode::HorizontallyAndVertically, FlipMode::None, [2.0, 2.0])); set(&mut s, effect, json!({"rotation": -30.0, "tileSafeRotation": false})); + let turned = transform_of(&s, effect); assert_eq!((turned.rotation, turned.tile_safe), (330.0, false), "a turn reads 0..360"); @@ -68,11 +76,14 @@ fn transform_moves_scales_and_flips_each_tile() { json!({"tileSafeRotation": 1}), ], ); + assert_eq!(transform_of(&s, effect), turned, "a refused value changes nothing"); set(&mut s, effect, json!({"scaling": [1e9, -5.0]})); + assert_eq!(transform_of(&s, effect).scaling, [TileTransform::SCALING.1, TileTransform::SCALING.0], "scaling clamps"); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY); } diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index d423c852..e1e27297 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -79,33 +79,44 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { let fid = f["id"].as_str().unwrap(); let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect"); let (owner, e) = s.doc.project.effect(eid).unwrap(); + assert_eq!(owner, layer); assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry"); assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid)); + execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); } - // A gradient map recolors the content; effect.set edits it and inspect shows it. + // A gradient map recolors the content; effect.set edits it and inspect shows it let gm = id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect"); let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}"); + execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap(); + assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95); assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err()); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains("GradientMap"), "inspect shows filter parameters"); + execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap(); - // Posterize on the mask; its steps are clamped. + // Posterize on the mask; its steps are clamped let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect"); execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap(); + assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post))); assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels, .. }) if levels == 64.0)); - // Material finishes fill the content's roughness and height. + + // Material finishes fill the content's roughness and height let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect"); + assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin)); assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height))); assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err()); - // A directional blur, slope blur and warp composite without trouble on a sphere. + + // A directional blur, slope blur and warp composite without trouble on a sphere for (fid, extra) in [ ("blurDirectional", json!({"radius": 40, "angle": 45})), ("slopeBlur", json!({"intensity": 0.5, "divider": 1})), diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index 43c8f56c..ccab5dba 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -56,8 +56,12 @@ impl EnvImage { /// Box-downsample by 2. pub fn half(&self) -> EnvImage { - let (width, height, data) = environment_sky::half(self.width, self.height, |x, y| self.get(x as i64, y as i64)); - EnvImage { width, height, data: data.iter().map(Vec3::to_array).collect() } + Self::half_from(self.width, self.height, |x, y| self.get(i64::from(x), i64::from(y))) + } + + fn half_from(width: u32, height: u32, texel: impl Fn(u32, u32) -> Vec3 + Sync) -> Self { + let (width, height, data) = environment_sky::half(width, height, texel); + Self { width, height, data: data.into_iter().map(|rgb| rgb.to_array()).collect() } } /// An imported equirect image (`rgba` row-major, top row first, sRGB-encoded when `srgb`) as @@ -65,16 +69,32 @@ impl EnvImage { /// range, and images larger than [`MAX_IMPORT_WIDTH`] are box-downsampled. None when the /// pixel count does not match the size. pub fn from_rgba(width: u32, height: u32, rgba: &[[f32; 4]], srgb: bool) -> Option { - if width == 0 || height == 0 || rgba.len() as u64 != width as u64 * height as u64 { + Self::from_pixels(width, height, rgba, srgb) + } + + /// An imported linear RGB equirect image, with the same validation and size limits as [Self::from_rgba]. + pub fn from_linear_rgb(width: u32, height: u32, rgb: &[[f32; 3]]) -> Option { + Self::from_pixels(width, height, rgb, false) + } + + fn from_pixels(width: u32, height: u32, pixels: &[[f32; COMPONENTS]], srgb: bool) -> Option { + if width == 0 || height == 0 || pixels.len() as u64 != width as u64 * height as u64 { return None; } - let linear = |v: f32| environment_sky::environment_linear(v, srgb); - let data = rgba.par_iter().map(|p| [linear(p[0]), linear(p[1]), linear(p[2])]).collect(); - let mut img = EnvImage { width, height, data }; + + let linear_rgb = |pixel: &[f32; COMPONENTS]| std::array::from_fn(|component| environment_sky::environment_linear(pixel[component], srgb)); + let mut img = if width > MAX_IMPORT_WIDTH || height > MAX_IMPORT_WIDTH { + // Linearize only the texels that contribute to the first reduced level + Self::half_from(width, height, |x, y| Vec3::from(linear_rgb(&pixels[y as usize * width as usize + x as usize]))) + } else { + Self { width, height, data: pixels.par_iter().map(linear_rgb).collect() } + }; + while img.width > MAX_IMPORT_WIDTH || img.height > MAX_IMPORT_WIDTH { img = img.half(); } - // The mip chain needs at least 4×2 texels at its last level. + + // The mip chain needs at least 4×2 texels at its last level if img.width < 128 || img.height < 64 { let (w, h) = (img.width.max(128), img.height.max(64)); let data = (0..w * h).map(|i| img.sample(dir_of(((i % w) as f32 + 0.5) / w as f32, ((i / w) as f32 + 0.5) / h as f32)).to_array()).collect(); diff --git a/crates/ui-egui/src/property_sheet/color_bar.rs b/crates/ui-egui/src/property_sheet/color_bar.rs index d120ce3f..f2322fa4 100644 --- a/crates/ui-egui/src/property_sheet/color_bar.rs +++ b/crates/ui-egui/src/property_sheet/color_bar.rs @@ -92,8 +92,8 @@ impl PropertySheet<'_> { let state_id = bar.with("picker"); let mut state = picker_state(ctx, state_id); if !state.open { - open_picker(ctx, &mut state, linear); - ctx.data_mut(|data| data.insert_temp(state_id, state)); + open_picker(ctx, state_id, &mut state, linear); + ctx.memory_mut(|memory| memory.caches.cache::().set(state_id, state)); } } diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index f975c19d..6fd7b040 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,4 +1,4 @@ -use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, 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::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; diff --git a/crates/ui-egui/tests/it/filter_card.rs b/crates/ui-egui/tests/it/filter_card.rs index 6c78e409..30834e46 100644 --- a/crates/ui-egui/tests/it/filter_card.rs +++ b/crates/ui-egui/tests/it/filter_card.rs @@ -17,6 +17,7 @@ fn a_pill_switches_its_channel_and_the_chip_picks_the_divider() { let chip = harness.get_by_role_and_label(Role::ComboBox, "÷10").rect(); click_at(&mut harness, chip.center()); + assert!(egui::Popup::is_any_open(&harness.ctx), "the chip opens its list"); let hundred = harness.get_by_role_and_label(Role::ListBoxOption, "÷100").rect(); @@ -33,6 +34,7 @@ fn restore_defaults_and_clear_on_the_card() { let restore = harness.get_by_role_and_label(Role::Button, "Restore defaults"); assert!(restore.accesskit_node().is_disabled(), "inert at the defaults"); + let restore = restore.rect(); let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect(); assert!((restore.center().y - clear.center().y).abs() < 0.5 && restore.right() < clear.left(), "⟲ beside × on the card"); @@ -68,6 +70,7 @@ fn the_filter_card_holds_its_parameters() { // A row inside the card keeps the card's bleed on both sides; a band would span the panel assert_eq!(attributes.left(), card.left() + CARD_BLEED, "{attributes:?} {card:?}"); assert_eq!(sub_group.left(), attributes.left(), "a sub-group is a caption in the card, not a card of its own"); + for slider in harness.query_all_by_role(Role::Slider) { assert!(slider.rect().bottom() <= attributes.top(), "Attributes is the card's last row: {:?}", slider.rect()); } diff --git a/crates/ui-egui/tests/it/filter_gradient.rs b/crates/ui-egui/tests/it/filter_gradient.rs index 9a485c56..fe9e1bde 100644 --- a/crates/ui-egui/tests/it/filter_gradient.rs +++ b/crates/ui-egui/tests/it/filter_gradient.rs @@ -18,6 +18,7 @@ fn a_gradient_marker_drags_its_color_along_the_ramp() { let Filter::GradientMap { positions, .. } = filter_of(&harness, effect) else { panic!() }; let moved = positions.get(1).copied().unwrap(); + assert!(moved > 0.6, "dragged right: {positions:?}"); undo(&mut harness); @@ -48,7 +49,9 @@ fn a_color_quantity_drag_is_its_own_undo_step() { let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); let linear = harness.get_by_role_and_label(Role::CheckBox, "Blend Color in Linear").rect(); click_at(&mut harness, linear.center()); + assert!(matches!(filter_of(&harness, effect), Filter::GradientMap { linear: false, .. })); + let depth = undo_depth(&harness); // From 2.6 colors to 3.2 (both round to the 3 it has), then to 4.2 diff --git a/crates/ui-egui/tests/it/filter_inputs.rs b/crates/ui-egui/tests/it/filter_inputs.rs index b3ff2d4f..4d1500ed 100644 --- a/crates/ui-egui/tests/it/filter_inputs.rs +++ b/crates/ui-egui/tests/it/filter_inputs.rs @@ -27,7 +27,9 @@ fn the_distance_map_slot_picks_its_source() { assert!(lowest(&harness, Role::ComboBox, "Distance Map").top() > topmost(&harness, Role::Button, "Attributes").bottom(), "after the filter card"); click(&mut harness, Role::ComboBox, "Distance Map"); + assert!(harness.query_by_role_and_label(Role::Tab, "Anchor points").is_some(), "the slot opens the source picker"); + click(&mut harness, Role::ListBoxOption, "Clouds"); let Some(Source::Procedural { pattern, low, high, .. }) = input(&harness, effect, "distanceMap") else { panic!("a procedural") }; @@ -36,6 +38,7 @@ fn the_distance_map_slot_picks_its_source() { // The filter card has its own ×: the slot's is the lower one click(&mut harness, Role::Button, "Clear"); + assert_eq!(input(&harness, effect, "distanceMap"), None, "back to its default white"); let ramp = harness.get_by_role_and_label(Role::Slider, "Distance Map").rect(); @@ -79,6 +82,7 @@ fn the_attributes_row_opens_on_a_click() { let (mut harness, _) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); let category = "Category: Filter"; assert!(harness.query_by_label(category).is_none(), "closed by default"); + let band = topmost(&harness, Role::Button, "Attributes"); assert!(band.bottom() < lowest(&harness, Role::ComboBox, "Distance Map").top(), "above the input's card"); @@ -109,6 +113,7 @@ fn the_sheet_keeps_its_layout_when_the_scroll_bar_comes_in() { for frame in 0..3 { harness.run_steps(1); + assert_eq!(layout(&harness), first, "frame {frame}"); } } diff --git a/crates/ui-egui/tests/it/filter_light.rs b/crates/ui-egui/tests/it/filter_light.rs index d93268ba..40e8190c 100644 --- a/crates/ui-egui/tests/it/filter_light.rs +++ b/crates/ui-egui/tests/it/filter_light.rs @@ -57,6 +57,7 @@ fn drop_shadow_angle_drag_is_one_undo_step() { assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); undo(&mut harness); + assert!(matches!(filter_of(&harness, effect), Filter::DropShadow { angle, .. } if angle == 90.0), "{:?}", filter_of(&harness, effect)); } @@ -91,6 +92,7 @@ fn baked_lighting_stylized_cards_set_the_sun_a_light_and_the_output() { let filter = filter_of(&harness, effect); let (stylized, light) = filter.stylized_lighting().unwrap(); + assert!(light.sun.intensity > 9.5, "{}", light.sun.intensity); assert!(stylized.lights[0].intensity > 1.9 && stylized.lights[1].intensity == 0.0, "{:?}", stylized.lights); assert_eq!(stylized.output, LightingOutput::Specular); diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 69244a47..53808c42 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -30,6 +30,7 @@ fn picking_from_the_slot_swaps_the_filter() { // The picker's search field has the focus as it opens harness.event(egui::Event::Text("sharp".into())); harness.run_steps(3); + assert_eq!(harness.query_all_by_label("Blur").count(), 0, "the search hides filters that don't match"); let at = harness.get_by_label("Sharpen").rect().center(); @@ -78,6 +79,7 @@ fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { harness.run_steps(3); let at = harness.get_by_label("Sharpen").rect().center(); click_at(&mut harness, at); + assert!(matches!(filter_of(&harness, added), Filter::Sharpen { .. }), "{:?}", filter_of(&harness, added)); } @@ -85,6 +87,7 @@ fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { fn escape_after_add_filter_keeps_the_empty_filter() { let (mut harness, _) = app_with_invert(); add_filter_from_the_wand(&mut harness); + assert!(harness.query_by_label("Sharpen").is_some(), "Add filter opened the picker"); harness.key_press(egui::Key::Escape); @@ -95,6 +98,7 @@ fn escape_after_add_filter_keeps_the_empty_filter() { assert!(matches!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&harness, added)); harness.state_mut().run("edit.undo", Value::Null); + assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the empty filter"); } @@ -111,6 +115,7 @@ fn add_filter_on_a_mask_adds_it_to_the_mask() { let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; let mask = harness.state().session.doc.project.layer(layer).unwrap().mask.clone().unwrap(); + assert!(mask.effects.iter().any(|effect| effect.id == added), "the filter went on the mask"); assert!(matches!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&harness, added)); assert!(harness.query_by_label("Sharpen").is_some(), "the mask filter's picker is open"); @@ -123,6 +128,7 @@ fn add_filter_reopens_closed_properties_to_show_its_picker() { let (mut harness, _) = app_with_invert(); harness.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties); harness.run_steps(3); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Invert").is_none()); add_filter_from_the_wand(&mut harness); @@ -138,6 +144,7 @@ fn keyboard_opens_the_slot_and_outside_click_closes_it() { harness.get_by_role_and_label(Role::ComboBox, "Invert").focus(); harness.key_press(key); harness.run_steps(3); + assert!(egui::Popup::is_any_open(&harness.ctx)); let position = harness.state().viewport_rect.center(); @@ -147,6 +154,7 @@ fn keyboard_opens_the_slot_and_outside_click_closes_it() { harness.run_steps(1); } harness.run_steps(3); + assert!(!egui::Popup::is_any_open(&harness.ctx)); assert!(matches!(filter_of(&harness, effect), Filter::Invert)); } diff --git a/crates/ui-egui/tests/it/filter_shape.rs b/crates/ui-egui/tests/it/filter_shape.rs index 50358d2b..3a2b5229 100644 --- a/crates/ui-egui/tests/it/filter_shape.rs +++ b/crates/ui-egui/tests/it/filter_shape.rs @@ -127,6 +127,7 @@ fn bevel_distance_drag_is_one_undo_step() { assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::DistanceBevel(before)); } @@ -195,6 +196,7 @@ fn warp_rows_follow_the_mode() { fn slope_blur_rows_set_the_smear() { let (mut harness, effect) = app_with("slopeBlur", "mask", WINDOW_HEIGHT); assert!(harness.query_by_label("Slope scale").is_none()); + let top = |harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str| harness.get_by_role_and_label(role, label).rect().top(); let order = [ top(&harness, Role::Slider, "Intensity"), @@ -266,6 +268,7 @@ fn legacy_warp_seed_past_two_to_the_24_opens_as_stored() { click_at(&mut harness, field.center()); let typed = harness.get_all_by_role(Role::TextInput).filter(|node| node.rect().intersects(field)).find_map(|node| node.accesskit_node().value()); + assert_eq!(typed, Some(LARGE_SEED.to_string())); } @@ -287,7 +290,9 @@ fn slope_blur_divider_seed_and_source_blur() { assert_eq!(slope.divider, 1000); assert_ne!(slope.seed, 0, "a new seed"); assert!((slope.source.blur - 0.5).abs() < 0.01, "stored on 0..1: {}", slope.source.blur); + let shown = harness.get_by_role_and_label(Role::Slider, "Blur").accesskit_node().numeric_value().unwrap(); + assert!((shown - 10.0).abs() < 0.2, "shown on 0..20: {shown}"); } diff --git a/crates/ui-egui/tests/it/filter_simple.rs b/crates/ui-egui/tests/it/filter_simple.rs index 52e04446..9157f62d 100644 --- a/crates/ui-egui/tests/it/filter_simple.rs +++ b/crates/ui-egui/tests/it/filter_simple.rs @@ -16,10 +16,12 @@ fn invert_switch_turns_it_off_and_on() { let switch = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); click_at(&mut harness, switch.center()); + assert_eq!(filter_of(&harness, effect), Filter::InvertOff); let switch = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); click_at(&mut harness, switch.center()); + assert_eq!(filter_of(&harness, effect), Filter::Invert); } @@ -122,6 +124,7 @@ fn simple_sliders_set_their_own_setting() { let after = filter_of(&harness, effect); let value = read(&after).unwrap(); + assert!((value - expected).abs() < SLIDER_TOLERANCE, "{filter} {label}: {value}, expected {expected}"); assert_ne!(read(&before), read(&after), "{filter} {label} changed"); } @@ -140,6 +143,7 @@ fn a_slider_drag_is_one_undo_step() { assert_eq!(undo_depth(&harness), depth + 1); undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::Sharpen { amount: 1.0 }); } @@ -149,11 +153,13 @@ fn pixelate_rows() { let (mut harness, effect) = app_with("pixelate", "mask", WINDOW_HEIGHT); let amount = harness.get_by_role_and_label(Role::Slider, "Pixels Amount"); assert_eq!(amount.accesskit_node().numeric_value().map(f64::round), Some(32.0)); + let amount = amount.rect(); let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply To Alpha").rect(); assert!(alpha.center().y > amount.center().y); click_at(&mut harness, alpha.center()); + assert!(matches!(filter_of(&harness, effect), Filter::Mosaic { alpha: false, .. })); click_at(&mut harness, along(amount, 1.0)); @@ -198,6 +204,7 @@ fn highpass_rows() { let (mut harness, effect) = app_with("highPass", "mask", WINDOW_HEIGHT); let radius = harness.get_by_role_and_label(Role::Slider, "Radius"); assert_eq!(radius.accesskit_node().numeric_value().map(|value| (value * 100.0).round()), Some(300.0)); + let radius = radius.rect(); let space = harness.get_by_role_and_label(Role::ComboBox, "Working space / Mask").rect(); let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply To Alpha").rect(); @@ -205,9 +212,11 @@ fn highpass_rows() { pick(&mut harness, "Working space / Mask", "sRGB (from ACEScg)"); click_at(&mut harness, alpha.center()); + assert_eq!(filter_of(&harness, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::SrgbFromAcescg, alpha: true }); click_at(&mut harness, along(radius, 1.0)); + assert!(matches!(filter_of(&harness, effect), Filter::HighPass { radius, .. } if radius > 250.0), "Radius 16 = 256 texels at 2K"); } @@ -218,6 +227,7 @@ fn grayscale_conversion_rows() { let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect().center().y; let sliders = ["Balance", "Contrast", "Red", "Green", "Blue", "Alpha"].map(|label| harness.get_by_role_and_label(Role::Slider, label).rect().center().y); let rows: Vec = std::iter::once(invert).chain(sliders).collect(); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); assert!(harness.query_by_role_and_label(Role::ComboBox, "Custom Input").is_none(), "no slot for the current channel"); diff --git a/crates/ui-egui/tests/it/filter_stylize.rs b/crates/ui-egui/tests/it/filter_stylize.rs index b285db69..936f4735 100644 --- a/crates/ui-egui/tests/it/filter_stylize.rs +++ b/crates/ui-egui/tests/it/filter_stylize.rs @@ -23,6 +23,7 @@ fn anisotropic_kuwahara_rows() { let Filter::AnisotropicKuwahara(kuwahara) = filter_of(&harness, effect) else { panic!("still Kuwahara") }; assert!(kuwahara.custom_input); + let slot = lowest(&harness, Role::ComboBox, "Custom Input"); let radius = harness.get_by_role_and_label(Role::Slider, "Radius").rect(); assert!(slot.center().y < radius.center().y, "its slot right under Extract Direction"); @@ -150,6 +151,7 @@ fn color_match_rows() { assert_eq!(color_match_of(&harness, effect).target_mode, TargetColorMode::ImageInput); assert!(harness.query_by_role_and_label(Role::Button, "Target Color").is_none(), "the Image Input slot replaces Target Color"); + let shown = harness.query_all_by_label("Image Input").count(); assert!(shown >= 2, "the mode and its slot: {shown}"); @@ -164,15 +166,18 @@ fn color_match_rows() { click_at(&mut harness, row.center()); assert_eq!(color_match_of(&harness, effect).source_mode, SourceColorMode::Parameter); + let source = harness.get_by_role_and_label(Role::Button, "Source Color").rect(); assert!(source.center().y < target_mode(&harness, "Image Input").center().y, "Source Color right under its mode"); let luma = harness.get_by_role_and_label(Role::Slider, "Luma").rect(); click_at(&mut harness, along(luma, 1.0)); + assert!(color_match_of(&harness, effect).luma > 0.95, "{}", color_match_of(&harness, effect).luma); let custom = harness.get_by_role_and_label(Role::CheckBox, "Custom Color Variation").rect(); click_at(&mut harness, custom.center()); + assert!(!color_match_of(&harness, effect).custom_variation); assert!(harness.query_by_role_and_label(Role::Slider, "Hue").is_none(), "the Color Variation card goes with its switch"); } diff --git a/crates/ui-egui/tests/it/filter_transform.rs b/crates/ui-egui/tests/it/filter_transform.rs index 38af6e79..4f526a30 100644 --- a/crates/ui-egui/tests/it/filter_transform.rs +++ b/crates/ui-egui/tests/it/filter_transform.rs @@ -82,5 +82,6 @@ fn rotation_drag_is_one_undo_step() { assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::Transform(TileTransform::LIBRARY)); } diff --git a/crates/ui-egui/tests/it/properties_lists.rs b/crates/ui-egui/tests/it/properties_lists.rs index ef3bcb47..e5aef5c7 100644 --- a/crates/ui-egui/tests/it/properties_lists.rs +++ b/crates/ui-egui/tests/it/properties_lists.rs @@ -174,6 +174,7 @@ fn check_list(harness: &mut Harness<'_, TextureCraftApp>, button: Rect, name: &s if !is_open(harness) && !open(harness, button) { return [problems, vec![format!("{name}: it does not open again after the wheel")]].concat(); } + if !pans(harness, gesture_start) { problems.push(format!("{name}: a middle drag in the view does not pan while it is open")); } @@ -182,6 +183,7 @@ fn check_list(harness: &mut Harness<'_, TextureCraftApp>, button: Rect, name: &s if !is_open(harness) && !open(harness, button) { return [problems, vec![format!("{name}: a second click does not open it")]].concat(); } + if !orbits(harness, gesture_start) { problems.push(format!("{name}: an Alt drag in the view does not orbit while it is open")); } @@ -189,6 +191,7 @@ fn check_list(harness: &mut Harness<'_, TextureCraftApp>, button: Rect, name: &s if !is_open(harness) && !open(harness, button) { return [problems, vec![format!("{name}: it does not open again")]].concat(); } + harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); if is_open(harness) { @@ -219,6 +222,7 @@ fn every_list_opens_leaves_the_view_its_camera_and_closes_on_escape_a_click_and_ for (screen, mut harness) in screens() { let count = lists(&harness).len(); assert!(count > 0, "{screen}: lists show"); + for index in 0..count { // Looked up again each time: a closed list or a stroke may move the rows below let Some((button, shown)) = lists(&harness).get(index).cloned() else { @@ -233,6 +237,7 @@ fn every_list_opens_leaves_the_view_its_camera_and_closes_on_escape_a_click_and_ } } } + assert!(problems.is_empty(), "{}", problems.join("\n")); } @@ -257,6 +262,7 @@ fn the_colour_picker_window_and_the_symmetry_settings_leave_the_view_its_wheel_m harness.run_steps(SETTLE_FRAMES); let settings_open = |harness: &Harness<'_, TextureCraftApp>| harness.query_by_label("Radial symmetry").is_some(); assert!(settings_open(&harness), "the settings open"); + let start = gesture_start(&harness); assert!(zooms(&mut harness, start), "the wheel over the view zooms with the symmetry settings open"); assert!(settings_open(&harness), "the wheel leaves the settings open"); From a9928aacf3ef2cbd28b19516a203d556fef4a836 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:30:01 +0000 Subject: [PATCH 6/6] Instanced folders: a filter's lit layer and height read the instance's space too The filter stack's own plans (the lit base colour below a filter and the heights it reads) take the traversal's folder offset, as the neighbourhood fields do since part 4. --- crates/compose/src/eval.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 7b0ef05b..b53c134f 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1532,10 +1532,11 @@ fn filter_region( .par_iter() .map(|&(tile_x, tile_y)| { // A base colour lit by its material below the filter lights it as the full render does - let lit_layer = if lit_prefix { plan(inputs, &[id], channels, tile_x, tile_y, 0, Some(below)).into_iter().find(|node| node.lights) } else { None }; + let lit_layer = + if lit_prefix { plan_in(inputs, &[id], channels, tile_x, tile_y, 0, Some(below), around).into_iter().find(|node| node.lights) } else { None }; let anchor_nodes = below_plan(inputs, id, channels, (tile_x, tile_y), Some(below), lit_layer.is_some()); let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); - let height_nodes = if heights { plan(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below)) } else { Vec::new() }; + let height_nodes = if heights { plan_in(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below), around) } else { Vec::new() }; let mut mask = None; let mut nodes = Vec::new(); let mut generator_sizes = None; @@ -6039,7 +6040,10 @@ soft {soft:?}" let shared = shared_histogram_fields(&inputs, &channels, &all_tiles(64, 64)); - assert!(shared.is_some_and(|fields| fields.contains_key(&FieldKey::Content(id, Channel::BaseColor))), "every sampled tile reads one field"); + assert!( + shared.is_some_and(|fields| fields.contains_key(&FieldKey::content(id, Channel::BaseColor, ContentsOffset::NONE))), + "every sampled tile reads one field" + ); } #[test]