Files
2026-10-12 15:09:22 -03:00

346 lines
12 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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),
};