From 413783575043db2f5a78541e2a0223bb6766b818 Mon Sep 17 00:00:00 2001 From: Imbris Date: Sun, 29 Sep 2019 01:53:22 -0400 Subject: [PATCH] Cache most recent chunk access in terrain meshing --- common/src/volumes/vol_grid_2d.rs | 21 +++++++++++++++++++++ voxygen/src/mesh/terrain.rs | 31 +++++++++++++++++++------------ 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/common/src/volumes/vol_grid_2d.rs b/common/src/volumes/vol_grid_2d.rs index 9ce00cef7b..9713888b95 100644 --- a/common/src/volumes/vol_grid_2d.rs +++ b/common/src/volumes/vol_grid_2d.rs @@ -161,6 +161,27 @@ impl VolGrid2d { } } +impl VolGrid2d { + // Note: this may be invalidated by mutations of the chunks hashmap + #[inline(always)] + pub fn get_vox_cached<'a>( + &'a self, + pos: Vec3, + cache: &'a mut Option<(Vec2, Arc)>, + ) -> Result<&V::Vox, VolGrid2dError> { + let ck = Self::chunk_key(pos); + let chunk = if cache.as_ref().map(|(key, _)| *key == ck).unwrap_or(false) { + &cache.as_ref().unwrap().1 + } else { + let chunk = self.chunks.get(&ck).ok_or(VolGrid2dError::NoSuchChunk)?; + *cache = Some((ck, chunk.clone())); + chunk + }; + let co = Self::chunk_offs(pos); + chunk.get(co).map_err(VolGrid2dError::ChunkError) + } +} + pub struct ChunkIter<'a, V: RectRasterableVol> { iter: hash_map::Iter<'a, Vec2, Arc>, } diff --git a/voxygen/src/mesh/terrain.rs b/voxygen/src/mesh/terrain.rs index 6f31f622fa..9a50c2a394 100644 --- a/voxygen/src/mesh/terrain.rs +++ b/voxygen/src/mesh/terrain.rs @@ -41,6 +41,8 @@ fn calc_light + ReadVol + Debug>( max: bounds.max + sunlight, }; + let mut get_cache = None; + let mut voids = HashMap::new(); let mut rays = vec![outer.size().d; outer.size().product() as usize]; for x in 0..outer.size().w { @@ -48,7 +50,7 @@ fn calc_light + ReadVol + Debug>( let mut outside = true; for z in (0..outer.size().d).rev() { let block = vol - .get(outer.min + Vec3::new(x, y, z)) + .get_vox_cached(outer.min + Vec3::new(x, y, z), &mut get_cache) .ok() .copied() .unwrap_or(Block::empty()); @@ -138,6 +140,8 @@ impl + ReadVol + Debug> Meshable + ReadVol + Debug> Meshable { + self.get_vox_cached($pos, &mut get_cache) + .ok() + .filter(|vox| vox.is_opaque()) + .and_then(|vox| vox.get_color()) + .map(|col| Rgba::from_opaque(col)) + .unwrap_or(Rgba::zero()) + }; }; let mut colors = [[[Rgba::zero(); 3]; 3]; 3]; for i in 0..3 { for j in 0..3 { for k in 0..3 { - colors[k][j][i] = get_color( + colors[k][j][i] = get_color!( Vec3::new(x, y, range.min.z) + Vec3::new(i as i32, j as i32, k as i32) - - 1, + - 1 ); } } @@ -193,11 +199,12 @@ impl + ReadVol + Debug> Meshable