diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index cdca3b83..dd440224 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -165,7 +165,7 @@ impl StackKey { match &effect.kind { EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), - EffectKind::Generator(generator) => generator.inputs.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::Generator(generator) => generator.sources().flat_map(Source::images).for_each(&mut record_image_name), EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)), _ => {} } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b0ae6b29..2b0500a7 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -40,6 +40,7 @@ use crate::sections; use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; +use crate::texture_layer; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; use crate::wear; use crate::wear_inputs::WearInputs; @@ -1657,7 +1658,7 @@ fn filter_region( _ => None, }; let components = match job { - Job::Mask(_) if generator.is_some() => 2, + Job::Mask(_) if generator.is_some() => GENERATOR_STAGE_COMPONENTS, Job::Mask(_) => 1, Job::Content(_) => 4, }; @@ -1727,7 +1728,8 @@ fn filter_region( let value = match (&mask, nodes.first()) { (Some(mask_stack), _) => { let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); - [texel.mask(mask_stack), ramp, 0.0, 0.0] + let texture = generator.and_then(|(generator, _)| texel.generator_texture(generator)).unwrap_or(0.0); + [texel.mask(mask_stack), ramp, texture, 0.0] } (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], @@ -1943,7 +1945,13 @@ fn filter_region( Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } -/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +/// What a generator's texture reads with nothing in its slot +const EMPTY_TEXTURE_SLOT: Source = Source::Uniform([0.0; 3]); + +/// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray +const GENERATOR_STAGE_COMPONENTS: usize = 3; + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp, texture gray) per texel, sizes in texels per side fn generator_region( generator: &Generator, blend: BlendMode, @@ -1954,7 +1962,7 @@ fn generator_region( (uv_tile, texture_set): (u32, u32), ) -> Vec { let (columns, rows) = (width as usize, height as usize); - let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + let mut ramps: Vec = stack.par_chunks(GENERATOR_STAGE_COMPONENTS).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); // Coarser than the UV tile: averaged over cells, then the blur around them let cell = generator.resolution.cell(uv_tile, texture_set) as usize; @@ -1968,11 +1976,18 @@ fn generator_region( ramps.par_iter_mut().for_each(|signal| *signal = sections::adjusted(generator.kind, §ion, *signal)); } + // The texture blends over the adjusted signal, before the global blur + if let Some(texture) = generator.texture_in_use() { + ramps.par_iter_mut().zip(stack.par_chunks(GENERATOR_STAGE_COMPONENTS)).for_each(|(signal, texel)| { + *signal = texture_layer::blended_over(texture, *signal, texel.get(2).copied().unwrap_or(0.0)); + }); + } + 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) + .par_chunks(GENERATOR_STAGE_COMPONENTS) .zip(ramps.par_iter()) .map(|(texel, ramp)| { let below = texel.first().copied().unwrap_or(0.0); @@ -3467,7 +3482,38 @@ impl<'a, 'b> Texel<'a, 'b> { fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let ramp = self.generator_ramp(generator, curvature_sizes); let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); - finish_generator(generator, adjusted) + let textured = match (generator.texture_in_use(), self.generator_texture(generator)) { + (Some(texture), Some(gray)) => texture_layer::blended_over(texture, adjusted, gray), + _ => adjusted, + }; + finish_generator(generator, textured) + } + + /// The gray of the generator's texture at this texel (None when it blends no texture) + fn generator_texture(&mut self, generator: &Generator) -> Option { + let texture = generator.texture_in_use()?; + let rgb = match texture.source.as_ref().unwrap_or(&EMPTY_TEXTURE_SLOT) { + Source::Image { name, .. } => { + let image = self.inp.images.get(name)?.clone(); + let read = |coordinates: Vec2| { + let [red, green, blue, _] = image.sample(coordinates.x, coordinates.y); + Vec3::new(red, green, blue) + }; + if texture.triplanar { + let normal = self + .generator_input_color(generator, BakedMap::WorldNormal) + .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let weights = texture_layer::triplanar_weights(texture, normal); + let coordinates = texture_layer::triplanar_coordinates(texture, self.bounds_position()); + weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight).to_array() + } else { + read(texture_layer::uv_coordinates(texture, self.coords().uv)).to_array() + } + } + // A value or an anchor reads the same wherever it is projected + other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + }; + Some(texture_layer::texture_gray(texture, rgb)) } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a2369743..3c921ff9 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -42,6 +42,7 @@ mod slope_texel; mod soft_box; pub mod solo; pub mod store; +mod texture_layer; pub mod thumb; pub mod tile_length; mod tile_pattern; diff --git a/crates/compose/src/texture_layer.rs b/crates/compose/src/texture_layer.rs new file mode 100644 index 00000000..95c40fa3 --- /dev/null +++ b/crates/compose/src/texture_layer.rs @@ -0,0 +1,150 @@ +//! A generator's texture (Use Texture): where it is read, how it turns gray and how it blends over the signal + +use texturecraft_core::{TextureBlend, TextureLayer}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +/// Exponent of the triplanar weights per unit of `1 / (1 − triplanar contrast)`: contrast 0 weighs the axes by the normal itself, 0.5 by its cube +const TRIPLANAR_SHARPNESS_POWER: f32 = 1.58; + +/// Smallest normal component still dividing the weights, so a zero normal weighs the axes evenly +const MIN_NORMAL_COMPONENT: f32 = 1e-6; + +/// Where the texture is read in UV: scaled about the centre of the UV square +pub(crate) fn uv_coordinates(texture: &TextureLayer, uv: Vec2) -> Vec2 { + (uv - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5) +} + +/// Where the texture is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1), scaled about their centre +pub(crate) fn triplanar_coordinates(texture: &TextureLayer, position: Vec3) -> [Vec2; 3] { + let scaled = |u: f32, v: f32| (Vec2::new(u, v) - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5); + [scaled(-position.z, position.y), scaled(position.x, position.z), scaled(position.x, position.y)] +} + +/// How much each projection (facing X, Y and Z) counts for a surface facing `normal`, summing to 1 +pub(crate) fn triplanar_weights(texture: &TextureLayer, normal: Vec3) -> [f32; 3] { + let contrast = texture.triplanar_contrast.clamp(*TextureLayer::TRIPLANAR_CONTRAST_RANGE.start(), *TextureLayer::TRIPLANAR_CONTRAST_RANGE.end()); + let sharpness = (1.0 - contrast).max(f32::EPSILON).powf(-TRIPLANAR_SHARPNESS_POWER); + let facing = normal.abs(); + let largest = facing.max_element().max(MIN_NORMAL_COMPONENT); + let weights = (facing / largest).powf(sharpness); + let total = weights.x + weights.y + weights.z; + if total > 0.0 { (weights / total).to_array() } else { [1.0 / 3.0; 3] } +} + +/// The texture's gray from its color: converted, inverted, contrasted, then brightened +pub(crate) fn texture_gray(texture: &TextureLayer, rgb: [f32; 3]) -> f32 { + let gray = texture.grayscale.gray(rgb).clamp(0.0, 1.0); + let gray = if texture.invert { 1.0 - gray } else { gray }; + + let contrast = texture.contrast.clamp(-1.0, 1.0); + let gray = if contrast > 0.0 { + let range = (1.0 - contrast).max(f32::EPSILON); + ((gray - 0.5) / range + 0.5).clamp(0.0, 1.0) + } else { + (gray - 0.5) * (1.0 + contrast) + 0.5 + }; + + let brightness = texture.brightness.clamp(-1.0, 1.0); + if brightness > 0.0 { gray + brightness * (1.0 - gray) } else { gray * (1.0 + brightness) } +} + +/// `gray` (the texture) blended over `signal` by the texture's blending mode and opacity +pub(crate) fn blended_over(texture: &TextureLayer, signal: f32, gray: f32) -> f32 { + let blend = match texture.blend { + TextureBlend::Normal => gray, + TextureBlend::Add => signal + gray, + TextureBlend::Subtract => signal - gray, + TextureBlend::Multiply => signal * gray, + TextureBlend::AddSub => signal + 2.0 * gray - 1.0, + TextureBlend::Max => signal.max(gray), + TextureBlend::Min => signal.min(gray), + TextureBlend::Overlay => { + if signal < 0.5 { + 2.0 * signal * gray + } else { + 1.0 - 2.0 * (1.0 - signal) * (1.0 - gray) + } + } + TextureBlend::Screen => 1.0 - (1.0 - signal) * (1.0 - gray), + TextureBlend::SoftLight => { + if gray < 0.5 { + 2.0 * signal * gray + signal * signal * (1.0 - 2.0 * gray) + } else { + 2.0 * signal * (1.0 - gray) + signal.max(0.0).sqrt() * (2.0 * gray - 1.0) + } + } + }; + let opacity = texture.opacity.clamp(0.0, 1.0); + (signal + (blend - signal) * opacity).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::GeneratorGrayscale; + + fn texture() -> TextureLayer { + TextureLayer { enabled: true, opacity: 1.0, ..TextureLayer::default() } + } + + #[test] + fn overlay_at_full_opacity_darkens_darks_and_lightens_lights() { + let texture = texture(); + assert!((blended_over(&texture, 0.25, 0.5) - 0.25).abs() < 1e-6, "mid gray leaves a dark signal unchanged"); + assert!(blended_over(&texture, 0.25, 0.2) < 0.25); + assert!(blended_over(&texture, 0.75, 0.8) > 0.75); + } + + #[test] + fn opacity_zero_leaves_the_signal() { + let texture = TextureLayer { opacity: 0.0, blend: TextureBlend::Normal, ..texture() }; + assert_eq!(blended_over(&texture, 0.3, 0.9), 0.3); + } + + #[test] + fn every_blend_stays_in_range() { + for blend in TextureBlend::ALL { + let texture = TextureLayer { blend, ..texture() }; + for signal in [0.0, 0.3, 0.5, 1.0] { + for gray in [0.0, 0.4, 1.0] { + let value = blended_over(&texture, signal, gray); + assert!((0.0..=1.0).contains(&value), "{blend:?} {signal} {gray} -> {value}"); + } + } + } + } + + #[test] + fn gray_is_converted_then_inverted_contrasted_and_brightened() { + let red = [1.0, 0.0, 0.0]; + assert_eq!(texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Red, ..texture() }, red), 1.0); + assert_eq!(texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Green, ..texture() }, red), 0.0); + assert!((texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Desaturation, ..texture() }, red) - 0.5).abs() < 1e-6); + let inverted = TextureLayer { grayscale: GeneratorGrayscale::Red, invert: true, ..texture() }; + assert_eq!(texture_gray(&inverted, red), 0.0); + let contrasted = TextureLayer { contrast: 0.5, ..texture() }; + assert!((texture_gray(&contrasted, [0.6; 3]) - 0.7).abs() < 1e-5, "contrast 0.5 doubles the distance from the middle"); + let flattened = TextureLayer { contrast: -1.0, ..texture() }; + assert!((texture_gray(&flattened, [0.9; 3]) - 0.5).abs() < 1e-6, "contrast −1 is flat gray"); + let brightened = TextureLayer { brightness: 0.5, ..texture() }; + assert!((texture_gray(&brightened, [0.4; 3]) - 0.7).abs() < 1e-6); + } + + #[test] + fn triplanar_weights_follow_the_normal_and_sharpen_with_contrast() { + let along_y = triplanar_weights(&texture(), Vec3::Y); + assert!((along_y[1] - 1.0).abs() < 1e-6); + let diagonal = Vec3::new(1.0, 0.5, 0.0).normalize(); + let soft = triplanar_weights(&TextureLayer { triplanar_contrast: 0.001, ..texture() }, diagonal); + let hard = triplanar_weights(&TextureLayer { triplanar_contrast: 0.9, ..texture() }, diagonal); + assert!(hard[0] > soft[0] && hard[1] < soft[1]); + assert!((soft.iter().sum::() - 1.0).abs() < 1e-5); + } + + #[test] + fn scale_is_about_the_centre() { + let texture = TextureLayer { scale: 2.0, ..texture() }; + assert_eq!(uv_coordinates(&texture, Vec2::splat(0.5)), Vec2::splat(0.5)); + assert_eq!(uv_coordinates(&texture, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0)); + } +} diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 7a96a5f9..dac833d1 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -1270,3 +1270,41 @@ fn a_folder_thumbnail_reads_compare_inputs_from_its_backdrop() { assert!(thumbnail.rgba[center] > thumbnail.rgba[center + 2], "visible red child"); } + +#[test] +fn replacing_a_generator_texture_image_invalidates_the_cached_stack() { + use std::sync::Arc; + use texturecraft_compose::{ImageRes, ImageStore}; + use texturecraft_core::{TextureBlend, TextureLayer}; + + let mut fixture = fixture(); + let hot_layer = heavy_stack(&mut fixture); + let texture = TextureLayer { enabled: true, source: Some(Source::image("grunge")), opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(effect(&mut fixture, EffectKind::Generator(Generator { texture: Some(texture), ..Generator::new(GeneratorKind::AmbientOcclusion) }))); + let textured = add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Clouds, 0.0, 1.0))]), Some(mask)); + let stack = &mut fixture.project.texture_sets[0].stack; + stack.retain(|id| *id != textured); + stack.insert(0, textured); + + let image_with_value = |value| Arc::new(ImageRes::new(4, 4, vec![[value, value, value, 1.0]; 16], false)); + let mut images = ImageStore::default(); + let baked = Default::default(); + let tiles = all_tiles(RES, RES); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot_layer)); + let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + + for (stage, value) in [("dark", 0.1), ("light", 0.9)] { + images.insert("grunge".into(), image_with_value(value)); + let input = inputs(&fixture, 0, &images, &baked); + composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + let retained = cache.len() - 1; + composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, 0, "{stage}: a new texture image drops the tiles cached below the hot layer"); + + let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); + } +} diff --git a/crates/compose/tests/generator_texture.rs b/crates/compose/tests/generator_texture.rs new file mode 100644 index 00000000..3800ccb6 --- /dev/null +++ b/crates/compose/tests/generator_texture.rs @@ -0,0 +1,218 @@ +//! A generator's texture (Use Texture) on a sphere: read in UV or triplanar, turned gray, blended over the signal before the global controls + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes, ImageStore, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorGrayscale, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, + SectionParameters, Source, TextureBlend, TextureLayer, 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; + +/// The ambient occlusion every texel of the sphere reads +const OCCLUSION: f32 = 0.3; + +/// Width of the split image: its left half black, its right half white +const SPLIT_WIDTH: u32 = 64; + +/// How far from a split's edge (in UV) a texel must sit to read one side only +const SPLIT_MARGIN: f32 = 0.05; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, + images: ImageStore, +} + +/// A unit sphere with a white fill layer, uniform occlusion and the images `flat` (one color) and `split` (black left, white right) +fn fixture(flat: [f32; 3]) -> 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(); + let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![OCCLUSION; (RES * RES) as usize]))].into() }; + + let [red, green, blue] = flat; + let flat = ImageRes::new(4, 4, vec![[red, green, blue, 1.0]; 16], false); + let split_texel = |index: u32| if index % SPLIT_WIDTH < SPLIT_WIDTH / 2 { [0.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }; + let split = ImageRes::new(SPLIT_WIDTH, SPLIT_WIDTH, (0..SPLIT_WIDTH * SPLIT_WIDTH).map(split_texel).collect(), false); + let images = [("flat".to_string(), Arc::new(flat)), ("split".to_string(), Arc::new(split))].into(); + Fixture { project, mesh, gbuf, layer, baked, images } +} + +/// A covered texel with its UV, world position and normal +struct SurfacePoint { + texel: (u32, u32), + uv: [f32; 2], + position: Vec3, + normal: Vec3, +} + +/// Every covered texel +fn surface(fixture: &Fixture) -> Vec { + (0..RES * RES) + .filter_map(|index| { + let texel = (index % RES, index / RES); + let uv = [(texel.0 as f32 + 0.5) / RES as f32, (texel.1 as f32 + 0.5) / RES as f32]; + fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| SurfacePoint { texel, uv, position: surface.pos, normal: 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 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: &fixture.images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// Ambient Occlusion on its section controls with `texture` reading image `image` +fn occlusion_with(image: &str, texture: TextureLayer) -> Generator { + Generator { texture: Some(TextureLayer { source: Some(Source::image(image)), ..texture }), ..Generator::new(GeneratorKind::AmbientOcclusion) } +} + +/// A texture turned on at full opacity, replacing the signal +fn replacing() -> TextureLayer { + TextureLayer { enabled: true, opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() } +} + +fn assert_all(actual: &[f32], expected: f32, what: &str) { + for (index, actual) in actual.iter().enumerate() { + assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); + } +} + +#[test] +fn a_texture_turned_off_or_at_opacity_zero_leaves_the_signal() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + + assert_all(&mask(&mut fixture, occlusion_with("flat", TextureLayer { enabled: false, ..replacing() }), &texels), OCCLUSION, "turned off"); + assert_all(&mask(&mut fixture, occlusion_with("flat", TextureLayer { opacity: 0.0, ..replacing() }), &texels), OCCLUSION, "opacity 0"); + assert_all(&mask(&mut fixture, occlusion_with("flat", TextureLayer::default()), &texels), OCCLUSION, "the reference's defaults"); +} + +#[test] +fn an_empty_texture_slot_blends_black() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let empty = Generator { texture: Some(TextureLayer { opacity: 0.5, ..replacing() }), ..Generator::new(GeneratorKind::AmbientOcclusion) }; + assert_all(&mask(&mut fixture, empty, &texels), OCCLUSION * 0.5, "half way to black"); +} + +#[test] +fn a_texture_needs_the_section_controls() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let earlier = Generator { section: None, global: Default::default(), ..occlusion_with("flat", replacing()) }; + let without = Generator { texture: None, ..earlier.clone() }; + assert_eq!(mask(&mut fixture, earlier, &texels), mask(&mut fixture, without, &texels)); +} + +#[test] +fn the_texture_turns_gray_by_its_conversion() { + let mut fixture = fixture([1.0, 0.25, 0.0]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + for (grayscale, expected) in [ + (GeneratorGrayscale::Average, 1.25 / 3.0), + (GeneratorGrayscale::Red, 1.0), + (GeneratorGrayscale::Green, 0.25), + (GeneratorGrayscale::Desaturation, 0.5), + (GeneratorGrayscale::Luma, 0.299 + 0.587 * 0.25), + ] { + let generator = occlusion_with("flat", TextureLayer { grayscale, ..replacing() }); + assert_all(&mask(&mut fixture, generator, &texels), expected, &format!("{grayscale:?}")); + } +} + +#[test] +fn overlay_with_a_mid_gray_texture_doubles_a_dark_signal_times_the_gray() { + let mut fixture = fixture([0.4; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let generator = occlusion_with("flat", TextureLayer { blend: TextureBlend::Overlay, opacity: 0.5, ..replacing() }); + let overlay = 2.0 * OCCLUSION * 0.4; + assert_all(&mask(&mut fixture, generator, &texels), OCCLUSION + (overlay - OCCLUSION) * 0.5, "overlay at half opacity"); +} + +#[test] +fn the_texture_blends_after_the_section_controls_and_before_the_global_ones() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + + let mut section_inverted = occlusion_with("flat", replacing()); + section_inverted.section = Some(SectionParameters { invert: true, ..section_inverted.section.unwrap() }); + assert_all(&mask(&mut fixture, section_inverted, &texels), 0.6, "the texture replaces the inverted section"); + + let globally_inverted = Generator { invert: true, ..occlusion_with("flat", replacing()) }; + assert_all(&mask(&mut fixture, globally_inverted, &texels), 0.4, "the global invert flips the texture"); + + let mut blurred = occlusion_with("flat", replacing()); + blurred.section = Some(SectionParameters { blur: 2.0, ..blurred.section.unwrap() }); + assert_all(&mask(&mut fixture, blurred, &texels), 0.6, "with the section blur (computed over a region)"); +} + +#[test] +fn uv_scale_repeats_the_texture_about_the_centre() { + let mut fixture = fixture([0.0; 3]); + let points = surface(&fixture); + let side = |u: f32| (u.rem_euclid(1.0) >= 0.5) as u8 as f32; + for scale in [1.0, 2.0, 3.0] { + let read_at = |u: f32| (u - 0.5) * scale + 0.5; + let clear: Vec<_> = points + .iter() + .filter(|point| { + let u = read_at(point.uv[0]).rem_euclid(1.0); + [0.0, 0.5, 1.0].iter().all(|edge| (u - edge).abs() > SPLIT_MARGIN * scale) + }) + .collect(); + let texels: Vec<_> = clear.iter().map(|point| point.texel).collect(); + let values = mask(&mut fixture, occlusion_with("split", TextureLayer { scale, ..replacing() }), &texels); + for (point, value) in clear.iter().zip(values) { + let expected = side(read_at(point.uv[0])); + assert!((value - expected).abs() < TOLERANCE, "scale {scale} at u {}: {value}, expected {expected}", point.uv[0]); + } + } +} + +#[test] +fn triplanar_reads_the_top_from_the_plane_facing_up() { + let mut fixture = fixture([0.0; 3]); + let (low, high) = fixture.mesh.bounds(); + let across = |position: Vec3| (position.x - low.x) / (high.x - low.x); + let top: Vec<_> = surface(&fixture).into_iter().filter(|point| point.normal.y > 0.95 && (across(point.position) - 0.5).abs() > SPLIT_MARGIN).collect(); + assert!(!top.is_empty()); + + let texels: Vec<_> = top.iter().map(|point| point.texel).collect(); + let sharp = TextureLayer { triplanar: true, triplanar_contrast: 1.0, ..replacing() }; + let values = mask(&mut fixture, occlusion_with("split", sharp), &texels); + for (point, value) in top.iter().zip(values) { + let expected = if across(point.position) >= 0.5 { 1.0 } else { 0.0 }; + assert!((value - expected).abs() < TOLERANCE, "at x {}: {value}, expected {expected}", across(point.position)); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 663efd1f..a169516b 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -20,6 +20,7 @@ mod decal_flip; mod decal_symmetry; mod filtering; mod generator_global; +mod generator_grayscale; mod light_parameters; mod micro_detail; mod output_resolution; @@ -27,6 +28,8 @@ mod resolution_mode; mod sampling; mod scale_mode; mod section_parameters; +mod texture_blend; +mod texture_layer; mod tile_blending; mod tile_generator; mod tile_input_distribution; @@ -45,6 +48,7 @@ pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; +pub use generator_grayscale::GeneratorGrayscale; pub use light_parameters::LightParameters; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; @@ -52,6 +56,8 @@ pub use resolution_mode::ResolutionMode; pub use sampling::Sampling; pub use scale_mode::ScaleMode; pub use section_parameters::SectionParameters; +pub use texture_blend::TextureBlend; +pub use texture_layer::TextureLayer; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; @@ -1062,6 +1068,9 @@ pub struct Generator { /// The Light generator's controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub light: Option, + /// The texture blended over the signal on the section controls (None: Use Texture never touched, as saved before it existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub texture: Option, } impl Generator { @@ -1094,6 +1103,16 @@ impl Generator { if reads_geometry { &[] } else { self.kind.inputs() } } + /// The texture the generator blends over its signal: only on the section controls, turned on with some opacity + pub fn texture_in_use(&self) -> Option<&TextureLayer> { + self.texture.as_ref().filter(|texture| texture.in_use() && self.section_controls().is_some()) + } + + /// Everything the generator reads instead of its mesh maps: its inputs, then its texture + pub fn sources(&self) -> impl Iterator { + self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())) + } + /// 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.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear @@ -1130,6 +1149,7 @@ impl Generator { wear: WearParameters::defaults(kind), section: SectionParameters::defaults(kind), light: LightParameters::defaults(kind), + texture: None, } } @@ -2103,7 +2123,7 @@ impl EffectKind { EffectKind::Material(fill) => fill.sources.values().any(|source| source.reads_anchor(anchor)), EffectKind::Generator(generator) => { generator.micro.is_some_and(|micro| anchor.is_none_or(|wanted| wanted == micro.anchor)) - || generator.inputs.values().any(|source| source.reads_anchor(anchor)) + || generator.sources().any(|source| source.reads_anchor(anchor)) } _ => false, } @@ -2114,7 +2134,7 @@ impl EffectKind { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], EffectKind::Material(fill) => fill.sources.values().collect(), - EffectKind::Generator(generator) => generator.inputs.values().collect(), + EffectKind::Generator(generator) => generator.sources().collect(), _ => Vec::new(), }; let mut anchors: Vec<_> = sources @@ -2137,7 +2157,7 @@ impl EffectKind { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], EffectKind::Material(fill) => fill.sources.values().collect(), - EffectKind::Generator(generator) => generator.inputs.values().collect(), + EffectKind::Generator(generator) => generator.sources().collect(), _ => Vec::new(), }; let id_map = match self { diff --git a/crates/core/src/layer/generator_grayscale.rs b/crates/core/src/layer/generator_grayscale.rs new file mode 100644 index 00000000..01ac149b --- /dev/null +++ b/crates/core/src/layer/generator_grayscale.rs @@ -0,0 +1,81 @@ +use serde::{Deserialize, Serialize}; + +/// How a color texture becomes one gray value +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GeneratorGrayscale { + /// Halfway between the brightest and the darkest channel + Desaturation, + /// The channels weighted by how bright the eye sees them + Luma, + /// The mean of the three channels + #[default] + Average, + Max, + Min, + Red, + Green, + Blue, +} + +impl GeneratorGrayscale { + pub const ALL: [GeneratorGrayscale; 8] = [ + GeneratorGrayscale::Desaturation, + GeneratorGrayscale::Luma, + GeneratorGrayscale::Average, + GeneratorGrayscale::Max, + GeneratorGrayscale::Min, + GeneratorGrayscale::Red, + GeneratorGrayscale::Green, + GeneratorGrayscale::Blue, + ]; + + /// The name the panel shows + pub fn label(self) -> &'static str { + match self { + GeneratorGrayscale::Desaturation => "Desaturation", + GeneratorGrayscale::Luma => "Luma", + GeneratorGrayscale::Average => "Average", + GeneratorGrayscale::Max => "Max", + GeneratorGrayscale::Min => "Min", + GeneratorGrayscale::Red => "Red channel", + GeneratorGrayscale::Green => "Green channel", + GeneratorGrayscale::Blue => "Blue channel", + } + } + + /// The name commands and saved projects use + pub fn id(self) -> &'static str { + match self { + GeneratorGrayscale::Desaturation => "desaturation", + GeneratorGrayscale::Luma => "luma", + GeneratorGrayscale::Average => "average", + GeneratorGrayscale::Max => "max", + GeneratorGrayscale::Min => "min", + GeneratorGrayscale::Red => "red", + GeneratorGrayscale::Green => "green", + GeneratorGrayscale::Blue => "blue", + } + } + + /// The conversion named by its id or its label, in any case + pub fn parse(name: &str) -> Option { + GeneratorGrayscale::ALL.into_iter().find(|mode| mode.id().eq_ignore_ascii_case(name) || mode.label().eq_ignore_ascii_case(name)) + } + + /// The gray of `rgb` + pub fn gray(self, [red, green, blue]: [f32; 3]) -> f32 { + // ITU-R BT.601 weights, the reference's Luma + const LUMA: [f32; 3] = [0.299, 0.587, 0.114]; + match self { + GeneratorGrayscale::Desaturation => (red.max(green).max(blue) + red.min(green).min(blue)) * 0.5, + GeneratorGrayscale::Luma => red * LUMA[0] + green * LUMA[1] + blue * LUMA[2], + GeneratorGrayscale::Average => (red + green + blue) / 3.0, + GeneratorGrayscale::Max => red.max(green).max(blue), + GeneratorGrayscale::Min => red.min(green).min(blue), + GeneratorGrayscale::Red => red, + GeneratorGrayscale::Green => green, + GeneratorGrayscale::Blue => blue, + } + } +} diff --git a/crates/core/src/layer/texture_blend.rs b/crates/core/src/layer/texture_blend.rs new file mode 100644 index 00000000..73c3f3cc --- /dev/null +++ b/crates/core/src/layer/texture_blend.rs @@ -0,0 +1,80 @@ +use serde::{Deserialize, Serialize}; + +/// How a generator's texture combines with its signal +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TextureBlend { + /// The texture replaces the signal + Normal, + /// The texture adds to the signal + Add, + /// The texture is taken from the signal + Subtract, + /// The texture multiplies the signal + Multiply, + /// The texture adds above its middle gray and subtracts below it + AddSub, + /// The brighter of the texture and the signal + Max, + /// The darker of the texture and the signal + Min, + /// The texture darkens the signal's darks and lightens its lights + #[default] + Overlay, + /// The inverse of multiplying the inverses: always lighter + Screen, + /// A gentler overlay led by the texture + SoftLight, +} + +impl TextureBlend { + pub const ALL: [TextureBlend; 10] = [ + TextureBlend::Normal, + TextureBlend::Add, + TextureBlend::Subtract, + TextureBlend::Multiply, + TextureBlend::AddSub, + TextureBlend::Max, + TextureBlend::Min, + TextureBlend::Overlay, + TextureBlend::Screen, + TextureBlend::SoftLight, + ]; + + /// The name the panel shows + pub fn label(self) -> &'static str { + match self { + TextureBlend::Normal => "Normal", + TextureBlend::Add => "Linear Dodge (Add)", + TextureBlend::Subtract => "Subtract", + TextureBlend::Multiply => "Multiply", + TextureBlend::AddSub => "Add/Sub", + TextureBlend::Max => "Max (Lighten)", + TextureBlend::Min => "Min (Darken)", + TextureBlend::Overlay => "Overlay", + TextureBlend::Screen => "Screen", + TextureBlend::SoftLight => "Soft light", + } + } + + /// The name commands and saved projects use + pub fn id(self) -> &'static str { + match self { + TextureBlend::Normal => "normal", + TextureBlend::Add => "add", + TextureBlend::Subtract => "subtract", + TextureBlend::Multiply => "multiply", + TextureBlend::AddSub => "addSub", + TextureBlend::Max => "max", + TextureBlend::Min => "min", + TextureBlend::Overlay => "overlay", + TextureBlend::Screen => "screen", + TextureBlend::SoftLight => "softLight", + } + } + + /// The blend named by its id or its label, in any case + pub fn parse(name: &str) -> Option { + TextureBlend::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/texture_layer.rs b/crates/core/src/layer/texture_layer.rs new file mode 100644 index 00000000..877e0f3d --- /dev/null +++ b/crates/core/src/layer/texture_layer.rs @@ -0,0 +1,76 @@ +use serde::{Deserialize, Serialize}; + +use super::Source; +use super::generator_grayscale::GeneratorGrayscale; +use super::texture_blend::TextureBlend; + +/// A texture a generator blends over its signal (the reference's Use Texture block): read as gray, adjusted, then blended before the global controls +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TextureLayer { + /// Use Texture: off keeps the settings but leaves the signal as it is + pub enabled: bool, + /// What the texture reads (None: an empty slot, uniform black) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + /// How much of the blend shows (0..1) + pub opacity: f32, + pub invert: bool, + pub grayscale: GeneratorGrayscale, + pub blend: TextureBlend, + /// Repeats across the UV square, about its centre ([`TextureLayer::SCALE_RANGE`]) + pub scale: f32, + /// Narrows the texture around its middle (above 0) or flattens it towards gray (below 0) (−1..1) + pub contrast: f32, + /// Lifts the texture towards white (above 0) or black (below 0) (−1..1) + pub brightness: f32, + /// Projected from the world's three axes rather than laid out in UV + pub triplanar: bool, + /// How sharply the three projections meet ([`TextureLayer::TRIPLANAR_CONTRAST_RANGE`]) + pub triplanar_contrast: f32, +} + +impl Default for TextureLayer { + /// The reference app's defaults: off, and at opacity 0 even once turned on + fn default() -> Self { + TextureLayer { + enabled: false, + source: None, + opacity: 0.0, + invert: false, + grayscale: GeneratorGrayscale::default(), + blend: TextureBlend::default(), + scale: 1.0, + contrast: 0.0, + brightness: 0.0, + triplanar: false, + triplanar_contrast: 0.5, + } + } +} + +impl TextureLayer { + pub const SCALE_RANGE: std::ops::RangeInclusive = 0.01..=10.0; + pub const TRIPLANAR_CONTRAST_RANGE: std::ops::RangeInclusive = 0.001..=1.0; + + /// Whether the texture changes the signal: turned on with some opacity (an empty slot blends black) + pub fn in_use(&self) -> bool { + self.enabled && self.opacity > 0.0 + } + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> TextureLayer { + let defaults = TextureLayer::default(); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + TextureLayer { + opacity: within(self.opacity, defaults.opacity, 0.0..=1.0), + scale: within(self.scale, defaults.scale, TextureLayer::SCALE_RANGE), + contrast: within(self.contrast, defaults.contrast, -1.0..=1.0), + brightness: within(self.brightness, defaults.brightness, -1.0..=1.0), + triplanar_contrast: within(self.triplanar_contrast, defaults.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE), + ..self + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c5ff7ec3..b8d53dd9 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -112,9 +112,9 @@ pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, + GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, SectionParameters, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, + Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, 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/inspect.rs b/crates/engine/src/inspect.rs index 09cdaecb..39918d33 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -153,6 +153,9 @@ fn generator_json(generator: &Generator) -> Value { if !generator.inputs.is_empty() { out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::>().into(); } + if let Some(texture) = &generator.texture { + out["texture"] = json!(texture); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 19a61f09..8f67edf9 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, + GeneratorKind, GeneratorGrayscale, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, TextureBlend, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{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), 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), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{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, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id or texture + 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 ), @@ -485,10 +485,38 @@ const AXIS_SUFFIXES: [&str; 3] = ["Invert", "Blend", "Weight"]; /// The Light generator's controls const LIGHT_KEYS: [&str; 5] = ["lightHorizontal", "lightVertical", "highlightGlossiness", "highlightLevel", "lightAttenuation"]; -/// The section controls, the axis keys and the light controls `params` gives +/// The texture controls (Use Texture); the texture itself is the `texture` input +const TEXTURE_KEYS: [&str; 10] = [ + "useTexture", + "textureOpacity", + "textureInvert", + "textureGrayscale", + "textureBlend", + "textureScale", + "textureContrast", + "textureBrightness", + "textureTriplanar", + "textureTriplanarContrast", +]; + +/// The input name of a generator's texture, beside the mesh map ids +const TEXTURE_INPUT: &str = "texture"; + +/// The section controls, the axis keys, the texture controls and the light controls `params` gives (a texture input counts as `texture`) 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().chain(LIGHT_KEYS.iter()).map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() + let mut keys: Vec = SECTION_KEYS + .iter() + .chain(TEXTURE_KEYS.iter()) + .chain(LIGHT_KEYS.iter()) + .map(|key| key.to_string()) + .chain(axis_keys) + .filter(|key| params.get(key).is_some()) + .collect(); + if strp(params, "input") == Some(TEXTURE_INPUT) { + keys.push(TEXTURE_INPUT.to_string()); + } + keys } /// The section and light controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model @@ -597,6 +625,44 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res } } generator.section = Some(section.clamped(kind)); + texture_from(command, params, generator) +} + +/// The texture controls in `params` (the generator is on its section controls already) +fn texture_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + if !TEXTURE_KEYS.iter().any(|key| params.get(*key).is_some()) { + return Ok(()); + } + let mut texture = generator.texture.clone().unwrap_or_default(); + if let Some(enabled) = boolp(params, "useTexture") { + texture.enabled = enabled; + } + for (key, value) in [ + ("textureOpacity", &mut texture.opacity), + ("textureScale", &mut texture.scale), + ("textureContrast", &mut texture.contrast), + ("textureBrightness", &mut texture.brightness), + ("textureTriplanarContrast", &mut texture.triplanar_contrast), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(invert) = boolp(params, "textureInvert") { + texture.invert = invert; + } + if let Some(triplanar) = boolp(params, "textureTriplanar") { + texture.triplanar = triplanar; + } + if let Some(value) = params.get("textureGrayscale") { + let name = value.as_str().ok_or_else(|| bad(command, "`textureGrayscale` must be a string"))?; + texture.grayscale = GeneratorGrayscale::parse(name).ok_or_else(|| bad(command, format!("unknown grayscale conversion `{name}`")))?; + } + if let Some(value) = params.get("textureBlend") { + let name = value.as_str().ok_or_else(|| bad(command, "`textureBlend` must be a string"))?; + texture.blend = TextureBlend::parse(name).ok_or_else(|| bad(command, format!("unknown blending mode `{name}`")))?; + } + generator.texture = Some(texture.clamped()); Ok(()) } @@ -604,7 +670,8 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res 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(), + "sectionInvert" | "sectionContrast" | TEXTURE_INPUT => SectionParameters::defaults(kind).is_some(), + _ if TEXTURE_KEYS.contains(&key) => SectionParameters::defaults(kind).is_some(), "sectionBlur" => SectionParameters::has_blur(kind), "sectionBalance" => SectionParameters::has_balance(kind), "sectionBrightness" => SectionParameters::has_brightness(kind), @@ -736,12 +803,22 @@ fn micro_param(session: &Session, command: &str, reader: LayerId, params: &Value Ok(Some(Some(MicroDetail { anchor, amount }))) } -/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`. -fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { +/// A generator input a command names: a mesh map it reads, or its texture +#[derive(Clone, Copy)] +enum GeneratorInput { + Map(BakedMap), + Texture, +} + +/// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture slot), for a generator on layer `owner` +fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; let Some(name) = params.get("input") else { return Ok(None) }; - let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?; - let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id or `texture`"))?; + let input = match name { + TEXTURE_INPUT => GeneratorInput::Texture, + _ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?), + }; let image = strp(params, "inputImage"); let value = f32p(params, "inputValue"); @@ -762,7 +839,7 @@ fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> R (None, None, None, true) => None, _ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")), }; - Ok(Some((map, source))) + Ok(Some((input, source))) } fn add_generator(session: &mut Session, params: &Value) -> Result { @@ -1060,15 +1137,19 @@ fn set(session: &mut Session, params: &Value) -> Result { if let Some(micro) = micro { generator.micro = micro; } - if let Some((map, source)) = input { - if !generator.inputs_in_use().contains(&map) { - return Err(bad(CMD, format!("this generator does not read a `{}` input", map.id()))); + match input { + Some((GeneratorInput::Map(map), source)) => { + if !generator.inputs_in_use().contains(&map) { + return Err(bad(CMD, format!("this generator does not read a `{}` input", map.id()))); + } + match source { + Some(source) => generator.inputs.insert(map, source), + None => generator.inputs.remove(&map), + }; } - - match source { - Some(source) => generator.inputs.insert(map, source), - None => generator.inputs.remove(&map), - }; + // generator_from refused the texture on kinds without one and moved the generator onto its section controls + Some((GeneratorInput::Texture, source)) => generator.texture.get_or_insert_default().source = source, + None => {} } } _ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")), diff --git a/crates/engine/tests/it/generator_texture.rs b/crates/engine/tests/it/generator_texture.rs new file mode 100644 index 00000000..9d640515 --- /dev/null +++ b/crates/engine/tests/it/generator_texture.rs @@ -0,0 +1,106 @@ +//! A generator's texture (Use Texture) through `effect.add.generator` and `effect.set`: its controls, its image as the `texture` input, and the kinds without one + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Generator, GeneratorGrayscale, LayerId, Source, TextureBlend, TextureLayer}; +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:?}"), + } +} + +/// A gray image resource, by the name it was imported under +fn gray_image(session: &mut Session) -> String { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("grunge.png", bytes).unwrap() +} + +#[test] +fn texture_controls_start_from_the_reference_defaults_and_clamp() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "curvature"})); + assert_eq!(generator(&session, effect).texture, None, "untouched until a texture control is given"); + + let edit = + json!({"effect": effect, "useTexture": true, "textureScale": 40.0, "textureContrast": -3.0, "textureBlend": "Soft light", "textureGrayscale": "red"}); + execute(&mut session, "effect.set", &edit).unwrap(); + let expected = TextureLayer { + enabled: true, + scale: *TextureLayer::SCALE_RANGE.end(), + contrast: -1.0, + blend: TextureBlend::SoftLight, + grayscale: GeneratorGrayscale::Red, + ..TextureLayer::default() + }; + assert_eq!(generator(&session, effect).texture, Some(expected)); + assert_eq!(TextureLayer::default().opacity, 0.0, "the reference starts the texture at opacity 0"); + + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "textureBlend": "dissolve"})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "textureGrayscale": "hue"})).is_err()); +} + +#[test] +fn the_texture_image_is_the_texture_input_and_stays_a_used_resource() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "ambientOcclusion"})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "texture", "inputImage": name})).unwrap(); + let plugged = generator(&session, effect); + assert_eq!(plugged.texture.as_ref().and_then(|texture| texture.source.clone()), Some(Source::image(name.clone()))); + assert!(plugged.inputs.is_empty(), "the texture is not a mesh map input"); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the texture"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "texture", "inputBaked": true})).unwrap(); + assert_eq!(generator(&session, effect).texture.and_then(|texture| texture.source), None, "inputBaked empties the slot"); +} + +#[test] +fn a_texture_moves_an_earlier_generator_onto_its_section_controls() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "position", "level": 0.8})); + assert_eq!(generator(&session, effect).section, None); + + execute(&mut session, "effect.set", &json!({"effect": effect, "textureOpacity": 0.5})).unwrap(); + let moved = generator(&session, effect); + assert!(moved.section.is_some()); + assert_eq!(moved.texture.map(|texture| texture.opacity), Some(0.5)); + + let both = json!({"effect": effect, "useTexture": true, "level": 0.2}); + assert!(execute(&mut session, "effect.set", &both).is_err(), "a texture control and the earlier model at once"); +} + +#[test] +fn kinds_without_a_texture_refuse_its_controls_and_its_input() { + let mut session = session(); + let name = gray_image(&mut session); + for kind in ["dirt", "edgeWear", "fiberGlassEdgeWear", "direction", "thinAreas"] { + let effect = add(&mut session, json!({"generator": kind})); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "useTexture": true})).is_err(), "{kind} useTexture"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "input": "texture", "inputImage": name})).is_err(), "{kind} texture input"); + assert_eq!(generator(&session, effect).texture, None, "{kind}"); + } + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + let effect = add(&mut session, json!({"generator": kind})); + let added = generator(&session, effect); + assert!(section_key_applies(added.kind, "textureTriplanar"), "{kind}"); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 44effae5..140ea6ff 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -38,6 +38,7 @@ mod frame_selection; mod generator_inputs; mod generator_sections; mod generator_swap; +mod generator_texture; mod generator_wear; mod gradient_map; mod high_poly_missed; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 7c6f7258..3cadca28 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,8 +4,8 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, - SectionParameters, Source, WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, GeneratorGrayscale, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, + SectionParameters, Source, TextureBlend, TextureLayer, WearParameters, }; use crate::TextureCraftApp; @@ -52,6 +52,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(generator.kind) { section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); + texture_parameters(app, ui, id, generator.texture.clone().unwrap_or_default()); } if let Some(defaults) = LightParameters::defaults(generator.kind) { light_parameters(app, ui, id, None, defaults); @@ -63,15 +64,19 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.button(tr("Restore defaults")).clicked() { - app.run("effect.set", defaults_of(id, generator.kind)); + app.run("effect.set", defaults_of(id, generator)); } }); }); }); - if !generator.inputs_in_use().is_empty() { + let texture = generator.texture.as_ref().filter(|texture| texture.enabled && SectionParameters::defaults(generator.kind).is_some()); + if !generator.inputs_in_use().is_empty() || texture.is_some() { section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { + if let Some(texture) = texture { + input_slot(app, ui, (layer, id), InputSlot::Texture, texture.source.as_ref(), false); + } for map in generator.inputs_in_use() { - input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail_in_use().is_some()); + input_slot(app, ui, (layer, id), InputSlot::Map(*map), generator.inputs.get(map), generator.detail_in_use().is_some()); } }); } @@ -315,7 +320,8 @@ 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 { +fn defaults_of(id: u64, generator: &Generator) -> Value { + let kind = generator.kind; let defaults = Generator::new(kind); let params = json!({ "effect": id, @@ -332,6 +338,10 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let own = match (&defaults.wear, &defaults.section, &defaults.light) { (Some(wear), _, _) => wear_params(kind, wear), (None, _, Some(light)) => light_params(light), + // The texture's controls only once it has them: its image stays in its slot + (None, Some(section), None) if generator.texture.is_some() => { + merged(merged(section_params(kind, section), global), texture_params(&TextureLayer::default())) + } (None, Some(section), None) => merged(section_params(kind, section), global), (None, None, None) => json!({ "level": defaults.level, @@ -433,6 +443,58 @@ fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { } /// The translated name of axis blending mode `blend` +/// Use Texture and, once it is on, the texture's controls and its opacity +fn texture_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, shown: TextureLayer) { + let mut edited = shown; + let mut edit = true_false(ui, tr("Use texture"), &mut edited.enabled).then_some(false); + if edited.enabled { + section(ui, "generator_texture", tr("Texture"), true, |ui| { + edit = edit.or(true_false(ui, tr("Invert"), &mut edited.invert).then_some(false)); + combo(ui, tr("Grayscale conversion"), tr(edited.grayscale.label()), |ui| { + for mode in GeneratorGrayscale::ALL { + if ui.selectable_label(mode == edited.grayscale, tr(mode.label())).clicked() { + edited.grayscale = mode; + edit = Some(false); + } + } + }); + combo(ui, tr("Blending mode"), tr(edited.blend.label()), |ui| { + for blend in TextureBlend::ALL { + if ui.selectable_label(blend == edited.blend, tr(blend.label())).clicked() { + edited.blend = blend; + edit = Some(false); + } + } + }); + edit = edit.or(slider_edit(ui, tr("Scale"), &mut edited.scale, TextureLayer::SCALE_RANGE, 2)); + edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, -1.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, -1.0..=1.0, 2)); + edit = edit.or(true_false(ui, tr("Triplanar"), &mut edited.triplanar).then_some(false)); + edit = edit.or(slider_edit(ui, tr("Triplanar contrast"), &mut edited.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE, 2)); + }); + edit = edit.or(slider_edit(ui, tr("Texture opacity"), &mut edited.opacity, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), texture_params(&edited))); + } +} + +/// The texture controls as `effect.set` keys (its image is the `texture` input) +fn texture_params(texture: &TextureLayer) -> Value { + json!({ + "useTexture": texture.enabled, + "textureOpacity": texture.opacity, + "textureInvert": texture.invert, + "textureGrayscale": texture.grayscale.id(), + "textureBlend": texture.blend.id(), + "textureScale": texture.scale, + "textureContrast": texture.contrast, + "textureBrightness": texture.brightness, + "textureTriplanar": texture.triplanar, + "textureTriplanarContrast": texture.triplanar_contrast, + }) +} + fn axis_blend_label(blend: AxisBlend) -> &'static str { match blend { AxisBlend::Normal => tr("Normal"), @@ -552,26 +614,62 @@ fn curvature_mode_label(mode: CurvatureMode) -> &'static str { } } -/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again. -fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) { +/// What an image input slot of a generator replaces: a mesh map it reads, or its texture +#[derive(Clone, Copy)] +enum InputSlot { + Map(BakedMap), + Texture, +} + +impl InputSlot { + /// The input's name in `effect.set` + fn id(self) -> &'static str { + match self { + InputSlot::Map(map) => map.id(), + InputSlot::Texture => "texture", + } + } + + fn title(self) -> &'static str { + match self { + InputSlot::Map(map) => tr(baked_map_label(map)), + InputSlot::Texture => tr("Texture"), + } + } + + /// The value a slot set to a uniform value starts at + fn neutral(self) -> f32 { + match self { + InputSlot::Map(map) => map.neutral()[0], + InputSlot::Texture => 0.0, + } + } +} + +/// One image input: what it reads now, a menu to replace it with a value, an anchor point or an image, and a button to empty it +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), slot: InputSlot, source: Option<&Source>, detail_sizes: bool) { let tokens = Tokens::get(ui.ctx()); - let input = map.id(); - let current = match source { - None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), - Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]), - Some(Source::Uniform(_)) => tr("Uniform value").to_string(), - Some(Source::Anchor { anchor, channel, .. }) => anchor_label(app, *anchor, *channel), - Some(Source::Procedural { .. }) => tr("Procedural").to_string(), + let input = slot.id(); + let current = match (source, slot) { + (None, InputSlot::Map(map)) => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + (None, InputSlot::Texture) | (Some(Source::Uniform(_)), _) => tr("Uniform value").to_string(), + (Some(Source::Image { name, .. }), _) => trf("Image: {name}", &[("name", name)]), + (Some(Source::Anchor { anchor, channel, .. }), _) => anchor_label(app, *anchor, *channel), + (Some(Source::Procedural { .. }), _) => tr("Procedural").to_string(), + }; + let empty_hint = match slot { + InputSlot::Map(_) => tr("Read the mesh map again"), + InputSlot::Texture => tr("Empty the slot"), }; let group = ui.group(|ui| { ui.horizontal(|ui| { - input_tile(app, ui, map, source); + input_tile(app, ui, slot, source); ui.vertical(|ui| { - ui.label(RichText::new(tr(baked_map_label(map))).strong()); + ui.label(RichText::new(slot.title()).strong()); ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() { + if source.is_some() && ui.button(ic::X).on_hover_text(empty_hint).clicked() { app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } }); @@ -580,11 +678,14 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 ui.push_id(input, |ui| { combo(ui, tr("Source"), current.clone(), |ui| { let anchors = anchors_below(&app.session.doc.project, layer); - if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + if let InputSlot::Map(_) = slot + && ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() + { app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } - if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + let uniform = matches!(source, Some(Source::Uniform(_))) || (source.is_none() && matches!(slot, InputSlot::Texture)); + if ui.selectable_label(uniform, tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": slot.neutral()})); } for (anchor, label) in &anchors { if ui @@ -602,13 +703,18 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 } }) }); - if let Some(Source::Uniform(value)) = source { - let mut value = value[0]; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); - } + let uniform = match (source, slot) { + (Some(Source::Uniform(value)), _) => Some(value[0]), + (None, InputSlot::Texture) => Some(slot.neutral()), + _ => None, + }; + if let Some(mut value) = uniform + && let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) + { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); } - if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) { + let replaced_curvature = matches!(slot, InputSlot::Map(BakedMap::Curvature)) && source.is_some_and(|source| !matches!(source, Source::Uniform(_))); + if detail_sizes && replaced_curvature { ui.label( RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) .size(NOTE_FONT_SIZE) @@ -621,14 +727,15 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 } } -/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list). -fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) { +/// The picture beside an image input: its image, its value as gray, an icon for an anchor or a procedural, else its mesh map's color (black for an empty texture) +fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, slot: InputSlot, source: Option<&Source>) { let tokens = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); let painter = ui.painter(); let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); - match source { - Some(Source::Image { name, .. }) => match app.session.images.get(name) { + let gray = |value: f32| egui::Color32::from_gray((value.clamp(0.0, 1.0) * 255.0).round() as u8); + match (source, slot) { + (Some(Source::Image { name, .. }), _) => match app.session.images.get(name) { Some(image) => { let texture = app.thumbs.image(ui.ctx(), name, image); painter.image(texture.id(), rect, whole, egui::Color32::WHITE); @@ -637,15 +744,18 @@ fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Opt painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); } }, - Some(Source::Uniform(value)) => { - painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8)); + (Some(Source::Uniform(value)), _) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(value[0])); } - Some(Source::Anchor { .. } | Source::Procedural { .. }) => { + (Some(Source::Anchor { .. } | Source::Procedural { .. }), _) => { let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); } - None => { + (None, InputSlot::Texture) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(slot.neutral())); + } + (None, InputSlot::Map(map)) => { let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 513ca72b..01bf845a 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -300,3 +300,60 @@ fn section_panel_snapshots() { harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap(); } } + +#[test] +fn use_texture_shows_the_texture_rows_and_its_slot() { + let (harness, _) = harness_with(false, json!({"generator": "position"})); + assert_eq!(count(&harness, "Use texture"), 1); + for label in ["Grayscale conversion", "Texture opacity", "Triplanar contrast", "Texture"] { + assert_eq!(count(&harness, label), 0, "{label} waits for Use texture"); + } + + let (harness, _) = harness_with(false, json!({"generator": "position", "useTexture": true})); + for label in ["Grayscale conversion", "Texture opacity", "Triplanar", "Triplanar contrast", "Scale"] { + assert_eq!(count(&harness, label), 1, "{label}"); + } + assert_eq!(count(&harness, "Texture"), 2, "the Texture section and the Texture slot in Image inputs"); + assert_eq!(count(&harness, "Blending mode"), 4, "the texture's beside the three axes'"); + + let (harness, _) = harness_with(false, json!({"generator": "dirt"})); + assert_eq!(count(&harness, "Use texture"), 0, "wear generators have no texture"); +} + +#[test] +fn the_texture_slot_reads_a_uniform_value_until_it_is_given_one() { + let (mut harness, effect) = harness_with(false, json!({"generator": "ambientOcclusion", "useTexture": true})); + let slot = |harness: &Harness<'_, TextureCraftApp>| { + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Uniform value")).count() + }; + assert_eq!(slot(&harness), 1, "an empty texture slot is a uniform value"); + assert_eq!(count(&harness, "Value"), 1, "with its value slider"); + + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + harness.run_steps(2); + assert_eq!(count(&harness, "Mesh map"), 0, "the texture has no mesh map to go back to"); + // The slot's heading also reads "Uniform value": the menu entry is the button + harness.get_by_role_and_label(Role::Button, "Uniform value").click(); + harness.run_steps(3); + let texture = generator(&harness, effect).texture.unwrap(); + assert_eq!(texture.source, Some(Source::Uniform([0.0; 3]))); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn texture_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 ["position", "ambientOcclusion"] { + let (mut harness, _) = harness_with(true, json!({"generator": kind, "useTexture": true, "textureOpacity": 0.6, "textureBlend": "normal"})); + harness.get_by_label("Use texture").scroll_to_me(); + harness.run_steps(12); + 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!("texture-panel-{kind}-{name}.png"))).unwrap(); + } + } +}