From 02bda17b9faaa77ddc270eb87a213bccda23edb5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH] Generators: Light on the reference's angles, highlight and attenuation Light takes the reference app's controls: a horizontal and a vertical angle, each a dial beside an Angle slider in degrees, highlight glossiness and level, and light attenuation. It shades the world space normal (else the mesh's normal) towards the light and fades the side away from it across the position map (else the mesh's bounds); invert shades the far side instead. Both maps can read an image input instead, and Light has no global adjustments. Light generators saved before keep their level, softness, noise and direction and render as before; a light control moves one onto the new controls. --- crates/compose/src/eval.rs | 10 +- crates/compose/src/sections.rs | 83 +++++++++++++- crates/compose/tests/generator_sections.rs | 49 ++++++++- crates/core/src/layer.rs | 23 ++-- crates/core/src/layer/light_parameters.rs | 50 +++++++++ crates/core/src/lib.rs | 2 +- crates/engine/src/mask_cmds.rs | 64 ++++++++--- crates/engine/src/smart_masks.rs | 5 +- crates/engine/tests/it/generator_sections.rs | 33 +++++- crates/ui-egui/src/generator_panel.rs | 109 +++++++++++++++++-- crates/ui-egui/src/widgets.rs | 31 ++++-- crates/ui-egui/tests/it/generator_panel.rs | 34 +++++- 12 files changed, 439 insertions(+), 54 deletions(-) create mode 100644 crates/core/src/layer/light_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 896dab07..1e342957 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2057,10 +2057,10 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, .collect() } -/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset (the light controls invert their shading themselves) fn finish_generator(generator: &Generator, ramp: f32) -> f32 { let value = generator.applied_global().apply(ramp); - let value = if generator.invert { 1.0 - value } else { value }; + let value = if generator.invert && generator.light.is_none() { 1.0 - value } else { value }; let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; (value + offset).clamp(0.0, 1.0) } @@ -3327,6 +3327,12 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(wear) = wear_parameters(generator) { return self.wear_ramp(generator, &wear, curvature_sizes); } + if let Some(light) = &generator.light { + let normal = + self.generator_input_color(generator, BakedMap::WorldNormal).map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let position = self.generator_input_color(generator, BakedMap::Position).map_or_else(|| self.bounds_position(), Vec3::from); + return sections::light_value(light, normal, position, generator.invert); + } if let Some(section) = generator.section_controls() { return self.section_signal(generator, §ion, curvature_sizes); } diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs index 2a6f9294..a9da83bc 100644 --- a/crates/compose/src/sections.rs +++ b/crates/compose/src/sections.rs @@ -1,6 +1,7 @@ -//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators +//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators, and the Light generator's shading -use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, SectionParameters}; +use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, LightParameters, SectionParameters}; +use texturecraft_geom::glam::Vec3; /// Gaussian sigma of the section blur per unit of its slider, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`] const BLUR_SIGMA_PER_UNIT: f32 = 4.5; @@ -14,6 +15,15 @@ const FULL_CONTRAST_STEP_OFFSET: f32 = 4.6e-5; /// The order the axes combine in, as indices into [`SectionParameters::axes`]: top to bottom is the base, front to back goes last const AXIS_ORDER: [usize; 3] = [SectionParameters::TOP_TO_BOTTOM, SectionParameters::RIGHT_TO_LEFT, SectionParameters::FRONT_TO_BACK]; +/// Distance of a light-facing tangent plane from the centre of the position map's unit cube +const ATTENUATION_PLANE_OFFSET: f32 = 0.5; + +/// Light attenuation above which the falloff fades the whole mesh towards black instead of steepening +const ATTENUATION_STEEPEST: f32 = 0.5; + +/// Shortest decoded normal still given a direction +const MIN_NORMAL_LENGTH: f32 = 1e-6; + /// A map's three channels (0..1) combined by `axes`: each axis read from its channel, inverted, blended over the axes before it and weighted pub(crate) fn axes_signal(channels: [f32; 3], axes: &[AxisLayer; 3]) -> f32 { AXIS_ORDER.iter().fold(0.0, |base, &index| { @@ -91,6 +101,35 @@ fn contrasted(value: f32, contrast: f32) -> f32 { ((value - (0.5 - half_range)) / (2.0 * half_range)).clamp(0.0, 1.0) } +/// The direction the light comes from: `horizontal` degrees around the up axis from -X towards +Z, `vertical` degrees above the horizon +pub(crate) fn light_direction(horizontal: f32, vertical: f32) -> Vec3 { + let (horizontal, vertical) = (horizontal.to_radians(), vertical.to_radians()); + Vec3::new(-vertical.cos() * horizontal.cos(), vertical.sin(), vertical.cos() * horizontal.sin()) +} + +/// The Light generator at a texel with world `normal` and `position` (0..1 across the mesh's bounds): lit, highlighted and faded with depth +pub(crate) fn light_value(light: &LightParameters, normal: Vec3, position: Vec3, invert: bool) -> f32 { + let direction = light_direction(light.horizontal, light.vertical); + let normal = if normal.length() > MIN_NORMAL_LENGTH { normal.normalize() } else { Vec3::Y }; + + // Glossiness 0 lights the half facing away too, 0.5 is a plain diffuse falloff + let glossiness = light.glossiness.clamp(*LightParameters::GLOSSINESS_RANGE.start(), *LightParameters::GLOSSINESS_RANGE.end()); + let threshold = 2.0 * glossiness - 1.0; + let diffuse = ((normal.dot(direction) - threshold) / (1.0 - threshold)).clamp(0.0, 1.0); + let highlight_level = light.highlight_level.clamp(0.0, 1.0); + let diffuse = if highlight_level >= 1.0 { if diffuse > 0.0 { 1.0 } else { 0.0 } } else { (diffuse / (1.0 - highlight_level)).clamp(0.0, 1.0) }; + + // Depth from the tangent plane facing the light + let depth = ATTENUATION_PLANE_OFFSET - (position - Vec3::splat(0.5)).dot(direction); + let attenuation = light.attenuation.clamp(0.0, 1.0); + let kept = if attenuation <= ATTENUATION_STEEPEST { + (1.0 - 2.0 * attenuation * depth).clamp(0.0, 1.0) + } else { + (1.0 - depth).clamp(0.0, 1.0) * (2.0 - 2.0 * attenuation) + }; + kept * if invert { 1.0 - diffuse } else { diffuse } +} + #[cfg(test)] mod tests { use super::*; @@ -196,4 +235,44 @@ mod tests { let radius = blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048) as f32; assert!((radius * (radius + 1.0)).sqrt() - 4.5 < 0.6, "three boxes of radius {radius} spread like sigma 4.5"); } + + #[test] + fn light_angles_point_at_the_reference_axes() { + let close = |a: Vec3, b: Vec3| (a - b).length() < 1e-5; + assert!(close(light_direction(0.0, 0.0), Vec3::NEG_X)); + assert!(close(light_direction(90.0, 0.0), Vec3::Z)); + assert!(close(light_direction(180.0, 0.0), Vec3::X)); + assert!(close(light_direction(33.0, 90.0), Vec3::Y)); + } + + #[test] + fn light_lights_the_faces_towards_it() { + let light = LightParameters { horizontal: 0.0, vertical: 0.0, attenuation: 0.0, ..LightParameters::defaults(GeneratorKind::Direction).unwrap() }; + let middle = Vec3::splat(0.5); + assert_eq!(light_value(&light, Vec3::NEG_X, middle, false), 1.0); + assert_eq!(light_value(&light, Vec3::X, middle, false), 0.0); + assert!((light_value(&light, Vec3::new(-1.0, 1.0, 0.0), middle, false) - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-5, "a plain diffuse falloff"); + assert_eq!(light_value(&light, Vec3::X, middle, true), 1.0, "invert lights the far side"); + + let half_lambert = LightParameters { glossiness: 0.0, ..light }; + assert!((light_value(&half_lambert, Vec3::Y, middle, false) - 0.5).abs() < 1e-6, "glossiness 0 lights the side faces half"); + let highlighted = LightParameters { highlight_level: 0.5, ..light }; + assert!((light_value(&highlighted, Vec3::new(-1.0, 3.0, 0.0), middle, false) - 2.0 * 10f32.sqrt().recip()).abs() < 1e-5); + let saturated = LightParameters { highlight_level: 1.0, ..light }; + assert_eq!(light_value(&saturated, Vec3::new(-0.01, 1.0, 0.0), middle, false), 1.0, "any lit texel is white"); + } + + #[test] + fn attenuation_darkens_the_side_away_from_the_light() { + let light = LightParameters { horizontal: 0.0, vertical: 0.0, glossiness: 0.0, ..LightParameters::defaults(GeneratorKind::Direction).unwrap() }; + let near = light_value(&light, Vec3::Y, Vec3::new(0.0, 0.5, 0.5), false); + let far = light_value(&light, Vec3::Y, Vec3::new(1.0, 0.5, 0.5), false); + assert!((near - 0.5).abs() < 1e-6, "the face of the bounds towards the light keeps its value"); + assert!((far - 0.25).abs() < 1e-6, "attenuation 0.25 halves it across the bounds"); + + let none = LightParameters { attenuation: 0.0, ..light }; + assert_eq!(light_value(&none, Vec3::Y, Vec3::new(1.0, 0.5, 0.5), false), near); + let full = LightParameters { attenuation: 1.0, ..light }; + assert_eq!(light_value(&full, Vec3::Y, Vec3::new(0.0, 0.5, 0.5), false), 0.0, "attenuation 1 is black everywhere"); + } } diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs index 3a9b65c4..27693163 100644 --- a/crates/compose/tests/generator_sections.rs +++ b/crates/compose/tests/generator_sections.rs @@ -1,11 +1,11 @@ -//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators on a sphere, beside their earlier model +//! The section and light controls of the Curvature, Ambient Occlusion, Position, World Space Normals and Light generators on a sphere, beside their earlier model use std::sync::Arc; use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; use texturecraft_core::{ - AxisBlend, BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, - SectionParameters, Source, TextureSet, + AxisBlend, BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, LightParameters, Mask, MaskBackground, + Project, SectionParameters, Source, TextureSet, }; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; @@ -77,7 +77,7 @@ fn earlier_ramp(generator: &Generator, signal: f32) -> f32 { } fn earlier(kind: GeneratorKind) -> Generator { - Generator { section: None, ..Generator::new(kind) } + Generator { section: None, light: None, ..Generator::new(kind) } } fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters)) -> Generator { @@ -88,6 +88,14 @@ fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters) generator } +fn with_light(change: impl FnOnce(&mut LightParameters)) -> Generator { + let mut generator = Generator::new(GeneratorKind::Direction); + let mut light = generator.light.unwrap(); + change(&mut light); + generator.light = Some(light); + generator +} + fn assert_close(actual: &[f32], expected: &[f32], what: &str) { for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); @@ -199,3 +207,36 @@ fn section_blur_spreads_occlusion_across_a_step() { fixture.baked = uniform_map(BakedMap::Position, 0.3); assert_close(&mask(&mut fixture, position, &row), &vec![0.3; row.len()], "position has no section blur"); } + +#[test] +fn light_angles_light_the_faces_towards_them() { + let mut fixture = fixture(); + let points = surface(&fixture); + let facing = |axis: Vec3| -> Vec<(u32, u32)> { points.iter().filter(|(_, _, nrm)| nrm.dot(axis) > 0.97).map(|point| point.0).collect() }; + + for (horizontal, vertical, towards) in [(0.0, 0.0, Vec3::NEG_X), (90.0, 0.0, Vec3::Z), (180.0, 0.0, Vec3::X), (0.0, 90.0, Vec3::Y)] { + let light = with_light(|light| (light.horizontal, light.vertical, light.attenuation) = (horizontal, vertical, 0.0)); + let lit = mask(&mut fixture, light.clone(), &facing(towards)); + let dark = mask(&mut fixture, light, &facing(-towards)); + assert!(lit.iter().all(|value| *value > 0.95), "{horizontal}° {vertical}° lights {towards}: {lit:?}"); + assert!(dark.iter().all(|value| *value == 0.0), "{horizontal}° {vertical}° leaves {} dark: {dark:?}", -towards); + } + + let inverted = Generator { invert: true, ..with_light(|light| (light.horizontal, light.vertical, light.attenuation) = (0.0, 0.0, 0.0)) }; + assert!(mask(&mut fixture, inverted, &facing(Vec3::X)).iter().all(|value| *value > 0.95), "invert lights the far side"); +} + +#[test] +fn light_attenuation_darkens_the_side_away_from_the_light() { + let mut fixture = fixture(); + let sides: Vec<(u32, u32)> = surface(&fixture).iter().filter(|(_, _, nrm)| nrm.y > 0.97).map(|point| point.0).collect(); + let half_lit = + |attenuation: f32| with_light(|light| (light.horizontal, light.vertical, light.glossiness, light.attenuation) = (0.0, 0.0, 0.0, attenuation)); + + let kept = mask(&mut fixture, half_lit(0.0), &sides); + let attenuated = mask(&mut fixture, half_lit(0.5), &sides); + for (kept, attenuated) in kept.iter().zip(&attenuated) { + assert!((kept - 0.5).abs() < 0.15, "the top is about half lit from the side: {kept}"); + assert!(*attenuated < kept * 0.75, "halfway across the bounds, attenuation darkens it: {attenuated} vs {kept}"); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 1e0f001d..fedcca8a 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -20,6 +20,7 @@ mod decal_flip; mod decal_symmetry; mod filtering; mod generator_global; +mod light_parameters; mod micro_detail; mod output_resolution; mod resolution_mode; @@ -44,6 +45,7 @@ pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; +pub use light_parameters::LightParameters; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; @@ -1000,7 +1002,7 @@ impl GeneratorKind { GeneratorKind::ThinAreas => &[BakedMap::Thickness], GeneratorKind::Position => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], - GeneratorKind::Direction => &[], + GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], } } @@ -1057,6 +1059,9 @@ pub struct Generator { /// The section controls of Curvature, Ambient Occlusion, Position and World Space Normals (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub section: Option, + /// The Light generator's controls (None: the level, softness and noise above, as saved before they existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub light: Option, } impl Generator { @@ -1067,9 +1072,9 @@ impl Generator { pub const MIN_NOISE_SCALE: f32 = 0.01; pub const MAX_NOISE_SCALE: f32 = 1000.0; - /// The global blur, balance and contrast the generator applies: none on the wear controls, which have no such controls + /// The global blur, balance and contrast the generator applies: none on the wear and light controls, which have no such controls pub fn applied_global(&self) -> GeneratorGlobal { - if self.wear.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } + if self.wear.is_some() || self.light.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } } /// The section controls the generator computes with: its own, World Space Normals' defaults when it has none (it has no earlier model), else None @@ -1079,7 +1084,7 @@ impl Generator { /// Whether the generator is on the level, softness and noise it had before the reference app's controls pub fn on_earlier_model(&self) -> bool { - self.wear.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear + self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear } pub fn new(kind: GeneratorKind) -> Generator { @@ -1112,6 +1117,7 @@ impl Generator { micro: None, wear: WearParameters::defaults(kind), section: SectionParameters::defaults(kind), + light: LightParameters::defaults(kind), } } @@ -2345,12 +2351,13 @@ mod tests { } #[test] - fn generators_saved_before_their_section_controls_load_on_the_earlier_model() { - for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position] { + fn generators_saved_before_their_section_or_light_controls_load_on_the_earlier_model() { + for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position, GeneratorKind::Direction] { let mut saved = serde_json::to_value(Generator::new(kind)).unwrap(); - assert!(saved.get("section").is_some(), "new {kind:?} generators have the reference's controls"); + let key = if kind == GeneratorKind::Direction { "light" } else { "section" }; + assert!(saved.get(key).is_some(), "new {kind:?} generators have the reference's controls"); - saved.as_object_mut().unwrap().remove("section"); + saved.as_object_mut().unwrap().remove(key); let loaded: Generator = serde_json::from_value(saved).unwrap(); assert!(loaded.on_earlier_model(), "{kind:?}: level, softness and noise keep driving it"); assert_eq!(loaded.applied_global(), loaded.global, "{kind:?} keeps its global adjustments"); diff --git a/crates/core/src/layer/light_parameters.rs b/crates/core/src/layer/light_parameters.rs new file mode 100644 index 00000000..5334675c --- /dev/null +++ b/crates/core/src/layer/light_parameters.rs @@ -0,0 +1,50 @@ +use serde::{Deserialize, Serialize}; + +use super::GeneratorKind; + +/// The Light generator's controls: where the light comes from, how its highlight spreads and how it fades across the mesh +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LightParameters { + /// Degrees around the up axis (0 from -X, 90 from +Z) + pub horizontal: f32, + /// Degrees above the horizon (90 from straight above) + pub vertical: f32, + /// How narrow the lit area is ([`LightParameters::GLOSSINESS_RANGE`]; 0.5 a plain diffuse falloff) + pub glossiness: f32, + /// How much the lit area is pushed to white (0..1; 1 every lit texel white) + pub highlight_level: f32, + /// How much the side away from the light darkens (0..1) + pub attenuation: f32, +} + +impl LightParameters { + pub const ANGLE_RANGE: std::ops::RangeInclusive = 0.0..=360.0; + pub const GLOSSINESS_RANGE: std::ops::RangeInclusive = 0.0..=0.999; + + /// The reference app's defaults for `kind`, or None for kinds other than Light + pub fn defaults(kind: GeneratorKind) -> Option { + (kind == GeneratorKind::Direction).then_some(LightParameters { + horizontal: 90.0, + vertical: 45.0, + glossiness: 0.5, + highlight_level: 0.0, + attenuation: 0.25, + }) + } + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> LightParameters { + let defaults = LightParameters::defaults(GeneratorKind::Direction).unwrap_or(self); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + LightParameters { + horizontal: within(self.horizontal, defaults.horizontal, LightParameters::ANGLE_RANGE), + vertical: within(self.vertical, defaults.vertical, LightParameters::ANGLE_RANGE), + glossiness: within(self.glossiness, defaults.glossiness, LightParameters::GLOSSINESS_RANGE), + highlight_level: within(self.highlight_level, defaults.highlight_level, 0.0..=1.0), + attenuation: within(self.attenuation, defaults.attenuation, 0.0..=1.0), + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 222613cf..c5ff7ec3 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -112,7 +112,7 @@ pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ AxisBlend, AxisLayer, 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, + GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 1b23275d..2ed442d1 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, + GeneratorKind, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ 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; \"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: swaps its kind in place, starting from that kind's defaults), wear and section controls (see effect.add.generator), 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: swaps its kind in place, starting from that kind's defaults), wear, section and light controls (see effect.add.generator), 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 ), @@ -472,7 +472,7 @@ pub fn wear_key_applies(kind: GeneratorKind, key: &str) -> bool { } } -/// The parameters that drive the earlier model of the kinds with section controls +/// The parameters that drive the earlier model of the kinds with section or light controls const EARLIER_SECTION_KEYS: [&str; 6] = ["level", "softness", "noise", "noiseScale", "offset", "direction"]; /// The section controls `effect.add.generator` and `effect.set` take, beside the axis keys made of [`AXIS_NAMES`] and [`AXIS_SUFFIXES`] @@ -482,32 +482,41 @@ const SECTION_KEYS: [&str; 5] = ["sectionInvert", "sectionBlur", "sectionBalance const AXIS_NAMES: [&str; 3] = ["rightLeft", "topBottom", "frontBack"]; const AXIS_SUFFIXES: [&str; 3] = ["Invert", "Blend", "Weight"]; -/// The section controls and the axis keys `params` gives +/// The Light generator's controls +const LIGHT_KEYS: [&str; 5] = ["lightHorizontal", "lightVertical", "highlightGlossiness", "highlightLevel", "lightAttenuation"]; + +/// The section controls, the axis keys and the light controls `params` gives fn given_new_model_keys(params: &Value) -> Vec { let axis_keys = AXIS_NAMES.iter().flat_map(|axis| AXIS_SUFFIXES.iter().map(move |suffix| format!("{axis}{suffix}"))); - SECTION_KEYS.iter().map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() + SECTION_KEYS.iter().chain(LIGHT_KEYS.iter()).map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() } -/// The section controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model +/// The section and light controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { let kind = generator.kind; let new_keys = given_new_model_keys(params); let earlier = EARLIER_SECTION_KEYS.iter().any(|key| params.get(*key).is_some()); - let Some(defaults) = SectionParameters::defaults(kind) else { + let section_defaults = SectionParameters::defaults(kind); + let light_defaults = LightParameters::defaults(kind); + if section_defaults.is_none() && light_defaults.is_none() { return match new_keys.first() { - Some(key) => { - Err(bad(command, format!("{} has no `{key}`: only Curvature, Ambient Occlusion, Position and World Space Normals have it", kind.label()))) - } + Some(key) => Err(bad( + command, + format!("{} has no `{key}`: only Curvature, Ambient Occlusion, Position, World Space Normals and Light have them", kind.label()), + )), None => Ok(()), }; - }; + } if let Some(unused) = new_keys.iter().find(|key| !section_key_applies(kind, key)) { return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); } if earlier { if !new_keys.is_empty() { - return Err(bad(command, "level, softness, noise, offset and direction drive the earlier model: give them or the section controls, not both")); + return Err(bad( + command, + "level, softness, noise, offset and direction drive the earlier model: give them or the section and light controls, not both", + )); } if kind == GeneratorKind::WorldSpaceNormals { return Err(bad( @@ -516,8 +525,13 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res )); } generator.section = None; + generator.light = None; return Ok(()); } + let on_light = generator.light.is_some() || (light_defaults.is_some() && !new_keys.is_empty()); + if on_light && GLOBAL_KEYS.iter().any(|key| params.get(*key).is_some()) { + return Err(bad(command, "Light has no global blur, balance or contrast on its light controls")); + } if new_keys.is_empty() { return Ok(()); } @@ -528,8 +542,28 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res (generator.level, generator.softness, generator.noise_amount, generator.noise_scale) = (defaults.level, defaults.softness, defaults.noise_amount, defaults.noise_scale); (generator.offset, generator.direction) = (defaults.offset, defaults.direction); + if light_defaults.is_some() { + generator.global = defaults.global; + } + } + if let Some(defaults) = light_defaults { + let light = generator.light.get_or_insert(defaults); + for (key, value) in [ + ("lightHorizontal", &mut light.horizontal), + ("lightVertical", &mut light.vertical), + ("highlightGlossiness", &mut light.glossiness), + ("highlightLevel", &mut light.highlight_level), + ("lightAttenuation", &mut light.attenuation), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + *light = light.clamped(); + return Ok(()); } + let Some(defaults) = section_defaults else { return Ok(()) }; let mut section = generator.section_controls().unwrap_or(defaults); for (key, value) in [ ("sectionBlur", &mut section.blur), @@ -561,7 +595,7 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res Ok(()) } -/// Whether section control `key` changes a generator of `kind` +/// Whether section or light control `key` changes a generator of `kind` pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { let axis_key = AXIS_NAMES.iter().any(|axis| key.strip_prefix(axis).is_some_and(|suffix| AXIS_SUFFIXES.contains(&suffix))); match key { @@ -570,7 +604,7 @@ pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { "sectionBalance" => SectionParameters::has_balance(kind), "sectionBrightness" => SectionParameters::has_brightness(kind), _ if axis_key => SectionParameters::has_axes(kind), - _ => false, + _ => LIGHT_KEYS.contains(&key) && LightParameters::defaults(kind).is_some(), } } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index ceeb23cf..6b98e571 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -79,9 +79,9 @@ pub fn find(name: &str) -> Option<&'static SmartMask> { const UP: [f32; 3] = [0.0, 1.0, 0.0]; -/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or the wear and section controls) +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or the wear, section and light controls) pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: None, light: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). @@ -95,6 +95,7 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, detail: None, wear: None, section: None, + light: None, ..Generator::new(kind) }) } diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index 02c68135..60676684 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -1,7 +1,7 @@ -//! The section controls through `effect.add.generator` and `effect.set`, beside the earlier level, softness and noise +//! The section and light controls through `effect.add.generator` and `effect.set`, beside the earlier level, softness and noise use serde_json::{Value, json}; -use texturecraft_engine::core::{AxisBlend, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters}; +use texturecraft_engine::core::{AxisBlend, EffectKind, Generator, GeneratorKind, LayerId, LightParameters, SectionParameters}; use texturecraft_engine::mask_cmds::section_key_applies; use texturecraft_engine::{Session, execute}; @@ -31,6 +31,9 @@ fn new_generators_start_on_the_reference_controls() { let added = generator(&session, effect); assert_eq!(added.section, SectionParameters::defaults(added.kind), "{kind}"); } + let effect = add(&mut session, json!({"generator": "direction"})); + let light = generator(&session, effect); + assert_eq!(light.light, LightParameters::defaults(GeneratorKind::Direction)); assert_eq!(GeneratorKind::parse("World Space Normals"), Some(GeneratorKind::WorldSpaceNormals)); } @@ -72,6 +75,7 @@ fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { (occlusion, "sectionBrightness"), (occlusion, "rightLeftInvert"), (position, "sectionBlur"), + (position, "lightHorizontal"), (dirt, "sectionContrast"), ] { assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.5})).is_err(), "{key} on {effect}"); @@ -88,3 +92,28 @@ fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { assert!(!section_key_applies(GeneratorKind::Position, "sectionBlur")); assert!(section_key_applies(GeneratorKind::WorldSpaceNormals, "rightLeftBlend")); } + +#[test] +fn light_takes_its_controls_and_refuses_the_global_ones() { + let mut session = session(); + let light = add(&mut session, json!({"generator": "direction"})); + execute(&mut session, "effect.set", &json!({"effect": light, "lightHorizontal": 400.0, "highlightGlossiness": 1.0, "invert": true})).unwrap(); + let edited = generator(&session, light); + let expected = LightParameters { + horizontal: 360.0, + glossiness: *LightParameters::GLOSSINESS_RANGE.end(), + ..LightParameters::defaults(GeneratorKind::Direction).unwrap() + }; + assert_eq!(edited.light, Some(expected)); + assert!(edited.invert); + + assert!(execute(&mut session, "effect.set", &json!({"effect": light, "blur": 0.5})).is_err(), "Light has no global blur"); + assert!(execute(&mut session, "effect.set", &json!({"effect": light, "sectionInvert": true})).is_err()); + + let earlier = add(&mut session, json!({"generator": "direction", "level": 0.4, "blur": 0.3})); + assert_eq!(generator(&session, earlier).light, None, "the earlier model keeps its global adjustments"); + execute(&mut session, "effect.set", &json!({"effect": earlier, "lightVertical": 60.0})).unwrap(); + let moved = generator(&session, earlier); + assert_eq!(moved.light.map(|light| light.vertical), Some(60.0)); + assert_eq!(moved.global, Generator::new(GeneratorKind::Direction).global, "the light controls have no global adjustments"); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index e9df3bba..effda2d1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,8 +4,8 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, SectionParameters, Source, - WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, + SectionParameters, Source, WearParameters, }; use crate::TextureCraftApp; @@ -13,7 +13,7 @@ use crate::dock::{anchor_entries, anchor_label, anchors_below, effect_anchors_be use crate::i18n::{baked_map_label, tr, trf}; use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; use crate::theme::{Tokens, caption}; -use crate::widgets::{combo, section, slider_edit}; +use crate::widgets::{combo, section, slider_edit, slider_edit_with_suffix}; /// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. const INPUT_TILE_SIZE: f32 = 32.0; @@ -23,6 +23,14 @@ const INPUT_TILE_ICON_SIZE: f32 = 16.0; /// Width of a False/True button, so the buttons line up under each other const TOGGLE_WIDTH: f32 = 136.0; +/// Edge of a light angle's dial, the width of its needle and the radius of its hub +const DIAL_SIZE: f32 = 36.0; +const DIAL_NEEDLE_WIDTH: f32 = 2.0; +const DIAL_HUB_RADIUS: f32 = 2.0; + +/// Closest to a dial's centre a pointer still turns it, so the angle is defined +const DIAL_DEAD_ZONE: f32 = 1.0; + /// The settings of generator effect `id`. pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { let tokens = Tokens::get(ui.ctx()); @@ -34,15 +42,20 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer if let Some(defaults) = WearParameters::defaults(generator.kind) { // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); + } else if let Some(light) = generator.light { + light_parameters(app, ui, id, Some(generator.invert), light); } else { global_adjustments(app, ui, id, generator); if generator.on_earlier_model() { ramp_parameters(app, ui, id, generator); } - // Saved before the section controls, a generator shows them at their defaults: editing one moves it onto them + // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(generator.kind) { section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); } + if let Some(defaults) = LightParameters::defaults(generator.kind) { + light_parameters(app, ui, id, None, defaults); + } } if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { micro_detail_properties(app, ui, id, generator.micro, layer); @@ -95,9 +108,9 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr } } -/// The inputs `generator` reads: none for Position on its earlier model, which reads the mesh itself +/// The inputs `generator` reads: none for Position and Light on their earlier model, which read the mesh itself fn inputs_in_use(generator: &Generator) -> &'static [BakedMap] { - let reads_geometry = generator.on_earlier_model() && generator.kind == GeneratorKind::Position; + let reads_geometry = generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction); if reads_geometry { &[] } else { generator.kind.inputs() } } @@ -322,10 +335,11 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); - let own = match (&defaults.wear, &defaults.section) { - (Some(wear), _) => wear_params(kind, wear), - (None, Some(section)) => merged(section_params(kind, section), global), - (None, None) => json!({ + let own = match (&defaults.wear, &defaults.section, &defaults.light) { + (Some(wear), _, _) => wear_params(kind, wear), + (None, _, Some(light)) => light_params(light), + (None, Some(section), None) => merged(section_params(kind, section), global), + (None, None, None) => json!({ "level": defaults.level, "softness": defaults.softness, "noise": defaults.noise_amount, @@ -436,6 +450,81 @@ fn axis_blend_label(blend: AxisBlend) -> &'static str { } } +/// The Light generator's controls of effect `id`, showing `shown`; `invert` adds its Invert row (None on the earlier model, whose global invert it is) +fn light_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, invert: Option, shown: LightParameters) { + if let Some(mut invert) = invert + && true_false(ui, tr("Invert"), &mut invert) + { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + let mut edited = shown; + let mut edit = angle_row(ui, "generator_light_horizontal", tr("Horizontal angle"), &mut edited.horizontal); + edit = edit.or(angle_row(ui, "generator_light_vertical", tr("Vertical angle"), &mut edited.vertical)); + edit = edit.or(slider_edit(ui, tr("Highlight glossiness"), &mut edited.glossiness, LightParameters::GLOSSINESS_RANGE, 2)); + edit = edit.or(slider_edit(ui, tr("Highlight level"), &mut edited.highlight_level, 0.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Light attenuation"), &mut edited.attenuation, 0.0..=1.0, 2)); + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), light_params(&edited))); + } +} + +/// The `effect.set` params that set every light control to `light` +fn light_params(light: &LightParameters) -> Value { + json!({ + "lightHorizontal": light.horizontal, + "lightVertical": light.vertical, + "highlightGlossiness": light.glossiness, + "highlightLevel": light.highlight_level, + "lightAttenuation": light.attenuation, + }) +} + +/// A light angle in degrees: its name, then a dial beside an Angle slider; `Some(merge)` when either changes it +fn angle_row(ui: &mut Ui, id: &str, label: &str, degrees: &mut f32) -> Option { + ui.label(label); + ui.push_id(id, |ui| { + ui.horizontal(|ui| { + let dial = angle_dial(ui, label, degrees); + let slider = ui.vertical(|ui| slider_edit_with_suffix(ui, tr("Angle"), degrees, LightParameters::ANGLE_RANGE, 0, "°")).inner; + dial.or(slider) + }) + .inner + }) + .inner +} + +/// A round dial whose needle points at `degrees` (counterclockwise from the right); dragging it turns it, `Some(merge)` like [`slider_edit`] +fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(egui::vec2(DIAL_SIZE, DIAL_SIZE), egui::Sense::click_and_drag()); + let mut edit = None; + if (response.dragged() || response.clicked()) + && let Some(pointer) = response.interact_pointer_pos() + { + let offset = pointer - rect.center(); + let turned = (-offset.y).atan2(offset.x).to_degrees().rem_euclid(*LightParameters::ANGLE_RANGE.end()); + if offset.length() > DIAL_DEAD_ZONE && (turned - *degrees).abs() > f32::EPSILON { + *degrees = turned; + // Later frames of one drag share its undo step + edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); + } + } + if response.drag_stopped() || response.clicked() { + ui.data_mut(|data| data.remove_temp::(response.id)); + } + let shown = *degrees; + response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(shown), label)); + + let painter = ui.painter(); + let radius = DIAL_SIZE * 0.5 - 1.0; + painter.circle(rect.center(), radius, tokens.field, egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.button_border)); + let (sin, cos) = degrees.to_radians().sin_cos(); + let tip = rect.center() + egui::vec2(cos, -sin) * radius; + painter.line_segment([rect.center(), tip], egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.accent)); + painter.circle_filled(rect.center(), DIAL_HUB_RADIUS, tokens.text); + edit +} + /// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { let shown = detail.cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 126f7be5..809fc048 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -19,7 +19,7 @@ pub fn dnd_release(resp: &Response) -> Option, decimals: usize) -> Response { - slider_inner(ui, label, value, range, decimals).0 + slider_inner(ui, label, value, range, decimals, "").0 } /// For an editor `id` drawn every frame: `Some(merge)` when it `changed`, merge true for a press's later changes (one undo step per drag; typing never merges) @@ -57,7 +57,12 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { /// true for the later changes of one drag, so the edit that applies them (with the command's /// `merge` param) continues the drag's first undo step. pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> Option { - slider_inner(ui, label, value, range, decimals).1 + slider_inner(ui, label, value, range, decimals, "").1 +} + +/// [`slider_edit`] showing `suffix` after the value (a unit such as °), which a typed value may leave out +pub fn slider_edit_with_suffix(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> Option { + slider_inner(ui, label, value, range, decimals, suffix).1 } /// Least width of a slider's value field, wide enough for a short number @@ -75,12 +80,24 @@ const SLIDER_KNOB_RADIUS: f32 = 4.5; /// The row above a slider's track, `label` and `value` as a field to type in: the field's id, and `Some(false)` on the frame a typed value replaces `value` pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (egui::Id, Option) { + suffixed_value_header(ui, label, value, range, decimals, "") +} + +/// [`value_header`] showing `suffix` after the value, which a typed value may leave out +fn suffixed_value_header( + ui: &mut Ui, + label: &str, + value: &mut f32, + range: std::ops::RangeInclusive, + decimals: usize, + suffix: &str, +) -> (egui::Id, Option) { let tokens = Tokens::get(ui.ctx()); let (minimum, maximum) = (*range.start(), *range.end()); let font = egui::TextStyle::Body.resolve(ui.style()); let value_width = [minimum, maximum] .into_iter() - .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) + .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}{suffix}"), font.clone(), tokens.text).size().x) .fold(SLIDER_VALUE_MIN_WIDTH, f32::max); let mut edit = None; let field = ui @@ -88,7 +105,7 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std ui.label(RichText::new(label).color(tokens.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = ui.next_auto_id(); - let shown = format!("{value:.decimals$}"); + let shown = format!("{value:.decimals$}{suffix}"); // Keep unfinished input while the document value is re-read each frame let mut text = ui.data(|data| data.get_temp::(id)).unwrap_or_else(|| shown.clone()); @@ -111,7 +128,7 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std if response.lost_focus() && !escape && text != shown - && let Ok(parsed) = text.trim().parse::() + && let Ok(parsed) = text.trim().strip_suffix(suffix).unwrap_or(text.trim()).trim_end().parse::() && parsed.is_finite() && parsed.clamp(minimum, maximum) != *value { @@ -127,10 +144,10 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std (field, edit) } -fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { +fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> (Response, Option) { let (minimum, maximum) = (*range.start(), *range.end()); let width = ui.available_width(); - let (field, mut edit) = value_header(ui, label, value, range, decimals); + let (field, mut edit) = suffixed_value_header(ui, label, value, range, decimals, suffix); let (rect, mut response) = ui.allocate_exact_size(vec2(width, SLIDER_TRACK_HEIGHT), Sense::click_and_drag()); if response.is_pointer_button_down_on() { ui.data_mut(|data| data.remove_temp::(field)); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index edf21484..6d49c460 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -153,6 +153,11 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { ("ambientOcclusion", &["Blur", "Balance", "Global contrast"][..], &["Brightness", "Blending mode", "Level"][..]), ("position", &["Balance", "Brightness", "Right to left", "Front to back"][..], &["Blur", "Level", "Sharp"][..]), ("worldSpaceNormals", &["Blur", "Balance", "Brightness", "Top to bottom"][..], &["Level", "Softness"][..]), + ( + "direction", + &["Horizontal angle", "Vertical angle", "Highlight glossiness", "Highlight level", "Light attenuation"][..], + &["Global blur", "Level"][..], + ), ]; for (kind, shown, hidden) in rows { let (harness, _) = harness_with(false, json!({"generator": kind})); @@ -166,6 +171,8 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); assert_eq!(count(&harness, "Blending mode"), 3); + let (harness, _) = harness_with(false, json!({"generator": "direction"})); + assert_eq!(count(&harness, "Angle"), 2, "an Angle slider beside each dial"); let (harness, _) = harness_with(false, json!({"generator": "position", "level": 0.4})); assert!(count(&harness, "Level") > 0 && count(&harness, "Balance") > 0, "the earlier model keeps its level beside the section at its defaults"); } @@ -202,6 +209,31 @@ fn a_section_control_moves_an_earlier_generator_onto_the_section_controls() { assert_eq!(count(&harness, "Level"), 0, "the earlier rows are gone"); } +#[test] +fn the_light_dial_turns_towards_the_pointer() { + let (mut harness, effect) = harness_with(false, json!({"generator": "direction"})); + harness.get_by_role_and_label(Role::Slider, "Horizontal angle").scroll_to_me(); + harness.run_steps(3); + let rect = harness.get_by_role_and_label(Role::Slider, "Horizontal angle").rect(); + let left = egui::pos2(rect.left() + 2.0, rect.center().y); + harness.drag_at(left); + harness.run_steps(2); + harness.drop_at(left); + harness.run_steps(3); + let horizontal = generator(&harness, effect).light.unwrap().horizontal; + assert!((horizontal - 180.0).abs() < 1.0, "a click left of the centre points the needle left: {horizontal}"); +} + +#[test] +fn restore_defaults_puts_a_light_back_on_its_defaults() { + let (mut harness, effect) = harness_with(false, json!({"generator": "direction", "lightHorizontal": 10.0, "highlightLevel": 0.7, "invert": true})); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Direction)); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -252,7 +284,7 @@ fn wear_panel_snapshots() { fn section_panel_snapshots() { let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); - for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals", "direction"] { let (mut harness, _) = harness_with(true, json!({"generator": kind})); harness.run_steps(12); harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap();