diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index e78ce0772..3b6d058ae 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -17,7 +17,7 @@ use std::collections::BTreeMap; use std::{ collections::{BTreeSet, HashMap}, sync::{ - Arc, Condvar, Mutex, OnceLock, + Arc, Condvar, Mutex, OnceLock, RwLock, atomic::{AtomicUsize, Ordering}, }, }; @@ -30,7 +30,7 @@ pub(super) struct StructureState { possible_sets: Vec, /// Structure indices of each decoration step, in registry order. pub(super) by_step: Vec>, - starts: Mutex>, + starts: StartCache, /// Concentric ring positions, computed on first use and shared with /// later generators of the same seed and dimension. rings: Arc>, @@ -108,6 +108,45 @@ impl RingWork { } } const START_CACHE_LIMIT: usize = 65536; +const START_SHARDS: usize = 64; + +/// The built starts by chunk, in shards: a lookup locks one shard for +/// reading. Each generated chunk reads the 289 start chunks around it +/// (`references`) and the server thread reads the starts of the chunks its +/// mobs and players are in; with one lock for all, the server thread waited +/// on the workers. +struct StartCache { + shards: Box<[RwLock>]>, +} +impl StartCache { + fn new() -> Self { + Self { + shards: (0..START_SHARDS).map(|_| RwLock::default()).collect(), + } + } + fn shard(&self, key: (i32, i32)) -> &RwLock> { + let hash = + (key.0 as u32).wrapping_mul(0x9E37_79B9) ^ (key.1 as u32).wrapping_mul(0x85EB_CA6B); + &self.shards[(hash >> (32 - START_SHARDS.trailing_zeros())) as usize] + } + fn get(&self, key: (i32, i32)) -> Option { + self.shard(key).read().unwrap().get(&key).cloned() + } + /// Keeps `starts` unless another thread built the same chunk's first: + /// everyone keeps the first, so placement state on its pieces is shared. + fn insert_first(&self, key: (i32, i32), starts: Starts) -> Starts { + let mut shard = self.shard(key).write().unwrap(); + if shard.len() >= START_CACHE_LIMIT / START_SHARDS { + shard.clear(); + } + shard.entry(key).or_insert(starts).clone() + } + fn clear(&self) { + for shard in &self.shards { + shard.write().unwrap().clear(); + } + } +} fn biome_set(data: &GeneratorData, value: &Value) -> Result, super::DecodeError> { let names: Vec<&str> = match value { @@ -167,7 +206,7 @@ impl StructureState { bindings, possible_sets, by_step, - starts: Mutex::new(HashMap::new()), + starts: StartCache::new(), rings, ring_work: OnceLock::new(), })) @@ -199,7 +238,7 @@ impl StructureState { /// Drop the cached starts, so that later chunks build fresh pieces (the /// pieces keep per-start placement state such as a shipwreck's height). pub(super) fn forget_starts(&self) { - self.starts.lock().unwrap().clear(); + self.starts.clear(); } /// The (cached) structure starts owned by a chunk. pub(super) fn starts_at( @@ -207,8 +246,8 @@ impl StructureState { context: &mut impl super::structure::start::StartContext, chunk: ChunkPos, ) -> Starts { - if let Some(found) = self.starts.lock().unwrap().get(&(chunk.x, chunk.z)) { - return found.clone(); + if let Some(found) = self.starts.get((chunk.x, chunk.z)) { + return found; } let rings = self.rings(context); let starts: Starts = Arc::new( @@ -225,13 +264,7 @@ impl StructureState { .map(Arc::new) .collect(), ); - let mut cache = self.starts.lock().unwrap(); - if cache.len() >= START_CACHE_LIMIT { - cache.clear(); - } - // Another thread may have built the same starts meanwhile: everyone - // keeps the first, so placement state on its pieces is shared. - cache.entry((chunk.x, chunk.z)).or_insert(starts).clone() + self.starts.insert_first((chunk.x, chunk.z), starts) } /// ChunkGenerator.findNearestMapStructure: the nearest start of one of /// `names` from block `from` (rings: every ring chunk; random spreads: @@ -385,6 +418,39 @@ mod tests { use super::*; use crate::worldgen::structure::stronghold::{ring_positions, ring_searches}; + /// The start cache keeps the first starts built for a chunk, spreads a + /// chunk's 289 reference lookups over the shards, and forgets on clear. + #[test] + fn start_cache_keeps_first_and_spreads_neighbours() { + let cache = StartCache::new(); + let first: Starts = Arc::new(Vec::new()); + let second: Starts = Arc::new(Vec::new()); + assert!(cache.get((3, -4)).is_none()); + assert!(Arc::ptr_eq( + &cache.insert_first((3, -4), first.clone()), + &first + )); + assert!(Arc::ptr_eq(&cache.insert_first((3, -4), second), &first)); + assert!(Arc::ptr_eq(&cache.get((3, -4)).unwrap(), &first)); + for (cx, cz) in [(0, 0), (-1000, 77), (i32::MAX - 8, i32::MIN + 8)] { + let mut used = vec![0; START_SHARDS]; + for x in cx - 8..=cx + 8 { + for z in cz - 8..=cz + 8 { + let shard = cache.shard((x, z)) as *const _; + let i = cache + .shards + .iter() + .position(|s| std::ptr::eq(s, shard)) + .unwrap(); + used[i] += 1; + } + } + assert!(used.iter().all(|&n| n > 0 && n < 20), "{used:?}"); + } + cache.clear(); + assert!(cache.get((3, -4)).is_none()); + } + /// Searches shared between threads give the positions of one thread /// running them in order, set by set. #[test]