@adatechnology/game-crowd
v0.8.7
Published
Any crowd as a struct of arrays, pure and seeded: relevance bands, perception by sight, hearing and smell, a sliced flow field, separation, attack slots, chain alerts, doors, piles against walls, abilities as type traits, corpses, population and migration
Maintainers
Readme
@adatechnology/game-crowd
Any crowd as a struct of arrays, pure and seeded: a horde, but also a street of people or a herd. Relevance bands with hysteresis, perception by sight,
hearing and smell, a sliced flow field, a spatial hash and separation, six attack slots, chain alerts, doors that take blows, piles of bodies against
walls, special moves as type traits, corpses, a blood trail, the population and migrations. No three.js, no audio, no game content: it emits events
(sound, effect, message, kill...) and the game plays, draws and shows them.
It is a literal port of the team game's horde (jogo.js G 66714-67430: hordeUpdate and everything it calls, with the doors of G 63796-64050). Every
number is in src/data/defaults.json with its source line, and the golden game-crowd.json (8 scripted scenes of the game code in node:vm, recorded by
tools/characters-catalog) is replayed frame by frame by the tests.
- The pack is data. Types (health, speeds, damage, bite, multipliers, perception, size), ages, outfits, segments and the clothes palette come in
pack.@adatechnology/game-characters-undeadgives the undead one (undeadCrowdPack(), the game's 13 types); any game writes its own. - Special moves are traits of a type (
vaultsLow,pounce,heavySwing,soundSeeker,caller,burns,waterWeak,submerged,ambush,burst,eatsCorpses,tracker...). A type without traits only walks, hears, sees and hits.pluginsadd moves without touching the core. - The normal world comes first. With no target (
target: null) nobody chases: agents wander and pause. The target is anything with theCrowdTargetshape;game-player'sPlayeris one as it is. - The world is a
NavGrid(createNavGrid, the game's 0.5 m grid with occupancy codes and heights) andwater(x, z); doors arecreateDoors. - Every draw is in the game's order on the stream you pass (
random); the flow field's budget isflow.cellsPerStep(default 20000 cells per step, the same field on any machine);flow.clockis the legacy time budget, used only when passed alone (() => 0finishes each field in one frame, as the golden does).
Install
pnpm add @adatechnology/game-crowdBrowser without a bundler (the global is GameCrowd):
<script src="https://unpkg.com/@adatechnology/game-crowd/dist/index.global.js"></script>Usage
import { createCrowd, createNavGrid } from '@adatechnology/game-crowd'
import { undeadCrowdPack } from '@adatechnology/game-characters-undead'
const grid = createNavGrid() // 768 m, 0.5 m cells, a solid border
grid.fillRect(x0, z0, x1, z1, 1, 3) // a wall 3 m tall
const crowd = createCrowd({ pack: undeadCrowdPack(), seed: 7, grid, water: (x, z) => pool.contains(x, z) })
crowd.doors.add(0, -2.1, 'x', 1.2)
crowd.on('sound', (s) => host.audio?.play({ sound: s.sound, volume: s.volume, position: s.position }))
crowd.on('effect', (e) => host.effects?.play({ effect: e.effect, point: e.point }))
crowd.on('message', ({ id, seconds }) => hud.show(id, seconds))
crowd.target = player // game-player's Player, or { state, grab, hurt, knock, release }
player.setWorld({ ...world, crowd: crowd.asPlayerCrowd() })
player.on('noise', ({ x, z, radius }) => crowd.emitNoise(x, z, radius))
// every frame, in the game's order
crowd.updateTrail(dt)
crowd.update(dt, { nightFactor, viewYaw: camera.yaw })
crowd.updatePopulation(dt, { x: camera.x, z: camera.z, yaw: camera.yaw, far: fog.far }, { target: 1200, migration })
crowd.updateCorpses(dt)
crowd.damage(i, { region: 0, amount: 35, distance: 12, caliber: { id: '9x19', class: 'pistol', skull: 1 } })
crowd.store.x[i] // the struct of arrays: x, z, y, yaw, state, hp, missing, band, variant...Walls, doors and gates of the world
bindNavObstacles(crowd, source) writes into the crowd's grid and doors what an SDK publishes as a NavObstacleSource of game-contracts (the houses of
game-floorplan-three with createHouseNavObstacles): each solid is a wall (a stub of a cut wall under 1.2 m a low wall the agents climb), each door or gate a crowd
door the agents push against and hit until it breaks, and the source is told (breakDoor, the house swings it open). Call binding.sync() once per fixed step before
crowd.update: a door that opened or closed and a wall a blast cut change only their own cells, from what was under them and the solids still standing there.
Furniture the agents shove
crowd.setMovables([{ id, minX, minZ, maxX, maxZ, top }]) lists the pieces on the floor the host lets the agents push (a sofa, a wardrobe). An agent walking into one
stops at its face and, going into it, leans numbers.shoveForce newtons (by its build) on it, with the arms out and the body forward (store.shoveX/shoveZ, read by the
look of game-crowd-three). The forces of the agents on the same piece add up, once per agent and update: crowd.shoves lists, after each update, the summed force, its
direction and how many push. The host decides whether the piece moves (its mass and friction) and moves it. Civilians do not shove: crowd.movableAt(x, z, radius) tells them a piece is ahead, and they walk round it along its face, always turning the same way.
Civilians, herds, flocks and the region model
import { HERD_ROLES, bindInfection, carrionCenter, createCivilians, createFlock, createHerd } from '@adatechnology/game-crowd'
// people with a routine by the hour; agents that are closer to them than to the target hunt them
const civilians = createCivilians(crowd, { people: [{ id: 'ana', home: 'house_2', routine: [[19, 'market']] }], buildings, hour: () => clock.hour })
civilians.on('bitten', ({ id, near }) => diary(id, near))
civilians.join('ana') // follows the target
civilians.flee('ana', path) // leaves; `gone` at the end
// animals: wander, rest, flee, call; their calls are noises the crowd hears
const herd = createHerd(crowd, { blocked: insideABuilding })
herd.add({ ...HERD_ROLES.cow, species: 'cow', x, z, walkHz: cow.walkHz, runHz: cow.runHz, size: quadrupedLayout(cow.body).size })
const vultures = createFlock({ count: 3, mode: 'carrion' })
// every frame, after crowd.updateTrail and before crowd.update
civilians.update(dt)
herd.update(dt)
vultures.update(herd.time, dt, carrionCenter(crowd.corpses.entries.map((e) => e.data), carcass), [camera.x, camera.z])
// the region model of game-infection: numbers become agents near the player and go back when far
const binding = bindInfection(crowd, infection, { place: (region, seed, k) => spotIn(region, seed, k), civilians, regionOf })
binding.materialize('downtown', 40)
binding.giveBack()Civilians are a literal port of the game's survivors on the block (jogo.js G 69960-70175: pontos, rota, npcZombies, zChaseNpc, npcMorre,
npcVira, npcMove, npcUpdate) without their names, lines, radio and diary; the herd of bichoLivre, zumbiPerto and bichosUpdate (G 66601-66700)
without the rig; the vultures of G 66700-66708 and the live map's ring of birds of the Bancada de Hordas (G 53609-53615). Two goldens replay them
with the horde: game-crowd-civilians.json (3 scenes) and game-crowd-herd.json.
Physics: a dense horde and the chain of a blast
CrowdOptions.physics is off by default and then the horde is the game's, bit for bit (the team goldens run with it off). CROWD_PHYSICS_DEFAULTS turns everything on:
const crowd = createCrowd({ pack, seed, physics: { ...CROWD_PHYSICS_DEFAULTS, playerPressure: { enabled: true, knockThreshold: 1500, crushDamagePerSecond: 6 } } })
// fixed steps only: the same seed gives the same result at 30, 60 and 144 fps
crowd.update(1 / 60, { target, bandCentre: [x, z] })
crowd.blast({ point: [x, y, z], energy: 200000, radius: 15, lethalRadius: 5 }) // resolved at the start of the next step, in one pass over the agents
crowd.stats.physics // falls by cause, fallsBeyondBlast, climbers, moundMax, thrownPeak, blastChecks...- Contact: inelastic impulses between bodies (symmetric Gauss-Seidel, so a low index has no advantage) and a position correction by the mean of what each agent was asked to move; it never adds energy.
- Pressure: a field apart from the contact that moves one hop per fixed step, so a file of N agents pushing on a wall gives its front
Ntimes the drive (design-chain-horde.mdsection 4.5). - Balance: standing, staggering, fallen, getting up and thrown, by pressure over a critical value of the body (
CrowdType.balanceand the personality), shoves, trips, landings and collapses. - Mound: lying bodies are a height per cell (integer millimetres) that others climb, trample and bring down when the base goes.
- Thrown bodies: a pool of 32 simulated here (
crowd.thrown) and only drawn by the renderer;thrown.priorityis'mixed'(half the slots to the fastest, half to the nearest to the band centre),'fastest'or'nearest'. - Personality: speed, reaction, stability, trip, drive, cadence, aggression, gait and idle from the identity of each agent, never from the shared random stream.
- Far band (R1): no pairs. Every 12th step a coarse grid of 2 m counts the standing walkers of band R1 per cell; above 4 bodies the wanted speed is
4 / bodiesand the field is(bodies − 4) · 150N, which the same balance rule reads (physics.density, needsbalance). A body that falls there lies without entering the mound, and joins it when it comes into R0. - Player pressure:
playerPressurereports the pressure of the horde on the target throughknockandhurt(off in the package; a game turns it on).
The crowd in the physics engine
createAgentBodies(loop, crowd, { radius }) gives each agent of the store a kinematic capsule on the agent layer, moved in the loop's crowd phase before every fixed step: game-crowd moves, the engine only lets the agents push what they meet (a door leaf, a prop, debris); agents meet neither each other nor the ground (LAYER_PAIRS). Capsule i follows agent i, also after a removal moved the last agent into i. Nothing the engine does is written back into the store, so state-hash and the team goldens are the same with or without it.
createDoorBodies(loop, doors, { leafMass, breakImpulse }) hangs each closed door on a hinge: a dynamic leaf on the prop layer with a breakImpulse; when the agents tear the hinge off, the crowd's door is broken through doors.hit (grid opened, events fired). A door that opens or breaks by another cause loses its leaf, and one shut again or added gets one. The corpses go through createCorpseBodies of game-physics (onSettled → relocateCorpse).
Cost (spec 008, 1 000 agents and a door, pnpm --filter @adatechnology/game-crowd test:cost): median 0.34 ms, p99 0.5 ms per fixed step.
The contact and the pressure in a worker
physics.worker is 'off' by default (the step runs where it always did). 'auto' moves the contact and the pressure to a worker when one can be made and stays in the step when it cannot; 'on' throws instead of staying.
The worker is one step behind: it is handed the state at the end of step k, and step k + 1 (workerLatency: 1, default) or k + 2 (workerLatency: 2) adds what it computed as deltas of position, push and velocity and replaces the pressure field. With the same inputs per step the answer is the same whichever thread computed it: inline (the same kernel on the calling thread) is the reference, and the tests compare it with a worker byte for byte. Balance, mound, thrown bodies and blasts stay on the main thread.
const crowd = createCrowd({ pack, seed, physics: { ...CROWD_PHYSICS_DEFAULTS, workers, workerLatency: 2 } })
// ...
crowd.dispose() // releases the crowd.physics residentworkers: the@adatechnology/game-workerscoordinator (CLAUDE.md §14); the crowd runs as itscrowd.physicsresident (crowdPhysicsKind) in lanesim, with a fixed due frame and a byte-identical main-thread fallback when late or absent. Withoutworkers(and withoutworkerFactory),worker: 'auto'stays on the main thread; the package never spawnsnew Worker(...)directly.workerTransport: 'shared'(only with a customworkerFactory, default whereSharedArrayBufferis usable): frame in aSharedArrayBuffer, control word withAtomics. The main thread waits for the answer, so the run is reproducible. A browser needs the page cross-origin isolated: serve it withCross-Origin-Opener-Policy: same-originandCross-Origin-Embedder-Policy: require-corp(orcredentialless), and every cross-origin sub-resource withCross-Origin-Resource-Policyor CORS.crossOriginIsolatedis thentrue. Node hasSharedArrayBufferalways.workerTransport: 'transfer'(only with a customworkerFactory): without isolation; the frame goes bypostMessagewith its buffer transferred. The main thread cannot wait for an event, so it applies the answer when it has arrived and runs without it otherwise (the contact then lags more): it is not reproducible.workerFactory: optional host-provided factory for callers that manage their own worker outsidegame-workers(the worker callsattachPhysicsWorker(port);tests/fixtures/node-physics-worker.mjsis a node example). Ignored whenworkersis passed.- The frame copies the grid occupancy every step (1 byte per cell, 2.4 MB for the default 768 m grid): a
NavGridno bigger than the playable area keeps that copy small.
Measured with bench/dense-update.mjs (node, 2000 agents pressed against a wall, all in band R0, WORKER=shared LATENCY=2): crowd.update on the main thread goes from 3.0 to 3.8 ms to 1.6 to 2.1 ms mean (the machine was loaded); with one step of latency the main thread waits for the worker for a third of its step, so it gains little. See specs/005-camadas-e-quadro/evidence.md, row T4b.perf.
bench/dense-update.mjs measures crowd.update with 1000 and 2000 agents pressed against a wall, with and without the physics.
What is not here yet
The drawing and the test area are in @adatechnology/game-crowd-three. The game's multi-floor houses (ANDARES) and the roof (ROOF) are not ported: the crowd walks one
ground grid (floor is kept on each agent for a game that adds floors).
Knock down by a car (knockDown, spec 008 T6.26)
crowd.knockDown(i, { x, z }) shoves only agent i and asks the balance to make it fall (cause SHOVE): it lies, slides with the push and gets up in the game-crowd time. Without physics.balance it falls back to a one-second stun. It is not the area blast. createRunOver (game-vehicles-driving) calls it in the knock band.
