Files
2026-11-14 12:18:41 -03:00

226 lines
13 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# World Generation
The server generates chunks from the world's seed, and players get the finished chunks. Mods add to what it generates
with ores (data) and features (the worldgen phase).
## Determinism
Every chunk is saved whole once it's generated, like Minecraft, so a saved chunk never changes when generation does.
Generation still has to come out **exactly the same every time**: a chunk is generated more than once, since what a
feature writes into a neighbor is generated again when that neighbor is (even years later, next to a saved chunk). If it
isn't the same, trees are cut off at chunk borders.
- **Never use `Math.random`, `Date`, `performance.now` or anything else that changes between runs.** Use the chunk's
`rng` and noise helpers, which are seeded from the world's seed.
- Don't keep state between chunks. Chunks generate in any order, and in several worldgen workers at once, each with its
own copy of the worldgen phases (and the game generates a few itself).
- Adding or removing a mod's features only changes chunks that haven't been generated yet, with seams where they meet
saved ones.
## The Passes
Each chunk goes through three passes:
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).
How tall the world is is up to its [dimension](terrain.md#height): the base game's goes from y 0 to 255, and its sea is
at y 64.
## Ores
`worldgen/ores.json`:
```json
{
"format_version": 1,
"ores": [
{
"id": "copper_tools:rich_copper_ore",
"replaces": "#bworld:raw_rocks",
"min_y": 5,
"max_y": 40,
"scale": 0.05,
"threshold": 0.72
}
]
}
```
`replaces` is a block, a `#tag` of blocks, or a list of those, like `["bworld:stone", "#bworld:raw_rocks"]`. Every block
in the chunk that is one of them and between `min_y` and `max_y` becomes the first ore whose 3D noise, 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 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 phase registers them:
```ts
import type { WorldgenContext } from "cubi/worldgen";
export function worldgen(gen: WorldgenContext) {
gen.register_feature("copper_tools:boulders", (chunk) => {
if (chunk.rng.next() > 0.1) return;
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 somewhere, at any
height, the way a NeoForge biome modifier adds a feature to the biomes it lists.
Feature ids are in the mod's namespace. Each feature's `rng` is seeded with the world's seed, the chunk and the
feature's id, so adding another mod's feature doesn't change what this one generates.
```ts
interface FeatureChunk {
readonly x: number; // chunk coordinates. blocks are chunk.x * 16 to chunk.x * 16 + 15
readonly z: number;
readonly seed: string;
readonly min_y: number; // the dimension's blocks go from min_y up to max_y - 1
readonly max_y: number;
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, y: number, z: number): string; // like "bworld:plains", inside this chunk only
set_biome(x: number, y: number, z: number, biome: string): void; // the 4 blocks tall cell y is in, see biomes.md
get_block(x: number, y: number, z: number): string | undefined; // inside this chunk only
set_block(x: number, y: number, z: number, id: string): void; // up to one chunk away
place_feature(id: string, x: number, y: number, z: number): boolean; // a data feature, see below
}
```
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. `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.
Generated blocks don't run `on_create`, and worldgen phases 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 fluid. |
| `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 }` (`min_y + n`) or `{ "below_top": n }` (`max_y - 1 - n`),
from the dimension's height.
- **Blocks** (`to_place`, `provider`, `state`): an id, or Minecraft's
`{ "type": "simple_state_provider", "state": { "Name": id } }`.
### Types and Modifiers in Code
The worldgen phase 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 is data: noises, density functions, a generator, biome rules and the dimension that picks the generator, 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 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 with code, but it throws: the terrain is data,
> see [Terrain](terrain.md).