// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // monsters spawning on their own near players, like minecraft's NaturalSpawner: every tick, one try in each chunk // around players while there's room under the monster cap. what spawns comes from mods' worldgen/spawns.json (see // SpawnJson), the way undergarden's biomes list its rotspawn import { CHUNK_SIZE } from "@/common/constants.ts"; import type { SpawnJson } from "@/common/mod_data.ts"; import { chunk_key } from "@/common/utils.ts"; import type { EntityManager } from "./entity/entity_manager.ts"; import { create_entity } from "./entity/entity_types.ts"; import { Mob } from "./entity/mob.ts"; import type { ServerPlayer } from "./player.ts"; import type { ServerWorld } from "./world.ts"; // minecraft's MONSTER category: 70 for the 17x17 chunks around a player, fewer when fewer chunks are around const MONSTER_CAP = 70; const CAP_AREA = 17 * 17; // how far from a player monsters count towards their own cap, in chunks const CAP_CHUNKS = 8; // never this close to a player or to the world spawn const MIN_DISTANCE = 24; // monsters further than this from every player despawn straight away, see Mob.check_despawn const MAX_DISTANCE = 128; // a try is up to 3 groups, each up to 4 spots wandering from the first, and makes at most 4 mobs const GROUPS = 3; const GROUP_SPOTS = 4; const CLUSTER_SIZE = 4; // how far each spot in a group is from the one before, at most, in x and in z const WANDER = 6; // how far light comes from, see ServerWorld.light_at const LIGHT_REACH = 15; // what spawning needs from the game server export interface SpawnerHost { readonly world: ServerWorld; readonly entities: EntityManager; players(): ServerPlayer[]; } export class NaturalSpawner { readonly spawns: readonly SpawnJson[]; // Math.random, tests replace it random: () => number = Math.random; constructor(spawns: readonly SpawnJson[]) { this.spawns = spawns.filter((spawn) => spawn.weight > 0); } // tries the chunks within distance chunks of a player that their client has, like minecraft's loaded chunks. the // server keeps fewer chunks than players see, and building one takes long, so only ones it still has: using // them every tick keeps them, and the chunks sent further out are the ones it forgets tick(host: SpawnerHost, distance: number) { const players = host.players(); if (this.spawns.length === 0 || players.length === 0) return; const chunks = new Map(); for (const player of players) { const px = Math.floor(player.x / CHUNK_SIZE); const pz = Math.floor(player.z / CHUNK_SIZE); for (let cx = px - distance; cx <= px + distance; cx++) { for (let cz = pz - distance; cz <= pz + distance; cz++) { if (player.chunks.has(cx, cz) && host.world.keep_chunk(cx, cz)) { chunks.set(chunk_key(cx, cz), [cx, cz]); } } } } // the monsters around, all together and near each player const cap = Math.floor(MONSTER_CAP * chunks.size / CAP_AREA); let count = 0; const near = new Map(players.map((player) => [player, 0])); const counted = (entity: Mob) => { count += 1; for (const player of players) { if (chunk_distance(player, entity.x, entity.z) <= CAP_CHUNKS) near.set(player, near.get(player)! + 1); } }; for (const entity of host.entities.all()) { if ( entity instanceof Mob && entity.category === "monster" && !entity.requires_persistence && chunks.has(chunk_key(Math.floor(entity.x / CHUNK_SIZE), Math.floor(entity.z / CHUNK_SIZE))) ) { counted(entity); } } for (const [cx, cz] of this.#shuffled([...chunks.values()])) { if (count >= cap) break; const middle_x = cx * CHUNK_SIZE + CHUNK_SIZE / 2; const middle_z = cz * CHUNK_SIZE + CHUNK_SIZE / 2; const room = players.some((player) => chunk_distance(player, middle_x, middle_z) <= CAP_CHUNKS && near.get(player)! < MONSTER_CAP ); if (room) this.spawn_in_chunk(host, cx, cz).forEach(counted); } } // one try: a random spot in the chunk between the bottom of the world and just above its surface, then groups // wandering around it at that height, in chunks the server has only. returns what spawned spawn_in_chunk(host: SpawnerHost, chunk_x: number, chunk_z: number): Mob[] { const { world } = host; const start_x = chunk_x * CHUNK_SIZE + this.#int(CHUNK_SIZE); const start_z = chunk_z * CHUNK_SIZE + this.#int(CHUNK_SIZE); const y = this.#int(world.surface_height(start_x, start_z) + 2); if (y < 1 || world.has_collision(start_x, y, start_z)) return []; const spawned: Mob[] = []; const world_spawn = world.spawn_point(); for (let group = 0; group < GROUPS; group++) { let x = start_x; let z = start_z; let spawn: SpawnJson | undefined; let size = Math.ceil(this.random() * GROUP_SPOTS); for (let i = 0; i < size; i++) { x += this.#int(WANDER) - this.#int(WANDER); z += this.#int(WANDER) - this.#int(WANDER); const fx = x + 0.5; const fz = z + 0.5; const player = host.entities.nearest_player(fx, y, fz, Infinity); if (!player) continue; const distance = Math.hypot(player.x - fx, player.y - y, player.z - fz); if (distance <= MIN_DISTANCE) continue; if (Math.hypot(world_spawn.x - fx, world_spawn.y - y, world_spawn.z - fz) < MIN_DISTANCE) continue; if (!world.has_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE))) continue; if (!spawn) { spawn = this.#pick(world.biome_at(x, y, z)); if (!spawn) break; size = spawn.min_count + this.#int(spawn.max_count - spawn.min_count + 1); } if (distance > MAX_DISTANCE || !spawns_in(spawn, world.biome_at(x, y, z))) continue; // in loaded chunks only, the light too, so trying never builds a chunk if (!world.has_chunks_around(x, z, LIGHT_REACH)) continue; if (!is_spawn_ground(world, x, y - 1, z)) continue; // before the rest since it's cheap, it doesn't change how likely spawning is if (spawn.chance !== undefined && this.random() >= spawn.chance) continue; const mob = create_entity(host.entities, spawn.entity); if (!(mob instanceof Mob)) return spawned; mob.set_position(fx, y, fz); if (!has_room(host.entities, mob) || !this.#dark_enough(world, x, y, z)) continue; mob.yaw = mob.head_yaw = this.random() * Math.PI * 2; host.entities.add_entity(mob); spawned.push(mob); if (spawned.length >= CLUSTER_SIZE) return spawned; } } return spawned; } // underground only: no sky light reaches it, so never on the surface even at night, and no block light either #dark_enough(world: ServerWorld, x: number, y: number, z: number) { const { sky, block } = world.light_at(x, y, z); return sky === 0 && block === 0; } // by weight, from the spawns of the biome #pick(biome: string): SpawnJson | undefined { const options = this.spawns.filter((spawn) => spawns_in(spawn, biome)); let left = this.random() * options.reduce((total, spawn) => total + spawn.weight, 0); for (const spawn of options) { left -= spawn.weight; if (left < 0) return spawn; } return options.at(-1); } #shuffled(list: T[]): T[] { for (let i = list.length - 1; i > 0; i--) { const j = this.#int(i + 1); [list[i], list[j]] = [list[j], list[i]]; } return list; } // 0 to below n #int(n: number) { return Math.floor(this.random() * n); } } function spawns_in(spawn: SpawnJson, biome: string) { return spawn.biomes === undefined || spawn.biomes.includes(biome); } // in chunks, the further of x and z function chunk_distance(player: ServerPlayer, x: number, z: number) { return Math.max( Math.abs(Math.floor(player.x / CHUNK_SIZE) - Math.floor(x / CHUNK_SIZE)), Math.abs(Math.floor(player.z / CHUNK_SIZE) - Math.floor(z / CHUNK_SIZE)), ); } // like minecraft's ON_GROUND placement: a whole solid block to stand on that isn't too bright, so not leaves, glass // or a lamp function is_spawn_ground(world: ServerWorld, x: number, y: number, z: number) { const block = world.get_block_info(x, y, z); return block !== undefined && block.has_collision && world.light_opacity(x, y, z) === 15 && (block.light_emission ?? 0) < 14; } // nothing it would bump into and no water where its box is function has_room(entities: EntityManager, mob: Mob) { const half = mob.width / 2; for (let x = Math.floor(mob.x - half); x < mob.x + half; x++) { for (let y = Math.floor(mob.y); y < mob.y + mob.height; y++) { for (let z = Math.floor(mob.z - half); z < mob.z + half; z++) { if (entities.has_collision(x, y, z) || entities.is_fluid(x, y, z)) return false; } } } return true; }