Files
bworld/common/generation.ts
T
2026-11-07 12:13:43 -03:00

236 lines
8.6 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// generating a chunk: the terrain from the generator's data (common/worldgen), then ores, then mods' features.
// only the server generates, players get finished chunks
import { Alea } from "@paulaboks/rng";
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import type { WorldShape } from "@/common/world_shape.ts";
import { BIOME_CELL_HEIGHT, ChunkColumn } from "@/common/section.ts";
import type { FeatureChunk, Position } from "@/common/mod_api/worldgen.ts";
import type { OreJson } from "@/common/mod_data.ts";
import { generate_noise_chunk } from "./worldgen/noise_chunk.ts";
import { get_biome } from "./worldgen/biomes.ts";
import type { Generator } from "./worldgen/generator.ts";
import { named_noise_2d, named_noise_3d } from "./worldgen/noise.ts";
export { named_noise_2d, named_noise_3d };
// what mods add to generation, see docs/modding/worldgen/index.md
export interface WorldgenSetup {
// where the dimension's blocks are, chunks hold its whole height
shape: WorldShape;
// the terrain, biomes and surface, from noise settings, see docs/modding/worldgen/terrain.md
generator: Generator;
// each mod's worldgen/ores.json, in load order. each is a pass of its own, so a mod's ores can replace an earlier
// mod's, like the base game's
ores: OreJson[][];
// code and data features in the order they run, see load_worldgen
features: SetupFeature[];
// data features by id, for chunk.place_feature
placeable: Map<string, (chunk: FeatureChunk, origin: Position) => boolean>;
}
export interface SetupFeature {
id: string;
generate: (chunk: FeatureChunk) => void;
// a code feature's biomes: it only runs in chunks with one of them somewhere. data features check each position
// themselves
biomes?: Set<string>;
}
export interface RawChunk {
// only what this chunk generated itself, with its biomes
column: ChunkColumn;
// blocks it generated in other chunks (from features like a mod's trees), flattened as x, y, z, numeric id
spills: Int32Array;
}
// features that threw, so each is only reported once
const failed_features = new Set<string>();
// what a chunk is generated into before it's made sections, indexed (y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x. a
// column at a time is how terrain is worked out, and features set blocks one at a time. kept for the next chunk, so
// generating isn't reentrant
let scratch = new Uint32Array(0);
// generates one chunk on its own. neighbors' spills get merged in by whoever assembles the world:
// a chunk's own blocks always win and spills only fill air, so the result doesn't depend on load order
export function generate_raw_chunk(
chunk_x: number,
chunk_z: number,
seed: string,
block_ids: Record<string, number>,
worldgen: WorldgenSetup,
// the value to store for each numeric id, with its default states. just the id when missing
default_values?: number[],
): RawChunk {
const shape = worldgen.shape;
if (scratch.length !== shape.volume) scratch = new Uint32Array(shape.volume);
const blocks = scratch.fill(AIR);
const spills: number[] = [];
const heights = new Int32Array(CHUNK_AREA);
// a biome cell's, see column_biomes
const biomes: string[] = new Array(CHUNK_AREA * shape.height / BIOME_CELL_HEIGHT);
const set = (x: number, y: number, z: number, nid: number) => {
if (!shape.contains(y)) {
return;
}
nid = default_values?.[nid] ?? nid;
const block_chunk_x = Math.floor(x / CHUNK_SIZE);
const block_chunk_z = Math.floor(z / CHUNK_SIZE);
if (block_chunk_x !== chunk_x || block_chunk_z !== chunk_z) {
spills.push(x, y, z, nid);
return;
}
const lx = x - chunk_x * CHUNK_SIZE;
const lz = z - chunk_z * CHUNK_SIZE;
blocks[(y - shape.min_y) * CHUNK_AREA + lz * CHUNK_SIZE + lx] = nid;
};
const id = (name: string) => {
const nid = block_ids[name];
return nid === undefined ? AIR : default_values?.[nid] ?? nid;
};
generate_noise_chunk(blocks, heights, biomes, chunk_x, chunk_z, shape, worldgen.generator.for_seed(seed), id);
for (const ores of worldgen.ores) {
generate_ores(blocks, chunk_x, chunk_z, shape, seed, block_ids, ores, default_values);
}
generate_features(blocks, heights, biomes, set, chunk_x, chunk_z, seed, block_ids, worldgen);
return { column: ChunkColumn.from_flat(chunk_x, chunk_z, shape, blocks, biomes), spills: new Int32Array(spills) };
}
// each block an ore replaces becomes the first ore whose noise is above its threshold
function generate_ores(
blocks: Uint32Array,
chunk_x: number,
chunk_z: number,
shape: WorldShape,
seed: string,
block_ids: Record<string, number>,
ores: OreJson[],
default_values: number[] | undefined,
) {
const usable = ores
.map((ore) => ({ ...ore, nid: block_ids[ore.id], replaces_nid: block_ids[ore.replaces] }))
.filter((ore) => ore.nid !== undefined && ore.replaces_nid !== undefined);
if (usable.length === 0) {
return;
}
const noises = usable.map((ore) => named_noise_3d(seed, ore.id));
for (let y = shape.min_y; y < shape.max_y; y++) {
for (let lz = 0; lz < CHUNK_SIZE; lz++) {
for (let lx = 0; lx < CHUNK_SIZE; lx++) {
const index = (y - shape.min_y) * CHUNK_AREA + lz * CHUNK_SIZE + lx;
const current = blocks[index] & ID_MASK;
if (current === AIR) {
continue;
}
for (let i = 0; i < usable.length; i++) {
const ore = usable[i];
if (current !== ore.replaces_nid || y < ore.min_y || y > ore.max_y) {
continue;
}
const wx = chunk_x * CHUNK_SIZE + lx;
const wz = chunk_z * CHUNK_SIZE + lz;
if (noises[i](wx * ore.scale, y * ore.scale, wz * ore.scale) > ore.threshold) {
blocks[index] = default_values?.[ore.nid] ?? ore.nid;
break;
}
}
}
}
}
}
function generate_features(
blocks: Uint32Array,
heights: Int32Array,
biomes: string[],
set: (x: number, y: number, z: number, nid: number) => void,
chunk_x: number,
chunk_z: number,
seed: string,
block_ids: Record<string, number>,
worldgen: WorldgenSetup,
) {
const shape = worldgen.shape;
const ids_by_nid: string[] = [];
for (const [id, nid] of Object.entries(block_ids)) {
ids_by_nid[nid] = id;
}
// the cell of biomes a y is in, the top or bottom one past the world's height
const cell = (y: number) => {
const clamped = Math.min(Math.max(y, shape.min_y), shape.max_y - 1);
return Math.floor((clamped - shape.min_y) / BIOME_CELL_HEIGHT) * CHUNK_AREA;
};
const local = (x: number, z: number, what: string) => {
const lx = x - chunk_x * CHUNK_SIZE;
const lz = z - chunk_z * CHUNK_SIZE;
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE) {
throw new Error(`${what}(${x}, ${z}) is outside chunk ${chunk_x}, ${chunk_z}`);
}
return lz * CHUNK_SIZE + lx;
};
const chunk_biomes = new Set(biomes);
for (const feature of worldgen.features) {
if (feature.biomes && ![...feature.biomes].some((biome) => chunk_biomes.has(biome))) continue;
const chunk: FeatureChunk = {
x: chunk_x,
z: chunk_z,
seed,
min_y: shape.min_y,
max_y: shape.max_y,
rng: new Alea(`${seed}_feature_${feature.id}_${chunk_x}_${chunk_z}`),
random: (name) => new Alea(`${seed}_${name}`),
noise_2d: (name) => named_noise_2d(seed, name),
noise_3d: (name) => named_noise_3d(seed, name),
height_at: (x, z) => heights[local(x, z, "height_at")],
biome_at: (x, y, z) => biomes[cell(y) + local(x, z, "biome_at")],
set_biome(x, y, z, biome) {
if (!get_biome(biome)) throw new Error(`set_biome: ${biome} isn't a biome`);
if (shape.contains(y)) biomes[cell(y) + local(x, z, "set_biome")] = biome;
},
get_block(x, y, z) {
if (!shape.contains(y)) {
return undefined;
}
const nid = blocks[(y - shape.min_y) * CHUNK_AREA + local(x, z, "get_block")] & ID_MASK;
return nid === AIR ? "cubi:air" : ids_by_nid[nid];
},
set_block(x, y, z, id) {
const nid = id === "cubi:air" ? AIR : block_ids[id];
if (nid === undefined) {
throw new Error(`unknown block ${id}`);
}
const dx = Math.floor(x / CHUNK_SIZE) - chunk_x;
const dz = Math.floor(z / CHUNK_SIZE) - chunk_z;
if (Math.abs(dx) > 1 || Math.abs(dz) > 1) {
throw new Error(`set_block(${x}, ${y}, ${z}) is more than one chunk away`);
}
set(x, y, z, nid);
},
place_feature(id, x, y, z) {
const place = worldgen.placeable.get(id);
if (!place) throw new Error(`place_feature: ${id} isn't a data feature`);
return place(chunk, { x, y, z });
},
};
try {
feature.generate(chunk);
} catch (e) {
// every client and the server hit the same error, so skipping it keeps them in agreement
if (!failed_features.has(feature.id)) {
failed_features.add(feature.id);
console.error(`Worldgen feature ${feature.id} failed, skipping it where it throws:`, e);
}
}
}
}