Add natural mob spawning for rotwalker

This commit is contained in:
2026-09-30 22:15:42 -03:00
parent 0052faa24d
commit a6fd508529
22 changed files with 714 additions and 7 deletions
+1 -1
View File
@@ -47,7 +47,7 @@ deno task build && deno task server # packs the mods and starts a se
**Entities**
- [Entities](docs/modding/entities/index.md): animals, scripted entities and entity models
- [Entities](docs/modding/entities/index.md): animals, monsters, natural spawning, scripted entities and entity models
- [Players](docs/modding/entities/players.md): the player API, health and hunger
**Inventories**
+3
View File
@@ -12,6 +12,7 @@ import {
type ManifestJson,
type OreJson,
type RecipeJson,
type SpawnJson,
type TagJson,
validate_block,
validate_entity,
@@ -21,6 +22,7 @@ import {
validate_model,
validate_ore,
validate_recipe,
validate_spawn,
validate_tag,
} from "./mod_data.ts";
import type { ModData } from "./mod_loader.ts";
@@ -139,6 +141,7 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
items: checked(raw_data.items, "items", validate_item, problems) as ItemJson[],
recipes: checked(raw_data.recipes, "recipes", validate_recipe, problems) as RecipeJson[],
ores: checked(raw_data.ores, "ores", validate_ore, problems) as OreJson[],
spawns: checked(raw_data.spawns, "spawns", validate_spawn, problems) as SpawnJson[],
entities: checked(raw_data.entities, "entities", validate_entity, problems) as EntityJson[],
entity_models: checked(
raw_data.entity_models,
+20 -1
View File
@@ -9,11 +9,13 @@ import {
type OreJson,
type RecipeJson,
SHARED_TAG_NAMESPACE,
type SpawnJson,
type TagJson,
type TagRegistry,
} from "./mod_data.ts";
import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts";
import { resolve_tags } from "./tags.ts";
import { BIOMES } from "./worldgen/overworld.ts";
export interface ModReport {
id: string;
@@ -31,6 +33,7 @@ export interface LoadedMod {
items: { file: string; json: ItemJson }[];
recipes: { file: string; json: RecipeJson }[];
ores: { file: string; json: OreJson }[];
spawns: { file: string; json: SpawnJson }[];
entities: { file: string; json: EntityJson }[];
entity_models: { file: string; json: EntityModelJson }[];
tags: { file: string; json: TagJson }[];
@@ -72,6 +75,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
const item_owners = new Map<string, string[]>();
const model_owners = new Map<string, string[]>();
const entity_owners = new Map<string, string[]>();
const entity_jsons = new Map<string, EntityJson>();
const entity_model_owners = new Map<string, string[]>();
const tag_owners = new Map<TagRegistry, Set<string>>();
const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]);
@@ -85,7 +89,10 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
}
for (const { json } of mod.items) add(item_owners, json.id, mod.id);
for (const { json } of mod.models) add(model_owners, json.id, mod.id);
for (const { json } of mod.entities) add(entity_owners, json.id, mod.id);
for (const { json } of mod.entities) {
add(entity_owners, json.id, mod.id);
entity_jsons.set(json.id, json);
}
for (const { json } of mod.entity_models) add(entity_model_owners, json.id, mod.id);
for (const { json } of mod.tags) {
if (!tag_owners.has(json.registry)) tag_owners.set(json.registry, new Set());
@@ -203,6 +210,18 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
if (json.model !== undefined) uses(file, json.model, "entity model");
uses(file, json.texture, "texture");
}
for (const { file, json } of mod.spawns) {
check_namespace(file, json.entity);
const entity = entity_jsons.get(json.entity);
if (!entity) errors.push(`${file}: entity ${json.entity} doesn't exist`);
else if (entity.behavior !== "monster") {
errors.push(`${file}: ${json.entity} isn't a monster, only monsters spawn on their own for now`);
}
// biomes are the engine's, whatever their namespace
for (const biome of json.biomes ?? []) {
if (!(biome in BIOMES)) errors.push(`${file}: biome ${biome} doesn't exist`);
}
}
for (const { file, json } of mod.entity_models) {
if ((entity_model_owners.get(json.id)?.length ?? 0) > 1) {
errors.push(`${file}: entity model ${json.id} is defined more than once`);
+41
View File
@@ -75,6 +75,22 @@ export interface OreJson {
threshold: number;
}
// mobs that spawn on their own, like neoforge's add_spawns biome modifier and undergarden's biome spawners. only
// monsters for now: in the dark near players, like minecraft's NaturalSpawner
export interface SpawnJson {
entity: string;
// how often it's picked over the other spawns where both can spawn
weight: number;
// how many spawn together
min_count: number;
max_count: number;
// only in these biomes, every biome when not set
biomes?: string[];
// the chance each spawn that passed every other check goes ahead, like undergarden's 1 in 10 for its rotspawn. 1
// when not set
chance?: number;
}
export interface ItemJson {
id: string;
texture: string;
@@ -701,6 +717,31 @@ export function validate_ore(json: unknown): Problems {
return problems;
}
export function validate_spawn(json: unknown): Problems {
if (!is_object(json)) return ["spawn must be an object"];
const problems = validate_id(json.entity, "entity");
for (const key of ["weight", "min_count", "max_count"]) {
if (!Number.isInteger(json[key]) || (json[key] as number) < (key === "weight" ? 0 : 1)) {
problems.push(
key === "weight"
? "weight must be a whole number, 0 or more"
: `${key} must be a whole number, 1 or more`,
);
}
}
if (typeof json.min_count === "number" && typeof json.max_count === "number" && json.min_count > json.max_count) {
problems.push("min_count must not be above max_count");
}
if (json.biomes !== undefined) {
if (!Array.isArray(json.biomes)) problems.push("biomes must be a list of biome ids");
else json.biomes.forEach((biome, i) => problems.push(...validate_id(biome, `biomes[${i}]`)));
}
if (json.chance !== undefined && (typeof json.chance !== "number" || !(json.chance > 0 && json.chance <= 1))) {
problems.push("chance must be a number above 0, at most 1");
}
return problems;
}
export function validate_entity(json: unknown): Problems {
if (!is_object(json)) return ["entity must be an object"];
const problems = [
+5
View File
@@ -14,6 +14,7 @@ import {
ModRecipeJson,
OreJson,
RecipeJson,
SpawnJson,
TagJson,
TagRegistry,
} from "./mod_data.ts";
@@ -29,6 +30,8 @@ export interface ModData {
items: ItemJson[];
recipes: RecipeJson[];
ores: OreJson[];
// natural spawns, see SpawnJson
spawns: SpawnJson[];
entities: EntityJson[];
entity_models: EntityModelJson[];
// tag files, see common/tags.ts
@@ -57,6 +60,7 @@ export class RecipeBook {
// every recipe as its json, in load order, for recipe viewers
all: RecipeJson[] = [];
ores: OreJson[] = [];
spawns: SpawnJson[] = [];
}
export class ModLoadError extends Error {
@@ -150,6 +154,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
}
}
recipes.ores.push(...data.ores);
recipes.spawns.push(...data.spawns);
}
return recipes;
+47
View File
@@ -68,6 +68,8 @@ around and look about. Unlike animals, they go away when no player is near. The
}
```
Monsters can also [spawn on their own](#natural-spawning) in the dark.
**Scripted** entities stay exactly where a script puts them. They don't fall, think or get hurt, and aren't saved with
the world, so a script never finds one it doesn't know about after a restart. The fishing hook is one:
@@ -84,6 +86,51 @@ the world, so a script never finds one it doesn't know about after a restart. Th
}
```
## Natural Spawning
Monsters spawn on their own in the dark around players, the way Minecraft's do. A mod lists which ones, how often and in
which biomes in `worldgen/spawns.json`, like NeoForge's `add_spawns` biome modifier. The Undergarden's rotwalkers:
```json
{
"format_version": 1,
"spawns": [
{
"entity": "undergarden:rotwalker",
"weight": 100,
"min_count": 4,
"max_count": 4,
"chance": 0.1
}
]
}
```
| Field | Default | Meaning |
| ----------- | ----------- | --------------------------------------------------------------------------------------------------------------- |
| `entity` | required | A `"monster"` entity. Only monsters spawn on their own for now. |
| `weight` | required | How often this one is picked over the others that can spawn in the same biome. |
| `min_count` | required | How many spawn together, at least. |
| `max_count` | required | And at most. |
| `biomes` | every biome | Biome ids, like `["bworld:dark_forest", "bworld:swamp"]`. See [World Generation](../worldgen/index.md#terrain). |
| `chance` | `1` | The chance a spawn that passed every other check goes ahead. The Undergarden gives its rotspawn 1 in 10. |
Every tick, the server makes one try in each chunk within 6 chunks of a player that their client has loaded:
1. It picks a random spot in the chunk, anywhere from the bottom of the world to just above the surface, so most spawns
are in caves.
2. From there, up to 3 groups wander up to 5 blocks a step at that height. The first spot of a group picks a spawn by
`weight` from the ones for its biome, and the group tries to spawn between `min_count` and `max_count` of it, at most
4 from one try.
3. Each spot has to be at least 24 blocks from every player and from the world spawn, on top of a whole solid block (not
leaves, glass or a block that gives off light 14 or more), with room for the entity's box and no water in it.
4. It has to be dark: no block light at all, and less likely the more sky light there is. Under the open sky monsters
only spawn at night.
There are at most 70 monsters for the 17x17 chunks around a player, fewer when fewer chunks are loaded. Monsters that
never despawn (named, riding or ridden, or that picked up an item) don't count. Like any monster, they despawn when no
player is near.
## Spawning From Scripts
```ts
+1
View File
@@ -19,6 +19,7 @@ mods/
recipes/*.json
tags/<registry>/<namespace>/*.json # tags, see resources/tags.md
worldgen/ores.json
worldgen/spawns.json # monsters that spawn on their own, see entities/index.md
textures/*.png
scripts/
server.ts # game logic, never sent to players
+1 -1
View File
@@ -2,7 +2,7 @@
"format_version": 1,
"id": "undergarden",
"name": "The Undergarden",
"description": "A port of quek's The Undergarden: so far the Rotwalker, a rotting monster that hunts players.",
"description": "A port of quek's The Undergarden: so far the Rotwalker, a rotting monster that spawns in the dark and hunts players.",
"version": "0.1.0",
"authors": [
"quek (original)",
+12
View File
@@ -0,0 +1,12 @@
{
"format_version": 1,
"spawns": [
{
"entity": "undergarden:rotwalker",
"weight": 100,
"min_count": 4,
"max_count": 4,
"chance": 0.1
}
]
}
+7
View File
@@ -35,6 +35,9 @@ export interface SavedMob extends SavedLivingEntity {
drop_chances?: Partial<Record<EquipmentSlot, number>>;
}
// what natural spawning counts a mob as, like minecraft's MobCategory
export type MobCategory = "monster" | "creature";
export abstract class Mob extends LivingEntity {
// doesn't think or move at all, not even falling
no_ai = false;
@@ -75,6 +78,10 @@ export abstract class Mob extends LivingEntity {
];
}
get category(): MobCategory {
return "creature";
}
#registered_goals = false;
// adds the kind's goals, see goals.ts. runs before its first thought, once the kind's fields are set
+5 -1
View File
@@ -15,7 +15,7 @@ import {
RandomLookAroundGoal,
RandomStrollGoal,
} from "./goals.ts";
import { Mob } from "./mob.ts";
import { Mob, type MobCategory } from "./mob.ts";
// the entity's class. the attributes are read while LivingEntity is being built, before any field of a subclass is
// set, so each kind gets its own class that has its json already
@@ -32,6 +32,10 @@ export function mod_entity_factory(json: EntityJson): EntityFactory {
override height = json.height;
override eye_height = json.height * 0.85;
override get category(): MobCategory {
return monster ? "monster" : "creature";
}
override default_attributes(): [AttributeType, number?][] {
return [
...super.default_attributes(),
+7
View File
@@ -74,6 +74,7 @@ import {
import { Mob } from "./entity/mob.ts";
import { LivingEntity } from "./entity/living_entity.ts";
import { EntityManager } from "./entity/entity_manager.ts";
import { NaturalSpawner } from "./natural_spawner.ts";
import { create_entity, entity_type_ids } from "./entity/entity_types.ts";
import { DAMAGE, type DamageSource, type SavedEntity } from "./entity/entity.ts";
import { ATTRIBUTES } from "./entity/attributes.ts";
@@ -170,6 +171,10 @@ export class GameServer {
entities: EntityManager;
mods: ModRuntime;
recipes: RecipeBook;
// monsters spawning on their own near players, see natural_spawner.ts
spawner: NaturalSpawner;
// minecraft's doMobSpawning game rule. tests turn it off so nothing turns up they didn't put there
do_mob_spawning = true;
// what runs tick(), for /tps. tests call tick() themselves
loop?: GameLoop;
// how long a tick can spend building chunks for players. tests lift it so what gets sent doesn't depend on speed
@@ -180,6 +185,7 @@ export class GameServer {
this.#mods = mods;
this.mods = mods.runtime;
this.recipes = mods.recipes;
this.spawner = new NaturalSpawner(mods.recipes.spawns);
const saved: SavedLevel | SavedLevelV4 | undefined = save?.level ? JSON.parse(save.level) : undefined;
if (saved && saved.version !== 5 && saved.version !== 4) {
@@ -1517,6 +1523,7 @@ export class GameServer {
// like minecraft: entities only move near players, and players pick up items by walking into them
#tick_entities() {
if (this.do_mob_spawning) this.spawner.tick(this, SIMULATION_DISTANCE);
this.entities.tick((entity) => this.#near_any_player(entity.x, entity.z));
const items = this.item_entities();
for (const player of this.#players.values()) {
+10
View File
@@ -1,6 +1,7 @@
// a Map that forgets the least recently used entries past max_size
export class LruMap<K, V> {
#map = new Map<K, V>();
#newest: K | undefined;
readonly max_size: number;
constructor(max_size: number) {
@@ -9,7 +10,10 @@ export class LruMap<K, V> {
get(key: K): V | undefined {
const value = this.#map.get(key);
// already the most recent, the same key over and over is common
if (key === this.#newest) return value;
if (value !== undefined) {
this.#newest = key;
// maps keep insertion order, so re-inserting moves it to the back
this.#map.delete(key);
this.#map.set(key, value);
@@ -18,6 +22,7 @@ export class LruMap<K, V> {
}
set(key: K, value: V) {
this.#newest = key;
this.#map.delete(key);
this.#map.set(key, value);
if (this.#map.size > this.max_size) {
@@ -25,6 +30,11 @@ export class LruMap<K, V> {
}
}
// without counting as a use
has(key: K) {
return this.#map.has(key);
}
delete(key: K) {
this.#map.delete(key);
}
+219
View File
@@ -0,0 +1,219 @@
// 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 { daylight } from "$/common/time.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 much darker the sky is at midnight, minecraft's skyDarken
const NIGHT_DARKEN = 11;
// the light monsters spawn in is at most a random level up to this, and there's no block light at all
const MONSTER_LIGHT = 7;
// 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<number, [number, number]>();
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, 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, 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;
}
// like minecraft's Monster.isDarkEnoughToSpawn: less likely the more sky light, never with block light, and
// darker than a random level. the sky's light counts for less at night
#dark_enough(world: ServerWorld, x: number, y: number, z: number) {
const { sky, block } = world.light_at(x, y, z);
if (sky > this.#int(32)) return false;
if (block > 0) return false;
const darken = Math.floor((1 - daylight(world.time)) * NIGHT_DARKEN);
return Math.max(sky - darken, block) <= this.#int(MONSTER_LIGHT + 1);
}
// 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<T>(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_liquid(x, y, z)) return false;
}
}
}
return true;
}
+155 -2
View File
@@ -1,5 +1,10 @@
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import {
block_light_emission,
block_light_opacity,
BlockRegistry,
EverythingRegistry,
} from "$/common/everything_registry.ts";
import { generate_raw_chunk, RawChunk, WorldgenSetup } from "$/common/generation.ts";
import { AIR_ID, BlockChange } from "$/common/protocol.ts";
import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
@@ -12,6 +17,11 @@ import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, Save
// generation only, rebuilt when needed. 256 KB each
const RAW_CACHE_SIZE = 128;
const CHUNK_CACHE_SIZE = 256;
// surface and sky heights, 1 KB each
const COLUMN_CACHE_SIZE = 1024;
// light reaches at most this far, see light_at
const LIGHT_REACH = 15;
const LIGHT_BOX = LIGHT_REACH * 2 + 1;
// how far from the middle of the world to look for dry land to spawn on, in chunks
const SPAWN_SEARCH_CHUNKS = 32;
// generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one
@@ -40,10 +50,17 @@ export class ServerWorld {
readonly worldgen: WorldgenSetup | undefined;
// what a freshly placed or generated block stores, by numeric id: the id with its default states
readonly default_values: number[] = [];
// for light_at, by numeric id
#opacity: Uint8Array;
#emission: Uint8Array;
// what generation made, and the final blocks with neighbors' leaves and player changes applied
#raw = new LruMap<number, RawChunk>(RAW_CACHE_SIZE);
#chunks = new LruMap<number, Uint32Array>(CHUNK_CACHE_SIZE);
// what generation decided each column's biome is, kept for longer than the rest of it
#biomes = new LruMap<number, string[]>(COLUMN_CACHE_SIZE);
// per column of a chunk, the highest block that isn't air, then the lowest y that sees the sky. see #columns_of
#columns = new LruMap<number, Int16Array>(COLUMN_CACHE_SIZE);
// changes from generated terrain, per chunk. saved as whole chunks
#changes = new Map<number, Map<string, BlockChange>>();
@@ -70,9 +87,14 @@ export class ServerWorld {
constructor(seed: string, worldgen?: WorldgenSetup) {
this.seed = seed;
this.worldgen = worldgen;
EverythingRegistry.get_registry<BlockRegistry>("blocks").forEach((block, nid) => {
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
this.#opacity = new Uint8Array(ID_MASK + 1);
this.#emission = new Uint8Array(ID_MASK + 1);
blocks.forEach((block, nid) => {
this.block_ids[block.id] = nid;
this.default_values[nid] = default_block_value(nid, block);
this.#opacity[nid] = block_light_opacity(block);
this.#emission[nid] = block_light_emission(block);
});
}
@@ -141,6 +163,128 @@ export class ServerWorld {
return nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
}
// like "bworld:plains", what generation decided
biome_at(x: number, z: number): string {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const biomes = this.#biomes.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).biomes;
return biomes[column_index(x, z)];
}
// whether the chunk is built and kept, like a loaded chunk in minecraft. nothing builds one by asking
has_chunk(chunk_x: number, chunk_z: number) {
return this.#chunks.has(chunk_key(chunk_x, chunk_z));
}
// counts as using the chunk so it's kept longer, if it's there. returns whether it is, see has_chunk
keep_chunk(chunk_x: number, chunk_z: number) {
return this.#chunks.get(chunk_key(chunk_x, chunk_z)) !== undefined;
}
// whether every chunk within radius blocks of x, z is, see has_chunk
has_chunks_around(x: number, z: number, radius: number) {
for (let cx = Math.floor((x - radius) / CHUNK_SIZE); cx <= Math.floor((x + radius) / CHUNK_SIZE); cx++) {
for (let cz = Math.floor((z - radius) / CHUNK_SIZE); cz <= Math.floor((z + radius) / CHUNK_SIZE); cz++) {
if (!this.has_chunk(cx, cz)) return false;
}
}
return true;
}
// how much light going through the block there loses, 0-15
light_opacity(x: number, y: number, z: number) {
return this.#opacity[this.get_block_nid(x, y, z)];
}
// the highest block that isn't air, -1 for an empty column. minecraft's WORLD_SURFACE heightmap
surface_height(x: number, z: number): number {
return this.#columns_of(x, z)[column_index(x, z)];
}
// the lowest y with nothing above it that stops light, where sky light is 15
sky_height(x: number, z: number): number {
return this.#columns_of(x, z)[CHUNK_AREA + column_index(x, z)];
}
// the sky and block light there, 0-15, the same as clients work out (see client/workers/lighting.ts) but for one
// position: searching out from it, cheapest first, for the brightest place light could come from. light loses
// max(1, opacity) for every block it goes into, and never gets further than 15 blocks
light_at(x: number, y: number, z: number): { sky: number; block: number } {
if (y >= CHUNK_HEIGHT) return { sky: 15, block: 0 };
if (y < 0) return { sky: 0, block: 0 };
// the box around it, 3x3 chunks at most, fetched once each. blocks are in it by their offset from the start
const first_x = Math.floor((x - LIGHT_REACH) / CHUNK_SIZE);
const first_z = Math.floor((z - LIGHT_REACH) / CHUNK_SIZE);
const chunks: (Uint32Array | undefined)[] = [];
const skies: (Int16Array | undefined)[] = [];
const box_index = (dx: number, dy: number, dz: number) =>
((dy + LIGHT_REACH) * LIGHT_BOX + dz + LIGHT_REACH) * LIGHT_BOX + dx + LIGHT_REACH;
// what light loses on its way from a block to the start. 255 is not reached yet
const cost = new Uint8Array(LIGHT_BOX ** 3).fill(255);
const queues: number[][] = Array.from({ length: LIGHT_REACH }, () => []);
let next = 0;
const reach = (dx: number, dy: number, dz: number) => {
if (y + dy < 0 || y + dy >= CHUNK_HEIGHT) return;
const at = box_index(dx, dy, dz);
if (cost[at] <= next) return;
cost[at] = next;
queues[next].push(dx, dy, dz);
};
reach(0, 0, 0);
let sky = 0;
let block = 0;
for (let lost = 0; lost < LIGHT_REACH; lost++) {
// nothing further away can be brighter than what's been found
if (LIGHT_REACH - lost <= sky && LIGHT_REACH - lost <= block) break;
const queue = queues[lost];
for (let i = 0; i < queue.length; i += 3) {
const dx = queue[i], dy = queue[i + 1], dz = queue[i + 2];
if (cost[box_index(dx, dy, dz)] !== lost) continue;
const bx = x + dx, by = y + dy, bz = z + dz;
const chunk_x = Math.floor(bx / CHUNK_SIZE);
const chunk_z = Math.floor(bz / CHUNK_SIZE);
const which = (chunk_z - first_z) * 3 + chunk_x - first_x;
const blocks = chunks[which] ??= this.#get_chunk(chunk_x, chunk_z);
const column = (bz - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + bx - chunk_x * CHUNK_SIZE;
const nid = blocks[by * CHUNK_AREA + column] & ID_MASK;
const columns = skies[which] ??= this.#columns_of(bx, bz);
if (by >= columns[CHUNK_AREA + column]) sky = Math.max(sky, LIGHT_REACH - lost);
block = Math.max(block, this.#emission[nid] - lost);
// light comes to this block from its neighbors, losing what going into it costs
next = lost + Math.max(1, this.#opacity[nid]);
if (next >= LIGHT_REACH) continue;
reach(dx, dy - 1, dz);
reach(dx, dy + 1, dz);
reach(dx - 1, dy, dz);
reach(dx + 1, dy, dz);
reach(dx, dy, dz - 1);
reach(dx, dy, dz + 1);
}
}
return { sky, block };
}
#columns_of(x: number, z: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const key = chunk_key(chunk_x, chunk_z);
let columns = this.#columns.get(key);
if (!columns) {
const blocks = this.#get_chunk(chunk_x, chunk_z);
columns = new Int16Array(CHUNK_AREA * 2);
for (let column = 0; column < CHUNK_AREA; column++) {
let y = CHUNK_HEIGHT - 1;
while (y >= 0 && (blocks[y * CHUNK_AREA + column] & ID_MASK) === AIR) y--;
columns[column] = y;
while (y >= 0 && this.#opacity[blocks[y * CHUNK_AREA + column] & ID_MASK] === 0) y--;
columns[CHUNK_AREA + column] = y + 1;
}
this.#columns.set(key, columns);
}
return columns;
}
// only changes the block, the game server runs behaviors and tiles. state bits default to the block's defaults
set_block(x: number, y: number, z: number, id: string, state?: number) {
if (y < 0 || y >= CHUNK_HEIGHT) {
@@ -157,6 +301,8 @@ export class ServerWorld {
const blocks = this.#get_chunk(chunk_x, chunk_z);
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = value;
this.#columns.delete(chunk_key(chunk_x, chunk_z));
const state_bits = value >>> 16;
this.#record_change(x, y, z, id, state_bits);
this.dirty = true;
@@ -221,6 +367,7 @@ export class ServerWorld {
console.error(`Couldn't load chunk ${chunk_x}, ${chunk_z}: ${(e as Error).message}`);
continue;
}
this.#columns.delete(chunk_key(chunk_x, chunk_z));
const generated = regenerate ? this.#generate_chunk(chunk_x, chunk_z) : undefined;
// unknown ids, from mods that are gone, stay as changes so they come back with the mod
const values = chunk.palette.map(([id, state]) => {
@@ -359,6 +506,7 @@ export class ServerWorld {
if (!raw) {
raw = generate_raw_chunk(chunk_x, chunk_z, this.seed, this.block_ids, this.worldgen, this.default_values);
this.#raw.set(key, raw);
this.#biomes.set(key, raw.biomes);
}
return raw;
}
@@ -414,3 +562,8 @@ export class ServerWorld {
function index_in_chunk(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
return y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE);
}
// a column's place in its chunk, the same as its blocks' in a layer
function column_index(x: number, z: number) {
return (z - Math.floor(z / CHUNK_SIZE) * CHUNK_SIZE) * CHUNK_SIZE + x - Math.floor(x / CHUNK_SIZE) * CHUNK_SIZE;
}
+1
View File
@@ -100,6 +100,7 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod {
items: entries(bmod.data.items),
recipes: entries(bmod.data.recipes),
ores: entries(bmod.data.ores),
spawns: entries(bmod.data.spawns),
entities: entries(bmod.data.entities),
entity_models: entries(bmod.data.entity_models),
tags: entries(bmod.data.tags),
+1 -1
View File
@@ -240,7 +240,7 @@ Deno.test("the atlas fits textures of any size, tallest first, without overlappi
Deno.test("a mod with only data packs and reads", () => {
const bmod = {
manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" },
data: { blocks: [], models: [], items: [], recipes: [], ores: [], entities: [], entity_models: [], tags: [] },
data: { blocks: [], models: [], items: [], recipes: [], ores: [], spawns: [], entities: [], entity_models: [], tags: [] },
scripts: {},
textures: new Map(),
};
+3
View File
@@ -32,6 +32,7 @@ export function mod_sources(mods_dir: string): ServerModSource[] {
items: mod.items.map((i) => i.json),
recipes: mod.recipes.map((r) => r.json),
ores: mod.ores.map((o) => o.json),
spawns: mod.spawns.map((s) => s.json),
entities: mod.entities.map((e) => e.json),
entity_models: mod.entity_models.map((m) => m.json),
tags: mod.tags.map((t) => t.json),
@@ -67,6 +68,8 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test
};
const game: GameServer = await start_game(host, save, seed, mod_sources(mods_dir));
game.chunk_send_budget_ms = Infinity;
// tests that want natural spawning turn it back on
game.do_mob_spawning = false;
// deno-lint-ignore no-explicit-any
const take = (conn: number): any[] => {
const messages = outbox.get(conn) ?? [];
+155
View File
@@ -0,0 +1,155 @@
// monsters spawning on their own in the dark near players, like undergarden's rotwalkers, see natural_spawner.ts and
// mods/undergarden/worldgen/spawns.json
import { assert, assertEquals } from "@std/assert";
import { CHUNK_SIZE } from "$/common/constants.ts";
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
import {
block_light_emission,
block_light_opacity,
BlockRegistry,
EverythingRegistry,
} from "$/common/everything_registry.ts";
import { LightRegion, REGION_LAYER, REGION_SIZE, REGION_VOID } from "$/client/workers/lighting.ts";
import { create_entity } from "$/server/game/entity/entity_types.ts";
import { Mob } from "$/server/game/entity/mob.ts";
import { test_game } from "./helpers.ts";
// chunk 6, 6: a closed stone room with its floor at y 60 and its roof at y 64, and alice standing 40 blocks away
const CHUNK = 6;
const FLOOR = 60;
const ROOF = 64;
async function setup(roof = "bworld:stone") {
const t = await test_game("mods");
const world = t.game.world;
const x0 = CHUNK * CHUNK_SIZE;
for (let x = x0 - 1; x <= x0 + CHUNK_SIZE; x++) {
for (let z = x0 - 1; z <= x0 + CHUNK_SIZE; z++) {
const wall = x < x0 || z < x0 || x >= x0 + CHUNK_SIZE || z >= x0 + CHUNK_SIZE;
world.set_block(x, FLOOR, z, "bworld:stone");
world.set_block(x, ROOF, z, wall ? "bworld:stone" : roof);
for (let y = FLOOR + 1; y < ROOF; y++) world.set_block(x, y, z, wall ? "bworld:stone" : "bworld:air");
}
}
t.join(1, "alice");
const alice = t.game.players()[0];
world.set_block(x0 + 48, FLOOR, x0 + 8, "bworld:stone");
// far enough to see the room and around it, it's 3 chunks away
t.send(1, { type: "view_distance", distance: 5 });
t.send(1, { type: "move", x: x0 + 48.5, y: FLOOR + 1, z: x0 + 8.5, yaw: 0, pitch: 0 });
// her client loads everything around her, the room too
for (let i = 0; i < 100 && alice.chunks.pending_count > 0; i++) {
t.game.tick();
t.send(1, { type: "chunk_batch_received", chunks_per_tick: 64 });
}
// what spawning would keep if it had been on, see NaturalSpawner.tick
for (let dx = -1; dx <= 1; dx++) {
for (let dz = -1; dz <= 1; dz++) world.get_block_nid(x0 + dx * CHUNK_SIZE, 0, x0 + dz * CHUNK_SIZE);
}
t.take(1);
return { ...t, world, alice, x0 };
}
// up to tries times, until something spawns
function try_spawning(game: Awaited<ReturnType<typeof setup>>["game"], tries: number): Mob[] {
for (let i = 0; i < tries; i++) {
const spawned = game.spawner.spawn_in_chunk(game, CHUNK, CHUNK);
if (spawned.length) return spawned;
}
return [];
}
Deno.test("the server's light is the same as what clients work out", async () => {
const { world, x0 } = await setup();
world.set_block(x0 + 3, FLOOR + 1, x0 + 3, "bworld:light");
world.set_block(x0 + 12, ROOF, x0 + 12, "bworld:air");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const opacity = new Uint8Array(REGION_VOID + 1);
const emission = new Uint8Array(REGION_VOID + 1);
blocks.forEach((block, nid) => {
opacity[nid] = block_light_opacity(block);
emission[nid] = block_light_emission(block);
});
opacity[REGION_VOID] = 15;
const region = new LightRegion();
const chunks = [];
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
chunks.push(decode_level_chunk(world.level_chunk(CHUNK + dx, CHUNK + dz)).blocks);
}
}
region.fill(chunks);
region.compute({ opacity, emission });
const check = (x: number, y: number, z: number) => {
const index = y * REGION_LAYER + (z - x0 + CHUNK_SIZE) * REGION_SIZE + x - x0 + CHUNK_SIZE;
const expected = { sky: region.sky[index], block: region.block_light[index] };
assertEquals(world.light_at(x, y, z), expected, `at ${x}, ${y}, ${z}`);
};
// the room, under the hole and around the light
for (let x = x0; x < x0 + CHUNK_SIZE; x++) {
for (let z = x0; z < x0 + CHUNK_SIZE; z++) {
for (let y = FLOOR; y <= ROOF + 1; y++) check(x, y, z);
}
}
// and anywhere else in the chunk
for (let i = 0; i < 2000; i++) {
check(
x0 + Math.floor(Math.random() * 16),
Math.floor(Math.random() * 256),
x0 + Math.floor(Math.random() * 16),
);
}
});
Deno.test("rotwalkers spawn in groups in the dark, on the ground and away from players", async () => {
const { game, alice } = await setup();
const spawned = try_spawning(game, 20000);
assert(spawned.length > 0, "something spawned");
assert(spawned.length <= 4);
for (const mob of spawned) {
assertEquals(mob.type, "undergarden:rotwalker");
assertEquals(mob.y, FLOOR + 1);
assert(Math.hypot(mob.x - alice.x, mob.y - alice.y, mob.z - alice.z) > 24);
assert(game.entities.get_entity(mob.id), "it's in the world");
}
});
Deno.test("nothing spawns where there's block light", async () => {
const { game } = await setup("bworld:light");
assertEquals(try_spawning(game, 20000), []);
});
Deno.test("nothing spawns within 24 blocks of a player", async () => {
const { game, x0, send } = await setup();
send(1, { type: "move", x: x0 + 8.5, y: FLOOR + 1, z: x0 + 8.5, yaw: 0, pitch: 0 });
assertEquals(try_spawning(game, 20000), []);
});
Deno.test("monsters stop spawning at the cap", async () => {
const { game, alice } = await setup();
const rotwalkers = () => game.entities.all().filter((e) => e.type === "undergarden:rotwalker").length;
// alice's chunks are loaded, so she's surrounded by them. nobody can spawn closer than 24 blocks anyway
for (let i = 0; i < 40; i++) {
const mob = create_entity(game.entities, "undergarden:rotwalker")!;
mob.set_position(alice.x, alice.y + 100, alice.z);
(mob as Mob).no_ai = true;
game.entities.add_entity(mob);
}
game.do_mob_spawning = true;
for (let i = 0; i < 200; i++) game.tick();
assertEquals(rotwalkers(), 40);
});
Deno.test("with mob spawning on, monsters turn up as the game ticks", async () => {
const { game } = await setup();
const rotwalkers = () => game.entities.all().filter((e) => e.type === "undergarden:rotwalker");
game.do_mob_spawning = true;
for (let i = 0; i < 3000 && rotwalkers().length === 0; i++) game.tick();
assert(rotwalkers().length > 0);
game.do_mob_spawning = false;
const before = rotwalkers().length;
for (let i = 0; i < 100; i++) game.tick();
assert(rotwalkers().length <= before, "none spawn with it off");
});
+1
View File
@@ -202,6 +202,7 @@ Deno.test("tags survive packing into a .bmod", () => {
items: [],
recipes: [],
ores: [],
spawns: [],
entities: [],
entity_models: [],
tags: [tag],
+18
View File
@@ -4,6 +4,7 @@ import {
entity_model_from_geo,
FORMAT_VERSION,
OreJson,
type SpawnJson,
type TagJson,
validate_block,
validate_entity,
@@ -12,6 +13,7 @@ import {
validate_model,
validate_ore,
validate_recipe,
validate_spawn,
validate_tag,
} from "$/common/mod_data.ts";
import { check_references, load_order, type LoadedMod, type ModReport } from "$/common/mod_check.ts";
@@ -70,6 +72,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
items: [],
recipes: [],
ores: [],
spawns: [],
entities: [],
entity_models: [],
tags: [],
@@ -169,6 +172,21 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
}
}
if (exists(`${dir}/worldgen/spawns.json`)) {
const spawns = read_json(`${dir}/worldgen/spawns.json`, (m) => error(`worldgen/spawns.json: ${m}`));
if (!is_object(spawns) || spawns.format_version !== FORMAT_VERSION || !Array.isArray(spawns.spawns)) {
error(`worldgen/spawns.json: must be { "format_version": ${FORMAT_VERSION}, "spawns": [ ... ] }`);
} else {
spawns.spawns.forEach((spawn, i) => {
const problems = validate_spawn(spawn);
for (const problem of problems) error(`worldgen/spawns.json: spawn ${i}: ${problem}`);
if (problems.length === 0) {
mod.spawns.push({ file: "worldgen/spawns.json", json: spawn as SpawnJson });
}
});
}
}
// a mod only registers ids in its own namespace
for (const { file, json } of [...mod.blocks, ...mod.models, ...mod.items, ...mod.entities]) {
if (json.id.split(":")[0] !== id) error(`${file}: ${json.id} isn't in this mod's namespace "${id}"`);
+1
View File
@@ -31,6 +31,7 @@ export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>>
items: mod.items.map((i) => i.json),
recipes: mod.recipes.map((r) => r.json),
ores: mod.ores.map((o) => o.json),
spawns: mod.spawns.map((s) => s.json),
entities: mod.entities.map((e) => e.json),
entity_models: mod.entity_models.map((m) => m.json),
tags: mod.tags.map((t) => t.json),