diff --git a/crates/horizon-world/src/worldgen/material_condition/density.rs b/crates/horizon-world/src/worldgen/material_condition/density.rs index 5c98c75e0..b10ea815a 100644 --- a/crates/horizon-world/src/worldgen/material_condition/density.rs +++ b/crates/horizon-world/src/worldgen/material_condition/density.rs @@ -15,6 +15,8 @@ pub struct MaterialDensitySources { surface: S, expected: DensityVolume, densities: Vec, + /// Eagerly sampled volumes, shared by bindings of the same density root. + buffers: Vec>, retained_samples: usize, plane: DensityVolume, sampler: Arc, @@ -23,7 +25,7 @@ pub struct MaterialDensitySources { } struct BoundDensity { sampler: Arc, - buffer: Option>, + buffer: Option, } impl MaterialDensitySources { pub fn sampler_context_mut(&mut self) -> &mut SamplerContext { @@ -50,6 +52,7 @@ impl MaterialDensitySources { surface, expected, densities: Vec::new(), + buffers: Vec::new(), retained_samples: 0, plane, sampler, @@ -71,13 +74,23 @@ impl MaterialSurfaceQueries for MaterialDensitySource { return Err(DecodeError::Field("material density storage bound")); } - let buffer = if eager { - let mut buffer = vec![0.0; self.expected.size()]; - sampler.sample_volume(&mut self.context, &mut buffer, self.expected)?; - self.retained_samples += buffer.len(); - Some(buffer) - } else { - None + let shared = self + .densities + .iter() + .find(|bound| bound.buffer.is_some() && Arc::ptr_eq(&bound.sampler, &sampler)) + .and_then(|bound| bound.buffer); + let buffer = match (eager, shared) { + (false, _) => None, + // Sampling a root over the same volume and context is deterministic, + // so a second binding (iron and copper veins' richness) reuses it. + (true, Some(buffer)) => Some(buffer), + (true, None) => { + let mut buffer = vec![0.0; self.expected.size()]; + sampler.sample_volume(&mut self.context, &mut buffer, self.expected)?; + self.retained_samples += buffer.len(); + self.buffers.push(buffer); + Some(self.buffers.len() - 1) + } }; let index = self.densities.len(); self.densities.push(BoundDensity { sampler, buffer }); @@ -89,9 +102,9 @@ impl MaterialSurfaceQueries for MaterialDensitySource .get(index) .ok_or(MaterialRuleError::MissingDensityProvider)?; let position = [position.x, position.y, position.z]; - if let Some(buffer) = &source.buffer { - if let Some(index) = self.expected.index_of_block(position) { - return Ok(buffer[index]); + if let Some(buffer) = source.buffer { + if let Some(index) = block_index(self.expected, position) { + return Ok(self.buffers[buffer][index]); } } Ok(source.sampler.sample_value(&mut self.context, position)?) @@ -145,3 +158,121 @@ impl MaterialSurfaceQueries for MaterialDensitySource self.surface.band(position) } } + +/// `DensityVolume::index_of_block` without its per-axis divisions for the +/// unit-step volumes the material stage samples (one or two lookups per block). +#[inline] +fn block_index(volume: DensityVolume, position: [i32; 3]) -> Option { + if volume.steps() != [1; 3] { + return volume.index_of_block(position); + } + let [mx, my, mz] = volume.minimum(); + let [sx, sy, sz] = volume.sizes(); + let x = position[0].wrapping_sub(mx) as u32 as usize; + let y = position[1].wrapping_sub(my) as u32 as usize; + let z = position[2].wrapping_sub(mz) as u32 as usize; + (x < sx && y < sy && z < sz).then(|| y + (x + z * sx) * sy) +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::density::SampleError; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Surface; + impl MaterialSurfaceQueries for Surface { + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + 0 + } + fn surface_secondary(&mut self, _: i32, _: i32) -> f64 { + 0.0 + } + } + /// Position-dependent values; counts bulk samples. + #[derive(Debug, Default)] + struct Counted(AtomicUsize); + impl DensitySampler for Counted { + fn sample_value(&self, _: &mut SamplerContext, p: [i32; 3]) -> Result { + Ok((p[0] * 10_000 + p[1] * 100 + p[2]) as f32) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + self.0.fetch_add(1, Ordering::Relaxed); + for z in 0..volume.sizes()[2] { + for x in 0..volume.sizes()[0] { + for y in 0..volume.sizes()[1] { + let [mx, my, mz] = volume.minimum(); + let p = [mx + x as i32, my + y as i32, mz + z as i32]; + buffer[volume.index([x, y, z]).unwrap()] = self.sample_value(context, p)?; + } + } + } + Ok(()) + } + } + fn sources() -> MaterialDensitySources { + let volume = DensityVolume::new([16, 24, 16], [32, -64, -16], [1; 3]).unwrap(); + MaterialDensitySources::new( + Surface, + volume, + Arc::new(Counted::default()), + SamplerContext::default(), + ) + .unwrap() + } + + #[test] + fn eager_bindings_of_one_root_share_a_single_sample() { + let mut sources = sources(); + let shared = Arc::new(Counted::default()); + let other = Arc::new(Counted::default()); + let a = sources.bind_density(shared.clone(), true).unwrap(); + let lazy = sources.bind_density(shared.clone(), false).unwrap(); + let b = sources.bind_density(shared.clone(), true).unwrap(); + let c = sources.bind_density(other.clone(), true).unwrap(); + assert_eq!(shared.0.load(Ordering::Relaxed), 1); + assert_eq!(other.0.load(Ordering::Relaxed), 1); + assert_eq!([a, lazy, b, c], [0, 1, 2, 3]); + for p in [[32, -64, -16], [47, -41, -1], [40, -50, -9], [48, 0, 0]] { + let position = BlockPos::new(p[0], p[1], p[2]); + let expected = (p[0] * 10_000 + p[1] * 100 + p[2]) as f32; + for index in [a, lazy, b, c] { + assert_eq!(sources.density(index, position).unwrap(), expected); + } + } + assert_eq!(shared.0.load(Ordering::Relaxed), 1); + } + + #[test] + fn block_index_matches_index_of_block() { + let unit = DensityVolume::new([16, 24, 16], [i32::MAX - 7, -64, -16], [1; 3]).unwrap(); + let strided = DensityVolume::new([5, 3, 5], [-8, -64, 0], [4, 8, 4]).unwrap(); + for volume in [unit, strided] { + let [mx, my, mz] = volume.minimum(); + for dx in [-1, 0, 1, 4, 7, 8, 15, 16, 17, 20] { + for dy in [-9, -1, 0, 8, 16, 23, 24] { + for dz in [-1, 0, 3, 15, 16, 20] { + let p = [ + mx.wrapping_add(dx), + my.wrapping_add(dy), + mz.wrapping_add(dz), + ]; + assert_eq!(block_index(volume, p), volume.index_of_block(p), "{p:?}"); + } + } + } + for p in [ + [i32::MIN, 0, 0], + [i32::MAX, i32::MAX, i32::MAX], + [0, i32::MIN, 0], + ] { + assert_eq!(block_index(volume, p), volume.index_of_block(p), "{p:?}"); + } + } + } +}