Skip to content

Make large battles run smoothly ​

A thousand units a side, or a 512-cell map, asks more of the page than a skirmish of twenty. Four things keep it smooth: the simulation in a worker, crowds drawn as copies of one mesh, navigation built off the page's thread, and measuring.

Quick start ​

ts
// src/game.worker.ts
import { serveWorld } from '@v12-engine/engine'
import { rules, onStart } from './rules'

serveWorld(rules, { onStart })
ts
// src/main.ts
launch({
	target: '#game',
	game,
	map: mapNamed(),
	worker: new Worker(new URL('./game.worker.ts', import.meta.url), { type: 'module' })
})

The world now steps in a worker, so a long tick no longer makes a frame late. On an M-series Mac with 1,000 footmen a side this took the page's work from 10.9 ms to 1.9 ms a frame (50 to 60 frames a second, 16 late frames to none). Your rules file must import only the engine, since the worker imports it too.

Build it yourself ​

1. Pass data to the worker ​

ts
// bench.worker.ts
serveWorld(melee, { onStart: (world, { args }) => benchStart(world, (args as { each: number }).each) })
// main.ts
launch({ target: '#bench', game: meleeGame, map: benchMap(), worker: new Worker(new URL('./bench.worker.ts', import.meta.url), { type: 'module' }), workerArgs: { each } })

Only plain data crosses. Saves, checkpoints, the log and the debug panel still work; replays are not recorded, the navmesh is not drawn, and the editor's Play here stays on the page. Assemble a page your own way with workerSession(worker, { rules: game, map }). See Making a game.

2. Draw crowds as copies ​

Units with a one-skeleton model are drawn as copies of one mesh past 25 cells by default (animations baked to a texture), with their own skeleton nearer where they are in view. A unit up close but off the screen is a copy too: it takes its skeleton a few cells before it comes into view (further ahead as the camera pans), so it is never seen changing, and keeps it two seconds after it leaves. Zoomed in on 130 units, half of them off the screen, that is about half the skeletons. A unit's clips are made as it first plays them, not all fifty of its model's with each copy. A copy's pose is mixed in the vertex shader from the two baked frames either side of its moment (clips are baked at 30 frames a second), so it changes every frame drawn, as a skeleton's does, not 30 times a second.

ts
footman: {
	baked: true, // copies at any distance; false for never; { near: 40 } or { model } for a simpler copy
	model: { src: 'characters/knight.glb', scale: 0.7 }
}
// for every type: GameView.units.baked = { near: 40 } or false
// at most so many skeletons, the nearest the camera (none by default: past it, units on the screen are copies too)
// GameView.units.baked = { most: 30 }

In the editor: Set up as a unit › Far off. Copies snap between animations rather than blend.

