API by package

@threenative/terrain API

Every public function and class in @threenative/terrain. Headless terrain authoring — noise, erosion, sculpting, roads, rivers, material splats and scatter — evaluated into ordinary typed arrays and indexed Three.js geometry.

On this page

Generated from the engine's capability manifest: 105 functions and 5 classes. Each entry is the exported signature, what it is for, and a working example. Start with the package overview.

applyPlacementOverrides

function · import { applyPlacementOverrides } from "@threenative/terrain"

Attach manual transforms to raw evaluated candidates and report orphan keys.

ts
function applyPlacementOverrides(state: ITerrainState, value: unknown): ITerrainState

Needs

  • npm i -D @threenative/terrain

Use it to

  • retain manual prop transforms across terrain scatter re-evaluation

Example

ts
const state = applyPlacementOverrides(terrain.evaluate(), document.placementOverrides ?? {});

Good to know

  • headless authoring; game applies transforms against its model bounds and actual terrain surface

Options

  • transform.grounding=false preserves requested Y while the game still measures clearance

bakeBiome

function · import { bakeBiome } from "@threenative/terrain"

Bake one biome: the recipe's evaluated state and the world package it streams. This is the composition terrain_generate and a game's build script both call, so the file layout a player streams is decided in one place. The biome is validated first — an inline spec from a request is checked here, not trusted — and the package's own placement runs are checked against the state they came from, so a bake can never ship a cell list that lost instances. An agent does not write this call to get a world: the threenative-terrain MCP tool terrain_generate takes the request in words ("a pine forest under snowy mountains with a river", "a volcanic island", or ground: { location } for a real place) and cooks the world.glb, recipe.json and world.json a game loads with ctx.assets.model.

ts
function bakeBiome(options: IBakeBiomeOptions): IBakedBiome

Needs

  • npm i -D @threenative/terrain

Use it to

  • bake one biome's world package from an evaluated recipe and a biome file
  • generate terrain with mountains, hills, a river, a lake or an island from a request in words
  • generate a landscape or open world map for a game
  • procedural terrain for a level: a volcanic island, a mountain valley or a coast
  • make a canyon, a volcano, a fjord, a desert, a tundra or a forest world
  • cook the real terrain of a place on Earth from its latitude and longitude

Example

ts
const baked = bakeBiome({ state: terrain.evaluate(), spec: validateBiome(json, "savanna"), assets });

Good to know

  • every instance's asset must be in assets; every instance must land in exactly one cell run

bakeMesh

function · import { bakeMesh } from "@threenative/terrain"

Bakes the recovered indexed top surface and optional vertical skirts into caller-owned arrays.

