API by package
@threenative/core API
Every public function and class in @threenative/core. The small vanilla Three.js game runtime foundation.
On this page
Generated from the engine's capability manifest: 196 functions and 76 classes. Each entry is the exported signature, what it is for, and a working example. Start with the package overview.
addFoliageBackLight
Adds subsurfaceColor times the far-face irradiance to a Two Sided Foliage leaf's emissive node.
function addFoliageBackLight(material: Material, backIrradiance: Node<"vec3">): booleanUse it to
- add bounce light to the far face of a two sided foliage leaf
Example
addFoliageBackLight(leaf, backIrradiance);Good to know
- the material needs the foliage marker and subsurfaceColor, else nothing is added and false is returned; call once per material
- the material needs
twoSidedFoliage = trueand asubsurfaceColor, or nothing is added and false is returned; backIrradiance is a vec3 node in the unit ofirradianceNode; call once per material
addInSlices
Attach hundreds of built objects to the scene in slices with an 8 ms default budget, presenting a frame between each.
async function addInSlices<T>( objects: Iterable<T>, add: (object: T, index: number) => void, options: IAddInSlicesOptions =Use it to
- add hundreds of built objects to the scene without one multi-second frame
- stream a detail tier in behind a loading curtain without the page looking hung
Example
const report = await addInSlices(objects, (object) => ctx.add(object), {
onProgress: ({ added, total }) => setProgress(added / total),
while: () => generation.live,
});Good to know
- the objects, and where each one goes, stay the game's; this decides only when each joins the graph
- input order is the attach order and cannot be changed
- a false
whilestops the run and is reported asstopped, never thrown
Options
- a slice ends on an 8 ms budget unless the game gives
sliceSize, and the reported sliceSize is then the measured average;marker: falsesilences the TN_ADD_SLICES line, not the report
addSpan
Attribute the render phase to 100% with a nested span tree, off unless TN_FRAME_SPANS asks. Every non-leaf reports its own time minus the spans inside it, so an unmeasured part shows up as a residual instead of being filed under "other"; a child that outlives its parent reports a negative residual rather than a clamped zero.
function addSpan(id: SpanId, ms: number): voidUse it to
- find out what inside the render phase is actually costing the frame
- tell a shadow pass's traversal from the main pass's, with the residual computed
- price an optimisation against a measured part of the phase rather than the whole of it
Example
if (spansRequested()) setSpanRecorder(new SpanRecorder());Good to know
- off by default and installed by
TN_FRAME_SPANS=1; unset, every call site is one guarded return - the tree is closed against the frame budget's own render phase, so
TN_FRAME_SPANSandTN_FRAME_BUDGETdescribe the same frames - measurement only: no span changes what is drawn, in what order, or with which renderer
aerodynamicCoefficients
Fly a fixed-wing aircraft with a real force balance instead of a steered velocity.
function aerodynamicCoefficients( alpha: number, flaps = 0, gear = 0, brakes = 0, ):Use it to
- fly an airplane with lift, drag, stall and control authority
- launch an aircraft off a moving carrier deck
- apply component damage or a loadout to an aircraft's performance
Example
const model = new FlightModel({ airframe: sbd, state: aircraft, wind: seaWind });
model.step(1 / 60, { turn: -1, pitch: 0.4 });Good to know
- every mass, area, power and inertia value comes from the game's airframe
- damage, stores and configuration arrive as the game's own modifier sample
afterPhysics
Register work that reads a body or camera after physics has moved it and before this frame draws. The engine owns the phase ordering; a callback cannot be misplaced by plugin-array order.
function afterPhysics( context: IAfterPhysicsContext, callback: AfterPhysicsCallback, ): () => voidUse it to
- read a body after physics has moved it
- place a camera or aim from the solved character transform
Example
afterPhysics(ctx, (dt) => camera.position.copy(player.mesh.position));Good to know
- register from a scene context; callbacks are cleared when that scene exits
aircraftMass
Fly a fixed-wing aircraft with a real force balance instead of a steered velocity.
function aircraftMass(state: IFlightState, airframe: IAircraftAirframe): numberUse it to
- fly an airplane with lift, drag, stall and control authority
- launch an aircraft off a moving carrier deck
- apply component damage or a loadout to an aircraft's performance
Example
const model = new FlightModel({ airframe: sbd, state: aircraft, wind: seaWind });
model.step(1 / 60, { turn: -1, pitch: 0.4 });Good to know
- every mass, area, power and inertia value comes from the game's airframe
- damage, stores and configuration arrive as the game's own modifier sample
airDensity
Fly a fixed-wing aircraft with a real force balance instead of a steered velocity.
function airDensity(y: number): numberUse it to
- fly an airplane with lift, drag, stall and control authority
- launch an aircraft off a moving carrier deck
- apply component damage or a loadout to an aircraft's performance
Example
const model = new FlightModel({ airframe: sbd, state: aircraft, wind: seaWind });
model.step(1 / 60, { turn: -1, pitch: 0.4 });Good to know
- every mass, area, power and inertia value comes from the game's airframe
- damage, stores and configuration arrive as the game's own modifier sample
alwaysRender
Keep an object drawn even when the render camera cannot resolve it. The engine's projected-size gate is on by default: an object whose world bounding sphere projects to fewer than 0.5 raster pixels in the camera about to render it is not submitted, per camera. Mark the player's own cockpit, a nameplate, a quest marker, or anything a game never wants to pop out of the frame. alwaysRender(object, false) removes the marker. Camera-attached objects and shadow casters are already kept, and the number of marked objects is reported beside the cull in the TN_PROJECTION window rather than hidden. The threshold itself is renderer.minimumProjectedPixels — a larger number cuts more aggressively, false leaves every object drawn while still measuring.
function alwaysRender(object: Object3D, enabled = true): voidUse it to
- keep a small object drawn when the engine would skip it as too far to resolve
- stop my cockpit, marker or player model popping out at distance
- a tiny object disappeared at range and I need it always visible
- widen or narrow the projected-size cull with a named threshold
Example
import { alwaysRender } from "@threenative/core";
alwaysRender(ctx.camera.children[0]); // a camera-attached cockpit stays drawnGood to know
- the marker is per object and is reported as
exemptMarkedin the projection window renderer.minimumProjectedPixels: falseleaves the scene drawn and keeps the measurement on- the marker is per object and survives scene rebuilds only as long as the object does
- disabling the gate (
renderer.minimumProjectedPixels: false) keeps its measurement on
Options
- renderer.minimumProjectedPixels sets the projected-pixel threshold, default 0.5
AnimationComposer
Compose game-authored locomotion and masked actions on one Three.js mixer.
class AnimationComposerUse it to
- synchronize walk/run/strafe clips with different durations
- reload with the upper body while locomotion continues
- apply an additive recoil clip with an explicit reference pose
- route root motion through collision-aware character movement
Example
const animation = new AnimationComposer({ root: rig, clips, samples: ["walk", "run"] });
animation.setWeights([0.5, 0.5]); animation.update(dt);Good to know
- one base phase, one masked override, at most two additive layers and eight actions
- root motion requires a separate rig below the body; advance, CharacterBody3D.move, finish with observed accepted motion after physics, then existing IK
- root motion excludes velocity-driven stride sync; unsupported parent transforms throw
- source clips remain immutable; dispose at scene exit
AnimationPlayer
Play a skinned or sprite animation from game code. A locomotion clip's playback rate is matched to the ground the body actually covers, so feet do not skate or spin — on by default, strideSync: false to keep the authored rate, and player.stride reports the measurement either way. Name the body a game moves as strideRoot when the rig is a child of it. Clips authored in place — every ActorX and Unreal export, every Mixamo "in place" clip, every stock animal pack — are matched too: their stride is read off the ground a planted foot sweeps, and stride.inPlace says so. A mesh counts at its lowest geometry point, so a boot's origin may sit anywhere; an in-place clip with no foot plant reports inPlace: true and clipGroundSpeed: 0, and stride sync stays off. Evaluation is automatic by default: updateRate: "auto" follows measured camera visibility and projected size. updateRate: 1 evaluates every frame; another positive safe integer names that frame interval. updateRateReport reports the effective rate, whether a named override is active, and whether the latest update evaluated. One-shots and fades stay full-rate; root-motion AnimationComposer advances every tick, and auto camera-ray targets and camera-parented rigs stay full-rate. A public mixer "loop" listener promotes the player to full-rate and observes only loop events after registration, so skipped pre-registration cycles are not replayed; updateRateReport reports that effective rate.
class AnimationPlayerUse it to
- play an animation on a character
- switch a character between idle and attack clips
- stop a walking character's feet from sliding or spinning
- match a walk or run cycle to how fast a character is moving
- match an in-place walk cycle with no root motion to the body's speed
- find out what speed an animation clip was authored for
- reduce animation CPU for distant characters
- inspect the effective animation evaluation rate
Example
const player = new AnimationPlayer({ clips, root: rig, strideRoot: body });Good to know
- name the body a game moves as strideRoot when the animated rig is a child of it
- a one-shot clip always plays at its authored rate; the matched rate re-times loops only
- a foot mesh is measured at its lowest geometry point (the sole), never its origin; a skinned mesh is measured through its bones
stride.inPlace: truewithclipGroundSpeed: 0means no foot plant was found and stride sync is not active; the playteststrideobservation carriesinPlace- the matched rate is held inside 0.15x-3x; a speed outside what the clip's own stride supports is clamped, and
stride.ratesays so
Options
- strideSync controls whether the matched rate is applied while stride is still measured
- updateRate: "auto" chooses the camera-based interval; 1 is full evaluation, and another positive safe integer requests that interval; a public
mixer"loop"listener promotes effective evaluation to 1 to preserve event timing
Atmosphere
Own the compute lifetime and expose only parameter-driven atmosphere nodes. The class deliberately creates no mesh, material, or scene light. A template chooses all of those, and the same object remains useful when a game supplies a completely different look.
class Atmosphere extends Group implements IComputeDrivenUse it to
- render a sunrise that changes as time and place change
- add distance haze from the depth of a scene pass
Example
const atmosphere = new Atmosphere({ rayleigh, mie, ozone, planetRadius, atmosphereRadius });
ctx.add(atmosphere);Good to know
- supply rayleigh, mie, ozone, planetRadius, and atmosphereRadius; there is no Earth fallback
- the game creates the sky object, surface, and sun from the returned nodes
Also found by
- green platforms bright saturated sky
AtmosphereLuts
Own the transmittance, multi-scattering, and sky-view compute lookup textures.
class AtmosphereLutsUse it to
- bake the three atmosphere LUTs once before a game shows its world
Example
const luts = new AtmosphereLuts({ rayleigh, mie, ozone, planetRadius, atmosphereRadius });Good to know
- supply all physical parameters; this class creates no scene appearance
attachToBone
Attach a game-owned object to a named skeleton bone.
function attachToBone(root: Object3D, boneName: string, child: Object3D): Object3DUse it to
- put a weapon in a character's hand
- hold a rifle in a character's right hand
- add an enemy that patrols the level, chases the player when it sees them, and holds a rifle in its right hand
- attach an accessory to a skinned model
- equip crew with swords and pistols
- put a sword or pistol in a crew member's hand
Example
import { attachToBone } from "@threenative/core";
attachToBone(character, "RightHand", rifle);Good to know
- when a request is to hold or attach a weapon to a hand, import and call
attachToBonefrom@threenative/core; do not manually parent, position, or rotate the rifle - if a stock visual has no skeleton, add a portable Three.js Bone named
RightHandunder the character, then callattachToBone; do not replace the helper with manual parenting
attitudeAxes
Fly a fixed-wing aircraft with a real force balance instead of a steered velocity.
function attitudeAxes(state: IFlightState): IFlightAxesUse it to
- fly an airplane with lift, drag, stall and control authority
- launch an aircraft off a moving carrier deck
- apply component damage or a loadout to an aircraft's performance
Example
const model = new FlightModel({ airframe: sbd, state: aircraft, wind: seaWind });
model.step(1 / 60, { turn: -1, pitch: 0.4 });Good to know
- every mass, area, power and inertia value comes from the game's airframe
- damage, stores and configuration arrive as the game's own modifier sample
AudioBus
Route effects through a named audio bus.
class AudioBusUse it to
- play a sound effect with a volume bus
- mute or adjust a category of game audio
- keep a gunshot audible at 20 metres by tuning positional falloff
- hold a loud mix below clipping with a compressor on the bus
- play cannon, wave, and ship sound effects
Example
const effects = new AudioBus({ camera });Good to know
- create buses before playing clips and dispose them with the game
- refDistance and rolloffFactor tune positional falloff and apply to playAt only
- compressor takes threshold, knee, ratio, attack and release from the game and takes effect on the bus sum
Replaces new Audio(.
AutoExposureNode
Auto exposure with Unreal 5.8.3's metering: a 64-bin histogram of log2 luminance (the darkest and brightest 10% ignored), key 0.18 x 2, -10 to +20 EV100, 3 stops/s brighter and 1 stop/s darker. AutoExposureNode meters a colour texture and outputs the adapted exposure; exposureSettings holds the defaults.
class AutoExposureNode extends Node<"float">Use it to
- the frame should expose itself the way a fresh Unreal project does as the sun and the view change
- a white snowfield or a bright storm should not meter to middle grey, and the compensation changes with the weather
Example
const slow = { ...exposureSettings, rateDown: 0.5 }; const node = new AutoExposureNode(input, slow, 1);Good to know
- WebGPU renderers only: a renderer without WebGPU keeps the fixed exposure and says so
Options
- every
IExposureSettingsfield, spread overexposureSettingsand passed toAutoExposureNode, replaces the Unreal default setExposureBias(stops)is Unreal's Exposure Compensation, live: the game changes it per place or weather (WorldEnvironment.applyreturns the node asexposure)
baseGeometryOf
The full-detail geometry of a mesh the loader gave an automatic LOD chain. Selection swaps mesh.geometry, so a ray test or a collision body built from the current geometry would change with the camera. Framework picking and gameplay collide against this instead: the authored LOD0, which never changes as the camera moves.
function baseGeometryOf(mesh: Mesh): BufferGeometryUse it to
- collide or ray-test the authored geometry of a mesh whose render detail changes with distance
Example
const geometry = baseGeometryOf(mesh);beginSpan
Attribute the render phase to 100% with a nested span tree, off unless TN_FRAME_SPANS asks. Every non-leaf reports its own time minus the spans inside it, so an unmeasured part shows up as a residual instead of being filed under "other"; a child that outlives its parent reports a negative residual rather than a clamped zero.
function beginSpan(id: SpanId): voidUse it to
- find out what inside the render phase is actually costing the frame
- tell a shadow pass's traversal from the main pass's, with the residual computed
- price an optimisation against a measured part of the phase rather than the whole of it
Example
if (spansRequested()) setSpanRecorder(new SpanRecorder());Good to know
- off by default and installed by
TN_FRAME_SPANS=1; unset, every call site is one guarded return - the tree is closed against the frame budget's own render phase, so
TN_FRAME_SPANSandTN_FRAME_BUDGETdescribe the same frames - measurement only: no span changes what is drawn, in what order, or with which renderer
Billboard3D
Face a game-owned object toward a perspective or orthographic camera.
class Billboard3DUse it to
- keep a world-space marker or nameplate facing the camera
- billboard a tree, label, or effect under a rotated parent
Example
const billboard = new Billboard3D(label, { camera });
billboard.update();Good to know
- call update from the owning scene; no global scene scan is installed
- orthographic cameras use their forward direction, and lockAxis restricts world rotation
BlendSpace1D
Select finite, normalized locomotion weights from sorted thresholds or a fixed triangulation.
class BlendSpace1DUse it to
- calculate 1D walk/run blend weights from speed
- calculate 2D locomotion weights from forward and strafe intent
Example
const blend = new BlendSpace1D([0, 2]); animation.setWeights(blend.sample(speed));Good to know
- duplicate samples, collinear triangles and invalid/incomplete triangulations throw at initialization
- outside 2D queries project to the nearest boundary subedge; output is borrowed scratch
BlendSpace2D
Select finite, normalized locomotion weights from sorted thresholds or a fixed triangulation.
class BlendSpace2DUse it to
- calculate 1D walk/run blend weights from speed
- calculate 2D locomotion weights from forward and strafe intent
Example
const blend = new BlendSpace1D([0, 2]); animation.setWeights(blend.sample(speed));Good to know
- duplicate samples, collinear triangles and invalid/incomplete triangulations throw at initialization
- outside 2D queries project to the nearest boundary subedge; output is borrowed scratch
boneContact
Measure whether a named bone reaches the object it is supposed to be touching, in metres.
function boneContact( root: Object3D, boneName: string, target: Object3D, ): IBoneContactReportUse it to
- check that a seated character's hands reach the keyboard
- check that a character's hips meet the chair it is sitting on
- turn "the character is not touching the prop" into a number a scenario can assert
Example
import { boneContact } from "@threenative/core";
const contact = boneContact(worker, "hand_r", keyboard);Good to know
- this walks the target's vertices; call it on a check or a debug sample, not every frame
boneLengthDeviations
Compare a rig's bone distances now against a captured snapshot and name every bone that moved.
function boneLengthDeviations( root: Object3D, bind: IBoneLengthSnapshot, options: IBoneLengthDeviationsOptions =Use it to
- find out why a skinned character renders deformed
- check that an animated pose keeps the skeleton rigid
- name the bone that breaks a posed skeleton without taking a screenshot
Example
import { boneLengths, boneLengthDeviations } from "@threenative/core";
const report = boneLengthDeviations(character, boneLengths(character));
if (!report.rigid && report.worst !== null) console.log(report.worst.bone, report.worst.ratio);Good to know
- a rigid skeleton preserves every parent→child distance under any pose; a named bone is a defect with an address
- this is a diagnostic — it reports numbers and names; it moves nothing and decides no appearance
boneLengths
Measure a rig's parent→child bone distances, in world space, as it stands right now.
function boneLengths(root: Object3D): IBoneLengthSnapshotUse it to
- capture a rig's bind-pose bone lengths before any clip plays
- measure a skeleton for the bone-length invariance check
Example
import { boneLengths } from "@threenative/core";
const baseline = boneLengths(character);Good to know
- the baseline and the later comparison must come from the same rig under the same ancestor transform, so a uniform scale cancels
BudgetLadder
A cost ladder for one render stage: the whole GPU frame against the frame period moves it, by Unreal's DynamicRenderScaling rule. A frame over the period for 2 frames in a row steps the level down at once, a frame over the period less 10% headroom steps it down after the 8-frame change period, and a frame with room steps it up. A stage steps only when it could absorb the overage at zero cost, and a level that failed is retried after a growing wait. It decides when to move; the game applies the move.
class BudgetLadder<L extends string>Use it to
- step a render stage down when the GPU frame goes over the frame period
- pick a quality level from measured GPU time without oscillating
Example
const ladder = new BudgetLadder({ levels: ["low", "high"], framePeriodMs: 1000 / 60, start: "high" }); const window = ladder.observe(stageMs, frameMs);Good to know
- levels are listed cheapest first, and the frame period is the game's own display target
- a frame without a resolved GPU reading never moves the level
Options
- explicit: true keeps the level and only reports a frame over the target
bvhIntersectFirstHit
Pack a selected static scene into TSL storage nodes for an upstream BVH ray query.
bvhIntersectFirstHit = upstream.bvhIntersectFirstHitUse it to
- trace thousands of scene rays inside a TSL kernel
- build a contact-occlusion or visibility query over loaded meshes
Example
const bvh = ctx.add(new GPUSceneBVH(ctx.scene, { include: (object) => object.userData.traceable === true }));Good to know
- call rebuild() after a scene transform or geometry change; the snapshot is static by default
- rebuild() is an explicit CPU SAH build proportional to selected triangles; process() is a no-op, and the game pays upstream traversal per shader ray
CameraShake
Produce a game-authored camera shake offset for a template-owned camera rig.
class CameraShakeUse it to
- add a hit, explosion, or landing shake to a camera
- compose a transient camera offset after camera damping
Example
const shake = new CameraShake({ amplitude, rotationAmplitude, frequency, decay, curve });Good to know
- amplitude, rotationAmplitude, frequency, decay, and curve are required game choices
- update returns an offset and never writes to a camera
CanvasLayer
Manage a camera or screen-facing canvas layer.
class CanvasLayerUse it to
- place a HUD layer above the Three.js scene
- attach a canvas layer to a camera
Example
const hud = new CanvasLayer(ctx.viewport);captureMouse
Lock the pointer to the game's surface: the capture every first-person mouse look needs. A browser grants capture only from a user gesture, so call it from a click or a pointerdown handler. A relative binding such as look: { pointerRelative: true } already requests capture on the first canvas click; this is the same request for a game that starts capture from another named gesture, and ctx.input.captureMouse() is the map's own way to ask.
function captureMouse(target: EventTarget): Promise<void> | undefinedUse it to
- lock the mouse pointer so first-person mouse look keeps the cursor out of the way
- stop the cursor leaving the window in the middle of a turn
Example
canvas.addEventListener("click", () => captureMouse(canvas));Good to know
- the browser grants capture only from a user gesture and a refusal is reported, never swallowed
- a relative binding requests capture on canvas click unless
captureOnClick: falseopts out
clipBoneCoverage
Report which bones of a character a clip does not drive.
function clipBoneCoverage(root: Object3D, clip: AnimationClip): IClipCoverageReportUse it to
- find out why a character keeps the previous animation's hand shape
- check how much of a rig a clip covers before shipping it
Example
import { clipBoneCoverage } from "@threenative/core";
const coverage = clipBoneCoverage(character, clip);Good to know
- a track that binds nothing counts as driving nothing
clipPoseError
Score a retargeted clip against the source it came from, per bone, in degrees.
function clipPoseError( subject: IClipPoseSubject, reference: IClipPoseSubject, options: IClipPoseErrorOptions =Use it to
- find out why a retargeted animation looks wrong on a character
- tell a fixed retarget from one that merely moved
- catch a retarget that rolled every limb about its own axis
Example
import { clipPoseError } from "@threenative/core";
const report = clipPoseError({ root: rig, clip: retargeted }, { root: source, clip: original });Good to know
- each bone is compared as a whole quaternion relative to its own rig's bind pose, so the two rigs never have to share a bind convention; a bone-direction check reports zero on the roll this catches
- both rigs must face the same way in world space, and both are driven and then restored to the transforms they arrived with
Options
- bones maps one rig's bone names onto the other's when they differ; samples sets how many poses are compared
clipTrackBindings
Report which of a clip's tracks bind to nothing on a character.
function clipTrackBindings(root: Object3D, clip: AnimationClip): IClipBindingReportUse it to
- find out why a character plays its bind pose instead of the animation
- check that a loaded clip actually drives the model it was written for
Example
import { clipTrackBindings } from "@threenative/core";
const bindings = clipTrackBindings(character, clip);Good to know
- the reason is Three.js's own, captured off its console hook so a scenario's console assertions stay clean
ClusteredBatch
Draw many copies of one over-detailed body, each at the detail its own distance earns. InstancedBatch collapses repeated props into one draw and gives every copy the same triangles. This gives a copy two hundred metres away a coarser cut than one twelve metres away, and still submits one draw per distance group rather than one per copy — which is what makes four hundred scanned boulders affordable. The shape, the surface and every transform stay the game's.
class ClusteredBatchUse it to
- draw hundreds of copies of a scanned or sculpted body without hundreds of draw calls
- stop distant copies of a dense prop from costing their full triangle count
Example
const boulders = new ClusteredBatch({ geometry, material, table });
boulders.place({ position: [x, y, z], rotation: [0, angle, 0] });
boulders.build({ name: "boulders", parent: ctx.scene });
// in the scene's update, before the render:
boulders.update(ctx.camera, ctx.renderer.domElement.height);Good to know
- the body's geometry must carry a cluster table from
assets.models.virtual - every copy is placed before build(); place() after build() throws
Options
- distanceRatio sets how wide one distance group is, default 1.25
- errorPixels sets the screen-space error budget, default 1 pixel
ClusteredMesh
Draw a model too detailed for the screen to resolve, without submitting the part it cannot. This is on, and a game does not call it. Any primitive of 65,536 triangles or more bakes to a cluster DAG in the asset pipeline, the loader returns a ClusteredMesh for it, and the engine takes the cut every frame before it renders. Each frame the mesh submits one draw holding only the clusters whose error projects to fewer than errorPixels screen pixels; a mesh nothing has cut yet draws in full, so the worst case is an ordinary Mesh. Geometry, surface and every appearance parameter stay the game's.
class ClusteredMesh extends MeshUse it to
- draw a model too detailed for the screen to resolve
- import a scanned or sculpted mesh of millions of triangles and still hold the frame
- stop a dense rock face or terrain body from costing its full triangle count up close
Example
// Nothing to call: the loader returns one of these and the engine cuts it every frame.
const face = await ctx.assets.model("quarry-face.glb");
ctx.scene.add(face.scene);Good to know
- the bake happens in the asset pipeline, never at run time — there is no runtime flag
- the payload costs about 3-4x a baked primitive's bytes;
assets.models.virtual: "none"opts out andminSourceTrianglesmoves the 65,536 line - needs a perspective camera; a screen-space error has no meaning without one
- one shadow cut is chosen at load and does not follow a shadow camera
Options
- errorPixels sets the screen-space error budget, default 1 pixel
- recutDistance sets how far the camera moves before the cut is retaken, default a thousandth of the mesh's radius
ComputeDrivenRegistry
Register game-owned IComputeDriven objects with the shared compute lifetime.
class ComputeDrivenRegistryUse it to
- use IComputeDriven for a cloth, fluid, boid, or other GPU simulation
- run a cloth or fluid simulation with ordered GPU passes
- keep IComputeDriven kernels warm before the first visible frame
Example
const registry = new ComputeDrivenRegistry(); registry.add(cloth, ctx.renderer.raw);Good to know
- add the object through ctx.add so it attaches, dispatches, and releases with its scene
counterDeviceOf
Count the frame's host-boundary crossings and the bytes it writes into GPU buffers, off unless TN_FRAME_SPANS asks for them. On the frame budget's own window as counters, so a crossing count and a millisecond split describe the same frames.
function counterDeviceOf(raw: unknown): unknownUse it to
- decide whether a CPU-bound frame is paying for the V8-to-host boundary
- measure how many bytes a frame writes into GPU buffers, and how many commands it issues
Example
const counters = FrameCounters.install(counterDeviceOf(renderer.raw));Good to know
- counts command-encoder and queue methods only;
mapAsyncand the presentation path are named, not folded in gpuBytesisqueue.writeBufferexactly, so it reconciles against a driver; texture uploads are not includedjsAllocBytesneedsperformance.memoryand stays absent where the platform lacks it
createAssetLoader
Create the portable asset loader a scene also receives as ctx.assets.
function createAssetLoader(options: IAssetLoaderOptions =Use it to
- preload models, textures, or audio before a scene enters
- keep downloaded web assets on disk between visits
- download the next scene before the player gets there
- free the disk cache from a settings menu
- prefetch assets into the Cache Storage disk cache of a large web game
- load assets from a nonstandard base path or a compiled asset manifest
- stream a large game: boot on the spawn bytes and prefetch the rest
- make the first scene play before the whole game finishes downloading
- draw a heavy model's coarsest level first and its full detail when the file lands
- draw a model's textures at their resident mips first and the whole files later
- coarse first model streaming
- streamMeshes and streamTextures: stream the meshes and textures of a model
- mip streaming textures
- TN_STREAMING_POOL
- TN_ASSET_LATE
- an asset pops in after the reveal and the game needs to count it
- a model texture looks blurry or low resolution right after load, then sharpens
- build a collider or navmesh from a streamed model only once its full file landed
- compressed texture upload on the owned engine (KTX2 to BC7 or ETC2 on the GPU)
- load a model with KHR_texture_basisu or EXT_meshopt_compression on the owned engine
- stream a finer mip level into a CompressedTexture that already draws
- KTX2Loader on the owned engine
- CompressedTexture upload
- TN_TEXTURE_TRANSCODE_TARGET
- TN_NATIVE_TEXTURE_UNSUPPORTED
- webRuntimeDecoders meshopt ktx2
Example
const assets = createAssetLoader({ basePath: "/assets" });
const rock = await assets.texture("rock.png");Good to know
- reuse the loader handed to scenes as
ctx.assetsinstead of building parallel caches - await everything the spawn camera sees before the reveal;
ctx.assets.prefetchand the background fill are for content out of view, or the player spawns into a half-built world - a whole-file load requested after the reveal that the game had not
prefetched logs oneTN_ASSET_LATEline with its bytes, so a pop-in is countable from a playtest - web only: a native host reads installed files, so
ctx.assets.cachereportsenabled: falsewith the reason andprefetchresolves at once - streaming is engine-owned and on by default: a cooked LOD-chained model loads its
.coarse.<digest>.glbcompanion first, then the full file at "soon" priority, and the full geometry replaces the coarse in place (clones and the projection mirror included); a failed coarse load falls back to the whole file and logsTN_ASSETS_STREAM_FAILED - texture streaming rides on the coarse parse: each shared
.ktx2of that model is read byRangeas its resident mips (the header and the tail), and the whole files replace them when the full model lands; a host withoutRangesends the whole file and keeps it whole.TN_STREAMING_POOLreportsfiles,residentBytes,fullBytes,deferredBytesandupgradedonce, two seconds after the last change - the whole texture keeps what the game set on the resident one (
anisotropy, wrap, filters, offset, repeat,userData), so the swap changes the mips and nothing else - every web build cooks meshopt geometry and KTX2 textures for both engines (
webRuntimeDecodersin create-threenative answers{ ktx2: true, meshopt: true }); the owned engine's glTF loader decodes both itself, with no JS decoder - the owned engine transcodes a KTX2 image to BC7 on a device with
texture-compression-bc, else ETC2, else RGBA8 with an engine mip chain, and printsTN_TEXTURE_TRANSCODE_TARGET <target>once; a block format needs a width and height that are multiples of 4, so any other size stays RGBA8 and the same line names it - a three
CompressedTexture(format plusmipmaps) uploads one GPU write per level; a block format the device lacks throwsTN_NATIVE_TEXTURE_UNSUPPORTEDby name instead of drawing garbage - levels are coarse-first: a level whose
mipmaps[i].datais null is not resident and the texture samples its finest resident level; setmipmaps[i].dataandneedsUpdate = trueto write that one finer level in place, without re-creating the texture or rewriting the other levels
Options
assets.cache: falseturns the disk cache off andassets.backgroundFill: falseturns the post-reveal fill off; both are reported onctx.assets.cachectx.assets.model(path, { whole: true })resolves only once the full file has replaced the coarse companion, for a collider or navmesh that copies vertices onceassets.streamMeshes: falseloads every model whole (reported once asTN_ASSETS_STREAM_MESHES_OFF);assets.streamTextures: falseloads every model texture whole (TN_ASSETS_STREAM_TEXTURES_OFF)engine: "threejs"runs three's ownKTX2LoaderandMeshoptDecoderin JS instead of the owned engine's decoders
Also found by
- different area props
- first playable screen external assets
createPipelineCensus
Read the renderer's bounded, versioned pipeline capture in a diagnostic or playtest tool.
function createPipelineCensus(options: IPipelineCensusOptions): PipelineCensusUse it to
- inspect shader and pipeline creation work during a real launch
- correlate pipeline creation with material, object, pass, and shader identities
Example
const capture = game.runtime.pipelineCensus?.();
// The game normally reaches this through `runtime.pipelineCensus`; direct construction exists
// for renderer adapters and contract tests, not for gameplay.Good to know
- the capture is bounded and incomplete when the backend cannot expose an observation
createRandom
Create a deterministic random source for portable gameplay.
function createRandom(seed?: number): IRandomUse it to
- get a seeded deterministic random number generator — the same mulberry32 a game would hand-roll
- seed enemy patrol choices
- reproduce the same procedural level in a playtest
Example
const random = createRandom(42);Good to know
- use the returned source instead of Math.random for replayable behavior
Replaces Math.random(.
createReplayDriver
Record or replay deterministic game input and state.
function createReplayDriver( recording: Recording, target: EventTarget, pointerTarget = target, )Use it to
- reproduce a gameplay bug from recorded input
- run a deterministic replay in a playtest
Example
const driver = createReplayDriver(recording, ctx.renderer.domElement);Good to know
- use a seeded random source and fixed-step simulation for meaningful replays
Also found by
- fixed seed fixed-step simulation
Daylight
An outdoor daylight rig: physical sky, one sun with open-world shadows that follow the eye, hemisphere fill, sky-coloured haze and the AgX tone curve. Every value is the game's.
class Daylight extends Group implements IComputeDrivenUse it to
- daytime sky, sun and shadows for a large outdoor map
- distant terrain should fade into the sky instead of a coloured wall
- match a Blender look-dev scene's sun, sky and exposure in the game
Example
const daylight = new Daylight({ follow: ctx.camera, sunDirection, sunColor, sunIntensity: 4, shadowExtents: [24, 96, 320], sky: { turbidity: 3, rayleigh: 1.4, mieCoefficient: 0.004, mieDirectionalG: 0.8 }, fill: { sky, ground, intensity: 1.1 }, haze: { color: horizon, density: 0.0011 }, exposure: 2 ** -0.6, skySize: 1600 });
ctx.add(daylight);Good to know
- every value is required; there is no default sun, sky, haze or exposure
skySizemust keep the sky box's corners inside the camera's far plane- shadowExtents follow
VirtualShadowNode: half-widths, finest first, strictly increasing
Options
- sky uniforms stay live on
daylight.sky; the light and fill aredaylight.sunanddaylight.fill
debugFlag
Read a debug switch from the URL, or from TN_DEBUG_* in the environment on a native launch.
function debugFlag(name: string): booleanUse it to
- read a debug toggle from the URL, an environment variable or a harness global
Example
import { debugFlag } from "@threenative/core";
if (debugFlag("freeCam")) camera.flyMode = true;Good to know
- a name in camelCase becomes UPPER_SNAKE:
debugFlag("freeCam")reads?freeCamorTN_DEBUG_FREE_CAM 0andfalseare off, so a saved URL cannot turn a switch back on
debugValue
Read the text a debug switch was given by the launch, on the same rule as debugFlag.
function debugValue(name: string): string | undefinedUse it to
- read a debug override whose value is not a boolean
- override a quality tier or a mode for one run without changing the code
Example
import { debugValue } from "@threenative/core";
const tier = debugValue("quality");Good to know
- the same name rule as
debugFlag:?quality=on the web,TN_DEBUG_QUALITYon a native launch - a name in camelCase becomes UPPER_SNAKE:
debugValue("quality")reads?quality=orTN_DEBUG_QUALITY
defineGame
Define the portable game entry shared by web and native.
function defineGame<TState extends Record<string, unknown>, TPhysics = undefined>( config: IGameConfig<TState, TPhysics>, ): IGame<TState, TPhysics>Use it to
- start a ThreeNative game from src/game.ts
- register physics and gameplay plugins
- let the player zoom the camera with a wheel, pinch, or gamepad axis
- frame a camera behind the player
Example
const game = defineGame({ input: { zoom: { scroll: true, pinch: true } }, scenes: { Play }, start: "Play" });Good to know
- keep DOM and React mounting in src/main.ts
- bind scroll or pinch and read the intent with ctx.input.axis(name); do not add a window wheel listener
- scroll: true uses the DOM wheel sign on browser and native: negative deltaY toward the user is positive intent
Also found by
- nearest target crosshair spawns
- third-person camera
- restart run without page reload
- field of view while aiming
describeSceneShape
Warn the agent that built the scene before a human plays it: a frame whose GPU is idle while its JS render phase is longer than the display's own period is a scene-shape problem, and the engine already has the shape. On by default in a debug launch, printed at most once per reported window as TN_SCENE_WARNING, and silent on a scene that is honestly GPU-bound.
function describeSceneShape( window: IFrameBudgetWindow, cull: IRenderCameraCullReport | undefined, ): ISceneShape | undefinedUse it to
- find out whether a slow frame is the scene's shape or the device
- tell an authoring agent what to reduce before it promises a merge
Example
defineGame({ display: { maxFps: 60 }, scenes: { Play } });Good to know
- the rule is derived from the frame's own numbers; the display period comes from the host's presentation cap or the game's declared target, never a constant
- no verdict without a measured GPU reading and a pass census — an absent measurement is not evidence
- the record carries objects considered, draws per pass, triangles per draw and shadow-exempt casters, so the reader is not dependent on the ranking
describeSceneWarning
Warn the agent that built the scene before a human plays it: a frame whose GPU is idle while its JS render phase is longer than the display's own period is a scene-shape problem, and the engine already has the shape. On by default in a debug launch, printed at most once per reported window as TN_SCENE_WARNING, and silent on a scene that is honestly GPU-bound.
function describeSceneWarning(warning: ISceneWarning): stringUse it to
- find out whether a slow frame is the scene's shape or the device
- tell an authoring agent what to reduce before it promises a merge
Example
defineGame({ display: { maxFps: 60 }, scenes: { Play } });Good to know
- the rule is derived from the frame's own numbers; the display period comes from the host's presentation cap or the game's declared target, never a constant
- no verdict without a measured GPU reading and a pass census — an absent measurement is not evidence
- the record carries objects considered, draws per pass, triangles per draw and shadow-exempt casters, so the reader is not dependent on the ranking
devGlobal
The one name every dev surface publishes under, and the reader/writer for it.
function devGlobal(scope: unknown): DevGlobal | undefinedUse it to
- read or extend the
__THREENATIVE__object a dev launch publishes
Example
import { DEV_GLOBAL_KEY, devGlobal } from "@threenative/core";
const tools = devGlobal(globalThis);Good to know
- every dev surface publishes under this key; the worker's typed mirror tuple names it too
directionalTransmittance
Approximate direct transmittance for a ray leaving the game surface.
function directionalTransmittance( parameters: IAtmosphereParameters | IResolvedAtmosphereParameters, direction: Vector3, ): Vector3Use it to
- colour a game-owned sun from atmosphere extinction
Example
const transmittance = directionalTransmittance(parameters, sunDirection);Good to know
- pass a non-zero direction; coefficients and radii come from the game
directionFromSolarPosition
Convert solar elevation and azimuth degrees into a normalized Three.js direction.
function directionFromSolarPosition(elevation: number, azimuth: number): Vector3Use it to
- aim a template's sun from solarPosition output
Example
const direction = directionFromSolarPosition(sun.elevation, sun.azimuth);Good to know
- elevation and azimuth must be finite degrees
displayPeriodMs
Warn the agent that built the scene before a human plays it: a frame whose GPU is idle while its JS render phase is longer than the display's own period is a scene-shape problem, and the engine already has the shape. On by default in a debug launch, printed at most once per reported window as TN_SCENE_WARNING, and silent on a scene that is honestly GPU-bound.
function displayPeriodMs( declaredTargetFps: number | undefined, ):Use it to
- find out whether a slow frame is the scene's shape or the device
- tell an authoring agent what to reduce before it promises a merge
Example
defineGame({ display: { maxFps: 60 }, scenes: { Play } });Good to know
- the rule is derived from the frame's own numbers; the display period comes from the host's presentation cap or the game's declared target, never a constant
- no verdict without a measured GPU reading and a pass census — an absent measurement is not evidence
- the record carries objects considered, draws per pass, triangles per draw and shadow-exempt casters, so the reader is not dependent on the ranking
endSpan
Attribute the render phase to 100% with a nested span tree, off unless TN_FRAME_SPANS asks. Every non-leaf reports its own time minus the spans inside it, so an unmeasured part shows up as a residual instead of being filed under "other"; a child that outlives its parent reports a negative residual rather than a clamped zero.
function endSpan(id: SpanId): voidUse it to
- find out what inside the render phase is actually costing the frame
- tell a shadow pass's traversal from the main pass's, with the residual computed
- price an optimisation against a measured part of the phase rather than the whole of it
Example
if (spansRequested()) setSpanRecorder(new SpanRecorder());Good to know
- off by default and installed by
TN_FRAME_SPANS=1; unset, every call site is one guarded return - the tree is closed against the frame budget's own render phase, so
TN_FRAME_SPANSandTN_FRAME_BUDGETdescribe the same frames - measurement only: no span changes what is drawn, in what order, or with which renderer
ensureVelocityOutput
Provision screen-space motion data for temporal nodes and keep per-instance history at the frame boundary.
function ensureVelocityOutput(pass: IVelocityRenderPass): MRTNodeUse it to
- keep a skinned character or instanced crowd stable in a temporal stage
- add the velocity output to a Three.js scene pass
- add a velocity target before a temporal stage consumes a scene pass
Example
const scenePass = pass(scene, camera);
ensureVelocityOutput(scenePass);
renderer.setOutputNode(scenePass);
const tracker = new VelocityTracker();
tracker.update(scene);
renderer.render(scene, camera);
tracker.commit(scene);Good to know
- call
VelocityTracker.update()before the render andcommit()after it - a pass is only given a velocity target when a temporal stage consumes it
- call only when a temporal stage is active
ev100FromCamera
Photometric exposure units: EV100 to the renderer multiplier and back, a physical camera's EV100, and a meter reading. Conversion only; the exposure and the light values are the game's.
function ev100FromCamera(aperture: number, shutterSeconds: number, iso: number): numberUse it to
- expose a frame lit in lux and nits with a physical camera exposure value
- expose like a camera with an aperture, a shutter time and an ISO
Example
renderer.toneMappingExposure = exposureFromEv100(ev100FromCamera(4, 1 / 60, 100));Good to know
- arguments must be finite; multipliers, apertures, shutter times, ISO and luminance must be > 0
- every argument must be finite and greater than zero
ev100FromExposure
Photometric exposure units: EV100 to the renderer multiplier and back, a physical camera's EV100, and a meter reading. Conversion only; the exposure and the light values are the game's.
function ev100FromExposure(multiplier: number): numberUse it to
- expose a frame lit in lux and nits with a physical camera exposure value
- report a hand-set exposure multiplier as an EV100
Example
renderer.toneMappingExposure = exposureFromEv100(ev100FromCamera(4, 1 / 60, 100));Good to know
- arguments must be finite; multipliers, apertures, shutter times, ISO and luminance must be > 0
- multiplier must be finite and greater than zero
ev100FromLuminance
Photometric exposure units: EV100 to the renderer multiplier and back, a physical camera's EV100, and a meter reading. Conversion only; the exposure and the light values are the game's.
function ev100FromLuminance(luminance: number): numberUse it to
- expose a frame lit in lux and nits with a physical camera exposure value
- meter a frame's average luminance in cd/m² into an exposure value
Example
renderer.toneMappingExposure = exposureFromEv100(ev100FromCamera(4, 1 / 60, 100));Good to know
- arguments must be finite; multipliers, apertures, shutter times, ISO and luminance must be > 0
- luminance must be finite and greater than zero
exposeDebug
Publish one game object under __THREENATIVE__.debug for a capture script or the console.
function exposeDebug(name: string, value: unknown): voidUse it to
- expose a game object to a capture script or the console in dev builds
Example
import { exposeDebug } from "@threenative/core";
exposeDebug("player", player);
// then from the console: __THREENATIVE__.debug.playerGood to know
- development builds only; a production build publishes nothing
exposureFromEv100
Photometric exposure units: EV100 to the renderer multiplier and back, a physical camera's EV100, and a meter reading. Conversion only; the exposure and the light values are the game's.
function exposureFromEv100(ev100: number): numberUse it to
- expose a frame lit in lux and nits with a physical camera exposure value
Example
renderer.toneMappingExposure = exposureFromEv100(ev100FromCamera(4, 1 / 60, 100));Good to know
- arguments must be finite; multipliers, apertures, shutter times, ISO and luminance must be > 0
- ev100 must be finite; a unitless scene keeps its own multiplier instead
fetchAsset
Fetch a data file the asset loader serves: each url assets.resolve(path) names, in order, until one answers ok. A built game serves the hashed output and a dev server the source path, so taking only the first url 404s on one of them. When none answers it throws TN_ASSET_NOT_SERVED naming every url tried and why, so a missing file is never a half-drawn world.
async function fetchAsset( assets: Pick<IAssetLoader, "resolve">, path: string, ): Promise<Response>Use it to
- load a baked JSON or binary file (a heightmap, a placement buffer, a data table) that the loader has no typed method for
- a data file loads in dev but 404s in the built game
Example
const heights = new Float32Array(await (await fetchAsset(ctx.assets, "world/forest.bin")).arrayBuffer());Good to know
- reads the response once; call
.json()or.arrayBuffer()on the result
FlightModel
Fly a fixed-wing aircraft with a real force balance instead of a steered velocity.
class FlightModel<TState extends IFlightState = IFlightState>Use it to
- fly an airplane with lift, drag, stall and control authority
- launch an aircraft off a moving carrier deck
- apply component damage or a loadout to an aircraft's performance
Example
const model = new FlightModel({ airframe: sbd, state: aircraft, wind: seaWind });
model.step(1 / 60, { turn: -1, pitch: 0.4 });Good to know
- every mass, area, power and inertia value comes from the game's airframe
- damage, stores and configuration arrive as the game's own modifier sample
FluidField2D
Simulate a deterministic 2D velocity-and-dye field on the GPU while exposing its data to game-owned rendering.
class FluidField2D extends GroupUse it to
- simulate smoke, fire, fog, wind, or fluid response on a grid
- inject a touch, pointer, or gameplay impulse into a fluid field
- sample fluid dye or velocity in a game-owned render node
- simulate ocean currents and wind affecting a sailing ship
- simulate ocean fluid dynamics and currents that affect a ship
Example
const field = new FluidField2D({ resolution: 256, pressureIterations: 20 });
ctx.add(field);
field.splat({ x: 0.5, y: 0.5 }, { x: 0.2, y: 0 }, 1);Good to know
- add the field through
ctx.addso renderer attachment, fixed-step dispatch, and release are automatic dyeandvelocityare numeric samplers; appearance stays in the game'ssrc/render/code- the conformance sample measures mean absolute velocity divergence at 0.001732 after four 32² steps with pressureIterations 2, below the 0.0025 threshold
Options
- pressureIterations, viscosity, vorticity, and splatRadius tune the solver without changing its pass order
FluidParticles3D
Simulate liquid as GPU particles (pour, splash, dam break, waterfall) and expose positions, a density volume and a surface height while the game owns every look.
class FluidParticles3D extends GroupUse it to
- pour, splash, or dam-break water that fills a container and flows around obstacles
- simulate water or another liquid as particles in a fluid simulation
- drop a ball or box into liquid and let it displace and float on the water
- emit a stream or waterfall of particle fluid and drain it somewhere else
- sample particle-fluid density or surface height in a game-owned render node
Example
const water = new FluidParticles3D({ capacity: 6000 });
ctx.add(water);
water.fill([-2.8, 0.1, -1.5], [-0.6, 3, 1.5]);Good to know
- add the fluid through
ctx.addso renderer attachment, fixed-step dispatch, and release are automatic - a renderer without WebGPU compute throws a named error at attach; it never draws nothing
emitrecycles the oldest slot oncecapacityslots have been used;fillstops at capacitysampleandstatsread a throttled GPU copy and reportstaleFrames; they are never live
Options
- iterations, viscosity, cohesion, vorticity, gravity and maxSpeed tune the solver without changing its pass order
formatSceneWarning
Warn the agent that built the scene before a human plays it: a frame whose GPU is idle while its JS render phase is longer than the display's own period is a scene-shape problem, and the engine already has the shape. On by default in a debug launch, printed at most once per reported window as TN_SCENE_WARNING, and silent on a scene that is honestly GPU-bound.
function formatSceneWarning(warning: ISceneWarning): stringUse it to
- find out whether a slow frame is the scene's shape or the device
- tell an authoring agent what to reduce before it promises a merge
Example
defineGame({ display: { maxFps: 60 }, scenes: { Play } });Good to know
- the rule is derived from the frame's own numbers; the display period comes from the host's presentation cap or the game's declared target, never a constant
- no verdict without a measured GPU reading and a pass census — an absent measurement is not evidence
- the record carries objects considered, draws per pass, triangles per draw and shadow-exempt casters, so the reader is not dependent on the ranking
formatSpansWindow
Attribute the render phase to 100% with a nested span tree, off unless TN_FRAME_SPANS asks. Every non-leaf reports its own time minus the spans inside it, so an unmeasured part shows up as a residual instead of being filed under "other"; a child that outlives its parent reports a negative residual rather than a clamped zero.
function formatSpansWindow(window: ISpanWindow): stringUse it to
- find out what inside the render phase is actually costing the frame
- tell a shadow pass's traversal from the main pass's, with the residual computed
- price an optimisation against a measured part of the phase rather than the whole of it
Example
if (spansRequested()) setSpanRecorder(new SpanRecorder());Good to know
- off by default and installed by
TN_FRAME_SPANS=1; unset, every call site is one guarded return - the tree is closed against the frame budget's own render phase, so
TN_FRAME_SPANSandTN_FRAME_BUDGETdescribe the same frames - measurement only: no span changes what is drawn, in what order, or with which renderer
formatUnlitFoliageWarning
Tell the agent that built the scene that its imported foliage is drawing with no image-based light: an alpha-cutout MeshStandardMaterial (or its Node twin) with scene.environment unset and no envMap of its own gets a hemisphere fill and one flat dark value, which is cardboard. Printed once per scene entry as TN_UNLIT_FOLIAGE, after enter(), with the fix in the same line.
function formatUnlitFoliageWarning(warning: IUnlitFoliageWarning): stringUse it to
- catch the "why does my forest look like cardboard" question before a human plays it
- audit a scene a game built from imported GLB foliage
Example
defineGame({ scenes: { Forest } }); // one TN_UNLIT_FOLIAGE line when the forest has no skyGood to know
- derived from the scene graph, not from a constant: cutout PBR with no environment in the scene and none on the material
- it changes nothing and never throws — the environment is appearance, so setting it stays the game's decision
Options
material.userData.tnUnlitOk = trueon a material a game deliberately renders unlit (the sameuserData.tn*naming the alpha and impostor conventions use)
formatValidationReport
Prove that nothing a cache skipped changed the picture: TN_RENDERLIST_VALIDATE=1 recomputes every world matrix the long way, every frame, and throws on the first element that disagrees with what the frame is about to draw.
function formatValidationReport(report: IValidationReport): stringUse it to
- prove a static freeze did not leave a stale transform on screen
- gate a scene in CI against silent transform divergence
Example
if (renderListValidationRequested()) console.log(formatValidationReport(report));Good to know
- off by default and expensive by construction — it does the work it is checking, twice
- it throws on the first divergence rather than logging; a validation mode that continues is one nobody reads
- it proves the frames it ran on and nothing else
FrameBudget
Read where the frame's milliseconds went, per presented frame, on any platform; each TN_FRAME_BUDGET window also carries the GPU time per resolved frame and the draw calls and triangles each render pass submitted.
class FrameBudgetUse it to
- show an on-screen frame time meter with p50, p95 and p99 percentiles
- find out why a game runs slowly on a phone
- attribute a frame to present wait, simulation, three.js render, or overlay
- tell whether the GPU is the frame's constraint from a per-frame series, not one lagged timestamp
- split a frame's draw calls and triangles per render pass (main, shadow, reflection)
- tell a shadow or reflection pass's cost from the main colour pass
- retain every asynchronous GPU render frame for a complete paired benchmark
Example
defineGame({ frameBudget: { reportEvery: 120 }, scenes: { Play } });Good to know
- on by default and printed as TN_FRAME_BUDGET; defineGame({ frameBudget: false }) silences the marker, not the measurement
- per-pass numbers are attributed to the innermost active render call, so nested shadow and reflection passes do not read as main
- GPU is a mean/p50/p95/max series over resolved frames (
gpu) withgpuStalecounting frames that had no fresh reading; absent means no timestamps, never zero ctx.renderer.observeGpuFrames({ maxFrames, maxQueries })is opt-in, bounded and fail-closed;take()delivers immutable complete render-query groups once, whilestatus()reports pending/undrained/queued membership and losses- observation preserves ordinary sampling; a complete benchmark explicitly requests
renderer.gpuTimestampFrameInterval: 1and joins Three query IDs to actual world renders, including separate overlay IDs stop()fences allocated frames and drains existing resolver work;dispose()invalidates late completions, and a failed observation must be disposed before replacement
FrameCounters
Count the frame's host-boundary crossings and the bytes it writes into GPU buffers, off unless TN_FRAME_SPANS asks for them. On the frame budget's own window as counters, so a crossing count and a millisecond split describe the same frames.
class FrameCountersUse it to
- decide whether a CPU-bound frame is paying for the V8-to-host boundary
- measure how many bytes a frame writes into GPU buffers, and how many commands it issues
Example
const counters = FrameCounters.install(counterDeviceOf(renderer.raw));Good to know
- counts command-encoder and queue methods only;
mapAsyncand the presentation path are named, not folded in gpuBytesisqueue.writeBufferexactly, so it reconciles against a driver; texture uploads are not includedjsAllocBytesneedsperformance.memoryand stays absent where the platform lacks it
gearClearance
Fly a fixed-wing aircraft with a real force balance instead of a steered velocity.
function gearClearance(state: IFlightState): numberUse it to
- fly an airplane with lift, drag, stall and control authority
- launch an aircraft off a moving carrier deck
- apply component damage or a loadout to an aircraft's performance
Example
const model = new FlightModel({ airframe: sbd, state: aircraft, wind: seaWind });
model.step(1 / 60, { turn: -1, pitch: 0.4 });Good to know
- every mass, area, power and inertia value comes from the game's airframe
- damage, stores and configuration arrive as the game's own modifier sample
getPlatform
Read the host platform without reaching for browser globals.
function getPlatform(): Readonly<IPlatformInfo>Use it to
- branch a portable game on web or native
- choose touch controls for a mobile device
- can I raytrace on native
- show gamepad prompts and bind pad buttons on a games console such as the PS4
Example
if (isMobile()) showTouchControls();
if (isConsole()) showPadPrompts(isPs4() ? "dualshock" : "generic");Good to know
- only use the returned platform facts; native globals are host-owned
- image ray tracing is unavailable on native until buffer-to-texture copy-out interop exists;
mystralRT.traceRaysrefuses instead of resolving success without a readable result - a native desktop host with ray tracing hardware traces ray batches with
mystralRT.traceRayBatch, which writes hit records into a typed array you own; readmystralRT.capabilities().rayBatchfirst, and keep the software BVH trace for the web and every other host - when
mystralRT.capabilities().sharedTransportis true,mystralRT.traceRayBatchGpu({ tlas, rays, hits, rayCount })traces between two GPUBuffers with no copy through CPU memory;raysneeds the CopySrc usage andhitsthe CopyDst usage, and each call costs CPU time, so measure it against the software trace for your batch size
GIBudget
Reports what a game's global illumination costs against the frame period: the GI share of the GPU frame and whether the frame fits its period less 10% headroom. The method (none, irradianceField, screenProbeGather) holds its level while the game runs, as Unreal's Lumen does: a frame over its period gets cheaper through the primary resolution scale, and the GI pass follows the lower resolution. The budget is the frame period, never a GI time in milliseconds, because a stage reading moves with the GPU clock.
class GIBudgetUse it to
- global illumination costs too much on a weak GPU
- see what share of the GPU frame the bounce light takes
- quality tier for indirect lighting that follows the hardware
Example
const gi = new GIBudget({ method: "screenProbeGather", stages: ["SSGI"], framePeriodMs: 1000 / 60 });
ctx.beforeRender(() => gi.observeRenderer(ctx.renderer.raw));Good to know
- the method never changes while the game runs: the primary resolution scale is the run-time lever
- the GPU time of a pass is read by the scene name three or the game gave it, so name every GI pass in
stages - timestamp queries are needed: without them every window is unobserved
Also found by
- lumen scalability
- sg.GlobalIlluminationQuality
- final gather method
GIVisualize
Shows the indirect diffuse light of a frame by itself, the counterpart of Unreal's Lumen Visualize IndirectDiffuse mode, so a lighting gap against a reference can be told apart from a scene gap. The game's chain builds the term; this class selects it and fails when the term is missing.
class GIVisualizeUse it to
- see only the bounce light of a frame
- compare indirect lighting alone against Unreal
- debug global illumination by looking at the indirect diffuse term
Example
const view = new GIVisualize({ mode: "indirectDiffuse", beauty: frame, indirectDiffuse: albedo.mul(bounce) });
pipeline.outputNode = view.node;Good to know
- the game's render chain builds the indirectDiffuse node (gathered and cached light times albedo); this class draws nothing else
- a mode whose term the chain did not build throws instead of showing the finished frame
Options
- mode: "off" returns the finished frame unchanged
Also found by
- lumen visualize
- indirect diffuse only
- r.Lumen.Visualize.IndirectDiffuse
GPUParticles3D
Dispatch a game-owned particle surface and process function through a pooled system.
class GPUParticles3D extends Sprite implements IComputeDrivenUse it to
- emit sparks, smoke, or other transient effects
- update many small visual particles
- trail dust, exhaust, or spray behind a moving object
- emit cannon smoke and muzzle flash particles
- fire a cannonball projectile with cannon smoke particles
- splash spray droplets with lifetime and gravity
- spawn water droplets, mist, or foam bubbles above a fluid surface
- falling snowflakes, rain or ash around the player that thicken into a windy storm or blizzard
- kick up a spray of powder snow or dust where a foot or a ball lands
- a hit, impact or explosion burst that starts at the point and moment it is asked for, and a second hit that must not move the first hit's live particles
- emitParticle a burst of GPU particles at a world position with its own free slots
Example
const particles = new GPUParticles3D(particleOptions);
particles.emitParticle({ count: 220, origin: hit.position });Good to know
- geometry, color, and timing remain supplied by the game
- a
spawnkernel makes bursts requests:emitParticle({ count, origin })reserves ring slots, the engine stampsbuffers.birthsandprocessreads age asruntime.time - births[i]; there is no readback - a spawn emitter is world space (identity world matrix);
localCoords: truefollows the parent - requests over
amountormaxSpawnPerFrameclamp, add tostats.clampedand warn once;stats.recycledLiveisundefinedwithout thelifetimeoption - the emitter measures its own bounds and stops computing and drawing after graceSeconds outside the camera view
- a game needs no emitting = visible gate, and an emitter with no measured bounds is never culled for leaving the view
- when measured GPU cost passes the frame budget, the smallest projected emitters pause first, and cull.reason reads outside-view or over-budget
Options
- localCoords, maxSpawnPerFrame and lifetime tune a spawn emitter;
restart()kills every particle and rewinds the ring - onCull: "clear" restarts a returning effect, the default "pause" resumes it with buffers intact
- bounds supplies a fixed local Box3 and skips GPU measurement, padding enlarges the world box, boundsEveryFrames sets the measurement cadence
- graceSeconds sets the seconds outside the view before culling, and Infinity disables view culling
GPUReadback
Copy a GPU buffer back to the CPU on a throttle, and report how old each sample is.
class GPUReadbackUse it to
- read a GPU simulation on the CPU without stalling the frame
- float a body on a wave field whose height only exists on the GPU
- count GPU-side survivors for a diagnostic without blocking drawing
- keep a ship floating on simulated ocean waves
Example
const heights = new GPUReadback({ attribute: field.value, everyFrames: 4 });Good to know
- the copy is asynchronous, so every sample carries staleFrames and is never this frame
- WebGPU only; the seam throws on a WebGL2 renderer rather than returning nothing
- one copy is in flight at a time and requests made during one are dropped, not queued
GPUSceneBVH
Pack a selected static scene into TSL storage nodes for an upstream BVH ray query.
class GPUSceneBVH extends Group implements IComputeDrivenUse it to
- trace thousands of scene rays inside a TSL kernel
- build a contact-occlusion or visibility query over loaded meshes
Example
const bvh = ctx.add(new GPUSceneBVH(ctx.scene, { include: (object) => object.userData.traceable === true }));Good to know
- call rebuild() after a scene transform or geometry change; the snapshot is static by default
- rebuild() is an explicit CPU SAH build proportional to selected triangles; process() is a no-op, and the game pays upstream traversal per shader ray
GrassField3D
Stream instanced grass in chunks around the camera; the game owns the blade and its TSL material.
class GrassField3D extends GroupUse it to
- grass that sways and parts around the player
- a meadow, lawn or grassy field over terrain that streams around the camera
- ground cover grass blades with distance thinning and LOD that does not pop
- grass flattened or pushed aside where the player, a creature or a vehicle walks
- grow grass on a terrain biome's grass rows with grassFieldFromBiome
- Grass that sways and parts around the player across a large terrain.
- Stream instanced ground cover in chunks around the camera under a frame budget.
- Meadow, lawn or field grass with distance thinning and LOD that does not pop.
Example
// the look lives in the kit's src/render/grass.ts
const grass = new GrassField3D({ blade: grassBlade(), material: grassMaterial, getHeight: height });
ctx.add(grass);
ctx.beforeRender(() => { grass.pushers[0]?.set(hero.x, hero.y, hero.z, 1.2); grass.update(ctx.camera); });Good to know
- call
update(camera)once per rendered frame fromctx.beforeRender; chunks build nearest first insidebuildBudgetMs - the material reads
GRASS_FIELD_ATTRIBUTESand the field'snodesuniforms, so its thinning matches the CPU trim - a chunk is built inside 1.3 × the draw distance and discarded past 1.4 ×, so a camera on the edge rebuilds nothing
- Call
update(camera)once per rendered frame, fromctx.beforeRender. - Rotating or scaling the field is not supported; translating it is.
Options
- densityScale and cullDistanceScale scale every density and distance at once; prewarm() builds all in range on the next update
GroundSnap
Keep a rendered model's feet on a surface while preserving an auditable override.
class GroundSnapUse it to
- keep a character's feet on the floor
- correct visual grounding after an animation update
Example
import { GroundSnap } from "@threenative/core";
const snap = new GroundSnap(character, { enabled: true });Good to know
- import from
@threenative/core; this moves the rendered model, not its physics collider
Options
- enabled controls whether correction is applied while clearance is still measured
InputMap
The map a game reads input through: named actions, 2D vectors and scalar axes resolved from keyboard, gamepad, mouse, wheel, pinch and touch. defineGame({ input }) builds one and hands it to the running game as ctx.input, so the usual route is a binding in the config and ctx.input.axis("move") in the update. Construct one directly to drive a menu, a replay or a test outside a running game.
class InputMapUse it to
- map WASD keys to a movement axis instead of reading the held key set in the update loop
- read a jump, a fire or a reload as one named action bound to key, gamepad button and mouse button together
- read mouse look, wheel zoom or a two-finger pinch as an axis the frame loop already ticks
- support an Xbox pad, a generic XInput clone, an 8BitDo or a Steam Deck controller
- the character drifts while the controller stick is idle
- the controller does nothing in Firefox on Linux
- a second controller or a wheel steals the input from the pad the player holds
Example
const game = defineGame({ input: { move: { up: ["KeyW"], down: ["KeyS"], left: ["KeyA"], right: ["KeyD"] } }, scenes: { Play } });
// inside the scene, per frame: ctx.input.axis("move") is 0 at rest and 1 at full tiltGood to know
buttonsis the gamepad andmouseButtonsthe mouse;up/down/left/rightare the directions ofvector(name), not the keys that press it- scroll, pinch and pointer-relative sources are declared on the binding and read through
axis(name); a game adds no window listener of its own - gamepad buttons are W3C standard indices on every pad: 0 south (A/Cross), 1 east, 2 west, 3 north, 4/5 shoulders, 6/7 triggers, 8 select, 9 start, 10/11 stick clicks; axes 0..3 are the sticks
- both sticks carry a radial dead zone,
0.2by default, reported per connected pad asTN_GAMEPAD; a pad the browser reports unmapped and the table does not know is ignored, never read with raw indices - a pad claims the input when a button goes down or a stick travels past half tilt, and keeps it while idle so its releases read; a stick resting past the dead zone or jittering across it claims nothing, so an idle pad in the first slot cannot steal input
Options
- defineGame({ gamepadDeadZone: 0 }) publishes raw axes
Also found by
- gamepad
- controller
- joypad
- xbox
- 8bitdo
- steam deck
installFilmicToneMapping
Unreal 5.8.3's tone curve, the default tone mapping of createRenderer and Game: a filmic curve in ACEScg (slope 0.88, toe 0.55, shoulder 0.26) after the gamut expansion and blue correction of Unreal's colour LUT. installFilmicToneMapping registers it as three's custom tone mapping.
function installFilmicToneMapping( raw: unknown, c: IFilmicCurve = FILMIC_CURVE, grade: IColorGrade = COLOR_GRADE, ): number | undefinedUse it to
- the frame should tone map the way a fresh Unreal project does
Example
const renderer = await createRenderer({ toneMapping: "aces" }); // the named overrideGood to know
- WebGPU renderers only: a renderer without a node library keeps ACES and reports
TN_TONEMAP
Options
createRenderer({ toneMapping: "aces" | "agx" | "neutral" | "none" })orgame.renderer.toneMappingin the game config; settingrenderer.raw.toneMappinglater wins
installSpanProbes
Attach the span probes to a renderer: three's render, _projectObject, the render list's sort, the per-draw submission, and the scene-graph walk. Installed for you when TN_FRAME_SPANS asks; exported so a harness can wrap a renderer it owns.
function installSpanProbes(target: ISpanProbeTarget, root: Object3D): () => voidUse it to
- measure which part of three's render path costs the frame
- attach the span tree to a renderer a test or a tool constructed itself
Example
const uninstall = installSpanProbes(renderer.raw, scene);Good to know
- returns an uninstall that restores every wrapper, asserted by test
- a renderer whose internals have moved loses that span rather than throwing, and it is absent from the report rather than zero
- only the outermost
_projectObjectopens a span, because three's recurses per child
InstancedBatch
Collapse many copies of one game-authored shape into a single draw, without counting them first. new InstancedMesh(geometry, material, count) needs the count before anything is placed, so a procedural builder ends up walking its layout twice or over-allocating. Place as you go and build() once; the shape, the surface and every transform stay the game's, and the built mesh is returned so instances can still be animated by the index place and span hand back.
class InstancedBatchUse it to
- draw hundreds of repeated props without hundreds of draw calls
- draw thousands of identical instanced blocks or obstacles in one mesh
- automatically select instanced prop detail from projected screen error using baked AutoLOD chains
- place repeated props when the count is not known until the layout has been walked
- build a chain, railing, cable, or tie rod out of point-to-point segments
Example
const curbs = new InstancedBatch({ geometry: new BoxGeometry(1, 1, 1), material });
curbs.place({ position: [x, 0.08, z], rotation: [0, angle, 0], scale: [length, 0.18, 0.42] });
curbs.build({ castShadow: true, name: "curbs", parent: ctx.scene });Good to know
- geometry and material are required and come from the game; the batch chooses neither
- span stretches along +Y, so its geometry must be unit-height and centred on the origin
- placing after build() throws, and build() returns undefined when nothing was placed
- baked AutoLOD chains survive geometry clone/transform preparation and partition instances automatically into spatially bounded draws in the engine frame loop at 4 px projected error; public instance slots remain stable
- unavailable authored levels report TN_INSTANCED_LOD_FAILED once naming the batch; a million-triangle batch with no chain reports TN_INSTANCED_LOD_UNAVAILABLE
Options
- autoLod: false leaves selection to the game; autoLod.maxPixelError and hysteresis override the measured-camera budget; lods supplies authored distance/geometry levels and wins over the baked chain
- castShadow and receiveShadow pass through to the built mesh and default to Three.js's own false
Also found by
- landmarks points of interest
- obstacles collectibles increasing pace
InstancedModel
Instance an entire multi-mesh, multi-material static model across many placements in spatial cells, keeping every child transform, baked AutoLOD chain and loader asset provenance intact. InstancedBatch instances one (geometry, material) primitive at a time; an imported model is a tree of child meshes, nested transforms and multi-material groups. Calling InstancedModel extracts every static part in source space, groups placements into XZ frustum-cullable spatial cells (default 48 m), preserves baked TN_discrete_lod chains on single-material meshes, and carries tnAssetPath provenance onto the built InstancedMesh batches so TN_ASSET_UNUSED and TN_STARTUP_OFFSCREEN_BYTES recognize instanced scenery without manual userData bookkeeping.
class InstancedModelUse it to
- instance a loaded multi-mesh glTF prop or building many times across a level
- replace repeated
clone()calls on static glTF buildings, barriers or roadside scenery with instanced batches - bucket scattered or instanced multi-part models into spatial cells for frustum culling
Example
const trees = new InstancedModel({ source: model.scene, cellSize: 48 });
trees.place({ position: [x, 0, z], rotation: [0, yaw, 0], scale });
trees.build({ castShadow: true, name: "trees", parent: ctx.scene });Good to know
- static meshes only: skinned meshes are skipped and an empty source throws; the game supplies source meshes, transforms and materials
- multi-material sections clone the base geometry per draw-range slice; single-material parts share the base geometry and its baked AutoLOD chain
- placing after build() throws, and build() returns an empty array when nothing was placed
Options
- cellSize sets the XZ spatial cell edge in metres (default 48), or false for one bucket across all placements
- autoLod, skip, castShadow and receiveShadow pass through cleanly to the underlying meshes
invalidateStatic
Stop recomposing the transforms of a subtree nobody moves. markStatic(root) composes the subtree once and freezes it; the engine re-arms a root whose own transform the game changes, and invalidateStatic(object) announces a write deeper inside one.
function invalidateStatic(object: Object3D): number | undefinedUse it to
- cut the per-frame matrix work of terrain, buildings, props and other scenery that never moves
- keep a frozen subtree correct when the game does move it after all
Example
invalidateStatic(drawbridge);Good to know
- staticness is authored, never guessed; no heuristic watches gameplay and decides for you
- it deletes the local and world matrix composes, not the walk itself — three 0.185 recurses into every child regardless
- a write deeper inside a frozen subtree must call
invalidateStatic;TN_RENDERLIST_VALIDATE=1is what proves it happened
isConsole
Read the host platform without reaching for browser globals.
function isConsole(): booleanUse it to
- branch a portable game on web or native
- choose touch controls for a mobile device
- can I raytrace on native
- show gamepad prompts and bind pad buttons on a games console such as the PS4
Example
if (isMobile()) showTouchControls();
if (isConsole()) showPadPrompts(isPs4() ? "dualshock" : "generic");Good to know
- only use the returned platform facts; native globals are host-owned
- image ray tracing is unavailable on native until buffer-to-texture copy-out interop exists;
mystralRT.traceRaysrefuses instead of resolving success without a readable result - a native desktop host with ray tracing hardware traces ray batches with
mystralRT.traceRayBatch, which writes hit records into a typed array you own; readmystralRT.capabilities().rayBatchfirst, and keep the software BVH trace for the web and every other host - when
mystralRT.capabilities().sharedTransportis true,mystralRT.traceRayBatchGpu({ tlas, rays, hits, rayCount })traces between two GPUBuffers with no copy through CPU memory;raysneeds the CopySrc usage andhitsthe CopyDst usage, and each call costs CPU time, so measure it against the software trace for your batch size
isMobile
Read the host platform without reaching for browser globals.
function isMobile(): booleanUse it to
- branch a portable game on web or native
- choose touch controls for a mobile device
- can I raytrace on native
- show gamepad prompts and bind pad buttons on a games console such as the PS4
Example
if (isMobile()) showTouchControls();
if (isConsole()) showPadPrompts(isPs4() ? "dualshock" : "generic");Good to know
- only use the returned platform facts; native globals are host-owned
- image ray tracing is unavailable on native until buffer-to-texture copy-out interop exists;
mystralRT.traceRaysrefuses instead of resolving success without a readable result - a native desktop host with ray tracing hardware traces ray batches with
mystralRT.traceRayBatch, which writes hit records into a typed array you own; readmystralRT.capabilities().rayBatchfirst, and keep the software BVH trace for the web and every other host - when
mystralRT.capabilities().sharedTransportis true,mystralRT.traceRayBatchGpu({ tlas, rays, hits, rayCount })traces between two GPUBuffers with no copy through CPU memory;raysneeds the CopySrc usage andhitsthe CopyDst usage, and each call costs CPU time, so measure it against the software trace for your batch size
isNative
Read the host platform without reaching for browser globals.
function isNative(): booleanUse it to
- branch a portable game on web or native
- choose touch controls for a mobile device
- can I raytrace on native
- show gamepad prompts and bind pad buttons on a games console such as the PS4
Example
if (isMobile()) showTouchControls();
if (isConsole()) showPadPrompts(isPs4() ? "dualshock" : "generic");Good to know
- only use the returned platform facts; native globals are host-owned
- image ray tracing is unavailable on native until buffer-to-texture copy-out interop exists;
mystralRT.traceRaysrefuses instead of resolving success without a readable result - a native desktop host with ray tracing hardware traces ray batches with
mystralRT.traceRayBatch, which writes hit records into a typed array you own; readmystralRT.capabilities().rayBatchfirst, and keep the software BVH trace for the web and every other host - when
mystralRT.capabilities().sharedTransportis true,mystralRT.traceRayBatchGpu({ tlas, rays, hits, rayCount })traces between two GPUBuffers with no copy through CPU memory;raysneeds the CopySrc usage andhitsthe CopyDst usage, and each call costs CPU time, so measure it against the software trace for your batch size
isPs4
Read the host platform without reaching for browser globals.
function isPs4(): booleanUse it to
- branch a portable game on web or native
- choose touch controls for a mobile device
- can I raytrace on native
- show gamepad prompts and bind pad buttons on a games console such as the PS4
Example
if (isMobile()) showTouchControls();
if (isConsole()) showPadPrompts(isPs4() ? "dualshock" : "generic");Good to know
- only use the returned platform facts; native globals are host-owned
- image ray tracing is unavailable on native until buffer-to-texture copy-out interop exists;
mystralRT.traceRaysrefuses instead of resolving success without a readable result - a native desktop host with ray tracing hardware traces ray batches with
mystralRT.traceRayBatch, which writes hit records into a typed array you own; readmystralRT.capabilities().rayBatchfirst, and keep the software BVH trace for the web and every other host - when
mystralRT.capabilities().sharedTransportis true,mystralRT.traceRayBatchGpu({ tlas, rays, hits, rayCount })traces between two GPUBuffers with no copy through CPU memory;raysneeds the CopySrc usage andhitsthe CopyDst usage, and each call costs CPU time, so measure it against the software trace for your batch size
isStatic
Stop recomposing the transforms of a subtree nobody moves. markStatic(root) composes the subtree once and freezes it; the engine re-arms a root whose own transform the game changes, and invalidateStatic(object) announces a write deeper inside one.
function isStatic(root: Object3D): booleanUse it to
- cut the per-frame matrix work of terrain, buildings, props and other scenery that never moves
- keep a frozen subtree correct when the game does move it after all
Example
invalidateStatic(drawbridge);Good to know
- staticness is authored, never guessed; no heuristic watches gameplay and decides for you
- it deletes the local and world matrix composes, not the walk itself — three 0.185 recurses into every child regardless
- a write deeper inside a frozen subtree must call
invalidateStatic;TN_RENDERLIST_VALIDATE=1is what proves it happened
isStreamedGeometry
True while a geometry is the coarse companion a streamed model draws first (PRD-860), before its full file replaces it in place. A caller that copies vertices (a trimesh collider, a navmesh bake, a merge) waits with ctx.assets.model(path, { whole: true }) instead of copying the coarse ones.
function isStreamedGeometry(geometry: BufferGeometry): booleanUse it to
- collider or navmesh built from a model is coarser than what is drawn
- wait for the full model before copying its vertices
- whole model before collision
- TN_COLLIDER_COARSE
Example
const coarse = isStreamedGeometry(mesh.geometry);Good to know
CollisionShape3D.fromMeshwith "trimesh" or "convexHull" on a streamed geometry warnsTN_COLLIDER_COARSEnaming the mesh and the{ whole: true }override, and still builds
isTouchscreenAvailable
Read the host platform without reaching for browser globals.
function isTouchscreenAvailable(): booleanUse it to
- branch a portable game on web or native
- choose touch controls for a mobile device
- can I raytrace on native
- show gamepad prompts and bind pad buttons on a games console such as the PS4
Example
if (isMobile()) showTouchControls();
if (isConsole()) showPadPrompts(isPs4() ? "dualshock" : "generic");Good to know
- only use the returned platform facts; native globals are host-owned
- image ray tracing is unavailable on native until buffer-to-texture copy-out interop exists;
mystralRT.traceRaysrefuses instead of resolving success without a readable result - a native desktop host with ray tracing hardware traces ray batches with
mystralRT.traceRayBatch, which writes hit records into a typed array you own; readmystralRT.capabilities().rayBatchfirst, and keep the software BVH trace for the web and every other host - when
mystralRT.capabilities().sharedTransportis true,mystralRT.traceRayBatchGpu({ tlas, rays, hits, rayCount })traces between two GPUBuffers with no copy through CPU memory;raysneeds the CopySrc usage andhitsthe CopyDst usage, and each call costs CPU time, so measure it against the software trace for your batch size
isWeb
Read the host platform without reaching for browser globals.
function isWeb(): booleanUse it to
- branch a portable game on web or native
- choose touch controls for a mobile device
- can I raytrace on native
- show gamepad prompts and bind pad buttons on a games console such as the PS4
Example
if (isMobile()) showTouchControls();
if (isConsole()) showPadPrompts(isPs4() ? "dualshock" : "generic");Good to know
- only use the returned platform facts; native globals are host-owned
- image ray tracing is unavailable on native until buffer-to-texture copy-out interop exists;
mystralRT.traceRaysrefuses instead of resolving success without a readable result - a native desktop host with ray tracing hardware traces ray batches with
mystralRT.traceRayBatch, which writes hit records into a typed array you own; readmystralRT.capabilities().rayBatchfirst, and keep the software BVH trace for the web and every other host - when
mystralRT.capabilities().sharedTransportis true,mystralRT.traceRayBatchGpu({ tlas, rays, hits, rayCount })traces between two GPUBuffers with no copy through CPU memory;raysneeds the CopySrc usage andhitsthe CopyDst usage, and each call costs CPU time, so measure it against the software trace for your batch size
lampPenumbraTangent
A lamp's penumbra radius in tangent units at a receiver, from the lamp's source radius and the blocker and receiver distances.
function lampPenumbraTangent( sourceRadius: number, blockerDistance: number, receiverDistance: number, ): numberUse it to
- measure a lamp shadow's penumbra width without a GPU
Example
const tangent = lampPenumbraTangent(0.05, 2, 3);Good to know
- sourceRadius is 0 or more; both distances are positive metres; the result is the geometric tangent, before penumbraScale
lampShadowMarker
The TN_LAMP_SHADOW line for the renderer's last frame, or undefined on a renderer that keeps no lamp counters (three's own).
function lampShadowMarker( renderer:Use it to
- log lamp shadow redraws and GPU time apart from the sun's on the owned engine
Example
const line = lampShadowMarker(renderer, frame);
if (line !== undefined) console.info(line);Good to know
- counters that do not add up to the frame's shadow draws throw TN_LAMP_SHADOW_INVALID
loadAll
Load a list with bounded concurrency, returning results in the input's order.
async function loadAll<TIn, TOut>( items: readonly TIn[], load: (item: TIn, index: number) => Promise<TOut>, options: ILoadAllOptions =Use it to
- load many models or textures in parallel instead of one at a time
- keep a loading screen moving while a list of assets downloads
Example
const species = await loadAll(names, (name) => ctx.assets.model(`flora/${name}.glb`));Good to know
- results are written to each item's own index and never appended, so a positional lookup finds the same asset on every load
- the first rejection rejects the call and no lane starts a load it had not begun
Options
- concurrency defaults to 6;
marker: falsesilences the TN_LOAD_ALL line, not onProgress
lodChainOf
The cooked automatic LOD chain (TN_discrete_lod) a loaded geometry carries, or undefined. Its levels share the base's vertex attributes and differ only in index, and errors are each level's world-unit error in the base's own space. A caller that draws one geometry many times (an instanced batch, a streamed world level) reads the reduced shapes here instead of re-cooking.
function lodChainOf(geometry: BufferGeometry): ILodChain | undefinedUse it to
- draw a cooked reduced level of a model in an instanced batch or streamed world level
Example
const chain = lodChainOf(baseGeometryOf(mesh)); const far = chain?.levels.at(-1);Good to know
- a geometry the loader built no chain for returns undefined
lodPixelScale
The screen pixels one world unit covers at depth for this camera and viewport. Perspective divides the projected scale by the depth; orthographic has no depth term and uses the frustum height instead. This is the number a level of detail is chosen against: multiply a level's world-space error by it and you have the on-screen error a player can see, which is the comparison updateModelLods makes from the baked chain.
function lodPixelScale(camera: Camera, viewportHeight: number, depth: number): numberUse it to
- pick a level of detail from an object's projected size in pixels on screen
- know how many screen pixels a world-space error covers at a given distance
Example
const pixels = lodPixelScale(camera, canvas.clientHeight, mesh.position.distanceTo(camera.position));Good to know
- a non-positive viewport height, a non-positive frustum height or an unprojectable camera throws
- a non-positive depth has no projected scale and returns Infinity
markStatic
Freeze a subtree nobody moves: markStatic(root) composes its transforms once and stops the per-frame recompose. It is the call a game makes on scenery, terrain, buildings and props. The engine re-arms a root whose own transform the game changes; a write deeper inside a frozen subtree is announced with invalidateStatic(object).
function markStatic(root: Object3D): numberUse it to
- freeze a static mesh or subtree so its matrices are not recomputed every frame
- stop the engine recomposing the transforms of props, terrain and buildings each frame
Example
markStatic(island); invalidateStatic(drawbridge);Good to know
- staticness is authored, never guessed; no heuristic watches gameplay and decides for you
- a write deeper inside a frozen subtree must call
invalidateStatic;TN_RENDERLIST_VALIDATE=1is what proves it happened
MatrixWorldPass
Walk the scene graph's world matrices each frame without recursing into a hidden subtree. On by default as renderer.matrixWorld: "visible". three's updateMatrixWorld recurses into every child whatever its visible flag, so a hidden LOD body, a merged stand-in and a parked model cost a world-matrix multiply each while nothing under them can draw. This pass mirrors three exactly for every visible node and defers a hidden node's subtree until the frame it shows again. A class that overrides updateMatrixWorld (SkinnedMesh, Camera) runs its own, and a hidden node that holds bones is walked, so no skeleton or view matrix goes stale.
class MatrixWorldPassUse it to
- update the world matrices of the visible objects each frame instead of the whole scene
- the per-frame world matrix walk is hot in a profile
- stop multiplying matrices for hidden models, LOD levels and merged stand-ins
- a game needs every node walked, exactly as three's own updateMatrixWorld does
Example
import { MatrixWorldPass } from "@threenative/core";
const pass = new MatrixWorldPass(); // renderer.matrixWorld defaults to "visible"Good to know
- a game that reads a hidden object's matrixWorld directly must use getWorldPosition or updateWorldMatrix(true, false) first
renderer.matrixWorld: "all"visits every node;TN_PROJECTIONreports the visited count either way
Options
- renderer.matrixWorld: "all" runs three's full walk instead of the visible-only default
measureThreePose
Measure a Three.js pose for grounded or attachment-aware checks.
function measureThreePose( object: Object3D, options: IMeasureThreePoseOptions =Use it to
- inspect a skinned model's posed bounds
- verify a character's visual pose
Example
const measurement = measureThreePose(model);Good to know
- precise per-vertex measurement is opt-in and not for frame loops
mergeByMaterial
Bake a hierarchy's static meshes into one mesh per material, with their transforms baked in. already made; nothing here decides appearance tree: add them to root and remove the sources yourself, or both draw vertices are not its own to bake texture mapping; a missing normal is recomputed
function mergeByMaterial(root: Object3D, options: IMergeByMaterialOptions): Mesh[]Use it to
- collapse a building or ship of dozens of boxes into one draw call per material
- consolidate the static parts of a group before adding it to the scene
Example
const [hull, deck] = mergeByMaterial(ship, { label: "ship" });
// a piece that must keep moving at run time:
const [steady] = mergeByMaterial(ship, { label: "ship", skip: (mesh) => mesh.name === "radar" });Good to know
- the material is the game's own instance and the split follows the materials the game
- the meshes come back in root's local space and unparented, with the originals still in the
- a skinned or instanced mesh, and a mesh with several materials, is left out — its
- a group where only some meshes carry uv throws naming the label rather than losing the
Options
- skip leaves one mesh out of its group and out of the result
mergeParts
Merge pieces a game authored out of primitives into one buffer, keeping each piece's own look. InstancedBatch collapses many copies of one shape; this collapses many different shapes that never move relative to each other — a building, a ship, a character built from boxes, or the static parts of an imported glTF model. Two things go wrong every time and neither is about how any of it looks. mergeGeometries hands back null on mismatched inputs instead of throwing, and the usual mismatch is invisible: one ExtrudeGeometry is non-indexed while every other primitive is indexed, so the merge fails at the first piece and the scene never loads. And a merged buffer draws with one surface, so per-piece colour is gone unless every piece carries a flat color attribute written before the merge. Both are mechanical. By default every part is stripped to position and the normals are recomputed from the merged buffer; pass preserve to keep authored normals and texture UVs while baking each part's object transform. Geometry, placement, colour and the surface it draws with all stay the game's.
function mergeParts( parts: Iterable<IMergePart>, options: IMergePartsOptions, ): BufferGeometryUse it to
- bake a building, ship or character authored out of primitives into one draw call
- merge multiple static Three.js meshes into one mesh per material
- consolidate the static parts of an imported glTF model into one buffer
- preserve texture UV coordinates and authored normals while baking object transforms
- merge many small geometries and keep each piece's own colour
- stop mergeGeometries from silently returning null on an extruded shape
Example
const wall = new Mesh(mergeParts(pieces, { label: "gatehouse" }), stone);
// pieces are meshes, or { geometry, matrix, color } when the colour is per piece:
const banner = mergeParts([{ color: 0x8b2f1a, geometry: cloth, matrix: placement }], { label: "banner" });
// keep a model's texture UVs and authored normals while baking its transforms:
const hull = mergeParts(hullParts, { label: "hull", preserve: ["uv", "normal"] });Good to know
- every part is de-indexed; without preserve it is stripped to position and normals are recomputed from the merged buffer
- preserve keeps the listed channels, transforming position and normal by the part's placement matrix while UV values are retained unchanged
- a part that does not carry a listed preserve channel throws naming the label, the part and the channel
- either every part names a color or none does, and a mix throws
- an empty part list throws, and a merge three.js refuses throws naming the label
Options
- color is per part and optional; without it no colour attribute is written and the surface alone decides
- preserve is optional and empty by default: position-only merge with recomputed normals, exactly as before
normaliseToMetres
Scale an asset to a real-world measurement and return the applied factor.
function normaliseToMetres(object: Object3D, options: INormaliseToMetresOptions): numberUse it to
- make a character exactly 1.8 metres tall
- normalize a prop or weapon to a known longest axis
Example
normaliseToMetres(character, { metres: 1.8, axis: "height" });Good to know
- skinned height uses a crown bone; game-specific asset expectations stay in render code
Replaces new Box3().setFromObject(.
onLaunchFailure
Called for every launch failure the engine notices, with the message to show the player.
function onLaunchFailure(listener: (failure: ILaunchFailure) => void): () => voidUse it to
- show the player why the game stopped loading instead of leaving the loading screen up
- report a stalled launch or a lost GPU device in the game's own UI
Example
const off = onLaunchFailure((failure) => shell.loading({ failure: failure.message }));parseReplayRecording
Validate and parse a replay recording file.
function parseReplayRecording(value: unknown): IReplayRecordingUse it to
- validate a recording before replaying it in another host
Example
const recording = parseReplayRecording(rawRecording);Good to know
- recordings are version 1; the parser fails closed with TN_REPLAY_* codes
PathFollow3D
Move an object along a Three.js curve with Godot-style path following.
class PathFollow3DUse it to
- move an enemy or prop along a patrol path
- sample a racing line from a curve
Example
const follower = new PathFollow3D({ points: patrolPoints, loop: true, speed: 3 });penumbraUv
Convert world-space caster gap to a shadow UV radius, floored at one texel.
function penumbraUv( gapMetres: number, sourceAngleRad: number, frustumWidthMetres: number, mapSize: number, ): numberUse it to
- measure a source-angle shadow's filter radius without a GPU
Example
const radius = penumbraUv(10, angle, 40, 2048);Good to know
- inputs must be finite and non-negative; sizes must be positive and angle < PI/2 radians
PipelineCensus
Read the renderer's bounded, versioned pipeline capture in a diagnostic or playtest tool.
class PipelineCensusUse it to
- inspect shader and pipeline creation work during a real launch
- correlate pipeline creation with material, object, pass, and shader identities
Example
const capture = game.runtime.pipelineCensus?.();
// The game normally reaches this through `runtime.pipelineCensus`; direct construction exists
// for renderer adapters and contract tests, not for gameplay.Good to know
- the capture is bounded and incomplete when the backend cannot expose an observation
PointerEvents3D
Dispatch portable pointer events from the game surface to registered Three.js objects.
class PointerEvents3D implements IPointerEvents3DUse it to
- let the player click on a thing in the world
- show a 3D object while a pointer hovers over it
- handle touch and mouse taps on a loaded model without naming its child meshes
- drag a crate or prop with the mouse or a finger
Example
ctx.pointer.on(tile, "tapped", (event) => place(event.point));Good to know
- listeners are side-table registrations; Three.js prototypes are never patched
- one raycast serves each active pointer and no raycast runs when nothing is registered
posedBounds
Measure a Three.js pose for grounded or attachment-aware checks.
function posedBounds(root: Object3D, meshes?: readonly Object3D[]): IThreePoseBoundsUse it to
- inspect a skinned model's posed bounds
- verify a character's visual pose
Example
const measurement = measureThreePose(model);Good to know
- precise per-vertex measurement is opt-in and not for frame loops
prewarm
Keep transient render surfaces in the renderer's pipeline cache before first use.
function prewarm(object: Object3D | readonly Object3D[]): voidUse it to
- prewarm a projectile, tracer, particle, or other transient effect
- avoid a long first-use frame for a newly visible effect
Example
prewarm(tracerPool);Good to know
- keep the surface visible with zero opacity; do not hide it with
visible = false
Replaces .visible = false.
ProbeVolume
Bake static diffuse irradiance that reaches surfaces from outside the camera view.
class ProbeVolume extends Object3D implements IComputeDrivenUse it to
- light bouncing from a room I cannot see
- light a wall with an off-screen emitter
- glass or fog inside a room takes the room's bounce light
Example
const probes = new ProbeVolume({ bounds, density: 0.5 }); ctx.add(probes); void probes.requestBake(scene);Good to know
- request a bake after static geometry and lights are authored; this is static-lighting-first, not fully dynamic relighting
- add the volume with ctx.add() so its incremental work is measured in the render phase
- call sample() or sampleNode() from a game-owned material before screen-space GI; the volume owns no light, material, or colour
- a translucent material or a fog sample has no side that faces the light: it reads sampleNonDirectional(position), one atlas fetch, the same in every direction (divide by pi for a radiance)
Options
- density, bounds, bakeBudgetMs, and bounces are game-owned choices
Also found by
- readable world lighting
- lumen translucency volume
- translucency gi
publishDevGlobal
The one name every dev surface publishes under, and the reader/writer for it.
function publishDevGlobal(name: string, value: unknown, scope: unknown): voidUse it to
- read or extend the
__THREENATIVE__object a dev launch publishes
Example
import { DEV_GLOBAL_KEY, devGlobal } from "@threenative/core";
const tools = devGlobal(globalThis);Good to know
- every dev surface publishes under this key; the worker's typed mirror tuple names it too
qualityPreset
The quality tiers of the Unreal 5.8.3 look: what high (a desktop, Unreal's Epic), medium and low (a phone) turn on, how a GPU family picks its start tier, and the global illumination and shadow filter settings per tier named after Unreal's scalability levels. A WorldEnvironment with no options starts from high. qualityTiers holds the tier tables: resolve picks a start tier from a GPU class, gi and shadow read a tier's settings.
function qualityPreset(tier: string): IWorldEnvironmentOptionsUse it to
- pick a start tier for the GPU class and read what that tier costs the look
- build a
WorldEnvironmentfor a weaker device from a named tier
Example
const world = new WorldEnvironment({ ...qualityPreset(qualityTiers.resolve({ gpuClass: renderer.gpuClass })), bloomEnabled: false });Good to know
- an unknown tier name throws with the names it expected
Options
- pass any
IWorldEnvironmentOptionsfield afterqualityPreset(tier), or an explicittiertoqualityTiers.resolve
RadianceCache
A probe field of diffuse irradiance that refreshes by tracing the packed scene, with no scene draw: the radiance cache of a dynamic global-illumination pass. Probes in view refresh first, oldest first, within numProbesToTraceBudget a frame; a lamp toggled in game code or a sun that steps more than one degree re-traces them while the old values keep lighting the frame.
class RadianceCache extends ProbeVolumeUse it to
- light follows a lamp that switches on and off in a room
- bounce light that updates when the sun moves, with no baked lightmap
- global illumination that refreshes fast enough to read as dynamic
Example
const bvh = new GPUSceneBVH(ctx.scene); ctx.add(bvh); const cache = new RadianceCache({ bounds, density: 0.5, trace: { bvh, sun, sky, camera: ctx.camera } }); ctx.add(cache);Good to know
- build a GPUSceneBVH of the static meshes first and pass it as trace.bvh; the cache reads colour and emissive from each material, a texture or a node is counted as ignored
- add the cache with ctx.add() so its refresh is measured in the render phase, and read it with sampleNode(position, normal) from a game-owned material
- a one-sided material is not seen from behind, as a cube capture would not draw it
Options
- numProbesToTraceBudget (100), probeResolution (8, so 64 rays a probe; 32 for a small emitter), bounds, density, bounces and the sun and sky values are game-owned
Also found by
- lumen radiance cache
- radiance cache
- irradiance field
- dynamic probe gi
readGIMarker
Parse a TN_GI console line back into its report, or undefined.
function readGIMarker(line: string): IGIBudgetReport | undefinedUse it to
- inspect which global illumination method ran and what the frame cost
Example
const report = readGIMarker(line); if (report?.verdict === "over") console.log(report.reason);Good to know
- non-marker lines and malformed markers return
undefined
readLampShadowMarker
Parse a TN_LAMP_SHADOW line back into its stats, or undefined.
function readLampShadowMarker(line: string): ILampShadowStats | undefinedUse it to
- count lamp shadow redraws from a renderer log, for example a moving-caster run
Example
const stats = readLampShadowMarker(line);
if (stats !== undefined) console.log(stats.lamps.redraws);Good to know
- non-marker lines and markers whose sun and lamp draws do not add up return
undefined
readProbeVolumeObservation
Read the most recent observation from a probe volume.
function readProbeVolumeObservation(value: unknown): IProbeVolumeObservation | undefinedUse it to
- inspect the latest probe bake observation
Example
const observation = readProbeVolumeObservation(probes);Good to know
- the returned observation is a measurement; it does not own lighting or materials
readRenderChainObservation
Compose game-provided render nodes in a measured, fail-closed chain. Authored stages use an opaque id and anchor before or after a built-in or another supplied stage; the engine does not need to know the effect's visual vocabulary.
function readRenderChainObservation( renderer: unknown, ): IRenderChainMarker["applied"] | undefinedUse it to
- compose screen-space effects in a canonical order
- insert a game-authored post stage into the measured render chain
- report which render tier and velocity route actually ran
Example
const chain = new RenderChain(renderer, { input: colour, stages, request: { stages: ["bloom"], tier: "auto" } });Good to know
- stage factories own colour, strength, and all other appearance choices
- authored stages declare exactly one before or after anchor
readRenderChainReport
Compose game-provided render nodes in a measured, fail-closed chain. Authored stages use an opaque id and anchor before or after a built-in or another supplied stage; the engine does not need to know the effect's visual vocabulary.
function readRenderChainReport(renderer: unknown): IRenderChainMarker | undefinedUse it to
- compose screen-space effects in a canonical order
- insert a game-authored post stage into the measured render chain
- report which render tier and velocity route actually ran
- expose the render tier and dropped-stage reasons to a playtest
- inspect whether a temporal pass received velocity
Example
const chain = new RenderChain(renderer, { input: colour, stages, request: { stages: ["bloom"], tier: "auto" } });Good to know
- stage factories own colour, strength, and all other appearance choices
- authored stages declare exactly one before or after anchor
- an absent value means no chain was installed and must fail a chain assertion
readShadowTierMarker
Parse a TN_SHADOW_TIER console line back into its report, or undefined.
function readShadowTierMarker(line: string): IShadowFilterReport | undefinedUse it to
- inspect which shadow filter tier ran and why it stepped
Example
const report = readShadowTierMarker(line); if (report?.stepped) console.log(report.reason);Good to know
- non-marker lines and malformed markers return
undefined
readVelocityPreviousBoneMatrices
Provision screen-space motion data for temporal nodes and keep per-instance history at the frame boundary.
function readVelocityPreviousBoneMatrices(object: Object3D): Float32Array | undefinedUse it to
- keep a skinned character or instanced crowd stable in a temporal stage
- add the velocity output to a Three.js scene pass
- inspect the previous skinned pose at a renderer adapter boundary
Example
const scenePass = pass(scene, camera);
ensureVelocityOutput(scenePass);
renderer.setOutputNode(scenePass);
const tracker = new VelocityTracker();
tracker.update(scene);
renderer.render(scene, camera);
tracker.commit(scene);Good to know
- call
VelocityTracker.update()before the render andcommit()after it - a pass is only given a velocity target when a temporal stage consumes it
readVelocityPreviousMatrices
Provision screen-space motion data for temporal nodes and keep per-instance history at the frame boundary.
function readVelocityPreviousMatrices(object: Object3D): Float32Array | undefinedUse it to
- keep a skinned character or instanced crowd stable in a temporal stage
- add the velocity output to a Three.js scene pass
- inspect the previous instance frame at a renderer adapter boundary
Example
const scenePass = pass(scene, camera);
ensureVelocityOutput(scenePass);
renderer.setOutputNode(scenePass);
const tracker = new VelocityTracker();
tracker.update(scene);
renderer.render(scene, camera);
tracker.commit(scene);Good to know
- call
VelocityTracker.update()before the render andcommit()after it - a pass is only given a velocity target when a temporal stage consumes it
readVelocityPreviousWorldMatrix
Provision screen-space motion data for temporal nodes and keep per-instance history at the frame boundary.
function readVelocityPreviousWorldMatrix(object: Object3D): Matrix4 | undefinedUse it to
- keep a skinned character or instanced crowd stable in a temporal stage
- add the velocity output to a Three.js scene pass
- inspect the previous rigid transform at a renderer adapter boundary
Example
const scenePass = pass(scene, camera);
ensureVelocityOutput(scenePass);
renderer.setOutputNode(scenePass);
const tracker = new VelocityTracker();
tracker.update(scene);
renderer.render(scene, camera);
tracker.commit(scene);Good to know
- call
VelocityTracker.update()before the render andcommit()after it - a pass is only given a velocity target when a temporal stage consumes it
readVirtualShadowMarker
Parse a TN_VIRTUAL_SHADOW console line back into its complete stats, or undefined.
function readVirtualShadowMarker(line: string): IVirtualShadowStats | undefinedUse it to
- inspect virtual shadow cache and mover counters from a renderer log
Example
const stats = readVirtualShadowMarker(line);
if (stats !== undefined) console.log(stats.reuseRatio);Good to know
- non-marker lines and markers with incomplete or non-numeric stats return
undefined
reconcileMirroredClips
Repair an exported rig whose animation clips are z-mirrored against its own bind pose.
function reconcileMirroredClips(root: Object3D, clips: readonly AnimationClip[]): booleanUse it to
- find out why a skinned character renders deformed
- repair an imported character that walks backwards with its spine folded
- load a rigged GLB through a custom loader and keep the framework's repair
Example
import { reconcileMirroredClips } from "@threenative/core";
if (reconcileMirroredClips(gltf.scene, gltf.animations)) console.info("clips were z-mirrored; repaired");Good to know
- the model loader already applies this automatically; only a game loading GLBs around it needs the call
- detection votes per tracked bone and converts only on an overwhelming signature; a file that does not carry it is left byte-identical
refreshStaticTransforms
Stop recomposing the transforms of a subtree nobody moves. markStatic(root) composes the subtree once and freezes it; the engine re-arms a root whose own transform the game changes, and invalidateStatic(object) announces a write deeper inside one.
function refreshStaticTransforms(): voidUse it to
- cut the per-frame matrix work of terrain, buildings, props and other scenery that never moves
- keep a frozen subtree correct when the game does move it after all
Example
invalidateStatic(drawbridge);Good to know
- staticness is authored, never guessed; no heuristic watches gameplay and decides for you
- it deletes the local and world matrix composes, not the walk itself — three 0.185 recurses into every child regardless
- a write deeper inside a frozen subtree must call
invalidateStatic;TN_RENDERLIST_VALIDATE=1is what proves it happened
RenderChain
Compose game-provided render nodes in a measured, fail-closed chain. Authored stages use an opaque id and anchor before or after a built-in or another supplied stage; the engine does not need to know the effect's visual vocabulary.
class RenderChainUse it to
- compose screen-space effects in a canonical order
- insert a game-authored post stage into the measured render chain
- report which render tier and velocity route actually ran
Example
const chain = new RenderChain(renderer, { input: colour, stages, request: { stages: ["bloom"], tier: "auto" } });Good to know
- stage factories own colour, strength, and all other appearance choices
- authored stages declare exactly one before or after anchor
renderListValidationRequested
Prove that nothing a cache skipped changed the picture: TN_RENDERLIST_VALIDATE=1 recomputes every world matrix the long way, every frame, and throws on the first element that disagrees with what the frame is about to draw.
function renderListValidationRequested(): booleanUse it to
- prove a static freeze did not leave a stale transform on screen
- gate a scene in CI against silent transform divergence
Example
if (renderListValidationRequested()) console.log(formatValidationReport(report));Good to know
- off by default and expensive by construction — it does the work it is checking, twice
- it throws on the first divergence rather than logging; a validation mode that continues is one nobody reads
- it proves the frames it ran on and nothing else
RenderListValidator
Prove that nothing a cache skipped changed the picture: TN_RENDERLIST_VALIDATE=1 recomputes every world matrix the long way, every frame, and throws on the first element that disagrees with what the frame is about to draw.
class RenderListValidatorUse it to
- prove a static freeze did not leave a stale transform on screen
- gate a scene in CI against silent transform divergence
Example
if (renderListValidationRequested()) console.log(formatValidationReport(report));Good to know
- off by default and expensive by construction — it does the work it is checking, twice
- it throws on the first divergence rather than logging; a validation mode that continues is one nobody reads
- it proves the frames it ran on and nothing else
renderTrapAudit
Catch scene state that silently loses environment fill or ignores authored opacity. After enter() the game first applies the opacity convention: a drawn material with opacity < 1 turns transparent and one TN_OPACITY_TRANSPARENT console warning names it (override: alphaHash: true, or opacity: 1). It then prints TN_ENVIRONMENT_TOO_SMALL as a console error with the fix, so playtest noConsoleErrors rejects it.
function renderTrapAudit(scene: Object3D &Use it to
- audit an equirectangular sky too narrow for three's WebGPU PMREM
- find visible opaque materials whose authored opacity is ignored
Example
renderTrapAudit(ctx.scene); // marker lines with the fixes, or an empty arrayGood to know
- structural scene reads only, one visible-tree walk per entry, at most five material examples
- the audit itself changes no scene state; the game loop's opacity convention is the only writer
replay
Record or replay deterministic game input and state.
function replay< TState extends Record<string, unknown> = Record<string, unknown>, TPhysics = undefined, >(options: IReplayOptions =Use it to
- reproduce a gameplay bug from recorded input
- run a deterministic replay in a playtest
Example
const driver = createReplayDriver(recording, ctx.renderer.domElement);Good to know
- use a seeded random source and fixed-step simulation for meaningful replays
Also found by
- fixed seed fixed-step simulation
resetAudioCueLedger
Forgets every recorded cue.
function resetAudioCueLedger(): voidUse it to
- clear the recorded audio cue counts between tests so one test cannot read another's plays
Example
resetAudioCueLedger();resetStaticTransforms
Stop recomposing the transforms of a subtree nobody moves. markStatic(root) composes the subtree once and freezes it; the engine re-arms a root whose own transform the game changes, and invalidateStatic(object) announces a write deeper inside one.
function resetStaticTransforms(): voidUse it to
- cut the per-frame matrix work of terrain, buildings, props and other scenery that never moves
- keep a frozen subtree correct when the game does move it after all
Example
invalidateStatic(drawbridge);Good to know
- staticness is authored, never guessed; no heuristic watches gameplay and decides for you
- it deletes the local and world matrix composes, not the walk itself — three 0.185 recurses into every child regardless
- a write deeper inside a frozen subtree must call
invalidateStatic;TN_RENDERLIST_VALIDATE=1is what proves it happened
resolveAtmosphereLutResolutions
Resolve the three LUT dimensions, allowing a game to trade startup cost for resolution.
function resolveAtmosphereLutResolutions( resolutions: Partial<IAtmosphereLutResolutions> | undefined, ): IAtmosphereLutResolutionsUse it to
- choose atmosphere LUT dimensions for a measured startup budget
Example
const resolutions = resolveAtmosphereLutResolutions({ skyView: { width: 128, height: 72 } });Good to know
- every width and height must be a positive integer; the dimensions are not a named fidelity tier
resolveAtmosphereParameters
Validate and clone game-owned atmosphere coefficients.
function resolveAtmosphereParameters( options: IAtmosphereParameters, ): IResolvedAtmosphereParametersUse it to
- validate atmosphere coefficients before a game creates its sky
Example
const parameters = resolveAtmosphereParameters({ rayleigh, mie, ozone, planetRadius, atmosphereRadius });Good to know
- provide all three coefficient vectors and both radii; omitted fields are errors
resolveTargetFps
Read what frame rate a game gets when its config does not say, and why. display.maxFps follows the display — capped at 120 on desktop and web, 60 on mobile — rather than the 60 every template used to ship, and an explicit number still wins with 0 still uncapping. The engine calls this itself; a game calls it when it needs the same number for its own frame-rate-dependent work, and TN_FRAME_BUDGET reports the resolved target and its source on every window.
function resolveTargetFps( config: ITargetFpsConfig | undefined, platform: ITargetFpsPlatform | undefined, measuredRefreshHz?: number, ): ITargetFpsUse it to
- my game does frame-rate-dependent work and must not hardcode 60
Example
resolveTargetFps(config, getPlatform()).targetFps;Good to know
- pass the measured display rate when you have one; without it the answer is the 60 fallback and says so
RippleField
Propagate a disturbance across a patch of water surface and let it fade. step is 1/60s or the CFL stability limit for the given resolution and speed, whichever is smaller
class RippleFieldUse it to
- make a splash or explosion ripple outward across water
- show the sea reacting to a bomb, shell, or torpedo hitting it
- leave a foam trail behind something moving through water
- disturb a water surface the player can see respond
- spread and drift foam on a water surface over time
Example
const ripples = new RippleField({ resolution: 128, size: 400 });
ripples.impulse(hit.x, hit.z, 6, -40, 0.5);
ripples.advance(dt);
const lift = ripples.heightAt(boat.x, boat.z);Good to know
- it draws nothing; the game supplies the mesh, the material and every colour
- add its height to an analytic swell, never in place of one
- the patch is finite and its rim absorbs; call recenter to keep it over the action
- there is no obstacle mask, because a mask is only correct for a body that never moves
Options
- speed, damping, foamHalfLife, current, step and maxSteps tune the solve; the default
ScatterField3D
Stream instanced copies of any baked mesh around a follow point, with distance thinning and levels of detail, from the game's own placement rule.
class ScatterField3D extends GroupNeeds
- npm i -D @threenative/procedural-environment for the bake these instances come from
Use it to
- scatter fallen logs, twigs, leaf litter, stones and ferns over a forest floor
- stream instanced props of any baked mesh round the player without one draw per prop
- place rocks, debris or plants on a heightfield with distance thinning and level of detail
Example
const floor = new ScatterField3D({ parts: [{ lods, material }], getHeight, density: 0.05, place });
ctx.add(floor);
ctx.beforeRender(() => floor.update(hero.position));Good to know
- call
update(follow)once per rendered frame placeruns once per candidate per tile build: return false for paths and clearings- rotating or scaling the field is not supported; translating it is
Also found by
- scatter rocks, debris and plants over terrain
Scene
Implement a portable Godot-shaped game scene lifecycle.
abstract class Scene< TState extends Record<string, unknown> = Record<string, unknown>, TPhysics = undefined, >Use it to
- add a playable level or menu scene
- move scene setup and per-frame gameplay out of the entry point
- run scene work once per actual world draw, after the frame's last fixed update and before the projection packs
Example
class Play extends Scene { update(ctx, dt) {} }
ctx.beforeRender(() => packBatches()); // cleared on scene change and stop, like ctx.afterPhysicsGood to know
- scene code must stay portable across web and native
ScenePicker
Raycast the game scene using the framework's picker.
class ScenePickerUse it to
- select an object under the pointer
- interact with the first collider or mesh hit
Example
const picker = new ScenePicker({ camera: ctx.camera, scene: ctx.scene, pointer: () => ctx.input.raw.pointer, viewport: ctx.viewport });Replaces new Raycaster(.
sceneWarning
Warn the agent that built the scene before a human plays it: a frame whose GPU is idle while its JS render phase is longer than the display's own period is a scene-shape problem, and the engine already has the shape. On by default in a debug launch, printed at most once per reported window as TN_SCENE_WARNING, and silent on a scene that is honestly GPU-bound.
function sceneWarning( window: IFrameBudgetWindow, shape: ISceneShape | undefined, declaredTargetFps: number | undefined, gpuClass?: string, ): ISceneWarning | undefinedUse it to
- find out whether a slow frame is the scene's shape or the device
- tell an authoring agent what to reduce before it promises a merge
Example
defineGame({ display: { maxFps: 60 }, scenes: { Play } });Good to know
- the rule is derived from the frame's own numbers; the display period comes from the host's presentation cap or the game's declared target, never a constant
- no verdict without a measured GPU reading and a pass census — an absent measurement is not evidence
- the record carries objects considered, draws per pass, triangles per draw and shadow-exempt casters, so the reader is not dependent on the ranking
Scheduler
Schedule delayed and repeating callbacks or tween numeric properties with game-owned cleanup.
class SchedulerUse it to
- delay an enemy patrol transition
- run a callback every simulation tick
- tween a numeric property with a game-owned curve
- a countdown timer: end the level when its time limit runs out
Example
const door = { y: 0 };
await ctx.tween(door, { y: 2.4 }, 0.5, { ease: (t) => 1 - (1 - t) ** 3 });Good to know
- dispose returned handles when the owning scene exits
- ease receives progress in the range 0 to 1 and its return value is the interpolation factor
Also found by
- tower defense game
- spawn waves
ScreenProbeGather
Lumen's Screen Probe Gather: one probe per 16 x 16 pixels traces an 8 x 8 octahedron of rays, the probes are filtered into an irradiance octahedron each, and a pixel blends the four nearest probes it can see, instead of every pixel tracing its own rays. A ray that hits on screen returns the lit frame minus the cache along it; a ray that leaves the screen continues through the packed scene up to the radiance cache's cell and reads the cache where it ended, so the light that arrives from off screen is that direction's and not the pixel's mean.
class ScreenProbeGatherUse it to
- bounce light that reads the room off screen instead of a flat ambient term
- global illumination that costs a fraction of one ray per pixel
- the light a corner sees from around the wall, which a per-pixel screen trace loses
- lumen screen probe gather
- lumen final gather
Example
const gather = new ScreenProbeGather({ camera, viewport, radiance, trace });
const gi = gather.gather(convertToTexture(input), depth(), normalView());
const bounce = gather.getGINode().rgb.mul(diffuseColor.rgb);Good to know
- the owned engine only: on engine: "threejs" the upstream node takes the camera as its fourth argument and has no probes, and gather() refuses
- the gather is a delta in E / pi: multiply it by the receiver's diffuse colour (mrt({ diffuseColor })) and add it after the scene pass, and give the scene pass no other indirect diffuse or the light is counted twice
- a viewport resize needs a new gather: the probe grid is fixed when it is built
- the grid is the cost: downsampleFactor 16 and an 8 x 8 octahedron are Unreal's Epic, 32 and 8 its High
- radiance answers in the frame's units (the cache read times the frame's gain), and a trace reads it only where the screen has nothing
Options
- downsampleFactor, tracingOctahedronResolution, cacheCellSize, timedPass and the strength of the composite are game-owned choices
setAttitude
Fly a fixed-wing aircraft with a real force balance instead of a steered velocity.
function setAttitude( state: IFlightState, heading = 0, pitch = 0, roll = 0, ): IFlightQuaternionUse it to
- fly an airplane with lift, drag, stall and control authority
- launch an aircraft off a moving carrier deck
- apply component damage or a loadout to an aircraft's performance
Example
const model = new FlightModel({ airframe: sbd, state: aircraft, wind: seaWind });
model.step(1 / 60, { turn: -1, pitch: 0.4 });Good to know
- every mass, area, power and inertia value comes from the game's airframe
- damage, stores and configuration arrive as the game's own modifier sample
setSpanRecorder
Attribute the render phase to 100% with a nested span tree, off unless TN_FRAME_SPANS asks. Every non-leaf reports its own time minus the spans inside it, so an unmeasured part shows up as a residual instead of being filed under "other"; a child that outlives its parent reports a negative residual rather than a clamped zero.
function setSpanRecorder(next: SpanRecorder | undefined): voidUse it to
- find out what inside the render phase is actually costing the frame
- tell a shadow pass's traversal from the main pass's, with the residual computed
- price an optimisation against a measured part of the phase rather than the whole of it
Example
if (spansRequested()) setSpanRecorder(new SpanRecorder());Good to know
- off by default and installed by
TN_FRAME_SPANS=1; unset, every call site is one guarded return - the tree is closed against the frame budget's own render phase, so
TN_FRAME_SPANSandTN_FRAME_BUDGETdescribe the same frames - measurement only: no span changes what is drawn, in what order, or with which renderer
ShadowFilterBudget
Steps a game's soft-shadow tier down (low, medium, high) when the whole GPU frame stays over the frame period, and back up when the frame has room, by the settings of Unreal's virtual shadow map budget (a linear model, 5% headroom). A frame that is slow for another reason keeps its shadows: the tier steps only when the shadow passes could absorb the overage. The game owns the sample counts of each tier and rebuilds its filter on each step; the tiers follow Unreal's sg.ShadowQuality Low, Medium and Epic.
class ShadowFilterBudgetUse it to
- soft shadow filter costs too much on a weak GPU
- step the shadow quality tier when the GPU frame goes over the frame period
- shadow quality tier that follows the hardware
Example
const filter = new ShadowFilterBudget({ tier: "high", framePeriodMs: 1000 / 60, onStep: (tier) => { light.shadow.filterNode = filterFor(tier); } });
ctx.beforeRender(() => filter.observeRenderer(ctx.renderer.raw));Good to know
- the game rebuilds its filter with the tier's sample counts on each step; this class draws nothing
- timestamp queries are needed: without them every window is unobserved and the tier holds
- the rule reads the whole GPU frame and the
Shadowstage, which the receiver filter inside the colour pass is not part of
Options
- explicit: true keeps the game's own sample counts and reports an over-budget frame
Also found by
- virtual shadow map scalability
- sg.ShadowQuality
ShortRangeAO
Unreal's Short Range AO: a horizon search of 2 sweeps around the view normal, 3 samples each at the squared fraction of a 32 px screen reach, at full resolution, with a bent normal at Epic. It is the occlusion that runs with dynamic global illumination — the contact detail Lumen keeps after the screen probe gather has already answered the wide occlusion — so a gathered frame is not darkened twice by two wide treatments. The result is one texture: rgb the bent normal in view space, a the share of the hemisphere left open, which multiplies indirect light only.
class ShortRangeAOUse it to
- contact shadow at the foot of an object while dynamic GI runs
- dark line where a wall meets the floor, without a second wide AO over the gathered light
- lumen short range ao
Example
const shortRange = new ShortRangeAO({ camera, viewport: renderer.drawingBufferSize });
const contact = shortRange.occlusion(depth(), normalView());
const indirect = input.rgb.mul(contact.a);Good to know
- it replaces GTAO when dynamic GI runs; a tier without GI keeps ambientOcclusion
- the occlusion multiplies indirect light only: direct light and emission keep their own occlusion
- multi-bounce and its albedo cap belong to the game's composite; Unreal caps the albedo at 0.5
- an authored stage that carries its name must anchor itself (
before: "ssgi"), because the chain's built-in order names no shortRangeAO
Options
- horizonSearchSliceCount, horizonSearchStepCount, reachPx, bentNormal and intensity are game-owned choices
SkeletalMesh3D
Shared preparation for an imported rigged character. Instances the rig with a skeleton-safe clone, normalises size with skin-aware measurement, validates requested clips against the file and rig at load time, and sets up AnimationPlayer with honest stride-root accounting. Animation evaluation inherits AnimationPlayer's automatic camera-based updateRate: "auto" default; updateRate: 1 evaluates every frame, another positive safe integer requests that interval, and updateRateReport exposes the effective rate, override status and latest result. One-shots and fades stay full-rate; root-motion AnimationComposer advances every tick, and auto camera-ray targets and camera-parented rigs stay full-rate. A public mixer "loop" listener promotes effective evaluation to 1 and observes only loop events after registration, so skipped pre-registration cycles are not replayed.
class SkeletalMesh3D extends AnimationPlayerUse it to
- put an animated character in the scene
- my imported character renders deformed
- instance an imported rigged character
- validate animation clips on a character rig at load time
- prepare a skinned character with safe skeleton cloning and stride sync
- reduce animation CPU for a crowd of imported rigs
- inspect an imported rig's effective animation evaluation rate
Example
import { SkeletalMesh3D } from "@threenative/core";
const character = new SkeletalMesh3D({
source: gltf.scene, clips: gltf.animations, requiredClips: ["idle", "walk"],
size: { metres: 1.8, axis: "height" }, strideRoot: body,
});
body.add(character.root); character.play("idle");
function update(dt: number): void { character.update(dt); }Good to know
- use strideRoot to name the body moved by game code when the rig is parented under it
- requiredClips fails closed at load time if any requested clip is missing or binds 0 tracks
Options
- strideSync controls whether locomotion playback rate matches ground covered
- size normalises the instance to real-world metres with skin-aware measurement
- updateRate: "auto" chooses the camera-based interval; 1 is full evaluation, and another positive safe integer requests that interval; a public
mixer"loop"listener promotes effective evaluation to 1 to preserve event timing
skeletonBones
List the names of every bone in a character hierarchy.
function skeletonBones(root: Object3D): readonly string[]Use it to
- inspect the available bones before attaching a game-owned object
- debug a missing skeleton bone name
Example
import { skeletonBones } from "@threenative/core";
const bones = skeletonBones(character);SkyCapture
Capture game-owned sky radiance into a sun-triggered, frame-budgeted environment map.
class SkyCaptureUse it to
- light a scene from a procedural sky when its sun moves
Example
const capture = new SkyCapture(renderer, skyNode); if (capture.update(sun)) scene.environment = capture.texture;Good to know
- use an initialized WebGPURenderer; the game supplies the sky and assigns the texture
- call update once per frame on an initialized WebGPURenderer; assign texture after it returns true
- sky nodes use a world-space view direction; keep supplied sky resources alive until dispose
SkyCaptureSchedule
Capture game-owned sky radiance into a sun-triggered, frame-budgeted environment map.
class SkyCaptureScheduleUse it to
- light a scene from a procedural sky when its sun moves
Example
const capture = new SkyCapture(renderer, skyNode); if (capture.update(sun)) scene.environment = capture.texture;Good to know
- use an initialized WebGPURenderer; the game supplies the sky and assigns the texture
snapRefreshRate
Read what frame rate a game gets when its config does not say, and why. display.maxFps follows the display — capped at 120 on desktop and web, 60 on mobile — rather than the 60 every template used to ship, and an explicit number still wins with 0 still uncapping. The engine calls this itself; a game calls it when it needs the same number for its own frame-rate-dependent work, and TN_FRAME_BUDGET reports the resolved target and its source on every window.
function snapRefreshRate(refreshHz: number): numberUse it to
- my game does frame-rate-dependent work and must not hardcode 60
Example
resolveTargetFps(config, getPlatform()).targetFps;Good to know
- pass the measured display rate when you have one; without it the answer is the 60 fallback and says so
SoftBody3D
Simulate an ordinary game-authored triangle mesh as cloth on the existing fixed-step GPU lane. The mesh supplies every visible choice. This class welds exporter duplicates, owns spring and position buffers, and replaces only the cloned material's position node. It adds no material, colour, texture, wind, stiffness, damping, or pinning default.
class SoftBody3D extends Mesh<BufferGeometry, NodeMaterial> implements IComputeDrivenUse it to
- make a flag, cape, or curtain move as cloth
- simulate a deforming surface while keeping one edge pinned
- simulate cloth sails blowing in the wind
- make cloth sails billow in wind on a ship
Example
const flag = new SoftBody3D(flagMesh, { pinned: topEdge, stiffness: 35, damping: 1.8, gravity: [0, -9.81, 0], wind: [1.5, 0, 0.4] });Good to know
- the mesh must use one Three.js node material and contain complete triangles
- pinned, stiffness, damping, gravity, and wind are required game-owned inputs
- Pixel 8 steady upper bound for the shipped 45-vertex pennant with readback every two frames: whole-starter update p95 4.66 ms, render p95 3.56 ms, and GPU timer 0.05 ms across three 300-frame final-rung windows at 552x248 with 4x MSAA; these whole-scene numbers are not isolated solver cost
Options
- timeStep follows the engine 1/60-second convention unless the game overrides it
- readbackEveryFrames enables an explicitly stale CPU position sample; zero disables it
softCircleDataTexture
Build a soft round sprite as pixel data instead of painting a canvas.
function softCircleDataTexture(size = 64, hardness = 0.25): DataTextureUse it to
- give smoke, flash, or glow sprites a radial alpha falloff
- generate sprite images that render identically under every backend
Example
const puff = softCircleDataTexture(64, 0.25);Good to know
- canvas-painted images sample black under WebGPURenderer; write sprites as pixel data there
solarPosition
Calculate solar elevation and azimuth from time, latitude, and longitude.
function solarPosition(input: ISolarPositionInput, target?: ISolarPosition): ISolarPosition;Use it to
- move a sun across a real day at a game's latitude and longitude
- run a day and night cycle over the game's sky
Example
const sun = solarPosition({ date, latitude: 49.28, longitude: -123.12, utcOffset: -8 });Good to know
- dates are interpreted as UTC unless utcOffset is supplied; no fixed sun direction is assumed
- pass a mutable { azimuth, elevation } target to reuse the result object in a steady frame loop
solarPositionAt
Calculate solar elevation and azimuth for one UTC date.
function solarPositionAt( date: Date | string, latitude: number, longitude: number, ): ISolarPositionUse it to
- calculate a sun direction from a timestamp and a game location
Example
const sun = solarPositionAt(new Date(), 49.28, -123.12);Good to know
- dates are interpreted as UTC; use solarPosition for an explicit local offset
sourceAngleShadowFilter
Source-angle blocker search and variable-radius PCF on three's shadow map.
function sourceAngleShadowFilter(Use it to
- soften a directional shadow as the caster-receiver gap grows
Example
sun.shadow.filterNode = sourceAngleShadowFilter({ sourceAngleRad: angle });Good to know
- sourceAngleRad is required, in radians in [0, PI/2); orthographic depth shadows only, not VSM
sourceRadiusShadowFilter
Source-radius blocker search and variable-radius PCF on a spot or point light's shadow map.
function sourceRadiusShadowFilter(Use it to
- soften a lamp's shadow by the lamp's size, as Unreal's SourceRadius does
Example
lamp.shadow.filterNode = sourceRadiusShadowFilter({ sourceRadius: 0.05 });Good to know
- sourceRadius is required, in metres, 0 or more (0 is one hard tap); penumbraScale, the share of the geometric penumbra kept, is in (0, 4] and defaults to 0.6, the width Unreal's lamp ray test resolves; forward-depth maps only
Options
- penumbraScale: 1 gives the geometric penumbra of a disk lamp
Also found by
- PCSS soft shadows
spanNow
Attribute the render phase to 100% with a nested span tree, off unless TN_FRAME_SPANS asks. Every non-leaf reports its own time minus the spans inside it, so an unmeasured part shows up as a residual instead of being filed under "other"; a child that outlives its parent reports a negative residual rather than a clamped zero.
function spanNow(): numberUse it to
- find out what inside the render phase is actually costing the frame
- tell a shadow pass's traversal from the main pass's, with the residual computed
- price an optimisation against a measured part of the phase rather than the whole of it
Example
if (spansRequested()) setSpanRecorder(new SpanRecorder());Good to know
- off by default and installed by
TN_FRAME_SPANS=1; unset, every call site is one guarded return - the tree is closed against the frame budget's own render phase, so
TN_FRAME_SPANSandTN_FRAME_BUDGETdescribe the same frames - measurement only: no span changes what is drawn, in what order, or with which renderer
spanRecorder
Attribute the render phase to 100% with a nested span tree, off unless TN_FRAME_SPANS asks. Every non-leaf reports its own time minus the spans inside it, so an unmeasured part shows up as a residual instead of being filed under "other"; a child that outlives its parent reports a negative residual rather than a clamped zero.
function spanRecorder(): SpanRecorder | undefinedUse it to
- find out what inside the render phase is actually costing the frame
- tell a shadow pass's traversal from the main pass's, with the residual computed
- price an optimisation against a measured part of the phase rather than the whole of it
Example
if (spansRequested()) setSpanRecorder(new SpanRecorder());Good to know
- off by default and installed by
TN_FRAME_SPANS=1; unset, every call site is one guarded return - the tree is closed against the frame budget's own render phase, so
TN_FRAME_SPANSandTN_FRAME_BUDGETdescribe the same frames - measurement only: no span changes what is drawn, in what order, or with which renderer
SpanRecorder
Attribute the render phase to 100% with a nested span tree, off unless TN_FRAME_SPANS asks. Every non-leaf reports its own time minus the spans inside it, so an unmeasured part shows up as a residual instead of being filed under "other"; a child that outlives its parent reports a negative residual rather than a clamped zero.
class SpanRecorderUse it to
- find out what inside the render phase is actually costing the frame
- tell a shadow pass's traversal from the main pass's, with the residual computed
- price an optimisation against a measured part of the phase rather than the whole of it
Example
if (spansRequested()) setSpanRecorder(new SpanRecorder());Good to know
- off by default and installed by
TN_FRAME_SPANS=1; unset, every call site is one guarded return - the tree is closed against the frame budget's own render phase, so
TN_FRAME_SPANSandTN_FRAME_BUDGETdescribe the same frames - measurement only: no span changes what is drawn, in what order, or with which renderer
spansRequested
Attribute the render phase to 100% with a nested span tree, off unless TN_FRAME_SPANS asks. Every non-leaf reports its own time minus the spans inside it, so an unmeasured part shows up as a residual instead of being filed under "other"; a child that outlives its parent reports a negative residual rather than a clamped zero.
function spansRequested(): booleanUse it to
- find out what inside the render phase is actually costing the frame
- tell a shadow pass's traversal from the main pass's, with the residual computed
- price an optimisation against a measured part of the phase rather than the whole of it
Example
if (spansRequested()) setSpanRecorder(new SpanRecorder());Good to know
- off by default and installed by
TN_FRAME_SPANS=1; unset, every call site is one guarded return - the tree is closed against the frame budget's own render phase, so
TN_FRAME_SPANSandTN_FRAME_BUDGETdescribe the same frames - measurement only: no span changes what is drawn, in what order, or with which renderer
SpectralOcean
Simulate a spectral ocean — cascaded wave spectra inverse-transformed on the GPU each frame.
class SpectralOcean extends Object3D implements IComputeDrivenUse it to
- make an ocean whose surface is the view rather than a background
- float a boat on waves the GPU is drawing
- drive a water material from a wave simulation without writing an FFT
- sail a ship on simulated ocean waves with buoyancy
Example
const sea = ctx.add(new SpectralOcean(oceanOptions));Good to know
- it draws nothing; the game supplies the mesh, the material and every colour
- CPU height is a throttled copy carrying staleFrames, never this frame and never exact
- an exact free CPU height needs an analytic wave field instead; that is a different contract
- cascades are ordered largest patchSize first and every tuning number is required
SpriteAnimator3D
Advance a game-owned non-uniform sprite atlas on the fixed step.
class SpriteAnimator3DUse it to
- play an animated pickup or sprite-sheet effect
- sequence atlas frames with different authored durations
Example
const animator = new SpriteAnimator3D({ texture: atlas, frames, mode: "pingPong" });Good to know
- the game supplies the atlas texture, surface, filtering, layout, and every frame duration
- update is driven by the scene fixed step; no wall clock or default frame rate is used
stageGpuReading
Read the GPU milliseconds of each named render pass of the newest resolved frame, such as SSGI or AO, with the whole frame's total.
function stageGpuReading(renderer: unknown): IStageGpuReading | undefinedUse it to
- read the GPU cost of one post-processing stage
- tell which render pass takes the GPU time
Example
const reading = stageGpuReading(renderer); const ssgiMs = reading?.stages.SSGI;Good to know
- absent before a whole frame resolves and on an adapter without timestamp queries; the frame number counts each reading once
staticTransformCensus
Stop recomposing the transforms of a subtree nobody moves. markStatic(root) composes the subtree once and freezes it; the engine re-arms a root whose own transform the game changes, and invalidateStatic(object) announces a write deeper inside one.
function staticTransformCensus(): IStaticTransformCensusUse it to
- cut the per-frame matrix work of terrain, buildings, props and other scenery that never moves
- keep a frozen subtree correct when the game does move it after all
Example
invalidateStatic(drawbridge);Good to know
- staticness is authored, never guessed; no heuristic watches gameplay and decides for you
- it deletes the local and world matrix composes, not the walk itself — three 0.185 recurses into every child regardless
- a write deeper inside a frozen subtree must call
invalidateStatic;TN_RENDERLIST_VALIDATE=1is what proves it happened
SurfaceCache
The Surface Cache: what a traced global-illumination ray reads where it hits a surface. A material atlas (base colour and emissive maps reduced to small tiles) answers the albedo and the glow at the hit UV; a flat material keeps its colour. SurfaceLights adds the scene's point and spot lamps at the hit, the brightest eight.
class SurfaceCacheUse it to
- give a traced bounce ray the texture colour and glow of the surface it hits
Example
const cache = SurfaceCache.from(materials); cache.albedo(slot, hit.uv.x, hit.uv.y, out);Good to know
- the materials are fixed when the cache is built; build a new one when a material or a map changes
- a map whose image the runtime does not show to JavaScript (the owned engine's glTF maps) returns the flat colour and is listed in
report.fallbacks; theimagesoption hands over its pixels - the cache owns no colour, texture or light; the game's materials and lamps are the only source
Options
- atlasSize and cardTexelDensityScale size the atlas; images supplies the pixels of a map the runtime hides
Also found by
- lumen surface cache
- lumen scene
- mesh cards
SurfaceLights
The local lamps at the hit of a traced ray: the point and spot lights whose range reaches it, the brightest eight, one shadow ray each. The Surface Cache gives the hit its colour; this gives it the lamps.
class SurfaceLightsUse it to
- light the hit of a traced ray with the scene's point and spot lamps
Example
const lamps = new SurfaceLights(lights); lamps.shade(point, normal, albedo, out, (i) => !occluded(i));Good to know
- the cap skips the ninth-brightest lamp and every one after it, and counts them in
skipped - the caller answers each shadow ray; the class owns no scene
Options
- maxLights caps the lamps evaluated at one hit
thinCards
A far level for a card mesh (needle or leaf quads): keep a share of its cards and grow each kept card about its own centre, so the crown holds its total surface area, as Unreal's Nanite "Preserve Area" foliage does. A simplifier cannot reduce disconnected cards, so the cooked chain leaves them at full count.
function thinCards(geometry: BufferGeometry, keep: number): BufferGeometryUse it to
- far trees draw too many alpha-tested needle or leaf card triangles
Example
const far = thinCards(needles.geometry, 0.4); // 40% of the cards, same areaGood to know
- the geometry must be indexed and carry no material groups, else it throws
- keep is in (0, 1]; a share that drops nothing returns the same geometry
- the choice is deterministic, and the source geometry is left untouched
TracedReflections
Reflection rays against the scene's triangles, in TSL. For a smooth surface, a ray finds what the screen cannot show (a room behind the camera, the far side of an object) and returns the hit's position, normal and material. The game lights the hit in its own stage. The kernel is plain TSL: float textures and a loop, no storage buffer.
class TracedReflectionsUse it to
- reflect what is behind the camera in a mirror or a chrome sphere
- make a glossy or wet floor reflect objects that are off screen
- trace a shadow ray from a reflected surface toward the sun
- split a surface's specular by roughness into traced, radiance-cache and diffuse-GI shares
Example
const traced = new TracedReflections(ctx.scene); const hit = traced.trace({ origin, direction, far: 30 }); // light hit.albedo at hit.position in the stageGood to know
- the pack is a snapshot of the static triangles taken when the object is built: build a new one after geometry moves
- instanced, skinned, batched and morphing meshes are not in the pack; report.skippedMoving counts them
- trace only pixels at or below maxRoughnessToTrace (0.4, Unreal's cut-off): each ray walks the tree
- a ray visits at most maxSteps tree nodes, then reports a miss; hit light, the miss colour and the blend with the frame stay in the game's src/render/
- the pack needs a device with float32-filterable
Options
- maxRoughnessToTrace, roughnessFadeLength, maxRoughnessToEvaluateRoughSpecular, roughSpecularFadeLength and maxSteps are game-owned choices
Also found by
- lumen reflections
- dedicated reflection rays
TracerPool3D
Pool travelling bullet-streak meshes for hitscan shots.
class TracerPool3DUse it to
- show where a hitscan round went
- show each round a weapon fires, one tracer per trigger press
- draw incoming fire without spawning projectiles
Example
const tracers = new TracerPool3D(ctx.scene, tracerOptions);
tracers.spawn(muzzle, shotDirection, hit.distance);Good to know
- the surface comes from the game; pooling, travel, and fading belong to the engine
- update once per frame and dispose with the owning scene
unlitFoliageWarning
Tell the agent that built the scene that its imported foliage is drawing with no image-based light: an alpha-cutout MeshStandardMaterial (or its Node twin) with scene.environment unset and no envMap of its own gets a hemisphere fill and one flat dark value, which is cardboard. Printed once per scene entry as TN_UNLIT_FOLIAGE, after enter(), with the fix in the same line.
function unlitFoliageWarning( scene: Object3D &Use it to
- catch the "why does my forest look like cardboard" question before a human plays it
- audit a scene a game built from imported GLB foliage
Example
defineGame({ scenes: { Forest } }); // one TN_UNLIT_FOLIAGE line when the forest has no skyGood to know
- derived from the scene graph, not from a constant: cutout PBR with no environment in the scene and none on the material
- it changes nothing and never throws — the environment is appearance, so setting it stays the game's decision
Options
material.userData.tnUnlitOk = trueon a material a game deliberately renders unlit (the sameuserData.tn*naming the alpha and impostor conventions use)
unmarkStatic
Stop recomposing the transforms of a subtree nobody moves. markStatic(root) composes the subtree once and freezes it; the engine re-arms a root whose own transform the game changes, and invalidateStatic(object) announces a write deeper inside one.
function unmarkStatic(root: Object3D): voidUse it to
- cut the per-frame matrix work of terrain, buildings, props and other scenery that never moves
- keep a frozen subtree correct when the game does move it after all
Example
invalidateStatic(drawbridge);Good to know
- staticness is authored, never guessed; no heuristic watches gameplay and decides for you
- it deletes the local and world matrix composes, not the walk itself — three 0.185 recurses into every child regardless
- a write deeper inside a frozen subtree must call
invalidateStatic;TN_RENDERLIST_VALIDATE=1is what proves it happened
updateAtmosphereParameters
Apply a partial game-owned atmosphere change while preserving validation.
function updateAtmosphereParameters( current: IResolvedAtmosphereParameters, patch: IAtmosphereParameterPatch, ): IResolvedAtmosphereParametersUse it to
- change scattering coefficients and rebake an atmosphere
Example
atmosphere.setAtmosphere({ rayleigh: [0.008, 0.016, 0.04] });Good to know
- patches cannot introduce omitted, negative, or non-finite physical values
updateClusteredMeshes
Take every clustered mesh under a root through this frame's cut, before the render. The engine already does this for the scene it renders; reach for it only to cut a subtree the engine does not render, such as one staged for a camera of your own.
function updateClusteredMeshes( root:Use it to
- cut a virtual-geometry subtree the engine does not render itself
Example
updateClusteredMeshes(stagedRoot, myCamera, ctx.renderer.domElement.height);updateModelLods
Draw a model at the detail its projected geometric error earns, from a chain the asset cook baked. This is engine-owned, and a game does not call it. assets.lod: {} opts in — the default-on front door opens after qualification — the model pass bakes TN_discrete_lod into eligible models, the loader registers the reader, and the engine runs the selection every frame before it renders. Each frame the mesh picks the cheapest baked level whose measured error projects to fewer than the resolved pixel budget, taking the camera's own projection, zoom, viewport and a conservative nearest depth into account. Refinement is immediate; coarsening waits for the resolved hysteresis. A mesh with no baked chain draws its full geometry.
function updateModelLods( root:Use it to
- draw a vehicle or hull built from many small meshes at distance without its full triangles
- stop a distant model from costing its authored mesh count and triangle count
- one source model, right detail by default, no hand-authored LOD files
Example
// Nothing to call: the loader returns a mesh with the chain and the engine selects every frame.
const hull = await ctx.assets.model("hull.glb");
ctx.scene.add(hull.scene);Good to know
- the chain is baked by the asset cook; there is no runtime generation and no runtime flag
assets.lod: falseopts out globally andassets.lod.overridesper asset, with no runtime controller installed- only static indexed triangles are eligible; skinned, morphed, alpha-blended or authored-LOD meshes keep full detail
- the real gate is measured benefit: a level must save at least
minSaving(20% default) of its predecessor, and a mesh that cannot is skipped, not forced
Options
assets.lod.generation.maxLevels,.minTriangles,.minTrianglesScope,.minSavingand.errorTargetsmove the bake's ceiling, pre-filter, its scope, its saving rule and its error ladder;assets.lod.runtime.maxPixelErrorand.hysteresismove the runtime budget and coarsen band; all by project, preset or asset
useRoughDiffuse
Unreal's Substrate rough diffuse (EON) on standard and physical materials, so direct sun and lamp light meets a rough surface the way Unreal shades it. The same roughDiffuse flag works on three's WebGPU renderer and on the owned engine.
function useRoughDiffuse(root: Object3D, enabled = true): numberUse it to
- shade rough surfaces under a sun or a lamp the way Unreal's Substrate does, not as flat Lambert
Example
useRoughDiffuse(scene);Good to know
- direct light only, indirect light stays Lambert; standard and physical materials; a lamp's
sourceRadiusin metres fades the effect to Lambert at 20 cm; a material changed after its first draw needsneedsUpdate
Options
- material.roughDiffuse = false, or useRoughDiffuse(root, false), puts Lambert back
Also found by
- Substrate EON, Diffuse_EON, Diffuse_GGX_Rough, rough diffuse, Oren-Nayar
validateWorldMatrices
Prove that nothing a cache skipped changed the picture: TN_RENDERLIST_VALIDATE=1 recomputes every world matrix the long way, every frame, and throws on the first element that disagrees with what the frame is about to draw.
function validateWorldMatrices(root: Object3D):Use it to
- prove a static freeze did not leave a stale transform on screen
- gate a scene in CI against silent transform divergence
Example
if (renderListValidationRequested()) console.log(formatValidationReport(report));Good to know
- off by default and expensive by construction — it does the work it is checking, twice
- it throws on the first divergence rather than logging; a validation mode that continues is one nobody reads
- it proves the frames it ran on and nothing else
velocityTexture
Provision screen-space motion data for temporal nodes and keep per-instance history at the frame boundary.
function velocityTexture(pass: IVelocityRenderPass): NodeUse it to
- keep a skinned character or instanced crowd stable in a temporal stage
- add the velocity output to a Three.js scene pass
- read screen-space motion for a temporal stage
Example
const scenePass = pass(scene, camera);
ensureVelocityOutput(scenePass);
renderer.setOutputNode(scenePass);
const tracker = new VelocityTracker();
tracker.update(scene);
renderer.render(scene, camera);
tracker.commit(scene);Good to know
- call
VelocityTracker.update()before the render andcommit()after it - a pass is only given a velocity target when a temporal stage consumes it
VelocityTracker
Provision screen-space motion data for temporal nodes and keep per-instance history at the frame boundary.
class VelocityTrackerUse it to
- keep a skinned character or instanced crowd stable in a temporal stage
- add the velocity output to a Three.js scene pass
- retain previous transforms for animated and instanced renderables
Example
const scenePass = pass(scene, camera);
ensureVelocityOutput(scenePass);
renderer.setOutputNode(scenePass);
const tracker = new VelocityTracker();
tracker.update(scene);
renderer.render(scene, camera);
tracker.commit(scene);Good to know
- call
VelocityTracker.update()before the render andcommit()after it - a pass is only given a velocity target when a temporal stage consumes it
- call
update()after gameplay writes andcommit()after the render
VirtualShadowNode
One directional shadow for a whole open world: camera-centred clip levels, each snapped to its own texel grid and re-rendered only when its window moves. Tracked casters draw into a per-level mover map every frame, so animated casters do not invalidate the cached levels after the one refresh caused by tracking or untracking them. Plugs into three's own light.shadow.shadowNode slot, so every material receives it.
class VirtualShadowNode extends ShadowBaseNodeUse it to
- crisp shadows close to the player across a large outdoor level
- shadow map too coarse over a big terrain
- one directional light shadow for a whole open world
- shadows shimmer when the camera moves
- shadow edges, tree lighting or level sharpness change while a third-person camera turns around its hero
Example
const sun = new DirectionalLight(0xffffff, 3);
sun.castShadow = true;
sun.shadow.shadowNode = new VirtualShadowNode(sun, { clipExtents: [12, 40, 120] });Good to know
- the light must be a DirectionalLight with
castShadowand a target in the scene - clipExtents are half-widths in world units, finest first, strictly increasing
- movers sort themselves: a layer-0 caster whose world matrix, instance matrix or deformation changed draws through the mover maps and leaves the cached levels, and returns to them after
staticAfterFramesquiet frames; the cache redraws only the region it left trackCaster(object)is the override that pins an object as a mover for good (it enables layerVIRTUAL_SHADOW_MOVER_LAYERon the object and its descendants), andpinStatic(object)opts an object out of detection; tracking or untracking refreshes only that object's region- call
object.layers.set(VIRTUAL_SHADOW_CASTER_LAYER)for a mesh that exists only to cast; the level cameras already render that layer and the main camera never does
Options
- bias, biasNode, normalBias, intensity, radius, blurSamples, mapType and filterNode stay on
light.shadow; mapSize and the other options here have defaults, andmarker: falsesilences the TN_VIRTUAL_SHADOW line, not the measurement - bias, biasNode, normalBias, intensity, radius, blurSamples, mapType and filterNode stay on
light.shadow; mapSize and the other options here have defaults - setFocus(point) centres every window on a subject (a third-person hero) instead of the eye, so an orbiting eye moves no shadow; setFocus(undefined) hands them back
- followViewFocus: false keeps eye follow; receiverPlaneBias: false uses only authored bias
- minWindowAspect: below 1, a level is as high as
sin(sun elevation)times its width, never under this, so a low sun's floor shadows keep the texel density of a high sun's; the default 1 keeps square levels
warmUpScene
Warms up scene for camera, in slices, presenting a frame between each. Fail closed on a nonsensical slice size rather than quietly choosing one: a zero or negative slice would loop forever, and a caller that passed it has a bug worth seeing now.
async function warmUpScene( renderer: IWarmUpRenderer, scene: Object3D, camera: Camera, options: IWarmUpOptions =Use it to
- compile a scene's shaders during the loading screen instead of on the first frame
- stop a native launch freezing for seconds inside its first rendered frame
Example
await warmUpScene(renderer, scene, camera, { onProgress: (p) => setLoading(p) });WaterSurface3D
Give a horizontal water surface the world mirrored in it, the world beneath it, and the metres of water between them.
class WaterSurface3DUse it to
- reflect the sky and the shoreline in a lake, pond or river
- see the bed through the water and have the shallows fade at the shore
- know how deep the water is under a pixel without a second render pass
- stop a water surface repeating in visible bands or stripes
- keep a crowd of small actors out of the water's reflection so the frame can afford it
- stop the water reflection redrawing the whole world every frame
- automatically reflect terrain and large casters without redrawing instanced small props
Example
const surface = new WaterSurface3D({ level: 0, maxThickness: 3, reflection: { resolutionScale: 0.5 } });
material.colorNode = mix(surface.refractionAt(offset), surface.reflectionAt(offset), fresnel);Good to know
- it draws nothing; the game supplies the mesh, the material and every colour
- the material must be transparent so the frame beneath it is already drawn
- thickness is metres, saturating at maxThickness; sky behind the surface reads deep
- one reflection is a second draw of the world; resolutionScale is its pixels only
- omitted reflection.layers automatically reflects terrain-sized surfaces and large non-instanced casters, excluding instanced/skinned props; TN_WATER_REFLECTION_DEFAULT reports the set once
- reflection.refreshInterval is in presented frames; 1 is every frame, and the default
- the mirror plane is level, from level alone; do not parent target to a scaled mesh
Options
- reflection.layers is an explicit Three Layers mask and wins over automatic filtering, including layer-0 mask 1; reflection.minSize overrides the default 10 metre minimum extent
WaveField
Evaluate analytic waves on CPU and displace game-owned vertices with the matching TSL graph. wanted, and the warp jacobian, every slope and both allocations are skipped
class WaveFieldUse it to
- float a boat on waves
- make water move
- find the water surface height at a point
Example
const field = new WaveField({ waves });
const { height, normal } = field.sample(x, z, elapsed);
const lift = field.heightAt(x, z, elapsed);Good to know
- supply every wave amplitude, wavelength, direction, speed and warp value
- call setTime for the default graph clock when the game advances its own time
- sample allocates a result and a normal vector; ask heightAt when only the height is
withVelocityContext
Provision screen-space motion data for temporal nodes and keep per-instance history at the frame boundary.
function withVelocityContext<T>(node: T, source: Node): TUse it to
- keep a skinned character or instanced crowd stable in a temporal stage
- add the velocity output to a Three.js scene pass
- hand the provisioned velocity source through a composed temporal graph
Example
const scenePass = pass(scene, camera);
ensureVelocityOutput(scenePass);
renderer.setOutputNode(scenePass);
const tracker = new VelocityTracker();
tracker.update(scene);
renderer.render(scene, camera);
tracker.commit(scene);Good to know
- call
VelocityTracker.update()before the render andcommit()after it - a pass is only given a velocity target when a temporal stage consumes it
WorldEnvironment
The node that says which lighting effects a scene runs and how strong they are, with a fresh Unreal 5.8.3 project's defaults: the filmic tone curve, Unreal-metered auto exposure, screen-space GI and ambient occlusion, SMAA, Unreal's bloom and local exposure. It builds the post chain through renderer.createRenderChain() and prints TN_RENDER_CHAIN naming every stage as applied or refused with a reason. Property names are Godot's Environment where it has one.
class WorldEnvironmentUse it to
- a scene should light and tone map like a fresh Unreal level without wiring each post stage by hand
- turn one lighting effect off, or pick a cheaper tier, for a weak GPU or a stylised look
Example
const world = new WorldEnvironment({ tonemapMode: "aces", autoExposureEnabled: false, exposure: 0.8 }); world.apply(renderer, scene, view);Good to know
- post stages run on WebGPU only: a renderer without it keeps the fixed exposure and reports
TN_AUTO_EXPOSURE_REFUSED, and a missing node library keeps ACES and reportsTN_TONEMAP - an unknown option value throws instead of becoming the default
Options
- every option on
IWorldEnvironmentOptions:tonemapMode: "aces" | "agx" | "neutral",autoExposureEnabled: falsewith a fixedexposure,bloomEnabled,gtaoEnabled,ssgiEnabled,screenSpaceAA
zenithTransmittance
Return direct vertical transmittance for the supplied atmosphere.
function zenithTransmittance( parameters: IAtmosphereParameters | IResolvedAtmosphereParameters, ): AtmosphereRgbUse it to
- check a supplied atmosphere's direct vertical transmittance
Example
const zenith = zenithTransmittance({ rayleigh, mie, ozone, planetRadius, atmosphereRadius });Good to know
- use the returned value as a validation oracle; the rendered path samples the LUT
acceptHotUpdate
Register hot-reload state preservation for a game.
function acceptHotUpdate<TState extends Record<string, unknown>, TPhysics>( game: IGame<TState, TPhysics>, hot: IImportMeta["hot"], ): voidUse it to
- keep game state while editing source in development
- diagnose state shape changes during hot reload
Example
acceptHotUpdate(game, import.meta.hot);Good to know
- use only in the web development entry
assertPortableState
Validate that hot-reload state can cross the Vite boundary.
function assertPortableState(state: unknown): voidUse it to
- preserve JSON-shaped state during hot reload
- reject a non-portable game state before reload
Example
assertPortableState(game.state.getState());Good to know
- state must contain finite numbers and plain objects only
connect
Open a bounded, authenticated WebTransport message channel shared by browser and native games.
function connect(url: string, options: INetworkOptions): Promise<INetworkConnection>Use it to
- connect two game clients over the portable WebTransport seam
- send ordered actions and bounded unreliable state messages between game clients
- exchange multiplayer messages without putting replication or gameplay in the engine
Example
const connection = await connect("https://game.example/game", { applicationProtocol: "my-game/1", credential, channels: [{ id: 1, delivery: "unreliable" }] });Good to know
- the URL must use HTTPS and the credential is supplied by the game's identity flow; this API never issues credentials
- channels, message sizes, and queues are validated before WebTransport opens, and reliable overflow returns false
- native qualification depends on the installed host WebTransport bridge; iOS remains unverified
Options
- connectTimeoutMs, maxReliableMessageBytes, maxQueuedReliableBytes, and maxQueuedDatagrams are named per-connection limits
playtest
Install the playtest bridge into a portable game.
function playtest< TState extends Record<string, unknown> = Record<string, unknown>, TPhysics = undefined, >(options: IPlaytestOptions =Use it to
- expose movement and world observations to a playtest
- connect a game to the ThreeNative scenario runner
Example
const game = defineGame({ plugins: [playtest()] });Good to know
- install once in the game's plugin list
createCssUiRoot
Mount React into a native CSS engine.
function createCssUiRoot(options: ICssUiRootOptions =Use it to
- mount a React HUD on the desktop host with no DOM in the runtime
- write one React component and run it on the web and on the desktop host
Example
const root = createCssUiRoot();
root.render(createElement("section", { className: "fixed inset-0 bg-zinc-900/90" }, "READY"));Good to know
- desktop only, and the game host must be built with the CSS backend (
TN_ENABLE_CSS_UI=1); Android, iOS and web phones render a React HUD in a web overlay instead - import
react, neverreact-dom, from a native entry - styling is CSS resolved by the native engine; JS only mirrors the element tree
createReactOverlay
@threenative/core/react — React that renders on a phone, with no DOM and no WebView. A subpath on purpose. react and react-reconciler are optional peers, and nothing in @threenative/core's main entry imports either of them, so a game that never mounts a React overlay pays nothing and core stays consumable from React Three Fiber. Importing this module is the opt-in. The element vocabulary is two components, borrowed from React Native rather than invented: View is a rectangle, Text is a run of glyphs. They are components and not lowercase intrinsics because view and text are already SVG tags in @types/react, and a HUD element that silently means <svg:text> on one platform is exactly the kind of quiet divergence this path exists to end.
function createReactOverlay(options: IReactOverlayOptions): IReactOverlayUse it to
- render a React HUD on Android or iOS without a WebView
- show the same React component on web and on a phone
- show a React HUD on Android, iOS or desktop native
- render the same React component on web and on a phone without a WebView
Example
const overlay = createReactOverlay({ canvasLayer: ctx.canvasLayer });Good to know
- styling is the
styleprop; Tailwind class names are CSS and cannot cross - import
react, neverreact-dom, from the portable native entry - import
react, neverreact-dom, from a native entry
measureText
Width in pixels of a glyph run at a given cell height.
function measureText(text: string, fontSize: number, letterSpacing = 0): numberUse it to
- measure native React HUD text before laying it out
Example
const scoreWidth = measureText("SCORE 10", 24)supportedGlyphs
Every character this glyph set can draw, for error messages and for the templates' AGENTS.md.
function supportedGlyphs(): stringUse it to
- discover which characters a native React HUD can draw
Example
supportedGlyphs().includes("A")supportedStyleKeys
Every style key the overlay implements, for the templates' AGENTS.md and for error messages.
function supportedStyleKeys(): readonly string[]Use it to
- discover which React HUD style properties work on native
Example
supportedStyleKeys().includes("centerX")Text
A run of bitmap glyphs, drawn as one instanced quad per lit pixel.
function Text(props: ITextProps): ReactNodeUse it to
- show text in a native React HUD without a DOM
Example
<Text style={{ color: "#ffffff", fontSize: 24 }}>SCORE 10</Text>Also found by
- objective panel journal
View
A rectangle. Paints when its style has a background; otherwise it only positions children.
function View(props: IViewProps): ReactNodeUse it to
- group and position native React HUD elements
Example
<View style={{ centerX: true, top: 24 }}><Text>READY</Text></View>cachedEnvironmentSample
The sample this renderer took of scene's environment, if it is still current.
function cachedEnvironmentSample( renderer: object, scene: Scene, ): IEnvironmentSample | undefinedUse it to
- skip a second environment readback in the same frame
Example
const hit = cachedEnvironmentSample(renderer, scene);Good to know
- a sample whose source texture or intensity moved is dropped, so a stale one never reaches a material
cacheEnvironmentSample
Remembers sample as this renderer's reading of scene's environment.
function cacheEnvironmentSample( renderer: object, scene: Scene, sample: IEnvironmentSample, ): voidUse it to
- reuse one environment readback across the materials of a scene
Example
cacheEnvironmentSample(renderer, scene, sample);captureEnvironmentSnapshot
The provenance of a scene's environment: which texture, at which intensity, in which colour space.
function captureEnvironmentSnapshot(scene: Scene): IEnvironmentSourceSnapshotUse it to
- reject an environment readback that belongs to a different sky
Example
const snapshot = captureEnvironmentSnapshot(scene);environmentSnapshotCurrent
Whether the scene's environment still matches the snapshot a sample was taken from.
function environmentSnapshotCurrent( scene: Scene, snapshot: IEnvironmentSourceSnapshot, ): booleanUse it to
- hold a material's fill light to the sky that is on screen now
Example
if (environmentSnapshotCurrent(scene, snapshot)) draw(snapshot);isWebGLFallbackRenderer
Whether a WebGPURenderer wrapper is running three's WebGL backend behind it.
function isWebGLFallbackRenderer(renderer: unknown): booleanUse it to
- refuse a GPU-only lane on a WebGL fallback instead of drawing something wrong
Example
if (isWebGLFallbackRenderer(renderer)) skipMaterialLane();materialLightingEnabled
Whether tier may run the material-lighting lane in environment.
function materialLightingEnabled( tier: QualityTier, environment: IMaterialLightingEnvironment, ): booleanUse it to
- decide whether this renderer is the admitted material lane
Example
if (materialLightingEnabled("high", env)) lightMaterials();Good to know
- high tier, browser, hardware WebGPU, not mobile, not software, not a WebGL fallback
measureEnvironment
The environment measure-and-sample mechanism every kit repeats: what the scene's environment actually contributes, a bounded GPU sample of it with a cache and a readback deadline, the provenance a stale readback is rejected by, and the gate that decides which renderer may run the material lane. The backlight itself is a shader with fixed constants, so it stays in each kit's src/render/ (stamped from one source there) where the game can change how it looks. This is machinery, not a look: every colour, gain and threshold arrives as an argument, and a kit that wants a different bound passes a different one. It lives here because twelve kits held byte-identical copies — 9 084 lines — so a fix to one left eleven wrong with every gate green (c93b427d0 touched 552 files for one look change).
function measureEnvironment(scene: Scene, maxSourceTexels: number): IEnvironmentMeasurementUse it to
- measure what a scene's environment actually contributes
- sample the environment on the GPU without stalling the frame
- keep an environment readback from reaching a frame it does not belong to
Example
const m = measureEnvironment(scene, 2048);reportEnvironmentContribution
The environment measure-and-sample mechanism every kit repeats: what the scene's environment actually contributes, a bounded GPU sample of it with a cache and a readback deadline, the provenance a stale readback is rejected by, and the gate that decides which renderer may run the material lane. The backlight itself is a shader with fixed constants, so it stays in each kit's src/render/ (stamped from one source there) where the game can change how it looks. This is machinery, not a look: every colour, gain and threshold arrives as an argument, and a kit that wants a different bound passes a different one. It lives here because twelve kits held byte-identical copies — 9 084 lines — so a fix to one left eleven wrong with every gate green (c93b427d0 touched 552 files for one look change).
function reportEnvironmentContribution( scene: Scene, options: IContributionControls, measurement?: IEnvironmentMeasurement, )Use it to
- measure what a scene's environment actually contributes
- sample the environment on the GPU without stalling the frame
- keep an environment readback from reaching a frame it does not belong to
Example
reportEnvironmentContribution(scene, {
darkThreshold: 0.02, fillAdmitted: true, fillColor: new Color(1, 1, 1), fillGain: 0.4,
maxSourceTexels: 2048, rimGain: 0.6,
});sampledRadiance
The mean radiance and colour of a bounded linear sample, or unknown with the reason.
function sampledRadiance(samples: unknown, intensity: number): IEnvironmentMeasurementUse it to
- turn an environment readback into the radiance a material's fill light needs
- know why an environment sample could not be measured
Example
const m = sampledRadiance(readback, 1);Good to know
- the sample must be the qualified 64x32 float RGBA readback; anything else is refused by name
sampleEnvironment
Measures and samples the scene's real environment on the GPU, bounded by a readback deadline.
async function sampleEnvironment( renderer: unknown, scene: Scene, environment: IMaterialLightingEnvironment, ): Promise<IEnvironmentSample>Use it to
- measure what a scene's environment actually contributes without stalling the frame
- give a material's fill light the environment's own radiance
Example
const sample = await sampleEnvironment(renderer, scene, env);Good to know
- off unless the renderer is the admitted high-tier WebGPU lane; every refusal is reported by name
- the readback is abandoned after the deadline and the frame keeps the previous answer
samplingSourceSupported
Whether an environment texture's mapping and colour space are qualified for the bounded GPU sample.
function samplingSourceSupported(source: NonNullable<Scene["environment"]>): booleanUse it to
- know why an environment was not sampled on the GPU
Example
if (samplingSourceSupported(source)) sample(source);CastPool
Step a spell's timeline: charge, release, travel, impact, linger, done.
class CastPoolUse it to
- a fireball or a lightning bolt that charges, flies, lands and lingers
- several spells mid-flight, with no allocation per cast
Example
const casts = new CastPool(world);
casts.cast(fireball, target, { from: hand });
casts.update(dt);Good to know
- the pool is fixed and recycles the cast alive longest; it never grows
- a ball that has passed its target lands on the target, however late the frame notices
Options
- timing, shape, speed and radius come from the spell; a cast may override shape and seed
createAegis
A ward around the caster: it forms, holds, and breaks outward when it expires.
function createAegis(world: SpellWorld, overrides: IFireSpellOverrides =Use it to
- a shield spell a player casts on themselves
- a magic barrier that forms around the caster
- make a protective bubble spell
- a defensive bubble that flashes when it breaks
Example
const aegis = createAegis(world);
casts.cast(aegis, world.focus);Good to know
- every colour, size, count and timing is a named override on the call
Options
- core, highlight, charge, impact, linger, radius, light
- core, highlight, charge, impact, linger, radius, light, shake
createArcaneBarrage
A volley of arcane missiles: fast, precise, and each one pops on arrival.
function createArcaneBarrage(world: SpellWorld, overrides: IFireSpellOverrides =Use it to
- an arcane missile spell that fires projectiles at a target
- a magic barrage a mage class spams
- a magic missile spell
- make an arcane bolt spell
- an arcane missile spell that fires several projectiles at a target
- a pink energy bolt with a short charge
Example
const barrage = createArcaneBarrage(world);
casts.cast(barrage, target);Good to know
- every colour, size, count and timing is a named override on the call
Options
- core, highlight, speed, charge, impact, linger, radius, burst, light
createFireball
A ball of fire that charges, crosses the room and leaves the floor burning.
function createFireball(world: SpellWorld, overrides: IFireSpellOverrides =Use it to
- a fireball spell the player casts at an enemy
- a burning projectile that explodes and scorches the ground
- a wizard's fire attack with a wind-up, a flight and an aftermath
- make a fireball
- a fireball spell a player casts at an enemy
Example
const fireball = createFireball(world);
casts.cast(fireball, target);Good to know
- every colour, size, count and timing is a named override on the call
- the first cast costs what the hundredth does: nothing is built at cast time
- the stock look ships as the default, and no override rebuilds a pipeline
Options
- core, highlight, speed, charge, impact, linger, radius, burst, trail, lingerBurst, light, shake, scorch
createGlacialSpike
A shard of ice that flies flat and fast, and freezes the ground it breaks on.
function createGlacialSpike(world: SpellWorld, overrides: IFireSpellOverrides =Use it to
- an ice spike spell that flies at a target and shatters
- a freezing projectile that leaves frost on the floor
- make an ice spell
- a cold spell with a charge, a flight and a lingering chill
Example
const spike = createGlacialSpike(world);
casts.cast(spike, target);Good to know
- every colour, size, count and timing is a named override on the call
Options
- core, highlight, speed, charge, impact, linger, radius, burst, trail, light
createInferno
A pillar of fire that erupts where it lands and keeps burning.
function createInferno(world: SpellWorld, overrides: IFireSpellOverrides =Use it to
- a fire area spell that erupts at a point and burns there
- an inferno column a boss drops on the arena
- make a sustained fire area spell
- a sustained flame that scorches the ground for seconds
Example
const inferno = createInferno(world);
casts.cast(inferno, target);Good to know
- every colour, size, count and timing is a named override on the call
Options
- core, highlight, charge, impact, linger, radius, burst, trail, light, shake, scorch
createSpell
Build a spell from a recipe: four beats, a tint, and the numbers between them.
function createSpell(world: SpellWorld, recipe: ISpellRecipe): ISpellUse it to
- author a spell the catalog does not cover, out of the same beats
Example
const spell = createSpell(world, recipe);Good to know
- read the world through SpellWorld only, so a game can swap the scene and the floor
createThunderstrike
A bolt out of the sky: it charges, strikes the point instantly, and the ground remembers it.
function createThunderstrike(world: SpellWorld, overrides: IFireSpellOverrides =Use it to
- a lightning strike spell that hits a point immediately
- a thunderbolt with a wind-up and a burnt mark where it lands
- make a lightning spell
- an electrical spell with a column of light from above
Example
const bolt = createThunderstrike(world);
casts.cast(bolt, target);Good to know
- every colour, size, count and timing is a named override on the call
Options
- core, highlight, charge, impact, linger, radius, light, shake, scorch
ParticleKindTable
Tune what a particle kind does, as data rather than a shader.
class ParticleKindTableUse it to
- retune a spell's particles at run time from a settings screen
- change how long, how fast or how heavy a kind of particle is without a new pipeline
Example
const kinds = new ParticleKindTable(["flame", "smoke"]);
kinds.set("flame", { lifetime: [0.3, 0.6], colour: [0.4, 0.8, 1] });Good to know
- set writes uniforms; no kernel, material or pipeline is rebuilt
- a table knows only the kinds it was asked for, so an unused kind costs nothing
Options
- lifetime, size, speed, cone, gravity, drag, buoyancy, alpha, colour and highlight
ReactionField
The marks a spell leaves on the floor: heat, char, wet, frost, crack and glow.
class ReactionFieldUse it to
- a fireball impact that leaves a scorch and fades over time
- ice that melts where lightning spread, or a lava geyser's crack
Example
field.splat({ heat: 1, char: 0.6, radius: 2.5, x: hit.x, z: hit.z });
field.update(dt);Good to know
- it draws nothing; the game decides what a mark looks like
- the patch is finite and every channel decays on its own half-life
Options
- halfLife, resolution and size tune the patch; pattern, radius, seed and angle set each mark
SpellLights
A fixed pool of spell lights, created once at zero intensity.
class SpellLightsUse it to
- a spell impact that glows without changing the light count
- a charge glow or a falling meteor lighting what it passes
Example
lights.flash({ x, y, z, color, intensity: 40, range: 12, seconds: 0.35 });Good to know
- the whole pool exists before the first cast; a cast changes intensity, never the list
- flash returns undefined when the pool is busy; a spell carries on without one
Options
- count is the pool size; each flash supplies position, colour, intensity, range and seconds
SpellWorld
Everything a spell may touch: the scene, the floor, the light pool, the surface field, one shake and one flash limiter.
class SpellWorld implements ICastEnvironmentUse it to
- cast an engine spell without passing a scene into every call
- honour an accessibility setting that limits flashing
Example
const world = new SpellWorld({ scene, groundAt });
const casts = new CastPool(world);Good to know
- damage, mana, cooldowns and who the target is stay in the game
- with reducedFlashes on, a fourth flash inside one second is refused, never dimmed
Options
- groundAt, castSlots, lightCount, reaction, shake and reducedFlashes are named options
bakeNoise
CPU bake of the Ultra Elements 3D noise, curl and blackbody textures that every spell volume samples.
function bakeNoise(Use it to
- the noise and blackbody textures an Ultra Elements spell needs before it first draws
Example
bakeNoise({ noiseSize: 64 }); // once at load, before createFx drawsGood to know
- costs about 0.6 s at 64^3 and about 5 s at 128^3 on the main thread; bake once at load
createFx
The shared Ultra Elements spell world: casts, volumes, spell lights and the per-frame CPU tick. Add fx.scenes.fx to the scene, addSpell each ported spell, call renderFrame(dt) each frame.
function createFx(o: IFxOptions)Use it to
- an Ultra Elements spell such as the raymarched teardrop Fireball cast at a target
- a volumetric fire spell drawn through the Three.js TSL node API on WebGPU
Example
const ultra = createFx({ camera, size: () => ({ width: innerWidth, height: innerHeight }), seed: 777 }); const fireball = ultra.addSpell(fire); scene.add(ultra.fx.scenes.fx);Good to know
- call bakeNoise first: the volume shaders sample its noise, curl and blackbody textures
groundShade
The Ultra Elements arena floor's response to the ground field and spell impacts (scorch, char, wet, glowing hot ground) as nodes for a game's own floor material: color, roughness, metalness, emissive from the floor's own surface at a world position.
function groundShade(wp: V3, surface: IGroundSurface)Use it to
- a floor that shows the Fireball's scorch and hot ground cooling over seconds
Example
const shade = groundShade(positionWorld, { albedo, rough: float(0.85), metal: float(0) }); floor.colorNode = vec4(shade.color, 1);Particles
The Ultra Elements GPU particle system behind fx.particles: a spell's kinds, emitters and field emitters.
class ParticlesUse it to
- the flames, embers, sparks, smoke and debris an Ultra Elements spell emits as it charges, flies and hits
Example
const flames = ultra.fx.particles.emitter("fire.flame"); // ultra from createFxconnectUiBridge
Open the message channel between a game and its UI, whatever host is underneath.
function connectUiBridge(options: IConnectOptions): IUiBridgeUse it to
- write a UI that talks to the game on web and on a phone alike
- send a message from a HUD rendered over the game surface
- connect game code to a platform-owned UI realm
- share one UI bridge implementation across web, Android, iOS, and desktop
Example
const bridge = connectUiBridge({ end: "ui" });Good to know
- the transport is discovered, never configured; no game names the web view
onUiIntent
Handle the actions a UI sends back to the game.
function onUiIntent( bridge: IUiBridge, listener: (intent: string, payload: unknown) => void, ): () => voidUse it to
- restart or pause a game from a button in its HUD
- handle a HUD button action in game code
- route native and web UI commands through one listener
Example
onUiIntent(bridge, (intent) => { if (intent === "restart") game.goto("Play"); });Good to know
- prefer game.ui.onIntent, which connects the bridge for you
publishHitRegions
Tell the native input host where a UI's touchable controls are.
function publishHitRegions(options: IRegistryOptions): IHitRegionRegistryUse it to
- let a touch on empty HUD space reach the game instead of the UI
- make a HUD button receive taps on a phone
- give native input hosts the rectangles claimed by UI controls
- keep touch hit testing aligned with a moving web or native HUD
Example
publishHitRegions({ bridge });Good to know
- mark controls with data-tn-interactive; pointer-events is not the mechanism
publishUiState
Publish the game's state so a UI in another process can mirror it.
function publishUiState<T>( bridge: IUiBridge, store: IPublishableStore<T>, options: IPublishOptions =Use it to
- show score or health in a UI rendered over the game surface
- keep a HUD in step with the game without re-rendering on the loop
- publish game state to a HUD in another realm
- keep a web and native UI mirror on the same coalesced state stream
Example
publishUiState(bridge, game.state);Good to know
- publishes once per rendered frame unless stateFlushMs selects a slower interval, and not at all with no UI listening
Also found by
- journal objective panel
- readable HUD
sendUiIntent
Send a player action from the UI back to the game.
function sendUiIntent(bridge: IUiBridge, intent: string, payload?: unknown): voidUse it to
- wire a Restart button in a HUD to the running game
- pause a game from a menu drawn over its surface
- send a button or menu action from a UI HUD to game code
- keep UI input portable across web and native hosts
Example
sendUiIntent(bridge, "restart");Good to know
- one-way; the game decides what each name means and may ignore one
subscribeUiState
Mirror the game's published state on the UI side.
function subscribeUiState<T>(bridge: IUiBridge): IUiStateMirror<T>Use it to
- read game state from a HUD that runs in the platform's web view
- read published game state from a UI HUD
- subscribe a web or native UI to the game's mirrored state
Example
const mirror = subscribeUiState(bridge);Good to know
- returns undefined until the game publishes its first state
serveWorkerGame
Runs inside the worker: wire the page's messages to the unchanged portable game. Call it last in the worker entry, after the game module evaluated: it posts the ready message the page waits for before it sends the canvas.
function serveWorkerGame( game:Use it to
- run the game loop in a web worker so a busy page cannot stall its frames
Example
serveWorkerGame(game);startWorkerGame
Runs on the page: own the canvas and the DOM, and feed the worker game. Call it before the UI mounts: the HUD's bridge host globals exist from this call on.
function startWorkerGame( worker: Worker, container: HTMLElement, ):Use it to
- host a worker-run game's canvas, input and HUD on the page
Example
const handle = startWorkerGame(new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }), root);AdmissionBudget
One frame's admission allowance, shared by every path that puts streamed content on screen. A streaming world has no frame-time ceiling anywhere else: a cell row arriving builds a batch per asset run over every placement in it, a terrain tile builds every LOD level, and the game's createCollider runs for every resident tile — all in the one frame that discovers them. That is the 100-330 ms hitch a 60 m/s camera feels every time the ring moves, and it is admission cost, not streaming: the loads never fail. The budget is opened once per update and drawn down by the units it admits. A unit always finishes, so a frame spends at most the limit plus the unit that crossed it, and the rest of the backlog waits for the next frame rather than being dropped.
class AdmissionBudget implements IAdmissionBudgetUse it to
- streamed terrain tiles or cells hitch the frame that admits them
- cap how many milliseconds a frame spends building streamed content
Example
tiles.follow(player.position, new AdmissionBudget(2, () => performance.now()));Good to know
- open a new budget each frame; a unit always finishes, so one unit can cross the limit
applyTerrainSurface
Apply a cooked GLB's package-authored layered surface to its marked terrain meshes. url is the loaded GLB URL; extras pointers are relative to it. Uses the same asset/fetch path as loadTerrainSplat on web and native. The caller owns the assigned materials' lifetime.
async function applyTerrainSurface( root: Object3D, options: ILoadTerrainSplatOptions, ): Promise<void>Use it to
- apply the authored layered terrain surface after loading a cooked world GLB
Example
await applyTerrainSurface(world.scene, { assets: ctx.assets, renderer: ctx.renderer, url: "world/world.glb" });Good to know
- url names the loaded GLB; tnTerrainSurface extras name a relative world package JSON
Options
tablemay replacebase,breakup,macroandlayers; bakedsplatandtexturesstay package-owned
bakedFractalNoise
Drop-in for mx_fractal_noise_float(p, octaves, lacunarity, diminish, amplitude): one read an octave.
function bakedFractalNoise( p: Node<"vec3">, octaves = 3, lacunarity = 2, diminish = 0.5, amplitude: Scalar = 1, ): Node<"float">Use it to
- fractal or fbm noise in a material costs too much GPU time per pixel
Example
const macro = bakedFractalNoise(vec3(positionWorld.x, 0, positionWorld.z).mul(0.014), 3);Good to know
- octaves is a build-time number; each octave is one filtered volume read
bakedNoise
Drop-in for mx_noise_float(p, amplitude, pivot) on a vec3 p: one filtered read of the baked volume instead of the per-pixel Perlin. Only the 3D form: three's 2D Perlin is another function (0.66 scale), so a vec2 caller keeps mx_noise_float. channel 1 to 3 are independent fields.
function bakedNoise( p: Node<"vec3">, amplitude: Scalar = 1, pivot: Scalar = 0, channel: 0 | 1 | 2 | 3 = 0, ): Node<"float">Use it to
- a terrain, foliage or water shader calls mx_noise_float per pixel and the frame is GPU bound
- open world ground material with procedural variation that must hold 60 FPS
Example
const patch = smoothstep(-0.35, 0.35, bakedNoise(positionWorld.mul(0.025)));Good to know
- the field tiles every NOISE_PERIOD units of p; at p = world metres x 2.6 that is a 3 m repeat
- vec3 input only: three's 2D Perlin is another function
Options
- keep mx_noise_float where exact analytic noise matters more than the frame
baseRingGap
The highest gap between a wide model's rim and the ground, one sample per angular sector: in each sector, the lowest vertex beyond rim of that sector's reach. A narrow buried stem then cannot hold a wide base up in the air on the downhill side. Sink the pose by gap (plus any burial the game wants) to close it.
function baseRingGap( geometry: BufferGeometry, matrix: Matrix4, ground: StaticGroundQuery, options:Use it to
- a cliff or crag model rests on a buried stem while its wide base hangs over the downhill ground
Example
const ring = baseRingGap(geometry, matrix, ground); if (ring.samples >= 4) matrix.elements[13] -= ring.gap + 0.5;Good to know
- throws
TN_STATIC_POSE_GROUNDwhere the ground does not answer; checksamplesbefore trustinggap
cellPlacements
Borrow the run's placement records as a live view over the placement buffer.
function cellPlacements(placements: ArrayBuffer, run: IWorldRun): Float32ArrayUse it to
- feed one cell's instance transforms into a batch without copying
Example
const records = cellPlacements(buffer, { asset: "tree", offset: 0, count: 120 });Good to know
- the returned view aliases the caller's buffer; writing to it mutates the source
footprintGap
How far the flat underside of a static geometry rises above the ground at its highest point. Snapping the lowest point leaves the downhill side of a flat-bottomed rock hanging; sinking the pose by this much buries the whole footprint. Returns 0 when the footprint is already buried.
function footprintGap( geometry: BufferGeometry, matrix: Matrix4, ground: StaticGroundQuery, margin = 0, ): numberUse it to
- a rock snapped to a slope shows a lip or a gap under its downhill side
Example
matrix.elements[13] -= footprintGap(geometry, matrix, ground, 0.08);Good to know
- the footprint is every vertex at the geometry's lowest local y; throws
TN_STATIC_POSE_GROUNDwhere the ground does not answer
getWorldCapabilities
Resolve the active world-generation path from host capability facts. The function accepts the adapter facts instead of reaching through a renderer-specific global, so browser and native hosts can report the same object. Missing limits are not treated as infinite: a host must either provide a valid GPU limit report or explicitly choose CPU fallback. GPU generation remains unavailable until a GPU readback can own the canonical field; a host adapter report therefore never upgrades a CPU fallback into a GPU generation claim.
function getWorldCapabilities(options: IWorldCapabilitiesOptions =Use it to
- decide whether generated terrain can use GPU compute
- report why terrain generation is using a reduced CPU fallback
Example
const capabilities = getWorldCapabilities({ limits: adapter.limits, cpuFallbackIterations: 8 });Good to know
- unsupported is returned when compute limits are unknown or below the requirement; callers must not silently continue
Options
- minimumWorkgroupsPerDimension, minimumStorageBufferBindingSize, and cpuFallbackIterations
Heightfield
One height buffer shared by world queries, rendered geometry, and a physics heightfield. The game supplies every value, so changing the terrain's shape never requires a package edit. fromSampler evaluates that game function exactly once at each vertex and retains only the resulting numbers. Queries interpolate those same numbers instead of evaluating the function again.
class Heightfield extends Group implements IComputeDrivenUse it to
- build terrain geometry and collision from one game-authored height function
- generate a terrain a player can walk across
- query the same ground height or normal that a player sees and collides with
- ask how high the ground is here
- build islands and coastlines from terrain
- keep a collider or other copy of a deforming terrain in step without rescanning the whole field (
trackChanges)
Example
const field = Heightfield.fromSampler({ rows: 65, columns: 65, width: 64, depth: 64, origin: { x: 0, z: 0 }, sampleHeight: terrainHeight });Good to know
- sampleHeight owns the terrain shape and stays in game source; the framework stores and interpolates its output
- rows and columns are vertex counts; geometry is row-major z-then-x and collider export transposes once into Rapier's column-major matrix order
Options
- rows, columns, width, depth, origin, and sampleHeight are explicit on every field
HeightfieldCollar
A heightfield's far ring: rings square rings past its playable square, one vertex per boundary sample, and the index grid that draws them.
class HeightfieldCollarUse it to
- draw the terrain past the playable square without hand-building a ring grid
- ground a character past the square, out to the walk band, on drawn triangles
Example
const collar = new HeightfieldCollar({ resolution: 129, size: 512, rings: 384, ringDistance: (ring) => (ring / 384) ** 1.65 * 2100, walkBand: 200, height: ({ x, z }) => surveyed.heightAt(x, z) });Good to know
- every ring vertex asks the game's
heightcallback; core owns no terrain look - the collar is a ring of triangles, not a field:
heightAtanswers on it and null off it
heightSamplerFromHeightmap
Build a game-usable sampleHeight from a raw v1 heightmap. The returned function interpolates bilinearly in world units and clamps to the map edges, so it plugs straight into Heightfield.fromSampler and TerrainTiles. Height is heightMin + v / 65535 * (heightMax - heightMin) at vertex (column, row).
function heightSamplerFromHeightmap( terrain: IWorldTerrain, extent: IWorldExtent, data: Uint16Array, ): (x: number, z: number) => numberUse it to
- turn an exported raw heightmap into terrain collision and rendering
- query ground height from a Blender-authored world package
Example
const sampleHeight = heightSamplerFromHeightmap(terrain, extent, await loadWorldHeightmap(url));Good to know
- the sampler reads the game's data; the framework never selects a terrain shape
instanceRandom
A random in [0, 1) that stays with its instance, as UE 5.8.3's PerInstanceRandom: hashed from the instance's world origin, never from its draw slot. WorldCells repacks instances on every refilter, main-pass cull and LOD switch, so instanceIndex names another tree from one frame to the next; a wind phase hashed from it re-rolled each crown about every 0.7 s of a walk and snapped its top by a median 0.37 m. Parts of one placement share its translation, so its bark and needles read one value.
function instanceRandom(): Node<"float">Use it to
- a per-instance random number that stays with each streamed placement as WorldCells repacks
- replace instanceIndex in a WorldCells part material, which WorldCells refuses
Example
const phase = instanceRandom().mul(6.2831);lakeReach
How far a lake's water reaches: the waterline its basin measures, margin times out, capped. The drawn surface and the swim footprint both size themselves here, so the shore a player sees is the shore they stop at.
function lakeReach(field: Heightfield, lake: IWaterLake): numberUse it to
- size a lake's footprint from its basin and the cap its biome row names
Example
const reach = lakeReach(field, { ...lake, margin: 1.12 });Good to know
- reads the heightfield at every bearing, once per lake, never per frame
lakeSurfaceGeometry
A lake's water surface: a level disc out to lakeReach, the footprint WaterBodies floods, with a metres attribute (water depth over the ground). Only cells with a corner the seed's water reaches get triangles, so the surface does not hover over dry hillside, a hollow past the basin's rim (a river valley beyond the dam) stays dry instead of standing under a sheet that stops where the reach does, and the shore follows the ground's contour. The rings pack towards the middle, so an irregular basin costs vertices where the camera sees them. Returns undefined when the basin holds no water at its level.
function lakeSurfaceGeometry( lake: IWaterLake, field: Heightfield, options: ILakeSurfaceOptions =Use it to
- draw a lake's water surface from the baked level and seed
- a lake's drawn water and the swimmer's water disagree
- lake water ends in a straight edge over a valley past the basin's rim
Example
const geometry = lakeSurfaceGeometry({ ...lake, margin: 1.12 }, field, { maxDepth: 1.6 });Good to know
- the lake row and field come from the game's bake; the game's material shades the geometry
loadTerrainSplat
The splat terrain surface a world package describes, for WorldCells.load({ surface }). Layers blend over a base by mask channels read as linear data (the masks ship raw, beside the heightmap, so no cook moves a blend threshold), with noise-broken edges and macro brightness variation. Texture sets tile in world metres on the package's ground plane (x, -z: a Z-up authoring tool's x and y), cliffs can be triplanar, and the base plus any layer that asks carries a normal map. Each layer answers light from its own ORM map where the table ships one and from the table's own roughness and metalness where it does not; a layer that states neither is matte and dielectric, and named in a warning. Nothing here is a look choice: textures, tiles, tints, thresholds, surface response and noise scales all come from the package's table, which the game authors once and its DCC shares.
async function loadTerrainSplat(options: ILoadTerrainSplatOptions): Promise<Material>Use it to
- terrain textured by splat masks exported from Blender with the world package
- the game's terrain should match the DCC's terrain material without a second copy
Example
const surface = await loadTerrainSplat({ assets: ctx.assets, renderer: ctx.renderer, url: "world/world.json" });
const world = await WorldCells.load({ assets: ctx.assets, url: "world/world.json", surface, follow, ring: 2 });Good to know
- the package's world.json must carry
terrain.layers.tableandterrain.layers.splat, written byexport_terrain_layersin theexport_world.pyrecipe - WebGPU allows 16 sampled textures per stage: same-size layers stack into one array texture per set, and
TN_TERRAIN_SPLAT samplers=<n>reports what is left
Options
tablemay replacebase,breakup,macroandlayersfrom game source; bakedsplatandtexturesstay package-owned
loadWorldHeightmap
Fetch a raw little-endian uint16 heightmap and expose it as samples.
async function loadWorldHeightmap(url: string): Promise<Uint16Array>Use it to
- load a world package's heightmap once before building terrain
Example
const data = await loadWorldHeightmap("/world/terrain/heightmap.u16");Good to know
- a non-OK response throws; bytes are byte-swapped only on a big-endian host
meshSections
A mesh's material sections: one per geometry group for a material array, else the whole mesh. Instanced props draw one batch per material, so an imported model splits here first.
function meshSections(mesh: Mesh): IMeshSection[]Use it to
- scatter or instance an imported glTF model that has several materials
Example
for (const section of meshSections(mesh)) parts.push(sectionGeometry(mesh, box, section));Good to know
- a section's
materialcan beundefinedfor a group naming a missing material slot; skip it
noiseVolume
The one volume every material shares: baked on first use, 1 MiB of RGBA8 (it stays in L2).
function noiseVolume(): Data3DTextureUse it to
- a material needs the raw baked noise texture to sample in its own TSL
Example
const volume = noiseVolume();Good to know
- baked once per page on the main thread (about 0.15 s); every channel is an independent field
repairZeroNormals
Recompute the normals of a geometry whose normals are missing, zero or not finite, and leave authored normals alone. Some exported art ships zero normals and draws black under any light. Run it after any reshape, so the recomputed normals fit the final shape.
function repairZeroNormals(geometry: BufferGeometry): booleanUse it to
- an imported model draws black or unlit because it ships zero normals
Example
geometry.scale(1.1, 1, 1.1); repairZeroNormals(geometry);Good to know
- one bad normal recomputes them all; an intentionally hard-edged model loses its authored split normals only if one is bad
riverRibbonGeometry
The water surface of every river, as one geometry with one group per river. Each station is a row across the river at its own surface height, out to reach widths either side of the centreline, the reach WaterBodies floods; one more row a reach past each end stands where WaterBodies clamps a segment, so the water a swimmer finds past a river's end is drawn there too (cut at the end station, the surface stopped in a straight edge with its carved bed dry beyond). Quads dry on both rows against field are dropped, so the surface ends at the shore. Past an end where the ground falls below the end's bed, the water would run off: that cap is not drawn, and the end stays cut at its last station. Attributes for the game's water material: flow (the unit downstream heading), flowUv (metres down the centreline, metres across it) and metres (water depth over the ground). It decides no colour, ripple or opacity: the game shades it.
function riverRibbonGeometry( rivers: readonlyUse it to
- draw a river's water surface from the baked stations
- a river's water stops in a straight edge, or a swimmer floats where no water is drawn
- share one river shape between the drawn water and the swimmer
- river water hangs over dry ground past the river's head or tail
Example
const geometry = riverRibbonGeometry(rivers, field, { maxDepth: 1.6 });Good to know
- stations, width and reach come from the game's bake; the game's material shades the geometry
sectionGeometry
One section's geometry in model space, standing on y = 0. Every section of a model takes the same base from the whole model's box, so a crown keeps its place on its trunk: basing each section on its own bounds detaches them. The mesh's LOD0 geometry is cloned under its world matrix, and a group becomes the clone's draw range.
function sectionGeometry( mesh: Mesh, box: Box3, section: IMeshSection, options:Use it to
- the crown of an instanced tree floats off its trunk, or the parts of a model separate
- turn each part of an imported model into a geometry for an instanced prop batch
Example
const box = new Box3().setFromObject(root); const geometry = sectionGeometry(mesh, box, section);Good to know
boxis the whole model's world bounds after any unit normalisation; callmesh.updateWorldMatrixfirst
shoreField
Distance to the shore and open-sea exposure for every node of a square height grid, measured once from the bake. distance is a two-pass chamfer distance to the nearest node at or above level (0 on dry ground). exposed floods from the grid's edge through water deeper than openDepth, then carry metres further into shallow water, so a sheltered lagoon behind a sand bar stays out of it. Both feed the game's surf and shore masks; neither decides a colour.
function shoreField( heights: ArrayLike<number>, resolution: number, size: number, level: number, options: IShoreFieldOptions =Use it to
- surf breaks only on water open to the sea, not in a sheltered lagoon
- distance from each water cell to the shore, for a foam or depth mask
Example
const { distance, exposed } = shoreField(world.heights, world.resolution, world.size, world.waterLevel);Good to know
- heights are row-major,
resolutionbyresolution, acrosssizemetres; measured once, never per frame
snowDiscFootprint
A circular contact footprint, sized from a radius the caller measures. The shape a sphere, a ball, a wheel or a probe presses into snow, and the default the physics binding derives from a sphere's contact geometry. Flat inside the radius, eased over the softness band, with a raised rim just outside it.
function snowDiscFootprint( radius: number, options: ISnowDiscFootprintOptions =Use it to
- press a ball, wheel or probe into snow
- give a sphere a physically sized snow contact instead of a boot shape
Example
const footprint = snowDiscFootprint(0.25);Good to know
- radius is metres; the footprint never grows with load, only deeper
Options
- softness widens the eased edge without changing the contact radius
SnowField
Persistent snow deformation over one canonical heightfield. Snow keeps four channels per cell — indentation, displaced bank, compaction and disturbance — and writes the combined surface (terrain + depth + bank - indent) back into the heightfield it was given. Queries, rendered geometry and collider export therefore all read one surface, and no second terrain representation exists. The field is numeric only: it never chooses a boot, a tread, a particle, a material or a camera. Games supply terrain heights, the snow depth, the contact profile and the response coefficients; this class owns the storage, the load-dependent penetration and the bounded recovery. It is a heightfield approximation — not granular snow, displaced-volume conservation, avalanches, melting or a calibrated material law.
class SnowFieldNeeds
- @threenative/core/world Heightfield as the canonical terrain and surface
Use it to
- leave footprints, tracks and tyre ruts in snow that persist and fill in over time
- let a fresh snowfall slowly fill older tracks back in as the field recovers
- let a pushed sphere carve a connected track and a dropped one settle into a crater
- store snow deformation that rendered geometry and collision both read
- reset a snowfield between rounds or change its depth at runtime
- show how packed the snow is where people have walked or objects have rested
Example
import { Heightfield } from "@threenative/core/world";
const terrain = Heightfield.fromSampler({ rows: 129, columns: 129, width: 64, depth: 64, origin: { x: 0, z: 0 }, sampleHeight: (x, z) => Math.sin(x * 0.1) * 0.5 });
const snow = new SnowField({ field: terrain, depth: 0.28, hardness: 0.3 });
snow.stamp({ x: 0, z: 0, area: 0.074, load: 784, duration: 0.1, footprint: snowDiscFootprint(0.12) });
snow.recover(1 / 60, 0.0012, 0.4);Good to know
- the field composes onto a Heightfield; construct the terrain first and let this own the surface
- zero depth is bare ground: contacts register no indentation at all
- out-of-region heightAt and normalAt follow Heightfield's error contract; sample returns zeros
Options
- depth, hardness, yieldFraction, maxBank and responseTime name the response coefficients
staticLowestY
Exact lowest world Y of a static geometry under matrix, the precise measurement GroundSnap audits against, cheap enough for a load that poses hundreds of thousands of props. An upright pose reads the bounding box. A tilted pose scans the vertices bottom first (sorted once per geometry) and stops once no later vertex can be lower: |x e1 + z e9| <= reach * hypot(e1, e9).
function staticLowestY(geometry: BufferGeometry, matrix: Matrix4): numberUse it to
- stand a scattered rock, tree or crate on the ground by its lowest point, not its origin
- props hover or sink because their pivot is not at their base
Example
placed.position.y += ground - staticLowestY(geometry, matrix);Good to know
- static geometry only; a skinned model uses
GroundSnap; the sort is cached per geometry, so do not mutate its positions
surfaceSampler
Heightfield.surfaceAt under the transform the game draws the field's mesh with, so a prop or a player stands on the triangles the eye sees rather than on the bilinear field between them. Answers null outside the field and for a transform it does not model (any rotation, or an unequal scale), so the caller keeps its own fallback there.
function surfaceSampler(field: Heightfield, matrixWorld: Matrix4): SurfaceSamplerUse it to
- stand props or a player on the drawn terrain triangles under a moved or scaled mesh
- props float or sink where the terrain mesh is drawn under a transform
Example
const ground = surfaceSampler(field, mesh.matrixWorld); const y = ground(x, z) ?? fallback;Good to know
- the mesh is
field.toGeometry()drawn upright under a uniform scale; readmatrixWorldafter it settles
TerrainTiles
Stream a bounded square of game-authored heightfields and keep their render and physics units together. The class composes ordinary THREE.LOD objects and leaves frustum/projection culling to the renderer's existing scene path.
class TerrainTiles extends Object3D implements IComputeDrivenUse it to
- stream terrain without cracks
- keep generated terrain resident around a moving player
- put a generated terrain tile into a game-owned physics world
- a hole or a flicker where streamed terrain tiles are still building (
settledHalf) - split the ground between streamed tiles and a far mesh around the player (
settledHalf)
Example
const tiles = new TerrainTiles({ sampleHeight, surface: gameSurface(), tileSize: 256, tileResolution: 129, residentTileBudget: 25, residentByteBudget: 32_000_000 });Good to know
- sampleHeight and surface are required game choices; no landform or surface preset is installed
- residentTileBudget and residentByteBudget are hard caps; a tile that cannot fit throws
- seam gap, LOD pop and the rendered-vertex finiteness scan are measurements that are off by default; TN_TERRAIN_VALIDATE=1, ?tnTerrainValidate=1 or validate: true runs them, and maxSeamGap, maxVisualSeamGap and maxLodPop report undefined while they are off
Options
- tileSize, tileResolution, lodFactors, lodDistances, skirtDepth, streamRadius, colliderRadius, mergeTiles, validate, and budgets
Also found by
- stream terrain across chunks
terrainValidationRequested
Whether TN_TERRAIN_VALIDATE asks for terrain validation on this launch.
function terrainValidationRequested(): booleanUse it to
- turn terrain's per-frame seam, LOD pop and vertex checks on for one run
- assert the terrain geometry a game streams before it ships
Example
// Reads its own the way `renderListValidationRequested` does: a native launch sets the
// environment variable, a browser asks with the query string, a test or harness sets the
// global. `0` and `false` are off, so a saved URL that enabled it still says "off".
const tiles = new TerrainTiles({ ...options, validate: terrainValidationRequested() });Good to know
- off by default: it is the work it checks, every frame
validateWorldPackage
Validate a world.json manifest against the v1 contract. Never throws on garbage input: a non-object manifest is WORLD_MALFORMED. Every problem is collected, so an exporter sees the complete list at once.
function validateWorldPackage( manifest: unknown, options: IWorldPackageValidationOptions, ):Use it to
- check a Blender-exported world package before the runtime attaches anything
- report why a world package cannot be streamed
Example
const { ok, errors } = validateWorldPackage(json, { placementsByteLength: buffer.byteLength });Good to know
- validation only checks structure and ranges; it never fetches the heightmap or GLBs
warmUnculled
Draw root with frustum culling off until it has drawn draws times, then cull it again and resolve. A pipeline is built by its first real draw (a startup warm-up compiles a different pass), so content the spawn view does not see — streamed tiles behind the player, a mirror that draws only when its water does — builds its pipelines after the reveal and hitches the first frames that see it. Join the promise to the loading curtain to build them behind it. Objects that join root while it warms draw unculled too.
function warmUnculled( ctx:Use it to
- the first frames after the loading curtain hitch on pipeline builds for content behind the camera
- streamed terrain or a lake compiles its pipelines after the reveal
Example
const warm = warmUnculled(ctx, lake.mesh); ctx.startup.hold("lake", () => warm);Good to know
ctx.beforeRenderruns on every world draw, also behind the curtain; join the promise to the curtain's hold
WaterBodies
One world's water, queried: surface height, current and footprint from the baked arrays. Rendering and physics read the same store, as they do for Heightfield, so the surface a player sees and the surface a swimmer rests on cannot disagree. Every station, level, extent and speed comes from the game, and the shading stays in the game's own src/render/. A river's segments sit in a uniform grid, so a query tests the few that can reach its cell instead of every station of every river.
class WaterBodiesUse it to
- ask how high the water is where a player swims
- ask which way a current carries a body
- ask which water body covers a point, and how high its surface is
- share one water store between rendering and physics
Example
const water = new WaterBodies({ ribbons, lakes, field }); const height = water.surfaceAt(x, z);Good to know
- every station, level, extent and speed comes from the game's own bake; a lake is measured on the field passed in
waterlineRadius
The furthest a lake's basin reaches on a bearing: where the drawn ground crosses its level. Twenty-four bearings step outwards and stop at the first bank, because binary-searching the whole ray can jump a dry ridge into another pond. Eighteen halvings land inside two centimetres at this scale, well under the ground's own sample spacing.
function waterlineRadius( field: Heightfield, centre: readonly number[], level: number, ): numberUse it to
- measure where a lake's water meets the ground it floods
- size a lake's drawn surface or the footprint a swimmer may enter
Example
const reach = waterlineRadius(field, lake.at, lake.level) * 1.12;Good to know
- returns metres on the furthest bearing; the caller applies its own cap
WorldCells
Stream a Blender-authored world package by cell and keep it resident around a followed point. The class composes TerrainTiles for the package's heightmap, builds one InstancedBatch per resident cell asset run, distance level and mesh part, and loads hand-placed chunk GLBs through loadAll + addInSlices. Ring residency, CPU per-asset maxDistance filtering, GPU dispatch culling, the per-asset lods levels, hard budgets and generation-tokened cancellation all live here; every geometry, material and surface still comes from the package's GLBs and the game. An asset is drawn per part, not per model: a GLB with several primitives is one InstancedBatch each, and a scattered part whose own material is transparent draws as an alpha cutout unless the game asks for blending, because an InstancedMesh cannot sort its instances. An asset with no nonempty authored lods can draw its own model's baked AutoLOD chain at distances measured over the autoLod viewport. An explicit empty list enrolls only unchanged static parts; section ranges, custom attributes, alpha foliage and vertex deformation retain source geometry.
class WorldCells extends Group implements IComputeDrivenUse it to
- stream a large Blender-authored world by cell instead of one huge GLB
- keep scattered props and hand-placed chunks resident around a moving player
- honour per-asset draw distances and hard streaming budgets without a mid-frame throw
Example
const world = await WorldCells.load({ url: "/world/world.json", surface, follow, ring: 1, budgets: { residentCells: 25, instances: 20000, bytes: 8000000 } });
scene.add(world);
world.update();Good to know
- surface is the game's; this class creates no material, colour or geometry
- a cell's model loads at
soonpriority, so a file the running scene awaits throughctx.assetsstarts first - budgets are hard caps that report pressure instead of over-committing
whenSpawnReady(position, radius, timeoutMs)snapshots a fixed region and settles from existing updates or disposal; it does not drive streaming, andprewarmedremains the separate draw gate- model loads are bounded by
concurrency(default 12) across every resident cell, not per cell - refilters are bounded by
rebuildsPerUpdate(default 16) per update, nearest cell first - residency and
placementReachfollowfollow; levels andmaxDistanceare graded from the render camera, as UE picks instance LODs per view;lodFrom: "follow",?tnLodFromCamera=0orTN_LOD_FROM_CAMERA=0grade fromfollow, reported asTN_WORLD_MAIN_CULL lodFrom= - admission is bounded by
admissionBudgetMs(default 2) per update across every path, plus at most one unit each for terrain and props; while props are queued terrain takes at most half, so neither starves the other, and a deferred cell keeps drawing what it has - SkinnedMesh parts are skipped; an instanced copy would draw one rest pose
- a baked chain's switch distances are measured against
autoLod(default 4 px of error over 60° and 1080 raster rows), because an instanced draw cannot select a level per instance; an asset with nonempty authoredlodsnever consults it; explicit empty lists enroll only unchanged static geometry/material parts - eligible static sources can use cooked HLOD (chunk-only alongside GPU scatter, whole-cell on CPU) after compilation and an observed main-context backend submission; projected-error hysteresis requires actual source triangle reduction and no extra material draws, unsupported or shared source stays resident, and collision/shadow paths retain source representations; stats().hlod counts lifecycle and charged resources, not GPU timing or physical allocation
prewarmedresolves once every prewarmed shared batch has been drawn; a game with a loading screen waits on it, andstats().pendingPrewarmis the same gate as a number- every
asset:level:partis one InstancedMesh for the main pass, plus one caster InstancedMesh per world-grid square ofclusterSizeon the shadow caster layer, so the main pass draws one mesh per key and a shadow level submits only the squares it covers - two definitions the asset loader resolves to one model — the same cooked
glb, the samelodsat the same distances, the samemaxDistanceand bounds — are one asset under the lexicographically smallest id: one model load, one set ofasset:level:partkeys, one prewarm and one refcount, released when the last cell holding any member of the group leaves the ring;TN_WORLD_ASSET_ALIASreports how many of the package's assets are really distinct - the main pass mesh draws only the squares the render camera's frustum covers — on by default, narrowed once per frame for every main batch by the engine's render-cadence dispatch, never for an orthographic camera — a batch with nothing to draw is hidden rather than submitted at
count 0, andTN_WORLD_MAIN_CULLreports both every five seconds - a loaded chunk is merged by material before it is added, so it submits one draw per material rather than one per node; a skinned, multi-material or morph-target mesh, one carrying a baked AutoLOD chain, and an instanced mesh past
chunkMergeMaxTriangles(default 43,690 triangles) or with a shape over 2,048 triangles, all keep their own geometry; a material group crossing 131,072 vertices (4 MiB of position + normal + uv) is split into several meshes in traversal order instead of one giant upload, indexed parts keep their index, andTN_WORLD_CHUNK_MERGEreports what the merge did and the bytes it left shadows.castDistanceis accepted and ignored (clusters replaced it);shadows.invalidateis called at most once a second after streamed records changed
Options
hlod: falsekeeps source rendering;partMaterialgives a part the game's own surface (a swaying tree); ring, budgets, terrain tile size/resolution, terrain stream and collider radius,transparentScatter,clusterSizeandshadows.invalidate, loadconcurrency,rebuildsPerUpdate,admissionBudgetMsand the package's per-asset maxDistance;impostorFar: "always"keeps the far aggregate the near ring's guaranteed radius made unnecessary
ctx.assets.memo
Returns what build returned the last time this build of the game ran, read back from disk, and calls build only when nothing is stored. Use it for seeded work that is the same every run: placement lists, painted sky pixels, terrain heights, a generated stage.
ctx.assets.memo<T>(key: string, build: () => T | Promise<T>): Promise<T>Use it to
- cache generated geometry between page loads
- stop rebuilding the same generated stage on every page load
- cache painted sky pixels or baked terrain heights between runs
- keep seeded placement work the same every run without recomputing it
- make a slow boot fast without shipping a baked asset
Example
const { pixels } = await ctx.assets.memo("sky", () => ({ pixels: paintSky() }));Good to know
- The value is named typed arrays; a map of names to typed arrays is what is stored.
- On the dev server and on a native host
buildruns every time, andTN_ASSET_MEMOreports why: the cache is a build artifact, not a substitute for authoring. - A new build of the game regenerates: the key alone does not pin a value across a rebuild.
- A game that drives a loader outside
defineGamemay call it whenever it likes; the reveal is not waited on.
Options
- TN_ASSET_MEMO reports why a run rebuilt instead of reading the store
renderer.matrixWorld
The per-frame world-matrix walk, on by default as "visible": a hidden subtree — a full-detail body behind a merged stand-in, a hidden LOD level, a parked or hangared model — is not recursed into, so nothing that cannot draw pays a world-matrix multiply. Every visible node is composed exactly as three does, a class that overrides updateMatrixWorld (SkinnedMesh, Camera) runs its own, and a hidden node that holds bones is still walked. "all" restores three's every-node walk.
renderer.matrixWorld?: "visible" | "all"Use it to
- updateMatrixWorld and multiplyMatrices are hot in a profile
- the per-frame matrix walk is slow with many hidden LOD bodies or paired full/hull models
- stop paying for matrices of models nothing can draw
- a skinned mesh or camera goes stale because its world matrix was not refreshed
- restore three's own full updateMatrixWorld walk
- compare how many scene nodes the engine walks per frame
Example
renderer: { matrixWorld: "all" } // in threenative.config.ts; omit for the visible-only defaultGood to know
- Unset is the shipping behaviour:
"visible", which does not recurse into a hidden subtree."all"visits every node exactly as three's ownupdateMatrixWorlddoes. - A game that reads a hidden object's
matrixWorlddirectly must not rely on the walk reaching it: usegetWorldPosition/getWorldQuaternion/getWorldScaleor callobject.updateWorldMatrix(true, false)first. - The walk is the engine's either way, so three's renderer never walks the scene a second time; the count of nodes visited is reported as
matrixWorldin everyTN_PROJECTIONwindow. - Bones are never skipped: a hidden node that holds a
Boneis walked, because a visibleSkinnedMeshdraws with its skeleton's matrices wherever the armature sits.
Options
- renderer.matrixWorld: "all" restores three's every-node walk; the visited count still reports
renderer.minimumProjectedPixels
Do not submit what the render camera cannot resolve. On by default at a conservative 0.5 projected pixel; an object below it is skipped per render camera. Raise the number to cull more, set false to leave every object drawn — the count of what was skipped still reports in TN_PROJECTION.
renderer.minimumProjectedPixels?: number | falseUse it to
- my frame is slow with many distant objects
- draw count is high but the screen is mostly empty
- far away models, aircraft, boats or props cost draw calls but are specks
- a large roster or fleet drops the frame rate while barely visible
- stop submitting objects smaller than a pixel to the camera
- cull by how big something looks to the camera rather than how far it is from the player
- tune how aggressively distant objects are skipped
- a small object I need disappeared at range
Example
renderer: { minimumProjectedPixels: 2 } // in threenative.config.tsGood to know
- Unset is the shipping behaviour: the gate runs at 0.5 px. A game that wants the cut a shipped title tuned names 2;
falseleaves every object drawn. - The decision reads the render camera's projection and viewport, not the player's distance — a camera far from the player still culls its own specks.
- It writes only
object.visible, which the projection's batch key ignores;castShadow,layersandfrustumCulledare never flipped, because that churns batch grouping. - Shadow casters and objects attached to the render camera are never dropped on the main view alone. Exempt any other object with
alwaysRender. - Turning the gate off with
falsedoes not turn its measurement off:TN_PROJECTIONstill reports considered and skipped counts ascull.
Options
- alwaysRender(object) keeps one object drawn whatever the render camera resolves
- renderer.minimumProjectedPixels: false leaves the scene drawn and keeps the measurement on
renderer.projection
The engine's scene-render projection — an internal mirror that collapses repeated draws, including animated skinned rigs that share a geometry and material into one palette draw per pass — on by default. Set renderer.projection: false to decline it, or projection: { materialChecks: 'everyFrame' } to keep it and pay for a per-material check on every frame.
renderer.projection?: boolean | { materialChecks?: 'spread' | 'everyFrame' }Use it to
- a crowd of animated characters draws slowly
- many SkinnedMesh copies of one rig, each its own draw call
- the game got slower after the projection engaged
- turn off the render projection, batching, or the instanced mirror
- draw count fell but frame time did not
- a multi-second freeze when the mirror first engages
- opt out of an engine render optimizer
- thousands of props each with their own material, one colour apart
- a material edit takes a few frames to show up
- check every batched material every frame anyway
Example
renderer: { projection: false } // in threenative.config.tsGood to know
- Unset is the shipping behaviour: the projection runs. Only an explicit
falsedeclines it. - An opted-out game builds no mirror and runs no eligibility scan; the authored scene is what renders, so declining costs nothing rather than being re-judged each frame.
- TN_RENDER_PROJECTION still reports the verdict, with reasonCode
disabledrather than one of the measured declines. materialChecks: 'spread'is the default: a bounded slice of the batched materials is proved per frame instead of all of them, so a frame of 4,096 colour-only materials costs 512 checks rather than 4,096. A base-colour edit is never delayed — that write is O(1) per member.- The price of
spreadis staleness on every other material edit: a material that gains a roughness, a map or a define still leaves its group and is drawn exactly, up tomaterialCheckStaleFramesframes later. TN_RENDER_PROJECTION reports that bound;materialChecks: 'everyFrame'sets it to 0 and restores the per-member, per-frame check. - Any other
materialChecksvalue throws at startup rather than falling back to a default.
Options
- renderer.projection: false declines the whole mirror and costs nothing to decline
- renderer: { projection: { materialChecks: 'everyFrame' } } proves every batched material every frame instead of the default bounded slice
ctx.after
Runs callback once, delay seconds of game time later, and returns a handle that cancels it. Game time stops while the game is paused, so a delayed beat does not fire behind a paused frame.
ctx.after(delay: number, callback: () => void): ScheduleHandleUse it to
- run a callback after a delay
- schedule a one-shot timer that pauses with the game
- do something a moment later without setTimeout
- cancel a pending delayed action when a scene exits
Example
const spawn = ctx.after(0.4, () => ctx.add(makeWave()));
spawn(); // cancelsGood to know
- The delay is game seconds: a paused game does not age it, and a slow frame does not skip it.
setTimeoutkeeps running while the game is paused and after the scene is gone; this does not.- Call the returned handle to cancel: a pending callback holds its scene's closure alive.
ctx.beforeRender
Registers work that runs once per actual world render, after the frame's last fixed update and before the projection reconciles and the renderer draws. The last place to change a transform, a uniform or a camera before the frame is presented.
ctx.beforeRender(callback: () => void): () => voidUse it to
- run a callback just before the frame renders
- update a camera or a uniform after physics and before the draw
- change a transform in the same frame it is seen
- run per-render work that must not run on a loader-only frame
Example
const stop = ctx.beforeRender(() => (material.uniforms.time.value = clock.elapsed));
// later: stop();Good to know
- A held, loader-only frame has no world draw and dispatches nothing.
- Runs after every fixed update in the frame, so a value it writes is the one drawn.
- Returns an unregister function; call it when the object that needed it is gone.
ctx.startup.progress
How much of the start scene has loaded and presented, 0 to 1, for a loading cover's bar. It never falls: a loader whose pending work grows keeps the number it reached rather than jumping backwards.
ctx.startup.progress: numberUse it to
- boot progress bar
- show how much of the start scene has loaded
- loading screen percentage
- a progress bar that never goes backwards
- report startup progress while assets stream in
Example
const width = `${Math.round(ctx.startup.progress * 100)}%`; // a cover the game draws on ctx.canvasLayerGood to know
- Never decreases, even when the loader is asked for more work mid-boot.
- Reaches 1 only after the first world render has been presented, not when the last byte arrived.
- A loading view the engine drew for you already reads it; this is for a cover the game draws itself.