Skip to content

LOD and caching

Updated

A big world quickly becomes expensive to draw: every tree, rock and lamp post costs the graphics card work each frame. MIRA gives you two components to keep large scenes fast. An LOD Group (level of detail) shows a detailed version of an object up close and simpler versions further away. A Cache Mesh draws every identical copy of an object in a single draw call, however many copies there are. This page explains both, how scripts work with them, and why hiding off-stage content is a cheap way to save processing time.

  • Models and primitives. LOD levels and cached copies are ordinary mesh entities. See Models and meshes.
  • Groups. A Group entity (ent-group) holds other entities as children. An LOD Group is a Group with the LOD Group component.
  • Draw calls. Each time the engine asks the graphics card to draw one mesh with one material is a draw call. Draw calls have a fixed overhead, so thousands of them slow a scene down, especially on phones and headsets.
  • Spawning. Scripts copy entities with spawn(source, options). See Scene and entities.

LODGroupComponent · comp-lod-group · on a Group, one per group

LODMeshComponent · comp-lod-mesh · on a Primitive Mesh, a model entity, or a Group that is not itself an LOD Group

An LOD Group turns a Group into a level-of-detail switch. Each direct child of the group that carries an LOD Mesh is one level. The group shows only the level that suits the camera’s distance and hides the others. A level can be a primitive, a model, or a Group holding several parts.

Tree LOD (Group + LOD Group, hysteresis 0.1)
├── Tree High (glTF + LOD Mesh, distance 0)
├── Tree Mid (glTF + LOD Mesh, distance 20)
└── Tree Low (glTF + LOD Mesh, distance 60)

LOD Group:

Prop Type Default Description
hysteresis number 0 0 to 0.999. How much nearer than a level’s distance the camera must come before the level it left shows again, as a fraction of that distance. Stops flicker at a boundary: with 0.1, the switch back from the 8 m level happens at 7.2 m.
loadAhead number 5 Metres, 0 to 10000. How far outside a level’s distances its model starts loading.

LOD Mesh:

Prop Type Default Description
distance number 0 Metres, 0 to 10000. The camera distance from which this level shows.

Values outside the range are clamped to it.

Member What it is
lodGroup.currentLevel The LOD Mesh component of the level shown now, or undefined. A getter.
lodGroup.lodLevels Every level’s LOD Mesh component. A getter.
lodMesh.distance The level’s distance, as used for switching. A getter.
lodMesh.ready Whether the level is loaded and can be shown. A getter.
  • Levels are ordered by distance. The shown level is the one with the largest distance the camera is at or beyond; the nearest level shows when the camera is closer than every distance.
  • The distance is measured from the camera to the group, divided by the camera’s zoom. In a headset the headset camera is used.
  • Levels are hidden for the session only: nothing is saved. A hidden level catches no pointer, leaves its Cache Mesh batch, and does no animation work.
  • In the editor the levels switch as the editor camera moves, and a selected level stays shown so you can edit it.
  • A disabled or removed LOD Group has no effect: every level shows, overlapping. That is handy while editing the levels side by side.
  • An LOD Mesh outside an LOD Group does nothing and warns once in the console.
  • The coarsest model level loads with the scene, so there is always something to show.
  • Every other model level loads only when the camera comes within loadAhead of the distances it shows at. Primitive and group levels always load.
  • Once loaded, a level is prepared while still hidden (shaders compiled, textures uploaded), so it swaps in without a stall.
  • Until a level is ready, the nearest ready level shows in its place, coarser first, so nothing pops in empty.
  • A loaded level stays loaded while its scene is active.

Cost: one distance per group per frame. The shown level depends on each viewer’s camera, so it is never sent over the network. Gaussian splats have their own level of detail and do not use these components.

CacheMeshComponent · comp-cache-mesh · on a Primitive Mesh, a model entity, a Water Mesh, or an Image or KTX2 entity

