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.
Before you start
Section titled “Before you start”- 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.
LOD Group and LOD Mesh
Section titled “LOD Group and LOD Mesh”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.
Script members
Section titled “Script members”| Member | What it is |
|---|---|
lod |
The LOD Mesh component of the level shown now, or undefined. A getter. |
lod |
Every level’s LOD Mesh component. A getter. |
lod |
The level’s distance, as used for switching. A getter. |
lodMesh.ready |
Whether the level is loaded and can be shown. A getter. |
How it switches
Section titled “How it switches”- Levels are ordered by
distance. The shown level is the one with the largestdistancethe 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.
Loading on demand
Section titled “Loading on demand”- 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
loadAheadof 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.
Cache Mesh
Section titled “Cache Mesh”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.
What counts as one look
Section titled “What counts as one look”- 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.
What is never batched
Section titled “What is never batched”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,boundsorsmoothNormalsinputs, or passes; - primitives cut by CSG tools;
- an entity whose Cache Mesh is disabled.
Behaviour
Section titled “Behaviour”- 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.
Hidden content does not animate
Section titled “Hidden content does not animate”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.
| Component | Type | What it does |
|---|---|---|
| LOD Group | comp-lod-group | Switches between child detail levels based on camera distance. |
| LOD Mesh | comp-lod-mesh | One detail level inside a LOD Group, shown from a set distance. |
| Cache Mesh | comp-cache-mesh | Draws this entity and every identical copy of it in one draw call. |
Examples
Section titled “Examples”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.
#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');}A script scatters 500 copies of a disabled tree template with random turns and sizes, and the Cache Mesh on each part draws all of them in one draw call per part.
Look around the forest; it is the same forest on every reload. Drag to orbit the camera, scroll to zoom.
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.scaleas 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.
#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)' : '');}A grove of trees with three levels of detail each: amber and detailed near, blue and coarse further out, a violet cone far away. The script logs every switch of the first tree with the camera's distance.
Scroll to zoom out and in, and watch the trees swap levels and the log report each switch of the front tree. Drag to orbit the camera.
lod.lodLevelslists every level’s LOD Mesh component;level.entityis the level’s entity andlevel.distanceits switching distance.lod.currentLevelis read every frame, which is just a property read. The script only logs when it changes.camerais the global for the camera the player sees through. It can beundefinedbefore rendering starts, hence the check.- The vectors are created once at the top and reused, so
updateallocates nothing each frame. level.readytells 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.
#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();}Four times a second, a script hides every member of a crowd farther than 40 m from the camera, and shows them again as the camera comes closer.
Scroll in and out: people farther than 40 m from the camera disappear, and come back as you approach. Drag to orbit the camera.
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.childrenincludes every child object;isEntity(child)keeps only the entities.person.visiblehides 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
visibleonly when it changes, so nothing is done for characters that stay put.
Snippets
Section titled “Snippets”1. Lower detail on phones
Section titled “1. Lower detail on phones”Phones and headsets have less power than desktops. This script shortens every LOD distance on mobile devices so cheaper levels show sooner.
#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()andDevice.isHeadset()tell the script what it runs on.level.distancereads the level’s current distance. Each one is multiplied by the slot’s factor withsetProps. The group re-sorts its levels by itself.loadAheadis 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.
Common mistakes
Section titled “Common mistakes”- 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
hysteresisto around0.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
setEnabledto cull. Disabling an entity also pauses its scripts and fires theirdisablehooks. For pure visual culling, usevisible. - Checking distances every frame for hundreds of entities. Use
throttleordelayto check a few times a second.