diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 25a23d10..124ece1b 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use std::sync::Arc; use rayon::prelude::*; -use texturecraft_core::{UvCheckerParameters, UvRandomColorParameters, gradient}; +use texturecraft_core::{UvCheckerParameters, UvRandomColorParameters}; use texturecraft_geom::{NO_TRI, TrianglePartition}; use texturecraft_texel::linear_to_srgb; use texturecraft_texel::noise::cell_hash; @@ -18,7 +18,9 @@ static CACHE: FieldCache = FieldCache::new(); /// UV Random Color at every working texel of `inp`: one value per UV island (0 outside the islands) pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, seed: u32) -> Arc> { let mut settings = vec![seed, u32::from(random.custom_gradient)]; - settings.extend(random.gradient.iter().flat_map(|color| color.map(f32::to_bits))); + settings.push(random.used_colors().len() as u32); + settings.extend(random.used_colors().iter().flat_map(|color| color.map(f32::to_bits))); + settings.extend(random.positions.iter().map(|position| position.to_bits())); CACHE.get_or_build(inp, &[], settings, |_| { let island_values = island_values(inp, |island| random_gray(random, seed, island)); let gbuf = inp.gbuf; @@ -43,7 +45,7 @@ fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> HashMap f32 { let island = island as i32; let color = if random.custom_gradient { - gradient(&random.gradient, cell_hash(island, 0, 0, seed)).unwrap_or([0.0; 3]) + random.at(cell_hash(island, 0, 0, seed)).unwrap_or([0.0; 3]) } else { std::array::from_fn(|channel| cell_hash(island, channel as i32 + 1, 0, seed)) }; diff --git a/crates/compose/tests/generator_uv_random_color.rs b/crates/compose/tests/generator_uv_random_color.rs index 529bc354..a546c627 100644 --- a/crates/compose/tests/generator_uv_random_color.rs +++ b/crates/compose/tests/generator_uv_random_color.rs @@ -97,6 +97,25 @@ fn a_one_color_gradient_colors_every_island_alike() { let mut fixture = fixture(); let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); - let values = mask(&mut fixture, UvRandomColorParameters { custom_gradient: true, gradient: vec![[0.1, 0.2, 0.3]] }, 0, &at); + let values = + mask(&mut fixture, UvRandomColorParameters { custom_gradient: true, gradient: vec![[0.1, 0.2, 0.3]], ..UvRandomColorParameters::default() }, 0, &at); assert!(values.iter().all(|value| (value - 0.2).abs() < 1e-5), "the mean of its channels"); } + +#[test] +fn moving_a_gradient_stop_brightens_the_islands() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + let black_to_white = |positions: Vec| UvRandomColorParameters { + custom_gradient: true, + gradient: vec![[0.0; 3], [1.0; 3]], + positions, + ..UvRandomColorParameters::default() + }; + + let even = mask(&mut fixture, black_to_white(Vec::new()), 0, &at); + let white_early = mask(&mut fixture, black_to_white(vec![0.0, 0.2]), 0, &at); + let mean = |values: &[f32]| values.iter().sum::() / values.len().max(1) as f32; + assert!(mean(&white_early) > mean(&even), "white reached sooner along the gradient: brighter islands"); + assert!(white_early.iter().zip(&even).all(|(early, even)| early >= even), "no island darker"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ccbf8ed9..bc82c7b7 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1044,19 +1044,9 @@ impl GeneratorKind { } } - /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the newest kinds wait for their panels) + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks) pub fn in_picker(self) -> bool { - !matches!( - self, - GeneratorKind::ThinAreas - | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor - | GeneratorKind::UvChecker - ) + self != GeneratorKind::ThinAreas } /// Whether the kind's result depends on its seed diff --git a/crates/core/src/layer/uv_random_color_parameters.rs b/crates/core/src/layer/uv_random_color_parameters.rs index 156a1be0..07b73e13 100644 --- a/crates/core/src/layer/uv_random_color_parameters.rs +++ b/crates/core/src/layer/uv_random_color_parameters.rs @@ -6,24 +6,74 @@ use serde::{Deserialize, Serialize}; pub struct UvRandomColorParameters { /// Pick each island's color along [`UvRandomColorParameters::gradient`] instead of at random pub custom_gradient: bool, - /// The gradient's colors, evenly spaced (linear RGB, [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] at most) + /// The gradient's colors (linear RGB, [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] at most) pub gradient: Vec<[f32; 3]>, + /// Each color's place on the gradient (0..1); colors past the end are evenly spaced (projects saved before have none) + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub positions: Vec, + /// How many of the colors the gradient uses (all of them where None): the rest are kept for when the count grows again + #[serde(default, skip_serializing_if = "Option::is_none")] + pub quantity: Option, } impl UvRandomColorParameters { pub const MAX_GRADIENT_COLORS: usize = 16; - /// Every color brought into 0..1 (non-finite components black), at most [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] of them, and at least one + /// The fewest colors the gradient's count goes down to + pub const MIN_QUANTITY: u8 = 2; + + /// Every color brought into 0..1 (non-finite components black), at most [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] of them, and at least one; places into 0..1, one per color at most pub fn clamped(self) -> UvRandomColorParameters { let unit = |value: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; let gradient: Vec<[f32; 3]> = self.gradient.into_iter().take(UvRandomColorParameters::MAX_GRADIENT_COLORS).map(|color| color.map(unit)).collect(); - UvRandomColorParameters { gradient: if gradient.is_empty() { UvRandomColorParameters::default().gradient } else { gradient }, ..self } + let gradient = if gradient.is_empty() { UvRandomColorParameters::default().gradient } else { gradient }; + let positions = self.positions.into_iter().take(gradient.len()).map(unit).collect(); + let quantity = self.quantity.map(|count| count.clamp(UvRandomColorParameters::MIN_QUANTITY, UvRandomColorParameters::MAX_GRADIENT_COLORS as u8)); + UvRandomColorParameters { gradient, positions, quantity, ..self } + } + + /// The colors the gradient uses: the first [`UvRandomColorParameters::quantity`] of them (all of them where it has none) + pub fn used_colors(&self) -> &[[f32; 3]] { + let used = self.quantity.map_or(self.gradient.len(), usize::from).min(self.gradient.len()); + self.gradient.get(..used).unwrap_or(&self.gradient) + } + + /// Each used color's place on the gradient, evenly spaced where it has none + pub fn used_positions(&self) -> Vec { + let used = self.used_colors().len(); + let last = used.saturating_sub(1).max(1) as f32; + (0..used).map(|index| self.positions.get(index).copied().unwrap_or(index as f32 / last)).collect() + } + + /// The gradient's color at `t` (linear blend) + pub fn at(&self, t: f32) -> Option<[f32; 3]> { + let colors = self.used_colors(); + + // An evenly spaced gradient (projects saved before) takes the path it took then, so it renders bit for bit as before + if self.positions.is_empty() { super::gradient(colors, t) } else { crate::gradient_input::ramp(colors, &self.positions, true, t) } + } + + /// Use the first `wanted` colors: an evenly spaced gradient keeps its places from now on, and each added color starts at 1 as the gradient's color there + pub fn set_quantity(&mut self, wanted: u8) { + let wanted = wanted.clamp(UvRandomColorParameters::MIN_QUANTITY, UvRandomColorParameters::MAX_GRADIENT_COLORS as u8); + // The used colors without a place keep the even place the gradient gave them; hidden colors keep theirs + let even = self.used_positions(); + let placed = self.positions.len(); + self.positions.extend(even.into_iter().skip(placed)); + let fill = self.at(1.0).unwrap_or([1.0; 3]); + let wanted_len = usize::from(wanted); + if self.gradient.len() < wanted_len { + self.gradient.resize(wanted_len, fill); + } + if self.positions.len() < wanted_len { + self.positions.resize(wanted_len, 1.0); + } + self.quantity = Some(wanted); } } impl Default for UvRandomColorParameters { - /// Random colors; the gradient black to white fn default() -> UvRandomColorParameters { - UvRandomColorParameters { custom_gradient: false, gradient: vec![[0.0; 3], [1.0; 3]] } + UvRandomColorParameters { custom_gradient: false, gradient: vec![[0.0; 3], [1.0; 3]], positions: Vec::new(), quantity: None } } } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index e34e9327..49cead62 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -117,6 +117,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); + v.extend(crate::generator_pick::specs()); v.extend(crate::mask_export::specs()); v.extend(crate::add_mask_cmds::specs()); v.extend(crate::color_selection_cmds::specs()); diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 7b620be0..172a1cf2 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -23,7 +23,7 @@ pub const DRIPPING_RUST_KEYS: [&str; 7] = ["rustSpreading", "rustContrast", "spreadingSmoothness", "dripsIntensity", "dripsSmoothness", "dripsSamples", "dripsAxis"]; /// The UV Random Color controls (it also takes the seed) -pub const UV_RANDOM_COLOR_KEYS: [&str; 2] = ["colorSourceMode", "gradientColors"]; +pub const UV_RANDOM_COLOR_KEYS: [&str; 4] = ["colorSourceMode", "gradientColors", "gradientPositions", "gradientQuantity"]; /// The UV Checker controls (it also takes the seed) pub const UV_CHECKER_KEYS: [&str; 6] = ["checkerColorMode", "checkerColor", "checkerGridTile", "checkerGridOpacity", "uvBordersColor", "uvBordersWidth"]; @@ -185,6 +185,20 @@ fn uv_random_color_from(command: &str, params: &Value, generator: &mut Generator let invalid = || bad(command, "`gradientColors` takes 1 to 16 colors, each [r, g, b] or \"#rrggbb\""); let items = value.as_array().filter(|items| (1..=UvRandomColorParameters::MAX_GRADIENT_COLORS).contains(&items.len())).ok_or_else(invalid)?; random.gradient = items.iter().map(|item| color_of(item).ok_or_else(invalid)).collect::>()?; + + // The colors given are the whole gradient: a count after them hides some again + random.quantity = None; + } + if let Some(value) = params.get("gradientPositions") { + let invalid = || bad(command, "`gradientPositions` must be numbers in 0..1, at most one per color"); + let places = value.as_array().filter(|places| places.len() <= random.gradient.len()).ok_or_else(invalid)?; + random.positions = places.iter().map(|place| place.as_f64().map(|place| place as f32).ok_or_else(invalid)).collect::>()?; + } + if params.get("gradientQuantity").is_some() { + let range = UvRandomColorParameters::MIN_QUANTITY..=UvRandomColorParameters::MAX_GRADIENT_COLORS as u8; + let wanted = u64p(params, "gradientQuantity").and_then(|count| u8::try_from(count).ok()).filter(|count| range.contains(count)); + let wanted = wanted.ok_or_else(|| bad(command, format!("`gradientQuantity` must be a whole number from {} to {}", range.start(), range.end())))?; + random.set_quantity(wanted); } generator.controls = Some(Box::new(KindControls::UvRandomColor(random.clamped()))); Ok(()) diff --git a/crates/engine/src/generator_pick.rs b/crates/engine/src/generator_pick.rs new file mode 100644 index 00000000..b6195451 --- /dev/null +++ b/crates/engine/src/generator_pick.rs @@ -0,0 +1,66 @@ +//! `effect.generator.pickPoint`: a 3D Distance or 3D Linear Gradient point set from where the mesh is under a viewport point + +use serde_json::{Value, json}; +use texturecraft_core::{EffectKind, GeneratorKind, LayerId}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::commands::{CommandSpec, bad, f32p, has_layer, strp, u64p}; +use crate::tool_cmds::viewport_of; +use crate::{Result, Session, cmd}; + +const CMD: &str = "effect.generator.pickPoint"; + +/// The least extent the mesh's bounds count with, so a flat mesh still places a point (the compositor's own floor) +const MIN_BOUNDS_EXTENT: f32 = 1e-6; + +pub fn specs() -> Vec { + vec![cmd!( + "effect.generator.pickPoint", + "Pick generator point on mesh", + [], + None, + "{effect, point?: distance|start|end (default distance on 3dDistance, start on 3dLinearGradient), x?, y?: viewport pixels (default its centre), viewport?: [w, h]} sets a 3D Distance or 3D Linear Gradient point to the mesh under that pixel, across the mesh's bounds as the generator reads it; returns the point", + has_layer, + pick_point + )] +} + +fn pick_point(session: &mut Session, params: &Value) -> Result { + let effect = u64p(params, "effect").ok_or_else(|| bad(CMD, "`effect` is required"))?; + let kind = match session.doc.project.effect(LayerId(effect)).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Generator(generator)) => generator.kind, + Some(_) => return Err(bad(CMD, format!("effect {effect} is not a generator"))), + None => return Err(bad(CMD, format!("no effect {effect}"))), + }; + let point = strp(params, "point").map(str::to_ascii_lowercase); + let key = match (kind, point.as_deref()) { + (GeneratorKind::ThreeDDistance, None | Some("distance")) => "distance", + (GeneratorKind::ThreeDLinearGradient, None | Some("start")) => "gradientStart", + (GeneratorKind::ThreeDLinearGradient, Some("end")) => "gradientEnd", + (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient, Some(other)) => { + return Err(bad(CMD, format!("{} has no point `{other}`", kind.label()))); + } + _ => return Err(bad(CMD, format!("{} has no point to pick: only 3D Distance and 3D Linear Gradient have one", kind.label()))), + }; + + let viewport = viewport_of(session, params); + let screen = match (f32p(params, "x"), f32p(params, "y")) { + (Some(x), Some(y)) => Vec2::new(x, y), + _ => viewport * 0.5, + }; + let hit = session.pick(screen, viewport).ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?; + let picked = across_bounds(hit.pos, session.mesh.bounds()).to_array().map(|coordinate| coordinate.clamp(0.0, 1.0)); + + let edit = match key { + "distance" => json!({"effect": effect, "distanceX": picked[0], "distanceY": picked[1], "distanceZ": picked[2]}), + _ => json!({"effect": effect, key: picked}), + }; + crate::mask_cmds::set(session, &edit)?; + Ok(json!({"effect": effect, "point": picked})) +} + +/// `position` across `bounds` as the 3D generators read the mesh: scaled evenly by the longest side, centred on 0.5 +pub fn across_bounds(position: Vec3, (low, high): (Vec3, Vec3)) -> Vec3 { + let longest = (high - low).max_element().max(MIN_BOUNDS_EXTENT); + (position - (low + high) * 0.5) / longest + Vec3::splat(0.5) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 336ba602..82d395ce 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod filter_about; pub mod filter_lib; pub mod folder_cmds; mod frame_target; +pub mod generator_pick; pub mod id_mask_view; pub mod inspect; pub mod instance_cmds; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 77341832..e7ef1e7a 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor|uvChecker, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (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), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...] (uvRandomColor, which also takes seed), checkerColorMode?: uniform|random, checkerColor?, checkerGridTile?: 1..24, checkerGridOpacity?, uvBordersColor?, uvBordersWidth? (uvChecker, which also takes seed), 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 (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor|uvChecker, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (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), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...], gradientPositions?: [0..1 per color], gradientQuantity?: 2..16 (uvRandomColor, which also takes seed), checkerColorMode?: uniform|random, checkerColor?, checkerGridTile?: 1..24, checkerGridOpacity?, uvBordersColor?, uvBordersWidth? (uvChecker, which also takes seed), 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 (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), @@ -1016,7 +1016,7 @@ fn histogram(s: &mut Session, p: &Value) -> Result { } /// Edit visibility, blending, name, effect parameters, or a filter's type -fn set(session: &mut Session, params: &Value) -> Result { +pub(crate) fn set(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.set"; let effect = effect_id(session, params, CMD)?; let blend = blend_param(CMD, params, "blend")?; diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index 4d5d3c70..6d03ef36 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -4,7 +4,10 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::json; -use texturecraft_core::{BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, LayerId, MaskBackground}; +use texturecraft_core::{ + BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, KindControls, LayerId, MaskBackground, Procedural, + ProceduralKind, Source, +}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::primitives; use texturecraft_texel::TILE; @@ -86,7 +89,13 @@ impl OrbPreview { /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, with None outside the shape /// Returns None for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { - self.generator_of(Generator::new(kind), size) + let mut generator = Generator::new(kind); + + // Grayscale Conversion grays the image it is given: its picture grays clouds, as it starts with none + if let Some(KindControls::Grayscale(grayscale)) = generator.controls.as_deref_mut() { + grayscale.source = Some(Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); + } + self.generator_of(generator, size) } /// [`Self::generator`] for `generator` as given (a Curvature generator with one detail size alone) diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index c4f7b3ed..735bef45 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -144,12 +144,46 @@ fn uv_random_color_takes_its_mode_and_gradient() { let params = json!({"generator": "UV Random Color", "colorSourceMode": "customGradient", "gradientColors": [[2.0, 0.5, 0.0], "#000000"]}); let effect = add(&mut session, params); - let expected = UvRandomColorParameters { custom_gradient: true, gradient: vec![[1.0, 0.5, 0.0], [0.0; 3]] }; + let expected = UvRandomColorParameters { custom_gradient: true, gradient: vec![[1.0, 0.5, 0.0], [0.0; 3]], ..UvRandomColorParameters::default() }; assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvRandomColor(expected)), "colors stay within 0..1"); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": []})).is_err()); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "colorSourceMode": "fancy"})).is_err()); } +#[test] +fn uv_random_color_gradient_takes_places_and_a_count() { + let mut session = session(); + let params = json!({"generator": "uvRandomColor", "colorSourceMode": "customGradient", "gradientColors": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]}); + let effect = add(&mut session, params); + let random = |session: &Session| match generator(session, effect).kind_controls() { + Some(KindControls::UvRandomColor(random)) => random, + other => panic!("not UV Random Color controls: {other:?}"), + }; + + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientPositions": [0.25, 0.75]})).unwrap(); + assert_eq!(random(&session).at(0.5), Some([0.5; 3]), "halfway between the two places"); + assert_eq!(random(&session).at(0.1), Some([0.0; 3]), "before the first place: the first color"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 3})).unwrap(); + assert_eq!(random(&session).used_colors().len(), 3); + assert_eq!(random(&session).used_positions(), vec![0.25, 0.75, 1.0], "an added color starts at the end"); + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [1.0, 0.0, 0.0]]})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 2})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 3})).unwrap(); + assert_eq!(random(&session).used_colors()[2], [1.0, 0.0, 0.0], "a hidden color comes back as it was"); + + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 17})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientPositions": [0.0, 0.1, 0.2, 0.3]})).is_err()); +} + +#[test] +fn uv_random_color_saved_without_places_loads_evenly_spaced() { + let saved: UvRandomColorParameters = + serde_json::from_value(json!({"customGradient": true, "gradient": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]})).unwrap(); + assert_eq!(saved.used_positions(), vec![0.0, 0.5, 1.0]); + assert_eq!(saved.at(0.5), Some([1.0; 3])); +} + #[test] fn uv_checker_takes_its_controls() { let mut session = session(); @@ -162,3 +196,26 @@ fn uv_checker_takes_its_controls() { assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvChecker(expected)), "the grid tile stops at 24"); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "checkerColorMode": "plaid"})).is_err()); } + +#[test] +fn picking_on_the_mesh_sets_the_point() { + let mut session = session(); + let distance = add(&mut session, json!({"generator": "3dDistance", "distanceX": 0.0, "distanceY": 0.0, "distanceZ": 0.0})); + let picked = execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance})).unwrap(); + let point = generator(&session, distance).distance_controls().unwrap().point; + assert_eq!(json!(point), picked["point"], "the point is where the mesh is under the viewport's centre"); + assert_ne!(point, [0.0; 3]); + + let gradient = add(&mut session, json!({"generator": "3dLinearGradient"})); + let before = generator(&session, gradient).linear_gradient_controls().unwrap(); + execute(&mut session, "effect.generator.pickPoint", &json!({"effect": gradient, "point": "end"})).unwrap(); + let after = generator(&session, gradient).linear_gradient_controls().unwrap(); + assert_eq!(after.start, before.start, "picking the end leaves the start"); + assert_eq!(json!(after.end), picked["point"], "the same pixel gives the same point"); + + let missed = json!({"effect": distance, "x": 0.0, "y": 0.0, "viewport": [512, 512]}); + assert!(execute(&mut session, "effect.generator.pickPoint", &missed).is_err(), "a corner off the mesh picks nothing"); + assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance, "point": "end"})).is_err()); + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": curvature})).is_err()); +} diff --git a/crates/ui-egui/src/fill_symmetry_panel.rs b/crates/ui-egui/src/fill_symmetry_panel.rs index b306c05e..a2796f79 100644 --- a/crates/ui-egui/src/fill_symmetry_panel.rs +++ b/crates/ui-egui/src/fill_symmetry_panel.rs @@ -91,7 +91,15 @@ fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetr let mut sliders = [ StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "", dial: false }, - StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°", dial: false }, + StackSlider { + label: tr("Angle span"), + value: &mut span_value, + range: FillSymmetry::SPANS, + typed: FillSymmetry::SPANS, + decimals: 0, + suffix: "°", + dial: false, + }, ]; let [count_edit, span_edit] = sheet.picture_sliders(&picture, &mut sliders); diff --git a/crates/ui-egui/src/generator_input_card.rs b/crates/ui-egui/src/generator_input_card.rs index 2cc9c41f..b63012ce 100644 --- a/crates/ui-egui/src/generator_input_card.rs +++ b/crates/ui-egui/src/generator_input_card.rs @@ -18,7 +18,14 @@ use crate::theme::Tokens; const GLYPH_SIZE: f32 = 12.0; /// The slot of input `slot` of generator effect `id` on `layer`, holding `source`: a card of its own, or a row of the card open now when `in_card` -pub(crate) fn input_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), slot: GeneratorInputSlot, source: Option<&Source>, in_card: bool) { +pub(crate) fn input_card( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + (layer, id): (LayerId, u64), + slot: GeneratorInputSlot, + source: Option<&Source>, + in_card: bool, +) { let tokens = Tokens::get(sheet.ui.ctx()); let input = slot.id(); let line = match (source, slot) { diff --git a/crates/ui-egui/src/generator_input_slot.rs b/crates/ui-egui/src/generator_input_slot.rs index 0e145a6f..4027cb4f 100644 --- a/crates/ui-egui/src/generator_input_slot.rs +++ b/crates/ui-egui/src/generator_input_slot.rs @@ -1,6 +1,6 @@ //! What one image input of a generator replaces or holds -use texturecraft_engine::core::{BakedMap, Generator, Source}; +use texturecraft_engine::core::{BakedMap, Generator, KindControls, Source}; use crate::i18n::{baked_map_label, tr}; @@ -12,6 +12,9 @@ pub(crate) enum GeneratorInputSlot { Grunge, MicroHeight, MicroNormal, + + /// Grayscale Conversion's image + Image, } impl GeneratorInputSlot { @@ -23,6 +26,7 @@ impl GeneratorInputSlot { GeneratorInputSlot::Grunge => "grunge", GeneratorInputSlot::MicroHeight => texturecraft_engine::micro_params::MICRO_HEIGHT_INPUT, GeneratorInputSlot::MicroNormal => texturecraft_engine::micro_params::MICRO_NORMAL_INPUT, + GeneratorInputSlot::Image => "image", } } @@ -33,6 +37,7 @@ impl GeneratorInputSlot { GeneratorInputSlot::Grunge => tr("Custom Grunge"), GeneratorInputSlot::MicroHeight => tr("Micro Height"), GeneratorInputSlot::MicroNormal => tr("Micro Normal"), + GeneratorInputSlot::Image => tr("Input Image"), } } @@ -41,7 +46,7 @@ impl GeneratorInputSlot { match self { GeneratorInputSlot::Map(map) => map.neutral()[0], GeneratorInputSlot::MicroHeight | GeneratorInputSlot::MicroNormal => 0.5, - GeneratorInputSlot::Texture | GeneratorInputSlot::Grunge => 0.0, + GeneratorInputSlot::Texture | GeneratorInputSlot::Grunge | GeneratorInputSlot::Image => 0.0, } } @@ -58,6 +63,10 @@ impl GeneratorInputSlot { GeneratorInputSlot::Grunge => generator.grunge.as_ref(), GeneratorInputSlot::MicroHeight => generator.micro.as_ref().and_then(|micro| micro.height_source.as_ref()), GeneratorInputSlot::MicroNormal => generator.micro.as_ref().and_then(|micro| micro.normal_source.as_ref()), + GeneratorInputSlot::Image => match generator.controls.as_deref() { + Some(KindControls::Grayscale(grayscale)) => grayscale.source.as_ref(), + _ => None, + }, } } } diff --git a/crates/ui-egui/src/generator_kind_rows.rs b/crates/ui-egui/src/generator_kind_rows.rs new file mode 100644 index 00000000..8b3e8960 --- /dev/null +++ b/crates/ui-egui/src/generator_kind_rows.rs @@ -0,0 +1,289 @@ +//! The Parameters rows of the kinds with only their own controls: 3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion, Dripping Rust, UV Random Color and UV Checker + +use egui::{Painter, Rect}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, Generator, GeneratorGrayscale, GrayscaleConversionParameters, KindControls, + LinearGradientParameters, UvCheckerParameters, UvRandomColorParameters, +}; + +use crate::TextureCraftApp; +use crate::fill_material_panel::take_color_pick; +use crate::generator_params::{DRIPS_AXES, kind_params, merged}; +use crate::generator_point_pick::PointPick; +use crate::i18n::{tr, trf}; +use crate::property_sheet::{NumberField, PropertySheet, StackSlider}; +use crate::theme::AXIS_COLORS; + +/// A 0..1 setting in the stack beside the preview +fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { + StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } +} + +/// A whole-number setting in the stack beside the preview +fn stacked_whole<'a>(label: &'a str, value: &'a mut f32, range: std::ops::RangeInclusive) -> StackSlider<'a> { + StackSlider { label, value, range: range.clone(), typed: range, decimals: 0, suffix: "", dial: false } +} + +/// The first edit of a stack beside the preview +fn first_edit(edits: [Option; N]) -> Option { + edits.into_iter().flatten().next() +} + +/// The rows of generator effect `id`, whose own controls are `controls`; `picture` draws the preview +pub(crate) fn kind_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + generator: &Generator, + controls: KindControls, + picture: &dyn Fn(&Painter, Rect), +) { + if generator.kind.includes_randomness() { + let mut seed = generator.seed; + if sheet.seed(tr("Seed"), &mut seed) { + app.run("effect.set", json!({"effect": id, "seed": seed})); + } + } + + // UV Random Color and UV Checker make colors: Invert is the reference's on the grayscale kinds only + if !matches!(controls, KindControls::UvRandomColor(_) | KindControls::UvChecker(_)) { + let mut invert = generator.invert; + if sheet.toggle(tr("Invert"), &mut invert) { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + } + + let edit = match controls { + KindControls::Distance(distance) => distance_rows(sheet, id, distance, picture), + KindControls::LinearGradient(gradient) => linear_gradient_rows(sheet, id, gradient, picture), + KindControls::BorderDistance(border) => border_rows(sheet, border, picture), + KindControls::Grayscale(grayscale) => grayscale_rows(sheet, grayscale, picture), + KindControls::DrippingRust(rust) => rust_rows(sheet, rust, picture), + KindControls::UvRandomColor(random) => random_color_rows(app, sheet, id, random), + KindControls::UvChecker(checker) => checker_rows(app, sheet, checker, picture), + }; + if let Some((merge, edited)) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), edited)); + } +} + +/// An edit: whether it continues the last undo step, and the controls to send +type KindEdit = Option<(bool, Value)>; + +/// The controls `controls` to send when `merge` says one was edited +fn sent(merge: Option, controls: KindControls) -> KindEdit { + merge.map(|merge| (merge, kind_params(&controls))) +} + +/// A point's X, Y and Z (across the mesh's evenly scaled bounds) with its pick-on-mesh button; returns its edit +fn point_row(sheet: &mut PropertySheet<'_>, label: &str, point: &mut [f32; 3], pick: PointPick) -> Option { + let mut fields: Vec = ["X", "Y", "Z"] + .into_iter() + .zip(AXIS_COLORS) + .zip(point.iter()) + .map(|((tag, color), value)| NumberField { tag, tag_color: Some(color), value: *value, speed: POINT_DRAG_SPEED, decimals: 2, suffix: "" }) + .collect(); + let ctx = sheet.ui.ctx().clone(); + let armed = crate::generator_point_pick::armed(&ctx) == Some(pick); + let (edited, clicked) = sheet.point_fields(label, &mut fields, armed); + if clicked { + crate::generator_point_pick::toggle(&ctx, pick); + } + let (index, merge) = edited?; + let (field, coordinate) = (fields.get(index)?, point.get_mut(index)?); + *coordinate = field.value.clamp(0.0, 1.0); + Some(merge) +} + +/// Change of a point's coordinate per pixel dragged +const POINT_DRAG_SPEED: f32 = 0.005; + +/// 3D Distance: Radius, Offset and Contrast beside the preview, then its point +fn distance_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: DistanceParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let radius = StackSlider { + label: tr("Radius"), + value: &mut edited.radius, + range: DistanceParameters::RADIUS_RANGE, + typed: DistanceParameters::RADIUS_RANGE, + decimals: 2, + suffix: "", + dial: false, + }; + let mut stack = [radius, stacked(tr("Offset"), &mut edited.offset), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(point_row(sheet, tr("3D Position"), &mut edited.point, PointPick { effect: id, point: "distance" })); + sent(edit, KindControls::Distance(edited)) +} + +/// 3D Linear Gradient: Balance and Contrast beside the preview, then its start and end +fn linear_gradient_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: LinearGradientParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut stack = [stacked(tr("Balance"), &mut edited.balance), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(point_row(sheet, tr("3D Position Start"), &mut edited.start, PointPick { effect: id, point: "start" })); + edit = edit.or(point_row(sheet, tr("3D Position End"), &mut edited.end, PointPick { effect: id, point: "end" })); + sent(edit, KindControls::LinearGradient(edited)) +} + +/// UV Border Distance: Distance, Smoothness and Balance beside the preview, then Contrast +fn border_rows(sheet: &mut PropertySheet<'_>, shown: BorderDistanceParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut stack = + [stacked(tr("Distance"), &mut edited.distance), stacked(tr("Smoothness"), &mut edited.smoothness), stacked(tr("Balance"), &mut edited.balance)]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(sheet.slider(tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); + sent(edit, KindControls::BorderDistance(edited)) +} + +/// Grayscale Conversion: its type, Balance, Contrast and Tile beside the preview, then Rotation and Safe Rotation (its image is in Image inputs) +fn grayscale_rows(sheet: &mut PropertySheet<'_>, shown: GrayscaleConversionParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut edit = None; + let name = |grayscale: GeneratorGrayscale| tr(grayscale.label()).to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Grayscale Type"), edited.grayscale, &GeneratorGrayscale::ALL, name, None) { + edited.grayscale = picked; + edit = Some(false); + } + let mut stack = [ + stacked(tr("Balance"), &mut edited.balance), + stacked(tr("Contrast"), &mut edited.contrast), + stacked_whole(tr("Tile"), &mut edited.tile, GrayscaleConversionParameters::TILE_RANGE), + ]; + edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); + edited.tile = edited.tile.round(); + edit = edit.or(sheet.angle(tr("Rotation"), &mut edited.rotation, 0.0..=360.0)); + if sheet.toggle(tr("Safe Rotation"), &mut edited.safe_rotation) { + edit = Some(false); + } + sent(edit, KindControls::Grayscale(edited)) +} + +/// Dripping Rust: Rust Spreading, Rust Contrast and Spreading Smoothness beside the preview, then the drips and the axis they run along +fn rust_rows(sheet: &mut PropertySheet<'_>, shown: DrippingRustParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut stack = [ + stacked(tr("Rust Spreading"), &mut edited.spreading), + stacked(tr("Rust Contrast"), &mut edited.contrast), + stacked(tr("Spreading Smoothness"), &mut edited.spreading_smoothness), + ]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(sheet.slider(tr("Drips Intensity"), &mut edited.drips_intensity, 0.0..=1.0, 2)); + edit = edit.or(sheet.slider(tr("Drips Smoothness"), &mut edited.drips_smoothness, 0.0..=1.0, 2)); + let mut samples = edited.drips_samples as f32; + if let Some(merge) = sheet.slider(tr("Drips Samples Amount"), &mut samples, 0.0..=DrippingRustParameters::MAX_SAMPLES as f32, 0) { + edited.drips_samples = samples.round() as u32; + edit = edit.or(Some(merge)); + } + let axes = [tr("X - Red Channel"), tr("Y - Green Channel"), tr("Z - Blue Channel")]; + let name = |axis: u8| axes.get(usize::from(axis)).copied().unwrap_or_default().to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Position Axis"), edited.axis, &[0, 1, 2], name, None) { + edited.axis = picked; + edit = Some(false); + } + debug_assert_eq!(DRIPS_AXES.len(), axes.len()); + sent(edit, KindControls::DrippingRust(edited)) +} + +/// UV Random Color: where its colors come from; a custom gradient shows the gradient editor (as the Gradient filter's) +fn random_color_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, shown: UvRandomColorParameters) -> KindEdit { + let mut edited = shown.clone(); + let mode = usize::from(edited.custom_gradient); + if let Some(picked) = sheet.switch(tr("Color Source Mode"), &[tr("Random"), tr("Custom Gradient")], mode) { + edited.custom_gradient = picked == 1; + return sent(Some(false), KindControls::UvRandomColor(edited)); + } + if !edited.custom_gradient { + return None; + } + + let used = shown.used_colors().to_vec(); + let mut places = shown.used_positions(); + if let Some(drag) = sheet.gradient_ramp(&used, &places, &|t| shown.at(t).unwrap_or([0.0; 3])) { + if let Some(place) = places.get_mut(drag.index) { + *place = drag.position; + } + return Some((drag.merge, gradient_places(&shown, &places))); + } + + let mut quantity = used.len() as f32; + let range = f32::from(UvRandomColorParameters::MIN_QUANTITY)..=UvRandomColorParameters::MAX_GRADIENT_COLORS as f32; + let slid = sheet.slider(tr("Color Quantity"), &mut quantity, range, 0).is_some(); + + // 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(("uv_random_color_quantity", id)); + let quantity = quantity.round(); + if let Some(merge) = crate::widgets::press_edit(sheet.ui, press, slid && quantity as usize != used.len()) { + return Some((merge, json!({"gradientQuantity": quantity}))); + } + + let mut edit = None; + 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) = take_color_pick(app, pick) { + if let Some(slot) = edited.gradient.get_mut(index) { + *slot = picked; + } + edit = Some((pick.merge, gradient_colors(&edited))); + } + if let Some(merge) = moved { + if let Some(slot) = places.get_mut(index) { + *slot = place; + } + edit = Some((merge, gradient_places(&shown, &places))); + } + } + edit +} + +/// The colors of `random` to send: all of them, then its count again (the colors reset it) +fn gradient_colors(random: &UvRandomColorParameters) -> Value { + let mut params = json!({"gradientColors": random.gradient}); + if let Some(quantity) = random.quantity { + params["gradientQuantity"] = json!(quantity); + } + params +} + +/// The places to send: `used` (the used colors' places) and the hidden colors' own +fn gradient_places(random: &UvRandomColorParameters, used: &[f32]) -> Value { + let hidden = random.positions.iter().skip(used.len()).copied(); + json!({"gradientPositions": used.iter().copied().chain(hidden).collect::>()}) +} + +/// UV Checker: its color mode with the uniform color, Checker Grid Tile, Checker Grid Opacity and UV Borders Width beside the preview, then UV Borders Color +fn checker_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, shown: UvCheckerParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut edit = None; + if let Some(picked) = sheet.switch(tr("Checker Color Mode"), &[tr("Uniform"), tr("Random")], usize::from(edited.random_colors)) { + edited.random_colors = picked == 1; + edit = Some(false); + } + if !edited.random_colors { + let pick = sheet.color_bar_led(tr("Checker Color"), edited.checker_color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = take_color_pick(app, pick) { + edited.checker_color = picked; + edit = Some(pick.merge); + } + } + + let mut tile = edited.grid_tile as f32; + let tiles = *UvCheckerParameters::GRID_TILE_RANGE.start() as f32..=*UvCheckerParameters::GRID_TILE_RANGE.end() as f32; + let mut stack = [ + stacked_whole(tr("Checker Grid Tile"), &mut tile, tiles), + stacked(tr("Checker Grid Opacity"), &mut edited.grid_opacity), + stacked(tr("UV Borders Width"), &mut edited.border_width), + ]; + edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); + edited.grid_tile = tile.round() as u32; + + let pick = sheet.color_bar_led(tr("UV Borders Color"), edited.border_color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = take_color_pick(app, pick) { + edited.border_color = picked; + edit = Some(pick.merge); + } + sent(edit, KindControls::UvChecker(edited)) +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 98d060ee..4f6661da 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -2,7 +2,9 @@ use egui::{Painter, Rect, TextureHandle}; use serde_json::json; -use texturecraft_engine::core::{CookResolution, Generator, GeneratorKind, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters}; +use texturecraft_engine::core::{ + CookResolution, Generator, GeneratorKind, KindControls, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters, +}; use crate::TextureCraftApp; use crate::fill_material_panel::{band_size, texture_set_size}; @@ -39,10 +41,14 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, parameters(app, sheet, (layer, id), generator); } - let inputs = generator.inputs_in_use(); - if !inputs.is_empty() && sheet.band(tr("Image inputs"), false, None, Some(&inputs.len().to_string())).open { - for map in inputs { - let slot = GeneratorInputSlot::Map(*map); + // The kinds with only their own controls show the images the reference lets them take: Grayscale Conversion's own + let slots: Vec = match generator.kind_controls() { + Some(KindControls::Grayscale(_)) => vec![GeneratorInputSlot::Image], + Some(_) => Vec::new(), + None => generator.inputs_in_use().iter().map(|map| GeneratorInputSlot::Map(*map)).collect(), + }; + if !slots.is_empty() && sheet.band(tr("Image inputs"), false, None, Some(&slots.len().to_string())).open { + for slot in slots { input_card(app, sheet, (layer, id), slot, slot.source(generator), false); } } @@ -108,6 +114,10 @@ fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, let texture = texture.or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); let picture = |painter: &Painter, rect: Rect| orb(painter, rect, texture.as_ref(), &tokens, &ctx); + if let Some(controls) = generator.kind_controls() { + crate::generator_kind_rows::kind_rows(app, sheet, id, generator, controls, &picture); + return; + } if let Some(defaults) = WearParameters::defaults(kind) { // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them wear_rows(app, sheet, (layer, id), generator, generator.wear.unwrap_or(defaults), &picture); diff --git a/crates/ui-egui/src/generator_params.rs b/crates/ui-egui/src/generator_params.rs index 96fc1980..00fd88d2 100644 --- a/crates/ui-egui/src/generator_params.rs +++ b/crates/ui-egui/src/generator_params.rs @@ -1,7 +1,7 @@ //! The `effect.set` keys of a generator's controls, as its panel sends them use serde_json::{Value, json}; -use texturecraft_engine::core::{Generator, GeneratorKind, LightParameters, MicroDetails, SectionParameters, TextureLayer, WearParameters}; +use texturecraft_engine::core::{Generator, GeneratorKind, KindControls, LightParameters, MicroDetails, SectionParameters, TextureLayer, WearParameters}; use texturecraft_engine::mask_cmds::{section_key_applies, wear_key_applies}; use texturecraft_engine::micro_params::micro_key_applies; @@ -81,6 +81,73 @@ pub(crate) fn light_params(light: &LightParameters) -> Value { }) } +/// Every control of a kind with only its own controls, set to `controls` (Grayscale Conversion's image is its `image` input, kept apart) +pub(crate) fn kind_params(controls: &KindControls) -> Value { + match controls { + KindControls::Distance(distance) => json!({ + "distanceX": distance.point[0], + "distanceY": distance.point[1], + "distanceZ": distance.point[2], + "distanceRadius": distance.radius, + "distanceOffset": distance.offset, + "distanceContrast": distance.contrast, + }), + KindControls::LinearGradient(gradient) => json!({ + "gradientStart": gradient.start, + "gradientEnd": gradient.end, + "gradientBalance": gradient.balance, + "gradientContrast": gradient.contrast, + }), + KindControls::BorderDistance(border) => json!({ + "borderDistance": border.distance, + "borderSmoothness": border.smoothness, + "borderBalance": border.balance, + "borderContrast": border.contrast, + }), + KindControls::Grayscale(grayscale) => json!({ + "grayscaleType": grayscale.grayscale.id(), + "grayscaleBalance": grayscale.balance, + "grayscaleContrast": grayscale.contrast, + "grayscaleTile": grayscale.tile, + "grayscaleRotation": grayscale.rotation, + "grayscaleSafeRotation": grayscale.safe_rotation, + }), + KindControls::DrippingRust(rust) => json!({ + "rustSpreading": rust.spreading, + "rustContrast": rust.contrast, + "spreadingSmoothness": rust.spreading_smoothness, + "dripsIntensity": rust.drips_intensity, + "dripsSmoothness": rust.drips_smoothness, + "dripsSamples": rust.drips_samples, + "dripsAxis": DRIPS_AXES.get(usize::from(rust.axis)).copied().unwrap_or("y"), + }), + KindControls::UvRandomColor(random) => { + let mut params = json!({ + "colorSourceMode": if random.custom_gradient { "customGradient" } else { "random" }, + "gradientColors": random.gradient, + "gradientPositions": random.positions, + }); + + // The colors reset the count to all of them: one kept hides the rest again + if let Some(quantity) = random.quantity { + params["gradientQuantity"] = json!(quantity); + } + params + } + KindControls::UvChecker(checker) => json!({ + "checkerColorMode": if checker.random_colors { "random" } else { "uniform" }, + "checkerColor": checker.checker_color, + "checkerGridTile": checker.grid_tile, + "checkerGridOpacity": checker.grid_opacity, + "uvBordersColor": checker.border_color, + "uvBordersWidth": checker.border_width, + }), + } +} + +/// Dripping Rust's `dripsAxis` names, by axis +pub(crate) const DRIPS_AXES: [&str; 3] = ["x", "y", "z"]; + /// Every micro details control a generator of `kind` has, set to `micro` (its images are the `microHeight` and `microNormal` inputs) pub(crate) fn micro_params(kind: GeneratorKind, micro: &MicroDetails) -> Value { let mut params = json!({ @@ -111,6 +178,9 @@ pub(crate) fn defaults_of(id: u64, generator: &Generator) -> Value { "customResolution": defaults.resolution.custom, "resolutionFactor": defaults.resolution.factor, }); + if let Some(controls) = &defaults.controls { + return merged(params, kind_params(controls)); + } // 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}); @@ -163,7 +233,18 @@ pub(crate) fn differs_from_defaults(generator: &Generator) -> bool { { restored.micro = Some(Box::new(MicroDetails { height_source: micro.height_source.clone(), normal_source: micro.normal_source.clone(), ..defaults })); } - restored.controls = generator.controls.clone(); + + // Grayscale Conversion's image stays in its slot + restored.controls = match (restored.controls.as_deref(), generator.controls.as_deref()) { + (_, None) => None, + (Some(KindControls::Grayscale(defaults)), Some(KindControls::Grayscale(saved))) => { + Some(Box::new(KindControls::Grayscale(texturecraft_engine::core::GrayscaleConversionParameters { + source: saved.source.clone(), + ..defaults.clone() + }))) + } + (defaults, _) => defaults.cloned().map(Box::new), + }; // Saved before the wear, section or light controls: the earlier model's own values count if generator.wear.is_none() { diff --git a/crates/ui-egui/src/generator_point_pick.rs b/crates/ui-egui/src/generator_point_pick.rs new file mode 100644 index 00000000..72712c84 --- /dev/null +++ b/crates/ui-egui/src/generator_point_pick.rs @@ -0,0 +1,30 @@ +//! Picking a 3D generator's point on the mesh: its crosshair button arms it, the next click in the 3D view sets the point, Esc or the button again cancels + +/// Which point of which generator effect the next click in the 3D view sets +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PointPick { + pub(crate) effect: u64, + + /// `effect.generator.pickPoint`'s point: distance, start or end + pub(crate) point: &'static str, +} + +/// Where the armed pick is kept: a transient UI mode, like the depth of field's focus pick +fn pick_id() -> egui::Id { + egui::Id::unique("tc_generator_point_pick") +} + +/// The point the next click in the 3D view sets, if one is armed +pub(crate) fn armed(ctx: &egui::Context) -> Option { + ctx.data(|data| data.get_temp::>(pick_id())).flatten() +} + +/// Arms `pick`, or disarms it when it is the one armed +pub(crate) fn toggle(ctx: &egui::Context, pick: PointPick) { + let next = if armed(ctx) == Some(pick) { None } else { Some(pick) }; + set(ctx, next); +} + +pub(crate) fn set(ctx: &egui::Context, pick: Option) { + ctx.data_mut(|data| data.insert_temp(pick_id(), pick)); +} diff --git a/crates/ui-egui/src/generator_section_rows.rs b/crates/ui-egui/src/generator_section_rows.rs index 0e7533a8..38377af0 100644 --- a/crates/ui-egui/src/generator_section_rows.rs +++ b/crates/ui-egui/src/generator_section_rows.rs @@ -23,8 +23,11 @@ fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, picture: &dyn Fn(&Painter, Rect)) { let (mut invert, mut global) = (generator.invert, generator.global); let invert_edit = sheet.toggle(tr("Global Invert"), &mut invert).then_some(false); - let mut stack = - [stacked(tr("Global Blur"), &mut global.blur), stacked(tr("Global Balance"), &mut global.balance), stacked(tr("Global Contrast"), &mut global.contrast)]; + let mut stack = [ + stacked(tr("Global Blur"), &mut global.blur), + stacked(tr("Global Balance"), &mut global.balance), + stacked(tr("Global Contrast"), &mut global.contrast), + ]; let stack_edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if let Some(merge) = invert_edit.or(stack_edit) { app.run( @@ -35,7 +38,14 @@ pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<' } /// The kind's own card (Curvature's mode and sizes in it), then one card per axis, showing `shown`; `solo` keeps the Curvature size under the pointer for the preview -pub(crate) fn section_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, shown: SectionParameters, solo: &mut Option) { +pub(crate) fn section_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + generator: &Generator, + shown: SectionParameters, + solo: &mut Option, +) { let kind = generator.kind; let title = match kind { GeneratorKind::Curvature => tr("Curvature"), diff --git a/crates/ui-egui/src/generator_wear_rows.rs b/crates/ui-egui/src/generator_wear_rows.rs index 09273f0b..c103ab72 100644 --- a/crates/ui-egui/src/generator_wear_rows.rs +++ b/crates/ui-egui/src/generator_wear_rows.rs @@ -38,11 +38,8 @@ pub(crate) fn wear_rows( let dirt = kind == GeneratorKind::Dirt; let (level_label, contrast_label) = if dirt { (tr("Dirt Level"), tr("Dirt Contrast")) } else { (tr("Wear Level"), tr("Wear Contrast")) }; let mut edited = wear; - let mut stack = [ - stacked(level_label, &mut edited.level), - stacked(contrast_label, &mut edited.contrast), - stacked(tr("Grunge Amount"), &mut edited.grunge_amount), - ]; + let mut stack = + [stacked(level_label, &mut edited.level), stacked(contrast_label, &mut edited.contrast), stacked(tr("Grunge Amount"), &mut edited.grunge_amount)]; let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if kind != GeneratorKind::FiberGlassEdgeWear { edit = edit.or(sheet.slider(tr("Grunge Scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); @@ -82,7 +79,14 @@ pub(crate) fn wear_rows( } /// 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) -pub(crate) fn light_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, invert: Option, shown: LightParameters, picture: &dyn Fn(&Painter, Rect)) { +pub(crate) fn light_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + invert: Option, + shown: LightParameters, + picture: &dyn Fn(&Painter, Rect), +) { if let Some(mut invert) = invert && sheet.toggle(tr("Invert"), &mut invert) { @@ -90,7 +94,15 @@ pub(crate) fn light_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_ } let mut edited = shown; - let angle = |label, value| StackSlider { label, value, range: LightParameters::ANGLE_RANGE, typed: LightParameters::ANGLE_RANGE, decimals: 0, suffix: "°", dial: true }; + let angle = |label, value| StackSlider { + label, + value, + range: LightParameters::ANGLE_RANGE, + typed: LightParameters::ANGLE_RANGE, + decimals: 0, + suffix: "°", + dial: true, + }; let mut stack = [ angle(tr("Horizontal Angle"), &mut edited.horizontal), angle(tr("Vertical Angle"), &mut edited.vertical), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d626d5c3..f13365a8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -46,8 +46,10 @@ pub mod fonts; mod frame_gizmo; mod generator_input_card; mod generator_input_slot; +mod generator_kind_rows; mod generator_panel; mod generator_params; +mod generator_point_pick; mod generator_section_rows; mod generator_slot; mod generator_wear_rows; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..3782cf3b 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -473,6 +473,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Let the innermost popup consume Escape before cancelling the active tool let popup_open = egui::Popup::is_any_open(ctx); + let point_pick_armed = crate::generator_point_pick::armed(ctx).is_some(); + let mut cancel_point_pick = false; let picker_open = crate::color_picker::open_window(ctx).is_some(); let no_widget_focused = ctx.memory(|memory| memory.focused().is_none()); @@ -528,6 +530,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::import_resources::keys_in(app, input, nothing_focused, popup_open); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; + } else if !popup_open && point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { + cancel_point_pick = true; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { @@ -543,6 +547,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { commands }); + if cancel_point_pick { + crate::generator_point_pick::set(ctx, None); + } for id in &commands_to_invoke { if matches!(id.as_str(), "layer.copy" | "layer.cut") diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index bde4267b..291d50d9 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -38,6 +38,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: && app.moving_on_model.is_none() && !gesture_key_held && !crate::viewport::focus_picking(ui.ctx()) + && crate::generator_point_pick::armed(ui.ctx()).is_none() && ui.input(|input| input.modifiers.is_none()); if !free || !response.clicked_by(PointerButton::Secondary) { diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index f16db1b3..c534afc3 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -107,7 +107,14 @@ impl PropertySheet<'_> { } /// A card for one axis: its letter on a chip in `tint`, the bold name and the value, then a full-width slider filled in `tint`; the axis's other rows follow, then [`Self::close_card`] - pub(crate) fn axis_card(&mut self, (letter, tint): (&str, Color32), name: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + pub(crate) fn axis_card( + &mut self, + (letter, tint): (&str, Color32), + name: &str, + value: &mut f32, + range: RangeInclusive, + decimals: usize, + ) -> Option { self.open_card(); self.scope = self.named_id("axis_card", name); self.space(AXIS_CARD_TOP); diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 2e352d98..2e321496 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -51,9 +51,25 @@ impl PropertySheet<'_> { pub(crate) fn number_fields(&mut self, label: &str, fields: &mut [NumberField], link: Option<&mut bool>, keep_link_slot: bool) -> Option<(usize, bool)> { let (control, center_y) = self.row(label); let slot = if link.is_some() || keep_link_slot { LINK_SLOT } else { 0.0 }; + let edited = self.fields_in(control, slot, label, fields); + if let Some(linked) = link { + self.link_button(pos2(self.right - LINK_SIZE / 2.0, center_y), linked); + } + edited + } + + /// A point in 3D: `label` on its own line, then its fields across the card and the pick-on-mesh button in the link slot, lit while `picking`; returns the edited index with whether it continues a drag, and whether the button was clicked + pub(crate) fn point_fields(&mut self, label: &str, fields: &mut [NumberField], picking: bool) -> (Option<(usize, bool)>, bool) { + let (control, center_y) = self.row_with(super::RowLead::Label { text: label, stack: true }); + let edited = self.fields_in(control, LINK_SLOT, label, fields); + let clicked = self.pick_button(pos2(self.right - LINK_SIZE / 2.0, center_y), label, picking); + (edited, clicked) + } + + /// `fields` side by side across `control`, leaving `slot` at its end + fn fields_in(&mut self, control: Rect, slot: f32, label: &str, fields: &mut [NumberField]) -> Option<(usize, bool)> { let count = fields.len().max(1) as f32; let width = (control.width() - slot - (count - 1.0) * FIELD_GAP) / count; - let mut edited = None; for (index, field) in fields.iter_mut().enumerate() { let left = control.left() + index as f32 * (width + FIELD_GAP); @@ -62,13 +78,27 @@ impl PropertySheet<'_> { edited = Some((index, edited.is_none_or(|(_, previous_merge)| previous_merge) && merge)); } } - - if let Some(linked) = link { - self.link_button(pos2(self.right - LINK_SIZE / 2.0, center_y), linked); - } edited } + /// The button that arms picking the point of row `label` on the mesh; returns whether it was clicked + fn pick_button(&mut self, center: egui::Pos2, label: &str, picking: bool) -> bool { + let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); + let id = self.named_id("pick_on_mesh", label); + let response = self.ui.interact(rect, id, Sense::click()); + let name = crate::i18n::trf("Pick {name} on the mesh", &[("name", &label)]); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, picking, &name)); + let response = self.tip(response, crate::i18n::tr("Pick on the mesh")); + + let tokens = self.tokens; + let (fill, border) = if picking { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + let painter = self.ui.painter(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); + painter.text(rect.center(), Align2::CENTER_CENTER, ic::CROSSHAIR_SIMPLE, FontId::proportional(ICON_SIZE), tokens.text); + self.paint_control_focus(&response); + response.clicked() + } + /// The link that keeps two values together; returns whether it was clicked pub(super) fn link_button(&mut self, center: egui::Pos2, linked: &mut bool) -> bool { let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); diff --git a/crates/ui-egui/src/property_sheet/size_columns.rs b/crates/ui-egui/src/property_sheet/size_columns.rs index da810113..ec6dd9d7 100644 --- a/crates/ui-egui/src/property_sheet/size_columns.rs +++ b/crates/ui-egui/src/property_sheet/size_columns.rs @@ -53,8 +53,17 @@ impl PropertySheet<'_> { let painter = self.ui.painter(); if hovered { - let face = Rect::from_min_max(pos2(column.left() + FACE_AIR, block.top() - FACE_OVERHANG), pos2(column.right() - FACE_AIR, block.bottom() + FACE_OVERHANG)); - painter.rect(face, CornerRadius::same(super::CONTROL_RADIUS), tokens.row_hover, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + let face = Rect::from_min_max( + pos2(column.left() + FACE_AIR, block.top() - FACE_OVERHANG), + pos2(column.right() - FACE_AIR, block.bottom() + FACE_OVERHANG), + ); + painter.rect( + face, + CornerRadius::same(super::CONTROL_RADIUS), + tokens.row_hover, + Stroke::new(1.0, tokens.field_border), + egui::StrokeKind::Inside, + ); } painter.text(pos2(x, block.top() + VALUE_LINE / 2.0), Align2::CENTER_CENTER, format!("{value:.2}"), semibold(SMALL_TEXT_SIZE), tokens.text); painter.line_segment([pos2(x, track_top), pos2(x, track_bottom)], Stroke::new(COLUMN_TRACK_WIDTH, tokens.button_border)); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index dc64aaae..ba44649f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -646,7 +646,8 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; // High display scales must respect the orb camera's allocation limit - let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_)); + let on_the_orb = + matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_)); let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; // Scrolling moves tiles beneath a stationary pointer diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3c5a3d7e..473eaf29 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -864,9 +864,27 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); } + // A 3D generator's armed point pick: a click sets the point there instead of painting + let point_pick = crate::generator_point_pick::armed(ui.ctx()); + if let Some(pick) = point_pick { + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); + if !alt + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() + { + let (at, viewport) = (local(pointer), app.session.viewport); + let params = json!({"effect": pick.effect, "point": pick.point, "x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]}); + + // A click off the mesh keeps it armed for the next + if app.run("effect.generator.pickPoint", params).is_some() { + crate::generator_point_pick::set(ui.ctx(), None); + } + } + } + // Depth of field focus pick: a click focuses there instead of painting - let focus_pick = focus_picking(ui.ctx()); - if focus_pick { + let focus_pick = focus_picking(ui.ctx()) || point_pick.is_some(); + if focus_picking(ui.ctx()) { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt && response.clicked_by(PointerButton::Primary) diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 78fc0d9c..e191d8b0 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; -use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters, Source, WearParameters}; +use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, KindControls, LayerId, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -388,3 +388,107 @@ fn texture_panel_snapshots() { } } } + +/// Whether control `label` with `role` shows on +fn is_on(harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { + harness.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn a_point_pick_waits_for_the_view_until_escape() { + let (mut harness, _) = harness_with(false, json!({"generator": "3dLinearGradient"})); + let (start, end) = ("Pick 3D Position Start on the mesh", "Pick 3D Position End on the mesh"); + assert!(!is_on(&harness, Role::Button, start) && !is_on(&harness, Role::Button, end)); + + click_live(&mut harness, Role::Button, end); + assert!(is_on(&harness, Role::Button, end), "armed: the next click in the view sets the end"); + assert!(!is_on(&harness, Role::Button, start), "only the point picked waits"); + + click_live(&mut harness, Role::Button, start); + assert!(is_on(&harness, Role::Button, start) && !is_on(&harness, Role::Button, end), "arming the start hands the wait over"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert!(!is_on(&harness, Role::Button, start), "Esc cancels the pick"); +} + +#[test] +fn a_gradient_color_place_moves_its_stop_in_one_step() { + let added = + json!({"generator": "uvRandomColor", "colorSourceMode": "customGradient", "gradientColors": [[0.0, 0.0, 0.0], [0.8, 0.3, 0.1], [1.0, 1.0, 1.0]]}); + let (mut harness, effect) = harness_with(false, added); + let places = |harness: &Harness<'_, TextureCraftApp>| match generator(harness, effect).kind_controls() { + Some(KindControls::UvRandomColor(random)) => random.used_positions(), + other => panic!("not UV Random Color controls: {other:?}"), + }; + let before = places(&harness); + + // Color 2's own track, after its marker on the ramp + let rect = harness.get_all_by_role_and_label(Role::Slider, "Color 2").last().expect("Color 2's place").rect(); + let (from, to) = (egui::pos2(rect.left() + 4.0, rect.center().y), egui::pos2(rect.right() - 4.0, rect.center().y)); + harness.drag_at(from); + harness.run_steps(2); + harness.hover_at(to); + harness.run_steps(2); + harness.drop_at(to); + harness.run_steps(3); + + let after = places(&harness); + assert!(after[1] > before[1], "Color 2 moved right along the gradient"); + assert_eq!((after[0], after[2]), (before[0], before[2]), "the other colors keep their places"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(places(&harness), before, "one undo step puts it back"); +} + +#[test] +fn the_color_rows_follow_the_color_mode() { + let (mut harness, _) = harness_with(false, json!({"generator": "uvChecker"})); + assert_eq!(count(&harness, "Checker Color"), 1, "uniform: its color shows"); + click_live(&mut harness, Role::RadioButton, "Random"); + assert_eq!(count(&harness, "Checker Color"), 0, "random colors: no color to pick"); + assert_eq!(count(&harness, "UV Borders Color"), 1, "the borders keep theirs"); + + let (mut harness, _) = harness_with(false, json!({"generator": "uvRandomColor"})); + assert_eq!(count(&harness, "Color 1"), 0, "random: no gradient"); + harness.get_by_role_and_label(Role::ComboBox, "Random").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::ListBoxOption, "Custom Gradient").click(); + harness.run_steps(3); + assert!(count(&harness, "Color 1") > 0 && count(&harness, "Color 2") > 0, "a custom gradient shows its colors"); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn new_kind_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(); + let gradient = json!([[0.02, 0.02, 0.02], [0.6, 0.12, 0.03], [0.8, 0.8, 0.8]]); + let kinds = [ + ("3dDistance", json!({})), + ("3dLinearGradient", json!({})), + ("uvBorderDistance", json!({})), + ("grayscaleConversion", json!({})), + ("drippingRust", json!({})), + ("uvRandomColor", json!({"colorSourceMode": "customGradient", "gradientColors": gradient, "gradientPositions": [0.0, 0.45, 1.0]})), + ("uvChecker", json!({})), + ]; + for (kind, extra) in kinds { + let mut added = json!({"generator": kind}); + added.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let (mut harness, _) = harness_with(true, added); + if kind == "grayscaleConversion" { + harness.get_by_role_and_label(Role::Button, "Image inputs").click(); + } + + // The orbs render on the preview worker + for _ in 0..40 { + harness.run_steps(4); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-{kind}-{name}.png"))).unwrap(); + } + } +}