From 745c756df52db1be9dc8ba0d601dc0a211fd5f12 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:21:20 +0100 Subject: [PATCH 1/9] perf(worldgen): cache carver biomes per worker --- .../horizon-world/src/worldgen/generator.rs | 68 ++++++++++++++++++- 1 file changed, 66 insertions(+), 2 deletions(-) diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7b73d35a8..75c3b3a6b 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -906,7 +906,15 @@ where Ok(chunk) } fn carver_biome(&self, worker: &mut WorkerState, origin: ChunkPos) -> Result { - if let Some(id) = self.carver_cache.lock().unwrap().get(&(origin.x, origin.z)) { + let key = (origin.x, origin.z); + if let Some(id) = worker.carver_biomes.get(&key) { + return Ok(*id); + } + if worker.carver_biomes.len() >= 4096 { + worker.carver_biomes.clear(); + } + if let Some(id) = self.carver_cache.lock().unwrap().get(&key) { + worker.carver_biomes.insert(key, *id); return Ok(*id); } let mut resolver = self.source.resolver( @@ -926,7 +934,8 @@ where if cache.len() >= CACHE_LIMIT * 4 { cache.clear(); } - cache.insert((origin.x, origin.z), id); + cache.insert(key, id); + worker.carver_biomes.insert(key, id); Ok(id) } fn generate( @@ -1393,6 +1402,9 @@ pub(super) struct WorkerState { pub(super) temperatures: Vec, biome_context: SamplerContext, carver_context: SamplerContext, + /// Seed/dimension-bound lookups avoid the shared mutex for overlapping + /// carver neighborhoods. Bounded independently of the shared cache. + carver_biomes: HashMap<(i32, i32), BiomeId>, timings: StageTimings, heights: HashMap<(i32, i32, u8), i32>, /// Decorate with structure pieces only (for structure parity checks). @@ -1868,6 +1880,7 @@ impl OverworldGenerator { .collect(), biome_context: SamplerContext::cached(), carver_context: SamplerContext::default(), + carver_biomes: HashMap::new(), timings: StageTimings::default(), structures_only: false, heights: HashMap::new(), @@ -1947,6 +1960,57 @@ impl GeneratorWorker { mod tests { use super::*; + #[test] + fn local_carver_cache_is_worker_owned_and_eviction_preserves_terrain() { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("worldgen/world_presets.json").exists() { + eprintln!("skipping: no worldgen bundle at {}", root.display()); + return; + } + let registry = Box::leak(Box::new( + crate::level::data::load_registry(&root).expect("registry"), + )); + let data = GeneratorData::load(&root.join("worldgen"), registry).unwrap(); + let generator = OverworldGenerator::new(data.clone(), 12345).unwrap(); + let mut first = generator.worker(); + let mut second = generator.worker(); + let pos = ChunkPos::new(0, 0); + let before = first.generate_proto(pos).unwrap(); + assert!(!first.state.carver_biomes.is_empty()); + assert!(second.state.carver_biomes.is_empty()); + second.generate_proto(pos).unwrap(); + assert_eq!(first.state.carver_biomes, second.state.carver_biomes); + let expected = first.state.carver_biomes.clone(); + first.state.carver_biomes.clear(); + // Fill unrelated origins to force eviction on the next local miss. + for x in 0..4096 { + first.state.carver_biomes.insert((x, 100_000), BiomeId(0)); + } + let after = first.generate_proto(pos).unwrap(); + assert_eq!(first.state.carver_biomes, expected); + for y in -64..320 { + for z in 0..16 { + for x in 0..16 { + assert_eq!(before.block(x, y, z), after.block(x, y, z)); + assert_eq!(before.biome_id_at(x, y, z), after.biome_id_at(x, y, z)); + } + } + } + assert!( + OverworldGenerator::new(data, -1) + .unwrap() + .worker() + .state + .carver_biomes + .is_empty() + ); + assert_eq!(second.state.carver_biomes, expected); + } + /// Generators of one seed and dimension share their ring positions; /// another seed or generator gets its own, and old entries go. #[test] From 08c77ad78534e5079fed9ba152e1b2d27142b0bf Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:15:22 +0200 Subject: [PATCH 2/9] Spawn mobs around every player, and despawn from the nearest of them Natural spawning returned without a local player, so a dedicated or --server-thread server spawned no mobs and a LAN host spawned them only around itself. ServerChunkCache.tickChunks now takes its spawning chunks from every player in the level (ChunkMap.collectSpawningChunks), the global caps from the natural spawn chunk tracker's size, and the local caps from each player (LocalMobCapCalculator). Inhabited time and thunder follow the same chunks (tickSpawningChunk), the wandering trader picks a random living player (getRandomPlayer), and mobs despawn by their distance to the nearest non-spectator of any kind. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 1 + crates/horizon-client/src/game/creatures.rs | 32 ++-- crates/horizon-client/src/game/lightning.rs | 8 +- .../src/game/natural_spawning.rs | 177 ++++++++++++++---- .../src/game/wandering_trader.rs | 25 ++- crates/horizon-client/src/mobs.rs | 3 + crates/horizon-client/src/mobs/ai.rs | 6 +- 7 files changed, 179 insertions(+), 73 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 0b3adec31..2a4969221 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -1024,6 +1024,7 @@ fn main() -> horizon_client::Result<()> { collision: &collision, data: &data, player: player.clone(), + nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position), others: $snapshot, others_grid: $grid, daylight: (world.day_time.rem_euclid(24000)) < 12000, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 422d050b6..d82e8a5aa 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -377,6 +377,7 @@ impl Game<'_> { } pub(super) fn mob_world_base<'s>(&'s self, others: &'s [Seen]) -> MobWorld<'s> { let (rain, thunder) = self.world.weather.levels(1.0); + let player = self.player_view(); MobWorld { world: &self.world, registry: self.pack.assets.registry, @@ -384,7 +385,8 @@ impl Game<'_> { movement: &self.motion.blocks, collision: self.collision, data: self.res.mob_data(), - player: self.player_view(), + nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position), + player, others, others_grid: None, daylight: self.dim != Dim::Nether && self.sky_darken() < 4, @@ -429,25 +431,6 @@ impl Game<'_> { }; spawning::LocalDifficulty::new(base, self.world.day_time, inhabited, moon) } - /// `ServerChunkCache.tickSpawningChunk`: chunks whose centre is within - /// 128 blocks of the player gain inhabited time. - fn tick_inhabited(&mut self) { - let Some(p) = self.player.as_ref().map(|p| p.position) else { - return; - }; - let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4); - for dx in -8..=8 { - for dz in -8..=8 { - let key = (pcx + dx, pcz + dz); - let (cx, cz) = (f64::from(key.0 * 16 + 8), f64::from(key.1 * 16 + 8)); - if (cx - p.x).powi(2) + (cz - p.z).powi(2) < 128.0 * 128.0 - && self.world.chunks.contains_key(&key) - { - *self.world.inhabited.entry(key).or_insert(0) += 1; - } - } - } - } /// Advance every mob one tick, then apply their events. pub(super) fn tick_creatures(&mut self) -> Result<()> { self.attack_ticks = self.attack_ticks.saturating_add(1); @@ -464,7 +447,6 @@ impl Game<'_> { } self.spawn_generation_creatures(key.0, key.1); } - self.tick_inhabited(); self.tick_leads(); self.spawn_natural(); // ServerChunkCache.tickChunks: the custom spawners tick only with spawn_mobs. @@ -505,6 +487,7 @@ impl Game<'_> { let ticking = self.entity_ticking_area(); // With guests on, each mob sees its nearest player (game/lan_mobs.rs). let guests = self.lan_guest_views(); + let players = self.level_players(); let mut bindings = match self.lan.as_mut() { Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players), _ => Default::default(), @@ -523,6 +506,13 @@ impl Game<'_> { let mut w = self.mob_world_base(&snapshot); w.others_grid = Some(&grid); let m = &mut mobs[i]; + w.nearest_player = super::natural_spawning::nearest_player( + &players, + m.position.x, + m.position.y, + m.position.z, + ) + .map(|p| p.position); let seen_guest = if guests.is_empty() { None } else { diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 7b480a8e6..6c4dd933f 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -24,14 +24,18 @@ pub(super) struct Bolt { converted: Vec, } impl Game<'_> { - /// One `tickThunder` roll per loaded chunk. + /// `ServerChunkCache.tickSpawningChunk`: one `tickThunder` roll per + /// spawning chunk (within 128 blocks of a player) that is in entity + /// ticking range. pub(super) fn tick_thunder(&mut self) { // isRaining (rain level > 0.2) and isThundering (> 0.9, sky light, no ceiling). let (rain, thunder) = self.world.weather.levels(1.0); if rain <= 0.2 || thunder <= 0.9 || self.dim != super::Dim::Overworld { return; } - let chunks: Vec<(i32, i32)> = self.world.chunks.keys().copied().collect(); + let (_, mut chunks) = self.spawning_chunks(&self.level_players()); + let levels = self.tickets.levels(); + chunks.retain(|&(x, z)| levels.random_ticking(x, z)); for (cx, cz) in chunks { if self.world.random.next_int_bound(100_000).unwrap_or(1) != 0 { continue; diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 059437d7b..9bf7023af 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -23,10 +23,54 @@ use horizon_core::{ use horizon_world::registry::BlockStateId; use std::collections::HashMap; +/// A player in the level in place, as spawning and despawning see it. +pub(super) struct LevelPlayer { + pub(super) position: Vec3, + pub(super) bounds: Aabb, + pub(super) alive: bool, + pub(super) creative: bool, + pub(super) spectator: bool, +} +impl LevelPlayer { + fn distance_sqr(&self, x: f64, y: f64, z: f64) -> f64 { + (self.position.x - x).powi(2) + + (self.position.y - y).powi(2) + + (self.position.z - z).powi(2) + } +} +/// `ChunkMap.euclideanDistanceSquared` below 128 blocks +/// (`playerIsCloseEnoughForSpawning`). +fn close_enough_for_spawning(p: &LevelPlayer, (cx, cz): (i32, i32)) -> bool { + let (x, z) = ( + f64::from(cx * 16 + 8) - p.position.x, + f64::from(cz * 16 + 8) - p.position.z, + ); + !p.spectator && x * x + z * z < 16384.0 +} +/// `EntityGetter.getNearestPlayer(x, y, z, -1, false)`: the nearest +/// non-spectator, alive or not. +pub(super) fn nearest_player( + players: &[LevelPlayer], + x: f64, + y: f64, + z: f64, +) -> Option<&LevelPlayer> { + let mut best: Option<(&LevelPlayer, f64)> = None; + for p in players.iter().filter(|p| !p.spectator) { + let d = p.distance_sqr(x, y, z); + if best.is_none_or(|(_, b)| d < b) { + best = Some((p, d)); + } + } + best.map(|(p, _)| p) +} + /// The game level as natural spawning reads it. pub(super) struct GameLevel<'g, 'a> { pub(super) game: &'g Game<'a>, pub(super) w: MobWorld<'g>, + /// Every player in the level ([`Game::level_players`]). + pub(super) players: Vec, /// Boxes of the mobs this pass created, not yet in the game's list. pub(super) pending: std::cell::RefCell>, /// The types and boxes of what a spawner created this tick. @@ -84,8 +128,11 @@ impl SpawnLevel for GameLevel<'_, '_> { fn world_seed(&self) -> i64 { self.w.world_seed } + /// `getNearestPlayer(x, y, z, distance, true)`, over every player. fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { - self.w.player_near(x, y, z, distance) + self.players.iter().any(|p| { + p.alive && !p.creative && !p.spectator && p.distance_sqr(x, y, z) < distance * distance + }) } } impl NaturalLevel for GameLevel<'_, '_> { @@ -138,12 +185,7 @@ impl NaturalLevel for GameLevel<'_, '_> { StructureSpawns::shared(&self.game.options.resources) } fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option { - let p = self.game.player.as_ref()?; - if self.game.spectator() { - return None; - } - let d = [p.position.x - x, p.position.y - y, p.position.z - z]; - Some(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]) + nearest_player(&self.players, x, y, z).map(|p| p.distance_sqr(x, y, z)) } fn respawn(&self) -> Option<[i32; 3]> { // The world spawn point lives in the overworld. @@ -184,9 +226,9 @@ impl NaturalLevel for GameLevel<'_, '_> { } fn unobstructed(&self, bounds: Aabb) -> bool { let player = self - .game - .player_view() - .is_some_and(|p| p.alive && !p.spectator && p.bounds.intersects(bounds)); + .players + .iter() + .any(|p| p.alive && !p.spectator && p.bounds.intersects(bounds)); !player && !self.pending.borrow().iter().any(|b| b.intersects(bounds)) && !self @@ -221,17 +263,10 @@ impl NaturalLevel for GameLevel<'_, '_> { } } impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> { + /// `Level.hasNearbyAlivePlayer`, over every player. fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool { - let Some(p) = self.game.player_view() else { - return false; - }; - if !p.alive || p.spectator { - return false; - } - let at = self.game.player.as_ref().map(|p| p.position); - at.is_some_and(|a| { - let d = (a.x - x).powi(2) + (a.y - y).powi(2) + (a.z - z).powi(2); - range < 0.0 || d < range * range + self.players.iter().any(|p| { + p.alive && !p.spectator && (range < 0.0 || p.distance_sqr(x, y, z) < range * range) }) } fn spawner_blocks_work(&self) -> bool { @@ -261,6 +296,7 @@ impl<'a> Game<'a> { GameLevel { game: self, w: self.mob_world_base(&[]), + players: self.level_players(), pending: Default::default(), pending_ids: Default::default(), } @@ -299,25 +335,82 @@ impl<'a> Game<'a> { } } } + /// Every player in the level in place: the local player, and the LAN + /// guests or server players in it. + pub(super) fn level_players(&self) -> Vec { + let mut players: Vec = self.lan.as_ref().map_or_else(Vec::new, |h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g)) + .map(|g| LevelPlayer { + position: Vec3::new(g.position[0], g.position[1], g.position[2]), + bounds: super::lan_mobs::guest_bounds(g), + alive: !g.dead, + creative: g.creative(), + spectator: g.spectator(), + }) + .collect() + }); + if let Some(p) = self.player_view() { + players.insert( + 0, + LevelPlayer { + position: p.position, + bounds: p.bounds, + alive: p.alive, + creative: p.creative, + spectator: p.spectator, + }, + ); + } + players + } + /// `ChunkMap.collectSpawningChunks`: the natural spawn chunk tracker's + /// chunks (within 8 chunks of a player, `getSpawnCandidateChunks`) that + /// are ticking and within 128 blocks of a non-spectator. Also returns how + /// many chunks the tracker holds (`getNaturalSpawnChunkCount`). + pub(super) fn spawning_chunks(&self, players: &[LevelPlayer]) -> (i32, Vec<(i32, i32)>) { + let mut candidates: Vec<(i32, i32)> = Vec::with_capacity(289 * players.len()); + let mut seen = horizon_client::fast_hash::FxHashSet::default(); + for p in players { + let (pcx, pcz) = ( + p.position.x.floor() as i32 >> 4, + p.position.z.floor() as i32 >> 4, + ); + for dx in -8..=8 { + for dz in -8..=8 { + let key = (pcx + dx, pcz + dz); + if seen.insert(key) { + candidates.push(key); + } + } + } + } + let count = candidates.len() as i32; + let levels = self.tickets.levels(); + candidates.retain(|&(cx, cz)| { + levels.loaded_ticking(cx, cz) + && super::ticking_chunk(&self.world, cx, cz) + && players + .iter() + .any(|p| close_enough_for_spawning(p, (cx, cz))) + }); + (count, candidates) + } /// `ServerChunkCache.tickChunks`: the spawn state over the loaded mobs, /// the categories under their global caps (creatures every 400 ticks), - /// then `spawnForChunk` in the shuffled chunks within 128 blocks of the - /// player. + /// then `tickSpawningChunk` in the shuffled spawning chunks of every + /// player: inhabited time, then `spawnForChunk`. pub(super) fn spawn_natural(&mut self) { - let Some(p) = self.player.as_ref().map(|p| p.position) else { + let players = self.level_players(); + if players.is_empty() { return; - }; - let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4); - // ChunkMap.collectSpawningChunks: tracked chunks whose centre is - // within 128 blocks of a non-spectator. - let spectator = self.spectator(); - let mut chunks: Vec<(i32, i32)> = (-8..=8) - .flat_map(|dx| (-8..=8).map(move |dz| (pcx + dx, pcz + dz))) - .filter(|&(cx, cz)| { - let (x, z) = (f64::from(cx * 16 + 8) - p.x, f64::from(cz * 16 + 8) - p.z); - !spectator && x * x + z * z < 16384.0 && self.world.chunks.contains_key(&(cx, cz)) - }) - .collect(); + } + let (spawnable, mut chunks) = self.spawning_chunks(&players); + for &key in &chunks { + *self.world.inhabited.entry(key).or_insert(0) += 1; + } let spawn_mobs = self.ui.rules.bool("spawn_mobs"); let spawn_enemies = self.ui.rules.bool("spawn_monsters"); let mut random = std::mem::replace(&mut self.world.random, LegacyRandom::new(0)); @@ -339,12 +432,14 @@ impl<'a> Game<'a> { persistent: m.persistent, }) .collect(); - let players = vec![SpawnPlayer { - position: [p.x, p.y, p.z], - spectator, - }]; - // A single player's natural spawn chunk tracker covers 17 x 17 chunks. - let mut state = SpawnState::new(&level, 289, players, &counted, |cx, cz| { + let players = players + .iter() + .map(|p| SpawnPlayer { + position: [p.position.x, p.position.y, p.position.z], + spectator: p.spectator, + }) + .collect(); + let mut state = SpawnState::new(&level, spawnable, players, &counted, |cx, cz| { self.world.chunks.contains_key(&(cx, cz)) }); let categories = if spawn_mobs { diff --git a/crates/horizon-client/src/game/wandering_trader.rs b/crates/horizon-client/src/game/wandering_trader.rs index d42ac662f..87ca5753b 100644 --- a/crates/horizon-client/src/game/wandering_trader.rs +++ b/crates/horizon-client/src/game/wandering_trader.rs @@ -6,7 +6,7 @@ use horizon_client::{ mobs::{Species, leash::Holder, spawning, trader}, save::{read_dat, write_dat}, }; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_world::nbt::Tag; const TICK_DELAY: i32 = 1200; @@ -83,10 +83,7 @@ impl Game<'_> { } /// `WanderingTraderSpawner.tick`. pub(super) fn tick_wandering_trader(&mut self) { - if self.dim != Dim::Overworld - || self.player.is_none() - || !self.ui.rules.bool("spawn_wandering_traders") - { + if self.dim != Dim::Overworld || !self.ui.rules.bool("spawn_wandering_traders") { return; } self.load_trader_data(); @@ -110,9 +107,23 @@ impl Game<'_> { } /// `WanderingTraderSpawner.spawn`. fn spawn_trader(&mut self) -> bool { - let Some(p) = self.player.as_ref().map(|p| p.position) else { + // ServerLevel.getRandomPlayer: one of the living players, drawn + // from the level random. + let alive: Vec = self + .level_players() + .into_iter() + .filter(|p| p.alive) + .map(|p| p.position) + .collect(); + if alive.is_empty() { return true; - }; + } + let pick = self + .world + .random + .next_int_bound(alive.len() as i32) + .unwrap_or(0); + let p = alive[pick as usize]; if self.world.random.next_int_bound(10).unwrap_or(1) != 0 { return false; } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 3fe743fab..c8155984c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1412,6 +1412,9 @@ pub struct MobWorld<'a> { pub collision: &'a BlockCollisionRegistry<'a>, pub data: &'a MobData, pub player: Option, + /// `getNearestPlayer(mob, -1)`: where the nearest non-spectator of every + /// player in the level stands, alive or not (the despawn distance). + pub nearest_player: Option, pub others: &'a [Seen], /// `others` by position, when the caller keeps one (the mob ticks). pub others_grid: Option<&'a seen_grid::SeenGrid>, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 709a57619..34276ddda 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1018,8 +1018,10 @@ pub fn despawn_check(m: &mut Mob, w: &MobWorld) -> bool { /// Mob.checkDespawn, before the tick (players are the only despawn /// reference). Returns false when the mob is discarded. fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { - let Some(p) = &w.player else { return true }; - let d = m.distance_sqr(p.position); + let Some(p) = w.nearest_player else { + return true; + }; + let d = m.distance_sqr(p); // requiresCustomPersistence: raiders in a raid, a tame nautilus, a sulfur // cube holding a block or let out of a bucket. let persistent = m.persistent From c755ca04f5bb1fae597841848479b362fff935e9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:31:12 +0200 Subject: [PATCH 3/9] Tick paintings, frames, boats, armor stands, falling blocks and TNT only in entity-ticking chunks ServerLevel.tick ticks an entity only where the chunk tickets make it entity ticking (inEntityTickingRange, and EntityTickList holds only the entities of entity-ticking chunks). Mobs, items and minecarts already checked it (#931); these six entity kinds ticked wherever they were loaded, so TNT went off and sand fell past the simulation distance. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 5 +++++ crates/horizon-client/src/game/armor_stands.rs | 5 +++++ crates/horizon-client/src/game/boats.rs | 7 ++++++- crates/horizon-client/src/game/frames.rs | 7 +++++++ crates/horizon-client/src/game/paintings.rs | 8 ++++++++ crates/horizon-client/src/game/tnt.rs | 6 ++++++ 6 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2cbdabaa4..772a26730 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2594,7 +2594,12 @@ impl Game<'_> { let mut dropped = Vec::new(); let mut collision_error = None; let entity_drops = self.ui.rules.bool("entity_drops"); + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); falling.retain_mut(|f| { + if !ticking(f.position.x.floor() as i32, f.position.z.floor() as i32) { + return true; + } let original = f.clone(); f.previous = f.position; f.age = f.age.wrapping_add(1); diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 6ff5c7c15..58cd27494 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -382,7 +382,12 @@ impl Game<'_> { subject: None, }; let mut dead = Vec::new(); + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); for (i, a) in self.armor_stands.iter_mut().enumerate() { + if !ticking(a.position.x.floor() as i32, a.position.z.floor() as i32) { + continue; + } a.tick(&mut scene); if !a.environment_tick(&self.world, self.res.facts(), self.pack.assets.registry) { dead.push(i); diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 1d1a6b628..f9740598e 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -443,8 +443,13 @@ impl Game<'_> { } /// Every boat but the ridden one (which ticks with its rider). pub(super) fn tick_boats(&mut self) { + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); for i in 0..self.boats.len() { - if Some(self.boats[i].id) == self.riding { + let p = self.boats[i].position; + if Some(self.boats[i].id) == self.riding + || !ticking(p.x.floor() as i32, p.z.floor() as i32) + { continue; } let b = self.boats[i].clone(); diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 857eb40a4..7f5e6c26a 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -282,8 +282,15 @@ impl Game<'_> { } /// BlockAttachedEntity.tick for frames. pub(super) fn tick_item_frames(&mut self) { + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); let mut i = 0; while i < self.item_frames.len() { + let at = center(&self.item_frames[i]); + if !ticking(at[0].floor() as i32, at[2].floor() as i32) { + i += 1; + continue; + } self.item_frames[i].check_interval += 1; if self.item_frames[i].check_interval >= 100 { self.item_frames[i].check_interval = 0; diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index bd2884575..321e59f7d 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -232,8 +232,16 @@ impl Game<'_> { } /// BlockAttachedEntity.tick: check survival every 100 ticks. pub(super) fn tick_paintings(&mut self) { + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); let mut i = 0; while i < self.paintings.len() { + let (lo, hi) = self.paintings[i].bounds(); + let centre = [0, 2].map(|k| ((lo[k] + hi[k]) / 2.0).floor() as i32); + if !ticking(centre[0], centre[1]) { + i += 1; + continue; + } self.paintings[i].check_interval += 1; if self.paintings[i].check_interval >= 100 { self.paintings[i].check_interval = 0; diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 92da4a0bb..80ad97d7f 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -156,8 +156,14 @@ impl Game<'_> { pub(super) fn tick_tnt(&mut self) -> Result<()> { let mut count = self.tnts.len(); let mut i = 0; + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); while i < count { let t = &mut self.tnts[i]; + if !ticking(t.position.x.floor() as i32, t.position.z.floor() as i32) { + i += 1; + continue; + } t.tick( &self.world, self.collision, From e805e9886c06d37685c27e3056717e425da4aa59 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:55:45 +0200 Subject: [PATCH 4/9] Scan for the motion-blocking top from the world surface, not the build limit getHeightmapPos(MOTION_BLOCKING) walked every column from y 319 down, one block lookup per y. Each precipitation roll (3 in 48 per ticking chunk per tick) and each isRainingAt paid for it: with the chunks of 10 players ticking it was most of tick_blocks. Only air lies above the WORLD_SURFACE heightmap the chunk already keeps, and air neither blocks motion nor holds a fluid, so the scan starts there. LevelAccess gains world_surface (the build limit by default, so other levels scan as before). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 3 +++ crates/horizon-world/src/level/mod.rs | 6 ++++++ crates/horizon-world/src/level/weather.rs | 6 ++++-- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2cbdabaa4..13d75817d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -510,6 +510,9 @@ impl EntityObstructionWorld for PlayerObstruction { } } impl LevelAccess for GameLevel<'_> { + fn world_surface(&self, x: i32, z: i32) -> i32 { + self.world.world_surface(x, z, |s| self.facts.is_air(s)) + } fn precipitation(&self, pos: BlockPos) -> Option { self.behaviours.precipitation_info(self, pos) } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index f1f0b21ac..c706ca280 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -301,6 +301,12 @@ pub trait LevelAccess { fn max_y(&self) -> i32 { 320 } + /// `getHeight(WORLD_SURFACE, x, z)`: one above the column's highest + /// block that isn't air. Only air lies above it, so scans for the other + /// heightmaps start there. The default, `max_y`, scans the whole column. + fn world_surface(&self, _x: i32, _z: i32) -> i32 { + self.max_y() + } /// Vanilla `level.random` (a `LegacyRandomSource`). fn random(&mut self) -> &mut LegacyRandom; fn game_time(&self) -> i64; diff --git a/crates/horizon-world/src/level/weather.rs b/crates/horizon-world/src/level/weather.rs index c43d96b15..93027d889 100644 --- a/crates/horizon-world/src/level/weather.rs +++ b/crates/horizon-world/src/level/weather.rs @@ -40,14 +40,16 @@ impl Behaviours { BiomePrecipitation::Rain } } - /// `getHeightmapPos(MOTION_BLOCKING, pos)`. + /// `getHeightmapPos(MOTION_BLOCKING, pos)`, scanning down from the + /// world surface (air neither blocks motion nor holds a fluid). pub fn motion_blocking_top( &self, level: &L, pos: BlockPos, ) -> BlockPos { let blocks = self.tag("minecraft:blocks_motion_in_heightmap"); - for y in (level.min_y()..level.max_y()).rev() { + let top = level.world_surface(pos.x, pos.z).min(level.max_y()); + for y in (level.min_y()..top).rev() { let state = level.block_state(BlockPos::new(pos.x, y, pos.z)); let fluid = self.fluid(state).kind() != FluidKind::Empty; if fluid || blocks.is_some_and(|t| t.contains(self.block(state))) { From 6a4bed4744eeb1b1e905ca2bab29ca7e9a5c399a Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:52:21 +0100 Subject: [PATCH 5/9] Coordinate concurrent neighbour cache misses by chunk key --- .../horizon-world/src/worldgen/generator.rs | 148 ++++++++++++++++++ .../src/worldgen/generator_structures.rs | 13 +- 2 files changed, 160 insertions(+), 1 deletion(-) diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7b73d35a8..ee0805d9a 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -635,6 +635,7 @@ struct Pipeline { picker: GlobalFluidPicker, zoom: BiomeZoom, biome_cache: BiomeCache, + biome_work: ChunkWork, carver_cache: Mutex>, pub(super) decoration: Option, pub(super) structures: Option, @@ -643,6 +644,30 @@ struct Pipeline { spawn_position: std::sync::OnceLock<[i32; 2]>, } const CACHE_LIMIT: usize = 16384; +/// Coordinates only equal missing neighbour keys. Weak entries retain no +/// computed values across eviction or explicit invalidation. Only one work +/// lock may be held at a time; finish shared prerequisites before acquiring it. +pub(super) struct ChunkWork(Mutex>>>); +impl ChunkWork { + pub(super) fn new() -> Self { + Self(Mutex::new(HashMap::new())) + } + pub(super) fn at(&self, key: (i32, i32)) -> Arc> { + let mut work = self.0.lock().unwrap(); + if let Some(lock) = work.get(&key).and_then(std::sync::Weak::upgrade) { + return lock; + } + if work.len() >= 4096 { + // Keep every active builder/waiter on its original lock, including + // when the result cache was cleared while it was in flight. + work.retain(|_, lock| lock.strong_count() > 0); + } + let lock = Arc::new(Mutex::new(())); + work.insert(key, Arc::downgrade(&lock)); + lock + } +} + type BiomeCache = Mutex>>>; fn state(registry: &BlockRegistry, raw: &Value) -> Result { @@ -834,6 +859,7 @@ where extensions, picker, biome_cache: Mutex::new(HashMap::new()), + biome_work: ChunkWork::new(), carver_cache: Mutex::new(HashMap::new()), decoration: None, structures: None, @@ -867,6 +893,11 @@ where worker: &mut WorkerState, pos: ChunkPos, ) -> Result>, GeneratorError> { + if let Some(chunk) = self.biome_cache.lock().unwrap().get(&(pos.x, pos.z)) { + return Ok(chunk.clone()); + } + let work = self.biome_work.at((pos.x, pos.z)); + let _work = work.lock().unwrap(); if let Some(chunk) = self.biome_cache.lock().unwrap().get(&(pos.x, pos.z)) { return Ok(chunk.clone()); } @@ -2013,4 +2044,121 @@ mod tests { .is_err() ); } + #[test] + fn neighbour_work_cleanup_keeps_active_keys_and_releases_idle_keys() { + let work = ChunkWork::new(); + let first = work.at((0, 0)); + let held = first.lock().unwrap(); + let same = work.at((0, 0)); + assert!(Arc::ptr_eq(&first, &same)); + assert!(!Arc::ptr_eq(&first, &work.at((1, 0)))); + // Sweep many expired weak entries while a builder and a prospective + // waiter retain their key. Cleanup must not split their coordination. + for x in 1..8192 { + drop(work.at((x, 1))); + } + assert!(work.0.lock().unwrap().len() <= 4096); + assert!(Arc::ptr_eq(&same, &work.at((0, 0)))); + let weak = Arc::downgrade(&first); + drop(held); + drop((first, same)); + assert!(weak.upgrade().is_none()); + let next = work.at((0, 0)); + assert_eq!(Arc::strong_count(&next), 1); + } + + /// Equal concurrent misses share one biome volume and the same mutable + /// structure pieces. Exercise cold ring startup before work coordination, + /// then cache eviction and explicit start invalidation with old Arcs alive. + #[test] + fn concurrent_neighbours_share_results_and_survive_invalidation() { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("worldgen/world_presets.json").exists() { + eprintln!("skipping: no worldgen bundle at {}", root.display()); + return; + } + let registry = Box::leak(Box::new( + crate::level::data::load_registry(&root).expect("registry"), + )); + let data = GeneratorData::load(&root.join("worldgen"), registry).expect("worldgen data"); + let preset: Value = serde_json::from_str(&data.world_presets["minecraft:normal"]).unwrap(); + let generator_json = &preset["dimensions"]["minecraft:overworld"]["generator"]; + let settings: Value = + serde_json::from_str(&data.settings[generator_json["settings"].as_str().unwrap()]) + .unwrap(); + let pipeline = Arc::new( + Pipeline::new( + data, + 12345, + XoroshiroRandom::new(12345), + generator_json, + &settings, + true, + Some((-64, 384)), + ) + .expect("pipeline"), + ); + let generator = OverworldGenerator { + pipeline: pipeline.clone(), + }; + let barrier = std::sync::Barrier::new(6); + let pos = ChunkPos::new(11, -11); // ancient city for this seed + let results = std::thread::scope(|scope| { + let handles: Vec<_> = (0..6) + .map(|_| { + scope.spawn(|| { + let mut worker = generator.worker(); + barrier.wait(); + let biomes = pipeline.biome_chunk(&mut worker.state, pos).unwrap(); + let starts = pipeline.structure_starts(&mut worker.state, pos); + (biomes, starts) + }) + }) + .collect(); + handles + .into_iter() + .map(|h| h.join().unwrap()) + .collect::>() + }); + let (biomes, starts) = &results[0]; + assert!(!starts.is_empty(), "fixture must exercise shared pieces"); + for (b, s) in &results[1..] { + assert!(Arc::ptr_eq(biomes, b)); + assert_eq!(starts.len(), s.len()); + for (first, other) in starts.iter().zip(s) { + assert!(Arc::ptr_eq(first, other)); + } + } + // Force the existing whole-cache biome eviction threshold. + { + let mut cache = pipeline.biome_cache.lock().unwrap(); + cache.clear(); + for x in 0..CACHE_LIMIT as i32 { + cache.insert((x, 10000), biomes.clone()); + } + } + let mut worker = generator.worker(); + let rebuilt = pipeline.biome_chunk(&mut worker.state, pos).unwrap(); + assert!(!Arc::ptr_eq(biomes, &rebuilt)); + assert_eq!(pipeline.biome_cache.lock().unwrap().len(), 1); + for section in 0..24 { + assert_eq!(biomes.section(section), rebuilt.section(section)); + } + worker.forget_structure_starts(); + let fresh = worker.structure_starts(pos); + assert_eq!(starts.len(), fresh.len()); + for (old, new) in starts.iter().zip(&fresh) { + assert!(!Arc::ptr_eq(old, new)); + assert_eq!(old.name, new.name); + assert_eq!(old.bounding_box, new.bounding_box); + } + let again = worker.structure_starts(pos); + for (first, hit) in fresh.iter().zip(&again) { + assert!(Arc::ptr_eq(first, hit)); + } + } } diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index 3b6d058ae..befa71e48 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -2,7 +2,7 @@ use super::{ biome::BiomeId, block_feature::FeatureBlockBindings, - generator::{GeneratorData, GeneratorError}, + generator::{ChunkWork, GeneratorData, GeneratorError}, structure::{ StructureResources, start::{ @@ -31,6 +31,7 @@ pub(super) struct StructureState { /// Structure indices of each decoration step, in registry order. pub(super) by_step: Vec>, starts: StartCache, + start_work: ChunkWork, /// Concentric ring positions, computed on first use and shared with /// later generators of the same seed and dimension. rings: Arc>, @@ -207,6 +208,7 @@ impl StructureState { possible_sets, by_step, starts: StartCache::new(), + start_work: ChunkWork::new(), rings, ring_work: OnceLock::new(), })) @@ -238,6 +240,8 @@ 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) { + // As before, a build already in flight can publish after this clear. + // Do not wait for work locks or retain initialized entries here. self.starts.clear(); } /// The (cached) structure starts owned by a chunk. @@ -249,7 +253,14 @@ impl StructureState { if let Some(found) = self.starts.get((chunk.x, chunk.z)) { return found; } + // Ring searches enlist other workers and wait for them: never hold a + // chunk-work lock while helping, even when this chunk has no starts. let rings = self.rings(context); + let work = self.start_work.at((chunk.x, chunk.z)); + let _work = work.lock().unwrap(); + if let Some(found) = self.starts.get((chunk.x, chunk.z)) { + return found; + } let starts: Starts = Arc::new( create_starts( &self.registry, From 0ab07f720967092847a487a70052dc8a53fed497 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:10:17 +0100 Subject: [PATCH 6/9] Fix spectator scroll wheel flight speed --- .../examples/game_loop_probe.rs | 24 ++++++--- crates/horizon-client/src/game.rs | 22 +++++--- crates/horizon-client/src/game/remote.rs | 7 ++- crates/horizon-client/src/motion.rs | 50 +++++++++++++++++-- crates/horizon-client/src/mouse.rs | 6 +++ .../parity/VanillaGameLoopOracle.java | 11 +++- tools/test_game_loop_parity.py | 13 +++-- 7 files changed, 111 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/examples/game_loop_probe.rs b/crates/horizon-client/examples/game_loop_probe.rs index 56da454d9..66a428162 100644 --- a/crates/horizon-client/examples/game_loop_probe.rs +++ b/crates/horizon-client/examples/game_loop_probe.rs @@ -233,22 +233,32 @@ fn mouse(c: &Value, out: &mut impl Write) -> Result<()> { fn scroll(c: &Value, out: &mut impl Write) -> Result<()> { let mut handler = MouseLook::default(); let mut slot = c["slot"].as_i64().unwrap() as i32; + let spectator = c["spectator"].as_bool().unwrap_or(false); + let mut speed = 0.05; // OptionInstance.set quantises the wheel sensitivity. let mut file = OptionsFile::default(); file.set("mouseWheelSensitivity", V::Double(db(&c["sens"]))); let sensitivity = file.double("mouseWheelSensitivity"); writeln!(out, "scroll")?; for op in c["ops"].as_array().unwrap() { - if let Some((wheel, _)) = + if let Some((wheel, (_, y))) = handler.on_scroll(db(&op[0]), db(&op[1]), b(&c["discrete"]), sensitivity) { - slot = horizon_client::mouse::ScrollWheelHandler::next_selection( - f64::from(wheel), - slot, - 9, - ); + if spectator { + speed = horizon_client::mouse::spectator_flying_speed(speed, y); + } else { + slot = horizon_client::mouse::ScrollWheelHandler::next_selection( + f64::from(wheel), + slot, + 9, + ); + } + } + if spectator { + writeln!(out, "{slot} {}", fb(speed))?; + } else { + writeln!(out, "{slot}")?; } - writeln!(out, "{slot}")?; } Ok(()) } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2cbdabaa4..aa49c539f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9925,15 +9925,25 @@ impl ApplicationHandler for Game<'_> { && self.sleeping.is_none() && self.player.is_some() && !self.extras_scroll(d) - && let Some((wheel, _)) = + && let Some((wheel, (_, vertical_steps))) = self.mouse .on_scroll(raw_x, raw_y, discrete, wheel_sensitivity) { - self.selected = horizon_client::mouse::ScrollWheelHandler::next_selection( - f64::from(wheel), - self.selected as i32, - 9, - ) as usize; + if self.spectator() { + if let Some(player) = &mut self.player { + player.flying_speed = horizon_client::mouse::spectator_flying_speed( + player.flying_speed, + vertical_steps, + ); + } + } else { + self.selected = + horizon_client::mouse::ScrollWheelHandler::next_selection( + f64::from(wheel), + self.selected as i32, + 9, + ) as usize; + } } if self.screen == Screen::Chat && d != 0.0 { self.chat_scroll(d); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 36c9fe4f3..f454771f3 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1805,7 +1805,12 @@ impl Game<'_> { } _ => {} }, - C::PlayerAbilities(p) => self.creative = p.flags & 8 != 0, + C::PlayerAbilities(p) => { + self.creative = p.flags & 8 != 0; + if let Some(player) = &mut self.player { + player.flying_speed = p.flying_speed; + } + } C::SetHeldSlot(p) => { self.selected = p.slot.clamp(0, 8) as usize; if let Some(r) = self.remote.as_mut() { diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 293aa61a2..6fca66c1d 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -224,6 +224,8 @@ pub struct PlayerMotion { /// Spectator mode: no physics, always flying (`Player.tick`). pub spectator: bool, pub flying: bool, + /// Client-side `Abilities.flyingSpeed`, adjusted by the spectator scroll wheel. + pub flying_speed: f32, /// The jump key last tick (LocalPlayer.aiStep's wasJumping). pub was_jumping: bool, /// `LocalPlayer.autoJumpEnabled` (the Auto-Jump option) and @@ -387,6 +389,7 @@ impl PlayerMotion { invulnerable: false, spectator: false, flying: false, + flying_speed: 0.05, was_jumping: false, auto_jump_enabled: false, auto_jump_time: 0, @@ -789,7 +792,7 @@ impl MotionWorld<'_, '_, '_> { // Vertical flight: jump up, shift down, three times the flying speed. let ya = i32::from(jumping) - i32::from(self.player.shift_key_down); if ya != 0 { - self.player.velocity.y += f64::from(ya as f32 * 0.05 * 3.0); + self.player.velocity.y += f64::from(ya as f32 * self.player.flying_speed * 3.0); } } self.dry_tick(TickInput::PreparedLocal { @@ -1863,8 +1866,8 @@ impl LivingAirWorld for MotionWorld<'_, '_, '_> { } fn flying_speed(&mut self) -> Result { if self.player.flying { - // Abilities.flyingSpeed 0.05, doubled when sprinting. - return Ok(if self.player.sprinting { 0.1 } else { 0.05 }); + // Player.getFlyingSpeed: abilities speed, doubled when sprinting. + return Ok(self.player.flying_speed * if self.player.sprinting { 2.0 } else { 1.0 }); } Ok(if self.player.sprinting { 0.025999999 @@ -2123,6 +2126,47 @@ mod tests { assert!(player.position.y < 84.0); } + #[test] + fn spectator_scroll_speed_controls_horizontal_and_vertical_flight() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let run = |steps| { + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); + let start = Vec3::new(20.5, 12.0, 20.5); + let mut player = PlayerMotion::new(&resources, start).unwrap(); + player.spectator = true; + player.flying_speed = crate::mouse::spectator_flying_speed(player.flying_speed, steps); + MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .controlled_simulation_tick(crate::sprint::Keys { + forward: true, + jump: true, + ..Default::default() + }) + .unwrap(); + player.position.subtract(start) + }; + let stopped = run(-100); + assert_eq!(stopped, Vec3::ZERO); + let normal = run(0); + let fast = run(10); + assert!(normal.y > 0.0 && normal.z > 0.0); + assert!((fast.y - normal.y * 2.0).abs() < 1e-6); + assert!((fast.z - normal.z * 2.0).abs() < 1e-6); + } + #[test] fn resident_spectator_flight_ignores_solid_and_climbable_blocks() { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); diff --git a/crates/horizon-client/src/mouse.rs b/crates/horizon-client/src/mouse.rs index d2794d790..1cee2be87 100644 --- a/crates/horizon-client/src/mouse.rs +++ b/crates/horizon-client/src/mouse.rs @@ -80,6 +80,12 @@ impl ScrollWheelHandler { } } +/// `MouseHandler.onScroll` with the spectator menu closed. Only vertical whole +/// wheel steps adjust `Abilities.flyingSpeed`; horizontal scrolling does not. +pub fn spectator_flying_speed(speed: f32, vertical_steps: i32) -> f32 { + (speed + vertical_steps as f32 * 0.005).clamp(0.0, 0.2) +} + /// Entity rotation as `Entity.turn` keeps it. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Rotation { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java index 0be89888a..294ceacac 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java @@ -118,13 +118,14 @@ public final class VanillaGameLoopOracle { static final class StubPlayer extends LocalPlayer { boolean scoping; + boolean spectator; StubPlayer() { super(null, null, null, null, null, Input.EMPTY, false, null, null); } @Override public boolean isScoping() { return scoping; } - @Override public boolean isSpectator() { return false; } + @Override public boolean isSpectator() { return spectator; } } static Minecraft shell; @@ -327,6 +328,12 @@ public final class VanillaGameLoopOracle { StubPlayer player = make(StubPlayer.class); Inventory inventory = make(Inventory.class); inventory.setSelectedSlot(c.get("slot").getAsInt()); + player.spectator = c.has("spectator") && c.get("spectator").getAsBoolean(); + field(net.minecraft.world.entity.player.Player.class, "abilities").set(player, new net.minecraft.world.entity.player.Abilities()); + var hud = make(net.minecraft.client.gui.Hud.class); + field(net.minecraft.client.gui.Hud.class, "spectatorGui").set(hud, + make(net.minecraft.client.gui.components.spectator.SpectatorGui.class)); + field(Gui.class, "hud").set(mc.gui, hud); field(net.minecraft.world.entity.player.Player.class, "inventory").set(player, inventory); mc.player = player; options.discreteMouseScroll().set(c.get("discrete").getAsBoolean()); @@ -336,7 +343,7 @@ public final class VanillaGameLoopOracle { for (var e : c.getAsJsonArray("ops")) { var op = e.getAsJsonArray(); h.onScroll(1L, d(op.get(0)), d(op.get(1))); - out.println(inventory.getSelectedSlot()); + out.println(inventory.getSelectedSlot() + (player.spectator ? " " + fb(player.getAbilities().getFlyingSpeed()) : "")); } } diff --git a/tools/test_game_loop_parity.py b/tools/test_game_loop_parity.py index d724dc6ac..101b3f238 100644 --- a/tools/test_game_loop_parity.py +++ b/tools/test_game_loop_parity.py @@ -120,8 +120,15 @@ def scroll_cases(rng): x = rng.choice([0.0, 0.0, 0.0, 1.0, -1.0, 0.25, -0.25, 0.4, 2.0, 5.5, -7.0, rng.uniform(-3, 3)]) y = rng.choice([0.0, 1.0, -1.0, 1.0, -1.0, 0.1, -0.3, 0.5, -0.5, 2.0, -3.0, 120.0, rng.uniform(-3, 3)]) ops.append([dbits(x), dbits(y)]) - yield dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), - slot=rng.randrange(9), ops=ops) + case = dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), + slot=rng.randrange(9), ops=ops) + yield case + yield dict(case, spectator=True) + # Bounds, recovery from each bound, fractional accumulation, and horizontal-only input. + yield dict(t='scroll', discrete=False, sens=dbits(1.0), slot=4, spectator=True, + ops=[[dbits(x), dbits(y)] for x, y in + [(0, 100), (0, -1), (0, -100), (0, 1), (0, .4), (0, .7), + (0, -.4), (0, -.7), (5, 0), (-5, 0)]]) def key_cases(rng): @@ -152,7 +159,7 @@ def main(): 'Window.calculateScale/setGuiScale and MouseHandler scaled positions, FramerateLimitTracker throttle reasons and ' 'limits (not the focus-lost exclusive-fullscreen branch, which reads SDL), MouseHandler.onMove/turnPlayer with ' 'sensitivity, cinematic smoothing, scoping and inversion, Entity.turn clamps, onScroll with ScrollWheelHandler ' - 'accumulation, discrete scrolling and hotbar selection, and ToggleKeyMapping/KeyMapping down, click and ' + 'accumulation, discrete scrolling, hotbar selection and spectator flight speed, and ToggleKeyMapping/KeyMapping down, click and ' 'screen-release state. The frame clock source (Blaze3D.getTime, System.nanoTime) is injected, so sleeping in ' 'FramerateLimiter and vsync present-mode selection are covered by Rust unit tests only.') harness.differential( From 2fe7cb3a4bb156daab731ff5b031621f6e39c763 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:23:23 +0100 Subject: [PATCH 7/9] Reuse terrain sampler scratch buffers between chunks --- crates/horizon-core/src/density/mod.rs | 7 ++ crates/horizon-core/src/density/tests.rs | 70 +++++++++++++++++++ .../horizon-world/src/worldgen/generator.rs | 26 +++++-- 3 files changed, 97 insertions(+), 6 deletions(-) diff --git a/crates/horizon-core/src/density/mod.rs b/crates/horizon-core/src/density/mod.rs index 6bc84a8d1..f4ee1af49 100644 --- a/crates/horizon-core/src/density/mod.rs +++ b/crates/horizon-core/src/density/mod.rs @@ -103,6 +103,13 @@ impl SamplerContext { self.scratch.push(buffer); result } + /// Start an independent evaluation, retaining only temporary scratch buffers. + /// Cached scalar/volume results and world bindings must not cross chunks or + /// graphs, whose cache IDs can refer to different functions. + pub fn reset(&mut self) { + self.caches = self.caches.as_ref().map(|_| Vec::new()); + self.fields = WorldFields::default(); + } /// Release retained storage between worlds or after unusually large work. pub fn clear_scratch(&mut self) { self.scratch.clear(); diff --git a/crates/horizon-core/src/density/tests.rs b/crates/horizon-core/src/density/tests.rs index 77a643097..9fad8bc4f 100644 --- a/crates/horizon-core/src/density/tests.rs +++ b/crates/horizon-core/src/density/tests.rs @@ -755,3 +755,73 @@ fn spline_lazy_branch_failure_preserves_completed_output_and_returns_scratch() { assert_eq!(context.scratch.len(), 2); assert_eq!(sampler.sample_value(&mut context, [0; 3]), Ok(7.0)); } + +#[test] +fn reset_retains_scratch_but_discards_graph_caches_and_world_bindings() { + let binding = Arc::new(ConstantSampler(17.0)); + let lifetime = Arc::downgrade(&binding); + let mut context = SamplerContext::cached() + .with_world_fields(WorldFields::default().with_field(WorldField::Beardifier, binding)); + let cached = CachingDensitySampler::new( + 0, + Arc::new(ContextBoundSampler::new(WorldField::Beardifier)), + ) + .unwrap(); + let volume = DensityVolume::new([2; 3], [0; 3], [1; 3]).unwrap(); + let mut output = [0.0; 8]; + cached + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert_eq!(output, [17.0; 8]); + assert_eq!(cached.sample_value(&mut context, [9; 3]), Ok(17.0)); + context + .with_buffer(128, |_, buffer| { + buffer.fill(99.0); + Ok(()) + }) + .unwrap(); + let allocation = context.scratch[0].as_ptr(); + let capacity = context.scratch[0].capacity(); + context.reset(); + assert!(lifetime.upgrade().is_none()); + assert!(context.caches.as_ref().unwrap().is_empty()); + assert_eq!(context.scratch[0].as_ptr(), allocation); + assert_eq!(context.scratch[0].capacity(), capacity); + // Same coordinates and cache ID must resolve the new context's fallback. + assert_eq!(cached.sample_value(&mut context, [9; 3]), Ok(0.0)); + cached + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert_eq!(output, [0.0; 8]); + // A different graph may reuse IDs without inheriting scalar/volume results. + context.reset(); + let replacement = CachingDensitySampler::new(0, Arc::new(ConstantSampler(3.0))).unwrap(); + assert_eq!(replacement.sample_value(&mut context, [9; 3]), Ok(3.0)); + replacement + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert_eq!(output, [3.0; 8]); +} + +#[test] +fn reset_after_sampling_error_drops_blender_and_preserves_uncached_mode() { + let blender = Arc::new(EmptyBlender); + let lifetime = Arc::downgrade(&blender); + let mut context = + SamplerContext::default().with_world_fields(WorldFields::default().with_blender(blender)); + let result: Result<(), SampleError> = context.with_buffer(64, |_, buffer| { + buffer.fill(42.0); + Err(SampleError::RecursiveCache) + }); + assert_eq!(result, Err(SampleError::RecursiveCache)); + let allocation = context.scratch[0].as_ptr(); + context.reset(); + assert!(lifetime.upgrade().is_none()); + assert!(context.caches.is_none()); + context + .with_buffer(32, |_, buffer| { + assert_eq!(buffer.as_ptr(), allocation); + Ok(()) + }) + .unwrap(); +} diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7b73d35a8..068fdf5bc 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -933,6 +933,19 @@ where &self, worker: &mut WorkerState, pos: ChunkPos, + ) -> Result { + let mut context = std::mem::take(&mut worker.terrain_context); + let result = self.generate_with_context(worker, pos, &mut context); + // Release chunk-specific bindings and caches even after a sampling error. + context.reset(); + worker.terrain_context = context; + result + } + fn generate_with_context( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + context: &mut SamplerContext, ) -> Result { let data = &self.data; let (min, height, sea) = ( @@ -985,13 +998,12 @@ where ), None => Vec::new(), }; - let mut context = SamplerContext::cached(); if let Some(beard) = self .structures .as_ref() .and_then(|s| s.beardifier(&references, pos)) { - context = context.with_world_fields( + *context = std::mem::take(context).with_world_fields( horizon_core::density::WorldFields::default().with_field( horizon_core::density::WorldField::Beardifier, Arc::new(beard), @@ -1016,7 +1028,7 @@ where .fork_positional(), RegistryAquiferBlockStates::new(data.registry).map_err(stage("aquifer"))?, volume, - &mut context, + context, ) .map_err(stage("aquifer"))?, ), @@ -1030,7 +1042,7 @@ where &mut chunk, volume, self.router.get(RouterField::FinalDensity).as_ref(), - &mut context, + context, aquifer.as_mut(), self.settings.default_block, ) @@ -1051,7 +1063,7 @@ where possible: Some(possible), }, preliminary_surface: self.preliminary.clone(), - density_context: &mut context, + density_context: context, write_min_y: min, write_max_y: min + height - 1, }, @@ -1086,7 +1098,7 @@ where possible: None, }, preliminary_surface: self.preliminary.clone(), - density_context: &mut context, + density_context: context, }, aquifer.as_mut(), &data.carving_blocks, @@ -1391,6 +1403,7 @@ pub struct StageTimings { /// thread-local caches and never change results. pub(super) struct WorkerState { pub(super) temperatures: Vec, + terrain_context: SamplerContext, biome_context: SamplerContext, carver_context: SamplerContext, timings: StageTimings, @@ -1866,6 +1879,7 @@ impl OverworldGenerator { .iter() .map(|s| BiomeTemperature::new(*s)) .collect(), + terrain_context: SamplerContext::cached(), biome_context: SamplerContext::cached(), carver_context: SamplerContext::default(), timings: StageTimings::default(), From c0f0c17ed4b05dd72d9ecda26ae6a925e0018f0c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 19 Oct 2026 03:07:17 +0200 Subject: [PATCH 8/9] Keep restored chunk entities out of /summon's result after a level switch Coming back to a level, the entities saved with its chunks wait in World::loaded_entities until the next tick spawns them, as vanilla's PersistentEntitySectionManager.processPendingLoads does. /summon pushed its compound onto that queue and drained all of it, so the first waiting entity took the id counted as the summon's root: after a Nether round trip `/summon minecraft:armor_stand ...` reported "Summoned new Pig". Summon now spawns only its own stack and leaves the queue to the tick. The command harness's settle now waits for the entities of the chunks around the player as well, like the oracle's settle (areEntitiesActuallyLoadedAndTicking), and a `portal` op sends the player through the nether portal it stands in (Entity.handlePortal: NetherPortalBlock.getPortalDestination, teleportToPortalDestination). The corpus's new `levels` group makes the round trip and checks the Overworld's pig and a summon's feedback on the way back. Fixes #947 Co-Authored-By: Claude Opus 5.5 --- .../src/game/command_harness.rs | 21 +++++++++++++++- .../horizon-client/src/game/commands/data.rs | 9 ++++++- .../horizon-client/src/game/nether_portal.rs | 6 +++++ .../parity/VanillaCommandExecOracle.java | 18 +++++++++++++ tools/command_exec_corpus.py | 25 ++++++++++++++++++- 5 files changed, 76 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/command_harness.rs b/crates/horizon-client/src/game/command_harness.rs index ed3f8b336..096ba1c74 100644 --- a/crates/horizon-client/src/game/command_harness.rs +++ b/crates/horizon-client/src/game/command_harness.rs @@ -4,7 +4,8 @@ //! command as the player (Commands.performPrefixedCommand) and records every //! system message it produced, as styled spans, with the results reported to //! the player's `CommandResultCallback`; `tick` advances the game; `settle` -//! waits until the terrain around the player is loaded. +//! waits until the terrain and entities around the player are loaded; +//! `portal` sends the player through the nether portal it stands in. use super::Game; use horizon_client::{Result, text::Text}; use serde_json::{Value, json}; @@ -40,6 +41,19 @@ pub(super) fn spans(text: &Text) -> Value { } impl Game<'_> { + /// The player's portal process finished in the nether portal it stands + /// in (the oracle's player is not ticked, so neither is the wait). + fn harness_portal(&mut self) -> Result<()> { + let Some(p) = &self.player else { + return Err("command harness: portal without a player".into()); + }; + let entry = horizon_core::position::BlockPos::containing(p.position); + let block = self.world.block(entry.x, entry.y, entry.z); + if &*self.res.facts().get(block).name != "minecraft:nether_portal" { + return Err("command harness: the player is not in a nether portal".into()); + } + self.player_through_nether_portal(entry) + } /// Load terrain until the player stands in lit chunks. fn harness_settle(&mut self, deadline: Instant) -> Result<()> { loop { @@ -51,6 +65,10 @@ impl Game<'_> { (p.position.z.floor() as i32) >> 4, ); if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { + // The oracle's settle also waits for the entities saved + // in those chunks (areEntitiesActuallyLoadedAndTicking): + // after a dimension change they come back from the save. + self.spawn_loaded_entities(); return Ok(()); } } @@ -130,6 +148,7 @@ impl Game<'_> { } } "settle" => self.harness_settle(deadline)?, + "portal" => self.harness_portal()?, other => return Err(format!("command harness: unknown op {other}").into()), } } diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index bbb388deb..89e3d6397 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -666,13 +666,20 @@ impl Game<'_> { /// Spawn an entity from its compound (`EntityType.loadEntityRecursive`); /// returns what was created. pub(super) fn spawn_entity_from_nbt(&mut self, tag: Tag) -> Option { - let before = self.next_entity; let key = { let p = entity_nbt::position(&tag)?; ((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4) }; + // Only this stack spawns now: the entities of chunks that finished + // loading wait for the level's entity tick, as in vanilla + // (PersistentEntitySectionManager.processPendingLoads), and must not + // take the ids counted as this stack's. + let mut waiting = std::mem::take(&mut self.world.loaded_entities); + let before = self.next_entity; self.world.loaded_entities.push((key, vec![tag])); self.spawn_loaded_entities(); + waiting.append(&mut self.world.loaded_entities); + self.world.loaded_entities = waiting; if self.next_entity == before { return None; } diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 94df10ec4..11c32f701 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -298,6 +298,12 @@ impl Game<'_> { else { return Ok(()); }; + self.player_through_nether_portal(entry) + } + /// `Entity.handlePortal` once the player's portal process at `entry` + /// finished: `NetherPortalBlock.getPortalDestination`, then + /// `teleportToPortalDestination` (`isAllowedToEnterPortal`). + pub(super) fn player_through_nether_portal(&mut self, entry: BlockPos) -> Result<()> { let Some(p) = self.player.as_ref() else { return Ok(()); }; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java index 4b61558d8..8c6225401 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java @@ -222,6 +222,7 @@ public final class VanillaCommandExecOracle { } } case "settle" -> settle(); + case "portal" -> portal(); default -> throw new IllegalArgumentException(line); } } @@ -278,6 +279,23 @@ public final class VanillaCommandExecOracle { } /** Force-load the chunks around the player (Horizon waits for its streamed terrain). */ + /** + * Entity.handlePortal once the player's portal process finished in the + * nether portal it stands in (the oracle does not tick the player). + */ + void portal() { + ServerLevel level = player.level(); + net.minecraft.core.BlockPos entry = player.blockPosition(); + if (!level.getBlockState(entry).is(net.minecraft.world.level.block.Blocks.NETHER_PORTAL)) { + throw new IllegalStateException("portal: the player is not in a nether portal"); + } + var block = (net.minecraft.world.level.block.NetherPortalBlock) net.minecraft.world.level.block.Blocks.NETHER_PORTAL; + var transition = block.getPortalDestination(level, player, entry); + if (transition != null) { + player.teleportToPortalDestination(level, transition); + } + } + void settle() { ServerLevel level = player.level(); int cx = player.chunkPosition().x(), cz = player.chunkPosition().z(); diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index eb99e1f1a..4757e66f0 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -2,7 +2,8 @@ Each group is a list of operations: `cmd` runs a command as the player and records its messages and results (`record: false` runs setup silently), -`tick` advances the game and `settle` loads the terrain around the player. +`tick` advances the game, `settle` loads the terrain and entities around the +player and `portal` sends the player through the nether portal it stands in. Everything happens high above the terrain (y 200 and up, where both worlds are air) after the world's entities are removed, so the results do not depend on world generation. @@ -394,6 +395,27 @@ def execute(): ] +def levels(): + """A nether portal round trip: on the way back the Overworld's entities (the + pig left by `entities`) are found and a summon names what it summoned.""" + return [ + *setup('/fill 2 231 12 5 236 12 minecraft:obsidian', '/fill 3 232 12 4 235 12 minecraft:nether_portal[axis=x]', + '/tp @s 3.5 232 12.5 0 0'), + {'op': 'portal'}, + {'op': 'settle'}, + cmd('/execute if dimension minecraft:the_nether run say through the portal'), + {'op': 'portal'}, + {'op': 'settle'}, + cmd('/execute if dimension minecraft:overworld run say back through the portal'), + cmd('/data get entity @s Pos'), + cmd('/data get entity @s Rotation'), + cmd('/execute if entity @e[type=minecraft:pig]'), + cmd('/summon minecraft:armor_stand 4.5 210 4.5 {NoGravity:1b,Tags:["lv"],CustomName:"Back"}'), + *setup('/kill @e[tag=lv]', '/fill 2 231 12 5 236 12 minecraft:air', '/tp @s 8.5 230 8.5 0 0'), + {'op': 'settle'}, + ] + + def items_and_loot(): return [ *setup('/clear @s', '/gamemode survival'), @@ -918,6 +940,7 @@ def groups(): ('entities', entities()), ('scores, teams and bossbars', scores()), ('execute', execute()), + ('levels', levels()), ('items and loot', items_and_loot()), ('world', world_misc()), ('progression', progression()), From f62e07c36ae955c5bb025ea70a731c8b693e38e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 19 Oct 2026 04:40:00 +0200 Subject: [PATCH 9/9] Read GPU readbacks without assuming the mapping's alignment A Vega 11 on Windows (Vulkan) panicked at launch in bytemuck's cast_slice with TargetAlignmentGreaterAndInputNotAligned, starting with the release that shipped occlusion culling. The section-test results and the GPU timer's timestamps were cast in place from the mapped range, which isn't guaranteed to be 4- or 8-byte aligned. Copy the words out instead. Fixes #953 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx/cull.rs | 6 ++++-- crates/horizon-client/src/gfx/timing.rs | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/gfx/cull.rs b/crates/horizon-client/src/gfx/cull.rs index 6926aab70..bcb738de3 100644 --- a/crates/horizon-client/src/gfx/cull.rs +++ b/crates/horizon-client/src/gfx/cull.rs @@ -273,7 +273,9 @@ impl Cull { } let mapped = r.buffer.slice(..r.slots.len() as u64 * 4); if let Ok(data) = mapped.get_mapped_range() { - let results: &[u32] = bytemuck::cast_slice(&data); + // The mapping isn't guaranteed to be 4-byte aligned (a Vega 11 + // on Windows panicked in cast_slice), so copy the words out. + let results: Vec = bytemuck::pod_collect_to_vec(&data); let (mut hidden, mut indices) = (0, 0u64); for (&result, &n) in results.iter().zip(&r.indices) { if result != r.stamp { @@ -283,7 +285,7 @@ impl Cull { } let share = indices as f32 / r.total.max(1) as f32; self.hidden = ([hidden, results.len()], share); - for (&slot, &result) in r.slots.iter().zip(results) { + for (&slot, &result) in r.slots.iter().zip(&results) { let slot = slot as usize; if slot >= self.seen.len() { self.seen.resize(slot + 1, false); diff --git a/crates/horizon-client/src/gfx/timing.rs b/crates/horizon-client/src/gfx/timing.rs index 5d2354234..8f8eee6ee 100644 --- a/crates/horizon-client/src/gfx/timing.rs +++ b/crates/horizon-client/src/gfx/timing.rs @@ -147,7 +147,8 @@ impl GpuTimer { continue; } if let Ok(data) = slot.buffer.slice(..).get_mapped_range() { - let stamps: &[u64] = bytemuck::cast_slice(&data); + // Read unaligned: the mapping isn't guaranteed to be 8-byte aligned. + let stamps: [u64; 2] = bytemuck::pod_read_unaligned(&data[..16]); let ticks = stamps[1].saturating_sub(stamps[0]); out.push((ticks as f64 * f64::from(self.period_ns) / 1e6) as f32); }