diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 933f9852..896dab07 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -15,7 +15,7 @@ use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, - PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, + PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; @@ -36,6 +36,7 @@ use crate::mask_gray::MaskGray; use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, placement, procedural_in, world_noise}; use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; +use crate::sections; use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; @@ -53,6 +54,9 @@ const COVERED: f32 = 0.9999; /// Largest projected step as a share of the image's longer side for non-UV projections const SEAM_JUMP_SHARE: f32 = 0.25; +/// Narrowest extent of the mesh's bounds a position is normalised across +const MIN_BOUNDS_EXTENT: f32 = 1e-6; + /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; @@ -508,8 +512,13 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } // Use reference-resolution reach so all callers classify the same filters as stages - EffectKind::Generator(generator) if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() => { - Some((index, texels(generator.applied_global().blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + EffectKind::Generator(generator) + if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() || sections::generator_blur_sigma(generator) > 0.0 => + { + let section_blur = sections::generator_blur_sigma(generator); + let section_reach = if section_blur > 0.0 { texels(section_blur) } else { 0.0 }; + let reach = texels(generator.applied_global().blur_radius()) + section_reach + generator.resolution.largest_cell(res) as f32; + Some((index, reach, Op::Blur(None))) } // A mirror reads anywhere in its UV tile @@ -1953,19 +1962,14 @@ fn generator_region( ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); } - let blur_radius = generator.applied_global().blur_radius_at(uv_tile).round() as usize; - if blur_radius > 0 { - let mut weights = cover.to_vec(); - blur(&mut weights, columns, rows, blur_radius); - let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); - blur(&mut sums, columns, rows, blur_radius); - ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { - if *weight > MIN_READ_WEIGHT { - *ramp = sum / weight; - } - }); + // The section controls act on the signal before the global blur, their own blur first + if let Some(section) = generator.section_controls() { + blur_over_cover(&mut ramps, cover, (columns, rows), sections::blur_radius_at(generator.kind, §ion, uv_tile)); + ramps.par_iter_mut().for_each(|signal| *signal = sections::adjusted(generator.kind, §ion, *signal)); } + blur_over_cover(&mut ramps, cover, (columns, rows), generator.applied_global().blur_radius_at(uv_tile).round() as usize); + // Finished and blended over the stack below, like the generator effect itself stack .par_chunks(2) @@ -1978,6 +1982,22 @@ fn generator_region( .collect() } +/// `values` blurred by three box passes of `radius`, weighted by `cover` so uncovered texels don't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], (columns, rows): (usize, usize), radius: usize) { + if radius == 0 { + return; + } + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, radius); + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + blur(&mut sums, columns, rows, radius); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(value, (sum, weight))| { + if *weight > MIN_READ_WEIGHT { + *value = sum / weight; + } + }); +} + /// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region @@ -2369,10 +2389,16 @@ fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { return wear::levels_in_use(generator.kind, &wear); } - let detail = generator.detail.as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + let detail = curvature_detail_in_use(generator).as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) } +/// The mode and detail sizes `generator` reads its curvature with: its own, the defaults on Curvature's section controls, else None +fn curvature_detail_in_use(generator: &Generator) -> Option { + let on_section = generator.kind == GeneratorKind::Curvature && generator.section_controls().is_some(); + generator.detail.clone().or_else(|| on_section.then(CurvatureDetail::default)) +} + /// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None fn wear_parameters(generator: &Generator) -> Option { generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) @@ -3296,10 +3322,14 @@ impl<'a, 'b> Texel<'a, 'b> { if needs_gray { [lum(value); 3] } else { value } } + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert (on the section controls, before those too). fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { if let Some(wear) = wear_parameters(generator) { return self.wear_ramp(generator, &wear, curvature_sizes); } + if let Some(section) = generator.section_controls() { + return self.section_signal(generator, §ion, curvature_sizes); + } let coords = self.coords(); let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); @@ -3319,6 +3349,7 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, }; let signal = if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; @@ -3354,10 +3385,39 @@ impl<'a, 'b> Texel<'a, 'b> { // Dirt gathers in dents; dents are occluded GeneratorKind::Dirt => -response, GeneratorKind::AmbientOcclusion => response, - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction => 0.0, + GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals => 0.0, } } + /// The signal a generator on its section controls adjusts at this texel: the axes of its map, its curvature or its occlusion + fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + match generator.kind { + GeneratorKind::Curvature => { + let detail = curvature_detail_in_use(generator).unwrap_or_default(); + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let curvature = self.generator_input(generator, BakedMap::Curvature); + let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); + self.curvature_detail(&detail, sizes, curvature, micro) + } + GeneratorKind::AmbientOcclusion => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + GeneratorKind::Position => { + let position = self.generator_input_color(generator, BakedMap::Position).unwrap_or_else(|| self.bounds_position().to_array()); + sections::axes_signal(position, §ion.axes) + } + GeneratorKind::WorldSpaceNormals => { + let normal = self.generator_input_color(generator, BakedMap::WorldNormal).unwrap_or_else(|| (self.coords().nrm * 0.5 + 0.5).to_array()); + sections::axes_signal(normal, §ion.axes) + } + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => 0.0, + } + } + + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) + fn bounds_position(&self) -> Vec3 { + let (low, high) = self.inp.bounds; + self.world().map_or(Vec3::ZERO, |position| ((position - low) / (high - low).max(Vec3::splat(MIN_BOUNDS_EXTENT))).clamp(Vec3::ZERO, Vec3::ONE)) + } + /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let curvature = self.generator_input(generator, BakedMap::Curvature).map_or(0.0, |curvature| curvature - 0.5); @@ -3396,7 +3456,8 @@ impl<'a, 'b> Texel<'a, 'b> { /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let ramp = self.generator_ramp(generator, curvature_sizes); - finish_generator(generator, ramp) + let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); + finish_generator(generator, adjusted) } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). @@ -3408,6 +3469,14 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// Generator input `map` at this texel as three channels (an encoded normal or position): what replaces the mesh map, else the mesh map (None when not baked) + fn generator_input_color(&mut self, generator: &Generator, map: BakedMap) -> Option<[f32; 3]> { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + None => self.baked_color(map), + } + } + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { let combine = |edges: f32, cavities: f32| { @@ -5852,7 +5921,8 @@ mod tests { for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { for mode in CurvatureMode::ALL { let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; - let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), wear: None, ..Generator::new(kind) }; + let generator = + Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), wear: None, section: None, ..Generator::new(kind) }; let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); fixture.project.layer_mut(layer).unwrap().mask = Some(mask); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 6318ea16..a2369743 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -36,6 +36,7 @@ pub mod projector_cover; pub mod projector_depth; mod projector_depth_cache; pub mod projector_view; +mod sections; mod shape_distance; mod slope_texel; mod soft_box; diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs new file mode 100644 index 00000000..2a6f9294 --- /dev/null +++ b/crates/compose/src/sections.rs @@ -0,0 +1,199 @@ +//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators + +use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, SectionParameters}; + +/// 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; + +/// Base of the section balance's power curve: balance 0 raises the signal to 1/25, balance 1 to 25 +const BALANCE_POWER_BASE: f32 = 25.0; + +/// How far above the middle a signal must be to turn white at full contrast +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]; + +/// 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| { + let axis = axes[index]; + if axis.weight <= 0.0 { + return base; + } + let layer = if axis.invert { 1.0 - channels[index] } else { channels[index] }; + (base + (blended(axis.blend, base, layer) - base) * axis.weight).clamp(0.0, 1.0) + }) +} + +/// `layer` blended over `base` by `blend`, unclamped +pub(crate) fn blended(blend: AxisBlend, base: f32, layer: f32) -> f32 { + match blend { + AxisBlend::Normal => layer, + AxisBlend::Add => base + layer, + AxisBlend::Subtract => base - layer, + AxisBlend::Multiply => base * layer, + AxisBlend::AddSub => base + 2.0 * layer - 1.0, + AxisBlend::Max => base.max(layer), + } +} + +/// Gaussian sigma of the section blur of a generator of `kind`, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`] (0 for kinds without it) +pub(crate) fn blur_sigma(kind: GeneratorKind, section: &SectionParameters) -> f32 { + if SectionParameters::has_blur(kind) { + section.blur.clamp(*SectionParameters::BLUR_RANGE.start(), *SectionParameters::BLUR_RANGE.end()) * BLUR_SIGMA_PER_UNIT + } else { + 0.0 + } +} + +/// Gaussian sigma of `generator`'s section blur in texels at 2K (0 without one) +pub(crate) fn generator_blur_sigma(generator: &Generator) -> f32 { + generator.section_controls().map_or(0.0, |section| blur_sigma(generator.kind, §ion)) +} + +/// The radius of the three box passes that blur like the section blur at `resolution` texels per side +pub(crate) fn blur_radius_at(kind: GeneratorKind, section: &SectionParameters, resolution: u32) -> usize { + let sigma = blur_sigma(kind, section) * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION; + + // Three boxes of radius r spread a texel with variance r (r + 1) + (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize +} + +/// `signal` after the section's balance, contrast, brightness and invert, as far as a generator of `kind` has them +pub(crate) fn adjusted(kind: GeneratorKind, section: &SectionParameters, signal: f32) -> f32 { + let mut value = signal.clamp(0.0, 1.0); + if SectionParameters::has_balance(kind) { + let balance = section.balance.clamp(0.0, 1.0); + value = if kind == GeneratorKind::AmbientOcclusion { + GeneratorGlobal { balance, ..GeneratorGlobal::default() }.apply(value) + } else { + value.powf(BALANCE_POWER_BASE.powf(2.0 * balance - 1.0)) + }; + } + value = contrasted(value, section.contrast.clamp(0.0, 1.0)); + if SectionParameters::has_brightness(kind) { + let brightness = section.brightness.clamp(*SectionParameters::BRIGHTNESS_RANGE.start(), *SectionParameters::BRIGHTNESS_RANGE.end()); + value = if brightness > 0.0 { value + brightness * (1.0 - value) } else { value * (1.0 + brightness) }; + } + if section.invert { 1.0 - value } else { value } +} + +/// `value` with its range narrowed around the middle by `contrast` (1 a step just above the middle) +fn contrasted(value: f32, contrast: f32) -> f32 { + if contrast <= 0.0 { + return value; + } + let half_range = 0.5 * (1.0 - contrast); + if 2.0 * half_range < GeneratorGlobal::MIN_RANGE { + return if value > 0.5 + FULL_CONTRAST_STEP_OFFSET { 1.0 } else { 0.0 }; + } + ((value - (0.5 - half_range)) / (2.0 * half_range)).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn axis(blend: AxisBlend, weight: f32) -> AxisLayer { + AxisLayer { invert: false, blend, weight } + } + + fn defaults(kind: GeneratorKind) -> SectionParameters { + SectionParameters::defaults(kind).unwrap() + } + + #[test] + fn each_axis_reads_its_own_channel() { + let channels = [0.2, 0.5, 0.9]; + for (index, expected) in channels.iter().enumerate() { + let mut axes = [axis(AxisBlend::Add, 0.0); 3]; + axes[index].weight = 1.0; + assert!((axes_signal(channels, &axes) - expected).abs() < 1e-6, "axis {index}"); + } + let mut inverted = [axis(AxisBlend::Add, 0.0); 3]; + inverted[SectionParameters::TOP_TO_BOTTOM] = AxisLayer { invert: true, ..axis(AxisBlend::Add, 1.0) }; + assert!((axes_signal(channels, &inverted) - 0.5).abs() < 1e-6); + inverted[SectionParameters::RIGHT_TO_LEFT] = AxisLayer { invert: true, ..axis(AxisBlend::Normal, 1.0) }; + assert!((axes_signal(channels, &inverted) - 0.8).abs() < 1e-6, "inverted red replaces the base"); + } + + #[test] + fn right_to_left_blends_over_top_to_bottom_and_front_to_back_goes_last() { + let channels = [0.3, 0.8, 0.6]; + let mut axes = [axis(AxisBlend::Add, 0.0), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)]; + for (blend, expected) in [ + (AxisBlend::Normal, 0.3), + (AxisBlend::Add, 1.0), + (AxisBlend::Subtract, 0.5), + (AxisBlend::Multiply, 0.24), + (AxisBlend::AddSub, 0.4), + (AxisBlend::Max, 0.8), + ] { + axes[SectionParameters::RIGHT_TO_LEFT] = axis(blend, 1.0); + assert!((axes_signal(channels, &axes) - expected).abs() < 1e-6, "{blend:?}"); + } + + axes[SectionParameters::RIGHT_TO_LEFT] = axis(AxisBlend::Normal, 1.0); + axes[SectionParameters::FRONT_TO_BACK] = axis(AxisBlend::Normal, 1.0); + assert!((axes_signal(channels, &axes) - 0.6).abs() < 1e-6, "front to back replaces both"); + } + + #[test] + fn a_weight_lerps_the_unclamped_blend_and_clamps_once() { + let channels = [0.9, 0.8, 0.0]; + let axes = [axis(AxisBlend::Add, 0.5), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)]; + assert!((axes_signal(channels, &axes) - 1.0).abs() < 1e-6, "0.8 + 0.45 clamps to 1"); + let axes = [axis(AxisBlend::Subtract, 0.5), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)]; + assert!((axes_signal(channels, &axes) - 0.35).abs() < 1e-6); + } + + #[test] + fn position_balance_is_a_power_curve_and_occlusion_balance_is_linear() { + let position = SectionParameters { balance: 0.25, ..defaults(GeneratorKind::Position) }; + assert!((adjusted(GeneratorKind::Position, &position, 0.5) - 0.5f32.powf(0.2)).abs() < 1e-5); + let position = SectionParameters { balance: 0.75, ..position }; + assert!((adjusted(GeneratorKind::Position, &position, 0.5) - 0.5f32.powf(5.0)).abs() < 1e-5); + + let occlusion = SectionParameters { balance: 0.25, ..defaults(GeneratorKind::AmbientOcclusion) }; + assert_eq!(adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.4), 0.0, "the lower half goes black"); + assert!((adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.75) - 0.5).abs() < 1e-6); + + let curvature = SectionParameters { balance: 0.0, ..defaults(GeneratorKind::Curvature) }; + assert_eq!(adjusted(GeneratorKind::Curvature, &curvature, 0.4), 0.4, "curvature has no balance"); + } + + #[test] + fn contrast_narrows_around_the_middle_and_full_contrast_steps_just_above_it() { + let half = SectionParameters { contrast: 0.5, ..defaults(GeneratorKind::Curvature) }; + assert_eq!(adjusted(GeneratorKind::Curvature, &half, 0.25), 0.0); + assert!((adjusted(GeneratorKind::Curvature, &half, 0.6) - 0.7).abs() < 1e-5); + + let full = SectionParameters { contrast: 1.0, ..half }; + assert_eq!(adjusted(GeneratorKind::Curvature, &full, 0.5), 0.0, "the middle itself stays black"); + assert_eq!(adjusted(GeneratorKind::Curvature, &full, 0.5001), 1.0); + } + + #[test] + fn brightness_lerps_towards_white_or_black_then_invert_flips() { + let brighter = SectionParameters { brightness: 0.5, ..defaults(GeneratorKind::WorldSpaceNormals) }; + assert!((adjusted(GeneratorKind::WorldSpaceNormals, &brighter, 0.4) - 0.7).abs() < 1e-6); + let darker = SectionParameters { brightness: -0.5, ..brighter }; + assert!((adjusted(GeneratorKind::WorldSpaceNormals, &darker, 0.4) - 0.2).abs() < 1e-6); + let inverted = SectionParameters { invert: true, ..darker }; + assert!((adjusted(GeneratorKind::WorldSpaceNormals, &inverted, 0.4) - 0.8).abs() < 1e-6); + + let occlusion = SectionParameters { brightness: 0.5, ..defaults(GeneratorKind::AmbientOcclusion) }; + assert_eq!(adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.4), 0.4, "ambient occlusion has no brightness"); + } + + #[test] + fn only_ambient_occlusion_and_world_space_normals_blur() { + let section = SectionParameters { blur: 16.0, ..defaults(GeneratorKind::Position) }; + assert_eq!(blur_sigma(GeneratorKind::Position, §ion), 0.0); + assert_eq!(blur_sigma(GeneratorKind::WorldSpaceNormals, §ion), 72.0); + assert_eq!(blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 0.0, ..section }, 2048), 0); + 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"); + } +} diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs new file mode 100644 index 00000000..3a9b65c4 --- /dev/null +++ b/crates/compose/tests/generator_sections.rs @@ -0,0 +1,201 @@ +//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals 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, +}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// How far a mask value may sit from the expected one +const TOLERANCE: f32 = 1e-3; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, +} + +/// A unit sphere with a white fill layer +fn fixture() -> Fixture { + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + Fixture { project, mesh, gbuf, layer, baked: BakedMaps::default() } +} + +/// A baked map of `map` holding `value` everywhere +fn uniform_map(map: BakedMap, value: f32) -> BakedMaps { + BakedMaps { resolution: RES, maps: [(map, Arc::new(vec![value; (RES * RES) as usize * map.components()]))].into() } +} + +/// Every covered texel with its world position and normal +fn surface(fixture: &Fixture) -> Vec<((u32, u32), Vec3, Vec3)> { + (0..RES * RES) + .filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos, surface.nrm))) + .collect() +} + +/// The mask of `generator` alone over black at `texels` +fn mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// The earlier model's smooth step of `signal` at `generator`'s level and softness +fn earlier_ramp(generator: &Generator, signal: f32) -> f32 { + let threshold = 1.0 - generator.level; + let ramp = ((signal - (threshold - generator.softness)) / (2.0 * generator.softness)).clamp(0.0, 1.0); + ramp * ramp * (3.0 - 2.0 * ramp) +} + +fn earlier(kind: GeneratorKind) -> Generator { + Generator { section: None, ..Generator::new(kind) } +} + +fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters)) -> Generator { + let mut generator = Generator::new(kind); + let mut section = generator.section.unwrap(); + change(&mut section); + generator.section = Some(section); + 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}"); + } +} + +#[test] +fn generators_saved_before_their_new_controls_render_as_before() { + let mut fixture = fixture(); + let points = surface(&fixture); + let texels: Vec<_> = points.iter().map(|point| point.0).collect(); + let (low, high) = fixture.mesh.bounds(); + let (center, radius) = ((low + high) * 0.5, (high - low).length() * 0.5); + + let position = earlier(GeneratorKind::Position); + let expected: Vec = points.iter().map(|(_, pos, _)| earlier_ramp(&position, ((*pos - center) / radius).y * 0.5 + 0.5)).collect(); + assert_close(&mask(&mut fixture, position, &texels), &expected, "position"); + + let direction = earlier(GeneratorKind::Direction); + let expected: Vec = points.iter().map(|(_, _, nrm)| earlier_ramp(&direction, nrm.y * 0.5 + 0.5)).collect(); + assert_close(&mask(&mut fixture, direction, &texels), &expected, "direction"); + + fixture.baked = uniform_map(BakedMap::AmbientOcclusion, 0.3); + let occlusion = earlier(GeneratorKind::AmbientOcclusion); + let expected = vec![earlier_ramp(&occlusion, 0.3); texels.len()]; + assert_close(&mask(&mut fixture, occlusion, &texels), &expected, "ambient occlusion"); + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion), &texels), &vec![0.3; texels.len()], "new ambient occlusion"); + + fixture.baked = uniform_map(BakedMap::Curvature, 0.7); + let curvature = Generator { detail: None, ..earlier(GeneratorKind::Curvature) }; + let expected = vec![earlier_ramp(&curvature, 0.7); texels.len()]; + assert_close(&mask(&mut fixture, curvature, &texels), &expected, "curvature"); +} + +#[test] +fn world_space_normals_combine_the_axes_of_the_normal() { + let mut fixture = fixture(); + let points = surface(&fixture); + let texels: Vec<_> = points.iter().map(|point| point.0).collect(); + let channel = |axis: usize| -> Vec { points.iter().map(|(_, _, nrm)| nrm[axis] * 0.5 + 0.5).collect() }; + + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::WorldSpaceNormals), &texels), &channel(1), "top to bottom by default"); + for (index, axis) in [(SectionParameters::RIGHT_TO_LEFT, 0), (SectionParameters::FRONT_TO_BACK, 2)] { + let generator = with_section(GeneratorKind::WorldSpaceNormals, |section| { + section.axes[SectionParameters::TOP_TO_BOTTOM].weight = 0.0; + section.axes[index].weight = 1.0; + }); + assert_close(&mask(&mut fixture, generator, &texels), &channel(axis), "one axis alone"); + } + + let multiplied = with_section(GeneratorKind::WorldSpaceNormals, |section| { + section.axes[SectionParameters::RIGHT_TO_LEFT] = texturecraft_core::AxisLayer { invert: true, blend: AxisBlend::Multiply, weight: 1.0 }; + }); + let expected: Vec = channel(1).iter().zip(channel(0)).map(|(top, right)| top * (1.0 - right)).collect(); + assert_close(&mask(&mut fixture, multiplied, &texels), &expected, "inverted right to left multiplies top to bottom"); + + // Without a baked map, the generator's own World Space Normal input reads instead of the mesh + let mut uniform = Generator::new(GeneratorKind::WorldSpaceNormals); + uniform.inputs.insert(BakedMap::WorldNormal, Source::Uniform([0.2, 0.9, 0.4])); + assert_close(&mask(&mut fixture, uniform, &texels), &vec![0.9; texels.len()], "a replaced input"); +} + +#[test] +fn position_reads_the_mesh_bounds_without_a_bake_and_the_baked_map_with_one() { + let mut fixture = fixture(); + let points = surface(&fixture); + let texels: Vec<_> = points.iter().map(|point| point.0).collect(); + let (low, high) = fixture.mesh.bounds(); + let expected: Vec = points.iter().map(|(_, pos, _)| (pos.y - low.y) / (high.y - low.y)).collect(); + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::Position), &texels), &expected, "bounds"); + + fixture.baked = uniform_map(BakedMap::Position, 0.25); + let balanced = with_section(GeneratorKind::Position, |section| section.balance = 0.25); + assert_close(&mask(&mut fixture, balanced, &texels), &vec![0.25f32.powf(0.2); texels.len()], "a power curve balance"); +} + +#[test] +fn occlusion_balance_is_linear_and_brightness_lerps() { + let mut fixture = fixture(); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.0).collect(); + fixture.baked = uniform_map(BakedMap::AmbientOcclusion, 0.6); + let balanced = with_section(GeneratorKind::AmbientOcclusion, |section| section.balance = 0.25); + assert_close(&mask(&mut fixture, balanced, &texels), &vec![0.2; texels.len()], "balance 0.25 stretches the upper half"); + + let inverted = with_section(GeneratorKind::AmbientOcclusion, |section| section.invert = true); + assert_close(&mask(&mut fixture, inverted, &texels), &vec![0.4; texels.len()], "section invert"); + + fixture.baked = uniform_map(BakedMap::Position, 0.4); + let brighter = with_section(GeneratorKind::Position, |section| section.brightness = 0.5); + assert_close(&mask(&mut fixture, brighter, &texels), &vec![0.7; texels.len()], "brightness 0.5 halves the way to white"); + let darker = with_section(GeneratorKind::Position, |section| section.brightness = -0.5); + assert_close(&mask(&mut fixture, darker, &texels), &vec![0.2; texels.len()], "brightness -0.5 halves the value"); +} + +#[test] +fn section_blur_spreads_occlusion_across_a_step() { + let mut fixture = fixture(); + let step: Vec = (0..RES * RES).map(|index| if index % RES < RES / 2 { 0.0 } else { 1.0 }).collect(); + fixture.baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(step))].into() }; + let row: Vec<(u32, u32)> = surface(&fixture).iter().map(|point| point.0).filter(|texel| texel.0.abs_diff(RES / 2) <= 2).collect(); + assert!(!row.is_empty()); + + let sharp = mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion), &row); + assert!(sharp.iter().all(|value| *value == 0.0 || *value == 1.0), "unblurred: {sharp:?}"); + let blurred = mask(&mut fixture, with_section(GeneratorKind::AmbientOcclusion, |section| section.blur = 16.0), &row); + assert!(blurred.iter().all(|value| *value > 0.05 && *value < 0.95), "blurred across the step: {blurred:?}"); + + let position = with_section(GeneratorKind::Position, |section| section.blur = 16.0); + 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"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index f2b3d7df..1e0f001d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -12,6 +12,8 @@ use crate::{ ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, }; +mod axis_blend; +mod axis_layer; mod curvature_detail; mod curvature_mode; mod decal_flip; @@ -23,6 +25,7 @@ mod output_resolution; mod resolution_mode; mod sampling; mod scale_mode; +mod section_parameters; mod tile_blending; mod tile_generator; mod tile_input_distribution; @@ -33,6 +36,8 @@ mod uv_transform; mod uv_wrap; mod wear_parameters; +pub use axis_blend::AxisBlend; +pub use axis_layer::AxisLayer; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; @@ -44,6 +49,7 @@ pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; pub use sampling::Sampling; pub use scale_mode::ScaleMode; +pub use section_parameters::SectionParameters; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; @@ -930,10 +936,12 @@ pub enum GeneratorKind { Direction, /// Worn edges of a fibreglass-like coating: the edges fade into its grunge FiberGlassEdgeWear, + /// The world space normal's axes combined into one gray + WorldSpaceNormals, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 8] = [ + pub const ALL: [GeneratorKind; 9] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -942,6 +950,7 @@ impl GeneratorKind { GeneratorKind::Position, GeneratorKind::Direction, GeneratorKind::FiberGlassEdgeWear, + GeneratorKind::WorldSpaceNormals, ]; pub fn label(self) -> &'static str { match self { @@ -953,6 +962,7 @@ impl GeneratorKind { GeneratorKind::Position => "Position", GeneratorKind::Direction => "Light", GeneratorKind::FiberGlassEdgeWear => "Fiber Glass Edge Wear", + GeneratorKind::WorldSpaceNormals => "World Space Normals", } } @@ -967,6 +977,7 @@ impl GeneratorKind { GeneratorKind::Position => "Position", GeneratorKind::Direction => "Direction", GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear", + GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals", } } @@ -987,7 +998,9 @@ impl GeneratorKind { GeneratorKind::Curvature => &[BakedMap::Curvature], GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], GeneratorKind::ThinAreas => &[BakedMap::Thickness], - GeneratorKind::Position | GeneratorKind::Direction => &[], + GeneratorKind::Position => &[BakedMap::Position], + GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], + GeneratorKind::Direction => &[], } } @@ -1041,6 +1054,9 @@ pub struct Generator { /// The wear kinds' controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub wear: Option, + /// 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, } impl Generator { @@ -1056,6 +1072,16 @@ impl Generator { if self.wear.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 + pub fn section_controls(&self) -> Option { + self.section.or_else(|| SectionParameters::defaults(self.kind).filter(|_| self.kind == GeneratorKind::WorldSpaceNormals)) + } + + /// 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 + } + pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), @@ -1085,6 +1111,7 @@ impl Generator { inputs: BTreeMap::new(), micro: None, wear: WearParameters::defaults(kind), + section: SectionParameters::defaults(kind), } } @@ -2317,6 +2344,24 @@ mod tests { assert!(curvature.get("wear").is_none(), "other kinds save no wear controls"); } + #[test] + fn generators_saved_before_their_section_controls_load_on_the_earlier_model() { + for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position] { + 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"); + + saved.as_object_mut().unwrap().remove("section"); + 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"); + } + + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::WorldSpaceNormals)).unwrap(); + saved.as_object_mut().unwrap().remove("section"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.section_controls(), SectionParameters::defaults(GeneratorKind::WorldSpaceNormals), "it has no earlier model"); + } + #[test] fn curvature_generators_saved_before_detail_sizes_load_without_them() { let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); diff --git a/crates/core/src/layer/axis_blend.rs b/crates/core/src/layer/axis_blend.rs new file mode 100644 index 00000000..bb53925d --- /dev/null +++ b/crates/core/src/layer/axis_blend.rs @@ -0,0 +1,52 @@ +use serde::{Deserialize, Serialize}; + +/// How an axis of a World Space Normals or Position generator combines with the axes before it +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AxisBlend { + /// The axis replaces what is below it + Normal, + /// The axis adds to what is below it + Add, + /// The axis is taken from what is below it + Subtract, + /// The axis multiplies what is below it + Multiply, + /// The axis adds above its middle gray and subtracts below it + AddSub, + /// The brighter of the axis and what is below it + Max, +} + +impl AxisBlend { + pub const ALL: [AxisBlend; 6] = [AxisBlend::Normal, AxisBlend::Add, AxisBlend::Subtract, AxisBlend::Multiply, AxisBlend::AddSub, AxisBlend::Max]; + + /// The name the panel shows + pub fn label(self) -> &'static str { + match self { + AxisBlend::Normal => "Normal", + AxisBlend::Add => "Linear Dodge (Add)", + AxisBlend::Subtract => "Subtract", + AxisBlend::Multiply => "Multiply", + AxisBlend::AddSub => "Add/Sub", + AxisBlend::Max => "Max (Lighten)", + } + } + + /// The name commands and saved projects use + pub fn id(self) -> &'static str { + match self { + AxisBlend::Normal => "normal", + AxisBlend::Add => "add", + AxisBlend::Subtract => "subtract", + AxisBlend::Multiply => "multiply", + AxisBlend::AddSub => "addSub", + AxisBlend::Max => "max", + } + } + + /// The blend named by its id or its label, in any case + pub fn parse(name: &str) -> Option { + AxisBlend::ALL.into_iter().find(|blend| blend.id().eq_ignore_ascii_case(name) || blend.label().eq_ignore_ascii_case(name)) + } +} diff --git a/crates/core/src/layer/axis_layer.rs b/crates/core/src/layer/axis_layer.rs new file mode 100644 index 00000000..58e5bae6 --- /dev/null +++ b/crates/core/src/layer/axis_layer.rs @@ -0,0 +1,14 @@ +use serde::{Deserialize, Serialize}; + +use super::axis_blend::AxisBlend; + +/// One axis of a World Space Normals or Position generator: its channel, inverted or not, blended over the axes before it +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AxisLayer { + /// The axis read from its far side + pub invert: bool, + pub blend: AxisBlend, + /// How much of the blend shows (0..1) + pub weight: f32, +} diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs new file mode 100644 index 00000000..583c4a99 --- /dev/null +++ b/crates/core/src/layer/section_parameters.rs @@ -0,0 +1,81 @@ +use serde::{Deserialize, Serialize}; + +use super::GeneratorKind; +use super::axis_blend::AxisBlend; +use super::axis_layer::AxisLayer; + +/// The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators, applied before the global ones +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SectionParameters { + pub invert: bool, + /// Blur of the signal ([`SectionParameters::BLUR_RANGE`]; Ambient Occlusion and World Space Normals) + pub blur: f32, + /// Shifts the signal darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged (not Curvature) + pub balance: f32, + /// Narrows the signal around its middle (0 unchanged, 1 a hard step) + pub contrast: f32, + /// Lifts the signal towards white (above 0) or black (below 0) ([`SectionParameters::BRIGHTNESS_RANGE`]; not Ambient Occlusion) + pub brightness: f32, + /// Right to left, top to bottom and front to back (Position and World Space Normals) + pub axes: [AxisLayer; 3], +} + +impl SectionParameters { + pub const BLUR_RANGE: std::ops::RangeInclusive = 0.0..=16.0; + pub const BRIGHTNESS_RANGE: std::ops::RangeInclusive = -1.0..=1.0; + /// Index in [`SectionParameters::axes`] of each axis + pub const RIGHT_TO_LEFT: usize = 0; + pub const TOP_TO_BOTTOM: usize = 1; + pub const FRONT_TO_BACK: usize = 2; + + /// The reference app's defaults for `kind`, or None for kinds without section controls + pub fn defaults(kind: GeneratorKind) -> Option { + let axis = |weight: f32| AxisLayer { invert: false, blend: AxisBlend::Add, weight }; + let defaults = SectionParameters { invert: false, blur: 0.0, balance: 0.5, contrast: 0.0, brightness: 0.0, axes: [axis(0.0), axis(1.0), axis(0.0)] }; + match kind { + GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals => Some(defaults), + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => None, + } + } + + /// Whether a generator of `kind` has the section blur + pub fn has_blur(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::AmbientOcclusion | GeneratorKind::WorldSpaceNormals) + } + + /// Whether a generator of `kind` has the section balance + pub fn has_balance(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals) + } + + /// Whether a generator of `kind` has the section brightness + pub fn has_brightness(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::Curvature | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals) + } + + /// Whether a generator of `kind` combines the three axes of a map + pub fn has_axes(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::Position | GeneratorKind::WorldSpaceNormals) + } + + /// Every value brought into its range, non-finite ones to the defaults of `kind` + pub fn clamped(self, kind: GeneratorKind) -> SectionParameters { + let defaults = SectionParameters::defaults(kind).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 } + }; + let axes = std::array::from_fn(|index| { + let (axis, default) = (self.axes[index], defaults.axes[index]); + AxisLayer { weight: within(axis.weight, default.weight, 0.0..=1.0), ..axis } + }); + SectionParameters { + invert: self.invert, + blur: within(self.blur, defaults.blur, SectionParameters::BLUR_RANGE), + balance: within(self.balance, defaults.balance, 0.0..=1.0), + contrast: within(self.contrast, defaults.contrast, 0.0..=1.0), + brightness: within(self.brightness, defaults.brightness, SectionParameters::BRIGHTNESS_RANGE), + axes, + } + } +} diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index b0c2de19..956dbd1a 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -49,7 +49,12 @@ impl WearParameters { match kind { GeneratorKind::EdgeWear | GeneratorKind::Dirt => Some(shared), GeneratorKind::FiberGlassEdgeWear => Some(WearParameters { curvature_weight: 0.25, ..shared }), - GeneratorKind::ThinAreas | GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::Direction => None, + GeneratorKind::ThinAreas + | GeneratorKind::Curvature + | GeneratorKind::AmbientOcclusion + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index b494aa57..222613cf 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,10 +111,10 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, + 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, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, + Sampling, ScaleMode, SectionParameters, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 9f5d493f..1b23275d 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, WearParameters, + 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, }; 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|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), level?, softness?, noise?, offset?: -1..1 added to the result (instead keep edgeWear and dirt 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), 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 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 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)}", has_layer, set ), @@ -472,8 +472,111 @@ pub fn wear_key_applies(kind: GeneratorKind, key: &str) -> bool { } } +/// The parameters that drive the earlier model of the kinds with section 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`] +const SECTION_KEYS: [&str; 5] = ["sectionInvert", "sectionBlur", "sectionBalance", "sectionContrast", "sectionBrightness"]; + +/// The name of each axis in its keys, in the order of [`SectionParameters::axes`], and what follows it +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 +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() +} + +/// The section 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 { + 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()))) + } + 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")); + } + if kind == GeneratorKind::WorldSpaceNormals { + return Err(bad( + command, + "World Space Normals has section controls only (sectionBalance, topBottomWeight…), no level, softness, noise, offset or direction", + )); + } + generator.section = None; + return Ok(()); + } + if new_keys.is_empty() { + return Ok(()); + } + + // Moving onto the reference's controls starts from the kind's defaults: the earlier model's values no longer apply + if generator.on_earlier_model() { + let defaults = Generator::new(kind); + (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); + } + + let mut section = generator.section_controls().unwrap_or(defaults); + for (key, value) in [ + ("sectionBlur", &mut section.blur), + ("sectionBalance", &mut section.balance), + ("sectionContrast", &mut section.contrast), + ("sectionBrightness", &mut section.brightness), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(invert) = boolp(params, "sectionInvert") { + section.invert = invert; + } + for (axis, name) in section.axes.iter_mut().zip(AXIS_NAMES) { + if let Some(invert) = boolp(params, &format!("{name}Invert")) { + axis.invert = invert; + } + if let Some(weight) = f32p(params, &format!("{name}Weight")) { + axis.weight = weight; + } + let blend_key = format!("{name}Blend"); + if let Some(blend) = params.get(&blend_key) { + let blend_name = blend.as_str().ok_or_else(|| bad(command, format!("`{blend_key}` must be a string")))?; + axis.blend = AxisBlend::parse(blend_name).ok_or_else(|| bad(command, format!("unknown blending mode `{blend_name}`")))?; + } + } + generator.section = Some(section.clamped(kind)); + Ok(()) +} + +/// Whether section 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 { + "sectionInvert" | "sectionContrast" => SectionParameters::defaults(kind).is_some(), + "sectionBlur" => SectionParameters::has_blur(kind), + "sectionBalance" => SectionParameters::has_balance(kind), + "sectionBrightness" => SectionParameters::has_brightness(kind), + _ if axis_key => SectionParameters::has_axes(kind), + _ => false, + } +} + fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { wear_from(command, params, generator)?; + section_from(command, params, generator)?; if let Some(level) = f32p(params, "level") { generator.level = level.clamp(0.0, 1.0); } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 244c412e..ceeb23cf 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -79,14 +79,24 @@ 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 wear controls) +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or the wear and section 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, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, wear: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { + level, + softness, + noise_amount: noise, + direction, + invert, + detail: None, + wear: None, + section: None, + ..Generator::new(kind) + }) } /// A triplanar grayscale pattern fill diff --git a/crates/engine/tests/it/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs index 6ea63f2f..b2c88885 100644 --- a/crates/engine/tests/it/bake_resolution.rs +++ b/crates/engine/tests/it/bake_resolution.rs @@ -127,5 +127,9 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap(); execute(&mut session, "effect.add.generator", &json!({"layer": layer.0, "generator": "ambientOcclusion"})).unwrap(); let mask = session.mask_at(layer, &[(376, 120), (266, 10)]).unwrap(); - assert_eq!(mask, vec![1.0, 0.0], "generators sample the whole bake through the working layout"); + let expected = [240.0 / 255.0, 20.0 / 255.0]; + assert!( + mask.iter().zip(expected).all(|(value, expected)| (value - expected).abs() < 0.001), + "generators sample the whole bake through the working layout: {mask:?}" + ); } diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs new file mode 100644 index 00000000..02c68135 --- /dev/null +++ b/crates/engine/tests/it/generator_sections.rs @@ -0,0 +1,90 @@ +//! The section 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::mask_cmds::section_key_applies; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +#[test] +fn new_generators_start_on_the_reference_controls() { + let mut session = session(); + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + let effect = add(&mut session, json!({"generator": kind})); + let added = generator(&session, effect); + assert_eq!(added.section, SectionParameters::defaults(added.kind), "{kind}"); + } + assert_eq!(GeneratorKind::parse("World Space Normals"), Some(GeneratorKind::WorldSpaceNormals)); +} + +#[test] +fn a_section_control_moves_an_earlier_generator_onto_the_defaults_with_that_change() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "position", "level": 0.8})); + assert_eq!(generator(&session, effect).section, None, "level keeps it on the earlier model"); + + let edit = json!({"effect": effect, "sectionBalance": 0.3, "rightLeftBlend": "Max (Lighten)", "frontBackWeight": 4.0, "sectionBrightness": -3.0}); + execute(&mut session, "effect.set", &edit).unwrap(); + + let moved = generator(&session, effect); + let mut expected = SectionParameters::defaults(GeneratorKind::Position).unwrap(); + expected.balance = 0.3; + expected.brightness = -1.0; + expected.axes[SectionParameters::RIGHT_TO_LEFT].blend = AxisBlend::Max; + expected.axes[SectionParameters::FRONT_TO_BACK].weight = 1.0; + assert_eq!(moved.section, Some(expected), "the rest at defaults, values clamped"); + assert_eq!(moved.level, Generator::new(GeneratorKind::Position).level, "the earlier model's values start over"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "noise": 0.5})).unwrap(); + assert_eq!(generator(&session, effect).section, None, "noise moves it back"); +} + +#[test] +fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { + let mut session = session(); + let curvature = add(&mut session, json!({"generator": "curvature"})); + let occlusion = add(&mut session, json!({"generator": "ambientOcclusion"})); + let position = add(&mut session, json!({"generator": "position"})); + let normals = add(&mut session, json!({"generator": "worldSpaceNormals"})); + let dirt = add(&mut session, json!({"generator": "dirt"})); + + for (effect, key) in [ + (curvature, "sectionBalance"), + (curvature, "sectionBlur"), + (curvature, "topBottomWeight"), + (occlusion, "sectionBrightness"), + (occlusion, "rightLeftInvert"), + (position, "sectionBlur"), + (dirt, "sectionContrast"), + ] { + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.5})).is_err(), "{key} on {effect}"); + } + for (effect, key) in [(curvature, "sectionBrightness"), (occlusion, "sectionBlur"), (normals, "sectionBlur"), (normals, "frontBackWeight")] { + execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.5})).unwrap(); + } + + assert!(execute(&mut session, "effect.set", &json!({"effect": position, "level": 0.5, "sectionContrast": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": normals, "softness": 0.5})).is_err(), "World Space Normals has no earlier model"); + assert!(execute(&mut session, "effect.set", &json!({"effect": position, "topBottomBlend": "overlay"})).is_err()); + assert_eq!(generator(&session, position).section, SectionParameters::defaults(GeneratorKind::Position), "a refused edit changes nothing"); + + assert!(!section_key_applies(GeneratorKind::Position, "sectionBlur")); + assert!(section_key_applies(GeneratorKind::WorldSpaceNormals, "rightLeftBlend")); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b3a87d44..44effae5 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -36,6 +36,7 @@ mod filters; mod folder_contents; mod frame_selection; mod generator_inputs; +mod generator_sections; mod generator_swap; mod generator_wear; mod gradient_map; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 54a2178e..e9df3bba 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,7 +4,8 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, Source, WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, SectionParameters, Source, + WearParameters, }; use crate::TextureCraftApp; @@ -35,9 +36,12 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); } else { global_adjustments(app, ui, id, generator); - ramp_parameters(app, ui, id, generator); - if generator.kind == GeneratorKind::Curvature { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + 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 + if let Some(defaults) = SectionParameters::defaults(generator.kind) { + section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); } } if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { @@ -51,9 +55,9 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer }); }); }); - if !generator.kind.inputs().is_empty() { + if !inputs_in_use(generator).is_empty() { section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { - for map in generator.kind.inputs() { + for map in inputs_in_use(generator) { input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); } }); @@ -91,6 +95,12 @@ 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 +fn inputs_in_use(generator: &Generator) -> &'static [BakedMap] { + let reads_geometry = generator.on_earlier_model() && generator.kind == GeneratorKind::Position; + if reads_geometry { &[] } else { generator.kind.inputs() } +} + /// What a generator kind makes, its category and its tags (read only). fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); @@ -103,6 +113,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::AmbientOcclusion => (tr("Occluded areas."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]), GeneratorKind::Position => (tr("A gradient across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), GeneratorKind::Direction => (tr("Surfaces facing a light."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + GeneratorKind::WorldSpaceNormals => (tr("Surfaces facing along the world's axes."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), }; // Wrapped rows: a long line must not widen the panel past its edge @@ -169,7 +180,7 @@ fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: Outpu /// Global invert, blur, balance and contrast: what every generator applies to its finished value. fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { let (mut invert, mut global) = (generator.invert, generator.global); - let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false); + let invert_edit = true_false(ui, tr("Global invert"), &mut invert).then_some(false); let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); @@ -299,7 +310,7 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let defaults = Generator::new(kind); - let mut params = json!({ + let params = json!({ "effect": id, "seed": defaults.seed, "invert": defaults.invert, @@ -309,10 +320,12 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { "microAnchor": null, }); - // A wear generator restores its wear controls only: the earlier model's keys would move it back onto that model - let own = match &defaults.wear { - Some(wear) => wear_params(kind, wear), - None => json!({ + // 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!({ "level": defaults.level, "softness": defaults.softness, "noise": defaults.noise_amount, @@ -324,9 +337,7 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { "contrast": defaults.global.contrast, }), }; - if let (Some(params), Value::Object(own)) = (params.as_object_mut(), own) { - params.extend(own); - } + let mut params = merged(params, own); if let (None, Some(detail)) = (&defaults.wear, defaults.detail) { params["mode"] = json!(format!("{:?}", detail.mode)); params["sizes"] = json!(detail.weights); @@ -334,9 +345,99 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { params } +/// The keys of `extra` added to the object `params` +fn merged(mut params: Value, extra: Value) -> Value { + if let (Some(params), Value::Object(extra)) = (params.as_object_mut(), extra) { + params.extend(extra); + } + params +} + +/// The section controls of generator effect `id` under the kind's own heading, showing `shown` +fn section_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, shown: SectionParameters) { + let kind = generator.kind; + let title = match kind { + GeneratorKind::Curvature => tr("Curvature"), + GeneratorKind::AmbientOcclusion => tr("Ambient occlusion"), + GeneratorKind::Position => tr("Position"), + _ => tr("World space normal"), + }; + section(ui, "generator_section", title, true, |ui| { + let mut edited = shown; + let mut edit = true_false(ui, tr("Invert"), &mut edited.invert).then_some(false); + if kind == GeneratorKind::Curvature { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + if SectionParameters::has_blur(kind) { + edit = edit.or(slider_edit(ui, tr("Blur"), &mut edited.blur, SectionParameters::BLUR_RANGE, 2)); + } + if SectionParameters::has_balance(kind) { + edit = edit.or(slider_edit(ui, tr("Balance"), &mut edited.balance, 0.0..=1.0, 2)); + } + edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); + if SectionParameters::has_brightness(kind) { + edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, SectionParameters::BRIGHTNESS_RANGE, 2)); + } + if SectionParameters::has_axes(kind) { + let titles = [tr("Right to left"), tr("Top to bottom"), tr("Front to back")]; + for (index, (axis, title)) in edited.axes.iter_mut().zip(titles).enumerate() { + // Each axis's dropdown needs its own id: the dropdown's id comes from its label + ui.push_id(("generator_axis", index), |ui| { + section(ui, "generator_axis", title, true, |ui| { + edit = edit.or(true_false(ui, tr("Invert"), &mut axis.invert).then_some(false)); + combo(ui, tr("Blending mode"), axis_blend_label(axis.blend), |ui| { + for blend in AxisBlend::ALL { + if ui.selectable_label(blend == axis.blend, axis_blend_label(blend)).clicked() { + axis.blend = blend; + edit = Some(false); + } + } + }); + }); + edit = edit.or(slider_edit(ui, title, &mut axis.weight, 0.0..=1.0, 2)); + }); + } + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), section_params(kind, &edited))); + } + }); +} + +/// The `effect.set` params that set every section control a generator of `kind` has to `section` +fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { + let mut params = json!({ + "sectionInvert": section.invert, + "sectionBlur": section.blur, + "sectionBalance": section.balance, + "sectionContrast": section.contrast, + "sectionBrightness": section.brightness, + }); + if let Some(params) = params.as_object_mut() { + for (name, axis) in ["rightLeft", "topBottom", "frontBack"].into_iter().zip(§ion.axes) { + params.insert(format!("{name}Invert"), json!(axis.invert)); + params.insert(format!("{name}Blend"), json!(axis.blend.id())); + params.insert(format!("{name}Weight"), json!(axis.weight)); + } + params.retain(|key, _| texturecraft_engine::mask_cmds::section_key_applies(kind, key)); + } + params +} + +/// The translated name of axis blending mode `blend` +fn axis_blend_label(blend: AxisBlend) -> &'static str { + match blend { + AxisBlend::Normal => tr("Normal"), + AxisBlend::Add => tr("Linear Dodge (Add)"), + AxisBlend::Subtract => tr("Subtract"), + AxisBlend::Multiply => tr("Multiply"), + AxisBlend::AddSub => tr("Add/Sub"), + AxisBlend::Max => tr("Max (Lighten)"), + } +} + /// 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 tokens = Tokens::get(ui.ctx()); let shown = detail.cloned().unwrap_or_default(); combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { for mode in CurvatureMode::ALL { @@ -346,18 +447,15 @@ fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, } }); - ui.label(caption(tr("Detail sizes"))); + let names = [tr("Sharp"), tr("Fine"), tr("Soft"), tr("Medium"), tr("Large"), tr("Big"), tr("Huge")]; let mut weights = shown.weights; let mut edit = None; - for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { - edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + for (weight, name) in weights.iter_mut().zip(names) { + edit = edit.or(slider_edit(ui, name, weight, 0.0..=1.0, 2)); } if let Some(merge) = edit { app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); } - if detail.is_none() { - ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tokens.text_dim)); - } } /// The translated name of curvature mode `mode`. @@ -365,8 +463,8 @@ fn curvature_mode_label(mode: CurvatureMode) -> &'static str { match mode { CurvatureMode::Edges => tr("Edges"), CurvatureMode::Cavities => tr("Cavities"), - CurvatureMode::Both => tr("Edges and cavities"), - CurvatureMode::Raw => tr("Raw curvature"), + CurvatureMode::Both => tr("Dual"), + CurvatureMode::Raw => tr("Unprocessed"), } } diff --git a/crates/ui-egui/tests/it/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs index a5b321bc..aae768dc 100644 --- a/crates/ui-egui/tests/it/curvature_generator.rs +++ b/crates/ui-egui/tests/it/curvature_generator.rs @@ -26,10 +26,20 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { (harness, LayerId(effect)) } +/// The name the panel's Mode dropdown gives `mode` +fn mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => "Edges", + CurvatureMode::Cavities => "Cavities", + CurvatureMode::Both => "Dual", + CurvatureMode::Raw => "Unprocessed", + } +} + fn select_mode(harness: &mut Harness<'_, TextureCraftApp>, current: CurvatureMode, next: CurvatureMode) { - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(current.label())).unwrap().click(); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(mode_label(current))).unwrap().click(); harness.run_steps(2); - harness.get_by_label(next.label()).click(); + harness.get_by_label(mode_label(next)).click(); harness.run_steps(4); } @@ -44,9 +54,9 @@ fn mode_and_detail_controls_apply_and_undo() { assert_eq!(detail(&harness).mode, CurvatureMode::Cavities); let previous = detail(&harness); let history = harness.state().session.history_labels().len(); - harness.get_by_label("8 px").scroll_to_me(); + harness.get_by_label("Large").scroll_to_me(); harness.run_steps(3); - let label = harness.get_by_label("8 px").rect(); + let label = harness.get_by_label("Large").rect(); let start = egui::pos2(label.left() + 20.0, label.bottom() + 10.0); let end = start + egui::vec2(100.0, 0.0); harness.drag_at(start); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index b53f5012..edf21484 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::Queryable; use serde_json::json; -use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, Source, WearParameters}; +use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -141,6 +141,67 @@ fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { assert!(generator(&harness, effect).inputs.is_empty()); } +/// How many nodes carry `label` +fn count(harness: &Harness<'_, TextureCraftApp>, label: &str) -> usize { + harness.query_all_by_label(label).count() +} + +#[test] +fn each_kind_shows_its_section_rows_and_no_earlier_ones() { + let rows = [ + ("curvature", &["Sharp", "Huge", "Brightness", "Global contrast"][..], &["Balance", "Blending mode", "Level"][..]), + ("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"][..]), + ]; + for (kind, shown, hidden) in rows { + let (harness, _) = harness_with(false, json!({"generator": kind})); + for label in shown { + assert!(count(&harness, label) > 0, "{kind} shows {label}"); + } + for label in hidden { + assert_eq!(count(&harness, label), 0, "{kind} hides {label}"); + } + } + + let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); + assert_eq!(count(&harness, "Blending mode"), 3); + 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"); +} + +#[test] +fn each_axis_has_its_own_blending_mode_dropdown() { + let (mut harness, effect) = harness_with(false, json!({"generator": "worldSpaceNormals"})); + let added = |harness: &Harness<'_, TextureCraftApp>| { + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).count() + }; + assert_eq!(added(&harness), 3); + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Multiply").click(); + harness.run_steps(3); + + let axes = generator(&harness, effect).section.unwrap().axes; + assert_eq!(axes.map(|axis| axis.blend), [AxisBlend::Add, AxisBlend::Add, AxisBlend::Multiply], "only front to back changed"); +} + +#[test] +fn a_section_control_moves_an_earlier_generator_onto_the_section_controls() { + let (mut harness, effect) = harness_with(false, json!({"generator": "position", "level": 0.4})); + assert_eq!(generator(&harness, effect).section, None); + + drag_slider(&mut harness, "Balance"); + + let section = generator(&harness, effect).section.expect("on the section controls now"); + let defaults = SectionParameters::defaults(GeneratorKind::Position).unwrap(); + assert_ne!(section.balance, defaults.balance, "the drag set the balance"); + assert_eq!(SectionParameters { balance: defaults.balance, ..section }, defaults, "the other controls start at their defaults"); + assert_eq!(count(&harness, "Level"), 0, "the earlier rows are gone"); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -185,3 +246,15 @@ fn wear_panel_snapshots() { harness.render().unwrap().save(directory.join(format!("wear-panel-{kind}.png"))).unwrap(); } } + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_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"] { + 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(); + } +}