A Cache Mesh draws its entity together with every identical copy of it in one instanced batch: the graphics card draws all of them in a single call. Each “look” costs one draw call however many copies there are. The copies can sit anywhere in the hierarchy, be spawned or cloned by a script, or come from a prefab. The component has no props: adding it is the whole setup.

  • A primitive: its geometry plus its material kind and props. Two boxes of different colours are two looks.
  • A model: each sub-mesh is its own look, made of its part of the file and its material. A model of three parts costs three draws whether there is one copy or a thousand.
  • Shadows: copies share a draw when their Cast and Receive shadow settings match.
  • Water: it joins the shared water pool, one draw for every cached water plane.
  • An image: its kind, source, size, tint, zoom, grayscale, opacity and side. A row of identical posters is one draw.

These draw on their own, as if they had no Cache Mesh:

  • skinned and morphed sub-meshes, since each copy poses them its own way (a model with mixed parts batches only its rigid ones);
  • meshes with a Reflector material;
  • a 360 (equirectangular) image;
  • Shader Materials that use the pointer, bounds or smoothNormals inputs, or passes;
  • primitives cut by CSG tools;
  • an entity whose Cache Mesh is disabled.
  • Each copy is drawn where its entity is, read every frame after every script, so moves made by scripts and node animation show on the same frame.
  • Hidden, disabled or LOD-hidden copies leave their batch, and copies outside the view are skipped.
  • Each entity keeps an invisible stand-in at its real shape, so picking, decals, physics colliders and the editor selection still work.

Cost: nothing without one; with one, one matrix per copy per frame.

Nothing animates while it is not shown, whatever hid it: the entity or a parent is hidden or disabled, or it is an LOD level that is not shown.

  • Animation Clips pause and carry on from where they were when the entity shows again.
  • Dynamic bones stop solving and start again from rest.
  • GIF and Lottie images decode no frames and resume on their own.

So hiding far-away or off-stage characters is a cheap way to save processing time. An entity’s visible property hides it for this session only, without saving or disabling it.

ComponentTypeWhat it does
LOD Groupcomp-lod-groupSwitches between child detail levels based on camera distance.
LOD Meshcomp-lod-meshOne detail level inside a LOD Group, shown from a set distance.
Cache Meshcomp-cache-meshDraws this entity and every identical copy of it in one draw call.

1. Plant a forest with one draw call per part

Section titled “1. Plant a forest with one draw call per part”

Make one tree entity named Tree with a Cache Mesh, and keep it disabled as a template. This script scatters 500 copies with random turns and sizes.

Forest.jx
#pragma slot(ref=count, type=Integer, min=1, max=5000, default=500)
#pragma slot(ref=area, type=Number, min=10, max=1000, default=120)
#pragma lifecycle(startup)
function startup() {
const tree = findEntity('Tree');
if (!tree) {
console.warn('No Tree template in the scene');
return;
}
const forest = Random.seeded('forest-1');
for (let i = 0; i < count; i++) {
spawn(tree, {
position: { x: forest.range(-area / 2, area / 2), y: 0, z: forest.range(-area / 2, area / 2) },
rotation: { x: 0, y: forest.range(0, M_TAU), z: 0 },
scale: forest.range(0.8, 1.3),
enabled: true,
});
}
log('Planted', count, 'trees');
}
  • Random.seeded('forest-1') makes a random generator that always produces the same sequence, so every player, and every reload, gets the same forest.
  • spawn(tree, { … }) copies the template with its Cache Mesh. Position, rotation and scale are different per copy, which does not split the batch: a copy’s transform is not part of its look.
  • scale as a single number scales all three axes.
  • With a three-part tree model, the 500 trees cost three draw calls in total.

2. Log LOD switches while you tune distances

Section titled “2. Log LOD switches while you tune distances”

While you tune an LOD Group, it helps to see which level shows and when. This script watches the group named Tree LOD and logs each switch, with the camera’s distance.

