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] 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