# spawnerKit 1.1.8
Enemy spawners, waves and pooling for any multiplayer game: put a Spawner on a synced entity, give it waves as a data file, and enemies arrive in one of 10 spawn patterns (the `pattern` setting) with one of 7 effects, get harder along one of 5 curves, and are reused from a pool instead of piling up.
Version **1.1.8** (`SK.VERSION`). The version, this README and `package.yaml` move together.
## Guides
Two guides ship inside this package, so every install has them:
- **How to spawn waves of enemies** (guide path `spawnerKit.package/how-to-spawn-waves-of-enemies`, file `how-to-spawn-waves-of-enemies.guide/guide.md`): what the kit's parts are and how they fit, spawners and spawn points, waves and schedules, budgets and difficulty curves, spawning items and pickups (not only enemies), despawning, limits and pooling, and who spawns what in multiplayer (the host decides, every player sees the same enemies).
- **Build a wave survival arena where every wave brings more and tougher enemies** (guide path `spawnerKit.package/build-a-wave-survival-arena-with-increasing-difficulty`, file `build-a-wave-survival-arena-with-increasing-difficulty.guide/guide.md`): from an empty world to a wave survival game, with spawnerKit for the waves, aiKit for enemies that chase and attack, and SecondWind for health, damage, death and respawn, all three installed from ZeroMind. Followed step by step in a brand-new world for 1.1.6, through Play and wave 1, with the kits installed in the order its step 2 gives (SecondWind first).
Open one by its guide path or its name: `zero guides read spawnerKit.package/how-to-spawn-waves-of-enemies` in the shell, the `guides` tool with that `path`, or the Docs panel (select the guide in the asset browser and press **Open in Docs** in its Inspector). The guide name alone works too (`zero guides read how-to-spawn-waves-of-enemies`). The guides point on to aiKit's two guides (`aiKit.package/how-to-give-npcs-a-brain`, `aiKit.package/how-to-make-enemies-that-patrol-chase-and-attack`), which open once aiKit is installed, and SecondWind's two (`SecondWind.package/how-to-add-health-and-damage-to-your-game`, `SecondWind.package/build-a-small-arena-game-with-health-bars-hit-markers-and-respawn`), which arrive with spawnerKit's install.
## Install
One call brings everything spawnerKit builds on: **SecondWind** (health, damage, death), **Lifeline** (health bars, under SecondWind), **MatchFlow** (rounds) and **juiceKit** (effects).
```
zeromind_install guid=866b48e5-deed-4e7f-84a8-94ec29134c81 at=/source
```
(or search ZeroMind for "spawnerKit" and install `spawnerKit.package`). spawnerKit lands in `/source/spawnerKit.package` and the four kits under `/source/deps/`, and `require("spawnerKit.api")` and `require("SecondWind.api")` both work from your own scripts. If your world already has one of those kits, spawnerKit uses it. The log can show `module ... has no root to resolve against` lines for the kits under `deps`. They do not stop once the install has landed: they come back every time the world loads (see [Known limits](#known-limits)).
Checked in a brand-new world: this one call, then the example below, word for word, ran all three waves (6, 9 and 13 enemies, every one cleared, all waves done in 51 s).
## Use it
Replace your scene's `build.luau` with this whole file (it makes its own ground, so nothing of the default scene is needed). It makes four spawn points around an arena, a spawner that plays three waves from a data file, a turret that shoots them, the pool readout, and a player whose body has SecondWind health so the enemies can hurt it.
```lua
local SK = require("spawnerKit.api")
local HK = require("SecondWind.api")
function content()
local ground = entity.spawn("ground")
ground.component.add("Model", { model = asset.resolve("@builtin::meshes.cube", "mesh"),
material = asset.resolve("@builtin::materials.lit_checkerboard", "material") })
ground.component.add("BoxCollider", {})
ground.localPosition = { 0, -0.1, 10 }
ground.localScale = { 60, 0.2, 60 }
-- SecondWind's world rules: one per scene, on a synced entity.
local rules = entity.spawnSynced("HealthRules")
rules.component.add(HK.RULES, { preset = "arcadeShooter", playerDeathStyle = "timed" })
-- Spawn points: plain entities (only the host reads them).
local A = { 0, 0, 20 }
local dirs = { ArenaNorth = { 0, 9 }, ArenaSouth = { 0, -9 }, ArenaEast = { 9, 0 }, ArenaWest = { -9, 0 } }
for name, d in dirs do
local p = entity.spawn(name, { position = { A[1] + d[1], 0, A[3] + d[2] } })
SK.addSpawnPoint(p, { group = "Arena", kind = "portal" })
end
-- The spawner: on a SYNCED entity, playing the waves in arenaWaves.data.
local spawner = entity.spawnSynced("Arena", { position = A })
SK.addSpawner(spawner, {
pattern = "portal", effect = "auto", curve = "steady",
waves = asset.resolve("arenaWaves", "data"),
maxAlive = 10, behavior = "chase", aggroRadius = 13, prewarm = 6,
})
-- A turret in the middle of the arena that reaches every portal, and the readout.
SK.addTurret(entity.spawn("ArenaTurret", { position = A }), { range = 12, only = "Arena" })
SK.addReadout(entity.spawn("PoolReadout"), { spawner = "Arena", corner = "topLeft" })
-- The player, with a SecondWind body (as in the gallery).
local setups = entity.spawn("PlayerSetups")
local prototype = entity.spawn("Player", { parent = setups })
prototype:setParticipation("PrototypeOnly")
local body = entity.spawn("body", { parent = prototype })
body.component.add("Asset", { source = asset.resolve("@builtin::avatars.humanoid", "avatar") })
HK.attach(body, { team = "players" })
local rig = entity.spawn("CameraRig", { parent = prototype })
rig:setNetworkScope("OwnerOnly")
rig.component.add("Camera", { behavior = asset.resolve("@builtin::controller.orbital_follow", "component") })
rig.localPosition = { 0, 2.2, -4.5 }
rig.localRotation = { 0, -0.9961332, -0.0878564, 0 }
prototype.component.add("PlayerPrototype", { body = body, camera = rig })
-- The player starts inside the arena, in the turret's reach.
local spawn = entity.spawn("Start", { parent = entity.spawn("Spawns"), position = { A[1], 0, A[3] - 6 } })
spawn.component.add("PlayerSpawn", { prototype = prototype })
end
```
Then make the waves: a folder `/source/arenaWaves.data` holding this `values.yaml` (word for word the kit's own `threeWaves.data`), plus a `.metadata` with a description and tags. The point names match the spawn points above. The data leaves `curve` empty on purpose, so the Spawner's `curve = "steady"` decides how much harder each wave gets.
```yaml
contract: spawnerKit.waveTable
values:
curve: ""
loop: false
waves:
- name: Scouts
delay: 3
gap: 1.0
points: [ArenaNorth, ArenaSouth]
enemies:
- { kind: grunt, count: 4 }
- { kind: runner, count: 2, gap: 0.5 }
- name: Pincer
delay: 4
gap: 0.7
points: [ArenaEast, ArenaWest]
order: mixed
enemies:
- { kind: grunt, count: 4 }
- { kind: flyer, count: 3 }
- name: The Brute
delay: 5
gap: 0.6
points: [ArenaNorth, ArenaEast, ArenaSouth, ArenaWest]
enemies:
- { kind: runner, count: 6, gap: 0.3 }
- { kind: brute, count: 1 }
- { kind: spitter, count: 2 }
```
Press play: after 3 s the Scouts come out of the north and south portals, then the Pincer out of east and west, then the Brute out of all four. On the steady curve the three waves bring 6, 9 and 13 enemies (as written they are 6, 7 and 9; steady adds 15% a wave, rounded up per entry).
To react to what happens, listen in code that runs while the game plays, such as the scene's `entrypoint.luau` (a `build.luau` runs while you author, not in play). Events fire on every peer, so every player's screen can react:
```lua
local SK = require("spawnerKit.api")
local conns = {}
function onLoad()
table.insert(conns, SK.on("waveStarted", function(e)
print(`{e.spawnerName}: wave {e.wave} of {e.waves}, "{e.name}", {e.total} enemies`)
end))
table.insert(conns, SK.on("despawned", function(e)
if e.reason == "killed" then print(`a {e.kind} went down`) end
end))
table.insert(conns, SK.on("allWavesDone", function(e)
print(`all {e.waves} waves done in {e.seconds} s: {e.killed} killed, {e.escaped} escaped`)
end))
end
function onUnload()
for _, c in conns do c:Disconnect() end
end
```
## Swap one setting
Every choice is one field. Nothing else needs to change.
```lua
-- In the build: a different arrival, effect, curve or look.
SK.addSpawner(spawner, { pattern = "sky", effect = "impact", curve = "breather", look = "neon", waves = ... })
-- While playing (on the host, see Multiplayer):
SK.setPattern("Arena", "burrow") -- next spawn rises out of the ground
SK.setEffect("Arena", "beam") -- "auto" goes back to the pattern's own effect
SK.setCurve("Arena", "steep")
```
- A pattern change applies from the next spawn. With `effect = "auto"` the effect follows the pattern (see the Patterns table).
- `pattern` is the setting's name. `style` is its older name and still works: `style = "sky"` in `SK.addSpawner` options sets the pattern, `SK.setStyle` is `SK.setPattern`, and a pattern id written straight into the Spawner's `style` field is used instead of `pattern` (leave `style` empty to let `pattern` decide).
- **Swapping the curve changes the waves.** In the [Use it](#use-it) example, change `curve = "steady"` to `curve = "steep"` in the build and the same three waves bring 6, 10 and 17 enemies instead of 6, 9 and 13, with more health and a faster pace; `breather` gives 6, 9 and 14, and `flat` or `stepped` give 6, 7 and 9 (stepped's first step up comes at wave 4). `SK.setCurve` while playing applies from the next wave that starts. `SK.planWave(t, n, { curveOverride = "steep" })` shows a wave's plan on any curve without playing it.
- **A curve named in the wave data wins** over the Spawner's `curve` field: a wave's own `curve`, then the table's `curve`, then the field. That is why the example data (like the kit's `threeWaves.data`) leaves `curve` empty (`""`): the Spawner's `curve` field and `SK.setCurve` decide. Write a curve into the data only when that table should always use it, and then neither of them changes its waves.
- Unknown ids are refused with an error that lists the known ones.
## Catalog
Everything the kit offers is labelled. `SK.catalog()` returns it all; `SK.find(query)` filters it:
```lua
SK.find({ kind = "pattern", genre = "towerDefense" }) -- point, path, burrow, trickle, scripted
SK.find({ kind = "effect", tag = "zombies" }) -- dirt
SK.find({ kind = { "pattern", "effect" }, genre = "bulletHell" })
SK.vocabulary() -- the kinds, families per kind and genres the labels use
```
Query keys are `kind` (pattern, effect, curve, enemy, look; the entries of the pattern list carry `kind = "style"`, and `kind = "style"` finds them too), `family`, `genre`, `tag` and `id`; each takes one value or a list (any of them matches), and every key given must match. An unknown key or kind is an error. Genres: waveShooter, hordeMode, towerDefense, arena, survival, bulletHell, platformer, roguelike, coop, boss.
### Spawn patterns (`pattern`)
| id | label | family | what it does | effect on auto | settings | tags | genres |
|---|---|---|---|---|---|---|---|
| `point` | Spawn point | placed | Each enemy appears exactly on one of the spawner's spawn points, picked in turn or at random. | smoke | points, pointOrder | classic, predictable, doors | waveShooter, arena, towerDefense, hordeMode, coop |
| `area` | Random in area | placed | Each enemy appears at a random spot inside a spawn point's box (sizeX by sizeZ), so a field fills up unevenly. | sparkle | points | scattered, organic | hordeMode, survival, arena, roguelike |
| `ring` | Ring around player | aroundPlayer | Enemies appear on a circle of ringRadius metres around a player and close in from every side. | smoke | ringRadius, target | surrounded, pressure, vampire-survivors | hordeMode, survival, bulletHell, roguelike |
| `offscreen` | Just off screen | aroundPlayer | Enemies appear just beyond the edge of the target player's view and walk in, so nobody sees them pop in. | none | offscreenMargin, target | endless, seamless, never-seen-appearing | hordeMode, survival, bulletHell, roguelike |
| `path` | Along a path | route | Enemies enter at the start of a path and walk a smooth curve through the spawn points of one group, in order, to the end: a Catmull-Rom spline from the engine's spline module (`@builtin::modules.spline`), drawn on the ground on every peer (`showPath`). | none | points, pathSpread, showPath | lanes, conveyor, marching, curved | towerDefense, platformer, arena |
| `portal` | Out of a portal | entrance | A swirling portal opens on a spawn point and each enemy steps out of it, growing from nothing. | portal | points | magic, rift, gate | arena, waveShooter, boss, roguelike |
| `sky` | Drop from the sky | entrance | A shadow marks the spot, then the enemy falls from skyHeight metres and lands with an impact. | impact | skyHeight, points | drop-pod, airborne, telegraphed | arena, waveShooter, survival, coop |
| `burrow` | Burrow up from the ground | entrance | The ground bulges, dirt bursts out and the enemy rises out of the floor from burrowDepth metres down. | dirt | burrowDepth, points | zombies, underground, creepy | hordeMode, survival, arena, towerDefense |
| `trickle` | Endless trickle | timing | No waves: one enemy every 1/rate seconds, forever (or until `total`), never more than maxAlive at once. Difficulty climbs every `trickleStep` spawns. | smoke | rate, maxAlive, total, trickleStep | endless, steady-stream, no-waves | survival, hordeMode, towerDefense |
| `scripted` | Scripted wave table | timing | Every spawn is written down: in each wave's `script` list, the second it happens, the enemy and the spawn point. Nothing is random. | beam | waves | authored, exact, set-piece | waveShooter, towerDefense, boss, arena |
How they enter: `point`, `area`, `ring`, `path`, `trickle` and `scripted` grow in over 0.35 s; `portal` grows over 0.8 s; `sky` falls (for 0.85 s from the default 9 m); `burrow` rises over 1.1 s; `offscreen` simply walks in. `area`, `sky` and `burrow` pick a random spot in a spawn point's box when it has a `sizeX`/`sizeZ`. With no spawn points at all, `ring`, `trickle` and `path` fall back to a ring around a player, and the others use the spawner's own position.
### Spawn effects (`effect`)
Each effect is juiceKit presets plus, for some, a few pooled shapes of the kit's own.
| id | label | family | what it does | juiceKit presets | tags | genres |
|---|---|---|---|---|---|---|
| `smoke` | Puff of smoke | classic | A round puff of smoke and a pop-in squash. | vfxSmoke, popIn | cartoon, ninja, poof | arena, waveShooter, platformer, coop |
| `portal` | Portal swirl | magic | A purple ring spins open on the ground, magic sparks burst out, and the enemy grows out of it. | vfxMagic, popIn | magic, purple, swirl | arena, roguelike, boss |
| `beam` | Sci-fi beam-in | scifi | A tall cyan beam of light drops onto the spot, crackles, and the enemy materialises inside it. | vfxZap, popIn | teleport, cyan, energy | waveShooter, arena, bulletHell |
| `dirt` | Dirt burst | ground | Clods of dirt and dust burst up out of the ground where the enemy surfaces. | vfxDust, jellyWobble | earth, rubble, zombies | hordeMode, survival, towerDefense |
| `impact` | Landing impact | impact | A dust ring, a ground shockwave and a short shake that nearby players feel. | landingHard | heavy, shockwave, shake | arena, survival, boss, coop |
| `sparkle` | Sparkle pop | magic | A bright pop with a burst of magic sparkles, juiceKit's own spawn combo. | spawn | cute, friendly, light | platformer, arena, coop |
| `none` | No effect | none | Enemies simply appear. Cheapest, for very large hordes. | none | quiet, performance | towerDefense, survival, bulletHell |
`sky` and `burrow` also telegraph: a shadow grows where a drop will land, a mound of dirt rises before a burrow, and the effect plays when the enemy arrives.
### Difficulty curves (`curve`)
| id | label | family | what it does | tags | genres |
|---|---|---|---|---|---|
| `steady` | Steady | linear | Every wave a little harder than the last: +15% enemies, +12% health, +6% pace per wave. | gentle, fair, predictable | waveShooter, towerDefense, coop, arena |
| `steep` | Steep | exponential | Grows by a percentage each wave (x1.32 enemies, x1.28 health), so wave 8 is a wall. | brutal, runaway, short-runs | hordeMode, survival, roguelike, bulletHell |
| `stepped` | Stepped plateaus | stepped | Three waves at the same level, then a big jump: room to learn each tier before the next. | tiers, chapters, learnable | towerDefense, arena, waveShooter |
| `breather` | With breather waves | rhythm | Climbs a little faster than steady, but every fourth wave is a breather: half the enemies at a gentle pace. | pacing, rest, intense | coop, hordeMode, waveShooter, survival |
| `flat` | Flat | flat | Every wave exactly as written in the data. For hand-tuned tables. | exact, tuning, tests | towerDefense, boss, arena |
### Sample enemies (`kind`)
| id | label | family | what it does | health / speed / damage / size | tags | genres |
|---|---|---|---|---|---|---|
| `grunt` | Grunt | melee | The everyday foot soldier: walks at the nearest player and hits on contact. | 40 / 2.6 / 10 / 0.9 | basic, walker | waveShooter, hordeMode, arena, towerDefense |
| `runner` | Runner | fast | Small and quick: twice as fast as a grunt with half the health. | 20 / 5.2 / 6 / 0.6 | fast, fragile, swarm | hordeMode, survival, arena |
| `brute` | Brute | heavy | Big, slow and hard to put down: five grunts' worth of health and a heavy hit. | 200 / 1.5 / 25 / 1.6 | tank, slow, big | arena, towerDefense, boss, coop |
| `flyer` | Flyer | flying | Hovers two metres up and swoops at players, ignoring the ground. | 30 / 3.6 / 8 / 0.7 | hover, airborne, drone | waveShooter, bulletHell, arena, survival |
| `spitter` | Spitter | ranged | Stops eight metres away and lobs damage at the nearest player every two seconds. | 35 / 2.2 / 7 / 0.85 | ranged, keeps-distance | waveShooter, arena, survival |
Melee enemies hit once a second on contact (physical damage, knockback 4); the spitter hits every 2 s from 8 m (poison damage). The flyer's body is drawn raised and bobs, but like every enemy it moves on the spawner's ground height (see Known limits).
Your own kinds: `SK.defineEnemy("goblin", { health = 30, speed = 4, damage = 5, size = 0.8, label = "Goblin", build = function(root, look) ... return parts end })`. Leave `build` out to borrow the grunt's look, or spawn local (`temporary = true`) children under `root` and return them. Every peer builds looks locally and checks wave data against the known kinds, so call `defineEnemy` in code that runs on every peer in play (a module your components require, or the scene's `entrypoint.luau`), not in `build.luau`.
### Looks (`look`)
| id | label | what it does | tags | genres |
|---|---|---|---|---|
| `toy` | Toy | Bright plastic shapes with big round eyes. | bright, plastic, friendly | platformer, arena, coop, towerDefense |
| `neon` | Neon | Dark bodies with glowing edges and eyes, readable at night and on dark arenas. | glowing, dark, synthwave | waveShooter, bulletHell, arena, survival |
The Spawner's `look` can also be `mixed` (alternating toy and neon); a wave entry's or script line's `look` overrides it.
## Waves as data
Waves live in a `.data` file of the `spawnerKit.waveTable` contract, given to the Spawner's `waves` field (`asset.resolve("<name>", "data")`). The same shape works as a Lua table through `SK.setWaves(sp, t)` or the Spawner's `waveTable` field (used when `waves` is empty); in Lua a bare list of waves is accepted too. Check a table with `SK.validateWaves(t)` and see exactly what a wave will do with `SK.planWave(t, n)` or `sp:planWave(n)`.
### Fields
| field | default | meaning |
|---|---|---|
| `curve` | `""` (none) | Difficulty curve for the whole table: steady, steep, stepped, breather, flat. Beats the Spawner's `curve`. |
| `loop` | `false` | After the last wave, start over from wave 1, harder each time (the wave number and so the curve keep climbing). The Spawner's `loop` field forces it on. |
| `waves[]` | required | The waves, in order. At least one. |
| `waves[].name` | `"Wave <n>"` | Shown in events and the readout. |
| `waves[].delay` | `2` | Seconds of waiting before this wave starts (see below for when the wait begins). |
| `waves[].gap` | `0.8` | Seconds between two spawns of this wave, divided by the curve's pace. |
| `waves[].points` | spawner's `points` | Spawn point names (or group names) the wave's spawns cycle through, in turn. |
| `waves[].order` | `inOrder` | `inOrder`: all of the first entry, then all of the next. `mixed`: one of each entry in turn. |
| `waves[].curve` | `""` | A curve for this wave only; beats the table's and the Spawner's. |
| `waves[].maxAlive` | `0` (use the Spawner's) | Most of this spawner's enemies alive at once while this wave spawns; above 0 it replaces the Spawner's `maxAlive`. |
| `waves[].enemies[].kind` | required | Enemy kind id: grunt, runner, brute, flyer, spitter or one you defined. |
| `waves[].enemies[].count` | `1` | How many; multiplied by the curve's count and rounded up (never below 1 when above 0). |
| `waves[].enemies[].gap` | the wave's `gap` | Seconds before each of this entry's spawns (divided by pace). |
| `waves[].enemies[].points` | the wave's `points` | Spawn points for this entry only. |
| `waves[].enemies[].look` | the Spawner's `look` | `toy` or `neon`. |
| `waves[].enemies[].health` | `1` | A **multiplier** on the kind's health (on top of the curve and `healthScale`). |
| `waves[].enemies[].speed` | `1` | A **multiplier** on the kind's speed (on top of the curve and `speedScale`). |
| `waves[].script[].at` | `0` | Seconds after the wave starts (after its delay). Not scaled by the curve's pace. |
| `waves[].script[].kind` | required | Enemy kind id. |
| `waves[].script[].point` | the wave's `points`, in turn | Spawn point name (or group name). |
| `waves[].script[].look` | the Spawner's `look` | `toy` or `neon`. |
A wave needs `enemies` or a `script`. When a wave has a non-empty `script`, it is played instead of `enemies`, whatever the pattern, and the curve does not change its count or timing (it still scales health, speed and damage). Unknown keys, unknown kinds or curves, negative delays and gaps, and counts that are not whole numbers are errors that name the wave and field. A Spawner whose table is missing or invalid reports the error on the component (and in `SK.state(sp).error`) and runs an endless trickle of its `enemy` instead.
### How delay, gap, advance and maxAlive work together
1. `start()` (or `autoStart`, or the MatchFlow round starting) waits wave 1's `delay`, then wave 1 begins and fires `waveStarted`.
2. The wave's spawns happen on a timetable: the first at 0 s, each next one a `gap` later (the entry's `gap` if it has one), divided by the curve's pace.
3. `maxAlive` caps how many of this spawner's enemies are alive at once (the wave's own `maxAlive` replaces it while that wave spawns; 0 means no cap). When the cap is reached the wave's clock **holds** at the next spawn until one is gone, so the remaining spawns shift later and keep their gaps.
4. When the last spawn is out, `advance` decides when the next wave's `delay` starts counting:
- `cleared` (default): once every enemy of this wave is gone. Waves never overlap.
- `timer`: right away. Waves can overlap; each still fires its own `waveCleared` when its enemies are gone.
5. A wave is cleared when all its spawns are out and none of its enemies is alive; that fires `waveCleared` (and calls MatchFlow's `clearWave()` when `matchEntity` is set). Clearing the last wave fires `allWavesDone`.
6. How many waves run: the table's length, or `wavesToRun` when it is above 0. A looping table with `wavesToRun = 0` is endless (its `waves` count is 0 in events and `allWavesDone` never fires).
7. After `allWavesDone`, `restartDelay` (≥ 0) starts the spawner again from wave 1 after that many seconds; -1 never does. With a `matchEntity`, the MatchFlow round restarts it instead.
## Difficulty curves
A curve turns a wave number into five multipliers: **count** (each entry's count, rounded up), **pace** (gaps are divided by it), **speed**, **health** and **damage** (each enemy's), plus `rest = true` on a breather wave. With `n = (wave - 1) × curveStrength`:
| curve | count | pace | speed | health | damage |
|---|---|---|---|---|---|
| `steady` | 1 + 0.15n | 1 + 0.06n | 1 + 0.04n | 1 + 0.12n | 1 + 0.05n |
| `steep` | 1.32^n | 1.12^n | 1.06^n | 1.28^n | 1.15^n |
| `stepped` (level L = floor((wave - 1) / 3) × strength) | 1 + 0.6L | 1 + 0.25L | 1 + 0.12L | 1 + 0.5L | 1 + 0.2L |
| `breather`, normal wave | 1 + 0.2n | 1 + 0.08n | 1 + 0.05n | 1 + 0.15n | 1 + 0.06n |
| `breather`, every 4th wave (rest) | 0.5 + 0.05n | 0.7 | 1 | 0.9 + 0.08n | 1 |
| `flat` | 1 | 1 | 1 | 1 | 1 |
Limits: count and pace stay within 0.1 to 12, speed 0.1 to 4, health 0.1 to 24, damage 0.1 to 12.
Count multiplier per wave at strength 1 (health in brackets):
| wave | steady | steep | stepped | breather | flat |
|---|---|---|---|---|---|
| 1 | 1.00 (1.00) | 1.00 (1.00) | 1.00 (1.00) | 1.00 (1.00) | 1 |
| 2 | 1.15 (1.12) | 1.32 (1.28) | 1.00 (1.00) | 1.20 (1.15) | 1 |
| 3 | 1.30 (1.24) | 1.74 (1.64) | 1.00 (1.00) | 1.40 (1.30) | 1 |
| 4 | 1.45 (1.36) | 2.30 (2.10) | 1.60 (1.50) | 0.65 (1.14) rest | 1 |
| 5 | 1.60 (1.48) | 3.04 (2.68) | 1.60 (1.50) | 1.80 (1.60) | 1 |
| 8 | 2.05 (1.84) | 6.98 (5.63) | 2.20 (2.00) | 0.85 (1.46) rest | 1 |
| 10 | 2.35 (2.08) | 12.00 (9.22) | 2.80 (2.50) | 2.80 (2.35) | 1 |
`curveStrength` scales how hard any curve bites (0 = flat, 2 = twice as steep). The trickle pattern uses level `1 + floor(spawns / trickleStep)` as its wave number. On top of the curve, the Spawner's `healthScale`, `speedScale` and `damageScale` multiply every enemy. Read any curve with `SK.curve(name, wave, strength)` or `SK.curveSeries(name, waves, strength)`.
## Pooling
Enemies are made once and reused. Each spawn takes an enemy of that kind out of the pool; when it dies, escapes, expires or is cleared, it goes back: hidden on every peer, parked underground at y = -400, its health components switched off so it costs nothing while it waits. A new entity is only **created** when the pool has no free enemy of that kind; every other spawn is **reused**, revived and healed to its new maximum by SecondWind.
So the entity count stays **flat**: it settles at the most enemies of each kind that were ever alive together (plus any prewarm), and wave 20 makes no more entities than wave 2. One synced entity per enemy is all that crosses the network; its look (one entity per shape) is built locally on each peer as temporary children. Effect shapes come from a small local pool too, so effects never grow the entity count either. The pool is shared by every Spawner in the scene and keyed by enemy kind.
- **Prewarm:** the Spawner's `prewarm` field makes that many enemies of the first wave's first kind (or the trickle's `enemy`) when it starts, so the first wave reuses instead of creating. `SK.prewarm(kind, n, look)` tops the free pool of a kind up to `n`, on the host.
- **Counters:** `SK.poolStats()` gives `{ created, reused, released, active, pooled, peakActive, entities }` on this peer; the host's are the real ones, and every peer reads them from `SK.state(sp).pool`.
- **The readout:** `SK.addReadout(e, opts)` shows, in a screen corner, how many enemies were created versus reused and the share of spawns reused, how many are in play and pooled, the scene's entity count (with its range over the last 30 s), script memory, each spawner's wave (`wave 2/3 next in 4s`, `all 3 waves done`) and, with `match`, the MatchFlow round. It reads the Spawners' synced snapshots, so every player sees the host's numbers.
## Events
```lua
local conn = SK.on("waveCleared", function(e) print("cleared", e.name) end)
SK.on("*", function(name, e) print(name, e.wave) end) -- every event: fn(name, payload)
conn:Disconnect()
```
Exactly five events, plus `"*"` for all of them. An unknown name is an error. Every payload carries `spawner` (the Spawner's entity id) and `spawnerName` (its entity name).
| event | when | payload keys |
|---|---|---|
| `waveStarted` | A wave began. | `spawner, spawnerName, wave, waves, name, total, rest, scale` (scale = `{ count, pace, speed, health, damage }`) |
| `waveCleared` | Every enemy of a wave was spawned and is gone. | `spawner, spawnerName, wave, waves, name, killed, escaped, seconds` |
| `spawned` | An enemy appeared. | `spawner, spawnerName, enemy, kind, look, pattern, style (the same as pattern), effect, wave, position, reused` |
| `despawned` | An enemy left play and went back to the pool. | the `spawned` keys plus `reason`: `killed`, `escaped`, `expired`, `cleared` or `reset` |
| `allWavesDone` | The last wave was cleared. | `spawner, spawnerName, waves, killed, escaped, seconds` |
- `enemy` is the enemy's entity id; `position` is where it appeared (`{x, y, z}`), in `despawned` too; `reused` is true when it came from the pool; `wave` is 0 for a trickle or a manual spawn.
- `waves` is the number of waves the spawner will run, 0 for an endless one. `seconds` is from the wave's start (or, in `allWavesDone`, from `start()`) to the clear.
- In `waveCleared`, `escaped` counts every enemy of the wave that was not killed. In `allWavesDone`, `killed` and `escaped` are the run's totals (`escaped` there counts escaped and expired enemies).
- **Events fire on every peer.** The host fires them as it decides. Other peers fire the wave events when the Spawner's synced snapshot says so, and `spawned`/`despawned` when an enemy's synced spawn counter or `active` flag changes. A player who joins later does not get a replay of what already happened.
- `SK.eventCounts()` tells how often each fired on this peer and the last 40.
## Multiplayer
- **One peer is in charge of each spawner: the owner of its synced entity** (normally whoever created it; this README calls it the host). Only it runs the waves, picks positions with its seeded random stream and spawns. Put the Spawner on an entity made with `entity.spawnSynced`; `SK.addSpawner` warns when it is not.
- **Enemies are synced entities owned by the host.** The host moves them, applies their damage and decides when they die. Every peer builds each enemy's look locally from its synced `kind` and `look`, shows or hides it from `active`, and plays the spawn effect locally (juiceKit `scope = "local"`) when the enemy's spawn counter `seq` changes, so every player sees the same effect at the same spot without an extra message. Turrets aim and draw their zaps locally on every peer; only the host's damage counts.
- **The snapshot:** the host publishes what each spawner is doing (phase, wave, counts, pool, last events) in its synced `snapshot` field whenever something changes and at least twice a second. `SK.state(sp)` reads it, the same on every peer.
- **Calls from any peer:** `start`, `stop`, `reset`, `nextWave` and `spawn` called on a peer that is not in charge are sent to the host on the channel `spawnerKit:<entityId>` (the Spawner's entity id) and carried out there. `despawnAll`, `SK.despawn` and `SK.prewarm` act only on the host; the setters (`setPattern`, `setStyle`, `setEffect`, `setCurve`, `setWaves`) write the Spawner's synced fields and are not forwarded, so call them where `SK.isAuthority(sp)` is true.
- **Host migration:** every other peer checks the spawner's owner twice a second. When the owner has left (or nobody owns it), the lowest remaining peer claims the entity after 0.5 s (any peer after 4 s). The new host adopts the enemies it now owns from the pool and carries on from the snapshot: the same wave, the next spawn in the plan, the same kill counts.
- **What the kit does against duplicate or missing enemies:** exactly one peer spawns. An entity no peer owns yet counts as the room host's (`multiplayer.isHost()`), so even then only one peer acts on it. Enemies are real synced entities, so every peer is meant to see the same set, and looks and effects come from their synced fields rather than from messages that could be lost. A new host resumes the current wave at the spawn after the last one the snapshot recorded; the one gap is a spawn made in the frame between the old host's last snapshot and its leaving. No duplicate enemy was ever seen in testing. Earlier releases saw new enemies reach a second player late; the engine issue behind that (#19353) is fixed. `SK.syncReport()` and the readout show, on every screen, whether the players see the same enemies (see [Two-player check](#two-player-check)).
### Two-player check
To see for yourself whether two machines show the same thing: open the world on two machines signed in to two different accounts, press Play on both, and read `SK.syncReport()` on each (the readout shows the same verdict on both screens). Every 2 s the host sends every other player a digest of its enemies and spawners, and each player compares it with its own view and counts missing, extra, duplicate, spawnSpot, drift, wave and peerSpawned problems. A difference counts only when it shows in two digests in a row, and the readout turns red only for a difference that is still there (a duplicate or a non-host spawn at once). `multiplayer.explain(enemyId, "spawnerKit.Enemy", "active")` says why a value is not arriving.
- **1.1.0:** checked on one machine only. The agent that prepared this release had one engine, cannot open a browser copy of the world (#20946), and a second engine on the same account joins as the same player (#14448). On that machine the README example played 6, 9 and 13 enemies in a brand-new world, and the kit's sync check reported no other player.
- **1.0.0 (two machines, the desktop app and a browser tab):** in every session only the host created enemies and no duplicate was ever seen. In the best session (the arena alone, three waves from `threeWaves.data`), the other player saw the same enemies with the same ids at the same spawn spots, live positions 0.1 to 0.6 m apart on average (worst 1 m, about one network update), and the same wave counters: 6, 9 and 13 on the steady curve. A browser tab running the full gallery at 6 to 10 fps fell a few seconds behind on reused enemies. Two kit bugs those sessions found are fixed: a player who was not in charge prewarmed pool enemies of their own when a MatchFlow round started, and a reused enemy could flash at its previous place on the other screen.
## MatchFlow
Set the Spawner's `matchEntity` to the name of an entity carrying `MatchFlow` (format `waves` fits best) and the spawner plays inside its rounds:
- the waves start when the round enters `playing` (with `autoStart` on);
- each cleared wave calls the match's `clearWave()`, so a `waves` round with `waves = 3` ends in victory when the third wave is cleared;
- when the round leaves `playing`, the spawner resets: every enemy back to the pool (`despawned` with reason `reset`), ready for the next round. `restartDelay` is ignored.
- If no peer runs the MatchFlow (its entity is owned by nobody and not in charge anywhere), the host plays the waves without it after 5 s and logs a warning.
```lua
local match = entity.spawnSynced("Match")
match.component.add("MatchFlow", { format = "waves", waves = 3, roundSeconds = 0, minPlayers = 1 })
SK.addSpawner(entity.spawnSynced("Arena", { position = A }), { waves = asset.resolve("arenaWaves", "data"), matchEntity = "Match" })
```
Give the readout `match = "Match"` to show the round's phase and cleared waves, and SecondWind's Rules `matchEntity = "Match"` so its round ends with MatchFlow's.
## SecondWind
Health, damage and death are SecondWind's. Every enemy gets `SecondWind.Vitals` (and Lifeline's health) through `HK.attach` with model `hitPoints`, death style `stay`, team `enemies` and no fall damage; on every spawn its maximum health is set to kind health × curve × `healthScale` × the entry's `health`. So:
- **Hurt enemies with SecondWind:** `HK.damage(enemyEntity, 25, { by = attacker, type = "fire" })` from your weapons. A killed enemy lies there for 0.7 s, then goes back to the pool (`despawned`, reason `killed`). `HK.explode`, traps and SecondWind's hit effects all work on them.
- **Enemies hurt players** with `HK.damage` (contact hits, the spitter's shots) and only chase players SecondWind says are alive, so give player bodies health: `HK.attach(body, { team = "players" })`, and one synced `SecondWind.Rules` entity in the scene.
- `healthBars` draws Lifeline's bar over each enemy.
## juiceKit
The spawn effects are juiceKit presets (see the Effects table) played with `scope = "local"` on every peer, plus the kit's own pooled shapes. The turret's sparks are local too; the spitter's shot plays juiceKit's `vfxZap` at the player it hits. juiceKit's global intensity and reduce-motion settings apply to all of them. Play an effect yourself, on this peer only, with `SK.playEffect("portal", { x, y, z }, { size = 1.5 })`.
## Reference
### Spawner component (on a synced entity)
All fields are synced.
| field | default | meaning |
|---|---|---|
| `pattern` | `point` | The spawn pattern, how enemies arrive: point, area, ring, offscreen, path, portal, sky, burrow, trickle or scripted. Swap it and nothing else changes. |
| `style` | `""` | Older name for `pattern`. Empty lets `pattern` decide; a pattern id here is used instead of `pattern`. `SK.addSpawner`, `SK.setPattern` and `SK.setStyle` always write `pattern` and leave this empty. |
| `effect` | `auto` | Spawn effect every player sees: smoke, portal, beam, dirt, impact, sparkle or none; auto picks the pattern's own. |
| `curve` | `steady` | Difficulty curve: steady, steep, stepped, breather or flat. A curve named in the wave data wins. |
| `curveStrength` | `1` | How hard the curve bites: 1 as designed, 0 flat, 2 twice as steep. |
| `waves` | none | A .data file of the waveTable contract: the waves this spawner plays. |
| `waveTable` | `{}` | Waves as a Lua table (set by SK.setWaves); used when `waves` is empty. |
| `wavesToRun` | `0` | How many waves to play: 0 = every wave in the table (endless when it loops). |
| `loop` | `false` | After the last wave, start the table over, harder each time (the curve keeps climbing). |
| `enemy` | `grunt` | Enemy kind for a trickle, and for manual spawns that name none. |
| `enemies` | `""` | A trickle's mix: comma list of kinds it picks from in turn (empty = `enemy`). |
| `look` | `toy` | How the enemies look: toy, neon, or mixed (alternating). |
| `points` | `""` | Spawn points this spawner uses: comma list of point names or group names. Empty = the points whose group is this spawner's name, else every point. |
| `pointOrder` | `cycle` | When a spawn names no point: take the points in turn, or at random. |
| `target` | `nearest` | Whom ring and offscreen spawn around: nearest, random, each (in turn), or the name of an entity. |
| `rate` | `1` | Trickle: spawns per second. |
| `maxAlive` | `12` | Most enemies of this spawner alive at once; a spawn waits until one is gone. 0 = no limit. |
| `total` | `0` | Trickle: stop after this many spawns (0 = endless). |
| `trickleStep` | `10` | Trickle: the difficulty curve goes up one level every this many spawns. |
| `advance` | `cleared` | When the next wave's delay starts: once this wave is cleared, or once it has finished spawning. |
| `autoStart` | `true` | Start by itself when play begins (or when the MatchFlow round starts); when false, call start(). |
| `restartDelay` | `-1` | Seconds after the last wave is cleared before the spawner starts again from wave 1; -1 = never (a MatchFlow round restarts it instead). |
| `behavior` | `chase` | What spawned enemies do: chase players, wander near where they appeared, march (path pattern), or hold still. |
| `aggroRadius` | `0` | Enemies only chase players within this many metres of the spawner; 0 = any distance. |
| `wanderRadius` | `4` | How far a wandering enemy roams from where it appeared, in metres. |
| `goal` | `""` | Name of a spawn point (or any entity) enemies head for when nobody is in reach; reaching it counts as escaping. |
| `lifetime` | `0` | Seconds an enemy stays before leaving by itself (reason 'expired'); 0 = never. |
| `healthBars` | `true` | Draw Lifeline's health bar over each enemy. |
| `healthScale` | `1` | Multiplies every enemy's health, on top of the curve. |
| `speedScale` | `1` | Multiplies every enemy's speed, on top of the curve. |
| `damageScale` | `1` | Multiplies every enemy's damage, on top of the curve. |
| `ringRadius` | `9` | Ring pattern: distance from the player, in metres. |
| `offscreenMargin` | `4` | Offscreen pattern: how far past the edge of the view, in metres. |
| `offscreenDistance` | `14` | Offscreen pattern: distance from the player, in metres. |
| `skyHeight` | `9` | Sky pattern: drop height, in metres. |
| `burrowDepth` | `1.6` | Burrow pattern: how deep they start, in metres. |
| `pathSpread` | `0.6` | Path pattern: sideways jitter so a column does not walk in single file, in metres. |
| `showPath` | `true` | Path pattern: draw the smooth curve the enemies walk on the ground, on every peer (small local dots, rebuilt when the pattern or the points change). |
| `prewarm` | `0` | Make this many enemies of the first kind into the pool before the first spawn. |
| `seed` | `1` | Seed for every random choice the host makes. |
| `matchEntity` | `""` | Name of an entity with MatchFlow: waves start when its round starts, each cleared wave calls clearWave(), and a round ending resets the spawner. |
| `snapshot` | `{}` | Written by the host only: what the spawner is doing, for every other peer. Read it through getState(). |
Enemies that `wander` roam around the spot where they appeared; `chase` enemies measure `aggroRadius` from the spawner, head for `goal` when nobody is in reach, and wander when there is no goal. The `path` pattern always makes its enemies march their route; reaching the end counts as escaping.
### Spawner methods
| method | what it does |
|---|---|
| `sp:start()` | Start from wave 1 (or start the trickle). On a peer that is not in charge the request goes to the host. |
| `sp:stop()` | Stop spawning; enemies already out stay. |
| `sp:reset()` | Stop, send every enemy of this spawner back to the pool (reason 'reset') and go back to before wave 1. |
| `sp:nextWave()` | Skip the wait before the next wave. |
| `sp:spawn(kind?, opts?) -> entity?` | Spawn one enemy now with this spawner's pattern and effect. opts: `{ point, look, health, speed }`. Returns the entity on the host, nil elsewhere (the host spawns it). |
| `sp:despawnAll(reason?)` | Send every enemy of this spawner back to the pool now (default reason `cleared`). Host only. |
| `sp:setWaves(t) -> (ok, errors)` | Put waves in as a Lua table (the same shape as the waveTable data), replacing the data file. Takes effect at the next start(). |
| `sp:getState()` | What this spawner is doing, the same on every peer: `phase` (idle, waiting, spawning, clearing, trickle, done, stopped), `running, wave, waves, name, spawned, total, alive, waveAlive, killed, escaped, spawnedTotal, nextIn, pool, entities, memoryKb, pattern, style (the same), curve, effect, host, error` and the last event payloads. |
| `sp:isAuthority() -> boolean` | Whether this peer is the one deciding and spawning for this spawner. |
| `sp:alive() -> { id }` | The entity ids of this spawner's enemies in play. |
| `sp:planWave(n)` | The wave plan this spawner would follow for wave n (who, when, from where), without spawning anything. |
### SpawnPoint component (on any entity; not synced)
Its transform is the spot. Every peer has the same scene and only the host reads it.
| field | default | meaning |
|---|---|---|
| `group` | `""` | Group name. A Spawner's `points` can name a group instead of single points; the points of one group, sorted by `order`, make a path. |
| `order` | `0` | Position along its group's path (lowest first). |
| `kind` | `point` | Which marker it draws: a pad, an area outline, a standing portal ring or a path dot. Every pattern can use every kind. |
| `sizeX` | `0` | Width of the area in metres (patterns area, sky and burrow pick a random spot inside); 0 = a single spot. |
| `sizeZ` | `0` | Depth of the area in metres. |
| `showMarker` | `true` | Draw the marker in play as well as in the editor. |
| `color` | orange | Colour of the marker. |
Method: `point:record()` returns `{ name, pos, sizeX, sizeZ, yaw, group, order, kind }`, what the placement maths reads.
### Turret component (on any entity; not synced)
| field | default | meaning |
|---|---|---|
| `range` | `10` | How far the turret reaches, in metres. |
| `interval` | `0.7` | Seconds between shots. |
| `damage` | `15` | Damage per shot (SecondWind damage). |
| `damageType` | `electric` | SecondWind damage type (physical, fire, ice, electric, poison), which picks the hit effect. |
| `only` | `""` | Only shoot enemies of this spawner (its entity name); empty = any enemy. |
| `color` | cyan | Colour of the turret's head and zap. |
### PoolReadout component (on any entity; local)
| field | default | meaning |
|---|---|---|
| `spawner` | `""` | Name of one Spawner to show; empty shows every spawner in the scene. |
| `corner` | `topLeft` | Which corner of the screen it sits in (topLeft, topRight, bottomLeft, bottomRight). |
| `title` | `spawnerKit pool` | Heading of the readout. |
| `maxSpawners` | `4` | Most spawner rows to list. |
| `match` | `""` | Name of a MatchFlow entity whose round to show (phase and wave); empty shows none. |
Method: `readout:numbers()` returns what it shows: `{ created, reused, active, pooled, entities, memoryKb, peer }`.
### Enemy component (added by the pool; you don't add it)
All fields are synced and written by the host.
| field | default | meaning |
|---|---|---|
| `kind` | `grunt` | Enemy kind id (grunt, runner, brute, flyer, spitter, or one a game defined). |
| `look` | `toy` | How it looks: toy or neon. |
| `active` | `false` | Whether it is in play; false means it is waiting in the pool, hidden. |
| `seq` | `0` | Bumped by the host each time this entity is spawned; every peer plays the spawn effect when it changes. |
| `uses` | `0` | How many times this entity has been spawned; above 1 means it was reused from the pool. |
| `spawner` | `""` | Entity id of the Spawner that spawned it. |
| `spawnerName` | `""` | Name of that Spawner, for events. |
| `wave` | `0` | The wave it belongs to (0 for a trickle). |
| `style` | `point` | The spawn pattern that placed it (the field keeps the older name). |
| `effect` | `smoke` | The spawn effect every peer plays when it appears. |
| `entrance` | `{}` | How it enters: `{ pos, from, entrance, duration }`. |
| `route` | `{}` | For the path pattern: the points of the smooth curve it walks, about 0.6 m apart. |
| `behavior` | `chase` | What it does once in play: chase players, wander near where it appeared, march its route, or hold still. |
| `speed` | `2.6` | Walking speed in metres per second (already scaled by the wave's difficulty). |
| `damage` | `10` | Damage per contact hit (or per shot for a spitter). |
| `aggroRadius` | `0` | Only chase players within this many metres of `home`; 0 = any distance. |
| `home` | `{}` | Centre of the area it guards or wanders in (`{x, y, z}`). |
| `wanderRadius` | `4` | How far from `home` a wandering enemy roams, in metres. |
| `goal` | `{}` | Where it heads when it has nobody to chase; reaching it counts as escaping (`{x, y, z}`, empty for none). |
| `lifetime` | `0` | Seconds before it leaves by itself (reason 'expired'); 0 = never. |
| `goneReason` | `""` | Why it last left play: killed, escaped, expired, cleared or reset. |
Method: `enemy:isAlive()`, whether it is in play and alive.
### `spawnerKit.api` (`local SK = require("spawnerKit.api")`)
Wherever a function takes a spawner (`sp`), it accepts the Spawner's entity, its entity name, or the component.
| function | what it does |
|---|---|
| `SK.addSpawnPoint(e, opts?) -> SpawnPoint` | Make an entity a spawn point. opts: group, order, kind (point/area/portal/path), sizeX, sizeZ, showMarker, color. |
| `SK.addSpawner(e, opts?) -> Spawner` | Make an entity a spawner. Use a SYNCED entity (entity.spawnSynced). opts are any Spawner fields. |
| `SK.addTurret(e, opts?) -> Turret` | Add a defence turret that zaps enemies through SecondWind. opts: range, interval, damage, damageType, only, color. |
| `SK.addReadout(e, opts?) -> PoolReadout` | Add the on-screen pool readout. opts: spawner, corner, title, maxSpawners, match. |
| `SK.spawner(x) -> Spawner?` | The Spawner component of an entity, an entity name, an id or a component; nil when there is none. |
| `SK.start(sp)` | Start a spawner from wave 1 (asks the host when called elsewhere). |
| `SK.stop(sp)` | Stop a spawner; enemies already out stay. |
| `SK.reset(sp)` | Reset a spawner: every enemy back to the pool, back before wave 1. |
| `SK.nextWave(sp)` | Skip the wait before a spawner's next wave. |
| `SK.spawn(sp, kind?, opts?) -> entity?` | Spawn one enemy now from a spawner, with its pattern and effect. opts: `{ point, look, health, speed }`. The entity on the host, nil elsewhere. |
| `SK.setPattern(sp, pattern)` | Swap a spawner's spawn pattern; takes effect from the next spawn. |
| `SK.setStyle(sp, pattern)` | Older name of `SK.setPattern`; does the same. |
| `SK.setEffect(sp, effect)` | Swap a spawner's spawn effect ("auto" follows the pattern). |
| `SK.setCurve(sp, curve)` | Swap a spawner's difficulty curve. |
| `SK.setWaves(sp, t) -> (ok, errors)` | Give a spawner waves as a Lua table (replacing its data file); takes effect at its next start. |
| `SK.state(sp)` | What a spawner is doing (the same on every peer). |
| `SK.isAuthority(sp) -> boolean` | Whether this peer decides and spawns for a spawner (the host). |
| `SK.despawn(enemy, reason?) -> boolean` | Send an enemy back to the pool now. reason: "killed", "escaped", "expired" or "cleared" (default). Host only; returns false elsewhere. |
| `SK.alive(sp?) -> { id }` | The ids of enemies in play: of one spawner, or of every spawner when sp is nil. |
| `SK.isEnemy(e) -> boolean` | Whether an entity (or id) is a spawnerKit enemy (pooled or in play). |
| `SK.validateWaves(t) -> (ok, errors)` | Check a wave table (Lua table or resolved waveTable data). Unknown enemy kinds are errors. |
| `SK.planWave(t, n, opts?)` | Plan wave n of a table without spawning: `{ wave, name, delay, total, duration, rest, spawns = { { t, kind, point, look, index } }, scale }`. opts: `{ curve = "steady", strength = 1, points = { "North" } }`. |
| `SK.loadWaves(ref)` | Read a waveTable .data asset (from asset.resolve("<name>", "data") or a Field.dataRef) into a plain table. |
| `SK.curve(name, wave, strength?)` | A difficulty curve's multipliers for one wave: `{ count, pace, speed, health, damage, rest, level }`. |
| `SK.curveSeries(name, waves, strength?)` | A curve's multipliers for waves 1..n, for graphs. |
| `SK.defineEnemy(id, def)` | Register an enemy kind for wave data. def: `{ health, speed, damage, size, hover, range, label, build = function(root, look) -> parts }`. |
| `SK.enemyKinds() -> { id }` | Every enemy kind id, sorted. |
| `SK.poolStats()` | The pool's counters on this peer: `{ created, reused, released, active, pooled, peakActive, entities }`. |
| `SK.prewarm(kind, n, look?)` | Make enemies of a kind into the pool ahead of time, until n wait there. Host only. |
| `SK.on(name, fn) -> conn` | Listen to a kit event on this peer; `conn:Disconnect()` stops it. |
| `SK.eventCounts()` | How many times each event fired on this peer, and the most recent ones. |
| `SK.catalog()` | Everything the kit offers, labelled: patterns (`styles`), effects, curves, enemies, looks, events, vocabulary and version. |
| `SK.find(query?) -> { entry }` | Catalog entries matching labels. Keys: kind, family, genre, tag, id; each a value or a list. |
| `SK.vocabulary()` | The words the catalog's labels use: kinds, families per kind, genres. |
| `SK.playEffect(id, pos, opts?)` | Play a spawn effect on this peer at a point. opts: `{ size, target }`. |
| `SK.effectStats()` | Effect counters on this peer: played, shapes made, shapes reused, live, pooled. |
| `SK.syncReport()` | Whether every player sees the same enemies. On a non-host peer, its own verdict against the host's latest digest; on the host, the verdict each other peer sent back. Counts missing, extra (duplicates included), duplicate, spawnSpot, drift, wave and peerSpawned problems, each once, with the last few as text. |
| `SK.syncCheck(opts)` | Tune the cross-peer check: `{ enabled = true, interval = 2, grace = 1.5, tolerance = 1.5 }`. |
Constants: `SK.VERSION` (`"1.1.8"`), the component assets `SK.SPAWNER`, `SK.SPAWN_POINT`, `SK.ENEMY`, `SK.TURRET`, `SK.READOUT`, and the id lists `SK.EVENTS`, `SK.PATTERNS` (also `SK.STYLES`), `SK.EFFECTS`, `SK.CURVES`, `SK.LOOKS`. The pure modules are reachable as `SK.waves`, `SK.curves`, `SK.placement`, `SK.pool` and `SK.util`.
## Tests
The kit's test suite is `spawnerKit` (92 tests, every public call). Run it in edit mode from the shell with `zero tests run spawnerKit`, or from Luau with:
```lua
tools.use("tests", "run", { suite = "spawnerKit" })
```
For 1.1.8 it passed 92 of 92, twice in a row, on the engine of 2026-11-10.
## Known limits
Open engine and platform issues spawnerKit is affected by:
- **Testing two players from one account** ([OrigoZero/zero#14448](https://github.com/OrigoZero/zero/issues/14448)). Two engines signed in to the same account collide as one player. To see what a second player sees, join with a second account.
- **Frame rate with many synced things** ([OrigoZero/zero#20750](https://github.com/OrigoZero/zero/issues/20750)). In a multiplayer session the frame rate drops as the number of synced entities grows, and every enemy (pooled ones included) is one synced entity. Keep `maxAlive` and `prewarm` modest, most of all for a browser tab.
- **Shared enemies after a lost connection** ([OrigoZero/zero#19490](https://github.com/OrigoZero/zero/issues/19490)). When both players lose their connection, pressing Play again does not rebuild the scene's shared objects (spawners, MatchFlow, health rules), so no spawner runs. The gallery guards against it: its entrypoint has the room's host recreate any missing shared objects at play start (`galleryShared`), and a game that builds its spawners with `entity.spawnSynced` in a scene build can do the same.
- **Long waits on test runs** ([OrigoZero/zero#19849](https://github.com/OrigoZero/zero/issues/19849)). A call that waits on the test suite can be handed back as a background task to wait on.
- **Browser builds are not checked by an agent** ([OrigoZero/zero#20946](https://github.com/OrigoZero/zero/issues/20946)). An agent cannot open its own copy of the world in a browser, so this release's checks ran in the desktop app.
- **Slow installs** ([OrigoZero/zero#21420](https://github.com/OrigoZero/zero/issues/21420)). spawnerKit brings four kits with it, and an install with several dependencies takes a while; "waiting for content" lines while it lands settle by themselves.
- **`has no root to resolve against` lines on every load** ([OrigoZero/zero#20407](https://github.com/OrigoZero/zero/issues/20407)). The log can show `module ... has no root to resolve against` (and "component source failed to load") lines for kits under `/source/deps/`. Once they appear in a world they do not settle after the install: they come back every time the world loads. In this world they name duplicate copies of Lifeline and MatchFlow under `deps`, and the gallery plays. Where the copy that fails is one a build needs, as with a second SecondWind (next entry), the build stops instead.
- **A kit installed twice** ([OrigoZero/zero#22816](https://github.com/OrigoZero/zero/issues/22816)). Installing a kit on its own when another install already brought it adds a second copy at `/source` and leaves the first under `/source/deps/`, instead of moving it up, and the log reports a `package collision`. Following the wave survival guide with aiKit installed before SecondWind left SecondWind 1.4.4 at `/source` and aiKit's 1.3.1 under `deps`, and the step 5 build then stopped with `no root to resolve against` for SecondWind's Vitals in the older copy: no walls, portals or waves. The guide now installs SecondWind first, which leaves one SecondWind, and the arena builds and plays. If a world already has two copies, start the guide again in a new world.
- **ZeroMind description one release behind** ([OrigoZero/zero#19258](https://github.com/OrigoZero/zero/issues/19258)). The description ZeroMind shows for the package can lag a release behind `package.yaml`; the package itself is current.
Limits of spawnerKit's own design:
- **Offscreen knows only the host's own camera.** Other players' cameras live on their own machines and are never sent. When the target is the host's own player, the offscreen pattern uses the host's real camera (its direction, field of view and aspect). For any other target (another player, or a named entity) it assumes a 60-degree, 16:9 camera looking along the target's facing, so with a free-orbiting camera an enemy can now and then appear inside that player's view. Raise `offscreenMargin` for more room, or use the `ring` pattern.
- **Cost per live enemy.** SecondWind's Vitals costs roughly 0.05 to 0.3 ms per live enemy per frame on desktop. On the engine of 2026-11-01 the full gallery (23 spawners, about 30 enemies in play, 52 labels) ran at a median of about 46 ms a frame on desktop, with SecondWind's Vitals the largest single script cost. Pooled enemies have their health components switched off and cost nothing. Keep `maxAlive` modest, especially in a browser tab.
- **Simple movement.** Enemies move kinematically on the spawner's ground height: no physics, no gravity, no pathfinding around walls. Use open arenas, `path` curves through gaps, or `behavior = "hold"` with your own movement. A path curve passes through every one of its points and swings round sharp corners; space the points out for gentle bends.
- **Damage numbers are all or nothing.** Lifeline draws floating damage numbers for every enemy on screen or for none (its HUD's `showNumbers`); a number can drift across a 3D label behind it. The gallery turns them on only while you are inside the arena, so the station labels stay clear.
- **Bandwidth.** The gallery, with 23 spawners and 30 to 40 enemies in play, sends about 110 KB/s and 43 messages a second from the host. Most of that is moving enemies' positions and Lifeline's one message per hit (a limit of the health kit, see SecondWind's README); the live curve pens keep their enemies standing still and their turrets slow to keep their share small. A game with one or two spawners and fewer enemies sends far less. Each Spawner publishes its state at most 5 times a second, and otherwise every 2 s.
- **Small screens.** From the gallery's start position, the label titles are readable on a phone held sideways, but the one-line subtitles and the live lines under the curve boards are only a few pixels tall there; walk towards a row to read them. On a desktop window every label is readable from the start, below MatchFlow's timer and wave banner.
- **MatchFlow's screens cover the middle between rounds.** In the gallery, when the arena's third wave is cleared, MatchFlow's results screen and then its "next match in" panel fill the middle of the screen for about 10 s (its `resultsSeconds` and `breakSeconds`), then the next round starts. Set `showUi = false` on your MatchFlow to draw your own from its state.
- **Web browser.** The gallery runs in a browser tab: the models and labels are built and running there, the same as on desktop, and the tab was the host of the two-player session. It runs much slower (about 10 fps against 30 to 40 on desktop with the full gallery), so keep `maxAlive` modest on the web. In the editor, the Scene view's camera menu must read **Active camera** in play: if it is set to the editor camera, play keeps drawing from the editor's fly camera and the gallery appears to be empty.
- **Scene rebuilds and old entities.** When a build re-places an entity whose component values were changed outside the build, the scene builder can keep the old values or refuse the add. `SK.addSpawner`, `SK.addSpawnPoint`, `SK.addTurret` and `SK.addReadout` update a component that is already there. If a rebuild still reports `already has a 'spawnerKit.…' component`, rename that entity in your build.
## Version history
- **1.1.8**: Dependency update only, no code change. spawnerKit now also pins the current juiceKit (98b784a). 1.1.7 still pinned an older juiceKit, so a game already running the current juiceKit refused to update to it: one juiceKit module would have run from two releases.
- **1.1.7**: Dependency update only, no code change. spawnerKit now pins SecondWind 1.4.5 (release 01M6Y6QY6998A01FEWS8D78EAQ) and the Lifeline and MatchFlow versions that SecondWind release uses. The 1.1.6 release pinned older SecondWind copies, so a game that also installed SecondWind 1.4.5 got enemies whose Vitals came from an old copy under `deps/.../versions/`, and their kills fired on that copy's event bus instead of the one `require("SecondWind.api")` returns. Now an enemy's Vitals is the same SecondWind the game uses, and `on("killed")` fires for it.
- **1.1.6**: Documentation only, so the kit plays exactly as in 1.1.5. **The wave survival guide works the first time again.** Its step 2 said to install aiKit, then SecondWind, then spawnerKit. In that order aiKit brings an older SecondWind of its own, installing SecondWind afterwards adds a second copy (OrigoZero/zero#22816), and the build in step 5 stops with `no root to resolve against` for SecondWind's Vitals in the older copy, leaving an empty floor. Step 2 now installs SecondWind first, then aiKit, then spawnerKit, which leaves one SecondWind; it says why the order matters, and "If something doesn't work" says what to do when a world already has two. The guide was then followed word for word in a brand-new world through Play and wave 1. Known limits describe both issues as they show up in that guide. Tests: 92 of 92, twice in a row. `SK.VERSION` is `"1.1.6"`.
- **1.1.5**: Documentation only, so the kit plays exactly as in 1.1.4. **The docs now say what you really see when you install.** The wave survival guide's step 2 said that installing SecondWind after aiKit moves aiKit's copy up and installs nothing twice; today you get two copies (the newer one at `/source`, which every kit reaches by name, and aiKit's under `deps`) and a `package collision` line in the log (OrigoZero/zero#22816, now in Known limits). The guide, the install section and Known limits said the `has no root to resolve against` lines stop once an install has landed; they come back every time the world loads, and they now cite OrigoZero/zero#20407. Tests: 92 of 92, twice in a row. `SK.VERSION` is `"1.1.5"`.
- **1.1.4**: **A player who joins a running game sees every enemy with its own look.** Before, an enemy that reached a joining player before the game had defined its kind showed the fallback grunt body (four green blocks) and kept it for good, even after the kind was defined, so that player saw grunts where everyone else saw the real enemies (or none, for a kind with no body). An enemy now rebuilds its look as soon as its kind's definition arrives or changes, in play and while authoring. Found and fixed by navKit's author in the Pathwise gallery (pull request #1, taken on main; the number 1.1.3 belongs to that pull request's branch and was never released, so this release is 1.1.4). Known limits now name only open issues, and both guides open by their name alone as well as by their guide path. Tests: 92 of 92 (one new test for this fix), twice in a row. `SK.VERSION` is `"1.1.4"`.
- **1.1.2**: The wave survival guide, corrected again after a player followed it. **When you fall, every enemy of the old run now vanishes.** Before, enemies still walking when the run reset were written back into the arena by navKit (aiKit's movement) and stood there frozen, some getting counted again in the next run. The guide's step 6 now tells navKit whenever spawnerKit moves an enemy (`syncWalker`, on `spawned` and `despawned`), the same way aiKit moves a character home. Checked three times in a row: falling with 10 enemies alive left none standing or counted, and every enemy of the new wave 1 came out of a portal. The guide now names the controls (W, A, S, D to move, Shift to run, Space to jump, right mouse button and drag to turn, F to shoot), says the readout appears once you press Play, and describes the brute as it really fights: it charges and smashes above 60% health, roars and backs off to shoot volleys from 8 to 14 m between 60% and 30%, and roars again and goes berserk below 30%. Everything that already worked (the shot, the wave sizes, the clean paste) is unchanged. Tests: 91 of 91, twice
# navKit 1.5.8
Navigation for characters, creatures, drones and vehicles in any multiplayer Zero world. Bake a walkable map from the level you already have with one call, connect places with ramps, stairs, ladders, jumps, teleporters and doors, and put a `NavAgent` on anything: it walks to a spot or follows something, smooths its path, slows down to arrive, steers around other agents, re-plans when something moves into its way, and tells you when it arrives or cannot get there. Eight movement styles, each with its own look, swap with one setting while running.
Version **1.5.8** (`NK.VERSION`). The version in this README, `package.yaml` and `NK.VERSION` move together.
navKit is built on the engine's own `@builtin::systems.pathfinding` package (A*, its grid and waypoint graphs, cost zones and off-mesh links) and `@builtin::modules.boids` (flock leader-following and the flier's obstacle probe). Both ship with every engine, so navKit needs nothing else installed.
## Guides
Two guides ship inside this package, so every install has them, and they come up in a ZeroMind search worded the way you would ask ("how to make enemies find a path to the player", "npc pathfinding around obstacles", "make a crowd walk across a square"):
- **How to make NPCs find their way: pathfinding, chasing the player and crowds with navKit** (guide path `navKit.package/how-to-make-npcs-find-their-way`, file `how-to-make-npcs-find-their-way.guide/guide.md`): from start to finish for someone new to the kit: the walkable map for a level (each kind of map), sending a character somewhere or having it follow something, changing how it moves, movable obstacles, crowds, ladders, jumps and doors, click to move, the debug view, multiplayer, and reacting when a character arrives or cannot get there.
- **Build a crate yard where guards chase you and you block them with crates** (guide path `navKit.package/build-a-crate-yard-where-guards-chase-you`, file `build-a-crate-yard-where-guards-chase-you.guide/guide.md`): an example game built step by step from installed kits: guards (aiKit) patrol and chase you, you shove crates (pushKit) against gaps to cut them off and they find another way round, villagers walk the market as a crowd, a lantern flares whenever one reaches a stall, and each escape adds a guard. SecondWind does your health.
Open one by its guide path or its short name: `zero guides read navKit.package/how-to-make-npcs-find-their-way` (or `zero guides read how-to-make-npcs-find-their-way`) in the shell, the `guides` tool with that `path`, or the Docs panel. Both link to the guides of the kits around navKit: aiKit (NPC brains), spawnerKit (spawning waves), weaponsKit (weapons) and SecondWind (health and damage).
## Quick start
This works in a brand-new world with nothing installed but navKit.
**1. Install** the `navKit.package` asset into `/source` (search ZeroMind for "navKit", or `zeromind_install guid=286dd3bb-0744-4157-b9f0-c98cc03ee326 at=/source`). navKit needs nothing else: it builds on engine packages every world already has.
**2. Add to `scenes/main.scene/build.luau`.** At the very top of the file:
```lua
local NK = require("navKit.api")
```
and at the end of `function content()`, just before its `end` (the new-world scene already has the ground, the light and the player):
```lua
-- a wall to walk around
local wall = entity.spawn("Wall", { position = { 0, 1, 6 }, scale = { 10, 2, 0.5 } })
wall.component.add("Model", { model = "cube" })
wall.component.add("BoxCollider", {})
-- bake a walkable grid of the ground when play starts
entity.spawn("NavMap").component.add(NK.MAP, { kind = "grid", size = { x = 40, y = 6, z = 40 } })
-- a runner that goes round the wall to the far side
local bot = entity.spawnSynced("Bot", { position = { 4, 0, 2 } })
NK.addAgent(bot, { style = "runner", target = { 0, 0, 12 } })
-- click the ground and it goes there instead; N shows the map and its path
NK.addClickToMove(bot)
entity.spawn("NavDebug").component.add(NK.DEBUG, { button = true })
```
**3. Press play.** The orange runner leans into a sprint, rounds the end of the wall and brakes to a stop behind it. Click anywhere on the ground and it runs there. Press N to see the baked grid (green), its path and the spot it steers for. Change `style = "runner"` to `"wheeled"` and it becomes a cart with a turning circle; to `"flier"` and it flies over the wall.
To react to what agents do, listen in code that runs in play, such as the scene's `entrypoint.luau`:
```lua
local NK = require("navKit.api")
local conn
function onLoad()
conn = NK.on("arrived", function(e) print(e.name .. " arrived at " .. math.floor(e.position.z)) end)
end
function onUnload()
if conn then conn:Disconnect() end
end
```
## What you get
| piece | what it is |
|---|---|
| `navKit.api` | the one interface: `local NK = require("navKit.api")` |
| `NavAgent` component | finds its way; `style` picks how it moves |
| `NavMap` component | bakes a map as soon as the game runs, once the level's colliders are in (the scene-file way to call `NK.bake`) |
| `NavLink` component | a ramp, stairs, ladder, jump, teleporter or door between two spots |
| `NavObstacle` component | its entity blocks the map where it stands; agents re-route when it moves |
| `ClickToMove` component | click or tap the ground and the agent goes there |
| `NavDebug` component | a key (N), and an optional on-screen button, that show or hide the debug drawing |
| `NavNet` component | the crowd line navKit spawns to send every agent's position in one update (internal) |
| `navDebug` render feature | draws the debug lines in play |
| `navKit` test suite | a test for every public call |
## Maps
```lua
local map = NK.bake({ kind = "grid" }) -- around every static collider
NK.bake({ kind = "multiLevel", name = "tower", min = { -20, -1, -20 }, max = { 20, 12, 20 } })
NK.bake({ kind = "waypoint", name = "fields", center = { 0, 0, 0 }, size = { 200, 20, 200 }, spacing = 6 })
```
A bake casts one ray down through each column of cells and keeps every floor it meets whose slope and headroom fit an agent; neighbouring floors join when the step between them is low enough. It reads **colliders** (a mesh with no collider is not in the physics world, so it is not ground), and **terrain**: a `Terrain` with collision on is a collider; one with collision off is read by its drawn surface. Everything that moves is left out: dynamic and kinematic bodies (pushable crates, characters), sensors and every NavAgent. Use `NavObstacle` for things that move and should block.
### Map types
| kind | label | what it is | best for | tags |
|---|---|---|---|---|
| `grid` | Walkable grid | A fine grid of cells over one floor (the lowest walkable floor of each spot), on the engine pathfinding package's grid graph. | rooms, streets, arenas up to ~100 m | precise, single-floor, indoor, arena, default |
| `waypoint` | Waypoint network | Points `spacing` metres apart, each on the roomiest spot near it, joined where a straight walk is clear, on the engine's waypoint graph. Cheap to search. | big open places | light, open-world, large, fast-search, outdoor |
| `multiLevel` (also `layered`) | Multi-level map | Every walkable floor over each spot (ground, balconies, upper storeys), joined by ramps and stairs in the level and by navKit links. | buildings, vertical levels | multi-floor, buildings, vertical, balconies, precise |
### Bake options
| option | default | meaning |
|---|---|---|
| `kind` | `grid` | grid, waypoint or multiLevel (`layered`, its older name, still works) |
| `name` | `"default"` | registry name; agents use the map under them, or the one named in their `map` field |
| `min`, `max` | around every static collider | the box to bake (or `center` + `size`) |
| `cellSize` | 0.5 (waypoint 1.0) | metres per cell |
| `agentRadius` | 0.4 | radius the waypoint network and debug view assume (paths use each agent's own radius) |
| `agentHeight` | 1.8 | headroom a floor needs |
| `maxStep` | 0.45 | tallest step between neighbouring cells |
| `maxSlope` | 42 | steepest walkable slope, degrees |
| `spacing` | 3.5 | waypoint maps: metres between points |
| `exclude` | `{}` | more entities the bake ignores |
| `terrain` | `true` | read terrain by its drawn surface where no collider answers |
| `spread` | `false` | yield between rows (call from a coroutine, e.g. a component hook) |
Every map keeps each cell's **clearance** (metres to the nearest wall or drop), so one bake serves agents of every width: a heavy (radius 0.8) is kept out of gaps a walker fits through.
The `NavMap` component bakes on every peer, desktop and browser alike, from the box `size` centred on its entity (`size.x = 0` bakes around everything). It starts on the first frame the game runs and waits until the static colliders in its box stop changing (a browser streams a level's assets in over its first seconds), then bakes. If that bake finds no walkable floor it tries again every second for 20 s, and if colliders arrive in its box within 30 s it bakes again (at most three times). Agents that need a map still being baked wait for it. `bakeInEdit` also bakes it in edit mode, for the debug view while authoring.
## Agents
```lua
local bot = entity.spawnSynced("Bot", { position = { 0, 0, 0 } })
NK.addAgent(bot, { style = "walker", target = { 10, 0, 4 } })
NK.setTarget(bot, { -6, 0, 9 }) -- from any peer
NK.follow(bot, "Player1") -- an entity, its name or its id
NK.setStyle(bot, "heavy") -- while it runs
NK.stop(bot)
print(NK.state(bot).status) -- idle, planning, moving, link, arrived, unreachable
```
What an agent does each frame, on the peer in charge of it:
- **plans** on the map under it (a few plans per frame, on a 5 ms budget), with its style's radius, link costs and refusals;
- **smooths** the path, dropping every corner a straight clear walk can skip, and rounds the corners it keeps;
- **slows down to arrive** inside its style's `slowRadius`, and before a link;
- **avoids other agents and players**: every player's character (and anything added with `NK.addBody`) counts as a heavy body it steers round and steps back out of, never pushes; it picks, from a fan of candidate velocities, the one closest to where it wants to go that does not run into anyone within its style's look-ahead time; how much it cares is its `avoidance`, scaled by how heavy the other one is (everyone steps aside for a heavy); bodies that still overlap push apart, the lighter one moving more;
- **re-plans** when an obstacle appears in, or leaves, its map, when the next stretch of its path is blocked, when the followed entity moves away, when its style changes, and when it stops making progress; a target that cannot be reached is retried every 3 s (`retry`); when the goal is out of reach (walled in, too narrow for it, only over a link its style refuses) it reports `unreachable` once and goes to the closest spot it can reach;
- **crosses links**: walks ramps, stairs and doors (waiting for a door to open), climbs ladders on the ladder's line, leaps jumps on an arc, and shrinks into a teleporter and grows out of the other pad.
### NavAgent fields
| field | default | meaning |
|---|---|---|
| `style` | `walker` | movement style; change it any time |
| `target`, `hasTarget` | `{0,0,0}`, `false` | walk to `target` while `hasTarget` is on |
| `follow` | none | an entity to follow instead (re-plans as it moves) |
| `followDistance` | 2 | how close to stop behind the followed entity |
| `map` | `""` | map name; empty = the map under the agent |
| `speed`, `radius` | 0 | 0 = the style's own |
| `group` | `""` | swarm flock group (empty = "swarm") |
| `look` | `auto` | `auto` builds the style's body on every peer; `none` keeps the entity's own visuals |
| `arriveDistance` | 0.3 | how close counts as arrived |
| `turnRate` | 0 | how fast it turns to face where it goes, radians a second; 0 = the style's own (wheeled agents steer by their turning circle) |
| `avoidance` | true | steer around other agents; off = keep to its path and let others make way (bodies still never overlap) |
| `debugDraw` | `auto` | this agent's path and steering lines: `auto` = while the debug drawing is on, `on` = always on this screen, `off` = never |
| `retry` | `true` | try an unreachable target again every 3 s |
| `paused` | `false` | hold still without forgetting the target |
| `netRate` | 4 | most position samples a second this agent puts in its crowd line for other players (see Multiplayer) |
| `netError` | 20 | with other players present, the synced transform (the fallback, and what `entity.position` reads on other peers) is re-sent once the agent is this many metres from where it was last sent; it also goes out on links, teleports and changes of floor, and every 10 s while the agent moves |
| `smooth` | `true` | on this screen, smooth the body between network updates |
State fields, written by the peer in charge and read anywhere: `status`, `routeData` (the path as compact text, which is what crosses the network), `currentLink`, `eventData` (the latest event other peers fire too, `seq|name|reason|kind`). Rebuilt from those on the peers that do not move the agent, and read there through `NK.state(e)` / `agent:getState()` (an engine refuses writes to a synced entity's fields from anyone but its owner, so those peers keep them on navKit's own record): the route (the smoothed path, `{ {x, y, z, via} }`, `via` = `walk` or a link kind), the latest event and its reason. On the peer in charge they are also the fields `route`, `eventSeq`, `lastEvent`, `lastReason`. Local to the peer in charge: `steerPoint`, `routeIndex`.
Methods (the same as the API calls): `agent:setTarget(pos)`, `agent:followEntity(e)`, `agent:stop()`, `agent:setStyle(id)`, `agent:getState()`, and `agent:visualPosition()` (where its body is drawn on this screen; `agent:visualXYZ()` answers the same as three numbers, with no table, for callers that ask every frame). Component events: `arrived`, `unreachable`, `linkStarted`, `linkFinished`, `styleChanged` (synced to every peer) and `replanned` (on the peer in charge only), each with `{ reason, kind, x, y, z }`.
## Movement styles
Every style is one setting on the agent and swaps while it runs (it re-plans with the new costs). Each has its own look, built from primitive shapes on every peer.
| id | label | family | what it does | speed | radius | refuses | look | tags |
|---|---|---|---|---|---|---|---|---|
| `walker` | Walker | ground | Steady pace, takes every kind of link, steps politely around others. | 3.0 | 0.4 | - | tall blue body, white visor, swinging arms | default, humanoid, npc, villager, balanced |
| `runner` | Runner | ground | Twice a walker's speed with quick acceleration; brakes late, takes jumps gladly. | 6.2 | 0.35 | - | short orange body leaning hard forward, swept fins, speed streaks | fast, athlete, courier, chaser, agile |
| `heavy` | Heavy | ground | Slow and wide: needs a broad path, barely yields and shoulders lighter agents aside. | 1.5 | 0.8 | ladder, jump | broad dark-red block, grey shoulders | tank, brute, big, slow, pusher, golem |
| `flier` | Flier | air | Ignores the map: flies straight over walls, crates and gaps at a hover height above whatever is below. | 4.5 | 0.5 | (no links needed) | cyan quad-rotor drone, spinning rotors | drone, bird, air, hover, flying, scout |
| `swarm` | Swarm | group | Small and many: moves as a flock with its group (separation, alignment, cohesion, following the group's leader). | 3.6 | 0.25 | ladder | three bobbing yellow bugs | flock, insects, herd, group, rats, boids |
| `wheeled` | Wheeled | vehicle | A cart: turning circle (2.2 m), cannot strafe, slows into tight turns. Ramps are fine. | 4.5 | 0.6 | ladder, jump, stairs | green cart, rolling black wheels | vehicle, cart, car, rover, robot, no-strafe |
| `sneaker` | Sneaker | ground | Cautious and slow; keeps to walls and cover instead of crossing open ground, avoids zones labelled `Exposed`. | 1.9 | 0.35 | - | low purple cloak, pointed hood, glowing eyes | stealth, thief, cautious, cover, spy, assassin |
| `climber` | Climber | ground | Loves ladders and jumps: takes them over a longer walk, climbs and leaps fast. | 3.3 | 0.35 | - | pink body, arms raised to yellow hands, rope coil | parkour, monkey, spider, agile, acrobat, vertical |
Path costs per style (multipliers on the engine's cost labels): runner `Jump 0.7`; wheeled `Ramp 0.8` (and refuses stairs, ladders and jumps, including cost zones labelled `Stairs`); sneaker `Exposed 8, Cover 0.4, Door 2`, plus 3.5x extra cost on open ground (cells far from any wall); climber `Ladder 0.12, Jump 0.15, Ramp 1.8, Stairs 1.8`.
Make your own: `NK.defineStyle("guard", { base = "walker", speed = 2.2, costs = { Door = 0.5 }, tags = { "guard" } })`. Unset values come from `base`. Call it on every peer (a module your components require, or the scene's entrypoint) before agents use it.
## Links
```lua
NK.addLink({ kind = "ladder", from = { 4, 0, 2 }, to = { 4, 3.2, 2.8 } })
NK.addLink({ kind = "jump", from = { 0, 3.2, 0 }, to = { 3.5, 3.2, 0 }, bidirectional = false })
NK.addLink({ kind = "teleporter", from = { -10, 0, 5 }, to = { 20, 6, 30 } })
local door = NK.addLink({ kind = "door", from = { 0, 0, 9 }, to = { 0, 0, 11 } })
NK.updateLink(door, { locked = true }) -- no path uses it until unlocked
```
Or as a component, on the entity marking one end:
```lua
entity.spawn("LadderFoot", { position = { 4, 0, 2 } })
.component.add(NK.LINK, { kind = "ladder", toOffset = { x = 0, y = 3.2, z = 0.8 } })
```
| kind | label | how agents cross it | cost label | refused by | tags |
|---|---|---|---|---|---|
| `ramp` | Ramp | walk the slope | `Ramp` | - | slope, walk, vehicle-friendly |
| `stairs` | Stairs | walk it at 70% speed | `Stairs` | wheeled | steps, walk, building |
| `ladder` | Ladder | climb on the lower end's line, then step off | `Ladder` | heavy, wheeled, swarm | vertical, climb, building |
| `jump` | Jump | leap on an arc | `Jump` | heavy, wheeled | gap, parkour, leap |
| `teleporter` | Teleporter | shrink on one pad, grow on the other | `Teleport` | - | warp, portal, sci-fi, instant |
| `door` | Door | wait for it to open, walk through | `Door` | locked doors only | building, gate, lockable |
A ramp or stairs that exists as geometry needs no link: the bake joins it. Links are for what the bake cannot see (a ladder, a gap to jump, a teleporter) or for marking a walkway with a cost label. A link is used only by a map that holds both of its ends (or the one named in its `map`). Link ends snap to the nearest walkable spot. `NavLink`'s `door` field names a panel that slides up while any agent is near or crossing it, on every peer.
**Cost zones:** the engine's own `PathfindingModifier` component (or `Pathfinding.addModifier`) marks a box with a label; every agent pays its style's cost for that label inside it (`Exposed`, `Cover`, `Stairs`, or your own). The gallery's sneaker lane uses one.
## Obstacles
```lua
local crate = entity.spawnSynced("Crate", { position = { 0, 0.6, 4 } })
crate.component.add("Model", { model = "cube" })
crate.component.add("BoxCollider", {})
crate.component.add("Physics", { kind = "dynamic", mass = 3 })
NK.addObstacle(crate, { padding = 0.3 })
NK.setBlocked("roadworks", { 0, 0, 0 }, { 4, 2, 4 }) -- a box with no entity; NK.setBlocked("roadworks") clears it
```
A `NavObstacle` blocks its bounds (plus `padding`) on every map, as an engine cost zone with an infinite cost. When it moves more than `moveThreshold` (0.2 m), the agents whose map it touches re-plan, so they route around where it is now and take the way it left open. It runs on every peer from the entity's own transform. `obstacle:box()` says where it blocks.
## Click to move and debug drawing
- `NK.addClickToMove(entity)`: clicking or tapping the ground sends that agent there, from every player's screen; the target goes to the peer in charge of the agent. A click is a press and release within 8 px and 0.35 s, so camera drags are ignored, and a press on the game's own on-screen UI (a button, a panel) is not a click on the ground. `clickAt(x, y)` does it from code. The component's `clicks` counter is counted on the peer in charge of the agent; a click from any other player still moves the agent, and that player's engine leaves the counter alone (it may not write another peer's entity, and would log a refusal for every click).
- `NK.debug(true)` / `NK.debug({ map = true, paths = false, steer = true })`, or a `NavDebug` component (key `KeyN` by default; `button = true` adds an on-screen panel in the bottom-right corner (its button answers a mouse click or a tap; in play the game holds the pointer, so the panel reads the press from the game's input and the UI's hit test as well as from the UI) whose button toggles it, by mouse or by touch, and `hint` puts a line of your own help text above that button): green lines are walkable ground, blue upper floors, amber narrow spots, cyan the waypoint networks, coloured arcs the links (yellow ladders, orange jumps, purple teleporters, white doors, grey when locked), red boxes the obstacles; each agent's path is drawn in its style's colour with a cross on every corner, and a white line with a pink diamond shows the spot it steers for. Drawing is per screen.
## Catalog
```lua
NK.find({ kind = "style", tag = "vehicle" }) -- wheeled
NK.find({ kind = { "style", "map" }, family = "ground" })
NK.find({ kind = "link", tag = "building" }) -- stairs, ladder, door
NK.catalog() -- { styles, maps, links, entries, events, version }
```
Query keys: `kind` (style, map, link), `family`, `tag`, `id`; each takes a value or a list (any matches); every key given must match. Unknown keys or kinds are errors.
## Events
```lua
local conn = NK.on("unreachable", function(e) print(e.name, e.reason) end)
NK.on("*", function(name, e) end)
conn:Disconnect()
```
| event | when | payload |
|---|---|---|
| `arrived` | an agent reached its target (or stopped `followDistance` short of what it follows) | `agent, name, style, status, position, reason, kind` |
| `unreachable` | no path, no map, or stuck too long; also fired once per goal when the goal is out of reach and the agent heads for the closest spot it can reach instead (`reason` says which; the agent then stops there with status `unreachable`) | same |
| `replanned` | a new path; `reason`: new target, target moved, blocked, obstacle moved, style changed, stuck, map baked, retry | same |
| `linkStarted`, `linkFinished` | crossing a link; `kind` is its kind | same |
| `styleChanged` | the style was swapped; `kind` is the new style | same |
| `baked` | a map was baked | `name, kind, info` |
| `obstacleMoved` | an obstacle appeared, moved or left | `key, entity, active` |
The peer in charge of an agent fires its events as they happen; every other peer fires them when the agent's synced `eventData` line changes, so every screen can react. `replanned` is the exception: it fires a dozen times a second in a busy crowd, so it stays on the peer in charge (the new route still reaches everyone). Two events within one network update can reach other peers as one.
## Multiplayer
- **The host moves the agents.** The peer that owns an agent's synced entity (normally its creator: the host, for a scene's entities) plans and moves it, and writes its transform and state fields, which reach every peer. While nobody owns it, the room host does. `NK.isAuthority(e)` says whether this peer is in charge.
- **Players who join late.** Agents are synced entities moved by the host, so a player who joins a running game gets every agent, the ones spawned at run time (the gallery's 30-person crowd) included, and draws them from the next crowd line. Measured twice with a second engine joining the running gallery: it saw all 30 of the plaza crowd, all moving within 12 seconds. Only the host spawns and adopts the gallery's crowd; a late joiner never spawns, adopts or removes any. A joiner sees exactly the pedestrians the host sees, each with only its navKit body: the gallery's crowd is spawnerKit enemies of a kind with no body of its own, and a joiner can receive them before its game has defined that kind, so spawnerKit used to give each one its fallback body (four green blocks) on top and keep it. The gallery runs spawnerKit 1.1.3, whose enemies rebuild their look once the kind is defined; that fix is sent to spawnerKit's own world. With spawnerKit 1.1.2 or older, a joiner can still see that fallback body on enemies of a kind the game defines in its own code.
- **Commands from anyone.** `NK.setTarget`, `follow`, `stop`, `setStyle`, `setPaused` and click-to-move work from any peer: a peer that is not in charge sends the command to the one that is (channel `navKit:cmd`).
- **Positions travel as one crowd line, not one update per agent.** Writing every agent's transform every frame floods a relay link: the 58-agent gallery sent about 96 KB/s, and a second player's view fell minutes behind. With other players in the room, the peer that moves agents writes one synced line (a `NavNet` component on a `navKit.crowdLine` entity it owns) holding each agent's slot number, position and facing. An agent appears in it up to `netRate` times a second while it moves, and every 2 s while it stands. Every other screen draws each body on a local pivot: the latest sample, carried on at its velocity for up to 0.6 s, eased into each correction, so agents glide instead of stepping. The agent's own synced transform becomes a slow fallback (each send costs a few hundred bytes): sent on links, teleports and changes of floor, once the agent is `netError` metres (20) from where it was last sent, and every 10 s while it moves. So on other peers `entity.position` can be a few metres behind; use `agent:visualPosition()` or `NK.state(e).position` there. Alone in a room, the transform is written every frame as before. Routes cross as compact text (`routeData`), events as one line (`eventData`), and the steering point and route index stay local.
- **Measured in the browser and with two players (1.2.1)** (the Pathwise gallery: a fresh Chrome tab in charge as host, a Zero desktop window joined beside it, 45-58 agents):
- **Browser in charge:** all five maps baked (about 1 s for the largest, 9,000 cells). 34-55 frames a second at 18-29 ms a frame, with navKit's whole tick at 3.5-4.6 ms a frame and occasional spikes to 16-72 ms when several long plans land together; the slowest single plan took 137 ms. An agent sent across the courtyard was moving at once and arrived in 6 s. All 29 pedestrians of the crowd reached the far side within 38 s and were all back within 59 s, watched from the desktop. No script errors.
- **Same places:** 57 of 57 agents and their styles on both screens. Bodies drawn on the desktop were 0.09-0.18 m from where the browser drew them on average (worst 0.72 m), with a 0.5-1.7 s lag and a 0.8-1.9 s round trip.
- **A crate in the way:** the crate, moved by the browser, reached the desktop in 0.4 s. Pushed out of the corridor, both screens routed the walkers straight through; pushed back in, the desktop showed all three going around within 4.8 s, and both screens agreed once settled.
- **A style change:** a swap made on the desktop showed there in 0.1-0.2 s, with the new look's parts built, and in the browser within 0.3 s.
- **Desktop in charge** (the browser handed its agents over, and the desktop owned all 57 within 3 s): all 29 pedestrians crossed and came back within 68 s, at 2.4 ms of navKit time a frame.
- With others present, `entity.position` of an agent follows only the slow fallback (it can lag 10 s on every screen, the moving one included): read where an agent is with `NK.agent(e):visualPosition()` or `NK.state(e).position`.
- **Measured with two players** (the Pathwise gallery, two Zero desktop windows, 88 agents, both freshly loaded): the same 88 agents and styles on both screens; bodies on the viewing screen 0.06-0.35 m from the moving screen's on average (worst 1.3 m); a ~1.5-3 s round trip that held steady; a style swap visible on the other screen within ~3 s; a moved crate and the box it blocks within 1.6 s, and the walkers' new detours on both screens within ~5 s; about 10.6 KB/s sent (96 KB/s before 1.1.0).
- **Everything else is local and identical.** Every peer bakes the same maps from the same scene, registers the same links and obstacles from the scene (obstacles follow their synced entity's transform), builds each agent's look from its synced `style`, and draws its own debug view.
- **When the player moving them leaves.** The agents a departed player was moving are claimed by the lowest-numbered player still in the room after 3 s, and walk on from where they stood; `NK.stats().orphans` counts any still waiting for the relay to grant the claim. Crowd lines a departed player left behind are removed by whoever the room hands them to.
- Put agents on synced entities (`entity.spawnSynced`). An agent on a plain local entity is moved by every peer separately.
## API reference (`local NK = require("navKit.api")`)
| call | what it does |
|---|---|
| `NK.bake(opts?) -> map` | Bake a map from the level (see Maps). |
| `NK.map(name?) -> map?` | A baked map by name (no name: the only one, or `default`). |
| `NK.maps() -> { map }` | Every baked map, by name. |
| `NK.mapAt(pos) -> map?` | The (smallest) map whose box holds a point. |
| `NK.removeMap(name) -> boolean` | Forget a map. |
| `NK.findPath(from, to, opts?) -> path` | A path without an agent: `{ status = ok/partial/unreachable, points, raw, cost, expanded, map, capped }`. opts: `map`, `style`, `radius`, `costs`, `refuse`, `exposure`, `smooth`. |
| `NK.isWalkable(pos, radius?, map?) -> boolean` | Is there floor here with room for that radius? |
| `NK.nearestPoint(pos, radius?, map?) -> pos?` | The nearest walkable spot. |
| `NK.addLink(opts) -> id` | Add a link (see Links). |
| `NK.updateLink(id, opts) -> boolean` | Change a link's ends, cost, `locked`, `enabled`, `bidirectional`, `map`. |
| `NK.removeLink(id) -> boolean` | Remove a link. |
| `NK.links() -> { link }` | Every link. |
| `NK.addAgent(e, opts?) -> NavAgent` | Add (or update) a NavAgent; opts are its fields, `target` sets `hasTarget`. Unknown styles are errors. |
| `NK.agent(e) -> NavAgent?` | The NavAgent of an entity, name, id or component. |
| `NK.agents() -> { NavAgent }` | Every agent on this peer. |
| `NK.addBody(entity, radius?)`, `NK.removeBody(entity)` | A character navKit does not move (a scripted NPC, a vehicle) that agents steer round and step back out of, like a player's; radius in metres, default 0.35. navKit never pushes it. |
| `NK.setAvoidPlayers(on)`, `NK.avoidsPlayers() -> boolean` | Whether agents steer round every player's character (on by default). |
| `NK.setTarget(e, pos)` | Send an agent to a spot (from any peer). |
| `NK.follow(e, target)` | Follow an entity. |
| `NK.stop(e)` | Stand still and forget the target. |
| `NK.setPaused(e, paused)` | Hold still without forgetting. |
| `NK.warp(e, pos)` | Put an agent on a spot at once (out of a doorway, back from far away) without walking there; it keeps its target and plans again from the new spot. Works from any peer. |
| `NK.setStyle(e, styleId)` | Swap the movement style while running. |
| `NK.state(e) -> table` | `status, style, target, follow, route, routeIndex, steer, link, position, lastEvent, reason, authority`. |
| `NK.isAuthority(e) -> boolean` | Whether this peer moves that agent. |
| `NK.addObstacle(e, opts?) -> NavObstacle` | Make an entity block the map (opts: `padding`, `moveThreshold`, `active`, `static`: true for scenery that never moves, blocked once with no per-frame check). |
| `NK.setBlocked(key, min?, max?)` | Block a box by key; without `min` it unblocks. |
| `NK.addClickToMove(e, opts?) -> ClickToMove` | Click or tap to move that agent. |
| `NK.debug(opts)` | Debug drawing on this screen: `true`, `false` or `{ map, paths, steer }`. |
| `NK.debugState() -> table` | `{ map, paths, steer, mapVerts, pathVerts }`. |
| `NK.styles()`, `NK.style(id)` | The movement styles, or one. |
| `NK.mapKinds()`, `NK.linkKinds()` | The map types and link kinds. |
| `NK.catalog()`, `NK.find(query?)` | Everything labelled; filter it. |
| `NK.defineStyle(id, def) -> style` | Add a movement style of your own. |
| `NK.on(name, fn) -> conn` | Listen to an event on this peer. |
| `NK.eventCounts() -> table` | How often each event fired here, and the last 40. |
| `NK.stats() -> table` | `agents, authority, maps, links, obstacles, plans, planMsLast, planMsMax, tickMs, queued, capped` (searches that hit the node budget), `carried` (frames a search was carried over), and what each part of the last tick took: `planFrameMs` (path planning), `stepMs` (stepping every agent), `stepMaxMs` (the slowest single agent), `gridMs` (the neighbour grid). |
| `NK.searchBudget(opts?) -> table` | Read or set how much path searching may cost: `maxNodes` (one search, default 10000), `frameMs` (planning time a frame shared by every agent, default 5; a longer search carries on next frame), `plansPerFrame` (8), `retryDelay` (3 s) and `retryMaxDelay` (30 s) for agents whose goal is out of reach (the wait doubles per failure). Returns the settings in force. |
| `NK.vec(v) -> {x, y, z}` | Read any point form (`{x=}`, `{1,2,3}`, a vector, an entity position). |
Constants: `NK.VERSION` (`"1.5.8"`), `NK.STYLES`, `NK.MAP_KINDS`, `NK.LINK_KINDS`, `NK.EVENTS`, and the component names `NK.AGENT`, `NK.OBSTACLE`, `NK.LINK`, `NK.MAP`, `NK.CLICK`, `NK.DEBUG`.
A baked map (from `NK.bake` or `NK.map`) also answers `map:findPath(from, to, profile)`, `map:heightAt(pos)`, `map:clearanceAt(pos)`, `map:isWalkable(pos, radius)`, `map:nearestPoint(pos, radius)`, `map:clearLine(a, b, radius)` and `map:info()`.
## Tests
The suite `navKit` has a test for every public call, and tests in which agents really move: one walks to its target and arrives, one goes around a box that appears in its way, one climbs a ladder on a multi-level map and another on a grid map (starting at the ladder's foot), a flier switched to walker in mid-air lands and arrives, an agent left inside a box steps out and arrives, an agent of every movement style buried by an obstacle on a grid map (and on waypoint and multi-level maps) is pushed clear and still arrives, an agent buried after arriving is pushed clear without arriving again, `arrived` fires exactly once per arrival even when the next target is set the moment it arrives, nine agents spawned on one spot with three to each goal all arrive without overlapping, an agent's own `turnRate`, `avoidance` and `debugDraw` do what they say, a `NavMap` whose colliders arrive late bakes again, and an obstacle whose engine box was removed behind navKit's back (as a reload can leave it) blocks again the next time it is set. Run it in edit mode with:
```lua
tools.use("tests", "run", { suite = "navKit" })
```
## Performance
On a desktop, the gallery's 58 agents cost about 2-5 ms of script time a frame in total (planning included), and baking its five maps (about 18,000 cells) takes about a second spread over the first frames of play. In a Chrome tab on a busy machine, with the browser alone in charge of all 58 agents, the gallery ran at about 7 to 12 frames a second, with navKit's own stats (`NK.stats()`) at about 24 ms a frame; much of the rest of the frame goes to sending synced state (see Known limits, #20750). An earlier check on a quieter machine measured 3.5-4.6 ms a frame and 34-55 frames a second; keep crowds there in the tens rather than the hundreds. A plan on a 9,000-cell grid takes 1-20 ms on a desktop (up to about 140 ms in a browser); at most 8 plans (or 5 ms of planning) run per frame, the rest wait their turn, and a search longer than that pauses and carries on next frame. One search expands at most 10,000 nodes (`NK.searchBudget`), so a goal that cannot be reached on a large map costs a bounded amount spread over frames rather than a whole-map search. The map debug drawing is uploaded once per change.
## Known limits
Each of these is a problem in the Zero engine, not in navKit, and each points at the issue it is tracked in on the engine's tracker (`OrigoZero/zero` on GitHub). navKit works around each one as described.
- **The engine's A\* puts link labels on the wrong step.** `Pathfinding`'s path rebuild drops edges without metadata, so on its own graphs a link's action lands several waypoints early. navKit's maps give every edge metadata, so navKit paths are right; it only matters if you call `Pathfinding.path` yourself on graphs of your own. Open issue: [OrigoZero/zero#19531](https://github.com/OrigoZero/zero/issues/19531).
- **The tops of sign letters are clipped.** `Text3D` labels lose the top edge of tall letters (the Pathwise gallery's signs show it). Nothing in navKit draws text; it affects worlds that label their navigation, like the gallery. Open issue: [OrigoZero/zero#19525](https://github.com/OrigoZero/zero/issues/19525).
- **In the browser, kits register late.** At startup a browser tab reports a missing engine module (`@builtin::modules.frameDriver`) for packages such as spawnerKit and juiceKit and registers their components only later, so things they spawn early can arrive before your own hooks are listening. The Pathwise gallery's crowd keeper adopts any pedestrian it missed once a second for this reason. Open issue: [OrigoZero/zero#19309](https://github.com/OrigoZero/zero/issues/19309).
- **Synced state costs frame time even when nothing changed.** Sending synced state takes 14 to 46 ms of every frame with other players in the room and in the browser, whatever navKit does, which holds the frame rate down there; navKit already sends all agents as one crowd line a few times a second. Measured: a Chrome tab on a busy machine, in charge of the gallery's 58 agents, ran at about 7 to 12 frames a second with navKit at about 24 ms a frame. Open issue: [OrigoZero/zero#20750](https://github.com/OrigoZero/zero/issues/20750).
- **Two windows signed in as the same person are one player.** Testing multiplayer with two windows on one account makes them collide as one player; test with two accounts. Open issue: [OrigoZero/zero#14448](https://github.com/OrigoZero/zero/issues/14448).
- **Installing into a fresh world is slow.** navKit has no dependencies outside the engine, but a world installing it together with packages that have several dependencies (the Pathwise gallery's crowd uses spawnerKit) waits a long time for the install. Open issue: [OrigoZero/zero#21420](https://github.com/OrigoZero/zero/issues/21420).
- **The ZeroMind description can lag a release.** Right after a release the package's description on ZeroMind can still show the previous version's text; this README is current. Open issue: [OrigoZero/zero#19258](https://github.com/OrigoZero/zero/issues/19258).
- **Browser builds are checked by hand.** An agent cannot start a browser build itself, so the browser numbers here come from the world owner's own check. Open issue: [OrigoZero/zero#20946](https://github.com/OrigoZero/zero/issues/20946).
- **Players do not push physics bodies.** The engine's character controller does not shove dynamic bodies, so a `NavObstacle` crate only moves if something moves it. **pushKit**, a separate package from the Pathwise world (search ZeroMind for "push a crate by walking into it"), lets players shove crates by walking into them; the gallery's corridor crate and the example guide use it. Open issue: [OrigoZero/zero#19539](https://github.com/OrigoZero/zero/issues/19539).
- **The player's camera does not show the engine's debug drawing in play.** `debugViz` draws only on the `debug` layer, which play cameras leave out, so navKit draws its debug lines itself (`navKit.navDebug` render feature, the engine's `debugGeometry` shader); headless engines draw nothing. Open issue: [OrigoZero/zero#19540](https://github.com/OrigoZero/zero/issues/19540).
- **Long waits with no progress shown.** Running navKit's tests (about a minute) and installing it together with other kits can take a while, and the call may come back as a background task to wait on. Let it finish. Open issue: [OrigoZero/zero#19849](https://github.com/OrigoZero/zero/issues/19849).
- **Links to other kits' guides open only when that kit is installed.** navKit's two guides link to the guides of aiKit, spawnerKit, weaponsKit and SecondWind by their guide path (`aiKit.package/how-to-give-npcs-a-brain`). A link opens when that kit is in your world; when it is not, it does not open, not even by the guide's id, and no doc names the link form, so it took trial and error to find. Each link says to search ZeroMind for the guide's title instead. Open issue: [OrigoZero/zero#22513](https://github.com/OrigoZero/zero/issues/22513).
- **Installing beside other kits leaves extra copies.** navKit on its own installs only its own package. Installed together with kits that pin engine files (the example guide's aiKit), the install can also write copies of engine files under `/source/deps/.../versions/` (in the guide's check, a copy of the engine's `debugGeometry` shader and aiKit's pinned copy of navKit 1.3.2, beside navKit 1.4.0 in `/source`). They do nothing: `require("navKit.api")`, aiKit's included, reaches the navKit in `/source`, and every agent ran on it. Open issue: [OrigoZero/zero#22451](https://github.com/OrigoZero/zero/issues/22451).
## How navKit behaves (design notes)
These are navKit's own choices, not bugs, so no issue tracks them.
- **Maps are baked, not rebuilt.** A level that changes shape (a wall built or destroyed) needs a new bake (`NK.bake` again, or `NavMap:rebake()`); only `NavObstacle` boxes follow moving things live. A `NavMap` does bake again by itself if colliders arrive in its box within 30 s of its first bake (a level still streaming in).
- **Grid maps are one floor.** A `grid` map keeps the lowest walkable floor of each spot; use `multiLevel` for floors above one another.
- **Agents do not collide with physics.** They are moved along the map, not pushed by the physics engine. They steer round every player's character and step back out of it, but a player who walks into an agent still passes through it (the player is moved by the physics engine, the agent is not). Agents never stand inside each other: overlapping bodies push apart (the lighter one more), even with `avoidance` off.
- **Fliers fly straight.** A flier heads straight for its target over whatever is below; it steers around tall things with the boids ray probe but does not plan a 3D route, so it can be held up behind a wall too tall to clear.
- **Ground height follows the map.** Agents stand on the baked floor height; a floor that moves after the bake (a lift) is not followed.
- **Avoidance is local and late.** Agents pick, each frame, the velocity nearest their path that does not run into anyone within about a second; two walkers meeting exactly head-on start stepping aside only about a metre apart. In a very dense crowd they can slow to a shuffle and re-plan ("stuck"); after seven checks without progress (about 11 s) an agent reports `unreachable` with reason `stuck` and, with `retry`, tries again.
- **Agents sent to one spot queue up.** Only one body fits on a spot: an agent whose goal is taken arrives when it touches an agent that has arrived nearer that goal.
- **Events can merge across the network.** Other peers fire agent events from a synced line, so two events within one network update arrive as the second, and `replanned` is not sent at all.
- **One navKit version per session.** Peers match an agent's synced fields by the NavAgent definition each of them loaded, so everyone in a session must run the same navKit. A fresh visit always does; an editor that hot-reloaded navKit while playing beside others may not (reload the page or restart play).
- **Agents of a player who left wait for the room.** When the peer moving some agents leaves, the lowest-numbered peer still in the room claims them after 3 s (`NK.stats().orphans` counts the ones still waiting); until the relay grants the claim they stand where they were.
- **A saturated link falls behind.** If a world sends more synced state than the relay link carries, discrete changes (a style swap, an event, a route) queue up and reach other players late. navKit's own traffic is one crowd line (about 1 KB, 4 times a second for 60 agents) plus a slow per-agent fallback; for very large crowds lower `netRate` or raise `netError`.
## Version history
- **1.5.8**: The engine references are recorded against the current engine library (@builtin a46974b). 1.5.7 moved the pin, but the release still recorded `@builtin::modules.boids.steering` at fe767b9 and the other engine parts at 9f6e9e7: the reference-only changes of the pin move did not reach the merged commit, so 1.5.7 behaves exactly like 1.5.6 (a world on a newer engine gets a partial pinned `boids.steering` without `boids.core` and fails with `module '..core' not found`). No behaviour changes.
- **1.5.7**: Built on the current engine library (@builtin 1279747; was fe767b9). 1.5.6's references to engine modules (`@builtin::modules.boids.steering` in the crowd, the engine pathfinding package) were recorded against fe767b9, so a world on a newer engine received a partial pinned copy of `modules.boids.steering` without the `boids.core` it requires, and every module that loads navKit (aiKit, takedownKit, traversalKit, concealKit) failed with `module '..core' not found`. Recorded fresh, they resolve to the engine's own modules. No behaviour changes.
- **1.5.6**: Documentation only: the 1.5.5 entry below said an allocation-free test workload stalled the same way as the crowd; it did not (it ran during a quiet stretch and nothing stalled). The entry now says what was measured.
- **1.5.5**: **Standing agents write nothing, and the tick says where its time went.** With one player in the room the crowd wrote every agent's position and rotation every frame (two new tables and two engine writes each), even for an agent standing still; it now skips the write when the agent has not moved or turned since the last one, since the transform already holds exactly that. With other players nothing changes (that path already sent only what moved). `NK.stats()` adds `planFrameMs`, `stepMs`, `stepMaxMs` and `gridMs`: what path planning, stepping every agent, the slowest single agent and the neighbour grid took in the last tick, so a probe can tell which part a slow frame was in. Measured in townsfolkKit's 40-person market: under heavy machine load the crowd's slow frames were stalls of 70-190 ms inside one agent's step or one path plan, in code that does no long work (over 1,040 real routes measured one by one, a path search never ran more than 0.1 ms without a pause point); on a quiet stretch no crowd frame went over 20 ms in 90 s. Tests 81/81.
- **1.5.4**: **A standing agent on the peer that moves it costs almost nothing to draw.** The crowd now records whether an agent's transform sits exactly on the spot it was simulated at (it was just written there, or the agent has not moved or turned since); while it does, and the body's pivot carries no offset, `applyVisual` keeps the drawn position and returns without any maths or writes. With other players present, a transform held back for the network still takes the full path, so nothing drawn changes. In townsfolkKit's 40-person market (most of them standing at stalls) the agents' own updates fell by about a third. Tests 81/81.
- **1.5.3**: **Straightening a path can pause too.** A path search already paused once the frame's planning budget (`planBudgetMs`, 5 ms) was spent, but the string-pull that straightens the path afterwards (`map:smooth`, a clear-line check per corner) always ran to the end in the frame the search finished. It now gives the planner the same chance to pause before each clear-line check and every 32 steps along a long line, so planning stays inside its budget. Measured over 312 townsfolk routes in Mirage Wells: the straightening was at most about 2 ms of work on a desktop (0.3 ms typically), and now pauses every few microseconds of it. Calls outside the crowd's planner (`NK.findPath`, `map:clearLine`) run as before. Asked for by townsfolkKit, whose browser readings showed crowd frames over 33 ms.
- **1.5.2**: Agents cost less a frame. The body's pivot (and, with `look = "none"`, the entity's own children) is written only when its offset changes, so an agent on the peer that moves it, or one standing still, writes nothing; the children of a `look = "none"` agent are listed once a second instead of every frame; the per-frame target and speed bookkeeping no longer makes tables. New `agent:visualXYZ()` answers where the body is drawn as three numbers, for callers that ask every frame. Asked for by townsfolkKit, whose 40-person market wrote each agent's empty pivot every frame (navKit.NavAgent x40 went from 3.3 to about 1.5-3 ms a frame there, on a loaded machine).
- **1.5.1**: **Agents steer round players.** Avoidance only ever looked at other agents, so guards, patrols and crowds walked straight into a standing player's character and through it. Every player's character (read from the scene's players on each peer) now stands in the avoidance grid as a heavy body: agents pick a way round it, and one that still overlaps steps back out of it on its own (navKit never moves a player). `NK.addBody(entity, radius?)` / `NK.removeBody(entity)` do the same for any other character navKit does not move, `NK.setAvoidPlayers(false)` turns it off, `NK.stats().bodies` counts them. Found in Dockhands (disguiseKit's level), where the foreman and the yard patrol walked 0.2 m into the player. New test (81 tests).
- **1.5.0**: **Bounded path searches.** A search used to be allowed to expand every node of the map (`max(8000, nodeCount)`), so on a 160 m town or 200 m dungeon grid an agent sent somewhere it could not reach searched all ~100,000 cells in one frame (2.7 s measured on a 160 m grid) and stalled the game, again on every retry. Now: one search expands at most `NK.searchBudget().maxNodes` nodes (default 10,000; `opts.maxNodes` on a profile still wins), and ends as a partial path to the closest spot found, or `unreachable` when that spot is where it began; the result says `capped = true`. Agents' searches share one budget a frame (`frameMs`, default 5 ms): a search still going when it is spent pauses and carries on next frame, so no frame is held up by planning (the same unreachable search: 51 slices of at most 27 ms, against 285 ms capped in one go and 2,734 ms before). An agent whose goal is out of reach retries after 3 s, then 6, 12, up to 30 s (`retryDelay`, `retryMaxDelay`); a new target resets it. `NK.searchBudget(opts?)` reads and sets all of these; `NK.stats()` adds `capped` and `carried`. `NK.findPath` called directly still runs at once (bounded by `maxNodes`). The API is unchanged otherwise. Tests for each (80 tests).
- **1.4.9**: navKit's own modules reach each other as `~navKit.<module>` instead of `~.<module>`, so every internal reference is recorded fresh against this release. A reference keeps the module version it was first recorded with: `api` still asked for an old `maps` version that no release holds, so in a fresh world its load waited forever on the fetch, path planning never started, and every agent read "unreachable". No behaviour changes.
- **1.4.8**: Released from a branch started at main's head and merged as a fast-forward, so the release and main are one commit. 1.4.7's pull request could not fast-forward, so its release (the branch push) and main (the merge) were two commits holding the same files; content recorded against each brought navKit twice, and a game built on aiKit was refused on a fresh install ("runs two releases"). No behaviour changes.
- **1.4.7**: Released from this world's main (package.yaml states the version unquoted again, so the version test reads it), so content installed from the world and content that names the release record the same navKit. 1.4.5 and 1.4.6 were published from their pull requests' own pushes while main stayed at 1.4.4, so a game that installed navKit from here and aiKit (which records the 1.4.6 release) got two navKit releases, and a fresh install of it was refused ("runs two releases"). `NK.VERSION` and this README still read 1.4.5 after the 1.4.6 change; all three say 1.4.7 now. No behaviour changes.
- **1.4.6**: Town-sized maps: a time-budgeted spread bake and a linear-time waypoint build.
- **1.4.5**: `NK.warp(e, pos)`: put an agent on a spot at once, for every player (its path and any link it was crossing are dropped, its transform is sent at once, and it plans again from there if it still has a target). Asked for by townsfolkKit, whose distant townsfolk time their trips instead of walking them and step in and out of house doors.
- **1.4.4**: Documentation: the package description says how to install navKit.
- **1.4.3**: Fixes for a player who joins someone else's game, found with a friend joining the Pathwise gallery. **`ClickToMove` stops logging a refusal per click**: a click from a player who is not in charge of the agent still moves it, but only the peer in charge counts it in `clicks` (an engine refuses writes to another peer's entity). **The gallery's crowd looks the same for a joiner**: a joiner saw each pedestrian with a second, blocky body on top (spawnerKit's fallback look, built before the gallery's pedestrian kind was defined there); fixed in spawnerKit 1.1.3, which the gallery now runs and which is sent to spawnerKit's world. **The gallery's crates stop flooding a joiner's log**: fixed in pushKit 1.0.2. README: click counter, late joiners.
- **1.4.2**: Fixes found while re-checking after updating the gallery's other kits. **No invisible walls after a reload**: a blocked box navKit had registered with the engine's pathfinding could outlive navKit's own record of it (a hot reload of the kit, or a script the engine's watchdog stopped before its cleanup ran), and then blocked every path through that spot for the rest of the session; navKit now removes such leftover boxes when it loads, and an obstacle whose box has gone gets a new one the next time it moves. **The crowd heals a stale slot**: a frame cut short while an agent was being removed could leave the crowd holding a slot with no agent, which stopped every agent; the crowd now drops such a slot. Known limits: guide links to kits that are not installed (#22513). A test for each obstacle case (77 tests).
- **1.4.1**: Documentation, from following the example guide in a fresh world against the published 1.4.0: installing aiKit beside navKit 1.4.0 also leaves aiKit's pinned navKit 1.3.2 under `/source/deps/.../versions/`, which does nothing (every agent, the guards included, runs on the navKit in `/source`); the guide's troubleshooting and the #22451 known limit say so.
- **1.4.0**: Guides and re-checks; no change to how agents move. **Two guides** ship inside the package: "How to make NPCs find their way" (every part of the kit for someone new to it) and "Build a crate yard where guards chase you and you block them with crates" (an example game from navKit, aiKit, SecondWind and pushKit, followed as written in a fresh world). **pushKit**: the gallery's pushable crate became its own package in the Pathwise world, so any game can let players shove crates (the example uses it). **Re-checked on today's engine**: a crate landing on an agent (every agent is pushed clear and carries on; 76/76 tests, twice) and `arrived` firing once per arrival (0 doubles in 334 live arrivals). Known limits: long waits (#19849) and extra copies left by installs beside other kits (#22451) added.
- **1.3.3**: `NavObstacle` gains `static` (block once, no per-frame check) and checks position before re-measuring bounds, so scenery obstacles cost nothing a frame (131 river boxes: 4.9 ms -> 0.45 ms).
- **1.3.2**: Documentation: the README heading, version line and constants name the current version again.
- **1.3.1**: Documentation: the browser frame rate measured with the browser alone in charge of the gallery (about 7 to 12 frames a second, navKit about 24 ms a frame) and the late-join result (a second engine joining the running gallery saw all 30 of the crowd, moving within 12 seconds).
- **1.3.0**: Fixes from a third review. **Buried agents get out**: when an obstacle lands on or settles over an agent (a dropped or pushed crate), the agent is moved to the nearest spot it can stand on clear of every obstacle and carries on to its goal; fliers rise over the box. It works for every movement style, on grid, waypoint and multi-level maps, and for agents that had already arrived (they stay arrived). `NK.stats()` counts it as `escapes`. **One `arrived` per arrival**: an agent given its next target the moment it arrived (a patrol) used to arrive a second time at the end of its old route while the new plan waited its turn, so anyone counting arrivals got double; now `arrived` fires once per arrival, on the peer moving the agent and on every other peer. **Gallery**: a red crate in the corridor drops on a walker every 8 s, or when a player stands on the red pad. Tests for each (76 tests).
- **1.2.1**: Fixes from a hands-on review on desktop and in the browser. **Browser**: `NavMap` now bakes from the first frame the game runs (it used to bake only if play mode was already on when it started, which in a browser left every map unbaked and every agent still), waits until its box's colliders stop arriving, retries a bake that found no floor, and bakes again when colliders arrive late; the `NavDebug` panel moves onto the window when the viewport camera does not draw the game UI. **Links**: a ladder (or any link) on a grid or waypoint map is walked to, climbed and stepped off on top, instead of being "climbed" a few metres early on flat ground (an engine A\* bug put link labels on the wrong step; every navKit edge now carries metadata); grid maps no longer join cells more than `maxStep` apart; an agent plans on the map holding both its start and its goal. **Styles**: a flier switched to a ground style in the air lands on the floor below and then plans, instead of hanging at its flight height. **Movement**: an agent the look-past shortcut carries beyond a corner counts the corner as passed (it used to dither there for seconds); an agent left where its map has no floor for it (inside a planter, after another player handed it over) steps out to the nearest walkable spot at its own height. **Multiplayer**: the agents of a player who left are claimed by the lowest-numbered player still in the room (`NK.stats().orphans`); crowd lines left behind are removed; each agent's synced transform (the slow fallback behind the crowd line) goes out only on links, teleports and floor changes, after `netError` metres (now 20) or every 10 s, where it used to go out ~55 times a second for 58 agents and saturate a browser's link. **Tests**: agents that walk, detour around a box that appears in their way, climb ladders on both map kinds, and land after a style swap, and step out of a box they were left inside; a `NavMap` with late colliders. **Second review**: new per-agent settings `turnRate`, `avoidance` and `debugDraw`; the multi-floor map kind is `multiLevel` (`layered` still works); bodies spawned on the very same spot part (they used to stay inside each other for good, the browser crowd's knot), and agents sent to one spot queue up beside whoever stands on it instead of shoving round them for ever; `NavDebug`'s button answers real mouse clicks and taps in play (the game holds the pointer there, so the UI never saw them), and `ClickToMove` asks the UI's hit test whether a press landed on the game's own UI. Tests for each (72 tests).
- **1.2.0**: `NavDebug` gains an on-screen panel (`button`, `hint`): a button in the bottom-right corner that toggles the debug drawing by mouse or touch, showing the key and a one-line legend while drawing. `ClickToMove` ignores presses on the game's own on-screen UI. The walker, runner, sneaker and climber looks are rebuilt to the engine's unit-sized meshes (they had been floating, with loose parts) and given clearer silhouettes and motion: the walker swings its arms, the runner leans into speed streaks, the sneaker is a low hooded cloak, the climber (now pink, apart from the green cart) reaches up hand over hand. A look's `scale` now scales the whole body about its feet. Tests for the new parts.
- **1.1.0**: Multiplayer bandwidth, found by a two-player test. Positions of all agents travel together in one crowd line per moving peer (new `NavNet` component; `netRate`, `netSlot`, `netWriter`), with the agent transform as a slow fallback (`netError`); other screens draw each body on a smoothed, predicted local pivot (`smooth`, `visualPosition()`); routes cross as compact text (`routeData`), events as one line (`eventData`); `replanned`, `steerPoint` and `routeIndex` stay on the peer in charge; a moment's status change is written once a frame; unchanged targets are not re-sent; teleport shrinking is drawn locally. Agents re-register if a hot reload empties the crowd. Tests for the new parts (56 in all).
- **1.0.0**: First release. Grid, waypoint and multi-level maps baked from colliders and terrain; ramp, stairs, ladder, jump, teleporter and door links with per-style refusals; NavAgent with smoothing, arrival, avoidance, re-planning and events; eight movement styles with their own looks; NavObstacle; ClickToMove; debug drawing; host-authoritative multiplayer; a test for every public call.