Skip to content

Big Worlds and Performance ​

What the engine does to keep a big scene smooth, and what a game can turn on. Each section says what it costs and where it stops helping.

Raycasting ​

A raycast used to test every triangle of every mesh whose bounding sphere the ray crossed. A ray at a 500k-triangle ground tested all 500k: about 16 ms on a desktop CPU, several times that on a phone or a headset, every time.

Since 0.21.0:

  • Big static meshes get a bounding volume hierarchy (three-mesh-bvh) the first time a ray reaches them, so a ray tests a few dozen triangles. The geometry itself is left alone (the hierarchy keeps its own index), every copy of a model shares one, and meshes under 600 triangles keep three's own test. Skinned and morphing meshes keep three's test too: their triangles move every frame. A geometry you rewrite in place is refitted; one rewritten again and again (a water surface) gives its hierarchy up.
  • Nothing raycasts a still pointer. The flat-screen UI pointer (UIInteractionSystem) casts only when the pointer moves, a button goes down or up, the camera moves, something is added or removed, or a tenth of a second has passed (a widget can move by itself). A scene with no buttons, toggles or sliders is never raycast at all. It tests the UI first and then only what stands between the camera and the widget.
  • XR pointing is one nearest-first search over the pointable objects.
  • world.query is cached until an entity or component comes or goes, and walks the smallest component store instead of every entity.

Measured on a heavy scene (400 models of 20k triangles and a 524k-triangle ground, pnpm bench in the engine repo, Apple M-series CPU):

0.20.00.21.0
UI pointer, still, per frame15.7 ms0.001 ms
UI pointer, moving, per frame16.0 ms0.009 ms
One script raycast16.0 ms0.044 ms
One raycast, first hit only15.9 ms0.031 ms
30 world.query calls over 10k entities8.7 ms0.005 ms

The hierarchy costs once: the first ray at the 524k-triangle ground took 70 to 80 ms to build it. Meshes no ray reaches never build one.

Asking for less ​

world.raycast takes options in place of near, and each makes a call cheaper:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";
import * as THREE from "three";

export default class Aim extends Behaviour {
  private forward = new THREE.Vector3();

  onUpdate() {
    const camera = this.world.getCamera();
    camera.getWorldDirection(this.forward);
    const [hit] = this.world.raycast(camera.position, this.forward, {
      far: 100,
      firstHitOnly: true, // the nearest only: tried nearest first, stops early
      visibleOnly: true, // hidden things don't block
      ignore: [this.entityId],
    });
    if (hit?.entityId != null) console.log("aiming at", hit.entityId);
  }
}
  • firstHitOnly is the big one. Use it whenever "what's in front" is the question.
  • entities: [id, ...] tests only those entities and their children, when you know what you're looking for (enemies, pickups).
  • layers keeps a ray to three.js layers you've put things on.

Turn the hierarchies off for a whole world with featureFlags: { acceleratedRaycast: false }, or for a moment with setAcceleratedRaycastEnabled(false) to compare.

Streaming ​

A big world doesn't need all of itself in memory. Put a StreamingComponent on a model, or on a group that holds a region of the world (a "cell"), and its models load when the player comes within loadDistance and are freed from memory (geometry, textures, GPU) once they're past unloadDistance.

FieldDefaultWhat it does
enabledtrueOff: always loaded.
loadDistance60Metres from the player within which its models load.
unloadDistance0Metres beyond which they're freed. 0: a quarter further than loadDistance.
radius0Distance is measured to a sphere this big around the entity, so a big region loads before the player reaches its middle. The editor sets it from the region's bounds.
priority0Higher loads first among regions the same distance away.
hideWhenUnloadedtrueDraw nothing under the entity while it's out of range (primitives too).

The gap between the two distances is what keeps a player standing on an edge from loading and freeing the same files over and over.

What stays while a region is out of range: the entities, their transforms, scripts, audio and physics. A trimesh collider keeps the shape it had, so the ground is still there under someone who walks back; a model that never loaded has no trimesh yet, so give the ground of a region a primitive collider or keep it out of streaming. Scripts keep running: stop work that only matters up close yourself (read this.world.getComponent(id, StreamingComponent)?.state, which is "loaded", "loading" or "unloaded").

