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
Attach manual transforms to raw evaluated candidates and report orphan keys.
function applyPlacementOverrides(state: ITerrainState, value: unknown): ITerrainStateNeeds
- npm i -D @threenative/terrain
Use it to
- retain manual prop transforms across terrain scatter re-evaluation
Example
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
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.
function bakeBiome(options: IBakeBiomeOptions): IBakedBiomeNeeds
- 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
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
Bakes the recovered indexed top surface and optional vertical skirts into caller-owned arrays.
function bakeMesh( state: ITerrainState,Needs
- npm i @threenative/terrain
Use it to
- bake an authored terrain into portable indexed mesh arrays
Example
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
Bakes finite LOD chunks, the same collision samples and resolved placements.
function bakeTerrain( state: ITerrainState,Needs
- npm i @threenative/terrain
Use it to
- prepare terrain arrays and collision before a game starts
Example
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
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.
function bakeWorldPackage( state: ITerrainState, options: IBakeWorldPackageOptions, ): IBakedWorldPackageNeeds
- npm i -D @threenative/terrain
Use it to
- hand an evaluated Strata terrain to a game without a Blender round trip
Example
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
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.
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
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
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.
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
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
Build the index once per world; ask nearby per scatter candidate or heightfield vertex.
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
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
CRC-checked bounded non-interlaced grayscale PNG height decoder.
async function decodeHeightPNG( input: Uint8Array | ArrayBuffer, options: IDecodeHeightPngOptions =Needs
- npm i @threenative/terrain
Use it to
- import numerical PNG8 or PNG16 terrain elevations
Example
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
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.
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
for (const record of decodePropBucket(bucket)) pose(record.key, record.position, record.quaternion);Good to know
- throws
TN_PROP_BUCKET_INVALIDwhen the record buffer, the IDs and the runs disagree
decodeRAW16
Validates dimensions and range before decoding numerical height samples.
function decodeRAW16( input: Uint8Array | ArrayBuffer,Needs
- npm i @threenative/terrain
Use it to
- import a RAW16 terrain height buffer with explicit dimensions
Example
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
Legacy terrain-only GLB encoding with embedded mesh arrays and no chosen material.
function encodeGLB(input: IBakedMesh | readonly IBakedMesh[])Needs
- npm i @threenative/terrain
Use it to
- export baked terrain geometry without engine extensions
Example
const glb = encodeGLB(bakeMesh(new Terrain({ resolution: 17 }).evaluate()));Good to know
- authoring data only; the game owns appearance, physics and rendering
encodeHeightPNG
Encodes numerical grayscale PNG16 with embedded elevation range.
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
const png = await encodeHeightPNG(new Terrain({ resolution: 17 }).evaluate());Good to know
- authoring data only; the game owns appearance, physics and rendering
encodeRAW16
Encodes finite metre elevations as an explicit-range RAW16 buffer.
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
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
Encodes the eight linear material-weight channels as two RGBA images.
async function encodeSplatPNGs(state: ITerrainState)Needs
- npm i @threenative/terrain
Use it to
- export terrain splat weights as linear data
Example
const maps = await encodeSplatPNGs(new Terrain({ resolution: 17 }).evaluate());Good to know
- authoring data only; the game owns appearance, physics and rendering
encodeZIP
Deterministic store-method ZIP with safe unique relative filenames.
function encodeZIP(files: readonly IExportFile[])Needs
- npm i @threenative/terrain
Use it to
- archive derived terrain files without another dependency
Example
const archive = encodeZIP([{ name: "height.raw", bytes: new Uint8Array(8) }]);Good to know
- authoring data only; the game owns appearance, physics and rendering
farForestPlacements
Far-field placements on the collar; also paints the collar's canopy attribute under each crown.
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
const trees = farForestPlacements({ size, resolution, collar, treeline, rules, asset, layer });Good to know
- the row's
farblock decides every density; the caller supplies the collar and layer
fieldWeight
A field's weight at (x, z), clamped to 0..1.
function fieldWeight(field: ICoverField, x: number, z: number): numberNeeds
- 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
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
World-space height gradient from the canonical samples.
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
const gradient = gradientAt(new Terrain({ resolution: 17 }).evaluate(), 0, 0);Good to know
- authoring data only; the game owns appearance, physics and rendering
grassFieldFromBiome
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.
function grassFieldFromBiome( biome: Pick<IBiomeSpec, "grass" | "seed">, ground: IGrassGround, ): IGrassFieldPlacement | nullNeeds
- 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
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.tsblade and material
landform
One call, one landscape: a calibrated layer recipe for a kind of environment.
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
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, thenevaluate()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
reliefis the highest-minus-lowest height in metres before the finishing passes shave a few percent;size,resolutionandseedas inTerrain
landformBackdrop
Distant mountains around a playable area: a landform window with a valley floor at its centre.
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
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
reliefandcenterHeightin metres;size,resolutionandseedas inlandform
liftMassif
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.
function liftMassif(tile: IMassifTile): Float32ArrayNeeds
- npm i -D @threenative/terrain
Use it to
- measure how tall a surveyed mountain stands above the valley floor around it
Example
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
Recovered numerical/project exports; GLB/runtime outputs contain terrain only.
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
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
Resolve a biome's fraction bands against this world's own height samples.
function measureBands( layers: readonly ILayerInfo[], heights: ArrayLike<number>, ): IMeasuredBandsNeeds
- npm i -D @threenative/terrain
Use it to
- turn a biome file's height fractions into the metres a world actually measured
Example
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
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.
function orderedScatterRules(spec: IBiomeSpec): IOrderedScatterRulesNeeds
- npm i -D @threenative/terrain
Use it to
- run a biome file's rows through the ordered scatter
Example
const rules = orderedScatterRules(spec);Good to know
- the file carries one foliage row, one grass row and a cover block
paintCanopyCover
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).
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
paintCanopyCover(values, { size: 512, resolution: 257 }, placements, { spruce: 7 });Good to know
crownsis metres of crown radius per unit of placement scale, keyed by asset; other assets paint nothing
placeMassif
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.
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
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,faceandkeepOuton the same call
propAssetOf
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.
function propAssetOf(modelKey: string): stringNeeds
- 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
const asset = propAssetOf("spruce:2"); // "spruce"propPackageFile
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.
function propPackageFile(world: string, bucket: string, suffix: string): stringNeeds
- 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
const file = propPackageFile("forest", "local:true", "props.bin"); // "forest.local-true.props.bin"propPackageFiles
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).
function propPackageFiles(pkg: IPropPackage, world: string): IPropPackageFilesNeeds
- npm i -D @threenative/terrain
Use it to
- write a compiled package to disk: one manifest and three files per streamed world
Example
const { manifest, files } = propPackageFiles(pkg, "forest");Good to know
- the manifest names the files; nothing here touches a file system
sampleHeight
Bilinear query of canonical height samples; triangle sampling is a separate contract.
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
const height = sampleHeight(new Terrain({ resolution: 17 }).evaluate(), 0, 0);Good to know
- authoring data only; the game owns appearance, physics and rendering
scatterProps
Every placement, for one world, from one seed: the game's own rule set, in its own draw order.
function scatterProps( data: IOrderedScatterField, focus:Needs
- npm i -D @threenative/terrain
Use it to
- bake a biome that says
"stream": "ordered"
Example
const { placements, counts } = scatterProps(data, focus, clearings);Good to know
data.rulesis the biome's rows, anddata.fieldthe ground they were graded on
skyVisibility
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.
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
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
Slope in degrees at a heightfield sample.
function slopeAtIndex(grid: ISampledGrid, i: number): numberNeeds
- npm i @threenative/terrain
Use it to
- measure terrain slope for authoring diagnostics
Example
const slope = slopeAtIndex(new Terrain({ resolution: 17 }).evaluate(), 0);Good to know
- authoring data only; the game owns appearance, physics and rendering
slopeQuantile
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.
function slopeQuantile(grid: ISampledGrid, quantile: number): numberNeeds
- 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
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
Recovered horizontal Catmull–Rom and vertically linear profile sampler.
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
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
Ordered, stable-ID terrain authoring with synchronous atomic transactions.
class TerrainNeeds
- 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 adderode({ method: "fluvial" })for dendritic valleys
Example
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;
sizeis the world edge in metres (1 to 100000), centred on the origin resolutioncounts vertices per edge and must be one of 17, 33, 65, 129, 257, 513 or 1025seedis an integer from 0 to 4294967295; one document and seed evaluate to the same arraysevaluate()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
Recovered prefix-caching authoring evaluator. Returned buffers belong to the caller.
class TerrainEvaluatorNeeds
- npm i @threenative/terrain
Use it to
- reuse terrain evaluation prefixes while authoring a finite heightfield
Example
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
Landform statistics used to calibrate generators against real DEMs.
function terrainStats(height: ArrayLike<number>, n: number, size: number): ITerrainStatsNeeds
- npm i @threenative/terrain
Use it to
- compare generated terrain with a USGS or SRTM crop on the same footprint
Example
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
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.
function validateBiome(spec: unknown, name: string): IBiomeSpecNeeds
- npm i @threenative/terrain
Use it to
- read a biome's rules from
starter/<biome>/biome.data.jsonbefore a game or a cook uses them
Example
const spec = validateBiome(JSON.parse(text), "forest");Good to know
- The file carries no appearance; colours, materials and shading stay game source
validateDocument
Validates the recovered recipe schema, operation allow-lists and numeric bounds.
function validateDocument(doc: ITerrainDocument): voidNeeds
- npm i @threenative/terrain
Use it to
- validate a terrain document before accepting an authoring write
Example
validateDocument(new Terrain({ resolution: 17 }).toJSON());Good to know
- authoring data only; the game owns appearance, physics and rendering
validatePlacementOverrides
Validate and clone stable-key placement transforms before saving or previewing them.
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
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
Check that the images an environment names are registered environment or image assets. @summary Validate the assets a preview environment refers to
function checkEnvironmentAssets( environment: IEnvironment, assets: readonlyNeeds
- npm i -D @threenative/terrain
Use it to
- refuse a saved environment whose sky or lighting image is not a registered file
Example
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
Gesture and transaction mechanics; the caller owns the controls, proxy and all rendering.
function createEditorSelection(Needs
- npm i -D @threenative/terrain
Use it to
- drive terrain-editor selection, gizmo drags, undo and saved transactions
Example
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
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.
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
const box = createTweakBox({ title: "Fog", knobs: { density: { min: 0, max: 0.1, value: 0.02 } }, onChange: (name, value) => console.info(name, value) });editorPlacementCenter
Transform the caller's measured geometry centre into the evaluated placement's world space.
function editorPlacementCenter(point: Vector3, pose: IPlacementOverride): Vector3Needs
- npm i -D @threenative/terrain
Use it to
- find the world-space centre of a placed terrain-editor instance
Example
const centre = editorPlacementCenter(localCentre.clone(), placement);Good to know
- the point is multiplied in place; the pose needs finite position, quaternion and scale
editorPointToClient
Project an injected world point to client pixels in the caller's viewport.
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
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
Query the rendered heightfield, including its triangulation rather than an interpolated bake.
function editorSurfaceHeight( ctx:Needs
- npm i -D @threenative/terrain
Use it to
- query terrain-editor surface elevation at world X/Z coordinates
Example
const height = editorSurfaceHeight(ctx, terrainMesh, x, z);Good to know
- the supplied mesh and raycast determine the surface; missing intersections return undefined
focusCamera
Frame a point, prop, landmark or region for the live viewport and projection. @summary Frame a focus target with an editor observation camera
function focusCamera( camera: ISavedCamera, request: IFocusRequest, resolve: IFocusResolver, ): IFocusOutcomeNeeds
- npm i -D @threenative/terrain
Use it to
- frame one selected prop, a registered landmark, a terrain region or a local point
Example
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
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
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
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
Read-only spatial inspection of one evaluated terrain revision.
function inspectSpatial( state: ITerrainState, revision: string, query: ISpatialQuery, ): ISpatialObservationNeeds
- npm i -D @threenative/terrain
Use it to
- measure a point, profile a transect or score a saved reference against the world
Example
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
Recipe footprints are heights over X/Z, never independently transformed solids.
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
const pose = landformPose(layer, terrain.size, footprintSize);Good to know
- the caller supplies world and default footprint sizes; unsupported layers return undefined
mountTerrainEditor
Mount recovered terrain controls around the project-owned ThreeNative view.
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
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
A foreground terrain hit occludes placements; matching uses the evaluated world position.
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
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
Convert viewport client coordinates once; the installed picker owns ray intersection.
function pickEditorSurface( ctx:Needs
- npm i -D @threenative/terrain
Use it to
- pick a terrain-editor surface from viewport client coordinates
Example
const hit = pickEditorSurface(ctx, [terrainMesh], event.clientX, event.clientY);Good to know
- the caller supplies the raycast implementation and ordered targets
probeTerrain
Probe the evaluated surface at one world point, separating bilinear from triangle values.
function probeTerrain( state: ITerrainState, revision: string, at: readonly number[], ): IPointObservationNeeds
- npm i -D @threenative/terrain
Use it to
- measure an authored terrain point with provenance and a revision identity
Example
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
Run one create / get / list / update / delete / activate operation over saved cameras. @summary Apply an editor camera operation to a saved camera set
function runCameraOperation(set: ICameraSet, operation: unknown): ICameraResultNeeds
- 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
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
Apply one get / patch / reset against the saved environment overrides; the caller commits it. @summary Run one preview-environment operation
function runEnvironmentOperation( current: IEnvironment, operation: unknown, ): IEnvironmentResultNeeds
- npm i -D @threenative/terrain
Use it to
- patch sun, haze, exposure or sea overrides from a controller or the editor GUI
Example
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
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
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
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
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
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
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
HTTP controller for the project-local terrain editor.
class TerrainEditorControllerNeeds
- npm i -D @threenative/terrain
Use it to
- inspect and atomically edit the terrain editor from an agent
Example
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
Convert a terrain-editor gizmo pose into a heightfield landform footprint.
function transformedLandform( layer: Layer, position: Vector3, quaternion: Quaternion, scale: Vector3, anchor: number, ): LayerNeeds
- npm i -D @threenative/terrain
Use it to
- apply a terrain-editor gizmo transform to a landform layer
Example
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
Validate one saved asset registration exactly as a document commit stores it. @summary Validate a registered terrain-editor asset entry
function validateAsset(input: unknown): IProjectAssetNeeds
- npm i -D @threenative/terrain
Use it to
- check a model, image or environment asset entry before saving it in the authoring document
Example
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
Validate the whole asset list of an authoring document. @summary Validate the registered terrain-editor assets
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
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
Normalise and validate one saved camera, exactly as a document commit would store it. @summary Validate an editor observation camera bookmark
function validateCamera( input: unknown, existing: readonly ISavedCamera[] = [], ): ISavedCameraNeeds
- npm i -D @threenative/terrain
Use it to
- create or update a named terrain-editor camera in the shared authoring document
Example
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
Validate a document's saved camera list, keeping ids unique across it. @summary Validate the saved editor camera list of an authoring document
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
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
Validate a complete overrides object exactly as a document commit stores it. @summary Validate preview environment overrides
function validateEnvironment(input: unknown): IEnvironmentNeeds
- npm i -D @threenative/terrain
Use it to
- save sun, sky, haze, exposure or ocean overrides in the shared authoring document
Example
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
Normalise and validate one saved reference, exactly as a document commit would store it.
function validateSpatialReference(input: unknown): ISavedSpatialReferenceNeeds
- npm i -D @threenative/terrain
Use it to
- accept a bounded local reference image registration into the shared document
Example
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
Validate surface mappings against the registered images they name. @summary Validate terrain-editor surface image mappings
function validateSurfaces( input: unknown, assets: readonly IProjectAsset[], ): ISurfaceMappingsNeeds
- 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
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
Mount the optional terrain document API on an existing loopback Vite server.
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
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
Project-local terrain document authority; no renderer or game dependency.
class TerrainEditorDocumentNeeds
- npm i -D @threenative/terrain
Use it to
- validate atomic revision-based project-local terrain document edits
Example
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
Prepare the game's validated, frozen portable scene; the server cook owns GLB encoding.
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
const prepared = await prepareWorldGLTF(input);Good to know
- browser authoring FileReader/canvas; all appearance and coherent water come from the game
bakeKit
Bake a copied kit, optionally using the caller's installed world cook.
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
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
Resolve shared starter assets locally, or download the package's pinned archive on demand.
async function starterAssetsDir(): Promise<string>Needs
- npm i -D @threenative/terrain
Use it to
- resolve terrain kit models and textures for offline baking
Example
const assets = await starterAssetsDir();Good to know
- Node authoring only; verifies archive size and SHA256 before atomic extraction
addStarterWorld
Load caller-authored starter data with one scene lifetime; all appearance comes from spec.
async function addStarterWorld<Extra extendsNeeds
- npm i -D @threenative/terrain
Use it to
- attach a baked starter world with game-owned surfaces, prop dressing and water
Example
await addStarterWorld(ctx, follow, spec);Good to know
- Runtime subpath; the game supplies every appearance and collision choice
addStreamedGround
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.
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
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
The quaternion a placement's own scatter numbers describe: the normal tilt, then the yaw.
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
const quaternion = authoredQuaternion(placement);beginScene
Start a scene's view accounting: the player view it opens in, and nothing measured yet.
function beginScene(world: string): voidNeeds
- npm i -D @threenative/terrain
Use it to
- start the run's view accounting when a scene enters
Example
beginScene("forest");collarArithmeticHeight
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.
function collarArithmeticHeight( collar: HeightfieldCollar, curve: ICollarRingCurve, x: number, z: number, ): numberNeeds
- npm i -D @threenative/terrain
Use it to
- answer a collar height on the CPU exactly as its tile shader computes it
Example
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
The collar's drawn height under (x, z); null where there is no collar.
function collarDrawnHeight(collar: HeightfieldCollar, x: number, z: number): number | nullNeeds
- npm i -D @threenative/terrain
Use it to
- measure or collide against the triangles a collar actually draws
Example
const y = collarDrawnHeight(collar, x, z);Good to know
- reads the collar it is given; never resamples the square or builds a surface
collarMorph
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.
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
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
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.
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
const { gap, fold } = collarSeamGap(collar, tilesHeight, x, z, 288, 2);Good to know
- the caller supplies the height the tiles draw; a coarser
stepsamples faster
createDiagnosticsState
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.
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
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
The per-world measurement: contacts, travel, edge overshoot, water and the frame facts a run reports.
function createMeasure(options: IMeasureOptions): IMeasureNeeds
- npm i -D @threenative/terrain @threenative/physics
Use it to
- measure one played starter world every fixed step
Example
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
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.
function createMorphedHeight( collar: HeightfieldCollar, curve: ICollarRingCurve, height: (x: number, z: number) => number, centreX: number, centreZ: number, half: number, band: number, ): (x: number, z: number) => numberNeeds
- npm i -D @threenative/terrain
Use it to
- check on the CPU the surface the tile shader draws after its morph
Example
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
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.
function createPlayerRig(options: IPlayerRigOptions): IPlayerRigNeeds
- npm i -D @threenative/terrain @threenative/physics
Use it to
- give a copied starter kit its player capsule, mannequin and follow camera
Example
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
What the loading reveal showed once the curtain lifts: drawn batches, pipelines and impostor readiness, measured against the reveal's own baseline.
function createRevealProbe(options: IRevealProbeOptions): IRevealProbeNeeds
- npm i -D @threenative/terrain
Use it to
- measure whether the spawn drew before the curtain released it
Example
const reveal = createRevealProbe({ camera, covered, phase, released, ...options });createSpawnGate
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.
function createSpawnGate(ctx: SpawnGateHost, options: ISpawnGateOptions): ISpawnGateNeeds
- npm i -D @threenative/terrain
Use it to
- hold a streamed starter world's loading screen until its spawn has landed
Example
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
Apply deterministic startup edits to the decoded placement data before a world is loaded.
function editWorldPlacements( data:Needs
- npm i -D @threenative/terrain
Use it to
- change generated terrain composition from game source without rebaking the world
Example
const edited = editWorldPlacements(data, { remove: ["scree:candidate:7:41"] }, (x, z) => field.heightAt(x, z));Options
- grounding defaults on, while
grounding: falsepreserves the authored Y coordinate
enterView
The camera cycle moved to another view: a keyed group for it, and a fresh measurement.
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
const { windows } = enterView("forest", "overview");invalidatePropShadows
Keep WorldCells' changed caster bounds when forwarding to the existing shadow renderer.
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
invalidatePropShadows(ctx.shadows, region);leaveScene
The scene is gone: nothing is on screen, so no window can belong to a view.
function leaveScene(): voidNeeds
- npm i -D @threenative/terrain
Use it to
- stop attributing windows to a view when its scene is left
Example
leaveScene();loadCanopy
The canopy weight the ground shader reads, painted from the placements the bake drew.
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
const canopy = await loadCanopy(assets, "forest");loadPropPackage
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.
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
const props = await loadPropPackage(assets, "forest");loadSky
The share of the sky each terrain vertex sees past the relief, as skyVisibility baked it.
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
const sky = await loadSky(assets, "forest");observeFrame
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.
function observeFrame(ctx: ICounterCtx): voidNeeds
- npm i -D @threenative/terrain
Use it to
- count a drawn frame and open the next GPU sample window
Example
ctx.beforeRender(() => observeFrame(ctx));observeWindow
The frame-budget window closed: latch it, and update the numbers the run reports.
function observeWindow(window: IFrameBudgetWindow): voidNeeds
- npm i -D @threenative/terrain
Use it to
- read the engine's own closed frame window into the run's report
Example
frameBudget: { onWindow: observeWindow }preparePose
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.
function preparePose( geometry: BufferGeometry, _material: Material, placement: IPlacement, transform: IPlacementOverride | undefined, groundAt: PropGroundQuery, rules: IPropGroundRules, pose?: IPropPoseOverride, ): IPropPoseNeeds
- npm i -D @threenative/terrain
Use it to
- ground one baked prop record on the game's height field before streaming it
Example
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
The pose and the transform an editor edited, prepared together so one write reports both.
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
const prepared = preparePropTransform(instance, transform, groundAt, rules);PropColliders
Stream caller-specified fixed collision shapes around a moving follow object.
class PropColliders extends Object3D implements IComputeDrivenNeeds
- npm i -D @threenative/terrain
Use it to
- attach nearby prop collision bodies from baked placement records
Example
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
Records per asset across the package's buckets: what the run report calls the scatter's counts.
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
const counts = propCounts(pkg, ["spruce", "boulder"]);propKey
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.
function propKey(placement: IPlacement, variant: number): stringNeeds
- npm i -D @threenative/terrain
Use it to
- name the model a baked or live placement record draws
Example
const key = propKey(placement, 2);propRatio
The shape propKey wrote, so the loader scales the model the record's one scale cannot carry.
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
const ratio = propRatio("spruce:2@1,0.5,0.5");publish
Publish the measurements and the scene's own facts into state, twice per second.
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
publish(ctx, { world, worldReady, frames, ...facts });readPropTransform
The transform an instance's current pose describes.
function readPropTransform(instance: IPropInstance): IPlacementOverrideNeeds
- npm i -D @threenative/terrain
Use it to
- read an edited prop's current pose for the scene format
Example
const transform = readPropTransform(instance);streamProps
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.
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
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
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.
function withAuthoredPose(placement: IPlacement): IPlacementNeeds
- npm i -D @threenative/terrain
Use it to
- fold an authored placement into the record transform the bake stores
Example
const record = withAuthoredPose(placement);writePropTransform
Writes a prepared pose onto the instance, reporting the transform only when the pose changed.
function writePropTransform( instance: IPropInstance, prepared: ReturnType<typeof preparePropTransform>, ): voidNeeds
- npm i -D @threenative/terrain
Use it to
- write an edited prop's prepared pose back onto its instance
Example
writePropTransform(instance, prepared);toGeometry
Converts baked arrays to ordinary geometry using the consumer's installed Three.js.
function toGeometry(mesh: IBakedMesh): BufferGeometryNeeds
- npm i @threenative/terrain
Use it to
- put an authored terrain mesh in a game-owned Three.js scene
Example
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