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
+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;
},