diff --git a/crates/horizon-client/examples/tick_chunk_membership_bench.rs b/crates/horizon-client/examples/tick_chunk_membership_bench.rs new file mode 100644 index 000000000..6b9cb8a0a --- /dev/null +++ b/crates/horizon-client/examples/tick_chunk_membership_bench.rs @@ -0,0 +1,143 @@ +//! Resident-key synchronization used by Game (registration callback work excluded). +//! Run: CARGO_INCREMENTAL=0 cargo run -p horizon-client --profile fast --example tick_chunk_membership_bench +use horizon_client::{ + chunk::Chunk, chunk_map::ChunkMap, tick_chunk_membership::TickChunkMembership, +}; +use std::{collections::HashSet, hint::black_box, sync::Arc, time::Instant}; + +type Key = (i32, i32); +#[derive(Default)] +struct Old { + keys: HashSet, +} +impl Old { + fn sync(&mut self, map: &ChunkMap) -> (usize, usize) { + let loaded: HashSet<_> = map.keys().copied().collect(); + let mut counts = (0, 0); + for key in loaded.difference(&self.keys.clone()) { + black_box(key); + counts.0 += 1; + } + for key in self.keys.difference(&loaded) { + black_box(key); + counts.1 += 1; + } + self.keys = loaded; + counts + } +} +fn new_sync(cache: &mut TickChunkMembership, map: &ChunkMap) -> (usize, usize) { + if !cache.synchronize(map) { + return (0, 0); + } + let added = cache.take_added(); + for key in &added { + black_box(key); + } + for key in cache.removed() { + black_box(key); + } + let counts = (added.len(), cache.removed().len()); + cache.recycle_added(added); + counts +} +fn map(offset: i32) -> ChunkMap { + let mut map = ChunkMap::default(); + // Share a payload: the synchronization path reads only keys, not block data. + let chunk = Arc::new(Chunk::empty(0, 0)); + for x in -16..=16 { + for z in -16..=16 { + map.insert((x + offset, z), chunk.clone()); + } + } + map +} +fn run(new: bool, scenario: usize, iterations: usize) -> (f64, (usize, usize)) { + let mut a = map(0); + let b = map(33); + let chunk = Arc::new(Chunk::empty(0, 0)); + let mut old = Old::default(); + let mut cache = TickChunkMembership::default(); + for _ in 0..64 { + if new { + black_box(new_sync(&mut cache, &a)); + } else { + black_box(old.sync(&a)); + } + } + let mut total = (0, 0); + let start = Instant::now(); + for i in 0..iterations { + let resident = match scenario { + 0 => &a, + 1 => { + let (previous, next) = if i % 2 == 0 { + ((-16, -16), (-17, -16)) + } else { + ((-17, -16), (-16, -16)) + }; + a.remove(&previous); + a.insert(next, chunk.clone()); + &a + } + 2 => { + if i % 2 == 0 { + &b + } else { + &a + } + } + _ => unreachable!(), + }; + let counts = if new { + new_sync(black_box(&mut cache), black_box(resident)) + } else { + old.sync(black_box(resident)) + }; + total.0 += counts.0; + total.1 += counts.1; + } + ( + start.elapsed().as_secs_f64() * 1e9 / iterations as f64, + black_box(total), + ) +} +fn main() { + println!("1089 keys, 64 warmup calls, 9 samples; ns/sync, median"); + for (scenario, name, iterations) in [ + (0, "stable", 10_000), + (1, "one-key same-count replacement", 2_000), + (2, "whole-map replacement", 1_000), + ] { + let mut before = Vec::new(); + let mut after = Vec::new(); + for sample in 0..9 { + let (old, new) = if sample % 2 == 0 { + ( + run(false, scenario, iterations), + run(true, scenario, iterations), + ) + } else { + let new = run(true, scenario, iterations); + (run(false, scenario, iterations), new) + }; + assert_eq!(old.1, new.1); + let expected = match scenario { + 0 => (0, 0), + 1 => (iterations, iterations), + _ => (1089 * iterations, 1089 * iterations), + }; + assert_eq!(new.1, expected); + before.push(old.0); + after.push(new.0); + } + before.sort_by(f64::total_cmp); + after.sort_by(f64::total_cmp); + println!( + "{name}: {:.1} -> {:.1} ns, {:.2}x; {iterations} iterations/sample", + before[4], + after[4], + before[4] / after[4] + ); + } +} diff --git a/crates/horizon-client/src/chunk_map.rs b/crates/horizon-client/src/chunk_map.rs new file mode 100644 index 000000000..81e06f020 --- /dev/null +++ b/crates/horizon-client/src/chunk_map.rs @@ -0,0 +1,122 @@ +//! Resident chunk membership, with a token for consumers that cache its keys. +use crate::{chunk::Chunk, fast_hash::FxHashMap}; +use std::{ + collections::hash_map::{Iter, ValuesMut}, + ops::Deref, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, +}; + +type Key = (i32, i32); +type Columns = FxHashMap>; +static NEXT_REVISION: AtomicU64 = AtomicU64::new(1); +fn next_revision() -> u64 { + NEXT_REVISION.fetch_add(1, Ordering::Relaxed) +} + +/// Read access behaves like a map. Structural writes are explicit so edits to +/// blocks or light don't invalidate consumers of the loaded chunk key set. +/// Tokens are process-wide: replacing the entire map also invalidates caches. +pub struct ChunkMap { + columns: Columns, + revision: u64, +} +impl Default for ChunkMap { + fn default() -> Self { + Self { + columns: Columns::default(), + revision: next_revision(), + } + } +} +impl ChunkMap { + pub fn membership_revision(&self) -> u64 { + self.revision + } + pub fn insert(&mut self, key: Key, chunk: Arc) -> Option> { + let previous = self.columns.insert(key, chunk); + if previous.is_none() { + self.revision = next_revision(); + } + previous + } + pub fn remove(&mut self, key: &Key) -> Option> { + let previous = self.columns.remove(key); + if previous.is_some() { + self.revision = next_revision(); + } + previous + } + pub fn clear(&mut self) { + if !self.columns.is_empty() { + self.columns.clear(); + self.revision = next_revision(); + } + } + pub fn get_mut(&mut self, key: &Key) -> Option<&mut Arc> { + self.columns.get_mut(key) + } + pub fn values_mut(&mut self) -> ValuesMut<'_, Key, Arc> { + self.columns.values_mut() + } +} +impl Deref for ChunkMap { + type Target = Columns; + fn deref(&self) -> &Columns { + &self.columns + } +} +impl<'a> IntoIterator for &'a ChunkMap { + type Item = (&'a Key, &'a Arc); + type IntoIter = Iter<'a, Key, Arc>; + fn into_iter(self) -> Self::IntoIter { + self.columns.iter() + } +} +impl crate::light::LightWorld for ChunkMap { + fn state(&self, x: i32, y: i32, z: i32) -> Option { + self.columns.state(x, y, z) + } + fn light(&self, x: i32, y: i32, z: i32) -> Option { + self.columns.light(x, y, z) + } + fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) { + self.columns.set_light(x, y, z, packed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn membership_tokens_track_keys_and_map_replacement_only() { + let mut map = ChunkMap::default(); + let empty = map.membership_revision(); + map.clear(); + map.remove(&(0, 0)); + assert_eq!(empty, map.membership_revision()); + let chunk = Arc::new(Chunk::empty(0, 0)); + map.insert((0, 0), chunk.clone()); + let inserted = map.membership_revision(); + assert_ne!(empty, inserted); + map.insert((0, 0), chunk.clone()); + Arc::make_mut(map.get_mut(&(0, 0)).unwrap()).lit = true; + for column in map.values_mut() { + Arc::make_mut(column).light_loaded = true; + } + crate::light::LightWorld::set_light(&mut map, 0, 0, 0, 0); + assert_eq!(inserted, map.membership_revision()); + map.remove(&(0, 0)); + map.insert((1, 0), chunk); + assert_eq!(map.len(), 1); + assert_ne!(inserted, map.membership_revision()); + let replaced = map.membership_revision(); + map.clear(); + assert_ne!(replaced, map.membership_revision()); + let cleared = map.membership_revision(); + map = ChunkMap::default(); + assert_ne!(cleared, map.membership_revision()); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0ea76b2ec..9221a7485 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -840,7 +840,7 @@ struct Game<'a> { end_portal_travel: bool, end: end::EndState, block_ticks: Ticks, - tick_chunks: HashSet<(i32, i32)>, + tick_chunks: horizon_client::tick_chunk_membership::TickChunkMembership, level_events: Vec, falling: Vec, paintings: Vec, @@ -1557,15 +1557,19 @@ impl Game<'_> { } /// Track which chunks are ticking (Ticks needs chunk load/unload). fn sync_tick_chunks(&mut self) { - let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); - for k in loaded.difference(&self.tick_chunks.clone()) { - self.register_chunk_ticks(*k); + if !self.tick_chunks.synchronize(&self.world.chunks) { + return; } - for k in self.tick_chunks.difference(&loaded) { + // Move only the added keys out so registration can borrow all of Game. + let added = self.tick_chunks.take_added(); + for &key in &added { + self.register_chunk_ticks(key); + } + for &key in self.tick_chunks.removed() { self.block_ticks - .remove_chunk(horizon_core::position::ChunkPos::new(k.0, k.1)); + .remove_chunk(horizon_core::position::ChunkPos::new(key.0, key.1)); } - self.tick_chunks = loaded; + self.tick_chunks.recycle_added(added); } /// ServerLevel.tick block phases: scheduled ticks, random ticks within the /// simulation distance, block events and moving pistons. @@ -9495,7 +9499,7 @@ pub fn run() -> Result<()> { end_portal_travel: false, end: Default::default(), block_ticks: Ticks::new(0), - tick_chunks: HashSet::new(), + tick_chunks: Default::default(), level_events: Vec::new(), falling: Vec::new(), paintings: Vec::new(), diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index e9cae01e3..d88d7693e 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -27,6 +27,7 @@ pub mod camera; pub mod cauldron; pub mod chat; pub mod chunk; +pub mod chunk_map; pub mod clipboard; pub mod clock; pub mod clouds; @@ -149,6 +150,7 @@ pub mod tab_list; pub mod telemetry; pub mod testgen; pub mod text; +pub mod tick_chunk_membership; pub mod title; pub mod title_edition; pub mod ui; diff --git a/crates/horizon-client/src/tick_chunk_membership.rs b/crates/horizon-client/src/tick_chunk_membership.rs new file mode 100644 index 000000000..42785f289 --- /dev/null +++ b/crates/horizon-client/src/tick_chunk_membership.rs @@ -0,0 +1,226 @@ +//! Tick scheduler membership, invalidated by resident key changes or resets. +use crate::chunk_map::ChunkMap; +use std::collections::HashSet; + +type Key = (i32, i32); + +#[derive(Default)] +pub struct TickChunkMembership { + keys: HashSet, + revision: Option, + added: Vec, + removed: Vec, +} + +impl TickChunkMembership { + /// A scheduler reset must re-register resident chunks even if the world did + /// not change. Keep this invalidation with the keys so callers cannot forget. + pub fn clear(&mut self) { + self.keys.clear(); + self.revision = None; + self.added.clear(); + self.removed.clear(); + } + + /// Returns false in O(1) when resident membership is unchanged. On change, + /// update the existing set and record only registration/removal deltas. + pub fn synchronize(&mut self, chunks: &ChunkMap) -> bool { + let revision = chunks.membership_revision(); + if self.revision == Some(revision) { + return false; + } + self.added.clear(); + self.removed.clear(); + self.keys.retain(|key| { + if chunks.contains_key(key) { + true + } else { + self.removed.push(*key); + false + } + }); + for &key in chunks.keys() { + if self.keys.insert(key) { + self.added.push(key); + } + } + self.revision = Some(revision); + true + } + + /// Allows registration to borrow the owning Game without cloning its set. + pub fn take_added(&mut self) -> Vec { + std::mem::take(&mut self.added) + } + + /// Retain scratch capacity after registration. + pub fn recycle_added(&mut self, mut added: Vec) { + added.clear(); + self.added = added; + } + + pub fn removed(&self) -> &[Key] { + &self.removed + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::chunk::Chunk; + use std::sync::Arc; + + fn compare(cache: &mut TickChunkMembership, old: &mut HashSet, map: &ChunkMap) { + let loaded: HashSet<_> = map.keys().copied().collect(); + let expected_added: HashSet<_> = loaded.difference(old).copied().collect(); + let expected_removed: HashSet<_> = old.difference(&loaded).copied().collect(); + if cache.synchronize(map) { + let added = cache.take_added(); + assert_eq!( + added.iter().copied().collect::>(), + expected_added + ); + assert_eq!( + cache.removed().iter().copied().collect::>(), + expected_removed + ); + cache.recycle_added(added); + } else { + assert!(expected_added.is_empty() && expected_removed.is_empty()); + } + assert_eq!(cache.keys, loaded); + *old = loaded; + } + + #[test] + fn matches_old_deltas_through_load_unload_replacement_and_reset() { + let mut map = ChunkMap::default(); + let chunk = Arc::new(Chunk::empty(0, 0)); + let mut cache = TickChunkMembership::default(); + let mut old = HashSet::new(); + compare(&mut cache, &mut old, &map); + assert!(!cache.synchronize(&map)); + for key in [(-16, -8), (0, 0), (12, -1)] { + map.insert(key, chunk.clone()); + compare(&mut cache, &mut old, &map); + } + map.remove(&(-16, -8)); + map.insert((-15, -8), chunk.clone()); // Same count, different key. + compare(&mut cache, &mut old, &map); + map.insert((0, 0), Arc::new(Chunk::empty(0, 0))); + assert!(!cache.synchronize(&map)); // Payload replacement needs no registration. + cache.clear(); + old.clear(); // Scheduler replaced with unchanged resident map. + compare(&mut cache, &mut old, &map); + map.clear(); + compare(&mut cache, &mut old, &map); + map = ChunkMap::default(); + assert!(cache.synchronize(&map)); // Distinct empty world has distinct token. + map.insert((-2, 4), chunk); + compare(&mut cache, &mut old, &map); + cache.clear(); + old.clear(); + map = ChunkMap::default(); + compare(&mut cache, &mut old, &map); + } + + #[test] + fn scheduler_keeps_saved_ticks_on_stable_membership_and_removes_unloaded_chunks() { + use horizon_core::{ + position::{BlockPos, ChunkPos}, + ticks::{ChunkTicks, SavedTick, TickPriority, TickTypeId}, + }; + use horizon_world::level::Ticks; + + fn register(ticks: &mut Ticks, key: Key) { + let pos = ChunkPos::new(key.0, key.1); + let saved = SavedTick { + kind: TickTypeId(1), + pos: BlockPos::new(key.0 * 16, 0, key.1 * 16), + delay: 5, + priority: TickPriority::Normal, + }; + ticks + .add_chunk( + pos, + ChunkTicks::from_saved(vec![saved]), + ChunkTicks::from_saved(vec![saved]), + ) + .unwrap(); + ticks.blocks.unpack_chunk(pos, 100); + ticks.fluids.unpack_chunk(pos, 100); + } + let mut map = ChunkMap::default(); + let chunk = Arc::new(Chunk::empty(0, 0)); + let mut cache = TickChunkMembership::default(); + let mut old_keys = HashSet::new(); + let mut old_ticks = Ticks::default(); + let mut new_ticks = Ticks::default(); + let keys = [(-3, -1), (2, 4), (-2, -1)]; + for step in 0..7 { + match step { + 0 => { + map.insert(keys[0], chunk.clone()); + map.insert(keys[1], chunk.clone()); + } + 2 => { + map.remove(&keys[0]); + map.insert(keys[2], chunk.clone()); + } + 3 => { + map.insert(keys[1], chunk.clone()); + } + 4 => { + // Reset only the scheduler: resident token is unchanged. + new_ticks = Ticks::default(); + old_ticks = Ticks::default(); + cache.clear(); + old_keys.clear(); + } + 5 => { + map.clear(); + } + 6 => { + map = ChunkMap::default(); + map.insert(keys[0], chunk.clone()); + new_ticks = Ticks::default(); + old_ticks = Ticks::default(); + cache.clear(); + old_keys.clear(); + } + _ => {} + } + let loaded: HashSet<_> = map.keys().copied().collect(); + for &key in loaded.difference(&old_keys) { + register(&mut old_ticks, key); + } + for &key in old_keys.difference(&loaded) { + old_ticks.remove_chunk(ChunkPos::new(key.0, key.1)); + } + old_keys = loaded; + if cache.synchronize(&map) { + let added = cache.take_added(); + for &key in &added { + register(&mut new_ticks, key); + } + for &key in cache.removed() { + new_ticks.remove_chunk(ChunkPos::new(key.0, key.1)); + } + cache.recycle_added(added); + } + for key in keys { + let pos = ChunkPos::new(key.0, key.1); + for (old, new) in [ + (&old_ticks.blocks, &new_ticks.blocks), + (&old_ticks.fluids, &new_ticks.fluids), + ] { + assert_eq!( + old.chunk(pos).map(|c| c.queued()), + new.chunk(pos).map(|c| c.queued()) + ); + assert_eq!(new.chunk(pos).is_some(), map.contains_key(&key)); + } + } + } + } +} diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 1b589041d..2d8213905 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -10,7 +10,7 @@ use std::{ pub struct World { pub fast_lava: bool, - pub chunks: crate::fast_hash::FxHashMap<(i32, i32), Arc>, + pub chunks: crate::chunk_map::ChunkMap, pub random: LegacyRandom, pub revision: u64, pub health_rules: crate::health::HealthRules,