LodMonitor.jx
#pragma lifecycle(startup, update)
let group;
let lod;
let lastLevel;
const cameraPosition = new THREE.Vector3();
const groupPosition = new THREE.Vector3();
function startup() {
group = findEntity('Tree LOD');
lod = group.getComponent(LODGroupComponent);
for (const level of lod.lodLevels) {
log('Level', level.entity.name, 'from', level.distance, 'm');
}
}
function update() {
const level = lod.currentLevel;
if (level === lastLevel || !camera) return;
lastLevel = level;
camera.getWorldPosition(cameraPosition);
group.getWorldPosition(groupPosition);
const distance = cameraPosition.distanceTo(groupPosition);
log('Showing', level ? level.entity.name : 'nothing', 'at', distance.toFixed(1), 'm',
level && !level.ready ? '(still loading)' : '');
}
  • lod.lodLevels lists every level’s LOD Mesh component; level.entity is the level’s entity and level.distance its switching distance.
  • lod.currentLevel is read every frame, which is just a property read. The script only logs when it changes.
  • camera is the global for the camera the player sees through. It can be undefined before rendering starts, hence the check.
  • The vectors are created once at the top and reused, so update allocates nothing each frame.
  • level.ready tells you whether the level’s model has finished loading; until then a coarser level stands in.

3. Hide far-away characters to save processing time

Section titled “3. Hide far-away characters to save processing time”

Animated characters cost work even when they are tiny in the distance. This script hides every character beyond a distance and shows them again as the player approaches. Hidden characters skip their animation entirely.

CrowdCulling.jx
#pragma slot(ref=hideBeyond, type=Number, min=5, max=500, default=40)
#pragma lifecycle(startup, update)
let crowd = [];
const eye = new THREE.Vector3();
const spot = new THREE.Vector3();
const check = throttle(() => {
if (!camera) return;
camera.getWorldPosition(eye);
for (const person of crowd) {
person.getWorldPosition(spot);
const near = eye.distanceTo(spot) < hideBeyond;
if (person.visible !== near) person.visible = near;
}
}, 250);
function startup() {
const group = findEntity('Crowd');
crowd = group.children.filter((child) => isEntity(child));
log('Watching', crowd.length, 'characters');
}
function update() {
check();
}
  • throttle(fn, 250) runs the check at most four times a second instead of every frame. Nobody notices a character appearing a quarter of a second late.
  • group.children includes every child object; isEntity(child) keeps only the entities.
  • person.visible hides or shows an entity for this session only, without saving anything or disabling its scripts. While hidden, its Animation Clip pauses and its dynamic bones stop.
  • The script writes visible only when it changes, so nothing is done for characters that stay put.

Phones and headsets have less power than desktops. This script shortens every LOD distance on mobile devices so cheaper levels show sooner.

MobileLod.jx
#pragma slot(ref=mobileFactor, type=Slider, min=0.2, max=1, step=0.05, default=0.5)
#pragma lifecycle(startup)
function startup() {
if (!Device.isMobile() && !Device.isHeadset()) return;
let changed = 0;
for (const name of ['Tree LOD', 'Rock LOD', 'House LOD']) {
const group = findEntity(name);
const lod = group && group.getComponent(LODGroupComponent);
if (!lod) continue;
for (const level of lod.lodLevels) {
level.setProps({ distance: level.distance * mobileFactor });
changed++;
}
lod.setProps({ loadAhead: lod.props.loadAhead * mobileFactor });
}
log('Scaled', changed, 'LOD distances by', mobileFactor);
}
  • Device.isMobile() and Device.isHeadset() tell the script what it runs on.
  • level.distance reads the level’s current distance. Each one is multiplied by the slot’s factor with setProps. The group re-sorts its levels by itself.
  • loadAhead is shortened too, so detailed models are not downloaded long before they could show.
  • These changes are local to this player: the shown level is never shared over the network anyway.
  • LOD Mesh on the wrong entity. A level must be a direct child of the LOD Group’s entity. An LOD Mesh anywhere else does nothing.
  • Leaving the LOD Group disabled. Disabled, it shows every level at once, overlapping.
  • Flicker at a boundary. A camera hovering at a level’s distance makes it switch back and forth. Set hysteresis to around 0.1.
  • Expecting skinned characters to batch. Skinned and morphed meshes always draw on their own. Use LOD levels and hiding for characters instead.
  • Many slightly different copies. A different colour, material prop or shadow setting is a different look and a separate draw. Keep cached copies identical.
  • Toggling setEnabled to cull. Disabling an entity also pauses its scripts and fires their disable hooks. For pure visual culling, use visible.
  • Checking distances every frame for hundreds of entities. Use throttle or delay to check a few times a second.