diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs index 4b5f84d5..c098fe29 100644 --- a/crates/compose/src/dripping_rust.rs +++ b/crates/compose/src/dripping_rust.rs @@ -36,8 +36,7 @@ const MIN_COVERAGE: f32 = 1e-3; static CACHE: FieldCache = FieldCache::new(); /// The rust before its spreading and contrast at every working texel of `inp` (0 outside the islands) -pub(crate) fn rust_field(inp: &Inputs, rust: &DrippingRustParameters, seed: u32) -> Arc> { - let occlusion = inp.baked.maps.get(&BakedMap::AmbientOcclusion); +pub(crate) fn rust_field(inp: &Inputs, coverage: u64, rust: &DrippingRustParameters, seed: u32) -> Arc> { let settings = vec![ rust.spreading_smoothness.to_bits(), rust.drips_intensity.to_bits(), @@ -46,7 +45,7 @@ pub(crate) fn rust_field(inp: &Inputs, rust: &DrippingRustParameters, seed: u32) u32::from(rust.axis), seed, ]; - CACHE.get_or_build(inp, &occlusion.into_iter().collect::>(), settings, |block| build(inp, rust, seed, block)) + CACHE.get_or_build(inp, coverage, &[BakedMap::AmbientOcclusion], settings, |block| build(inp, rust, seed, block)) } /// The value at a working texel: the rust spread and contrasted diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 653e9f80..582f5bbf 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2419,7 +2419,7 @@ fn compares_this_layer(kind: &EffectKind) -> bool { } /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. -fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { +fn prepare_curvature_sizes(inp: &EvaluationInputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); prepare_mask_curvature_sizes(inp, masks); @@ -2506,7 +2506,7 @@ fn wear_parameters(generator: &Generator) -> Option { } /// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. -fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { +fn prepare_mask_curvature_sizes<'a>(inp: &EvaluationInputs, masks: impl Iterator) { let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { if let EffectKind::Generator(generator) = &effect.kind { @@ -2516,7 +2516,7 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator( None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; let maps = match &effect.kind { - EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator)), + EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), || inp.coverage_identity()), _ => GeneratorMaps::default(), }; let (depth, covers_all, projection) = match &effect.kind { @@ -7368,6 +7368,77 @@ soft {soft:?}" assert_eq!(builds.get(), 2, "a smaller working atlas builds them again"); } + /// Builds a field cache made: the counter goes up with each build + fn counted_build(builds: &std::cell::Cell) -> impl FnOnce((u32, u32)) -> Vec + '_ { + move |_| { + builds.set(builds.get() + 1); + vec![0.0; 4] + } + } + + #[test] + fn a_whole_map_field_is_built_again_when_its_mesh_map_is_read_at_another_bake_size() { + let cache = crate::field_cache::FieldCache::new(); + let builds = std::cell::Cell::new(0); + let mut fixture = fixture(); + let occlusion = Arc::new(vec![0.5; 16]); + let images = ImageStore::default(); + for resolution in [4, 4, 8] { + fixture.baked = BakedMaps { resolution, maps: [(BakedMap::AmbientOcclusion, occlusion.clone())].into() }; + let inputs = inputs(&fixture, &images, None); + cache.get_or_build( + &inputs, + crate::field_cache::coverage_identity(&fixture.gbuf), + &[BakedMap::AmbientOcclusion], + Vec::new(), + counted_build(&builds), + ); + } + + assert_eq!(builds.get(), 2, "4 × 4 reuses its field; the same map read as 8 × 2 builds another"); + } + + #[test] + fn a_whole_map_field_is_built_again_after_any_texel_of_its_coverage_changes() { + let cache = crate::field_cache::FieldCache::new(); + let builds = std::cell::Cell::new(0); + let mut fixture = fixture(); + let images = ImageStore::default(); + let build_on = |fixture: &Fixture| { + let inputs = inputs(fixture, &images, None); + cache.get_or_build(&inputs, crate::field_cache::coverage_identity(&fixture.gbuf), &[], Vec::new(), counted_build(&builds)); + }; + build_on(&fixture); + build_on(&fixture); + + // The second texel, in place: the same allocation, one triangle different + fixture.gbuf.tri[1] = if fixture.gbuf.tri[1] == NO_TRI { 0 } else { NO_TRI }; + build_on(&fixture); + + assert_eq!(builds.get(), 2); + } + + #[test] + fn a_whole_map_field_read_again_outlives_fields_built_before_it() { + const FIELDS_KEPT: u32 = 8; + let cache = crate::field_cache::FieldCache::new(); + let builds = std::cell::Cell::new(0); + let fixture = fixture(); + let images = ImageStore::default(); + let inputs = inputs(&fixture, &images, None); + let coverage = crate::field_cache::coverage_identity(&fixture.gbuf); + let field = |settings: u32| { + cache.get_or_build(&inputs, coverage, &[], vec![settings], counted_build(&builds)); + }; + (0..FIELDS_KEPT).for_each(field); + field(0); + field(FIELDS_KEPT); + let built = builds.get(); + field(0); + + assert_eq!(builds.get(), built, "the field read again stays when a newer one pushes the oldest out"); + } + #[test] fn a_micro_detail_saved_before_micro_details_renders_as_saved_on_the_earlier_model() { const SAVED_AMOUNT: f32 = 0.25; diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs index 2f9027fe..dbb8f392 100644 --- a/crates/compose/src/eval/evaluation_inputs.rs +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -22,6 +22,7 @@ pub(super) struct EvaluationInputs<'a> { instance_draws: OnceLock>, depth_maps: Mutex>, gradients: Mutex>>, + coverage: OnceLock, } impl<'a> EvaluationInputs<'a> { @@ -33,9 +34,15 @@ impl<'a> EvaluationInputs<'a> { instance_draws: OnceLock::new(), depth_maps: Mutex::new(Vec::new()), gradients: Mutex::default(), + coverage: OnceLock::new(), } } + /// The working layout's coverage identity, hashed on first use only: the whole-map generator fields' cache reads it ([`crate::field_cache::coverage_identity`]) + pub(super) fn coverage_identity(&self) -> u64 { + *self.coverage.get_or_init(|| crate::field_cache::coverage_identity(self.inputs.gbuf)) + } + pub(super) fn environment(&self) -> EnvironmentSh { if let Some(environment) = self.environment.get() { return *environment; diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index 1458cb3f..51581173 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -1,5 +1,9 @@ use std::sync::{Arc, Mutex}; +use rayon::prelude::*; +use texturecraft_core::BakedMap; +use texturecraft_geom::UvGBuffer; + use crate::eval::Inputs; use crate::field_cache_key::FieldCacheKey; use crate::working_field::working_block; @@ -8,8 +12,19 @@ use crate::working_field::working_block; const CACHE_ENTRIES: usize = 8; const CACHE_BYTES: usize = 256 << 20; -/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile -const FINGERPRINT_STRIDE: usize = 31; +/// Texels hashed together before their hashes are combined, so the coverage hashes in parallel +const COVERAGE_CHUNK_TEXELS: usize = 1 << 16; + +/// The 64-bit FNV prime, spreading each step of the coverage hash over every bit +const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; + +/// The identity of `gbuf`'s coverage: its size and the triangle under every texel, hashed (read once per evaluation, as it reads every texel) +pub(crate) fn coverage_identity(gbuf: &UvGBuffer) -> u64 { + let chunk_hash = + |chunk: &[u32]| chunk.iter().fold(chunk.len() as u64, |hash, triangle| (hash.rotate_left(5) ^ u64::from(*triangle)).wrapping_mul(FNV_PRIME)); + let chunks: Vec = gbuf.tri.par_chunks(COVERAGE_CHUNK_TEXELS).map(chunk_hash).collect(); + chunks.iter().fold((u64::from(gbuf.width) << 32) | u64::from(gbuf.height), |hash, chunk| (hash.rotate_left(7) ^ chunk).wrapping_mul(FNV_PRIME)) +} /// Built fields by what they were built from, most recently used last pub(crate) struct FieldCache { @@ -21,26 +36,39 @@ impl FieldCache { FieldCache { entries: Mutex::new(Vec::new()) } } - /// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work - pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc>], settings: Vec, build: impl FnOnce((u32, u32)) -> Vec) -> Arc> { + /// The field of `inp`'s working layout (its coverage: [`coverage_identity`]) reading the baked `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work + pub(crate) fn get_or_build( + &self, + inp: &Inputs, + coverage: u64, + maps: &[BakedMap], + settings: Vec, + build: impl FnOnce((u32, u32)) -> Vec, + ) -> Arc> { let gbuf = inp.gbuf; let block = working_block(inp); + let read = maps.iter().filter_map(|map| inp.baked.maps.get(map).map(|data| (Arc::downgrade(data), (inp.baked.resolution, inp.baked.height(*map))))); let key = FieldCacheKey { layout: gbuf.tri.as_ptr() as usize, size: (gbuf.width, gbuf.height), - fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), + coverage, block, scales: inp.block_scales.clone(), positions: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()), uvs: (inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()), - maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), + maps: read.collect(), settings, }; + // A hit moves to the most recently used end let cached = { let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(key, _)| key.maps.iter().all(|map| map.strong_count() > 0)); - entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone()) + entries.retain(|(key, _)| key.maps.iter().all(|(map, _)| map.strong_count() > 0)); + let hit = entries.iter().position(|(cached, _)| *cached == key).map(|index| entries.remove(index)); + hit.map(|(cached, field)| { + entries.push((cached, field.clone())); + field + }) }; if let Some(field) = cached { return field; diff --git a/crates/compose/src/field_cache_key.rs b/crates/compose/src/field_cache_key.rs index d29d80f5..1010ac97 100644 --- a/crates/compose/src/field_cache_key.rs +++ b/crates/compose/src/field_cache_key.rs @@ -2,28 +2,31 @@ use std::sync::Weak; use texturecraft_core::BlockScales; -/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits +/// What a field was built from: the working layout (the g-buffer's address, size, coverage, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits #[derive(Clone)] pub(crate) struct FieldCacheKey { pub(crate) layout: usize, pub(crate) size: (u32, u32), - pub(crate) fingerprint: u64, + /// Every texel's triangle, hashed: [`crate::field_cache::coverage_identity`] + pub(crate) coverage: u64, pub(crate) block: (u32, u32), pub(crate) scales: BlockScales, /// The mesh's positions and UVs, each by address and length: a UV edit changes island fields pub(crate) positions: (usize, usize), pub(crate) uvs: (usize, usize), - pub(crate) maps: Vec>>, + /// The mesh maps it samples, each with the size it was baked at: one allocation read as another layout reads other texels + pub(crate) maps: Vec<(Weak>, (u32, u32))>, pub(crate) settings: Vec, } impl PartialEq for FieldCacheKey { fn eq(&self, other: &FieldCacheKey) -> bool { - let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b)); + let same_maps = self.maps.len() == other.maps.len() + && self.maps.iter().zip(&other.maps).all(|((a, a_size), (b, b_size))| a.strong_count() > 0 && a.ptr_eq(b) && a_size == b_size); same_maps && self.layout == other.layout && self.size == other.size - && self.fingerprint == other.fingerprint + && self.coverage == other.coverage && self.block == other.block && self.scales == other.scales && self.positions == other.positions diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 151ae176..503a32c9 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -27,8 +27,8 @@ pub(crate) struct GeneratorMaps { } impl GeneratorMaps { - /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size) - pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool]) -> GeneratorMaps { + /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size); `coverage` gives the working layout's coverage identity for whole-map fields + pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], coverage: impl Fn() -> u64) -> GeneratorMaps { let micro = generator.micro_in_use().map(|micro| micro.clone().clamped(generator.kind)); let micro_curvature = micro.as_ref().filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); @@ -39,10 +39,10 @@ impl GeneratorMaps { }; let controls = generator.kind_controls(); let field = match &controls { - Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), - Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)), - Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, random, generator.seed)), - Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, checker, generator.seed)), + Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, coverage(), border)), + Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, coverage(), rust, generator.seed)), + Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, coverage(), random, generator.seed)), + Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, coverage(), checker, generator.seed)), _ => None, }; GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) } diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index b324e4ac..9cced087 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -18,8 +18,8 @@ const SMOOTHNESS_SIGMA_2K: f32 = 45.0; static CACHE: FieldCache = FieldCache::new(); /// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands) -pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) -> Arc> { - CACHE.get_or_build(inp, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block)) +pub(crate) fn border_gradient(inp: &Inputs, coverage: u64, border: &BorderDistanceParameters) -> Arc> { + CACHE.get_or_build(inp, coverage, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block)) } /// The value at a working texel: the gradient balanced, contrasted and inverted diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 6ce27082..d5233984 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -17,12 +17,12 @@ use crate::working_field::REFERENCE_TILE_TEXELS; static CACHE: FieldCache = FieldCache::new(); /// UV Random Color at every working texel of `inp`: one value per UV island (0 outside the islands) -pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, seed: u32) -> Arc> { +pub(crate) fn random_color_field(inp: &Inputs, coverage: u64, random: &UvRandomColorParameters, seed: u32) -> Arc> { let mut settings = vec![seed, u32::from(random.custom_gradient)]; settings.push(random.used_colors().len() as u32); settings.extend(random.used_colors().iter().flat_map(|color| color.map(f32::to_bits))); settings.extend(random.positions.iter().map(|position| position.to_bits())); - CACHE.get_or_build(inp, &[], settings, |_| { + CACHE.get_or_build(inp, coverage, &[], settings, |_| { let island_values = island_values(inp, |island| random_gray(random, seed, island)); let gbuf = inp.gbuf; gbuf.tri.par_iter().map(|triangle| island_values.get(triangle).copied().unwrap_or(0.0)).collect() @@ -73,10 +73,10 @@ const RANDOM_SATURATION: std::ops::RangeInclusive = 0.06..=0.57; const RANDOM_VALUE: std::ops::RangeInclusive = 0.42..=0.80; /// UV Checker at every working texel of `inp`: the gray of its color, the mean of the sRGB-encoded channels as the reference reads it (0 outside the islands) -pub(crate) fn checker_field(inp: &Inputs, checker: &UvCheckerParameters, seed: u32) -> Arc> { +pub(crate) fn checker_field(inp: &Inputs, coverage: u64, checker: &UvCheckerParameters, seed: u32) -> Arc> { let mut settings = vec![seed, u32::from(checker.random_colors), checker.grid_tile, checker.grid_opacity.to_bits(), checker.border_width.to_bits()]; settings.extend(checker.checker_color.iter().chain(&checker.border_color).map(|value| value.to_bits())); - CACHE.get_or_build(inp, &[], settings, |block| { + CACHE.get_or_build(inp, coverage, &[], settings, |block| { let gbuf = inp.gbuf; let (width, height) = (gbuf.width, gbuf.height); let island_colors = if checker.random_colors { island_colors(inp, seed) } else { HashMap::new() };