@v12-engine/engine 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/abilities/buffs.d.ts +83 -0
- package/dist/abilities/castTold.d.ts +12 -0
- package/dist/abilities/charges.d.ts +28 -0
- package/dist/abilities/dispel.d.ts +9 -0
- package/dist/abilities/effectFields.d.ts +10 -0
- package/dist/abilities/effects/buff.d.ts +8 -0
- package/dist/abilities/effects/core.d.ts +1 -0
- package/dist/abilities/effects/damage.d.ts +1 -0
- package/dist/abilities/effects/heal.d.ts +2 -0
- package/dist/abilities/effects/missile.d.ts +1 -0
- package/dist/abilities/effects/moves.d.ts +11 -0
- package/dist/abilities/effects/passives.d.ts +15 -0
- package/dist/abilities/effects/sight.d.ts +4 -0
- package/dist/abilities/effects/spawn.d.ts +2 -0
- package/dist/abilities/effects/timed.d.ts +4 -0
- package/dist/abilities/effects/trade.d.ts +1 -0
- package/dist/abilities/effects.d.ts +122 -0
- package/dist/abilities/land.d.ts +21 -0
- package/dist/abilities/scaled.d.ts +21 -0
- package/dist/abilities/text.d.ts +113 -0
- package/dist/ai/area.d.ts +53 -0
- package/dist/ai/brain.d.ts +528 -0
- package/dist/ai/budget.d.ts +67 -0
- package/dist/ai/checks.d.ts +115 -0
- package/dist/ai/computer.d.ts +166 -0
- package/dist/ai/defence.d.ts +108 -0
- package/dist/ai/define.d.ts +21 -0
- package/dist/ai/economy.d.ts +129 -0
- package/dist/ai/geometry.d.ts +35 -0
- package/dist/ai/goals.d.ts +360 -0
- package/dist/ai/index.d.ts +38 -0
- package/dist/ai/knowledge.d.ts +418 -0
- package/dist/ai/lanes.d.ts +232 -0
- package/dist/ai/melee/build.d.ts +61 -0
- package/dist/ai/melee/goals.d.ts +299 -0
- package/dist/ai/melee/heroes.d.ts +27 -0
- package/dist/ai/melee/index.d.ts +14 -0
- package/dist/ai/melee/production.d.ts +8 -0
- package/dist/ai/melee/surrender.d.ts +24 -0
- package/dist/ai/micro.d.ts +278 -0
- package/dist/ai/mission.d.ts +195 -0
- package/dist/ai/missionRules.d.ts +18 -0
- package/dist/ai/module.d.ts +116 -0
- package/dist/ai/options.d.ts +61 -0
- package/dist/ai/plans/build.d.ts +280 -0
- package/dist/ai/plans/placement.d.ts +82 -0
- package/dist/ai/plans/plans.d.ts +105 -0
- package/dist/ai/plans/production.d.ts +210 -0
- package/dist/ai/plans/purse.d.ts +73 -0
- package/dist/ai/plans/tech.d.ts +37 -0
- package/dist/ai/profiles.d.ts +204 -0
- package/dist/ai/reach.d.ts +4 -0
- package/dist/ai/report.d.ts +203 -0
- package/dist/ai/roles.d.ts +133 -0
- package/dist/ai/rules.d.ts +288 -0
- package/dist/ai/scouting.d.ts +98 -0
- package/dist/ai/settings.d.ts +73 -0
- package/dist/ai/squads.d.ts +429 -0
- package/dist/ai/strength.d.ts +167 -0
- package/dist/ai/task.d.ts +118 -0
- package/dist/ai/tasks/attack.d.ts +7 -0
- package/dist/ai/tasks/capture.d.ts +21 -0
- package/dist/ai/tasks/creep.d.ts +16 -0
- package/dist/ai/tasks/defend.d.ts +29 -0
- package/dist/ai/tasks/drop.d.ts +34 -0
- package/dist/ai/tasks/escort.d.ts +16 -0
- package/dist/ai/tasks/gather.d.ts +23 -0
- package/dist/ai/tasks/harass.d.ts +7 -0
- package/dist/ai/tasks/hold.d.ts +20 -0
- package/dist/ai/tasks/index.d.ts +32 -0
- package/dist/ai/tasks/move.d.ts +19 -0
- package/dist/ai/tasks/patrol.d.ts +8 -0
- package/dist/ai/tasks/retreat.d.ts +20 -0
- package/dist/ai/tasks/scout.d.ts +29 -0
- package/dist/ai/tasks/shared.d.ts +74 -0
- package/dist/ai/team.d.ts +155 -0
- package/dist/ai/threat.d.ts +91 -0
- package/dist/ai/view.d.ts +366 -0
- package/dist/ai/waves.d.ts +126 -0
- package/dist/ai.js +6239 -0
- package/dist/ai.js.map +1 -0
- package/dist/aiTesting.d.ts +179 -0
- package/dist/areas.d.ts +149 -0
- package/dist/attacks.d.ts +66 -0
- package/dist/attributes.d.ts +66 -0
- package/dist/brain-BvVdUhX8.js +7659 -0
- package/dist/brain-BvVdUhX8.js.map +1 -0
- package/dist/builds-C6LfgvEU.js +460 -0
- package/dist/builds-C6LfgvEU.js.map +1 -0
- package/dist/bytes.d.ts +6 -0
- package/dist/camps.d.ts +95 -0
- package/dist/capture.d.ts +131 -0
- package/dist/cellLayers.d.ts +75 -0
- package/dist/cinematics.d.ts +194 -0
- package/dist/clock.d.ts +32 -0
- package/dist/commands.d.ts +235 -0
- package/dist/components.d.ts +184 -0
- package/dist/computers.d.ts +108 -0
- package/dist/concealment.d.ts +61 -0
- package/dist/coreComponents-syuh2fPG.js +5149 -0
- package/dist/coreComponents-syuh2fPG.js.map +1 -0
- package/dist/coreComponents.d.ts +1 -0
- package/dist/dashing.d.ts +8 -0
- package/dist/debug.d.ts +36 -0
- package/dist/debug.js +3 -0
- package/dist/debugCommands-CzjrSm66.js +14739 -0
- package/dist/debugCommands-CzjrSm66.js.map +1 -0
- package/dist/debugCommands.d.ts +213 -0
- package/dist/debugging.d.ts +10 -0
- package/dist/definitions.d.ts +43 -0
- package/dist/defs.d.ts +1162 -0
- package/dist/denying.d.ts +81 -0
- package/dist/destructibles.d.ts +27 -0
- package/dist/determinism-BCymQwiE.js +518 -0
- package/dist/determinism-BCymQwiE.js.map +1 -0
- package/dist/determinism.d.ts +121 -0
- package/dist/dialog.d.ts +94 -0
- package/dist/effectRefs.d.ts +16 -0
- package/dist/effects.d.ts +80 -0
- package/dist/endings.d.ts +22 -0
- package/dist/engagement.d.ts +108 -0
- package/dist/engineEvents.d.ts +710 -0
- package/dist/entity.d.ts +409 -0
- package/dist/entityIndex.d.ts +50 -0
- package/dist/errors.d.ts +85 -0
- package/dist/events.d.ts +97 -0
- package/dist/exactMath.d.ts +63 -0
- package/dist/features.d.ts +10 -0
- package/dist/fields.d.ts +114 -0
- package/dist/fixture.d.ts +17 -0
- package/dist/fog.d.ts +110 -0
- package/dist/formation.d.ts +111 -0
- package/dist/friendlyFire.d.ts +26 -0
- package/dist/game-DiJEN-Ks.js +5800 -0
- package/dist/game-DiJEN-Ks.js.map +1 -0
- package/dist/game.d.ts +501 -0
- package/dist/gameData.d.ts +325 -0
- package/dist/gameFiles.d.ts +26 -0
- package/dist/gates.d.ts +28 -0
- package/dist/generate.d.ts +403 -0
- package/dist/generateWorker.d.ts +39 -0
- package/dist/grid.d.ts +53 -0
- package/dist/ground.d.ts +127 -0
- package/dist/groundSpeed.d.ts +22 -0
- package/dist/hero.d.ts +177 -0
- package/dist/home.d.ts +14 -0
- package/dist/hooks.d.ts +780 -0
- package/dist/hotReload.d.ts +76 -0
- package/dist/ids.d.ts +26 -0
- package/dist/index.d.ts +227 -0
- package/dist/index.js +4701 -0
- package/dist/index.js.map +1 -0
- package/dist/inspect-D9dWHmZ0.js +491 -0
- package/dist/inspect-D9dWHmZ0.js.map +1 -0
- package/dist/inspect.d.ts +176 -0
- package/dist/inventory.d.ts +18 -0
- package/dist/items.d.ts +91 -0
- package/dist/lanes.d.ts +213 -0
- package/dist/life.d.ts +53 -0
- package/dist/local-Dkovq42k.js +1379 -0
- package/dist/local-Dkovq42k.js.map +1 -0
- package/dist/log.d.ts +140 -0
- package/dist/manaBurn.d.ts +39 -0
- package/dist/map/file.d.ts +114 -0
- package/dist/map/images.d.ts +18 -0
- package/dist/map/look.d.ts +47 -0
- package/dist/map/pathProfile.d.ts +13 -0
- package/dist/map/resize.d.ts +54 -0
- package/dist/map/schema.d.ts +10 -0
- package/dist/map/terrain.d.ts +32 -0
- package/dist/map/types.d.ts +613 -0
- package/dist/map.d.ts +7 -0
- package/dist/mapCheck/cells.d.ts +19 -0
- package/dist/mapCheck/rule.d.ts +30 -0
- package/dist/mapCheck/rules/names.d.ts +3 -0
- package/dist/mapCheck/rules/objects.d.ts +3 -0
- package/dist/mapCheck/rules/paths.d.ts +3 -0
- package/dist/mapCheck/rules/players.d.ts +3 -0
- package/dist/mapCheck/rules/races.d.ts +3 -0
- package/dist/mapCheck/rules/random.d.ts +3 -0
- package/dist/mapCheck/rules/regions.d.ts +3 -0
- package/dist/mapCheck/rules/targets.d.ts +3 -0
- package/dist/mapCheck/rules/walking.d.ts +3 -0
- package/dist/mapCheck.d.ts +23 -0
- package/dist/mapFields.d.ts +364 -0
- package/dist/mapFile.d.ts +23 -0
- package/dist/mapMeasure.d.ts +95 -0
- package/dist/mapMerge.d.ts +19 -0
- package/dist/mapObjectives.d.ts +82 -0
- package/dist/mapObjects.d.ts +1 -0
- package/dist/math.d.ts +44 -0
- package/dist/messages.d.ts +150 -0
- package/dist/missionRules-C-bGxm0Q.js +523 -0
- package/dist/missionRules-C-bGxm0Q.js.map +1 -0
- package/dist/missionRules.d.ts +179 -0
- package/dist/mods.d.ts +146 -0
- package/dist/names.d.ts +93 -0
- package/dist/navigation/agentParams.d.ts +4 -0
- package/dist/navigation/air.d.ts +89 -0
- package/dist/navigation/builds.d.ts +140 -0
- package/dist/navigation/groundAreas.d.ts +23 -0
- package/dist/navigation/navigation.d.ts +127 -0
- package/dist/navigation/recast.d.ts +214 -0
- package/dist/navigation/sidePaths.d.ts +69 -0
- package/dist/navigation/sized.d.ts +1 -0
- package/dist/navigation-worker.js +11 -0
- package/dist/navigation-worker.js.map +1 -0
- package/dist/nearest.d.ts +8 -0
- package/dist/noise.d.ts +12 -0
- package/dist/objectives.d.ts +93 -0
- package/dist/orders/basic.d.ts +96 -0
- package/dist/orders/build.d.ts +91 -0
- package/dist/orders/cast.d.ts +105 -0
- package/dist/orders/facts.d.ts +14 -0
- package/dist/orders/harvest.d.ts +94 -0
- package/dist/orders/idle.d.ts +7 -0
- package/dist/orders/items.d.ts +14 -0
- package/dist/orders/queue.d.ts +24 -0
- package/dist/pack.schema.json +6621 -0
- package/dist/packs/director/index.d.ts +81 -0
- package/dist/packs/heroes/campaign.d.ts +137 -0
- package/dist/packs/heroes/carry.d.ts +59 -0
- package/dist/packs/heroes/commands.d.ts +6 -0
- package/dist/packs/heroes/hire.d.ts +9 -0
- package/dist/packs/heroes/index.d.ts +12 -0
- package/dist/packs/heroes/making.d.ts +16 -0
- package/dist/packs/heroes/respawn.d.ts +42 -0
- package/dist/packs/moba/index.d.ts +34 -0
- package/dist/packs/pack.d.ts +84 -0
- package/dist/packs-g5thvmGn.js +3199 -0
- package/dist/packs-g5thvmGn.js.map +1 -0
- package/dist/packs.d.ts +84 -0
- package/dist/paths.d.ts +51 -0
- package/dist/plain.d.ts +17 -0
- package/dist/player.d.ts +117 -0
- package/dist/portals.d.ts +66 -0
- package/dist/prefabs.d.ts +139 -0
- package/dist/presetBuildings.d.ts +52 -0
- package/dist/presetGround.d.ts +22 -0
- package/dist/profiles-B3NS9jwk.js +335 -0
- package/dist/profiles-B3NS9jwk.js.map +1 -0
- package/dist/races.d.ts +136 -0
- package/dist/randomGroups.d.ts +2 -0
- package/dist/registry.d.ts +464 -0
- package/dist/remains.d.ts +119 -0
- package/dist/replication.d.ts +103 -0
- package/dist/rng.d.ts +17 -0
- package/dist/rules.d.ts +395 -0
- package/dist/rulesCheck.d.ts +37 -0
- package/dist/runes.d.ts +41 -0
- package/dist/save.d.ts +277 -0
- package/dist/scenario.d.ts +56 -0
- package/dist/scheduler.d.ts +67 -0
- package/dist/score.d.ts +306 -0
- package/dist/sequences.d.ts +132 -0
- package/dist/server/doorman.d.ts +21 -0
- package/dist/server/gameServer.d.ts +346 -0
- package/dist/server/index.d.ts +24 -0
- package/dist/server/lobby.d.ts +1 -0
- package/dist/server/log.d.ts +13 -0
- package/dist/server/match.d.ts +24 -0
- package/dist/server/mode.d.ts +168 -0
- package/dist/server/navigation-worker.d.ts +1 -0
- package/dist/server/navigation.d.ts +11 -0
- package/dist/server/ops.d.ts +78 -0
- package/dist/server/packs.d.ts +15 -0
- package/dist/server/ratings.d.ts +62 -0
- package/dist/server/relay.d.ts +34 -0
- package/dist/server/rooms.d.ts +162 -0
- package/dist/server/seat.d.ts +2 -0
- package/dist/server/seatSettings.d.ts +15 -0
- package/dist/server/secret.d.ts +5 -0
- package/dist/server/start.d.ts +54 -0
- package/dist/server/websocket.d.ts +74 -0
- package/dist/server.js +2861 -0
- package/dist/server.js.map +1 -0
- package/dist/session/can.d.ts +20 -0
- package/dist/session/commandReplay.d.ts +92 -0
- package/dist/session/debug.d.ts +65 -0
- package/dist/session/delay.d.ts +15 -0
- package/dist/session/delta.d.ts +98 -0
- package/dist/session/entityState.d.ts +1 -0
- package/dist/session/local.d.ts +214 -0
- package/dist/session/memory.d.ts +27 -0
- package/dist/session/protocol.d.ts +1155 -0
- package/dist/session/remote.d.ts +530 -0
- package/dist/session/replay.d.ts +114 -0
- package/dist/session/seed.d.ts +7 -0
- package/dist/session/share.d.ts +78 -0
- package/dist/session/socket.d.ts +8 -0
- package/dist/session/wire.d.ts +153 -0
- package/dist/session/worker.d.ts +227 -0
- package/dist/shared.d.ts +171 -0
- package/dist/sides.d.ts +75 -0
- package/dist/sight.d.ts +27 -0
- package/dist/simulate-oXBiw1Ff.js +167 -0
- package/dist/simulate-oXBiw1Ff.js.map +1 -0
- package/dist/simulate-worker.d.ts +1 -0
- package/dist/simulate-worker.js +28 -0
- package/dist/simulate-worker.js.map +1 -0
- package/dist/simulate.d.ts +154 -0
- package/dist/smart.d.ts +9 -0
- package/dist/spatial.d.ts +62 -0
- package/dist/spawning.d.ts +33 -0
- package/dist/stances.d.ts +76 -0
- package/dist/start.d.ts +71 -0
- package/dist/stats.d.ts +122 -0
- package/dist/summons.d.ts +63 -0
- package/dist/systems/abilities.d.ts +3 -0
- package/dist/systems/combat.d.ts +71 -0
- package/dist/systems/combatTold.d.ts +14 -0
- package/dist/systems/construction.d.ts +34 -0
- package/dist/systems/economy.d.ts +21 -0
- package/dist/systems/fog.d.ts +19 -0
- package/dist/systems/life.d.ts +3 -0
- package/dist/systems/movement.d.ts +105 -0
- package/dist/systems/orders.d.ts +7 -0
- package/dist/systems/production.d.ts +49 -0
- package/dist/systems/productionQueue.d.ts +40 -0
- package/dist/systems/victory.d.ts +14 -0
- package/dist/talk.d.ts +65 -0
- package/dist/tech.d.ts +62 -0
- package/dist/techTree.d.ts +38 -0
- package/dist/terrain.d.ts +173 -0
- package/dist/terrainSave.d.ts +29 -0
- package/dist/testing.d.ts +58 -0
- package/dist/testing.js +822 -0
- package/dist/testing.js.map +1 -0
- package/dist/tiles.d.ts +34 -0
- package/dist/timers.d.ts +146 -0
- package/dist/tomes.d.ts +48 -0
- package/dist/trade.d.ts +28 -0
- package/dist/transport.d.ts +76 -0
- package/dist/tunables.d.ts +45 -0
- package/dist/upkeep.d.ts +16 -0
- package/dist/veterancy.d.ts +80 -0
- package/dist/walls.d.ts +86 -0
- package/dist/world.d.ts +1118 -0
- package/package.json +80 -5
- package/README.md +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"game-DiJEN-Ks.js","names":["bounty","bountyEvent","found","healed","healedEvent","missedEvent"],"sources":["../src/errors.ts","../src/upkeep.ts","../src/groundSpeed.ts","../src/rules.ts","../src/mods.ts","../src/abilities/castTold.ts","../src/cellLayers.ts","../src/concealment.ts","../src/features.ts","../src/systems/fog.ts","../src/life.ts","../src/clock.ts","../src/systems/combatTold.ts","../src/navigation/sized.ts","../src/orders/basic.ts","../src/orders/items.ts","../src/definitions.ts","../src/registry.ts","../src/systems/abilities.ts","../src/systems/life.ts","../src/fog.ts","../src/sight.ts","../src/spawning.ts","../src/entityIndex.ts","../src/navigation/air.ts","../src/spatial.ts","../src/prefabs.ts","../src/world.ts","../src/game.ts"],"sourcesContent":["/**\n * What becomes of a part of a game that throws: a hook's handler, a listener, a system, a timer, a unit's order, a\n * player's command. The game says (`GameModule.onError`), or whoever runs it (a server, a page); a world that is told\n * nothing throws, as it always did, so that a test sees every error.\n */\nimport type { EntityId, PlayerId } from './entity'\nimport type { World } from './world'\n\n/**\n * - `throw`: the error goes on to whoever stepped the world. Nothing is hidden: for tests and development\n * - `end`: the game ends there, with the reason kept (`world.failure`) and told to the players. The world is not\n * stepped again. What a server and a launched game do when nothing is said: one game ends, and nothing else does\n * - `disable`: the part that threw is switched off and the game goes on without it: the handler, the listener, the\n * system or the timer no longer runs; the order is taken off its unit, the command refused. Never done unasked: a\n * rule that is quietly gone is a game that goes quietly wrong\n *\n * @beta\n */\nexport type ErrorAnswer = 'throw' | 'end' | 'disable'\n\n/**\n * The part of the game that threw\n *\n * @beta\n */\nexport interface ErrorSite {\n\tkind: 'hook' | 'listener' | 'system' | 'timer' | 'order' | 'command'\n\t/** Its id: the handler's, the listener's, the system's name, the timer's, the order's or the command's type */\n\tid: string\n\t/** The hook a handler is on */\n\thook?: string\n\t/** The unit whose order it was */\n\tentity?: EntityId\n\t/** The player whose command it was */\n\tplayer?: PlayerId\n\t/** The mod that added the part or changed it last, for a game with mods (`composeGame`) */\n\tmod?: string\n}\n\n/**\n * What to do about an error: the same for all of them, or decided for each\n *\n * @beta\n */\nexport type ErrorPolicy = ErrorAnswer | ((error: unknown, where: ErrorSite, world: World) => ErrorAnswer)\n\n/**\n * Why a game ended on an error (`world.failure`): plain data, for a log, a save's notes, a player's screen\n *\n * @beta\n */\nexport interface WorldFailure {\n\t/** What is said to whoever played: no more than that it stopped, and in what */\n\tmessage: string\n\twhere: ErrorSite\n\terror: { name: string; message: string; stack?: string }\n\ttick: number\n}\n\n/** Thrown to leave the tick a game ends in (`end`): caught by `World.step`, and never seen outside it */\nexport class GameEnded extends Error {\n\tconstructor(readonly failure: WorldFailure) {\n\t\tsuper(failure.message)\n\t}\n}\n\n/**\n * Why a command was turned away (`commandRejected`): a type the game has not got, fields not as its definition says, a\n * player not in the game, a unit not theirs, one there is not, more than a tick takes, or a director's command sent\n * with no cinematic playing on the sender's screen (`withDirector`)\n *\n * @beta\n */\nexport type RejectedKind = 'unknownType' | 'badFields' | 'noSuchPlayer' | 'notTheirs' | 'noSuchUnit' | 'tooMany' | 'notDirecting'\n\n/** What a part switched off is kept as (`world.disabled`, a save): its kind, id, hook and mod, nothing of the moment it threw */\nexport const siteOf = (where: ErrorSite): ErrorSite => ({\n\tkind: where.kind,\n\tid: where.id,\n\t...(where.hook !== undefined && { hook: where.hook }),\n\t...(where.mod !== undefined && { mod: where.mod })\n})\n\n/**\n * The name a part goes by among those switched off (`world.disabled`)\n *\n * @internal\n */\nexport const siteKey = (where: ErrorSite): string => (where.kind === 'hook' ? `hook:${where.hook}:${where.id}` : `${where.kind}:${where.id}`)\n\n/**\n * A part in words: `the handler \"thorns\" of the hook \"damage\"`\n *\n * @beta\n */\nexport function siteWords(where: ErrorSite): string {\n\tswitch (where.kind) {\n\t\tcase 'hook':\n\t\t\treturn `the handler \"${where.id}\" of the hook \"${where.hook}\"`\n\t\tcase 'listener':\n\t\t\treturn `the listener \"${where.id}\"`\n\t\tcase 'system':\n\t\t\treturn `the system \"${where.id}\"`\n\t\tcase 'timer':\n\t\t\treturn `the timer \"${where.id}\"`\n\t\tcase 'order':\n\t\t\treturn `the order \"${where.id}\" of the unit ${where.entity}`\n\t\tcase 'command':\n\t\t\treturn `the command \"${where.id}\" of player ${where.player}`\n\t}\n}\n\n/** Which mod added or last changed each part of a game put together with mods, by the words `composeGame` knows it by */\nconst changedBy = new WeakMap<object, ReadonlyMap<string, string>>()\n\n/** Kept by `composeGame` for the game it makes: who changed what, to say whose a part that throws is */\nexport function notePartOwners(game: object, owners: ReadonlyMap<string, string>): void {\n\tchangedBy.set(game, owners)\n}\n\n/** The parts' owners as noted for a game: none for one without mods */\nexport const partOwners = (game: object): ReadonlyMap<string, string> => changedBy.get(game) ?? new Map()\n\nconst PART_WORDS: Record<ErrorSite['kind'], string> = {\n\thook: 'hook handler',\n\tlistener: 'listener',\n\tsystem: 'system',\n\ttimer: 'timer',\n\torder: 'order',\n\tcommand: 'command'\n}\n\n/** The mod a part is of, when a mod added it or changed it: nothing for a part of the game itself */\nexport const modOfPart = (game: object | null | undefined, where: ErrorSite): string | undefined =>\n\tgame ? changedBy.get(game)?.get(`${PART_WORDS[where.kind]} \"${where.id}\"`) : undefined\n","import type { PlayerId } from './entity'\nimport type { World } from './world'\n\n/** @beta */\nexport interface Upkeep {\n\t/** 0 without upkeep, then counting up with the tiers of the game */\n\ttier: number\n\tname: string\n\t/** Part of the gold a worker brings in that reaches the player */\n\tincome: number\n}\n\n/**\n * What a player's army costs them, by how much supply they use\n *\n * @beta\n */\nexport function upkeepOf(world: World, player: PlayerId): Upkeep {\n\tconst { supplyUsed } = world.player(player)\n\tlet upkeep: Upkeep = { tier: 0, name: 'No upkeep', income: 1 }\n\tworld.registry.upkeep.forEach((tier, index) => {\n\t\tif (supplyUsed > tier.above) upkeep = { tier: index + 1, name: tier.name, income: tier.income }\n\t})\n\treturn upkeep\n}\n","import type { Entity } from './entity'\nimport type { Registry } from './registry'\nimport type { Terrain } from './terrain'\nimport type { World } from './world'\n\n/*\n * Ground that slows (master plan FI5): a tile's `speed` and a layer of cells' `speed` multiply how fast a unit on\n * foot goes over the cell it stands on, read each tick by the engine's `moveSpeed` rule (`GameRules.movement.moveSpeed`, which\n * a game's own replaces, keeping the last word). What flies or sails is not slowed. Nothing is kept: the speed is the\n * map's paint and the game's definitions, the same on every machine\n */\n\n/** The speed of each tile of a world's game, by its index in the paint (0 is no tile): worked out once a registry */\nconst TILE_SPEEDS = new WeakMap<object, Float32Array>()\n\nfunction tileSpeeds(registry: Registry): Float32Array {\n\tlet speeds = TILE_SPEEDS.get(registry)\n\tif (!speeds) {\n\t\tspeeds = new Float32Array(registry.tiles.length + 1).fill(1)\n\t\tregistry.tiles.forEach((tile, index) => {\n\t\t\tspeeds![index + 1] = tile.speed !== undefined && tile.speed >= 0 ? tile.speed : 1\n\t\t})\n\t\tTILE_SPEEDS.set(registry, speeds)\n\t}\n\treturn speeds\n}\n\n/**\n * How fast one on foot goes over a cell of the map, as a multiplier: the tile's `speed` times the `speed` of every\n * layer of cells that is not 0 there; 1 where nothing says. Off the map, 1\n *\n * @beta\n */\nexport function groundSpeedOfCell(world: World, x: number, z: number): number {\n\treturn groundSpeedOn(world.registry, world.terrain, x, z)\n}\n\n/** `groundSpeedOfCell` of a game's ground before there is a world of it: what its navigation is cut with */\nexport function groundSpeedOn(registry: Registry, terrain: Terrain, x: number, z: number): number {\n\tconst column = Math.floor(x)\n\tconst row = Math.floor(z)\n\tif (column < 0 || row < 0 || column >= terrain.width || row >= terrain.depth) return 1\n\tconst cell = row * terrain.width + column\n\tlet speed = tileSpeeds(registry)[terrain.tiles[cell]] ?? 1\n\tfor (const layer of registry.cellLayers) {\n\t\tif (layer.speed === undefined || layer.speed < 0) continue\n\t\tconst cells = terrain.cells[layer.id]\n\t\tif (cells && cells[cell]) speed *= layer.speed\n\t}\n\treturn speed\n}\n\n/**\n * How fast a unit goes where it stands, as a multiplier of its speed: the ground's for one on foot\n * (`groundSpeedOfCell`), 1 for what flies or sails\n *\n * @beta\n */\nexport function groundSpeedAt(world: World, entity: Entity): number {\n\tif (entity.flying || entity.def.naval) return 1\n\treturn groundSpeedOfCell(world, entity.pos.x, entity.pos.z)\n}\n\n/** Whether any of a game's ground slows or speeds one on foot: a tile, or a layer of cells, with a speed of its own */\nexport function hasGroundSpeeds(registry: Registry): boolean {\n\treturn (\n\t\tregistry.tiles.some((tile) => tile.speed !== undefined && tile.speed >= 0 && tile.speed !== 1) ||\n\t\tregistry.cellLayers.some((layer) => layer.speed !== undefined && layer.speed >= 0 && layer.speed !== 1)\n\t)\n}\n","import type { DamageType, Stats, UnitTypeDef } from './defs'\nimport type { Registry } from './registry'\nimport { orderSays } from './orders/facts'\nimport { clamp } from './math'\nimport { mitigation } from './stats'\nimport { shootsUphill, UPHILL_MISS } from './systems/combat'\nimport { defaultPickAttack, farthestAcquisition } from './attacks'\nimport type { Entity, PlayerId } from './entity'\nimport { type Upkeep, upkeepOf } from './upkeep'\nimport { defaultEngageLayer, defaultEngageRoom } from './engagement'\nimport type { World } from './world'\nimport type { OrderInit } from './registry'\nimport type { GameModule } from './game'\nimport { groundSpeedAt } from './groundSpeed'\nimport type { ScoreRules } from './score'\nimport { defaultHeroRules, type HeroRules } from './hero'\nimport { moving } from './entity'\n\n/**\n * A rule of `HudSharing`: one value for every unit, or a function deciding it for each (only heroes', only a boss's)\n *\n * @beta\n */\nexport type HudShareRule<T> = T | ((world: World, entity: Entity) => T)\n\n/**\n * What of a unit the players who see it are told beyond what they always are (`GameRules.hud`), each for the plates\n * over it to show. What is not shared never reaches a player, so no screen can show it. A game's own data goes in a\n * component with `replicate` (the client's `hudData` reads it)\n *\n * @beta\n */\nexport interface HudSharing {\n\t/**\n\t * The seconds left of its buffs (`EntityState.buffTimes`): to everyone who sees it (`true`), to its owner and their\n\t * allies (`'allies'`), or to no one (`false`, when left out)\n\t */\n\tshareBuffTimes?: HudShareRule<boolean | 'allies'>\n\t/**\n\t * Its abilities (`EntityState.abilities`) to everyone who sees it, its side's or not: those it has learned and\n\t * their levels (`'icons'`), with how much of their cooldowns is left too (`'cooldowns'`), or none (`'none'`, when\n\t * left out: its side has them in `own` all the same)\n\t */\n\tshareAbilities?: HudShareRule<'none' | 'icons' | 'cooldowns'>\n\t/** A hero's experience (`HeroSent.xp`) to everyone who sees it. Its side's alone when left out */\n\tshareXp?: HudShareRule<boolean>\n}\n\n/**\n * A unit in a queue, not made yet, as the supply it will take is asked of it (`GameRules.supply.of`)\n *\n * @beta\n */\nexport interface QueuedUnit {\n\treadonly def: UnitTypeDef\n\treadonly owner: PlayerId\n\treadonly queued: true\n}\n\n/**\n * How the fog of war keeps what was seen (`GameRules.fog`)\n *\n * @beta\n */\nexport interface FogRules {\n\t/** Part of its sight a unit has at night, for types that do not say (`UnitTypeDef.sightNight`) */\n\tnightSight: number\n\t/**\n\t * What is kept of what was seen once: `remembered`, ground drawn dim and buildings as they were last seen (when left\n\t * out); `nothing`, out of sight is as never seen (ground black again, buildings forgotten; building there is still\n\t * allowed)\n\t */\n\texplored?: 'remembered' | 'nothing'\n\t/**\n\t * The whole map explored from the start, the fog over it all the same (as classic RTS melee maps are): the ground drawn\n\t * dim, and what stands on it and belongs to no player (trees, mines, rocks, neutral buildings: shops, taverns, the\n\t * creeps' own) seen from the first moment, as it stood then; units, and players' buildings, only once in sight. A map\n\t * says otherwise (`MapDef.explored`). No when left out\n\t */\n\tstartExplored?: boolean\n\t/** How ground never seen is drawn: `black` (when left out), or `dim` as explored ground is */\n\tmask?: 'black' | 'dim'\n}\n\n/**\n * The numbers and formulas of a kind of game that are not about any one unit: the supply cap, what selling gives\n * back, how a hit is mitigated. In groups, each about one thing: supply, production, the economy, combat, movement,\n * the fog, talk, the camps, heroes, what the HUD is told, the score. A game module changes the ones it wants\n * (`GameModule.rules`: any of a group, the rest of it the engine's) and a pack the ones it brings (`GamePack.rules`).\n *\n * Read them from `world.rules` in the simulation, and from `session.registry.rules` on a player's screen.\n *\n * @beta\n */\nexport interface GameRules {\n\t/** What armies cost in supply, and how much a player may have (`SupplyRules`) */\n\tsupply: SupplyRules\n\t/** What buildings make and how they go up (`ProductionRules`) */\n\tproduction: ProductionRules\n\t/** What is paid back, paid for and given away (`EconomyRules`) */\n\teconomy: EconomyRules\n\t/** How a hit lands and how much of it is felt, and who fights whom (`CombatRules`) */\n\tcombat: CombatRules\n\t/** How units find their way among each other (`MovementRules`) */\n\tmovement: MovementRules\n\t/** What is seen and kept of what was (`FogRules`) */\n\tfog: FogRules\n\t/** Pings, chat and pauses (`TalkRules`) */\n\ttalk: TalkRules\n\t/**\n\t * Creeps' camps (`camps.ts`): how far creeps chase away from their camp (`leash`), whether they sleep at home at night\n\t * until attacked (`sleep`), and the seconds after a camp is cleared that it comes back, for every camp (`respawn`, see\n\t * `Camp.respawn`; never when left out). What makes creeps keep to them, sleep and come back is the heroes pack's\n\t * (`withHeroes`)\n\t */\n\tcamps: CampRules\n\t/**\n\t * Heroes' numbers (`HeroRules`): how many a player may have, the experience a level takes, what bringing one back\n\t * costs. The heroes pack's to change (`withHeroes(rules)`); the classic RTS numbers when left out\n\t */\n\theroes: HeroRules\n\t/**\n\t * What of a unit the players who see it are told beyond what they always are (its health, mana, level, buffs and\n\t * their stacks), for the plates over it to show (indicators-plan U3): the seconds left of its buffs, its abilities,\n\t * a hero's experience. Nothing more than that when left out\n\t *\n\t * @beta\n\t */\n\thud: HudSharing\n\t/**\n\t * What the game counts of its players for its score (a classic RTS score screen): kills, losses, damage, healing,\n\t * resources, its own (`ScoreRules`, `presetScore()`, `defineStat`). Counted by the rules as the game goes, kept in\n\t * saves, told to the players as it says. Nothing is counted when left out\n\t *\n\t * @beta\n\t */\n\tscore?: ScoreRules\n\t/**\n\t * Whether a player may command an entity: its owner, and whoever the owner shares control with\n\t * (`world.sides.shareControl`, a force's `sharedControl`), when left out. What every command is checked against, and\n\t * what decides whose units a player is told the own state of (orders, the queue, the bag)\n\t */\n\tmayCommand(world: World, player: PlayerId, entity: Entity): boolean\n}\n\n/**\n * Supply (`GameRules.supply`)\n *\n * @beta\n */\nexport interface SupplyRules {\n\t/** Supply no player can go past, however much they build to provide it */\n\tmax: number\n\t/**\n\t * Pools of supply besides the one there always is (`supply`, food), by name, each with what it is called and its\n\t * most: a cap on commanders, on vehicles. A unit takes of one with `supplies`, a building provides with\n\t * `suppliesProvided`. None when left out\n\t */\n\tpools?: Record<string, { name: string; max: number }>\n\t/**\n\t * Supply a unit takes: summons taking none, an aura that lowers it. Its type's `supply`, when left out. Asked of the\n\t * units there are, and of those in a queue, which are not yet (`QueuedUnit`: their type and owner)\n\t */\n\tof(world: World, unit: Entity | QueuedUnit): number\n}\n\n/**\n * Production and construction (`GameRules.production`)\n *\n * @beta\n */\nexport interface ProductionRules {\n\t/** Things a building can have waiting to be made */\n\tqueue: number\n\t/** Part of what a structure cost that comes back when it is called off while being built */\n\tcancelRefund: number\n\t/** Part of its health a structure starts being built with */\n\tconstructionHealth: number\n\t/** How fast a structure goes up with so many builders at it, as a part of its build time a second: the first builder all of it, every other half, when left out */\n\tbuildRate(world: World, structure: Entity, builders: number): number\n}\n\n/**\n * Selling, repairing, giving and upkeep (`GameRules.economy`)\n *\n * @beta\n */\nexport interface EconomyRules {\n\t/** Part of an item's price a shop pays for it */\n\tsellPrice: number\n\t/** Part of what a building cost that mending all of its health costs */\n\trepairCost: number\n\t/** The part of what a player gives an ally that is lost on the way, 0..1 (see `give`). Nothing when left out */\n\ttradeTax: number\n\t/** What a player's army costs them in income. The game's upkeep tiers by supply used, when left out */\n\tupkeep(world: World, player: PlayerId): Upkeep\n}\n\n/**\n * Fighting (`GameRules.combat`)\n *\n * @beta\n */\nexport interface CombatRules {\n\t/**\n\t * Whether a basic attack of `attacker` strikes critically, and what it multiplies the damage by then: a number for a\n\t * critical strike, nothing for none. Asked as the attack goes off, before whether it misses. None when left out (a\n\t * game's crits: `withMobaStats`, or its own)\n\t */\n\tcritical(world: World, attacker: Entity, stats: Readonly<Stats>): number | undefined\n\t/**\n\t * What is left of damage once the defences of the target had their say, as a part of it. `source` is the stats\n\t * of whoever deals it, when someone does. Armor and magic resist, with penetration, when left out\n\t */\n\tmitigation(type: DamageType, target: Readonly<Stats>, source?: Readonly<Stats>): number\n\t/**\n\t * Keeps stats within what the game allows, once everything that changes them was added up. Changes them in place.\n\t * The default keeps attack speed within its limits (below)\n\t */\n\tclampStats(stats: Stats, rules: Readonly<GameRules>): void\n\t/** Seconds an ability takes to be ready again, for a unit with these stats. Its cooldown as it is, when left out */\n\tcooldown(seconds: number, stats: Readonly<Stats>): number\n\t/**\n\t * How much of a slow a unit with these stats takes: `slow` is what slows it, added up, below 0 (-0.3 for 30% slower).\n\t * All of it, when left out\n\t */\n\tslowTaken(stats: Readonly<Stats>, slow: number): number\n\t/** What the heals and shields `source` gives are multiplied by. 1, when left out */\n\thealPower(world: World, source: Entity): number\n\t/** Nobody attacks slower or faster than this, whatever they carry: [lowest, highest] attack speed */\n\tattackSpeedLimits: [number, number]\n\t/** Seconds a corpse lies where a unit of flesh died, for spells to use (see `raiseDead`). None at all for 0 */\n\tcorpseTime: number\n\t/** The chance, 0..1, that an attack of `attacker` at `target` goes wide. A quarter up a cliff, when left out */\n\tmissChance(world: World, attacker: Entity, target: Entity): number\n\t/**\n\t * What part of an attack that hits an area an entity standing there gets, 0..1: 0 spares it. `source` is who fired\n\t * it, `distance` how far from the middle the entity is. Everyone there but whoever fired it, all of it in the inner\n\t * half and half outside, when left out\n\t */\n\tsplash(world: World, source: Entity | undefined, other: Entity, distance: number, radius: number): number\n\t/** How far a unit looks for enemies by itself, and chases them. The farthest `acquisitionRange` of its attacks, when left out */\n\tacquisitionRange(world: World, entity: Entity): number\n\t/**\n\t * Which of its attacks (`UnitTypeDef.attacks`, by place) an attacker uses against a target, or -1 for none: it cannot\n\t * attack it. The first whose `targets` reach the target where it is, when left out (`defaultPickAttack`): a siege\n\t * weapon for what is on the ground, a second for the air. Asked for every target looked at: keep it cheap\n\t */\n\tpickAttack(world: World, attacker: Entity, target: Entity): number\n\t/**\n\t * What a hit is multiplied by for the attack's type against the target's armour type, as classic RTS games have it\n\t * (pierce against light, siege against fortified), before armour and shields: none when left out. Attacks name\n\t * their type (`AttackDef.attackType`), abilities as they deal damage (`DamageOptions.attackType`), unit types their\n\t * armour (`UnitTypeDef.armourType`); a type the table has not got is refused as the game is made\n\t */\n\tdamageTable?: DamageTable\n\t/**\n\t * The layer an attacker fights from, around a target: room is counted apart for each (see `engageRoom`). The air\n\t * for what flies, the water for boats, the ground for the rest, when left out; any name of the game's own besides\n\t */\n\tengageLayer(world: World, attacker: Entity): string\n\t/**\n\t * How many attackers like this one (of its layer, reaching as far) may fight a target at once. A full target is\n\t * picked last, and the melee spread around it on as many spots. As many as stand side by side around it, out where\n\t * they reach, when left out: few for swords around a footman, all of them for long guns\n\t */\n\tengageRoom(world: World, target: Entity, attacker: Entity): number\n\t/**\n\t * Seconds a unit that picked a target by itself closes in on it without getting closer before it lets it go and\n\t * fights something else (blocked by its own in a pass, say). A target it was told to attack it never lets go. One,\n\t * when left out; Infinity never\n\t */\n\tgiveUpChase(world: World, attacker: Entity, target: Entity): number\n}\n\n/**\n * How units move among each other (`GameRules.movement`)\n *\n * @beta\n */\nexport interface MovementRules {\n\t/**\n\t * Whether an ally standing in the way of a unit on its way steps aside when asked (see `makeWay`). Those standing\n\t * about with nothing to do, or waiting by a fight for a spot in it, when left out: not those fighting, walking or\n\t * with orders of their own\n\t */\n\tmakesWay(world: World, mover: Entity, other: Entity): boolean\n\t/**\n\t * How far ahead, in ground units, a unit on its way looks for others standing in it, to go round them\n\t * (`goesAround`) or, where it cannot, ask them to step aside (`makesWay`) before it reaches them. 0 looks no\n\t * further than its nose: it then goes round nothing, and asks only once it is held up. 3 when left out\n\t */\n\tlookAhead(world: World, mover: Entity): number\n\t/**\n\t * Whether a unit goes round the units standing in its way (`around`), where the way round is `longer` ground units\n\t * more than the `straight` way to the next corner of its path, rather than through them, which slows it until they\n\t * step aside or it has pushed past. Yes for up to a unit and a half more, and a quarter of the straight way, when\n\t * left out. Where the way round is found is the `detour` hook's\n\t */\n\tgoesAround(world: World, mover: Entity, around: readonly Entity[], longer: number, straight: number): boolean\n\t/**\n\t * Whether a group sent somewhere with a right-click moves at the pace of its slowest (`OrderParams.together`), so\n\t * that it arrives together: no when left out, each at its own speed. Attack-moves are each at their own always\n\t */\n\ttogether?: boolean\n\t/**\n\t * The formation units ordered to a point together take, by id (`FormationDef`), where the order names none\n\t * (`OrderInit.formation`): `rows` when left out, which keeps a tight group's shape and lines a scattered one up\n\t */\n\tformation(world: World, units: readonly Entity[], init: OrderInit): string\n\t/**\n\t * How fast a unit goes where it is, from its `moveSpeed`: slower in shallow water, faster on roads. Asked every\n\t * tick for every unit that moves: keep it cheap. Its speed as it is, when left out\n\t */\n\tmoveSpeed(world: World, entity: Entity, speed: number): number\n}\n\n/**\n * Pings, chat and pauses (`GameRules.talk`)\n *\n * @beta\n */\nexport interface TalkRules {\n\t/**\n\t * Pings (see `ping`): how many a player may send `within` so many seconds, the kinds there are (a hero arena game's\n\t * when left out; a game adds its own), and what each kind asks of a computer ally (indicators-plan P4): a request on\n\t * its team's board (`help`, which computers answer by sending fighters; `attack`, `defend` and `rally`, put on the\n\t * board for the brains that read them), or nothing. A kind not named is heard and not acted on. `kinds` may be\n\t * worked out from the registry as the game plays (`(registry) => …`): from a file of the game's (`registry.file`),\n\t * one the editor writes, so a kind added there is let go at once (see `pingKinds`)\n\t */\n\tpings: {\n\t\tmost: number\n\t\twithin: number\n\t\tkinds: readonly string[] | ((registry: Registry) => readonly string[])\n\t\tmeanings: Readonly<Record<string, 'help' | 'attack' | 'defend' | 'rally' | 'ignore'>>\n\t}\n\t/** Lines of chat: how many a player may send `within` so many seconds, and how long one may be */\n\tlines: { most: number; within: number; length: number }\n\t/** Pauses in a game on a server (see `askPause`): how many each player may ask for (none at 0), and how many seconds one lasts at most */\n\tpauses: { each: number; seconds: number }\n}\n\n/**\n * A damage table: what a hit of each attack type is multiplied by against each armour type (`GameRules.combat.damageTable`).\n * `table[attack][armour]`, the rows the attacks in their order, the columns the armours in theirs\n *\n * @beta\n */\nexport interface DamageTable {\n\tattacks: readonly string[]\n\tarmours: readonly string[]\n\ttable: readonly (readonly number[])[]\n}\n\n/**\n * What a hit is multiplied by, by a damage table: 1 for no table, no attack type, no armour type, or one the table\n * has not got\n *\n * @beta\n */\nexport function damageMultiplier(table: DamageTable | undefined, attackType: string | undefined, armourType: string | undefined): number {\n\tif (!table || attackType === undefined || armourType === undefined) return 1\n\tconst row = table.attacks.indexOf(attackType)\n\tconst column = table.armours.indexOf(armourType)\n\tif (row < 0 || column < 0) return 1\n\treturn table.table[row]?.[column] ?? 1\n}\n\n/**\n * Refuses a damage table that is not one, and a unit type whose attack or armour names a type the table has not got:\n * as the game is made, so that a misspelling fails then and not in a fight. A game without a table is checked for\n * nothing\n *\n * @beta\n */\nexport function checkDamageTable(game: GameModule): void {\n\tconst table = game.rules?.combat?.damageTable as DamageTable | undefined\n\tif (!table) return\n\tconst say = (why: string) => {\n\t\tthrow new Error(`${game.id}: the damage table ${why}`)\n\t}\n\tif (!Array.isArray(table.attacks) || !Array.isArray(table.armours) || !Array.isArray(table.table)) say('needs attacks, armours and a table')\n\tif (table.table.length !== table.attacks.length) say(`has ${table.table.length} rows for ${table.attacks.length} attack types`)\n\tfor (const [row, numbers] of table.table.entries()) {\n\t\tif (!Array.isArray(numbers) || numbers.length !== table.armours.length)\n\t\t\tsay(\n\t\t\t\t`has ${Array.isArray(numbers) ? numbers.length : 'no'} numbers in the row of ${table.attacks[row]} for ${table.armours.length} armour types`\n\t\t\t)\n\t\tfor (const number of numbers)\n\t\t\tif (!Number.isFinite(number) || number < 0)\n\t\t\t\tsay(`has ${String(number)} in the row of ${table.attacks[row]}: a multiplier is a number, 0 or more`)\n\t}\n\tfor (const unit of game.units ?? []) {\n\t\tfor (const { attackType: attack } of unit.attacks ?? [])\n\t\t\tif (attack !== undefined && !table.attacks.includes(attack))\n\t\t\t\tsay(`has no attack type \"${attack}\", which ${unit.id}'s attack names: it has ${table.attacks.join(', ')}`)\n\t\tif (unit.armourType !== undefined && !table.armours.includes(unit.armourType))\n\t\t\tsay(`has no armour type \"${unit.armourType}\", which ${unit.id} names: it has ${table.armours.join(', ')}`)\n\t}\n}\n\n/**\n * The engine's rules: those of a classic RTS melee game\n *\n * @beta\n */\nexport const defaultRules: Readonly<GameRules> = Object.freeze({\n\tsupply: {\n\t\tmax: 100,\n\t\t// none besides food: a game names its own\n\t\tpools: undefined,\n\t\tof: (_world: World, unit: Entity | QueuedUnit) => unit.def.supply ?? 0\n\t},\n\tproduction: {\n\t\tqueue: 7,\n\t\tcancelRefund: 0.75,\n\t\tconstructionHealth: 0.1,\n\t\tbuildRate: (_world: World, _structure: Entity, builders: number) => 1 + (builders - 1) * 0.5\n\t},\n\teconomy: {\n\t\tsellPrice: 0.7,\n\t\trepairCost: 0.35,\n\t\ttradeTax: 0,\n\t\tupkeep: (world: World, player: PlayerId) => upkeepOf(world, player)\n\t},\n\tcombat: {\n\t\tcritical: () => undefined,\n\t\tmitigation,\n\t\tclampStats(stats: Stats, rules: Readonly<GameRules>) {\n\t\t\tconst { attackSpeedLimits } = rules.combat\n\t\t\tif (stats.attackSpeed > 0) stats.attackSpeed = clamp(stats.attackSpeed, attackSpeedLimits[0], attackSpeedLimits[1])\n\t\t},\n\t\tcooldown: (seconds: number) => seconds,\n\t\tslowTaken: (_stats: Readonly<Stats>, slow: number) => slow,\n\t\thealPower: () => 1,\n\t\tattackSpeedLimits: [0.1, 5] as [number, number],\n\t\tcorpseTime: 60,\n\t\tmissChance: (world: World, attacker: Entity, target: Entity) => (shootsUphill(world, attacker, target) ? UPHILL_MISS : 0),\n\t\tsplash: (_world: World, source: Entity | undefined, other: Entity, distance: number, radius: number) =>\n\t\t\tother === source ? 0 : distance <= radius / 2 ? 1 : 0.5,\n\t\tacquisitionRange: (_world: World, entity: Entity) => farthestAcquisition(entity.def),\n\t\tpickAttack: defaultPickAttack,\n\t\t// no table: a hit is what it is, before armour\n\t\tdamageTable: undefined,\n\t\tengageLayer: defaultEngageLayer,\n\t\tengageRoom: defaultEngageRoom,\n\t\tgiveUpChase: () => 1\n\t},\n\tmovement: {\n\t\tmakesWay: (world: World, _mover: Entity, other: Entity) =>\n\t\t\tother.get(moving)?.status !== 'moving' && !other.get(moving)?.anchored && (other.orders.length === 0 || orderSays(world, other, 'waiting')),\n\t\tlookAhead: () => 3,\n\t\tgoesAround: (_world: World, _mover: Entity, _around: readonly Entity[], longer: number, straight: number) => longer <= 1.5 + straight * 0.25,\n\t\tformation: () => 'rows',\n\t\t// slowed by the ground it stands on (a tile's or a layer of cells' `speed`), unless it flies or sails\n\t\tmoveSpeed: (world: World, entity: Entity, speed: number) => speed * groundSpeedAt(world, entity),\n\t\ttogether: false\n\t},\n\tfog: { nightSight: 0.6, explored: undefined, startExplored: undefined, mask: undefined },\n\ttalk: {\n\t\tpings: {\n\t\t\tmost: 4,\n\t\t\twithin: 5,\n\t\t\tkinds: ['look', 'danger', 'assist', 'onMyWay'],\n\t\t\tmeanings: { danger: 'help', assist: 'help', push: 'attack', hold: 'defend', retreat: 'rally' } as TalkRules['pings']['meanings']\n\t\t},\n\t\tlines: { most: 5, within: 5, length: 160 },\n\t\tpauses: { each: 3, seconds: 60 }\n\t},\n\t// the classic RTS numbers: creeps chase 11 cells, sleep at night, and a camp cleared stays cleared\n\tcamps: { leash: 11, sleep: true, respawn: undefined },\n\theroes: defaultHeroRules,\n\t// what everyone who sees a unit is told and no more\n\thud: {},\n\tscore: undefined,\n\tmayCommand: (world: World, player: PlayerId, entity: Entity) => entity.owner === player || world.sides.controlOf(entity.owner).includes(player)\n})\n\n/**\n * Creeps' camps' rules (`GameRules.camps`)\n *\n * @beta\n */\nexport interface CampRules {\n\t/** How far creeps chase away from their camp */\n\tleash: number\n\t/** Whether creeps sleep at home at night, until attacked */\n\tsleep: boolean\n\t/** Seconds after a camp is cleared that it comes back, for every camp (see `Camp.respawn`). Never when left out */\n\trespawn?: number\n}\n\n/** What is said of a group of the rules: any of it, a group in it in part as well. A function, a list and a table whole */\nexport type RulesPart<T> = T extends (...args: never[]) => unknown\n\t? T\n\t: T extends readonly unknown[]\n\t\t? T\n\t\t: T extends object\n\t\t\t? { [K in keyof T]?: RulesPart<T[K]> }\n\t\t\t: T\n\n/**\n * What a game says of its rules (`GameModule.rules`), or a pack (`GamePack.rules`): any of them, a group in part\n * (`{ supply: { max: 200 } }`), the engine's for the rest. The damage table, the score and the HUD's sharing are\n * given whole\n *\n * @beta\n */\nexport type RulesInit = { [K in Exclude<keyof GameRules, 'score' | 'hud'>]?: RulesPart<GameRules[K]> } & {\n\tscore?: ScoreRules\n\thud?: HudSharing\n}\n\n/** Whether a value is a group of the rules to be laid over in part: a plain object of named parts, not a table or a list */\nconst isGroup = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype\n\n/**\n * Lays what is said of rules over rules, group by group: a group of named parts (`supply`, `talk.pings`) part by part,\n * everything else whole. A name the rules have not got is refused: a typo would otherwise change nothing, without a word\n *\n * @internal\n */\nexport function layRules<T extends object>(under: T, over: object, path = ''): T {\n\tconst laid: Record<string, unknown> = { ...(under as Record<string, unknown>) }\n\tfor (const [key, value] of Object.entries(over)) {\n\t\tif (value === undefined) continue\n\t\tif (!(key in under)) throw new Error(`\"${path}${key}\" is not a game rule`)\n\t\tconst before = (under as Record<string, unknown>)[key]\n\t\tlaid[key] = isGroup(before) && Object.keys(before).length && isGroup(value) ? layRules(before, value, `${path}${key}.`) : value\n\t}\n\treturn laid as T\n}\n\n/**\n * What is said of rules laid over what was said before (a pack's over the game's, a mod's over the game's), group by\n * group as `layRules` does, neither of them whole\n *\n * @internal\n */\nexport function overRules(under: RulesInit, over: RulesInit): RulesInit {\n\tconst laid: Record<string, unknown> = { ...under }\n\tfor (const [key, value] of Object.entries(over)) {\n\t\tif (value === undefined) continue\n\t\tconst before = laid[key]\n\t\tlaid[key] = isGroup(before) && isGroup(value) ? overRules(before as RulesInit, value as RulesInit) : value\n\t}\n\treturn laid as RulesInit\n}\n\n/**\n * The names of the rules what is said of them changes, group by group (`supply.max`, `talk.pings.most`): what two\n * mods are found to both change by\n *\n * @internal\n */\nexport function rulesSaid(said: object, path = ''): string[] {\n\treturn Object.entries(said).flatMap(([key, value]) =>\n\t\tvalue === undefined ? [] : isGroup(value) && Object.keys(value).length ? rulesSaid(value, `${path}${key}.`) : [`${path}${key}`]\n\t)\n}\n\n/**\n * The rules of a game: what its module changes, over the engine's\n *\n * @internal\n */\nexport function resolveRules(changes: RulesInit = {}): Readonly<GameRules> {\n\treturn Object.freeze(layRules(defaultRules, changes))\n}\n","import type { RaceDef } from './races'\nimport { notePartOwners, partOwners } from './errors'\nimport type { Component } from './components'\nimport type { EventKey } from './events'\nimport type { EffectKind } from './abilities/effects'\nimport type { CommandDef } from './commands'\nimport type { AbilityDef, BuffDef, ItemDef, ResourceDef, StatDef, UnitTypeDef, UpgradeDef } from './defs'\nimport type { GameModule } from './game'\nimport type { AreaDef } from './areas'\nimport type { ListenerDef } from './events'\nimport type { SequenceDef } from './sequences'\nimport type { TimerDef } from './timers'\nimport type { HookDef } from './hooks'\nimport type { OrderBehavior, SystemDef } from './registry'\nimport { overRules, type RulesInit, rulesSaid } from './rules'\nimport type { GamePack } from './packs/pack'\n\n/**\n * A mod: changes to a game, made on top of it instead of on a copy of it. A new hero, other numbers, a rule of its\n * own. `composeGame` applies mods to a game in the order they need each other, and tells about two mods that change\n * the same thing without one knowing of the other, before anyone plays.\n *\n * @beta\n */\nexport interface ModDef {\n\tid: string\n\t/** `major.minor.patch`. Mods that need this one say which versions they work with */\n\tversion: string\n\tname?: string\n\t/**\n\t * The game and the mods it is made for, each `id`, `id@1.2.3` (that version only) or `id@^1.2` (that major version,\n\t * from 1.2 on). The game counts as one of them, by its id and `GameModule.version`\n\t */\n\trequires?: string[]\n\t/** Makes the changes, through the builder */\n\tapply(game: GameBuilder): void\n}\n\n/**\n * Typed help for writing a mod\n *\n * @beta\n */\nexport const defineMod = (def: ModDef): ModDef => def\n\n/**\n * Definitions of one kind, by id: what a mod adds, changes or takes out\n *\n * @beta\n */\nexport interface Collection<T> {\n\tget(id: string): T | undefined\n\thas(id: string): boolean\n\t/** Throws when there is one of that id already: that is `override` */\n\tadd(def: T): void\n\t/** Changes one that is there: a new definition, or the fields that are different. Throws when there is none */\n\toverride(id: string, change: Partial<T> | ((def: T) => T)): void\n\t/** Throws when there is none of that id */\n\tremove(id: string): void\n\tall(): readonly T[]\n}\n\n/**\n * The game a mod is applied to, as it stands after the mods before it\n *\n * @beta\n */\nexport interface GameBuilder {\n\t/** What the game is so far: to read, not to change. Changes go through the rest of the builder */\n\treadonly current: Readonly<GameModule>\n\tunits: Collection<UnitTypeDef>\n\tabilities: Collection<AbilityDef>\n\tbuffs: Collection<BuffDef>\n\titems: Collection<ItemDef>\n\tupgrades: Collection<UpgradeDef>\n\t/** The sides players can play (`GameModule.races`) */\n\traces: Collection<RaceDef>\n\tstats: Collection<StatDef>\n\tresources: Collection<ResourceDef>\n\t/** Kinds of ability effects, by their type (`defineEffect`) */\n\teffects: Collection<EffectKind>\n\torders: Collection<OrderBehavior>\n\tcommands: Collection<CommandDef>\n\t/** The game's hook handlers, by id. `withoutHook` takes out one of the engine's */\n\thooks: Collection<HookDef>\n\t/** How the game reacts to events, by id */\n\tlisteners: Collection<ListenerDef>\n\t/** The state of its own the game keeps, by id: a mod's own components are added here */\n\tcomponents: Collection<Component<any>>\n\t/** The events of its own the game emits, by id */\n\tevents: Collection<EventKey<any>>\n\t/** The parts of the map the rules watch, by id */\n\tareas: Collection<AreaDef>\n\t/** What the game can set to go off later, by id */\n\ttimers: Collection<TimerDef>\n\t/** The game's scripts of steps, by id */\n\tsequences: Collection<SequenceDef>\n\twithoutHook(id: string): void\n\t/** The parts of the rules the game opts into (`GameModule.packs`), by id: `packs.add(withHeroes())` @beta */\n\tpacks: Collection<GamePack>\n\t/** Takes out a command of the engine's or a pack's, by its type (`GameModule.withoutCommands`) @beta */\n\twithoutCommand(type: string): void\n\t/** Takes out an order of the engine's or a pack's, by its type (`GameModule.withoutOrders`) @beta */\n\twithoutOrder(type: string): void\n\t/** Adds a system of the mod's own, or one in place of the engine's of the same name */\n\taddSystem(system: SystemDef): void\n\t/** Takes out a system: one of the engine's, or one the game gave as an object, by name */\n\twithoutSystem(name: string): void\n\t/** Changes rules of the game (`GameRules`): any of them, a group in part (`{ supply: { max: 200 } }`) */\n\trules(changes: RulesInit): void\n\t/** Changes one of the game's settings that are one thing, not a list */\n\tset<K extends Setting>(key: K, value: GameModule[K]): void\n}\n\n/** The parts of a game a mod can only put something else in the place of */\ntype Setting = 'name' | 'currency' | 'upkeep' | 'day' | 'victory' | 'start' | 'report' | 'ai'\n\n/**\n * Throws when a requirement is not met, or two mods change the same thing without one requiring the other\n *\n * @beta\n */\nexport class ModError extends Error {}\n\n/**\n * A game with mods on it: a new `GameModule`, which `createWorld` takes like any other. Its id names the game and\n * the mods (`melee+goldRush`), and `mods` lists them with their versions. Mods are applied after the ones they\n * require, otherwise in the order given. Neither the game nor the mods are changed\n *\n * @beta\n */\nexport function composeGame(base: GameModule, mods: ModDef[]): GameModule {\n\tconst ordered = order(base, mods)\n\tconst draft: GameModule = {\n\t\t...base,\n\t\tunits: [...base.units],\n\t\t// a pack's with the hash of its bytes (`packFromJson`): the game's hash has it, what a save and a lobby check\n\t\tmods: [...(base.mods ?? []), ...ordered.map((mod) => ({ id: mod.id, version: mod.version, ...((mod as { hash?: string }).hash && { hash: (mod as { hash?: string }).hash }) }))]\n\t}\n\tconst touched = new Map<string, string>()\n\tconst conflicts: string[] = []\n\tconst requires = closure(ordered)\n\n\tfor (const mod of ordered) {\n\t\t// who changed what: a second mod changing it, without knowing of the first, is a conflict\n\t\tconst touch = (what: string) => {\n\t\t\tconst before = touched.get(what)\n\t\t\tif (before && before !== mod.id && !requires.get(mod.id)!.has(before) && !requires.get(before)!.has(mod.id)) {\n\t\t\t\tconflicts.push(`${what}: changed by \"${before}\" and by \"${mod.id}\", and neither requires the other`)\n\t\t\t}\n\t\t\ttouched.set(what, mod.id)\n\t\t}\n\t\tmod.apply(builder(draft, touch))\n\t}\n\tif (conflicts.length) throw new ModError(`Mods that do not go together:\\n${conflicts.join('\\n')}`)\n\tdraft.id = [base.id, ...ordered.map((mod) => mod.id)].join('+')\n\t// whose each part is, for saying which mod a part that throws belongs to (`ErrorSite.mod`). Beside the game, not\n\t// in it: what a game is, and its hash, stay what they were\n\tnotePartOwners(draft, new Map([...partOwners(base), ...touched]))\n\t// what it was made of, to make it again of their new versions (hot reload, `recompose`): beside it, as the owners\n\tcompositions.set(draft, { base, mods })\n\treturn draft\n}\n\n/** What each game made by `composeGame` was made of: its base and its mods, as they were given */\nconst compositions = new WeakMap<GameModule, { base: GameModule; mods: readonly ModDef[] }>()\n\n/**\n * What a game made by `composeGame` was made of, its base and its mods; nothing for one that was not\n *\n * @internal\n */\nexport function compositionOf(game: GameModule): { base: GameModule; mods: readonly ModDef[] } | undefined {\n\treturn compositions.get(game)\n}\n\n/**\n * A game made by `composeGame` made again, of its base and its mods as they are now (a base made of mods made again\n * too): what a game played with mods takes as one of them, or its base, is saved while it runs (hot reload). A game not\n * made so is itself. Throws as `composeGame` does: mods that no longer go together\n *\n * @beta\n */\nexport function recompose(game: GameModule): GameModule {\n\tconst made = compositions.get(game)\n\treturn made ? composeGame(recompose(made.base), [...made.mods]) : game\n}\n\n/**\n * Whether a game is made of this game or mod: is it, or has it as its base or one of its mods, at any depth\n *\n * @beta\n */\nexport function isMadeOf(game: GameModule, part: GameModule | ModDef): boolean {\n\tif (game === part) return true\n\tconst made = compositions.get(game)\n\treturn !!made && (made.mods.includes(part as ModDef) || isMadeOf(made.base, part))\n}\n\nfunction builder(draft: GameModule, touch: (what: string) => void): GameBuilder {\n\tconst list = <T, K extends keyof GameModule>(field: K, kind: string, idOf: (def: T) => string): Collection<T> => {\n\t\tconst items = () => ((draft[field] as T[] | undefined) ?? []) as T[]\n\t\tconst write = (next: T[]) => ((draft as unknown as Record<string, unknown>)[field] = next)\n\t\tconst find = (id: string) => items().find((def) => idOf(def) === id)\n\t\tconst must = (id: string) => find(id) ?? fail(`${kind} \"${id}\" is not in the game`)\n\t\treturn {\n\t\t\tget: find,\n\t\t\thas: (id) => !!find(id),\n\t\t\tall: items,\n\t\t\tadd(def) {\n\t\t\t\tconst id = idOf(def)\n\t\t\t\tif (find(id)) fail(`${kind} \"${id}\" is in the game already: override it instead`)\n\t\t\t\ttouch(`${kind} \"${id}\"`)\n\t\t\t\twrite([...items(), def])\n\t\t\t},\n\t\t\toverride(id, change) {\n\t\t\t\tconst old = must(id)\n\t\t\t\ttouch(`${kind} \"${id}\"`)\n\t\t\t\tconst next = typeof change === 'function' ? change(old) : { ...old, ...change }\n\t\t\t\twrite(items().map((def) => (def === old ? next : def)))\n\t\t\t},\n\t\t\tremove(id) {\n\t\t\t\tconst old = must(id)\n\t\t\t\ttouch(`${kind} \"${id}\"`)\n\t\t\t\twrite(items().filter((def) => def !== old))\n\t\t\t}\n\t\t}\n\t}\n\n\tconst effects = list<EffectKind, 'effects'>('effects', 'effect', (def) => def.type)\n\n\treturn {\n\t\tget current() {\n\t\t\treturn draft\n\t\t},\n\t\tunits: list<UnitTypeDef, 'units'>('units', 'unit type', (def) => def.id),\n\t\tabilities: list<AbilityDef, 'abilities'>('abilities', 'ability', (def) => def.id),\n\t\tbuffs: list<BuffDef, 'buffs'>('buffs', 'buff', (def) => def.id),\n\t\titems: list<ItemDef, 'items'>('items', 'item', (def) => def.id),\n\t\tupgrades: list<UpgradeDef, 'upgrades'>('upgrades', 'upgrade', (def) => def.id),\n\t\traces: list<RaceDef, 'races'>('races', 'race', (def) => def.id),\n\t\tstats: list<StatDef, 'stats'>('stats', 'stat', (def) => def.id),\n\t\tresources: list<ResourceDef, 'resources'>('resources', 'resource', (def) => def.id),\n\t\teffects,\n\t\torders: list<OrderBehavior, 'orders'>('orders', 'order', (def) => def.type),\n\t\tcommands: list<CommandDef, 'commands'>('commands', 'command', (def) => def.type),\n\t\thooks: list<HookDef, 'hooks'>('hooks', 'hook handler', (def) => def.id),\n\t\tlisteners: list<ListenerDef, 'listeners'>('listeners', 'listener', (def) => def.id),\n\t\tcomponents: list<Component<any>, 'components'>('components', 'component', (def) => def.id),\n\t\tevents: list<EventKey<any>, 'events'>('events', 'event', (def) => def.id),\n\t\tareas: list<AreaDef, 'areas'>('areas', 'area', (def) => def.id),\n\t\ttimers: list<TimerDef, 'timers'>('timers', 'timer', (def) => def.id),\n\t\tsequences: list<SequenceDef, 'sequences'>('sequences', 'sequence', (def) => def.id),\n\t\twithoutHook(id) {\n\t\t\ttouch(`hook handler \"${id}\"`)\n\t\t\tdraft.withoutHooks = [...(draft.withoutHooks ?? []), id]\n\t\t},\n\t\tpacks: list<GamePack, 'packs'>('packs', 'pack', (def) => def.id),\n\t\twithoutCommand(type) {\n\t\t\ttouch(`command \"${type}\"`)\n\t\t\tdraft.withoutCommands = [...(draft.withoutCommands ?? []), type]\n\t\t},\n\t\twithoutOrder(type) {\n\t\t\ttouch(`order \"${type}\"`)\n\t\t\tdraft.withoutOrders = [...(draft.withoutOrders ?? []), type]\n\t\t},\n\t\taddSystem(system) {\n\t\t\tif (typeof system !== 'function') touch(`system \"${system.name}\"`)\n\t\t\tdraft.systems = [...(draft.systems ?? []), system]\n\t\t},\n\t\twithoutSystem(name) {\n\t\t\ttouch(`system \"${name}\"`)\n\t\t\tconst systems = draft.systems ?? []\n\t\t\tconst own = systems.filter((system) => typeof system !== 'function' && system.name === name)\n\t\t\tif (own.length) draft.systems = systems.filter((system) => !own.includes(system))\n\t\t\telse draft.withoutSystems = [...(draft.withoutSystems ?? []), name]\n\t\t},\n\t\trules(changes) {\n\t\t\tfor (const name of rulesSaid(changes)) touch(`rule \"${name}\"`)\n\t\t\tdraft.rules = overRules(draft.rules ?? {}, changes)\n\t\t},\n\t\tset(key, value) {\n\t\t\ttouch(`setting \"${key}\"`)\n\t\t\tdraft[key] = value\n\t\t}\n\t}\n}\n\n/** The mods in the order they are applied: each after what it requires. Throws for what is missing or out of range */\nfunction order(base: GameModule, mods: ModDef[]): ModDef[] {\n\tconst byId = new Map<string, ModDef>()\n\tfor (const mod of mods) {\n\t\tif (byId.has(mod.id) || mod.id === base.id) fail(`\"${mod.id}\" is there twice`)\n\t\tversion(mod.version, `the version of \"${mod.id}\"`)\n\t\tbyId.set(mod.id, mod)\n\t}\n\tconst versions = new Map<string, string>([[base.id, base.version ?? '1.0.0'], ...mods.map((mod) => [mod.id, mod.version] as [string, string])])\n\tfor (const mod of mods) {\n\t\tfor (const requirement of mod.requires ?? []) {\n\t\t\tconst [id, range] = requirement.split('@')\n\t\t\tconst have = versions.get(id)\n\t\t\tif (have === undefined) fail(`\"${mod.id}\" requires \"${id}\", which is not there`)\n\t\t\tif (range && !satisfies(have, range)) fail(`\"${mod.id}\" requires ${id} ${range}, and it is ${have}`)\n\t\t}\n\t}\n\tconst ordered: ModDef[] = []\n\tconst state = new Map<string, 'visiting' | 'done'>()\n\tconst visit = (mod: ModDef, path: string[]) => {\n\t\tif (state.get(mod.id) === 'done') return\n\t\tif (state.get(mod.id) === 'visiting') fail(`Mods require each other in a circle: ${[...path, mod.id].join(' → ')}`)\n\t\tstate.set(mod.id, 'visiting')\n\t\tfor (const requirement of mod.requires ?? []) {\n\t\t\tconst needed = byId.get(requirement.split('@')[0])\n\t\t\tif (needed) visit(needed, [...path, mod.id])\n\t\t}\n\t\tstate.set(mod.id, 'done')\n\t\tordered.push(mod)\n\t}\n\tfor (const mod of mods) visit(mod, [])\n\treturn ordered\n}\n\n/** For each mod, every mod it requires, directly or through others */\nfunction closure(mods: ModDef[]): Map<string, Set<string>> {\n\tconst all = new Map<string, Set<string>>()\n\t// in order, so whatever a mod requires has its set already\n\tfor (const mod of mods) {\n\t\tconst set = new Set<string>()\n\t\tfor (const requirement of mod.requires ?? []) {\n\t\t\tconst id = requirement.split('@')[0]\n\t\t\tset.add(id)\n\t\t\tfor (const further of all.get(id) ?? []) set.add(further)\n\t\t}\n\t\tall.set(mod.id, set)\n\t}\n\treturn all\n}\n\nfunction version(text: string, what: string): number[] {\n\tconst parts = text.split('.').map(Number)\n\tif (parts.length < 1 || parts.length > 3 || parts.some((part) => !Number.isInteger(part) || part < 0)) fail(`${what} is not a version: \"${text}\"`)\n\twhile (parts.length < 3) parts.push(0)\n\treturn parts\n}\n\n/**\n * Whether a version is in a range: `1.2.3` exactly, or `^1.2` for 1.2 and later of major version 1\n *\n * @beta\n */\nexport function satisfies(have: string, range: string): boolean {\n\tconst caret = range.startsWith('^')\n\tconst want = version(caret ? range.slice(1) : range, `the range \"${range}\"`)\n\tconst is = version(have, `the version \"${have}\"`)\n\tif (!caret) return is.every((part, i) => part === want[i])\n\tif (is[0] !== want[0]) return false\n\tfor (let i = 1; i < 3; i++) if (is[i] !== want[i]) return is[i] > want[i]\n\treturn true\n}\n\nfunction fail(message: string): never {\n\tthrow new ModError(message)\n}\n\n/**\n * What identifies a game exactly: its definitions, the source of its code, and its mods. Two worlds made from games\n * with the same hash play by the same rules: what a lobby, a save and a replay check\n *\n * @internal\n */\nexport function gameHash(game: GameModule, options: { code?: boolean } = {}): string {\n\tconst code = options.code ?? true\n\tconst text = JSON.stringify(game, function (this: unknown, key, value) {\n\t\t// what only a server runs, around the games: not the game itself, and not on a player's side\n\t\tif (key === 'server') return undefined\n\t\t// a component's number is the process's, given in the order its modules defined components (a server's entry\n\t\t// defines more of the engine's before the game's than a player's page does): its id is what the game is (bug 18)\n\t\tif (key === 'slot' && isComponent(this)) return undefined\n\t\t// the maps it ships: what a map is is the map's hash, not the game's (S36)\n\t\tif (key === 'maps' && value === game.maps) return undefined\n\t\t// without the code: that a function is there, not how a build happens to print it\n\t\tif (typeof value === 'function') return code ? `fn:${value.toString()}` : 'fn'\n\t\tif (typeof value === 'number' && !Number.isFinite(value)) return String(value)\n\t\treturn value\n\t})\n\t// FNV-1a, twice over with different starts, for 64 bits: enough to tell versions apart, not a secret\n\tlet a = 0x811c9dc5\n\tlet b = 0x01000193 ^ 0x5bd1e995\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst c = text.charCodeAt(i)\n\t\ta = Math.imul(a ^ c, 0x01000193)\n\t\tb = Math.imul(b ^ c, 0x5bd1e995)\n\t}\n\treturn (a >>> 0).toString(16).padStart(8, '0') + (b >>> 0).toString(16).padStart(8, '0')\n}\n\n/** Whether an object is a component (`defineComponent`): an id, its number, and every field a component has, in its shape */\nconst isComponent = (value: unknown): boolean => {\n\tconst part = value as { id?: unknown; slot?: unknown } | null\n\treturn typeof part?.id === 'string' && typeof part.slot === 'number' && 'replicate' in part && 'snapshot' in part && 'refs' in part\n}\n","import { abilityCast, castStarted, channelEnded, channelStarted } from '#engine/engineEvents'\nimport { replicateEvent } from '../replication'\nimport { aimOf } from '../defs'\n\n/**\n * What players are told of casting (the cast order's events): the wind-up, a channel's start and end, the cast. Beside\n * the abilities, whose order emits them\n */\n\n/** A spell being wound up, to those who see the caster: where it aims, and for how long */\nexport const toldWindup = replicateEvent(castStarted, 'windup', ({ caster, ability, point, duration }, view) => {\n\tif (!duration || !view.knows(caster)) return undefined\n\tconst aim = point ?? caster.pos\n\t// what an item gives is at its first level\n\tconst level = caster.abilities.find((state) => state.id === ability.id)?.level || 1\n\treturn { type: 'windup', id: caster.id, ability: ability.id, level, x: aim.x, z: aim.z, duration }\n})\n\n/** A channel begun, to those who see the caster */\nexport const toldChannelStarted = replicateEvent(channelStarted, 'channel', ({ caster, ability, duration }, view) =>\n\tview.knows(caster) ? { type: 'channel', id: caster.id, ability: ability.id, on: true, duration } : undefined\n)\n\n/** A channel over, to those who see the caster */\nexport const toldChannelEnded = replicateEvent(channelEnded, 'channel', ({ caster, ability, interrupted }, view) =>\n\tview.knows(caster) ? { type: 'channel', id: caster.id, ability: ability.id, on: false, interrupted } : undefined\n)\n\n/** A cast, to those who see the caster or where it lands */\nexport const toldCast = replicateEvent(abilityCast, 'cast', ({ caster, ability, level, target, point, charged }, view) => {\n\tif (!view.knows(caster) && !view.sees(point.x, point.z)) return undefined\n\tconst aim = aimOf(ability, level)\n\tconst radius = aim?.shape === 'circle' ? aim.radius : 0\n\treturn {\n\t\ttype: 'cast',\n\t\tid: view.knows(caster) ? caster.id : undefined,\n\t\tability: ability.id,\n\t\tlevel,\n\t\tx: point.x,\n\t\tz: point.z,\n\t\ttarget: target && view.knows(target) ? target.id : undefined,\n\t\tradius: radius || undefined,\n\t\tcharged\n\t}\n})\n","import { cellsChanged, cellsSeen } from '#engine/engineEvents'\nimport { type AreaShape, inShape, shapeBounds } from './areas'\nimport type { Terrain } from './terrain'\nimport type { World } from './world'\nimport { replicateEvent, type SessionView } from './replication'\nimport { teamMemory } from './session/memory'\n\n/**\n * A layer of cells a game paints its maps with, for its rules to read: where the bushes are, what burns, where a\n * lane runs. A value per cell (0 to 255, 0 being none), kept with the map (`GameMap.cells`), in the world's ground\n * (`Terrain.cells`, read with `terrain.cellAt`), its saves and what each player is sent. The rules change it while\n * the game runs with `world.setCells`: the players who see a cell are told at once, the others as it comes into their\n * sight (`TeamMemory.cells`), so a change in the dark is not given away. The editor paints the layers a game lists\n * (`GameModule.cellLayers`), with the values it names\n *\n * @beta\n */\nexport interface CellLayerDef {\n\t/** Its key in `Terrain.cells` and in the map's file */\n\tid: string\n\t/** What the editor calls it */\n\tname: string\n\t/** What it is for, for the editor's tooltip */\n\tdescription?: string\n\t/** The colour the editor shows it in, 0 to 1 each */\n\tcolor?: [number, number, number]\n\t/**\n\t * The values the editor paints with, named: `[{ value: 1, name: 'Bush' }]`. One value, 1, named after the layer when\n\t * left out: a layer of cells that are or are not\n\t */\n\tvalues?: { value: number; name: string; color?: [number, number, number] }[]\n\t/**\n\t * How fast one on foot goes over a cell of the layer that is not 0, as a multiplier of its speed: a swamp at 0.5. 1\n\t * when left out; a cell of several such layers is slowed by each (`groundSpeedOfCell`)\n\t */\n\tspeed?: number\n}\n\n/**\n * Typed help for writing a layer of cells\n *\n * @beta\n */\nexport const defineCellLayer = (def: CellLayerDef): CellLayerDef => def\n\n/**\n * The values a layer is painted with, as the editor offers them: its own, or 1, named after the layer\n *\n * @beta\n */\nexport const cellLayerValues = (def: CellLayerDef): NonNullable<CellLayerDef['values']> => def.values ?? [{ value: 1, name: def.name }]\n\n/**\n * The cells of a terrain in a shape, as indices into its layers: the cells whose middle is in it\n *\n * @beta\n */\nexport function cellsIn(terrain: Pick<Terrain, 'width' | 'depth'>, shape: AreaShape): number[] {\n\tconst { width, depth } = terrain\n\tconst { x0, z0, x1, z1 } = shapeBounds(shape)\n\tconst cells: number[] = []\n\tfor (let cz = Math.max(Math.floor(z0), 0); cz < Math.min(Math.ceil(z1), depth); cz++) {\n\t\tfor (let cx = Math.max(Math.floor(x0), 0); cx < Math.min(Math.ceil(x1), width); cx++) {\n\t\t\tif (inShape(shape, { x: cx + 0.5, z: cz + 0.5 })) cells.push(cz * width + cx)\n\t\t}\n\t}\n\treturn cells\n}\n\n/** Whether a team sees a cell of the ground: its middle */\nconst seesCell = (world: World, team: number, cell: number): boolean =>\n\tworld.fog.isVisible(team, (cell % world.terrain.width) + 0.5, Math.floor(cell / world.terrain.width) + 0.5)\n\n/**\n * Cells of a layer the rules set (`world.setCells`), each with what it was: what each team that does not see a cell\n * keeps of it as it last knew it (`TeamMemory.cells`), to be told when it comes into sight. A cell set back to what the\n * team knows is nothing to tell; one the team sees is told now\n */\nexport function rememberUnseenCells(world: World, layer: string, cells: readonly number[], was: readonly number[], value: number): void {\n\tconst memories = world.state(teamMemory)\n\tfor (const team of world.fog.teams) {\n\t\tlet known = memories[team]?.cells?.[layer]\n\t\tfor (let i = 0; i < cells.length; i++) {\n\t\t\tconst cell = cells[i]\n\t\t\tif (seesCell(world, team, cell)) {\n\t\t\t\tif (known) delete known[cell]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst knew = known?.[cell] ?? was[i]\n\t\t\tif (knew === value) {\n\t\t\t\tif (known) delete known[cell]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (!known) {\n\t\t\t\tconst memory = (memories[team] ??= { structures: {}, cleared: [] })\n\t\t\t\tknown = (memory.cells ??= {})[layer] ??= {}\n\t\t\t}\n\t\t\tknown[cell] = knew\n\t\t}\n\t}\n}\n\n/**\n * The cells changed out of a team's sight that are in it now (`TeamMemory.cells`), told to the team as they are now\n * (`cellsSeen`) and forgotten: after the fog is worked out again (`fogSystem`)\n */\nexport function tellCellsInSight(world: World): void {\n\tif (!world.states.has(teamMemory)) return\n\tconst memories = world.state(teamMemory)\n\tfor (const [key, memory] of Object.entries(memories)) {\n\t\tif (!memory.cells) continue\n\t\tconst team = Number(key)\n\t\tfor (const [layer, known] of Object.entries(memory.cells)) {\n\t\t\tlet byValue: Map<number, number[]> | undefined\n\t\t\tfor (const at in known) {\n\t\t\t\tconst cell = Number(at)\n\t\t\t\tif (!seesCell(world, team, cell)) continue\n\t\t\t\tdelete known[cell]\n\t\t\t\tconst value = world.terrain.cellAt(layer, (cell % world.terrain.width) + 0.5, Math.floor(cell / world.terrain.width) + 0.5)\n\t\t\t\tbyValue ??= new Map()\n\t\t\t\tlet cells = byValue.get(value)\n\t\t\t\tif (!cells) byValue.set(value, (cells = []))\n\t\t\t\tcells.push(cell)\n\t\t\t}\n\t\t\tfor (const [value, cells] of byValue ?? []) world.events.emit(cellsSeen, { team, layer, cells, value })\n\t\t\tif (byValue && Object.keys(known).length === 0) delete memory.cells[layer]\n\t\t}\n\t\tif (Object.keys(memory.cells).length === 0) delete memory.cells\n\t}\n}\n\n/**\n * The world's ground as a team knows it: its layers' cells as the team last saw those changed out of its sight\n * (`TeamMemory.cells`). The ground itself where the team knows all of it, or for an observer (no team)\n */\nexport function groundKnownTo(world: World, team: number | undefined): Terrain {\n\tconst { terrain } = world\n\tconst known = team === undefined || !world.states.has(teamMemory) ? undefined : world.state(teamMemory)[team]?.cells\n\tif (!known) return terrain\n\tconst cells: Record<string, Uint8Array> = { ...terrain.cells }\n\tfor (const [layer, was] of Object.entries(known)) {\n\t\tconst values = (cells[layer] = new Uint8Array(cells[layer] ?? terrain.width * terrain.depth))\n\t\tfor (const at in was) values[Number(at)] = was[at]\n\t}\n\treturn Object.create(terrain, { cells: { value: cells } }) as Terrain\n}\n\n/** Whether the seat's player is told of cells their team sees changed, rather than as they come into sight: an observer is told of all */\nconst toldNow = (view: SessionView, cell: number): boolean => view.observer || seesCell(view.world, view.team, cell)\n\n/** A layer's cells changed (`world.setCells`): to those who see them. The others are told as they come into sight (`toldCellsSeen`) */\nexport const toldCells = replicateEvent(cellsChanged, 'cells', ({ layer, cells, value }, view) => {\n\tconst at = cells.filter((cell) => toldNow(view, cell))\n\treturn at.length ? { type: 'cells', layer, at, value } : undefined\n})\n\n/** Cells changed out of a team's sight came into it (`tellCellsInSight`): to the team, as they are now. An observer was told already */\nexport const toldCellsSeen = replicateEvent(cellsSeen, 'cells', ({ team, layer, cells, value }, view) =>\n\t!view.observer && view.team === team ? { type: 'cells', layer, at: [...cells], value } : undefined\n)\n","import { cellsChanged, rustled } from '#engine/engineEvents'\nimport type { Entity } from './entity'\nimport { exposure, detection } from './entity'\nimport type { GamePack } from './packs/pack'\nimport { distSq } from './math'\nimport { defineHook } from './hooks'\nimport type { System } from './registry'\nimport type { World } from './world'\nimport { replicateEvent } from './replication'\n\n/**\n * Hiding places painted on a map, as a layer of cells (`CellLayerDef`): tall grass, a forest's edge. Who stands in one\n * is seen by another team only from inside the same patch of it (the cells of the layer that touch, sides or corners),\n * or from close by (`reach`). An attacker in one is seen by whom it hits for a moment, as anyone is (`expose`), and\n * what detects the invisible (`entity.detected`) sees it too. A game turns it on, on as many layers as it likes:\n *\n * export const rules = { ...myGame, packs: [withConcealment({ layer: 'bush' })] }\n *\n * Everything that asks what a team sees (`world.isVisibleTo`) goes by it: what units pick to attack, the commands a\n * player may give, the fog's memory, and each player's snapshots, so the computer player and the players over a wire\n * see what the rules let them. Nothing is saved: it is worked out from the layer and where everyone stands\n *\n * @beta\n */\nexport interface ConcealmentOptions {\n\t/** The layer of cells that hides (`Terrain.cells`): any cell of it with a value other than 0 */\n\tlayer: string\n\t/** How near, in cells, someone of another team has to be to see into it from outside: 2 when left out */\n\treach?: number\n\t/**\n\t * What it hides: units on the ground, of anyone, when left out (not structures, not what flies). A game's own, to hide\n\t * heroes only or let some types never hide\n\t */\n\thides?: (world: World, entity: Entity) => boolean\n\t/**\n\t * Whether a team sees a hidden entity anyway, after what the patch and `reach` make of it: a ward, a scout's ability.\n\t * Asked only of what would otherwise be hidden\n\t */\n\tseenBy?: (world: World, entity: Entity, team: number) => boolean\n\t/**\n\t * Whether one hidden in it gives itself away by moving, as the brush of a hero arena game shakes: the teams that do not see it are\n\t * told where it moves in it and steps into it (a `rustle` event, where they see the ground; not who), and their\n\t * screens shake the bushes there. `true` for every team, a function to say for each (`team`), no when left out:\n\t * a hidden unit shakes nothing on the screens of those who do not see it\n\t */\n\trustle?: boolean | ((world: World, entity: Entity, team: number) => boolean)\n\t/** How often one moving in it is told again, in seconds: 0.3 when left out. Stepping in is told at once */\n\trustleEvery?: number\n\t/** The id of its hook and its system, to replace or leave out: `concealment:<layer>` when left out */\n\tid?: string\n}\n\n/** What a world's patches of a layer are, worked out once and again when the layer changes */\ninterface Patches {\n\t/** The cells of the layer this was worked out from: another array (the map resized, a save loaded) works it out again */\n\tcells: Uint8Array | undefined\n\t/** The patch of each cell, 1 and up; 0 for none */\n\tof: Int32Array\n\tdirty: boolean\n\t/** Whether `occupied` was worked out yet: at the start of every tick, by the system, and never in the middle of one */\n\tcounted: boolean\n\t/** The patches each team has someone on the ground in, by team */\n\toccupied: Map<number, Set<number>>\n\tstop: () => void\n}\n\nconst known = new WeakMap<World, Map<string, Patches>>()\n\n/** The patches of the layer of a world, worked out again when the layer changed since */\nfunction patchesOf(world: World, layer: string): Patches {\n\tlet byLayer = known.get(world)\n\tif (!byLayer) known.set(world, (byLayer = new Map()))\n\tlet patches = byLayer.get(layer)\n\tif (!patches) {\n\t\tconst made: Patches = { cells: undefined, of: new Int32Array(0), dirty: true, counted: false, occupied: new Map(), stop: () => {} }\n\t\tmade.stop = world.events.on(cellsChanged, (change) => {\n\t\t\tif (change.layer === layer) made.dirty = true\n\t\t})\n\t\tbyLayer.set(layer, (patches = made))\n\t}\n\tconst cells = world.terrain.cells[layer]\n\tif (patches.dirty || patches.cells !== cells) {\n\t\tpatches.of = label(cells, world.terrain.width, world.terrain.depth)\n\t\tpatches.cells = cells\n\t\tpatches.dirty = false\n\t}\n\treturn patches\n}\n\n/** The patches of a layer: each cell the number of the patch it is in, the cells of the layer that touch (corners too) */\nfunction label(cells: Uint8Array | undefined, width: number, depth: number): Int32Array {\n\tconst of = new Int32Array(width * depth)\n\tif (!cells) return of\n\tlet next = 0\n\tconst stack: number[] = []\n\tfor (let start = 0; start < cells.length; start++) {\n\t\tif (!cells[start] || of[start]) continue\n\t\tof[start] = ++next\n\t\tstack.push(start)\n\t\twhile (stack.length) {\n\t\t\tconst c = stack.pop()!\n\t\t\tconst x = c % width\n\t\t\tconst z = (c - x) / width\n\t\t\tfor (let dz = -1; dz <= 1; dz++) {\n\t\t\t\tfor (let dx = -1; dx <= 1; dx++) {\n\t\t\t\t\tconst nx = x + dx\n\t\t\t\t\tconst nz = z + dz\n\t\t\t\t\tif (nx < 0 || nz < 0 || nx >= width || nz >= depth) continue\n\t\t\t\t\tconst n = nz * width + nx\n\t\t\t\t\tif (cells[n] && !of[n]) {\n\t\t\t\t\t\tof[n] = next\n\t\t\t\t\t\tstack.push(n)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn of\n}\n\n/** Units on the ground, not structures: what hides when a game does not say */\nconst onTheGround = (_world: World, entity: Entity) => !entity.def.footprint && !entity.flying && entity.def.kind === 'unit'\n\n/**\n * The patch of a layer an entity stands in, 1 and up, or 0 where it stands in none (`ConcealmentOptions`). For a\n * game's rules and screen: who is in the grass\n *\n * @beta\n */\nexport function patchAt(world: World, layer: string, x: number, z: number): number {\n\tconst { terrain } = world\n\tif (x < 0 || z < 0 || x >= terrain.width || z >= terrain.depth) return 0\n\treturn patchesOf(world, layer).of[Math.floor(z) * terrain.width + Math.floor(x)]\n}\n\n/**\n * A game where what stands in a layer of cells is hidden from the teams that are not in it with them (see\n * `ConcealmentOptions`): a `visible` hook, and a system that works out who has someone in which patch at the start of\n * every tick (the same in every copy of the game, whoever asks what in between). On as many layers as it is given\n *\n * @beta\n */\nexport function withConcealment(options: ConcealmentOptions): GamePack {\n\tconst { layer, hides = onTheGround, seenBy } = options\n\tconst reach = options.reach ?? 2\n\tconst id = options.id ?? `concealment:${layer}`\n\tconst { rustle } = options\n\tconst count: System = {\n\t\tname: id,\n\t\tphase: 'commands',\n\t\tupdate(world) {\n\t\t\tif (!world.terrain.cells[layer]) return\n\t\t\tconst patches = patchesOf(world, layer)\n\t\t\tcountOccupied(world, patches, hides)\n\t\t\tif (rustle) tellRustles(world, layer, patches, hides, rustle, options.rustleEvery ?? 0.3)\n\t\t}\n\t}\n\tconst hook = defineHook({\n\t\thook: 'visible',\n\t\tid,\n\t\trun(world, event) {\n\t\t\tif (!event.visible) return\n\t\t\tconst { entity, team } = event\n\t\t\tif (!world.terrain.cells[layer]) return\n\t\t\tconst patches = patchesOf(world, layer)\n\t\t\tconst { width, depth } = world.terrain\n\t\t\tconst { x, z } = entity.pos\n\t\t\tif (x < 0 || z < 0 || x >= width || z >= depth) return\n\t\t\tconst patch = patches.of[Math.floor(z) * width + Math.floor(x)]\n\t\t\tif (!patch || !hides(world, entity)) return\n\t\t\t// seen for a moment by whom it hit, and by what sees the invisible\n\t\t\tif (entity.get(exposure)?.has(team) || entity.get(detection)?.has(team)) return\n\t\t\t// worked out at the start of the tick; once, where nothing ticked yet (a world just made or loaded: as it would be)\n\t\t\tif (!patches.counted) countOccupied(world, patches, hides)\n\t\t\tif (patches.occupied.get(team)?.has(patch)) return\n\t\t\t// someone of the team close by\n\t\t\tfor (const near of world.spatial.query(x, z, reach)) {\n\t\t\t\tif (near === entity || !near.alive || near.hidden) continue\n\t\t\t\tif (world.player(near.owner).team !== team || world.player(near.owner).neutral) continue\n\t\t\t\tif (distSq(near.pos, { x, z }) <= reach * reach) return\n\t\t\t}\n\t\t\tif (seenBy?.(world, entity, team)) return\n\t\t\tevent.visible = false\n\t\t}\n\t})\n\treturn { id: 'concealment', options, hooks: [hook], systems: [count] }\n}\n\n/** Where each that hides stood the tick before, and in which patch: what a rustle is told from. Not the world's state */\nconst stood = new WeakMap<World, Map<number, { x: number; z: number; patch: number }>>()\n\n/** One hidden that moved in a patch, or stepped into one: told to the teams the game says (`ConcealmentOptions.rustle`) */\nfunction tellRustles(\n\tworld: World,\n\tlayer: string,\n\tpatches: Patches,\n\thides: NonNullable<ConcealmentOptions['hides']>,\n\trustle: NonNullable<ConcealmentOptions['rustle']>,\n\tseconds: number\n): void {\n\tlet was = stood.get(world)\n\tif (!was) stood.set(world, (was = new Map()))\n\tconst every = Math.max(1, Math.round(seconds / world.dt))\n\tconst { width, depth } = world.terrain\n\tconst teams = typeof rustle === 'function' ? [...new Set([...world.players.values()].filter((p) => !p.neutral).map((p) => p.team))] : undefined\n\t// the actors only: scenery stands still and is neutral, which neither rustles nor has a team in a patch\n\tfor (const entity of world.actors.values()) {\n\t\tif (!entity.alive || entity.hidden || !hides(world, entity)) continue\n\t\tconst { x, z } = entity.pos\n\t\tconst patch = x < 0 || z < 0 || x >= width || z >= depth ? 0 : patches.of[Math.floor(z) * width + Math.floor(x)]\n\t\tconst before = was.get(entity.id)\n\t\tif (!before) {\n\t\t\twas.set(entity.id, { x, z, patch })\n\t\t\tcontinue\n\t\t}\n\t\tconst dx = before.x - x\n\t\tconst dz = before.z - z\n\t\tconst moved = dx * dx + dz * dz > 1e-4\n\t\tconst entered = !!patch && patch !== before.patch\n\t\tbefore.x = x\n\t\tbefore.z = z\n\t\tbefore.patch = patch\n\t\tif (!patch || !moved || (!entered && (world.tick + entity.id) % every !== 0)) continue\n\t\tconst told = teams && typeof rustle === 'function' ? teams.filter((team) => rustle(world, entity, team)) : undefined\n\t\tif (told && !told.length) continue\n\t\tworld.events.emit(rustled, { layer, entity, x, z, entered, ...(told && { teams: told }) })\n\t}\n\tif (was.size > world.entities.size * 2 + 64) for (const id of was.keys()) if (!world.entities.has(id)) was.delete(id)\n}\n\n/** The patches each team has someone in, worked out anew */\nfunction countOccupied(world: World, patches: Patches, hides: NonNullable<ConcealmentOptions['hides']>): void {\n\tpatches.counted = true\n\tconst { occupied, of } = patches\n\tfor (const set of occupied.values()) set.clear()\n\tconst { width, depth } = world.terrain\n\t// the actors only: scenery stands still and is neutral, which neither rustles nor has a team in a patch\n\tfor (const entity of world.actors.values()) {\n\t\tif (!entity.alive || entity.hidden || !hides(world, entity)) continue\n\t\tconst { x, z } = entity.pos\n\t\tif (x < 0 || z < 0 || x >= width || z >= depth) continue\n\t\tconst patch = of[Math.floor(z) * width + Math.floor(x)]\n\t\tif (!patch) continue\n\t\tconst owner = world.player(entity.owner)\n\t\tif (owner.neutral) continue\n\t\tlet set = occupied.get(owner.team)\n\t\tif (!set) occupied.set(owner.team, (set = new Set()))\n\t\tset.add(patch)\n\t}\n}\n\n/** One hidden moving in a layer: where the player sees the ground, to whom the rules tell it, a shake of the bushes */\nexport const toldRustle = replicateEvent(rustled, 'rustle', ({ layer, entity, x, z, entered, teams }, view) => {\n\tif (view.observer || view.knows(entity) || !view.sees(x, z)) return undefined\n\tif (teams && !teams.includes(view.team)) return undefined\n\treturn { type: 'rustle', layer, x: Math.round(x * 10) / 10, z: Math.round(z * 10) / 10, ...(entered && { entered }) }\n})\n","import { bounty as bountyEvent } from '#engine/engineEvents'\nimport { onCast, onHit, onKill } from './abilities/effects'\nimport { garrisonHooks } from './transport'\nimport { summonHooks, worthless } from './summons'\nimport { defineHook, type HookDef } from './hooks'\nimport { dropLoot } from './items'\nimport { engineMessage } from './messages'\nimport { Path } from './paths'\nimport { earn } from './player'\nimport { replicateEvent } from './replication'\n\n/**\n * The rules the engine brings along, written as hook handlers like any game module's. A module can leave any\n * of them out by id (`GameModule.withoutHooks`), or put its own in place of one by giving a handler the same id.\n *\n * @beta\n */\nexport const coreHooks: HookDef[] = [\n\tdefineHook({\n\t\thook: 'canPlace',\n\t\tid: 'mapPathsClear',\n\t\trun(world, event) {\n\t\t\t// nothing is built on a path of the map that says so (`MapPath.keepClear`): a road that has to stay open\n\t\t\tif (!event.allowed) return\n\t\t\tconst { site } = event\n\t\t\tfor (const def of world.map.paths) {\n\t\t\t\tif (!def.keepClear) continue\n\t\t\t\tconst path = new Path(def.points, def.width)\n\t\t\t\tfor (let cz = Math.floor(site.z - site.hd); cz < Math.ceil(site.z + site.hd); cz++) {\n\t\t\t\t\tfor (let cx = Math.floor(site.x - site.hw); cx < Math.ceil(site.x + site.hw); cx++) {\n\t\t\t\t\t\tif (!path.containsCell(cx, cz)) continue\n\t\t\t\t\t\tevent.allowed = false\n\t\t\t\t\t\tevent.reason = engineMessage('cannotBuildThere')\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}),\n\tdefineHook({\n\t\thook: 'beforeDeath',\n\t\tid: 'undying',\n\t\trun(_world, event) {\n\t\t\t// what cannot die of damage is left standing with next to nothing\n\t\t\tif (!event.fromDamage || !event.entity.def.undying) return\n\t\t\tevent.prevented = true\n\t\t\tevent.entity.hp = Math.max(event.entity.hp, 1)\n\t\t}\n\t}),\n\tdefineHook({\n\t\thook: 'death',\n\t\tid: 'loot',\n\t\trun(world, { entity, killer }) {\n\t\t\tif (killer && world.areEnemies(killer.owner, entity.owner) && !worthless(entity)) dropLoot(world, entity, killer)\n\t\t}\n\t}),\n\tdefineHook({\n\t\thook: 'death',\n\t\tid: 'bounty',\n\t\trun(world, { entity, killer }) {\n\t\t\tconst { bounty } = entity.def\n\t\t\tconst { currency } = world.registry\n\t\t\tif (!bounty || !currency || !killer || !world.areEnemies(killer.owner, entity.owner) || worthless(entity)) return\n\t\t\tconst amount = world.rng.int(bounty[0], bounty[1])\n\t\t\tearn(world.player(killer.owner).resources, currency, amount)\n\t\t\tworld.events.emit(bountyEvent, { entity, player: killer.owner, amount })\n\t\t}\n\t}),\n\tdefineHook({\n\t\thook: 'afterDamage',\n\t\tid: 'onHit',\n\t\trun(world, { target, source, attack }) {\n\t\t\t// effects of an attack that hit and did not kill: a slow, a second strike...\n\t\t\tif (attack && source?.alive && target.alive) onHit(world, source, target)\n\t\t}\n\t}),\n\tdefineHook({\n\t\thook: 'afterCast',\n\t\tid: 'onCast',\n\t\trun(world, { caster, ability, item, charged }) {\n\t\t\t// the caster's passives that react to its casts. What spends a charge does not count to the next one\n\t\t\tif (!item && !charged) onCast(world, caster, ability)\n\t\t}\n\t}),\n\tdefineHook({\n\t\thook: 'afterDeath',\n\t\tid: 'onKill',\n\t\trun(world, { entity, killer, attack }) {\n\t\t\tif (killer?.alive && killer.abilities.length && world.areEnemies(killer.owner, entity.owner)) onKill(world, killer, entity, attack)\n\t\t}\n\t}),\n\t...summonHooks,\n\t...garrisonHooks\n]\n\n/** A bounty, to whoever got it */\nexport const toldBounty = replicateEvent(bountyEvent, 'bounty', ({ entity, player, amount }, view) =>\n\tplayer === view.player ? { type: 'bounty', x: entity.pos.x, z: entity.pos.z, amount } : undefined\n)\n","import { layerOf } from '#engine/abilities/buffs'\nimport { exposure, detection } from '../entity'\nimport { constructionSite } from './construction'\nimport type { Entity } from '#engine/entity'\nimport { statsOf } from '#engine/stats'\nimport type { System } from '#engine/registry'\nimport type { World } from '#engine/world'\nimport { snapshotPart } from '../replication'\nimport { tellCellsInSight } from '#engine/cellLayers'\n\n/**\n * Seconds an attacker stays in sight of the team it hit, wherever it stands\n *\n * @internal\n */\nexport const EXPOSED_FOR = 2\n\n/**\n * Lets a team see the entity for a while, for having attacked it: from the dark, from high ground, from anywhere\n *\n * @beta\n */\nexport function expose(entity: Entity, team: number): void {\n\tlet seconds = entity.get(exposure)\n\tif (!seconds) entity.set(exposure, (seconds = new Map()))\n\tseconds.set(team, EXPOSED_FOR)\n}\n\n/**\n * The level an entity looks out from. From the air, nothing is above\n *\n * @internal\n */\nexport const viewLevel = (world: World, entity: Entity): number =>\n\tlayerOf(world, entity) === 'air' ? Infinity : world.terrain.levelAt(entity.pos.x, entity.pos.z)\n\n/** The circles lit during an update, four numbers each: team, x, z, radius. Kept between updates so nothing is allocated */\nconst lit: number[] = []\nconst found: Entity[] = []\n\n/**\n * Works out what every team sees, every few ticks: clears the `visible` grids and lights a circle around\n * everything that looks around (units and buildings by their sight, reveal spells, scouting missiles,\n * invisible units that were found, attackers that gave themselves away).\n */\nexport const fogSystem: System = {\n\tname: 'fog',\n\tphase: 'cleanup',\n\t// every few ticks is often enough for the eye\n\tevery: 3,\n\tupdate(world, dt) {\n\t\tconst { fog } = world\n\t\tlit.length = 0\n\t\tconst light = (team: number, x: number, z: number, radius: number, level?: number) => {\n\t\t\tfog.reveal(team, x, z, radius, level)\n\t\t\tlit.push(team, x, z, radius)\n\t\t\t// and the teams it shares what it sees with\n\t\t\tfor (const other of world.sides.visionOf(team)) {\n\t\t\t\t// a team that only gets sight shared with it (one from a save, with nobody on it yet) gets fog of its own\n\t\t\t\tfog.addTeam(other)\n\t\t\t\tfog.reveal(other, x, z, radius, level)\n\t\t\t\tlit.push(other, x, z, radius)\n\t\t\t}\n\t\t}\n\n\t\tfog.beginUpdate()\n\t\tfor (const entity of world.actors.values()) {\n\t\t\tif (!entity.alive || entity.hidden) continue\n\t\t\tconst owner = world.player(entity.owner)\n\t\t\tif (owner.neutral) continue\n\t\t\t// construction sites barely see past their own walls\n\t\t\tconst { sight: full } = statsOf(world, entity)\n\t\t\tconst sight = entity.isStructure && entity.has(constructionSite) ? Math.min(full, entity.def.radius + 2) : full\n\t\t\tlight(owner.team, entity.pos.x, entity.pos.z, sight, viewLevel(world, entity))\n\t\t}\n\t\tfor (const reveal of world.reveals) light(reveal.team, reveal.x, reveal.z, reveal.radius)\n\t\t// what an ability sent out to look around\n\t\tfor (const missile of world.missiles) {\n\t\t\tif (missile.effect.sight) light(world.player(missile.owner).team, missile.x, missile.z, missile.effect.sight)\n\t\t}\n\t\tfor (const entity of world.index.with(detection)) {\n\t\t\t// what was found is seen where it stands, in the dark too\n\t\t\tif (!entity.alive) continue\n\t\t\tfor (const team of entity.get(detection)!.keys()) light(team, entity.pos.x, entity.pos.z, entity.def.radius + 1)\n\t\t}\n\t\tfor (const entity of world.index.with(exposure)) {\n\t\t\tconst seconds = entity.get(exposure)!\n\t\t\tfor (const [team, remaining] of seconds) {\n\t\t\t\tconst left = remaining - dt\n\t\t\t\tif (left > 0 && entity.alive && !entity.hidden) light(team, entity.pos.x, entity.pos.z, entity.def.radius + 1)\n\t\t\t\tif (left > 0) seconds.set(team, left)\n\t\t\t\telse seconds.delete(team)\n\t\t\t}\n\t\t\tif (seconds.size === 0) entity.remove(exposure)\n\t\t}\n\t\tfog.endUpdate()\n\n\t\t// Which structures each team sees now, and has ever seen (so they can still be pointed at once out of sight).\n\t\t// Nothing can be in sight outside the circles that were just lit, so only those are looked at: the cost follows\n\t\t// how much is looking around, not how many trees the map has\n\t\tfor (const inSight of world.sceneryInSight.values()) inSight.clear()\n\t\tfor (let i = 0; i < lit.length; i += 4) {\n\t\t\tconst team = lit[i]\n\t\t\tconst bit = fog.teamBit(team)\n\t\t\tlet inSight = world.sceneryInSight.get(team)\n\t\t\tif (!inSight) world.sceneryInSight.set(team, (inSight = new Set()))\n\t\t\t// structures alone: in a battle each circle holds hundreds of units, none of them looked for here\n\t\t\tfor (const entity of world.spatial.queryStatic(lit[i + 1], lit[i + 2], lit[i + 3], found)) {\n\t\t\t\tif (entity.scenery) {\n\t\t\t\t\tif (inSight.has(entity) || !world.isVisibleTo(entity, team)) continue\n\t\t\t\t\tinSight.add(entity)\n\t\t\t\t\tentity.seenBy |= bit\n\t\t\t\t} else if (!(entity.seenBy & bit) && world.isVisibleTo(entity, team)) entity.seenBy |= bit\n\t\t\t}\n\t\t}\n\t\t// the cells the rules changed out of a team's sight, told as they come into it (RV7)\n\t\ttellCellsInSight(world)\n\t}\n}\n\n/**\n * What the player is told of the spots revealed (`Snapshot.reveals`): their team's own, and another's only where they see:\n * where an enemy's spell looks is the enemy's to know. A quiet one shows what it shows, and is nothing to draw; none to a computer\n */\nexport const revealsPart = snapshotPart('reveals', (view) =>\n\tview.forComputer\n\t\t? []\n\t\t: view.world.reveals\n\t\t\t\t.filter((reveal) => !reveal.quiet && (reveal.team === view.team || view.sees(reveal.x, reveal.z)))\n\t\t\t\t.map(({ id, x, z, radius, left, team }) => ({ id, x, z, radius, left, ours: team === view.team }))\n)\n","/**\n * How things are hurt, healed and die in a world (`world.life`): damage through the hooks, armor and shields; healing;\n * death through its hooks, the entity leaving the world, a fallen hero waiting out of it. The world's `damage`, `heal`\n * and `kill` are this\n */\nimport { damaged, entityDied, healed as healedEvent } from '#engine/engineEvents'\nimport { dashing } from './dashing'\nimport { absorb } from './abilities/buffs'\nimport { footprintOf } from './defs'\nimport { type Entity, fighting, deposit } from './entity'\nimport type { Death } from './hooks'\nimport { hurtWhileChannelling } from './orders/cast'\nimport { clearOrders } from './orders/queue'\nimport { damageMultiplier } from './rules'\nimport { statsOf } from './stats'\nimport { expose } from './systems/fog'\nimport type { DamageOptions, DeathCause, DeathReason, World } from './world'\nimport { replicateEvent } from './replication'\n\n/**\n * How a world's entities are hurt, healed and die\n *\n * @beta\n */\nexport class Life {\n\t/** Who died and is to be taken out of the world at the end of the tick (`World.step`) */\n\treadonly dead: Entity[] = []\n\n\tconstructor(private readonly world: World) {}\n\n\t/**\n\t * Deals damage. In order:\n\t * 1. the `beforeDamage` hook, which can change the amount or call it off;\n\t * 2. armor or magic resist, then shields, take their part;\n\t * 3. the rest comes off the target's health, and it dies when nothing is left (see `kill`);\n\t * 4. the `afterDamage` hook, for what follows from a hit: life steal, effects on hit.\n\t */\n\tdamage(target: Entity, amount: number, source?: Entity, options: DamageOptions = {}): void {\n\t\t// one already being killed takes no more: its death goes on as it began\n\t\tif (!target.alive || target.def.invulnerable || this.dying.has(target)) return\n\t\t// the cheat: what those who may use the debug tools own is not hurt\n\t\tif (this.world.cheats.invulnerable && this.world.debugPlayers.has(target.owner)) return\n\t\tconst attack = options.attack ?? false\n\t\tconst crit = options.crit ?? false\n\t\tconst { ability, tags } = options\n\t\tconst before = this.world.hooks.run('beforeDamage', {\n\t\t\ttarget,\n\t\t\tsource,\n\t\t\tamount,\n\t\t\ttype: options.damageType ?? 'physical',\n\t\t\tattack,\n\t\t\tcrit,\n\t\t\tability,\n\t\t\ttags,\n\t\t\tcancelled: false\n\t\t})\n\t\tif (before.cancelled || !target.alive) return\n\t\tconst { type } = before\n\t\tconst from = source ? statsOf(this.world, source) : undefined\n\t\t// the attack's type against the target's armour type, by the game's table, and the hook's say over it\n\t\tconst attackType = options.attackType ?? (attack ? source?.def.attacks?.[0]?.attackType : undefined)\n\t\tconst armourType = target.def.armourType\n\t\tlet multiplier = damageMultiplier(this.world.rules.combat.damageTable, attackType, armourType)\n\t\tif (this.world.hooks.has('damageMultiplier'))\n\t\t\tmultiplier = this.world.hooks.run('damageMultiplier', { target, source, attackType, armourType, attack, multiplier }).multiplier\n\t\tconst arrived = Math.max(before.amount * multiplier * this.world.rules.combat.mitigation(type, statsOf(this.world, target), from), 0)\n\t\t// what counts hits takes one, however hard it is struck\n\t\tconst dealt = target.def.hits ? 1 : target.buffs.length ? absorb(target, arrived) : arrived\n\t\tconst taken = Math.min(dealt, target.hp)\n\t\ttarget.hp -= dealt\n\t\ttarget.hurtAt = this.world.time\n\t\tif (source && target.get(fighting)) target.get(fighting)!.lastAttacker = source.id\n\t\t// a recall, and whatever else is kept up only while unhurt, is broken off\n\t\tif (dealt > 0 && target.orders.length) hurtWhileChannelling(this.world, target)\n\t\tif (source && this.world.areEnemies(source.owner, target.owner)) expose(source, this.world.player(target.owner).team)\n\t\tthis.world.events.emit(damaged, { target, source, amount: dealt, type, crit, attack, ability, tags })\n\t\tif (target.hp <= 0)\n\t\t\tthis.die(target, source, attack, 'damage', {\n\t\t\t\ttype,\n\t\t\t\tamount: dealt,\n\t\t\t\toverkill: Math.max(dealt - taken, 0),\n\t\t\t\tcrit,\n\t\t\t\tability,\n\t\t\t\ttags,\n\t\t\t\t...(options.how && { how: options.how })\n\t\t\t})\n\t\tthis.world.hooks.run('afterDamage', { target, source, dealt, taken, type, attack, crit, ability, tags })\n\t}\n\n\t/** Gives health back, after the `beforeHeal` hook had its say. Returns how much of it was needed */\n\theal(target: Entity, amount: number, source?: Entity): number {\n\t\tif (!target.alive || amount <= 0 || this.dying.has(target)) return 0\n\t\tconst before = this.world.hooks.run('beforeHeal', { target, source, amount, cancelled: false })\n\t\tif (before.cancelled) return 0\n\t\tamount = before.amount\n\t\tconst healed = Math.min(amount, target.maxHp - target.hp)\n\t\tif (healed <= 0) return 0\n\t\ttarget.hp += healed\n\t\tthis.world.events.emit(healedEvent, { target, source, amount: healed })\n\t\treturn healed\n\t}\n\n\t/**\n\t * Kills an entity by the rules, not by damage: felled, cancelled, run out of time. `attack` says that an attack of\n\t * the killer did it; `reason` why (`DeathReason`: `killed` when left out, or the game's own word, `sold`), for the\n\t * hooks and the screen\n\t */\n\tkill(entity: Entity, killer?: Entity, attack = false, reason: DeathReason = 'killed'): void {\n\t\tthis.die(entity, killer, attack, reason)\n\t}\n\n\t/**\n\t * How anything dies. In order:\n\t * 1. the `beforeDeath` hook, which can keep it alive;\n\t * 2. its orders and production are called off;\n\t * 3. the `death` hook, while it still stands where it was: experience, loot, bounty;\n\t * 4. it leaves the world (a fallen hero waits out of it to be brought back);\n\t * 5. the `afterDeath` hook, for what follows: effects of the killer on a kill.\n\t */\n\tprivate die(entity: Entity, killer: Entity | undefined, attack: boolean, reason: DeathReason, cause?: DeathCause): void {\n\t\tif (!entity.alive || this.dying.has(entity)) return\n\t\tif (this.world.hooks.run('beforeDeath', { entity, killer, attack, fromDamage: !!cause, cause, reason, prevented: false }).prevented) return\n\t\t// from here on it is dying: still alive and where it was for the `death` hooks, but what they do to it, or what\n\t\t// what they do does to it (a blast that kills a neighbour whose own blast comes back), kills it no second time\n\t\tthis.dying.add(entity)\n\t\ttry {\n\t\t\tclearOrders(this.world, entity)\n\t\t\tthis.world.leave(entity)\n\t\t\t// how the blow says it dies, for the `death` hook to keep or change\n\t\t\tconst death: Death = { entity, killer, attack, cause, reason, ...(cause?.how && { how: cause.how }) }\n\t\t\tthis.world.hooks.run('death', death)\n\t\t\tthis.fall(entity, killer, attack, cause, death)\n\t\t} finally {\n\t\t\tthis.dying.delete(entity)\n\t\t}\n\t}\n\n\t/** Who is being killed right now: their `death` hooks are running. They take no damage, no healing, and die once */\n\tprivate readonly dying = new Set<Entity>()\n\n\t/** Whether an entity is being killed right now: alive still, while its `death` hooks run, and past saving */\n\tisDying(entity: Entity): boolean {\n\t\treturn this.dying.has(entity)\n\t}\n\n\t/** What follows the `death` hooks: the entity is gone from the world, and it is told */\n\tprivate fall(entity: Entity, killer: Entity | undefined, attack: boolean, cause: DeathCause | undefined, death: Death): void {\n\t\tentity.setAlive(false)\n\t\tentity.hp = 0\n\t\tentity.clearBuffs()\n\t\tentity.remove(dashing)\n\t\tthis.detach(entity)\n\t\t// what stays around, out of the world, until it is brought back: a fallen hero, where the heroes pack is on\n\t\tif (!this.world.hooks.has('fallenHero') || !this.world.hooks.run('fallenHero', { entity, killer, stays: false }).stays) this.dead.push(entity)\n\t\tthis.world.events.emit(entityDied, { entity, killer, attack, cause, how: death.how, reason: death.reason })\n\t\tthis.world.hooks.run('afterDeath', death)\n\t\t// a resource used up takes down what stood on it: there is nothing for it to stand on\n\t\tconst above = this.world.get(entity.get(deposit)?.under)\n\t\tif (above?.alive && !this.isDying(above)) this.kill(above, undefined, false, 'removed')\n\t}\n\n\tprivate detach(entity: Entity): void {\n\t\tthis.world.nav.removeAgent(entity.id)\n\t\tif (entity.isStructure) this.world.spatial.removeStatic(entity)\n\t\tif (entity.cell) {\n\t\t\tconst fp = footprintOf(entity.def)\n\t\t\tthis.world.grid.release(entity.cell.x, entity.cell.z, fp.w, fp.d, entity.id)\n\t\t\tthis.world.nav.removeObstacle(entity.id)\n\t\t}\n\t\t// what stood on a resource: the resource has its ground again, and is free to be built on\n\t\tconst under = this.world.get(entity.on)\n\t\tif (under?.get(deposit) && under.cell) {\n\t\t\tif (under.get(deposit)!.under === entity.id) under.get(deposit)!.under = undefined\n\t\t\tif (under.alive) {\n\t\t\t\tconst fp = footprintOf(under.def)\n\t\t\t\tthis.world.grid.occupy(under.cell.x, under.cell.z, fp.w, fp.d, under.id)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** A death, to those who see the dead: who killed it where they see the killer too (`SessionEvent` `death`) */\nexport const toldDeath = replicateEvent(entityDied, 'death', ({ entity, killer, attack, cause, how, reason }, view) => {\n\tif (!view.knows(entity)) return undefined\n\tconst seen = killer && killer !== entity && view.knows(killer) ? killer : undefined\n\treturn {\n\t\ttype: 'death',\n\t\tid: entity.id,\n\t\tfrom: seen && { x: seen.pos.x, z: seen.pos.z },\n\t\tkiller: seen?.id,\n\t\tkillerType: seen?.def.id,\n\t\tattack,\n\t\tdamageType: cause?.type,\n\t\tability: cause?.ability,\n\t\toverkill: cause?.overkill,\n\t\tcrit: cause?.crit,\n\t\thow,\n\t\t...(reason !== 'damage' && { reason }),\n\t\t...(cause?.tags?.length && { tags: [...cause.tags] })\n\t}\n})\n\n/** A hit, to those who see who took it: who dealt it where they see them too */\nexport const toldDamage = replicateEvent(damaged, 'damage', ({ target, source, amount, type, attack, crit, ability, tags }, view) => {\n\tif (!view.knows(target)) return undefined\n\tconst seen = source && view.knows(source) ? source : undefined\n\treturn {\n\t\ttype: 'damage',\n\t\tid: target.id,\n\t\tamount,\n\t\tdamageType: type,\n\t\tsource: seen?.id,\n\t\tsourceType: seen?.def.id,\n\t\tattack,\n\t\tcrit,\n\t\tability: seen ? ability : undefined,\n\t\ttags\n\t}\n})\n\n/** Healing, to those who see who was healed */\nexport const toldHeal = replicateEvent(healedEvent, 'heal', ({ target, source, amount }, view) =>\n\tview.knows(target) ? { type: 'heal', id: target.id, amount, source: source && view.knows(source) ? source.id : undefined } : undefined\n)\n\n/** A critical strike's number over who took it */\nexport const toldCrit = replicateEvent(damaged, 'crit', ({ target, amount, crit }, view) =>\n\tcrit && view.knows(target) ? { type: 'crit', id: target.id, amount: Math.round(amount) } : undefined\n)\n","/**\n * The time of day of a world (`world.clock`): the hour, whether it is night, turned forward to an hour or stopped at one.\n * The world's clock of ticks is the world's (`world.time`); this is the day's, which a map and a script move\n */\nimport { hourOf, isNight } from './defs'\nimport type { World } from './world'\nimport { snapshotPart } from './replication'\n\n/**\n * The time of day of a world: what its day (`GameModule.day`) and the time played make of it, turned forward or stopped\n * by a map or a script. Kept in a save (`WorldInternals.clockShift`, `stillHour`)\n *\n * @beta\n */\nexport class Clock {\n\t/** Seconds the time of day is ahead of the time played */\n\tshift = 0\n\t/** The hour, when the clock does not move (`stop`) */\n\tstill: number | undefined = undefined\n\t/** Whether it was night, and when that was worked out: asked many times a tick, worked out once */\n\tprivate readonly seen: { day: unknown; time: number; shift: number; still: number | undefined; night: boolean } = {\n\t\tday: undefined,\n\t\ttime: Number.NaN,\n\t\tshift: 0,\n\t\tstill: undefined,\n\t\tnight: false\n\t}\n\n\tconstructor(private readonly world: World) {}\n\n\t/** Hour of the day, 0..24. Noon in a game without days */\n\tget hour(): number {\n\t\tif (this.still !== undefined && this.world.registry.day) return this.still\n\t\treturn hourOf(this.world.registry.day, this.world.time + this.shift)\n\t}\n\n\t/** Turns the clock forward to an hour, for a map that wants to start at night or a debug tool */\n\tsetHour(hour: number): void {\n\t\tconst { day } = this.world.registry\n\t\tif (this.still !== undefined) this.still = hour\n\t\telse if (day) this.shift += (((((hour - this.hour) % 24) + 24) % 24) / 24) * day.length\n\t}\n\n\t/** Stops the clock at the hour it is, for a map that is always night; `false` lets it go on from there */\n\tstop(still = true): void {\n\t\tconst { day } = this.world.registry\n\t\tif (still) this.still ??= this.hour\n\t\telse if (this.still !== undefined) {\n\t\t\tconst hour = this.still\n\t\t\tthis.still = undefined\n\t\t\tif (day) this.setHour(hour)\n\t\t}\n\t}\n\n\t/** Whether the clock stands still (`stop`) */\n\tget stopped(): boolean {\n\t\treturn this.still !== undefined\n\t}\n\n\t/**\n\t * Whether the sun is down. Asked for every unit's sight and stats, many times a tick: kept for the moment it was\n\t * worked out at (the day, the time, the clock's shift, an hour that stands still), so it is worked out once a tick\n\t */\n\tget night(): boolean {\n\t\tconst { seen } = this\n\t\tconst { day } = this.world.registry\n\t\tconst { time } = this.world\n\t\tif (seen.time === time && seen.shift === this.shift && seen.still === this.still && seen.day === day) return seen.night\n\t\tseen.day = day\n\t\tseen.time = time\n\t\tseen.shift = this.shift\n\t\tseen.still = this.still\n\t\tseen.night = isNight(day, this.hour)\n\t\treturn seen.night\n\t}\n}\n\n/** The hour of the day, in a game with one (`Snapshot.hour`) */\nexport const hourPart = snapshotPart('hour', ({ world }) => (world.registry.day ? world.hour : undefined), true)\n","import { attackStarted, impact, missed as missedEvent, projectileRemoved } from '#engine/engineEvents'\nimport { replicateEvent, snapshotPart } from '../replication'\nimport type { ProjectileState } from '../session/protocol'\n\n/**\n * What players are told of fights (the combat system's events): a swing, a shot landing, a miss, a blast. Beside the\n * combat system, which emits them\n */\n\n/** A swing, to those who see the attacker */\nexport const toldAttack = replicateEvent(attackStarted, 'attack', ({ attacker, target, weapon }, view) =>\n\tview.knows(attacker)\n\t\t? { type: 'attack', id: attacker.id, target: target && view.knows(target) ? target.id : undefined, ...(weapon > 0 && { weapon }) }\n\t\t: undefined\n)\n\n/** A shot landing: to its side, and to those who see where */\nexport const toldShot = replicateEvent(projectileRemoved, 'shot', (shot, view) => {\n\tif (!view.isAlly(shot.owner) && !view.sees(shot.tx, shot.tz)) return undefined\n\tconst target = shot.splash ? undefined : view.world.get(shot.target)\n\treturn {\n\t\ttype: 'shot',\n\t\tid: shot.id,\n\t\tx: shot.tx,\n\t\tz: shot.tz,\n\t\ttarget: target && view.knows(target) ? target.id : undefined,\n\t\tmiss: shot.miss,\n\t\tcrit: shot.crit\n\t}\n})\n\n/** A miss, to those who see who missed or who was missed */\nexport const toldMiss = replicateEvent(missedEvent, 'miss', ({ x, z, source, target }, view) =>\n\t(source && view.knows(source)) || (target && view.knows(target)) ? { type: 'miss', x, z } : undefined\n)\n\n/** A blast: to its side, and to those who see where */\nexport const toldImpact = replicateEvent(impact, 'impact', ({ x, z, radius, owner }, view) =>\n\tview.isAlly(owner) || view.sees(x, z) ? { type: 'impact', x, z, radius } : undefined\n)\n\n/** The projectiles in flight the player is told of: their side's, and those where they see (`Snapshot.projectiles`); none to a computer */\nexport const projectilesPart = snapshotPart('projectiles', (view) => {\n\tconst projectiles: ProjectileState[] = []\n\tif (view.forComputer) return projectiles\n\tconst { world } = view\n\tfor (const p of world.projectiles) {\n\t\tif (!view.isAlly(p.owner) && !view.sees(p.x, p.z)) continue\n\t\tconst source = world.get(p.source)\n\t\tconst state: ProjectileState = {\n\t\t\tid: p.id,\n\t\t\tx: p.x,\n\t\t\tz: p.z,\n\t\t\tkind: p.kind ?? '',\n\t\t\towner: p.owner,\n\t\t\tcrit: p.crit,\n\t\t\tdamageType: p.type,\n\t\t\tlook: p.look,\n\t\t\tsource: source && view.knows(source) ? source.id : undefined\n\t\t}\n\t\tconst target = p.splash ? undefined : world.get(p.target)\n\t\tif (target && view.knows(target)) state.target = target.id\n\t\tif (p.splash) {\n\t\t\tstate.from = { x: p.sx, z: p.sz }\n\t\t\tstate.to = { x: p.tx, z: p.tz }\n\t\t}\n\t\tprojectiles.push(state)\n\t}\n\treturn projectiles\n})\n","import type { Rect, Vec2 } from '#engine/math'\nimport type { AgentParams, AgentSave, AgentState, NavDebugGeometry, Navigation } from './navigation'\n\n/**\n * The ground cut for units of several sizes (S38): a navigation for each, an agent on the one for the biggest size it\n * is not smaller than, so a big unit keeps from walls as far as it needs and a small one still fits through a gap.\n * What is not about an agent (obstacles, where one can stand, a path asked for) goes to each, or to the smallest.\n * Each size has its own crowd: units of different sizes do not steer around each other, they walk through, as units\n * on the ground and in the air do\n *\n * @internal\n */\nexport class SizedNavigation implements Navigation {\n\tprivate readonly sizeOf = new Map<number, number>()\n\n\t/** `sizes` from the smallest up, each with the radius it was cut for */\n\tconstructor(readonly sizes: readonly { radius: number; navigation: Navigation }[]) {\n\t\tif (!sizes.length) throw new Error('Navigation: no sizes to cut the ground for')\n\t}\n\n\tget version(): number {\n\t\treturn this.sizes[0].navigation.version\n\t}\n\n\t/** The size an agent of a radius goes on: the biggest it is not smaller than, the smallest for one smaller than all */\n\tsizeFor(radius: number): number {\n\t\tlet chosen = 0\n\t\tthis.sizes.forEach((size, i) => {\n\t\t\tif (radius >= size.radius) chosen = i\n\t\t})\n\t\treturn chosen\n\t}\n\n\tprivate of(id: number): Navigation {\n\t\treturn this.sizes[this.sizeOf.get(id) ?? 0].navigation\n\t}\n\n\taddAgent(id: number, position: Vec2, params: AgentParams): void {\n\t\tthis.removeAgent(id)\n\t\tthis.sizeOf.set(id, this.sizeFor(params.radius))\n\t\tthis.of(id).addAgent(id, position, params)\n\t}\n\n\tremoveAgent(id: number): void {\n\t\tif (!this.sizeOf.has(id)) return\n\t\tthis.of(id).removeAgent(id)\n\t\tthis.sizeOf.delete(id)\n\t}\n\n\thasAgent(id: number): boolean {\n\t\treturn this.sizeOf.has(id) && this.of(id).hasAgent(id)\n\t}\n\n\tsetDestination(id: number, target: Vec2): boolean {\n\t\treturn this.of(id).setDestination(id, target)\n\t}\n\n\tclearDestination(id: number): void {\n\t\tthis.of(id).clearDestination(id)\n\t}\n\n\tteleport(id: number, position: Vec2): void {\n\t\tthis.of(id).teleport(id, position)\n\t}\n\n\tsetAnchored(id: number, anchored: boolean): void {\n\t\tthis.of(id).setAnchored(id, anchored)\n\t}\n\n\tsetGhost(id: number, ghost: boolean): void {\n\t\tthis.of(id).setGhost(id, ghost)\n\t}\n\n\tsetSpeed(id: number, speed: number): void {\n\t\tthis.of(id).setSpeed(id, speed)\n\t}\n\n\treadAgent(id: number, out: AgentState): boolean {\n\t\treturn this.sizeOf.has(id) && this.of(id).readAgent(id, out)\n\t}\n\n\tsaveAgent(id: number): AgentSave | undefined {\n\t\treturn this.sizeOf.has(id) ? this.of(id).saveAgent(id) : undefined\n\t}\n\n\trestoreAgent(id: number, save: AgentSave): void {\n\t\t// its size is in its radius, which the save has\n\t\tthis.removeAgent(id)\n\t\tthis.sizeOf.set(id, this.sizeFor(save.radius))\n\t\tthis.of(id).restoreAgent(id, save)\n\t}\n\n\treseat(agents: readonly (readonly [id: number, save: AgentSave])[]): void {\n\t\t// each size anew, with its agents in the save's order: its size is in its radius, which the save has\n\t\tthis.sizeOf.clear()\n\t\tfor (const [id, save] of agents) this.sizeOf.set(id, this.sizeFor(save.radius))\n\t\tthis.sizes.forEach((size, i) => size.navigation.reseat(agents.filter(([id]) => this.sizeOf.get(id) === i)))\n\t}\n\n\tsettle(version: number): void {\n\t\tfor (const size of this.sizes) size.navigation.settle(version)\n\t}\n\n\t/** Slow ground weighed again on each size's navigation, where a slowing layer changed */\n\tgroundChanged(cells: readonly number[]): void {\n\t\tfor (const size of this.sizes) size.navigation.groundChanged?.(cells)\n\t}\n\n\t/** Each size's navigation cut again of the ground as it is now */\n\treshape(): boolean {\n\t\tlet any = false\n\t\tfor (const size of this.sizes) any = !!size.navigation.reshape?.() || any\n\t\treturn any\n\t}\n\n\tupdate(dt: number): void {\n\t\tfor (const size of this.sizes) size.navigation.update(dt)\n\t}\n\n\taddObstacle(key: number, rect: Rect): boolean {\n\t\t// in the way of every size, or of none: refused by one is taken back from those it went into\n\t\tconst added: Navigation[] = []\n\t\tfor (const { navigation } of this.sizes) {\n\t\t\tif (!navigation.addObstacle(key, rect)) {\n\t\t\t\tfor (const done of added) done.removeObstacle(key)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tadded.push(navigation)\n\t\t}\n\t\treturn true\n\t}\n\n\tremoveObstacle(key: number): void {\n\t\tfor (const size of this.sizes) size.navigation.removeObstacle(key)\n\t}\n\n\tholdObstacles(hold: boolean): void {\n\t\tfor (const size of this.sizes) size.navigation.holdObstacles?.(hold)\n\t}\n\n\tobstacleRoom(): number {\n\t\treturn Math.min(...this.sizes.map((size) => size.navigation.obstacleRoom()))\n\t}\n\n\tsameCrowd(a: number, b: number): boolean {\n\t\tconst sizeA = this.sizeOf.get(a)\n\t\tconst sizeB = this.sizeOf.get(b)\n\t\tif (sizeA === undefined || sizeB === undefined || sizeA !== sizeB) return false\n\t\treturn this.sizes[sizeA].navigation.sameCrowd?.(a, b) ?? true\n\t}\n\n\tclosestPoint(point: Vec2, searchRadius?: number): Vec2 | null {\n\t\treturn this.sizes[0].navigation.closestPoint(point, searchRadius)\n\t}\n\n\tfindPath(from: Vec2, to: Vec2): Vec2[] | null {\n\t\treturn this.sizes[0].navigation.findPath(from, to)\n\t}\n\n\tdebugGeometry(): NavDebugGeometry {\n\t\treturn this.sizes[0].navigation.debugGeometry()\n\t}\n\n\tdispose(): void {\n\t\tfor (const size of this.sizes) size.navigation.dispose()\n\t\tthis.sizeOf.clear()\n\t}\n}\n","import { edgeDistance, type Entity, type EntityId, type Order } from '#engine/entity'\nimport type { Vec2 } from '#engine/math'\nimport type { OrderBehavior, OrderInits } from '#engine/registry'\nimport { statsOf } from '#engine/stats'\nimport { acquireInRange, bombard, canAttack, canSee, cancelSwing, disengage, engage, fireOnTheMove, searchTarget } from '#engine/systems/combat'\nimport { attackStat, groundAttack } from '#engine/attacks'\nimport { halt, isMovingTo, moveTo, moveToEntity, setAnchored } from '#engine/systems/movement'\nimport type { World } from '#engine/world'\nimport { engageWith, isBlocked, shun } from '#engine/engagement'\nimport { engineMessage } from '#engine/messages'\nimport { hypot } from '#engine/exactMath'\nimport { moving, fighting } from '../entity'\n\n/**\n * What `hold` keeps in its order: what it is fighting, 0 for nothing\n *\n * @beta\n */\nexport interface HoldState {\n\t/** What it fights, 0 for nothing */\n\ttarget?: EntityId\n}\n\n/**\n * What `attack` keeps: whether it lost sight and walks to where it last saw its target\n *\n * @beta\n */\nexport interface AttackState {\n\t/** Walking to where it last saw its target */\n\tsearching?: boolean\n\t/** Where it last saw it */\n\tlastSeen?: Vec2\n}\n\n/**\n * What walking to a point and fighting on the way keeps (`attackMove`, `attackPath`, `patrol`)\n *\n * @beta\n */\nexport interface AdvanceState {\n\t/** What it fights, 0 for nothing */\n\ttarget?: EntityId\n\t/** To walk on again once the fight is over */\n\tresume?: boolean\n\t/** Held up behind its own, waiting */\n\twaiting?: boolean\n\t/** The point it last set out for */\n\theading?: Vec2\n}\n\n/**\n * What an order along a path keeps (`followPath`, `attackPath`): the bend it goes to next, and which way. Set as it starts\n *\n * @beta\n */\nexport interface AlongPath {\n\t/** The bend of the path it goes to next, by its place in the path */\n\tleg: number\n\t/** Which way along the path: towards its last point (1) or its first (-1) */\n\tstep: 1 | -1\n}\n\n/**\n * What `patrol` keeps: its two ends and the one it goes to (set as it starts), and whether it found one out of reach\n *\n * @beta\n */\nexport interface PatrolState extends AdvanceState {\n\t/** The point it was sent to, and where it stood */\n\tends: [Vec2, Vec2]\n\t/** Which of the two it goes to */\n\tleg: number\n\t/** It could not get to the other end */\n\tstuck?: boolean\n}\n\n/**\n * What `follow` keeps: the tick it last set out after its target\n *\n * @beta\n */\nexport interface FollowState {\n\t/** The tick it last set out after its target */\n\ttried?: number\n}\n\n/**\n * What `attackGround` keeps: whether it walked into range already\n *\n * @beta\n */\nexport interface AttackGroundState {\n\t/** It walked into range already */\n\twalked?: boolean\n}\n\n/** How close a unit gets to the unit or building it was sent to */\nconst FOLLOW_RANGE = 0.75\n\n/** What a move remembers: what it shoots at on its way, with an attack that fires on the move (`AttackDef.onTheMove`) */\nexport interface MoveState {\n\tshooting?: number\n}\n\nexport const moveOrder: OrderBehavior<MoveState, OrderInits['move']> = {\n\ttype: 'move',\n\tformation: true,\n\taccepts: (_world, entity) => !!entity.get(moving),\n\tstart(world, entity, order) {\n\t\tconst target = world.get(order.init.target)\n\t\t// at its group's pace, where it goes together (GP1)\n\t\tconst m = entity.get(moving)\n\t\tif (m) m.cap = order.init.speedCap\n\t\tif (target) moveToEntity(world, entity, target, FOLLOW_RANGE)\n\t\telse if (order.init.point) moveTo(world, entity, order.init.point, { groupId: order.groupId, facing: order.init.facing })\n\t},\n\tupdate(world, entity, order, dt) {\n\t\tconst m = entity.get(moving)!\n\t\t// an attack that fires on the move: what it passes, shot at as it goes\n\t\tif (entity.def.attacks?.some((attack) => attack.onTheMove)) order.state.shooting = fireOnTheMove(world, entity, order.state.shooting, dt)\n\t\tif (order.init.target) {\n\t\t\tconst target = world.get(order.init.target)\n\t\t\tif (!target || target.hidden) return 'done'\n\t\t\t// a moving target is chased until caught up with, and that is the end of it\n\t\t\tif (m.status === 'moving') return 'running'\n\t\t\treturn m.status === 'failed' ? 'failed' : 'done'\n\t\t}\n\t\tif (m.status === 'moving') return 'running'\n\t\treturn m.status === 'failed' ? 'failed' : 'done'\n\t},\n\tend(_world, entity, order) {\n\t\tif (order.state.shooting !== undefined) cancelSwing(entity)\n\t\tconst m = entity.get(moving)\n\t\tif (m) m.cap = undefined\n\t}\n}\n\n/** Stand still and only fight what comes into range */\nexport const holdOrder: OrderBehavior<HoldState, OrderInits['hold']> = {\n\ttype: 'hold',\n\taccepts: (_world, entity) => !!entity.get(moving),\n\tstart(world, entity) {\n\t\thalt(world, entity)\n\t\tsetAnchored(world, entity, true)\n\t},\n\tupdate(world, entity, order, dt) {\n\t\tif (!entity.def.attacks?.length) return 'running'\n\t\tconst { state } = order\n\t\tconst target = world.get(state.target)\n\t\tif (target) {\n\t\t\tif (engage(world, entity, target, dt, false) === 'attacking') return 'running'\n\t\t\tstate.target = 0\n\t\t}\n\t\tif ((world.tick + entity.id) % 4 === 0) {\n\t\t\tconst found = acquireInRange(world, entity)\n\t\t\t// claimed at once, so that others picking in the same tick count it\n\t\t\tif (found) engageWith(world, entity, found)\n\t\t\tstate.target = found?.id ?? 0\n\t\t}\n\t\treturn 'running'\n\t},\n\tend(world, entity) {\n\t\tdisengage(world, entity)\n\t}\n}\n\nexport const attackOrder: OrderBehavior<AttackState, OrderInits['attack']> = {\n\ttype: 'attack',\n\taccepts(world, entity, init) {\n\t\tconst target = world.get(init.target)\n\t\treturn !!target && canAttack(world, entity, target, true)\n\t},\n\tstart(world, _entity, order) {\n\t\t// a structure stays where it was seen: one remembered in the fog (the command accepts it) is walked to, not given up on\n\t\tconst target = world.get(order.init.target)\n\t\tif (target?.isStructure) order.state.lastSeen = { x: target.pos.x, z: target.pos.z }\n\t},\n\tupdate(world, entity, order, dt) {\n\t\tconst { state } = order\n\t\tconst target = world.get(order.init.target)\n\t\tif (!target || !canAttack(world, entity, target, true)) return 'done'\n\n\t\tif (!canSee(world, entity, target)) {\n\t\t\t// lost sight: walk to where it was last seen, then give up\n\t\t\tconst m = entity.get(moving)\n\t\t\tif (!m || !state.lastSeen) return 'done'\n\t\t\tif (!state.searching) {\n\t\t\t\tstate.searching = true\n\t\t\t\tdisengage(world, entity)\n\t\t\t\tmoveTo(world, entity, state.lastSeen)\n\t\t\t\treturn 'running'\n\t\t\t}\n\t\t\treturn m.status === 'moving' ? 'running' : 'done'\n\t\t}\n\t\tstate.searching = false\n\t\tstate.lastSeen = { x: target.pos.x, z: target.pos.z }\n\n\t\tconst result = engage(world, entity, target, dt, !!entity.get(moving), true)\n\t\treturn result === 'invalid' || result === 'outOfRange' ? 'done' : 'running'\n\t},\n\tend(world, entity) {\n\t\tdisengage(world, entity)\n\t}\n}\n\ntype Advance = 'fighting' | 'walking' | 'arrived' | 'failed'\n\n/**\n * One tick of walking to a point and fighting everything met on the way.\n * What it needs to remember is kept in the state of the order.\n */\nfunction advance(world: World, entity: Entity, order: Order<AdvanceState>, point: Vec2, dt: number): Advance {\n\tconst { state } = order\n\tif (entity.def.attacks?.length) {\n\t\tconst target = world.get(state.target)\n\t\tif (target) {\n\t\t\tconst result = engage(world, entity, target, dt, true)\n\t\t\tconst escaped = edgeDistance(entity, target) > world.rules.combat.acquisitionRange(world, entity) * 1.6\n\t\t\t// held up on the way to it (by its own, in a pass): something else, or on its way\n\t\t\tconst blocked = result === 'chasing' && isBlocked(world, entity, target)\n\t\t\tif (result !== 'invalid' && !escaped && !blocked) return 'fighting'\n\t\t\tif (blocked) shun(world, entity, target)\n\t\t\tstate.target = 0\n\t\t\tstate.resume = true\n\t\t\tdisengage(world, entity)\n\t\t}\n\t\tif (state.resume || (world.tick + entity.id) % 4 === 0) {\n\t\t\tconst { target: found, passedOver: waiting } = searchTarget(world, entity)\n\t\t\tif (found) {\n\t\t\t\tstate.waiting = false\n\t\t\t\tengageWith(world, entity, found)\n\t\t\t\tstate.target = found.id\n\t\t\t\tstate.resume = true\n\t\t\t\treturn 'fighting'\n\t\t\t}\n\t\t\t// it let go of what it could not get at, and the fight is still on: it waits by it, out of the way, for a\n\t\t\t// spot or for its side to win, and does not walk on alone past it\n\t\t\t// stops where it is once: stepping aside for others afterwards is left to go on\n\t\t\tif (waiting && !state.waiting && entity.get(moving)?.status === 'moving') halt(world, entity)\n\t\t\tstate.waiting = waiting\n\t\t}\n\t\tif (state.waiting) return 'fighting'\n\t}\n\n\tconst m = entity.get(moving)!\n\tif (state.resume || !isMovingTo(entity, point)) {\n\t\t// on the way again after a fight, or on the way to somewhere else\n\t\t// compared by where it is, not by being the same object: order state has to come back the same from a save\n\t\tconst heading = state.heading\n\t\tif (!state.resume && m.status !== 'moving' && heading?.x === point.x && heading.z === point.z) {\n\t\t\t// stuck in a crowd is not lost: it tries again, as long as there is a way there\n\t\t\tif (m.status === 'failed' && m.stuck) {\n\t\t\t\tmoveTo(world, entity, point, { groupId: order.groupId, facing: order.init.facing })\n\t\t\t\treturn 'walking'\n\t\t\t}\n\t\t\treturn m.status === 'failed' ? 'failed' : 'arrived'\n\t\t}\n\t\tstate.resume = false\n\t\tstate.heading = { x: point.x, z: point.z }\n\t\tmoveTo(world, entity, point, { groupId: order.groupId, facing: order.init.facing })\n\t\treturn 'walking'\n\t}\n\treturn 'walking'\n}\n\n/** Walk to a point, fighting everything met on the way */\nexport const attackMoveOrder: OrderBehavior<AdvanceState, OrderInits['attackMove']> = {\n\ttype: 'attackMove',\n\tformation: true,\n\twaiting: (order) => order.state.waiting === true,\n\taccepts: (_world, entity, init) => !!entity.get(moving) && !!init.point,\n\tupdate(world, entity, order, dt) {\n\t\tconst result = advance(world, entity, order, order.init.point!, dt)\n\t\treturn result === 'arrived' ? 'done' : result === 'failed' ? 'failed' : 'running'\n\t},\n\tend(world, entity) {\n\t\tdisengage(world, entity)\n\t}\n}\n\n/** The points of a path of the world's map, by name: none for a path it does not have */\nconst pathPoints = (world: World, name: string | undefined): readonly Vec2[] | undefined =>\n\tname === undefined ? undefined : world.map.paths.find((path) => path.name === name)?.points\n\n/**\n * Where along a path a unit sets out from, and which way: away from the end it is nearer to, from the bend after the\n * stretch it stands by. What two sides sent along one lane from its two ends need: each goes towards the other\n */\nfunction setOut(points: readonly Vec2[], at: Vec2, towards?: 'first' | 'last'): { leg: number; step: 1 | -1 } {\n\tconst nearerFirst = hypot(at.x - points[0].x, at.z - points[0].z) <= hypot(at.x - points.at(-1)!.x, at.z - points.at(-1)!.z)\n\tconst step = towards ? (towards === 'last' ? 1 : -1) : nearerFirst ? 1 : -1\n\tlet nearest = 1\n\tlet best = Infinity\n\tfor (let i = 1; i < points.length; i++) {\n\t\tconst a = points[i - 1]\n\t\tconst b = points[i]\n\t\tconst dx = b.x - a.x\n\t\tconst dz = b.z - a.z\n\t\tconst length = dx * dx + dz * dz\n\t\tconst t = length > 0 ? Math.min(Math.max(((at.x - a.x) * dx + (at.z - a.z) * dz) / length, 0), 1) : 0\n\t\tconst d = hypot(at.x - (a.x + dx * t), at.z - (a.z + dz * t))\n\t\tif (d < best) {\n\t\t\tbest = d\n\t\t\tnearest = i\n\t\t}\n\t}\n\t// the bend ahead, the way it goes: the end of its stretch going forwards, the start of it going back\n\treturn { leg: step === 1 ? nearest : nearest - 1, step }\n}\n\n/**\n * Walk along a path of the map, bend after bend, to its far end: away from the end it starts nearer to. Done there.\n * Nothing on the way stops it: a tower defense's invaders, a caravan. With `attackPath`, it fights its way instead\n *\n * @internal\n */\nexport const followPathOrder: OrderBehavior<AlongPath, OrderInits['followPath']> = {\n\ttype: 'followPath',\n\taccepts: (world, entity, init) => !!entity.get(moving) && (pathPoints(world, init.path)?.length ?? 0) >= 2,\n\tstart(world, entity, order) {\n\t\tconst points = pathPoints(world, order.init.path)!\n\t\tObject.assign(order.state, setOut(points, entity.pos, order.init.towards))\n\t\tmoveTo(world, entity, points[order.state.leg])\n\t},\n\tupdate(world, entity, order) {\n\t\tconst points = pathPoints(world, order.init.path)\n\t\tif (!points) return 'failed'\n\t\tconst { state } = order\n\t\tconst status = entity.get(moving)!.status\n\t\tif (status === 'moving') return 'running'\n\t\tif (status === 'failed') {\n\t\t\t// pushed off its way by the crowd: on to the same bend again\n\t\t\tmoveTo(world, entity, points[state.leg])\n\t\t\treturn 'running'\n\t\t}\n\t\tstate.leg += state.step\n\t\tif (state.leg < 0 || state.leg >= points.length) return 'done'\n\t\tmoveTo(world, entity, points[state.leg])\n\t\treturn 'running'\n\t}\n}\n\n/**\n * Go along a path of the map to its far end, fighting everything met on the way, as attack-move does to a point: a\n * lane's minions. Away from the end it starts nearer to; done at the other\n *\n * @internal\n */\nexport const attackPathOrder: OrderBehavior<AlongPath & AdvanceState, OrderInits['attackPath']> = {\n\ttype: 'attackPath',\n\twaiting: (order) => order.state.waiting === true,\n\taccepts: (world, entity, init) => !!entity.get(moving) && (pathPoints(world, init.path)?.length ?? 0) >= 2,\n\tstart(world, entity, order) {\n\t\tObject.assign(order.state, setOut(pathPoints(world, order.init.path)!, entity.pos, order.init.towards))\n\t},\n\tupdate(world, entity, order, dt) {\n\t\tconst points = pathPoints(world, order.init.path)\n\t\tif (!points) return 'failed'\n\t\tconst { state } = order\n\t\tconst result = advance(world, entity, order, points[state.leg], dt)\n\t\tif (result === 'failed') return 'failed'\n\t\tif (result !== 'arrived') return 'running'\n\t\tstate.leg += state.step\n\t\tif (state.leg < 0 || state.leg >= points.length) return 'done'\n\t\t// on to the next bend: what it remembered of the way to the last one is of no use\n\t\tstate.heading = undefined\n\t\treturn 'running'\n\t},\n\tend(world, entity) {\n\t\tdisengage(world, entity)\n\t}\n}\n\n/**\n * Walk a path of the map back and forth, bend after bend, fighting everything met on the way, until told otherwise: a\n * patrol route (`MapObjectOrder`, a map's guard). From the end it starts nearer to, turned back at each end\n *\n * @internal\n */\nexport const patrolPathOrder: OrderBehavior<AlongPath & AdvanceState, OrderInits['patrolPath']> = {\n\ttype: 'patrolPath',\n\twaiting: (order) => order.state.waiting === true,\n\taccepts: (world, entity, init) => !!entity.get(moving) && (pathPoints(world, init.path)?.length ?? 0) >= 2,\n\tstart(world, entity, order) {\n\t\tObject.assign(order.state, setOut(pathPoints(world, order.init.path)!, entity.pos, order.init.towards))\n\t},\n\tupdate(world, entity, order, dt) {\n\t\tconst points = pathPoints(world, order.init.path)\n\t\tif (!points) return 'failed'\n\t\tconst { state } = order\n\t\tconst result = advance(world, entity, order, points[state.leg], dt)\n\t\tif (result === 'failed') return 'failed'\n\t\tif (result !== 'arrived') return 'running'\n\t\t// at an end: back the other way\n\t\tif (state.leg + state.step < 0 || state.leg + state.step >= points.length) state.step = state.step === 1 ? -1 : 1\n\t\tstate.leg += state.step\n\t\tstate.heading = undefined\n\t\treturn 'running'\n\t},\n\tend(world, entity) {\n\t\tdisengage(world, entity)\n\t}\n}\n\n/** Walk back and forth between where the unit stands and a point, fighting everything met on the way, until told otherwise */\nexport const patrolOrder: OrderBehavior<PatrolState, OrderInits['patrol']> = {\n\ttype: 'patrol',\n\tformation: true,\n\taccepts: (_world, entity, init) => !!entity.get(moving) && !!init.point,\n\tstart(_world, entity, order) {\n\t\torder.state.ends = [\n\t\t\t{ x: order.init.point!.x, z: order.init.point!.z },\n\t\t\t{ x: entity.pos.x, z: entity.pos.z }\n\t\t]\n\t\torder.state.leg = 0\n\t\t// which way to look at the end only makes sense for one of the two\n\t\torder.init.facing = undefined\n\t},\n\tupdate(world, entity, order, dt) {\n\t\tconst { state } = order\n\t\tconst result = advance(world, entity, order, state.ends[state.leg], dt)\n\t\tif (result === 'arrived') state.leg = 1 - state.leg\n\t\telse if (result === 'failed') {\n\t\t\t// cannot get there: the other end then, and give up when that is out of reach as well\n\t\t\tif (state.stuck) return 'failed'\n\t\t\tstate.stuck = true\n\t\t\tstate.leg = 1 - state.leg\n\t\t} else if (result === 'walking' && entity.get(moving)!.stalledTime === 0) state.stuck = false\n\t\treturn 'running'\n\t},\n\tend(world, entity) {\n\t\tdisengage(world, entity)\n\t}\n}\n\n/** How far behind a unit stays that follows another */\nconst FOLLOW_DISTANCE = 1.2\n/** And how far the other one has to get away before it starts walking again */\nconst FOLLOW_SLACK = 1.5\n\n/** Stay with a unit wherever it goes, for as long as it lives */\nexport const followOrder: OrderBehavior<FollowState, OrderInits['follow']> = {\n\ttype: 'follow',\n\taccepts(world, entity, init) {\n\t\tconst target = world.get(init.target)\n\t\treturn !!entity.get(moving) && !!target && target !== entity && !!target.get(moving)\n\t},\n\tupdate(world, entity, order) {\n\t\tconst target = world.get(order.init.target)\n\t\tif (!target) return 'done'\n\t\t// inside something: wait in front of it\n\t\tif (target.hidden) return 'running'\n\t\tif (!world.areAllies(entity.owner, target.owner) && !canSee(world, entity, target)) return 'done'\n\t\tconst m = entity.get(moving)!\n\t\tconst away = edgeDistance(entity, target)\n\t\tif (m.status === 'moving') return 'running'\n\t\tif (away > FOLLOW_DISTANCE + FOLLOW_SLACK) {\n\t\t\tif (m.status === 'failed' && order.state.tried === world.tick - 1) return 'failed'\n\t\t\torder.state.tried = world.tick\n\t\t\tmoveToEntity(world, entity, target, FOLLOW_DISTANCE)\n\t\t}\n\t\treturn 'running'\n\t}\n}\n\n/** Attack a spot on the ground, or what stands there, until told otherwise. For attacks that hit an area */\nexport const attackGroundOrder: OrderBehavior<AttackGroundState, OrderInits['attackGround']> = {\n\ttype: 'attackGround',\n\taccepts(world, entity, init) {\n\t\tif (groundAttack(entity.def) < 0 || !entity.get(fighting)) return false\n\t\treturn !!init.point || !!world.get(init.target)\n\t},\n\tstart(world, _entity, order) {\n\t\tconst target = world.get(order.init.target)\n\t\tif (target) order.init.point = { x: target.pos.x, z: target.pos.z }\n\t},\n\tupdate(world, entity, order, dt) {\n\t\tconst { state } = order\n\t\tconst point = order.init.point!\n\t\t// aimed at something: that is gone at some point\n\t\tif (order.init.target && !world.get(order.init.target)) return 'done'\n\t\tif (bombard(world, entity, point, dt) === 'attacking') return 'running'\n\n\t\tconst m = entity.get(moving)\n\t\tif (!m) return 'failed'\n\t\tif (m.status === 'moving') return 'running'\n\t\tif (state.walked) {\n\t\t\tworld.message(entity.owner, engineMessage('cannotReach'))\n\t\t\treturn 'failed'\n\t\t}\n\t\tstate.walked = true\n\t\tdisengage(world, entity)\n\t\tconst range = attackStat(statsOf(world, entity), entity.def.attacks?.[groundAttack(entity.def)], 'range') + entity.def.radius\n\t\t// no closer than it has to, but close enough to be in range for sure\n\t\tmoveTo(world, entity, point, { range: Math.max(range - 0.6, 0.2) })\n\t\treturn 'running'\n\t},\n\tend(world, entity) {\n\t\tdisengage(world, entity)\n\t}\n}\n","import { edgeDistance } from '#engine/entity'\nimport { dropOnGround, findItem, giveItem, pickUp, REACH, takeItem } from '#engine/items'\nimport { freeSlot, inventorySlots } from '#engine/inventory'\nimport { dist } from '#engine/math'\nimport type { OrderBehavior, OrderInits } from '#engine/registry'\nimport { moveTo, moveToEntity } from '#engine/systems/movement'\nimport { engineMessage } from '#engine/messages'\nimport { moving } from '../entity'\n\n/**\n * What the item orders keep: whether they walked to it already\n *\n * @beta\n */\nexport interface ItemOrderState {\n\t/** It walked to it already */\n\twalked?: boolean\n}\n\n/** Walk to an item on the ground and take it */\nexport const pickUpOrder: OrderBehavior<ItemOrderState, OrderInits['pickUp']> = {\n\ttype: 'pickUp',\n\taccepts(world, entity, init) {\n\t\tconst item = world.items.find((i) => i.id === init.item)\n\t\tif (!entity.has(inventorySlots) || !entity.get(moving) || !item) return false\n\t\t// what lies out of sight is not there to be picked up: a screen shows the items in sight alone (on a map explored\n\t\t// from the start, the dark is nowhere)\n\t\treturn world.fog.isVisible(world.player(entity.owner).team, item.x, item.z)\n\t},\n\tupdate(world, entity, order) {\n\t\tconst item = world.items.find((i) => i.id === order.init.item)\n\t\tif (!item) return 'done'\n\t\tconst m = entity.get(moving)!\n\t\tif (dist(entity.pos, item) > REACH) {\n\t\t\tif (m.status === 'moving') return 'running'\n\t\t\tif (order.state.walked && m.status === 'failed') return 'failed'\n\t\t\torder.state.walked = true\n\t\t\tmoveTo(world, entity, item, { range: REACH * 0.7 })\n\t\t\treturn 'running'\n\t\t}\n\t\tif (freeSlot(entity) < 0) {\n\t\t\tworld.message(entity.owner, engineMessage('inventoryFull'))\n\t\t\treturn 'failed'\n\t\t}\n\t\tpickUp(world, entity, item.id)\n\t\treturn 'done'\n\t}\n}\n\n/** Put an item down somewhere, or hand it to someone */\nexport const dropItemOrder: OrderBehavior<ItemOrderState, OrderInits['dropItem']> = {\n\ttype: 'dropItem',\n\taccepts(world, entity, init) {\n\t\tif (!entity.get(moving) || !findItem(entity, init.item)) return false\n\t\tconst target = world.get(init.target)\n\t\tif (init.target) return !!target && target !== entity && target.has(inventorySlots) && world.areAllies(entity.owner, target.owner)\n\t\treturn !!init.point\n\t},\n\tupdate(world, entity, order) {\n\t\tif (!findItem(entity, order.init.item)) return 'done'\n\t\tconst m = entity.get(moving)!\n\t\tconst receiver = order.init.target ? world.get(order.init.target) : undefined\n\t\tif (order.init.target && !receiver) return 'done'\n\n\t\tif (receiver) {\n\t\t\tif (edgeDistance(entity, receiver) > REACH) {\n\t\t\t\tmoveToEntity(world, entity, receiver, REACH * 0.7)\n\t\t\t\treturn m.status === 'failed' ? 'failed' : 'running'\n\t\t\t}\n\t\t\tif (freeSlot(receiver) < 0) {\n\t\t\t\tworld.message(entity.owner, engineMessage('theirInventoryFull'))\n\t\t\t\treturn 'failed'\n\t\t\t}\n\t\t\tgiveItem(world, receiver, takeItem(world, entity, order.init.item!)!)\n\t\t\treturn 'done'\n\t\t}\n\n\t\tif (dist(entity.pos, order.init.point!) > REACH) {\n\t\t\tif (m.status === 'moving') return 'running'\n\t\t\tif (order.state.walked && m.status === 'failed') return 'failed'\n\t\t\torder.state.walked = true\n\t\t\tmoveTo(world, entity, order.init.point!, { range: REACH * 0.7 })\n\t\t\treturn 'running'\n\t\t}\n\t\tconst held = findItem(entity, order.init.item)\n\t\tif (held && world.hooks.has('beforeDrop')) {\n\t\t\tconst before = world.hooks.run('beforeDrop', { entity, item: held, cancelled: false })\n\t\t\tif (before.cancelled) {\n\t\t\t\tif (before.reason) world.message(entity.owner, before.reason)\n\t\t\t\treturn 'failed'\n\t\t\t}\n\t\t}\n\t\tdropOnGround(world, takeItem(world, entity, order.init.item!)!, order.init.point!)\n\t\treturn 'done'\n\t}\n}\n","/**\n * One kind of definition of a game's, by key (`Definitions`): its unit types, its abilities, its buffs... What every\n * kind of a registry is, so that each is defined, found, listed and replaced the one way, and a tool that walks every\n * kind (the Data panel, mods, saves) walks one list (`Registry.kinds`)\n */\n\n/**\n * The definitions of one kind, by key: in the order they were defined, one of a key defined again in the place of the\n * one before it\n *\n * @beta\n */\nexport class Definitions<T> {\n\tprivate readonly byKey = new Map<string, T>()\n\n\tconstructor(\n\t\t/** What one is called, for what is said of one there is not: `unit type`, `ability` */\n\t\treadonly kind: string,\n\t\t/** Its key: the id, or an order's or a command's type */\n\t\tprivate readonly keyOf: (def: T) => string = (def) => (def as { id: string }).id,\n\t\t/** What a definition must be to be taken: throws for one that is not */\n\t\tprivate readonly check?: (def: T) => void\n\t) {}\n\n\t/** Takes a definition, in the place of the one of its key where there is one */\n\tdefine(def: T): this {\n\t\tthis.check?.(def)\n\t\tthis.byKey.set(this.keyOf(def), def)\n\t\treturn this\n\t}\n\n\t/** Takes the definition of a key out: false for one there is not */\n\tremove(key: string): boolean {\n\t\treturn this.byKey.delete(key)\n\t}\n\n\t/** The definition of a key: throws for one there is not */\n\tget(key: string): T {\n\t\tconst def = this.byKey.get(key)\n\t\tif (def === undefined) throw new Error(`Unknown ${this.kind} \"${key}\"`)\n\t\treturn def\n\t}\n\n\t/** The definition of a key, or nothing for one there is not */\n\tfind(key: string): T | undefined {\n\t\treturn this.byKey.get(key)\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.byKey.has(key)\n\t}\n\n\t/** Every definition, in the order they were defined */\n\tall(): T[] {\n\t\treturn [...this.byKey.values()]\n\t}\n\n\t/** Every key, in the order they were defined */\n\tkeys(): string[] {\n\t\treturn [...this.byKey.keys()]\n\t}\n\n\tget size(): number {\n\t\treturn this.byKey.size\n\t}\n\n\t/** Takes another's definitions over its own: those it has that the other has not are kept */\n\ttakeFrom(other: Definitions<T>): void {\n\t\tfor (const [key, def] of other.byKey) this.byKey.set(key, def)\n\t}\n}\n","import type { AdvanceState, AlongPath, AttackGroundState, AttackState, FollowState, HoldState, PatrolState } from './orders/basic'\nimport type { GameFileDef } from './gameFiles'\nimport type { ReplicatedEvent, SnapshotPart } from './replication'\nimport { DATA_KINDS, type DataDefs, type DataKind } from './gameData'\nimport { Definitions } from './definitions'\nimport type { BuildState, RepairState, WorkState } from './orders/build'\nimport type { CastState } from './orders/cast'\nimport type { HarvestState } from './orders/harvest'\nimport type { ItemOrderState } from './orders/items'\nimport type { BoardState, LoadState, UnloadState } from './transport'\nimport type { RaceDef } from './races'\nimport type { Logger } from './log'\nimport type { Component } from './components'\nimport { type EventKey, eventById } from './events'\nimport type { EffectHandler, EffectKind } from './abilities/effects'\nimport type { CommandDef } from './commands'\nimport {\n\ttype AbilityDef,\n\ttype BuffDef,\n\tCORE_STAT_KEYS,\n\ttype DayCycle,\n\ttype ItemDef,\n\tnoStats,\n\ttype ResourceDef,\n\ttype ResourceKind,\n\ttype StatDef,\n\ttype Stats,\n\ttype UnitTypeDef,\n\ttype UpgradeDef,\n\ttype UpkeepTier\n} from './defs'\nimport type { Entity, EntityId, Order, PlayerId } from './entity'\nimport type { Vec2 } from './math'\nimport type { StatPart } from './stats'\nimport type { FormationDef } from './formation'\nimport type { AssembledGame, GameModule } from './game'\nimport { gameHash } from './mods'\nimport { defaultRules, type GameRules } from './rules'\nimport type { TileDef } from './tiles'\nimport type { PrefabDef } from './prefabs'\nimport type { TunableDef } from './tunables'\nimport type { World } from './world'\nimport type { CellLayerDef } from './cellLayers'\nimport type { ResolvedScore } from './score'\n\n/** @beta */\nexport type OrderStatus = 'running' | 'done' | 'failed'\n\n/**\n * What an order can be given, every order's field in one: for what reads an order of any type (the queue, a save, a\n * screen's waypoints). An order of a type is given its own of them (`OrderInits`)\n *\n * @beta\n */\nexport interface OrderParams {\n\ttarget?: EntityId\n\tpoint?: Vec2\n\t/** Type to build, for build orders */\n\tunitType?: string\n\t/** Ability to use, for cast orders */\n\tability?: string\n\t/** An item: the one to use, drop or hand over by its place in the inventory, or the one on the ground to pick up */\n\titem?: number\n\t/** Direction to face at the end. Commands fill this in with the direction of travel */\n\tfacing?: number\n\t/**\n\t * For a move: the group goes at the pace of its slowest (campaign plan GP1), so that it arrives together. The\n\t * command works the pace out (`speedCap`)\n\t */\n\ttogether?: boolean\n\t/** For a move: the fastest it goes, set by the command for a group that goes `together`: the slowest one's speed */\n\tspeedCap?: number\n\t/** A path of the map, by its name (`MapPath`): for the orders that go along one (`followPath`, `attackPath`) */\n\tpath?: string\n\t/**\n\t * Which way along `path`: to its first point or its last. Away from the end the unit is nearer to when left out: a\n\t * minion back on its lane after a chase, past its middle, goes on the way it was going\n\t */\n\ttowards?: 'first' | 'last'\n}\n\n/**\n * What each order type is given (`Order.init`), by type (design review E14): the engine's, and a game's own added by\n * declaration merging, as `OrderStates` is:\n *\n * ```ts\n * declare module '@v12-engine/engine' {\n * \tinterface OrderInits {\n * \t\t'mygame.dig': { point?: Vec2 }\n * \t}\n * }\n * ```\n *\n * Every field may be missing from what a command sends, which comes from a player: the behaviour's `accepts` checks\n * what it needs\n *\n * @beta\n */\nexport interface OrderInits {\n\tmove: Pick<OrderParams, 'point' | 'facing' | 'target' | 'together' | 'speedCap'>\n\thold: Pick<OrderParams, 'facing'>\n\tattack: Pick<OrderParams, 'target' | 'facing'>\n\tattackMove: Pick<OrderParams, 'point' | 'facing'>\n\tfollowPath: Pick<OrderParams, 'path' | 'towards'>\n\tattackPath: Pick<OrderParams, 'path' | 'towards'>\n\tpatrolPath: Pick<OrderParams, 'path' | 'towards'>\n\tpatrol: Pick<OrderParams, 'point' | 'facing'>\n\tfollow: Pick<OrderParams, 'target'>\n\tattackGround: Pick<OrderParams, 'point' | 'target'>\n\tcast: Pick<OrderParams, 'ability' | 'item' | 'target' | 'point'>\n\tharvest: Pick<OrderParams, 'target'>\n\treturn: Pick<OrderParams, 'target'>\n\tbuild: Pick<OrderParams, 'unitType' | 'point' | 'facing'>\n\tconstruct: Pick<OrderParams, 'target'>\n\trepair: Pick<OrderParams, 'target'>\n\tpickUp: Pick<OrderParams, 'target' | 'item'>\n\tdropItem: Pick<OrderParams, 'item' | 'point' | 'target'>\n\tboard: Pick<OrderParams, 'target'>\n\tload: Pick<OrderParams, 'target'>\n\tunload: Pick<OrderParams, 'point'>\n}\n\n/**\n * What an order of a type is given: its `OrderInits` entry, every order's fields (`OrderParams`) for a type not in it\n *\n * @beta\n */\nexport type OrderInitOf<Type extends string> = Type extends keyof OrderInits ? OrderInits[Type] : OrderParams\n\n/**\n * What a command asks a unit to do: the order's type and what it is given (`OrderInitOf`). Turned into an `Order` once\n * it is accepted\n *\n * @beta\n */\nexport type OrderInit<Type extends string = string> = {\n\ttype: Type\n\t/**\n\t * The formation units ordered to a point together take, by id (`FormationDef`): the engine's `rows`, `circle`,\n\t * `square` or `none`, or a game's own. What the rules say (`GameRules.movement.formation`: `rows`) when left out\n\t */\n\tformation?: string\n} & OrderInitOf<Type>\n\n/**\n * Logic behind an order type. Orders are the only way units act, which is what\n * makes queueing work for everything. Game modules can register their own.\n *\n * `State` is what it keeps in the order (`Order.state`), every field optional: the order starts with none of them.\n * `OrderStates` names each order type's, for `registry.order(type)` to hand back the behaviour typed\n *\n * @beta\n */\nexport interface OrderBehavior<State extends object = Record<string, any>, Init extends object = OrderParams> {\n\ttype: string\n\t/** Units ordered to a point together are spread out in a formation instead of all walking to the same spot */\n\tformation?: boolean\n\t/** Whether the entity is able to carry out this order at all */\n\taccepts(world: World, entity: Entity, init: Init): boolean\n\t/** Called once when the order reaches the front of the queue */\n\tstart?(world: World, entity: Entity, order: Order<State, Init>): void\n\tupdate(world: World, entity: Entity, order: Order<State, Init>, dt: number): OrderStatus\n\t/** Called when the order finishes or is interrupted, to undo anything it left behind */\n\tend?(world: World, entity: Entity, order: Order<State, Init>): void\n\t/**\n\t * Whether the unit is in the middle of it and cannot be called away (a cast past turning back): what was to come\n\t * after is dropped, it is finished first (`interrupt`). Never, when left out\n\t */\n\tcommitted?(order: Order<State, Init>): boolean\n\t/**\n\t * Whether the unit stands waiting by a fight for a spot in it (an attack-move held up): an ally on its way may ask it\n\t * aside (`rules.movement.makesWay`). Never, when left out\n\t */\n\twaiting?(order: Order<State, Init>): boolean\n\t/** Whether the unit keeps something up that being stunned breaks off (a channelled ability). Never, when left out */\n\tchannelling?(order: Order<State, Init>): boolean\n\t/** Whether the unit has begun what it builds (its site is down): what it builds is counted as itself. Never, when left out */\n\tbuilding?(order: Order<State, Init>): boolean\n}\n\n/**\n * A fact the engine asks of an order, its behaviour's to say (`OrderBehavior.committed`, `waiting`, `channelling`,\n * `building`)\n *\n * @beta\n */\nexport type OrderFact = 'committed' | 'waiting' | 'channelling' | 'building'\n\n/**\n * What each order type keeps in its orders (`Order.state`), by type: the engine's, and a game's own added to it by\n * declaration merging, for `registry.order(type)` to say what its behaviour keeps:\n *\n * ```ts\n * declare module '@v12-engine/engine' {\n * \tinterface OrderStates {\n * \t\t'mygame.dig': { dug?: number }\n * \t}\n * }\n * ```\n *\n * @beta\n */\nexport interface OrderStates {\n\tmove: NoState\n\thold: HoldState\n\tattack: AttackState\n\tattackMove: AdvanceState\n\tfollowPath: AlongPath\n\tattackPath: AlongPath & AdvanceState\n\tpatrol: PatrolState\n\tfollow: FollowState\n\tattackGround: AttackGroundState\n\tcast: CastState\n\tharvest: HarvestState\n\treturn: HarvestState\n\tbuild: BuildState\n\tconstruct: WorkState\n\trepair: RepairState\n\tpickUp: ItemOrderState\n\tdropItem: ItemOrderState\n\tboard: BoardState\n\tload: LoadState\n\tunload: UnloadState\n}\n\n/**\n * What an order that keeps nothing keeps\n *\n * @beta\n */\nexport type NoState = Record<string, never>\n\n/**\n * What an order of a type keeps: its `OrderStates` entry, any plain data for a type not in it\n *\n * @beta\n */\nexport type OrderStateOf<Type extends string> = Type extends keyof OrderStates ? OrderStates[Type] : Record<string, any>\n\n/**\n * The part of a tick a system runs in, see `PHASES` in the scheduler\n *\n * @beta\n */\nexport type SystemPhase = 'commands' | 'decide' | 'move' | 'resolve' | 'cleanup'\n\n/**\n * Something that runs every tick, or every few: moves units, lands attacks, works out what each team sees.\n * When it runs is worked out once, from its phase, then from what it says it comes before and after.\n *\n * @beta\n */\nexport interface System {\n\t/** Unique in a world. A game's system with the name of a core one takes its place */\n\tname: string\n\t/** `cleanup` when left out: after everything else in the tick */\n\tphase?: SystemPhase\n\t/** Names of systems in the same phase this one runs ahead of, or after */\n\tbefore?: string[]\n\tafter?: string[]\n\t/** Runs once in so many ticks, for work that does not need doing every tick. Every tick when left out */\n\tevery?: number\n\t/** With `every`, the tick in each round it runs at: systems with the same `every` and other offsets spread the work */\n\toffset?: number\n\t/**\n\t * `dt` is the time since it last ran: the length of a tick, times `every`. Before `each`, for a system that has\n\t * both. One of the two is needed\n\t */\n\tupdate?(world: World, dt: number): void\n\t/**\n\t * What `each` is run for (OB5): every actor (`'actors'`, when left out), what has a component, in the order of its\n\t * id as a walk through the actors would meet it (`EntityIndex.ordered`: a system about a few, like the buildings\n\t * that train, does not look at every unit and tree), or the actors a test says yes to\n\t *\n\t * @beta\n\t */\n\tover?: SystemOver\n\t/**\n\t * Run for each entity of `over`, in order, after `update`. The dead are not left out: a system that wants only the\n\t * living says so\n\t *\n\t * @beta\n\t */\n\teach?(world: World, entity: Entity, dt: number): void\n\t/**\n\t * What it keeps in itself, for a save: plain data. For state that is easier kept in a system than in a component\n\t * (`World.state`): a computer player's plans, a director's mood\n\t */\n\tsave?(world: World): unknown\n\t/** Takes back what `save` gave, in a world loaded from a save: when it is made, or added again (`addSystem`) */\n\trestore?(world: World, data: unknown): void\n}\n\n/**\n * What a system runs `each` for (`System.over`): every actor, what has a component, or the actors a test says yes to\n *\n * @beta\n */\nexport type SystemOver = 'actors' | Component<unknown, unknown> | ((entity: Entity, world: World) => boolean)\n\n/**\n * A system, or what makes one for each world: for a system that keeps state of its own, which belongs to one game\n *\n * @beta\n */\nexport type SystemDef = System | ((world: World) => System)\n\n/** What the engine's own ids start with */\nconst CORE = 'core.'\n\n/**\n * What is thrown for a component or an event of its own that a game uses without listing it (`GameModule.components`,\n * `GameModule.events`): no world finds it by its id, so a save, a snapshot or the index would lose it\n *\n * @beta\n */\nexport class UnlistedError extends Error {\n\tconstructor(\n\t\t/** What it is: a component or an event */\n\t\treadonly kind: 'component' | 'event',\n\t\t/** Its id */\n\t\treadonly id: string,\n\t\t/** The id of the game that used it */\n\t\treadonly game: string\n\t) {\n\t\tsuper(\n\t\t\t`The ${kind} \"${id}\" is used by the game \"${game}\" without being listed in it: add it to GameModule.${kind}s, as its timers and listeners are`\n\t\t)\n\t\tthis.name = 'UnlistedError'\n\t}\n}\n\n/** A list's entries by id, with their place: worked out once a list (`tile`, `resource`, `tunable` are asked every tick) */\nconst indexes = new WeakMap<readonly { id: string }[], Map<string, { def: never; at: number }>>()\nfunction indexOf<T extends { id: string }>(list: readonly T[]): Map<string, { def: T; at: number }> {\n\tlet index = indexes.get(list)\n\tif (!index) indexes.set(list, (index = new Map(list.map((def, at) => [def.id, { def: def as never, at }]))))\n\treturn index as Map<string, { def: T; at: number }>\n}\n\n/** @beta */\nexport class Registry {\n\t/** The game's unit types, buildings and resources (`GameModule.units`) */\n\treadonly units = new Definitions<UnitTypeDef>('unit type', undefined, (def) => {\n\t\tif (def.kind !== 'unit' && !def.footprint) throw new Error(`Unit type \"${def.id}\" needs a footprint`)\n\t})\n\t/** The orders units can be given, the engine's and the game's, by type */\n\treadonly orders = new Definitions<OrderBehavior>('order type', (behavior) => behavior.type)\n\t/** How groups line up (`GameModule.formations`) */\n\treadonly formations = new Definitions<FormationDef>('formation')\n\t/** The game's research (`GameModule.upgrades`) */\n\treadonly upgrades = new Definitions<UpgradeDef>('upgrade')\n\t/** Every ability there is, of units, heroes and items alike (`GameModule.abilities`) */\n\treadonly abilities = new Definitions<AbilityDef>('ability')\n\t/** The game's buffs (`GameModule.buffs`) */\n\treadonly buffs = new Definitions<BuffDef>('buff')\n\t/** The game's items (`GameModule.items`) */\n\treadonly items = new Definitions<ItemDef>('item')\n\t/** The game's races, in its order (`GameModule.races`): none in a game without */\n\treadonly races = new Definitions<RaceDef>('race')\n\t/** The game's prefabs (`GameModule.prefabs`) */\n\treadonly prefabs = new Definitions<PrefabDef>('prefab')\n\t/** The commands a world takes, the engine's and the game's, by type */\n\treadonly commands = new Definitions<CommandDef>('command', (def) => def.type)\n\t/** What each type of an ability's effect does, by type */\n\treadonly effects = new Definitions<EffectKind>('effect type', (effect) => effect.type)\n\t/**\n\t * The kinds of definition a game's data is kept for (`DataKind`), each its collection: what the Data panel, mods,\n\t * saves and a game's reload walk, one loop each\n\t */\n\treadonly kinds: { readonly [K in DataKind]: Definitions<DataDefs[K]> } = {\n\t\tunits: this.units,\n\t\tabilities: this.abilities,\n\t\tbuffs: this.buffs,\n\t\titems: this.items,\n\t\tupgrades: this.upgrades,\n\t\traces: this.races\n\t}\n\t/** The components the game lists (`GameModule.components`), and those its app keeps in its worlds, by id */\n\tprivate readonly components = new Map<string, Component<unknown>>()\n\t/** The engine's own components (`coreComponents`) and the listed, by id: what `component` finds, in one look */\n\tprivate readonly known = new Map<string, Component<unknown>>()\n\t/** The events of its own the game lists (`GameModule.events`), by id */\n\tprivate readonly events = new Map<string, EventKey<unknown>>()\n\n\t/**\n\t * Takes in the engine's own components, which every game has (`coreComponents`)\n\t *\n\t * @internal\n\t */\n\tdefineCore(components: readonly Component<unknown>[]): void {\n\t\tfor (const component of components) if (!this.components.has(component.id)) this.known.set(component.id, component)\n\t}\n\n\t/** Takes in the components and events a game lists. Throws for an id that is there twice, another way */\n\tdefineParts(components: readonly Component<unknown>[], events: readonly EventKey<unknown>[]): void {\n\t\tfor (const component of components) {\n\t\t\tconst before = this.components.get(component.id)\n\t\t\tif (before && before !== component) throw new Error(`The component \"${component.id}\" is there twice`)\n\t\t\tthis.components.set(component.id, component)\n\t\t\tthis.known.set(component.id, component)\n\t\t}\n\t\tfor (const event of events) {\n\t\t\tconst before = this.events.get(event.id)\n\t\t\tif (before && before !== event) throw new Error(`The event \"${event.id}\" is there twice`)\n\t\t\tthis.events.set(event.id, event)\n\t\t}\n\t}\n\n\t/** A component of this game by its id: one the game lists, or one of the engine's own (`coreComponents`). None for any other */\n\tcomponent(id: string): Component<unknown> | undefined {\n\t\treturn this.known.get(id)\n\t}\n\n\t/** A component of this game by its id, as something of the world uses it: throws for one the game does not list (`UnlistedError`) */\n\tused(id: string): Component<unknown> {\n\t\tconst found = this.component(id)\n\t\tif (!found) throw new UnlistedError('component', id, this.game)\n\t\treturn found\n\t}\n\n\t/**\n\t * An event of the game's own by its id: listed, or the engine's (`core.`). One of a game's that it does not list\n\t * throws (`UnlistedError`)\n\t */\n\tevent(id: string): EventKey<unknown> | undefined {\n\t\tconst listed = this.events.get(id)\n\t\tif (listed) return listed\n\t\tconst known = eventById(id)\n\t\tif (known && !id.startsWith(CORE)) throw new UnlistedError('event', id, this.game)\n\t\treturn known\n\t}\n\n\t/**\n\t * The components the game lists, for what goes through them all: the map's fields they have\n\t *\n\t * @beta\n\t */\n\tlistedComponents(): Iterable<Component<unknown, unknown>> {\n\t\treturn this.components.values()\n\t}\n\n\t/** Whether the game lists a component or an event, or it is one of the engine's own */\n\tlists(kind: 'component' | 'event', id: string): boolean {\n\t\treturn kind === 'component' ? this.known.has(id) : id.startsWith(CORE) || this.events.has(id)\n\t}\n\n\t/** The log of the world this is the registry of, once there is one (`World.log`) */\n\tlog?: Logger\n\n\t/**\n\t * Takes the definitions of another registry of the same game over its own (`world.reload`): its unit types,\n\t * abilities, buffs, items, upgrades and races, the code of its effects and orders, its rules, and its module. Those\n\t * it has that the other has not are kept (a world may have units of them). What the game is made of otherwise (its\n\t * resources, stats, components, events) stays as it is: a world was made of it\n\t */\n\ttakeFrom(other: Registry): void {\n\t\tfor (const kind of DATA_KINDS) (this.kinds[kind] as Definitions<unknown>).takeFrom(other.kinds[kind] as Definitions<unknown>)\n\t\tthis.effects.takeFrom(other.effects)\n\t\tthis.orders.takeFrom(other.orders)\n\t\tthis.formations.takeFrom(other.formations)\n\t\tthis.rules = other.rules\n\t\tthis.score = other.score\n\t\tthis.day = other.day\n\t\tthis.report = other.report\n\t\tthis.tunables = other.tunables\n\t\tthis.files = new Map(other.files)\n\t\tthis.fileDefs = new Map(other.fileDefs)\n\t\tthis.upkeep = other.upkeep\n\t\tthis.module = other.module\n\t\t// what identifies the game is worked out again, of the module as it is now\n\t\tthis.hashed = this.dataHashed = undefined\n\t}\n\n\t/** Lowest threshold first. Empty for a game without upkeep */\n\tupkeep: UpkeepTier[] = []\n\t/** Id of the game module it was made from */\n\tgame = ''\n\t/** The game module it was made from */\n\tmodule: GameModule | null = null\n\tprivate hashed?: string\n\n\t/** What identifies the game exactly, mods and code included (see `gameHash`). Worked out the first time it is asked for */\n\tget hash(): string {\n\t\treturn (this.hashed ??= this.module ? gameHash(this.module) : '')\n\t}\n\n\tprivate dataHashed?: string\n\n\t/**\n\t * What identifies the game's data: everything but how its code reads (see `gameHash`). What a server and a player\n\t * check they share: the two run builds of the same code that print it differently\n\t */\n\tget dataHash(): string {\n\t\treturn (this.dataHashed ??= this.module ? gameHash(this.module, { code: false }) : '')\n\t}\n\n\t/** The version of what the game keeps in a save (`GameModule.saves.version`): 1 for a game that says none */\n\tget saveVersion(): number {\n\t\treturn this.module?.saves?.version ?? 1\n\t}\n\t/** The game's own stats, next to the engine's (`GameModule.stats`) */\n\tstats: StatDef[] = []\n\t/** The game put together with its packs (`assembleGame`): set as the registry is made of it */\n\tassembly: AssembledGame | null = null\n\t/** The engine's parts and the game's that give an entity something as it is made (`Component.onSpawn`), in order */\n\tspawning: readonly Component<unknown, unknown>[] = []\n\t/** The engine's parts and the game's that call something off as an entity leaves its owner (`Component.onLeave`) */\n\tleaving: readonly Component<unknown, unknown>[] = []\n\t/** The engine's parts and the game's that may have a structure stand open, in nobody's way (`Component.passable`) */\n\tpassing: readonly Component<unknown, unknown>[] = []\n\t/** Whether a structure stands open now, in nobody's way, by its parts (`Component.passable`): a gate opened */\n\tstandsOpen(entity: Entity): boolean {\n\t\tfor (const part of this.passing) if (entity.has(part) && part.passable!(entity.get(part)!, entity)) return true\n\t\treturn false\n\t}\n\t/** What the game's packs add to a unit's stats (`GamePack.stats`): a hero's growth */\n\tstatParts: StatPart[] = []\n\t/** How each event of the world is told to a player, the engine's then the packs' (`replicateEvent`), in order */\n\treplications: readonly ReplicatedEvent[] = []\n\t/** The parts of a player's snapshot, the engine's then the packs' (`SnapshotPart`), in order */\n\tsnapshotParts: readonly SnapshotPart[] = []\n\t/** What the game counts of its players (`GameRules.score`), its stats made: null for a game that counts nothing */\n\tscore: ResolvedScore | null = null\n\t/** What each of the game's own files was read as (`GameModule.files`), by id */\n\tprivate files = new Map<string, unknown>()\n\t/** The game's own files (`GameModule.files`), by id */\n\tprivate fileDefs = new Map<string, GameFileDef<unknown>>()\n\n\t/** What the rules read of a file of the game's own data (`GameModule.files`): throws for one the game does not list */\n\tfile<T>(def: GameFileDef<T>): T {\n\t\tif (!this.files.has(def.id)) throw new Error(`The file \"${def.id}\" is not the game's: list it in GameModule.files`)\n\t\treturn this.files.get(def.id) as T\n\t}\n\n\t/** Puts what a file of the game's is read as, for this registry's world alone: the editor's panel, as it is edited */\n\tsetFile<T>(def: GameFileDef<T>, value: T): void {\n\t\tthis.files.set(def.id, value)\n\t\tthis.fileDefs.set(def.id, def as GameFileDef<unknown>)\n\t}\n\n\t/** A file of the game's own data by its id (`waves.json`): what reads it, for an editor that writes it. None for one the game does not list */\n\tfileDef(id: string): GameFileDef<unknown> | undefined {\n\t\treturn this.fileDefs.get(id)\n\t}\n\n\t/** A prefab of the game's by id, for `world.spawnPrefab`; throws for one there is not */\n\tprefab(id: string): PrefabDef {\n\t\tconst def = this.prefabs.find(id)\n\t\tif (!def) throw new Error(`No prefab is called \"${id}\": list it in GameModule.prefabs, or give the prefab itself`)\n\t\treturn def\n\t}\n\n\t/** What the ground can be painted with, in the order of their indices: the first is 1 (`GameModule.tiles`) */\n\ttiles: TileDef[] = []\n\t/** The game's layers of cells (`GameModule.cellLayers`): what `Terrain.cells` is keyed by, with what each means */\n\tcellLayers: CellLayerDef[] = []\n\t/** The numbers of the rules to be tuned while the game plays (`GameModule.tunables`) */\n\ttunables: TunableDef[] = []\n\n\t/** A tunable by id, or nothing for one the game does not have */\n\ttunable(id: string): TunableDef | undefined {\n\t\treturn indexOf(this.tunables).get(id)?.def\n\t}\n\n\t/** The index of a tile of the game, for painting the ground in code: `terrain.tiles[cell] = registry.tile('road')` */\n\ttile(id: string): number {\n\t\tconst found = indexOf(this.tiles).get(id)\n\t\tif (!found) throw new Error(`Unknown tile \"${id}\"`)\n\t\treturn found.at + 1\n\t}\n\n\t/** The ids of the game's tiles, in the order of their indices */\n\tget tileIds(): string[] {\n\t\treturn this.tiles.map((tile) => tile.id)\n\t}\n\t/** Every stat there is in the game, the engine's first */\n\tstatKeys: string[] = [...CORE_STAT_KEYS]\n\t/** Every stat of the game at 0, its own at their default: what base stats start from */\n\tstatDefaults: Readonly<Stats> = noStats() as Stats\n\t/** The game's numbers that are not about any one unit (`GameModule.rules`) */\n\trules: Readonly<GameRules> = defaultRules\n\t/** Null for a game where it is always day */\n\tday: DayCycle | null = null\n\t/** What the game tells each player about itself, see `GameModule.report`. Asked by the session that runs the world */\n\treport: ((world: World, player: PlayerId) => Record<string, unknown>) | null = null\n\t/** The resources of the game, in the order players are shown them */\n\tresources: ResourceDef[] = []\n\t/**\n\t * The resource prices, bounties, revives and sales are in: the game's money. Null for a game without one,\n\t * where there is nothing of that kind to pay with\n\t */\n\tcurrency: ResourceKind | null = null\n\t/** The command type, or undefined for one the game does not have: commands come from outside, and may name anything */\n\tcommand(type: string): CommandDef | undefined {\n\t\treturn this.commands.find(type)\n\t}\n\n\t/** The definition of a resource, or undefined for one the game does not have */\n\tresource(id: ResourceKind): ResourceDef | undefined {\n\t\treturn indexOf(this.resources).get(id)?.def\n\t}\n\n\t/** A unit type by id: throws for one the game does not have (`units`) */\n\tunit(id: string): UnitTypeDef {\n\t\treturn this.units.get(id)\n\t}\n\n\t/** An upgrade by id: throws for one the game does not have (`upgrades`) */\n\tupgrade(id: string): UpgradeDef {\n\t\treturn this.upgrades.get(id)\n\t}\n\n\t/** A race by id: throws for one the game does not have (`races`) */\n\trace(id: string): RaceDef {\n\t\treturn this.races.get(id)\n\t}\n\n\t/** An ability by id: throws for one the game does not have (`abilities`) */\n\tability(id: string): AbilityDef {\n\t\treturn this.abilities.get(id)\n\t}\n\n\t/** A buff by id: throws for one the game does not have (`buffs`) */\n\tbuff(id: string): BuffDef {\n\t\treturn this.buffs.get(id)\n\t}\n\n\t/** An item by id: throws for one the game does not have (`items`) */\n\titem(id: string): ItemDef {\n\t\treturn this.items.get(id)\n\t}\n\n\t/** What an effect type does: throws for one there is not (`effects`) */\n\teffect(type: string): EffectHandler {\n\t\treturn this.effects.get(type).run as EffectHandler\n\t}\n\n\t/** An order type's behaviour, typed by what its orders keep (`OrderStates`): throws for one there is not (`orders`) */\n\torder<Type extends string>(type: Type): OrderBehavior<OrderStateOf<Type>, OrderInitOf<Type>> {\n\t\treturn this.orders.get(type) as unknown as OrderBehavior<OrderStateOf<Type>, OrderInitOf<Type>>\n\t}\n\n\t/** A formation by id: throws for one there is not (`formations`) */\n\tformation(id: string): FormationDef {\n\t\treturn this.formations.get(id)\n\t}\n}\n","import { buffRemoved } from '#engine/engineEvents'\nimport { inventorySlots, slotsOf } from '#engine/inventory'\nimport { constructionSite } from './construction'\nimport { AURA_LINGER, applyBuff, fullShield, hasBuff, isRooted, isStunned } from '#engine/abilities/buffs'\nimport { shopStock } from '#engine/items'\nimport { updateDashes, updateLingering, updateMissiles } from '#engine/abilities/effects'\nimport { buffEffects, buffEnded } from '#engine/abilities/land'\nimport { refillUses } from '#engine/abilities/charges'\nimport { type AbilityDef, at, passiveEffects } from '#engine/defs'\nimport { edgeDistance, type Entity } from '#engine/entity'\nimport { castRange, notReady, validTarget } from '#engine/orders/cast'\nimport { createOrder, giveOrder } from '#engine/orders/queue'\nimport type { System } from '#engine/registry'\nimport { refreshVitals, statsOf } from '#engine/stats'\nimport type { World } from '#engine/world'\nimport { canSee } from './combat'\nimport { moving, fighting } from '../entity'\n\n/** Ticks between two rounds of upkeep: auras and autocast do not need to run every tick */\nconst UPKEEP_INTERVAL = 6\n/** How far beyond the reach of an ability a unit looks for something to autocast on */\nconst AUTOCAST_SEARCH = 3\n\nconst found: Entity[] = []\n\n/** Marks the buff a unit's ability keeps up on another (or itself) as kept, not timed: what a plate shows of it */\nfunction keptUp(target: Entity, buff: string, source: Entity): void {\n\tfor (const instance of target.buffs) if (instance.id === buff && instance.source === source.id && !instance.kept) instance.kept = true\n}\n\n/** What one ability does all the time, for one round */\nfunction upkeep(world: World, entity: Entity, ability: AbilityDef, level: number, lasting: boolean): void {\n\tfor (const effect of passiveEffects(ability)) {\n\t\tif (effect.type === 'buff') {\n\t\t\t// renewed rather than left alone, so that it follows the level of the ability. What an item gives goes with the item\n\t\t\tif (effect.buff) {\n\t\t\t\tapplyBuff(world, entity, effect.buff, lasting ? Infinity : AURA_LINGER, entity, level)\n\t\t\t\tif (!lasting) keptUp(entity, effect.buff, entity)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif (effect.type !== 'aura') {\n\t\t\t// whatever else a game came up with: it is asked every round. `onHit` has nothing to do here\n\t\t\tconst point = { x: entity.pos.x, z: entity.pos.z }\n\t\t\tworld.registry.effect(effect.type)({ world, caster: entity, ability, level, point, interval: UPKEEP_INTERVAL * world.dt }, effect)\n\t\t\tcontinue\n\t\t}\n\t\tconst radius = at(effect.radius, level)\n\t\tif (!effect.buff || !radius) continue\n\t\tconst affects = effect.affects ?? (world.registry.buff(effect.buff).harmful ? 'enemies' : 'allies')\n\t\tfor (const other of world.spatial.query(entity.pos.x, entity.pos.z, radius, found)) {\n\t\t\tif (!other.alive || other.hidden || !other.isUnit) continue\n\t\t\tif (other !== entity && edgeDistance(entity, other) > radius) continue\n\t\t\tif (affects === 'enemies' && !world.areEnemies(entity.owner, other.owner)) continue\n\t\t\tif (affects === 'allies' && !world.areAllies(entity.owner, other.owner)) continue\n\t\t\tapplyBuff(world, other, effect.buff, AURA_LINGER, entity, level)\n\t\t\tkeptUp(other, effect.buff, entity)\n\t\t}\n\t}\n}\n\nfunction upkeepPassives(world: World, entity: Entity): void {\n\tfor (const state of entity.abilities) {\n\t\tif (state.level > 0) upkeep(world, entity, world.registry.ability(state.id), state.level, true)\n\t}\n\tfor (const instance of slotsOf(entity) ?? []) {\n\t\tconst passive = instance && world.registry.item(instance.item).passive\n\t\tif (passive) upkeep(world, entity, world.registry.ability(passive), 1, false)\n\t}\n}\n\n/** Whether casting the ability on the target would do it any good */\nfunction useful(ability: AbilityDef, level: number, target: Entity): boolean {\n\tfor (const effect of ability.effects) {\n\t\tif (effect.type === 'heal' && target.hp <= target.maxHp - Math.min(at(effect.amount, level), target.maxHp * 0.1)) return true\n\t\tif (effect.type === 'buff' && effect.buff && !hasBuff(target, effect.buff)) return true\n\t\tif (effect.type === 'damage') return true\n\t}\n\treturn false\n}\n\nfunction autocast(world: World, entity: Entity): void {\n\tif (entity.orders.length > 0 || entity.hidden || entity.get(fighting)?.passive) return\n\tfor (const state of entity.abilities) {\n\t\tif (!state.autocast || state.cooldown > 0 || state.charges === 0 || state.level < 1) continue\n\t\tconst ability = world.registry.ability(state.id)\n\t\t// the game's own way: where to use it now, for any kind of ability\n\t\tif (ability.autoAim) {\n\t\t\tif (notReady(world, entity, ability)) continue\n\t\t\tconst aim = ability.autoAim(world, entity, state)\n\t\t\tif (!aim) continue\n\t\t\tgiveOrder(world, entity, createOrder(world, { type: 'cast', ability: ability.id, target: aim.target, point: aim.point }))\n\t\t\treturn\n\t\t}\n\t\tif (ability.target !== 'unit' || (!world.cheats.noManaCosts && at(ability.manaCost, state.level) > entity.mana)) continue\n\n\t\tconst reach = castRange(world, entity, ability, state.level) + AUTOCAST_SEARCH\n\t\tlet best: Entity | undefined\n\t\tlet bestScore = Infinity\n\t\tfor (const other of world.spatial.query(entity.pos.x, entity.pos.z, reach, found)) {\n\t\t\tif (!validTarget(world, entity, ability, other) || !useful(ability, state.level, other)) continue\n\t\t\tif (other !== entity && (edgeDistance(entity, other) > reach || !canSee(world, entity, other))) continue\n\t\t\t// whoever is worst off first, the closest one among equals\n\t\t\tconst score = other.hp / other.maxHp + edgeDistance(entity, other) * 0.01\n\t\t\tif (score < bestScore) {\n\t\t\t\tbestScore = score\n\t\t\t\tbest = other\n\t\t\t}\n\t\t}\n\t\tif (best) {\n\t\t\tgiveOrder(world, entity, createOrder(world, { type: 'cast', ability: ability.id, target: best.id }))\n\t\t\treturn\n\t\t}\n\t}\n}\n\n/** Everything about abilities that happens on its own: regeneration, cooldowns, buffs running out, auras, autocast */\nexport const abilitySystem: System = {\n\tname: 'abilities',\n\tphase: 'decide',\n\tupdate(world, dt) {\n\t\tupdateMissiles(world, dt)\n\t\tupdateLingering(world, dt)\n\t\tupdateDashes(world, dt)\n\t\tfor (const entity of world.actors.values()) {\n\t\t\tif (!entity.alive) continue\n\n\t\t\t// with no cooldowns, the ones that were running when that was switched on are over too\n\t\t\tconst pass = world.cheats.noCooldowns ? Infinity : dt\n\t\t\tfor (const state of entity.abilities) {\n\t\t\t\tif (state.cooldown > 0) state.cooldown = Math.max(state.cooldown - pass, 0)\n\t\t\t\tif (state.charges !== undefined) refillUses(world, entity, state, pass)\n\t\t\t}\n\n\t\t\tfor (let i = entity.buffs.length - 1; i >= 0; i--) {\n\t\t\t\tconst buff = entity.buffs[i]\n\t\t\t\tconst before = buff.elapsed\n\t\t\t\tbuff.remaining -= dt\n\t\t\t\tbuff.elapsed += dt\n\t\t\t\tconst def = world.registry.buff(buff.id)\n\t\t\t\t// every so often while it lasts: as many times as `every` went by in this tick\n\t\t\t\tconst tick = def.onTick\n\t\t\t\tif (tick && tick.every > 0) {\n\t\t\t\t\t// from the time before this tick: worked out back from after it, rounding could lose one\n\t\t\t\t\tconst times = Math.floor(buff.elapsed / tick.every) - Math.floor(before / tick.every)\n\t\t\t\t\tfor (let n = 0; n < times && entity.alive; n++) {\n\t\t\t\t\t\ttick.run?.(world, entity, buff)\n\t\t\t\t\t\tif (tick.effects) buffEffects(world, entity, buff, tick.effects)\n\t\t\t\t\t}\n\t\t\t\t\tif (!entity.alive) break\n\t\t\t\t}\n\t\t\t\tif (buff.remaining <= 0) {\n\t\t\t\t\tentity.dropBuff(i)\n\t\t\t\t\tbuffEnded(world, entity, buff)\n\t\t\t\t\tdef.onRemove?.(world, entity, buff, true)\n\t\t\t\t\tworld.hooks.run('buffEnd', { entity, buff, expired: true })\n\t\t\t\t\tworld.events.emit(buffRemoved, { entity, buff: buff.id, expired: true })\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// a shield that grows back, once its owner has been left alone for long enough\n\t\t\t\tif (def.recharge !== undefined && world.time - entity.hurtAt >= def.recharge) {\n\t\t\t\t\tbuff.shield = fullShield(world, def, world.get(buff.source) ?? entity, buff.level)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const instance of slotsOf(entity) ?? []) {\n\t\t\t\tif (instance?.state && instance.state.cooldown > 0) instance.state.cooldown = Math.max(instance.state.cooldown - pass, 0)\n\t\t\t\tif (instance?.state?.charges !== undefined) refillUses(world, entity, instance.state, pass, true)\n\t\t\t}\n\t\t\tfor (const stock of entity.get(shopStock) ?? []) {\n\t\t\t\tconst max = world.registry.item(stock.item).stock?.max ?? 0\n\t\t\t\tif (stock.count >= max || !entity.operational) continue\n\t\t\t\tstock.restock -= dt\n\t\t\t\tif (stock.restock <= 0) {\n\t\t\t\t\tstock.count++\n\t\t\t\t\tstock.restock = world.registry.item(stock.item).stock?.restock ?? 60\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst stats = statsOf(world, entity)\n\t\t\t// what changed the stats may have changed how much health and mana there is room for\n\t\t\tif (stats.health !== entity.maxHp || stats.mana !== entity.maxMana) refreshVitals(world, entity)\n\t\t\tif (entity.maxMana > 0 && stats.manaRegen !== 0) entity.mana = Math.min(entity.mana + stats.manaRegen * dt, entity.maxMana)\n\t\t\tif (stats.healthRegen !== 0 && !(entity.isStructure && entity.has(constructionSite)))\n\t\t\t\tentity.hp = Math.min(entity.hp + stats.healthRegen * dt, entity.maxHp)\n\t\t\t// left alone for long enough, it is whole again\n\t\t\tconst { recovers } = entity.def\n\t\t\tif (recovers !== undefined && entity.hp < entity.maxHp && world.time - entity.hurtAt >= recovers) entity.hp = entity.maxHp\n\t\t\tif (entity.hp <= 0) {\n\t\t\t\tworld.kill(entity)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// slowed or hasted units have to be told to the navigation\n\t\t\tconst m = entity.get(moving)\n\t\t\tif (m && !entity.hidden) {\n\t\t\t\tconst speed =\n\t\t\t\t\tentity.buffs.length && (isStunned(world, entity) || isRooted(world, entity))\n\t\t\t\t\t\t? 0\n\t\t\t\t\t\t: Math.min(world.rules.movement.moveSpeed(world, entity, stats.moveSpeed), m.cap ?? Infinity)\n\t\t\t\tif (Math.abs(speed - m.speed) > 1e-6) {\n\t\t\t\t\tm.speed = speed\n\t\t\t\t\tworld.nav.setSpeed(entity.id, speed)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ((entity.abilities.length === 0 && !entity.has(inventorySlots)) || (world.tick + entity.id) % UPKEEP_INTERVAL !== 0) continue\n\t\t\tupkeepPassives(world, entity)\n\t\t\tif (!isStunned(world, entity) && !entity.asleep) autocast(world, entity)\n\t\t}\n\t}\n}\n","import { detection } from '#engine/entity'\nimport type { System } from '#engine/registry'\nimport type { World } from '#engine/world'\n\n/** Counts down what only lasts a while: things that are gone after some time, invisibility setting in, being found, spots that are revealed */\nexport const lifeSystem: System = {\n\tname: 'life',\n\tphase: 'cleanup',\n\tupdate(world: World) {\n\t\tconst { dt } = world\n\t\tfor (const entity of world.actors.values()) {\n\t\t\tif (!entity.alive) continue\n\t\t\tif (entity.unseenIn) entity.unseenIn = Math.max(entity.unseenIn - dt, 0)\n\t\t\tconst detected = entity.get(detection)\n\t\t\tif (detected) {\n\t\t\t\tfor (const [team, left] of detected) {\n\t\t\t\t\tif (left > dt) detected.set(team, left - dt)\n\t\t\t\t\telse detected.delete(team)\n\t\t\t\t}\n\t\t\t\tif (detected.size === 0) entity.remove(detection)\n\t\t\t}\n\t\t\tif (entity.expires !== null) {\n\t\t\t\tconst left = entity.expireIn(entity.expires - dt)!\n\t\t\t\tif (left <= 0) world.kill(entity, undefined, false, 'expired')\n\t\t\t}\n\t\t}\n\t\tfor (let i = world.reveals.length - 1; i >= 0; i--) {\n\t\t\tconst reveal = world.reveals[i]\n\t\t\treveal.left -= dt\n\t\t\tif (reveal.left <= 0) world.reveals.splice(i, 1)\n\t\t}\n\t}\n}\n","import { packBytes, unpackBytes } from './bytes'\nimport { clamp } from './math'\n\n/** @internal */\nexport const FOG_UNEXPLORED = 0\n/** @internal */\nexport const FOG_EXPLORED = 1\n/** @internal */\nexport const FOG_VISIBLE = 2\n\n/**\n * Bit positions are 0..31: JavaScript bitwise operators work on 32 bit integers\n *\n * @internal\n */\nexport const MAX_FOG_TEAMS = 32\n\n/**\n * Per team visibility of the map, one cell per world unit.\n *\n * Each team has two grids. `visible` is what the team sees right now and is cleared and drawn again\n * on every update. `explored` only ever gets set: ground the team has looked at at least once, which\n * is drawn as the dimmed \"explored\" fog and lets players build there.\n */\n/** The fog in a save, see `FogOfWar.save` */\nexport interface FogSave {\n\tversion: number\n\trevealed: number[]\n\t/** Cells of each team, packed */\n\tteams: Record<number, { visible: string; explored: string }>\n\t/**\n\t * Each team's bit in the masks entities keep (`Entity.seenBy`): in the order teams first had fog, which a world loaded\n\t * from the save would not know otherwise once a player has moved to another team. Saves from before it numbered them\n\t * from the teams the world was made with\n\t */\n\tbits?: Record<number, number>\n\t/** Whether the map is explored from the start, for the teams to come too (`FogOfWar.exploredFromStart`) */\n\texploredFromStart?: true\n}\n\n/** Whether the middle of a cell of a row is in a circle: `across` is the square of how far the row's middle is from the circle's */\nconst inside = (cx: number, x: number, across: number, r2: number): boolean => (cx + 0.5 - x) * (cx + 0.5 - x) + across <= r2\n\n/** @beta */\nexport class FogOfWar {\n\t// (the maps below hold a team's cells for every team of `teams`, made together in the constructor: a `get(team)!` on\n\t// one of those teams cannot miss)\n\tprivate readonly visible = new Map<number, Uint8Array>()\n\tprivate readonly explored = new Map<number, Uint8Array>()\n\tprivate readonly revealed = new Set<number>()\n\t/**\n\t * One bit per team, for per-entity bitmasks like `Entity.seenBy`. Team ids come from the map and can be\n\t * any number (the creeps are team 1000), so they are numbered 0, 1, 2... here instead of being used as\n\t * bit positions directly: `1 << 1000` is `1 << 8` in JavaScript and would mix up two teams.\n\t */\n\tprivate readonly bits = new Map<number, number>()\n\tprivate readonly levels: Uint8Array\n\t/**\n\t * What is being lit during an update (`beginUpdate`), a bit a cell, a row of the map `words` of 32 bits: a row of a\n\t * circle is a word or two, not hundreds of cells. Written into the grids as the update ends\n\t */\n\tprivate readonly lit = new Map<number, Uint32Array>()\n\tprivate readonly words: number\n\tprivate updating = false\n\t/** The cells at or under each level, as bits: what a viewer on that level sees of what it lights. Made as they are first asked for */\n\tprivate readonly levelMasks = new Map<number, Uint32Array>()\n\t/** The highest level of the ground: a viewer on it or above sees everything it lights. -1 until worked out */\n\tprivate top = -1\n\t/** Bumped every time visibility is recomputed */\n\tversion = 0\n\n\tconstructor(\n\t\treadonly width: number,\n\t\treadonly depth: number,\n\t\tteams: number[],\n\t\t/** Level of every cell: nobody sees up a cliff. All on the ground floor when left out */\n\t\tlevels?: Uint8Array\n\t) {\n\t\tthis.levels = levels ?? new Uint8Array(width * depth)\n\t\tthis.words = Math.ceil(width / 32)\n\t\tif (teams.length > MAX_FOG_TEAMS) throw new Error(`Fog of war supports at most ${MAX_FOG_TEAMS} teams, got ${teams.length}`)\n\t\tfor (const team of teams) this.makeTeam(team)\n\t}\n\n\t/** Gives a team that has none yet fog of its own: a player moved to a new team mid-game. Nothing for one there is */\n\taddTeam(team: number): void {\n\t\tif (this.visible.has(team)) return\n\t\tthis.makeTeam(team)\n\t\tthis.version++\n\t}\n\n\t/**\n\t * Whether the whole map is explored from the start (`FogRules.startExplored`, `MapDef.explored`): every team's, and\n\t * the teams' made from now on. What stands on it and is no player's is then known to every team from the first moment\n\t * (the sessions' `TeamMemory.startKnown`). Set with `exploreFromStart`\n\t */\n\texploredFromStart = false\n\n\t/** Grids for a team, and the first bit no other team has */\n\tprivate makeTeam(team: number, bit = this.freeBit()): void {\n\t\tthis.visible.set(team, new Uint8Array(this.width * this.depth))\n\t\tthis.explored.set(team, new Uint8Array(this.width * this.depth).fill(this.exploredFromStart ? 1 : 0))\n\t\tthis.bits.set(team, bit)\n\t\tthis.lit.set(team, new Uint32Array(this.words * this.depth))\n\t}\n\n\tprivate freeBit(): number {\n\t\tconst taken = new Set(this.bits.values())\n\t\tfor (let place = 0; place < MAX_FOG_TEAMS; place++) if (!taken.has(1 << place)) return 1 << place\n\t\tthrow new Error(`Fog of war supports at most ${MAX_FOG_TEAMS} teams`)\n\t}\n\n\t/** The team's bit in per-entity team masks. 0 for a team without fog (neutral), which then never shows up in one */\n\t/** What each team sees and has explored, for a save, with each team's bit */\n\tsave(): FogSave {\n\t\tconst save: FogSave = {\n\t\t\tversion: this.version,\n\t\t\trevealed: [...this.revealed],\n\t\t\tteams: {},\n\t\t\tbits: Object.fromEntries(this.bits),\n\t\t\t...(this.exploredFromStart && { exploredFromStart: true })\n\t\t}\n\t\tfor (const team of this.teams) save.teams[team] = { visible: packBytes(this.visible.get(team)!), explored: packBytes(this.explored.get(team)!) }\n\t\treturn save\n\t}\n\n\trestore(save: FogSave): void {\n\t\tconst cells = this.width * this.depth\n\t\tif (save.bits) {\n\t\t\t// the teams as the saved world had them, each with its bit: those of players who moved since, too\n\t\t\tfor (const team of this.teams) {\n\t\t\t\tthis.visible.delete(team)\n\t\t\t\tthis.explored.delete(team)\n\t\t\t\tthis.lit.delete(team)\n\t\t\t}\n\t\t\tthis.bits.clear()\n\t\t\tfor (const [team, bit] of Object.entries(save.bits)) this.makeTeam(Number(team), bit)\n\t\t}\n\t\tfor (const team of this.teams) {\n\t\t\tconst saved = save.teams[team]\n\t\t\tconst visible = saved && unpackBytes(saved.visible, cells)\n\t\t\tconst explored = saved && unpackBytes(saved.explored, cells)\n\t\t\tif (!visible || !explored) throw new Error(`Save: the fog of team ${team} is missing or not the size of the map`)\n\t\t\tthis.visible.get(team)!.set(visible)\n\t\t\tthis.explored.get(team)!.set(explored)\n\t\t}\n\t\tthis.revealed.clear()\n\t\tfor (const team of save.revealed) this.revealed.add(team)\n\t\tthis.exploredFromStart = !!save.exploredFromStart\n\t\tthis.version = save.version\n\t}\n\n\tteamBit(team: number): number {\n\t\treturn this.bits.get(team) ?? 0\n\t}\n\n\tget teams(): number[] {\n\t\treturn [...this.visible.keys()]\n\t}\n\n\t/** Debug switch: the team sees everything */\n\tsetRevealed(team: number, revealed: boolean): void {\n\t\tif (revealed) this.revealed.add(team)\n\t\telse this.revealed.delete(team)\n\t\tthis.version++\n\t}\n\n\tisRevealed(team: number): boolean {\n\t\treturn this.revealed.has(team)\n\t}\n\n\t/**\n\t * Starts working out what is seen: what is lit from here to `endUpdate` is collected as bits, and the grids\n\t * are written when it ends, so `visible` and `explored` say what they did before until then\n\t */\n\tbeginUpdate(): void {\n\t\tthis.updating = true\n\t\tfor (const bits of this.lit.values()) bits.fill(0)\n\t}\n\n\tendUpdate(): void {\n\t\tthis.updating = false\n\t\tconst { width, depth, words } = this\n\t\tfor (const [team, bits] of this.lit) {\n\t\t\tconst visible = this.visible.get(team)!\n\t\t\tconst explored = this.explored.get(team)!\n\t\t\tvisible.fill(0)\n\t\t\tfor (let cz = 0; cz < depth; cz++) {\n\t\t\t\tfor (let w = 0; w < words; w++) {\n\t\t\t\t\tlet word = bits[cz * words + w]\n\t\t\t\t\tif (word === 0) continue\n\t\t\t\t\tconst row = cz * width + w * 32\n\t\t\t\t\tif (word === 0xffffffff) {\n\t\t\t\t\t\tfor (let i = row; i < row + 32; i++) {\n\t\t\t\t\t\t\tvisible[i] = 1\n\t\t\t\t\t\t\texplored[i] = 1\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\twhile (word !== 0) {\n\t\t\t\t\t\tconst low = word & -word\n\t\t\t\t\t\tconst i = row + 31 - Math.clz32(low)\n\t\t\t\t\t\tvisible[i] = 1\n\t\t\t\t\t\texplored[i] = 1\n\t\t\t\t\t\tword ^= low\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.version++\n\t}\n\n\t/**\n\t * Says the ground's levels changed (`Terrain.levels` written to while the world runs): what a viewer on a level sees\n\t * is worked out from them once, and again after this\n\t *\n\t * @beta\n\t */\n\tlevelsChanged(): void {\n\t\tthis.levelMasks.clear()\n\t\tthis.top = -1\n\t}\n\n\tprivate highest(): number {\n\t\tif (this.top < 0) {\n\t\t\tlet top = 0\n\t\t\tfor (const level of this.levels) if (level > top) top = level\n\t\t\tthis.top = top\n\t\t}\n\t\treturn this.top\n\t}\n\n\tprivate maskOf(level: number): Uint32Array {\n\t\tlet mask = this.levelMasks.get(level)\n\t\tif (!mask) {\n\t\t\tconst { width, depth, words, levels } = this\n\t\t\tmask = new Uint32Array(words * depth)\n\t\t\tfor (let cz = 0; cz < depth; cz++) {\n\t\t\t\tfor (let cx = 0; cx < width; cx++) if (levels[cz * width + cx] <= level) mask[cz * words + (cx >> 5)] |= 1 << (cx & 31)\n\t\t\t}\n\t\t\tthis.levelMasks.set(level, mask)\n\t\t}\n\t\treturn mask\n\t}\n\n\t/** Lights up what a viewer at the point sees. Ground above the viewer's `level` stays dark, so a flyer passes Infinity */\n\treveal(team: number, x: number, z: number, radius: number, level = Infinity): void {\n\t\tconst visible = this.visible.get(team)\n\t\tconst explored = this.explored.get(team)\n\t\tif (!visible || !explored) return\n\t\tconst { width, depth, words } = this\n\t\tconst minZ = clamp(Math.floor(z - radius), 0, depth - 1)\n\t\tconst maxZ = clamp(Math.ceil(z + radius), 0, depth - 1)\n\t\tconst r2 = radius * radius\n\t\tconst bits = this.updating ? this.lit.get(team)! : null\n\t\tconst mask = bits && level < this.highest() ? this.maskOf(level) : null\n\t\tfor (let cz = minZ; cz <= maxZ; cz++) {\n\t\t\tconst dz = cz + 0.5 - z\n\t\t\tconst across = dz * dz\n\t\t\tif (across > r2) continue\n\t\t\t// the cells of the row whose middle is in the circle: from the root, then made exact (the same test as ever)\n\t\t\tconst half = Math.sqrt(r2 - across)\n\t\t\tlet from = Math.max(Math.ceil(x - half - 0.5), 0)\n\t\t\tlet to = Math.min(Math.floor(x + half - 0.5), width - 1)\n\t\t\twhile (from <= to && !inside(from, x, across, r2)) from++\n\t\t\twhile (to >= from && !inside(to, x, across, r2)) to--\n\t\t\twhile (from > 0 && inside(from - 1, x, across, r2)) from--\n\t\t\twhile (to < width - 1 && inside(to + 1, x, across, r2)) to++\n\t\t\tif (to < from) continue\n\t\t\tif (!bits) {\n\t\t\t\t// outside an update: the grids at once\n\t\t\t\tconst { levels } = this\n\t\t\t\tfor (let cx = from; cx <= to; cx++) {\n\t\t\t\t\tconst i = cz * width + cx\n\t\t\t\t\tif (levels[i] > level) continue\n\t\t\t\t\tvisible[i] = 1\n\t\t\t\t\texplored[i] = 1\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst first = from >> 5\n\t\t\tconst last = to >> 5\n\t\t\tconst row = cz * words\n\t\t\tconst head = -1 << (from & 31)\n\t\t\tconst tail = -1 >>> (31 - (to & 31))\n\t\t\tif (first === last) bits[row + first] |= mask ? head & tail & mask[row + first] : head & tail\n\t\t\telse {\n\t\t\t\tbits[row + first] |= mask ? head & mask[row + first] : head\n\t\t\t\tfor (let w = first + 1; w < last; w++) bits[row + w] |= mask ? mask[row + w] : -1\n\t\t\t\tbits[row + last] |= mask ? tail & mask[row + last] : tail\n\t\t\t}\n\t\t}\n\t}\n\n\tstateAt(team: number, x: number, z: number): number {\n\t\tif (this.revealed.has(team)) return FOG_VISIBLE\n\t\tconst visible = this.visible.get(team)\n\t\tif (!visible) return FOG_UNEXPLORED\n\t\tconst cx = clamp(Math.floor(x), 0, this.width - 1)\n\t\tconst cz = clamp(Math.floor(z), 0, this.depth - 1)\n\t\tconst i = cz * this.width + cx\n\t\tif (visible[i]) return FOG_VISIBLE\n\t\treturn this.explored.get(team)![i] ? FOG_EXPLORED : FOG_UNEXPLORED\n\t}\n\n\tisVisible(team: number, x: number, z: number): boolean {\n\t\treturn this.stateAt(team, x, z) === FOG_VISIBLE\n\t}\n\n\tisExplored(team: number, x: number, z: number): boolean {\n\t\treturn this.stateAt(team, x, z) !== FOG_UNEXPLORED\n\t}\n\n\t/** A team has seen every cell once: the map starts explored for it */\n\texploreAll(team: number): void {\n\t\tthis.explored.get(team)?.fill(1)\n\t\tthis.version++\n\t}\n\n\t/**\n\t * The whole map explored from the start, for every team and the teams to come (`exploredFromStart`), or no longer:\n\t * then each team has explored what it sees now, and no more (a debug switch, mid-game)\n\t *\n\t * @beta\n\t */\n\texploreFromStart(on: boolean): void {\n\t\tthis.exploredFromStart = on\n\t\tfor (const team of this.teams) {\n\t\t\tconst explored = this.explored.get(team)!\n\t\t\tif (on) explored.fill(1)\n\t\t\telse explored.set(this.visible.get(team)!)\n\t\t}\n\t\tthis.version++\n\t}\n\n\t/** Raw per cell state for rendering */\n\tcells(team: number): { visible: Uint8Array; explored: Uint8Array } | null {\n\t\tconst visible = this.visible.get(team)\n\t\tconst explored = this.explored.get(team)\n\t\treturn visible && explored ? { visible, explored } : null\n\t}\n}\n","/**\n * What each team of a world sees of its entities (`world.sight`): by the fog, what is invisible and who detects it, and\n * what the game makes of it (the `visible` hook: units in a bush)\n */\nimport { detection } from './entity'\nimport type { Entity } from './entity'\nimport { FOG_VISIBLE } from './fog'\nimport type { World } from './world'\n\n/**\n * What each team sees of a world's entities\n *\n * @beta\n */\nexport class Sight {\n\t/**\n\t * What is handed to the `visible` handlers, again and again, so that asking allocates nothing: the world's own, a\n\t * handler that asks again getting an object of its own\n\t */\n\tprivate readonly asking: { entity: Entity; team: number; visible: boolean } = { entity: undefined!, team: 0, visible: false }\n\n\tconstructor(private readonly world: World) {}\n\n\t/** Whether a team currently sees the entity */\n\tsees(entity: Entity, team: number): boolean {\n\t\tif (entity.hidden) return false\n\t\tconst owner = this.world.player(entity.owner)\n\t\tif (!owner.neutral && owner.team === team) return true\n\t\tconst seen = this.inSight(entity, team)\n\t\t// what the game makes of it: units in brush, a tower that sees everything near it. Asked for every entity, team\n\t\t// and snapshot: the one object handed out again and again, so that asking allocates nothing\n\t\tif (!this.world.hooks.has('visible')) return seen\n\t\t// a handler that asks again, as it decides (a game's `seenBy`): an object of its own then\n\t\tconst shared = this.asking.entity === undefined\n\t\tconst asking = shared ? this.asking : { entity, team, visible: seen }\n\t\tasking.entity = entity\n\t\tasking.team = team\n\t\tasking.visible = seen\n\t\tconst visible = this.world.hooks.run('visible', asking).visible\n\t\tif (shared) this.asking.entity = undefined!\n\t\treturn visible\n\t}\n\n\t/** Whether an entity is invisible right now: by its type (`invisible`), or a buff that says so */\n\tisInvisible(entity: Entity): boolean {\n\t\tif (entity.unseen) return true\n\t\tif (!entity.buffs.length) return false\n\t\tfor (const instance of entity.buffs) {\n\t\t\tconst flag = this.world.registry.buff(instance.id).invisible\n\t\t\tif (typeof flag === 'function' ? flag(this.world, entity, instance) : flag) return true\n\t\t}\n\t\treturn false\n\t}\n\n\t/** Whether a team sees an entity of someone else's, by the fog and what is invisible */\n\tprivate inSight(entity: Entity, team: number): boolean {\n\t\tif (this.isInvisible(entity) && !entity.get(detection)?.has(team)) return false\n\t\tif (entity.def.footprint) {\n\t\t\t// structures are visible as soon as any part of them is\n\t\t\tconst { hw, hd } = entity.rect\n\t\t\tconst { x, z } = entity.pos\n\t\t\treturn (\n\t\t\t\tthis.world.fog.stateAt(team, x, z) === FOG_VISIBLE ||\n\t\t\t\tthis.world.fog.stateAt(team, x - hw + 0.5, z - hd + 0.5) === FOG_VISIBLE ||\n\t\t\t\tthis.world.fog.stateAt(team, x + hw - 0.5, z - hd + 0.5) === FOG_VISIBLE ||\n\t\t\t\tthis.world.fog.stateAt(team, x - hw + 0.5, z + hd - 0.5) === FOG_VISIBLE ||\n\t\t\t\tthis.world.fog.stateAt(team, x + hw - 0.5, z + hd - 0.5) === FOG_VISIBLE\n\t\t\t)\n\t\t}\n\t\treturn this.world.fog.stateAt(team, entity.pos.x, entity.pos.z) === FOG_VISIBLE\n\t}\n\n\t/**\n\t * Whether a team has ever laid eyes on the entity. Kept up to date for structures only, see the fog system.\n\t * A team that sees the whole map (out of the game, or a debug switch) has seen everything there is\n\t */\n\thasSeen(entity: Entity, team: number): boolean {\n\t\treturn this.world.fog.isRevealed(team) || (entity.seenBy & this.world.fog.teamBit(team)) !== 0\n\t}\n}\n","import { constructionStarted, entitySpawned } from '#engine/engineEvents'\nimport { dashing } from './dashing'\nimport { footprintOf, isScenery } from './defs'\nimport { deposit, Entity, fighting, moving, type PlayerId } from './entity'\nimport type { Vec2 } from './math'\nimport { agentParamsOf } from './navigation/agentParams'\nimport { resourceAt } from './orders/build'\nimport { clearOrders } from './orders/queue'\nimport { constructionSite } from './systems/construction'\nimport { halt, setGhost } from './systems/movement'\nimport type { SpawnOptions, World } from './world'\n/**\n * How entities come into the world and are moved about in it, as the world's own part (`World.spawn`, `place`,\n * `setOwner`, `setHidden`, `setLifetime`): what a type is given as it is made, its place on the ground, the grid and the\n * ways, whose it is, whether it is inside something, how long it lasts. The world's methods are this.world part's\n */\nexport class Spawning {\n\tconstructor(private readonly world: World) {}\n\n\tspawn(typeId: string, owner: PlayerId, position: Vec2, options: SpawnOptions = {}): Entity {\n\t\tconst def = this.world.registry.unit(typeId)\n\t\tthis.world.player(owner)\n\t\tlet pos = position\n\t\tlet cell: { x: number; z: number } | undefined\n\t\tif (def.kind !== 'unit') {\n\t\t\tconst fp = footprintOf(def)\n\t\t\tcell = this.world.grid.cellFor(position.x, position.z, fp.w, fp.d)\n\t\t\tpos = { x: cell.x + fp.w / 2, z: cell.z + fp.d / 2 }\n\t\t} else {\n\t\t\tpos = this.world.layerOf(def).closestPoint(position, 8) ?? position\n\t\t}\n\n\t\tconst entity = new Entity(this.world.newEntityId(), def, owner, pos)\n\t\tentity.facing = entity.prevFacing = options.facing ?? 0\n\t\tentity.scale = options.scale ?? 1\n\t\tentity.look = options.look\n\t\tentity.cell = cell\n\t\tentity.expireIn(options.lifetime ?? def.lifetime ?? null)\n\t\tentity.lifetime = entity.expires ?? 0\n\t\tif (def.invisible) entity.unseenIn = def.invisible.after ?? 0\n\t\tif (def.hits) entity.hp = entity.maxHp = def.hits\n\n\t\tif (def.kind === 'unit') {\n\t\t\tconst speed = def.stats.moveSpeed\n\t\t\tif (speed) {\n\t\t\t\tentity.set(moving, {\n\t\t\t\t\tspeed,\n\t\t\t\t\tstatus: 'idle',\n\t\t\t\t\tgoal: { x: pos.x, z: pos.z },\n\t\t\t\t\tgoalEntity: 0,\n\t\t\t\t\trange: 0,\n\t\t\t\t\tgroupId: 0,\n\t\t\t\t\tnavGoal: { x: pos.x, z: pos.z },\n\t\t\t\t\tnavVersion: 0,\n\t\t\t\t\tcorner: { x: pos.x, z: pos.z },\n\t\t\t\t\tbestDistance: 0,\n\t\t\t\t\tstalledTime: 0,\n\t\t\t\t\tanchored: false,\n\t\t\t\t\tghost: false,\n\t\t\t\t\tfinalFacing: null\n\t\t\t\t})\n\t\t\t\tthis.world.nav.addAgent(entity.id, pos, agentParamsOf(entity, speed))\n\t\t\t}\n\t\t} else {\n\t\t\tconst fp = footprintOf(def)\n\t\t\tthis.world.grid.occupy(cell!.x, cell!.z, fp.w, fp.d, entity.id)\n\t\t\t// on a resource (a cursed mine on a gold mine): the two know of each other\n\t\t\tconst under = resourceAt(this.world, def, pos)\n\t\t\tif (under) {\n\t\t\t\tunder.get(deposit)!.under = entity.id\n\t\t\t\tentity.on = under.id\n\t\t\t}\n\t\t\t// placing is refused before the room runs out (`placementProblem`); what is put down by a script past it stands,\n\t\t\t// and does not block: said, never thrown in the middle of a tick\n\t\t\t// (said once: a map past the room would say it for each of thousands of trees, and stall the page that shows it)\n\t\t\tif (!this.world.nav.addObstacle(entity.id, entity.rect) && !this.world.obstaclesRefused++)\n\t\t\t\tthis.world.log.warn(\n\t\t\t\t\t'navigation',\n\t\t\t\t\t`There is no room for another obstacle: ${def.id} does not block the way, nor what is put down after it while there is none`,\n\t\t\t\t\t{\n\t\t\t\t\t\tentity: entity.id\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\tif (def.resource) entity.set(deposit, { amount: def.resource.amount, occupants: 0 })\n\t\t\tif (options.underConstruction) {\n\t\t\t\tconst site = typeof options.underConstruction === 'object' ? options.underConstruction : {}\n\t\t\t\tentity.set(constructionSite, {\n\t\t\t\t\tprogress: 0,\n\t\t\t\t\tbuildTime: site.buildTime ?? def.buildTime ?? 1,\n\t\t\t\t\tbuilders: 0,\n\t\t\t\t\t...(site.paid && { paid: site.paid })\n\t\t\t\t})\n\t\t\t\tentity.hp = Math.max(1, Math.round(entity.maxHp * this.world.rules.production.constructionHealth))\n\t\t\t}\n\t\t}\n\t\tentity.mana = Math.min(def.initialMana ?? entity.maxMana, entity.maxMana)\n\t\tfor (const id of def.abilities ?? []) {\n\t\t\tentity.addAbility({ id, level: 1, cooldown: 0, autocast: this.world.registry.ability(id).autocast ?? false })\n\t\t}\n\t\tif (def.attacks?.length)\n\t\t\tentity.set(fighting, { cooldown: 0, swing: 0, swingTarget: 0, autoTarget: 0, lastAttacker: 0, guard: null, passive: false })\n\t\t// what each part of the game gives it as it is made, by its type: a queue, slots, a hold (`Component.onSpawn`)\n\t\tfor (const part of this.world.registry.spawning) part.onSpawn!(entity, this.world)\n\n\t\t// what a pack gives it of its own: a hero's level, a shop's wares (`withHeroes`)\n\t\tif (this.world.hooks.has('made')) this.world.hooks.run('made', entity)\n\n\t\tthis.world.entities.set(entity.id, entity)\n\t\tthis.world.index.add(entity)\n\t\tif (entity.isStructure) this.world.spatial.insertStatic(entity)\n\t\tentity.setScenery(isScenery(def) && this.world.player(owner).neutral && !entity.has(constructionSite) && entity.expires === null)\n\t\tif (!entity.scenery) this.world.actors.set(entity.id, entity)\n\t\t// scenery that appears where a team is looking is in sight right away, not at the next fog update\n\t\telse {\n\t\t\tfor (const [team, inSight] of this.world.sceneryInSight) if (this.world.isVisibleTo(entity, team)) inSight.add(entity)\n\t\t}\n\t\t// what the owner's research does besides stats (`UpgradeDef.apply`)\n\t\tfor (const [id, level] of this.world.player(owner).upgrades) this.world.registry.upgrade(id).apply?.(this.world, entity, level)\n\t\t// before the hooks, which may want to know who it is\n\t\tif (options.name) this.world.setName(entity, options.name)\n\t\tthis.world.hooks.run('spawn', entity)\n\t\tthis.world.events.emit(entitySpawned, entity)\n\t\tif (entity.has(constructionSite)) this.world.events.emit(constructionStarted, entity)\n\t\treturn entity\n\t}\n\n\t/**\n\t * What its parts call off as an entity leaves its owner, dying or given away (`Component.onLeave`)\n\t *\n\t * @internal\n\t */\n\tleave(entity: Entity): void {\n\t\tfor (const part of this.world.registry.leaving) if (entity.has(part)) part.onLeave!(entity, this.world)\n\t}\n\n\t/**\n\t * Turns scenery into an actor, for good: something gave it a reason to be looked at every tick, like a buff\n\t * that has to run out. Whatever does that to an entity calls this.world; the debug checks catch what forgets to.\n\t */\n\twake(entity: Entity): void {\n\t\tif (!entity.scenery) return\n\t\tentity.setScenery(false)\n\t\tthis.world.actors.set(entity.id, entity)\n\t}\n\n\t/** Puts a unit somewhere else, where it stands: the way through is not its concern. Structures stay where they were built */\n\tplace(entity: Entity, point: Vec2): void {\n\t\tif (entity.isStructure) throw new Error(`${entity.def.id}#${entity.id} is a structure: it cannot be moved`)\n\t\tentity.moveTo(point.x, point.z)\n\t\tif (entity.get(moving) && !entity.hidden && !entity.get(dashing)?.height) this.world.nav.teleport(entity.id, point)\n\t}\n\n\t/**\n\t * Gives an entity to another player, from now on in everything: whose it is, whom it fights, what it counts for.\n\t * What it was doing is called off, and what it was making is given back to the one it belonged to\n\t */\n\tsetOwner(entity: Entity, owner: PlayerId): void {\n\t\tif (entity.owner === owner) return\n\t\tthis.world.player(owner)\n\t\tclearOrders(this.world, entity)\n\t\tthis.leave(entity)\n\t\tif (entity.get(fighting)) Object.assign(entity.get(fighting)!, { autoTarget: 0, lastAttacker: 0, guard: null })\n\t\tthis.world.index.remove(entity)\n\t\tentity.changeOwner(owner)\n\t\tthis.world.index.add(entity)\n\t\t// filed this.world tick under its old owner's: the grid's cells by owner wait for the next filing\n\t\tthis.world.spatial.ownerChanged()\n\t\t// a tree that now belongs to someone counts for them: it is not scenery any more\n\t\tif (entity.scenery && !this.world.player(owner).neutral) this.wake(entity)\n\t}\n\n\t/**\n\t * Takes a unit out of the world for a while, or puts it back: a worker inside a gold mine, a unit carried in\n\t * something. While hidden it is not found, not seen and in nobody's way, and its orders wait. It comes back at\n\t * `at`, or where it went in, on the nearest ground it can stand on. Structures cannot hide\n\t */\n\tsetHidden(entity: Entity, hidden: boolean, at?: Vec2): void {\n\t\tif (entity.hidden === hidden) return\n\t\tif (entity.isStructure) throw new Error(`${entity.def.id}#${entity.id} is a structure: it cannot hide`)\n\t\tconst m = entity.get(moving)\n\t\tif (hidden) {\n\t\t\tif (m) {\n\t\t\t\thalt(this.world, entity)\n\t\t\t\tthis.world.nav.removeAgent(entity.id)\n\t\t\t}\n\t\t\tthis.wake(entity)\n\t\t\tentity.setInside(true)\n\t\t\treturn\n\t\t}\n\t\tentity.setInside(false)\n\t\tconst nav = this.world.navFor(entity)\n\t\tconst point = nav.closestPoint(at ?? entity.pos, 8) ?? at ?? entity.pos\n\t\tentity.moveTo(point.x, point.z)\n\t\tentity.prevPos.x = point.x\n\t\tentity.prevPos.z = point.z\n\t\tif (!m) return\n\t\tthis.world.nav.addAgent(entity.id, point, agentParamsOf(entity, m.speed))\n\t\t// the agent is new, so it lost its flags\n\t\tconst { ghost } = m\n\t\tm.ghost = false\n\t\tm.anchored = false\n\t\tm.status = 'idle'\n\t\tsetGhost(this.world, entity, ghost)\n\t}\n\n\t/** Gives an entity a time after which it is gone by itself, like a ward, or takes it away with `null` */\n\tsetLifetime(entity: Entity, seconds: number | null): void {\n\t\tif (seconds !== null) this.wake(entity)\n\t\tentity.expireIn(seconds)\n\t\tentity.lifetime = seconds ?? 0\n\t}\n}\n","import type { Component } from './components'\nimport type { Entity, PlayerId } from './entity'\n\nconst none: ReadonlySet<Entity> = new Set()\n\n/** Entities in the order of their ids, with the highest id filed: what comes next goes at the end when it is higher */\nclass ById extends Set<Entity> {\n\tlast = 0\n}\n\n/**\n * Entities filed by what they are asked for by: whose they are, which have a component (and, for a component that\n * asks, whose they are too: `Component.index`). Answers questions like \"the heroes of player 2\"\n * or \"every shop\" without going through every entity of the world, most of which are trees. Kept up to date by the\n * world as entities come and go, and by the entities as they get or lose a component.\n *\n * Every set keeps entities in the order of their ids, the order they came into the world and the one a walk through\n * `World.entities` gives, however and whenever each was filed: one that changed owner or type, or was given a component\n * late, takes its place among the others, as it has in a world loaded from a save. Code that picks the first of equals\n * gets the same one either way. A set an entity is filed into out of its place is made again: a walk through it under\n * way goes on through the one it had\n */\nexport class EntityIndex {\n\t/** `componentOf`: a component of the world's game by its id, an error for one it does not list (`registry.used`) */\n\tconstructor(private readonly componentOf: (id: string) => Component<unknown, unknown> | undefined) {}\n\n\tprivate readonly owned = new Map<PlayerId, ById>()\n\tprivate readonly components = new Map<string, ById>()\n\t/** By component id, then by owner: for the components that ask (`index: 'owner'`) */\n\tprivate readonly byOwner = new Map<string, Map<PlayerId, ById>>()\n\t/** By component id, what has it in the order of the entities' ids (`ordered`): made again once it changes */\n\tprivate readonly inOrder = new Map<string, readonly Entity[]>()\n\n\t/** Everything the player owns, dead heroes waiting to be brought back included */\n\townedBy(player: PlayerId): ReadonlySet<Entity> {\n\t\treturn this.owned.get(player) ?? none\n\t}\n\n\t/**\n\t * Everything that has the component; with a player, what the player owns of it, for a component filed by owner\n\t * (`Component.index: 'owner'`; throws for one that is not)\n\t */\n\twith(key: Component<unknown, unknown>, owner?: PlayerId): ReadonlySet<Entity> {\n\t\tif (owner === undefined) return this.components.get(key.id) ?? none\n\t\tconst owners = this.byOwner.get(key.id)\n\t\tif (!owners) {\n\t\t\tif (key.index === 'owner') return none\n\t\t\tthrow new Error(`Index: \"${key.id}\" is not filed by owner: define it with index: 'owner' to ask for a player's`)\n\t\t}\n\t\treturn owners.get(owner) ?? none\n\t}\n\n\t/**\n\t * Everything that has the component, in the order of the entities' ids: the order a walk through `World.actors`\n\t * meets them in. What a system that runs over a component goes through (`System.over`), so a game plays the same\n\t * as one that looks at every actor. A list of its own, kept until what has the component changes: what is given it\n\t * or loses it while the list is gone through is in the next one\n\t */\n\tordered(key: Component<unknown, unknown>): readonly Entity[] {\n\t\tlet list = this.inOrder.get(key.id)\n\t\tif (!list) {\n\t\t\tconst set = this.components.get(key.id)\n\t\t\tlist = set ? [...set] : []\n\t\t\tthis.inOrder.set(key.id, list)\n\t\t}\n\t\treturn list\n\t}\n\n\tadd(entity: Entity): void {\n\t\tfile(this.owned, entity.owner, entity)\n\t\tfor (const component of entity.heldComponents()) this.fileComponent(entity, component.id)\n\t\tentity.index = this\n\t}\n\n\tremove(entity: Entity): void {\n\t\tthis.owned.get(entity.owner)?.delete(entity)\n\t\tfor (const component of entity.heldComponents()) this.dropComponent(entity, component.id)\n\t\tentity.index = null\n\t}\n\n\t/** An entity in the index was given a component, or had it taken away. Told by the entity */\n\t/** Whether the component with this id asks to be filed by owner */\n\tprivate byOwnerOf(id: string): boolean {\n\t\treturn this.componentOf(id)?.index === 'owner'\n\t}\n\n\tcomponentChanged(entity: Entity, id: string, has: boolean): void {\n\t\tif (has) this.fileComponent(entity, id)\n\t\telse this.dropComponent(entity, id)\n\t}\n\n\tprivate fileComponent(entity: Entity, id: string): void {\n\t\tfile(this.components, id, entity)\n\t\tthis.inOrder.delete(id)\n\t\tif (this.byOwnerOf(id)) {\n\t\t\tlet owners = this.byOwner.get(id)\n\t\t\tif (!owners) this.byOwner.set(id, (owners = new Map()))\n\t\t\tfile(owners, entity.owner, entity)\n\t\t}\n\t}\n\n\tprivate dropComponent(entity: Entity, id: string): void {\n\t\tif (this.components.get(id)?.delete(entity)) this.inOrder.delete(id)\n\t\tthis.byOwner.get(id)?.get(entity.owner)?.delete(entity)\n\t}\n\n\t/** Throws when the index does not say what the entities are. See `debugChecks` */\n\tcheck(entities: Iterable<Entity>): void {\n\t\tlet count = 0\n\t\tfor (const entity of entities) {\n\t\t\tcount++\n\t\t\tconst what = `${entity.def.id}#${entity.id}`\n\t\t\tif (!this.ownedBy(entity.owner).has(entity)) throw new Error(`Index: ${what} is not filed under its owner ${entity.owner}`)\n\t\t\tfor (const { id } of entity.heldComponents()) {\n\t\t\t\tif (!this.components.get(id)?.has(entity)) throw new Error(`Index: ${what} is not filed under its component ${id}`)\n\t\t\t\tif (this.byOwnerOf(id) && !this.byOwner.get(id)?.get(entity.owner)?.has(entity))\n\t\t\t\t\tthrow new Error(`Index: ${what} is not filed under its owner for its component ${id}`)\n\t\t\t}\n\t\t}\n\t\tlet filed = 0\n\t\tfor (const set of this.owned.values()) filed += set.size\n\t\tif (filed !== count) throw new Error(`Index: ${filed} entities filed by owner, the world has ${count}`)\n\t\tfor (const [id, set] of this.components) {\n\t\t\tfor (const entity of set)\n\t\t\t\tif (!entity.heldComponents().some((held) => held.id === id))\n\t\t\t\t\tthrow new Error(`Index: ${entity.def.id}#${entity.id} is filed under ${id}, which it has not`)\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis.owned.clear()\n\t\tthis.components.clear()\n\t\tthis.byOwner.clear()\n\t\tthis.inOrder.clear()\n\t}\n}\n\nfunction file<K>(map: Map<K, ById>, key: K, entity: Entity): void {\n\tlet set = map.get(key)\n\tif (!set) map.set(key, (set = new ById()))\n\tif (entity.id > set.last) {\n\t\tset.add(entity)\n\t\tset.last = entity.id\n\t\treturn\n\t}\n\tif (set.has(entity)) return\n\t// out of its place: the set made again with it among the others\n\tconst again = new ById()\n\tfor (const each of set) {\n\t\tif (each.id > entity.id) again.add(entity)\n\t\tagain.add(each)\n\t}\n\tagain.add(entity)\n\tagain.last = set.last\n\tmap.set(key, again)\n}\n","import type { Rect, Vec2 } from '#engine/math'\nimport type { AgentParams, AgentSave, AgentState, NavDebugGeometry, Navigation } from './navigation'\nimport { hypot } from '#engine/exactMath'\n\ninterface Flyer {\n\tid: number\n\tx: number\n\tz: number\n\tvx: number\n\tvz: number\n\tradius: number\n\tspeed: number\n\ttarget: Vec2 | null\n\tanchored: boolean\n\tghost: boolean\n}\n\n/** How hard flyers that overlap push each other apart, in units per second per unit of overlap */\nconst SEPARATION = 6\n/** Seconds a flyer takes to get up to speed or to turn around */\nconst INERTIA = 0.15\n/** A cell's key is its column times this, plus its row: room for a map's cells however small they are */\nconst CELL_ROW = 1 << 20\n\n/**\n * Where flyers move. There is nothing in the way up there but other flyers and the edge of the map,\n * so they go straight to where they are sent and only keep from flying inside one another.\n */\nexport class AirNavigation implements Navigation {\n\treadonly version = 0\n\tprivate readonly flyers = new Map<number, Flyer>()\n\n\tconstructor(\n\t\tprivate readonly width: number,\n\t\tprivate readonly depth: number\n\t) {}\n\n\tprivate inside(point: Vec2): Vec2 {\n\t\treturn { x: Math.min(Math.max(point.x, 0.5), this.width - 0.5), z: Math.min(Math.max(point.z, 0.5), this.depth - 0.5) }\n\t}\n\n\taddAgent(id: number, position: Vec2, params: AgentParams): void {\n\t\tconst { x, z } = this.inside(position)\n\t\tthis.flyers.set(id, { id, x, z, vx: 0, vz: 0, radius: params.radius, speed: params.speed, target: null, anchored: false, ghost: false })\n\t}\n\n\tremoveAgent(id: number): void {\n\t\tthis.flyers.delete(id)\n\t}\n\n\tsaveAgent(id: number): AgentSave | undefined {\n\t\tconst flyer = this.flyers.get(id)\n\t\tif (!flyer) return undefined\n\t\tconst { x, z, vx, vz, radius, speed, target, anchored, ghost } = flyer\n\t\treturn { x, z, vx, vz, radius, speed, flying: true, target: target && { x: target.x, z: target.z }, anchored, ghost }\n\t}\n\n\treseat(agents: readonly (readonly [id: number, save: AgentSave])[]): void {\n\t\t// flyers are gone through in the order they came: the save's, as a world loaded from it has them\n\t\tthis.flyers.clear()\n\t\tfor (const [id, save] of agents) this.restoreAgent(id, save)\n\t}\n\n\t// up here nothing is worked out ahead, so a flyer comes back exactly as it was\n\trestoreAgent(id: number, save: AgentSave): void {\n\t\tconst { x, z, vx, vz, radius, speed, target, anchored, ghost } = save\n\t\tthis.flyers.set(id, { id, x, z, vx, vz, radius, speed, target: target && { x: target.x, z: target.z }, anchored, ghost })\n\t}\n\n\tsettle(): void {}\n\n\thasAgent(id: number): boolean {\n\t\treturn this.flyers.has(id)\n\t}\n\n\tsetDestination(id: number, target: Vec2): boolean {\n\t\tconst flyer = this.flyers.get(id)\n\t\tif (!flyer) return false\n\t\tflyer.target = this.inside(target)\n\t\tflyer.anchored = false\n\t\treturn true\n\t}\n\n\tclearDestination(id: number): void {\n\t\tconst flyer = this.flyers.get(id)\n\t\tif (flyer) flyer.target = null\n\t}\n\n\tteleport(id: number, position: Vec2): void {\n\t\tconst flyer = this.flyers.get(id)\n\t\tif (!flyer) return\n\t\tconst { x, z } = this.inside(position)\n\t\tflyer.x = x\n\t\tflyer.z = z\n\t}\n\n\tsetAnchored(id: number, anchored: boolean): void {\n\t\tconst flyer = this.flyers.get(id)\n\t\tif (!flyer) return\n\t\tflyer.anchored = anchored\n\t\tif (anchored) flyer.target = null\n\t}\n\n\tsetGhost(id: number, ghost: boolean): void {\n\t\tconst flyer = this.flyers.get(id)\n\t\tif (flyer) flyer.ghost = ghost\n\t}\n\n\tsetSpeed(id: number, speed: number): void {\n\t\tconst flyer = this.flyers.get(id)\n\t\tif (flyer) flyer.speed = speed\n\t}\n\n\treadAgent(id: number, out: AgentState): boolean {\n\t\tconst flyer = this.flyers.get(id)\n\t\tif (!flyer) return false\n\t\tout.x = flyer.x\n\t\tout.z = flyer.z\n\t\tout.vx = flyer.vx\n\t\tout.vz = flyer.vz\n\t\t// nothing to go around up here\n\t\tout.cx = out.nx = flyer.target?.x ?? flyer.x\n\t\tout.cz = out.nz = flyer.target?.z ?? flyer.z\n\t\treturn true\n\t}\n\n\tupdate(dt: number): void {\n\t\tconst flyers = [...this.flyers.values()]\n\t\tconst blend = Math.min(dt / INERTIA, 1)\n\t\tconst cells = this.cellsOf(flyers)\n\t\tconst near: number[] = []\n\t\tfor (let i = 0; i < flyers.length; i++) {\n\t\t\tconst flyer = flyers[i]\n\t\t\tlet wantX = 0\n\t\t\tlet wantZ = 0\n\t\t\tif (flyer.target && !flyer.anchored) {\n\t\t\t\tconst dx = flyer.target.x - flyer.x\n\t\t\t\tconst dz = flyer.target.z - flyer.z\n\t\t\t\tconst distance = hypot(dx, dz)\n\t\t\t\tif (distance > 1e-4) {\n\t\t\t\t\t// no faster than it takes to get there in this tick\n\t\t\t\t\tconst speed = Math.min(flyer.speed, distance / dt)\n\t\t\t\t\twantX = (dx / distance) * speed\n\t\t\t\t\twantZ = (dz / distance) * speed\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!flyer.anchored && !flyer.ghost) {\n\t\t\t\t// those in the cells about it, in the order they came, as going through them all adds them up (RV42)\n\t\t\t\tnear.length = 0\n\t\t\t\tconst cx = Math.floor(flyer.x / cells.size)\n\t\t\t\tconst cz = Math.floor(flyer.z / cells.size)\n\t\t\t\tfor (let x = cx - 1; x <= cx + 1; x++) {\n\t\t\t\t\tfor (let z = cz - 1; z <= cz + 1; z++) {\n\t\t\t\t\t\tconst cell = cells.of.get(x * CELL_ROW + z)\n\t\t\t\t\t\tif (cell) for (const j of cell) near.push(j)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnear.sort((a, b) => a - b)\n\t\t\t\tfor (const j of near) {\n\t\t\t\t\tconst other = flyers[j]\n\t\t\t\t\tif (other === flyer) continue\n\t\t\t\t\tconst dx = flyer.x - other.x\n\t\t\t\t\tconst dz = flyer.z - other.z\n\t\t\t\t\tconst reach = flyer.radius + other.radius\n\t\t\t\t\tconst distance = hypot(dx, dz)\n\t\t\t\t\tif (distance >= reach) continue\n\t\t\t\t\tconst push = (reach - distance) * SEPARATION\n\t\t\t\t\t// right on top of each other: apart along a line that is the same every time\n\t\t\t\t\tconst nx = distance > 1e-4 ? dx / distance : flyer.id < other.id ? 1 : -1\n\t\t\t\t\tconst nz = distance > 1e-4 ? dz / distance : 0\n\t\t\t\t\twantX += nx * push\n\t\t\t\t\twantZ += nz * push\n\t\t\t\t}\n\t\t\t}\n\t\t\tflyer.vx += (wantX - flyer.vx) * blend\n\t\t\tflyer.vz += (wantZ - flyer.vz) * blend\n\t\t}\n\t\tfor (const flyer of flyers) {\n\t\t\tif (flyer.anchored) {\n\t\t\t\tflyer.vx = flyer.vz = 0\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst { x, z } = this.inside({ x: flyer.x + flyer.vx * dt, z: flyer.z + flyer.vz * dt })\n\t\t\tflyer.x = x\n\t\t\tflyer.z = z\n\t\t}\n\t}\n\n\t/**\n\t * The flyers that push (all but ghosts), by cells twice the widest one's radius across: two that overlap are in the\n\t * same cell or next to each other, so each looks at its own cell and the eight about it, not at every flyer\n\t */\n\tprivate cellsOf(flyers: readonly Flyer[]): { size: number; of: Map<number, number[]> } {\n\t\tlet widest = 0\n\t\tfor (const flyer of flyers) if (!flyer.ghost) widest = Math.max(widest, flyer.radius)\n\t\t// a hair more, so that rounding never puts two that touch two cells apart\n\t\tconst size = widest * 2 * 1.001 + 1e-6\n\t\tconst of = new Map<number, number[]>()\n\t\tfor (let i = 0; i < flyers.length; i++) {\n\t\t\tconst flyer = flyers[i]\n\t\t\tif (flyer.ghost) continue\n\t\t\tconst key = Math.floor(flyer.x / size) * CELL_ROW + Math.floor(flyer.z / size)\n\t\t\tconst cell = of.get(key)\n\t\t\tif (cell) cell.push(i)\n\t\t\telse of.set(key, [i])\n\t\t}\n\t\treturn { size, of }\n\t}\n\n\taddObstacle(_key: number, _rect: Rect): boolean {\n\t\treturn true\n\t}\n\n\tobstacleRoom(): number {\n\t\treturn Infinity\n\t}\n\n\tremoveObstacle(_key: number): void {}\n\n\tclosestPoint(point: Vec2): Vec2 {\n\t\treturn this.inside(point)\n\t}\n\n\tfindPath(from: Vec2, to: Vec2): Vec2[] {\n\t\treturn [this.inside(from), this.inside(to)]\n\t}\n\n\tdebugGeometry(): NavDebugGeometry {\n\t\treturn { triangles: new Float32Array(0), lines: new Float32Array(0) }\n\t}\n\n\tdispose(): void {\n\t\tthis.flyers.clear()\n\t}\n}\n\n/** How far from the water a boat sent onto land still finds the water nearest where it was sent */\nconst NAVAL_REACH = 40\n\n/**\n * The ground, the air and the water as one: agents are told apart when they are added and find their own layer from\n * then on. Everything that is not about an agent, like obstacles and looking for walkable ground, is about the ground.\n * Boats go on the ground where the map has no water to go on (`water` is left out)\n */\nexport class LayeredNavigation implements Navigation {\n\tprivate readonly flying = new Set<number>()\n\tprivate readonly naval = new Set<number>()\n\n\tconstructor(\n\t\treadonly ground: Navigation,\n\t\treadonly air: Navigation,\n\t\treadonly water?: Navigation\n\t) {}\n\n\tget version(): number {\n\t\treturn this.ground.version\n\t}\n\n\tprivate of(id: number): Navigation {\n\t\treturn this.flying.has(id) ? this.air : this.naval.has(id) && this.water ? this.water : this.ground\n\t}\n\n\t/** The layer of a kind of agent: for finding where one can be put */\n\tlayer(kind: { flying?: boolean; naval?: boolean }): Navigation {\n\t\treturn kind.flying ? this.air : kind.naval && this.water ? this.water : this.ground\n\t}\n\n\taddAgent(id: number, position: Vec2, params: AgentParams): void {\n\t\tthis.removeAgent(id)\n\t\tif (params.flying) this.flying.add(id)\n\t\telse if (params.naval) this.naval.add(id)\n\t\tthis.of(id).addAgent(id, position, params)\n\t}\n\n\tremoveAgent(id: number): void {\n\t\tthis.of(id).removeAgent(id)\n\t\tthis.flying.delete(id)\n\t\tthis.naval.delete(id)\n\t}\n\n\thasAgent(id: number): boolean {\n\t\treturn this.of(id).hasAgent(id)\n\t}\n\n\tsetDestination(id: number, target: Vec2): boolean {\n\t\tconst layer = this.of(id)\n\t\t// a boat sent onto land goes to the water nearest it\n\t\tif (this.naval.has(id) && layer === this.water) return layer.setDestination(id, layer.closestPoint(target, NAVAL_REACH) ?? target)\n\t\treturn layer.setDestination(id, target)\n\t}\n\n\tclearDestination(id: number): void {\n\t\tthis.of(id).clearDestination(id)\n\t}\n\n\tteleport(id: number, position: Vec2): void {\n\t\tthis.of(id).teleport(id, position)\n\t}\n\n\tsetAnchored(id: number, anchored: boolean): void {\n\t\tthis.of(id).setAnchored(id, anchored)\n\t}\n\n\tsetGhost(id: number, ghost: boolean): void {\n\t\tthis.of(id).setGhost(id, ghost)\n\t}\n\n\tsetSpeed(id: number, speed: number): void {\n\t\tthis.of(id).setSpeed(id, speed)\n\t}\n\n\treadAgent(id: number, out: AgentState): boolean {\n\t\treturn this.of(id).readAgent(id, out)\n\t}\n\n\tsaveAgent(id: number): AgentSave | undefined {\n\t\tconst save = this.of(id).saveAgent(id)\n\t\treturn save && { ...save, flying: this.flying.has(id) || undefined, naval: this.naval.has(id) || undefined }\n\t}\n\n\trestoreAgent(id: number, save: AgentSave): void {\n\t\tthis.removeAgent(id)\n\t\tif (save.flying) this.flying.add(id)\n\t\telse if (save.naval) this.naval.add(id)\n\t\tthis.of(id).restoreAgent(id, save)\n\t}\n\n\treseat(agents: readonly (readonly [id: number, save: AgentSave])[]): void {\n\t\t// each layer anew, with the agents of it in the save's order; who flies and who sails as the save says\n\t\tthis.flying.clear()\n\t\tthis.naval.clear()\n\t\tfor (const [id, save] of agents) {\n\t\t\tif (save.flying) this.flying.add(id)\n\t\t\telse if (save.naval) this.naval.add(id)\n\t\t}\n\t\t// a boat where there is no water layer goes on the ground's, as `of` puts it\n\t\tconst sails = (save: AgentSave) => !save.flying && !!save.naval && !!this.water\n\t\tthis.ground.reseat(agents.filter(([, save]) => !save.flying && !sails(save)))\n\t\tthis.air.reseat(agents.filter(([, save]) => !!save.flying))\n\t\tthis.water?.reseat(agents.filter(([, save]) => sails(save)))\n\t}\n\n\tsettle(version: number): void {\n\t\tthis.ground.settle(version)\n\t\tthis.air.settle(version)\n\t\tthis.water?.settle(version)\n\t}\n\n\t/** Slow ground is the ground's: what flies or sails goes at one speed (EN2) */\n\tgroundChanged(cells: readonly number[]): void {\n\t\tthis.ground.groundChanged?.(cells)\n\t}\n\n\t/** The ground's and the water's cut again of the ground as it is now: what flies goes over it all the same */\n\treshape(): boolean {\n\t\tconst ground = !!this.ground.reshape?.()\n\t\tconst water = !!this.water?.reshape?.()\n\t\treturn ground || water\n\t}\n\n\tupdate(dt: number): void {\n\t\tthis.ground.update(dt)\n\t\tthis.air.update(dt)\n\t\tthis.water?.update(dt)\n\t}\n\n\taddObstacle(key: number, rect: Rect): boolean {\n\t\treturn this.ground.addObstacle(key, rect)\n\t}\n\n\tobstacleRoom(): number {\n\t\treturn this.ground.obstacleRoom()\n\t}\n\n\tholdObstacles(hold: boolean): void {\n\t\tthis.ground.holdObstacles?.(hold)\n\t}\n\n\tremoveObstacle(key: number): void {\n\t\tthis.ground.removeObstacle(key)\n\t}\n\n\tsameCrowd(a: number, b: number): boolean {\n\t\tconst layer = this.of(a)\n\t\tif (layer !== this.of(b)) return false\n\t\treturn layer.sameCrowd?.(a, b) ?? true\n\t}\n\n\tclosestPoint(point: Vec2, searchRadius?: number): Vec2 | null {\n\t\treturn this.ground.closestPoint(point, searchRadius)\n\t}\n\n\tfindPath(from: Vec2, to: Vec2): Vec2[] | null {\n\t\treturn this.ground.findPath(from, to)\n\t}\n\n\tdebugGeometry(): NavDebugGeometry {\n\t\treturn this.ground.debugGeometry()\n\t}\n\n\tdispose(): void {\n\t\tthis.ground.dispose()\n\t\tthis.air.dispose()\n\t\tthis.water?.dispose()\n\t}\n}\n","import type { Entity, PlayerId } from './entity'\n\n/**\n * Uniform grid for \"what is near this point\" queries. The map is cut into square cells and every entity is\n * filed under the cells it is in, so a query only looks at the few cells around the point instead of at every\n * entity in the world.\n *\n * There are two layers:\n * - Units move, so they are filed again from scratch every tick (`rebuild`), which is simpler and cheaper than\n * following every unit from cell to cell. A unit is filed by its center only, so queries look a little\n * further than asked, by the radius of the biggest unit, not to miss one whose edge is in range.\n * - Structures (buildings, trees, mines) never move, so they are filed once when they appear and taken out when\n * they go (`insertStatic`, `removeStatic`). They are filed under every cell their footprint covers, so a query\n * finds them by any part of them without looking further than asked. That matters: padding queries by the\n * size of the biggest building would make every query near a forest go through far more trees.\n */\nexport class SpatialIndex {\n\tprivate readonly cols: number\n\tprivate readonly rows: number\n\tprivate readonly cells: Entity[][]\n\tprivate readonly staticCells: Entity[][]\n\t/**\n\t * By cell, the one owner of every unit filed in it this tick, or -1 for none or more than one: what a search that\n\t * passes over a side's own leaves out cell by cell (`query`'s `skip`). Not to be gone by once an owner changed\n\t * since (`ownerChanged`), until the next filing\n\t */\n\tprivate readonly soleOwner: Int32Array\n\tprivate ownersMoved = false\n\t/** Radius of the biggest unit filed this tick */\n\tprivate maxRadius = 0\n\t/** Counts queries. A structure that covers several cells is marked with it when found, so it is only found once */\n\tprivate stamp = 0\n\n\tconstructor(\n\t\twidth: number,\n\t\tdepth: number,\n\t\tprivate readonly cellSize = 4\n\t) {\n\t\tthis.cols = Math.ceil(width / cellSize)\n\t\tthis.rows = Math.ceil(depth / cellSize)\n\t\tthis.cells = Array.from({ length: this.cols * this.rows }, () => [])\n\t\tthis.staticCells = Array.from({ length: this.cols * this.rows }, () => [])\n\t\tthis.soleOwner = new Int32Array(this.cols * this.rows).fill(-1)\n\t}\n\n\tprivate col(x: number): number {\n\t\treturn Math.min(Math.max(Math.floor(x / this.cellSize), 0), this.cols - 1)\n\t}\n\n\tprivate row(z: number): number {\n\t\treturn Math.min(Math.max(Math.floor(z / this.cellSize), 0), this.rows - 1)\n\t}\n\n\t/** Files every unit again. Called once per tick, before the systems run. Structures in `entities` are passed over */\n\trebuild(entities: Iterable<Entity>): void {\n\t\tfor (const cell of this.cells) cell.length = 0\n\t\tthis.maxRadius = 0\n\t\tthis.ownersMoved = false\n\t\tconst sole = this.soleOwner\n\t\tsole.fill(-1)\n\t\tfor (const entity of entities) {\n\t\t\tif (!entity.alive || entity.hidden || entity.isStructure) continue\n\t\t\tconst at = this.row(entity.pos.z) * this.cols + this.col(entity.pos.x)\n\t\t\tconst cell = this.cells[at]\n\t\t\tsole[at] = cell.length === 0 || sole[at] === entity.owner ? entity.owner : -1\n\t\t\tcell.push(entity)\n\t\t\tif (entity.def.radius > this.maxRadius) this.maxRadius = entity.def.radius\n\t\t}\n\t}\n\n\t/** A unit filed this tick has another owner now: no cell's one owner is gone by until the next filing */\n\townerChanged(): void {\n\t\tthis.ownersMoved = true\n\t}\n\n\t/** Files a structure under every cell it covers, for as long as it stands */\n\tinsertStatic(entity: Entity): void {\n\t\tthis.forCellsOf(entity, (cell) => cell.push(entity))\n\t}\n\n\tremoveStatic(entity: Entity): void {\n\t\tthis.forCellsOf(entity, (cell) => {\n\t\t\tconst index = cell.indexOf(entity)\n\t\t\tif (index < 0) return\n\t\t\t// the others keep their order (insertion order, which a load restores): ties between targets break by it\n\t\t\tcell.splice(index, 1)\n\t\t})\n\t}\n\n\tprivate forCellsOf(entity: Entity, fn: (cell: Entity[]) => void): void {\n\t\tconst { x, z, hw, hd } = entity.rect\n\t\tconst maxX = this.col(x + hw)\n\t\tconst maxZ = this.row(z + hd)\n\t\tfor (let cz = this.row(z - hd); cz <= maxZ; cz++) {\n\t\t\tfor (let cx = this.col(x - hw); cx <= maxX; cx++) fn(this.staticCells[cz * this.cols + cx])\n\t\t}\n\t}\n\n\t/**\n\t * Entities that could be within `radius` of the point: every structure that has a part in the square around it,\n\t * and every unit whose center is close enough for its edge to be. Callers do the exact distance check.\n\t *\n\t * The answer is written into `out`, which callers keep around and pass again so that nothing is allocated. While going\n\t * through the answer, a caller that does something which can lead to another query with the same `out` (dealing damage\n\t * can set off effects that look around) has to go through a copy instead: the other query would overwrite it.\n\t *\n\t * `skip`: owners whose units the caller passes over anyway (a side's own, as it picks a target): a cell of units of\n\t * one such owner alone is left out. What is left is what the full answer had, in the same order, less some of theirs\n\t */\n\tquery(x: number, z: number, radius: number, out: Entity[] = [], skip?: (owner: PlayerId) => boolean): Entity[] {\n\t\tout.length = 0\n\t\tconst stamp = ++this.stamp\n\t\tconst sole = skip && !this.ownersMoved ? this.soleOwner : undefined\n\n\t\tlet r = radius + this.maxRadius\n\t\tlet maxX = this.col(x + r)\n\t\tlet maxZ = this.row(z + r)\n\t\tfor (let cz = this.row(z - r); cz <= maxZ; cz++) {\n\t\t\tfor (let cx = this.col(x - r); cx <= maxX; cx++) {\n\t\t\t\tconst at = cz * this.cols + cx\n\t\t\t\tif (sole && sole[at] >= 0 && skip!(sole[at])) continue\n\t\t\t\tconst cell = this.cells[at]\n\t\t\t\tfor (let i = 0; i < cell.length; i++) out.push(cell[i])\n\t\t\t}\n\t\t}\n\n\t\tr = radius\n\t\tmaxX = this.col(x + r)\n\t\tmaxZ = this.row(z + r)\n\t\tfor (let cz = this.row(z - r); cz <= maxZ; cz++) {\n\t\t\tfor (let cx = this.col(x - r); cx <= maxX; cx++) {\n\t\t\t\tconst cell = this.staticCells[cz * this.cols + cx]\n\t\t\t\tfor (let i = 0; i < cell.length; i++) {\n\t\t\t\t\tconst entity = cell[i]\n\t\t\t\t\tif (entity.spatialStamp === stamp) continue\n\t\t\t\t\tentity.spatialStamp = stamp\n\t\t\t\t\tout.push(entity)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out\n\t}\n\n\t/**\n\t * Only the structures that have a part in the square around the point: buildings, trees, mines, every kind but a\n\t * unit. For who looks for those alone, among crowds of units that would otherwise all be gone through. Into `out`,\n\t * as `query`\n\t */\n\tqueryStatic(x: number, z: number, radius: number, out: Entity[] = []): Entity[] {\n\t\tout.length = 0\n\t\tconst stamp = ++this.stamp\n\t\tconst maxX = this.col(x + radius)\n\t\tconst maxZ = this.row(z + radius)\n\t\tfor (let cz = this.row(z - radius); cz <= maxZ; cz++) {\n\t\t\tfor (let cx = this.col(x - radius); cx <= maxX; cx++) {\n\t\t\t\tconst cell = this.staticCells[cz * this.cols + cx]\n\t\t\t\tfor (let i = 0; i < cell.length; i++) {\n\t\t\t\t\tconst entity = cell[i]\n\t\t\t\t\tif (entity.spatialStamp === stamp) continue\n\t\t\t\t\tentity.spatialStamp = stamp\n\t\t\t\t\tout.push(entity)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out\n\t}\n}\n","import { type Camp, spawnCamp } from './camps'\nimport { type AreaShape, shapeAt } from './areas'\nimport type { Entity, PlayerId } from './entity'\nimport { MAP_CREEPS, MAP_NEUTRAL } from './map'\nimport { cos, sin } from './exactMath'\nimport { hashText, type Vec2 } from './math'\nimport type { World } from './world'\n\n/*\n * Prefabs in code (master plan FA4): a group of things a game spawns as one, at a place, for a player: a camp of a\n * kind, a base for the computer's expansion, a wave's fortress. The same shape the editor's prefab files have of their\n * contents, in the map's plain terms (no client types): the editor places one as a designer would, and a game spawns\n * one at tick 300, and they look the same. A game's own are `definePrefab`; the files a designer made are\n * `prefabsFrom(import.meta.glob('./prefabs/*.prefab.json', { eager: true }))`.\n *\n * What a prefab spawns at runtime is what the engine has at runtime: units and buildings (`world.spawn`), camps of\n * creeps (`spawnCamp`) and areas the rules watch (`world.areas.add`). Scenery, points and paths are the map's own\n * and have no life at runtime: a file's are left out, and said so once.\n */\n\n/** A unit or a building of a prefab, where it stands around the prefab's middle *\n * @beta\n */\nexport interface PrefabObject {\n\ttype: string\n\t/**\n\t * Whose: the player the prefab is spawned for (`'owner'`, the default), neutral, the creeps, or a player of the\n\t * map's by id (a file's objects say the id they had; one that is a player's becomes `'owner'` as the file is read)\n\t */\n\towner?: 'owner' | 'neutral' | 'creeps' | PlayerId\n\tx: number\n\tz: number\n\t/** Radians, the way entities face */\n\tfacing?: number\n\tscale?: number\n\tlook?: string\n\t/** A name of its own, for the rules to find it by: made free where it is taken (a number added) */\n\tname?: string\n\t/** 0..1 of its health, less than whole */\n\thealth?: number\n\t/** Structures: as a construction site */\n\tunderConstruction?: boolean\n}\n\n/** A camp of creeps of a prefab *\n * @beta\n */\nexport interface PrefabCamp {\n\tx: number\n\tz: number\n\tunits: string[]\n\tname?: string\n}\n\n/** An area the rules watch, of a prefab: its id gets the spawn's own suffix, so that two of one prefab are two areas *\n * @beta\n */\nexport interface PrefabArea {\n\tid: string\n\tshape: AreaShape\n}\n\n/** A prefab inside a prefab: spawned with it, its middle where it says from the outer one's, turned and sized with it *\n * @beta\n */\nexport interface PrefabInside {\n\t/** The prefab's id */\n\tprefab: string\n\tx: number\n\tz: number\n\t/** Radians, the way facings turn: on top of the outer prefab's turn */\n\tfacing?: number\n\tscale?: number\n}\n\n/** What a prefab is made of, around its middle (0, 0) *\n * @beta\n */\nexport interface PrefabContents {\n\tobjects?: PrefabObject[]\n\tcamps?: PrefabCamp[]\n\tareas?: PrefabArea[]\n\t/** Prefabs inside it, spawned with it (a prefab that holds itself, at any depth, is not spawned past the first) */\n\tprefabs?: PrefabInside[]\n}\n\n/**\n * A prefab of a game's own: what `world.spawnPrefab` puts down as one. Its contents as data, or made for the place\n * and the world (a camp the stronger the farther from the starts)\n *\n * @beta\n */\nexport interface PrefabDef {\n\t/** Shared by every game: give it a prefix of the game's (`'td.fortress'`) */\n\tid: string\n\tname?: string\n\tcontents: PrefabContents | ((at: Vec2, world: World) => PrefabContents)\n}\n\n/**\n * Typed help for writing a prefab\n *\n * @beta\n */\nexport const definePrefab = (def: PrefabDef): PrefabDef => def\n\n/** How a prefab is spawned: where its middle goes, for whom, turned and sized *\n * @beta\n */\nexport interface SpawnPrefabOptions {\n\tat: Vec2\n\t/** The player the prefab's `'owner'` objects are spawned for: neutral when left out */\n\towner?: PlayerId\n\t/** Radians, the way facings turn: the prefab turned around its middle */\n\tfacing?: number\n\tscale?: number\n\t/** Parts left out, by their index in the prefab's lists: a gate without its towers */\n\twithout?: { objects?: number[]; camps?: number[]; areas?: number[]; prefabs?: number[] }\n}\n\n/** What a prefab spawned became *\n * @beta\n */\nexport interface SpawnedPrefab {\n\tentities: Entity[]\n\tcamps: Camp[]\n\t/** The ids of the areas added */\n\tareas: string[]\n}\n\n/**\n * A prefab put down in the world as one: its objects spawned (`world.spawn`, for the owner given or as each says),\n * its camps (`spawnCamp`: a world with camps seats the creeps, `PlayerInit.creeps`), its areas added under ids of\n * their own; turned and sized around its middle as asked\n *\n * @beta\n */\nexport function spawnPrefab(world: World, prefab: PrefabDef | string, options: SpawnPrefabOptions): SpawnedPrefab {\n\treturn spawnWithin(world, prefab, options, [])\n}\n\n/** `spawnPrefab`, told the prefabs it is inside of: one inside itself is not spawned again */\nfunction spawnWithin(world: World, prefab: PrefabDef | string, options: SpawnPrefabOptions, within: readonly string[]): SpawnedPrefab {\n\tconst def = typeof prefab === 'string' ? world.registry.prefab(prefab) : prefab\n\tconst contents = typeof def.contents === 'function' ? def.contents(options.at, world) : def.contents\n\tconst turn = options.facing ?? 0\n\tconst scale = options.scale ?? 1\n\tconst c = cos(turn)\n\tconst s = sin(turn)\n\t// the way facings turn: a quarter takes what was ahead (+z) to the right (+x)\n\tconst place = (p: Vec2): Vec2 => {\n\t\tconst x = p.x * scale\n\t\tconst z = p.z * scale\n\t\treturn { x: options.at.x + x * c + z * s, z: options.at.z - x * s + z * c }\n\t}\n\tconst ownerOf = (owner: PrefabObject['owner']): PlayerId =>\n\t\towner === 'neutral' ? MAP_NEUTRAL : owner === 'creeps' ? MAP_CREEPS : typeof owner === 'number' ? owner : (options.owner ?? MAP_NEUTRAL)\n\tconst out: SpawnedPrefab = { entities: [], camps: [], areas: [] }\n\t// the areas' ids are the world's: the same in every world played the same way, and in one loaded from a save\n\tlet suffix: number | undefined\n\tcontents.objects?.forEach((object, i) => {\n\t\tif (options.without?.objects?.includes(i)) return\n\t\tconst entity = world.spawn(object.type, ownerOf(object.owner), place(object), {\n\t\t\tfacing: (object.facing ?? 0) + turn,\n\t\t\t...(object.scale !== undefined && { scale: object.scale * scale }),\n\t\t\t...(object.look !== undefined && { look: object.look }),\n\t\t\t...(object.name !== undefined && { name: freeName(world, object.name) }),\n\t\t\t...(object.underConstruction && { underConstruction: true })\n\t\t})\n\t\tif (object.health !== undefined && object.health < 1) entity.hp = Math.max(1, Math.round(entity.maxHp * object.health))\n\t\tout.entities.push(entity)\n\t})\n\tcontents.camps?.forEach((camp, i) => {\n\t\tif (options.without?.camps?.includes(i)) return\n\t\tconst made = spawnCamp(world, MAP_CREEPS, place(camp), camp.units)\n\t\tif (camp.name) made.name = freeName(world, camp.name)\n\t\tout.camps.push(made)\n\t})\n\tcontents.areas?.forEach((area, i) => {\n\t\tif (options.without?.areas?.includes(i)) return\n\t\tconst at = place(area.shape)\n\t\tconst shape: AreaShape = shapeAt(area.shape, at, scale)\n\t\tconst id = `${area.id}#${(suffix ??= world.newId())}`\n\t\tworld.areas.add({ id, shape })\n\t\tout.areas.push(id)\n\t})\n\tcontents.prefabs?.forEach((inside, i) => {\n\t\tif (options.without?.prefabs?.includes(i) || inside.prefab === def.id || within.includes(inside.prefab)) return\n\t\tconst made = spawnWithin(\n\t\t\tworld,\n\t\t\tinside.prefab,\n\t\t\t{\n\t\t\t\tat: place(inside),\n\t\t\t\t...(options.owner !== undefined && { owner: options.owner }),\n\t\t\t\tfacing: turn + (inside.facing ?? 0),\n\t\t\t\tscale: scale * (inside.scale ?? 1)\n\t\t\t},\n\t\t\t[...within, def.id]\n\t\t)\n\t\tout.entities.push(...made.entities)\n\t\tout.camps.push(...made.camps)\n\t\tout.areas.push(...made.areas)\n\t})\n\treturn out\n}\n\n/** A name of the prefab's, free on this world: as it is, or with a number */\nfunction freeName(world: World, name: string): string {\n\tif (!world.named(name)) return name\n\tfor (let n = 2; ; n++) if (!world.named(`${name} ${n}`)) return `${name} ${n}`\n}\n\n/** What a prefab's file holds, as far as the engine reads it: the editor's shape (a copy with a name and a version), or the first files' bare copy */\ninterface PrefabFileLike {\n\tname?: string\n\tversion?: number\n\tcontents?: ClipLike\n\t/** A variant of another prefab of the files, by its name: the fields it overrides and the parts it leaves out, by kind and id */\n\tvariant?: { of: string; over?: Overrides; without?: Without }\n\t/** Prefabs of the files inside it, by name: where, turned and sized, and what it overrides and leaves out of each */\n\tprefabs?: { id: number; prefab: string; x: number; z: number; turn?: number; scale?: number; over?: Overrides; without?: Without }[]\n}\n\ntype Overrides = Partial<Record<string, Record<number, Record<string, unknown>>>>\ntype Without = Partial<Record<string, number[]>>\n\ninterface ClipObject {\n\tid?: number\n\ttype: string\n\towner: PlayerId\n\tx: number\n\tz: number\n\tfacing?: number\n\tscale?: number\n\tlook?: string\n\tname?: string\n\thealth?: number\n\tunderConstruction?: boolean\n}\n\ninterface ClipLike {\n\tkind?: string\n\tobjects?: ClipObject[]\n\tcamps?: { id?: number; x: number; z: number; units: string[]; name?: string }[]\n\tregions?: { id?: number; name: string; shape: AreaShape }[]\n}\n\n/** The lists of a file's copy the engine reads */\nconst KINDS = ['objects', 'camps', 'regions'] as const\n\n/**\n * The id a part of a prefab inside another has in the outer one's copy, as the editor and `prefabsFrom` number it:\n * made from the inner prefab's id there and the part's id in it (itself one of these, a level down), the same each\n * time it is read; below zero, where a prefab's own parts (the map's ids they had) never are\n *\n * @beta\n */\nexport function nestedPartId(nested: number, id: number): number {\n\treturn -(parseInt(hashText(`${nested}/${id}`), 16) || 1)\n}\n\n/**\n * A file read through the others it names, as the editor places it: a variant's source with its overrides, the file's\n * own parts, the prefabs inside it unpacked where it says; what holds itself or names a file there is not is left out\n */\nfunction readThrough(file: PrefabFileLike, name: string, read: (name: string) => PrefabFileLike | undefined, within: readonly string[]): ClipLike {\n\tconst path = [...within, name]\n\tconst out: Required<Omit<ClipLike, 'kind'>> = { objects: [], camps: [], regions: [] }\n\tconst join = (more: ClipLike) => {\n\t\tfor (const kind of KINDS) {\n\t\t\tconst taken = new Set(out[kind].map((part) => part.id))\n\t\t\tfor (const part of more[kind] ?? []) {\n\t\t\t\tif (part.id !== undefined && taken.has(part.id)) {\n\t\t\t\t\tlet next = 1\n\t\t\t\t\twhile (taken.has(next)) next++\n\t\t\t\t\tpart.id = next\n\t\t\t\t}\n\t\t\t\ttaken.add(part.id)\n\t\t\t\t;(out[kind] as unknown[]).push(part)\n\t\t\t}\n\t\t}\n\t}\n\tconst through = (of: string): ClipLike | undefined => {\n\t\tconst other = !path.includes(of) ? read(of) : undefined\n\t\treturn other && readThrough(other, of, read, path)\n\t}\n\tif (file.variant) {\n\t\tconst source = through(file.variant.of)\n\t\tif (source) join(overriddenClip(source, file.variant.over, file.variant.without))\n\t}\n\tjoin(structuredClone(file.contents ?? {}))\n\tfor (const nested of file.prefabs ?? []) {\n\t\tconst inner = through(nested.prefab)\n\t\tif (!inner) continue\n\t\tconst turn = nested.turn ?? 0\n\t\tconst scale = nested.scale ?? 1\n\t\t// the engine's own sines: a prefab read on any machine is the same prefab\n\t\tconst c = cos(turn)\n\t\tconst s = sin(turn)\n\t\tconst place = <T extends { x: number; z: number }>(p: T): T => {\n\t\t\tconst x = p.x * scale\n\t\t\tconst z = p.z * scale\n\t\t\treturn { ...p, x: nested.x + x * c + z * s, z: nested.z - x * s + z * c }\n\t\t}\n\t\tconst placed = overriddenClip(inner, nested.over, nested.without)\n\t\tjoin({\n\t\t\tobjects: (placed.objects ?? []).map((object) => ({\n\t\t\t\t...place(object),\n\t\t\t\tid: nestedPartId(nested.id, object.id ?? 0),\n\t\t\t\tfacing: (object.facing ?? 0) + turn,\n\t\t\t\t...(scale !== 1 && { scale: (object.scale ?? 1) * scale })\n\t\t\t})),\n\t\t\tcamps: (placed.camps ?? []).map((camp) => ({ ...place(camp), id: nestedPartId(nested.id, camp.id ?? 0) })),\n\t\t\tregions: (placed.regions ?? []).map((region) => ({\n\t\t\t\t...region,\n\t\t\t\tid: nestedPartId(nested.id, region.id ?? 0),\n\t\t\t\tshape: shapeAt(region.shape, place(region.shape), scale)\n\t\t\t}))\n\t\t})\n\t}\n\treturn out\n}\n\n/** A copy with fields of its parts overridden and parts left out, by kind and id */\nfunction overriddenClip(clip: ClipLike, over: Overrides | undefined, without: Without | undefined): ClipLike {\n\tconst out: ClipLike = {}\n\tfor (const kind of KINDS) {\n\t\tconst left = new Set(without?.[kind] ?? [])\n\t\tconst fields = over?.[kind] ?? {}\n\t\t;(out[kind] as unknown[]) = (clip[kind] ?? [])\n\t\t\t.filter((part) => part.id === undefined || !left.has(part.id))\n\t\t\t.map((part) => ({ ...structuredClone(part), ...(part.id !== undefined && structuredClone(fields[part.id])) }))\n\t}\n\treturn out\n}\n\n/**\n * The prefabs a designer made in the editor (`prefabs/<name>.prefab.json` of the game's folder), as prefabs of the\n * game's, by their file names: `prefabsFrom(import.meta.glob('./prefabs/*.prefab.json', { eager: true }))`, or any\n * record of name to file. An object of a player's becomes the owner's; scenery, points and paths are left out. A\n * variant is read through its source and a prefab with prefabs inside through those, as the editor places them, from\n * the files given\n *\n * @beta\n */\nexport function prefabsFrom(files: Record<string, unknown>, options: { prefix?: string } = {}): PrefabDef[] {\n\tconst byName = new Map<string, PrefabFileLike>()\n\tfor (const [path, data] of Object.entries(files)) {\n\t\tconst file = ((data as { default?: unknown })?.default ?? data) as PrefabFileLike\n\t\tif (file?.contents?.kind !== 'v12-clip') continue\n\t\tbyName.set(file.name ?? path.replace(/^.*[\\\\/]/, '').replace(/\\.prefab\\.json$/, ''), file)\n\t}\n\tconst out: PrefabDef[] = []\n\tfor (const [name, file] of byName) {\n\t\tconst clip = file.variant || file.prefabs?.length ? readThrough(file, name, (of) => byName.get(of), []) : file.contents!\n\t\tout.push({\n\t\t\tid: `${options.prefix ?? ''}${name}`,\n\t\t\tname,\n\t\t\tcontents: {\n\t\t\t\tobjects: (clip.objects ?? []).map(({ owner, ...object }) => ({\n\t\t\t\t\t...object,\n\t\t\t\t\towner: owner === MAP_NEUTRAL ? 'neutral' : owner === MAP_CREEPS ? 'creeps' : 'owner'\n\t\t\t\t})),\n\t\t\t\tcamps: (clip.camps ?? []).map(({ x, z, units, name }) => ({ x, z, units, ...(name && { name }) })),\n\t\t\t\tareas: (clip.regions ?? []).map((region) => ({ id: region.name, shape: region.shape }))\n\t\t\t}\n\t\t})\n\t}\n\treturn out\n}\n","import {\n\tcellsChanged,\n\tgroundReshaped,\n\tcheckpoint,\n\tcommandHandled,\n\tcommandRejected,\n\tentityRemoved,\n\tenvironmentChanged,\n\tmessageSent,\n\tworldFailed\n} from '#engine/engineEvents'\nimport { Life } from './life'\nimport { dashing } from './dashing'\nimport { Sight } from './sight'\nimport { Sides } from './sides'\nimport { Clock } from './clock'\nimport { Spawning } from './spawning'\nimport { constructionSite } from './systems/construction'\nimport { cellsIn, rememberUnseenCells } from './cellLayers'\nimport { executeCommand, type IssuedCommand } from './commands'\nimport type { Camp } from './camps'\nimport type { ChatAudience, PingKind } from './talk'\nimport { checksOf, type DebugChecks } from './debug'\nimport { type AbilityDef, type AttackDef, type Cost, type DamageType, type EffectDef, type EffectOf, isScenery, type ResourceKind } from './defs'\nimport { detection, Entity, type EntityId, exposure, type ItemInstance, type PlayerId } from './entity'\nimport { EntityIndex } from './entityIndex'\nimport { type ErrorPolicy, type ErrorSite, GameEnded, modOfPart, type RejectedKind, siteKey, siteOf, siteWords, type WorldFailure } from './errors'\nimport { Emitter } from './events'\nimport { coreHooks } from './features'\nimport { errorFields, Logger, type LogLevel, rootLogger } from './log'\nimport { type AnyHook, type HookDef, Hooks } from './hooks'\nimport { FogOfWar } from './fog'\nimport { BuildGrid } from './grid'\nimport type { Vec2 } from './math'\nimport { AirNavigation, LayeredNavigation } from './navigation/air'\nimport type { SidePaths } from './navigation/sidePaths'\nimport type { Navigation } from './navigation/navigation'\nimport { Player, type PlayerInit, type SpentOn } from './player'\nimport type { Registry, System } from './registry'\nimport { hasGroundSpeeds } from './groundSpeed'\nimport type { GameRules } from './rules'\nimport { Scheduler } from './scheduler'\nimport { Score } from './score'\nimport { Computers } from './computers'\nimport { type Component, StateStore } from './components'\nimport { type Message, type MessageRef, toMessage } from './messages'\nimport { Rng } from './rng'\nimport { settleRaces } from './races'\nimport { tunableChanged, tunings } from './tunables'\nimport { type DataKind, type DataValues, definitionChanged, definitionIn, mergeValues, redefineIn, redefinitions } from './gameData'\nimport { SpatialIndex } from './spatial'\nimport { type GroundItem } from './items'\nimport { statsOf } from './stats'\nimport type { Terrain } from './terrain'\nimport { applyTerrainPatch, type GroundBase, type TerrainPatch } from './ground'\nimport { type AreaDef, type AreaShape, Areas } from './areas'\nimport { Dialog, type SaidLine } from './dialog'\nimport { Objectives, type ObjectiveState, type ObjectiveStatus } from './objectives'\nimport { coreTimers, type SequenceDef, Sequences } from './sequences'\nimport { type TimerDef, Timers } from './timers'\nimport type { ListenerDef } from './events'\nimport type { Trace } from './inspect'\nimport type { CinematicChoice, CinematicCue, CinematicCueSent, CinematicEnded } from './cinematics'\nimport { type EffectCue, type EffectOptions, playEffect, stopEffect } from './effects'\nimport { mapInfo, names, WorldMap } from './names'\nimport type { MapEnvironment } from './map'\nimport { type PrefabDef, type SpawnedPrefab, spawnPrefab, type SpawnPrefabOptions } from './prefabs'\n\n/**\n * What two players are to each other, when set apart from their teams (`World.setRelation`)\n *\n * @beta\n */\nexport type PlayerRelation = 'ally' | 'enemy' | 'neutral'\n\n/** @beta */\nexport interface Projectile {\n\tid: number\n\tsource: EntityId\n\towner: PlayerId\n\ttarget: EntityId\n\tx: number\n\tz: number\n\tprevX: number\n\tprevZ: number\n\t/** Where it is heading. Follows the target while it lives */\n\ttx: number\n\ttz: number\n\tspeed: number\n\tdamage: number\n\ttype: DamageType\n\tcrit: boolean\n\t/** Fired uphill and going to miss: it flies all the way and does nothing when it comes down */\n\tmiss: boolean\n\t/** Where it was fired from */\n\tsx: number\n\tsz: number\n\t/** Set for shots that hit an area instead of a target */\n\tsplash?: { radius: number; fells: boolean; targets?: AttackDef['targets'] }\n\t/** What it looks like, when the rules say: a look of the shooter's visual, for the screen (a flaming arrow) */\n\tlook?: string\n\t/** The type of what shot it: the screen draws it so, even once the shooter is gone or out of sight */\n\tkind: string\n\t/** Words of the game's own about it, which its damage carries (see `BeforeAttack.tags`) */\n\ttags?: string[]\n\t/** How what it kills dies, for the screen (see `AttackDef.how`) */\n\thow?: string\n\t/** Which of its shooter's attacks it is of, by place (`UnitTypeDef.attacks`): the first when left out */\n\tweapon?: number\n}\n\n/**\n * What an ability sent on its way: it travels in a line and does something to everything it passes through\n *\n * @beta\n */\nexport interface Missile {\n\tid: number\n\towner: PlayerId\n\tsource: EntityId\n\tability: string\n\tlevel: number\n\tx: number\n\tz: number\n\tprevX: number\n\tprevZ: number\n\t/** Direction, of length 1 */\n\tdx: number\n\tdz: number\n\tspeed: number\n\t/** How far it still goes */\n\tleft: number\n\t/** Seconds until it sets off, and how long that took in all */\n\tdelay: number\n\tforms: number\n\tradius: number\n\teffect: EffectOf<'missile'>\n\t/** Whom it has passed through already. Missiles sent together share it: what one of them hit the others pass by */\n\thit: Set<EntityId>\n\t/** The unit it flies after, for the ones that do */\n\ttarget: EntityId\n\t/** How far it has come */\n\ttravelled: number\n\t/** How far it has come since it set off, or sprang on last (`EffectFields.bounce`): how far along its arc it is */\n\tleg: number\n\t/** How high above the ground its arc carries it now, for whoever draws it: 0 for what is not thrown in an arc */\n\theight: number\n\t/** How many times it has sprung on to another */\n\tbounces: number\n\t/** Something got in its way: what happens where it ends does not */\n\tstopped: boolean\n}\n\n/**\n * Something an ability does a while after it was cast\n *\n * @beta\n */\nexport interface Delayed {\n\tleft: number\n\tcaster: Entity\n\tability: AbilityDef\n\tlevel: number\n\tpoint: Vec2\n\teffects: EffectDef[]\n\t/** What its arrival goes by, when not the ability */\n\timpact?: string\n}\n\n/**\n * Ground an ability goes on working on for a while\n *\n * @beta\n */\nexport interface Zone {\n\tid: number\n\tcaster: Entity\n\tability: AbilityDef\n\tlevel: number\n\tx: number\n\tz: number\n\tleft: number\n\t/** Seconds until what is inside is next seen to */\n\tnext: number\n\teffect: EffectOf<'zone'>\n}\n\n/** @beta */\nexport type MessageKind = 'error' | 'info' | 'hint'\n\n/** @beta */\nexport interface WorldEvents {\n\tentitySpawned: Entity\n\tentityRemoved: Entity\n\t/**\n\t * `cause`: the blow, for what died of damage. `how`: what the rules made of the death in the `death` hook, for the\n\t * screen to show (`'exploded'`, `'burned'`)\n\t */\n\tentityDied: { entity: Entity; killer?: Entity; attack: boolean; cause?: DeathCause; how?: string; reason: DeathReason }\n\t/** A buff was put on, or put on again (`renewed`, with the level it had before: `previousLevel`) */\n\tbuffApplied: { target: Entity; buff: string; level: number; source?: Entity; renewed: boolean; previousLevel?: number }\n\t/** A buff came off: it ran out (`expired`), or was taken off. Not for the buffs of something that dies */\n\tbuffRemoved: { entity: Entity; buff: string; expired: boolean }\n\tdamaged: { target: Entity; source?: Entity; amount: number; type: DamageType; crit: boolean; attack: boolean; ability?: string; tags?: string[] }\n\t/** An attack went wide. Where it would have landed, and whom it was for */\n\tmissed: { x: number; z: number; source?: Entity; target?: Entity }\n\thealed: { target: Entity; source?: Entity; amount: number }\n\t/** `weapon`: which of its attacks swings, by place (`UnitTypeDef.attacks`) */\n\tattackStarted: { attacker: Entity; target?: Entity; weapon: number }\n\tprojectileSpawned: Projectile\n\tprojectileRemoved: Projectile\n\t/** An attack that hits an area came down */\n\timpact: { x: number; z: number; radius: number; owner: PlayerId }\n\tconstructionStarted: Entity\n\tconstructionFinished: Entity\n\t/** A construction was called off by its owner: it dies next, with the reason `cancelled` */\n\tconstructionCancelled: Entity\n\t/** A building started to turn into another type (`UnitTypeDef.upgradesTo`), over `time` seconds */\n\tmorphStarted: { entity: Entity; into: string; time: number }\n\t/** That was called off, or the building died before it was done */\n\tmorphCancelled: { entity: Entity; into: string }\n\tunitTrained: { building: Entity; unit: Entity }\n\t/** An entity became another type: `from`, what it was */\n\tentityMorphed: { entity: Entity; from: string }\n\tplayerDefeated: Player\n\t/** A player gave up (see `surrender`): `playerDefeated` follows */\n\tplayerSurrendered: { player: PlayerId }\n\t/** A player asked for a pause, and the rules let them (see `askPause`): whoever runs the world pauses it, for `seconds` at most */\n\tpauseAsked: { player: PlayerId; seconds: number; left: number }\n\tgameOver: { winner: number }\n\t/** The game ended on an error in its rules (`world.failure`): it is not stepped again */\n\tworldFailed: WorldFailure\n\t/** A unit got into a transport (`UnitTypeDef.transport`), or out of one */\n\tboarded: { passenger: Entity; transport: Entity }\n\t/** A unit was hired at a place that hires (`UnitTypeDef.hires`) */\n\tunitHired: { shop: Entity; unit: Entity; player: PlayerId }\n\tunloaded: { passenger: Entity; transport: Entity }\n\theroLevelUp: { hero: Entity; level: number }\n\t/** A hero earned experience (`grantXp`): how much, after `beforeXp`, and the level it is at after it */\n\txpGained: { hero: Entity; amount: number; level: number; from?: Entity }\n\t/**\n\t * A unit's mana changed by something it did or was given: spent on a cast (`amount` below 0, `ability` the one cast)\n\t * or given by an effect (above 0). Not its regeneration, which would be every tick\n\t */\n\tmanaChanged: { entity: Entity; amount: number; ability?: string; source?: Entity }\n\t/**\n\t * A pool of a game's own on a unit (rage, energy, charges) changed: emitted by the game's rules\n\t * (`world.events.emit(resourceChanged, …)`), heard by the screens of the unit's owner and allies (`resource`)\n\t */\n\tresourceChanged: { entity: Entity; kind: string; amount: number; reason?: string }\n\theroRevived: Entity\n\t/** `duration`: seconds of the wind-up */\n\tcastStarted: { caster: Entity; ability: AbilityDef; point?: Vec2; duration: number }\n\t/** A channelled ability started to be kept up, or ended: done, or `interrupted` */\n\tchannelStarted: { caster: Entity; ability: AbilityDef; duration: number }\n\tchannelEnded: { caster: Entity; ability: AbilityDef; interrupted: boolean }\n\tmissileSpawned: Missile\n\tmissileHit: { missile: Missile; target: Entity }\n\tmissileRemoved: Missile\n\tabilityCast: { caster: Entity; ability: AbilityDef; level: number; target?: Entity; point: Vec2; charged?: boolean }\n\t/** What an ability set off arrived: a missile hit, a rush ended, the time was up */\n\tabilityImpact: { caster: Entity; ability: AbilityDef; level: number; target?: Entity; point: Vec2; radius: number; impact?: string }\n\tresearchFinished: { building: Entity; upgrade: string; level: number }\n\titemDropped: GroundItem\n\titemPicked: { entity: Entity; item: ItemInstance }\n\t/** Every creep of a camp is gone. It comes back after a while, when it says so (see `Camp.respawn`) */\n\tcampCleared: { camp: Camp }\n\t/** A camp cleared came back, its creeps where they stood (see `respawnCamp`) */\n\tcampReturned: { camp: Camp }\n\t/** A player marked a spot for their allies, or for everyone (see `ping`) */\n\tpinged: { player: PlayerId; point: Vec2; kind: PingKind; to: ChatAudience; by?: string }\n\t/** A player gave an ally resources (see `give`): how much went, and how much came after the tax */\n\ttraded: { from: PlayerId; to: PlayerId; resource: string; sent: number; received: number }\n\t/** A player traded one resource for another at a rate (see `exchange`): how much of what went, and how much of what came */\n\texchanged: { player: PlayerId; sold: string; sent: number; bought: string; received: number }\n\t/** A player said a line (see `chat`): to their side, or to everyone */\n\tchatted: { player: PlayerId; text: string; to: ChatAudience; by?: string }\n\t/** What a unit carries changed: an item given, taken, bought, sold, used up, or a hero carried in with theirs */\n\tinventoryChanged: { entity: Entity }\n\tbounty: { entity: Entity; player: PlayerId; amount: number }\n\t/** A worker struck what it is mending */\n\tworked: { worker: Entity; target: Entity }\n\t/** A worker struck the tree it is working on */\n\tchopped: { worker: Entity; source: Entity }\n\t/** A worker handed in what it carried: `amount` as it went into the purse, `upkeep` what upkeep took of it at the door */\n\tresourcesDeposited: { entity: Entity; player: PlayerId; kind: ResourceKind; amount: number; upkeep?: number }\n\t/**\n\t * A player paid for something (`spend`), or was given back what they paid (`refund`, `giveBack`): `on` what (`unit`,\n\t * `upgrade`, `structure`, `item`, `hire`, `repair`... or a game's own word), and its id\n\t */\n\tresourcesSpent: { player: PlayerId; cost: Cost; on: SpentOn; id?: string; refund: boolean }\n\t/**\n\t * A command, or a part of one, that a player's own client never sends: not what it says it is (an unknown type, a\n\t * field missing or of the wrong kind), or naming another player's unit, or a unit there never was. What a race makes\n\t * (an order to a unit that has just died) is not one. A server counts these against whoever sent them (`onCheat`);\n\t * a game's own commands may emit it too\n\t */\n\t/**\n\t * A command turned away (`RejectedKind`: why, for what counts them, as a server's cheat counter does), with the\n\t * reason in words for the log\n\t */\n\tcommandRejected: { player?: PlayerId; type?: string; kind: RejectedKind; reason: string }\n\t/** A command that came with a number of its sender's (`seq`) was carried out: refused with the first error the player was told, or not */\n\tcommandHandled: { player: PlayerId; seq: number; refusal?: Message }\n\t/** Feedback for a player, like \"Not enough gold\": what the client finds the words for */\n\tmessageSent: { player: PlayerId; message: Message; kind: MessageKind; seconds?: number }\n\t/** A unit walked into an area of the game (`GameModule.areas`) */\n\tenteredArea: { area: string; entity: Entity }\n\t/** A unit walked out of one. What dies in an area is not said to leave it */\n\tleftArea: { area: string; entity: Entity }\n\t/** An objective of a player was given (`was` undefined), got further along, was done or failed */\n\tobjectiveChanged: { player: PlayerId; objective: ObjectiveState; was?: ObjectiveStatus }\n\t/** Someone said a line, to some players or everyone (see `world.dialog`) */\n\tlineSaid: SaidLine\n\t/** A line was skipped by whom it was said to: it ends early for them */\n\tlineEnded: { id: number; to: PlayerId[] }\n\t/** A player went over to another team (`setTeam`) */\n\tteamChanged: { player: PlayerId; from: number; to: number }\n\t/** The rules marked a moment to start again from, like the start of a wave: a session keeps a save of it */\n\tcheckpoint: { label: Message }\n\t/** The rules play one of the view's cinematics on the screens of some players, or everyone's (see `playCinematic`) */\n\tcinematicCue: CinematicCue\n\t/** The rules cue the cinematic playing on some screens, or everyone's (see `cueCinematic`) */\n\tcinematicCued: CinematicCueSent\n\t/** A cinematic the rules played is over on a player's screen, as their screen said (see `cinematic`'s `wait`) */\n\tcinematicEnded: CinematicEnded\n\t/** A player picked an answer of a cinematic's choice, as their screen said (see `cinematicChose`) */\n\tcinematicChoice: CinematicChoice\n\t/** The rules play one of the view's effects at a place or on an entity, for everyone who sees it (see `world.effect`) */\n\teffectStarted: EffectCue\n\t/** The rules stop an effect they played (see `world.stopEffect`) */\n\teffectStopped: { id: number; fade?: number }\n\t/**\n\t * One hidden in a layer of cells moved in it, or stepped into it (`ConcealmentOptions.rustle`): told to the teams\n\t * it names that do not see it (all of them, where none are named), where they see the ground, as a shake of what the\n\t * layer draws there\n\t */\n\trustled: { layer: string; entity: Entity; x: number; z: number; entered: boolean; teams?: number[] }\n\t/**\n\t * Cells of a layer (`Terrain.cells`) were set to a value (`setCells`): told to the players who see them, the others\n\t * as they come into sight (`cellsSeen`)\n\t */\n\tcellsChanged: { layer: string; cells: number[]; value: number }\n\t/**\n\t * Cells of a layer that changed out of a team's sight came into it (`TeamMemory.cells`): told to that team's players,\n\t * the cells at `value` now\n\t */\n\tcellsSeen: { team: number; layer: string; cells: number[]; value: number }\n\t/** A part of the ground was reshaped (`reshapeGround`): as it is now, told to every player */\n\tgroundReshaped: { patch: TerrainPatch }\n\t/** What the map looks like beyond its ground changed (`setEnvironment`): as it is now, told to every player */\n\t/** `over`: the seconds the screens ease into it over, where the rules said */\n\tenvironmentChanged: { environment: MapEnvironment; over?: number }\n}\n\n/**\n * What a world checks of itself and of its game as it runs, over the process's: for tests, development, a server that\n * runs games of its own\n *\n * @beta\n */\nexport interface WorldChecks {\n\t/** The engine's checks on itself (`DebugChecks`): all on or off, some of them; the process's (`setDebugChecks`) when left out */\n\tchecks?: boolean | Partial<DebugChecks>\n}\n\n/**\n * What a world is made of (`new World`): its ground and ways, its game, its players, its systems and hooks, and what it\n * checks of itself\n *\n * @beta\n */\nexport interface WorldOptions extends WorldChecks {\n\tterrain: Terrain\n\tnavigation: Navigation\n\t/** Where boats go (`UnitTypeDef.naval`): the deep water. None for a map without, and boats go on the ground */\n\twaterNavigation?: Navigation\n\t/** The navigations the sides plan their routes on, of what each knows (`GameModule.paths: 'seen'`). None when left out */\n\tsidePaths?: SidePaths\n\tregistry: Registry\n\tplayers: PlayerInit[]\n\t/** The races one is drawn from for a player given `random`: all of the game's when left out */\n\trandomRaces?: readonly string[]\n\t/** Makes the systems of the world, once it is made: what keeps state of its own keeps it for this world */\n\tsystems: (world: World) => System[]\n\t/** Hook handlers. The engine's own (`coreHooks`) when left out */\n\thooks?: HookDef[]\n\t/** How the game reacts to events, subscribed in this order once the world is made */\n\tlisteners?: ListenerDef[]\n\t/** Parts of the map the rules watch */\n\tareas?: AreaDef[]\n\t/** What the game can set to go off later, by id */\n\ttimers?: TimerDef[]\n\t/** Scripts of steps the game can start, by id */\n\tsequences?: SequenceDef[]\n\tseed?: number\n\t/** Simulation steps per second */\n\ttickRate?: number\n\t/** The logger the world's own is made under (`world.log`): the root one when left out */\n\tlog?: Logger\n\t/** The least an entry of the world's log must matter to be said (`GameModule.log`) */\n\tlogLevel?: LogLevel\n\t/** What becomes of a part of the game that throws (`GameModule.onError`): it throws on, when left out */\n\tonError?: ErrorPolicy\n}\n\n/** @beta */\nexport interface DamageOptions {\n\t/** Physical when left out */\n\tdamageType?: DamageType\n\t/** A basic attack: life steal works on it */\n\tattack?: boolean\n\t/** It struck critically. The amount is what it is, this is for whoever is watching */\n\tcrit?: boolean\n\t/** The ability that dealt it, by id: for \"immune to Ice Storm\", or a kill feed. Left out for a basic attack */\n\tability?: string\n\t/** Words of the game's own about it (`'fire'`, `'explosive'`), for hooks and the screen to decide on */\n\ttags?: string[]\n\t/** How what this blow kills dies, for the screen (`'burnt'`): the death's `how` (`AttackDef.how`, `AbilityDef.how`) */\n\thow?: string\n\t/** The attack's type by the game's damage table (`GameRules.combat.damageTable`): an ability's say, where a basic attack has its `AttackDef.attackType` */\n\tattackType?: string\n}\n\n/**\n * What killed something that died of damage: the blow that did it\n *\n * @beta\n */\nexport interface DeathCause {\n\ttype: DamageType\n\t/** What the blow took off */\n\tamount: number\n\t/** How much more it was than there was health left */\n\toverkill: number\n\tcrit: boolean\n\tability?: string\n\ttags?: string[]\n\t/** How the blow says what it kills dies (`DamageOptions.how`) */\n\thow?: string\n}\n\n/**\n * Why something died, when it was not of damage: killed by the rules (`killed`, `world.kill`), its building called\n * off (`cancelled`), its time out (`expired`), a resource used up (`depleted`), brought down by a blast (`felled`), taken\n * away with what it stood on or by the debug tools (`removed`), or the game's own word (`sold`, `sacrificed`). `damage`\n * for one that ran out of health\n *\n * @beta\n */\nexport type DeathReason = 'damage' | 'killed' | 'cancelled' | 'expired' | 'depleted' | 'felled' | 'removed' | (string & {})\n\n/**\n * A spot a team sees for a while, with nothing standing there\n *\n * @beta\n */\nexport interface Reveal {\n\tid: number\n\tteam: number\n\tx: number\n\tz: number\n\tradius: number\n\t/** Seconds it goes on */\n\tleft: number\n\t/** Shown, and nothing drawn for it: what the rules show a player, as a cinematic looks at it. A spell's, when left out */\n\tquiet?: boolean\n}\n\n/** @beta */\nexport interface SpawnOptions {\n\tfacing?: number\n\t/** How big it is drawn */\n\tscale?: number\n\t/** Which of the models of its type it is drawn with, for things that come in kinds like trees */\n\tlook?: string\n\t/** A name of its own, for the rules to find it by: `world.named('gate')` */\n\tname?: string\n\t/** Seconds it lasts, when that is not what its type says */\n\tlifetime?: number\n\t/** Structures only: start as a construction site, with its build time and what was paid when they are not its type's */\n\tunderConstruction?: boolean | { buildTime?: number; paid?: Cost }\n}\n\n/** See `World.internals` */\nexport interface WorldInternals {\n\tnextEntityId: number\n\tnextId: number\n\tclockShift: number\n\t/** The hour the clock stands at, when it does not move */\n\tstillHour?: number\n\tcommands: IssuedCommand[]\n\t/** Who died and has not been taken out of the world yet: at the end of the tick that comes */\n\tdead?: EntityId[]\n}\n\n/**\n * What watches a world from outside (`World.watch`): told of each command a player gives it, each save taken of it,\n * and each tick it ran\n *\n * @beta\n */\nexport interface WorldWatcher {\n\t/** A command given from outside a tick, before the tick it is applied at runs */\n\tcommand?(command: IssuedCommand): void\n\t/** A save was taken, which put the world's crowd back as a load puts it */\n\tsaved?(): void\n\t/** A tick ran */\n\tstepped?(): void\n}\n\n/** @beta */\nexport class World {\n\t/** Obstacles the navigation had no room for (`RecastNavigationOptions.maxObstacles`): what is put down past it does not block the way */\n\tobstaclesRefused = 0\n\treadonly terrain: Terrain\n\t/** The ground it started on, where it was made from a map (S36): what a save keeps only the changes of */\n\tground?: GroundBase\n\t/** The ground and the air. Agents find their own layer, everything else is about the ground */\n\treadonly nav: Navigation\n\t/**\n\t * The navigations the sides plan their routes on, of the buildings each knows (`GameModule.paths: 'seen'`): routes\n\t * of ground units are planned on their side's, and walked on `nav`. None where routes know everything\n\t *\n\t * @beta\n\t */\n\treadonly sidePaths?: SidePaths\n\t/** The ground, the air and the water, to find where a kind of unit can be */\n\tprivate readonly layers: LayeredNavigation\n\t/** The navigation an entity goes on: the air for what flies, the water for boats where the map has it, the ground for the rest */\n\t/**\n\t * The ways a type of entity walks, flies or sails on (`navFor` for one made)\n\t *\n\t * @internal\n\t */\n\tlayerOf(def: { flying?: boolean; naval?: boolean }): Navigation {\n\t\treturn this.layers.layer(def)\n\t}\n\n\t/**\n\t * An id for an entity about to be made (`Spawning`)\n\t *\n\t * @internal\n\t */\n\tnewEntityId(): number {\n\t\treturn this.nextEntityId++\n\t}\n\n\tnavFor(entity: Entity): Navigation {\n\t\treturn this.layers.layer({ flying: entity.flying, naval: entity.def.naval })\n\t}\n\t/** The air alone */\n\treadonly air: Navigation\n\treadonly registry: Registry\n\treadonly grid: BuildGrid\n\treadonly fog: FogOfWar\n\treadonly spatial: SpatialIndex\n\t/** What happened, for whoever watches: sessions, tests. Sent out at the end of each tick. Rules use `hooks` */\n\treadonly events = new Emitter()\n\t/**\n\t * What this world says about what it does: `world.log.warn('waves', 'nothing to send', { wave })`. Each entry says\n\t * the game and the tick it is from, and goes to whoever asked (`world.log.to(sink)`) and to the logger the world\n\t * was made under. It changes nothing in the world, and is not in a save\n\t */\n\treadonly log: Logger\n\t/**\n\t * The engine's checks on itself this world runs (`DebugChecks`): what it was made with (`CreateWorldOptions.checks`),\n\t * the process's (`setDebugChecks`) when it says nothing. Slow: tests and development\n\t */\n\tchecks: DebugChecks = checksOf(undefined)\n\t/** Moved on by `invalidateStats` without an entity: every entity's stats are added up again when next asked for */\n\tstatsVersion = 0\n\t/** What the debug tools follow of the rules as they run: hooks and listeners. Null when nobody asks, see `EventLog` */\n\ttrace: Trace | null = null\n\t/** Where game modules and mods take part in damage, deaths, orders and the like, see `HookEvents` */\n\treadonly hooks: Hooks\n\t/** The areas of the game, and who is in them */\n\treadonly areas: Areas\n\t/** What is set to go off later: `world.timers.after(30, waveComes)` */\n\treadonly timers: Timers\n\t/** Scripts of steps that run over time: `world.sequences.start(briefing)` */\n\treadonly sequences: Sequences\n\t/** What each player is set to do, in a mission */\n\treadonly objectives: Objectives\n\t/**\n\t * What the game counts of its players (`GameRules.score`): `world.score.add(player, 'towersLost')`, `get`, `team`.\n\t * Counts nothing in a game that does not ask\n\t *\n\t * @beta\n\t */\n\treadonly score: Score\n\t/** What is said, by whom, to whom: `world.dialog.say(player, line)`, or `talk` in a sequence */\n\treadonly dialog: Dialog\n\treadonly rng: Rng\n\treadonly players = new Map<PlayerId, Player>()\n\t/** Everything in the world, by id. Fallen heroes stay in here while they wait to be brought back */\n\treadonly entities = new Map<EntityId, Entity>()\n\t/**\n\t * The entities that are not scenery: the ones that move, act or change by themselves. Systems that run\n\t * every tick go through these instead of `entities`, which on a big map is mostly trees.\n\t */\n\treadonly actors = new Map<EntityId, Entity>()\n\t/**\n\t * The scenery each team sees right now, by team. Kept by the fog system whenever it works out what everyone sees:\n\t * scenery never moves, so this only changes then. Lets a session describe what is in sight without testing every tree\n\t */\n\treadonly sceneryInSight = new Map<number, Set<Entity>>()\n\t/** Entities by owner, heroes by owner, shops. For questions that would otherwise go through every entity */\n\treadonly index = new EntityIndex((id) => this.registry.used(id))\n\treadonly projectiles: Projectile[] = []\n\treadonly missiles: Missile[] = []\n\treadonly delayed: Delayed[] = []\n\treadonly zones: Zone[] = []\n\t/** Switches for trying things out. A game that is played for real leaves them off */\n\treadonly cheats = {\n\t\t/** Abilities and what is carried can be used again at once */\n\t\tnoCooldowns: false,\n\t\t/** Abilities cost no mana, and are cast with none left */\n\t\tnoManaCosts: false,\n\t\t/** What the players allowed the debug tools own (`debugPlayers`) takes no harm, and so does not die of it */\n\t\tinvulnerable: false,\n\t\t/** How fast the game goes, 1 as it should, 0 paused: whoever runs it (a session in the page, a server) goes by it */\n\t\tspeed: 1\n\t}\n\t/**\n\t * Players who may use the debug commands (`debug.*`, see `debugCommands.ts`): who a session lets, a seat in the page\n\t * that asked, a server started to. Not in a save: whoever loads it says again\n\t */\n\treadonly debugPlayers = new Set<PlayerId>()\n\t/**\n\t * The entity each object of the map became, by the object's id (`MapObject.id`): what the map put down as the world\n\t * was made of it (`createWorldFromMap`), and what the editor's Play here put down since (`debug.mapObject`), for the\n\t * editor to find again what it moves and takes away (EQ10). Kept in a save\n\t */\n\treadonly mapEntities = new Map<number, EntityId>()\n\t/** Spots a team sees for a while without anything there to see them */\n\treadonly reveals: Reveal[] = []\n\t/** State of game modules and mods for the whole game, see `state` */\n\treadonly states = new StateStore()\n\t/** Items lying on the ground */\n\treadonly items: GroundItem[] = []\n\t/** Runs the systems, in order, each as often as it asks */\n\treadonly scheduler: Scheduler\n\t/** The computer players: who is seated, kept in a save and seated again by a load (`world.computers.seat`) */\n\treadonly computers: Computers\n\t/** What the world's numbers started from (`rng`): 1 when none was given. A computer player's own numbers start from it and its player */\n\treadonly seed: number\n\n\treadonly tickRate: number\n\t/** Seconds per tick */\n\treadonly dt: number\n\ttick = 0\n\t/** How things are hurt, healed and die (`Life`) */\n\treadonly life: Life = new Life(this)\n\t/** What each team sees of the entities (`Sight`): the fog, what is invisible, the game's say */\n\treadonly sight: Sight = new Sight(this)\n\t/** Who is on whose side (`Sides`): teams, relations, shared vision and control */\n\treadonly sides: Sides = new Sides(this)\n\t/** How entities come into the world and are moved about in it (`Spawning`) */\n\treadonly spawning: Spawning = new Spawning(this)\n\t/** The time of day (`Clock`): the hour, night, turned forward or stopped */\n\treadonly clock: Clock = new Clock(this)\n\t/** Team that won, once the game is decided */\n\twinner: number | null = null\n\t/**\n\t * What becomes of a part of the game that throws: a hook's handler, a listener, a system, a timer, an order, a\n\t * command (`ErrorPolicy`). The game's own (`GameModule.onError`), or whoever runs the world's; with neither it\n\t * throws, as it always did. A server and a launched game end the game where nothing is said (`??= 'end'`)\n\t */\n\terrorPolicy?: ErrorPolicy\n\t/** Why the game ended on an error, once it has (`end`): the world is not stepped again */\n\tfailure: WorldFailure | null = null\n\t/** The parts switched off for having thrown (`disable`), by name (`siteKey`): kept in a save, and off again when it is loaded */\n\treadonly disabled = new Map<string, ErrorSite>()\n\t/** True through a tick: an error then can end the game; outside one it is whoever called's */\n\tprivate stepping = false\n\tprivate toldFailure = false\n\t/** Errors already answered `throw` further in: not asked about again on their way out */\n\tprivate readonly thrown = new WeakSet<object>()\n\n\tprivate nextEntityId = 1\n\tprivate nextId = 1\n\tprivate commands: IssuedCommand[] = []\n\t/** Commands each player gave since the last tick, from outside one: what `commandLimit` counts */\n\tprivate readonly given = new Map<PlayerId, number>()\n\t/** Commands let go since the last tick, by player: told of at the next (`commandRejected`) */\n\tprivate readonly overLimit = new Map<PlayerId, number>()\n\t/** Those of them the sender numbered: each answered at the next tick, refused (`commandHandled`), for a screen that waits on it */\n\tprivate readonly overLimitSeqs: { player: PlayerId; seq: number }[] = []\n\n\t/**\n\t * Commands a player may give between two ticks, at most (`issue`, from outside a tick): those past it are let go,\n\t * and the tick says so once (`commandRejected`, reason `tooManyCommands`), and answers each the sender numbered,\n\t * refused (`commandHandled`). A server's rate limit keeps far under it; this bounds what has none (a worker, a\n\t * page's own host, a script gone wrong). The computer and scripts, which give theirs in a tick, are not counted.\n\t * 100 when left out; `Infinity` for none\n\t *\n\t * @beta\n\t */\n\tcommandLimit = 100\n\n\tconstructor(options: WorldOptions) {\n\t\tthis.terrain = options.terrain\n\t\tthis.air = new AirNavigation(options.terrain.width, options.terrain.depth)\n\t\tthis.layers = new LayeredNavigation(options.navigation, this.air, options.waterNavigation)\n\t\tthis.nav = this.layers\n\t\tthis.sidePaths = options.sidePaths\n\t\tthis.registry = options.registry\n\t\tthis.log = (options.log ?? rootLogger).child({ level: options.logLevel, context: () => ({ game: this.registry.game, tick: this.tick }) })\n\t\t// what the registry has to say (a part the game does not list) is said by the world it is the registry of\n\t\tthis.registry.log = this.log\n\t\tthis.errorPolicy = options.onError\n\t\tif (options.checks !== undefined) this.checks = checksOf(options.checks)\n\t\t// an event of the game's own that the game does not list is an error (`UnlistedError`)\n\t\tthis.events.watch((type) => {\n\t\t\tif (typeof type === 'string' && !this.registry.lists('event', type)) this.registry.event(type)\n\t\t})\n\t\tthis.hooks = new Hooks(this)\n\t\tfor (const hook of options.hooks ?? coreHooks) this.hooks.add(hook)\n\t\t// a layer of cells that slows one on foot, changed in play: the ways weigh it again where it changed (EN2)\n\t\tif (hasGroundSpeeds(this.registry)) {\n\t\t\tconst slowing = new Set(this.registry.cellLayers.filter((layer) => layer.speed !== undefined && layer.speed !== 1).map((layer) => layer.id))\n\t\t\tthis.events.on(cellsChanged, ({ layer, cells }) => {\n\t\t\t\tif (!slowing.has(layer)) return\n\t\t\t\tthis.nav.groundChanged?.(cells)\n\t\t\t\tthis.sidePaths?.groundChanged(cells)\n\t\t\t})\n\t\t}\n\t\tthis.tickRate = options.tickRate ?? 30\n\t\tthis.dt = 1 / this.tickRate\n\t\tthis.seed = options.seed ?? 1\n\t\tthis.rng = new Rng(this.seed)\n\t\tthis.computers = new Computers(this)\n\t\tfor (const init of options.players) this.players.set(init.id, new Player(init))\n\t\t// a race for each who plays: drawn from the world's numbers only where one is to be drawn\n\t\tsettleRaces(this.players.values(), this.registry, (count) => this.rng.int(0, count - 1), options.randomRaces)\n\t\tthis.grid = new BuildGrid(this.terrain)\n\t\tconst teams = new Set<number>()\n\t\tfor (const player of this.players.values()) if (!player.neutral) teams.add(player.team)\n\t\tthis.fog = new FogOfWar(this.terrain.width, this.terrain.depth, [], this.terrain.levels)\n\t\t// the whole map explored from the start where the rules say (`FogRules.startExplored`), for the teams there are and\n\t\t// to come. A map says otherwise as the game is made from it (`MapDef.explored`)\n\t\tthis.fog.exploredFromStart = !!this.rules.fog?.startExplored\n\t\tfor (const team of teams) this.fog.addTeam(team)\n\t\tthis.spatial = new SpatialIndex(this.terrain.width, this.terrain.depth)\n\t\t// last: what makes a system may look at the world\n\t\tthis.scheduler = new Scheduler(options.systems(this))\n\t\tthis.areas = new Areas(this, options.areas ?? [])\n\t\tthis.timers = new Timers(this, [...coreTimers, ...(options.timers ?? [])])\n\t\tthis.sequences = new Sequences(this, options.sequences ?? [])\n\t\tthis.objectives = new Objectives(this)\n\t\tthis.dialog = new Dialog(this)\n\t\t// counted ahead of the game's listeners: one that hears of a kill reads the score with it\n\t\tthis.score = new Score(this)\n\t\tconst ids = new Set<string>()\n\t\t// the game's listeners, then the ones its sequences need for what they wait for\n\t\tfor (const listener of [...(options.listeners ?? []), ...Sequences.listenersFor(options.sequences ?? [])]) {\n\t\t\tif (ids.has(listener.id)) throw new Error(`Listener \"${listener.id}\" is there twice`)\n\t\t\tids.add(listener.id)\n\t\t\tconst off = `listener:${listener.id}`\n\t\t\tthis.events.on(listener.event, (payload) => {\n\t\t\t\t// one switched off for having thrown no longer hears anything\n\t\t\t\tif (this.disabled.size && this.disabled.has(off)) return\n\t\t\t\tthis.trace?.listener(listener.id)\n\t\t\t\ttry {\n\t\t\t\t\tlistener.run(this, payload)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.caught(error, { kind: 'listener', id: listener.id })\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\t/** The systems, in the order they run */\n\tget systems(): readonly System[] {\n\t\treturn this.scheduler.systems\n\t}\n\n\t/** Adds a system to the running world, like a computer player. It takes its place by its phase, `before` and `after` */\n\taddSystem(system: System): void {\n\t\tthis.scheduler.add(system)\n\t\t// in a loaded world, what it kept when the game was saved\n\t\tconst saved = this.savedSystems.get(system.name)\n\t\tif (saved !== undefined && system.restore) {\n\t\t\tthis.savedSystems.delete(system.name)\n\t\t\tsystem.restore(this, saved)\n\t\t}\n\t}\n\n\t/** What systems kept in themselves when the game was saved, for those not added yet */\n\tprivate readonly savedSystems = new Map<string, unknown>()\n\n\t/** Gives the systems what they kept in a save (see `System.save`): those there now, and those added later */\n\trestoreSystems(saved: Record<string, unknown>): void {\n\t\tthis.savedSystems.clear()\n\t\tfor (const [name, data] of Object.entries(saved)) {\n\t\t\tconst system = this.systems.find((each) => each.name === name)\n\t\t\tif (system?.restore) system.restore(this, data)\n\t\t\telse this.savedSystems.set(name, data)\n\t\t}\n\t}\n\n\t/** Takes a system out by name. False when there is none of that name */\n\tremoveSystem(name: string): boolean {\n\t\treturn this.scheduler.remove(name)\n\t}\n\n\tget time(): number {\n\t\treturn this.tick * this.dt\n\t}\n\n\t/** A number of the rules as it is tuned now (`TunableDef`): what it was set to while playing, or its default */\n\ttunable(id: string): number {\n\t\tconst def = this.registry.tunable(id)\n\t\tif (!def) throw new Error(`The game has no tunable \"${id}\"`)\n\t\treturn this.state(tunings)[id] ?? def.default\n\t}\n\n\t/** Tunes a number of the rules, within its bounds, and says so (`tunableChanged`) */\n\tsetTunable(id: string, value: number): void {\n\t\tconst def = this.registry.tunable(id)\n\t\tif (!def || !Number.isFinite(value)) return\n\t\tconst set = Math.min(Math.max(value, def.min), def.max)\n\t\tthis.setState(tunings, { ...this.state(tunings), [id]: set })\n\t\tthis.events.emit(tunableChanged, { id, value: set })\n\t}\n\n\t/**\n\t * Changes a definition while the game runs (S61): a unit type's health, an ability's cooldown, as the editor's Data\n\t * panel tries them. What is made of it from then on is made of the new one; a unit type's units already in the world\n\t * take it at once, with as much of their health lost as before. Kept with the world and in its save, and said\n\t * (`definitionChanged`). False for a definition the game does not have\n\t */\n\tredefine(kind: DataKind, id: string, values: DataValues): boolean {\n\t\tif (!redefineIn(this.registry, kind, id, values)) return false\n\t\tconst kept = this.state(redefinitions)\n\t\tconst before = kept[kind] ?? {}\n\t\tthis.setState(redefinitions, { ...kept, [kind]: { ...before, [id]: mergeValues(before[id] ?? {}, values) } })\n\t\tif (kind === 'units') this.retype(new Set([id]))\n\t\tthis.events.emit(definitionChanged, { kind, id, values })\n\t\treturn true\n\t}\n\n\t/**\n\t * The units of these types take their type as the registry has it now, with as much of their health lost as\n\t * before: after it was changed (`redefine`, `reloadGame`). Every type when none are said\n\t *\n\t * @internal\n\t */\n\tretype(types?: ReadonlySet<string>): void {\n\t\tfor (const entity of this.entities.values()) {\n\t\t\tif (types && !types.has(entity.def.id)) continue\n\t\t\tconst def = definitionIn(this.registry, 'units', entity.def.id)\n\t\t\tif (!def || def === entity.def) continue\n\t\t\t// filed again, as a unit that turns into another type is: what it sells, what it is, may be other now\n\t\t\tthis.index.remove(entity)\n\t\t\tentity.retype(def)\n\t\t\tthis.index.add(entity)\n\t\t\tconst hurt = entity.maxHp - entity.hp\n\t\t\tentity.maxHp = statsOf(this, entity).health\n\t\t\tif (entity.alive) entity.hp = Math.max(entity.maxHp - hurt, 1)\n\t\t}\n\t}\n\n\t/** State of a game module or a mod for the whole game: made from the component's default when first asked for */\n\tstate<T>(key: Component<T, unknown>): T {\n\t\t// one the game does not list is an error (`UnlistedError`)\n\t\tif (!this.registry.lists('component', key.id)) this.registry.used(key.id)\n\t\treturn this.states.get(key)\n\t}\n\n\tsetState<T>(key: Component<T, unknown>, value: T): void {\n\t\tthis.states.set(key, value)\n\t}\n\n\t/** The game's numbers that are not about any one unit, like the supply cap (`GameModule.rules`) */\n\tget rules(): Readonly<GameRules> {\n\t\treturn this.registry.rules\n\t}\n\n\t/** Hour of the day, 0..24. Noon in a game without days (`clock.hour`) */\n\tget hour(): number {\n\t\treturn this.clock.hour\n\t}\n\n\t/** Whether the sun is down (`clock.night`): asked for every unit's sight and stats, many times a tick */\n\tget night(): boolean {\n\t\treturn this.clock.night\n\t}\n\n\t/** Unique id for orders, order groups and projectiles */\n\tnewId(): number {\n\t\treturn this.nextId++\n\t}\n\n\tplayer(id: PlayerId): Player {\n\t\tconst player = this.players.get(id)\n\t\tif (!player) throw new Error(`Unknown player ${id}`)\n\t\treturn player\n\t}\n\n\t/** Whether an entity of this id was ever made here: one that died was, one of a number not yet given out never was */\n\tmade(id: EntityId): boolean {\n\t\treturn Number.isInteger(id) && id >= 1 && id < this.nextEntityId\n\t}\n\n\t/** Living entity with this id */\n\tget(id: EntityId | undefined): Entity | undefined {\n\t\tif (!id) return undefined\n\t\tconst entity = this.entities.get(id)\n\t\treturn entity?.alive ? entity : undefined\n\t}\n\n\t/**\n\t * The entity of this name, while it lives: one named on the map in the editor, or in code. Nothing once it is\n\t * dead, or when there never was one. A game can say which names there are: `world.named<RoadNames>('gate')`\n\t */\n\tnamed<Name extends string = string>(name: Name): Entity | undefined {\n\t\treturn this.get(this.state(names)[name])\n\t}\n\n\t/** The name an entity was given, if any */\n\tnameOf(entity: Entity): string | undefined {\n\t\tconst all = this.state(names)\n\t\tfor (const name in all) if (all[name] === entity.id) return name\n\t\treturn undefined\n\t}\n\n\t/**\n\t * Names an entity, for the rules to find it by (`named`), or takes its name away with none. It has one name, and a\n\t * name is one entity's: taking that of another that still lives throws. The name of the dead is free\n\t */\n\tsetName(entity: Entity, name: string | undefined): void {\n\t\tconst all = this.state(names)\n\t\tconst before = this.nameOf(entity)\n\t\tif (before === name) return\n\t\tif (name !== undefined) {\n\t\t\tconst holder = this.named(name)\n\t\t\tif (holder) throw new Error(`\"${name}\" is the name of ${holder.def.id}#${holder.id} already: ${entity.def.id}#${entity.id} cannot have it too`)\n\t\t\tall[name] = entity.id\n\t\t}\n\t\tif (before !== undefined) delete all[before]\n\t}\n\n\t/**\n\t * What the map this world was made from says that is not an entity: its name, and what the game kept with it\n\t * (`GameMap.data`). Kept in the world, so a save has it. Empty for a world made without a map\n\t */\n\tget map(): WorldMap {\n\t\treturn new WorldMap(this.state(mapInfo))\n\t}\n\n\t/** Whether two players fight each other (`sides.enemies`): asked of every target, every tick */\n\tareEnemies(a: PlayerId, b: PlayerId): boolean {\n\t\treturn this.sides.enemies(a, b)\n\t}\n\n\t/** Whether two players are on one side (`sides.allies`) */\n\tareAllies(a: PlayerId, b: PlayerId): boolean {\n\t\treturn this.sides.allies(a, b)\n\t}\n\n\t/** Whether a player may command an entity (`sides.mayCommand`): what every command is checked against */\n\tmayCommand(player: PlayerId, entity: Entity): boolean {\n\t\treturn this.sides.mayCommand(player, entity)\n\t}\n\n\t/** Whether a team currently sees the entity (`sight.sees`): asked of every entity, team and snapshot */\n\tisVisibleTo(entity: Entity, team: number): boolean {\n\t\treturn this.sight.sees(entity, team)\n\t}\n\n\t/**\n\t * Creates an entity. Structures are centered on the grid cells closest to `position`;\n\t * the caller is responsible for checking `grid.canPlace` when that matters.\n\t */\n\t/**\n\t * A prefab put down as one: its objects spawned for the owner given, its camps and areas with them, turned and sized\n\t * around its middle (`spawnPrefab`)\n\t *\n\t * @beta\n\t */\n\tspawnPrefab(prefab: PrefabDef | string, options: SpawnPrefabOptions): SpawnedPrefab {\n\t\treturn spawnPrefab(this, prefab, options)\n\t}\n\n\tspawn(typeId: string, owner: PlayerId, position: Vec2, options: SpawnOptions = {}): Entity {\n\t\treturn this.spawning.spawn(typeId, owner, position, options)\n\t}\n\n\t/**\n\t * What its parts call off as an entity leaves its owner, dying or given away (`Component.onLeave`)\n\t *\n\t * @internal\n\t */\n\tleave(entity: Entity): void {\n\t\tthis.spawning.leave(entity)\n\t}\n\n\t/**\n\t * Turns scenery into an actor, for good: something gave it a reason to be looked at every tick, like a buff\n\t * that has to run out. Whatever does that to an entity calls this; the debug checks catch what forgets to.\n\t */\n\twake(entity: Entity): void {\n\t\tthis.spawning.wake(entity)\n\t}\n\n\t/**\n\t * Sets cells of one of the game's layers (`Terrain.cells`, `CellLayerDef`) to a value: by their indices, or those in\n\t * a shape. A bush burnt, grass grown. The players who see a cell are told at once (a `cells` event), the others as it\n\t * comes into their sight (`TeamMemory.cells`), and saves keep it. Returns the cells that changed\n\t */\n\t/**\n\t * Changes what the map looks like beyond its ground, as the game goes: a storm rolling in (`weather`), night mist\n\t * (`fog`), the sky going red. Over what it was, field by field; a field given as undefined goes back to none. Every\n\t * player sees it (an `environment` event), a save keeps it, and a player who joins later is told it as it is.\n\t *\n\t * `over` (seconds) has the screens ease into it, from what they show: the rain comes on, the wind gets up, the mist\n\t * thickens. The world has the new look at once: a save or a player who joins sees it as it ends\n\t */\n\tsetEnvironment(change: Partial<MapEnvironment>, options: { over?: number } = {}): void {\n\t\tconst info = this.state(mapInfo)\n\t\tconst environment: MapEnvironment = { ...info.environment }\n\t\tfor (const [key, value] of Object.entries(change) as [keyof MapEnvironment, unknown][]) {\n\t\t\tif (value === undefined) delete environment[key]\n\t\t\telse Object.assign(environment, { [key]: structuredClone(value) })\n\t\t}\n\t\tthis.setState(mapInfo, { ...info, environment })\n\t\tconst over = options.over && options.over > 0 ? options.over : undefined\n\t\tthis.events.emit(environmentChanged, { environment: structuredClone(environment), ...(over && { over }) })\n\t}\n\n\t/**\n\t * Plays one of the view's effects (`GameView.fx.defs`) on the screens of the players who see where it is, or those it is\n\t * for (`to`): at a place (`at`), or on an entity (`on`, at a `point` of its model), with knobs (`params`). Its random\n\t * parts go by a seed, the same on every screen. Nothing it does decides anything: it is not in the world's state, a\n\t * save, or what a player who joins later is told. What it gives back stops it (`stopEffect`)\n\t *\n\t * @beta\n\t */\n\teffect(effect: string, options: EffectOptions = {}): number {\n\t\treturn playEffect(this, effect, options)\n\t}\n\n\t/**\n\t * Stops an effect the rules played (`effect`) on every screen, as its own `stop` says, over `fade` seconds\n\t *\n\t * @beta\n\t */\n\tstopEffect(id: number, options: { fade?: number } = {}): void {\n\t\tstopEffect(this, id, options)\n\t}\n\n\tsetCells(layer: string, cells: readonly number[] | AreaShape, value: number): number[] {\n\t\tconst { terrain } = this\n\t\tif (!Number.isInteger(value) || value < 0 || value > 255) throw new Error(`setCells: ${value} is not a value a cell holds, 0 to 255`)\n\t\tconst values = terrain.cellLayer(layer)\n\t\tconst changed: number[] = []\n\t\tconst was: number[] = []\n\t\tfor (const c of Array.isArray(cells) ? cells : cellsIn(terrain, cells as AreaShape)) {\n\t\t\tif (c < 0 || c >= values.length || values[c] === value) continue\n\t\t\twas.push(values[c])\n\t\t\tvalues[c] = value\n\t\t\tchanged.push(c)\n\t\t}\n\t\tif (!changed.length) return changed\n\t\t// what each team that does not see a cell knew of it, for it to be told as it comes into sight (RV7)\n\t\trememberUnseenCells(this, layer, changed, was, value)\n\t\tthis.events.emit(cellsChanged, { layer, cells: changed, value })\n\t\treturn changed\n\t}\n\n\t/**\n\t * Reshapes a part of the ground as the game goes (`TerrainPatch`): its heights, cliffs, water, paint, what is kept\n\t * off it and the game's layers of cells, all at once, as the editor's Play here pushes the map's ground into the game\n\t * played (`debug.ground`, EQ10). What the rules go by follows: who sees whom from the levels, where can be built, and\n\t * the ways, cut again of the ground as it is now (`Navigation.reshape`: on this thread, every machine the same, and\n\t * not for nothing on a big map). What stands on it stays where it is. Every player is told (a `ground` event), and\n\t * saves keep it. Throws where the patch does not fit the ground (`terrainPatchProblem`)\n\t *\n\t * @beta\n\t */\n\treshapeGround(patch: TerrainPatch): void {\n\t\tapplyTerrainPatch(this.terrain, patch)\n\t\tthis.fog.levelsChanged()\n\t\tthis.grid.groundChanged(patch)\n\t\tthis.nav.reshape?.()\n\t\tthis.sidePaths?.reshape()\n\t\tthis.events.emit(groundReshaped, { patch })\n\t}\n\n\t/** Lets a team see a spot for a while, with nothing standing there */\n\treveal(team: number, point: Vec2, radius: number, seconds: number, options: { quiet?: boolean } = {}): Reveal {\n\t\tconst reveal: Reveal = { id: this.nextId++, team, x: point.x, z: point.z, radius, left: seconds, ...(options.quiet && { quiet: true }) }\n\t\tthis.reveals.push(reveal)\n\t\treturn reveal\n\t}\n\n\t/** Puts a unit somewhere else, where it stands: the way through is not its concern. Structures stay where they were built */\n\tplace(entity: Entity, point: Vec2): void {\n\t\tthis.spawning.place(entity, point)\n\t}\n\n\t/**\n\t * Gives an entity to another player, from now on in everything: whose it is, whom it fights, what it counts for.\n\t * What it was doing is called off, and what it was making is given back to the one it belonged to\n\t */\n\tsetOwner(entity: Entity, owner: PlayerId): void {\n\t\tthis.spawning.setOwner(entity, owner)\n\t}\n\n\t/**\n\t * Takes a unit out of the world for a while, or puts it back: a worker inside a gold mine, a unit carried in\n\t * something. While hidden it is not found, not seen and in nobody's way, and its orders wait. It comes back at\n\t * `at`, or where it went in, on the nearest ground it can stand on. Structures cannot hide\n\t */\n\tsetHidden(entity: Entity, hidden: boolean, at?: Vec2): void {\n\t\tthis.spawning.setHidden(entity, hidden, at)\n\t}\n\n\t/** Gives an entity a time after which it is gone by itself, like a ward, or takes it away with `null` */\n\tsetLifetime(entity: Entity, seconds: number | null): void {\n\t\tthis.spawning.setLifetime(entity, seconds)\n\t}\n\n\t/** Deals damage (`life.damage`): the hooks, armor and shields, health, death */\n\tdamage(target: Entity, amount: number, source?: Entity, options: DamageOptions = {}): void {\n\t\tthis.life.damage(target, amount, source, options)\n\t}\n\n\t/** Heals (`life.heal`): how much it healed */\n\theal(target: Entity, amount: number, source?: Entity): number {\n\t\treturn this.life.heal(target, amount, source)\n\t}\n\n\t/** Kills (`life.kill`) */\n\tkill(entity: Entity, killer?: Entity, attack = false, reason: DeathReason = 'killed'): void {\n\t\tthis.life.kill(entity, killer, attack, reason)\n\t}\n\n\t/**\n\t * Tells a player something, like why what they asked for cannot be done. The world says which message,\n\t * and the player's screen finds the words for it (see `Message`). A bare string is a key without params\n\t */\n\tmessage(player: PlayerId, message: MessageRef, kind: MessageKind = 'error'): void {\n\t\tconst said = toMessage(message)\n\t\t// told while a command of theirs is carried out: why it was refused\n\t\tconst { handling } = this\n\t\tif (handling && handling.player === player && kind === 'error') handling.refusal ??= said\n\t\tthis.events.emit(messageSent, { player, message: said, kind })\n\t}\n\n\t/**\n\t * Gives a player a hint (campaign plan CP5): a message of the kind `hint`, shown for `seconds` (the screen's own\n\t * time when left out), which a player who turned hints off in the settings does not see\n\t */\n\thint(player: PlayerId, message: MessageRef, options: { seconds?: number } = {}): void {\n\t\tconst said: WorldEvents['messageSent'] = { player, message: toMessage(message), kind: 'hint' }\n\t\tif (options.seconds !== undefined) said.seconds = options.seconds\n\t\tthis.events.emit(messageSent, said)\n\t}\n\n\t/** The command being carried out, to find out whether it was refused: see `executeCommand` */\n\thandling?: { player: PlayerId; refusal: Message | undefined }\n\n\t/**\n\t * What a save needs that is the world's own business: id counters, the clock and the commands waiting for\n\t * the next tick. For `saveWorld` and `loadWorld` only\n\t */\n\tinternals(): WorldInternals {\n\t\treturn {\n\t\t\tnextEntityId: this.nextEntityId,\n\t\t\tnextId: this.nextId,\n\t\t\tclockShift: this.clock.shift,\n\t\t\t...(this.clock.still !== undefined && { stillHour: this.clock.still }),\n\t\t\tcommands: this.commands,\n\t\t\t...(this.life.dead.length > 0 && { dead: this.life.dead.map((entity) => entity.id) })\n\t\t}\n\t}\n\n\t/** Puts back what `internals` gave, for `loadWorld` only */\n\trestoreInternals(internals: WorldInternals): void {\n\t\tthis.nextEntityId = internals.nextEntityId\n\t\tthis.nextId = internals.nextId\n\t\tthis.clock.shift = internals.clockShift\n\t\tthis.clock.still = internals.stillHour\n\t\tthis.commands = [...internals.commands]\n\t\t// the dead are found once the entities are back: see `restoreDead`\n\t}\n\n\t/** Puts back who died and waits to be taken out (`WorldInternals.dead`), once the entities are back. For `loadWorld` only */\n\trestoreDead(ids: readonly EntityId[]): void {\n\t\tfor (const id of ids) {\n\t\t\tconst entity = this.entities.get(id)\n\t\t\tif (!entity) throw new Error(`Save: the dead ${id} is not in it`)\n\t\t\tthis.life.dead.push(entity)\n\t\t}\n\t}\n\n\t/**\n\t * Queues a player command. It is applied at the start of the next tick; talk (a command whose def says\n\t * `outsideTick`: chat, a ping) given between ticks is carried out at once, a paused game's too (RV14)\n\t */\n\tissue(command: IssuedCommand): void {\n\t\tif (!this.stepping && typeof command?.type === 'string' && this.registry.command(command.type)?.outsideTick) {\n\t\t\t// kept by what records the game where it was given, and carried out there again by its replay\n\t\t\tfor (const watcher of this.watchers) watcher.command?.(command)\n\t\t\texecuteCommand(this, command)\n\t\t\treturn\n\t\t}\n\t\tif (!this.stepping && typeof command?.player === 'number') {\n\t\t\tconst given = (this.given.get(command.player) ?? 0) + 1\n\t\t\tthis.given.set(command.player, given)\n\t\t\tif (given > this.commandLimit) {\n\t\t\t\tthis.overLimit.set(command.player, (this.overLimit.get(command.player) ?? 0) + 1)\n\t\t\t\tif (typeof command.seq === 'number') this.overLimitSeqs.push({ player: command.player, seq: command.seq })\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tthis.commands.push(command)\n\t\t// one given from outside a tick is a player's: what a replay of commands keeps. One given in a tick (a computer\n\t\t// player's, a script's) the tick gives again when it runs again\n\t\tif (!this.stepping) for (const watcher of this.watchers) watcher.command?.(command)\n\t}\n\n\t/** What watches the world from outside (`watch`) */\n\tprivate readonly watchers = new Set<WorldWatcher>()\n\n\t/**\n\t * Watches the world from outside, for what records it (a replay of commands, `recordGame`): each command a player\n\t * gives it, each save taken of it, each tick. Changes nothing. Gives what stops watching\n\t *\n\t * @beta\n\t */\n\twatch(watcher: WorldWatcher): () => void {\n\t\tthis.watchers.add(watcher)\n\t\treturn () => void this.watchers.delete(watcher)\n\t}\n\n\t/** A save of the world was taken, which put its crowd back (`saveWorld`): told to what watches it. The engine's */\n\tsaved(): void {\n\t\tfor (const watcher of this.watchers) watcher.saved?.()\n\t}\n\n\t/** Advances the simulation by one fixed tick */\n\t/**\n\t * The entities that are all of what is asked, for scripts: whose they are, of which type, in which area. Only the\n\t * living, unless asked. A new list: for what runs every tick, go through `index` or `areas` instead\n\t */\n\tfind(filter: { owner?: PlayerId; type?: string; area?: string; dead?: boolean } = {}): Entity[] {\n\t\tconst from =\n\t\t\tfilter.area !== undefined\n\t\t\t\t? this.areas.inside(filter.area)\n\t\t\t\t: filter.owner !== undefined\n\t\t\t\t\t? this.index.ownedBy(filter.owner)\n\t\t\t\t\t: this.entities.values()\n\t\tconst found: Entity[] = []\n\t\tfor (const entity of from) {\n\t\t\tif (filter.owner !== undefined && entity.owner !== filter.owner) continue\n\t\t\tif (filter.type !== undefined && entity.def.id !== filter.type) continue\n\t\t\tif (!filter.dead && !entity.alive) continue\n\t\t\tfound.push(entity)\n\t\t}\n\t\treturn found\n\t}\n\n\t/**\n\t * Marks a moment to start again from, like the start of a wave, with what the player is told it is (\"Wave 6\").\n\t * A session keeps a save of the world as it is at the end of this tick, for \"Retry from wave 6\"\n\t */\n\tcheckpoint(label: MessageRef): void {\n\t\tthis.events.emit(checkpoint, { label: toMessage(label) })\n\t}\n\n\tstep(): void {\n\t\t// a game that ended on an error stays as it was: nothing of it runs again\n\t\tif (this.failure) return\n\t\tthis.events.hold()\n\t\tthis.stepping = true\n\t\ttry {\n\t\t\tthis.advance()\n\t\t} catch (error) {\n\t\t\t// the tick a game ends in is left where it failed (`caught`): everything else goes on to whoever stepped\n\t\t\tif (!(error instanceof GameEnded)) throw error\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\t// what happened goes out now that the tick is over\n\t\t\t\tthis.events.release()\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof GameEnded)) throw error\n\t\t\t} finally {\n\t\t\t\tthis.stepping = false\n\t\t\t}\n\t\t}\n\t\tif (this.failure && !this.toldFailure) {\n\t\t\tthis.toldFailure = true\n\t\t\tthis.events.emit(worldFailed, this.failure)\n\t\t}\n\t\tfor (const watcher of this.watchers) watcher.stepped?.()\n\t}\n\n\t/**\n\t * What a part of the game that threw comes to, by what the world says of errors (`errorPolicy`). It returns when\n\t * the part is to be switched off or let go (`disable`): the caller does that, and goes on. It throws otherwise: the\n\t * error itself (`throw`), or what leaves the tick of a game that ends there (`end`)\n\t */\n\tcaught(error: unknown, where: ErrorSite): void {\n\t\t// already answered further in: a game ending, or an error on its way out\n\t\tif (error instanceof GameEnded) throw error\n\t\tconst judged = typeof error === 'object' && error !== null\n\t\tif (judged && this.thrown.has(error)) throw error\n\t\tconst policy = this.errorPolicy ?? 'throw'\n\t\t// whose it is, in a game with mods\n\t\tconst mod = modOfPart(this.registry.module, where)\n\t\tif (mod) where = { ...where, mod }\n\t\tlet answer = typeof policy === 'function' ? policy(error, where, this) : policy\n\t\t// outside a tick there is no tick to leave: whoever called the world is told\n\t\tif (answer === 'end' && !this.stepping) answer = 'throw'\n\t\tif (answer === 'throw') {\n\t\t\tif (judged) this.thrown.add(error)\n\t\t\tthrow error\n\t\t}\n\t\tconst fields = { ...where, error: errorFields(error) }\n\t\tif (answer === 'disable') {\n\t\t\tconst kept =\n\t\t\t\twhere.kind === 'order' ? 'the order is taken off the unit' : where.kind === 'command' ? 'the command is refused' : 'it is switched off'\n\t\t\tthis.log.error('game', `${siteWords(where)} threw: ${kept}, and the game goes on`, fields)\n\t\t\tif (where.kind !== 'order' && where.kind !== 'command') this.disabled.set(siteKey(where), siteOf(where))\n\t\t\treturn\n\t\t}\n\t\tthis.failure = { message: `The game stopped: ${siteWords(where)} failed`, where, error: errorFields(error), tick: this.tick }\n\t\tthis.log.error('game', `${siteWords(where)} threw: the game ends`, fields)\n\t\tthrow new GameEnded(this.failure)\n\t}\n\n\t/** Switches off the parts a save says were (`world.disabled`): the same game goes on as the one that was saved */\n\tdisable(sites: Iterable<ErrorSite>): void {\n\t\tfor (const site of sites) {\n\t\t\tthis.disabled.set(siteKey(site), siteOf(site))\n\t\t\tif (site.kind === 'system') this.scheduler.disable(site.id)\n\t\t\telse if (site.kind === 'hook') this.hooks.remove(site.hook as AnyHook, site.id)\n\t\t}\n\t}\n\n\tprivate advance(): void {\n\t\tif (this.checks.scenery) this.checkScenery()\n\t\tif (this.checks.index) this.index.check(this.entities.values())\n\t\t// where everything stood at the start of the tick: the renderer draws in between this and where it ends up\n\t\tfor (const entity of this.actors.values()) {\n\t\t\tentity.prevPos.x = entity.pos.x\n\t\t\tentity.prevPos.z = entity.pos.z\n\t\t\tentity.prevFacing = entity.facing\n\t\t}\n\n\t\tthis.given.clear()\n\t\tif (this.overLimit.size) {\n\t\t\tfor (const [player, count] of this.overLimit)\n\t\t\t\tthis.events.emit(commandRejected, {\n\t\t\t\t\tplayer,\n\t\t\t\t\tkind: 'tooMany',\n\t\t\t\t\treason: `tooManyCommands: ${count} past the ${this.commandLimit} a tick takes`\n\t\t\t\t})\n\t\t\tthis.overLimit.clear()\n\t\t}\n\t\tif (this.commands.length) {\n\t\t\tconst commands = this.commands\n\t\t\tthis.commands = []\n\t\t\tfor (const command of commands) executeCommand(this, command)\n\t\t}\n\t\t// and each let go that its sender numbered is answered, refused, after those taken\n\t\tif (this.overLimitSeqs.length) {\n\t\t\tfor (const { player, seq } of this.overLimitSeqs) this.events.emit(commandHandled, { player, seq, refusal: { key: 'tooManyCommands' } })\n\t\t\tthis.overLimitSeqs.length = 0\n\t\t}\n\n\t\tthis.spatial.rebuild(this.actors.values())\n\t\tthis.scheduler.run(this)\n\n\t\tif (this.life.dead.length) {\n\t\t\tfor (const entity of this.life.dead) {\n\t\t\t\tthis.entities.delete(entity.id)\n\t\t\t\tthis.actors.delete(entity.id)\n\t\t\t\tthis.index.remove(entity)\n\t\t\t\tthis.hooks.run('remove', entity)\n\t\t\t\tthis.events.emit(entityRemoved, entity)\n\t\t\t}\n\t\t\tthis.life.dead.length = 0\n\t\t}\n\t\tthis.tick++\n\t}\n\n\t/** Throws when scenery has something that only actors get looked after for. See `debugChecks` */\n\tprivate checkScenery(): void {\n\t\tfor (const entity of this.entities.values()) {\n\t\t\tif (!entity.scenery || !entity.alive) continue\n\t\t\tconst problem =\n\t\t\t\t(!isScenery(entity.def) && 'a type that is not scenery') ||\n\t\t\t\t(!this.player(entity.owner).neutral && 'an owner') ||\n\t\t\t\t(entity.buffs.length > 0 && 'buffs') ||\n\t\t\t\t(entity.orders.length > 0 && 'orders') ||\n\t\t\t\t(entity.hidden && 'been hidden') ||\n\t\t\t\t(entity.get(dashing) && 'a dash') ||\n\t\t\t\t(entity.has(constructionSite) && 'a construction site') ||\n\t\t\t\t(entity.expires !== null && 'a lifetime') ||\n\t\t\t\t((entity.has(exposure) || entity.has(detection)) && 'been exposed or detected')\n\t\t\tif (problem) throw new Error(`Scenery ${entity.def.id}#${entity.id} has ${problem}, but nothing woke it up (World.wake)`)\n\t\t}\n\t}\n\n\t/** Whether it was disposed: its navigation is freed, and it is not to be stepped again */\n\tget disposed(): boolean {\n\t\treturn this.wasDisposed\n\t}\n\tprivate wasDisposed = false\n\n\t/**\n\t * Frees what the world holds outside of JavaScript's memory: its navigation (a navmesh, its tiles and its crowd, in\n\t * WebAssembly, which is never collected by itself). Whoever made the world disposes it once done with it: the\n\t * session that owns it (`LocalSession`'s `ownsWorld`), the host (`SessionHost`'s), a test. Once is enough: again does\n\t * nothing\n\t */\n\tdispose(): void {\n\t\tif (this.wasDisposed) return\n\t\tthis.wasDisposed = true\n\t\tthis.events.clear()\n\t\tthis.nav.dispose()\n\t\tthis.sidePaths?.dispose()\n\t\tthis.entities.clear()\n\t\tthis.actors.clear()\n\t\tthis.index.clear()\n\t}\n}\n","import type { CellLayerDef } from './cellLayers'\nimport { regionCinematic } from './cinematics'\nimport type { GameFileDef } from './gameFiles'\nimport { toldBuffOff, toldBuffOn } from './abilities/buffs'\nimport { toldCast, toldChannelEnded, toldChannelStarted, toldWindup } from './abilities/castTold'\nimport { toldMana, toldMissileHit } from './abilities/effects'\nimport { toldStrike } from './abilities/land'\nimport { toldCells, toldCellsSeen } from './cellLayers'\nimport { toldCinematic, toldCinematicCue } from './cinematics'\nimport { toldCommand } from './commands'\nimport { toldRustle } from './concealment'\nimport { toldLine, toldLineEnded } from './dialog'\nimport { toldEffect, toldEffectStopped } from './effects'\nimport { toldBounty } from './features'\nimport { toldRedefined } from './gameData'\nimport { toldLevelUp, toldRevived, toldXp } from './hero'\nimport { toldPicked } from './items'\nimport { toldCrit, toldDamage, toldDeath, toldHeal } from './life'\nimport { toldEnvironment } from './map'\nimport { toldMessage } from './messages'\nimport { toldObjective } from './objectives'\nimport { eventsPart, type ReplicatedEvent, type SnapshotPart, snapshotPart } from './replication'\nimport { debugPart } from './debugCommands'\nimport { hourPart } from './clock'\nimport { outcomePart } from './systems/victory'\nimport { projectilesPart } from './systems/combatTold'\nimport { missilesPart } from './abilities/effects'\nimport { itemsPart } from './items'\nimport { revealsPart } from './systems/fog'\nimport { scoreLinePart, scorePart } from './score'\nimport { corpsesPart } from './summons'\nimport { toldAttack, toldImpact, toldMiss, toldShot } from './systems/combatTold'\nimport { toldBuilt, toldConstructionCancelled, toldConstructionStarted, toldWork } from './systems/construction'\nimport { toldChop, toldResource } from './systems/economy'\nimport { toldResearched, toldTrained, toldUpgradeStarted } from './systems/production'\nimport { toldUpgradeCancelled } from './systems/productionQueue'\nimport { toldChat, toldPing } from './talk'\nimport { toldMorphed } from './tech'\nimport type { PrefabDef } from './prefabs'\nimport type { MapGenerator } from './generate'\nimport type { ErrorPolicy } from './errors'\nimport type { Logger, LogLevel } from './log'\nimport type { Component } from './components'\nimport type { EventKey } from './events'\nimport type { EffectKind } from './abilities/effects'\nimport { coreEffects } from './abilities/effects/core'\nimport { coreFormations, type FormationDef } from './formation'\nimport { type CommandDef, coreCommands } from './commands'\nimport { debugCommands, redefineCommand, toldGround } from './debugCommands'\nimport { drawFromGroup, dropFromTable } from './randomGroups'\nimport { boardOrder, loadOrder, transportSank, transportSystem, unloadOrder } from './transport'\nimport { gateStates, setUpGates } from './gates'\nimport { tuneCommand, type TunableDef } from './tunables'\nimport type { EditableData } from './gameData'\nimport { spawnCamp } from './camps'\nimport { corpseSystem, summonEffects } from './summons'\nimport { dispelEffects } from './abilities/dispel'\nimport { coreHooks } from './features'\nimport type { HookDef } from './hooks'\nimport { checkRaces, type RaceDef, raceHooks, raceResources } from './races'\nimport { spawnStart, type StartDef } from './start'\nimport {\n\ttype AbilityDef,\n\ttype BuffDef,\n\ttype Cost,\n\ttype DayCycle,\n\ttype ItemDef,\n\tnoStats,\n\ttype ResourceDef,\n\ttype ResourceKind,\n\ttype StatDef,\n\ttype Stats,\n\ttype UnitTypeDef,\n\ttype UpgradeDef,\n\ttype UpkeepTier\n} from './defs'\nimport { RecastNavigation, type RecastNavigationOptions } from './navigation/recast'\nimport { SidePaths, sideKnowledgeSystem } from './navigation/sidePaths'\nimport { SizedNavigation } from './navigation/sized'\nimport type { Navigation } from './navigation/navigation'\nimport {\n\tattackGroundOrder,\n\tattackMoveOrder,\n\tattackOrder,\n\tattackPathOrder,\n\tpatrolPathOrder,\n\tfollowOrder,\n\tfollowPathOrder,\n\tholdOrder,\n\tmoveOrder,\n\tpatrolOrder\n} from './orders/basic'\nimport { buildOrder, constructOrder, repairOrder } from './orders/build'\nimport { castOrder } from './orders/cast'\nimport { dropItemOrder, pickUpOrder } from './orders/items'\nimport { harvestOrder, returnOrder } from './orders/harvest'\nimport type { Entity, PlayerId } from './entity'\nimport type { BrainDef } from './ai/brain'\nimport type { GameAi } from './ai/profiles'\nimport type { GamePack } from './packs/pack'\nimport type { StatPart } from './stats'\nimport type { MapProblem } from './mapFields'\nimport { inventorySlots } from './inventory'\nimport { gathering } from './orders/harvest'\nimport { productionQueue } from './systems/productionQueue'\nimport { cargo } from './transport'\nimport { fieldValues, type MapEditorDef, mapCampData, mapFields, mapRegionData, mapPlayerData } from './mapFields'\nimport { MAX_TILES, type TileDef } from './tiles'\nimport { DEFAULT_MAX_PLAYERS, type GameMap, MAP_CREEPS, MAP_NEUTRAL, MAX_MAP_PLAYERS, type MapObjectOrder } from './map'\nimport { mapInfo } from './names'\nimport { type GameData, withData } from './gameData'\nimport type { PlayerInit, Purse } from './player'\nimport { type OrderBehavior, Registry, type System, type SystemDef } from './registry'\nimport { checkDamageTable, overRules, resolveRules, type RulesInit } from './rules'\nimport { abilitySystem } from './systems/abilities'\nimport { combatSystem } from './systems/combat'\nimport { constructionSystem } from './systems/construction'\nimport { supplySystem } from './systems/economy'\nimport { fogSystem } from './systems/fog'\nimport { lifeSystem } from './systems/life'\nimport { movementSystem } from './systems/movement'\nimport { orderSystem } from './systems/orders'\nimport { productionSystem } from './systems/production'\nimport { lastTeamStanding } from './systems/victory'\nimport type { Terrain } from './terrain'\nimport { restoreWorld, SaveError, savedPlayers, type SaveRules, updateSave, type WorldSave } from './save'\nimport { cloneTerrain, groundOf, MissingGround, startedOn, startingTerrain } from './ground'\nimport { World, type WorldChecks } from './world'\nimport { resolveScore, scoreSystem } from './score'\nimport { type AreaDef, areaSystem } from './areas'\nimport { type SequenceDef, sequenceSystem } from './sequences'\nimport { type TimerDef, timerSystem } from './timers'\nimport type { ListenerDef } from './events'\nimport { giveMapOrders, spawnMapObject } from './mapObjects'\nimport { coreComponents } from './coreComponents'\nimport { groundSpeedOn, hasGroundSpeeds } from './groundSpeed'\n\nconst coreOrders: OrderBehavior[] = [\n\tmoveOrder,\n\tholdOrder,\n\tattackOrder,\n\tattackMoveOrder,\n\tfollowPathOrder,\n\tattackPathOrder,\n\tpatrolPathOrder,\n\tattackGroundOrder,\n\tpatrolOrder,\n\tfollowOrder,\n\tharvestOrder,\n\treturnOrder,\n\tbuildOrder,\n\tconstructOrder,\n\trepairOrder,\n\tcastOrder,\n\tpickUpOrder,\n\tdropItemOrder,\n\tboardOrder,\n\tloadOrder,\n\tunloadOrder\n]\n\n/**\n * The systems the engine brings along, by phase: decisions first, then movement, then everything that reacts to where\n * units ended up. Within a phase, in this order. A module can do without any of them by name (`GameModule.withoutSystems`),\n * or put its own in place of one by giving a system the same name\n *\n * @beta\n */\nexport const coreSystems: readonly System[] = [\n\ttimerSystem,\n\tabilitySystem,\n\torderSystem,\n\tmovementSystem,\n\tcombatSystem,\n\tconstructionSystem,\n\tproductionSystem,\n\tsupplySystem,\n\tareaSystem,\n\tlifeSystem,\n\tfogSystem,\n\tsequenceSystem,\n\ttransportSystem,\n\tcorpseSystem\n]\n\n/**\n * A game module is the data and rules of one kind of game. The engine knows nothing\n * about peasants or town halls, it gets all of that from here.\n *\n * @beta\n */\nexport interface GameModule {\n\tid: string\n\tname: string\n\t/** `major.minor.patch`, for mods to say which versions of the game they work with. 1.0.0 when left out */\n\tversion?: string\n\t/** The mods on it, with their versions, when it was made with `composeGame` */\n\tmods?: { id: string; version: string; hash?: string }[]\n\t/**\n\t * Players a map of the game may have, besides the neutral and the creeps: 8 when left out, 32 at most\n\t * (`MAX_MAP_PLAYERS`). A map with more is refused, saying so, not cut\n\t */\n\tmaxPlayers?: number\n\tunits: UnitTypeDef[]\n\t/**\n\t * The sides players can play, each with its own roster (`UnitTypeDef.race`): none when left out, and with that no\n\t * race anywhere. The first is what a player plays when nobody chose\n\t */\n\traces?: RaceDef[]\n\tupgrades?: UpgradeDef[]\n\tabilities?: AbilityDef[]\n\tbuffs?: BuffDef[]\n\titems?: ItemDef[]\n\t/** What players have amounts of and pay with, in the order they are shown. None when left out */\n\tresources?: ResourceDef[]\n\t/** The resource prices, bounties, revives and sales are in. The first resource when left out */\n\tcurrency?: ResourceKind\n\tupkeep?: UpkeepTier[]\n\t/** Stats of the game's own, next to the engine's (`CoreStats`). Units, buffs, items and upgrades change them, and abilities scale with them, like any other */\n\tstats?: StatDef[]\n\t/** Day and night. Always day when left out */\n\tday?: DayCycle\n\t/** The numbers of the game that are not about any one unit, like the supply cap. The engine's for those left out */\n\trules?: RulesInit\n\t/**\n\t * Kinds of effects abilities can have, next to the ones the engine knows (`defineEffect`): one of a type the engine has\n\t * takes its place\n\t */\n\teffects?: EffectKind[]\n\t/** Extra order types, or replacements for the core ones */\n\torders?: OrderBehavior[]\n\t/**\n\t * Formations of its own for units ordered to a point together (`FormationDef`), next to the engine's `rows`,\n\t * `circle`, `square` and `none`, or in place of one of the same id. Which an order takes is the order's to say\n\t * (`OrderInit.formation`), and the rules' where it does not (`GameRules.movement.formation`)\n\t */\n\tformations?: FormationDef[]\n\t/** Commands of the game's own, made with `defineCommand`, or replacements for the core ones */\n\tcommands?: CommandDef[]\n\t/** Types of the engine's own commands, or a pack's, the module does without (`coreCommands`, `heroCommands`) @beta */\n\twithoutCommands?: string[]\n\t/** Types of the engine's own orders, or a pack's, the module does without: a unit is then never given one @beta */\n\twithoutOrders?: string[]\n\t/**\n\t * The parts of the rules the game opts into, with what they bring (`GamePack`): `[withHeroes()]` for heroes, camps\n\t * and shops. None when left out. The game's own commands, orders, systems and hooks come after a pack's, and one of\n\t * the same id takes its place\n\t *\n\t * @beta\n\t */\n\tpacks?: GamePack[]\n\t/**\n\t * Systems of the game's own. They run after the core ones unless they give a phase (see `System`); one with the name\n\t * of a core system takes its place, and its phase too unless it gives its own. A function makes a system for each\n\t * world: what keeps state between ticks has to be made that way, or every game made from the module shares it\n\t */\n\tsystems?: SystemDef[]\n\t/** Names of the engine's own systems the module does without (see `coreSystems`) */\n\twithoutSystems?: string[]\n\t/** Handlers of hooks: how the module takes part in damage, deaths, orders. One with the id of a core one takes its place */\n\thooks?: HookDef[]\n\t/** Ids of the engine's own hook handlers the module does without, like `bounty` (see `coreHooks`) */\n\twithoutHooks?: string[]\n\t/** How the game reacts to events, the engine's and its own (see `defineListener`) */\n\tlisteners?: ListenerDef[]\n\t/**\n\t * The state of its own the game keeps (see `defineComponent`): on entities, players and the world. Given here as\n\t * timers and listeners are, so that a world knows who is told which (`replicate`) from its own game, and not from\n\t * whatever else the process has loaded. One used without being listed is an error (`UnlistedError`): no world\n\t * finds it, so a save or a snapshot would lose it\n\t */\n\tcomponents?: Component<any>[]\n\t/** The events of its own the game emits (see `defineEvent`): given here for the same reason */\n\tevents?: EventKey<any>[]\n\t/** Parts of the map the rules watch: who walks in and out (see `AreaDef`) */\n\tareas?: AreaDef[]\n\t/** Groups of things the game spawns as one (see `definePrefab`, `world.spawnPrefab`); a designer's from the editor through `prefabsFrom` */\n\tprefabs?: PrefabDef[]\n\t/** What the game sets to go off later (see `defineTimer`): given here, so that a save finds them by id */\n\ttimers?: TimerDef[]\n\t/** Scripts of steps the game starts, like a mission's (see `defineSequence`): given here, so that a save finds them */\n\tsequences?: SequenceDef[]\n\t/** Files of the game's own data its rules read as they run, and a panel edits (see `defineGameFile`, `registry.file`) */\n\tfiles?: GameFileDef<unknown>[]\n\t/** Decides who is out and who won. The last team with a building, when left out. Null for a game nobody can lose */\n\tvictory?: SystemDef | null\n\t/**\n\t * How its saves outlive its patches (`SaveRules`): the version of what it keeps in a save, the steps that bring an\n\t * older save up to it, and what becomes of a save made with other rules. A game that declares it, even empty, loads\n\t * the saves made before a patch; one that does not refuses every save not made with its very rules, as a test wants\n\t */\n\tsaves?: SaveRules\n\t/**\n\t * Runs once a world is loaded from a save, everything put back: for what a game keeps outside the world, to make\n\t * again from what is in it\n\t */\n\tafterLoad?: (world: World) => void\n\t/**\n\t * Runs as a world takes a new version of the game while it runs (hot reload, `reloadGame`), the new version's: for\n\t * what the game made of the old one (a cache of its definitions, a state worked out of them), to make again. What\n\t * else hears it: `world.events.on(gameReloaded, …)`, and a screen's `GameView.on`\n\t */\n\tonReload?: (world: World) => void\n\t/** What the game does on a server, around its games: who joins and leaves, the start and the end (see `ServerHooks`) */\n\tserver?: ServerHooks\n\t/** What a player starts a map with, for players the map places nothing for: a hall and workers as data, or a function (`StartDef`) */\n\tstart?: StartDef\n\t/**\n\t * The brains of its computer players (`defineBrain`), given here as components and timers are, so that a save that\n\t * remembers a seat by its brain's id (`world.computers.seat`) finds the brain again when loaded. The first is what a\n\t * seat that names no brain gets: `meleeBrain` of `@v12-engine/engine/ai` for a game played as melee, or a computer\n\t * player of the game's own (`defineComputer`). None listed: the game has no computer player, and seating one throws\n\t */\n\tbrains?: BrainDef[]\n\t/**\n\t * What it says of its computer players' profiles (`GameAi`, AI plan D1): difficulties and personalities of its own\n\t * beside the engine's, defaults over the engine's, and whether a lobby offers each seat a difficulty and a\n\t * personality (`seatSettingsOf`)\n\t */\n\tai?: GameAi\n\t/**\n\t * What the ground of its maps can be painted with, in order: the first is index 1 of `Terrain.tiles`, 0 being no\n\t * paint (see `TileDef`). What each looks like is the view's (`GameView.ground.tiles`)\n\t */\n\ttiles?: TileDef[]\n\t/**\n\t * Its own layers of cells, for its rules to read and the editor to paint: where the bushes are (see `CellLayerDef`).\n\t * Any layer can be read and set by id whether it is listed or not; listed, the editor offers it\n\t */\n\tcellLayers?: CellLayerDef[]\n\t/** Numbers of its rules to be tuned while it plays (`defineTunable`), read with `world.tunable(id)` */\n\ttunables?: TunableDef[]\n\t/**\n\t * The maps the game ships (S36): a world made from one of them keeps, in its save and in the welcome a server sends,\n\t * only what changed of its ground, and whoever reads it finds the rest here (by its name and the ground it makes).\n\t * Not in the game's hash. A map not among them, or changed since, is kept whole, as before\n\t */\n\tmaps?: readonly GameMap[]\n\t/**\n\t * Its generator of maps (`MapGenerator`, `generateMap`): what the editor's New map from a generator and the page's\n\t * Random map make a map with, its parameters as their sliders. None when left out: the engine's `presetGenerator`\n\t * is there to take, with the game's trees and rocks\n\t */\n\tgenerator?: MapGenerator\n\t/**\n\t * Which fields of its definitions the editor's Data panel may change (S61): `all`, or by kind (`units`,\n\t * `abilities`, `buffs`, `items`, `upgrades`) all of them, some (their paths, `stats.health`, or fields said in full,\n\t * with bounds and a kind), or each definition's own in code. None when left out. What is changed there is kept in\n\t * the game's `data.json`, which the game reads over its code with `withData`\n\t */\n\teditable?: EditableData\n\t/**\n\t * How its worlds find their way: the radius the walkable ground is cut for, how steep it may be, how many units the\n\t * crowd makes room for at first (`maxAgents`). What a world is made with (`CreateWorldOptions.navigation`) goes over it\n\t */\n\tnavigation?: RecastNavigationOptions\n\t/**\n\t * What a route of a ground unit knows of the buildings in its way (determinism plan F2): `all` of them (the default),\n\t * as the ground is; or only those its side has `seen`, so the way it goes in the dark says nothing of what is there.\n\t * With `seen`, each side has a navigation of its own to plan on, of what it knows: a few megabytes a side on a big\n\t * map. Units still walk around every building: they see one before they reach it, and plan again\n\t *\n\t * @beta\n\t */\n\tpaths?: 'all' | 'seen'\n\t/**\n\t * How much its worlds say (`world.log`): the least an entry must matter to be said, everything when left out.\n\t * Where the entries go is whoever runs the game's to say (`world.log.to`, the logger a world is made under)\n\t */\n\tlog?: { level?: LogLevel }\n\t/**\n\t * What becomes of a part of the game that throws (a hook's handler, a listener, a system, a timer, an order, a\n\t * command): `throw` (the error goes on: tests), `end` (the game ends there, the players told), `disable` (the part\n\t * is switched off and the game goes on), or a function that says which for each. When left out: a world throws, and\n\t * a server and a launched game end the game (`world.errorPolicy`)\n\t */\n\tonError?: ErrorPolicy\n\t/** What the game brings to the map editor (see `MapEditorDef`) */\n\teditor?: MapEditorDef\n\t/**\n\t * What the game tells each player about itself, beyond what the engine knows: the wave a tower defense is at,\n\t * a score, a countdown. Plain data that survives being sent; it goes into every snapshot as `report`, where the\n\t * game's view (`GameView.hud.status`) puts it on the screen. Only what that player may know\n\t */\n\treport?: (world: World, player: PlayerId) => Record<string, unknown>\n}\n\n/**\n * A seat at a game on a server: a player who joined, or a computer player\n *\n * @beta\n */\nexport interface ServerSeat {\n\tplayer: PlayerId\n\tname: string\n\tai: boolean\n\t/** Whether someone is connected to it right now */\n\tconnected: boolean\n\t/** The team it plays for, where the mode says: who it is with and against */\n\tteam?: number\n\t/** Whether who sits there said they are ready, in the lobby: once every player seated is, the game starts */\n\tready?: boolean\n\t/** What is chosen for this seat (`ServerHooks.seatSettings`), by name: none where the game has no such settings */\n\tsettings?: Record<string, string>\n\t/** Settings of the seat the mode fixes (`ModeSeat.fixed`: a race the map gives its player), by name: not the lobby's to change */\n\tfixed?: string[]\n\t/** Who sits there, as they are rated (`ratedId`: a hash of their key, safe to show), and their rating in the mode where the server keeps ratings */\n\trated?: string\n\trating?: number\n\t/** A vote to let who sits there go (`kick`), in the lobby: how many voted, and how many it takes */\n\tkick?: { votes: number; needed: number }\n}\n\n/**\n * How a game on a server ended: who won, and each seat's outcome\n *\n * @beta\n */\nexport interface GameResult {\n\tgame: string\n\tmode: string\n\t/** The winning team, or null for a game that was stopped */\n\twinner: number | null\n\t/** Seconds of game time */\n\tduration: number\n\t/** What the players were told, for a game that ended on an error and not by its rules (`World.failure`) */\n\tfailed?: string\n\tseats: (ServerSeat & { outcome: 'victory' | 'defeat' | 'none' })[]\n}\n\n/**\n * What a game does on a server (`GameModule.server`). Only ever run there: a player's screen has none of it. The\n * lobby's settings come to `onGameStart` as the lobby left them\n *\n * @beta\n */\nexport interface ServerHooks {\n\t/** Settings of the lobby, by name: what can be chosen, and what is chosen until someone does */\n\tsettings?: Record<string, LobbySetting>\n\t/**\n\t * Settings of each seat, by name: a race, a difficulty, a colour. Chosen in the lobby by who sits there, and for a\n\t * seat the computer plays or nobody holds, by any player seated; each seat's (`ServerSeat.settings`) are handed to\n\t * its computer player (`GameMode.ai`) and to the start (`onGameStart`)\n\t */\n\tseatSettings?: Record<string, LobbySetting>\n\t/** Someone took a seat in the lobby, or came back to theirs in a game (`world` then) */\n\tonPlayerJoin?(seat: ServerSeat, world?: World): void\n\t/** Someone left their seat: in the lobby, or in a game (`world` then), where they may come back */\n\tonPlayerLeave?(seat: ServerSeat, world?: World): void\n\t/** The game starts, with the world made and the lobby's settings */\n\tonGameStart?(world: World, seats: readonly ServerSeat[], settings: Record<string, string>): void\n\t/** The game ended: who won, as plain data, before it is kept (`saveResult`) */\n\tonGameEnd?(world: World, result: GameResult): void\n\t/** Keeps a game's result: in a file, a database, a ranking. A server writes it to a file of its own without */\n\tsaveResult?(result: GameResult): void | Promise<void>\n}\n\n/**\n * A setting of a lobby or of a seat (`ServerHooks.settings`, `seatSettings`)\n *\n * @beta\n */\nexport interface LobbySetting {\n\tlabel: string\n\t/** What can be chosen, as it is kept */\n\toptions: string[]\n\t/** What each option is shown as, where it is not the option itself */\n\tlabels?: Record<string, string>\n\t/** What is chosen until someone does */\n\tdefault: string\n\t/** Of a seat: no two seats may hold the same (a colour). One held by another seat is not chosen */\n\tunique?: boolean\n}\n\n/** @beta */\nexport interface CreateWorldOptions extends WorldChecks {\n\tterrain: Terrain\n\tgame: GameModule\n\tplayers: PlayerInit[]\n\t/** The races one is drawn from for a player given `random` (`PlayerInit.race`): all of the game's when left out */\n\trandomRaces?: readonly string[]\n\tseed?: number\n\t/**\n\t * Simulation steps per second: 30 when left out. A save made at another rate is refused (`loadWorld`), so a game\n\t * that changes it starts new games\n\t *\n\t * @beta\n\t */\n\ttickRate?: number\n\tnavigation?: RecastNavigationOptions\n\t/**\n\t * Components the app keeps in the world beside the game's own (`GameModule.components`): what is the app's, not\n\t * the game's rules (where the screen is played from, a tool's own; `Component.portable` false). Its game's and the\n\t * engine's when left out: one neither lists is an error (`UnlistedError`)\n\t */\n\tcomponents?: readonly Component<unknown, unknown>[]\n\t/** The logger the world's own is made under (`world.log`): a server's, a page's. The root one when left out */\n\tlog?: Logger\n\t/** What becomes of a part of the game that throws, where the game does not say (`GameModule.onError`) */\n\tonError?: ErrorPolicy\n}\n\n/**\n * How the engine's events are told to the players, each written beside what emits it, in the order a seat hears them:\n * two told of one event (a hit and its critical number) are told in this order\n */\nconst coreReplications: readonly ReplicatedEvent[] = [\n\ttoldDeath,\n\ttoldCells,\n\ttoldCellsSeen,\n\ttoldRedefined,\n\ttoldEnvironment,\n\ttoldGround,\n\ttoldCommand,\n\ttoldAttack,\n\ttoldDamage,\n\ttoldHeal,\n\ttoldBuffOn,\n\ttoldBuffOff,\n\ttoldTrained,\n\ttoldConstructionStarted,\n\ttoldBuilt,\n\ttoldConstructionCancelled,\n\ttoldUpgradeStarted,\n\ttoldUpgradeCancelled,\n\ttoldMorphed,\n\ttoldRevived,\n\ttoldPicked,\n\ttoldResearched,\n\ttoldShot,\n\ttoldMissileHit,\n\ttoldWindup,\n\ttoldChannelStarted,\n\ttoldChannelEnded,\n\ttoldCast,\n\ttoldStrike,\n\ttoldCrit,\n\ttoldMiss,\n\ttoldImpact,\n\ttoldWork,\n\ttoldChop,\n\ttoldLevelUp,\n\ttoldXp,\n\ttoldMana,\n\ttoldResource,\n\ttoldBounty,\n\ttoldMessage,\n\ttoldObjective,\n\ttoldLine,\n\ttoldLineEnded,\n\ttoldCinematic,\n\ttoldCinematicCue,\n\ttoldEffect,\n\ttoldEffectStopped,\n\ttoldRustle,\n\ttoldPing,\n\ttoldChat\n]\n\n/** What the game tells each player about itself, with its packs' beside it (`Snapshot.report`, `GameModule.report`) */\nconst reportPart = snapshotPart('report', ({ world, player }) => world.registry.report?.(world, player))\n\n/** The engine's parts of a player's snapshot, each captured by its feature, in their order (`SnapshotPart`) */\nconst coreSnapshotParts: readonly SnapshotPart[] = [\n\tdebugPart,\n\thourPart,\n\toutcomePart,\n\tprojectilesPart,\n\tmissilesPart,\n\titemsPart,\n\trevealsPart,\n\teventsPart,\n\treportPart,\n\tscorePart,\n\tscoreLinePart,\n\tcorpsesPart\n]\n\n/**\n * The engine's parts that give an entity something as it is made, or call it off as it leaves its owner: a worker's\n * load, a building's queue, the slots of what carries, a hold\n */\nconst coreParts: readonly Component<unknown, unknown>[] = [gathering, productionQueue, inventorySlots, cargo] as Component<unknown, unknown>[]\n\n/**\n * A game put together with its packs (`assembleGame`): every list the engine runs, the packs' in it, in one place. A\n * pack's parts come before the game's own, so that one of the game's of the same id or name takes its place; what the\n * game leaves out of the engine's (`withoutCommands`, `withoutOrders`, `withoutHooks`, `withoutSystems`) it leaves out\n * of its packs' too\n *\n * @beta\n */\nexport interface AssembledGame {\n\treadonly game: GameModule\n\t/** The packs' commands and the game's */\n\treadonly commands: readonly CommandDef[]\n\t/** The packs' orders and the game's */\n\treadonly orders: readonly OrderBehavior[]\n\t/** The packs' systems, as given (made for each world, and left out by name then: `withoutSystems`) */\n\treadonly packSystems: readonly SystemDef[]\n\treadonly hooks: readonly HookDef[]\n\treadonly listeners: readonly ListenerDef[]\n\t/** The packs' kinds of effects (`GamePack.effects`), before the game's own */\n\treadonly effects: readonly EffectKind[]\n\treadonly timers: readonly TimerDef[]\n\treadonly components: readonly Component<unknown, unknown>[]\n\treadonly events: readonly EventKey<unknown>[]\n\treadonly statParts: readonly StatPart[]\n\t/** The stats of the game: its packs' (`GamePack.stats`), then its own (`GameModule.stats`) */\n\treadonly stats: readonly StatDef[]\n\t/** The packs' ways of telling the players of the world's events (`GamePack.replications`) */\n\treadonly replications: readonly ReplicatedEvent[]\n\t/** The packs' parts of the players' snapshots (`GamePack.snapshotParts`) */\n\treadonly snapshotParts: readonly SnapshotPart[]\n\t/** The game's rules with what each pack lays over them, in order */\n\treadonly rules: RulesInit\n\t/** The game's report of a player at the end, with each pack's beside it: none where none says */\n\treadonly report: ((world: World, player: PlayerId) => Record<string, unknown>) | null\n\t/** How it is won: the game's own where it says, else the last pack's that says, else the engine's (`lastTeamStanding`) */\n\treadonly victory: SystemDef | null | undefined\n\t/** What the game and its packs find wrong with a map, in the editor */\n\treadonly check: ((map: GameMap, registry: Registry) => MapProblem[]) | undefined\n}\n\n/** Each game's assembly, made once */\nconst assemblies = new WeakMap<GameModule, AssembledGame>()\n\n/**\n * A game with its packs put together (`AssembledGame`): what the registry, the systems, the hooks, the listeners and the\n * timers of a world of it are made of. Refuses a pack without one it says it goes with (`GamePack.requires`)\n *\n * @beta\n */\nexport function assembleGame(game: GameModule): AssembledGame {\n\tconst known = assemblies.get(game)\n\tif (known) return known\n\tconst packs = game.packs ?? []\n\tfor (const pack of packs)\n\t\tfor (const needed of pack.requires ?? [])\n\t\t\tif (!packs.some((each) => each.id === needed))\n\t\t\t\tthrow new Error(`The pack \"${pack.id}\" goes with the pack \"${needed}\", which \"${game.id}\" does not have`)\n\tconst from = <T>(pick: (pack: GamePack) => readonly T[] | undefined): T[] => packs.flatMap((pack) => pick(pack) ?? [])\n\tconst withoutCommands = new Set(game.withoutCommands ?? [])\n\tconst withoutOrders = new Set(game.withoutOrders ?? [])\n\tconst withoutHooks = new Set(game.withoutHooks ?? [])\n\tlet rules: RulesInit = game.rules ?? {}\n\tfor (const pack of packs) {\n\t\tif (!pack.rules) continue\n\t\tconst over = pack.rules(resolveRules(rules))\n\t\trules = overRules(rules, over)\n\t}\n\tconst reports = [game.report, ...packs.map((pack) => pack.report?.bind(pack))].filter((each) => each !== undefined)\n\tconst checks = [game.editor?.check, ...packs.map((pack) => pack.check?.bind(pack))].filter((each) => each !== undefined)\n\tconst victories = packs.filter((pack) => pack.victory !== undefined)\n\tconst assembly: AssembledGame = {\n\t\tgame,\n\t\tcommands: [...from((pack) => pack.commands).filter((command) => !withoutCommands.has(command.type)), ...(game.commands ?? [])],\n\t\torders: [...from((pack) => pack.orders).filter((order) => !withoutOrders.has(order.type)), ...(game.orders ?? [])],\n\t\tpackSystems: from((pack) => pack.systems),\n\t\thooks: [...from((pack) => pack.hooks).filter((hook) => !withoutHooks.has(hook.id)), ...(game.hooks ?? [])],\n\t\tlisteners: [...from((pack) => pack.listeners), ...(game.listeners ?? [])],\n\t\teffects: [...from((pack) => pack.effects), ...(game.effects ?? [])],\n\t\ttimers: [...from((pack) => pack.timers), ...(game.timers ?? [])],\n\t\tcomponents: [...from((pack) => pack.components), ...(game.components ?? [])],\n\t\tevents: [...from((pack) => pack.events), ...(game.events ?? [])],\n\t\tstatParts: from((pack) => pack.statParts),\n\t\tstats: [...from((pack) => pack.stats), ...(game.stats ?? [])],\n\t\treplications: from((pack) => pack.replications),\n\t\tsnapshotParts: from((pack) => pack.snapshotParts),\n\t\trules,\n\t\treport: reports.length ? (world, player) => Object.assign({}, ...reports.map((report) => report!(world, player))) : null,\n\t\tvictory: game.victory !== undefined ? game.victory : victories.at(-1)?.victory,\n\t\tcheck: checks.length ? (map, registry) => checks.flatMap((check) => check!(map, registry)) : undefined\n\t}\n\tassemblies.set(game, assembly)\n\treturn assembly\n}\n\n/**\n * Everything a game module defines, looked up by id: with the engine's own components, and those an app keeps in its\n * worlds (`own`: `CreateWorldOptions.components`)\n *\n * @beta\n */\nexport function createRegistry(game: GameModule, own: readonly Component<unknown, unknown>[] = []): Registry {\n\tconst registry = new Registry()\n\tregistry.defineCore(coreComponents())\n\tconst assembly = assembleGame(game)\n\tregistry.assembly = assembly\n\tconst withoutOrders = new Set(game.withoutOrders ?? [])\n\tfor (const order of coreOrders) if (!withoutOrders.has(order.type)) registry.orders.define(order)\n\tfor (const order of assembly.orders) registry.orders.define(order)\n\tfor (const formation of coreFormations) registry.formations.define(formation)\n\tfor (const formation of game.formations ?? []) registry.formations.define(formation)\n\tconst withoutCommands = new Set(game.withoutCommands ?? [])\n\tfor (const command of [\n\t\t...(coreCommands as readonly CommandDef[]).filter((command) => !withoutCommands.has(command.type)),\n\t\t...debugCommands,\n\t\ttuneCommand,\n\t\tredefineCommand\n\t])\n\t\tregistry.commands.define(command as CommandDef)\n\tfor (const command of assembly.commands) registry.commands.define(command)\n\tfor (const kind of [...coreEffects, ...summonEffects, ...dispelEffects, ...assembly.effects]) registry.effects.define(kind)\n\tfor (const buff of game.buffs ?? []) registry.buffs.define(buff)\n\tfor (const ability of game.abilities ?? []) registry.abilities.define(ability)\n\tfor (const item of game.items ?? []) registry.items.define(item)\n\tfor (const prefab of game.prefabs ?? []) registry.prefabs.define(prefab)\n\tregistry.upkeep = [...(game.upkeep ?? [])].sort((a, b) => a.above - b.above)\n\tregistry.game = game.id\n\tregistry.module = game\n\tregistry.day = game.day ?? null\n\tregistry.rules = resolveRules(assembly.rules)\n\tregistry.score = resolveScore(registry.rules.score, game)\n\tregistry.report = assembly.report\n\tregistry.resources = [...(game.resources ?? [])]\n\tregistry.currency = game.currency ?? game.resources?.[0]?.id ?? null\n\tregistry.tiles = checkTiles(game.tiles ?? [])\n\tregistry.cellLayers = game.cellLayers ?? []\n\tregistry.tunables = [...(game.tunables ?? [])]\n\tregistry.defineParts([...assembly.components, ...own], assembly.events)\n\t// what each part gives an entity as it is made, and calls off as it leaves its owner: the engine's, then the game's\n\tconst parts = [...coreParts, ...assembly.components]\n\tregistry.spawning = parts.filter((part) => part.onSpawn)\n\tregistry.leaving = parts.filter((part) => part.onLeave)\n\tregistry.passing = parts.filter((part) => part.passable)\n\tdefineStats(registry, assembly.stats)\n\tregistry.statParts = [...assembly.statParts]\n\tregistry.replications = [...coreReplications, ...assembly.replications]\n\tregistry.snapshotParts = [...coreSnapshotParts, ...assembly.snapshotParts]\n\tfor (const race of game.races ?? []) registry.races.define(race)\n\tfor (const file of game.files ?? []) registry.setFile(file, file.read(file.data))\n\tfor (const unit of game.units) registry.units.define(unit)\n\tfor (const upgrade of game.upgrades ?? []) registry.upgrades.define(upgrade)\n\tcheckCosts(game)\n\tcheckRaces(game)\n\tcheckDamageTable(game)\n\tcheckStats(game, new Set(registry.statKeys))\n\tcheckSaves(game)\n\treturn registry\n}\n\n/**\n * Throws when what a game says of its saves cannot be: a version that is no whole number from 1, or a step from a\n * version the game is not past yet, which would never run\n */\nfunction checkSaves(game: GameModule): void {\n\tconst { version = 1, migrate } = game.saves ?? {}\n\tif (!Number.isInteger(version) || version < 1)\n\t\tthrow new Error(`The version of the saves of \"${game.id}\" is a whole number from 1, not ${String(version)}`)\n\tif (typeof migrate !== 'object') return\n\tfor (const from of Object.keys(migrate).map(Number)) {\n\t\tif (!Number.isInteger(from) || from < 1 || from >= version) {\n\t\t\tthrow new Error(\n\t\t\t\t`\"${game.id}\" has a step for saves of version ${from}, and its saves are of version ${version}: the steps are from 1 to ${version - 1}, each to the version after it`\n\t\t\t)\n\t\t}\n\t}\n}\n\n/** The game's tiles, as they are: throws for one that is there twice, or for too many to keep in a byte */\nfunction checkTiles(tiles: TileDef[]): TileDef[] {\n\tif (tiles.length > MAX_TILES) throw new Error(`A game has at most ${MAX_TILES} tiles, not ${tiles.length}`)\n\tconst seen = new Set<string>()\n\tfor (const tile of tiles) {\n\t\tif (seen.has(tile.id)) throw new Error(`The tile \"${tile.id}\" is there twice`)\n\t\tseen.add(tile.id)\n\t}\n\treturn [...tiles]\n}\n\n/** The game's own stats next to the engine's, and what every unit starts with of them */\nfunction defineStats(registry: Registry, stats: readonly StatDef[]): void {\n\tconst defaults: Record<string, number> = { ...noStats() }\n\tfor (const stat of stats) {\n\t\tif (stat.id in defaults) throw new Error(`The stat \"${stat.id}\" is there twice, or is one of the engine's`)\n\t\tdefaults[stat.id] = stat.default ?? 0\n\t}\n\tregistry.stats = [...stats]\n\tregistry.statKeys = Object.keys(defaults)\n\tregistry.statDefaults = Object.freeze(defaults) as Stats\n}\n\n/**\n * Throws when something changes or scales with a stat the game does not have: most likely a typo, which would\n * otherwise do nothing, or turn a stat into NaN. Stats are any text to the type checker, so this is where it is caught\n */\nfunction checkStats(game: GameModule, known: Set<string>): void {\n\tconst check = (what: string, keys: object | undefined, also: string[] = []) => {\n\t\tfor (const key in keys) if (!known.has(key) && !also.includes(key)) throw new Error(`${what} has the stat \"${key}\", which the game does not have`)\n\t}\n\tconst change = (what: string, change: { stats?: object; percent?: object } | undefined) => {\n\t\tcheck(what, change?.stats)\n\t\tcheck(what, change?.percent)\n\t}\n\t// scaling can be anywhere in a tree of effects\n\tconst scaling = (what: string, within: unknown): void => {\n\t\tif (typeof within !== 'object' || within === null) return\n\t\tfor (const [key, value] of Object.entries(within)) {\n\t\t\tif (key === 'scaling' || key === 'shieldScaling') check(what, value as object, ['level', 'bonusAttackDamage'])\n\t\t\telse scaling(what, value)\n\t\t}\n\t}\n\tfor (const unit of game.units) {\n\t\tcheck(`Unit type \"${unit.id}\"`, unit.stats)\n\t\tchange(`The growth of \"${unit.id}\"`, unit.hero?.growth)\n\t\tfor (const [i, attack] of (unit.attacks ?? []).entries())\n\t\t\tfor (const stat of Object.values(attack.stats ?? {}))\n\t\t\t\tif (!known.has(stat)) throw new Error(`Attack ${i + 1} of \"${unit.id}\" reads the stat \"${stat}\", which the game does not have`)\n\t}\n\tfor (const buff of game.buffs ?? []) {\n\t\tchange(`Buff \"${buff.id}\"`, buff)\n\t\tscaling(`Buff \"${buff.id}\"`, buff)\n\t}\n\tfor (const item of game.items ?? []) change(`Item \"${item.id}\"`, item.bonus)\n\tfor (const upgrade of game.upgrades ?? []) for (const effect of upgrade.effects) change(`Upgrade \"${upgrade.id}\"`, effect)\n\tfor (const ability of game.abilities ?? []) scaling(`Ability \"${ability.id}\"`, ability)\n}\n\n/**\n * Throws when something costs a resource the game does not have: a typo, or something that is not a resource at\n * all, like supply. Either would otherwise make it something nobody can ever afford, without a word\n */\nfunction checkCosts(game: GameModule): void {\n\tconst known = new Set((game.resources ?? []).map((resource) => resource.id))\n\tif (game.currency !== undefined && !known.has(game.currency)) throw new Error(`The currency \"${game.currency}\" is not a resource of the game`)\n\tconst check = (what: string, cost: Cost | undefined) => {\n\t\tfor (const kind in cost) if (!known.has(kind)) throw new Error(`${what} costs \"${kind}\", which is not a resource of the game`)\n\t}\n\tfor (const unit of game.units) check(`Unit type \"${unit.id}\"`, unit.cost)\n\tfor (const upgrade of game.upgrades ?? []) check(`Upgrade \"${upgrade.id}\"`, upgrade.cost)\n\tfor (const item of game.items ?? []) check(`Item \"${item.id}\"`, item.cost)\n}\n\n/**\n * The ground's navigation: cut for a unit of ordinary size (0.5), or for each size the game names (`radii`), each\n * unit on the one for its size. Big ones on one cut for 0.5 fit through the same gaps and overlap walls a little,\n * which is better than everyone keeping the distance from a wall that the biggest unit in the game needs\n */\nasync function groundNavigationOf(terrain: Terrain, options: RecastNavigationOptions = {}): Promise<Navigation> {\n\tconst radii = [...new Set(options.radii ?? [])].sort((a, b) => a - b)\n\tif (radii.length < 2) return RecastNavigation.create(terrain, { agentRadius: radii[0] ?? 0.5, ...options })\n\tconst sizes: { radius: number; navigation: Navigation }[] = []\n\ttry {\n\t\tfor (const radius of radii) sizes.push({ radius, navigation: await RecastNavigation.create(terrain, { ...options, agentRadius: radius }) })\n\t} catch (error) {\n\t\tfor (const size of sizes) size.navigation.dispose()\n\t\tthrow error\n\t}\n\treturn new SizedNavigation(sizes)\n}\n\n/**\n * The navigations the sides plan their routes on (`GameModule.paths: 'seen'`): one for each team that plays, cut for\n * the game's smallest unit. None where routes know everything\n */\nasync function sidePathsOf(\n\tgame: GameModule,\n\tterrain: Terrain,\n\tplayers: readonly { team: number; neutral?: boolean; creeps?: boolean }[],\n\toptions: RecastNavigationOptions\n): Promise<SidePaths | undefined> {\n\tif (game.paths !== 'seen') return undefined\n\tconst teams = [...new Set(players.filter((player) => !player.neutral && !player.creeps).map((player) => player.team))].sort((a, b) => a - b)\n\tconst radius = Math.min(...(options.radii?.length ? options.radii : [options.agentRadius ?? 0.5]))\n\treturn SidePaths.create(terrain, teams, { ...options, agentRadius: radius })\n}\n\n/** Where boats go, on a map with deep water: a navigation of the water at its surface. Nothing on one without */\nasync function waterNavigationOf(terrain: Terrain, options?: RecastNavigationOptions): Promise<RecastNavigation | undefined> {\n\tif (!terrain.hasDeepWater) return undefined\n\t// boats are cut for one size: the smallest the game names\n\treturn RecastNavigation.create(terrain, {\n\t\tagentRadius: 0.5,\n\t\t...options,\n\t\t...(options?.radii?.length && { agentRadius: Math.min(...options.radii) }),\n\t\tsurface: 'water'\n\t})\n}\n\n/** @beta */\nexport async function createWorld(options: CreateWorldOptions): Promise<World> {\n\tconst { terrain, game, players, seed } = options\n\tconst registry = createRegistry(game, options.components)\n\n\tconst world = await makeWorld(game, registry, terrain, {\n\t\tplayers: players.map((player) => ({ ...player, resources: startingResources(game, player) })),\n\t\tnavigation: options.navigation,\n\t\trandomRaces: options.randomRaces,\n\t\tseed,\n\t\ttickRate: options.tickRate,\n\t\tlog: options.log,\n\t\tonError: options.onError,\n\t\tchecks: options.checks\n\t})\n\t// what each race starts its players with, once the races are settled (one drawn for those given random)\n\traceResources(world, players)\n\t// what each side knows without seeing, as it is put down from now (`GameModule.paths: 'seen'`)\n\tworld.sidePaths?.attach(world)\n\treturn world\n}\n\n/**\n * A world of a game on a terrain, its navigations built (freed again where what follows fails), its parts the game's put\n * together with its packs (`assembleGame`): what a world made new and a world loaded from a save have in common\n */\nasync function makeWorld(\n\tgame: GameModule,\n\tregistry: Registry,\n\tterrain: Terrain,\n\toptions: WorldChecks & {\n\t\tplayers: PlayerInit[]\n\t\tnavigation?: RecastNavigationOptions\n\t\trandomRaces?: readonly string[]\n\t\tseed?: number\n\t\ttickRate?: number\n\t\tlog?: Logger\n\t\tonError?: ErrorPolicy\n\t}\n): Promise<World> {\n\tconst navigationOptions: RecastNavigationOptions = {\n\t\t// slow ground weighed by the ways, where the game has any (EN2)\n\t\t...(hasGroundSpeeds(registry) && { speedAt: (x: number, z: number) => groundSpeedOn(registry, terrain, x, z) }),\n\t\t...game.navigation,\n\t\t...options.navigation\n\t}\n\tconst navigation = await groundNavigationOf(terrain, navigationOptions)\n\tconst waterNavigation = await freedOnError(navigation, () => waterNavigationOf(terrain, navigationOptions))\n\tconst sidePaths = await freedOnError(navigation, () =>\n\t\tfreedOnError(waterNavigation, () => sidePathsOf(game, terrain, options.players, navigationOptions))\n\t)\n\tconst assembly = registry.assembly!\n\treturn freedOnError(navigation, () =>\n\t\tfreedOnError(\n\t\t\twaterNavigation,\n\t\t\t() =>\n\t\t\t\tnew World({\n\t\t\t\t\tterrain,\n\t\t\t\t\tnavigation,\n\t\t\t\t\twaterNavigation,\n\t\t\t\t\tsidePaths,\n\t\t\t\t\tregistry,\n\t\t\t\t\tplayers: options.players,\n\t\t\t\t\trandomRaces: options.randomRaces,\n\t\t\t\t\tseed: options.seed,\n\t\t\t\t\ttickRate: options.tickRate,\n\t\t\t\t\tlog: options.log,\n\t\t\t\t\tlogLevel: game.log?.level,\n\t\t\t\t\tonError: game.onError ?? options.onError,\n\t\t\t\t\tchecks: options.checks,\n\t\t\t\t\tsystems: (world) => systemsOf(world, assembly),\n\t\t\t\t\thooks: hooksOf(assembly),\n\t\t\t\t\tlisteners: listenersOf(assembly),\n\t\t\t\t\tareas: game.areas,\n\t\t\t\t\ttimers: timersOf(assembly),\n\t\t\t\t\tsequences: game.sequences\n\t\t\t\t})\n\t\t)\n\t)\n}\n\n/**\n * Runs what makes something of a navigation already made: the navigation is freed when it fails (WebAssembly memory,\n * which nothing else would free), and the error goes on\n */\nasync function freedOnError<T>(navigation: { dispose(): void } | undefined, make: () => T | Promise<T>): Promise<T> {\n\ttry {\n\t\treturn await make()\n\t} catch (error) {\n\t\tnavigation?.dispose()\n\t\tthrow error\n\t}\n}\n\n/** Runs what is done to a world just made: the world is disposed when it fails, and the error goes on */\nasync function disposedOnError(world: World, run: () => void | Promise<void>): Promise<World> {\n\ttry {\n\t\tawait run()\n\t\treturn world\n\t} catch (error) {\n\t\tworld.dispose()\n\t\tthrow error\n\t}\n}\n\n/**\n * What a player starts with: what they were given, or else what the game starts everyone with (nothing, for the\n * neutral players). Every resource of the game is in it, at 0 at least\n */\nfunction startingResources(game: GameModule, player: PlayerInit): Purse {\n\tconst purse: Purse = {}\n\tfor (const resource of game.resources ?? []) {\n\t\tpurse[resource.id] = player.resources ? (player.resources[resource.id] ?? 0) : player.neutral ? 0 : (resource.start ?? 0)\n\t}\n\treturn { ...player.resources, ...purse }\n}\n\n/**\n * The engine's hook handlers without the ones the module does without, then the module's own\n *\n * @beta\n */\nexport interface LoadWorldOptions extends WorldChecks {\n\t/** The game module the save was made with, by id. A save holds no code: rules come from here */\n\tgame: GameModule\n\t/**\n\t * The map it is loaded on (a scene that opens its map again): its definitions are laid over the game's in place\n\t * of those the save kept (`GameMap.definitions`). The save's own when left out\n\t */\n\tmap?: Pick<GameMap, 'definitions'>\n\tnavigation?: RecastNavigationOptions\n\t/** Components the app keeps in the world beside the game's own, as `CreateWorldOptions.components`: those of the world saved */\n\tcomponents?: readonly Component<unknown, unknown>[]\n\t/**\n\t * Loads a save made with other rules of the game (its code or its mods changed since) whatever the game says of\n\t * those (`GameModule.saves.onMismatch`). An older version of its saves is brought up to date all the same\n\t */\n\tanyVersion?: boolean\n\t/** The logger the world's own is made under, as `CreateWorldOptions.log` */\n\tlog?: Logger\n\t/** What becomes of a part of the game that throws, as `CreateWorldOptions.onError` */\n\tonError?: ErrorPolicy\n\t/** The maps a save's ground may be one of (S36): the game's own (`GameModule.maps`) when left out */\n\tmaps?: readonly GameMap[]\n}\n\n/**\n * A world from a save (see `saveWorld`), carrying on where it was. A save made before, by an older engine or by the\n * game before a patch, is brought up to date first (`updateSave`), or refused with a `SaveError` that says why.\n * Navigation is built again; units come back with the speed and destination they had, but the way they find around\n * each other is worked out anew, so the game from there on is close to, and not quite, the one that was saved\n *\n * @beta\n */\nexport async function loadWorld(saved: WorldSave, options: LoadWorldOptions): Promise<World> {\n\t// the definitions of the map it was made from laid over the game again (RC8): the map's it is loaded on, where the\n\t// caller says one, else those the save kept. Its rules hash has them: a save of other definitions is the game's\n\t// mismatch (`SaveRules.onMismatch`)\n\tconst kept = (saved.state?.[mapInfo.id] as { definitions?: GameData } | undefined)?.definitions\n\tconst definitions = options.map ? options.map.definitions : kept\n\tconst game = definitions ? withData(options.game, definitions) : options.game\n\tconst registry = createRegistry(game, options.components)\n\t// as the game reads it now, or refused, before anything is built for it\n\tconst save = updateSave(saved, registry, { anyVersion: options.anyVersion })\n\t// all of the ground, or the map the world was made from and what changed of it (S36): that map is one of the game's\n\tlet ground: ReturnType<typeof groundOf>\n\ttry {\n\t\tground = groundOf(save.terrain, options.maps ?? game.maps, game)\n\t} catch (error) {\n\t\tif (error instanceof MissingGround) throw new SaveError(`Save: ${error.message}`, 'ground')\n\t\tthrow error\n\t}\n\tconst { terrain } = ground\n\tconst world = await makeWorld(game, registry, terrain, {\n\t\tplayers: savedPlayers(save),\n\t\tnavigation: options.navigation,\n\t\ttickRate: save.tickRate,\n\t\tlog: options.log,\n\t\tonError: options.onError,\n\t\tchecks: options.checks\n\t})\n\t// a save that is refused, or a game's afterLoad that throws, leaves nothing behind\n\treturn disposedOnError(world, () => {\n\t\t// what it started as, for its next save\n\t\tworld.ground = ground.base\n\t\trestoreWorld(world, save)\n\t\t// the gates as the save had them: the obstacles of shut ones are not in it\n\t\tif (save.state && gateStates.id in save.state) setUpGates(world)\n\t\t// the computer players the save remembers, seated again with their memory, before the game looks\n\t\tworld.computers.restore()\n\t\tgame.afterLoad?.(world)\n\t})\n}\n\n/** The systems of a world of the game: the core ones and its packs', but those it leaves out, then its own, then who wins */\nfunction systemsOf(world: World, assembly: AssembledGame): System[] {\n\tconst { game } = assembly\n\tconst make = (def: SystemDef) => (typeof def === 'function' ? def(world) : def)\n\tconst without = new Set(game.withoutSystems ?? [])\n\tconst systems = [...coreSystems, ...assembly.packSystems.map(make)].filter((system) => !without.has(system.name))\n\tfor (const def of game.systems ?? []) {\n\t\tconst system = make(def)\n\t\tconst index = systems.findIndex((core) => core.name === system.name)\n\t\tif (index < 0) systems.push(system)\n\t\t// in place of the core one, and in its phase unless it says\n\t\telse\n\t\t\tsystems[index] = system.phase\n\t\t\t\t? system\n\t\t\t\t: { ...system, phase: systems[index].phase, update: system.update?.bind(system), each: system.each?.bind(system) }\n\t}\n\t// what each side learns of the buildings in its way, right after the fog says what it sees\n\tif (game.paths === 'seen') systems.splice(systems.findIndex((system) => system.name === 'fog') + 1, 0, sideKnowledgeSystem)\n\t// the score's gauges and timeline, in a game that counts\n\tif (world.registry.score) systems.push(scoreSystem(world))\n\tif (assembly.victory !== null) systems.push(make(assembly.victory ?? lastTeamStanding))\n\treturn systems\n}\n\nfunction hooksOf(assembly: AssembledGame): HookDef[] {\n\tconst without = new Set(assembly.game.withoutHooks ?? [])\n\treturn [...coreHooks.filter((hook) => !without.has(hook.id)), ...assembly.hooks, ...raceHooks(assembly.game)]\n}\n\n/** How the world reacts to events: the engine's, the packs', the game's */\nfunction listenersOf(assembly: AssembledGame): ListenerDef[] {\n\treturn [dropFromTable, transportSank, regionCinematic, ...assembly.listeners]\n}\n\n/** What can be set to go off later: the packs' and the game's */\nfunction timersOf(assembly: AssembledGame): TimerDef[] | undefined {\n\treturn assembly.timers.length ? [...assembly.timers] : undefined\n}\n\n/** @beta */\nexport interface MapWorldOptions {\n\tmap: GameMap\n\tgame: GameModule\n\t/**\n\t * The race each player plays, by player (`GameModule.races`): one of the game's, or `random`. Chosen in a lobby, a\n\t * page's own menu. Those left out play what the map fixes for them (`MapPlayer.race`), or the game's first\n\t */\n\traces?: Readonly<Record<PlayerId, string>>\n\t/** The team each player plays for, by player, over the map's (`MapPlayer.team`): chosen in a lobby */\n\tteams?: Readonly<Record<PlayerId, number>>\n\t/** The colour of each player, by player, over the map's (`MapPlayer.color`): chosen in a lobby */\n\tcolors?: Readonly<Record<PlayerId, [number, number, number]>>\n\t/**\n\t * Whether the world has the creeps player. When the map has something for it when left out: a camp, or something\n\t * placed for the creeps. A world without camps that had one anyway would never be won: a team would always be left\n\t */\n\tcreeps?: boolean\n\tseed?: number\n\tnavigation?: RecastNavigationOptions\n\t/** Components the app keeps in the world beside the game's own, as `CreateWorldOptions.components` */\n\tcomponents?: readonly Component<unknown, unknown>[]\n\t/** The logger the world's own is made under, as `CreateWorldOptions.log` */\n\tlog?: Logger\n\t/** What becomes of a part of the game that throws, as `CreateWorldOptions.onError` */\n\tonError?: ErrorPolicy\n}\n\n/**\n * A world as a map lays it out: its ground, the players it has room for, and everything placed on it.\n * Players with a start location that the map places nothing for get what the game starts everyone with.\n * Throws for a map made for another game (`GameMap.game`).\n *\n * @beta\n */\nexport async function createWorldFromMap(options: MapWorldOptions): Promise<World> {\n\tconst { map } = options\n\t// the map's own definitions over the game's data (RC8): a footman of this map alone\n\tconst game = map.definitions ? withData(options.game, map.definitions) : options.game\n\tif (map.game !== undefined && map.game !== game.id) throw new Error(`\"${map.name}\" is a map for the game \"${map.game}\", not for \"${game.id}\"`)\n\tconst most = maxPlayersOf(game)\n\tconst seated = map.players.filter((player) => player.id !== MAP_CREEPS && player.id !== MAP_NEUTRAL).length\n\tif (seated > most) throw new Error(`\"${map.name}\" has ${seated} players, and ${game.name} allows ${most} (\\`GameModule.maxPlayers\\`)`)\n\tconst creeps = options.creeps ?? (map.camps.length > 0 || map.objects.some((object) => object.owner === MAP_CREEPS))\n\tconst players: PlayerInit[] = [\n\t\t{ id: MAP_NEUTRAL, name: 'Neutral', team: 0, color: [0.8, 0.75, 0.4], neutral: true },\n\t\t...map.players.map((player) => ({\n\t\t\tid: player.id,\n\t\t\tname: player.name,\n\t\t\tteam: options.teams?.[player.id] ?? player.team,\n\t\t\tcolor: options.colors?.[player.id] ?? player.color,\n\t\t\t...(player.resources && { resources: { ...player.resources } }),\n\t\t\t// as the code says, or else as the map fixes it\n\t\t\t...((options.races?.[player.id] ?? player.race) !== undefined && { race: options.races?.[player.id] ?? player.race })\n\t\t})),\n\t\t...(creeps ? [{ id: MAP_CREEPS, name: 'Creeps', team: 1000, color: [0.42, 0.36, 0.3] as [number, number, number], creeps: true }] : [])\n\t]\n\t// painted as the game's tiles go: what is painted with a tile the game does not have is plain ground. The ground\n\t// it starts as is kept with the world: a save of it keeps only what changed, where the game has the map (S36)\n\tconst terrain = startingTerrain(map, game)\n\tconst base = startedOn(map.name, cloneTerrain(terrain))\n\tconst world = await createWorld({\n\t\tterrain,\n\t\tgame,\n\t\tplayers,\n\t\t// random draws from what the map offers\n\t\t...(map.races?.length && { randomRaces: map.races }),\n\t\tseed: options.seed,\n\t\tnavigation: options.navigation,\n\t\t...(options.components && { components: options.components }),\n\t\tlog: options.log,\n\t\tonError: options.onError\n\t})\n\t// what the map puts in the world, and what the game does with it: a failure leaves nothing behind\n\tworld.ground = base\n\treturn disposedOnError(world, () => {\n\t\t// a copy: the world is its own, and so is its save\n\t\tworld.setState(mapInfo, {\n\t\t\tname: map.name,\n\t\t\t// the map's own fields with what they are when not set, a region, a point or a path by its name\n\t\t\tdata: fieldValues(mapFields(world.registry), structuredClone(map.data), map),\n\t\t\tpoints: structuredClone(map.points),\n\t\t\tpaths: structuredClone(map.paths),\n\t\t\t...(map.environment && { environment: structuredClone(map.environment) }),\n\t\t\t...(map.doodads.length > 0 && { doodads: structuredClone(map.doodads) }),\n\t\t\t...(map.regions.length > 0 && { regions: structuredClone(map.regions) }),\n\t\t\t...(map.cameras.length > 0 && { cameras: structuredClone(map.cameras) }),\n\t\t\tplayers: map.players.map((player) => ({\n\t\t\t\tid: player.id,\n\t\t\t\t...(player.controller && { controller: player.controller }),\n\t\t\t\tdata: mapPlayerData(world.registry, player, map)\n\t\t\t})),\n\t\t\t...(map.forces?.length && { forces: structuredClone(map.forces) }),\n\t\t\t...(map.itemTables?.length && { itemTables: structuredClone(map.itemTables) }),\n\t\t\t...(map.definitions && { definitions: structuredClone(map.definitions) })\n\t\t})\n\t\t// the gates, shut ones in the way\n\t\tsetUpGates(world)\n\t\t// a force that shares control: every player of it may command the others' units\n\t\tfor (const force of map.forces ?? []) {\n\t\t\tif (!force.sharedControl) continue\n\t\t\tconst members = map.players.filter((player) => player.team === force.team)\n\t\t\tfor (const one of members) for (const other of members) if (one !== other) world.sides.shareControl(one.id, other.id)\n\t\t}\n\t\t// the whole map explored from the start, as the map says, else as the game's rules do (`FogRules.startExplored`)\n\t\tworld.fog.exploreFromStart(map.explored ?? world.rules.fog?.startExplored ?? false)\n\t\t// the time of day the map starts at, and whether it moves\n\t\tif (map.day?.start !== undefined) world.clock.setHour(map.day.start)\n\t\tif (map.day?.still) world.clock.stop()\n\t\t// the regions first: what is placed may be inside one from the start, and the game's hooks may ask\n\t\tfor (const region of map.regions) {\n\t\t\tif (world.areas.has(region.name)) throw new Error(`The region \"${region.name}\" of \"${map.name}\" has the name of an area of the game`)\n\t\t\tconst area = { id: region.name, shape: { ...region.shape } }\n\t\t\tworld.areas.add(area)\n\t\t\tif (world.hooks.has('mapRegion')) world.hooks.run('mapRegion', { area, region, data: mapRegionData(world.registry, region, map) })\n\t\t}\n\t\tconst known = new Set(players.map((player) => player.id))\n\t\tconst placed = new Set<PlayerId>()\n\t\t// what is drawn from a random group is drawn now, once, from the world's own numbers: the same for the same seed\n\t\tconst groups = new Map((map.randomGroups ?? []).map((group) => [group.name, group]))\n\t\tconst drawn = (type: string, random: string | undefined) => {\n\t\t\tconst group = random === undefined ? undefined : groups.get(random)\n\t\t\treturn (group && drawFromGroup(group, world.registry, world.rng)) ?? type\n\t\t}\n\t\t// what stands still goes first, so that units find their way around it\n\t\tconst objects = map.objects\n\t\t\t.map((object) => (object.random ? { ...object, type: drawn(object.type, object.random) } : object))\n\t\t\t.filter((object) => world.registry.units.has(object.type) && known.has(object.owner))\n\t\t// and of that, resources before buildings: what goes up on a resource (`builtOn`) finds it there\n\t\tconst rank = (type: string) => ({ resource: 0, building: 1, unit: 2 })[world.registry.unit(type).kind] ?? 1\n\t\tobjects.sort((a, b) => rank(a.type) - rank(b.type))\n\t\t// every structure's obstacle made into the ground's tiles together, as a load does (RV42): a wooded tile once, not\n\t\t// once a tree. Let go before the first unit, which is put on the ways with every structure in them\n\t\tlet held = true\n\t\tworld.nav.holdObstacles?.(true)\n\t\tconst letGo = () => {\n\t\t\tif (held) world.nav.holdObstacles?.(false)\n\t\t\theld = false\n\t\t}\n\t\t/** Units of the map with orders of their own, given once everything stands (a path's ends, a guard's post) */\n\t\tconst ordered: [Entity, MapObjectOrder[]][] = []\n\t\tfor (const object of objects) {\n\t\t\tif (held && rank(object.type) === 2) letGo()\n\t\t\tconst entity = spawnMapObject(world, object, map)\n\t\t\tif (object.orders?.length) ordered.push([entity, object.orders])\n\t\t\tplaced.add(object.owner)\n\t\t}\n\t\tletGo()\n\t\tfor (const [entity, orders] of ordered) giveMapOrders(world, entity, orders)\n\t\tfor (const camp of map.camps) {\n\t\t\t// a unit of a camp is one of a random group when it says `@group`\n\t\t\tconst units = camp.units\n\t\t\t\t.map((type) => (type.startsWith('@') ? drawn('', type.slice(1)) : type))\n\t\t\t\t.filter((type) => world.registry.units.has(type))\n\t\t\tif (!units.length) continue\n\t\t\tconst made = spawnCamp(world, MAP_CREEPS, camp, units)\n\t\t\tif (camp.name) made.name = camp.name\n\t\t\tif (camp.respawn !== undefined) made.respawn = camp.respawn\n\t\t\tif (world.hooks.has('mapCamp')) world.hooks.run('mapCamp', { camp: made, from: camp, data: mapCampData(world.registry, camp, map) })\n\t\t}\n\t\t// a player's race has a start of its own, in place of the game's\n\t\tconst raceDef = (player: PlayerId) => {\n\t\t\tconst race = world.players.get(player)?.race\n\t\t\treturn race === undefined ? undefined : world.registry.race(race)\n\t\t}\n\t\tfor (const player of map.players) {\n\t\t\tif (player.start && !placed.has(player.id)) spawnStart(world, raceDef(player.id)?.start ?? game.start, player.id, player.start)\n\t\t}\n\t\t// a copy of a race keeps the original's `onStart` unless it says not to (`RaceDef.inherits`)\n\t\tfor (const player of map.players) {\n\t\t\tconst race = raceDef(player.id)\n\t\t\tif (race && race.inherits?.onStart !== false) race.onStart?.(world, player.id)\n\t\t}\n\t\t// what a pack starts of its own from the map: the objectives it gives at the start (`mapObjectives`)\n\t\tif (world.hooks.has('mapStart')) world.hooks.run('mapStart', { map })\n\t})\n}\n\n/**\n * Players a map of the game may have (`GameModule.maxPlayers`): 8 when it says nothing, never more than the fog keeps apart\n *\n * @beta\n */\nexport const maxPlayersOf = (game: GameModule): number => Math.max(1, Math.min(Math.floor(game.maxPlayers ?? DEFAULT_MAX_PLAYERS), MAX_MAP_PLAYERS))\n"],"mappings":";;;;AA4DA,IAAa,YAAb,cAA+B,MAAM;CACf;CAArB,YAAY,SAAgC;EAC3C,MAAM,QAAQ,OAAO;EADD,KAAA,UAAA;CAErB;AACD;;AAYA,IAAa,UAAU,WAAiC;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