A unit with its own skeleton has its parts merged into one mesh (the knight's nine: one draw, in the view and every shadow pass). merge: false keeps them apart, for code that hides or recolours a part; the copies of a crowd are one mesh either way:

ts
footman: { model: { src: 'characters/knight.glb', scale: 0.7, merge: false } } // this model's; it wins over the game's
// for every model that does not say: GameView.units.merge = false

Zoomed in on the test game's 100 footmen, parts take about 1,840 draws a frame against 260 merged. Each copy is built merged or not as it is made: a look changed with client.looks.set rebuilds the units up close a few a frame, their clip going on.

3. Build navigation off the page's thread ​

ts
// navigation.worker.ts
import { serveNavigationBuilds } from '@v12-engine/engine'

serveNavigationBuilds()
ts
startApp({
	target: '#root',
	scenes,
	navigationWorker: () => new Worker(new URL('./navigation.worker.ts', import.meta.url), { type: 'module' })
})

A 512-cell map takes about two seconds to build; builds are cached by a hash of the ground. Keep them across page loads:

ts
import { createWorldFromMap, type GameMap, type Rules, type NavigationBuilds } from '@v12-engine/engine'
import { indexedStore } from '@v12-engine/client'

declare const game: Rules, map: GameMap

const kept = indexedStore<{ id: string; data: Uint8Array }>('my-game-navigation', 'builds')
const builds: NavigationBuilds = {
	cache: {
		get: async (key) => (await kept.read(key))?.data,
		set: (key, data) => kept.write({ id: key, data })
	}
}
const world = await createWorldFromMap({ map, rules: game, navigation: { builds } })

4. Measure ​

sh
cd packages/bench
node scripts/benchPage.mjs --n 400 --only main --rounds 1 --json out.json
npm run frames -w bench -- measure

benchPage.mjs runs the fight in packages/bench/bench.html (?n=600, &worker=1, ?quality=low) in Chromium and reports frames, where frame time goes, memory and long tasks; --scenario battle keeps a battle going. The frames scenarios (scripts/frames/scenarios/) measure the slowest frames of the real game. Measure alone on the machine.

Reference ​

Scenery batching ​

Scenery is merged by map chunk (one mesh per material per chunk); a model with many doodads is drawn as copies by chunk; trees and mines are copies by chunk. A doodad that moves, turns, is tinted or brushed is drawn on its own and merged again after settle seconds.

ts
sceneryBatching: { chunk: 24, instanced: 32, copyChunk: 24, staticChunk: 48 },
scenery: {
	'my-props/statue.glb': { batch: false },
	'my-props/windmill.glb': { animation: 'Sails_Loop' }
}

const chest = client.doodads.named('chest')!
client.doodads.play(chest.id, 'Chest_Open', { loop: false, onEnd: () => console.log('open') })
const copy = client.doodads.lift(chest.id, { parts: true }) // its own copy, to move or animate
client.doodads.settle(chest.id) // merged again once still
client.doodads.stats // { merged, chunks, chunkMeshes, copies, own, ... }
SettingDefaultWhat it does
sceneryBatching.chunk32Cells a merged chunk
sceneryBatching.instanced16Doodads of one model before they become copies
sceneryBatching.copyChunk16Cells a chunk of copies
sceneryBatching.staticChunk32Cells a chunk of trees and mines (client.renderer.staticChunk)
MapDoodad.batch, MapDoodad.animationPer doodad: never merge; play a clip
GameView.units.shareShare identical materials and atlases between models ({ materials: false } to stop)

A point of a unit's model (client.renderer.kit.point(id, name)) is where it is drawn now. View › Merge scenery in the editor compares.

The frame budget ​

Work spread over frames (units given a skeleton, debris, detail switches, merging, grass laid) shares one budget, FrameBudget: total 6 ms a frame, each at most its most (dressing 4, debris 4, switches 2, merging 4, foliage 4), first in order first.

ts
scene: { frameBudget: { total: 8, most: { merging: 6 }, order: ['switches', 'dressing', 'debris', 'merging'] } }
client.frameBudget.total = 4 // while running; client.frameBudget.sample() for the numbers

Client caps ​

GameView.world.limits (the caps) sets voices, lights, weather, splashes and mist drawn at once; uiInterval and frameTime set HUD updates and simulated frame time.

Reading the stats window ​

The HUD's stats window shows simulation, drawing and GPU time, and per-system tick time in the page. Phases, per frame splits the CPU part by CLIENT_PHASES; Hitches lists recent frames over 33 ms and what took them; First seen lists frames over 25 ms with the shaders compiled and the models built in them, what a warm-up can make ahead (Warm-up and first-seen hitches). In code: client.debugTools.perf.sample(entities) (phases, hitches); add your own phase with GameView.framePhases.

Other measures (packages/bench/scripts) ​

benchMemory.mjs (heap and textures), benchLoad.mjs (requests and time to a running game; npm run build -w example first), bench/profile.bench.ts (CPU profiles with PROF_OUT), profile.mjs <file> --hitches. Frame scenarios: measure, ab, steady, ticks, knobs, costs, baseline.

In the example ​

  • apps/example/launch.html?worker plays melee in a worker (apps/example/src/examples/game.worker.ts).
  • apps/example/src/navigation.worker.ts builds every scene's navigation.
  • Far-off detail: Detail by distance. Many headless games: Testing your rules.