Move world generation outside the engine and into mods and data files

This commit is contained in:
2026-10-11 00:33:59 -03:00
parent afe6e03d4c
commit 3d2b235f64
118 changed files with 8250 additions and 1108 deletions
+11 -10
View File
@@ -12,8 +12,8 @@ What world generation has today (see [World Generation](docs/modding/worldgen/in
- **The server generates every chunk** (`server/game/world.ts`, `common/generation.ts`). Players only get finished
chunks, so generation code and data never have to reach clients.
- **Three passes per chunk:** terrain (the engine's overworld, with its trees grown inside the terrain pass), then ores
(`worldgen/ores.json`), then features (`register_feature` in a worldgen script).
- **Three passes per chunk:** terrain (data, see [GENERATION.md](GENERATION.md)), then ores (`worldgen/ores.json`), then
features, code or data, by step. The base game's trees are a code feature in `vegetal_decoration`.
- **Chunks generate alone.** A feature may write up to one chunk away. Those writes are "spills" that only fill air in
the neighbor, so the result doesn't depend on which chunk generates first.
- **Determinism is the rule everything rests on.** A save only keeps player changes. Untouched terrain is generated
@@ -24,7 +24,7 @@ What world generation has today (see [World Generation](docs/modding/worldgen/in
surface.
- **Blocks:** numeric states (up to 16 bits), `variants`, `parts`, shapes, tile data, containers, components and shared
rules. Tags exist for blocks, items and entities. Biomes are a registry of data (`worldgen/biomes/` in a mod), but
which one a column gets is still engine code (`pick_biome`).
which one a column gets is data too, a biome source's rules (see [GENERATION.md](GENERATION.md)).
- **Loot:** a block's `drops` is one item id. There are no loot tables.
What's missing for structures:
@@ -46,7 +46,7 @@ The order a chunk generates in becomes:
```
1. structure starts which structures overlap this chunk, assembled into pieces (cached, never saved)
2. terrain the overworld, shaped around pieces that adapt the terrain; no trees inside pieces
2. terrain the overworld, shaped around pieces that adapt the terrain
3. ores as now
4. structures each overlapping piece writes the blocks inside this chunk, by step
5. features data features and script features, by step
@@ -397,8 +397,9 @@ That's Trek's `monster_room/upper/default`, its configured and placed feature jo
`rarity_filter`, `in_square`, `height_range`, `heightmap`, `biome`, `surface_relative_threshold_filter`,
`block_predicate_filter`.
- First feature types, from what Trek uses: `fossil` (a template, which covers Trek's monster rooms), `simple_block`,
`block_column`, `disk` and `spring_feature`. Then the base game's own: `ore`, `tree` and `random_patch`, as the
terrain moves out of the engine (Phase 6 of the [modding plan](docs/modding_plan.md)).
`block_column`, `disk` and `spring_feature`, and `ore` and `random_patch` for the base game. Its trees stay code. The
format, `simple_block`, `block_column`, the first placement modifiers and `register_feature_type` are built already,
see [Data Features](docs/modding/worldgen/index.md#data-features).
- Worldgen scripts register more types with `register_feature_type(id, (chunk, config, origin) => ...)`, so a data
feature can use a type a mod wrote in code. `register_feature` stays for features that are only code.
- **Features that reach into other chunks are evaluated from each chunk they touch.** Where a feature starts is decided
@@ -492,8 +493,8 @@ so it's the same idea. The terrain pass gets the boxes of every piece in or near
box. Above its floor, inside its box, clear what the terrain put there.
- **`beard_box`:** the same, without fading at the edges.
- **`bury` and `encapsulate`:** fill around the piece instead. Trek doesn't use them, so they can come later.
- **Trees:** the terrain pass doesn't grow trees whose trunk is inside a piece's box (grown out a few blocks), so
villages don't get trees through their roofs. Trees still grow around them.
- **Trees:** the base game's trees feature doesn't grow trees whose trunk is inside a piece's box (grown out a few
blocks), using `chunk.structures`, so villages don't get trees through their roofs. Trees still grow around them.
Like Minecraft, `terrain_matching` pieces (paths) don't adapt the terrain: they follow it.
@@ -624,8 +625,8 @@ Check: a village chest has loot the first time it's opened and not the second.
Check: Trek's monster rooms generate underground.
**Phase 7: the rest, as it's needed.** `concentric_rings`, `bury` and `encapsulate`, `spawn_overrides`, mirroring,
structure types from scripts, and the base game's ores and trees as data features. Meanwhile blocks keep being added,
and each one lets more of Trek's templates generate whole.
structure types from scripts, and the base game's ores as data features. Meanwhile blocks keep being added, and each one
lets more of Trek's templates generate whole.
## Open Questions
+44 -3
View File
@@ -30,6 +30,17 @@ import {
import type { ModData } from "./mod_loader.ts";
import { type LootTableJson, validate_loot_table } from "./loot.ts";
import { type BiomeJson, validate_biome } from "./worldgen/biomes.ts";
import {
type BiomeSourceJson,
type DensityFunctionJson,
type NoiseJson,
type NoiseSettingsJson,
validate_biome_source,
validate_density_function,
validate_noise,
validate_noise_settings,
} from "./worldgen/data.ts";
import { type FeatureJson, validate_feature } from "./worldgen/features.ts";
import { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts";
import { ENGINE_GLOBAL } from "./hooks.ts";
@@ -166,10 +177,37 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[],
loot_tables: checked(raw_data.loot_tables, "loot_tables", validate_loot_table, problems) as LootTableJson[],
biomes: checked(raw_data.biomes, "biomes", validate_biome, problems) as BiomeJson[],
noises: checked(raw_data.noises, "noises", validate_noise, problems) as NoiseJson[],
density_functions: checked(
raw_data.density_functions,
"density_functions",
validate_density_function,
problems,
) as DensityFunctionJson[],
noise_settings: checked(
raw_data.noise_settings,
"noise_settings",
validate_noise_settings,
problems,
) as NoiseSettingsJson[],
biome_sources: checked(
raw_data.biome_sources,
"biome_sources",
validate_biome_source,
problems,
) as BiomeSourceJson[],
features: checked(raw_data.features, "features", validate_feature, problems) as FeatureJson[],
};
// a mod only registers ids in its own namespace
const registered = [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models];
for (const { id } of [...registered, ...data.effects, ...data.loot_tables!, ...data.biomes!]) {
const worldgen = [
...data.noises!,
...data.density_functions!,
...data.noise_settings!,
...data.biome_sources!,
...data.features!,
];
for (const { id } of [...registered, ...data.effects, ...data.loot_tables!, ...data.biomes!, ...worldgen]) {
if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`);
}
@@ -236,12 +274,15 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
return { manifest, data, scripts, textures, texture_json, credits };
}
// the same mod without its server and worldgen scripts, what players get. the server sends them the world
// the same mod without its server and worldgen scripts and the terrain's data, what players get. the server sends
// them the world
export function client_copy(bmod: Bmod): Bmod {
const scripts = { ...bmod.scripts };
delete scripts.server;
delete scripts.worldgen;
return { ...bmod, scripts };
const { noises: _n, density_functions: _d, noise_settings: _s, biome_sources: _b, features: _f, ...data } =
bmod.data;
return { ...bmod, scripts, data };
}
function checked(list: unknown, name: string, validate: (json: unknown) => string[], problems: string[]): unknown[] {
+35 -35
View File
@@ -1,28 +1,33 @@
// generating a chunk: the overworld's terrain (common/worldgen), then ores, then mods' features.
// runs in chunk workers on the server and every client, which must all get the same blocks
// generating a chunk: the terrain from the generator's data (common/worldgen), then ores, then mods' features.
// only the server generates, players get finished chunks
import { Alea } from "@paulaboks/rng";
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
import type { FeatureChunk } from "$/common/mod_api/worldgen.ts";
import type { FeatureChunk, Position } from "$/common/mod_api/worldgen.ts";
import type { OreJson } from "$/common/mod_data.ts";
import { generate_overworld } from "./worldgen/overworld.ts";
import { type Wood, WOODS } from "./worldgen/trees.ts";
import type { Generator } from "./worldgen/generator.ts";
import { named_noise_2d, named_noise_3d } from "./worldgen/noise.ts";
export { named_noise_2d, named_noise_3d };
// the base game's ores, placed like mods' ores.json. the world is 256 tall with the sea at 64
const BASE_ORES: OreJson[] = [
{ id: "bworld:coal_ore", replaces: "bworld:stone", min_y: 5, max_y: 200, scale: 0.05, threshold: 0.55 },
{ id: "bworld:copper_ore", replaces: "bworld:stone", min_y: 5, max_y: 110, scale: 0.06, threshold: 0.6 },
{ id: "bworld:tin_ore", replaces: "bworld:stone", min_y: 5, max_y: 70, scale: 0.06, threshold: 0.62 },
{ id: "bworld:iron_ore", replaces: "bworld:stone", min_y: 5, max_y: 80, scale: 0.05, threshold: 0.65 },
{ id: "bworld:gold_ore", replaces: "bworld:stone", min_y: 5, max_y: 36, scale: 0.04, threshold: 0.7 },
];
// what mods add to generation, see docs/modding/worldgen/index.md
export interface WorldgenSetup {
ores: OreJson[];
features: { id: string; generate: (chunk: FeatureChunk) => void }[];
// the terrain, biomes and surface, from noise settings, see docs/modding/worldgen/terrain.md
generator: Generator;
// each mod's worldgen/ores.json, in load order. each is a pass of its own, so a mod's ores can replace an earlier
// mod's, like the base game's
ores: OreJson[][];
// code and data features in the order they run, see load_worldgen
features: SetupFeature[];
// data features by id, for chunk.place_feature
placeable: Map<string, (chunk: FeatureChunk, origin: Position) => boolean>;
}
export interface SetupFeature {
id: string;
generate: (chunk: FeatureChunk) => void;
// a code feature's biomes: it only runs in chunks with one of them. data features check each position themselves
biomes?: Set<string>;
}
export interface RawChunk {
@@ -44,7 +49,7 @@ export function generate_raw_chunk(
chunk_z: number,
seed: string,
block_ids: Record<string, number>,
worldgen?: WorldgenSetup,
worldgen: WorldgenSetup,
// the value to store for each numeric id, with its default states. just the id when missing
default_values?: number[],
): RawChunk {
@@ -73,25 +78,12 @@ export function generate_raw_chunk(
const nid = block_ids[name];
return nid === undefined ? AIR : default_values?.[nid] ?? nid;
};
// each wood's are named after it, like bworld:oak_log
const wood_ids = (part: "log" | "leaves") =>
Object.fromEntries(WOODS.map((wood) => [wood, id(`bworld:${wood}_${part}`)])) as Record<Wood, number>;
generate_overworld(blocks, heights, biomes, chunk_x, chunk_z, seed, {
stone: id("bworld:stone"),
dirt: id("bworld:dirt"),
grass: id("bworld:grass"),
snow: id("bworld:snow_block"),
water: id("bworld:water"),
logs: wood_ids("log"),
leaves: wood_ids("leaves"),
block: id,
}, (x, y, z, block) => spills.push(x, y, z, block));
generate_ores(blocks, chunk_x, chunk_z, seed, block_ids, BASE_ORES, default_values);
generate_overworld(blocks, heights, biomes, chunk_x, chunk_z, worldgen.generator.for_seed(seed), id);
if (worldgen) {
generate_ores(blocks, chunk_x, chunk_z, seed, block_ids, worldgen.ores, default_values);
generate_features(blocks, heights, biomes, set, chunk_x, chunk_z, seed, block_ids, worldgen.features);
for (const ores of worldgen.ores) {
generate_ores(blocks, chunk_x, chunk_z, seed, block_ids, ores, default_values);
}
generate_features(blocks, heights, biomes, set, chunk_x, chunk_z, seed, block_ids, worldgen);
return { blocks, spills: new Int32Array(spills), biomes };
}
@@ -148,7 +140,7 @@ function generate_features(
chunk_z: number,
seed: string,
block_ids: Record<string, number>,
features: WorldgenSetup["features"],
worldgen: WorldgenSetup,
) {
const ids_by_nid: string[] = [];
for (const [id, nid] of Object.entries(block_ids)) {
@@ -164,12 +156,15 @@ function generate_features(
return lz * CHUNK_SIZE + lx;
};
for (const feature of features) {
const chunk_biomes = new Set(biomes);
for (const feature of worldgen.features) {
if (feature.biomes && ![...feature.biomes].some((biome) => chunk_biomes.has(biome))) continue;
const chunk: FeatureChunk = {
x: chunk_x,
z: chunk_z,
seed,
rng: new Alea(`${seed}_feature_${feature.id}_${chunk_x}_${chunk_z}`),
random: (name) => new Alea(`${seed}_${name}`),
noise_2d: (name) => named_noise_2d(seed, name),
noise_3d: (name) => named_noise_3d(seed, name),
height_at: (x, z) => heights[local(x, z, "height_at")],
@@ -193,6 +188,11 @@ function generate_features(
}
set(x, y, z, nid);
},
place_feature(id, x, y, z) {
const place = worldgen.placeable.get(id);
if (!place) throw new Error(`place_feature: ${id} isn't a data feature`);
return place(chunk, { x, y, z });
},
};
try {
feature.generate(chunk);
+46 -3
View File
@@ -1,11 +1,49 @@
// what worldgen scripts get, see docs/modding/worldgen/index.md. runs on the server and must be deterministic
import type { Id } from "./shared.ts";
import type { Id, Position } from "./shared.ts";
export type { Id } from "./shared.ts";
export type { Id, Position } from "./shared.ts";
export interface WorldgenContext {
register_terrain(id: Id, generate: (chunk: TerrainChunk) => void): void;
register_feature(id: Id, generate: (chunk: FeatureChunk) => void): void;
// a feature that's code, run on every chunk. see FeatureOptions for when
register_feature(id: Id, generate: (chunk: FeatureChunk) => void, options?: FeatureOptions): void;
// a type of feature data features can use: places config at origin, returns whether it placed anything
// deno-lint-ignore no-explicit-any
register_feature_type<C = any>(id: Id, place: (chunk: FeatureChunk, config: C, origin: Position) => boolean): void;
// a placement modifier data features can use: the positions after it, from the ones before. config is its json
register_placement_modifier<C = Record<string, unknown>>(
id: Id,
modify: (chunk: FeatureChunk, config: C, positions: Position[]) => Position[],
): void;
// every biome mods added, for what features read from them, like which trees grow
biomes(): FeatureBiome[];
}
// the order features run in, minecraft's decoration steps. features without one run in the last
export type FeatureStep =
| "raw_generation"
| "lakes"
| "local_modifications"
| "underground_structures"
| "surface_structures"
| "strongholds"
| "underground_ores"
| "underground_decoration"
| "fluid_springs"
| "vegetal_decoration"
| "top_layer_modification";
export interface FeatureOptions {
step?: FeatureStep;
// only runs in chunks with one of these biomes
biomes?: Id | Id[];
}
// a biome, as features see it
export interface FeatureBiome {
id: Id;
// its json's trees, see docs/modding/worldgen/biomes.md
trees?: { chance: number; kinds: string[]; wood: Record<string, string> };
}
export interface FeatureChunk {
@@ -15,6 +53,9 @@ export interface FeatureChunk {
readonly seed: string;
// seeded from the seed, chunk and feature id
readonly rng: { next(): number };
// seeded from the seed and name alone, the same in every chunk. for things decided across chunks, like trees
// spread over a grid of cells
random(name: string): { next(): number };
// 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;
@@ -23,6 +64,8 @@ export interface FeatureChunk {
biome_at(x: number, z: number): Id;
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
place_feature(id: Id, x: number, y: number, z: number): boolean;
}
export interface TerrainChunk extends FeatureChunk {
+125
View File
@@ -20,6 +20,19 @@ import { resolve_tags } from "./tags.ts";
import type { TextureJson } from "./texture_animation.ts";
import { loot_references, type LootTableJson } from "./loot.ts";
import { biome_blocks, type BiomeJson } from "./worldgen/biomes.ts";
import {
biome_source_refs,
type BiomeSourceJson,
density_function_refs,
type DensityFunctionJson,
new_refs,
noise_refs,
noise_settings_refs,
type NoiseJson,
type NoiseSettingsJson,
type WorldgenRefs,
} from "./worldgen/data.ts";
import { feature_refs, type FeatureJson } from "./worldgen/features.ts";
export interface ModReport {
id: string;
@@ -44,6 +57,12 @@ export interface LoadedMod {
tags: { file: string; json: TagJson }[];
loot_tables: { file: string; json: LootTableJson }[];
biomes: { file: string; json: BiomeJson }[];
// the terrain as data, see common/worldgen/data.ts
noises: { file: string; json: NoiseJson }[];
density_functions: { file: string; json: DensityFunctionJson }[];
noise_settings: { file: string; json: NoiseSettingsJson }[];
biome_sources: { file: string; json: BiomeSourceJson }[];
features: { file: string; json: FeatureJson }[];
textures: string[];
// absolute paths by texture id
texture_files: Map<string, string>;
@@ -95,6 +114,16 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]);
const textures = new Set<string>(engine_textures);
// terrain data by kind, then id
const worldgen_owners: Record<string, Map<string, string[]>> = {
noise: new Map(),
"density function": new Map(),
"noise settings": new Map(),
"biome source": new Map(),
};
const biome_rule_owners = new Map<string, string[]>();
const all_noise_settings: NoiseSettingsJson[] = [];
const feature_owners = new Map<string, string[]>();
for (const mod of mods) {
for (const { json } of mod.blocks) {
@@ -116,6 +145,17 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
for (const { json } of mod.effects) add(effect_owners, json.id, mod.id);
for (const { json } of mod.loot_tables ?? []) loot_tables.add(json.id);
for (const { json } of mod.biomes ?? []) add(biome_owners, json.id, mod.id);
for (const { json } of mod.noises ?? []) add(worldgen_owners.noise, json.id, mod.id);
for (const { json } of mod.density_functions ?? []) add(worldgen_owners["density function"], json.id, mod.id);
for (const { json } of mod.features ?? []) add(feature_owners, json.id, mod.id);
for (const { json } of mod.noise_settings ?? []) {
add(worldgen_owners["noise settings"], json.id, mod.id);
all_noise_settings.push(json);
}
for (const { json } of mod.biome_sources ?? []) {
add(worldgen_owners["biome source"], json.id, mod.id);
for (const rule of json.rules) add(biome_rule_owners, rule.id, mod.id);
}
for (const { json } of mod.tags) {
if (!tag_owners.has(json.registry)) tag_owners.set(json.registry, new Set());
tag_owners.get(json.registry)!.add(json.id);
@@ -275,6 +315,91 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
// mods' conditions and functions are registered by scripts, the server checks them when it starts
for (const id of refs.custom) check_namespace(file, id);
}
// the terrain as data: every id defined once, and everything it uses there
const check_worldgen = (kind: string, file: string, id: string, refs: WorldgenRefs) => {
if ((worldgen_owners[kind].get(id)?.length ?? 0) > 1) {
errors.push(`${file}: ${kind} ${id} is also defined by ${worldgen_owners[kind].get(id)!.join(", ")}`);
}
const exists = (ids: Set<string>, what: string, owners: Map<string, string[]>) => {
for (const used of ids) {
check_namespace(file, used);
if (!owners.has(used)) errors.push(`${file}: ${what} ${used} doesn't exist`);
}
};
exists(refs.noises, "noise", worldgen_owners.noise);
exists(refs.functions, "density function", worldgen_owners["density function"]);
exists(refs.biome_sources, "biome source", worldgen_owners["biome source"]);
exists(refs.biomes, "biome", biome_owners);
for (const block of refs.blocks) uses(file, block, "block");
};
for (const { file, json } of mod.noises ?? []) {
const refs = new_refs();
noise_refs(json, refs);
check_worldgen("noise", file, json.id, refs);
}
for (const { file, json } of mod.density_functions ?? []) {
const refs = new_refs();
density_function_refs(json, refs);
check_worldgen("density function", file, json.id, refs);
}
for (const { file, json } of mod.noise_settings ?? []) {
const refs = new_refs();
noise_settings_refs(json as unknown as Record<string, unknown>, refs);
check_worldgen("noise settings", file, json.id, refs);
}
for (const { file, json } of mod.biome_sources ?? []) {
const refs = new_refs();
biome_source_refs(json as unknown as Record<string, unknown>, refs);
check_worldgen("biome source", file, json.id, refs);
// 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"]);
for (const rule of json.rules) {
for (const name of Object.keys(rule.when ?? {})) {
if (!names.has(name)) {
errors.push(
`${file}: rule ${rule.id} looks at ${name}, which ${settings.id} doesn't have. it has ${
[...names].join(", ")
}`,
);
}
}
}
}
for (const rule of json.rules) {
if ((biome_rule_owners.get(rule.id)?.length ?? 0) > 1) {
errors.push(
`${file}: biome rule ${rule.id} is also defined by ${
biome_rule_owners.get(rule.id)!.join(", ")
}`,
);
}
const target = rule.before ?? rule.after;
if (target !== undefined && !biome_rule_owners.has(target)) {
errors.push(`${file}: rule ${rule.id} goes next to ${target}, which isn't a biome rule`);
}
}
}
for (const { file, json } of mod.features ?? []) {
if ((feature_owners.get(json.id)?.length ?? 0) > 1) {
errors.push(
`${file}: feature ${json.id} is also defined by ${feature_owners.get(json.id)!.join(", ")}`,
);
}
const refs = { blocks: new Set<string>(), biomes: new Set<string>(), custom: new Set<string>() };
feature_refs(json, refs);
for (const block of refs.blocks) uses(file, block, "block");
for (const biome of refs.biomes) {
check_namespace(file, biome);
if (!biome_owners.has(biome)) errors.push(`${file}: biome ${biome} doesn't exist`);
}
// check-mods doesn't run scripts, the server checks these when it starts
for (const custom of refs.custom) {
check_namespace(file, custom);
warnings.push(`${file}: ${custom} isn't built in, a worldgen script must register it`);
}
}
for (const { file, json } of mod.biomes ?? []) {
if ((biome_owners.get(json.id)?.length ?? 0) > 1) {
errors.push(`${file}: biome ${json.id} is also defined by ${biome_owners.get(json.id)!.join(", ")}`);
+21 -2
View File
@@ -23,6 +23,8 @@ import {
import { resolve_tags, Tags } from "./tags.ts";
import type { LootTableJson } from "./loot.ts";
import { type BiomeJson, register_biome } from "./worldgen/biomes.ts";
import type { BiomeSourceJson, DensityFunctionJson, NoiseJson, NoiseSettingsJson } from "./worldgen/data.ts";
import type { FeatureJson } from "./worldgen/features.ts";
import { register_block_item } from "./utils.ts";
import type { ModelJson } from "./block_models.ts";
@@ -46,6 +48,13 @@ export interface ModData {
loot_tables?: LootTableJson[];
// see common/worldgen/biomes.ts. missing from mods packed before biomes were data
biomes?: BiomeJson[];
// the terrain as data, see common/worldgen/data.ts. server only, players' copies leave them out
noises?: NoiseJson[];
density_functions?: DensityFunctionJson[];
noise_settings?: NoiseSettingsJson[];
biome_sources?: BiomeSourceJson[];
// data features, see common/worldgen/features.ts. server only too
features?: FeatureJson[];
}
// a mod as the server lists it to clients, in load order: the .bmod players download, without its server script
@@ -71,7 +80,8 @@ export class RecipeBook {
by_type = new Map<string, ModRecipeJson[]>();
// every recipe as its json, in load order, for recipe viewers
all: RecipeJson[] = [];
ores: OreJson[] = [];
// each mod's ores, in load order. each mod's are their own pass, see generate_raw_chunk
ores: OreJson[][] = [];
spawns: SpawnJson[] = [];
}
@@ -129,6 +139,15 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
for (const json of data.biomes ?? []) {
register_biome(json);
}
// compiled into a generator once every mod's are in, see common/worldgen/generator.ts
for (const json of data.noises ?? []) EverythingRegistry.register("noises", json.id, json);
for (const json of data.density_functions ?? []) {
EverythingRegistry.register("density_functions", json.id, json);
}
for (const json of data.noise_settings ?? []) EverythingRegistry.register("noise_settings", json.id, json);
for (const json of data.biome_sources ?? []) EverythingRegistry.register("biome_sources", json.id, json);
// compiled with the types worldgen scripts register, see common/worldgen_loader.ts
for (const json of data.features ?? []) EverythingRegistry.register("features", json.id, json);
} catch (e) {
throw new ModLoadError(id, (e as Error).message);
}
@@ -181,7 +200,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
break;
}
}
recipes.ores.push(...data.ores);
if (data.ores.length > 0) recipes.ores.push(data.ores);
recipes.spawns.push(...data.spawns);
}
+11 -29
View File
@@ -1,9 +1,8 @@
// biomes as data: worldgen/biomes/<name>.json in a mod, see docs/modding/worldgen/biomes.md. which biome a column
// gets is still code (pick_biome in overworld.ts), these say what a biome looks like once it's picked
// gets is the generator's biome rules (worldgen/biome_source), these say what a biome looks like once it's picked
import { EverythingRegistry } from "../everything_registry.ts";
import { ID_PATTERN } from "../mod_data.ts";
import { farming_day } from "../time.ts";
import { TREE_KINDS, type TreeKind, type Wood, WOODS } from "./trees.ts";
export const SEASONS = ["spring", "summer", "autumn", "winter"] as const;
export type Season = typeof SEASONS[number];
@@ -31,8 +30,9 @@ export interface BiomeJson {
colors?: { grass?: string; foliage?: string; water?: string };
// how likely each tree cell is to have a tree, and which kinds grow, picked evenly (list one twice to make it
// twice as likely). wood is the logs and leaves a kind grows here when it isn't its own, like big oaks being dark
// oak in the dark forest
trees?: { chance: number; kinds: TreeKind[]; wood?: Partial<Record<TreeKind, Wood>> };
// oak in the dark forest. the trees feature reads it (bworld's, in its worldgen script), which says what kinds
// and woods there are
trees?: { chance: number; kinds: string[]; wood?: Record<string, string> };
}
// what's registered in "biomes", with the defaults filled in
@@ -42,7 +42,7 @@ export interface Biome {
surface: Required<SurfaceJson>;
// 0xRRGGBB
colors: { grass?: number; foliage?: number; water?: number };
trees?: { chance: number; kinds: TreeKind[]; wood: Partial<Record<TreeKind, Wood>> };
trees?: { chance: number; kinds: string[]; wood: Record<string, string> };
}
export function biome_from_json(json: BiomeJson): Biome {
@@ -88,13 +88,6 @@ export function biome_season(id: string, time: number): Season {
return get_biome(id)?.season ?? calendar_season(farming_day(time));
}
// the logs and leaves a kind of tree grows in a biome
export function tree_wood(kind: TreeKind, biome: Biome): Wood {
const wood = biome.trees?.wood[kind];
if (wood) return wood;
return kind === "big_oak" ? "oak" : kind;
}
// the block ids a biome's json uses, for checking they exist
export function biome_blocks(json: BiomeJson): string[] {
const { top, filler, underwater_top, underwater_filler } = json.surface;
@@ -152,27 +145,16 @@ export function validate_biome(json: unknown): string[] {
if (typeof trees.chance !== "number" || trees.chance < 0 || trees.chance > 1) {
problems.push("trees.chance must be a number from 0 to 1");
}
if (!Array.isArray(trees.kinds) || trees.kinds.length === 0) {
// which kinds and woods there are is up to the trees feature, bworld's checks them when it loads
if (
!Array.isArray(trees.kinds) || trees.kinds.length === 0 ||
!trees.kinds.every((kind) => typeof kind === "string")
) {
problems.push("trees.kinds must list at least one kind of tree");
} else {
for (const kind of trees.kinds) {
if (!TREE_KINDS.includes(kind)) {
problems.push(`trees.kinds: ${kind} isn't one of ${TREE_KINDS.join(", ")}`);
}
}
}
if (trees.wood !== undefined) {
if (!is_object(trees.wood)) {
if (!is_object(trees.wood) || !Object.values(trees.wood).every((wood) => typeof wood === "string")) {
problems.push("trees.wood must be { <kind>: <wood> }");
} else {
for (const [kind, wood] of Object.entries(trees.wood)) {
if (!TREE_KINDS.includes(kind as TreeKind)) {
problems.push(`trees.wood: ${kind} isn't a kind of tree`);
}
if (!WOODS.includes(wood as Wood)) {
problems.push(`trees.wood.${kind} must be one of ${WOODS.join(", ")}`);
}
}
}
}
}
+543
View File
@@ -0,0 +1,543 @@
// world generation as data: noises, density functions, noise settings (a generator) and biome sources, see
// docs/modding/worldgen/terrain.md. checked here, compiled by density.ts and generator.ts. the names follow
// minecraft's (density functions, the noise router, surface rules) where the idea is the same
import { ID_PATTERN, TAG_ID_PATTERN } from "../mod_data.ts";
// ids of worldgen data can have folders, like "bworld:overworld/erosion"
export const WORLDGEN_ID_PATTERN = TAG_ID_PATTERN;
// noises
export interface NoiseJson {
id: string;
// what it's seeded with, with the world's seed. the id's path when not set
seed_name?: string;
// the size in blocks of the first octave's features. each octave after it is twice as fine
wavelength: number;
// each octave's strength, 0 skips one
amplitudes: number[];
// 2 (x and z) when not set, or 3
dimensions?: 2 | 3;
// 3d noises: how much slower it changes up and down than across
vertical_stretch?: number;
// the noise's measured percentiles, every 5% (tools/noise_quantiles.ts), for spreading it evenly from -1 to 1. or
// another noise's id to use its table, for noises with the same amplitudes
quantiles?: number[] | string;
}
// density functions: a number for every position. a number is a constant, a string is another density function's id
export type DensityJson = number | string | DensityObjectJson;
export interface DensityObjectJson {
type: string;
[field: string]: unknown;
}
// a file in worldgen/density_function: a density function with an id
export type DensityFunctionJson = DensityObjectJson & { id: string };
// a range of numbers, any bound can be left out. in range_choice a bound can also be a density function
export interface RangeJson {
min_inclusive?: number;
min_exclusive?: number;
max_inclusive?: number;
max_exclusive?: number;
}
export interface SplineJson {
coordinate: DensityJson;
points: { location: number; value: number | SplineJson; derivative?: number }[];
}
// noise settings: a generator
export interface NoiseSettingsJson {
id: string;
sea_level: number;
// what everything solid is made of, where the surface rule doesn't say otherwise
default_block: string;
// density is sampled every cell_width blocks across and each part's cell_height up, and blended in between
cell_width: number;
terrain: { density: DensityJson; cell_height: number };
// solid only where both terrain and caves are above 0
caves: { density: DensityJson; cell_height: number };
// the ground's height before 3d noise, for surface rules, biomes and finding things far away
preliminary_surface: DensityJson;
// named values biome rules read, like temperature
climate: Record<string, DensityJson>;
// a column is steep when its preliminary surface is this much higher or lower than a neighbor's
steep: number;
biome_source: string;
// what fills empty space, the first that applies
fluids: FluidJson[];
surface_rule: SurfaceRuleJson;
}
export interface FluidJson {
block: string;
// only below this y
below: number;
// "open_sky": nothing but air above, down from the top of the world. or where a density function is in a range
where: "open_sky" | ({ function: DensityJson } & RangeJson);
}
export type SurfaceRuleJson =
| { type: "sequence"; sequence: SurfaceRuleJson[] }
| { type: "condition"; if_true: SurfaceConditionJson; then_run: SurfaceRuleJson }
| { type: "block"; result_state: { Name: string } }
| { type: "biome_surface"; part: BiomeSurfacePart };
export const BIOME_SURFACE_PARTS = ["top", "filler", "underwater_top", "underwater_filler"] as const;
export type BiomeSurfacePart = typeof BIOME_SURFACE_PARTS[number];
export type SurfaceConditionJson =
// the solid blocks above it before air, 0 for the top one, is at most offset
| { type: "stone_depth"; offset: number }
// within the biome's filler_depth below the top
| { type: "filler_depth" }
// at or above the preliminary surface plus offset
| { type: "above_preliminary_surface"; offset?: number }
// the column's ground, the first solid block from the top, is below sea level - 1
| { type: "surface_underwater" }
| { type: "steep" }
// the biome's surface has bare_cliffs
| { type: "bare_cliffs" }
// at or above where a density function says
| { type: "y_at_least"; function: DensityJson }
| { type: "biome"; biome_is: string[] }
| { type: "not"; invert: SurfaceConditionJson };
// biome sources: which biome a column gets
export interface BiomeSourceJson {
id: string;
// adds its rules to another biome source, each before or after one of its rules
extends?: string;
rules: BiomeRuleJson[];
}
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
when?: Record<string, RangeJson | boolean>;
biome: string;
}
// what worldgen data refers to, for checking it all exists
export interface WorldgenRefs {
noises: Set<string>;
functions: Set<string>;
blocks: Set<string>;
biomes: Set<string>;
biome_sources: Set<string>;
}
export function new_refs(): WorldgenRefs {
return { noises: new Set(), functions: new Set(), blocks: new Set(), biomes: new Set(), biome_sources: new Set() };
}
const ARITHMETIC = ["add", "sub", "mul", "div", "min", "max"];
export const DENSITY_TYPES = [
"constant",
"x",
"y",
"z",
"noise",
...ARITHMETIC,
"abs",
"clamp",
"smoothstep",
"spline",
"range_choice",
"cache_2d",
];
const RANGE_KEYS = ["min_inclusive", "min_exclusive", "max_inclusive", "max_exclusive"] as const;
export function validate_noise(json: unknown): string[] {
const problems: string[] = [];
if (!is_object(json)) return ["noise must be an object"];
worldgen_id(json.id, "id", problems);
if (json.seed_name !== undefined && typeof json.seed_name !== "string") problems.push("seed_name must be text");
if (!(typeof json.wavelength === "number" && json.wavelength > 0)) problems.push("wavelength must be above 0");
if (
!Array.isArray(json.amplitudes) || json.amplitudes.length === 0 ||
!json.amplitudes.every((a) => typeof a === "number" && Number.isFinite(a)) ||
json.amplitudes.every((a) => a === 0)
) {
problems.push("amplitudes must be a list of numbers, not all 0");
}
if (json.dimensions !== undefined && json.dimensions !== 2 && json.dimensions !== 3) {
problems.push("dimensions must be 2 or 3");
}
if (json.vertical_stretch !== undefined) {
if (json.dimensions !== 3) problems.push("vertical_stretch is only for 3d noises");
if (!(typeof json.vertical_stretch === "number" && json.vertical_stretch > 0)) {
problems.push("vertical_stretch must be above 0");
}
}
const quantiles = json.quantiles;
if (quantiles !== undefined && typeof quantiles !== "string") {
if (
!Array.isArray(quantiles) || quantiles.length < 2 ||
!quantiles.every((q, i) => typeof q === "number" && (i === 0 || q > quantiles[i - 1]))
) {
problems.push("quantiles must be at least 2 numbers going up, or a noise's id");
}
} else if (typeof quantiles === "string") {
worldgen_id(quantiles, "quantiles", problems);
}
return problems;
}
// the noises a noise file refers to: the one it takes its quantiles from
export function noise_refs(json: NoiseJson, refs: WorldgenRefs) {
if (typeof json.quantiles === "string") refs.noises.add(json.quantiles);
}
export function validate_density_function(json: unknown): string[] {
if (!is_object(json)) return ["density_function must be an object"];
const problems: string[] = [];
worldgen_id(json.id, "id", problems);
const { id: _, ...fn } = json;
check_density(fn, "", new_refs(), problems);
return problems;
}
export function density_function_refs(json: DensityFunctionJson, refs: WorldgenRefs) {
const { id: _, ...fn } = json;
check_density(fn, "", refs, []);
}
// checks a density function, adding what it refers to to refs. at is where it is, for messages
export function check_density(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
const where = at ? `${at}: ` : "";
if (typeof json === "number") {
if (!Number.isFinite(json)) problems.push(`${where}must be a finite number`);
return;
}
if (typeof json === "string") {
if (WORLDGEN_ID_PATTERN.test(json)) refs.functions.add(json);
else problems.push(`${where}"${json}" isn't a density function's id`);
return;
}
if (!is_object(json) || typeof json.type !== "string") {
problems.push(`${where}must be a number, a density function's id or { "type": ... }`);
return;
}
const field = (name: string) => check_density(json[name], at ? `${at}.${name}` : name, refs, problems);
const number = (name: string) => {
if (typeof json[name] !== "number" || !Number.isFinite(json[name])) {
problems.push(`${where}${name} must be a number`);
}
};
switch (json.type) {
case "constant":
number("argument");
break;
case "x":
case "y":
case "z":
break;
case "noise":
if (typeof json.noise === "string" && WORLDGEN_ID_PATTERN.test(json.noise)) refs.noises.add(json.noise);
else problems.push(`${where}noise must be a noise's id`);
if (json.even !== undefined && typeof json.even !== "boolean") {
problems.push(`${where}even must be true or false`);
}
for (const axis of ["x", "y", "z"]) if (json[axis] !== undefined) field(axis);
break;
case "abs":
case "cache_2d":
field("argument");
break;
case "clamp":
field("input");
number("min");
number("max");
if ((json.min as number) > (json.max as number)) problems.push(`${where}min is above max`);
break;
case "smoothstep":
field("input");
number("from");
number("to");
if (json.from === json.to) problems.push(`${where}from and to must be different`);
break;
case "spline":
check_spline(json.spline, at ? `${at}.spline` : "spline", refs, problems);
break;
case "range_choice":
field("input");
if (!RANGE_KEYS.some((key) => json[key] !== undefined)) problems.push(`${where}needs at least one bound`);
for (const key of RANGE_KEYS) if (json[key] !== undefined) field(key);
field("when_in_range");
field("when_out_of_range");
break;
default:
if (ARITHMETIC.includes(json.type)) {
field("argument1");
field("argument2");
} else {
problems.push(`${where}type ${json.type} isn't one of ${DENSITY_TYPES.join(", ")}`);
}
}
}
function check_spline(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
if (!is_object(json) || !Array.isArray(json.points) || json.points.length === 0) {
problems.push(`${at}: must be { "coordinate": ..., "points": [ ... ] }`);
return;
}
check_density(json.coordinate, `${at}.coordinate`, refs, problems);
let last = -Infinity;
json.points.forEach((point: unknown, i: number) => {
const here = `${at}.points[${i}]`;
if (!is_object(point) || typeof point.location !== "number") {
problems.push(`${here}: must be { "location", "value", "derivative" }`);
return;
}
if (point.location < last) problems.push(`${here}: locations must go up`);
last = point.location;
if (typeof point.value !== "number") check_spline(point.value, `${here}.value`, refs, problems);
if (point.derivative !== undefined && typeof point.derivative !== "number") {
problems.push(`${here}: derivative must be a number`);
}
});
}
export function validate_noise_settings(json: unknown): string[] {
if (!is_object(json)) return ["noise_settings must be an object"];
const problems: string[] = [];
noise_settings_refs(json, new_refs(), problems);
return problems;
}
export function noise_settings_refs(json: Record<string, unknown>, refs: WorldgenRefs, problems: string[] = []) {
worldgen_id(json.id, "id", problems);
const whole = (name: string, min: number, max: number) => {
const value = json[name];
if (!(Number.isInteger(value) && (value as number) >= min && (value as number) <= max)) {
problems.push(`${name} must be a whole number from ${min} to ${max}`);
}
};
whole("sea_level", 0, 256);
block_id(json.default_block, "default_block", refs, problems);
if (![1, 2, 4, 8, 16].includes(json.cell_width as number)) problems.push("cell_width must be 1, 2, 4, 8 or 16");
for (const part of ["terrain", "caves"]) {
const value = json[part];
if (!is_object(value)) {
problems.push(`${part} must be { "density", "cell_height" }`);
continue;
}
check_density(value.density, `${part}.density`, refs, problems);
if (![1, 2, 4, 8, 16, 32].includes(value.cell_height as number)) {
problems.push(`${part}.cell_height must be 1, 2, 4, 8, 16 or 32`);
}
}
check_density(json.preliminary_surface, "preliminary_surface", refs, problems);
if (!is_object(json.climate)) {
problems.push("climate must be { <name>: <density function> }");
} else {
for (const [name, value] of Object.entries(json.climate)) {
if (!/^[a-z_]+$/.test(name) || name === "surface" || name === "steep") {
problems.push(`climate.${name}: names are lowercase letters and _, and not surface or steep`);
}
check_density(value, `climate.${name}`, refs, problems);
}
}
if (!(typeof json.steep === "number" && json.steep >= 0)) problems.push("steep must be a number, 0 or more");
if (typeof json.biome_source === "string" && WORLDGEN_ID_PATTERN.test(json.biome_source)) {
refs.biome_sources.add(json.biome_source);
} else {
problems.push("biome_source must be a biome source's id");
}
if (!Array.isArray(json.fluids)) {
problems.push("fluids must be a list");
} else {
json.fluids.forEach((fluid: unknown, i: number) => {
const at = `fluids[${i}]`;
if (!is_object(fluid)) {
problems.push(`${at}: must be { "block", "below", "where" }`);
return;
}
block_id(fluid.block, `${at}.block`, refs, problems);
if (!Number.isInteger(fluid.below)) problems.push(`${at}.below must be a whole number`);
if (fluid.where !== "open_sky") {
if (!is_object(fluid.where)) {
problems.push(`${at}.where must be "open_sky" or { "function", <range> }`);
} else {
check_density(fluid.where.function, `${at}.where.function`, refs, problems);
check_range(fluid.where, `${at}.where`, problems);
}
}
});
}
check_surface_rule(json.surface_rule, "surface_rule", refs, problems);
}
function check_surface_rule(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at}: must be a rule`);
return;
}
switch (json.type) {
case "sequence":
if (!Array.isArray(json.sequence)) problems.push(`${at}.sequence must be a list of rules`);
else json.sequence.forEach((rule, i) => check_surface_rule(rule, `${at}.sequence[${i}]`, refs, problems));
break;
case "condition":
check_surface_condition(json.if_true, `${at}.if_true`, refs, problems);
check_surface_rule(json.then_run, `${at}.then_run`, refs, problems);
break;
case "block":
if (!is_object(json.result_state)) problems.push(`${at}.result_state must be { "Name": <block> }`);
else block_id(json.result_state.Name, `${at}.result_state.Name`, refs, problems);
break;
case "biome_surface":
if (!BIOME_SURFACE_PARTS.includes(json.part as BiomeSurfacePart)) {
problems.push(`${at}.part must be one of ${BIOME_SURFACE_PARTS.join(", ")}`);
}
break;
default:
problems.push(`${at}: type must be sequence, condition, block or biome_surface`);
}
}
function check_surface_condition(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at}: must be a condition`);
return;
}
switch (json.type) {
case "stone_depth":
if (!Number.isInteger(json.offset)) problems.push(`${at}.offset must be a whole number`);
break;
case "above_preliminary_surface":
if (json.offset !== undefined && typeof json.offset !== "number") {
problems.push(`${at}.offset must be a number`);
}
break;
case "filler_depth":
case "surface_underwater":
case "steep":
case "bare_cliffs":
break;
case "y_at_least":
check_density(json.function, `${at}.function`, refs, problems);
break;
case "biome":
if (!Array.isArray(json.biome_is) || !json.biome_is.every((b) => typeof b === "string")) {
problems.push(`${at}.biome_is must be a list of biome ids`);
} else {
for (const biome of json.biome_is) refs.biomes.add(biome);
}
break;
case "not":
check_surface_condition(json.invert, `${at}.invert`, refs, problems);
break;
default:
problems.push(
`${at}: type must be stone_depth, filler_depth, above_preliminary_surface, surface_underwater, steep, ` +
`bare_cliffs, y_at_least, biome or not`,
);
}
}
export function validate_biome_source(json: unknown): string[] {
if (!is_object(json)) return ["biome_source must be an object"];
const problems: string[] = [];
biome_source_refs(json, new_refs(), problems);
return problems;
}
export function biome_source_refs(json: Record<string, unknown>, refs: WorldgenRefs, problems: string[] = []) {
worldgen_id(json.id, "id", problems);
if (json.extends !== undefined) {
if (typeof json.extends === "string" && WORLDGEN_ID_PATTERN.test(json.extends)) {
refs.biome_sources.add(json.extends);
} else problems.push("extends must be a biome source's id");
}
if (!Array.isArray(json.rules)) {
problems.push("rules must be a list");
return;
}
json.rules.forEach((rule: unknown, i: number) => {
const at = `rules[${i}]`;
if (!is_object(rule)) {
problems.push(`${at}: must be { "id", "when", "biome" }`);
return;
}
worldgen_id(rule.id, `${at}.id`, problems);
const placed = [rule.before, rule.after].filter((id) => id !== undefined);
if (json.extends !== undefined && placed.length !== 1) {
problems.push(`${at}: a rule added to another biome source needs before or after, one of them`);
}
if (json.extends === undefined && placed.length > 0) {
problems.push(`${at}: before and after are for rules added to another biome source, with extends`);
}
for (const id of placed) worldgen_id(id, `${at}.before/after`, problems);
if (typeof rule.biome === "string" && ID_PATTERN.test(rule.biome)) refs.biomes.add(rule.biome);
else problems.push(`${at}.biome must be a biome's id`);
if (rule.when !== undefined) {
if (!is_object(rule.when)) {
problems.push(`${at}.when must be { <climate value>: <range>, "steep": true or false }`);
} else {
for (const [name, condition] of Object.entries(rule.when)) {
if (name === "steep") {
if (typeof condition !== "boolean") problems.push(`${at}.when.steep must be true or false`);
} else {
check_range(condition, `${at}.when.${name}`, problems);
}
}
}
}
});
}
// a range of numbers, with at least one bound
function check_range(json: unknown, at: string, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at} must be a range like { "min_inclusive": 0 }`);
return;
}
let bounds = 0;
for (const key of RANGE_KEYS) {
if (json[key] === undefined) continue;
bounds++;
if (typeof json[key] !== "number") problems.push(`${at}.${key} must be a number`);
}
if (bounds === 0) problems.push(`${at} needs at least one of ${RANGE_KEYS.join(", ")}`);
}
// a test of whether a value is in the range, with only the bounds it has: value >= min, value < max
export function range_test(range: RangeJson): (value: number) => boolean {
const tests: ((value: number) => boolean)[] = [];
const { min_inclusive, min_exclusive, max_inclusive, max_exclusive } = range;
if (min_inclusive !== undefined) tests.push((value) => value >= min_inclusive);
if (min_exclusive !== undefined) tests.push((value) => value > min_exclusive);
if (max_inclusive !== undefined) tests.push((value) => value <= max_inclusive);
if (max_exclusive !== undefined) tests.push((value) => value < max_exclusive);
if (tests.length === 1) return tests[0];
if (tests.length === 2) {
const [a, b] = tests;
return (value) => a(value) && b(value);
}
return (value) => tests.every((test) => test(value));
}
function worldgen_id(value: unknown, field: string, problems: string[]) {
if (!(typeof value === "string" && WORLDGEN_ID_PATTERN.test(value))) {
problems.push(`${field} must be an id like "my_mod:thing" or "my_mod:folder/thing"`);
}
}
function block_id(value: unknown, field: string, refs: WorldgenRefs, problems: string[]) {
if (typeof value === "string" && ID_PATTERN.test(value)) refs.blocks.add(value);
else problems.push(`${field} must be a block's id`);
}
function is_object(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+342
View File
@@ -0,0 +1,342 @@
// compiles density functions (see data.ts) into plain closures, once per seed, so generating a chunk never reads json.
// every operation is a pair, so it rounds exactly like the code it was written from: a world generated from the same
// data is the same block for block. named functions that don't change with y are worked out once per column
import { clamp, OctaveNoise2D, OctaveNoise3D, Quantiles, smoothstep } from "./noise.ts";
import type { DensityFunctionJson, DensityJson, DensityObjectJson, NoiseJson, SplineJson } from "./data.ts";
// a density function's value at a block
export type Density = (x: number, y: number, z: number) => number;
// where named noises and density functions come from
export interface DensitySources {
noise(id: string): NoiseJson | undefined;
function(id: string): DensityFunctionJson | undefined;
}
interface CompiledNoise {
json: NoiseJson;
sample2?: OctaveNoise2D;
sample3?: OctaveNoise3D;
quantiles?: Quantiles;
}
const X: Density = (x) => x;
const Y: Density = (_x, y) => y;
const Z: Density = (_x, _y, z) => z;
export class DensityCompiler {
readonly seed: string;
#sources: DensitySources;
#functions = new Map<string, Density>();
#noises = new Map<string, CompiledNoise>();
#varies_with_y = new Map<string, boolean>();
// named functions being compiled, to find ones that use themselves
#compiling: string[] = [];
constructor(seed: string, sources: DensitySources) {
this.seed = seed;
this.#sources = sources;
}
compile(json: DensityJson): Density {
if (typeof json === "number") return () => json;
if (typeof json === "string") return this.#named(json);
return this.#object(json);
}
// a named density function, compiled once. one that's the same all the way up a column is cached per column
#named(id: string): Density {
const done = this.#functions.get(id);
if (done) return done;
const json = this.#sources.function(id);
if (!json) throw new Error(`density function ${id} doesn't exist`);
if (this.#compiling.includes(id)) {
throw new Error(`density function ${id} uses itself: ${[...this.#compiling, id].join(" -> ")}`);
}
this.#compiling.push(id);
const { id: _, ...fn } = json;
const inner = this.#object(fn as DensityObjectJson);
this.#compiling.pop();
const compiled = this.varies_with_y(id) ? inner : per_column(inner);
this.#functions.set(id, compiled);
return compiled;
}
// whether a density function can be different at different heights of the same column
varies_with_y(json: DensityJson): boolean {
if (typeof json === "number") return false;
if (typeof json === "string") {
let varies = this.#varies_with_y.get(json);
if (varies === undefined) {
const named = this.#sources.function(json);
if (!named) throw new Error(`density function ${json} doesn't exist`);
// a loop is reported by #named, assume no while looking
this.#varies_with_y.set(json, false);
const { id: _, ...fn } = named;
varies = this.varies_with_y(fn as DensityObjectJson);
this.#varies_with_y.set(json, varies);
}
return varies;
}
switch (json.type) {
case "y":
return true;
case "noise": {
const axes = ["x", "z"].map((axis) =>
json[axis] !== undefined && this.varies_with_y(json[axis] as DensityJson)
);
if (axes.some((v) => v)) return true;
if (this.#noise(json.noise as string).json.dimensions !== 3) return false;
return json.y === undefined || this.varies_with_y(json.y as DensityJson);
}
case "spline":
return this.#spline_varies(json.spline as SplineJson);
default:
return Object.entries(json).some(([key, value]) =>
key !== "type" && (typeof value === "string" || typeof value === "object") && value !== null &&
!Array.isArray(value) && this.varies_with_y(value as DensityJson)
);
}
}
#spline_varies(spline: SplineJson): boolean {
return this.varies_with_y(spline.coordinate) ||
spline.points.some((point) => typeof point.value !== "number" && this.#spline_varies(point.value));
}
#object(json: DensityObjectJson): Density {
const field = (name: string) => this.compile(json[name] as DensityJson);
switch (json.type) {
case "constant": {
const value = json.argument as number;
return () => value;
}
case "x":
return X;
case "y":
return Y;
case "z":
return Z;
case "noise":
return this.#noise_function(json);
case "add":
case "sub":
case "mul":
case "div":
case "min":
case "max":
return arithmetic(json.type, json.argument1 as DensityJson, json.argument2 as DensityJson, this);
case "abs": {
const argument = field("argument");
return (x, y, z) => Math.abs(argument(x, y, z));
}
case "clamp": {
const input = field("input");
const min = json.min as number;
const max = json.max as number;
return (x, y, z) => clamp(input(x, y, z), min, max);
}
case "smoothstep": {
const input = field("input");
const from = json.from as number;
const to = json.to as number;
return (x, y, z) => smoothstep(from, to, input(x, y, z));
}
case "spline":
return this.#spline(json.spline as SplineJson);
case "range_choice":
return this.#range_choice(json);
case "cache_2d": {
if (this.varies_with_y(json.argument as DensityJson)) {
throw new Error("cache_2d around a density function that changes with y");
}
return per_column(field("argument"));
}
default:
throw new Error(`density function type ${json.type} doesn't exist`);
}
}
#noise(id: string): CompiledNoise {
let noise = this.#noises.get(id);
if (noise) return noise;
const json = this.#sources.noise(id);
if (!json) throw new Error(`noise ${id} doesn't exist`);
const name = json.seed_name ?? id.slice(id.indexOf(":") + 1);
noise = json.dimensions === 3
? {
json,
sample3: new OctaveNoise3D(this.seed, name, json.wavelength, json.amplitudes, json.vertical_stretch),
}
: { json, sample2: new OctaveNoise2D(this.seed, name, json.wavelength, json.amplitudes) };
this.#noises.set(id, noise);
noise.quantiles = this.#quantiles(id, []);
return noise;
}
// a noise's quantile table, or the one of the noise it names
#quantiles(id: string, seen: string[]): Quantiles | undefined {
const json = this.#sources.noise(id);
if (!json) throw new Error(`noise ${seen.at(-1) ?? id} takes its quantiles from ${id}, which doesn't exist`);
if (json.quantiles === undefined) return undefined;
if (typeof json.quantiles !== "string") return new Quantiles(json.quantiles);
if (seen.includes(id)) throw new Error(`noise ${id}'s quantiles go round in a loop`);
return this.#quantiles(json.quantiles, [...seen, id]);
}
#noise_function(json: DensityObjectJson): Density {
const noise = this.#noise(json.noise as string);
const even = json.even === true;
if (even && !noise.quantiles) throw new Error(`noise ${json.noise} has no quantiles to be spread evenly with`);
const quantiles = noise.quantiles!;
const axis = (name: string, plain: Density) =>
json[name] === undefined ? plain : this.compile(json[name] as DensityJson);
const plain = json.x === undefined && json.y === undefined && json.z === undefined;
if (noise.sample2) {
const n = noise.sample2;
if (plain) return even ? (x, _y, z) => quantiles.even(n.sample(x, z)) : (x, _y, z) => n.sample(x, z);
const fx = axis("x", X);
const fz = axis("z", Z);
return even
? (x, y, z) => quantiles.even(n.sample(fx(x, y, z), fz(x, y, z)))
: (x, y, z) => n.sample(fx(x, y, z), fz(x, y, z));
}
const n = noise.sample3!;
if (plain) return even ? (x, y, z) => quantiles.even(n.sample(x, y, z)) : (x, y, z) => n.sample(x, y, z);
const fx = axis("x", X);
const fy = axis("y", Y);
const fz = axis("z", Z);
return even
? (x, y, z) => quantiles.even(n.sample(fx(x, y, z), fy(x, y, z), fz(x, y, z)))
: (x, y, z) => n.sample(fx(x, y, z), fy(x, y, z), fz(x, y, z));
}
// minecraft's CubicSpline: a smooth curve through points, where a point's value can itself be a spline of another
// coordinate. that nesting is how the terrain turns continentalness, erosion and ridges into heights
#spline(json: SplineJson): Density {
const coordinate = this.compile(json.coordinate);
const locations = json.points.map((point) => point.location);
const values = json.points.map((point) =>
typeof point.value === "number" ? point.value : this.#spline(point.value)
);
const slopes = json.points.map((point) => point.derivative ?? 0);
const last = locations.length - 1;
const value_of = (i: number, x: number, y: number, z: number) => {
const value = values[i];
return typeof value === "number" ? value : value(x, y, z);
};
return (x, y, z) => {
const c = coordinate(x, y, z);
if (c <= locations[0]) {
return value_of(0, x, y, z) + slopes[0] * (c - locations[0]);
}
if (c >= locations[last]) {
return value_of(last, x, y, z) + slopes[last] * (c - locations[last]);
}
let i = 0;
while (locations[i + 1] < c) i++;
const x0 = locations[i];
const x1 = locations[i + 1];
const width = x1 - x0;
const t = (c - x0) / width;
const y0 = value_of(i, x, y, z);
const y1 = value_of(i + 1, x, y, z);
// hermite interpolation, written the way minecraft does it
const a = slopes[i] * width - (y1 - y0);
const b = -slopes[i + 1] * width + (y1 - y0);
return y0 + (y1 - y0) * t + t * (1 - t) * (a + (b - a) * t);
};
}
// one function or the other, by whether the input is within bounds, which can themselves be density functions
#range_choice(json: DensityObjectJson): Density {
const input = this.compile(json.input as DensityJson);
const inside = this.compile(json.when_in_range as DensityJson);
const outside = this.compile(json.when_out_of_range as DensityJson);
const bound = (name: string) => json[name] === undefined ? undefined : this.compile(json[name] as DensityJson);
const min_inclusive = bound("min_inclusive");
const min_exclusive = bound("min_exclusive");
const max_inclusive = bound("max_inclusive");
const max_exclusive = bound("max_exclusive");
return (x, y, z) => {
const value = input(x, y, z);
const within = (min_inclusive === undefined || value >= min_inclusive(x, y, z)) &&
(min_exclusive === undefined || value > min_exclusive(x, y, z)) &&
(max_inclusive === undefined || value <= max_inclusive(x, y, z)) &&
(max_exclusive === undefined || value < max_exclusive(x, y, z));
return within ? inside(x, y, z) : outside(x, y, z);
};
}
}
// remembers the last column's value, like minecraft's cache_2d. columns are generated one after another
function per_column(inner: Density): Density {
let last_x = NaN;
let last_z = NaN;
let last = 0;
return (x, y, z) => {
if (x === last_x && z === last_z) return last;
last = inner(x, y, z);
last_x = x;
last_z = z;
return last;
};
}
// a pair of arguments, with a number folded in instead of called, and two numbers worked out once
function arithmetic(type: string, first: DensityJson, second: DensityJson, compiler: DensityCompiler): Density {
const op = OPERATIONS[type];
if (typeof first === "number" && typeof second === "number") {
const value = op(first, second);
return () => value;
}
if (typeof second === "number") {
const a = compiler.compile(first);
switch (type) {
case "add":
return (x, y, z) => a(x, y, z) + second;
case "sub":
return (x, y, z) => a(x, y, z) - second;
case "mul":
return (x, y, z) => a(x, y, z) * second;
case "div":
return (x, y, z) => a(x, y, z) / second;
}
}
if (typeof first === "number") {
const b = compiler.compile(second);
switch (type) {
case "add":
return (x, y, z) => first + b(x, y, z);
case "sub":
return (x, y, z) => first - b(x, y, z);
case "mul":
return (x, y, z) => first * b(x, y, z);
case "div":
return (x, y, z) => first / b(x, y, z);
}
}
const a = compiler.compile(first);
const b = compiler.compile(second);
switch (type) {
case "add":
return (x, y, z) => a(x, y, z) + b(x, y, z);
case "sub":
return (x, y, z) => a(x, y, z) - b(x, y, z);
case "mul":
return (x, y, z) => a(x, y, z) * b(x, y, z);
case "div":
return (x, y, z) => a(x, y, z) / b(x, y, z);
default:
return (x, y, z) => op(a(x, y, z), b(x, y, z));
}
}
const OPERATIONS: Record<string, (a: number, b: number) => number> = {
add: (a, b) => a + b,
sub: (a, b) => a - b,
mul: (a, b) => a * b,
div: (a, b) => a / b,
min: (a, b) => Math.min(a, b),
max: (a, b) => Math.max(a, b),
};
+601
View File
@@ -0,0 +1,601 @@
// data features: worldgen/features/<path>.json in a mod, a feature's type and config (what) with a list of placement
// modifiers (where), see docs/modding/worldgen/index.md. like minecraft's configured and placed features joined into
// one file. the types and modifiers here are built in, worldgen scripts register more
import { EverythingRegistry } from "../everything_registry.ts";
import type { BlockRegistry } from "../everything_registry.ts";
import { CHUNK_HEIGHT, CHUNK_SIZE } from "../constants.ts";
import { ID_PATTERN, TAG_ID_PATTERN } from "../mod_data.ts";
import { list_matches } from "../tags.ts";
import { can_stand_on } from "../utils.ts";
import { AIR_ID } from "../protocol.ts";
import type { FeatureChunk, FeatureStep, Position } from "../mod_api/worldgen.ts";
// the order features run in, minecraft's decoration steps. a feature without a step runs in the last
export const FEATURE_STEPS: FeatureStep[] = [
"raw_generation",
"lakes",
"local_modifications",
"underground_structures",
"surface_structures",
"strongholds",
"underground_ores",
"underground_decoration",
"fluid_springs",
"vegetal_decoration",
"top_layer_modification",
];
export const DEFAULT_STEP: FeatureStep = "top_layer_modification";
export interface FeatureJson {
id: string;
// a built in type, like "minecraft:block_column", or one a worldgen script registers
type: string;
config?: Record<string, unknown>;
placement?: PlacementJson[];
// only where the column is one of these biomes
biomes?: string | string[];
step?: FeatureStep;
}
export interface PlacementJson {
type: string;
[field: string]: unknown;
}
// a type of feature: places config at origin with the chunk's random numbers, returns whether it placed anything
export type FeatureType = (chunk: FeatureChunk, config: unknown, origin: Position) => boolean;
// a placement modifier: the positions after it, from the ones before
export type PlacementModifier = (chunk: FeatureChunk, config: unknown, positions: Position[]) => Position[];
// a built in name without its namespace, so "minecraft:count" and "count" are the same. undefined for a mod's own
export function builtin_name(type: string): string | undefined {
if (!type.includes(":")) return type;
return type.startsWith("minecraft:") ? type.slice("minecraft:".length) : undefined;
}
// checking
// what a feature uses, for check-mods
export interface FeatureRefs {
blocks: Set<string>;
biomes: Set<string>;
// types and modifiers that aren't built in, which a worldgen script has to register
custom: Set<string>;
}
export function validate_feature(json: unknown): string[] {
const problems: string[] = [];
feature_refs(json, { blocks: new Set(), biomes: new Set(), custom: new Set() }, problems);
return problems;
}
export function feature_refs(json: unknown, refs: FeatureRefs, problems: string[] = []) {
if (!is_object(json)) {
problems.push("feature must be an object");
return;
}
if (!(typeof json.id === "string" && TAG_ID_PATTERN.test(json.id))) {
problems.push(`id must be an id like "my_mod:thing" or "my_mod:folder/thing"`);
}
if (json.step !== undefined && !FEATURE_STEPS.includes(json.step as FeatureStep)) {
problems.push(`step must be one of ${FEATURE_STEPS.join(", ")}`);
}
if (json.biomes !== undefined) {
const biomes = typeof json.biomes === "string" ? [json.biomes] : json.biomes;
if (!Array.isArray(biomes) || !biomes.every((b) => typeof b === "string" && ID_PATTERN.test(b))) {
problems.push("biomes must be a biome's id or a list of them");
} else {
for (const biome of biomes) refs.biomes.add(biome);
}
}
if (json.config !== undefined && !is_object(json.config)) problems.push("config must be an object");
if (typeof json.type !== "string") {
problems.push("type must be a feature type");
} else {
const name = builtin_name(json.type);
if (name === undefined) refs.custom.add(json.type);
else if (!(name in FEATURE_TYPES)) problems.push(`type ${json.type} isn't built in`);
else FEATURE_TYPES[name].check((json.config ?? {}) as Record<string, unknown>, "config", refs, problems);
}
if (json.placement !== undefined) {
if (!Array.isArray(json.placement)) {
problems.push("placement must be a list of placement modifiers");
return;
}
json.placement.forEach((modifier: unknown, i: number) => {
const at = `placement[${i}]`;
if (!is_object(modifier) || typeof modifier.type !== "string") {
problems.push(`${at}: must be { "type": ... }`);
return;
}
const name = builtin_name(modifier.type);
if (name === undefined) refs.custom.add(modifier.type);
else if (!(name in MODIFIERS)) problems.push(`${at}: ${modifier.type} isn't a built in placement modifier`);
else MODIFIERS[name].check(modifier, at, refs, problems);
});
}
}
// compiling: a data feature becomes a function of the chunk, run with the chunk's random numbers
export interface CompiledFeature {
// where it runs, then what it places at each position
generate(chunk: FeatureChunk): void;
// what chunk.place_feature does: its type and config at a position, without its placement
place(chunk: FeatureChunk, origin: Position): boolean;
}
export function compile_feature(
json: FeatureJson,
types: Map<string, FeatureType>,
modifiers: Map<string, PlacementModifier>,
): CompiledFeature {
const config = json.config ?? {};
const builtin = builtin_name(json.type);
let place: (chunk: FeatureChunk, origin: Position) => boolean;
if (builtin !== undefined) {
place = FEATURE_TYPES[builtin].compile(config);
} else {
const type = types.get(json.type);
if (!type) {
throw new Error(
`feature ${json.id}: type ${json.type} isn't built in, and no worldgen script registered it`,
);
}
place = (chunk, origin) => type(chunk, config, origin);
}
const steps = (json.placement ?? []).map((modifier, i) => {
const name = builtin_name(modifier.type);
if (name !== undefined) return MODIFIERS[name].compile(modifier);
const custom = modifiers.get(modifier.type);
if (!custom) {
throw new Error(
`feature ${json.id}: placement[${i}] ${modifier.type} isn't built in, and no worldgen script registered it`,
);
}
return (chunk: FeatureChunk, positions: Position[]) => custom(chunk, modifier, positions);
});
const biomes = json.biomes === undefined
? undefined
: new Set(typeof json.biomes === "string" ? [json.biomes] : json.biomes);
return {
place,
generate(chunk) {
// minecraft's origin: the chunk's corner at the bottom of the world
let positions: Position[] = [{ x: chunk.x * CHUNK_SIZE, y: 0, z: chunk.z * CHUNK_SIZE }];
for (const step of steps) positions = step(chunk, positions);
for (const position of positions) {
if (
biomes &&
!(inside(chunk, position.x, position.z) && biomes.has(chunk.biome_at(position.x, position.z)))
) {
continue;
}
place(chunk, position);
}
},
};
}
// built in feature types
interface Builtin<T> {
check(json: Record<string, unknown>, at: string, refs: FeatureRefs, problems: string[]): void;
compile(json: Record<string, unknown>): T;
}
const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Position) => boolean>> = {
// one block, where it can stand
simple_block: {
check(json, at, refs, problems) {
check_state(json.to_place, `${at}.to_place`, refs, problems);
},
compile(json) {
const id = state_id(json.to_place);
return (chunk, { x, y, z }) => {
if (!survives(chunk, id, x, y, z)) return false;
chunk.set_block(x, y, z, id);
return true;
};
},
},
// layers of blocks stacked up (or down) from the origin, cut short where allowed_placement doesn't hold
block_column: {
check(json, at, refs, problems) {
if (!Array.isArray(json.layers) || json.layers.length === 0) {
problems.push(`${at}.layers must be a list of { "height", "provider" }`);
} else {
json.layers.forEach((layer: unknown, i: number) => {
const here = `${at}.layers[${i}]`;
if (!is_object(layer)) {
problems.push(`${here} must be { "height", "provider" }`);
return;
}
check_int(layer.height, `${here}.height`, problems);
check_state(layer.provider, `${here}.provider`, refs, problems);
});
}
if (json.direction !== undefined && json.direction !== "up" && json.direction !== "down") {
problems.push(`${at}.direction must be "up" or "down"`);
}
if (json.allowed_placement !== undefined) {
check_predicate(json.allowed_placement, `${at}.allowed_placement`, refs, problems);
}
if (json.prioritize_tip !== undefined && typeof json.prioritize_tip !== "boolean") {
problems.push(`${at}.prioritize_tip must be true or false`);
}
},
compile(json) {
const layers = (json.layers as { height: unknown; provider: unknown }[]).map((layer) => ({
height: int_provider(layer.height),
id: state_id(layer.provider),
}));
const dy = json.direction === "down" ? -1 : 1;
const allowed = json.allowed_placement === undefined
? (chunk: FeatureChunk, x: number, y: number, z: number) => block_at(chunk, x, y, z) === AIR_ID
: block_predicate(json.allowed_placement);
const tip_first = json.prioritize_tip === true;
return (chunk, { x, y, z }) => {
const column: string[] = [];
for (const layer of layers) {
const height = layer.height(chunk);
for (let i = 0; i < height; i++) column.push(layer.id);
}
let fits = 0;
while (fits < column.length && allowed(chunk, x, y + fits * dy, z)) fits++;
if (fits === 0) return false;
const placed = tip_first ? column.slice(column.length - fits) : column.slice(0, fits);
placed.forEach((id, i) => chunk.set_block(x, y + i * dy, z, id));
return true;
};
},
},
};
// built in placement modifiers
type Modifier = (chunk: FeatureChunk, positions: Position[]) => Position[];
const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"];
const MODIFIERS: Record<string, Builtin<Modifier>> = {
// each position becomes count of them
count: {
check(json, at, _refs, problems) {
check_int(json.count, `${at}.count`, problems);
},
compile(json) {
const count = int_provider(json.count);
return (chunk, positions) =>
positions.flatMap((p) => Array.from({ length: count(chunk) }, () => ({ ...p })));
},
},
// one in chance positions are kept
rarity_filter: {
check(json, at, _refs, problems) {
if (!(Number.isInteger(json.chance) && (json.chance as number) >= 1)) {
problems.push(`${at}.chance must be a whole number, 1 or more`);
}
},
compile(json) {
const chance = json.chance as number;
return (chunk, positions) => positions.filter(() => chunk.rng.next() < 1 / chance);
},
},
// somewhere random in the chunk, across
in_square: {
check() {},
compile() {
return (chunk, positions) =>
positions.map((p) => {
const x = p.x + Math.floor(chunk.rng.next() * CHUNK_SIZE);
const z = p.z + Math.floor(chunk.rng.next() * CHUNK_SIZE);
return { x, y: p.y, z };
});
},
},
// moved by up to xz_spread across and y_spread up or down
random_offset: {
check(json, at, _refs, problems) {
check_int(json.xz_spread ?? 0, `${at}.xz_spread`, problems);
check_int(json.y_spread ?? 0, `${at}.y_spread`, problems);
},
compile(json) {
const xz = int_provider(json.xz_spread ?? 0);
const y = int_provider(json.y_spread ?? 0);
return (chunk, positions) =>
positions.map((p) => ({ x: p.x + xz(chunk), y: p.y + y(chunk), z: p.z + xz(chunk) }));
},
},
// at a height
height_range: {
check(json, at, _refs, problems) {
check_height(json.height, `${at}.height`, problems);
},
compile(json) {
const height = height_provider(json.height);
return (chunk, positions) => positions.map((p) => ({ x: p.x, y: height(chunk), z: p.z }));
},
},
// on top of the column: WORLD_SURFACE on its highest block, OCEAN_FLOOR on its highest that isn't a liquid.
// positions outside the chunk are dropped
heightmap: {
check(json, at, _refs, problems) {
if (!HEIGHTMAPS.includes(json.heightmap as string)) {
problems.push(`${at}.heightmap must be one of ${HEIGHTMAPS.join(", ")}`);
}
},
compile(json) {
const floor = String(json.heightmap).startsWith("OCEAN_FLOOR");
return (chunk, positions) =>
positions.flatMap((p) => {
if (!inside(chunk, p.x, p.z)) return [];
let y = CHUNK_HEIGHT - 1;
while (y >= 0 && !counts_for_heightmap(chunk.get_block(p.x, y, p.z), floor)) y--;
return [{ x: p.x, y: y + 1, z: p.z }];
});
},
},
// where a block predicate holds
block_predicate_filter: {
check(json, at, refs, problems) {
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
},
compile(json) {
const predicate = block_predicate(json.predicate);
return (chunk, positions) => positions.filter((p) => predicate(chunk, p.x, p.y, p.z));
},
},
};
function counts_for_heightmap(id: string | undefined, floor: boolean) {
if (id === undefined || id === AIR_ID) return false;
return !floor || !EverythingRegistry.get<BlockRegistry>("blocks", id)?.liquid;
}
// block predicates, like minecraft's
type Predicate = (chunk: FeatureChunk, x: number, y: number, z: number) => boolean;
const PREDICATES = ["matching_blocks", "solid", "replaceable", "would_survive", "not", "all_of", "any_of", "true"];
function check_predicate(json: unknown, at: string, refs: FeatureRefs, problems: string[]) {
if (!is_object(json) || typeof json.type !== "string") {
problems.push(`${at} must be a block predicate, { "type": ... }`);
return;
}
const name = builtin_name(json.type);
if (name === undefined || !PREDICATES.includes(name)) {
problems.push(`${at}: ${json.type} isn't one of ${PREDICATES.join(", ")}`);
return;
}
if (
json.offset !== undefined &&
!(Array.isArray(json.offset) && json.offset.length === 3 && json.offset.every(Number.isInteger))
) {
problems.push(`${at}.offset must be [x, y, z], whole numbers`);
}
switch (name) {
case "matching_blocks": {
const blocks = typeof json.blocks === "string" ? [json.blocks] : json.blocks;
if (!Array.isArray(blocks) || !blocks.every((b) => typeof b === "string")) {
problems.push(`${at}.blocks must be a block, a #tag, or a list of them`);
} else {
for (const block of blocks) refs.blocks.add(block);
}
break;
}
case "would_survive":
check_state(json.state, `${at}.state`, refs, problems);
break;
case "not":
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
break;
case "all_of":
case "any_of":
if (!Array.isArray(json.predicates)) problems.push(`${at}.predicates must be a list`);
else json.predicates.forEach((p, i) => check_predicate(p, `${at}.predicates[${i}]`, refs, problems));
}
}
function block_predicate(json: unknown): Predicate {
const predicate = json as Record<string, unknown>;
const [ox, oy, oz] = (predicate.offset as number[] | undefined) ?? [0, 0, 0];
const at =
(test: (id: string | undefined, chunk: FeatureChunk, x: number, y: number, z: number) => boolean): Predicate =>
(chunk, x, y, z) => test(block_at(chunk, x + ox, y + oy, z + oz), chunk, x + ox, y + oy, z + oz);
const info = (id: string | undefined) =>
id === undefined ? undefined : EverythingRegistry.get<BlockRegistry>("blocks", id);
switch (builtin_name(predicate.type as string)) {
case "matching_blocks": {
const blocks = typeof predicate.blocks === "string" ? [predicate.blocks] : predicate.blocks as string[];
return at((id) => id !== undefined && list_matches("blocks", blocks, id));
}
case "solid":
return at((id) => id !== undefined && info(id)?.has_collision === true);
case "replaceable":
return at((id) => id === AIR_ID || info(id)?.replaceable === true);
case "would_survive": {
const state = state_id(predicate.state);
return at((_id, chunk, x, y, z) => survives(chunk, state, x, y, z));
}
case "not": {
const inner = block_predicate(predicate.predicate);
return (chunk, x, y, z) => !inner(chunk, x + ox, y + oy, z + oz);
}
case "all_of": {
const inner = (predicate.predicates as unknown[]).map(block_predicate);
return (chunk, x, y, z) => inner.every((p) => p(chunk, x + ox, y + oy, z + oz));
}
case "any_of": {
const inner = (predicate.predicates as unknown[]).map(block_predicate);
return (chunk, x, y, z) => inner.some((p) => p(chunk, x + ox, y + oy, z + oz));
}
default:
return () => true;
}
}
// whether a block could be at x y z: where it is, it isn't air, and it can stand on what's under it (place_on)
function survives(chunk: FeatureChunk, id: string, x: number, y: number, z: number) {
if (y < 0 || y >= CHUNK_HEIGHT) return false;
const below = block_at(chunk, x, y - 1, z);
return below !== undefined && can_stand_on(EverythingRegistry.get<BlockRegistry>("blocks", id), below);
}
// the block at x y z, undefined outside the chunk or the world
function block_at(chunk: FeatureChunk, x: number, y: number, z: number) {
return inside(chunk, x, z) ? chunk.get_block(x, y, z) : undefined;
}
function inside(chunk: FeatureChunk, x: number, z: number) {
return Math.floor(x / CHUNK_SIZE) === chunk.x && Math.floor(z / CHUNK_SIZE) === chunk.z;
}
// block states: a block's id, or minecraft's { "type": "simple_state_provider", "state": { "Name": id } }
function check_state(json: unknown, at: string, refs: FeatureRefs, problems: string[]) {
const id = typeof json === "string"
? json
: is_object(json) && is_object(json.state)
? json.state.Name
: is_object(json)
? json.Name
: undefined;
if (typeof id === "string" && ID_PATTERN.test(id)) refs.blocks.add(id);
else problems.push(`${at} must be a block's id or { "type": "simple_state_provider", "state": { "Name": ... } }`);
}
function state_id(json: unknown): string {
if (typeof json === "string") return json;
const object = json as Record<string, unknown>;
return (is_object(object.state) ? object.state.Name : object.Name) as string;
}
// numbers: a whole number, { "type": "constant", "value" }, { "type": "uniform", "min_inclusive", "max_inclusive" } or
// { "type": "weighted_list", "distribution": [{ "data", "weight" }] }, like minecraft's int providers
type IntProvider = (chunk: FeatureChunk) => number;
function check_int(json: unknown, at: string, problems: string[]) {
if (Number.isInteger(json)) return;
if (!is_object(json)) {
problems.push(`${at} must be a whole number or { "type": "uniform", ... }`);
return;
}
switch (builtin_name(String(json.type))) {
case "constant":
if (!Number.isInteger(json.value)) problems.push(`${at}.value must be a whole number`);
break;
case "uniform":
if (!Number.isInteger(json.min_inclusive) || !Number.isInteger(json.max_inclusive)) {
problems.push(`${at} needs whole numbers min_inclusive and max_inclusive`);
} else if ((json.min_inclusive as number) > (json.max_inclusive as number)) {
problems.push(`${at}: min_inclusive is above max_inclusive`);
}
break;
case "weighted_list":
if (!Array.isArray(json.distribution) || json.distribution.length === 0) {
problems.push(`${at}.distribution must be a list of { "data", "weight" }`);
} else {
json.distribution.forEach((entry: unknown, i: number) => {
if (!is_object(entry) || !(Number.isInteger(entry.weight) && (entry.weight as number) > 0)) {
problems.push(`${at}.distribution[${i}] needs a whole number weight above 0`);
} else {
check_int(entry.data, `${at}.distribution[${i}].data`, problems);
}
});
}
break;
default:
problems.push(`${at}.type must be constant, uniform or weighted_list`);
}
}
function int_provider(json: unknown): IntProvider {
if (typeof json === "number") return () => json;
const object = json as Record<string, unknown>;
switch (builtin_name(String(object.type))) {
case "constant": {
const value = object.value as number;
return () => value;
}
case "uniform": {
const min = object.min_inclusive as number;
const span = (object.max_inclusive as number) - min + 1;
return (chunk) => min + Math.floor(chunk.rng.next() * span);
}
default: {
const entries = (object.distribution as { data: unknown; weight: number }[]).map((entry) => ({
data: int_provider(entry.data),
weight: entry.weight,
}));
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
return (chunk) => {
let roll = Math.floor(chunk.rng.next() * total);
for (const entry of entries) {
if (roll < entry.weight) return entry.data(chunk);
roll -= entry.weight;
}
return entries.at(-1)!.data(chunk);
};
}
}
}
// heights: an anchor ({ "absolute" }, { "above_bottom" } or { "below_top" }), { "type": "constant", "value": anchor }
// or { "type": "uniform", "min_inclusive": anchor, "max_inclusive": anchor }
function check_height(json: unknown, at: string, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at} must be a height, like { "absolute": 10 } or { "type": "uniform", ... }`);
return;
}
if (json.type === undefined) return check_anchor(json, at, problems);
switch (builtin_name(String(json.type))) {
case "constant":
check_anchor(json.value, `${at}.value`, problems);
break;
case "uniform":
check_anchor(json.min_inclusive, `${at}.min_inclusive`, problems);
check_anchor(json.max_inclusive, `${at}.max_inclusive`, problems);
break;
default:
problems.push(`${at}.type must be constant or uniform`);
}
}
function check_anchor(json: unknown, at: string, problems: string[]) {
const keys = ["absolute", "above_bottom", "below_top"];
if (
!is_object(json) || Object.keys(json).length !== 1 || !keys.includes(Object.keys(json)[0]) ||
!Number.isInteger(Object.values(json)[0])
) {
problems.push(`${at} must be one of { "absolute": y }, { "above_bottom": n } or { "below_top": n }`);
}
}
function anchor(json: unknown): number {
const object = json as Record<string, number>;
if (object.absolute !== undefined) return object.absolute;
if (object.above_bottom !== undefined) return object.above_bottom;
return CHUNK_HEIGHT - 1 - object.below_top;
}
function height_provider(json: unknown): IntProvider {
const object = json as Record<string, unknown>;
if (object.type === undefined) {
const y = anchor(object);
return () => y;
}
if (builtin_name(String(object.type)) === "constant") {
const y = anchor(object.value);
return () => y;
}
const min = anchor(object.min_inclusive);
const span = anchor(object.max_inclusive) - min + 1;
return (chunk) => min + Math.floor(chunk.rng.next() * span);
}
function is_object(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+91
View File
@@ -0,0 +1,91 @@
// a generator: noise settings, and the density functions, noises and biome rules it uses. compiled once for each
// seed, see OverworldTerrain. 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 { DensitySources } from "./density.ts";
import { OverworldTerrain } from "./terrain.ts";
// everything worldgen data mods registered, in load order
export interface WorldgenData {
noises: NoiseJson[];
density_functions: DensityFunctionJson[];
noise_settings: NoiseSettingsJson[];
biome_sources: BiomeSourceJson[];
}
export class Generator {
readonly settings: NoiseSettingsJson;
// the biome source's rules with every mod's added in, the first that holds picks a column's biome
readonly rules: BiomeRuleJson[];
readonly sources: DensitySources;
#seeds = new Map<string, OverworldTerrain>();
// throws when the data doesn't add up, like a density function that doesn't exist
constructor(id: string, data: WorldgenData) {
const settings = data.noise_settings.find((settings) => settings.id === id);
if (!settings) throw new Error(`there's no generator ${id}: no mod has worldgen/noise_settings for it`);
this.settings = settings;
const noises = new Map(data.noises.map((noise) => [noise.id, noise]));
const functions = new Map(data.density_functions.map((fn) => [fn.id, fn]));
this.sources = { noise: (id) => noises.get(id), function: (id) => functions.get(id) };
this.rules = merge_rules(settings, data.biome_sources);
// compiling once finds missing noises and functions, and loops, before any chunk is generated
this.for_seed("");
}
for_seed(seed: string): OverworldTerrain {
let terrain = this.#seeds.get(seed);
if (!terrain) {
terrain = new OverworldTerrain(seed, this);
this.#seeds.set(seed, terrain);
}
return terrain;
}
}
// the generator called id, from what mods registered
export function compile_generator(id: string): Generator {
const all = <T>(registry: string) => (EverythingRegistry.get_registry<T>(registry) ?? []).filter((v) => v);
return new Generator(id, {
noises: all("noises"),
density_functions: all("density_functions"),
noise_settings: all("noise_settings"),
biome_sources: all("biome_sources"),
});
}
// the biome source the settings name, with the rules of every source that extends it put in, in load order
function merge_rules(settings: NoiseSettingsJson, sources: BiomeSourceJson[]): BiomeRuleJson[] {
const base = sources.find((source) => source.id === settings.biome_source && source.extends === undefined);
if (!base) throw new Error(`noise settings ${settings.id}: biome source ${settings.biome_source} doesn't exist`);
const rules = [...base.rules];
for (const source of sources.filter((source) => source.extends === base.id)) {
for (const rule of source.rules) {
const target = rule.before ?? rule.after!;
const at = rules.findIndex((other) => other.id === target);
if (at < 0) {
throw new Error(
`biome source ${source.id}: rule ${rule.id} goes ${rule.before ? "before" : "after"} ${target}, ` +
`which ${base.id} doesn't have`,
);
}
rules.splice(rule.before ? at : at + 1, 0, rule);
}
}
const names = new Set([...Object.keys(settings.climate), "surface", "steep"]);
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}`);
seen.add(rule.id);
for (const name of Object.keys(rule.when ?? {})) {
if (!names.has(name)) {
throw new Error(
`biome rule ${rule.id}: ${name} isn't a climate value of ${settings.id}, which has ${
[...names].join(", ")
}`,
);
}
}
}
return rules;
}
+108 -235
View File
@@ -1,200 +1,110 @@
// fills a chunk with the overworld: the terrain's density sampled on a coarse grid and interpolated (minecraft's
// noise cells), caves cut out of it, water up to sea level, then biomes and their surface blocks
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, SEA_LEVEL } from "$/common/constants.ts";
import { OctaveNoise2D } from "./noise.ts";
import { OverworldTerrain, TerrainColumn } from "./terrain.ts";
import { grow_tree, tree_sites, type Wood } from "./trees.ts";
import { type Biome, get_biome, tree_wood } from "./biomes.ts";
// density is sampled every CELL_WIDTH blocks across and CELL_HEIGHT up, caves every CAVE_CELL_HEIGHT up since
// tunnels are thinner than terrain features
const CELL_WIDTH = 4;
const CELL_HEIGHT = 8;
const CAVE_CELL_HEIGHT = 4;
const CORNERS = CHUNK_SIZE / CELL_WIDTH + 1;
const TERRAIN_LEVELS = CHUNK_HEIGHT / CELL_HEIGHT + 1;
const CAVE_LEVELS = CHUNK_HEIGHT / CAVE_CELL_HEIGHT + 1;
// surface blocks only go this far below the ground's height, so cave floors stay stone
const SURFACE_REACH = 20;
// a column is a cliff when its ground is this much higher or lower than a neighbor's
const STEEP = 3.5;
// snow covers the tops of everything above this, give or take
const SNOW_LINE = SEA_LEVEL + 112;
// the blocks the overworld is made of, as numeric ids
export interface OverworldBlocks {
stone: number;
dirt: number;
grass: number;
snow: number;
water: number;
logs: Record<Wood, number>;
leaves: Record<Wood, number>;
// any other block, for biomes' surfaces
block(id: string): number;
}
// a biome's surface, as numeric ids
interface Surface {
top: number;
filler: number;
filler_depth: number;
underwater_top: number;
underwater_filler: number;
bare_cliffs: boolean;
}
// picks a column's biome from its climate and shape, like minecraft's multi noise biome source
export function pick_biome(column: TerrainColumn, surface_y: number, steep: boolean): string {
const { continentalness: c, erosion, ridges, temperature: t, humidity: h } = column.climate;
const flat = Math.abs(erosion);
const valley = Math.abs(ridges);
const frozen = t < -0.65;
const cold = t < -0.3;
const warm = t > 0.2;
const hot = t > 0.55;
if (surface_y < SEA_LEVEL - 1) {
if (valley < 0.06 && c > -0.2) return frozen ? "bworld:frozen_river" : "bworld:river";
if (c < -0.45) {
return frozen ? "bworld:deep_frozen_ocean" : hot ? "bworld:deep_lukewarm_ocean" : "bworld:deep_ocean";
}
return frozen ? "bworld:frozen_ocean" : hot ? "bworld:warm_ocean" : "bworld:ocean";
}
if (c < -0.12 && surface_y <= SEA_LEVEL + 4) {
return steep ? "bworld:stony_shore" : cold ? "bworld:snowy_beach" : "bworld:beach";
}
if (valley < 0.04 && c > -0.2 && surface_y <= SEA_LEVEL + 1) {
return frozen ? "bworld:frozen_river" : "bworld:river";
}
const above = surface_y - SEA_LEVEL;
if (above > 105) {
if (cold) return "bworld:frozen_peaks";
return column.jaggedness > 0.35 ? "bworld:jagged_peaks" : "bworld:stony_peaks";
}
if (above > 60 && cold) {
return "bworld:snowy_slopes";
}
if (above > 30 && !cold && h > -0.3) {
return "bworld:meadow";
}
if (frozen) return h > 0 ? "bworld:snowy_taiga" : "bworld:snowy_plains";
if (cold) return h > 0 ? "bworld:taiga" : "bworld:plains";
if (hot) return h < -0.2 ? "bworld:desert" : h < 0.4 ? "bworld:savanna" : "bworld:jungle";
if (warm) return h < -0.3 ? "bworld:savanna" : h > 0.6 ? "bworld:jungle" : "bworld:forest";
if (h > 0.5 && flat > 0.6) return "bworld:swamp";
return h < -0.35 ? "bworld:plains" : h < 0.45 ? "bworld:forest" : "bworld:dark_forest";
}
interface SeedGenerators {
terrain: OverworldTerrain;
snow_line: OctaveNoise2D;
}
const generators = new Map<string, SeedGenerators>();
function generators_for(seed: string): SeedGenerators {
let found = generators.get(seed);
if (!found) {
found = {
terrain: new OverworldTerrain(seed),
snow_line: new OctaveNoise2D(seed, "snow_line", 96, [1, 1]),
};
generators.set(seed, found);
}
return found;
}
// fills blocks (indexed y * CHUNK_AREA + z * CHUNK_SIZE + x) and each column's surface height and biome.
// blocks trees put in other chunks go to spill
// a column's biome without generating its chunk, from its height before 3d noise, so it can be a little off near
// coasts and cliffs. for searching far away, like /locatebiome
export function estimate_biome(seed: string, x: number, z: number): { biome: string; y: number } {
const { terrain } = generators_for(seed);
const column = terrain.column(x, z);
const y = Math.round(column.height);
const flat = pick_biome(column, y, false);
// most columns are the same either way, the neighbors are only worth sampling when they aren't
if (flat === pick_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]) => terrain.column(nx, nz));
const steep = neighbors.some((neighbor) => Math.abs(neighbor.height - column.height) >= STEEP);
return { biome: steep ? pick_biome(column, y, true) : flat, y };
}
// noise cells), caves cut out of it, then each column's biome, its surface blocks and fluids. what all of it is comes
// from the generator's noise settings, see OverworldTerrain and docs/modding/worldgen/terrain.md. trees and the rest
// are features, after it
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts";
import { get_biome } from "./biomes.ts";
import type { OverworldTerrain, TerrainColumn } from "./terrain.ts";
import {
compile_fluids,
compile_surface_rule,
surface_rule_reach,
type SurfaceBlocks,
type SurfaceContext,
} from "./surface_rules.ts";
// fills blocks (indexed 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
export function generate_overworld(
blocks: Uint32Array,
heights: Int32Array,
biomes: string[],
chunk_x: number,
chunk_z: number,
seed: string,
ids: OverworldBlocks,
spill: (x: number, y: number, z: number, block: number) => void,
terrain: OverworldTerrain,
block: (id: string) => number,
) {
const { terrain, snow_line } = generators_for(seed);
const settings = terrain.settings;
const cell_width = settings.cell_width;
const cell_height = settings.terrain.cell_height;
const cave_cell_height = settings.caves.cell_height;
const corners = CHUNK_SIZE / cell_width + 1;
const terrain_levels = CHUNK_HEIGHT / cell_height + 1;
const cave_levels = CHUNK_HEIGHT / cave_cell_height + 1;
const x0 = chunk_x * CHUNK_SIZE;
const z0 = chunk_z * CHUNK_SIZE;
// density at the corners of every cell
const corner_columns: TerrainColumn[] = [];
for (let cz = 0; cz < CORNERS; cz++) {
for (let cx = 0; cx < CORNERS; cx++) {
corner_columns.push(terrain.column(x0 + cx * CELL_WIDTH, z0 + cz * CELL_WIDTH));
for (let cz = 0; cz < corners; cz++) {
for (let cx = 0; cx < corners; cx++) {
corner_columns.push(terrain.column(x0 + cx * cell_width, z0 + cz * cell_width));
}
}
const solid = new Float32Array(CORNERS * CORNERS * TERRAIN_LEVELS);
const caves = new Float32Array(CORNERS * CORNERS * CAVE_LEVELS);
const solid = new Float32Array(corners * corners * terrain_levels);
const caves = new Float32Array(corners * corners * cave_levels);
for (let i = 0; i < corner_columns.length; i++) {
const column = corner_columns[i];
const x = x0 + (i % CORNERS) * CELL_WIDTH;
const z = z0 + Math.floor(i / CORNERS) * CELL_WIDTH;
for (let level = 0; level < TERRAIN_LEVELS; level++) {
solid[i * TERRAIN_LEVELS + level] = terrain.density(column, x, level * CELL_HEIGHT, z);
const x = x0 + (i % corners) * cell_width;
const z = z0 + Math.floor(i / corners) * cell_width;
for (let level = 0; level < terrain_levels; level++) {
solid[i * terrain_levels + level] = terrain.density(column, x, level * cell_height, z);
}
// caves only matter below the ground, skip the sky above it
const cave_top = column.height + CAVE_CELL_HEIGHT;
for (let level = 0; level < CAVE_LEVELS; level++) {
const y = level * CAVE_CELL_HEIGHT;
caves[i * CAVE_LEVELS + level] = y > cave_top ? 1 : terrain.cave(column, x, y, z);
for (let level = 0; level < cave_levels; level++) {
caves[i * cave_levels + level] = terrain.cave(column, x, level * cave_cell_height, z);
}
}
// every column of the chunk plus a ring around it, for how steep the ground is
// every column of the chunk plus a ring around it, for how steep the ground is. the chunk's own with their
// climate, for their biome
const columns: TerrainColumn[] = [];
const ring = CHUNK_SIZE + 2;
for (let z = -1; z <= CHUNK_SIZE; z++) {
for (let x = -1; x <= CHUNK_SIZE; x++) {
columns.push(terrain.column(x0 + x, z0 + z));
const inside = x >= 0 && x < CHUNK_SIZE && z >= 0 && z < CHUNK_SIZE;
columns.push(terrain.column(x0 + x, z0 + z, inside));
}
}
const column_at = (x: number, z: number) => columns[(z + 1) * ring + x + 1];
// biomes are registered by mods (bworld's are in mods/bworld/worldgen/biomes), with their surfaces' ids looked up
// once per chunk
const found = new Map<string, { biome: Biome; surface: Surface }>();
const biome_info = (id: string) => {
let info = found.get(id);
if (!info) {
const found = new Map<string, SurfaceBlocks>();
const surface_of = (id: string) => {
let surface = found.get(id);
if (!surface) {
const biome = get_biome(id);
if (!biome) throw new Error(`biome ${id} isn't registered, is the bworld mod loaded?`);
const { surface } = biome;
info = {
biome,
surface: {
top: ids.block(surface.top),
filler: ids.block(surface.filler),
filler_depth: surface.filler_depth,
underwater_top: ids.block(surface.underwater_top),
underwater_filler: ids.block(surface.underwater_filler),
bare_cliffs: surface.bare_cliffs,
},
if (!biome) throw new Error(`biome ${id} isn't registered, is the mod that adds it loaded?`);
surface = {
top: block(biome.surface.top),
filler: block(biome.surface.filler),
filler_depth: biome.surface.filler_depth,
underwater_top: block(biome.surface.underwater_top),
underwater_filler: block(biome.surface.underwater_filler),
bare_cliffs: biome.surface.bare_cliffs,
};
found.set(id, info);
found.set(id, surface);
}
return info;
return surface;
};
const surface_rule = compile_surface_rule(settings.surface_rule, terrain, block);
const fluids = compile_fluids(settings.fluids, terrain, block);
// no fluid goes higher than this, and nothing below the rule's reach needs it
const fluid_top = Math.max(...settings.fluids.map((fluid) => fluid.below));
const reach = surface_rule_reach(settings.surface_rule);
const default_block = block(settings.default_block);
const sea_level = settings.sea_level;
const context: SurfaceContext = {
x: 0,
y: 0,
z: 0,
depth: 0,
underwater: false,
steep: false,
preliminary: 0,
biome: "",
surface: undefined!,
};
for (let z = 0; z < CHUNK_SIZE; z++) {
@@ -202,54 +112,15 @@ export function generate_overworld(
fill_column(x, z);
}
}
grow_trees();
function grow_trees() {
// logs replace any tree's leaves
const all_leaves = new Set(Object.values(ids.leaves));
const place = (x: number, y: number, z: number, block: "log" | "leaves", wood: Wood) => {
if (y < 0 || y >= CHUNK_HEIGHT) return;
const id = block === "log" ? ids.logs[wood] : ids.leaves[wood];
const lx = x - x0;
const lz = z - z0;
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE) {
// the other chunk only takes it where it has air
spill(x, y, z, id);
return;
}
const i = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
const current = blocks[i];
if (current === 0 || (block === "log" && all_leaves.has(current))) {
blocks[i] = id;
}
};
for (const site of tree_sites(seed, chunk_x, chunk_z)) {
const column = (site.z - z0) * CHUNK_SIZE + (site.x - x0);
const { biome } = biome_info(biomes[column]);
const trees = biome.trees;
if (!trees || site.rng.next() >= trees.chance) continue;
// on soil with air above it, so never under water or on bare rock
const ground_y = heights[column];
const ground = blocks[ground_y * CHUNK_AREA + column];
const above = blocks[(ground_y + 1) * CHUNK_AREA + column];
if ((ground !== ids.grass && ground !== ids.dirt && ground !== ids.snow) || above !== 0) continue;
const kind = trees.kinds[Math.floor(site.rng.next() * trees.kinds.length)];
const wood = tree_wood(kind, biome);
grow_tree(kind, site.x, ground_y + 1, site.z, site.rng, (x, y, z, block) => place(x, y, z, block, wood));
}
}
function fill_column(x: number, z: number) {
const cell_x = Math.min(Math.floor(x / CELL_WIDTH), CORNERS - 2);
const cell_z = Math.min(Math.floor(z / CELL_WIDTH), CORNERS - 2);
const tx = (x - cell_x * CELL_WIDTH) / CELL_WIDTH;
const tz = (z - cell_z * CELL_WIDTH) / CELL_WIDTH;
const c00 = cell_z * CORNERS + cell_x;
const cell_x = Math.min(Math.floor(x / cell_width), corners - 2);
const cell_z = Math.min(Math.floor(z / cell_width), corners - 2);
const tx = (x - cell_x * cell_width) / cell_width;
const tz = (z - cell_z * cell_width) / cell_width;
const c00 = cell_z * corners + cell_x;
const c10 = c00 + 1;
const c01 = c00 + CORNERS;
const c01 = c00 + corners;
const c11 = c01 + 1;
const w00 = (1 - tx) * (1 - tz);
const w10 = tx * (1 - tz);
@@ -260,16 +131,17 @@ export function generate_overworld(
grid[c00 * levels + level] * w00 + grid[c10 * levels + level] * w10 +
grid[c01 * levels + level] * w01 + grid[c11 * levels + level] * w11;
// solid where both the terrain and the caves are above 0
const is_solid = new Uint8Array(CHUNK_HEIGHT);
for (let y = 0; y < CHUNK_HEIGHT; y++) {
const level = Math.min(Math.floor(y / CELL_HEIGHT), TERRAIN_LEVELS - 2);
const t = (y - level * CELL_HEIGHT) / CELL_HEIGHT;
let density = blend(solid, TERRAIN_LEVELS, level) * (1 - t) + blend(solid, TERRAIN_LEVELS, level + 1) * t;
const level = Math.min(Math.floor(y / cell_height), terrain_levels - 2);
const t = (y - level * cell_height) / cell_height;
let density = blend(solid, terrain_levels, level) * (1 - t) + blend(solid, terrain_levels, level + 1) * t;
if (density > 0) {
const cave_level = Math.min(Math.floor(y / CAVE_CELL_HEIGHT), CAVE_LEVELS - 2);
const ct = (y - cave_level * CAVE_CELL_HEIGHT) / CAVE_CELL_HEIGHT;
const cave = blend(caves, CAVE_LEVELS, cave_level) * (1 - ct) +
blend(caves, CAVE_LEVELS, cave_level + 1) * ct;
const cave_level = Math.min(Math.floor(y / cave_cell_height), cave_levels - 2);
const ct = (y - cave_level * cave_cell_height) / cave_cell_height;
const cave = blend(caves, cave_levels, cave_level) * (1 - ct) +
blend(caves, cave_levels, cave_level + 1) * ct;
density = Math.min(density, cave);
}
is_solid[y] = density > 0 ? 1 : 0;
@@ -281,48 +153,49 @@ export function generate_overworld(
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) >= STEEP);
const biome = pick_biome(column, surface_y, steep);
const { surface } = biome_info(biome);
const snow_y = SNOW_LINE + snow_line.sample(x0 + x, z0 + z) * 10;
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;
context.x = x0 + x;
context.z = z0 + z;
context.steep = steep;
context.preliminary = ground;
context.biome = biome;
context.surface = surface_of(biome);
const index = (y: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
// the same sum as the rule's own condition, so it can't disagree with it
const lowest = ground + reach;
// solid blocks since the last air going down, 0 is a block with air on top
let depth = -1;
// nothing but air above so far: water fills it up to sea level
// nothing but air above so far
let open_sky = true;
// whether the ground's surface is under water, for its cover
let underwater = false;
for (let y = CHUNK_HEIGHT - 1; y >= 0; y--) {
context.y = y;
if (!is_solid[y]) {
depth = -1;
// and a river's tunnel under a mountain, and the caves it runs into
if ((open_sky || column.underground_river > 0) && y < SEA_LEVEL) {
blocks[index(y)] = ids.water;
if (y < fluid_top) {
const fluid = fluids(context, open_sky);
if (fluid !== undefined) blocks[index(y)] = fluid;
}
continue;
}
depth += 1;
if (open_sky) {
open_sky = false;
underwater = y < SEA_LEVEL - 1;
underwater = y < sea_level - 1;
}
// surface rules reach the ground and anything above it, not cave floors
let block = ids.stone;
if (y >= ground - SURFACE_REACH) {
if (depth === 0) {
if (underwater) block = surface.underwater_top;
else if (y >= snow_y) block = steep ? ids.stone : ids.snow;
else block = steep && surface.bare_cliffs ? ids.stone : surface.top;
} else if (depth <= surface.filler_depth) {
block = underwater ? surface.underwater_filler : surface.filler;
}
if (y < lowest) {
blocks[index(y)] = default_block;
continue;
}
blocks[index(y)] = block;
context.depth = depth;
context.underwater = underwater;
blocks[index(y)] = surface_rule(context) ?? default_block;
}
}
}
-72
View File
@@ -1,72 +0,0 @@
// minecraft's CubicSpline: a smooth curve through points, where a point's value can itself be a spline of another
// input. that nesting is how its terrain (and tectonic's) turns continentalness, erosion and ridges into heights:
// a spline over continentalness whose points are splines over erosion, whose points are splines over ridges.
// K names the inputs, see TerrainInputs
export type SplineValue<K extends string> = number | Spline<K>;
export interface SplinePoint<K extends string> {
at: number;
value: SplineValue<K>;
// the slope there, worked out from the neighbors when not given
slope?: number;
}
export class Spline<K extends string> {
readonly input: K;
#locations: number[];
#values: SplineValue<K>[];
#slopes: number[];
constructor(input: K, points: SplinePoint<K>[]) {
this.input = input;
this.#locations = points.map((point) => point.at);
this.#values = points.map((point) => point.value);
// catmull-rom slopes between the neighbors, flat at the ends and where values are splines
this.#slopes = points.map((point, i) => {
if (point.slope !== undefined) return point.slope;
const before = points[i - 1];
const after = points[i + 1];
if (!before || !after || typeof before.value !== "number" || typeof after.value !== "number") {
return 0;
}
return (after.value - before.value) / (after.at - before.at);
});
}
get(inputs: Readonly<Record<K, number>>): number {
const x = inputs[this.input];
const locations = this.#locations;
const last = locations.length - 1;
if (x <= locations[0]) {
return value_of(this.#values[0], inputs) + this.#slopes[0] * (x - locations[0]);
}
if (x >= locations[last]) {
return value_of(this.#values[last], inputs) + this.#slopes[last] * (x - locations[last]);
}
let i = 0;
while (locations[i + 1] < x) i++;
const x0 = locations[i];
const x1 = locations[i + 1];
const width = x1 - x0;
const t = (x - x0) / width;
const y0 = value_of(this.#values[i], inputs);
const y1 = value_of(this.#values[i + 1], inputs);
// hermite interpolation, written the way minecraft does it
const a = this.#slopes[i] * width - (y1 - y0);
const b = -this.#slopes[i + 1] * width + (y1 - y0);
return y0 + (y1 - y0) * t + t * (1 - t) * (a + (b - a) * t);
}
}
function value_of<K extends string>(value: SplineValue<K>, inputs: Readonly<Record<K, number>>) {
return typeof value === "number" ? value : value.get(inputs);
}
// a spline through points given as [at, value, slope], like minecraft's json with its derivatives. slope is 0 when
// left out, like minecraft's
export function spline<K extends string>(input: K, points: [number, SplineValue<K>, number?][]) {
return new Spline(input, points.map(([at, value, slope]) => ({ at, value, slope: slope ?? 0 })));
}
+134
View File
@@ -0,0 +1,134 @@
// what solid blocks and empty space become, from the noise settings' surface_rule and fluids (see data.ts), compiled
// for each chunk with its block ids. like minecraft's surface rules: a rule gives a block or nothing, and a sequence
// gives its first rule's block
import { type FluidJson, range_test, type SurfaceConditionJson, type SurfaceRuleJson } from "./data.ts";
import type { OverworldTerrain } from "./terrain.ts";
// a biome's surface as numeric ids
export interface SurfaceBlocks {
top: number;
filler: number;
filler_depth: number;
underwater_top: number;
underwater_filler: number;
bare_cliffs: boolean;
}
// the block being decided, one context reused for the whole chunk
export interface SurfaceContext {
x: number;
y: number;
z: number;
// solid blocks above it before air, 0 for one with air on top
depth: number;
// the column's ground, the first solid block from the top, is below sea level - 1
underwater: boolean;
steep: boolean;
// the column's height before 3d noise
preliminary: number;
biome: string;
surface: SurfaceBlocks;
}
type Rule = (context: SurfaceContext) => number | undefined;
type Condition = (context: SurfaceContext) => boolean;
export function compile_surface_rule(
json: SurfaceRuleJson,
terrain: OverworldTerrain,
block: (id: string) => number,
): Rule {
switch (json.type) {
case "sequence": {
const rules = json.sequence.map((rule) => compile_surface_rule(rule, terrain, block));
return (context) => {
for (const rule of rules) {
const result = rule(context);
if (result !== undefined) return result;
}
return undefined;
};
}
case "condition": {
const condition = compile_condition(json.if_true, terrain);
const then = compile_surface_rule(json.then_run, terrain, block);
return (context) => condition(context) ? then(context) : undefined;
}
case "block": {
const id = block(json.result_state.Name);
return () => id;
}
case "biome_surface": {
const part = json.part;
return (context) => context.surface[part];
}
}
}
function compile_condition(json: SurfaceConditionJson, terrain: OverworldTerrain): Condition {
switch (json.type) {
case "stone_depth": {
const offset = json.offset;
return (context) => context.depth <= offset;
}
case "filler_depth":
return (context) => context.depth <= context.surface.filler_depth;
case "above_preliminary_surface": {
const offset = json.offset ?? 0;
return (context) => context.y >= context.preliminary + offset;
}
case "surface_underwater":
return (context) => context.underwater;
case "steep":
return (context) => context.steep;
case "bare_cliffs":
return (context) => context.surface.bare_cliffs;
case "y_at_least": {
const at = terrain.compiler.compile(json.function);
return (context) => context.y >= at(context.x, context.y, context.z);
}
case "biome": {
const biomes = new Set(json.biome_is);
return (context) => biomes.has(context.biome);
}
case "not": {
const inner = compile_condition(json.invert, terrain);
return (context) => !inner(context);
}
}
}
// how far above the preliminary surface the rule starts giving blocks, when its outermost condition says, so the
// blocks below it can skip it. -Infinity when it doesn't say
export function surface_rule_reach(json: SurfaceRuleJson): number {
if (json.type === "condition" && json.if_true.type === "above_preliminary_surface") {
return json.if_true.offset ?? 0;
}
return -Infinity;
}
// the fluid empty space at the context's y becomes, if any. open_sky is whether there's only air above it
export function compile_fluids(
json: FluidJson[],
terrain: OverworldTerrain,
block: (id: string) => number,
): (context: SurfaceContext, open_sky: boolean) => number | undefined {
const fluids = json.map((fluid) => {
const id = block(fluid.block);
const below = fluid.below;
if (fluid.where === "open_sky") {
return (context: SurfaceContext, open_sky: boolean) => open_sky && context.y < below ? id : undefined;
}
const where = terrain.compiler.compile(fluid.where.function);
const test = range_test(fluid.where);
return (context: SurfaceContext) =>
context.y < below && test(where(context.x, context.y, context.z)) ? id : undefined;
});
return (context, open_sky) => {
for (const fluid of fluids) {
const id = fluid(context, open_sky);
if (id !== undefined) return id;
}
return undefined;
};
}
+99 -622
View File
@@ -1,644 +1,121 @@
// the shape of the overworld, built the way minecraft 1.18+ does it and shaped after tectonic
// (https://github.com/Apollounknowndev/tectonic, MIT): large noises for continents, erosion and ridges feed nested
// splines that give each column a target height, how jagged its peaks are and how rough its ground is. a 3d density
// around that height decides what's solid, and caves are cut out of it. tectonic's look comes from its splines,
// ported here in its units (1 is 128 blocks): oceans that wind between big continents with islands out at sea,
// mountain ranges where erosion is low, rivers along the valleys between ridges that go underground through
// mountains, and on the flatter land four kinds of region picked by a slow noise and the climate: valleys and
// plateaus (and badlands ridges where it's hot), tiered mesas, rolling hills and jungle pillars, and wetlands and dunes
import { CHUNK_HEIGHT, SEA_LEVEL } from "$/common/constants.ts";
import { clamp, OctaveNoise2D, OctaveNoise3D, Quantiles, smoothstep } from "./noise.ts";
import { Spline, spline } from "./spline.ts";
// 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_overworld calls density and cave through here, so engine access mods can
// hook them. bworld's overworld is shaped after tectonic (https://github.com/Apollounknowndev/tectonic, MIT), its
// splines are in mods/bworld/worldgen/density_function/overworld
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";
// measured with tools/noise_quantiles.ts
const QUANTILES_6 = new Quantiles([
-0.833,
-0.386,
-0.311,
-0.256,
-0.21,
-0.17,
-0.133,
-0.098,
-0.065,
-0.032,
0,
0.032,
0.065,
0.098,
0.133,
0.17,
0.21,
0.256,
0.311,
0.386,
0.833,
]);
const QUANTILES_4 = new Quantiles([
-0.917,
-0.48,
-0.393,
-0.328,
-0.273,
-0.222,
-0.174,
-0.13,
-0.086,
-0.042,
0,
0.042,
0.086,
0.13,
0.174,
0.222,
0.273,
0.328,
0.393,
0.48,
0.917,
]);
const QUANTILES_3 = new Quantiles([
-0.91,
-0.468,
-0.377,
-0.308,
-0.249,
-0.199,
-0.154,
-0.113,
-0.073,
-0.036,
0,
0.036,
0.073,
0.113,
0.154,
0.199,
0.249,
0.308,
0.377,
0.468,
0.91,
]);
const QUANTILES_2 = new Quantiles([
-0.962,
-0.536,
-0.439,
-0.368,
-0.306,
-0.248,
-0.195,
-0.146,
-0.096,
-0.046,
0,
0.046,
0.096,
0.146,
0.195,
0.248,
0.306,
0.368,
0.439,
0.536,
0.962,
]);
const QUANTILES_TEMPERATURE = new Quantiles([
-0.973,
-0.6,
-0.509,
-0.44,
-0.379,
-0.319,
-0.254,
-0.19,
-0.127,
-0.063,
0,
0.063,
0.127,
0.19,
0.254,
0.319,
0.379,
0.44,
0.509,
0.6,
0.973,
]);
// blocks of height per unit of density, how soft the ground's surface is
const THICKNESS = 20;
// solid ground always ends here, and nothing reaches past the top of the world
const TOP_SLIDE_START = CHUNK_HEIGHT - 24;
const TOP_SLIDE_END = CHUNK_HEIGHT - 4;
const MIN_CAVE_Y = 5;
// the climate at a column. continentalness, erosion and ridges are scaled to about tectonic's ranges, temperature and
// humidity are spread evenly from -1 to 1
export interface Climate {
// tectonic's raw continents: deep ocean below -0.45, ocean to -0.2, the coast to 0, then further and further
// inland. islands raise it out at sea
continentalness: number;
// low is mountains, high is flat land. both ends are flat, see erosion_folded
erosion: number;
// 0 along valleys, where rivers run, and further from 0 towards the ridges between them
ridges: number;
temperature: number;
humidity: number;
}
// everything 2d about a column that the density needs, worked out once per column
// what the terrain worked out about a column
export interface TerrainColumn {
climate: Climate;
x: number;
z: number;
// where the ground's surface is before 3d noise, in blocks
height: number;
// how much 3d noise moves the ground, in units of density. high where tectonic's terrain is rugged
roughness: number;
// 0 to 1, how much its peaks are sharp ridges
jaggedness: number;
// 0 to 1, how close it is to the middle of a river that goes under a mountain here, see cave
underground_river: number;
// its climate values in the order the noise settings name them, when column was asked for them
climate?: number[];
}
// what tectonic's splines read: the climate, folded, and the small noises its regions are made of
type Input =
| "continents"
| "erosion"
| "erosion_folded"
| "ridges"
| "ridges_folded"
| "region"
| "regions"
| "temperature"
| "vegetation"
| "lower_tier"
| "upper_tier"
| "badlands"
| "hills"
| "wetland"
| "pillar";
type TerrainInputs = Record<Input, number>;
type S = Spline<Input>;
const s = (input: Input, points: [number, number | S, number?][]): S => spline(input, points);
// tectonic's raw continents from how far the continents noise is from 0: 0 is the middle of an ocean
const CONTINENT_SHAPE = s("continents", [[0, 0], [0.4, 0.575, 1], [0.48, 0.68, 1]]);
// tectonic's temperature and vegetation indexes, 1 to 5, from its climate parameters
const TEMPERATURE_INDEX = s("temperature", [
[-0.48, 1],
[-0.42, 2],
[-0.18, 2],
[-0.12, 3],
[0.17, 3],
[0.23, 4],
[0.52, 4],
[0.58, 5],
]);
const VEGETATION_INDEX = s("vegetation", [
[-0.38, 1],
[-0.32, 2],
[-0.13, 2],
[-0.07, 3],
[0.07, 3],
[0.13, 4],
[0.27, 4],
[0.33, 5],
]);
// from here on, tectonic's splines: heights in its units, relative to sea level
// a river: down to below sea level where the ridges noise is 0, back up to the land around it
const RIVER = s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01]]);
const GENTLE_RIVER = s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01, 0.1]]);
const lower_tier = (low: number, high: number) => s("lower_tier", [[0, low], [0.15, high]]);
const badlands = (low: number, high: number) => s("badlands", [[0.45, 0.05], [0.6, low, 1.5], [0.63, high, 0.2]]);
// club: valleys between plateaus, with badlands ridges where it's hot
const PLATEAUS = s("ridges", [
[-0.5, 0.25, -0.1],
[-0.4, lower_tier(0.1, 0.22)],
[-0.3, 0.05, -0.8],
[-0.1, 0.01],
[-0.03, -0.06, -0.5],
[0.03, -0.06, 0.5],
[0.1, 0.01],
[0.3, 0.05, 0.8],
[0.4, lower_tier(0.135, 0.28)],
[0.5, 0.35, 0.1],
]);
const SINGLE_VALLEY = s("ridges", [
[-0.5, 0.25, -0.1],
[-0.4, lower_tier(0.1, 0.22)],
[-0.3, 0.05, -0.8],
[-0.1, 0.01],
[-0.03, -0.06, -0.5],
[0.03, -0.06, 0.5],
[0.075, 0.01],
[0.14, 0.05, 0.8],
[0.2, lower_tier(0.135, 0.28)],
[0.3, 0.35],
[0.45, 0.03],
]);
const DOUBLE_VALLEY = s("ridges", [
[-0.45, 0.03],
[-0.3, 0.25],
[-0.2, lower_tier(0.1, 0.22)],
[-0.125, 0.05, -0.8],
[-0.075, 0.01],
[-0.03, -0.06, -0.5],
[0.03, -0.06, 0.5],
[0.075, 0.01],
[0.125, 0.05, 0.8],
[0.2, lower_tier(0.135, 0.28)],
[0.3, 0.35],
[0.45, 0.03],
]);
const CLUB = s("temperature", [
[1, PLATEAUS],
[2, s("vegetation", [[1, SINGLE_VALLEY], [2, PLATEAUS]])],
[3, s("vegetation", [[2, SINGLE_VALLEY], [3, PLATEAUS], [4, PLATEAUS], [5, DOUBLE_VALLEY]])],
[4, PLATEAUS],
[5, s("ridges_folded", [[0, -0.15, 2.5], [0.1, 0.04], [0.2, badlands(0.15, 0.185)], [0.3, badlands(0.185, 0.5)]])],
]);
// heart: rolling hills where it's mild, and in jungles ridges cut by narrow valleys
const HEART = s("temperature", [
[
3,
s("vegetation", [
[2, s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01, 0.1], [0.2, s("hills", [[0, 0.01, 0.225]])]])],
[3, GENTLE_RIVER],
]),
],
[
4,
s("vegetation", [
[3, GENTLE_RIVER],
[
4,
s("ridges", [
[-0.75, 0.05],
[-0.175, 0.015],
[-0.125, 0.01],
[-0.04, -0.06, -0.7],
[0.04, -0.06, 0.7],
[0.125, 0.01],
]),
],
[5, s("ridges_folded", [[0.04, -0.06, 0.7], [0.125, 0.01], [0.175, 0.015], [0.75, 0.05], [0.8, 0.6]])],
]),
],
[5, s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01, 0.15]])],
]);
// spade: land in tiers, and tall mesas where it's hot
const SPADE = s("temperature", [
[
4,
s("ridges_folded", [
[0.03, -0.06, 0.5],
[0.1, 0.01],
[0.3, 0.05, 0.8],
[0.4, lower_tier(0.1, 0.22)],
[0.55, 0.25, 1],
[0.6, s("upper_tier", [[0, 0.25], [0.15, 0.45]])],
[0.64, 0.5],
]),
],
[
5,
s("ridges_folded", [
[0.025, -0.075, 0.03],
[0.1, 0.05],
[0.175, 0.1, 1.5],
[0.2, 0.225, 0.2],
[0.4, 0.6, 7],
[0.4, 0.6, 0.1],
[0.8, 0.7],
[0.85, 0.4],
[1, 0.4],
[1.05, 0.04],
]),
],
]);
// diamond: flat land with wetlands, and deserts (their dunes are added on top, see DUNES)
const DIAMOND = s("temperature", [
[
4,
s("vegetation", [
[2, GENTLE_RIVER],
[
3,
s("ridges_folded", [
[0.03, -0.06, 0.5],
[0.1, 0.01],
[0.15, s("wetland", [[-0.45, -0.03, 0.03], [-0.3, 0.005], [0.3, 0.005], [0.45, -0.03, -0.03]])],
]),
],
]),
],
[5, s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0.01, 0.15]])],
]);
// which region: by erosion's sign, then the slow region noise
const REGIONS = s("erosion", [
[-0.02, s("region", [[-0.1, CLUB], [0.1, HEART]])],
[0.04, s("region", [[-0.1, SPADE], [0.1, DIAMOND]])],
]);
// the regions, after REGIONS and its height multiplier
const REGION = s("regions", [[0, 0, 1]]);
const WEAK_REGION = s("regions", [[0, 0, 0.5]]);
const HILLS = s("ridges_folded", [[0, -0.1, 1], [0.175, 0.075, 0.3], [0.3, 0.25]]);
const LOW_RIDGES = s("ridges_folded", [[0.38, -0.03], [0.45, 0.03]]);
const inland = (top: number, high: number, low: number, ridge: number, regions_end: number, hills: number) =>
s("erosion_folded", [
[0, top],
[0.175, high],
[0.3, low],
[0.375, s("ridges_folded", [[0, -0.1], [0.1, 0.125, 5], [0.1667, 0.225], [0.3, ridge]])],
[0.425, WEAK_REGION],
[0.5, REGION],
[regions_end, REGION],
[hills, HILLS],
[0.95, HILLS],
[1.075, LOW_RIDGES],
]);
// shallower than tectonic's, the world goes 64 blocks below sea level instead of 128
const DEEP_OCEAN = -0.33;
const OCEAN = -0.17;
// target height above sea level: the ocean floor, then coasts, then further inland mountains where erosion is low
// and the regions where it's high
const OFFSET = s("continents", [
[-0.45, DEEP_OCEAN],
[-0.35, OCEAN],
[-0.195, -0.14],
[
-0.155,
s("erosion_folded", [
[0.2, s("ridges_folded", [[0, -0.1], [0.15, 0.15, 3], [0.25, 0.22]]), -0.17],
[0.3, s("ridges_folded", [[0.03, -0.06, 0.5], [0.1, 0]])],
]),
],
[
0,
s("erosion_folded", [
[0, 0.65],
[0.15, 0.425, -1.5],
[0.3, 0.33],
[0.375, s("ridges_folded", [[0, -0.1], [0.15, 0.15], [0.3, 0.25]])],
[0.4, RIVER],
[0.95, RIVER],
[1.075, LOW_RIDGES],
]),
],
[0.1, inland(0.95, 0.55, 0.36, 0.3, 0.825, 0.875)],
[0.8, inland(1.1, 0.65, 0.38, 0.33, 0.8, 0.9)],
]);
// how jagged the peaks are, 0 to 0.2: only the tallest mountains, deep inland
const JAGGEDNESS = s("continents", [[0, 0], [0.175, s("erosion_folded", [[0, 0.2], [0.125, 0]])]]);
// tectonic's factor: how steeply density rises below the surface. low is rugged ground full of overhangs, on the
// ridges of hilly land
const rugged = (ridges: S) => s("erosion_folded", [[0.825, 5.6], [0.875, ridges], [0.975, ridges], [1.025, 5.6]]);
const FACTOR = s("continents", [
[-0.19, 5.6],
[-0.15, rugged(s("ridges", [[0, 5.6], [0.1, 0.6]]))],
[0.03, rugged(s("ridges", [[0, 5.6], [0.1, 0.6]]))],
[0.06, rugged(s("ridges_folded", [[0.25, 5.6], [0.4, 1.3]]))],
]);
// how tall dunes get, up to 6, in hot flat land of the diamond region
const DUNE_HEIGHT = s("temperature", [
[4, 0],
[5, s("region", [[0, 0], [0.1, s("ridges_folded", [[0, 0], [0.25, 6]])]])],
]);
const DUNES = s("continents", [
[0, 0],
[0.05, s("erosion_folded", [[0.4, 0], [0.45, DUNE_HEIGHT], [0.8, DUNE_HEIGHT], [0.85, 0]])],
]);
// jungle pillars: tall narrow columns in heart's jungles, on the ridges between its valleys
const pillar = (mid: number, high: number) => s("pillar", [[0.05, 0], [0.2, mid, -0.2], [0.5, high, 0.05]]);
const JUNGLE_PILLARS = s("region", [
[0, 0],
[
0.1,
s("temperature", [
[3, 0],
[
4,
s("vegetation", [
[3, 0],
[4, s("ridges", [[-0.75, pillar(0.4, 0.7)], [-0.175, pillar(0.25, 0.5)], [-0.125, 0]])],
[
5,
s("ridges_folded", [[0.125, 0], [0.175, pillar(0.25, 0.5)], [0.75, pillar(0.45, 0.75)], [
0.8,
0,
]]),
],
]),
],
[5, 0],
]),
],
]);
const PILLARS = s("continents", [
[0, 0],
[0.1, s("erosion", [[-0.875, 0], [-0.825, JUNGLE_PILLARS], [-0.425, JUNGLE_PILLARS], [-0.375, 0]])],
]);
// blocks per unit of tectonic's height. without its vertical scale of 1.125, which is for minecraft's taller world
const BLOCKS_PER_UNIT = 128;
// the 3d noise's strength at tectonic's usual factor
const ROUGHNESS = 0.12;
// rivers that reach mountains go under them in a tunnel this tall around sea level, this wide in ridges
const RIVER_TUNNEL_BOTTOM = SEA_LEVEL - 5;
const RIVER_TUNNEL_TOP = SEA_LEVEL + 4;
const RIVER_TUNNEL_WIDTH = 0.035;
// only where the ground is this far above the river, otherwise it's an open valley
const RIVER_TUNNEL_COVER = 12;
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;
}
export class OverworldTerrain {
#continents: OctaveNoise2D;
#island_a: OctaveNoise2D;
#island_b: OctaveNoise2D;
#erosion: OctaveNoise2D;
#ridges: OctaveNoise2D;
#temperature: OctaveNoise2D;
#humidity: OctaveNoise2D;
#warp_x: OctaveNoise2D;
#warp_z: OctaveNoise2D;
#region: OctaveNoise2D;
#height_multiplier: OctaveNoise2D;
#lower_tier: OctaveNoise2D;
#upper_tier: OctaveNoise2D;
#badlands: OctaveNoise2D;
#hills: OctaveNoise2D;
#wetland: OctaveNoise2D;
#pillar: OctaveNoise2D;
#dune: OctaveNoise2D;
#dune_warp: OctaveNoise2D;
#mountain_ridges: OctaveNoise2D;
#ground: OctaveNoise3D;
#cheese: OctaveNoise3D;
#spaghetti_a: OctaveNoise3D;
#spaghetti_b: OctaveNoise3D;
#entrances: OctaveNoise2D;
readonly seed: string;
readonly settings: NoiseSettingsJson;
readonly compiler: DensityCompiler;
#preliminary: Density;
#terrain: Density;
#caves: Density;
#climate: Density[];
#rules: CompiledRule[];
// the amplitudes match the quantile tables above, so each noise can be spread evenly
constructor(seed: string) {
this.#continents = new OctaveNoise2D(seed, "continents", 2560, [1, 1, 2, 2, 1, 1]);
this.#island_a = new OctaveNoise2D(seed, "island_a", 320, [1, 1]);
this.#island_b = new OctaveNoise2D(seed, "island_b", 320, [1, 1]);
this.#erosion = new OctaveNoise2D(seed, "erosion", 1280, [1, 1, 0, 1, 1]);
this.#ridges = new OctaveNoise2D(seed, "ridges", 640, [1, 2, 1]);
this.#temperature = new OctaveNoise2D(seed, "temperature", 3072, [1.5, 0, 1]);
this.#humidity = new OctaveNoise2D(seed, "humidity", 1536, [1, 1]);
this.#warp_x = new OctaveNoise2D(seed, "warp_x", 200, [1, 1]);
this.#warp_z = new OctaveNoise2D(seed, "warp_z", 200, [1, 1]);
this.#region = new OctaveNoise2D(seed, "region", 2048, [1, 1, 2, 2, 1, 1]);
this.#height_multiplier = new OctaveNoise2D(seed, "height_multiplier", 1024, [1, 2, 1]);
this.#lower_tier = new OctaveNoise2D(seed, "lower_tier", 512, [1, 2, 1]);
this.#upper_tier = new OctaveNoise2D(seed, "upper_tier", 512, [1, 2, 1]);
this.#badlands = new OctaveNoise2D(seed, "badlands", 512, [1, 2, 1]);
this.#hills = new OctaveNoise2D(seed, "hills", 320, [1, 1]);
this.#wetland = new OctaveNoise2D(seed, "wetland", 96, [1, 1]);
this.#pillar = new OctaveNoise2D(seed, "pillar", 32, [1, 1]);
this.#dune = new OctaveNoise2D(seed, "dune", 96, [1, 1]);
this.#dune_warp = new OctaveNoise2D(seed, "dune_warp", 400, [1, 1]);
this.#mountain_ridges = new OctaveNoise2D(seed, "mountain_ridges", 256, [1, 1]);
this.#ground = new OctaveNoise3D(seed, "ground", 64, [1, 1, 0.5], 1.2);
this.#cheese = new OctaveNoise3D(seed, "cheese", 80, [1, 0.5], 0.6);
this.#spaghetti_a = new OctaveNoise3D(seed, "spaghetti_a", 64, [1], 0.8);
this.#spaghetti_b = new OctaveNoise3D(seed, "spaghetti_b", 64, [1], 0.8);
this.#entrances = new OctaveNoise2D(seed, "entrances", 90, [1, 1]);
}
climate(x: number, z: number): Climate {
// a small warp, so coasts and biome edges aren't the noise's smooth blobs
const wx = x + this.#warp_x.sample(x, z) * 24;
const wz = z + this.#warp_z.sample(x, z) * 24;
return {
continentalness: this.#continentalness(wx, wz),
erosion: QUANTILES_4.even(this.#erosion.sample(wx, wz)) * 1.05,
ridges: QUANTILES_3.even(this.#ridges.sample(wx, wz)) * 0.7,
temperature: QUANTILES_TEMPERATURE.even(this.#temperature.sample(wx, wz)),
humidity: QUANTILES_2.even(this.#humidity.sample(wx, wz)),
constructor(seed: string, generator: Generator) {
this.seed = seed;
this.settings = generator.settings;
this.compiler = new DensityCompiler(seed, generator.sources);
const compile = (json: DensityJson, what: string) => {
try {
return this.compiler.compile(json);
} catch (e) {
throw new Error(`noise settings ${this.settings.id}, ${what}: ${(e as Error).message}`);
}
};
this.#preliminary = compile(this.settings.preliminary_surface, "preliminary_surface");
this.#terrain = compile(this.settings.terrain.density, "terrain");
this.#caves = compile(this.settings.caves.density, "caves");
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));
}
// like tectonic: land is where the continents noise is far from 0, so oceans wind along where it crosses 0. out
// in the deep ocean, islands come up where either of two island noises is high
#continentalness(x: number, z: number) {
const far = Math.abs(QUANTILES_6.even(this.#continents.sample(x, z))) * 0.85;
const continents = -0.8 + CONTINENT_SHAPE.get({ continents: far } as TerrainInputs);
if (continents >= -0.5) return continents;
// scaled so about 3 in 100 of the deep ocean is island, both noises are spread evenly unlike tectonic's
const island = Math.max(
QUANTILES_2.even(this.#island_a.sample(x, z)),
QUANTILES_2.even(this.#island_b.sample(x, z)),
) * 0.76;
const deep = smoothstep(-0.5, -0.8, continents) * 0.7;
return Math.max(continents, (island + 0.05) * deep - 0.7);
// with_climate works the climate out too, which is cheap right after the height since they share their inputs
column(x: number, z: number, with_climate = false): TerrainColumn {
const height = this.#preliminary(x, 0, z);
return with_climate ? { x, z, height, climate: this.climate(x, z) } : { x, z, height };
}
column(x: number, z: number): TerrainColumn {
const climate = this.climate(x, z);
const { continentalness, erosion, ridges } = climate;
const lower = QUANTILES_3.even(this.#lower_tier.sample(x, z));
const upper = QUANTILES_3.even(this.#upper_tier.sample(x, z));
const inputs: TerrainInputs = {
continents: continentalness,
erosion,
erosion_folded: Math.abs(erosion),
ridges,
ridges_folded: Math.abs(ridges),
region: QUANTILES_6.even(this.#region.sample(x, z)) * 0.5 + 0.1,
regions: 0,
temperature: TEMPERATURE_INDEX.get({ temperature: climate.temperature } as TerrainInputs),
vegetation: VEGETATION_INDEX.get({ vegetation: climate.humidity } as TerrainInputs),
lower_tier: Math.abs(lower) * 0.3,
upper_tier: Math.abs(upper) * 0.3,
badlands: Math.abs(QUANTILES_3.even(this.#badlands.sample(x, z))) * 0.7,
hills: Math.abs(QUANTILES_2.even(this.#hills.sample(x, z))),
wetland: QUANTILES_2.even(this.#wetland.sample(x, z)) * 0.6,
pillar: 1.7 * (QUANTILES_2.even(this.#pillar.sample(x, z)) * 0.7 - 0.35),
};
const multiplier = clamp(1.2 + 0.4 * QUANTILES_3.even(this.#height_multiplier.sample(x, z)), 0.8, 1.6);
inputs.regions = multiplier * REGIONS.get(inputs);
const offset = OFFSET.get(inputs) + PILLARS.get(inputs);
let height = offset * BLOCKS_PER_UNIT;
// jagged peaks: sharp ridgelines along the tallest mountains
const jaggedness = clamp(JAGGEDNESS.get(inputs) / 0.2, 0, 1);
if (jaggedness > 0) {
const ridge = 1 - Math.abs(this.#mountain_ridges.sample(x, z));
height += jaggedness * 36 * ridge * ridge;
}
// dunes: long ridges of sand, swept one way
const dunes = DUNES.get(inputs) / 6;
if (dunes > 0) {
const sweep = this.#dune_warp.sample(x, z) * 40;
const crest = 1 - Math.abs(this.#dune.sample(x + sweep, z * 0.35));
height += dunes * 7 * crest * crest;
}
const roughness = ROUGHNESS * 5.6 / FACTOR.get(inputs);
const valley = 1 - inputs.ridges_folded / RIVER_TUNNEL_WIDTH;
const covered = height > RIVER_TUNNEL_TOP - SEA_LEVEL + RIVER_TUNNEL_COVER;
const underground_river = valley > 0 && covered && continentalness > -0.17 ? valley : 0;
return { climate, height: SEA_LEVEL + height, roughness, jaggedness, underground_river };
// the column's climate values, in the order the noise settings name them
climate(x: number, z: number): number[] {
return this.#climate.map((value) => value(x, 0, z));
}
// positive is solid, before caves
density(column: TerrainColumn, x: number, y: number, z: number) {
let density = (column.height - y) / THICKNESS + column.roughness * this.#ground.sample(x, y, z);
if (y > TOP_SLIDE_START) {
density -= smoothstep(TOP_SLIDE_START, TOP_SLIDE_END, y) * 4;
}
if (y < 1) {
density = Math.max(density, 1);
}
return density;
density(_column: TerrainColumn, x: number, y: number, z: number): number {
return this.#terrain(x, y, z);
}
// negative where a cave is. caves stay under the ground's skin except at entrances, and never break
// the floor of oceans and rivers. rivers under mountains are tunnels, see generate_overworld for their water
cave(column: TerrainColumn, x: number, y: number, z: number) {
if (y < MIN_CAVE_Y) {
return 1;
}
let river = 1;
if (column.underground_river > 0 && y >= RIVER_TUNNEL_BOTTOM - 2 && y <= RIVER_TUNNEL_TOP + 2) {
const middle = (RIVER_TUNNEL_BOTTOM + RIVER_TUNNEL_TOP) / 2;
const half = (RIVER_TUNNEL_TOP - RIVER_TUNNEL_BOTTOM) / 2;
river = (Math.max(1 - column.underground_river, Math.abs(y - middle) / half) - 1) * 4;
}
const depth = column.height - y;
if (column.height < SEA_LEVEL + 3 && depth < 14) {
return river;
}
if (depth < 7 && this.#entrances.sample(x, z) < 0.5) {
return river;
}
// negative where a cave is
cave(_column: TerrainColumn, x: number, y: number, z: number): number {
return this.#caves(x, y, z);
}
// cheese caves: big open caverns
const cheese = (0.52 - this.#cheese.sample(x, y, z)) * 4;
// spaghetti caves: long winding tunnels where two noises are both near zero
const a = Math.abs(this.#spaghetti_a.sample(x, y, z));
const b = Math.abs(this.#spaghetti_b.sample(x, y, z));
const spaghetti = (Math.max(a, b) - 0.07) * 8;
return Math.min(cheese, spaghetti, river);
// 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);
for (const rule of this.#rules) {
if (rule.holds(climate, surface_y, steep)) return rule.biome;
}
throw new Error(`no rule of biome source ${this.settings.biome_source} holds at ${column.x}, ${column.z}`);
}
// a column's biome without generating its chunk, 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);
// 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 };
}
}
function compile_rule(biome: string, when: Record<string, RangeJson | boolean>, names: string[]): CompiledRule {
const tests: CompiledRule["holds"][] = [];
for (const [name, condition] of Object.entries(when)) {
if (name === "steep") {
tests.push((_climate, _surface, steep) => steep === condition);
} else if (name === "surface") {
const test = range_test(condition as RangeJson);
tests.push((_climate, surface) => test(surface));
} else {
const index = names.indexOf(name);
const test = range_test(condition as RangeJson);
tests.push((climate) => test(climate[index]));
}
}
return {
biome,
holds(climate, surface_y, steep) {
for (let i = 0; i < tests.length; i++) {
if (!tests[i](climate, surface_y, steep)) return false;
}
return true;
},
};
}
+116 -16
View File
@@ -1,31 +1,101 @@
// imports mods' worldgen scripts and collects what they register. used by client chunk workers and the game server
import type { WorldgenContext } from "$/common/mod_api/worldgen.ts";
// imports mods' worldgen scripts and collects what they and mods' data add to generation: the generator, ores, and
// features, code and data, in the order they run. used by the game server
import type { FeatureBiome, FeatureChunk, FeatureStep, WorldgenContext } from "$/common/mod_api/worldgen.ts";
import type { OreJson } from "$/common/mod_data.ts";
import type { WorldgenSetup } from "./generation.ts";
import type { SetupFeature, WorldgenSetup } from "./generation.ts";
import { EverythingRegistry } from "./everything_registry.ts";
import { ModLoadError } from "./mod_loader.ts";
import { loading_mod } from "./hooks.ts";
import { compile_generator } from "./worldgen/generator.ts";
import type { Biome } from "./worldgen/biomes.ts";
import {
compile_feature,
DEFAULT_STEP,
FEATURE_STEPS,
type FeatureJson,
type FeatureType,
type PlacementModifier,
} from "./worldgen/features.ts";
export async function load_worldgen(
scripts: { mod: string; url: string; engine_access?: boolean }[],
ores: OreJson[],
): Promise<WorldgenSetup> {
const setup: WorldgenSetup = { ores, features: [] };
export interface WorldgenSources {
// every mod's id, in load order
mods: string[];
scripts: { mod: string; url: string; engine_access?: boolean }[];
ores: OreJson[][];
// the noise settings the world uses. it and data features come from mods' data, which is already registered
generator: string;
}
for (const { mod, url, engine_access } of scripts) {
// a feature before it's put in order
interface Pending {
feature: SetupFeature;
mod: string;
step: FeatureStep;
// data features go before a mod's code features, sorted by id. code features keep the order they were registered
data: boolean;
order: number;
}
export async function load_worldgen(sources: WorldgenSources): Promise<WorldgenSetup> {
const setup: WorldgenSetup = {
generator: compile_generator(sources.generator),
ores: sources.ores,
features: [],
placeable: new Map(),
};
const pending: Pending[] = [];
const types = new Map<string, FeatureType>();
const modifiers = new Map<string, PlacementModifier>();
const data_features = (EverythingRegistry.get_registry<FeatureJson>("features") ?? []).filter((f) => f);
const biomes = (EverythingRegistry.get_registry<Biome>("biomes") ?? []).filter((b) => b).map((
biome,
): FeatureBiome => ({
id: biome.id,
...(biome.trees
? { trees: { ...biome.trees, kinds: [...biome.trees.kinds], wood: { ...biome.trees.wood } } }
: {}),
}));
for (const { mod, url, engine_access } of sources.scripts) {
const own = (id: string, what: string) => {
if (!id.startsWith(`${mod}:`)) {
throw new ModLoadError(mod, `${what} ${id} must be in the namespace "${mod}"`);
}
};
const ctx: WorldgenContext = {
register_feature(id, generate) {
if (!id.startsWith(`${mod}:`)) {
throw new ModLoadError(mod, `feature ${id} must be in the namespace "${mod}"`);
register_feature(id, generate, options = {}) {
own(id, "feature");
if (pending.some((p) => p.feature.id === id) || data_features.some((f) => f.id === id)) {
throw new ModLoadError(mod, `feature ${id} is registered twice, as code or data`);
}
if (setup.features.some((f) => f.id === id)) {
throw new ModLoadError(mod, `feature ${id} is registered twice`);
const step = options.step ?? DEFAULT_STEP;
if (!FEATURE_STEPS.includes(step)) {
throw new ModLoadError(mod, `feature ${id}: step must be one of ${FEATURE_STEPS.join(", ")}`);
}
setup.features.push({ id, generate });
const listed = options.biomes === undefined ? undefined : [options.biomes].flat();
pending.push({
feature: { id, generate, ...(listed ? { biomes: new Set(listed) } : {}) },
mod,
step,
data: false,
order: pending.length,
});
},
register_feature_type(id, place) {
own(id, "feature type");
if (types.has(id)) throw new ModLoadError(mod, `feature type ${id} is registered twice`);
types.set(id, place as FeatureType);
},
register_placement_modifier(id, modify) {
own(id, "placement modifier");
if (modifiers.has(id)) throw new ModLoadError(mod, `placement modifier ${id} is registered twice`);
modifiers.set(id, modify as PlacementModifier);
},
biomes: () => biomes,
register_terrain(id) {
throw new ModLoadError(
mod,
`can't register terrain ${id}: the base terrain is still built into the engine (see docs/modding_plan.md)`,
`can't register terrain ${id}: terrain is data now, see docs/modding/worldgen/terrain.md`,
);
},
};
@@ -39,5 +109,35 @@ export async function load_worldgen(
});
}
// data features last, so they can use the types and modifiers every script registered
for (const json of data_features) {
const mod = json.id.split(":")[0];
let compiled;
try {
compiled = compile_feature(json, types, modifiers);
} catch (e) {
throw new ModLoadError(mod, (e as Error).message);
}
const generate = compiled.generate;
setup.placeable.set(json.id, compiled.place);
pending.push({
feature: { id: json.id, generate: (chunk: FeatureChunk) => generate(chunk) },
mod,
step: json.step ?? DEFAULT_STEP,
data: true,
order: 0,
});
}
// by step, then mod, then a mod's data features by id, then its code features as they were registered
const mod_order = new Map(sources.mods.map((mod, i) => [mod, i]));
const order_of = (mod: string) => mod_order.get(mod) ?? sources.mods.length;
pending.sort((a, b) =>
FEATURE_STEPS.indexOf(a.step) - FEATURE_STEPS.indexOf(b.step) ||
order_of(a.mod) - order_of(b.mod) ||
Number(b.data) - Number(a.data) ||
(a.data ? a.feature.id.localeCompare(b.feature.id) : a.order - b.order)
);
setup.features = pending.map((p) => p.feature);
return setup;
}
+1
View File
@@ -7,6 +7,7 @@
"check-mods": "deno run --allow-read --allow-run tools/check_mods.ts",
"pack-mod": "deno run --allow-read --allow-write --allow-run --allow-env tools/pack_mod.ts",
"test": "deno test --allow-read --allow-write --allow-run tests/",
"bench": "deno bench --allow-read --allow-write --allow-run tests/",
"desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-ffi --allow-env=BWORLD_SERVER,BWORLD_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME,DEBUG --include build --include server_mods --include server/game/worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld",
"desktop-all": "deno run -A tools/desktop_all.ts"
},
+4
View File
@@ -22,6 +22,10 @@ mods/
loot_tables/**/*.json # loot tables, see resources/loot_tables.md
worldgen/ores.json
worldgen/biomes/*.json # one biome per file, see worldgen/biomes.md
worldgen/noise/**/*.json # the terrain as data, never sent to players. see worldgen/terrain.md
worldgen/density_function/**/*.json
worldgen/noise_settings/**/*.json
worldgen/biome_source/**/*.json
worldgen/spawns.json # monsters that spawn on their own, see entities/index.md
textures/*.png
textures/*.json # animations, see resources/textures.md
+5 -5
View File
@@ -4,10 +4,8 @@ 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/`.
> [!NOTE]
> Which biome a column gets is still decided by the engine (`pick_biome` in `common/worldgen/overworld.ts`), from the
> column's climate and height. It only picks the base game's biomes, so a biome a mod adds doesn't generate anywhere
> yet. Mods can still list it in their spawns.
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).
## A Biome
@@ -56,7 +54,9 @@ tinted, which trees grow, and whether it has a season of its own. Biomes are dat
| `trees.wood` | the logs and leaves a kind grows here when it isn't its own, like dark oak for `big_oak` | |
Tree kinds are `oak`, `big_oak`, `birch`, `spruce`, `jungle`, `acacia` and `cherry`. Woods are `oak`, `spruce`, `birch`,
`jungle`, `acacia`, `dark_oak` and `cherry`. Trees only grow on grass, dirt or snow with air above.
`jungle`, `acacia`, `dark_oak` and `cherry`. Trees only grow on grass, dirt or snow with air above. They're the base
game's trees feature (`mods/bworld/scripts/trees.ts`), which reads every biome's `trees`. It checks the kinds and woods
when the server starts, so `check-mods` doesn't.
Above the snow line, around y 176, the top block is snow whatever the biome says.
+124 -15
View File
@@ -19,9 +19,9 @@ and their builds end up half buried.
Each chunk goes through three passes:
1. **Terrain.** The ground, water, caves and trees. This is built into the engine for now, see below.
2. **Ores.** Every mod's `worldgen/ores.json`, in load order.
3. **Features.** Every mod's registered features, in load order.
1. **Terrain.** The ground, water, caves and biomes, from data, see [Terrain](terrain.md).
2. **Ores.** Every mod's `worldgen/ores.json`, in load order, the base game's first.
3. **Features.** Every mod's features, code and data, by step and then load order, see [Order](#order).
The world is 256 blocks tall and the sea is at y 64.
@@ -49,9 +49,30 @@ Every block in the chunk that is `replaces` and between `min_y` and `max_y` beco
sampled at `(x, y, z) × scale`, is above `threshold`. A smaller `scale` makes bigger veins, and a higher `threshold`
makes rarer ones. Each ore's noise is seeded with its id, so ores don't line up with each other.
Each mod's ores are a pass of their own, after the mods loaded before it. So a mod's ore can replace another mod's, like
`"replaces": "bworld:coal_ore"` for a rare vein inside coal. The base game's are in `mods/bworld/worldgen/ores.json`.
## Features
Features are functions that run on every chunk after terrain and ores. The worldgen script registers them:
Features are what's added to every chunk after its terrain and ores: trees, cacti, boulders, springs. A feature is code
or data, whichever is easier for it, and the two can use each other:
- **Data** suits a known kind of thing placed somewhere, like a column of cactus on sand. It's short, `check-mods`
checks it, and it can use types and modifiers a script registers.
- **Code** suits logic that doesn't fit a type, like the base game's trees, which spread themselves over a grid of cells
across chunks (`mods/bworld/scripts/trees.ts`).
### Order
Features run by **step**, Minecraft's decoration steps: `raw_generation`, `lakes`, `local_modifications`,
`underground_structures`, `surface_structures`, `strongholds`, `underground_ores`, `underground_decoration`,
`fluid_springs`, `vegetal_decoration`, `top_layer_modification`. A feature without a step runs in the last one. Within a
step they go by mod load order, and within a mod its data features go first, sorted by id, then its code features in the
order they were registered. The base game's trees are in `vegetal_decoration`, so features in later steps see them.
### Code Features
The worldgen script registers them:
```ts
import type { WorldgenContext } from "bworld/worldgen";
@@ -62,10 +83,12 @@ export function setup(gen: WorldgenContext) {
const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16);
const z = chunk.z * 16 + Math.floor(chunk.rng.next() * 16);
chunk.set_block(x, chunk.height_at(x, z) + 1, z, "bworld:stone");
});
}, { step: "surface_structures", biomes: ["bworld:plains", "bworld:meadow"] });
}
```
`step` and `biomes` are optional. With `biomes`, the feature only runs in chunks that have one of them.
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.
@@ -75,36 +98,122 @@ interface FeatureChunk {
readonly z: number;
readonly seed: string;
readonly rng: { next(): number }; // 0 to 1
random(name: string): { next(): number }; // seeded from the world's seed and name, the same in every chunk
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
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
}
```
All coordinates are world coordinates. `noise_2d` and `noise_3d` return seeded noise functions, the same for the same
`name` in every chunk, so features can make patterns that continue across chunk borders.
`name` in every chunk, so features can make patterns that continue across chunk borders. `random` does the same for
random numbers: the base game's trees take each cell's from `random("tree_<x>_<z>")`, so every chunk that looks at a
cell agrees on where its tree is.
`set_block` can write up to one chunk away, so a tree near the border can grow into the next chunk. Writes into another
chunk only fill air, so the result doesn't depend on which chunk generates first.
`gen.biomes()` lists every biome mods added, with their `trees`, for features that read biomes' data the way the base
game's trees do.
Generated blocks don't run `on_create`, and worldgen scripts can't use the server or client API.
### Data Features
A file in `worldgen/features/`: Minecraft's configured feature (`type` and `config`, what) and placed feature
(`placement`, where) in one, plus `biomes` and `step`:
```json
{
"format_version": 1,
"feature": {
"id": "copper_tools:cobble_columns",
"type": "minecraft:block_column",
"config": {
"layers": [{
"height": { "type": "uniform", "min_inclusive": 1, "max_inclusive": 3 },
"provider": "bworld:cobblestone"
}]
},
"placement": [
{ "type": "minecraft:count", "count": 4 },
{ "type": "minecraft:in_square" },
{ "type": "minecraft:heightmap", "heightmap": "OCEAN_FLOOR_WG" }
],
"biomes": ["bworld:plains"],
"step": "underground_decoration"
}
}
```
Placement starts at the chunk's corner at the bottom of the world, and each modifier turns the positions so far into new
ones. The feature's type is placed at each position that ends up in one of `biomes`, or at every one without `biomes`.
Built in names work with or without `minecraft:`.
| Type | Config | Places |
| -------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `simple_block` | `to_place` | One block, where it can stand (its `place_on`). |
| `block_column` | `layers` (`height`, `provider`), `direction`, `allowed_placement`, `prioritize_tip` | Layers stacked `up` (or `down`), cut short where `allowed_placement` doesn't hold (air when not set). |
| Placement modifier | Fields | Does |
| ------------------------ | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `count` | `count` | Each position becomes `count` of them. |
| `rarity_filter` | `chance` | Keeps one in `chance`. |
| `in_square` | | Moves each to a random spot in the chunk, across. |
| `random_offset` | `xz_spread`, `y_spread` | Moves each by those amounts. |
| `height_range` | `height` | Sets the height: an anchor or `constant`/`uniform` of anchors. |
| `heightmap` | `heightmap` | On top of the column: `WORLD_SURFACE_WG`, `WORLD_SURFACE` and `MOTION_BLOCKING` on its highest block, `OCEAN_FLOOR_WG` and `OCEAN_FLOOR` on its highest that isn't a liquid. |
| `block_predicate_filter` | `predicate` | Keeps the positions where a block predicate holds. |
- **Block predicates:** `matching_blocks` (`blocks`: ids and #tags), `solid`, `replaceable`, `would_survive` (`state`),
`not`, `all_of`, `any_of` and `true`. Each takes an `offset`.
- **Numbers** (int providers): a whole number, or `constant`, `uniform` (`min_inclusive`, `max_inclusive`) or
`weighted_list` (`distribution` of `data` and `weight`).
- **Heights:** `{ "absolute": y }`, `{ "above_bottom": n }` or `{ "below_top": n }`.
- **Blocks** (`to_place`, `provider`, `state`): an id, or Minecraft's
`{ "type": "simple_state_provider", "state": { "Name": id } }`.
### Types and Modifiers in Code
A worldgen script can add types and placement modifiers for data features to use, by id:
```ts
gen.register_feature_type<{ block: string; height: number }>("copper_tools:pillar", (chunk, config, origin) => {
for (let i = 0; i < config.height; i++) chunk.set_block(origin.x, origin.y + i, origin.z, config.block);
return true;
});
gen.register_placement_modifier(
"copper_tools:middle",
(chunk, config, positions) => positions.map((p) => ({ x: chunk.x * 16 + 8, y: p.y, z: chunk.z * 16 + 8 })),
);
```
And code can place a data feature with `chunk.place_feature(id, x, y, z)`: its type and config at that spot, without its
placement, with the calling feature's random numbers.
`check-mods` can't run scripts, so it warns about a type or modifier that isn't built in. The server checks them when it
starts, and doesn't start if a data feature uses one no script registered, or if an id is both a code and a data
feature.
## Terrain
The terrain itself is built into the engine (`common/worldgen/`). It works like Minecraft 1.18+, shaped after the
[Tectonic](https://github.com/Apollounknowndev/tectonic) mod: continents, erosion and ridges noises set every column's
height and roughness, and a 3D density is carved into caves. Oceans wind between large continents, with islands out at
sea. Mountain ranges rise where erosion is low, and rivers run along the valleys between ridges, going underground where
they reach mountains. The flatter land is split into regions with their own shapes: valleys and plateaus (with badlands
ridges where it's hot), tiered mesas, rolling hills and jungle pillars, and wetlands and desert dunes.
The terrain is data: noises, density functions, a generator and biome rules, see [Terrain](terrain.md). The base game's
works like Minecraft 1.18+, shaped after the [Tectonic](https://github.com/Apollounknowndev/tectonic) mod: continents,
erosion and ridges noises set every column's height and roughness, and a 3D density is carved into caves. Oceans wind
between large continents, with islands out at sea. Mountain ranges rise where erosion is low, and rivers run along the
valleys between ridges, going underground where they reach mountains. The flatter land is split into regions with their
own shapes: valleys and plateaus (with badlands ridges where it's hot), tiered mesas, rolling hills and jungle pillars,
and wetlands and desert dunes.
Which biome each column gets is part of the terrain, but what a biome looks like is data: see [Biomes](biomes.md).
Which biome each column gets is the generator's biome rules, see [Biome Sources](terrain.md#biome-sources), and what a
biome looks like is its own file, see [Biomes](biomes.md).
`deno run -A tools/worldgen_preview.ts [seed] [out dir] [x z]` renders it to PNG files, around chunk `x z`.
> [!NOTE]
> `register_terrain` exists in the API for mods that replace the terrain generator, but it throws for now: the terrain
> hasn't moved out of the engine yet.
> `register_terrain` exists in the API for mods that replace the terrain with code, but it throws: the terrain is data,
> see [Terrain](terrain.md).
+257
View File
@@ -0,0 +1,257 @@
# Terrain
The shape of the world, which biome each column gets, what its ground is made of and where water goes are all data, in a
mod's `worldgen/` folders. The engine only knows how to evaluate them. The base game's overworld is in
`mods/bworld/worldgen/`, and a mod can add biomes to it with rules of its own.
It works like Minecraft's: noises feed **density functions**, a **noise settings** file puts them together into a
generator, and a **biome source** picks biomes. The names and fields follow Minecraft's where the idea is the same, so
the [Minecraft Wiki](https://minecraft.wiki/w/Density_function) explains most of them. Where bworld differs, it says so
below.
These files are server only: they're left out of the copy of a `.bmod` players download.
```
my_mod/
worldgen/noise/<path>.json # noises
worldgen/density_function/<path>.json # named density functions
worldgen/noise_settings/<path>.json # generators
worldgen/biome_source/<path>.json # biome rules, or rules added to another mod's
```
Ids can have folders, like `bworld:overworld/erosion` in `worldgen/density_function/overworld/erosion.json`.
## How a Chunk Is Made
1. The generator's `terrain` and `caves` density functions are sampled at the corners of cells, `cell_width` blocks
across and each one's `cell_height` up, and blended in between. A block is solid where both are above 0.
2. Each column's biome is the first biome rule that holds, from its climate, the height of its ground and whether it's
steep.
3. Each solid block goes through the `surface_rule`, which gives grass, sand, snow and so on, or `default_block`.
4. Each empty block below the surface of a `fluid` gets it, like water up to sea level.
5. Then [ores](index.md#ores) and [features](index.md#features), like the base game's trees, which grow as the biome's
`trees` say.
## Noises
`worldgen/noise/erosion.json`:
```json
{
"format_version": 1,
"noise": {
"id": "bworld:erosion",
"wavelength": 1280,
"amplitudes": [1, 1, 0, 1, 1],
"quantiles": [-0.917, -0.48, -0.393, "...", 0.917]
}
}
```
| Field | Meaning | Default |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `wavelength` | The size in blocks of the first octave's features. | required |
| `amplitudes` | Each octave's strength. Each octave is twice as fine as the one before. 0 skips one. | required |
| `dimensions` | `2` for x and z, `3` for x, y and z. | `2` |
| `vertical_stretch` | For 3D noises, how much slower it changes up and down than across. | `1` |
| `quantiles` | The noise's percentiles, every 5%, for spreading it evenly from -1 to 1 (see `even` below). Or another noise's id to use its table. | none |
| `seed_name` | What it's seeded with, together with the world's seed. | the id's path |
Unlike Minecraft's, bworld's noises are simplex noise sized by `wavelength` instead of a first octave. Octave noise is
bunched up in the middle of its range. `deno run tools/noise_quantiles.ts '[1,1,0,1,1]'` measures the `quantiles` for a
set of amplitudes, so `"even": true` can spread it out.
## Density Functions
A density function gives a number for every block. A file in `worldgen/density_function/` is one with an `id`:
```json
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/erosion",
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:erosion",
"even": true,
"x": "bworld:overworld/warp_x",
"z": "bworld:overworld/warp_z"
},
"argument2": 1.05
}
}
```
Wherever a density function goes, a number is a constant and a string is a named density function's id.
| Type | Fields | Gives |
| ---------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `constant` | `argument` | The number. A bare number does the same. |
| `x`, `y`, `z` | | The block's position. bworld's own. |
| `noise` | `noise`, `even`, `x`, `y`, `z` | The noise at the block, or at the position `x`, `y` and `z` give. `even` spreads it by its quantiles. |
| `add`, `sub`, `mul`, `div`, `min`, `max` | `argument1`, `argument2` | The two put together. `sub` and `div` are bworld's own. |
| `abs` | `argument` | Without its sign. |
| `clamp` | `input`, `min`, `max` | `input`, kept from `min` to `max`. |
| `smoothstep` | `input`, `from`, `to` | 0 at `from`, 1 at `to`, a smooth curve in between. bworld's own. |
| `spline` | `spline`: `{ coordinate, points }` | A smooth curve through `points` (`{ location, value, derivative }`) along `coordinate`. A `value` can be another spline, like Minecraft's. `derivative` is 0 when left out. |
| `range_choice` | `input`, bounds, `when_in_range`, `when_out_of_range` | One or the other by whether `input` is within the bounds: `min_inclusive`, `min_exclusive`, `max_inclusive`, `max_exclusive`, any of them. A bound can be a density function. |
| `cache_2d` | `argument` | The same, worked out once per column. Only for functions that don't change with y. |
Named density functions that don't change with y are worked out once per column on their own, so a function used by
several others, like `bworld:overworld/continents`, costs the same as using it once.
Every operation takes two arguments, so how its numbers round is written down. Two generators that do the same sums in
the same order make the same world block for block. The base game's terrain was moved from code into these files that
way, and `tests/worldgen_golden_test.ts` checks it never changes by accident.
## Noise Settings
A generator. The base game's is `worldgen/noise_settings/overworld.json`:
```json
{
"format_version": 1,
"noise_settings": {
"id": "bworld:overworld",
"sea_level": 64,
"default_block": "bworld:stone",
"cell_width": 4,
"terrain": { "density": "bworld:overworld/terrain", "cell_height": 8 },
"caves": { "density": "bworld:overworld/caves", "cell_height": 4 },
"preliminary_surface": "bworld:overworld/height",
"climate": {
"continentalness": "bworld:overworld/continents",
"temperature": "bworld:overworld/temperature",
"humidity": "bworld:overworld/humidity",
"valley": "bworld:overworld/ridges_folded",
"flatness": "bworld:overworld/erosion_folded",
"jaggedness": "bworld:overworld/jaggedness"
},
"steep": 3.5,
"biome_source": "bworld:overworld",
"fluids": [
{ "block": "bworld:water", "below": 64, "where": "open_sky" },
{
"block": "bworld:water",
"below": 64,
"where": { "function": "bworld:overworld/underground_river", "min_exclusive": 0 }
}
],
"surface_rule": { "...": "see below" }
}
}
```
| Field | Meaning |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `sea_level` | Where the sea's surface is, for surface rules. |
| `default_block` | What solid ground is where the surface rule doesn't say otherwise. |
| `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`. |
| `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. |
| `surface_rule` | What solid blocks become. |
The world uses `bworld:overworld`. The server doesn't start without it.
## Biome Sources
The rules that pick a column's biome. The first that holds wins, so they go from the most particular to the most
general. The base game's, `worldgen/biome_source/overworld.json`, starts with rivers and oceans under water and ends
with `bworld:dark_forest`, which holds everywhere:
```json
{
"format_version": 1,
"biome_source": {
"id": "bworld:overworld",
"rules": [
{
"id": "bworld:river_bed_frozen",
"when": {
"surface": { "max_exclusive": 63 },
"valley": { "max_exclusive": 0.06 },
"continentalness": { "min_exclusive": -0.2 },
"temperature": { "max_exclusive": -0.65 }
},
"biome": "bworld:frozen_river"
},
{ "id": "bworld:dark_forest", "biome": "bworld:dark_forest" }
]
}
}
```
`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.
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.
### Adding Biomes
A mod adds its biomes with a biome source that `extends` another, putting each rule `before` or `after` one of its
rules. Lavender fields on all the land above the beaches that isn't mountains, before the climate picks forests and
plains:
```json
{
"format_version": 1,
"biome_source": {
"id": "lavender:fields",
"extends": "bworld:overworld",
"rules": [{
"id": "lavender:fields",
"before": "bworld:snowy_taiga",
"when": { "surface": { "min_inclusive": 70, "max_inclusive": 120 } },
"biome": "lavender:fields"
}]
}
}
```
Rules from several mods go in in load order. The biome itself is a [biome file](biomes.md) as usual.
## 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
`sequence` that gives a block wins. Blocks no rule gives anything for are the `default_block`.
| Rule | Fields | Gives |
| --------------- | ------------------------ | -------------------------------------------------------------------------------------------- |
| `sequence` | `sequence` | The first block its rules give. |
| `condition` | `if_true`, `then_run` | What `then_run` gives, when `if_true` holds. |
| `block` | `result_state: { Name }` | That block. |
| `biome_surface` | `part` | The column's biome's `top`, `filler`, `underwater_top` or `underwater_filler`. bworld's own. |
| Condition | Fields | Holds |
| --------------------------- | ---------- | ----------------------------------------------------------------------------------- |
| `stone_depth` | `offset` | When the solid blocks above it before air are at most `offset`. 0 is the top block. |
| `filler_depth` | | Within the biome's `filler_depth` below the top. bworld's own. |
| `above_preliminary_surface` | `offset` | At or above the preliminary surface plus `offset`. |
| `surface_underwater` | | When the column's ground is below `sea_level` - 1. bworld's own. |
| `steep` | | When the column is steep, see the noise settings' `steep`. |
| `bare_cliffs` | | When the biome's surface has `bare_cliffs`. bworld's own. |
| `y_at_least` | `function` | At or above the height a density function gives, like a snow line. bworld's own. |
| `biome` | `biome_is` | In one of the biomes. |
| `not` | `invert` | When `invert` doesn't. |
The base game's: within 20 blocks of the ground, the top block is the biome's underwater cover under water, snow (or
stone on cliffs) above the snow line, stone on bare cliffs, and the biome's `top` otherwise. Below it, the biome's
filler down to its `filler_depth`. Everything else is stone.
## Changing the Base Game's Terrain
A mod can add biomes to it, but can't replace its files yet: an id defined by two mods is an error. Anything that
changes the terrain changes untouched land in existing worlds, the same as adding a [feature](index.md#features). The
worldgen fingerprint keeps chunks players changed as they were.
[Engine access](../misc/engine.md) mods can hook `engine.common.OverworldTerrain`, whose `density` and `cave` are called
for every cell corner.
`deno run -A tools/worldgen_preview.ts [seed] [out dir] [x z]` renders the base game's generator to PNG files, around
chunk `x z`.
+6 -5
View File
@@ -283,7 +283,8 @@ engine assets in `assets/`.
| Mining: tool speed, `requires_tool`, drops | engine (`client/game_mode.ts`, `server/game/game_server.ts`) | Phase 5 |
| Day and night lengths, sky colors | engine (`common/time.ts`, `client/rendering/game_renderer.ts`) | Phase 5 |
| Where new players spawn | engine (`server/game/world.ts`) | Phase 5 |
| Terrain, biomes, trees and ores | engine (`common/worldgen/`, `common/generation.ts`) | Phase 6 |
| Terrain, biomes and ores | `mods/bworld/worldgen/` (data) | Done |
| Trees | `mods/bworld/scripts/trees.ts` (a code feature) | Done |
### Rules That Keep Existing Worlds Working
@@ -340,10 +341,10 @@ and dropped, containers clicked, players moving between chunks, entities.
rules become something `mods/bworld` sets, with the engine asking it on both sides so clients still predict breaking.
Check: all tests pass unchanged, and old saves still load.
**Phase 6: world generation.** First a golden fixture: a SHA-256 of the final blocks of 64 chunks for 3 seeds, recorded
from the current code. Then port `common/worldgen/` to `mods/bworld/scripts/worldgen.ts` as the `bworld:overworld`
terrain generator (with `register_terrain`), and the ore table to `mods/bworld/worldgen/ores.json`. The server refuses
to start without a terrain generator. Check: the fixture matches exactly.
**Phase 6: world generation.** Moved to data instead of a worldgen script, see [GENERATION.md](../GENERATION.md). The
golden fixture, the ore table, and the terrain, biomes, surface and water as data are done: the server refuses to start
without the `bworld:overworld` generator, and the fixture matches exactly. Trees are a code feature in bworld's worldgen
script.
**Done when** searching `client/`, `common/` and `server/` for `"bworld:` finds only `bworld:air`, removing
`mods/bworld` gives an engine that starts and says it needs a terrain generator, the base game uses no engine access,
+2 -1
View File
@@ -83,7 +83,8 @@ SOFTWARE.
# Tectonic
The overworld's terrain is shaped after Tectonic by Apollo: https://github.com/Apollounknowndev/tectonic
The overworld's terrain is shaped after Tectonic by Apollo: https://github.com/Apollounknowndev/tectonic. Its splines
are ported to `worldgen/density_function/overworld`.
License: MIT
@@ -1,11 +1,13 @@
// trees, part of the terrain pass. where they grow can't depend on which chunk generates first, so it only
// depends on the seed: every CELL x CELL cell has one candidate spot and a random priority, and a candidate becomes a
// tree only if no other candidate within MIN_DISTANCE has a higher priority (then its biome may still say no). that
// spreads trees out like poisson disk sampling: never closer than MIN_DISTANCE, but without lining up in a grid.
// a tree is placed by the chunk its trunk is in, leaves that reach into the next chunk go through the spills like any
// other block there
import { Alea } from "@paulaboks/rng";
import { CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts";
// the base game's trees, a feature that's code. biomes say which kinds grow and how often (their json's "trees"), this
// says what the kinds are. where they grow can't depend on which chunk generates first, so it only depends on the
// seed: every CELL x CELL cell has one candidate spot and a random priority, and a candidate becomes a tree only if no
// other candidate within MIN_DISTANCE has a higher priority (then its biome may still say no). that spreads trees out
// like poisson disk sampling: never closer than MIN_DISTANCE, but without lining up in a grid. a tree is placed by the
// chunk its trunk is in, leaves that reach into the next chunk only fill air there
import type { FeatureBiome, FeatureChunk, WorldgenContext } from "bworld/worldgen";
const CHUNK_SIZE = 16;
const CHUNK_HEIGHT = 256;
const CELL = 4;
// trunks are at least this far apart
@@ -20,11 +22,13 @@ export type TreeKind = typeof TREE_KINDS[number];
export const WOODS = ["oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "cherry"] as const;
export type Wood = typeof WOODS[number];
type Random = { next(): number };
export interface TreeSite {
x: number;
z: number;
// seeded from the cell, what's left of it picks the tree
rng: Alea;
rng: Random;
}
interface Candidate extends TreeSite {
@@ -32,23 +36,23 @@ interface Candidate extends TreeSite {
}
// every cell's candidate, from the seed and the cell alone
function candidate(seed: string, cell_x: number, cell_z: number): Candidate {
const rng = new Alea(`${seed}_tree_${cell_x}_${cell_z}`);
function candidate(chunk: FeatureChunk, cell_x: number, cell_z: number): Candidate {
const rng = chunk.random(`tree_${cell_x}_${cell_z}`);
const x = cell_x * CELL + Math.floor(rng.next() * CELL);
const z = cell_z * CELL + Math.floor(rng.next() * CELL);
return { x, z, priority: rng.next(), rng };
}
// the spots in the chunk where a tree may grow, before biome and ground are checked
export function tree_sites(seed: string, chunk_x: number, chunk_z: number): TreeSite[] {
function tree_sites(chunk: FeatureChunk): TreeSite[] {
const cells = CHUNK_SIZE / CELL;
const first_x = chunk_x * cells - REACH;
const first_z = chunk_z * cells - REACH;
const first_x = chunk.x * cells - REACH;
const first_z = chunk.z * cells - REACH;
const size = cells + 2 * REACH;
const candidates: Candidate[] = [];
for (let cz = 0; cz < size; cz++) {
for (let cx = 0; cx < size; cx++) {
candidates.push(candidate(seed, first_x + cx, first_z + cz));
candidates.push(candidate(chunk, first_x + cx, first_z + cz));
}
}
@@ -74,11 +78,11 @@ export function tree_sites(seed: string, chunk_x: number, chunk_z: number): Tree
return sites;
}
// log replaces anything that isn't ground, leaves only fill air
export type PlaceBlock = (x: number, y: number, z: number, block: "log" | "leaves") => void;
// log replaces leaves, everything else only fills air
type PlaceBlock = (x: number, y: number, z: number, block: "log" | "leaves") => void;
// grows a tree with its trunk's bottom at x, y, z. returns false when it wouldn't fit under the top of the world
export function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Alea, place: PlaceBlock) {
function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random, place: PlaceBlock) {
const random = (min: number, max: number) => min + Math.floor(rng.next() * (max - min + 1));
const trunk = (height: number) => {
for (let i = 0; i < height; i++) place(x, y + i, z, "log");
@@ -195,3 +199,60 @@ export function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng:
}
return true;
}
// trees grow on these, with air above
const SOIL = new Set(["bworld:grass", "bworld:dirt", "bworld:snow_block"]);
const LEAVES = new Set(WOODS.map((wood) => `bworld:${wood}_leaves`));
export function register_trees(gen: WorldgenContext) {
const trees = new Map<string, NonNullable<FeatureBiome["trees"]>>();
for (const biome of gen.biomes()) {
if (!biome.trees) continue;
for (const kind of biome.trees.kinds) {
if (!TREE_KINDS.includes(kind as TreeKind)) {
throw new Error(`biome ${biome.id}: trees.kinds: ${kind} isn't one of ${TREE_KINDS.join(", ")}`);
}
}
for (const [kind, wood] of Object.entries(biome.trees.wood)) {
if (!TREE_KINDS.includes(kind as TreeKind)) {
throw new Error(`biome ${biome.id}: trees.wood: ${kind} isn't a kind of tree`);
}
if (!WOODS.includes(wood as Wood)) {
throw new Error(`biome ${biome.id}: trees.wood.${kind} must be one of ${WOODS.join(", ")}`);
}
}
trees.set(biome.id, biome.trees);
}
gen.register_feature("bworld:trees", (chunk) => {
const x0 = chunk.x * CHUNK_SIZE;
const z0 = chunk.z * CHUNK_SIZE;
const place = (x: number, y: number, z: number, block: "log" | "leaves", wood: string) => {
if (y < 0 || y >= CHUNK_HEIGHT) return;
const id = `bworld:${wood}_${block}`;
if (x < x0 || x >= x0 + CHUNK_SIZE || z < z0 || z >= z0 + CHUNK_SIZE) {
// the other chunk only takes it where it has air
chunk.set_block(x, y, z, id);
return;
}
const current = chunk.get_block(x, y, z);
if (current === "bworld:air" || (block === "log" && LEAVES.has(current!))) chunk.set_block(x, y, z, id);
};
for (const site of tree_sites(chunk)) {
const here = trees.get(chunk.biome_at(site.x, 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 !== "bworld:air") continue;
const kind = here.kinds[Math.floor(site.rng.next() * here.kinds.length)] as TreeKind;
// big oaks grow oak, every other kind its own wood, unless the biome says
const wood = here.wood[kind] ?? (kind === "big_oak" ? "oak" : kind);
grow_tree(kind, site.x, ground_y + 1, site.z, site.rng, (x, y, z, block) => place(x, y, z, block, wood));
}
}, { step: "vegetal_decoration" });
}
+5 -2
View File
@@ -1,8 +1,11 @@
// the base game's features, on top of the engine's terrain. runs in chunk workers and must give the same world every
// time: only chunk.rng and the noise helpers, never Math.random or the time
// the base game's features, on top of the terrain (which is data, worldgen/). runs on the server and must give the
// same world every time: only chunk.rng, chunk.random and the noise helpers, never Math.random or the time
import type { FeatureChunk, WorldgenContext } from "bworld/worldgen";
import { register_trees } from "./trees.ts";
export function setup(gen: WorldgenContext) {
// trees grow in vegetal_decoration, before the cactus looks for air in the last step
register_trees(gen);
gen.register_feature("bworld:cactus", cactus);
}
@@ -0,0 +1,391 @@
{
"format_version": 1,
"biome_source": {
"id": "bworld:overworld",
"rules": [
{
"id": "bworld:river_bed_frozen",
"when": {
"surface": {
"max_exclusive": 63
},
"valley": {
"max_exclusive": 0.06
},
"continentalness": {
"min_exclusive": -0.2
},
"temperature": {
"max_exclusive": -0.65
}
},
"biome": "bworld:frozen_river"
},
{
"id": "bworld:river_bed",
"when": {
"surface": {
"max_exclusive": 63
},
"valley": {
"max_exclusive": 0.06
},
"continentalness": {
"min_exclusive": -0.2
}
},
"biome": "bworld:river"
},
{
"id": "bworld:deep_frozen_ocean",
"when": {
"surface": {
"max_exclusive": 63
},
"continentalness": {
"max_exclusive": -0.45
},
"temperature": {
"max_exclusive": -0.65
}
},
"biome": "bworld:deep_frozen_ocean"
},
{
"id": "bworld:deep_lukewarm_ocean",
"when": {
"surface": {
"max_exclusive": 63
},
"continentalness": {
"max_exclusive": -0.45
},
"temperature": {
"min_exclusive": 0.55
}
},
"biome": "bworld:deep_lukewarm_ocean"
},
{
"id": "bworld:deep_ocean",
"when": {
"surface": {
"max_exclusive": 63
},
"continentalness": {
"max_exclusive": -0.45
}
},
"biome": "bworld:deep_ocean"
},
{
"id": "bworld:frozen_ocean",
"when": {
"surface": {
"max_exclusive": 63
},
"temperature": {
"max_exclusive": -0.65
}
},
"biome": "bworld:frozen_ocean"
},
{
"id": "bworld:warm_ocean",
"when": {
"surface": {
"max_exclusive": 63
},
"temperature": {
"min_exclusive": 0.55
}
},
"biome": "bworld:warm_ocean"
},
{
"id": "bworld:ocean",
"when": {
"surface": {
"max_exclusive": 63
}
},
"biome": "bworld:ocean"
},
{
"id": "bworld:stony_shore",
"when": {
"continentalness": {
"max_exclusive": -0.12
},
"surface": {
"max_inclusive": 68
},
"steep": true
},
"biome": "bworld:stony_shore"
},
{
"id": "bworld:snowy_beach",
"when": {
"continentalness": {
"max_exclusive": -0.12
},
"surface": {
"max_inclusive": 68
},
"temperature": {
"max_exclusive": -0.3
}
},
"biome": "bworld:snowy_beach"
},
{
"id": "bworld:beach",
"when": {
"continentalness": {
"max_exclusive": -0.12
},
"surface": {
"max_inclusive": 68
}
},
"biome": "bworld:beach"
},
{
"id": "bworld:river_frozen",
"when": {
"valley": {
"max_exclusive": 0.04
},
"continentalness": {
"min_exclusive": -0.2
},
"surface": {
"max_inclusive": 65
},
"temperature": {
"max_exclusive": -0.65
}
},
"biome": "bworld:frozen_river"
},
{
"id": "bworld:river",
"when": {
"valley": {
"max_exclusive": 0.04
},
"continentalness": {
"min_exclusive": -0.2
},
"surface": {
"max_inclusive": 65
}
},
"biome": "bworld:river"
},
{
"id": "bworld:frozen_peaks",
"when": {
"surface": {
"min_exclusive": 169
},
"temperature": {
"max_exclusive": -0.3
}
},
"biome": "bworld:frozen_peaks"
},
{
"id": "bworld:jagged_peaks",
"when": {
"surface": {
"min_exclusive": 169
},
"jaggedness": {
"min_exclusive": 0.35
}
},
"biome": "bworld:jagged_peaks"
},
{
"id": "bworld:stony_peaks",
"when": {
"surface": {
"min_exclusive": 169
}
},
"biome": "bworld:stony_peaks"
},
{
"id": "bworld:snowy_slopes",
"when": {
"surface": {
"min_exclusive": 124
},
"temperature": {
"max_exclusive": -0.3
}
},
"biome": "bworld:snowy_slopes"
},
{
"id": "bworld:meadow",
"when": {
"surface": {
"min_exclusive": 94
},
"temperature": {
"min_inclusive": -0.3
},
"humidity": {
"min_exclusive": -0.3
}
},
"biome": "bworld:meadow"
},
{
"id": "bworld:snowy_taiga",
"when": {
"temperature": {
"max_exclusive": -0.65
},
"humidity": {
"min_exclusive": 0
}
},
"biome": "bworld:snowy_taiga"
},
{
"id": "bworld:snowy_plains",
"when": {
"temperature": {
"max_exclusive": -0.65
}
},
"biome": "bworld:snowy_plains"
},
{
"id": "bworld:taiga",
"when": {
"temperature": {
"max_exclusive": -0.3
},
"humidity": {
"min_exclusive": 0
}
},
"biome": "bworld:taiga"
},
{
"id": "bworld:cold_plains",
"when": {
"temperature": {
"max_exclusive": -0.3
}
},
"biome": "bworld:plains"
},
{
"id": "bworld:desert",
"when": {
"temperature": {
"min_exclusive": 0.55
},
"humidity": {
"max_exclusive": -0.2
}
},
"biome": "bworld:desert"
},
{
"id": "bworld:hot_savanna",
"when": {
"temperature": {
"min_exclusive": 0.55
},
"humidity": {
"max_exclusive": 0.4
}
},
"biome": "bworld:savanna"
},
{
"id": "bworld:hot_jungle",
"when": {
"temperature": {
"min_exclusive": 0.55
}
},
"biome": "bworld:jungle"
},
{
"id": "bworld:warm_savanna",
"when": {
"temperature": {
"min_exclusive": 0.2
},
"humidity": {
"max_exclusive": -0.3
}
},
"biome": "bworld:savanna"
},
{
"id": "bworld:warm_jungle",
"when": {
"temperature": {
"min_exclusive": 0.2
},
"humidity": {
"min_exclusive": 0.6
}
},
"biome": "bworld:jungle"
},
{
"id": "bworld:warm_forest",
"when": {
"temperature": {
"min_exclusive": 0.2
}
},
"biome": "bworld:forest"
},
{
"id": "bworld:swamp",
"when": {
"humidity": {
"min_exclusive": 0.5
},
"flatness": {
"min_exclusive": 0.6
}
},
"biome": "bworld:swamp"
},
{
"id": "bworld:dry_plains",
"when": {
"humidity": {
"max_exclusive": -0.35
}
},
"biome": "bworld:plains"
},
{
"id": "bworld:forest",
"when": {
"humidity": {
"max_exclusive": 0.45
}
},
"biome": "bworld:forest"
},
{
"id": "bworld:dark_forest",
"biome": "bworld:dark_forest"
}
]
}
}
@@ -0,0 +1,16 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/badlands",
"type": "mul",
"argument1": {
"type": "abs",
"argument": {
"type": "noise",
"noise": "bworld:badlands",
"even": true
}
},
"argument2": 0.7
}
}
@@ -0,0 +1,20 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/cave_entrances",
"type": "range_choice",
"input": "bworld:overworld/depth",
"max_exclusive": 7,
"when_in_range": {
"type": "range_choice",
"input": {
"type": "noise",
"noise": "bworld:entrances"
},
"max_exclusive": 0.5,
"when_in_range": "bworld:overworld/river_tunnel",
"when_out_of_range": "bworld:overworld/open_caves"
},
"when_out_of_range": "bworld:overworld/open_caves"
}
}
@@ -0,0 +1,37 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/caves",
"type": "range_choice",
"input": {
"type": "y"
},
"min_exclusive": {
"type": "add",
"argument1": "bworld:overworld/height",
"argument2": 4
},
"when_in_range": 1,
"when_out_of_range": {
"type": "range_choice",
"input": {
"type": "y"
},
"max_exclusive": 5,
"when_in_range": 1,
"when_out_of_range": {
"type": "range_choice",
"input": "bworld:overworld/height",
"max_exclusive": 67,
"when_in_range": {
"type": "range_choice",
"input": "bworld:overworld/depth",
"max_exclusive": 14,
"when_in_range": "bworld:overworld/river_tunnel",
"when_out_of_range": "bworld:overworld/cave_entrances"
},
"when_out_of_range": "bworld:overworld/cave_entrances"
}
}
}
}
@@ -0,0 +1,56 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/continents",
"type": "range_choice",
"input": "bworld:overworld/continents_base",
"min_inclusive": -0.5,
"when_in_range": "bworld:overworld/continents_base",
"when_out_of_range": {
"type": "max",
"argument1": "bworld:overworld/continents_base",
"argument2": {
"type": "sub",
"argument1": {
"type": "mul",
"argument1": {
"type": "add",
"argument1": {
"type": "mul",
"argument1": {
"type": "max",
"argument1": {
"type": "noise",
"noise": "bworld:island_a",
"even": true,
"x": "bworld:overworld/warp_x",
"z": "bworld:overworld/warp_z"
},
"argument2": {
"type": "noise",
"noise": "bworld:island_b",
"even": true,
"x": "bworld:overworld/warp_x",
"z": "bworld:overworld/warp_z"
}
},
"argument2": 0.76
},
"argument2": 0.05
},
"argument2": {
"type": "mul",
"argument1": {
"type": "smoothstep",
"input": "bworld:overworld/continents_base",
"from": -0.5,
"to": -0.8
},
"argument2": 0.7
}
},
"argument2": 0.7
}
}
}
}
@@ -0,0 +1,30 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/continents_base",
"type": "add",
"argument1": -0.8,
"argument2": {
"type": "spline",
"spline": {
"coordinate": "bworld:overworld/continents_far",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.4,
"value": 0.575,
"derivative": 1
},
{
"location": 0.48,
"value": 0.68,
"derivative": 1
}
]
}
}
}
}
@@ -0,0 +1,18 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/continents_far",
"type": "mul",
"argument1": {
"type": "abs",
"argument": {
"type": "noise",
"noise": "bworld:continents",
"even": true,
"x": "bworld:overworld/warp_x",
"z": "bworld:overworld/warp_z"
}
},
"argument2": 0.85
}
}
@@ -0,0 +1,11 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/depth",
"type": "sub",
"argument1": "bworld:overworld/height",
"argument2": {
"type": "y"
}
}
}
@@ -0,0 +1,36 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/dune_crest",
"type": "sub",
"argument1": 1,
"argument2": {
"type": "abs",
"argument": {
"type": "noise",
"noise": "bworld:dune",
"x": {
"type": "add",
"argument1": {
"type": "x"
},
"argument2": {
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:dune_warp"
},
"argument2": 40
}
},
"z": {
"type": "mul",
"argument1": {
"type": "z"
},
"argument2": 0.35
}
}
}
}
}
@@ -0,0 +1,116 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/dunes",
"type": "div",
"argument1": {
"type": "spline",
"spline": {
"coordinate": "bworld:overworld/continents",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.05,
"value": {
"coordinate": "bworld:overworld/erosion_folded",
"points": [
{
"location": 0.4,
"value": 0
},
{
"location": 0.45,
"value": {
"coordinate": "bworld:overworld/temperature_index",
"points": [
{
"location": 4,
"value": 0
},
{
"location": 5,
"value": {
"coordinate": "bworld:overworld/region",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.1,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.25,
"value": 6
}
]
}
}
]
}
}
]
}
},
{
"location": 0.8,
"value": {
"coordinate": "bworld:overworld/temperature_index",
"points": [
{
"location": 4,
"value": 0
},
{
"location": 5,
"value": {
"coordinate": "bworld:overworld/region",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.1,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.25,
"value": 6
}
]
}
}
]
}
}
]
}
},
{
"location": 0.85,
"value": 0
}
]
}
}
]
}
},
"argument2": 6
}
}
@@ -0,0 +1,15 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/erosion",
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:erosion",
"even": true,
"x": "bworld:overworld/warp_x",
"z": "bworld:overworld/warp_z"
},
"argument2": 1.05
}
}
@@ -0,0 +1,8 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/erosion_folded",
"type": "abs",
"argument": "bworld:overworld/erosion"
}
}
@@ -0,0 +1,26 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/ground_density",
"type": "add",
"argument1": {
"type": "div",
"argument1": {
"type": "sub",
"argument1": "bworld:overworld/height",
"argument2": {
"type": "y"
}
},
"argument2": 20
},
"argument2": {
"type": "mul",
"argument1": "bworld:overworld/roughness",
"argument2": {
"type": "noise",
"noise": "bworld:ground"
}
}
}
}
@@ -0,0 +1,9 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/height",
"type": "add",
"argument1": 64,
"argument2": "bworld:overworld/height_above_sea"
}
}
@@ -0,0 +1,27 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/height_above_sea",
"type": "range_choice",
"input": "bworld:overworld/dunes",
"min_exclusive": 0,
"when_in_range": {
"type": "add",
"argument1": "bworld:overworld/height_jagged",
"argument2": {
"type": "mul",
"argument1": {
"type": "mul",
"argument1": {
"type": "mul",
"argument1": "bworld:overworld/dunes",
"argument2": 7
},
"argument2": "bworld:overworld/dune_crest"
},
"argument2": "bworld:overworld/dune_crest"
}
},
"when_out_of_range": "bworld:overworld/height_jagged"
}
}
@@ -0,0 +1,9 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/height_base",
"type": "mul",
"argument1": "bworld:overworld/offset",
"argument2": 128
}
}
@@ -0,0 +1,27 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/height_jagged",
"type": "range_choice",
"input": "bworld:overworld/jaggedness",
"min_exclusive": 0,
"when_in_range": {
"type": "add",
"argument1": "bworld:overworld/height_base",
"argument2": {
"type": "mul",
"argument1": {
"type": "mul",
"argument1": {
"type": "mul",
"argument1": "bworld:overworld/jaggedness",
"argument2": 36
},
"argument2": "bworld:overworld/mountain_ridge"
},
"argument2": "bworld:overworld/mountain_ridge"
}
},
"when_out_of_range": "bworld:overworld/height_base"
}
}
@@ -0,0 +1,22 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/height_multiplier",
"type": "clamp",
"input": {
"type": "add",
"argument1": 1.2,
"argument2": {
"type": "mul",
"argument1": 0.4,
"argument2": {
"type": "noise",
"noise": "bworld:height_multiplier",
"even": true
}
}
},
"min": 0.8,
"max": 1.6
}
}
@@ -0,0 +1,12 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/hills",
"type": "abs",
"argument": {
"type": "noise",
"noise": "bworld:hills",
"even": true
}
}
}
@@ -0,0 +1,11 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/humidity",
"type": "noise",
"noise": "bworld:humidity",
"even": true,
"x": "bworld:overworld/warp_x",
"z": "bworld:overworld/warp_z"
}
}
@@ -0,0 +1,41 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/jaggedness",
"type": "clamp",
"input": {
"type": "div",
"argument1": {
"type": "spline",
"spline": {
"coordinate": "bworld:overworld/continents",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.175,
"value": {
"coordinate": "bworld:overworld/erosion_folded",
"points": [
{
"location": 0,
"value": 0.2
},
{
"location": 0.125,
"value": 0
}
]
}
}
]
}
},
"argument2": 0.2
},
"min": 0,
"max": 1
}
}
@@ -0,0 +1,16 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/lower_tier",
"type": "mul",
"argument1": {
"type": "abs",
"argument": {
"type": "noise",
"noise": "bworld:lower_tier",
"even": true
}
},
"argument2": 0.3
}
}
@@ -0,0 +1,15 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/mountain_ridge",
"type": "sub",
"argument1": 1,
"argument2": {
"type": "abs",
"argument": {
"type": "noise",
"noise": "bworld:mountain_ridges"
}
}
}
}
@@ -0,0 +1,793 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/offset",
"type": "add",
"argument1": {
"type": "spline",
"spline": {
"coordinate": "bworld:overworld/continents",
"points": [
{
"location": -0.45,
"value": -0.33
},
{
"location": -0.35,
"value": -0.17
},
{
"location": -0.195,
"value": -0.14
},
{
"location": -0.155,
"value": {
"coordinate": "bworld:overworld/erosion_folded",
"points": [
{
"location": 0.2,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": -0.1
},
{
"location": 0.15,
"value": 0.15,
"derivative": 3
},
{
"location": 0.25,
"value": 0.22
}
]
},
"derivative": -0.17
},
{
"location": 0.3,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.03,
"value": -0.06,
"derivative": 0.5
},
{
"location": 0.1,
"value": 0
}
]
}
}
]
}
},
{
"location": 0,
"value": {
"coordinate": "bworld:overworld/erosion_folded",
"points": [
{
"location": 0,
"value": 0.65
},
{
"location": 0.15,
"value": 0.425,
"derivative": -1.5
},
{
"location": 0.3,
"value": 0.33
},
{
"location": 0.375,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": -0.1
},
{
"location": 0.15,
"value": 0.15
},
{
"location": 0.3,
"value": 0.25
}
]
}
},
{
"location": 0.4,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.03,
"value": -0.06,
"derivative": 0.5
},
{
"location": 0.1,
"value": 0.01
}
]
}
},
{
"location": 0.95,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.03,
"value": -0.06,
"derivative": 0.5
},
{
"location": 0.1,
"value": 0.01
}
]
}
},
{
"location": 1.075,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.38,
"value": -0.03
},
{
"location": 0.45,
"value": 0.03
}
]
}
}
]
}
},
{
"location": 0.1,
"value": {
"coordinate": "bworld:overworld/erosion_folded",
"points": [
{
"location": 0,
"value": 0.95
},
{
"location": 0.175,
"value": 0.55
},
{
"location": 0.3,
"value": 0.36
},
{
"location": 0.375,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": -0.1
},
{
"location": 0.1,
"value": 0.125,
"derivative": 5
},
{
"location": 0.1667,
"value": 0.225
},
{
"location": 0.3,
"value": 0.3
}
]
}
},
{
"location": 0.425,
"value": {
"coordinate": "bworld:overworld/regions",
"points": [
{
"location": 0,
"value": 0,
"derivative": 0.5
}
]
}
},
{
"location": 0.5,
"value": {
"coordinate": "bworld:overworld/regions",
"points": [
{
"location": 0,
"value": 0,
"derivative": 1
}
]
}
},
{
"location": 0.825,
"value": {
"coordinate": "bworld:overworld/regions",
"points": [
{
"location": 0,
"value": 0,
"derivative": 1
}
]
}
},
{
"location": 0.875,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": -0.1,
"derivative": 1
},
{
"location": 0.175,
"value": 0.075,
"derivative": 0.3
},
{
"location": 0.3,
"value": 0.25
}
]
}
},
{
"location": 0.95,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": -0.1,
"derivative": 1
},
{
"location": 0.175,
"value": 0.075,
"derivative": 0.3
},
{
"location": 0.3,
"value": 0.25
}
]
}
},
{
"location": 1.075,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.38,
"value": -0.03
},
{
"location": 0.45,
"value": 0.03
}
]
}
}
]
}
},
{
"location": 0.8,
"value": {
"coordinate": "bworld:overworld/erosion_folded",
"points": [
{
"location": 0,
"value": 1.1
},
{
"location": 0.175,
"value": 0.65
},
{
"location": 0.3,
"value": 0.38
},
{
"location": 0.375,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": -0.1
},
{
"location": 0.1,
"value": 0.125,
"derivative": 5
},
{
"location": 0.1667,
"value": 0.225
},
{
"location": 0.3,
"value": 0.33
}
]
}
},
{
"location": 0.425,
"value": {
"coordinate": "bworld:overworld/regions",
"points": [
{
"location": 0,
"value": 0,
"derivative": 0.5
}
]
}
},
{
"location": 0.5,
"value": {
"coordinate": "bworld:overworld/regions",
"points": [
{
"location": 0,
"value": 0,
"derivative": 1
}
]
}
},
{
"location": 0.8,
"value": {
"coordinate": "bworld:overworld/regions",
"points": [
{
"location": 0,
"value": 0,
"derivative": 1
}
]
}
},
{
"location": 0.9,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": -0.1,
"derivative": 1
},
{
"location": 0.175,
"value": 0.075,
"derivative": 0.3
},
{
"location": 0.3,
"value": 0.25
}
]
}
},
{
"location": 0.95,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0,
"value": -0.1,
"derivative": 1
},
{
"location": 0.175,
"value": 0.075,
"derivative": 0.3
},
{
"location": 0.3,
"value": 0.25
}
]
}
},
{
"location": 1.075,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.38,
"value": -0.03
},
{
"location": 0.45,
"value": 0.03
}
]
}
}
]
}
}
]
}
},
"argument2": {
"type": "spline",
"spline": {
"coordinate": "bworld:overworld/continents",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.1,
"value": {
"coordinate": "bworld:overworld/erosion",
"points": [
{
"location": -0.875,
"value": 0
},
{
"location": -0.825,
"value": {
"coordinate": "bworld:overworld/region",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.1,
"value": {
"coordinate": "bworld:overworld/temperature_index",
"points": [
{
"location": 3,
"value": 0
},
{
"location": 4,
"value": {
"coordinate": "bworld:overworld/vegetation_index",
"points": [
{
"location": 3,
"value": 0
},
{
"location": 4,
"value": {
"coordinate": "bworld:overworld/ridges",
"points": [
{
"location": -0.75,
"value": {
"coordinate": "bworld:overworld/pillar",
"points": [
{
"location": 0.05,
"value": 0
},
{
"location": 0.2,
"value": 0.4,
"derivative": -0.2
},
{
"location": 0.5,
"value": 0.7,
"derivative": 0.05
}
]
}
},
{
"location": -0.175,
"value": {
"coordinate": "bworld:overworld/pillar",
"points": [
{
"location": 0.05,
"value": 0
},
{
"location": 0.2,
"value": 0.25,
"derivative": -0.2
},
{
"location": 0.5,
"value": 0.5,
"derivative": 0.05
}
]
}
},
{
"location": -0.125,
"value": 0
}
]
}
},
{
"location": 5,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.125,
"value": 0
},
{
"location": 0.175,
"value": {
"coordinate": "bworld:overworld/pillar",
"points": [
{
"location": 0.05,
"value": 0
},
{
"location": 0.2,
"value": 0.25,
"derivative": -0.2
},
{
"location": 0.5,
"value": 0.5,
"derivative": 0.05
}
]
}
},
{
"location": 0.75,
"value": {
"coordinate": "bworld:overworld/pillar",
"points": [
{
"location": 0.05,
"value": 0
},
{
"location": 0.2,
"value": 0.45,
"derivative": -0.2
},
{
"location": 0.5,
"value": 0.75,
"derivative": 0.05
}
]
}
},
{
"location": 0.8,
"value": 0
}
]
}
}
]
}
},
{
"location": 5,
"value": 0
}
]
}
}
]
}
},
{
"location": -0.425,
"value": {
"coordinate": "bworld:overworld/region",
"points": [
{
"location": 0,
"value": 0
},
{
"location": 0.1,
"value": {
"coordinate": "bworld:overworld/temperature_index",
"points": [
{
"location": 3,
"value": 0
},
{
"location": 4,
"value": {
"coordinate": "bworld:overworld/vegetation_index",
"points": [
{
"location": 3,
"value": 0
},
{
"location": 4,
"value": {
"coordinate": "bworld:overworld/ridges",
"points": [
{
"location": -0.75,
"value": {
"coordinate": "bworld:overworld/pillar",
"points": [
{
"location": 0.05,
"value": 0
},
{
"location": 0.2,
"value": 0.4,
"derivative": -0.2
},
{
"location": 0.5,
"value": 0.7,
"derivative": 0.05
}
]
}
},
{
"location": -0.175,
"value": {
"coordinate": "bworld:overworld/pillar",
"points": [
{
"location": 0.05,
"value": 0
},
{
"location": 0.2,
"value": 0.25,
"derivative": -0.2
},
{
"location": 0.5,
"value": 0.5,
"derivative": 0.05
}
]
}
},
{
"location": -0.125,
"value": 0
}
]
}
},
{
"location": 5,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.125,
"value": 0
},
{
"location": 0.175,
"value": {
"coordinate": "bworld:overworld/pillar",
"points": [
{
"location": 0.05,
"value": 0
},
{
"location": 0.2,
"value": 0.25,
"derivative": -0.2
},
{
"location": 0.5,
"value": 0.5,
"derivative": 0.05
}
]
}
},
{
"location": 0.75,
"value": {
"coordinate": "bworld:overworld/pillar",
"points": [
{
"location": 0.05,
"value": 0
},
{
"location": 0.2,
"value": 0.45,
"derivative": -0.2
},
{
"location": 0.5,
"value": 0.75,
"derivative": 0.05
}
]
}
},
{
"location": 0.8,
"value": 0
}
]
}
}
]
}
},
{
"location": 5,
"value": 0
}
]
}
}
]
}
},
{
"location": -0.375,
"value": 0
}
]
}
}
]
}
}
}
}
@@ -0,0 +1,48 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/open_caves",
"type": "min",
"argument1": {
"type": "min",
"argument1": {
"type": "mul",
"argument1": {
"type": "sub",
"argument1": 0.52,
"argument2": {
"type": "noise",
"noise": "bworld:cheese"
}
},
"argument2": 4
},
"argument2": {
"type": "mul",
"argument1": {
"type": "sub",
"argument1": {
"type": "max",
"argument1": {
"type": "abs",
"argument": {
"type": "noise",
"noise": "bworld:spaghetti_a"
}
},
"argument2": {
"type": "abs",
"argument": {
"type": "noise",
"noise": "bworld:spaghetti_b"
}
}
},
"argument2": 0.07
},
"argument2": 8
}
},
"argument2": "bworld:overworld/river_tunnel"
}
}
@@ -0,0 +1,21 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/pillar",
"type": "mul",
"argument1": 1.7,
"argument2": {
"type": "sub",
"argument1": {
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:pillar",
"even": true
},
"argument2": 0.7
},
"argument2": 0.35
}
}
}
@@ -0,0 +1,17 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/region",
"type": "add",
"argument1": {
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:region",
"even": true
},
"argument2": 0.5
},
"argument2": 0.1
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,15 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/ridges",
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:ridges",
"even": true,
"x": "bworld:overworld/warp_x",
"z": "bworld:overworld/warp_z"
},
"argument2": 0.7
}
}
@@ -0,0 +1,8 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/ridges_folded",
"type": "abs",
"argument": "bworld:overworld/ridges"
}
}
@@ -0,0 +1,49 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/river_tunnel",
"type": "range_choice",
"input": "bworld:overworld/underground_river",
"min_exclusive": 0,
"when_in_range": {
"type": "range_choice",
"input": {
"type": "y"
},
"min_inclusive": 57,
"max_inclusive": 70,
"when_in_range": {
"type": "mul",
"argument1": {
"type": "sub",
"argument1": {
"type": "max",
"argument1": {
"type": "sub",
"argument1": 1,
"argument2": "bworld:overworld/underground_river"
},
"argument2": {
"type": "div",
"argument1": {
"type": "abs",
"argument": {
"type": "sub",
"argument1": {
"type": "y"
},
"argument2": 63.5
}
},
"argument2": 4.5
}
},
"argument2": 1
},
"argument2": 4
},
"when_out_of_range": 1
},
"when_out_of_range": 1
}
}
@@ -0,0 +1,13 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/river_valley",
"type": "sub",
"argument1": 1,
"argument2": {
"type": "div",
"argument1": "bworld:overworld/ridges_folded",
"argument2": 0.035
}
}
}
@@ -0,0 +1,168 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/roughness",
"type": "div",
"argument1": {
"type": "mul",
"argument1": 0.12,
"argument2": 5.6
},
"argument2": {
"type": "spline",
"spline": {
"coordinate": "bworld:overworld/continents",
"points": [
{
"location": -0.19,
"value": 5.6
},
{
"location": -0.15,
"value": {
"coordinate": "bworld:overworld/erosion_folded",
"points": [
{
"location": 0.825,
"value": 5.6
},
{
"location": 0.875,
"value": {
"coordinate": "bworld:overworld/ridges",
"points": [
{
"location": 0,
"value": 5.6
},
{
"location": 0.1,
"value": 0.6
}
]
}
},
{
"location": 0.975,
"value": {
"coordinate": "bworld:overworld/ridges",
"points": [
{
"location": 0,
"value": 5.6
},
{
"location": 0.1,
"value": 0.6
}
]
}
},
{
"location": 1.025,
"value": 5.6
}
]
}
},
{
"location": 0.03,
"value": {
"coordinate": "bworld:overworld/erosion_folded",
"points": [
{
"location": 0.825,
"value": 5.6
},
{
"location": 0.875,
"value": {
"coordinate": "bworld:overworld/ridges",
"points": [
{
"location": 0,
"value": 5.6
},
{
"location": 0.1,
"value": 0.6
}
]
}
},
{
"location": 0.975,
"value": {
"coordinate": "bworld:overworld/ridges",
"points": [
{
"location": 0,
"value": 5.6
},
{
"location": 0.1,
"value": 0.6
}
]
}
},
{
"location": 1.025,
"value": 5.6
}
]
}
},
{
"location": 0.06,
"value": {
"coordinate": "bworld:overworld/erosion_folded",
"points": [
{
"location": 0.825,
"value": 5.6
},
{
"location": 0.875,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.25,
"value": 5.6
},
{
"location": 0.4,
"value": 1.3
}
]
}
},
{
"location": 0.975,
"value": {
"coordinate": "bworld:overworld/ridges_folded",
"points": [
{
"location": 0.25,
"value": 5.6
},
{
"location": 0.4,
"value": 1.3
}
]
}
},
{
"location": 1.025,
"value": 5.6
}
]
}
}
]
}
}
}
}
@@ -0,0 +1,16 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/snow_line",
"type": "add",
"argument1": 176,
"argument2": {
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:snow_line"
},
"argument2": 10
}
}
}
@@ -0,0 +1,11 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/temperature",
"type": "noise",
"noise": "bworld:temperature",
"even": true,
"x": "bworld:overworld/warp_x",
"z": "bworld:overworld/warp_z"
}
}
@@ -0,0 +1,44 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/temperature_index",
"type": "spline",
"spline": {
"coordinate": "bworld:overworld/temperature",
"points": [
{
"location": -0.48,
"value": 1
},
{
"location": -0.42,
"value": 2
},
{
"location": -0.18,
"value": 2
},
{
"location": -0.12,
"value": 3
},
{
"location": 0.17,
"value": 3
},
{
"location": 0.23,
"value": 4
},
{
"location": 0.52,
"value": 4
},
{
"location": 0.58,
"value": 5
}
]
}
}
}
@@ -0,0 +1,17 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/terrain",
"type": "range_choice",
"input": {
"type": "y"
},
"max_exclusive": 1,
"when_in_range": {
"type": "max",
"argument1": "bworld:overworld/top_slide",
"argument2": 1
},
"when_out_of_range": "bworld:overworld/top_slide"
}
}
@@ -0,0 +1,28 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/top_slide",
"type": "range_choice",
"input": {
"type": "y"
},
"min_exclusive": 232,
"when_in_range": {
"type": "sub",
"argument1": "bworld:overworld/ground_density",
"argument2": {
"type": "mul",
"argument1": {
"type": "smoothstep",
"input": {
"type": "y"
},
"from": 232,
"to": 252
},
"argument2": 4
}
},
"when_out_of_range": "bworld:overworld/ground_density"
}
}
@@ -0,0 +1,23 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/underground_river",
"type": "range_choice",
"input": "bworld:overworld/river_valley",
"min_exclusive": 0,
"when_in_range": {
"type": "range_choice",
"input": "bworld:overworld/height_above_sea",
"min_exclusive": 16,
"when_in_range": {
"type": "range_choice",
"input": "bworld:overworld/continents",
"min_exclusive": -0.17,
"when_in_range": "bworld:overworld/river_valley",
"when_out_of_range": 0
},
"when_out_of_range": 0
},
"when_out_of_range": 0
}
}
@@ -0,0 +1,16 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/upper_tier",
"type": "mul",
"argument1": {
"type": "abs",
"argument": {
"type": "noise",
"noise": "bworld:upper_tier",
"even": true
}
},
"argument2": 0.3
}
}
@@ -0,0 +1,44 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/vegetation_index",
"type": "spline",
"spline": {
"coordinate": "bworld:overworld/humidity",
"points": [
{
"location": -0.38,
"value": 1
},
{
"location": -0.32,
"value": 2
},
{
"location": -0.13,
"value": 2
},
{
"location": -0.07,
"value": 3
},
{
"location": 0.07,
"value": 3
},
{
"location": 0.13,
"value": 4
},
{
"location": 0.27,
"value": 4
},
{
"location": 0.33,
"value": 5
}
]
}
}
}
@@ -0,0 +1,18 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/warp_x",
"type": "add",
"argument1": {
"type": "x"
},
"argument2": {
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:warp_x"
},
"argument2": 24
}
}
}
@@ -0,0 +1,18 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/warp_z",
"type": "add",
"argument1": {
"type": "z"
},
"argument2": {
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:warp_z"
},
"argument2": 24
}
}
}
@@ -0,0 +1,13 @@
{
"format_version": 1,
"density_function": {
"id": "bworld:overworld/wetland",
"type": "mul",
"argument1": {
"type": "noise",
"noise": "bworld:wetland",
"even": true
},
"argument2": 0.6
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"format_version": 1,
"noise": {
"id": "bworld:badlands",
"wavelength": 512,
"amplitudes": [
1,
2,
1
],
"quantiles": "bworld:ridges"
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"format_version": 1,
"noise": {
"id": "bworld:cheese",
"wavelength": 80,
"amplitudes": [
1,
0.5
],
"dimensions": 3,
"vertical_stretch": 0.6
}
}
@@ -0,0 +1,38 @@
{
"format_version": 1,
"noise": {
"id": "bworld:continents",
"wavelength": 2560,
"amplitudes": [
1,
1,
2,
2,
1,
1
],
"quantiles": [
-0.833,
-0.386,
-0.311,
-0.256,
-0.21,
-0.17,
-0.133,
-0.098,
-0.065,
-0.032,
0,
0.032,
0.065,
0.098,
0.133,
0.17,
0.21,
0.256,
0.311,
0.386,
0.833
]
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"noise": {
"id": "bworld:dune",
"wavelength": 96,
"amplitudes": [
1,
1
]
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"noise": {
"id": "bworld:dune_warp",
"wavelength": 400,
"amplitudes": [
1,
1
]
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"noise": {
"id": "bworld:entrances",
"wavelength": 90,
"amplitudes": [
1,
1
]
}
}
+37
View File
@@ -0,0 +1,37 @@
{
"format_version": 1,
"noise": {
"id": "bworld:erosion",
"wavelength": 1280,
"amplitudes": [
1,
1,
0,
1,
1
],
"quantiles": [
-0.917,
-0.48,
-0.393,
-0.328,
-0.273,
-0.222,
-0.174,
-0.13,
-0.086,
-0.042,
0,
0.042,
0.086,
0.13,
0.174,
0.222,
0.273,
0.328,
0.393,
0.48,
0.917
]
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"format_version": 1,
"noise": {
"id": "bworld:ground",
"wavelength": 64,
"amplitudes": [
1,
1,
0.5
],
"dimensions": 3,
"vertical_stretch": 1.2
}
}
@@ -0,0 +1,13 @@
{
"format_version": 1,
"noise": {
"id": "bworld:height_multiplier",
"wavelength": 1024,
"amplitudes": [
1,
2,
1
],
"quantiles": "bworld:ridges"
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"format_version": 1,
"noise": {
"id": "bworld:hills",
"wavelength": 320,
"amplitudes": [
1,
1
],
"quantiles": "bworld:humidity"
}
}
+34
View File
@@ -0,0 +1,34 @@
{
"format_version": 1,
"noise": {
"id": "bworld:humidity",
"wavelength": 1536,
"amplitudes": [
1,
1
],
"quantiles": [
-0.962,
-0.536,
-0.439,
-0.368,
-0.306,
-0.248,
-0.195,
-0.146,
-0.096,
-0.046,
0,
0.046,
0.096,
0.146,
0.195,
0.248,
0.306,
0.368,
0.439,
0.536,
0.962
]
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"format_version": 1,
"noise": {
"id": "bworld:island_a",
"wavelength": 320,
"amplitudes": [
1,
1
],
"quantiles": "bworld:humidity"
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"format_version": 1,
"noise": {
"id": "bworld:island_b",
"wavelength": 320,
"amplitudes": [
1,
1
],
"quantiles": "bworld:humidity"
}
}
@@ -0,0 +1,13 @@
{
"format_version": 1,
"noise": {
"id": "bworld:lower_tier",
"wavelength": 512,
"amplitudes": [
1,
2,
1
],
"quantiles": "bworld:ridges"
}
}
@@ -0,0 +1,11 @@
{
"format_version": 1,
"noise": {
"id": "bworld:mountain_ridges",
"wavelength": 256,
"amplitudes": [
1,
1
]
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"format_version": 1,
"noise": {
"id": "bworld:pillar",
"wavelength": 32,
"amplitudes": [
1,
1
],
"quantiles": "bworld:humidity"
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"format_version": 1,
"noise": {
"id": "bworld:region",
"wavelength": 2048,
"amplitudes": [
1,
1,
2,
2,
1,
1
],
"quantiles": "bworld:continents"
}
}
+35
View File
@@ -0,0 +1,35 @@
{
"format_version": 1,
"noise": {
"id": "bworld:ridges",
"wavelength": 640,
"amplitudes": [
1,
2,
1
],
"quantiles": [
-0.91,
-0.468,
-0.377,
-0.308,
-0.249,
-0.199,
-0.154,
-0.113,
-0.073,
-0.036,
0,
0.036,
0.073,
0.113,
0.154,
0.199,
0.249,
0.308,
0.377,
0.468,
0.91
]
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"noise": {
"id": "bworld:snow_line",
"wavelength": 96,
"amplitudes": [
1,
1
]
}
}
@@ -0,0 +1,12 @@
{
"format_version": 1,
"noise": {
"id": "bworld:spaghetti_a",
"wavelength": 64,
"amplitudes": [
1
],
"dimensions": 3,
"vertical_stretch": 0.8
}
}
@@ -0,0 +1,12 @@
{
"format_version": 1,
"noise": {
"id": "bworld:spaghetti_b",
"wavelength": 64,
"amplitudes": [
1
],
"dimensions": 3,
"vertical_stretch": 0.8
}
}
@@ -0,0 +1,35 @@
{
"format_version": 1,
"noise": {
"id": "bworld:temperature",
"wavelength": 3072,
"amplitudes": [
1.5,
0,
1
],
"quantiles": [
-0.973,
-0.6,
-0.509,
-0.44,
-0.379,
-0.319,
-0.254,
-0.19,
-0.127,
-0.063,
0,
0.063,
0.127,
0.19,
0.254,
0.319,
0.379,
0.44,
0.509,
0.6,
0.973
]
}
}
@@ -0,0 +1,13 @@
{
"format_version": 1,
"noise": {
"id": "bworld:upper_tier",
"wavelength": 512,
"amplitudes": [
1,
2,
1
],
"quantiles": "bworld:ridges"
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"noise": {
"id": "bworld:warp_x",
"wavelength": 200,
"amplitudes": [
1,
1
]
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"noise": {
"id": "bworld:warp_z",
"wavelength": 200,
"amplitudes": [
1,
1
]
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"format_version": 1,
"noise": {
"id": "bworld:wetland",
"wavelength": 96,
"amplitudes": [
1,
1
],
"quantiles": "bworld:humidity"
}
}
@@ -0,0 +1,154 @@
{
"format_version": 1,
"noise_settings": {
"id": "bworld:overworld",
"sea_level": 64,
"default_block": "bworld:stone",
"cell_width": 4,
"terrain": {
"density": "bworld:overworld/terrain",
"cell_height": 8
},
"caves": {
"density": "bworld:overworld/caves",
"cell_height": 4
},
"preliminary_surface": "bworld:overworld/height",
"climate": {
"continentalness": "bworld:overworld/continents",
"temperature": "bworld:overworld/temperature",
"humidity": "bworld:overworld/humidity",
"valley": "bworld:overworld/ridges_folded",
"flatness": "bworld:overworld/erosion_folded",
"jaggedness": "bworld:overworld/jaggedness"
},
"steep": 3.5,
"biome_source": "bworld:overworld",
"fluids": [
{
"block": "bworld:water",
"below": 64,
"where": "open_sky"
},
{
"block": "bworld:water",
"below": 64,
"where": {
"function": "bworld:overworld/underground_river",
"min_exclusive": 0
}
}
],
"surface_rule": {
"type": "condition",
"if_true": {
"type": "above_preliminary_surface",
"offset": -20
},
"then_run": {
"type": "sequence",
"sequence": [
{
"type": "condition",
"if_true": {
"type": "stone_depth",
"offset": 0
},
"then_run": {
"type": "sequence",
"sequence": [
{
"type": "condition",
"if_true": {
"type": "surface_underwater"
},
"then_run": {
"type": "biome_surface",
"part": "underwater_top"
}
},
{
"type": "condition",
"if_true": {
"type": "y_at_least",
"function": "bworld:overworld/snow_line"
},
"then_run": {
"type": "sequence",
"sequence": [
{
"type": "condition",
"if_true": {
"type": "steep"
},
"then_run": {
"type": "block",
"result_state": {
"Name": "bworld:stone"
}
}
},
{
"type": "block",
"result_state": {
"Name": "bworld:snow_block"
}
}
]
}
},
{
"type": "condition",
"if_true": {
"type": "steep"
},
"then_run": {
"type": "condition",
"if_true": {
"type": "bare_cliffs"
},
"then_run": {
"type": "block",
"result_state": {
"Name": "bworld:stone"
}
}
}
},
{
"type": "biome_surface",
"part": "top"
}
]
}
},
{
"type": "condition",
"if_true": {
"type": "filler_depth"
},
"then_run": {
"type": "sequence",
"sequence": [
{
"type": "condition",
"if_true": {
"type": "surface_underwater"
},
"then_run": {
"type": "biome_surface",
"part": "underwater_filler"
}
},
{
"type": "biome_surface",
"part": "filler"
}
]
}
}
]
}
}
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"format_version": 1,
"ores": [
{
"id": "bworld:coal_ore",
"replaces": "bworld:stone",
"min_y": 5,
"max_y": 200,
"scale": 0.05,
"threshold": 0.55
},
{
"id": "bworld:copper_ore",
"replaces": "bworld:stone",
"min_y": 5,
"max_y": 110,
"scale": 0.06,
"threshold": 0.6
},
{
"id": "bworld:tin_ore",
"replaces": "bworld:stone",
"min_y": 5,
"max_y": 70,
"scale": 0.06,
"threshold": 0.62
},
{
"id": "bworld:iron_ore",
"replaces": "bworld:stone",
"min_y": 5,
"max_y": 80,
"scale": 0.05,
"threshold": 0.65
},
{
"id": "bworld:gold_ore",
"replaces": "bworld:stone",
"min_y": 5,
"max_y": 36,
"scale": 0.04,
"threshold": 0.7
}
]
}
+2 -3
View File
@@ -61,7 +61,6 @@ import {
number,
word,
} from "$/common/commands.ts";
import { estimate_biome } from "$/common/worldgen/overworld.ts";
import { biome_ids, get_biome } from "$/common/worldgen/biomes.ts";
import type { GameLoop } from "./game_loop.ts";
import { update_crafting_result } from "./crafting.ts";
@@ -160,7 +159,7 @@ interface SavedTile {
export interface GameMods {
listings: ModListing[];
recipes: RecipeBook;
worldgen?: WorldgenSetup;
worldgen: WorldgenSetup;
runtime: ModRuntime;
}
@@ -1304,7 +1303,7 @@ 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 = estimate_biome(this.world.seed, cx, cz);
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 };
+10 -1
View File
@@ -13,6 +13,10 @@ import { clear_hooks, expose_engine } from "$/common/hooks.ts";
import { common_engine } from "$/common/engine_modules.ts";
import { server_engine } from "./engine_modules.ts";
// the generator worlds use: a mod's worldgen/noise_settings, the base game's overworld. the server doesn't start
// without it
const GENERATOR = "bworld:overworld";
export interface ServerModSource {
listing: ModListing;
data: ModData;
@@ -42,7 +46,12 @@ export async function start_game(
? [{ mod: mod.listing.id, url: mod.worldgen_url, engine_access: mod.listing.engine_access }]
: []
);
const worldgen = await load_worldgen(worldgen_scripts, recipes.ores);
const worldgen = await load_worldgen({
mods: mods.map((mod) => mod.listing.id),
scripts: worldgen_scripts,
ores: recipes.ores,
generator: GENERATOR,
});
const runtime = new ModRuntime();
// before the world loads, its mobs can have effects
+13 -2
View File
@@ -48,7 +48,7 @@ export function position_key(x: number, y: number, z: number) {
export class ServerWorld {
readonly seed: string;
readonly block_ids: Record<string, number> = {};
readonly worldgen: WorldgenSetup | undefined;
readonly worldgen: WorldgenSetup;
// what a freshly placed or generated block stores, by numeric id: the id with its default states
readonly default_values: number[] = [];
// for light_at, by numeric id
@@ -85,7 +85,7 @@ export class ServerWorld {
on_block_change?: (x: number, y: number, z: number, id: string, state: number) => void;
on_tile_item_change?: (x: number, y: number, z: number, item: ItemData | undefined) => void;
constructor(seed: string, worldgen?: WorldgenSetup) {
constructor(seed: string, worldgen: WorldgenSetup) {
this.seed = seed;
this.worldgen = worldgen;
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
@@ -173,6 +173,11 @@ export class ServerWorld {
}
// like "bworld:plains", what generation decided
// a column's biome without generating its chunk, a little off near coasts and cliffs, see OverworldTerrain
estimate_biome(x: number, z: number): { biome: string; y: number } {
return this.worldgen.generator.for_seed(this.seed).estimate_biome(x, z);
}
biome_at(x: number, z: number): string {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
@@ -209,6 +214,12 @@ export class ServerWorld {
return found;
}
// what generation makes in a chunk, neighbors' spills included, without what players changed. built again every
// call, for comparing generation (tests/worldgen_golden_test.ts)
generated_blocks(chunk_x: number, chunk_z: number): Uint32Array {
return this.#generate_chunk(chunk_x, chunk_z);
}
// whether every chunk within radius blocks of x, z is, see has_chunk
has_chunks_around(x: number, z: number, radius: number) {
for (let cx = Math.floor((x - radius) / CHUNK_SIZE); cx <= Math.floor((x + radius) / CHUNK_SIZE); cx++) {

Some files were not shown because too many files have changed in this diff Show More