How it decides:

  • Every check (five a second), each region's distance to the player is measured: the camera, unless a script picks something else with this.world.streaming?.setFocus(entityId).
  • Loads go nearest first, maxConcurrentLoads at a time (4). Models outside any region load at once, as before, and nearest first.
  • A file is freed once nothing loaded shows it. Two regions using the same rock share one copy, and it stays while either is loaded.
  • settings.memoryBudgetMB (0: none) frees regions early when streamed content holds more than that, furthest first, but only regions already past their load distance. Nothing the player is inside is ever freed for the budget.
  • The editor always shows everything. Streaming runs in Preview and in the published game.
ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export default class StreamAroundPlayer extends Behaviour {
  init() {
    const streaming = this.world.streaming;
    if (!streaming) return;
    streaming.setFocus(this.entityId); // the player, not the camera
    streaming.settings.maxConcurrentLoads = 2; // gentler on a phone
    streaming.settings.memoryBudgetMB = 300;
  }

  onUpdate() {
    const stats = this.world.streaming?.getStats(this.world);
    if (stats && stats.loading > 0) console.log(`${stats.loading} regions loading`);
  }
}

Laying out a streamed world ​

  • One region per area a player sees at once: a town, a stretch of forest, a room. Tens of regions, not thousands: each one is checked five times a second.
  • Make loadDistance a little more than how far the player can see into the region, so it's in before it's in view. Pair it with fog or a cull distance so nothing pops at the edge.
  • Keep what's always near (the player, the HUD, the ground under the start) outside regions.
  • What a region holds is downloaded only when it loads, when the project's Asset loading is "Load the scene, the rest on demand".

Levels of detail ​

A rock 200 m away covers a few pixels and doesn't need 20,000 triangles. An LODComponent on a model lists simpler copies of it and when to draw them:

FieldDefaultWhat it does
levels[]{ path, screenSize } per simpler file, most detailed first. Level 0 is the model's own file.
cullScreenSize0Don't draw below this share of the screen's height (0: always draw).
cullDistance0Don't draw further than this many metres (0: no limit).
hysteresis0.15How much bigger the object must get before going back to more detail.
enabledtrueOff: level 0, always drawn.

Screen size is the share of the screen's height the model's bounding sphere covers: 1 fills the screen top to bottom, 0.1 is a tenth of it. It follows the camera's field of view (and a headset's) and the entity's scale, so one set of numbers works for a pebble and a mountain. Level i is drawn once the model is smaller than levels[i - 1].screenSize; going back up needs it to be hysteresis bigger than that, so a model on the edge doesn't flicker between levels. Switches are instant: there's no cross-fade, so pick levels close enough that a switch isn't noticed at its screen size.

The editor makes the files: select a model, Levels of detail, Generate (or ask the agent). It writes name.lod1.glb, name.lod2.glb and so on next to the model with meshoptimizer, half the triangles each step by default, and fills in the component. A level file loads the first time it's needed and is freed with the model when streaming frees it.

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";
import { LODComponent } from "@relu-interactives/spatial-ecs/components";

export default class FarTrees extends Behaviour {
  init() {
    // Every tree: simpler past a quarter of the screen, gone past 300 m.
    for (const id of this.world.query(LODComponent)) {
      const lod = this.world.getComponent(id, LODComponent);
      if (lod) lod.cullDistance = 300;
    }
    // Phones: simpler levels sooner (null follows the quality preset).
    if (this.world.lod) this.world.lod.bias = 0.7;
  }
}
  • cullDistance and cullScreenSize work on any entity, not only models: put them on a group to stop drawing a whole village past a distance. What isn't drawn keeps its scripts, physics and audio.
  • Each object's level is chosen one frame in four (world.lod.spread), all of them at once after the camera jumps: distances hardly change in a frame.
  • Quality: screen sizes are multiplied by world.lod.bias, which follows the quality preset unless a script sets it (low 0.6, medium 0.8, high 1, ultra 1.25).
  • Raycasts hit the level drawn now, never a hidden one; physics uses level 0.
  • Not for skinned models: an animated character's levels would need their own skeletons, so skinned models only use cullDistance and cullScreenSize.
  • Per-entity material edits apply to level 0 only; the other levels draw the file's own materials.
  • The editor always draws level 0.

