3D biomes

This commit is contained in:
2026-11-07 12:13:43 -03:00
parent b726ce9695
commit 22191d260c
53 changed files with 874 additions and 316 deletions
+2 -2
View File
@@ -169,8 +169,8 @@ export class Hud {
#render_info(client: Client) {
const { day, hour, minute } = clock(client.level.time);
const { x, z } = client.player;
const biome = client.level.biome_at(Math.floor(x), Math.floor(z));
const { x, y, z } = client.player;
const biome = client.level.biome_at(Math.floor(x), Math.floor(y), Math.floor(z));
const lines = [
`Day ${day}`,
`${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`,
+16 -21
View File
@@ -22,7 +22,7 @@ import {
} from "@/common/everything_registry.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, column_heights, section_index, type SectionData } from "@/common/section.ts";
import { ChunkColumn, column_heights, section_index, type SectionBiomes, type SectionData } from "@/common/section.ts";
import { AssetManager } from "../assets.ts";
import { ChunkWorkerPool } from "../chunk_workers.ts";
import type { FaceGroup, FromChunkWorker, SectionLight } from "../workers/chunk_messages.ts";
@@ -53,7 +53,7 @@ export interface Chunk {
sky: Int16Array;
// one for each of its sections, from the bottom of the world up
sections: RenderSection[];
// each column's biome grass color, x then z, then each column's foliage color, then water color
// each of its biome palette's grass, foliage and water colors, three numbers a biome
biome_colors: Uint32Array;
}
@@ -226,12 +226,9 @@ export class ClientLevel {
// a whole chunk, replacing it if it was already here. its blocks are this client's numeric ids with their state bits
set_chunk(column: ChunkColumn) {
const { x, z } = column;
const biome_colors = new Uint32Array(CHUNK_AREA * 3);
column.biomes.forEach((biome, column) => {
biome_colors[column] = grass_color(biome);
biome_colors[CHUNK_AREA + column] = foliage_color(biome);
biome_colors[CHUNK_AREA * 2 + column] = water_color(biome);
});
const biome_colors = Uint32Array.from(
column.biomes.palette.flatMap((biome) => [grass_color(biome), foliage_color(biome), water_color(biome)]),
);
const sky = column_heights(column, this.#light.opacity).slice(CHUNK_AREA);
@@ -358,22 +355,17 @@ export class ClientLevel {
return block ? collision_shape_at(block, value) : true;
}
// the column's biome, undefined in unloaded chunks
biome_at(x: number, z: number): string | undefined {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
return this.get_chunk(chunk_x, chunk_z)
?.column.biomes[(z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
// the biome at a block, undefined in unloaded chunks
biome_at(x: number, y: number, z: number): string | undefined {
return this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE))?.column.biome_at(x, y, z);
}
// the biome's water color at a column as 0xRRGGBB, see "tint". plains' in unloaded chunks
water_color(x: number, z: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const chunk = this.get_chunk(chunk_x, chunk_z);
// the biome's water color at a block as 0xRRGGBB, see "tint". plains' in unloaded chunks
water_color(x: number, y: number, z: number) {
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
if (!chunk) return DEFAULT_WATER_COLOR;
return chunk
.biome_colors[CHUNK_AREA * 2 + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
const biome = chunk.column.biomes.palette.indexOf(chunk.column.biome_at(x, y, z));
return chunk.biome_colors[biome * 3 + 2];
}
// the fluid there and how high it is, for fluids pushing things along. unloaded chunks have none
@@ -620,12 +612,14 @@ export class ClientLevel {
const end = Math.min(chunk.sections.length, highest + 2);
const chunks: (SectionData[] | null)[] = [];
const sky: (Int16Array | null)[] = [];
const biomes: (SectionBiomes[] | null)[] = [];
const biome_colors: (Uint32Array | null)[] = [];
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
const neighbor = this.get_chunk(chunk.x + dx, chunk.z + dz);
chunks.push(neighbor?.column.sections.slice(first, end).map((section) => section.data) ?? null);
sky.push(neighbor?.sky ?? null);
biomes.push(neighbor?.column.biomes.sections.slice(first, end) ?? null);
biome_colors.push(neighbor?.biome_colors ?? null);
}
}
@@ -638,6 +632,7 @@ export class ClientLevel {
first,
chunks,
sky,
biomes,
biome_colors,
camera: [camera.x, camera.y, camera.z],
});
+9 -9
View File
@@ -92,9 +92,9 @@ const rules_world: SharedWorld = {
const shape = client?.level.collision_shape(x, y, z) ?? false;
return covers_face(shape === true ? FULL_SHAPE : shape === false ? EMPTY_SHAPE : shape, face);
},
biome_at: (x, z) => client?.level.biome_at(Math.floor(x), Math.floor(z)),
season_at(x, z) {
const biome = this.biome_at(x, z);
biome_at: (x, y, z) => client?.level.biome_at(Math.floor(x), Math.floor(y), Math.floor(z)),
season_at(x, y, z) {
const biome = this.biome_at(x, y, z);
return biome === undefined ? undefined : biome_season(biome, client!.level.time);
},
};
@@ -340,12 +340,12 @@ function client_context(listing: ModListing): ClientContext {
return { x, y, z };
},
get biome() {
const { x, z } = need_client().player;
return rules_world.biome_at(x, z);
const { x, y, z } = need_client().player;
return rules_world.biome_at(x, y, z);
},
get season() {
const { x, z } = need_client().player;
return rules_world.season_at(x, z);
const { x, y, z } = need_client().player;
return rules_world.season_at(x, y, z);
},
is_swimming: () => need_client().player.swimming,
is_sneaking: () => need_client().player.holding_sneak,
@@ -358,8 +358,8 @@ function client_context(listing: ModListing): ClientContext {
},
get_client_data: (x, y, z, field) =>
structuredClone(need_client().level.get_block_data(x, y, z)?.[field]) as never,
biome_at: (x, z) => rules_world.biome_at(x, z),
season_at: (x, z) => rules_world.season_at(x, z),
biome_at: (x, y, z) => rules_world.biome_at(x, y, z),
season_at: (x, y, z) => rules_world.season_at(x, y, z),
get min_y() {
return need_client().level.shape.min_y;
},
+1 -1
View File
@@ -56,7 +56,7 @@ export class GameRenderer {
const { x, y, z } = client.camera;
const [bx, by, bz] = [Math.floor(x), Math.floor(y), Math.floor(z)];
if (!client.level.is_fluid(bx, by, bz)) return;
const color = client.level.water_color(bx, bz);
const color = client.level.water_color(bx, by, bz);
draw_rect(0, 0, canvas.width, canvas.height, [
(color >> 16) / 255,
((color >> 8) & 0xff) / 255,
+4 -2
View File
@@ -5,7 +5,7 @@ import type { BlockRegistry } from "@/common/everything_registry.ts";
import type { SpriteRegion } from "@/common/constants.ts";
import type { ModelJson } from "@/common/block_models.ts";
import type { WorldShapeJson } from "@/common/world_shape.ts";
import type { SectionData } from "@/common/section.ts";
import type { SectionBiomes, SectionData } from "@/common/section.ts";
import type { SortType } from "./translucent_sort.ts";
// messages between the main thread and the chunk workers
@@ -58,7 +58,9 @@ export type ToChunkWorker =
chunks: (SectionData[] | null)[];
// the same chunks' sky heights, see column_heights in common/section.ts
sky: (Int16Array | null)[];
// the same chunks' biome colors (see Chunk.biome_colors in client_level.ts), blended across their edges
// the same chunks' biome cells, of the same sections as chunks, and their biome palettes' colors (see
// Chunk.biome_colors in client_level.ts), blended across their edges
biomes: (SectionBiomes[] | null)[];
biome_colors: (Uint32Array | null)[];
// where the camera is, to sort the translucent quads
camera: number[];
+40 -11
View File
@@ -22,7 +22,7 @@ import {
type ToChunkWorker,
UNALIGNED_GROUP,
} from "./chunk_messages.ts";
import { Section, section_index, SECTION_VOLUME } from "@/common/section.ts";
import { BIOME_CELL_HEIGHT, Section, section_index, SECTION_VOLUME, type SectionBiomes } from "@/common/section.ts";
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
import {
bake_block,
@@ -153,7 +153,9 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
const bottom = world_min_y + message.first * SECTION_HEIGHT;
region.fill(chunks, message.sky, bottom);
region.compute(light_tables);
blend_biome_colors(message.biome_colors);
biomes = message.biomes;
biome_colors = message.biome_colors;
blended_any = false;
const sections: SectionMesh[] = message.sections.map(({ index, version }) => {
// the section's bottom in the region
const from = (index - message.first) * SECTION_HEIGHT;
@@ -225,18 +227,41 @@ function post(message: FromChunkWorker, transfer: Transferable[]) {
self.postMessage(message, transfer);
}
// like minecraft's biome blend at its default radius: each column's grass, foliage and water color is the average of the 5x5
// columns around it, so biome edges fade instead of being a line. neighbors that aren't there are left out
// like minecraft's biome blend at its default radius: each column's grass, foliage and water color is the average of
// the 5x5 columns around it at the same height, so biome edges fade instead of being a line. neighbors that aren't
// there are left out. colors aren't blended up and down
const BLEND_RADIUS = 2;
// the middle chunk's blended colors, x then z, grass then foliage then water
// the 3x3 chunks' biome cells and colors of the request being meshed, see "mesh"
let biomes: (SectionBiomes[] | null)[] = [];
let biome_colors: (Uint32Array | null)[] = [];
// the middle chunk's blended colors at a layer of cells, x then z, grass then foliage then water
const blended = new Uint32Array(CHUNK_AREA * 3);
// the 3x3 chunks' biome palette index of each column at that layer, so a layer with the same biomes as the last one
// blended isn't blended again, unless none has been for this request
const blended_cells = new Uint8Array(9 * CHUNK_AREA);
let blended_any = false;
const layer_cells = new Uint8Array(9 * CHUNK_AREA);
// what MeshQuad.tint is for the biome's colors, they aren't colors since those only go up to 0xffffff
const GRASS = -1;
const FOLIAGE = -2;
const WATER = -3;
function blend_biome_colors(colors: (Uint32Array | null)[]) {
for (const offset of [0, CHUNK_AREA, CHUNK_AREA * 2]) {
// blends the colors of the layer of biome cells y is in, in the region's section from (see "mesh")
function blend_biome_colors(from: number, y: number) {
const layer = ((y & 15) >> 2) << 8;
for (let i = 0; i < 9; i++) {
const cells = biomes[i]?.[from >> 4];
if (cells === undefined) continue;
if (typeof cells === "number") layer_cells.fill(cells, i * CHUNK_AREA, (i + 1) * CHUNK_AREA);
else layer_cells.set(cells.subarray(layer, layer + CHUNK_AREA), i * CHUNK_AREA);
}
let same = blended_any;
for (let i = 0; i < layer_cells.length && same; i++) same = layer_cells[i] === blended_cells[i];
if (same) return;
blended_cells.set(layer_cells);
blended_any = true;
for (let part = 0; part < 3; part++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
let r = 0;
@@ -248,9 +273,12 @@ function blend_biome_colors(colors: (Uint32Array | null)[]) {
// which of the 3x3 chunks, and where in it
const sx = x + dx + CHUNK_SIZE;
const sz = z + dz + CHUNK_SIZE;
const chunk = colors[Math.floor(sz / CHUNK_SIZE) * 3 + Math.floor(sx / CHUNK_SIZE)];
if (!chunk) continue;
const color = chunk[offset + (sz % CHUNK_SIZE) * CHUNK_SIZE + (sx % CHUNK_SIZE)];
const chunk = Math.floor(sz / CHUNK_SIZE) * 3 + Math.floor(sx / CHUNK_SIZE);
const colors = biome_colors[chunk];
if (!colors || !biomes[chunk]) continue;
const cell =
layer_cells[chunk * CHUNK_AREA + (sz % CHUNK_SIZE) * CHUNK_SIZE + (sx % CHUNK_SIZE)];
const color = colors[cell * 3 + part];
r += color >> 16;
g += (color >> 8) & 0xff;
b += color & 0xff;
@@ -260,7 +288,7 @@ function blend_biome_colors(colors: (Uint32Array | null)[]) {
const color = count === 0
? 0xffffff
: (Math.round(r / count) << 16) | (Math.round(g / count) << 8) | Math.round(b / count);
blended[offset + z * CHUNK_SIZE + x] = color;
blended[part * CHUNK_AREA + z * CHUNK_SIZE + x] = color;
}
}
}
@@ -721,6 +749,7 @@ function make_section_mesh(
// nothing to mesh in a section of air
const air = section.blocks === null && section.value === AIR;
for (let y = from; y < from + SECTION_HEIGHT && !air; y++) {
if (y % BIOME_CELL_HEIGHT === 0) blend_biome_colors(from, y);
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
// the middle chunk of the region
+3 -4
View File
@@ -5,7 +5,7 @@
// player, and which chunks are in a player's view. see "Chunk Streaming" in docs/modding_plan.md
import { deflateSync, inflateSync } from "fflate";
import { Reader, Writer } from "./bytes.ts";
import { type ChunkColumn, read_column, type Section, write_column } from "./section.ts";
import { type ChunkColumn, type ColumnBiomes, read_column, type Section, write_column } from "./section.ts";
// the view distances clients can ask for, in chunks, like minecraft's
export const MIN_VIEW_DISTANCE = 2;
@@ -38,8 +38,7 @@ export interface LevelChunk {
// block values (numeric id | state bits << 16) in the receiver's numbering, see decode_level_chunk. from the bottom
// of the world up, the dimension's whole height
sections: Section[];
// each column's biome, x then z
biomes: string[];
biomes: ColumnBiomes;
}
// a level_chunk message, like minecraft's ClientboundLevelChunkWithLightPacket without the light (clients light
@@ -47,7 +46,7 @@ export interface LevelChunk {
//
// u8 LEVEL_CHUNK
// i32 chunk x, i32 chunk z
// the rest deflated: the biomes and the sections' block values, see write_column in common/section.ts
// the rest deflated: the sections' block values and biomes, see write_column in common/section.ts
export function encode_level_chunk(chunk: ChunkColumn): Uint8Array<ArrayBuffer> {
const writer = new Writer();
write_column(writer, chunk.sections, chunk.biomes);
+18 -6
View File
@@ -6,10 +6,11 @@
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 { ChunkColumn } from "@/common/section.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";
@@ -33,12 +34,13 @@ export interface WorldgenSetup {
export interface SetupFeature {
id: string;
generate: (chunk: FeatureChunk) => void;
// a code feature's biomes: it only runs in chunks with one of them. data features check each position themselves
// 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 each column's biome
// 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;
@@ -68,7 +70,8 @@ export function generate_raw_chunk(
const blocks = scratch.fill(AIR);
const spills: number[] = [];
const heights = new Int32Array(CHUNK_AREA);
const biomes: string[] = new Array(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)) {
@@ -155,11 +158,17 @@ function generate_features(
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;
@@ -169,7 +178,6 @@ function generate_features(
return lz * CHUNK_SIZE + lx;
};
const shape = worldgen.shape;
const chunk_biomes = new Set(biomes);
for (const feature of worldgen.features) {
if (feature.biomes && ![...feature.biomes].some((biome) => chunk_biomes.has(biome))) continue;
@@ -184,7 +192,11 @@ function generate_features(
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, z) => biomes[local(x, z, "biome_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;
+3 -3
View File
@@ -55,9 +55,9 @@ export interface ClientContext {
// a field of the block's client data, what server scripts set with BlockRef.set_client_data, a copy.
// undefined when it isn't set or the chunk isn't loaded
get_client_data<T>(x: number, y: number, z: number, field: string): T | undefined;
// the column's biome and its season, undefined when the chunk isn't loaded
biome_at(x: number, z: number): Id | undefined;
season_at(x: number, z: number): Season | undefined;
// the biome at a block and its season, like the server's. undefined when the chunk isn't loaded
biome_at(x: number, y: number, z: number): Id | undefined;
season_at(x: number, y: number, z: number): Season | undefined;
// the dimension's blocks go from min_y up to max_y - 1
readonly min_y: number;
readonly max_y: number;
+5 -4
View File
@@ -70,7 +70,7 @@ export interface BlockRef {
readonly x: number;
readonly y: number;
readonly z: number;
// the biome of its column and that biome's season, see ServerWorld.biome_at
// the biome at the block and that biome's season, see ServerWorld.biome_at
readonly biome: Id;
readonly season: Season;
// tile data, any json value. saved with the world, never sent to clients
@@ -358,10 +358,11 @@ export interface ServerWorld {
// whether the chunk the column is in was ever generated, so reading its blocks generates nothing. for code that
// reaches far, like a walk along something long, which can stop at the rest: nobody has built anything there
is_loaded(x: number, z: number): boolean;
// the column's biome, like "bworld:plains", and that biome's season. in chunks that aren't loaded it's what
// the biome at a block, like "bworld:plains", and that biome's season, like neoforge's level.getBiome(pos). one per
// block across and every 4 blocks up, see docs/modding/worldgen/biomes.md. in chunks that aren't loaded it's what
// generation makes there, which takes a while the first time
biome_at(x: number, z: number): Id;
season_at(x: number, z: number): Season;
biome_at(x: number, y: number, z: number): Id;
season_at(x: number, y: number, z: number): Season;
// the dimension's blocks go from min_y up to max_y - 1. outside them get_block is air and nothing can be placed
readonly min_y: number;
readonly max_y: number;
+4 -3
View File
@@ -198,9 +198,10 @@ export interface SharedWorld {
// whether the block's side is a full square things can attach to, like minecraft's isFaceSturdy: its collision
// shape covers the whole face. false for air, plants, water and the sides of a slab
is_face_sturdy(x: number, y: number, z: number, face: Face): boolean;
// the column's biome, like "bworld:plains", and that biome's season. undefined when the chunk isn't loaded
biome_at(x: number, z: number): Id | undefined;
season_at(x: number, z: number): Season | undefined;
// the biome at a block, like "bworld:plains", and that biome's season, like neoforge's level.getBiome(pos). one per
// block across and every 4 blocks up, see docs/modding/worldgen/biomes.md. undefined when the chunk isn't loaded
biome_at(x: number, y: number, z: number): Id | undefined;
season_at(x: number, y: number, z: number): Season | undefined;
}
// a block in the world, for rules
+8 -4
View File
@@ -38,7 +38,7 @@ export type FeatureStep =
export interface FeatureOptions {
step?: FeatureStep;
// only runs in chunks with one of these biomes
// only runs in chunks with one of these biomes somewhere, at any height
biomes?: Id | Id[];
}
@@ -66,9 +66,14 @@ export interface FeatureChunk {
// create_noise_2d(new Alea(seed + "_" + name)), cached per seed and name
noise_2d(name: string): (x: number, z: number) => number;
noise_3d(name: string): (x: number, y: number, z: number) => number;
// surface height and biome, inside this chunk only
// the column's surface height, inside this chunk only
height_at(x: number, z: number): number;
biome_at(x: number, z: number): Id;
// the biome at a block, like neoforge's level.getBiome(pos), inside this chunk only. biomes are one per block
// across and one every 4 blocks up, see docs/modding/worldgen/biomes.md. above and below the world it's the one at
// its top or bottom
biome_at(x: number, y: number, z: number): Id;
// sets the biome of the 4 blocks tall cell y is in, inside this chunk only. nothing outside the world's height
set_biome(x: number, y: number, z: number, biome: Id): void;
get_block(x: number, y: number, z: number): Id | undefined; // inside this chunk only
set_block(x: number, y: number, z: number, id: Id): void; // up to one chunk away, like trees
// a data feature's type and config at x, y, z, without its placement. whether it placed anything
@@ -77,5 +82,4 @@ export interface FeatureChunk {
export interface TerrainChunk extends FeatureChunk {
set_height(x: number, z: number, height: number): void;
set_biome(x: number, z: number, biome: Id): void;
}
+2 -1
View File
@@ -36,6 +36,7 @@ import {
noise_settings_refs,
type NoiseJson,
type NoiseSettingsJson,
RULE_NAMES,
type WorldgenRefs,
} from "./worldgen/data.ts";
import { feature_refs, type FeatureJson } from "./worldgen/features.ts";
@@ -443,7 +444,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
// what its rules look at, in every generator that uses it
const users = all_noise_settings.filter((settings) => settings.biome_source === (json.extends ?? json.id));
for (const settings of users) {
const names = new Set([...Object.keys(settings.climate), "surface", "steep"]);
const names = new Set([...Object.keys(settings.climate), ...RULE_NAMES]);
for (const rule of json.rules) {
for (const name of Object.keys(rule.when ?? {})) {
if (!names.has(name)) {
+1 -1
View File
@@ -12,7 +12,7 @@ export const AIR_ID = "cubi:air";
// bump when a client and server of different versions can't play together.
// the server rejects a different version before the client downloads anything
export const PROTOCOL_VERSION = 27;
export const PROTOCOL_VERSION = 28;
export interface PlayerInfo {
id: string;
+181 -60
View File
@@ -55,18 +55,93 @@ export class Section {
}
}
// a chunk's blocks, its dimension's whole height, and each column's biome
// biomes are one per block across, and one every BIOME_CELL_HEIGHT blocks up: a cell
export const BIOME_CELL_HEIGHT = 4;
export const SECTION_BIOMES = CHUNK_AREA * SECTION_HEIGHT / BIOME_CELL_HEIGHT;
// a column's biome palette can't be longer, since a cell's index in it is a byte
export const MAX_COLUMN_BIOMES = 256;
// a biome cell's place in its section's biomes: its layer of cells, then z, then x
export function biome_index(x: number, y: number, z: number) {
return (((y & 15) >> 2) << 8) | ((z & 15) << 4) | (x & 15);
}
// a section's biomes: one index into its column's biome palette for all of it, or SECTION_BIOMES of them. an array is
// never changed once it's made, see ChunkColumn.set_biome, so sections with the same biomes can share one: most of a
// column's when biomes don't change with height
export type SectionBiomes = number | Uint8Array;
// a chunk's biomes
export interface ColumnBiomes {
// every biome in it, at most MAX_COLUMN_BIOMES
palette: string[];
// by section from the bottom up, like its blocks
sections: SectionBiomes[];
}
// biomes from each cell's biome id, a layer of cells at a time from the bottom of the world up, then z, then x. or
// CHUNK_AREA of them, each column's biome all the way up. count is how many sections there are
export function column_biomes(cells: string[], count: number): ColumnBiomes {
const palette: string[] = [];
const indexes = new Map<string, number>();
const sections: SectionBiomes[] = [];
const section = new Uint8Array(SECTION_BIOMES);
// runs of the same biome are common, it's only looked up when it changes
let last: string | undefined;
let last_index = 0;
for (let s = 0; s < count; s++) {
let same = true;
for (let i = 0; i < SECTION_BIOMES; i++) {
const biome = cells[cells.length === CHUNK_AREA ? i & 255 : s * SECTION_BIOMES + i];
if (biome !== last) {
last = biome;
let index = indexes.get(biome);
if (index === undefined) {
if (palette.length === MAX_COLUMN_BIOMES) throw new Error(`More than ${MAX_COLUMN_BIOMES} biomes`);
index = palette.push(biome) - 1;
indexes.set(biome, index);
}
last_index = index;
}
section[i] = last_index;
if (last_index !== section[0]) same = false;
}
sections.push(same ? section[0] : section.slice());
}
share_same(sections);
return { palette, sections };
}
// sections whose biomes are the same as the one below's share its array
function share_same(sections: SectionBiomes[]) {
for (let s = 1; s < sections.length; s++) {
const below = sections[s - 1];
const here = sections[s];
if (typeof below === "number" || typeof here === "number" || below === here) continue;
let i = 0;
while (i < SECTION_BIOMES && below[i] === here[i]) i++;
if (i === SECTION_BIOMES) sections[s] = below;
}
}
// the biome at world coordinates in a chunk's biomes, see ChunkColumn.biome_at
export function biome_in(biomes: ColumnBiomes, shape: WorldShape, x: number, y: number, z: number): string {
y = Math.min(Math.max(y, shape.min_y), shape.max_y - 1);
const section = biomes.sections[(y - shape.min_y) >> 4];
return biomes.palette[typeof section === "number" ? section : section[biome_index(x, y, z)]];
}
// a chunk's blocks and biomes, its dimension's whole height
export class ChunkColumn {
readonly x: number;
readonly z: number;
readonly shape: WorldShape;
// from min_y up
readonly sections: Section[];
// x then z
readonly biomes: string[];
readonly biomes: ColumnBiomes;
constructor(x: number, z: number, shape: WorldShape, sections: Section[], biomes: string[]) {
if (sections.length * SECTION_HEIGHT !== shape.height) {
constructor(x: number, z: number, shape: WorldShape, sections: Section[], biomes: ColumnBiomes) {
if (sections.length * SECTION_HEIGHT !== shape.height || biomes.sections.length !== sections.length) {
throw new Error(`Chunk ${x}, ${z} has ${sections.length} sections, its dimension ${shape.height / 16}`);
}
this.x = x;
@@ -76,13 +151,39 @@ export class ChunkColumn {
this.biomes = biomes;
}
// from every block's value in one array, y from min_y then z then x, which is copied
// from every block's value in one array, y from min_y then z then x, which is copied, and the biomes of its cells,
// see column_biomes
static from_flat(x: number, z: number, shape: WorldShape, blocks: Uint32Array, biomes: string[]): ChunkColumn {
const sections: Section[] = [];
for (let start = 0; start < blocks.length; start += SECTION_VOLUME) {
sections.push(Section.of(blocks.subarray(start, start + SECTION_VOLUME)));
}
return new ChunkColumn(x, z, shape, sections, biomes);
return new ChunkColumn(x, z, shape, sections, column_biomes(biomes, sections.length));
}
// the biome at world coordinates. above and below the dimension it's the one at its top or bottom
biome_at(x: number, y: number, z: number): string {
return biome_in(this.biomes, this.shape, x, y, z);
}
// sets the biome of the cell y is in. does nothing outside the dimension's height
set_biome(x: number, y: number, z: number, biome: string) {
if (!this.shape.contains(y)) return;
const { palette, sections } = this.biomes;
let index = palette.indexOf(biome);
if (index === -1) {
if (palette.length === MAX_COLUMN_BIOMES) {
throw new Error(`More than ${MAX_COLUMN_BIOMES} biomes in a chunk`);
}
index = palette.push(biome) - 1;
}
const s = (y - this.shape.min_y) >> 4;
const section = sections[s];
if (section === index) return;
// a copy, since other sections and other chunks' copies can share the array
const changed = typeof section === "number" ? new Uint8Array(SECTION_BIOMES).fill(section) : section.slice();
changed[biome_index(x, y, z)] = index;
sections[s] = changed;
}
// the block value at world coordinates, air outside the dimension's height
@@ -99,7 +200,9 @@ export class ChunkColumn {
clone(): ChunkColumn {
const sections = this.sections.map((section) => new Section(section.blocks?.slice() ?? section.value));
return new ChunkColumn(this.x, this.z, this.shape, sections, [...this.biomes]);
// the sections' biome arrays are never changed, so they can be shared
const biomes = { palette: [...this.biomes.palette], sections: [...this.biomes.sections] };
return new ChunkColumn(this.x, this.z, this.shape, sections, biomes);
}
// every block's value in one array, like from_flat's
@@ -117,49 +220,51 @@ export function to_flat(sections: Section[]): Uint32Array {
return blocks;
}
// bits per block of a section's palette, the smallest that fits. more than 256 kinds are written whole
// bits per value of a paletted container's palette, the smallest that fits. more than 256 kinds are written whole
const PALETTE_BITS = [1, 2, 4, 8];
const DIRECT_BITS = 32;
// a column's biomes and sections, as level_chunk and saved chunks hold them (see common/chunk_streaming.ts and
// server/game/saves.ts). the network sends block values, a save the index of each block in its palette:
// a column's sections and biomes, as level_chunk and saved chunks hold them (see common/chunk_streaming.ts and
// server/game/saves.ts). the network sends block values, a save the index of each block in its own palette:
//
// u16 biome palette size, then each biome: u8 length and the id as utf-8
// u8 each column's biome palette index, x then z. left out when there's one biome
// u16 how many sections there are
// each section of 16x16x16 blocks, bottom first, a paletted container:
// u8 bits per block
// 0: u32 the value of every block
// 1, 2, 4, 8: u16 palette size, u32 each value, then each block's palette index packed from the low bits up
// 32: u32 each block's value
export function write_column(writer: Writer, sections: Section[], biomes: string[]) {
if (biomes.length !== CHUNK_AREA) throw new Error(`${biomes.length} biomes in a chunk`);
const biome_palette = [...new Set(biomes)];
writer.u16(biome_palette.length);
for (const biome of biome_palette) writer.string(biome);
if (biome_palette.length > 1) {
for (const biome of biomes) writer.u8(biome_palette.indexOf(biome));
// each section, bottom first:
// its 16x16x16 blocks, a paletted container of their values
// its biome cells (see biome_index), a paletted container of their biome palette indexes
//
// a paletted container, like minecraft's:
// u8 bits per value
// 0: u32 every value
// 1, 2, 4, 8: u16 palette size, u32 each value, then each one's palette index packed from the low bits up
// 32: u32 each value
export function write_column(writer: Writer, sections: Section[], biomes: ColumnBiomes) {
if (biomes.sections.length !== sections.length || biomes.palette.length > MAX_COLUMN_BIOMES) {
throw new Error("Bad biomes");
}
writer.u16(biomes.palette.length);
for (const biome of biomes.palette) writer.string(biome);
writer.u16(sections.length);
for (const section of sections) write_section(writer, section);
sections.forEach((section, i) => {
write_paletted(writer, section.blocks ?? section.value);
write_paletted(writer, biomes.sections[i]);
});
}
function write_section(writer: Writer, section: Section) {
const blocks = section.blocks;
if (blocks === null) {
function write_paletted(writer: Writer, values: number | Uint32Array | Uint8Array) {
if (typeof values === "number") {
writer.u8(0);
writer.u32(section.value);
writer.u32(values);
return;
}
// each block's palette index. runs of the same block are common, so it's looked up when the block changes
const indexes = new Uint16Array(SECTION_VOLUME);
// each value's palette index. runs of the same value are common, so it's looked up when the value changes
const indexes = new Uint16Array(values.length);
const palette: number[] = [];
const index_of = new Map<number, number>();
let last_value = blocks[0] + 1;
let last_value = values[0] + 1;
let last_index = 0;
for (let i = 0; i < SECTION_VOLUME; i++) {
const value = blocks[i];
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (value !== last_value) {
last_value = value;
let index = index_of.get(value);
@@ -180,7 +285,7 @@ function write_section(writer: Writer, section: Section) {
const bits = PALETTE_BITS.find((bits) => palette.length <= 1 << bits);
if (bits === undefined) {
writer.u8(DIRECT_BITS);
for (const value of blocks) writer.u32(value);
for (const value of values) writer.u32(value);
return;
}
@@ -188,43 +293,59 @@ function write_section(writer: Writer, section: Section) {
writer.u16(palette.length);
for (const value of palette) writer.u32(value);
const per_byte = 8 / bits;
for (let i = 0; i < SECTION_VOLUME; i += per_byte) {
for (let i = 0; i < values.length; i += per_byte) {
let byte = 0;
for (let j = 0; j < per_byte; j++) byte |= indexes[i + j] << (j * bits);
writer.u8(byte);
}
}
// throws when it isn't what write_column writes. map turns each value read into what the sections hold, and can throw
// for a value that's wrong
export function read_column(reader: Reader, map: (value: number) => number): { sections: Section[]; biomes: string[] } {
const biome_palette: string[] = [];
const biome_count = reader.u16();
if (biome_count === 0) throw new Error("No biomes");
for (let i = 0; i < biome_count; i++) biome_palette.push(reader.string());
const biomes: string[] = new Array(CHUNK_AREA);
for (let column = 0; column < CHUNK_AREA; column++) {
const index = biome_count > 1 ? reader.u8() : 0;
if (index >= biome_count) throw new Error("Bad biome index");
biomes[column] = biome_palette[index];
// throws when it isn't what write_column writes. map turns each block value read into what the sections hold, and can
// throw for a value that's wrong. flat_biomes reads what came before biomes had heights (format 3 saves): after the
// biome palette, a u8 palette index per column (x then z) when there's more than one, and sections of blocks alone
export function read_column(
reader: Reader,
map: (value: number) => number,
flat_biomes = false,
): { sections: Section[]; biomes: ColumnBiomes } {
const palette: string[] = [];
const palette_size = reader.u16();
if (palette_size === 0 || palette_size > MAX_COLUMN_BIOMES) throw new Error("Bad biome palette");
for (let i = 0; i < palette_size; i++) palette.push(reader.string());
const biome = (index: number) => {
if (index >= palette_size) throw new Error("Bad biome index");
return index;
};
let columns: string[] | undefined;
if (flat_biomes) {
columns = Array.from({ length: CHUNK_AREA }, () => palette[palette_size > 1 ? biome(reader.u8()) : 0]);
}
const count = reader.u16();
if (count * SECTION_HEIGHT > HIGHEST_Y - LOWEST_Y) throw new Error(`Too many sections, ${count}`);
const sections: Section[] = [];
for (let i = 0; i < count; i++) sections.push(read_section(reader, map));
return { sections, biomes };
const cells: SectionBiomes[] = [];
for (let i = 0; i < count; i++) {
sections.push(new Section(read_paletted(reader, new Uint32Array(SECTION_VOLUME), map)));
if (!flat_biomes) cells.push(read_paletted(reader, new Uint8Array(SECTION_BIOMES), biome));
}
share_same(cells);
return { sections, biomes: columns ? column_biomes(columns, count) : { palette, sections: cells } };
}
function read_section(reader: Reader, map: (value: number) => number): Section {
// into values, unless they're all one, which is returned instead
function read_paletted<T extends Uint32Array | Uint8Array>(
reader: Reader,
values: T,
map: (value: number) => number,
): number | T {
const bits = reader.u8();
if (bits === 0) return new Section(map(reader.u32()));
const blocks = new Uint32Array(SECTION_VOLUME);
if (bits === 0) return map(reader.u32());
if (bits === DIRECT_BITS) {
for (let i = 0; i < SECTION_VOLUME; i++) blocks[i] = map(reader.u32());
return new Section(blocks);
for (let i = 0; i < values.length; i++) values[i] = map(reader.u32());
return values;
}
if (!PALETTE_BITS.includes(bits)) throw new Error(`Bad bits per block ${bits}`);
if (!PALETTE_BITS.includes(bits)) throw new Error(`Bad bits per value ${bits}`);
const palette: number[] = [];
const size = reader.u16();
@@ -232,15 +353,15 @@ function read_section(reader: Reader, map: (value: number) => number): Section {
for (let i = 0; i < size; i++) palette.push(map(reader.u32()));
const per_byte = 8 / bits;
const mask = (1 << bits) - 1;
for (let i = 0; i < SECTION_VOLUME; i += per_byte) {
for (let i = 0; i < values.length; i += per_byte) {
const byte = reader.u8();
for (let j = 0; j < per_byte; j++) {
const index = (byte >> (j * bits)) & mask;
if (index >= size) throw new Error("Bad palette index");
blocks[i + j] = palette[index];
values[i + j] = palette[index];
}
}
return new Section(blocks);
return values;
}
// per column of a chunk (z * 16 + x), the highest y that isn't air, min_y - 1 for an empty one, then the lowest y with
+10 -4
View File
@@ -125,12 +125,18 @@ export interface BiomeRuleJson {
id: string;
before?: string;
after?: string;
// every condition holds: a range of a climate value from the noise settings, of "surface" (the ground's y), or
// "steep": true or false. no conditions always holds
// every condition holds: a range of a climate value from the noise settings, or of one of RULE_VALUES, or "steep":
// true or false. no conditions always holds
when?: Record<string, RangeJson | boolean>;
biome: string;
}
// what biome rules look at besides a generator's climate, so its climate values can't be named these: the ground's y,
// a biome cell's lowest y and how far that is below the ground (0 at the ground, negative above it)
export const RULE_VALUES = ["surface", "y", "depth"];
// whether a column is steep, see NoiseSettingsJson.steep
export const RULE_NAMES = [...RULE_VALUES, "steep"];
// dimensions: a world to play and the noise settings that generate it, like neoforge's level stems. the world plays the
// one with "default": true, and only one loaded mod can have one
@@ -293,8 +299,8 @@ const noise_settings_schema: z.ZodType<NoiseSettingsJson> = z.object({
caves: z.object({ density, cell_height }),
preliminary_surface: density,
climate: z.record(
z.string("isn't a name a climate value can have: lowercase letters and _, but not surface or steep")
.regex(/^[a-z_]+$/).refine((name) => name !== "surface" && name !== "steep"),
z.string(`isn't a name a climate value can have: lowercase letters and _, but not ${RULE_NAMES.join(", ")}`)
.regex(/^[a-z_]+$/).refine((name) => !RULE_NAMES.includes(name)),
density,
),
steep: z.number().min(0),
+3 -2
View File
@@ -46,7 +46,7 @@ export interface FeatureJson {
type: string;
config?: Record<string, unknown>;
placement?: PlacementJson[];
// only where the column is one of these biomes
// only where the biome at the position is one of these
biomes?: string | string[];
step?: FeatureStep;
}
@@ -233,7 +233,8 @@ export function compile_feature(
for (const position of positions) {
if (
biomes &&
!(inside(chunk, position.x, position.z) && biomes.has(chunk.biome_at(position.x, position.z)))
!(inside(chunk, position.x, position.z) &&
biomes.has(chunk.biome_at(position.x, position.y, position.z)))
) {
continue;
}
+9 -2
View File
@@ -4,7 +4,14 @@
// a generator: noise settings, and the density functions, noises and biome rules it uses. compiled once for each
// seed, see NoiseTerrain. the data comes from mods' worldgen folders, see docs/modding/worldgen/terrain.md
import { EverythingRegistry } from "../everything_registry.ts";
import type { BiomeRuleJson, BiomeSourceJson, DensityFunctionJson, NoiseJson, NoiseSettingsJson } from "./data.ts";
import {
type BiomeRuleJson,
type BiomeSourceJson,
type DensityFunctionJson,
type NoiseJson,
type NoiseSettingsJson,
RULE_NAMES,
} from "./data.ts";
import type { DensitySources } from "./density.ts";
import { NoiseTerrain } from "./terrain.ts";
@@ -75,7 +82,7 @@ function merge_rules(settings: NoiseSettingsJson, sources: BiomeSourceJson[]): B
rules.splice(rule.before ? at : at + 1, 0, rule);
}
}
const names = new Set([...Object.keys(settings.climate), "surface", "steep"]);
const names = new Set([...Object.keys(settings.climate), ...RULE_NAMES]);
const seen = new Set<string>();
for (const rule of rules) {
if (seen.has(rule.id)) throw new Error(`biome source ${base.id}: two rules are called ${rule.id}`);
+17 -5
View File
@@ -7,6 +7,7 @@
// are features, after it
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import type { WorldShape } from "@/common/world_shape.ts";
import { BIOME_CELL_HEIGHT } from "@/common/section.ts";
import { get_biome } from "./biomes.ts";
import type { NoiseTerrain, TerrainColumn } from "./terrain.ts";
import {
@@ -17,8 +18,9 @@ import {
type SurfaceContext,
} from "./surface_rules.ts";
// fills blocks (indexed (y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x) and each column's surface height and biome. block is
// a block's numeric id with its default states
// fills blocks (indexed (y - min_y) * CHUNK_AREA + z * CHUNK_SIZE + x), each column's surface height and each biome
// cell's biome (indexed like blocks, a layer of cells at a time, see column_biomes). block is a block's numeric id with
// its default states
export function generate_noise_chunk(
blocks: Uint32Array,
heights: Int32Array,
@@ -39,6 +41,9 @@ export function generate_noise_chunk(
const cave_levels = height / cave_cell_height + 1;
const x0 = chunk_x * CHUNK_SIZE;
const z0 = chunk_z * CHUNK_SIZE;
const cells = height / BIOME_CELL_HEIGHT;
// the cell a y is in, below the world the lowest
const ground_cell = (y: number) => Math.max(0, Math.floor((y - min_y) / BIOME_CELL_HEIGHT));
// density at the corners of every cell
const corner_columns: TerrainColumn[] = [];
@@ -160,10 +165,17 @@ export function generate_noise_chunk(
const ground = column.height;
const neighbors = [column_at(x - 1, z), column_at(x + 1, z), column_at(x, z - 1), column_at(x, z + 1)];
const steep = neighbors.some((neighbor) => Math.abs(neighbor.height - ground) >= settings.steep);
const biome = terrain.biome(column, surface_y, steep);
heights[z * CHUNK_SIZE + x] = surface_y;
biomes[z * CHUNK_SIZE + x] = biome;
// the biome of each cell, worked out once for the whole column when no rule looks at heights. the ground's
// surface is its own cell's
let biome = "";
for (let cell = 0; cell < cells; cell++) {
const y = min_y + cell * BIOME_CELL_HEIGHT;
if (cell === 0 || terrain.by_height) biome = terrain.biome(column, surface_y, steep, y);
biomes[cell * CHUNK_AREA + z * CHUNK_SIZE + x] = biome;
}
biome = biomes[ground_cell(surface_y) * CHUNK_AREA + z * CHUNK_SIZE + x];
context.x = x0 + x;
context.z = z0 + z;
+41 -20
View File
@@ -1,12 +1,13 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the shape of the world and which biome each column gets, from a generator's data (see generator.ts): its density
// functions compiled for one seed. generate_noise_chunk calls density and cave through here, so engine access mods can
// the shape of the world and which biome each column gets at each height, from a generator's data (see generator.ts):
// its density functions compiled for one seed. generate_noise_chunk calls density and cave through here, so engine access mods can
// hook them
import { type Density, DensityCompiler } from "./density.ts";
import { type DensityJson, type NoiseSettingsJson, range_test, type RangeJson } from "./data.ts";
import type { Generator } from "./generator.ts";
import { BIOME_CELL_HEIGHT } from "@/common/section.ts";
// what the terrain worked out about a column
export interface TerrainColumn {
@@ -20,8 +21,8 @@ export interface TerrainColumn {
interface CompiledRule {
biome: string;
// climate values by their index in the noise settings' climate, the surface's y, steep
holds(climate: number[], surface: number, steep: boolean): boolean;
// climate values by their index in the noise settings' climate, the surface's y, steep, and the biome cell's lowest y
holds(climate: number[], surface: number, steep: boolean, y: number): boolean;
}
export class NoiseTerrain {
@@ -33,6 +34,8 @@ export class NoiseTerrain {
#caves: Density;
#climate: Density[];
#rules: CompiledRule[];
// whether any rule looks at y or depth. when none do, a column's biome is the same all the way up
readonly by_height: boolean;
constructor(seed: string, generator: Generator) {
this.seed = seed;
@@ -51,6 +54,7 @@ export class NoiseTerrain {
const names = Object.keys(this.settings.climate);
this.#climate = names.map((name) => compile(this.settings.climate[name], `climate.${name}`));
this.#rules = generator.rules.map((rule) => compile_rule(rule.biome, rule.when ?? {}, names));
this.by_height = generator.rules.some((rule) => "y" in (rule.when ?? {}) || "depth" in (rule.when ?? {}));
}
// with_climate works the climate out too, which is cheap right after the height since they share their inputs
@@ -74,26 +78,37 @@ export class NoiseTerrain {
return this.#caves(x, y, z);
}
// the first of the biome source's rules that holds for the column, with its ground at surface_y
biome(column: TerrainColumn, surface_y: number, steep: boolean): string {
const climate = column.climate ?? this.climate(column.x, column.z);
// the first of the biome source's rules that holds for the biome cell from y up, in a column with its ground at
// surface_y. the column's climate is worked out once, and kept on it
biome(column: TerrainColumn, surface_y: number, steep: boolean, y: number): string {
const climate = column.climate ??= this.climate(column.x, column.z);
for (const rule of this.#rules) {
if (rule.holds(climate, surface_y, steep)) return rule.biome;
if (rule.holds(climate, surface_y, steep, y)) return rule.biome;
}
throw new Error(`no rule of biome source ${this.settings.biome_source} holds at ${column.x}, ${column.z}`);
throw new Error(
`no rule of biome source ${this.settings.biome_source} holds at ${column.x}, ${y}, ${column.z}`,
);
}
// a column's biome without generating its chunk, from its height before 3d noise, so it can be a little off near
// the highest y in a column where it's this biome, the ground's or a biome cell's lowest one below it (cells start
// at min_y), without generating its chunk. that's from its height before 3d noise, so it can be a little off near
// coasts and cliffs. for searching far away, like /locatebiome
estimate_biome(x: number, z: number): { biome: string; y: number } {
const column = this.column(x, z);
const y = Math.round(column.height);
const flat = this.biome(column, y, false);
locate_biome(biome: string, x: number, z: number, min_y: number): number | undefined {
const column = this.column(x, z, true);
const ground = Math.round(column.height);
let steep = false;
// most columns are the same either way, the neighbors are only worth sampling when they aren't
if (flat === this.biome(column, y, true)) return { biome: flat, y };
const neighbors = [[x - 1, z], [x + 1, z], [x, z - 1], [x, z + 1]].map(([nx, nz]) => this.column(nx, nz));
const steep = neighbors.some((neighbor) => Math.abs(neighbor.height - column.height) >= this.settings.steep);
return { biome: steep ? this.biome(column, y, true) : flat, y };
if (this.biome(column, ground, false, ground) !== this.biome(column, ground, true, ground)) {
const neighbors = [[x - 1, z], [x + 1, z], [x, z - 1], [x, z + 1]].map(([nx, nz]) => this.column(nx, nz));
steep = neighbors.some((neighbor) => Math.abs(neighbor.height - column.height) >= this.settings.steep);
}
if (this.biome(column, ground, steep, ground) === biome) return ground;
if (!this.by_height) return undefined;
const cell = min_y + Math.floor((ground - min_y) / BIOME_CELL_HEIGHT) * BIOME_CELL_HEIGHT;
for (let y = cell - BIOME_CELL_HEIGHT; y >= min_y; y -= BIOME_CELL_HEIGHT) {
if (this.biome(column, ground, steep, y) === biome) return y;
}
return undefined;
}
}
@@ -105,6 +120,12 @@ function compile_rule(biome: string, when: Record<string, RangeJson | boolean>,
} else if (name === "surface") {
const test = range_test(condition as RangeJson);
tests.push((_climate, surface) => test(surface));
} else if (name === "y") {
const test = range_test(condition as RangeJson);
tests.push((_climate, _surface, _steep, y) => test(y));
} else if (name === "depth") {
const test = range_test(condition as RangeJson);
tests.push((_climate, surface, _steep, y) => test(surface - y));
} else {
const index = names.indexOf(name);
const test = range_test(condition as RangeJson);
@@ -113,9 +134,9 @@ function compile_rule(biome: string, when: Record<string, RangeJson | boolean>,
}
return {
biome,
holds(climate, surface_y, steep) {
holds(climate, surface_y, steep, y) {
for (let i = 0; i < tests.length; i++) {
if (!tests[i](climate, surface_y, steep)) return false;
if (!tests[i](climate, surface_y, steep, y)) return false;
}
return true;
},
+1 -1
View File
@@ -202,7 +202,7 @@ ctx.player.is_swimming(); // see ../entities/players.md#swimming
ctx.player.biome; // and ctx.player.season, see ../worldgen/biomes.md#seasons
ctx.world.get_block(x, y, z); // a block id, what this client sees
ctx.world.get_client_data<number>(x, y, z, "speed"); // see ../blocks/tiledata.md#client-data, a copy
ctx.world.biome_at(x, z); // and ctx.world.season_at(x, z), undefined where nothing's loaded
ctx.world.biome_at(x, y, z); // and ctx.world.season_at(x, y, z), undefined where nothing's loaded
ctx.world.time; // see Time
ctx.world.min_y; // and ctx.world.max_y, see ../worldgen/terrain.md#height
ctx.items.ids(); // every item, in load order
+25 -15
View File
@@ -4,8 +4,14 @@ A biome says what the ground looks like where it's picked: the blocks on top, th
tinted, which trees grow, and whether it has a season of its own. Biomes are data, one file each in a mod's
`worldgen/biomes/` folder. The base game's are in `mods/bworld/worldgen/biomes/`.
Which biome a column gets is up to the generator's biome rules, from the column's climate and height. A mod's biome
generates where a rule it adds puts it, see [Adding Biomes](terrain.md#adding-biomes).
Which biome a place gets is up to the generator's biome rules, from the column's climate, the ground's height and how
far under it the place is. A mod's biome generates where a rule it adds puts it, see
[Adding Biomes](terrain.md#adding-biomes).
Biomes are one per block across and one every 4 blocks up, a cell from `y` to `y + 3` where `y` is a multiple of 4 above
the world's bottom. The base game's are the same all the way up a column, and a mod can add biomes under the ground, see
[Underground Biomes](terrain.md#underground-biomes). The ground's surface blocks are always its own cell's biome's, and
so is the filler under them.
## A Biome
@@ -62,14 +68,14 @@ Above the snow line, around y 176, the top block is snow whatever the biome says
## Biome Ids
Biome ids are what features' `biome_at` gives and what spawns list. The base game has `bworld:deep_ocean`,
Biome ids are what `biome_at` gives and what spawns list. The base game has `bworld:deep_ocean`,
`bworld:deep_frozen_ocean`, `bworld:deep_lukewarm_ocean`, `bworld:ocean`, `bworld:frozen_ocean`, `bworld:warm_ocean`,
`bworld:river`, `bworld:frozen_river`, `bworld:beach`, `bworld:snowy_beach`, `bworld:stony_shore`, `bworld:plains`,
`bworld:meadow`, `bworld:forest`, `bworld:dark_forest`, `bworld:swamp`, `bworld:taiga`, `bworld:snowy_plains`,
`bworld:snowy_taiga`, `bworld:savanna`, `bworld:jungle`, `bworld:desert`, `bworld:snowy_slopes`, `bworld:stony_peaks`,
`bworld:jagged_peaks` and `bworld:frozen_peaks`.
`/locatebiome <id>` finds the nearest one.
`/locatebiome <id>` finds the nearest one, and how high it is: the ground's y, or under it for a biome under the ground.
## Biome Tags
@@ -83,7 +89,9 @@ Biomes have [tags](../resources/tags.md) too, in `tags/biomes/`. Every base game
| `#bworld:is_forest` | `forest`, `dark_forest`, `savanna`, `plains`, `snowy_plains`, `taiga`, `snowy_taiga`, `jungle`, `swamp`, `desert` |
A mod's biome joins one by adding itself to the tag's file, like `tags/biomes/bworld/is_forest.json`, and a script
checks a biome with `ctx.tags.has("biomes", "bworld:is_forest", ctx.world.biome_at(x, z))`.
checks a biome with `ctx.tags.has("biomes", "bworld:is_forest", ctx.world.biome_at(x, y, z))`.
Biomes under the ground go in the common tags NeoForge mods check, `#c:is_underground`, and `#c:is_cave` for caves.
## Seasons
@@ -94,17 +102,19 @@ summer in `desert`.
Scripts read the season where something is:
| Where | Biome | Season |
| ------------------------------------------------ | -------------------------- | --------------------------- |
| a block in a server component, like `on_tick` | `block.biome` | `block.season` |
| an entity from `ctx.world.spawn_entity` | `entity.biome` | `entity.season` |
| a player, on the server | `player.biome` | `player.season` |
| any column, in server, shared and client scripts | `ctx.world.biome_at(x, z)` | `ctx.world.season_at(x, z)` |
| the player on this client | `ctx.player.biome` | `ctx.player.season` |
| Where | Biome | Season |
| ----------------------------------------------- | ----------------------------- | ------------------------------ |
| a block in a server component, like `on_tick` | `block.biome` | `block.season` |
| an entity from `ctx.world.spawn_entity` | `entity.biome` | `entity.season` |
| a player, on the server | `player.biome` | `player.season` |
| any block, in server, shared and client scripts | `ctx.world.biome_at(x, y, z)` | `ctx.world.season_at(x, y, z)` |
| the player on this client | `ctx.player.biome` | `ctx.player.season` |
| a feature's chunk, see [Features](index.md) | `chunk.biome_at(x, y, z)` | |
Entities and players go by the column their feet are in. On the server a column always has a biome: in a chunk that
isn't loaded it's what generation makes there, which takes a while the first time. In shared rules and client scripts
it's what that client has loaded, and `undefined` where it has nothing.
`biome_at` is NeoForge's `level.getBiome(pos)`. Entities and players go by the block their feet are in, like
`level.getBiome(entity.blockPosition())`. Above and below the world it's the biome at its top or bottom. On the server
every block has a biome: in a chunk that isn't loaded it's what generation makes there, which takes a while the first
time. In shared rules and client scripts it's what that client has loaded, and `undefined` where it has nothing.
```ts
ctx.components.register_block("my_mod:crop", {
+4 -2
View File
@@ -90,7 +90,8 @@ export function setup(gen: WorldgenContext) {
}
```
`step` and `biomes` are optional. With `biomes`, the feature only runs in chunks that have one of them.
`step` and `biomes` are optional. With `biomes`, the feature only runs in chunks that have one of them somewhere, at any
height, the way a NeoForge biome modifier adds a feature to the biomes it lists.
Feature ids are in the mod's namespace. Each feature's `rng` is seeded with the world's seed, the chunk and the
feature's id, so adding another mod's feature doesn't change what this one generates.
@@ -107,7 +108,8 @@ interface FeatureChunk {
noise_2d(name: string): (x: number, z: number) => number;
noise_3d(name: string): (x: number, y: number, z: number) => number;
height_at(x: number, z: number): number; // surface height, inside this chunk only
biome_at(x: number, z: number): string; // like "bworld:plains", inside this chunk only
biome_at(x: number, y: number, z: number): string; // like "bworld:plains", inside this chunk only
set_biome(x: number, y: number, z: number, biome: string): void; // the 4 blocks tall cell y is in, see biomes.md
get_block(x: number, y: number, z: number): string | undefined; // inside this chunk only
set_block(x: number, y: number, z: number, id: string): void; // up to one chunk away
place_feature(id: string, x: number, y: number, z: number): boolean; // a data feature, see below
+41 -3
View File
@@ -151,7 +151,7 @@ A generator. The base game's is `worldgen/noise_settings/overworld.json`:
| `cell_width` | How far apart across `terrain` and `caves` are sampled, 1 to 16. |
| `terrain`, `caves` | Their density function, and how far apart up they're sampled. Solid where both are above 0. |
| `preliminary_surface` | The ground's height before 3D noise. Surface rules, `steep` and `/locatebiome` use it. |
| `climate` | Named values biome rules look at. Any names, except `surface` and `steep`. |
| `climate` | Named values biome rules look at. Any names, except `surface`, `y`, `depth` and `steep`. |
| `steep` | A column is steep when its preliminary surface is this much higher or lower than a neighbor's. |
| `biome_source` | The biome source that picks its biomes. |
| `fluids` | What empty space becomes, the first that applies: below `below`, where there's `open_sky` (nothing but air above) or where a density function is in a range. |
@@ -187,8 +187,18 @@ with `bworld:dark_forest`, which holds everywhere:
}
```
`when` holds when all its conditions do: a range of one of the generator's `climate` values, a range of `surface` (the y
of the column's top solid block), or `"steep": true` or `false`. Rules without `when` always hold.
Rules pick a biome for each 4 blocks tall cell of a column, see [Biomes](biomes.md). `when` holds when all its
conditions do, each a range of one of these, or `"steep": true` or `false`. Rules without `when` always hold.
| Name | Meaning |
| ----------------- | ---------------------------------------------------------------------------------------- |
| a `climate` value | One of the generator's, the same all the way up a column. |
| `surface` | The y of the column's top solid block. |
| `y` | The cell's lowest y. |
| `depth` | How far the cell is below the ground, `surface - y`: 0 at the ground, negative above it. |
A rule that looks at neither `y` nor `depth` holds all the way up a column, so the base game's rules give a column one
biome. When no rule looks at them, a column's biome is worked out once.
This is bworld's own, not Minecraft's multi-noise biome source: a rule can look at how high the ground really is and
whether it's a cliff, which is how beaches, peaks and stony shores are placed.
@@ -217,6 +227,34 @@ plains:
Rules from several mods go in in load order. The biome itself is a [biome file](biomes.md) as usual.
### Underground Biomes
A rule with `depth` or `y` puts a biome under the ground. It has to come before the rules it takes the place of, and the
base game's all hold all the way down, so it goes before the first one. Mossy caves more than 16 blocks down, where it's
humid:
```json
{
"format_version": 1,
"biome_source": {
"id": "my_mod:mossy_caves",
"extends": "bworld:overworld",
"rules": [{
"id": "my_mod:mossy_caves",
"before": "bworld:river_bed_frozen",
"when": {
"depth": { "min_exclusive": 16 },
"humidity": { "min_exclusive": 0.4 }
},
"biome": "my_mod:mossy_caves"
}]
}
}
```
The ground keeps the biome of its own cell, surface blocks and all. Spawns, `entity.biome`, seasons and grass, leaf and
water colors follow the biome where they are, so an underground biome's spawn list and colors work under the ground.
## Surface Rules
What a solid block becomes, like Minecraft's surface rules: a rule gives a block or nothing, and the first one in a
+4 -2
View File
@@ -145,14 +145,16 @@ export function register_fishing(ctx: ServerContext) {
ctx.loot.register_condition("bworld:season", (params, context) => {
const seasons = params.seasons as string[];
if (!context.position) return true;
return seasons.includes(ctx.world.season_at(context.position.x, context.position.z));
const { x, y, z } = context.position;
return seasons.includes(ctx.world.season_at(x, y, z));
});
// "biomes": ["bworld:swamp", "#bworld:is_ocean"], holds in any of the biomes or biome tags at the loot's
// position. without a position it holds, like bworld:season
ctx.loot.register_condition("bworld:biome", (params, context) => {
if (!context.position) return true;
const biome = ctx.world.biome_at(context.position.x, context.position.z);
const { x, y, z } = context.position;
const biome = ctx.world.biome_at(x, y, z);
return (params.biomes as string[]).some((entry) =>
entry.startsWith("#") ? ctx.tags.has("biomes", entry, biome) : entry === biome
);
+3 -2
View File
@@ -235,11 +235,12 @@ export function register_trees(gen: WorldgenContext) {
};
for (const site of tree_sites(chunk)) {
const here = trees.get(chunk.biome_at(site.x, site.z));
// the biome of the ground it grows from
const ground_y = chunk.height_at(site.x, site.z);
const here = trees.get(chunk.biome_at(site.x, ground_y, site.z));
if (!here || site.rng.next() >= here.chance) continue;
// on soil with air above it, so never under water or on bare rock
const ground_y = chunk.height_at(site.x, site.z);
const ground = chunk.get_block(site.x, ground_y, site.z);
const above = chunk.get_block(site.x, ground_y + 1, site.z);
if (!SOIL.has(ground!) || above !== "cubi:air") continue;
+2 -2
View File
@@ -27,10 +27,10 @@ function cactus(chunk: FeatureChunk) {
const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16);
const z = chunk.z * 16 + Math.floor(chunk.rng.next() * 16);
const height = pick_height(chunk.rng.next());
if (chunk.biome_at(x, z) !== "bworld:desert") {
const ground = chunk.height_at(x, z);
if (chunk.biome_at(x, ground, z) !== "bworld:desert") {
continue;
}
const ground = chunk.height_at(x, z);
if (chunk.get_block(x, ground, z) !== "bworld:sand") {
continue;
}
+3 -3
View File
@@ -79,10 +79,10 @@ export interface EntityLevel {
// the fluid there and how high it is, for fluids pushing things along
fluid_at(x: number, y: number, z: number): FluidInCell | undefined;
get_block_info(x: number, y: number, z: number): BlockRegistry | undefined;
// the column's biome, like "bworld:plains"
biome_at(x: number, z: number): string;
// the biome at a block, like "bworld:plains"
biome_at(x: number, y: number, z: number): string;
// that biome's season now, see biome_season in common/worldgen/biomes.ts
season_at(x: number, z: number): Season;
season_at(x: number, y: number, z: number): Season;
add_entity(entity: Entity): void;
get_entity(id: string): Entity | undefined;
// entities whose feet are within the box around x, y, z
+4 -4
View File
@@ -116,12 +116,12 @@ export class EntityManager implements EntityLevel {
return this.#host.world.get_block_info(x, y, z);
}
biome_at(x: number, z: number) {
return this.#host.world.biome_at(x, z);
biome_at(x: number, y: number, z: number) {
return this.#host.world.biome_at(x, y, z);
}
season_at(x: number, z: number) {
return biome_season(this.biome_at(x, z), this.#host.world.time);
season_at(x: number, y: number, z: number) {
return biome_season(this.biome_at(x, y, z), this.#host.world.time);
}
fluid_at(x: number, y: number, z: number) {
+5 -6
View File
@@ -1607,8 +1607,8 @@ export class GameServer {
});
}
// like minecraft's /locate biome: columns LOCATE_STEP apart, in square rings out from x, z. the closest in the
// first ring that has one
// like minecraft's /locate biome: columns LOCATE_STEP apart, in square rings out from x, z, each from its ground
// down. the closest in the first ring that has one
#locate_biome(biome: string, x: number, z: number) {
for (let ring = 0; ring * LOCATE_STEP <= LOCATE_RADIUS; ring++) {
let best: { x: number; y: number; z: number; distance: number } | undefined;
@@ -1616,11 +1616,10 @@ export class GameServer {
for (let dz = -ring; dz <= ring; dz++) {
if (Math.max(Math.abs(dx), Math.abs(dz)) !== ring) continue;
const [cx, cz] = [x + dx * LOCATE_STEP, z + dz * LOCATE_STEP];
const found = this.world.estimate_biome(cx, cz);
const distance = Math.hypot(dx, dz);
if (found.biome === biome && (!best || distance < best.distance)) {
best = { x: cx, y: found.y, z: cz, distance };
}
if (best && distance >= best.distance) continue;
const y = this.world.locate_biome(biome, cx, cz);
if (y !== undefined) best = { x: cx, y, z: cz, distance };
}
}
if (best) return best;
+11 -8
View File
@@ -663,10 +663,10 @@ export class ModRuntime {
y,
z,
get biome() {
return game.world.biome_at(x, z);
return game.world.biome_at(x, y, z);
},
get season() {
return biome_season(game.world.biome_at(x, z), game.world.time);
return biome_season(game.world.biome_at(x, y, z), game.world.time);
},
get data() {
return game.world.get_tile(x, y, z)?.mod_data;
@@ -942,9 +942,12 @@ export class ModRuntime {
return { x: fx + 0, y: fy + 0, z: fz + 0 };
},
is_loaded: (x, z) => game().world.is_generated(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)),
biome_at: (x, z) => game().world.biome_at(Math.floor(x), Math.floor(z)),
season_at: (x, z) =>
biome_season(game().world.biome_at(Math.floor(x), Math.floor(z)), game().world.time),
biome_at: (x, y, z) => game().world.biome_at(Math.floor(x), Math.floor(y), Math.floor(z)),
season_at: (x, y, z) =>
biome_season(
game().world.biome_at(Math.floor(x), Math.floor(y), Math.floor(z)),
game().world.time,
),
get min_y() {
return game().world.shape.min_y;
},
@@ -1507,7 +1510,7 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
};
},
get biome() {
return game.world.biome_at(Math.floor(player.x), Math.floor(player.z));
return game.world.biome_at(Math.floor(player.x), Math.floor(player.y), Math.floor(player.z));
},
get season() {
return biome_season(this.biome, game.world.time);
@@ -1676,10 +1679,10 @@ export function entity_ref(entity: Entity): EntityRef {
return { x: entity.x, y: entity.y, z: entity.z };
},
get biome() {
return entity.level.biome_at(Math.floor(entity.x), Math.floor(entity.z));
return entity.level.biome_at(Math.floor(entity.x), Math.floor(entity.y), Math.floor(entity.z));
},
get season() {
return entity.level.season_at(Math.floor(entity.x), Math.floor(entity.z));
return entity.level.season_at(Math.floor(entity.x), Math.floor(entity.y), Math.floor(entity.z));
},
get removed() {
return entity.removed;
+2 -2
View File
@@ -125,11 +125,11 @@ export class NaturalSpawner {
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));
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, z))) continue;
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;
+25 -14
View File
@@ -7,23 +7,31 @@
// u8 format, CHUNK_FORMAT
// i16 the bottom of the lowest section, the dimension's min_y when it was saved
// u32 palette size, then each entry: u8 id length, the id as utf-8, u16 state bits
// the biomes and the sections, bottom first, each block the index of its entry in the palette. see write_column in
// common/section.ts, which level_chunk uses too
// the sections' blocks and biomes, bottom first, each block the index of its entry in the palette. see
// write_column in common/section.ts, which level_chunk uses too
//
// blocks are saved by their string ids, so mods can come and go without a save's numbers meaning other blocks. every
// chunk the game generates is saved whole, like minecraft's, so a change to world generation only shows in chunks never
// generated before. a chunk loaded into a dimension with another height keeps the sections both have (see
// ServerWorld's #from_saved).
// formats 1 and 2 are still read. they're big-endian and from when the world was 0 to 256 high: after the palette, the
// formats 1, 2 and 3 are still read, with each column's biome all the way up. format 3 is this one from before biomes
// had heights, see read_column's flat_biomes. they're big-endian and from when the world was 0 to 256 high: after the palette, the
// index of every block from y 0 up, then z, then x, u8 each or u16 for more than 256 entries. format 2 then has a u8
// biome palette size, each biome as u8 length and utf-8, and a u8 biome index a column. format 1 has no biomes, but a
// bit per block for whether world generation made it, from when only chunks players changed were saved
import { CHUNK_AREA } from "@/common/constants.ts";
import { Reader, Writer } from "@/common/bytes.ts";
import { read_column, Section, SECTION_VOLUME, write_column } from "@/common/section.ts";
import {
column_biomes,
type ColumnBiomes,
read_column,
Section,
SECTION_VOLUME,
write_column,
} from "@/common/section.ts";
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
export const CHUNK_FORMAT = 3;
export const CHUNK_FORMAT = 4;
// how many blocks a chunk of formats 1 and 2 has
const FLAT_VOLUME = CHUNK_AREA * 256;
@@ -60,8 +68,8 @@ export interface ChunkBlocks {
min_y: number;
// the palette index of each block, a section at a time from min_y up
sections: Section[];
// each column's, see ServerWorld.biome_at. format 1 chunks don't have them
biomes?: string[];
// see ServerWorld.biome_at. format 1 chunks don't have them
biomes?: ColumnBiomes;
}
export function encode_chunk(chunk: Required<ChunkBlocks>): Uint8Array<ArrayBuffer> {
@@ -80,9 +88,11 @@ export function encode_chunk(chunk: Required<ChunkBlocks>): Uint8Array<ArrayBuff
// throws when the bytes aren't a chunk this can read
export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
const format = bytes[0];
if (format !== CHUNK_FORMAT && format !== 2 && format !== 1) throw new Error(`Unknown chunk format ${format}`);
const reader = new Reader(bytes.subarray(1), format === CHUNK_FORMAT);
const min_y = format === CHUNK_FORMAT ? reader.i16() : 0;
if (format < 1 || format > CHUNK_FORMAT) throw new Error(`Unknown chunk format ${format}`);
// formats 1 and 2 are big-endian, and flat
const flat = format <= 2;
const reader = new Reader(bytes.subarray(1), !flat);
const min_y = flat ? 0 : reader.i16();
if (min_y % SECTION_HEIGHT !== 0) throw new Error(`Bad min_y ${min_y}`);
const palette: [string, number][] = [];
const palette_size = reader.u32();
@@ -92,8 +102,8 @@ export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
return value;
};
if (format === CHUNK_FORMAT) {
const { sections, biomes } = read_column(reader, index);
if (!flat) {
const { sections, biomes } = read_column(reader, index, format === 3);
if (!reader.done) throw new Error("Wrong size");
return { palette, min_y, sections, biomes };
}
@@ -105,17 +115,18 @@ export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
{ length: FLAT_VOLUME / SECTION_VOLUME },
(_, i) => Section.of(blocks.subarray(i * SECTION_VOLUME, (i + 1) * SECTION_VOLUME)),
);
let biomes: string[] | undefined;
let biomes: ColumnBiomes | undefined;
if (format === 1) {
reader.take(FLAT_VOLUME / 8);
} else {
const biome_palette: string[] = [];
const biome_palette_size = reader.u8();
for (let i = 0; i < biome_palette_size; i++) biome_palette.push(reader.string());
biomes = [...reader.take(CHUNK_AREA)].map((i) => {
const columns = [...reader.take(CHUNK_AREA)].map((i) => {
if (i >= biome_palette_size) throw new Error("Bad biome palette index");
return biome_palette[i];
});
biomes = column_biomes(columns, sections.length);
}
if (!reader.done) throw new Error("Wrong size");
return { palette, min_y, sections, biomes };
+18 -11
View File
@@ -3,7 +3,7 @@
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, column_heights, Section, SECTION_VOLUME } from "@/common/section.ts";
import { biome_in, ChunkColumn, column_heights, type ColumnBiomes, Section, SECTION_VOLUME } from "@/common/section.ts";
import { BlockRegistry, EverythingRegistry, light_tables } from "@/common/everything_registry.ts";
import { generate_raw_chunk, RawChunk, WorldgenSetup } from "@/common/generation.ts";
import { AIR_ID } from "@/common/protocol.ts";
@@ -114,7 +114,7 @@ export class ServerWorld {
#raw = new LruMap<number, RawChunk>(RAW_CACHE_SIZE);
#chunks = new LruMap<number, LoadedChunk>(CHUNK_CACHE_SIZE, (key, chunk) => this.#evict(key, chunk));
// what generation decided each column's biome is, and what it put in neighbors, kept for longer than the rest
#biomes = new LruMap<number, string[]>(SPILL_CACHE_SIZE);
#biomes = new LruMap<number, ColumnBiomes>(SPILL_CACHE_SIZE);
#spills = new LruMap<number, Int32Array>(SPILL_CACHE_SIZE);
// raw chunks generated on this thread because nothing had made them yet: with a worldgen pool, what still waits
// on generation. see GameServer's /tps
@@ -238,16 +238,17 @@ export class ServerWorld {
return nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
}
// like "bworld:plains", what generation decided
// a column's biome without generating its chunk, a little off near coasts and cliffs, see NoiseTerrain
estimate_biome(x: number, z: number): { biome: string; y: number } {
return this.worldgen.generator.for_seed(this.seed).estimate_biome(x, z);
// the highest y in a column where it's this biome without generating its chunk, a little off near coasts and
// cliffs, see NoiseTerrain.locate_biome
locate_biome(biome: string, x: number, z: number): number | undefined {
return this.worldgen.generator.for_seed(this.seed).locate_biome(biome, x, z, this.shape.min_y);
}
biome_at(x: number, z: number): string {
// like "bworld:plains", what generation decided. one per block across and every 4 blocks up, see ChunkColumn
biome_at(x: number, y: number, z: number): string {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
return this.#chunk_biomes(chunk_x, chunk_z)[column_index(x, z)];
return biome_in(this.#chunk_biomes(chunk_x, chunk_z), this.shape, x, y, z);
}
// a saved chunk's are the ones saved with it, which loads it. other chunks' come from generation without building
@@ -704,13 +705,19 @@ export class ServerWorld {
}
return section;
});
let biomes = saved.biomes;
if (!biomes) {
let saved_biomes = saved.biomes;
if (!saved_biomes) {
// saved before chunks had them. saved again with them
const key = chunk_key(chunk_x, chunk_z);
biomes = [...this.#biomes.get(key) ?? this.#get_raw(chunk_x, chunk_z).column.biomes];
saved_biomes = this.#biomes.get(key) ?? this.#get_raw(chunk_x, chunk_z).column.biomes;
this.#mark_unsaved(chunk_x, chunk_z);
}
// past what the save has, its top or bottom section's go on
const last = saved_biomes.sections.length - 1;
const biomes = {
palette: [...saved_biomes.palette],
sections: sections.map((_, s) => saved_biomes.sections[Math.min(Math.max(offset + s, 0), last)]),
};
return { column: new ChunkColumn(chunk_x, chunk_z, this.shape, sections, biomes), unknown };
}
+2 -2
View File
@@ -6,7 +6,7 @@
// server/worldgen_workers.ts). requests go nearest first, a worker has a couple at a time so priorities stay fresh, and what the
// game stops wanting is dropped before it starts
import type { RawChunk } from "@/common/generation.ts";
import { ChunkColumn, Section, type SectionData } from "@/common/section.ts";
import { ChunkColumn, type ColumnBiomes, Section, type SectionData } from "@/common/section.ts";
import { WorldShape } from "@/common/world_shape.ts";
import type { WorldgenBundle } from "@/common/worldgen_bundle.ts";
import { chunk_key } from "@/common/utils.ts";
@@ -19,7 +19,7 @@ export type WorkerToPool =
| { type: "ready" }
| { type: "failed"; error: string }
// a raw chunk's sections as their data, since what's sent between workers loses its class
| { type: "chunk"; x: number; z: number; sections: SectionData[]; spills: Int32Array; biomes: string[] }
| { type: "chunk"; x: number; z: number; sections: SectionData[]; spills: Int32Array; biomes: ColumnBiomes }
| { type: "error"; x: number; z: number; error: string };
// the game's end of a channel to a worker
+6 -1
View File
@@ -34,7 +34,12 @@ self.onmessage = (event: MessageEvent<{ port: MessagePort }>) => {
try {
const raw = (await loaded!).generate(x, z);
const sections = raw.column.sections.map((section) => section.data);
const buffers = sections.flatMap((data) => typeof data === "number" ? [] : [data.buffer]);
// sections can share their biomes' array
const buffers = new Set(
[...sections, ...raw.column.biomes.sections].flatMap((data) =>
typeof data === "number" ? [] : [data.buffer]
),
);
send({ type: "chunk", x, z, sections, spills: raw.spills, biomes: raw.column.biomes }, [
...buffers,
raw.spills.buffer,
+15 -6
View File
@@ -7,7 +7,7 @@ import { assert, assertEquals } from "@std/assert";
import { CHUNK_AREA } from "@/common/constants.ts";
import { decode_level_chunk, encode_level_chunk, is_within_view } from "@/common/chunk_streaming.ts";
import { PROTOCOL_VERSION } from "@/common/protocol.ts";
import { ChunkColumn, section_index, to_flat } from "@/common/section.ts";
import { BIOME_CELL_HEIGHT, ChunkColumn, section_index, to_flat } from "@/common/section.ts";
import { WorldShape } from "@/common/world_shape.ts";
import { sent_block, test_game } from "./helpers.ts";
@@ -22,22 +22,31 @@ Deno.test("a chunk comes back as it was encoded, whatever its sections hold", ()
blocks[2 * section + i] = i % 16;
blocks[3 * section + i] = (i % 300) | ((i % 7) << 16);
}
const biomes = Array.from({ length: CHUNK_AREA }, (_, i) => i < 100 ? "bworld:plains" : "bworld:desert");
const shape = new WorldShape({ min_y: -64, max_y: 320, sky_light: true });
// two biomes across, and a third in the cells from the 40th up
const biomes = Array.from(
{ length: shape.volume / BIOME_CELL_HEIGHT },
(_, i) => i >= 40 * CHUNK_AREA ? "test:caves" : i % CHUNK_AREA < 100 ? "bworld:plains" : "bworld:desert",
);
const decoded = decode_level_chunk(encode_level_chunk(ChunkColumn.from_flat(-3, 70000, shape, blocks, biomes)));
const column = ChunkColumn.from_flat(-3, 70000, shape, blocks, biomes);
const decoded = decode_level_chunk(encode_level_chunk(column));
assertEquals(decoded.x, -3);
assertEquals(decoded.z, 70000);
assertEquals(to_flat(decoded.sections), blocks);
assertEquals(decoded.sections.map((section) => section.blocks === null).indexOf(false), 1, "uniform ones stay so");
assertEquals(decoded.biomes, biomes);
assertEquals(decoded.biomes, column.biomes);
const back = new ChunkColumn(-3, 70000, shape, decoded.sections, decoded.biomes);
assertEquals(back.biome_at(-48 + 3, 95, 70000 * 16 + 2), "bworld:plains");
assertEquals(back.biome_at(-48 + 3, 96, 70000 * 16 + 2), "test:caves");
// one biome, and the receiver's numbering
const one = decode_level_chunk(
encode_level_chunk(ChunkColumn.from_flat(0, 0, shape, blocks, biomes.map(() => "bworld:plains"))),
encode_level_chunk(ChunkColumn.from_flat(0, 0, shape, blocks, new Array(CHUNK_AREA).fill("bworld:plains"))),
(value) => value === 7 ? 70 : value,
);
assertEquals(one.biomes, biomes.map(() => "bworld:plains"));
assertEquals(one.biomes.palette, ["bworld:plains"]);
assertEquals(one.biomes.sections, new Array(24).fill(0));
assertEquals(one.sections[0].value, 70);
assertEquals(one.sections[1].get(0), 1);
});
+31
View File
@@ -0,0 +1,31 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the client's level in tests, apart from tests/helpers.ts so tests that don't use it don't load the renderer
import { ClientLevel } from "@/client/level/client_level.ts";
import { AssetManager } from "@/client/assets.ts";
import type { ToChunkWorker } from "@/client/workers/chunk_messages.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import type { WorldShape } from "@/common/world_shape.ts";
// a client's level for the loaded mods' blocks, numbered the same as the server's, without a gpu or chunk workers: what
// it asks its workers to mesh is kept in requests instead of being sent
export function client_level(shape: WorldShape) {
AssetManager.instance.assets["cubi:textures"] = { width: 16, height: 16 };
AssetManager.instance.assets["cubi:textures_info"] = {};
const requests: Extract<ToChunkWorker, { type: "mesh" }>[] = [];
const real = globalThis.Worker;
globalThis.Worker = class {
postMessage(message: ToChunkWorker) {
if (message.type === "mesh") requests.push(message);
}
terminate() {}
} as unknown as typeof Worker;
try {
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const level = new ClientLevel(Array.from(blocks, (block) => block?.id), shape, 2);
return { level, requests };
} finally {
globalThis.Worker = real;
}
}
+3 -21
View File
@@ -4,15 +4,13 @@
// the client meshes a section at a time, and a block changing only meshes again the sections it can change the look
// or the light of, see ClientLevel's #block_changed
import { assertEquals } from "@std/assert";
import { ClientLevel } from "@/client/level/client_level.ts";
import { AssetManager } from "@/client/assets.ts";
import { Camera } from "@/client/camera.ts";
import type { ToChunkWorker } from "@/client/workers/chunk_messages.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import { CHUNK_AREA } from "@/common/constants.ts";
import { ChunkColumn } from "@/common/section.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { test_game } from "./helpers.ts";
import { client_level } from "./client_level.ts";
const GROUND_TOP = 63;
const ROOF = 200;
@@ -21,23 +19,7 @@ const ROOF = 200;
// its chunk workers is kept in requests instead of being sent
async function meshed_level() {
await test_game("mods");
AssetManager.instance.assets["cubi:textures"] = { width: 16, height: 16 };
AssetManager.instance.assets["cubi:textures_info"] = {};
const requests: Extract<ToChunkWorker, { type: "mesh" }>[] = [];
const real = globalThis.Worker;
globalThis.Worker = class {
postMessage(message: ToChunkWorker) {
if (message.type === "mesh") requests.push(message);
}
terminate() {}
} as unknown as typeof Worker;
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
let level: ClientLevel;
try {
level = new ClientLevel(Array.from(blocks, (block) => block?.id), DEFAULT_SHAPE, 2);
} finally {
globalThis.Worker = real;
}
const { level, requests } = client_level(DEFAULT_SHAPE);
const stone = EverythingRegistry.get_id("blocks", "bworld:stone")!;
for (let x = -2; x <= 2; x++) {
+2 -2
View File
@@ -205,7 +205,7 @@ Deno.test("/locatebiome says where the nearest biome of a kind is", async () =>
};
const answer = say("/locatebiome bworld:plains");
const [x, , z] = answer.match(/at (-?\d+) (-?\d+) (-?\d+)/)!.slice(1).map(Number);
assertEquals(game.world.estimate_biome(x, z).biome, "bworld:plains");
const [x, y, z] = answer.match(/at (-?\d+) (-?\d+) (-?\d+)/)!.slice(1).map(Number);
assertEquals(game.world.locate_biome("bworld:plains", x, z), y);
assert(say("/locatebiome bworld:nowhere").includes("There's no biome bworld:nowhere"));
});
+1 -1
View File
@@ -131,7 +131,7 @@ Deno.test("every morning a crab pot in water uses its bait to catch something, f
const column = (ocean: boolean) => {
for (let x = -2048; x <= 2048; x += 32) {
for (let z = -2048; z <= 2048; z += 32) {
if (tags.has("biomes", "bworld:is_ocean", t.game.world.biome_at(x, z)) === ocean) return [x, z];
if (tags.has("biomes", "bworld:is_ocean", t.game.world.biome_at(x, 64, z)) === ocean) return [x, z];
}
}
throw new Error("no such column near spawn");
+1 -1
View File
@@ -163,7 +163,7 @@ Deno.test("a fish with biomes is only caught in them, by id or #tag", async () =
const find = (matches: (biome: string) => boolean) => {
for (let x = -4096; x <= 4096; x += 64) {
for (let z = -4096; z <= 4096; z += 64) {
const biome = t.game.world.biome_at(x, z);
const biome = t.game.world.biome_at(x, 64, z);
const season = biome_season(biome, t.game.world.time);
if (matches(biome) && (season === "summer" || season === "winter")) return { x, y: 64, z };
}
+17 -2
View File
@@ -3,7 +3,8 @@
// the golden fixture's hashes, shared by the tests that check generation against it: worldgen_golden_test.ts,
// worldgen_bundle_test.ts and worldgen_pool_test.ts. hashed by name, since numeric ids move whenever a block is added
import { AIR, ID_MASK } from "@/common/constants.ts";
import { AIR, CHUNK_AREA, ID_MASK } from "@/common/constants.ts";
import { BIOME_CELL_HEIGHT, type ChunkColumn } from "@/common/section.ts";
import type { RawChunk } from "@/common/generation.ts";
import { AIR_ID } from "@/common/protocol.ts";
import { sha256 } from "@/common/utils.ts";
@@ -41,7 +42,21 @@ export function raw_hash(raw: RawChunk, name: (value: number) => string): Promis
for (let i = 0; i < raw.spills.length; i += 4) {
spills.push(raw.spills[i], raw.spills[i + 1], raw.spills[i + 2], name(raw.spills[i + 3]));
}
return hash(blocks_text(raw.column.to_flat(), name), JSON.stringify(spills), raw.column.biomes.join(","));
return hash(blocks_text(raw.column.to_flat(), name), JSON.stringify(spills), biomes_text(raw.column));
}
// each column's biome, x then z, then every biome cell's when any isn't its column's, so a world whose biomes don't
// change with height hashes as it did before biomes had heights
function biomes_text(column: ChunkColumn) {
const { min_y, max_y } = column.shape;
const at = (i: number, y: number) => column.biome_at(column.x * 16 + (i & 15), y, column.z * 16 + (i >> 4));
const columns = Array.from({ length: CHUNK_AREA }, (_, i) => at(i, min_y));
const cells: string[] = [];
for (let y = min_y; y < max_y; y += BIOME_CELL_HEIGHT) {
for (let i = 0; i < CHUNK_AREA; i++) cells.push(at(i, y));
}
const flat = cells.every((biome, i) => biome === columns[i % CHUNK_AREA]);
return flat ? columns.join(",") : `${columns.join(",")}|${cells.join(",")}`;
}
// what the fixture's "final" is: the chunk with its neighbors' spills
+3 -1
View File
@@ -199,7 +199,8 @@ export function chunk_worker(
// the sections of the middle one of 3x3 chunks meshed by a chunk worker, asked for the way the client asks: all of
// them, or the indexes in options.sections. the chunks are each block's value in one array, y from the bottom of the
// world then z then x, null where there's none. what comes back is each section's mesh, and all of them put together:
// world then z then x, null where there's none, all of one biome whose grass, foliage and water colors are each chunk's
// options.biome_colors. what comes back is each section's mesh, and all of them put together:
// their layers' quads one after another, their light, their visuals with indexes in the whole chunk (like an array's)
// and the bounds of them all
export async function mesh_column(
@@ -231,6 +232,7 @@ export async function mesh_column(
first,
chunks: columns.map((column) => column?.sections.slice(first, end).map((section) => section.data) ?? null),
sky: columns.map((column) => column && column_heights(column, opacity).slice(CHUNK_AREA)),
biomes: columns.map((column) => column?.biomes.sections.slice(first, end) ?? null),
biome_colors: options.biome_colors ?? chunks.map(() => null),
camera: options.camera ?? [0, 0, 0],
};
+6 -6
View File
@@ -72,10 +72,10 @@ Deno.test("blocks, entities, players and the world know their biome's season", a
const season_of = (biome: string) => get_biome(biome)?.season ?? "spring";
// spawn is on dry land
const biome = ctx.world.biome_at(0, 0);
assertEquals(biome, game.world.biome_at(0, 0));
const biome = ctx.world.biome_at(0, 100, 0);
assertEquals(biome, game.world.biome_at(0, 100, 0));
assertEquals(season_of(biome), "winter");
assertEquals(ctx.world.season_at(0.7, 0.2), "winter");
assertEquals(ctx.world.season_at(0.7, 100.5, 0.2), "winter");
game.set_block(0, 100, 0, "testmod:thermometer");
assertEquals(created, [{ biome, season: season_of(biome) }]);
@@ -89,9 +89,9 @@ Deno.test("blocks, entities, players and the world know their biome's season", a
assertEquals([alice.biome, alice.season], [biome, season_of(biome)]);
// somewhere far off, in a chunk nobody loaded, it's what generation makes there
const far = ctx.world.biome_at(5000, -3000);
assertEquals(far, game.world.biome_at(5000, -3000));
assertEquals(ctx.world.season_at(5000, -3000), season_of(far));
const far = ctx.world.biome_at(5000, 64, -3000);
assertEquals(far, game.world.biome_at(5000, 64, -3000));
assertEquals(ctx.world.season_at(5000, 64, -3000), season_of(far));
} finally {
Deno.removeSync(dir, { recursive: true });
}
+56 -3
View File
@@ -7,10 +7,13 @@ import { Alea } from "@paulaboks/rng";
import { AIR, CHUNK_AREA } from "@/common/constants.ts";
import { Reader, Writer } from "@/common/bytes.ts";
import {
BIOME_CELL_HEIGHT,
ChunkColumn,
column_biomes,
column_heights,
read_column,
Section,
SECTION_BIOMES,
SECTION_VOLUME,
to_flat,
write_column,
@@ -21,10 +24,12 @@ const SHAPE = new WorldShape({ min_y: -64, max_y: 320, sky_light: true });
const [STONE, GLASS, LEAVES] = [1, 2, 3];
// light goes through air and glass, leaves and stone stop it
const OPACITY = Uint8Array.of(0, 15, 0, 1);
// every column's biome all the way up
const PLAINS: string[] = new Array(CHUNK_AREA).fill("test:plains");
function empty_column(x = 0, z = 0) {
const sections = Array.from({ length: SHAPE.height / 16 }, () => new Section(AIR));
return new ChunkColumn(x, z, SHAPE, sections, new Array(CHUNK_AREA).fill("test:plains"));
return new ChunkColumn(x, z, SHAPE, sections, column_biomes(PLAINS, sections.length));
}
Deno.test("a section is one value until a block in it differs", () => {
@@ -54,7 +59,7 @@ Deno.test("a column's blocks are at their world coordinates, from min_y to max_y
const flat = column.to_flat();
assertEquals(flat[0 * CHUNK_AREA + 15 * 16 + 0], STONE);
assertEquals(flat[383 * CHUNK_AREA + 0 * 16 + 15], GLASS);
const again = ChunkColumn.from_flat(-2, 3, SHAPE, flat, column.biomes);
const again = ChunkColumn.from_flat(-2, 3, SHAPE, flat, PLAINS);
assertEquals(again.to_flat(), flat);
assertEquals(again.sections.filter((section) => section.blocks).length, 2);
@@ -112,7 +117,14 @@ Deno.test("sections are written and read back as they were, however many kinds o
);
});
sections.push(new Section(GLASS));
const biomes = Array.from({ length: CHUNK_AREA }, (_, i) => `test:biome_${i % 3}`);
// three biomes in the lowest 5 sections, one in the rest
const biomes = column_biomes(
Array.from(
{ length: sections.length * SECTION_BIOMES },
(_, i) => i < 5 * SECTION_BIOMES ? `test:biome_${i % 3}` : "test:one",
),
sections.length,
);
const writer = new Writer();
write_column(writer, sections, biomes);
@@ -126,3 +138,44 @@ Deno.test("sections are written and read back as they were, however many kinds o
assertEquals(read_column(new Reader(bytes), (value) => value + 1).sections.at(-1)!.value, GLASS + 1);
assertThrows(() => read_column(new Reader(bytes.subarray(0, bytes.length - 1)), (value) => value));
});
Deno.test("a column's biomes are one per block across and every 4 blocks up, and set a cell at a time", () => {
// a cave biome from y 0 to 3 under one column, the rest plains
const cells = Array.from(
{ length: SHAPE.height / BIOME_CELL_HEIGHT * CHUNK_AREA },
(_, i) => i === (0 - SHAPE.min_y) / BIOME_CELL_HEIGHT * CHUNK_AREA + 5 * 16 + 4 ? "test:cave" : "test:plains",
);
const column = ChunkColumn.from_flat(0, 0, SHAPE, new Uint32Array(SHAPE.volume), cells);
assertEquals([0, 3].map((y) => column.biome_at(4, y, 5)), ["test:cave", "test:cave"]);
assertEquals([-1, 4].map((y) => column.biome_at(4, y, 5)), ["test:plains", "test:plains"]);
assertEquals(column.biome_at(5, 0, 5), "test:plains");
// above and below the world, the top's and the bottom's
assertEquals([column.biome_at(4, 1000, 5), column.biome_at(4, -1000, 5)], ["test:plains", "test:plains"]);
// sections with the same biomes all the way up share theirs
const plains = column_biomes(PLAINS.map((biome, i) => i < 5 ? "test:desert" : biome), 24);
assert(plains.sections.every((section) => section === plains.sections[0]));
column.set_biome(9, 100, 9, "test:desert");
for (let y = 100; y < 104; y++) assertEquals(column.biome_at(9, y, 9), "test:desert");
for (const y of [99, 104]) assertEquals(column.biome_at(9, y, 9), "test:plains");
assertEquals(column.biome_at(9, 100, 10), "test:plains");
// nothing outside the world's height
column.set_biome(9, 320, 9, "test:desert");
assertEquals(column.biome_at(9, 319, 9), "test:plains");
// a copy's biomes are its own, even where sections shared theirs
const sharing = ChunkColumn.from_flat(
0,
0,
SHAPE,
new Uint32Array(SHAPE.volume),
PLAINS.map((biome, i) => i < 5 ? "test:desert" : biome),
);
const copy = sharing.clone();
copy.set_biome(9, 0, 0, "test:cave");
assertEquals([copy.biome_at(9, 0, 0), sharing.biome_at(9, 0, 0), copy.biome_at(9, 16, 0)], [
"test:cave",
"test:plains",
"test:plains",
]);
});
+6 -5
View File
@@ -5,6 +5,7 @@
// docs/modding/worldgen/terrain.md. tests/worldgen_golden_test.ts checks the base game's makes the same world
import { assert, assertEquals, assertRejects } from "@std/assert";
import { generate_raw_chunk } from "@/common/generation.ts";
import { CHUNK_AREA } from "@/common/constants.ts";
import { copy_dir, test_game } from "./helpers.ts";
// mods/bworld and a mod with files, in a temp folder
@@ -55,15 +56,15 @@ Deno.test("a mod's biome generates where its rule, added to the base game's, say
for (let cz = -2; cz < 2; cz++) {
const { column } = generate_raw_chunk(cx, cz, "lavender", block_ids, worldgen, default_values);
const { min_y, max_y } = game.world.shape;
column.biomes.forEach((biome, i) => {
if (biome !== "lavender:fields") return;
fields++;
// its surface: the top block of the column is its sand
for (let i = 0; i < CHUNK_AREA; i++) {
const [x, z] = [cx * 16 + i % 16, cz * 16 + Math.floor(i / 16)];
// its surface: the top block of the column is its sand
let y = max_y - 1;
while (y > min_y && column.get(x, y, z) === 0) y--;
if (column.biome_at(x, y, z) !== "lavender:fields") continue;
fields++;
assertEquals(column.get(x, y, z), block_ids["bworld:sand"]);
});
}
}
}
assert(fields > 100, `only ${fields} columns of lavender fields`);
+3 -9
View File
@@ -27,13 +27,8 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
const empty = () => new Uint32Array(DEFAULT_SHAPE.volume);
const chunks = [empty(), empty(), empty(), empty(), chunk, empty(), empty(), empty(), empty()];
const colors = chunks.map(() => null as Uint32Array | null);
const biome_colors = ({ grass, foliage, water = 0 }: Colors) => {
const array = new Uint32Array(CHUNK_AREA * 3);
array.fill(grass, 0, CHUNK_AREA);
array.fill(foliage, CHUNK_AREA, CHUNK_AREA * 2);
array.fill(water, CHUNK_AREA * 2);
return array;
};
// the colors of each chunk's one biome
const biome_colors = ({ grass, foliage, water = 0 }: Colors) => Uint32Array.of(grass, foliage, water);
colors[4] = biome_colors(middle);
if (west) colors[3] = biome_colors(west);
@@ -105,8 +100,7 @@ Deno.test("every column the overworld generates has a biome with grass, foliage
blocks.forEach((b, nid) => block_ids[b.id] = nid);
for (const [x, z] of [[0, 0], [30, -12], [-80, 45]]) {
const { biomes } = generate_raw_chunk(x, z, game.world.seed, block_ids, game.world.worldgen).column;
assertEquals(biomes.length, CHUNK_AREA);
for (const biome of biomes) {
for (const biome of biomes.palette) {
const { colors } = get_biome(biome)!;
assert(colors.grass !== undefined, `${biome} has no grass color`);
assert(colors.foliage !== undefined, `${biome} has no foliage color`);
+156
View File
@@ -0,0 +1,156 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// biomes have heights: one per block across and every 4 blocks up, chosen by biome rules that can look at "y" and
// "depth", see docs/modding/worldgen/biomes.md. a mod adds an underground biome to the base game's with one rule
import { assert, assertEquals } from "@std/assert";
import type { ServerContext } from "@/common/mod_api/server.ts";
import { validate_noise_settings } from "@/common/worldgen/data.ts";
import { client_level } from "./client_level.ts";
import { copy_dir, test_game } from "./helpers.ts";
// mods/bworld and a mod whose biome is everywhere more than 16 blocks under the ground. its scripts keep what a feature
// saw of chunk 0, 0's biomes at 8, 8, and the server's context. the feature also sets the cell 9, 201, 9 to it
function deep_mod() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_deep_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const write = (path: string, content: unknown) => {
Deno.mkdirSync(`${dir}/deep/${path.slice(0, path.lastIndexOf("/"))}`, { recursive: true });
Deno.writeTextFileSync(`${dir}/deep/${path}`, typeof content === "string" ? content : JSON.stringify(content));
};
write("manifest.json", {
format_version: 1,
id: "deep",
name: "Deep",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { worldgen: "scripts/worldgen.ts", server: "scripts/server.ts" },
});
write("worldgen/biomes/caves.json", {
format_version: 1,
biome: {
id: "deep:caves",
surface: { top: "bworld:stone", filler: "bworld:stone", filler_depth: 1 },
season: "winter",
},
});
write("worldgen/biome_source/caves.json", {
format_version: 1,
biome_source: {
id: "deep:caves",
extends: "bworld:overworld",
// before every rule of the base game's, which all hold all the way down
rules: [{
id: "deep:caves",
before: "bworld:river_bed_frozen",
when: { depth: { min_exclusive: 16 } },
biome: "deep:caves",
}],
},
});
write(
"scripts/worldgen.ts",
`import type { WorldgenContext } from "cubi/worldgen";
export function setup(gen: WorldgenContext) {
gen.register_feature("deep:look", (chunk) => {
if (chunk.x !== 0 || chunk.z !== 0) return;
const ground = chunk.height_at(8, 8);
(globalThis as any).deep_seen = [chunk.biome_at(8, ground, 8), chunk.biome_at(8, ground - 40, 8)];
chunk.set_biome(9, 201, 9, "deep:caves");
});
}`,
);
write(
"scripts/server.ts",
`import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
(globalThis as any).deep_ctx = ctx;
}`,
);
return dir;
}
const seen = () => (globalThis as unknown as { deep_seen: string[] }).deep_seen;
const server_ctx = () => (globalThis as unknown as { deep_ctx: ServerContext }).deep_ctx;
Deno.test("a rule with depth puts a biome under the ground, and the ground keeps its own and its blocks", async () => {
const dir = deep_mod();
try {
const { game } = await test_game(dir);
const world = game.world;
const ground = world.surface_height(8, 8);
const surface = world.biome_at(8, ground, 8);
assert(surface !== "deep:caves", "the ground's biome is the base game's");
assertEquals(world.biome_at(8, ground - 40, 8), "deep:caves");
assertEquals(world.biome_at(8, world.shape.min_y - 100, 8), "deep:caves", "below the world, its bottom's");
// features see the same, and set the 4 blocks tall cell a y is in
assertEquals(seen(), [surface, "deep:caves"]);
assertEquals([199, 200, 203, 204].map((y) => world.biome_at(9, y, 9) === "deep:caves"), [
false,
true,
true,
false,
]);
// the blocks are what the base game makes without it
const blocks = [[0, 0], [2, -3]].map(([x, z]) => world.generated_blocks(x, z).to_flat());
const plain = (await test_game("mods")).game.world;
assertEquals(blocks, [[0, 0], [2, -3]].map(([x, z]) => plain.generated_blocks(x, z).to_flat()));
} finally {
Deno.removeSync(dir, { recursive: true });
}
});
Deno.test("biomes under the ground are saved, sent to clients, and where entities stand", async () => {
const dir = deep_mod();
try {
const { game, join, send, take } = await test_game(dir);
const world = game.world;
const ground = world.surface_height(8, 8);
const deep = ground - 40;
// a client reads them from the chunk it's sent
const { level } = client_level(world.shape);
level.load_chunk(world.level_chunk(0, 0));
assertEquals(level.biome_at(8, deep, 8), "deep:caves");
assertEquals(level.biome_at(8, ground, 8), world.biome_at(8, ground, 8));
level.dispose();
// scripts read the biome and season at a block, and an entity's at its feet
const ctx = server_ctx();
assertEquals([ctx.world.biome_at(8.5, deep, 8.5), ctx.world.season_at(8.5, deep, 8.5)], [
"deep:caves",
"winter",
]);
const chicken = ctx.world.spawn_entity("bworld:chicken", 8.5, deep, 8.5);
assertEquals([chicken.biome, chicken.season], ["deep:caves", "winter"]);
// /locatebiome finds it under the ground, and says how deep
join(1, "alice");
send(1, { type: "move", x: 8.5, y: ground + 1, z: 8.5, yaw: 0, pitch: 0 });
take(1);
send(1, { type: "chat", text: "/locatebiome deep:caves" });
const answer = take(1).filter((m) => m.type === "chat").map((m) => m.text).join("\n");
const [x, y, z] = answer.match(/at (-?\d+) (-?\d+) (-?\d+)/)!.slice(1).map(Number);
assertEquals(world.locate_biome("deep:caves", x, z), y);
assert(y < world.locate_biome(world.biome_at(x, 1000, z), x, z)! - 16, `${answer}, not under the ground`);
// and they come back with the chunk
world.set_block(8, ground + 1, 8, "bworld:stone");
const loaded = (await test_game(dir, game.save())).game.world;
assertEquals(loaded.biome_at(8, deep, 8), "deep:caves");
assertEquals(loaded.biome_at(8, ground, 8), world.biome_at(8, ground, 8));
} finally {
Deno.removeSync(dir, { recursive: true });
}
});
Deno.test("a generator's climate values can't be named like what biome rules look at", async () => {
const json =
JSON.parse(await Deno.readTextFile("mods/bworld/worldgen/noise_settings/overworld.json")).noise_settings;
assertEquals(validate_noise_settings(json), []);
for (const name of ["y", "depth"]) {
const problems = validate_noise_settings({ ...json, climate: { ...json.climate, [name]: 0 } });
assert(problems.some((problem) => problem.includes("climate")), `${name}: ${problems}`);
}
});
+4 -3
View File
@@ -60,15 +60,16 @@ Deno.test("trees grow the wood of their kind and biome", async () => {
for (let cx = -8; cx < 8; cx++) {
for (let cz = -8; cz < 8; cz++) {
const { column } = generate_raw_chunk(cx, cz, "wood-test", ids, game.world.worldgen);
const [blocks, biomes] = [column.to_flat(), column.biomes];
const blocks = column.to_flat();
blocks.forEach((block, i) => {
const leaves = leaves_of.get(block);
if (leaves) found_leaves.add(leaves);
const wood = wood_of.get(block);
// the bottom of a trunk
if (!wood || !ground.has(blocks[i - CHUNK_AREA])) return;
const column = i % CHUNK_AREA;
const biome = biomes[column];
// the trunk's ground's biome
const y = game.world.shape.min_y + Math.floor(i / CHUNK_AREA) - 1;
const biome = column.biome_at(cx * 16 + i % 16, y, cz * 16 + Math.floor(i / 16) % 16);
const info = get_biome(biome)!;
const allowed = info.trees!.kinds.map((kind) =>
info.trees!.wood[kind] ?? (kind === "big_oak" ? "oak" : kind)
+35 -11
View File
@@ -8,7 +8,8 @@ import { ChunkBlocks, decode_chunk, encode_chunk, SavedChunk } from "@/server/ga
import { list_chunks, read_chunk, region_file, write_chunks } from "@/server/regions.ts";
import { sent_block, test_game } from "./helpers.ts";
import { DEFAULT_SHAPE, WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, section_index, to_flat } from "@/common/section.ts";
import { biome_in, ChunkColumn, column_biomes, section_index, to_flat } from "@/common/section.ts";
import { Writer } from "@/common/bytes.ts";
// a chunk at the height of the base game's dimension, which the test worlds play
function chunk_data(seed: number, palette_size = 3, shape = DEFAULT_SHAPE): Required<ChunkBlocks> {
@@ -16,12 +17,8 @@ function chunk_data(seed: number, palette_size = 3, shape = DEFAULT_SHAPE): Requ
for (let i = 0; i < palette_size; i++) palette.push([`test:block_${i}`, i % 5]);
const blocks = new Uint32Array(shape.volume).map((_, i) => (i * seed) % palette_size);
const biomes = Array.from({ length: CHUNK_AREA }, (_, i) => `test:biome_${(i * seed) % 4}`);
return {
palette,
min_y: shape.min_y,
sections: ChunkColumn.from_flat(0, 0, shape, blocks, biomes).sections,
biomes,
};
const { sections, biomes: column_biomes } = ChunkColumn.from_flat(0, 0, shape, blocks, biomes);
return { palette, min_y: shape.min_y, sections, biomes: column_biomes };
}
// the palette entry of a saved chunk's block
@@ -44,9 +41,14 @@ function old_format(format: 1 | 2, chunk: ChunkBlocks) {
if (format === 1) {
bytes.push(...new Uint8Array(flat.length / 8));
} else {
const biome_palette = [...new Set(chunk.biomes)];
// each column's biome at the bottom
const columns = Array.from(
{ length: CHUNK_AREA },
(_, i) => biome_in(chunk.biomes!, DEFAULT_SHAPE, i, 0, i >> 4),
);
const biome_palette = [...new Set(columns)];
bytes.push(biome_palette.length, ...biome_palette.flatMap(string));
bytes.push(...chunk.biomes!.map((biome) => biome_palette.indexOf(biome)));
bytes.push(...columns.map((biome) => biome_palette.indexOf(biome)));
}
return Uint8Array.from(bytes);
}
@@ -80,6 +82,28 @@ Deno.test("a chunk's blocks and biomes come back as they were saved, with more t
assertEquals(to_flat(old.sections), to_flat(chunk.sections));
assertEquals(old.biomes, format === 1 ? undefined : chunk.biomes);
}
// and format 3, from before biomes had heights: each column's biome, which goes all the way up
const columns = Array.from({ length: CHUNK_AREA }, (_, i) => i < 10 ? "test:a" : "test:b");
const writer = new Writer();
writer.u8(3);
writer.i16(0);
writer.u32(1);
writer.string("test:block_0");
writer.u16(0);
writer.u16(2);
writer.string("test:a");
writer.string("test:b");
for (const biome of columns) writer.u8(biome === "test:a" ? 0 : 1);
writer.u16(16);
// sections all of the one block
for (let i = 0; i < 16; i++) {
writer.u8(0);
writer.u32(0);
}
const three = decode_chunk(writer.bytes());
assertEquals(three.sections.map((section) => section.value), new Array(16).fill(0));
assertEquals(three.biomes, column_biomes(columns, 16));
});
Deno.test("region files keep chunks, including negative ones, and saving one again doesn't touch the others", async () => {
@@ -136,7 +160,7 @@ Deno.test("every chunk generated is saved whole, and saved again only when it ch
const chunk = decode_chunk(saved.chunks.find((c) => c.x === 0 && c.z === 0)!.data);
assertEquals(saved_block(chunk, 3, 120, 5), ["bworld:stone", 0]);
assert(saved_block(chunk, 3, 10, 5)[0] !== AIR_ID);
assertEquals(chunk.biomes![5 * 16 + 3], game.world.biome_at(3, 5));
assertEquals(biome_in(chunk.biomes!, DEFAULT_SHAPE, 3, 120, 5), game.world.biome_at(3, 120, 5));
const untouched = decode_chunk(saved.chunks.find((c) => c.x === 5 && c.z === 5)!.data);
assertEquals(
Uint32Array.from(to_flat(untouched.sections), (block) => {
@@ -192,7 +216,7 @@ Deno.test("chunks saved before they had biomes get them from generation, and are
at_0_0.data = old_format(1, decode_chunk(at_0_0.data));
const { game } = await test_game("mods", saved);
assertEquals(game.world.get_block_id(3, 121, 5), "bworld:stone");
assertEquals(game.world.biome_at(3, 5), biomes[5 * 16 + 3]);
assertEquals(game.world.biome_at(3, 120, 5), biome_in(biomes, DEFAULT_SHAPE, 3, 120, 5));
const again = game.save().chunks.find((c) => c.x === 0 && c.z === 0)!;
assertEquals(decode_chunk(again.data).biomes, biomes);
});
+1 -1
View File
@@ -31,7 +31,7 @@ Deno.test("cacti grow 1 to 3 tall on desert sand, 2 or 3 tries a chunk", async (
// the bottom of each cactus
if (at(x, y, z) !== cactus || at(x, y - 1, z) === cactus) continue;
assertEquals(at(x, y - 1, z), sand, "on sand");
assertEquals(chunk.column.biomes[z * CHUNK_SIZE + x], "bworld:desert");
assertEquals(chunk.column.biome_at(x0 + x, y - 1, z0 + z), "bworld:desert");
let height = 0;
while (at(x, y + height, z) === cactus) height++;
heights.push(height);
+1 -1
View File
@@ -193,7 +193,7 @@ const shade = (color: [number, number, number], factor: number): [number, number
const column = terrain.column(x, z);
heights[pz * size + px] = column.height;
const surface = Math.round(column.height);
const biome = terrain.biome(column, surface, false);
const biome = terrain.biome(column, surface, false, surface);
const color = BIOME_COLORS[biome] ?? [255, 0, 255];
rgb.set(color, (pz * size + px) * 3);
}