ts
function bakeMesh( state: ITerrainState,

Needs

  • npm i @threenative/terrain

Use it to

  • bake an authored terrain into portable indexed mesh arrays

Example

ts
const mesh = bakeMesh(new Terrain({ resolution: 17 }).evaluate());

Good to know

  • no material is chosen; vertex colours exist only with a caller-supplied palette

Options

  • step, chunk bounds, skirtDepth and palette belong to the caller

bakeTerrain

function · import { bakeTerrain } from "@threenative/terrain"

Bakes finite LOD chunks, the same collision samples and resolved placements.

ts
function bakeTerrain( state: ITerrainState,

Needs

  • npm i @threenative/terrain

Use it to

  • prepare terrain arrays and collision before a game starts

Example

ts
const baked = bakeTerrain(new Terrain({ resolution: 129 }).evaluate(), { chunkCells: 64 });

Good to know

  • collision origin is the southwest corner; engine Heightfield origin is its centre

Options

  • chunkCells, lodSteps, skirtDepth and palette are explicit authoring choices

bakeWorldPackage

function · import { bakeWorldPackage } from "@threenative/terrain"

Bake an evaluated terrain into the engine's world package: a world.json manifest, a uint16 heightmap, a splat mask array, a placement buffer of eight float32 per instance, a placement ID sidecar and the square cells that stream them. The encodings and row orders are the ones the Blender recipe export_world.py writes, so one runtime streams both without a second reader.

ts
function bakeWorldPackage( state: ITerrainState, options: IBakeWorldPackageOptions, ): IBakedWorldPackage

Needs

  • npm i -D @threenative/terrain

Use it to

  • hand an evaluated Strata terrain to a game without a Blender round trip

Example

ts
const { manifest, files } = bakeWorldPackage(state, { assets });

Good to know

  • headless authoring; no three, no DOM, and nothing here decides how the world looks

Options

  • every asset path, bound, LOD distance and cell size comes from the caller's options

collarSampler

function · import { collarSampler } from "@threenative/terrain"

The collar's height at any (x, z), and a way to raise one of its per-vertex attributes at a placement: both read the collar's own quad grid, so a lane that reshapes the collar moves the trees with it.

ts
function collarSampler(collar: HeightfieldCollar)

Needs

  • npm i -D @threenative/terrain

Use it to

  • plant a far field on a drawn collar and paint the canopy its crowns cover

Example

ts
const sampler = collarSampler(collar); const height = sampler.at(x, z);

Good to know

  • the collar decides where a tree stands; this sampler never resamples the square

compilePropBuckets

function · import { compilePropBuckets } from "@threenative/terrain"

Group placements into their streamed worlds and write each world's cells and records. The order is the streamed one: cells sorted by x then z, assets sorted by name inside a cell, and records in the order the entries arrived inside a run. Same-cell, same-asset placements keep their input order, so a re-run of a seeded bake reproduces the buffer byte for byte.

ts
function compilePropBuckets( entries: readonly IPropBucketEntry[], options: ICompilePropBucketsOptions =

Needs

  • npm i -D @threenative/terrain

Use it to

  • bake the prop worlds a game streams, once, instead of compiling them at load

Example

ts
const pkg = compilePropBuckets(entries, { bounds });

Good to know

  • headless; the caller decides every placement, its streamed world, its reach and its pose

Options

  • cellSize and the base extent; the bucket, reach and kind of every entry

createSegmentIndex

function · import { createSegmentIndex } from "@threenative/terrain"

Build the index once per world; ask nearby per scatter candidate or heightfield vertex.

ts
function createSegmentIndex<T>( segments: readonly IWaterSegment<T>[], cellSize: number, ): ISegmentIndex<T>

Needs

  • npm i @threenative/terrain

Use it to

  • test scatter candidates or terrain vertices against rivers and lakes without scanning every segment
  • find which river stations can reach a heightfield vertex when baking a wet margin

Example

ts
const rivers = createSegmentIndex(segments, 32); const wet = rivers.nearby(x, z).some(isWet);

Good to know

  • returns candidates only; the caller applies its own exact distance and level test

decodeHeightPNG

function · import { decodeHeightPNG } from "@threenative/terrain"

CRC-checked bounded non-interlaced grayscale PNG height decoder.

ts
async function decodeHeightPNG( input: Uint8Array | ArrayBuffer, options: IDecodeHeightPngOptions =

Needs

  • npm i @threenative/terrain

Use it to

  • import numerical PNG8 or PNG16 terrain elevations

Example

ts
const png = await encodeHeightPNG(new Terrain({ resolution: 17 }).evaluate()); const heights = await decodeHeightPNG(png);

Good to know

  • authoring data only; the game owns appearance, physics and rendering

decodePropBucket

function · import { decodePropBucket } from "@threenative/terrain"

The records of one compiled prop bucket, read back in record order: the inverse of compilePropBuckets, so a loader that fetched a bake's files gets each record's ID, model, pose and reach without re-deriving the container layout.

ts
function decodePropBucket(bucket: IPropBucketPackage): IPropBucketRecord[]

Needs

  • npm i -D @threenative/terrain

Use it to

  • read a baked prop bucket back into placements to ground them on this machine's terrain

Example

ts
for (const record of decodePropBucket(bucket)) pose(record.key, record.position, record.quaternion);

Good to know

  • throws TN_PROP_BUCKET_INVALID when the record buffer, the IDs and the runs disagree

decodeRAW16

function · import { decodeRAW16 } from "@threenative/terrain"

Validates dimensions and range before decoding numerical height samples.

ts
function decodeRAW16( input: Uint8Array | ArrayBuffer,

Needs

  • npm i @threenative/terrain

Use it to

  • import a RAW16 terrain height buffer with explicit dimensions

Example

ts
const decoded = decodeRAW16(new Uint8Array(8), { width: 2, height: 2, min: 0, max: 1 });

Good to know

  • authoring data only; the game owns appearance, physics and rendering

encodeGLB

function · import { encodeGLB } from "@threenative/terrain"

Legacy terrain-only GLB encoding with embedded mesh arrays and no chosen material.

ts
function encodeGLB(input: IBakedMesh | readonly IBakedMesh[])

Needs

  • npm i @threenative/terrain

Use it to

  • export baked terrain geometry without engine extensions

Example

ts
const glb = encodeGLB(bakeMesh(new Terrain({ resolution: 17 }).evaluate()));

Good to know

  • authoring data only; the game owns appearance, physics and rendering

encodeHeightPNG

function · import { encodeHeightPNG } from "@threenative/terrain"

Encodes numerical grayscale PNG16 with embedded elevation range.

ts
async function encodeHeightPNG(state: ITerrainState, options: Partial<IHeightRange> =

Needs

  • npm i @threenative/terrain

Use it to

  • export a terrain heightmap without an eight-bit colour conversion

Example

ts
const png = await encodeHeightPNG(new Terrain({ resolution: 17 }).evaluate());

Good to know

  • authoring data only; the game owns appearance, physics and rendering

encodeRAW16

function · import { encodeRAW16 } from "@threenative/terrain"

Encodes finite metre elevations as an explicit-range RAW16 buffer.

ts
function encodeRAW16( values: ArrayLike<number> & Iterable<number>, options: IRaw16Options =

Needs

  • npm i @threenative/terrain

Use it to

  • export terrain heights with a numerical range sidecar

Example

ts
const raw = encodeRAW16(new Float32Array([0, 1]), { min: 0, max: 1 });

Good to know

  • authoring data only; the game owns appearance, physics and rendering

encodeSplatPNGs

function · import { encodeSplatPNGs } from "@threenative/terrain"

Encodes the eight linear material-weight channels as two RGBA images.

ts
async function encodeSplatPNGs(state: ITerrainState)

Needs

  • npm i @threenative/terrain

Use it to

  • export terrain splat weights as linear data

Example

ts
const maps = await encodeSplatPNGs(new Terrain({ resolution: 17 }).evaluate());

Good to know

  • authoring data only; the game owns appearance, physics and rendering

encodeZIP

function · import { encodeZIP } from "@threenative/terrain"

Deterministic store-method ZIP with safe unique relative filenames.

ts
function encodeZIP(files: readonly IExportFile[])

Needs

  • npm i @threenative/terrain

Use it to

  • archive derived terrain files without another dependency

Example

ts
const archive = encodeZIP([{ name: "height.raw", bytes: new Uint8Array(8) }]);

Good to know

  • authoring data only; the game owns appearance, physics and rendering

farForestPlacements

function · import { farForestPlacements } from "@threenative/terrain"

Far-field placements on the collar; also paints the collar's canopy attribute under each crown.

ts
function farForestPlacements(options: IFarFieldOptions): IPlacement[]

Needs

  • npm i -D @threenative/terrain

Use it to

  • plant the stand past a game's playable square, out to the drawn collar

Example

ts
const trees = farForestPlacements({ size, resolution, collar, treeline, rules, asset, layer });

Good to know

  • the row's far block decides every density; the caller supplies the collar and layer

fieldWeight

function · import { fieldWeight } from "@threenative/terrain"

A field's weight at (x, z), clamped to 0..1.

ts
function fieldWeight(field: ICoverField, x: number, z: number): number

Needs

  • npm i -D @threenative/terrain

Use it to

  • sample the stand field a biome's trees and cover thin on
  • measure the drift a biome's blades grow by, or the mat field its cover follows

Example

ts
const stand = fieldWeight(STAND_FIELD, x, z);

Good to know

  • the field is a value, so two worlds sample the same formula with their own numbers

gradientAt

function · import { gradientAt } from "@threenative/terrain"

World-space height gradient from the canonical samples.

ts
function gradientAt(grid: ISampledGrid, x: number, z: number): [number, number]

Needs

  • npm i @threenative/terrain

Use it to

  • measure an authored terrain gradient in metres

Example

ts
const gradient = gradientAt(new Terrain({ resolution: 17 }).evaluate(), 0, 0);

Good to know

  • authoring data only; the game owns appearance, physics and rendering

grassFieldFromBiome

function · import { grassFieldFromBiome } from "@threenative/terrain"

Turns a terrain biome's grass rows and its ground into GrassField3D placement options, so a generated or cooked world grows streamed grass with one call. Returns null when the biome has no grass rows: the game draws no field. Each row covers its own slope band (full to slope[1], gone slopeFalloff degrees past it), its own height band above ground.floor (fading over heightFalloff below the ceiling) and stays waterMargin above ground.waterLevel; the field takes the strongest row at each spot.

ts
function grassFieldFromBiome( biome: Pick<IBiomeSpec, "grass" | "seed">, ground: IGrassGround, ): IGrassFieldPlacement | null

Needs

  • npm i -D @threenative/terrain

Use it to

  • grow streamed grass on a terrain world's biome grass rows
  • a Strata or terrain_generate world with a meadow that sways round the player
  • feed a cooked biome to GrassField3D

Example

ts
const placement = grassFieldFromBiome(biome, { heightAt: (x, z) => field.heightAt(x, z), waterLevel: 0 });
if (placement) ctx.add(new GrassField3D({ ...placement, blade: grassBlade(), material: grassMaterial }));

Good to know

  • the look stays the game's: pass the result with the kit's render/grass.ts blade and material

landform

function · import { landform } from "@threenative/terrain"

One call, one landscape: a calibrated layer recipe for a kind of environment.

ts
function landform(kind: LandformKind, options: ILandformOptions =

Needs

  • npm i @threenative/terrain

Use it to

  • start an open world, a distant backdrop or a mountain level from a kind of place

Example

ts
const terrain = landform("alpine", { size: 5000, resolution: 513, seed: 4 }); const state = terrain.evaluate();

Good to know

  • returns an ordinary Terrain: add roads, rivers, scatter or more layers, then evaluate() in a build script
  • shape only; materials, colours and textures belong to the game
  • calibrated at size 5000, resolution 513; other sizes keep the same slopes and scale the relief with size

Options

  • relief is the highest-minus-lowest height in metres before the finishing passes shave a few percent; size, resolution and seed as in Terrain

landformBackdrop

function · import { landformBackdrop } from "@threenative/terrain"

Distant mountains around a playable area: a landform window with a valley floor at its centre.

ts
function landformBackdrop( kind: LandformKind, options: IBackdropOptions =

Needs

  • npm i @threenative/terrain

Use it to

  • add a mountain backdrop around a playable area that the game's detail terrain covers

Example

ts
const { size, resolution, heights } = landformBackdrop("temperateMountains", { seed: 7, centerHeight: 13 });

Good to know

  • resolution up to 513: the window is cut from a world twice as wide at the same spacing; build script only
  • shape only; the game places, colours and fades it

Options

  • relief and centerHeight in metres; size, resolution and seed as in landform

liftMassif

function · import { liftMassif } from "@threenative/terrain"

A tile's mountain above its own foot: the heights minus a smooth surface through its border, so its edge is exactly zero and stands on any ground with no wall or ramp. Signed: a valley inside the mountain cuts below the foot, as it does in the survey.

ts
function liftMassif(tile: IMassifTile): Float32Array

Needs

  • npm i -D @threenative/terrain

Use it to

  • measure how tall a surveyed mountain stands above the valley floor around it

Example

ts
const lifted = liftMassif({ id: "hill", size: 400, resolution: 3, heights: [0, 0, 0, 0, 90, 0, 0, 0, 0] });

Good to know

  • the tile must cover the whole mountain; a summit crop lifts as a cone

makeExport

function · import { makeExport } from "@threenative/terrain"

Recovered numerical/project exports; GLB/runtime outputs contain terrain only.

ts
function makeExport( state: ITerrainState | null, recipe: ITerrainDocument, kind: "project", ): Promise<IExportArchive>;

Needs

  • npm i @threenative/terrain

Use it to

  • export a terrain recipe and its numerical runtime data

Example

ts
const terrain = new Terrain({ resolution: 17 }); const file = await makeExport(terrain.evaluate(), terrain.toJSON(), "project");

Good to know

  • authoring data only; the game owns appearance, physics and rendering

measureBands

function · import { measureBands } from "@threenative/terrain"

Resolve a biome's fraction bands against this world's own height samples.

ts
function measureBands( layers: readonly ILayerInfo[], heights: ArrayLike<number>, ): IMeasuredBands

Needs

  • npm i -D @threenative/terrain

Use it to

  • turn a biome file's height fractions into the metres a world actually measured

Example

ts
const bands = measureBands(spec.layers, state.height);

Good to know

  • samples are finite and at least one; a flat field resolves every band onto its one height

orderedScatterRules

function · import { orderedScatterRules } from "@threenative/terrain"

A biome's rows as the ordered generators read them. The rule is short and shared; only these numbers differ between a wood, a barren shoulder, a dune field and a tundra, so the biome file names them rather than the code. A biome whose tree is not one this generator has art for fails here, naming the species, rather than planting nothing.

ts
function orderedScatterRules(spec: IBiomeSpec): IOrderedScatterRules

Needs

  • npm i -D @threenative/terrain

Use it to

  • run a biome file's rows through the ordered scatter

Example

ts
const rules = orderedScatterRules(spec);

Good to know

  • the file carries one foliage row, one grass row and a cover block

paintCanopyCover

function · import { paintCanopyCover } from "@threenative/terrain"

Paint each placed tree's crown into a per-vertex canopy grid, so the ground under a stand reads as forest floor rather than open turf. values is row-major Z then X, centred on the origin, at the heightfield's own spacing; each vertex keeps the strongest crown that reaches it (0 to 1).

ts
function paintCanopyCover( values: Float32Array, world:

Needs

  • npm i -D @threenative/terrain

Use it to

  • shade the ground under a baked stand, at bake time or after a placement edit

Example

ts
paintCanopyCover(values, { size: 512, resolution: 257 }, placements, { spruce: 7 });

Good to know

  • crowns is metres of crown radius per unit of placement scale, keyed by asset; other assets paint nothing

placeMassif

function · import { placeMassif } from "@threenative/terrain"

Stands one surveyed mountain behind a world, chosen and posed by a seed: the tile from a list, a point on a bearing and distance, a turn that faces its steepest wall to the centre within 20 degrees, a mirror and a summit height. It stands on the host's own foot (a smooth surface through the host under its border), replacing the host's hills inside its square, and leaves the centre square untouched. Appends one heightmap layer; the placement carries the tile-spacing heights a relief map reads.

ts
function placeMassif( terrain: Terrain, options: IPlaceMassifOptions, ):

Needs

  • npm i -D @threenative/terrain

Use it to

  • put a real-shaped mountain behind a generated world, a different one per seed

Example

ts
const { terrain, placement } = placeMassif(new Terrain({ size: 5000, resolution: 129 }), { seed: 3, tile: { id: "cone", size: 2000, resolution: 3, heights: [0, 0, 0, 0, 900, 0, 0, 0, 0] } });

Good to know

  • the tile must be a whole mountain whose border is valley floor; erosion after it carves the survey

Options

  • at, bearing, distance, height, top, face and keepOut on the same call

propAssetOf

function · import { propAssetOf } from "@threenative/terrain"

The asset a package run names. A prop run names the model it draws, asset:variant[@shape]; a container written by bakeWorldPackage names the asset alone. Both reduce to the asset here, which is what a count, a material or a placement's own asset field holds.

ts
function propAssetOf(modelKey: string): string

Needs

  • npm i -D @threenative/terrain

Use it to

  • count one species across a world's prop buckets, or name the asset a run draws

Example

ts
const asset = propAssetOf("spruce:2"); // "spruce"

propPackageFile

function · import { propPackageFile } from "@threenative/terrain"

A path under world/ that no bucket name can break: local:true becomes local-true. The bucket's own name is kept in the manifest, so this rename is only a file-system concern.

ts
function propPackageFile(world: string, bucket: string, suffix: string): string

Needs

  • npm i -D @threenative/terrain

Use it to

  • name one of a bucket's three files without a bucket key that breaks a path

Example

ts
const file = propPackageFile("forest", "local:true", "props.bin"); // "forest.local-true.props.bin"

propPackageFiles

function · import { propPackageFiles } from "@threenative/terrain"

Write a compiled package as the manifest the game fetches and one set of files per bucket. The manifest names the files rather than embedding them, so a loader fetches only the buckets its query flags keep (?farForest=on keeps the far field, ?meadow=off drops the vista cover).

ts
function propPackageFiles(pkg: IPropPackage, world: string): IPropPackageFiles

Needs

  • npm i -D @threenative/terrain

Use it to

  • write a compiled package to disk: one manifest and three files per streamed world

Example

ts
const { manifest, files } = propPackageFiles(pkg, "forest");

Good to know

  • the manifest names the files; nothing here touches a file system

sampleHeight

function · import { sampleHeight } from "@threenative/terrain"

Bilinear query of canonical height samples; triangle sampling is a separate contract.

ts
sampleHeight = (grid: ISampledGrid, x: number, z: number): number => sampleGrid( grid.height, grid.resolution, grid.resolution, x / grid.size + 0.5, z / grid.size + 0.5, )

Needs

  • npm i @threenative/terrain

Use it to

  • query an authored heightfield at world coordinates

Example

ts
const height = sampleHeight(new Terrain({ resolution: 17 }).evaluate(), 0, 0);

Good to know

  • authoring data only; the game owns appearance, physics and rendering

scatterProps

function · import { scatterProps } from "@threenative/terrain"

Every placement, for one world, from one seed: the game's own rule set, in its own draw order.

ts
function scatterProps( data: IOrderedScatterField, focus:

Needs

  • npm i -D @threenative/terrain

Use it to

  • bake a biome that says "stream": "ordered"

Example

ts
const { placements, counts } = scatterProps(data, focus, clearings);

Good to know

  • data.rules is the biome's rows, and data.field the ground they were graded on

skyVisibility

function · import { skyVisibility } from "@threenative/terrain"

The share of the sky each heightfield vertex sees past the terrain around it: 1 on open ground, lower on a valley floor, at a cliff foot or in a crater. The logic follows TerraForge3D's horizon ambient pass (MIT, heightfield/ambient/compute.glsl): march outward along evenly spaced azimuths, keep the highest horizon each one meets, and integrate the cosine-weighted sky above it, which is cos² of the horizon angle per azimuth. Only ground that rises over both the vertex's tangent plane and the horizontal occludes, so a straight slope and a steep face over a flat floor stay open: the lighting already counts the slope's own tilt. Heights are row-major Z then X, centred on the origin, as the baked world stores them. Every node marches: a strided march filled bilinearly erred by 0.13 at p99 on the alpine survey's creases. About 0.4 s of CPU a world, so bakeKit runs it and the game loads <world>.sky.bin.

ts
function skyVisibility( heights: ArrayLike<number>, resolution: number, size: number,

Needs

  • npm i -D @threenative/terrain

Use it to

  • bake a heightfield's sky occlusion for the ground's ambient light

Example

ts
const sky = skyVisibility(heights, 257, 512);

Good to know

  • offline: about 0.4 s of CPU for a 257² field; bake it, do not run it per frame

slopeAtIndex

function · import { slopeAtIndex } from "@threenative/terrain"

Slope in degrees at a heightfield sample.

ts
function slopeAtIndex(grid: ISampledGrid, i: number): number

Needs

  • npm i @threenative/terrain

Use it to

  • measure terrain slope for authoring diagnostics

Example

ts
const slope = slopeAtIndex(new Terrain({ resolution: 17 }).evaluate(), 0);

Good to know

  • authoring data only; the game owns appearance, physics and rendering

slopeQuantile

function · import { slopeQuantile } from "@threenative/terrain"

A slope, in degrees, that the given share of this terrain's interior vertices lie at or below. Placement rules keyed to fixed degrees break when a world is rebaked smoother or rougher: an outcrop rule of "over 30 degrees" placed nothing on a forest whose 98th percentile is 22. Asking the terrain for its own steepest share keeps the rule meaning the same thing on every world.

ts
function slopeQuantile(grid: ISampledGrid, quantile: number): number

Needs

  • npm i @threenative/terrain

Use it to

  • place rocks or cliffs on a terrain's own steepest ground instead of a fixed slope in degrees

Example

ts
const steep = slopeQuantile(grid, 0.98); if (slopeAt(x, z) > Math.min(30, steep)) placeRock(x, z);

Good to know

  • interior vertices only (edges have one-sided differences); quantile must be in [0, 1]

splinePoints

function · import { splinePoints } from "@threenative/terrain"

Recovered horizontal Catmull–Rom and vertically linear profile sampler.

ts
function splinePoints( points: readonly (readonly [number, number, number])[], step = 3, smooth = true, ): [number, number, number][]

Needs

  • npm i @threenative/terrain

Use it to

  • sample a road or river profile without vertical overshoot

Example

ts
const points = splinePoints([[0, 4, 0], [10, 2, 10]], 3, false);

Good to know

  • authoring data only; the game owns appearance, physics and rendering

Terrain

class · import { Terrain } from "@threenative/terrain"

Ordered, stable-ID terrain authoring with synchronous atomic transactions.

ts
class Terrain

Needs

  • npm i @threenative/terrain

Use it to

  • author seeded terrain with noise, sculpting, erosion, roads, rivers and scatter
  • generate a procedural heightmap landscape or island for a game
  • make realistic mountains, hills, desert, coast, tundra or volcano terrain: start from landform(kind), or add erode({ method: "fluvial" }) for dendritic valleys

Example

ts
const terrain = new Terrain({ size: 512, resolution: 257, seed: 73 }).noise({ id: "hills", amplitude: 35 });

Good to know

  • authoring stays outside the game's steady-play graph; no renderer or physics is created
  • units are metres with Y up; size is the world edge in metres (1 to 100000), centred on the origin
  • resolution counts vertices per edge and must be one of 17, 33, 65, 129, 257, 513 or 1025
  • seed is an integer from 0 to 4294967295; one document and seed evaluate to the same arrays
  • evaluate() is synchronous on the calling thread: run it in a build script, never per frame
  • no art is chosen or shipped: materials, models and texture paths belong to the game

Options

  • size, resolution, seed and all layer parameters are caller choices

TerrainEvaluator

class · import { TerrainEvaluator } from "@threenative/terrain"

Recovered prefix-caching authoring evaluator. Returned buffers belong to the caller.

ts
class TerrainEvaluator

Needs

  • npm i @threenative/terrain

Use it to

  • reuse terrain evaluation prefixes while authoring a finite heightfield

Example

ts
const terrain = new Terrain({ resolution: 17 }); const evaluator = new TerrainEvaluator(); const state = evaluator.evaluate(terrain.toJSON());

Good to know

  • evaluates authoring documents only; games consume pre-baked arrays

Options

  • cacheMB bounds retained prefix data

terrainStats

function · import { terrainStats } from "@threenative/terrain"

Landform statistics used to calibrate generators against real DEMs.

ts
function terrainStats(height: ArrayLike<number>, n: number, size: number): ITerrainStats

Needs

  • npm i @threenative/terrain

Use it to

  • compare generated terrain with a USGS or SRTM crop on the same footprint

Example

ts
const stats = terrainStats(state.height, state.resolution, state.size);

Good to know

  • square grids only; compare crops of equal spacing, because slope and curvature depend on it

validateBiome

function · import { validateBiome } from "@threenative/terrain"

One biome file, checked field by field. The file is biome.data.json: biome.json is Biome's own configuration name, and a data file called that is parsed as a project config and fails the lint.

ts
function validateBiome(spec: unknown, name: string): IBiomeSpec

Needs

  • npm i @threenative/terrain

Use it to

  • read a biome's rules from starter/<biome>/biome.data.json before a game or a cook uses them

Example

ts
const spec = validateBiome(JSON.parse(text), "forest");

Good to know

  • The file carries no appearance; colours, materials and shading stay game source

validateDocument

function · import { validateDocument } from "@threenative/terrain"

Validates the recovered recipe schema, operation allow-lists and numeric bounds.

ts
function validateDocument(doc: ITerrainDocument): void

Needs

  • npm i @threenative/terrain

Use it to

  • validate a terrain document before accepting an authoring write

Example

ts
validateDocument(new Terrain({ resolution: 17 }).toJSON());

Good to know

  • authoring data only; the game owns appearance, physics and rendering

validatePlacementOverrides

function · import { validatePlacementOverrides } from "@threenative/terrain"

Validate and clone stable-key placement transforms before saving or previewing them.

ts
function validatePlacementOverrides( value: unknown =

Needs

  • npm i -D @threenative/terrain

Use it to

  • validate finite positive manual prop transforms before a terrain authoring transaction

Example

ts
const transforms = validatePlacementOverrides(document.placementOverrides);

Good to know

  • grounding defaults on only when omitted; position and scale have three components and quaternion is unit length

Options

  • grounding=false preserves authored Y and keeps clearance observable

checkEnvironmentAssets

function · import { checkEnvironmentAssets } from "@threenative/terrain/editor"

Check that the images an environment names are registered environment or image assets. @summary Validate the assets a preview environment refers to

ts
function checkEnvironmentAssets( environment: IEnvironment, assets: readonly

Needs

  • npm i -D @threenative/terrain

Use it to

  • refuse a saved environment whose sky or lighting image is not a registered file

Example

ts
checkEnvironmentAssets({ sky: { image: "dusk" } }, document.assets ?? []);

Good to know

  • throws by name; HDR/EXR environment files and ordinary images are accepted, models are not

Options

  • the project owns which images it registers

createEditorSelection

function · import { createEditorSelection } from "@threenative/terrain/editor"

Gesture and transaction mechanics; the caller owns the controls, proxy and all rendering.

ts
function createEditorSelection(

Needs

  • npm i -D @threenative/terrain

Use it to

  • drive terrain-editor selection, gizmo drags, undo and saved transactions

Example

ts
const selection = createEditorSelection({ gizmo, proxy, controller, grounding, surface, defaultFootprintSize, refreshPose, drawFootprint, restorePlacement, previewPlacement, setSaving, selectedChanged, setNavigation, message });

Good to know

  • the caller supplies the TransformControls, proxy, controller and every drawing callback

createTweakBox

function · import { createTweakBox } from "@threenative/terrain/editor"

A box of range bars and colour pickers over the running game, for tuning numbers by eye. The game names its knobs and applies each change itself; the box owns the page elements, the stored values and the Copy button, whose JSON is what gets pasted back and written into the game's own source. With no document (a native launch, a test) it draws nothing and still holds the values, so the game code that reads them is the same on every target.

ts
function createTweakBox<K extends string>(options: ITweakBoxOptions<K>): ITweakBox<K>

Needs

  • npm i -D @threenative/terrain

Use it to

  • tune look numbers by eye with live range bars and colour pickers while the game runs

Example

ts
const box = createTweakBox({ title: "Fog", knobs: { density: { min: 0, max: 0.1, value: 0.02 } }, onChange: (name, value) => console.info(name, value) });

editorPlacementCenter

function · import { editorPlacementCenter } from "@threenative/terrain/editor"

Transform the caller's measured geometry centre into the evaluated placement's world space.

ts
function editorPlacementCenter(point: Vector3, pose: IPlacementOverride): Vector3

Needs

  • npm i -D @threenative/terrain

Use it to

  • find the world-space centre of a placed terrain-editor instance

Example

ts
const centre = editorPlacementCenter(localCentre.clone(), placement);

Good to know

  • the point is multiplied in place; the pose needs finite position, quaternion and scale

editorPointToClient

function · import { editorPointToClient } from "@threenative/terrain/editor"

Project an injected world point to client pixels in the caller's viewport.

ts
function editorPointToClient( point: Vector3, camera: Camera, box:

Needs

  • npm i -D @threenative/terrain

Use it to

  • convert a terrain-editor world point to viewport client pixels

Example

ts
const [x, y] = editorPointToClient(point.clone(), camera, canvas.getBoundingClientRect());

Good to know

  • the point is projected in place; pass a clone to keep the original

editorSurfaceHeight

function · import { editorSurfaceHeight } from "@threenative/terrain/editor"

Query the rendered heightfield, including its triangulation rather than an interpolated bake.

ts
function editorSurfaceHeight( ctx:

Needs

  • npm i -D @threenative/terrain

Use it to

  • query terrain-editor surface elevation at world X/Z coordinates

Example

ts
const height = editorSurfaceHeight(ctx, terrainMesh, x, z);

Good to know

  • the supplied mesh and raycast determine the surface; missing intersections return undefined

focusCamera

function · import { focusCamera } from "@threenative/terrain/editor"

Frame a point, prop, landmark or region for the live viewport and projection. @summary Frame a focus target with an editor observation camera

ts
function focusCamera( camera: ISavedCamera, request: IFocusRequest, resolve: IFocusResolver, ): IFocusOutcome

Needs

  • npm i -D @threenative/terrain

Use it to

  • frame one selected prop, a registered landmark, a terrain region or a local point

Example

ts
const outcome = focusCamera(camera, { target: { kind: "prop", id: "pine-3" }, aspect: 16 / 9 }, resolve);

Good to know

  • framing only; an unknown target returns a named diagnostic and no camera

Options

  • the view supplies target bounds, the live aspect and the camera to keep

inspectImage

function · import { inspectImage } from "@threenative/terrain/editor"

Validate a PNG, JPEG, WebP, Radiance HDR or OpenEXR container and read its pixel size. @summary Inspect an image file's container and pixel size without decoding it

ts
function inspectImage( bytes: Uint8Array, format: string, limits:

Needs

  • npm i -D @threenative/terrain

Use it to

  • check an imported surface or environment image for damage and for the project's size limit

Example

ts
const report = inspectImage(bytes, "png", { maxDimension: 8192 });

Good to know

  • headers and checksums only; throws by name for a damaged, truncated or oversize file

Options

  • the project sets the dimension limit

inspectSpatial

function · import { inspectSpatial } from "@threenative/terrain/editor"

Read-only spatial inspection of one evaluated terrain revision.

ts
function inspectSpatial( state: ITerrainState, revision: string, query: ISpatialQuery, ): ISpatialObservation

Needs

  • npm i -D @threenative/terrain

Use it to

  • measure a point, profile a transect or score a saved reference against the world

Example

ts
const observation = inspectSpatial(state, revision, { kind: "point", at: [0, 0] });

Good to know

  • authoring data only; queries outside the extent or without observations throw

Options

  • the caller owns the revision identity and the evaluated state being inspected

landformPose

function · import { landformPose } from "@threenative/terrain/editor"

Recipe footprints are heights over X/Z, never independently transformed solids.

ts
function landformPose(layer: Layer, worldSize: number, defaultSize: number)

Needs

  • npm i -D @threenative/terrain

Use it to

  • derive a terrain-editor gizmo pose from a landform layer

Example

ts
const pose = landformPose(layer, terrain.size, footprintSize);

Good to know

  • the caller supplies world and default footprint sizes; unsupported layers return undefined

mountTerrainEditor

function · import { mountTerrainEditor } from "@threenative/terrain/editor"

Mount recovered terrain controls around the project-owned ThreeNative view.

ts
async function mountTerrainEditor(options:

Needs

  • npm i -D @threenative/terrain

Use it to

  • open the terrain brush and layer GUI around game-owned rendering

Example

ts
await mountTerrainEditor({ createView: createEditorView, materialColours: terrainPalette });

Good to know

  • browser authoring only; createView and materialColours are required game choices

Options

  • createView owns the renderer scene, materials, lighting and camera

pickEditorPlacement

function · import { pickEditorPlacement } from "@threenative/terrain/editor"

A foreground terrain hit occludes placements; matching uses the evaluated world position.

ts
function pickEditorPlacement( ctx: Parameters<typeof pickEditorSurface>[0], terrain: Mesh, meshes: readonly Object3D[], placements: Iterable<

Needs

  • npm i -D @threenative/terrain

Use it to

  • pick a placed instance in the terrain editor from viewport client coordinates

Example

ts
const id = pickEditorPlacement(ctx, terrainMesh, meshes, placements, event.clientX, event.clientY);

Good to know

  • the caller supplies the raycast context, terrain mesh, instanced meshes and evaluated placements

pickEditorSurface

function · import { pickEditorSurface } from "@threenative/terrain/editor"

Convert viewport client coordinates once; the installed picker owns ray intersection.

ts
function pickEditorSurface( ctx:

Needs

  • npm i -D @threenative/terrain

Use it to

  • pick a terrain-editor surface from viewport client coordinates

Example

ts
const hit = pickEditorSurface(ctx, [terrainMesh], event.clientX, event.clientY);

Good to know

  • the caller supplies the raycast implementation and ordered targets

probeTerrain

function · import { probeTerrain } from "@threenative/terrain/editor"

Probe the evaluated surface at one world point, separating bilinear from triangle values.

ts
function probeTerrain( state: ITerrainState, revision: string, at: readonly number[], ): IPointObservation

Needs

  • npm i -D @threenative/terrain

Use it to

  • measure an authored terrain point with provenance and a revision identity

Example

ts
const probe = probeTerrain(state, revision, [12, -4]);

Good to know

  • authoring data only; non-finite, malformed and out-of-extent queries throw

Options

  • the caller owns the revision identity and the evaluated state being inspected

runCameraOperation

function · import { runCameraOperation } from "@threenative/terrain/editor"

Run one create / get / list / update / delete / activate operation over saved cameras. @summary Apply an editor camera operation to a saved camera set

ts
function runCameraOperation(set: ICameraSet, operation: unknown): ICameraResult

Needs

  • npm i -D @threenative/terrain

Use it to

  • drive the terrain editor camera list from an agent or the GUI through one shared dispatch

Example

ts
const next = runCameraOperation(set, { op: "activate", id: "survey" });

Good to know

  • pure: the input set is never mutated, an unknown id throws, and deleting the live camera falls back

Options

  • the caller persists the returned set against its own revision

runEnvironmentOperation

function · import { runEnvironmentOperation } from "@threenative/terrain/editor"

Apply one get / patch / reset against the saved environment overrides; the caller commits it. @summary Run one preview-environment operation

ts
function runEnvironmentOperation( current: IEnvironment, operation: unknown, ): IEnvironmentResult

Needs

  • npm i -D @threenative/terrain

Use it to

  • patch sun, haze, exposure or sea overrides from a controller or the editor GUI

Example

ts
const result = runEnvironmentOperation({}, { op: "patch", values: { sun: { elevation: 25 } } });

Good to know

  • authoring metadata only; a null field returns to the project's own value

Options

  • the project's render source decides what each value does

sniff

function · import { sniff } from "@threenative/terrain/editor"

The kind and format a file's own bytes declare, whatever its name says. @summary Identify a GLB, PNG, JPEG, WebP, HDR or EXR file by its header

ts
function sniff( bytes: Uint8Array, ):

Needs

  • npm i -D @threenative/terrain

Use it to

  • decide whether a dropped or downloaded file is a model, surface image or environment image

Example

ts
const kind = sniff(new Uint8Array(await file.arrayBuffer()))?.kind;

Good to know

  • reads only the first bytes; a file it cannot name returns undefined and must be refused

Options

  • the caller decides what to do with an unknown file

surfaceSpace

function · import { surfaceSpace } from "@threenative/terrain/editor"

The colour space an input's pixels are read in, from the channel its name ends with. @summary Resolve a surface input name to sRGB or linear

ts
function surfaceSpace(input: string): "srgb" | "linear"

Needs

  • npm i -D @threenative/terrain

Use it to

  • decide how an imported image bound to a named surface input must be sampled

Example

ts
const space = surfaceSpace("bark.normal");

Good to know

  • throws by name for an input that is not <surface>.<channel> with a known channel

Options

  • the project owns which surface inputs exist

TerrainEditorController

class · import { TerrainEditorController } from "@threenative/terrain/editor"

HTTP controller for the project-local terrain editor.

ts
class TerrainEditorController

Needs

  • npm i -D @threenative/terrain

Use it to

  • inspect and atomically edit the terrain editor from an agent

Example

ts
const controller = new TerrainEditorController(editorUrl); const snapshot = await controller.snapshot();

Good to know

  • optional tooling; only subscribe/mount touches DOM; stale revisions fail explicitly

Options

  • editorUrl is the activation-returned project URL

transformedLandform

function · import { transformedLandform } from "@threenative/terrain/editor"

Convert a terrain-editor gizmo pose into a heightfield landform footprint.

ts
function transformedLandform( layer: Layer, position: Vector3, quaternion: Quaternion, scale: Vector3, anchor: number, ): Layer

Needs

  • npm i -D @threenative/terrain

Use it to

  • apply a terrain-editor gizmo transform to a landform layer

Example

ts
const next = transformedLandform(layer, position, quaternion, scale, surfaceHeight);

Good to know

  • finite coordinates and positive scales are required; X/Z rotations that overhang throw

validateAsset

function · import { validateAsset } from "@threenative/terrain/editor"

Validate one saved asset registration exactly as a document commit stores it. @summary Validate a registered terrain-editor asset entry

ts
function validateAsset(input: unknown): IProjectAsset

Needs

  • npm i -D @threenative/terrain

Use it to

  • check a model, image or environment asset entry before saving it in the authoring document

Example

ts
const asset = validateAsset({ id: "oak", kind: "model", name: "oak.glb", path: "models/0123456789ab-oak.glb", sha256: "0123456789ab".padEnd(64, "0"), bytes: 2180, status: "ready" });

Good to know

  • authoring metadata only; ids, content-hashed paths, bounds and unit adjustments are checked, files are not read

Options

  • the project owns its asset directory and which entries it keeps

validateAssets

function · import { validateAssets } from "@threenative/terrain/editor"

Validate the whole asset list of an authoring document. @summary Validate the registered terrain-editor assets

ts
function validateAssets(input: unknown): IProjectAsset[]

Needs

  • npm i -D @threenative/terrain

Use it to

  • check every registered model, image and environment entry together, with unique ids

Example

ts
const assets = validateAssets(document.assets ?? []);

Good to know

  • at most 64 entries; unique ids; each entry as validateAsset

Options

  • the project owns its asset directory and which entries it keeps

validateCamera

function · import { validateCamera } from "@threenative/terrain/editor"

Normalise and validate one saved camera, exactly as a document commit would store it. @summary Validate an editor observation camera bookmark

ts
function validateCamera( input: unknown, existing: readonly ISavedCamera[] = [], ): ISavedCamera

Needs

  • npm i -D @threenative/terrain

Use it to

  • create or update a named terrain-editor camera in the shared authoring document

Example

ts
const camera = validateCamera({ id: "survey", name: "Survey", position: [40, 60, 40], target: [0, 12, 0], up: [0, 1, 0], projection: "perspective", fov: 50, near: 0.5, far: 900 });

Good to know

  • authoring metadata only; finite noncoincident poses, usable up, valid projection, ordered planes

Options

  • the caller owns the document revision and the live viewport aspect

validateCameras

function · import { validateCameras } from "@threenative/terrain/editor"

Validate a document's saved camera list, keeping ids unique across it. @summary Validate the saved editor camera list of an authoring document

ts
function validateCameras(input: unknown): ISavedCamera[]

Needs

  • npm i -D @threenative/terrain

Use it to

  • reject a disk document whose saved cameras are malformed or duplicated

Example

ts
const cameras = validateCameras(JSON.parse(saved).cameras ?? []);

Good to know

  • authoring metadata only; the same validation the camera operations apply

Options

  • the document owns how many cameras it keeps; the list bound is the editor's own

validateEnvironment

function · import { validateEnvironment } from "@threenative/terrain/editor"

Validate a complete overrides object exactly as a document commit stores it. @summary Validate preview environment overrides

ts
function validateEnvironment(input: unknown): IEnvironment

Needs

  • npm i -D @threenative/terrain

Use it to

  • save sun, sky, haze, exposure or ocean overrides in the shared authoring document

Example

ts
const environment = validateEnvironment({ sun: { elevation: 25, intensity: 3 } });

Good to know

  • authoring metadata only; unknown fields and unsupported fog modes are refused by name

Options

  • the project's render source defines what each value does; absent fields keep its own

validateSpatialReference

function · import { validateSpatialReference } from "@threenative/terrain/editor"

Normalise and validate one saved reference, exactly as a document commit would store it.

ts
function validateSpatialReference(input: unknown): ISavedSpatialReference

Needs

  • npm i -D @threenative/terrain

Use it to

  • accept a bounded local reference image registration into the shared document

Example

ts
const reference = validateSpatialReference(JSON.parse(saved));

Good to know

  • authoring metadata only; rejects unknown fields, malformed points and unknown scale

Options

  • a project owns the image file; only its hash and provenance travel in the document

validateSurfaces

function · import { validateSurfaces } from "@threenative/terrain/editor"

Validate surface mappings against the registered images they name. @summary Validate terrain-editor surface image mappings

ts
function validateSurfaces( input: unknown, assets: readonly IProjectAsset[], ): ISurfaceMappings

Needs

  • npm i -D @threenative/terrain

Use it to

  • save which imported PBR image replaces which named surface input of the project's render source

Example

ts
const surfaces = validateSurfaces({ "bark.normal": { asset: "my-normal" } }, document.assets ?? []);

Good to know

  • authoring metadata only; each input is <surface>.<channel>; every asset must be a registered image

Options

  • the project's render source defines which surface inputs exist and what they draw

terrainEditor

function · import { terrainEditor } from "@threenative/terrain/editor/server"

Mount the optional terrain document API on an existing loopback Vite server.

ts
function terrainEditor(options:

Needs

  • npm i -D @threenative/terrain vite

Use it to

  • share terrain recipe edits between an agent and the live terrain editor

Example

ts
const editor = terrainEditor({ documentPath: resolve("terrain/world.json") });

Good to know

  • dev tooling only; serve a project-owned /terrain-editor/index.html; no runtime import

Options

  • documentPath and optional configured viewerUrl belong to the project

TerrainEditorDocument

class · import { TerrainEditorDocument } from "@threenative/terrain/editor/server"

Project-local terrain document authority; no renderer or game dependency.

ts
class TerrainEditorDocument

Needs

  • npm i -D @threenative/terrain

Use it to

  • validate atomic revision-based project-local terrain document edits

Example

ts
const document = new TerrainEditorDocument("/project/terrain/world.json"); const snapshot = document.snapshot();

Good to know

  • Node authoring only; documentPath is a configured absolute regular file; input is bounded to 64 MiB

Options

  • the project chooses its document path; revisions come from validated content

prepareWorldGLTF

function · import { prepareWorldGLTF } from "@threenative/terrain/export"

Prepare the game's validated, frozen portable scene; the server cook owns GLB encoding.

ts
async function prepareWorldGLTF(input: IWorldGLBInput): Promise<

Needs

  • npm i -D @threenative/terrain

Use it to

  • export the terrain as a glb for another three.js project via the headless cook
  • prepare the terrain editor's resolved world for headless portable GLB cooking

Example

ts
const prepared = await prepareWorldGLTF(input);

Good to know

  • browser authoring FileReader/canvas; all appearance and coherent water come from the game

bakeKit

function · import { bakeKit } from "@threenative/terrain/kit"

Bake a copied kit, optionally using the caller's installed world cook.

ts
async function bakeKit( url: string, options: IBakeKitOptions | IBakeKitWorldOptions, ): Promise<void>

Needs

  • npm i -D @threenative/terrain

Use it to

  • bake a copied terrain starter kit into its offline world package

Example

ts
await bakeKit(import.meta.url, { sky: "hdri/game-sky.hdr" });

Good to know

  • Node authoring only; recipes, asset tables and sky paths stay in the game

starterAssetsDir

function · import { starterAssetsDir } from "@threenative/terrain/kit"

Resolve shared starter assets locally, or download the package's pinned archive on demand.

ts
async function starterAssetsDir(): Promise<string>

Needs

  • npm i -D @threenative/terrain

Use it to

  • resolve terrain kit models and textures for offline baking

Example

ts
const assets = await starterAssetsDir();

Good to know

  • Node authoring only; verifies archive size and SHA256 before atomic extraction

addStarterWorld

function · import { addStarterWorld } from "@threenative/terrain/starter"

Load caller-authored starter data with one scene lifetime; all appearance comes from spec.

ts
async function addStarterWorld<Extra extends

Needs

  • npm i -D @threenative/terrain

Use it to

  • attach a baked starter world with game-owned surfaces, prop dressing and water

Example

ts
await addStarterWorld(ctx, follow, spec);

Good to know

  • Runtime subpath; the game supplies every appearance and collision choice

addStreamedGround

function · import { addStreamedGround } from "@threenative/terrain/starter"

PRD-790: the ground past the playable square, streamed around the player by TerrainTiles out to the collar's reach. Tiles sample the kit's own height function, the surface the square and the collar's vertices stand on, so a tile meets the square and its neighbours with no step. The tile material slides the outermost tile onto the collar's drawn height (collarMorph), so at the collar every tile vertex stands on it; ?tnTerrainValidate=1 reports streamCollarGap. The largest block of resident tiles around the player is written to the stream each frame: the tiles draw inside it, the collar everywhere else, so a tile that is still building leaves the collar showing, never a hole.

ts
function addStreamedGround(options: IStreamedGroundOptions):

Needs

  • npm i -D @threenative/terrain @threenative/physics

Use it to

  • stream an authored square's ground past its edge, out to a drawn collar

Example

ts
const ground = addStreamedGround({ ctx, name, size, resolution, height, collar, curve, reach, stream, surface, follow, report });

Good to know

  • the game supplies the height, the collar, its curve and the tile material

authoredQuaternion

function · import { authoredQuaternion } from "@threenative/terrain/starter"

The quaternion a placement's own scatter numbers describe: the normal tilt, then the yaw.

ts
function authoredQuaternion( placement: IPlacement, ): readonly [number, number, number, number]

Needs

  • npm i -D @threenative/terrain

Use it to

  • compose a placement's authored rotation before grounding it

Example

ts
const quaternion = authoredQuaternion(placement);

beginScene

function · import { beginScene } from "@threenative/terrain/starter"

Start a scene's view accounting: the player view it opens in, and nothing measured yet.

ts
function beginScene(world: string): void

Needs

  • npm i -D @threenative/terrain

Use it to

  • start the run's view accounting when a scene enters

Example

ts
beginScene("forest");

collarArithmeticHeight

function · import { collarArithmeticHeight } from "@threenative/terrain/starter"

The collar triangle under (x, z) found by arithmetic alone, as the tile shader finds it: the ring from the ring spacing, the perimeter step from the face the point projects onto, and the triangle from the point's place in the quad. On one face the world point is an affine map of (scale, share * scale), so weights read there are the drawn triangle's own.

ts
function collarArithmeticHeight( collar: HeightfieldCollar, curve: ICollarRingCurve, x: number, z: number, ): number

Needs

  • npm i -D @threenative/terrain

Use it to

  • answer a collar height on the CPU exactly as its tile shader computes it

Example

ts
const y = collarArithmeticHeight(collar, { power: 1.65, reach: 2100 }, x, z);

Good to know

  • the curve must be the one the collar was built with

collarDrawnHeight

function · import { collarDrawnHeight } from "@threenative/terrain/starter"

The collar's drawn height under (x, z); null where there is no collar.

ts
function collarDrawnHeight(collar: HeightfieldCollar, x: number, z: number): number | null

Needs

  • npm i -D @threenative/terrain

Use it to

  • measure or collide against the triangles a collar actually draws

Example

ts
const y = collarDrawnHeight(collar, x, z);

Good to know

  • reads the collar it is given; never resamples the square or builds a surface

collarMorph

function · import { collarMorph } from "@threenative/terrain/starter"

PRD-790 box 2: the streamed tiles' vertex shift. Only the outermost tile of the square the tiles draw slides onto the collar's drawn height, smoothly over that tile, so at the square's edge every tile vertex stands on the collar; the ground inside keeps the survey's smooth surface. The collar's heights go to the GPU once, as a float texture of rings by perimeter steps.

ts
function collarMorph( collar: HeightfieldCollar, curve: ICollarRingCurve, stream: ICollarStream, band: number, ): Node<"vec3">

Needs

  • npm i -D @threenative/terrain

Use it to

  • slide the streamed ground's outer tile onto a drawn collar without a seam

Example

ts
tile.positionNode = collarMorph(collar, { power: 1.65, reach: 2100 }, stream, 64);

Good to know

  • the curve must be the one the collar was built with; the band is one tile wide

collarSeamGap

function · import { collarSeamGap } from "@threenative/terrain/starter"

PRD-790: where streamed tiles meet the collar. The tiles draw inside the square (centreX, centreZ, half) and the collar outside it, so the seam is that square's edge, past the playable square. gap is the largest step at the tiles' edge vertices (spacing apart), as core measures a tile-to-tile seam; fold is the largest step between them, where a fold of the collar's coarser triangles crosses a tile's straight edge.

ts
function collarSeamGap( collar: HeightfieldCollar, height: (x: number, z: number) => number, centreX: number, centreZ: number, half: number, spacing: number, step = 0.1, ):

Needs

  • npm i -D @threenative/terrain

Use it to

  • prove a streamed ground and its collar meet without a step

Example

ts
const { gap, fold } = collarSeamGap(collar, tilesHeight, x, z, 288, 2);

Good to know

  • the caller supplies the height the tiles draw; a coarser step samples faster

createDiagnosticsState

function · import { createDiagnosticsState } from "@threenative/terrain/starter"

The state one world's measurements are reported through, with its own name in it. The game spreads this into its own state and adds the look values it also reports; the counters live here. The window groups and the drawn-frame counts are module-level on purpose: ctx.goto builds a new scene for the next world, and the numbers a run reports are the run's, not one scene's.

ts
function createDiagnosticsState(world: string)

Needs

  • npm i -D @threenative/terrain @threenative/physics

Use it to

  • start a kit's game state with the measurements every streamed starter world reports

Example

ts
const state = { ...createDiagnosticsState("forest"), showcase: false };

Good to know

  • the world name is the one this state measures; a blank name fails rather than reporting ""

createMeasure

function · import { createMeasure } from "@threenative/terrain/starter"

The per-world measurement: contacts, travel, edge overshoot, water and the frame facts a run reports.

ts
function createMeasure(options: IMeasureOptions): IMeasure

Needs

  • npm i -D @threenative/terrain @threenative/physics

Use it to

  • measure one played starter world every fixed step

Example

ts
const measure = createMeasure({ world, physics: ctx.physics, raycast, actor, player, ...options });

Good to know

  • the game supplies the actor, the player body and the probe fixture; it owns no look

createMorphedHeight

function · import { createMorphedHeight } from "@threenative/terrain/starter"

The height a tile vertex stands at once collarMorph moved it: the survey inside the band, the collar's arithmetic height at the drawn square's edge. The seam measure reads this.

ts
function createMorphedHeight( collar: HeightfieldCollar, curve: ICollarRingCurve, height: (x: number, z: number) => number, centreX: number, centreZ: number, half: number, band: number, ): (x: number, z: number) => number

Needs

  • npm i -D @threenative/terrain

Use it to

  • check on the CPU the surface the tile shader draws after its morph

Example

ts
const height = createMorphedHeight(collar, curve, surveyHeight, x, z, 288, 64);

Good to know

  • mirrors collarMorph's weight exactly; both read the same curve and band

createPlayerRig

function · import { createPlayerRig } from "@threenative/terrain/starter"

The player: the capsule the solver moves, the mannequin that rides it, and the third-person camera that follows with the terrain as its walls. The stepped world is the authority for both the ground the player stands on and the wall the orbit camera cannot pass, which is why both queries mask to the game's ground layer: what the player can walk on. Every appearance value — the mannequin, its clips, the gait speeds, the capsule and the camera framing — comes from the game.

ts
function createPlayerRig(options: IPlayerRigOptions): IPlayerRig

Needs

  • npm i -D @threenative/terrain @threenative/physics

Use it to

  • give a copied starter kit its player capsule, mannequin and follow camera

Example

ts
const rig = createPlayerRig({ at, field, mannequin, clips, gait, camera, probe, ...options });

Good to know

  • the game builds the camera and the wall probe; the package owns only their wiring

createRevealProbe

function · import { createRevealProbe } from "@threenative/terrain/starter"

What the loading reveal showed once the curtain lifts: drawn batches, pipelines and impostor readiness, measured against the reveal's own baseline.

ts
function createRevealProbe(options: IRevealProbeOptions): IRevealProbe

Needs

  • npm i -D @threenative/terrain

Use it to

  • measure whether the spawn drew before the curtain released it

Example

ts
const reveal = createRevealProbe({ camera, covered, phase, released, ...options });

createSpawnGate

function · import { createSpawnGate } from "@threenative/terrain/starter"

The spawn gate: one deadline, one settlement, one failure report. WorldCells.whenSpawnReady is the data authority and each streamed world's prewarmed is the draw gate; this gate turns their landing into the loading screen's release, and writes the one console line a failed spawn leaves behind.

ts
function createSpawnGate(ctx: SpawnGateHost, options: ISpawnGateOptions): ISpawnGate

Needs

  • npm i -D @threenative/terrain

Use it to

  • hold a streamed starter world's loading screen until its spawn has landed

Example

ts
const gate = createSpawnGate(ctx, { world, progress, witness, released });

Good to know

  • Every value it reports is supplied by the game; a failure writes one TN_ line

editWorldPlacements

function · import { editWorldPlacements } from "@threenative/terrain/starter"

Apply deterministic startup edits to the decoded placement data before a world is loaded.

ts
function editWorldPlacements( data:

Needs

  • npm i -D @threenative/terrain

Use it to

  • change generated terrain composition from game source without rebaking the world

Example

ts
const edited = editWorldPlacements(data, { remove: ["scree:candidate:7:41"] }, (x, z) => field.heightAt(x, z));

Options

  • grounding defaults on, while grounding: false preserves the authored Y coordinate

enterView

function · import { enterView } from "@threenative/terrain/starter"

The camera cycle moved to another view: a keyed group for it, and a fresh measurement.

ts
function enterView(world: string, view: string):

Needs

  • npm i -D @threenative/terrain

Use it to

  • switch the measured view when the benchmark camera cycle moves

Example

ts
const { windows } = enterView("forest", "overview");

invalidatePropShadows

function · import { invalidatePropShadows } from "@threenative/terrain/starter"

Keep WorldCells' changed caster bounds when forwarding to the existing shadow renderer.

ts
function invalidatePropShadows( shadow:

Needs

  • npm i -D @threenative/terrain

Use it to

  • forward a streamed world's changed caster bounds to the game's shadow renderer

Example

ts
invalidatePropShadows(ctx.shadows, region);

leaveScene

function · import { leaveScene } from "@threenative/terrain/starter"

The scene is gone: nothing is on screen, so no window can belong to a view.

ts
function leaveScene(): void

Needs

  • npm i -D @threenative/terrain

Use it to

  • stop attributing windows to a view when its scene is left

Example

ts
leaveScene();

loadCanopy

function · import { loadCanopy } from "@threenative/terrain/starter"

The canopy weight the ground shader reads, painted from the placements the bake drew.

ts
async function loadCanopy( assets: Pick<IAssetLoader, "resolve">, world: string, ): Promise<Float32Array>

Needs

  • npm i -D @threenative/terrain

Use it to

  • load the canopy map a streamed world's ground shades with

Example

ts
const canopy = await loadCanopy(assets, "forest");

loadPropPackage

function · import { loadPropPackage } from "@threenative/terrain/starter"

The baked prop package of one world, fetched as the bake wrote it. The files are the bake's output, not the game's: the manifest names one container, one reach array and one placement-ID list per streamed world, and nothing here derives a placement.

ts
async function loadPropPackage( assets: Pick<IAssetLoader, "resolve">, world: string, ): Promise<IPropPackage>

Needs

  • npm i -D @threenative/terrain

Use it to

  • load the prop containers a bake wrote for one world

Example

ts
const props = await loadPropPackage(assets, "forest");

loadSky

function · import { loadSky } from "@threenative/terrain/starter"

The share of the sky each terrain vertex sees past the relief, as skyVisibility baked it.

ts
async function loadSky( assets: Pick<IAssetLoader, "resolve">, world: string, ): Promise<Float32Array>

Needs

  • npm i -D @threenative/terrain

Use it to

  • load the sky-visibility map a streamed world's ground shades with

Example

ts
const sky = await loadSky(assets, "forest");

observeFrame

function · import { observeFrame } from "@threenative/terrain/starter"

One world frame was drawn: count it, and open a fresh GPU sample window if the view or the readiness changed. Called from the render hook, before the camera is placed.

ts
function observeFrame(ctx: ICounterCtx): void

Needs

  • npm i -D @threenative/terrain

Use it to

  • count a drawn frame and open the next GPU sample window

Example

ts
ctx.beforeRender(() => observeFrame(ctx));

observeWindow

function · import { observeWindow } from "@threenative/terrain/starter"

The frame-budget window closed: latch it, and update the numbers the run reports.

ts
function observeWindow(window: IFrameBudgetWindow): void

Needs

  • npm i -D @threenative/terrain

Use it to

  • read the engine's own closed frame window into the run's report

Example

ts
frameBudget: { onWindow: observeWindow }

preparePose

function · import { preparePose } from "@threenative/terrain/starter"

The pose a prop draws at, grounded on the game's own height field. The record's quaternion, when present, replaces the rotation a live placement composes; every step below it — the ground snap, the boulder burial, the flat-footprint sink and the crag base ring — still runs, because the record is a pose and not an override of the pose. A placement with no ground under it fails closed by its own id, so a streamed world cannot silently float.

ts
function preparePose( geometry: BufferGeometry, _material: Material, placement: IPlacement, transform: IPlacementOverride | undefined, groundAt: PropGroundQuery, rules: IPropGroundRules, pose?: IPropPoseOverride, ): IPropPose

Needs

  • npm i -D @threenative/terrain

Use it to

  • ground one baked prop record on the game's height field before streaming it

Example

ts
const pose = preparePose(foot.geometry, material, record.placement, undefined, groundAt, rules);

Good to know

  • the burial, footprint and base-ring assets are the game's; the package applies them

preparePropTransform

function · import { preparePropTransform } from "@threenative/terrain/starter"

The pose and the transform an editor edited, prepared together so one write reports both.

ts
function preparePropTransform( instance: IPropInstance, transform: IPlacementOverride | undefined, groundAt: PropGroundQuery, rules: IPropGroundRules, )

Needs

  • npm i -D @threenative/terrain

Use it to

  • re-pose one prop the editor edited and keep the transform it reported

Example

ts
const prepared = preparePropTransform(instance, transform, groundAt, rules);

PropColliders

class · import { PropColliders } from "@threenative/terrain/starter"

Stream caller-specified fixed collision shapes around a moving follow object.

ts
class PropColliders extends Object3D implements IComputeDriven

Needs

  • npm i -D @threenative/terrain

Use it to

  • attach nearby prop collision bodies from baked placement records

Example

ts
new PropColliders(ctx, follow, manifest, records, shapes, reach, name);

Good to know

  • Shapes and reach are supplied by the game; detach releases every body

propCounts

function · import { propCounts } from "@threenative/terrain/starter"

Records per asset across the package's buckets: what the run report calls the scatter's counts.

ts
function propCounts( pkg: IPropPackage, assetNames: readonly string[], ): Record<string, number>

Needs

  • npm i -D @threenative/terrain

Use it to

  • report how many records each asset drew, zero included

Example

ts
const counts = propCounts(pkg, ["spruce", "boulder"]);

propKey

function · import { propKey } from "@threenative/terrain/starter"

The model a record draws: its asset, its variant, and the shape a non-uniform edit gave it. WorldCells names the model through the run the record sits in, so this key is what the container stores. A placement with one uniform scale draws its variant as authored (spruce:2); a placement the editor scaled unevenly draws a model of that shape (spruce:2@1,0.5,0.5), so the record stays one uniform scale and the picture keeps the edit.

ts
function propKey(placement: IPlacement, variant: number): string

Needs

  • npm i -D @threenative/terrain

Use it to

  • name the model a baked or live placement record draws

Example

ts
const key = propKey(placement, 2);

propRatio

function · import { propRatio } from "@threenative/terrain/starter"

The shape propKey wrote, so the loader scales the model the record's one scale cannot carry.

ts
function propRatio(key: string): [number, number, number]

Needs

  • npm i -D @threenative/terrain

Use it to

  • scale a streamed model by the shape its record's single scale cannot carry

Example

ts
const ratio = propRatio("spruce:2@1,0.5,0.5");

publish

function · import { publish } from "@threenative/terrain/starter"

Publish the measurements and the scene's own facts into state, twice per second.

ts
function publish( ctx:

Needs

  • npm i -D @threenative/terrain

Use it to

  • write the measured view and frame numbers into the game's state

Example

ts
publish(ctx, { world, worldReady, frames, ...facts });

readPropTransform

function · import { readPropTransform } from "@threenative/terrain/starter"

The transform an instance's current pose describes.

ts
function readPropTransform(instance: IPropInstance): IPlacementOverride

Needs

  • npm i -D @threenative/terrain

Use it to

  • read an edited prop's current pose for the scene format

Example

ts
const transform = readPropTransform(instance);

streamProps

function · import { streamProps } from "@threenative/terrain/starter"

Load the prop worlds, pose every record on the ground, and hand each bucket to WorldCells. The passes are short and yield between slices, because the whole point of streaming is that the first frame does not wait for 200 000 records: the records are decoded and grounded in slices, and each bucket loads as its own world.

ts
async function streamProps(options: IPropWorldOptions)

Needs

  • npm i -D @threenative/terrain

Use it to

  • stream a world's baked prop containers and its live placements through WorldCells

Example

ts
const props = await streamProps({ package: propPackage, groundAt, parts, materials, surface,
  follow, size, whileCurrent, variantOf, reachOf, bucketOf, lodOf, ...options });

Good to know

  • the variant, reach, bucket, LOD and gate rows are the game's; the package only applies

withAuthoredPose

function · import { withAuthoredPose } from "@threenative/terrain/starter"

A placement as a package record stores it: the authored pose becomes its transform, at one scale. A record holds position, quaternion and one uniform scale, so an edited placement's own transform is folded down to the scale its record carries. The shape that scale removed is propKey's ratio, and the drawable model that ratio names carries it instead.

ts
function withAuthoredPose(placement: IPlacement): IPlacement

Needs

  • npm i -D @threenative/terrain

Use it to

  • fold an authored placement into the record transform the bake stores

Example

ts
const record = withAuthoredPose(placement);

writePropTransform

function · import { writePropTransform } from "@threenative/terrain/starter"

Writes a prepared pose onto the instance, reporting the transform only when the pose changed.

ts
function writePropTransform( instance: IPropInstance, prepared: ReturnType<typeof preparePropTransform>, ): void

Needs

  • npm i -D @threenative/terrain

Use it to

  • write an edited prop's prepared pose back onto its instance

Example

ts
writePropTransform(instance, prepared);

toGeometry

function · import { toGeometry } from "@threenative/terrain/three"

Converts baked arrays to ordinary geometry using the consumer's installed Three.js.

ts
function toGeometry(mesh: IBakedMesh): BufferGeometry

Needs

  • npm i @threenative/terrain

Use it to

  • put an authored terrain mesh in a game-owned Three.js scene

Example

ts
const geometry = toGeometry(bakeMesh(new Terrain({ resolution: 17 }).evaluate()));

Good to know

  • creates only geometry; the caller owns its material, scene and disposal

Options

  • every surface choice remains in game source
View source on GitHub ↗