Culling ​

three.js already skips meshes outside the camera's view (frustum culling). The engine adds:

Instanced meshes ​

An instanced mesh is culled as one object, by a sphere around all its instances. Since 0.21.0 the engine measures that sphere again whenever an instance moves (it was measured once, so a moved instance could vanish at the screen's edge), and uploads instance matrices only when one changed (every matrix was sent to the GPU every frame). Scattered grass and trees are split into chunks, so each chunk is culled on its own (see Terrain).

Occlusion culling ​

Put an OccluderComponent on solid, roughly box-shaped things you can't see through: walls, buildings, rock faces, a hill's core. Each frame the engine draws their bounding boxes (shrunk by inset, 5% by default) into a small depth buffer on the CPU, 256 × 128, and skips drawing every model and primitive that is completely behind them.

  • It runs on the CPU, so it works the same on WebGL 2, WebGPU and a headset, and answers for this frame: nothing pops in as you turn, which GPU occlusion queries (a frame or two late) can't avoid.
  • It errs towards drawing. An occluder's depth is taken at the farthest point of each pixel, a pixel is covered only when its centre is, an object is tested on a rectangle a pixel bigger than it, triangles are clipped to the near plane (a wall running past the camera still hides what's behind its far part), and an occluder the camera stands inside is skipped. An object shows the frame it's uncovered and hides only after two covered frames. The one way it can be wrong: something seen only through a gap between two occluders narrower than one of the buffer's pixels (about five screen pixels across at 1280 wide).
  • When it hasn't hidden anything for a second, it tests one frame in 15 (idleInterval), so a scene where occluders don't help hardly pays for them. Terrain cells lower than the eye aren't drawn into it: ground below you can't hide what stands on the ground beyond it.
  • Measured on a 20 × 20 grid of 12 m buildings seen from street level (in the engine's tests): 249 of the 399 in view hidden, 0.7 ms a frame on a desktop CPU, and every hidden building checked with rays to 125 points on it, none of them visible.
  • What's hidden keeps its scripts, physics and audio. It doesn't cast its shadow either, so a tall building behind a low wall can lose its shadow on the street: don't make low walls occluders where that shows.
  • The editor draws everything. In a headset it's off unless this.world.occlusion.xr = true: it tests from the head, and each eye sees a little more.
  • this.world.occlusion.getStats() says how many occluders were drawn, how many objects were tested and hidden, and how long it took. maxOccluders (64, nearest and biggest first) and setResolution(width, height) trade what's hidden for time.

Good occluders are big and simple. A tree, a fence, glass or anything with holes is not one: it would hide what shows through it.

Terrain ​

A TerrainComponent on an Empty makes ground: a heightmap drawn in square chunks, painted in up to four colour layers, with a physics collider.

FieldDefaultWhat it does
size256Metres per side. The entity's origin is the centre.
resolution257Height samples per side (17 to 2049). 257 over 256 m is one a metre.
dataPath""A .terrain file with sculpted heights and paint (the editor writes it). Empty: made from noise.
noiserolling hills{ seed, amplitude, featureSize, octaves, ridged, flattenCenter }. Same settings, same ground.
layersgrass, dirt, rock, snow{ name, color, variation }: flat colours with a little hand-painted variation.
autoPaint, paintRuleson; rock on slopes, snow up highWithout a file, paint by height and slope: { layer, minHeight, maxHeight, minSlope, maxSlope, blend }.
chunkQuads64Grid squares per chunk side. Each chunk is one draw call.
lodDistance80Chunks this far away drop to half the points, twice as far a quarter, and so on. 0: always full.
flatShadingfalseFaceted, low-poly look.
collidertrueA fixed Rapier heightfield that matches the drawn ground.
occludertrueHills hide what's behind them (occlusion culling).

Chunks meet without gaps at different levels: their edges share heights and normals, and a skirt hangs down around each to hide where a detailed chunk's edge has points a simpler one hasn't. The look is vertex colour, so it's the same on WebGL, WebGPU and a headset, and costs no textures.

Scripts read and change the ground through this.world.terrain:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export default class StickToGround extends Behaviour {
  onUpdate() {
    const position = this.threeRef.object.position;
    const ground = this.world.terrain?.heightAt(this.world, position.x, position.z);
    if (ground != null) position.y = ground;
  }
}
  • heightAt(world, x, z) and normalAt(world, x, z) are in world space (null off the terrain). getTerrains() lists terrain entities.
  • edit(id) gives the terrain's Heightfield: raise, flatten, smooth, roughen, path (carve a road between two points), paint, autoPaint(rules), generate(noise). Only the chunks an edit touched are rebuilt, and the collider and occluders follow. save(id) returns the .terrain file's bytes.
  • A model or prefab placed on a terrain should use heightAt for its height; the editor's placement does.

Grass ​

A GrassComponent on the terrain entity grows stylised grass: thin blades coloured from baseColor to tipColor, swaying with windStrength and windSpeed, density blades a square metre, out to viewDistance (50 m). Blades are made in chunks around the camera (a few a frame, nearest first) and dropped once far behind, and each chunk draws fewer of its blades as it gets further, so the grass thins out instead of ending in a line. mask keeps it to a paint layer (layer, minWeight), a height range and slopes under maxSlope.

The sway is a vertex shader: GLSL on WebGL, TSL on WebGPU. Grass is never hit by raycasts and casts no shadow unless castShadow is on.

Trees, rocks and bushes ​

A ScatterComponent on the terrain entity scatters models: each item is { path, density (per 100 m²), minScale, maxScale, alignToGround, sink, spacing, mask, impostorDistance, cullDistance, castShadow, seed }. They're drawn in chunks (chunkSize, 48 m), each chunk one instanced draw per mesh of the model and culled on its own. Placement is worked out from the settings each time, so it's always the same and nothing about it is saved.

  • Impostors: past impostorDistance (90 m) a chunk draws flat pictures of the model facing the camera instead of the model. The pictures are taken once per model with the game's renderer, from eight directions, and a chunk shows the one nearest its view. They don't sway or cast shadows.
  • Past cullDistance (400 m) nothing is drawn, and chunks well past it are dropped.
  • Scattered things have no colliders. Put the few you can bump into (big rocks, trunks by a path) in the scene as entities with physics.

Measured: a big world, before and after ​

pnpm example:large-world in the engine repo builds one world and flies a camera through it: a 1 km terrain (513 × 513 heights), grass, about 15,000 scattered trees, a city block of 160 buildings, and 2,000 statues of 19,000 triangles each in 25 regions. ?mode=baseline builds the same content with this page's features off (full-detail terrain, every tree a full model at any distance, no LODs, no streaming, no occlusion); ?mode=optimised turns them on. ?frames=600 flies 360 m from the forested hills into the city at 36 m/s and times each frame with the GPU's work included.

Apple M-series laptop, 1280 × 720, Chromium, each pair run back to back (the machine was busy with other apps, so absolute numbers moved between pairs; the ratio held):

WebGL baselineWebGL optimisedWebGPU baselineWebGPU optimised
Average frame21.5 ms3.0 ms85.2 ms15.2 ms
95th percentile32.8 ms4.3 ms111 ms40.7 ms
Worst frame72 ms16 ms174 ms126 ms
Draw calls2,970380
Triangles drawn38.2 M0.77 M

(WebGPU's draw counters add up across frames outside its own animation loop, so its draw and triangle counts aren't comparable; the scene is the same.) The optimised run's worst frames are streaming: a region's models loading as the camera reaches it.

None of this was measured on a phone or a headset. Their GPUs are where the triangle and draw-call savings matter most, and their CPUs are several times slower than this one, so expect bigger frame times on both sides.