@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.
Files changed (341) hide show
  1. package/LICENSE +21 -0
  2. package/dist/abilities/buffs.d.ts +83 -0
  3. package/dist/abilities/castTold.d.ts +12 -0
  4. package/dist/abilities/charges.d.ts +28 -0
  5. package/dist/abilities/dispel.d.ts +9 -0
  6. package/dist/abilities/effectFields.d.ts +10 -0
  7. package/dist/abilities/effects/buff.d.ts +8 -0
  8. package/dist/abilities/effects/core.d.ts +1 -0
  9. package/dist/abilities/effects/damage.d.ts +1 -0
  10. package/dist/abilities/effects/heal.d.ts +2 -0
  11. package/dist/abilities/effects/missile.d.ts +1 -0
  12. package/dist/abilities/effects/moves.d.ts +11 -0
  13. package/dist/abilities/effects/passives.d.ts +15 -0
  14. package/dist/abilities/effects/sight.d.ts +4 -0
  15. package/dist/abilities/effects/spawn.d.ts +2 -0
  16. package/dist/abilities/effects/timed.d.ts +4 -0
  17. package/dist/abilities/effects/trade.d.ts +1 -0
  18. package/dist/abilities/effects.d.ts +122 -0
  19. package/dist/abilities/land.d.ts +21 -0
  20. package/dist/abilities/scaled.d.ts +21 -0
  21. package/dist/abilities/text.d.ts +113 -0
  22. package/dist/ai/area.d.ts +53 -0
  23. package/dist/ai/brain.d.ts +528 -0
  24. package/dist/ai/budget.d.ts +67 -0
  25. package/dist/ai/checks.d.ts +115 -0
  26. package/dist/ai/computer.d.ts +166 -0
  27. package/dist/ai/defence.d.ts +108 -0
  28. package/dist/ai/define.d.ts +21 -0
  29. package/dist/ai/economy.d.ts +129 -0
  30. package/dist/ai/geometry.d.ts +35 -0
  31. package/dist/ai/goals.d.ts +360 -0
  32. package/dist/ai/index.d.ts +38 -0
  33. package/dist/ai/knowledge.d.ts +418 -0
  34. package/dist/ai/lanes.d.ts +232 -0
  35. package/dist/ai/melee/build.d.ts +61 -0
  36. package/dist/ai/melee/goals.d.ts +299 -0
  37. package/dist/ai/melee/heroes.d.ts +27 -0
  38. package/dist/ai/melee/index.d.ts +14 -0
  39. package/dist/ai/melee/production.d.ts +8 -0
  40. package/dist/ai/melee/surrender.d.ts +24 -0
  41. package/dist/ai/micro.d.ts +278 -0
  42. package/dist/ai/mission.d.ts +195 -0
  43. package/dist/ai/missionRules.d.ts +18 -0
  44. package/dist/ai/module.d.ts +116 -0
  45. package/dist/ai/options.d.ts +61 -0
  46. package/dist/ai/plans/build.d.ts +280 -0
  47. package/dist/ai/plans/placement.d.ts +82 -0
  48. package/dist/ai/plans/plans.d.ts +105 -0
  49. package/dist/ai/plans/production.d.ts +210 -0
  50. package/dist/ai/plans/purse.d.ts +73 -0
  51. package/dist/ai/plans/tech.d.ts +37 -0
  52. package/dist/ai/profiles.d.ts +204 -0
  53. package/dist/ai/reach.d.ts +4 -0
  54. package/dist/ai/report.d.ts +203 -0
  55. package/dist/ai/roles.d.ts +133 -0
  56. package/dist/ai/rules.d.ts +288 -0
  57. package/dist/ai/scouting.d.ts +98 -0
  58. package/dist/ai/settings.d.ts +73 -0
  59. package/dist/ai/squads.d.ts +429 -0
  60. package/dist/ai/strength.d.ts +167 -0
  61. package/dist/ai/task.d.ts +118 -0
  62. package/dist/ai/tasks/attack.d.ts +7 -0
  63. package/dist/ai/tasks/capture.d.ts +21 -0
  64. package/dist/ai/tasks/creep.d.ts +16 -0
  65. package/dist/ai/tasks/defend.d.ts +29 -0
  66. package/dist/ai/tasks/drop.d.ts +34 -0
  67. package/dist/ai/tasks/escort.d.ts +16 -0
  68. package/dist/ai/tasks/gather.d.ts +23 -0
  69. package/dist/ai/tasks/harass.d.ts +7 -0
  70. package/dist/ai/tasks/hold.d.ts +20 -0
  71. package/dist/ai/tasks/index.d.ts +32 -0
  72. package/dist/ai/tasks/move.d.ts +19 -0
  73. package/dist/ai/tasks/patrol.d.ts +8 -0
  74. package/dist/ai/tasks/retreat.d.ts +20 -0
  75. package/dist/ai/tasks/scout.d.ts +29 -0
  76. package/dist/ai/tasks/shared.d.ts +74 -0
  77. package/dist/ai/team.d.ts +155 -0
  78. package/dist/ai/threat.d.ts +91 -0
  79. package/dist/ai/view.d.ts +366 -0
  80. package/dist/ai/waves.d.ts +126 -0
  81. package/dist/ai.js +6239 -0
  82. package/dist/ai.js.map +1 -0
  83. package/dist/aiTesting.d.ts +179 -0
  84. package/dist/areas.d.ts +149 -0
  85. package/dist/attacks.d.ts +66 -0
  86. package/dist/attributes.d.ts +66 -0
  87. package/dist/brain-BvVdUhX8.js +7659 -0
  88. package/dist/brain-BvVdUhX8.js.map +1 -0
  89. package/dist/builds-C6LfgvEU.js +460 -0
  90. package/dist/builds-C6LfgvEU.js.map +1 -0
  91. package/dist/bytes.d.ts +6 -0
  92. package/dist/camps.d.ts +95 -0
  93. package/dist/capture.d.ts +131 -0
  94. package/dist/cellLayers.d.ts +75 -0
  95. package/dist/cinematics.d.ts +194 -0
  96. package/dist/clock.d.ts +32 -0
  97. package/dist/commands.d.ts +235 -0
  98. package/dist/components.d.ts +184 -0
  99. package/dist/computers.d.ts +108 -0
  100. package/dist/concealment.d.ts +61 -0
  101. package/dist/coreComponents-syuh2fPG.js +5149 -0
  102. package/dist/coreComponents-syuh2fPG.js.map +1 -0
  103. package/dist/coreComponents.d.ts +1 -0
  104. package/dist/dashing.d.ts +8 -0
  105. package/dist/debug.d.ts +36 -0
  106. package/dist/debug.js +3 -0
  107. package/dist/debugCommands-CzjrSm66.js +14739 -0
  108. package/dist/debugCommands-CzjrSm66.js.map +1 -0
  109. package/dist/debugCommands.d.ts +213 -0
  110. package/dist/debugging.d.ts +10 -0
  111. package/dist/definitions.d.ts +43 -0
  112. package/dist/defs.d.ts +1162 -0
  113. package/dist/denying.d.ts +81 -0
  114. package/dist/destructibles.d.ts +27 -0
  115. package/dist/determinism-BCymQwiE.js +518 -0
  116. package/dist/determinism-BCymQwiE.js.map +1 -0
  117. package/dist/determinism.d.ts +121 -0
  118. package/dist/dialog.d.ts +94 -0
  119. package/dist/effectRefs.d.ts +16 -0
  120. package/dist/effects.d.ts +80 -0
  121. package/dist/endings.d.ts +22 -0
  122. package/dist/engagement.d.ts +108 -0
  123. package/dist/engineEvents.d.ts +710 -0
  124. package/dist/entity.d.ts +409 -0
  125. package/dist/entityIndex.d.ts +50 -0
  126. package/dist/errors.d.ts +85 -0
  127. package/dist/events.d.ts +97 -0
  128. package/dist/exactMath.d.ts +63 -0
  129. package/dist/features.d.ts +10 -0
  130. package/dist/fields.d.ts +114 -0
  131. package/dist/fixture.d.ts +17 -0
  132. package/dist/fog.d.ts +110 -0
  133. package/dist/formation.d.ts +111 -0
  134. package/dist/friendlyFire.d.ts +26 -0
  135. package/dist/game-DiJEN-Ks.js +5800 -0
  136. package/dist/game-DiJEN-Ks.js.map +1 -0
  137. package/dist/game.d.ts +501 -0
  138. package/dist/gameData.d.ts +325 -0
  139. package/dist/gameFiles.d.ts +26 -0
  140. package/dist/gates.d.ts +28 -0
  141. package/dist/generate.d.ts +403 -0
  142. package/dist/generateWorker.d.ts +39 -0
  143. package/dist/grid.d.ts +53 -0
  144. package/dist/ground.d.ts +127 -0
  145. package/dist/groundSpeed.d.ts +22 -0
  146. package/dist/hero.d.ts +177 -0
  147. package/dist/home.d.ts +14 -0
  148. package/dist/hooks.d.ts +780 -0
  149. package/dist/hotReload.d.ts +76 -0
  150. package/dist/ids.d.ts +26 -0
  151. package/dist/index.d.ts +227 -0
  152. package/dist/index.js +4701 -0
  153. package/dist/index.js.map +1 -0
  154. package/dist/inspect-D9dWHmZ0.js +491 -0
  155. package/dist/inspect-D9dWHmZ0.js.map +1 -0
  156. package/dist/inspect.d.ts +176 -0
  157. package/dist/inventory.d.ts +18 -0
  158. package/dist/items.d.ts +91 -0
  159. package/dist/lanes.d.ts +213 -0
  160. package/dist/life.d.ts +53 -0
  161. package/dist/local-Dkovq42k.js +1379 -0
  162. package/dist/local-Dkovq42k.js.map +1 -0
  163. package/dist/log.d.ts +140 -0
  164. package/dist/manaBurn.d.ts +39 -0
  165. package/dist/map/file.d.ts +114 -0
  166. package/dist/map/images.d.ts +18 -0
  167. package/dist/map/look.d.ts +47 -0
  168. package/dist/map/pathProfile.d.ts +13 -0
  169. package/dist/map/resize.d.ts +54 -0
  170. package/dist/map/schema.d.ts +10 -0
  171. package/dist/map/terrain.d.ts +32 -0
  172. package/dist/map/types.d.ts +613 -0
  173. package/dist/map.d.ts +7 -0
  174. package/dist/mapCheck/cells.d.ts +19 -0
  175. package/dist/mapCheck/rule.d.ts +30 -0
  176. package/dist/mapCheck/rules/names.d.ts +3 -0
  177. package/dist/mapCheck/rules/objects.d.ts +3 -0
  178. package/dist/mapCheck/rules/paths.d.ts +3 -0
  179. package/dist/mapCheck/rules/players.d.ts +3 -0
  180. package/dist/mapCheck/rules/races.d.ts +3 -0
  181. package/dist/mapCheck/rules/random.d.ts +3 -0
  182. package/dist/mapCheck/rules/regions.d.ts +3 -0
  183. package/dist/mapCheck/rules/targets.d.ts +3 -0
  184. package/dist/mapCheck/rules/walking.d.ts +3 -0
  185. package/dist/mapCheck.d.ts +23 -0
  186. package/dist/mapFields.d.ts +364 -0
  187. package/dist/mapFile.d.ts +23 -0
  188. package/dist/mapMeasure.d.ts +95 -0
  189. package/dist/mapMerge.d.ts +19 -0
  190. package/dist/mapObjectives.d.ts +82 -0
  191. package/dist/mapObjects.d.ts +1 -0
  192. package/dist/math.d.ts +44 -0
  193. package/dist/messages.d.ts +150 -0
  194. package/dist/missionRules-C-bGxm0Q.js +523 -0
  195. package/dist/missionRules-C-bGxm0Q.js.map +1 -0
  196. package/dist/missionRules.d.ts +179 -0
  197. package/dist/mods.d.ts +146 -0
  198. package/dist/names.d.ts +93 -0
  199. package/dist/navigation/agentParams.d.ts +4 -0
  200. package/dist/navigation/air.d.ts +89 -0
  201. package/dist/navigation/builds.d.ts +140 -0
  202. package/dist/navigation/groundAreas.d.ts +23 -0
  203. package/dist/navigation/navigation.d.ts +127 -0
  204. package/dist/navigation/recast.d.ts +214 -0
  205. package/dist/navigation/sidePaths.d.ts +69 -0
  206. package/dist/navigation/sized.d.ts +1 -0
  207. package/dist/navigation-worker.js +11 -0
  208. package/dist/navigation-worker.js.map +1 -0
  209. package/dist/nearest.d.ts +8 -0
  210. package/dist/noise.d.ts +12 -0
  211. package/dist/objectives.d.ts +93 -0
  212. package/dist/orders/basic.d.ts +96 -0
  213. package/dist/orders/build.d.ts +91 -0
  214. package/dist/orders/cast.d.ts +105 -0
  215. package/dist/orders/facts.d.ts +14 -0
  216. package/dist/orders/harvest.d.ts +94 -0
  217. package/dist/orders/idle.d.ts +7 -0
  218. package/dist/orders/items.d.ts +14 -0
  219. package/dist/orders/queue.d.ts +24 -0
  220. package/dist/pack.schema.json +6621 -0
  221. package/dist/packs/director/index.d.ts +81 -0
  222. package/dist/packs/heroes/campaign.d.ts +137 -0
  223. package/dist/packs/heroes/carry.d.ts +59 -0
  224. package/dist/packs/heroes/commands.d.ts +6 -0
  225. package/dist/packs/heroes/hire.d.ts +9 -0
  226. package/dist/packs/heroes/index.d.ts +12 -0
  227. package/dist/packs/heroes/making.d.ts +16 -0
  228. package/dist/packs/heroes/respawn.d.ts +42 -0
  229. package/dist/packs/moba/index.d.ts +34 -0
  230. package/dist/packs/pack.d.ts +84 -0
  231. package/dist/packs-g5thvmGn.js +3199 -0
  232. package/dist/packs-g5thvmGn.js.map +1 -0
  233. package/dist/packs.d.ts +84 -0
  234. package/dist/paths.d.ts +51 -0
  235. package/dist/plain.d.ts +17 -0
  236. package/dist/player.d.ts +117 -0
  237. package/dist/portals.d.ts +66 -0
  238. package/dist/prefabs.d.ts +139 -0
  239. package/dist/presetBuildings.d.ts +52 -0
  240. package/dist/presetGround.d.ts +22 -0
  241. package/dist/profiles-B3NS9jwk.js +335 -0
  242. package/dist/profiles-B3NS9jwk.js.map +1 -0
  243. package/dist/races.d.ts +136 -0
  244. package/dist/randomGroups.d.ts +2 -0
  245. package/dist/registry.d.ts +464 -0
  246. package/dist/remains.d.ts +119 -0
  247. package/dist/replication.d.ts +103 -0
  248. package/dist/rng.d.ts +17 -0
  249. package/dist/rules.d.ts +395 -0
  250. package/dist/rulesCheck.d.ts +37 -0
  251. package/dist/runes.d.ts +41 -0
  252. package/dist/save.d.ts +277 -0
  253. package/dist/scenario.d.ts +56 -0
  254. package/dist/scheduler.d.ts +67 -0
  255. package/dist/score.d.ts +306 -0
  256. package/dist/sequences.d.ts +132 -0
  257. package/dist/server/doorman.d.ts +21 -0
  258. package/dist/server/gameServer.d.ts +346 -0
  259. package/dist/server/index.d.ts +24 -0
  260. package/dist/server/lobby.d.ts +1 -0
  261. package/dist/server/log.d.ts +13 -0
  262. package/dist/server/match.d.ts +24 -0
  263. package/dist/server/mode.d.ts +168 -0
  264. package/dist/server/navigation-worker.d.ts +1 -0
  265. package/dist/server/navigation.d.ts +11 -0
  266. package/dist/server/ops.d.ts +78 -0
  267. package/dist/server/packs.d.ts +15 -0
  268. package/dist/server/ratings.d.ts +62 -0
  269. package/dist/server/relay.d.ts +34 -0
  270. package/dist/server/rooms.d.ts +162 -0
  271. package/dist/server/seat.d.ts +2 -0
  272. package/dist/server/seatSettings.d.ts +15 -0
  273. package/dist/server/secret.d.ts +5 -0
  274. package/dist/server/start.d.ts +54 -0
  275. package/dist/server/websocket.d.ts +74 -0
  276. package/dist/server.js +2861 -0
  277. package/dist/server.js.map +1 -0
  278. package/dist/session/can.d.ts +20 -0
  279. package/dist/session/commandReplay.d.ts +92 -0
  280. package/dist/session/debug.d.ts +65 -0
  281. package/dist/session/delay.d.ts +15 -0
  282. package/dist/session/delta.d.ts +98 -0
  283. package/dist/session/entityState.d.ts +1 -0
  284. package/dist/session/local.d.ts +214 -0
  285. package/dist/session/memory.d.ts +27 -0
  286. package/dist/session/protocol.d.ts +1155 -0
  287. package/dist/session/remote.d.ts +530 -0
  288. package/dist/session/replay.d.ts +114 -0
  289. package/dist/session/seed.d.ts +7 -0
  290. package/dist/session/share.d.ts +78 -0
  291. package/dist/session/socket.d.ts +8 -0
  292. package/dist/session/wire.d.ts +153 -0
  293. package/dist/session/worker.d.ts +227 -0
  294. package/dist/shared.d.ts +171 -0
  295. package/dist/sides.d.ts +75 -0
  296. package/dist/sight.d.ts +27 -0
  297. package/dist/simulate-oXBiw1Ff.js +167 -0
  298. package/dist/simulate-oXBiw1Ff.js.map +1 -0
  299. package/dist/simulate-worker.d.ts +1 -0
  300. package/dist/simulate-worker.js +28 -0
  301. package/dist/simulate-worker.js.map +1 -0
  302. package/dist/simulate.d.ts +154 -0
  303. package/dist/smart.d.ts +9 -0
  304. package/dist/spatial.d.ts +62 -0
  305. package/dist/spawning.d.ts +33 -0
  306. package/dist/stances.d.ts +76 -0
  307. package/dist/start.d.ts +71 -0
  308. package/dist/stats.d.ts +122 -0
  309. package/dist/summons.d.ts +63 -0
  310. package/dist/systems/abilities.d.ts +3 -0
  311. package/dist/systems/combat.d.ts +71 -0
  312. package/dist/systems/combatTold.d.ts +14 -0
  313. package/dist/systems/construction.d.ts +34 -0
  314. package/dist/systems/economy.d.ts +21 -0
  315. package/dist/systems/fog.d.ts +19 -0
  316. package/dist/systems/life.d.ts +3 -0
  317. package/dist/systems/movement.d.ts +105 -0
  318. package/dist/systems/orders.d.ts +7 -0
  319. package/dist/systems/production.d.ts +49 -0
  320. package/dist/systems/productionQueue.d.ts +40 -0
  321. package/dist/systems/victory.d.ts +14 -0
  322. package/dist/talk.d.ts +65 -0
  323. package/dist/tech.d.ts +62 -0
  324. package/dist/techTree.d.ts +38 -0
  325. package/dist/terrain.d.ts +173 -0
  326. package/dist/terrainSave.d.ts +29 -0
  327. package/dist/testing.d.ts +58 -0
  328. package/dist/testing.js +822 -0
  329. package/dist/testing.js.map +1 -0
  330. package/dist/tiles.d.ts +34 -0
  331. package/dist/timers.d.ts +146 -0
  332. package/dist/tomes.d.ts +48 -0
  333. package/dist/trade.d.ts +28 -0
  334. package/dist/transport.d.ts +76 -0
  335. package/dist/tunables.d.ts +45 -0
  336. package/dist/upkeep.d.ts +16 -0
  337. package/dist/veterancy.d.ts +80 -0
  338. package/dist/walls.d.ts +86 -0
  339. package/dist/world.d.ts +1118 -0
  340. package/package.json +80 -5
  341. package/README.md +0 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debugCommands-CzjrSm66.js","names":["inventoryChanged","cinematicCue","cinematicEnded","resourcesSpentEvent","giveBack","NOTHING","index","release","plain","wait","cinematicCueEvent","plain","cinematicCuedEvent","cinematicEndedEvent","cinematicChoiceEvent","plain","REACH","inventoryChangedEvent","REACH","hasRoom","near","workedEvent","pingedEvent","chattedEvent","tradedEvent","exchangedEvent","pauseAskedEvent","commandRejectedEvent","researchCommand","giveCommand","commandHandledEvent"],"sources":["../src/exactMath.ts","../src/math.ts","../src/start.ts","../src/orders/facts.ts","../src/components.ts","../src/inventory.ts","../src/defs.ts","../src/stats.ts","../src/events.ts","../src/engineEvents.ts","../src/session/memory.ts","../src/replication.ts","../src/abilities/land.ts","../src/abilities/text.ts","../src/systems/construction.ts","../src/entity.ts","../src/player.ts","../src/messages.ts","../src/shared.ts","../src/abilities/charges.ts","../src/navigation/agentParams.ts","../src/systems/productionQueue.ts","../src/hero.ts","../src/abilities/scaled.ts","../src/abilities/buffs.ts","../src/attacks.ts","../src/engagement.ts","../src/systems/movement.ts","../src/systems/combat.ts","../src/plain.ts","../src/debug.ts","../src/timers.ts","../src/sequences.ts","../src/cinematics.ts","../src/effectRefs.ts","../src/dashing.ts","../src/abilities/effectFields.ts","../src/abilities/effects.ts","../src/fields.ts","../src/formation.ts","../src/items.ts","../src/orders/queue.ts","../src/orders/cast.ts","../src/grid.ts","../src/orders/harvest.ts","../src/nearest.ts","../src/races.ts","../src/tech.ts","../src/systems/production.ts","../src/orders/build.ts","../src/hooks.ts","../src/transport.ts","../src/smart.ts","../src/talk.ts","../src/trade.ts","../src/systems/victory.ts","../src/endings.ts","../src/orders/idle.ts","../src/systems/orders.ts","../src/commands.ts","../src/summons.ts","../src/paths.ts","../src/abilities/dispel.ts","../src/abilities/effects/buff.ts","../src/abilities/effects/damage.ts","../src/abilities/effects/heal.ts","../src/abilities/effects/missile.ts","../src/home.ts","../src/abilities/effects/moves.ts","../src/abilities/effects/passives.ts","../src/abilities/effects/sight.ts","../src/abilities/effects/spawn.ts","../src/abilities/effects/timed.ts","../src/abilities/effects/trade.ts","../src/abilities/effects/core.ts","../src/log.ts","../src/gameData.ts","../src/map/types.ts","../src/tiles.ts","../src/map/look.ts","../src/rng.ts","../src/terrain.ts","../src/map/pathProfile.ts","../src/map/terrain.ts","../src/bytes.ts","../src/terrainSave.ts","../src/ground.ts","../src/mapFields.ts","../src/randomGroups.ts","../src/mapObjects.ts","../src/debugCommands.ts"],"sourcesContent":["/**\n * The maths the simulation does, the same to the last bit in every engine (determinism D3). JavaScript says exactly\n * what `+`, `-`, `*`, `/` and `Math.sqrt` give, but not `Math.sin`, `Math.cos`, `Math.atan`, `Math.atan2` or\n * `Math.hypot`: V8, SpiderMonkey and JavaScriptCore each have their own, and two versions of one can differ (Node 22's\n * `atan2` and Chromium's do, in the last bit). These are fdlibm's (FreeBSD's msun), written with what is exact\n * everywhere, so a world run in a page, in a worker, on a server or in a replay comes out the same.\n *\n * Within a unit in the last place of `Math`'s; they are not faster. What only draws (a view, an effect) has no need of\n * them: what decides does\n */\n\n/** The high 32 bits of a number as a double: its sign, its exponent and the top of its fraction */\nconst view = new DataView(new ArrayBuffer(8))\nfunction highWord(x: number): number {\n\tview.setFloat64(0, x)\n\treturn view.getInt32(0)\n}\n\n// ---- sin, cos (k_sin.c, k_cos.c, e_rem_pio2.c)\n\nconst S1 = -1.66666666666666324348e-1\nconst S2 = 8.33333333332248946124e-3\nconst S3 = -1.98412698298579493134e-4\nconst S4 = 2.75573137070700676789e-6\nconst S5 = -2.50507602534068634195e-8\nconst S6 = 1.58969099521155010221e-10\n\n/** sin on [-π/4, π/4], of `x + y` where `y` is the tail of a reduced argument (`tail` false when there is none) */\nfunction kernelSin(x: number, y: number, tail: boolean): number {\n\tconst z = x * x\n\tconst w = z * z\n\tconst r = S2 + z * (S3 + z * S4) + z * w * (S5 + z * S6)\n\tconst v = z * x\n\tif (!tail) return x + v * (S1 + z * r)\n\treturn x - (z * (0.5 * y - v * r) - y - v * S1)\n}\n\nconst C1 = 4.16666666666666019037e-2\nconst C2 = -1.38888888888741095749e-3\nconst C3 = 2.48015872894767294178e-5\nconst C4 = -2.75573143513906633035e-7\nconst C5 = 2.0875723212981748279e-9\nconst C6 = -1.13596475577881948265e-11\n\n/** cos on [-π/4, π/4], of `x + y` */\nfunction kernelCos(x: number, y: number): number {\n\tconst z = x * x\n\tlet w = z * z\n\tconst r = z * (C1 + z * (C2 + z * C3)) + w * w * (C4 + z * (C5 + z * C6))\n\tconst hz = 0.5 * z\n\tw = 1 - hz\n\treturn w + (1 - w - hz + (z * r - x * y))\n}\n\nconst INV_PIO2 = 6.36619772367581382433e-1\nconst PIO2_1 = 1.57079632673412561417\nconst PIO2_1T = 6.07710050650619224932e-11\nconst PIO2_2 = 6.0771005063039659766e-11\nconst PIO2_2T = 2.02226624879595063154e-21\nconst PIO2_3 = 2.0222662487111664558e-21\nconst PIO2_3T = 8.47842766036889956997e-32\nconst TWO_PI = 6.283185307179586\n/** 1.5 × 2⁵²: added and taken away, it rounds a number to the nearest integer, ties to even, in every engine */\nconst ROUNDER = 6755399441055744\n\n/** `x` less the nearest multiple of π/2: which multiple (`n`), and the rest as a head and a tail (`y0 + y1`) */\nconst reduced = { n: 0, y0: 0, y1: 0 }\nfunction reduce(x: number): void {\n\t// far out (more than 2²⁰·π/2), whole turns are taken off first: less exact than fdlibm's long reduction, as exact\n\t// in every engine, and an angle in a game is never there\n\tif (Math.abs(x) > 1647099.3291652855) x -= TWO_PI * (x / TWO_PI + ROUNDER - ROUNDER)\n\tconst fn = x * INV_PIO2 + ROUNDER - ROUNDER\n\tlet r = x - fn * PIO2_1\n\tlet w = fn * PIO2_1T\n\tlet y0 = r - w\n\tconst j = (highWord(x) >> 20) & 0x7ff\n\tlet i = j - ((highWord(y0) >> 20) & 0x7ff)\n\tif (i > 16) {\n\t\t// a second step, where the first took off nearly all of it\n\t\tlet t = r\n\t\tw = fn * PIO2_2\n\t\tr = t - w\n\t\tw = fn * PIO2_2T - (t - r - w)\n\t\ty0 = r - w\n\t\ti = j - ((highWord(y0) >> 20) & 0x7ff)\n\t\tif (i > 49) {\n\t\t\tt = r\n\t\t\tw = fn * PIO2_3\n\t\t\tr = t - w\n\t\t\tw = fn * PIO2_3T - (t - r - w)\n\t\t\ty0 = r - w\n\t\t}\n\t}\n\treduced.n = fn\n\treduced.y0 = y0\n\treduced.y1 = r - y0 - w\n}\n\n/**\n * The sine, the same in every engine (fdlibm's)\n *\n * @beta\n */\nexport function sin(x: number): number {\n\tconst ax = Math.abs(x)\n\tif (ax <= 0.7853981633974483) return ax < 7.450580596923828e-9 ? x : kernelSin(x, 0, false)\n\tif (!Number.isFinite(x)) return NaN\n\treduce(x)\n\tconst { y0, y1 } = reduced\n\tswitch (reduced.n & 3) {\n\t\tcase 0:\n\t\t\treturn kernelSin(y0, y1, true)\n\t\tcase 1:\n\t\t\treturn kernelCos(y0, y1)\n\t\tcase 2:\n\t\t\treturn -kernelSin(y0, y1, true)\n\t\tdefault:\n\t\t\treturn -kernelCos(y0, y1)\n\t}\n}\n\n/**\n * The cosine, the same in every engine (fdlibm's)\n *\n * @beta\n */\nexport function cos(x: number): number {\n\tconst ax = Math.abs(x)\n\tif (ax <= 0.7853981633974483) return ax < 7.450580596923828e-9 ? 1 : kernelCos(x, 0)\n\tif (!Number.isFinite(x)) return NaN\n\treduce(x)\n\tconst { y0, y1 } = reduced\n\tswitch (reduced.n & 3) {\n\t\tcase 0:\n\t\t\treturn kernelCos(y0, y1)\n\t\tcase 1:\n\t\t\treturn -kernelSin(y0, y1, true)\n\t\tcase 2:\n\t\t\treturn -kernelCos(y0, y1)\n\t\tdefault:\n\t\t\treturn kernelSin(y0, y1, true)\n\t}\n}\n\n// ---- atan, atan2 (s_atan.c, e_atan2.c)\n\nconst ATAN_HI = [4.63647609000806093515e-1, 7.85398163397448278999e-1, 9.82793723247329054082e-1, 1.570796326794896558]\nconst ATAN_LO = [2.26987774529616870924e-17, 3.06161699786838301793e-17, 1.39033110312309984516e-17, 6.12323399573676603587e-17]\nconst AT = [\n\t3.33333333333329318027e-1, -1.99999999998764832476e-1, 1.42857142725034663711e-1, -1.1111110405462355788e-1, 9.09088713343650656196e-2,\n\t-7.69187620504482999495e-2, 6.66107313738753120669e-2, -5.83357013379057348645e-2, 4.97687799461593236017e-2, -3.6531572744216915527e-2,\n\t1.62858201153657823623e-2\n]\n\n/**\n * The arctangent, the same in every engine (fdlibm's)\n *\n * @beta\n */\nexport function atan(x: number): number {\n\tif (Number.isNaN(x)) return NaN\n\tconst negative = x < 0 || Object.is(x, -0)\n\tlet ax = Math.abs(x)\n\tif (ax >= 7.378697629483821e19) return negative ? -(ATAN_HI[3] + ATAN_LO[3]) : ATAN_HI[3] + ATAN_LO[3]\n\tlet id: number\n\tif (ax < 0.4375) {\n\t\tif (ax < 7.450580596923828e-9) return x\n\t\tid = -1\n\t\tax = x\n\t} else if (ax < 1.1875) {\n\t\tif (ax < 0.6875) {\n\t\t\tid = 0\n\t\t\tax = (2 * ax - 1) / (2 + ax)\n\t\t} else {\n\t\t\tid = 1\n\t\t\tax = (ax - 1) / (ax + 1)\n\t\t}\n\t} else if (ax < 2.4375) {\n\t\tid = 2\n\t\tax = (ax - 1.5) / (1 + 1.5 * ax)\n\t} else {\n\t\tid = 3\n\t\tax = -1 / ax\n\t}\n\tconst z = ax * ax\n\tconst w = z * z\n\tconst s1 = z * (AT[0] + w * (AT[2] + w * (AT[4] + w * (AT[6] + w * (AT[8] + w * AT[10])))))\n\tconst s2 = w * (AT[1] + w * (AT[3] + w * (AT[5] + w * (AT[7] + w * AT[9]))))\n\tif (id < 0) return ax - ax * (s1 + s2)\n\tconst result = ATAN_HI[id] - (ax * (s1 + s2) - ATAN_LO[id] - ax)\n\treturn negative ? -result : result\n}\n\nconst PI = 3.141592653589793116\nconst PI_LO = 1.2246467991473531772e-16\nconst PI_O_2 = 1.570796326794896558\nconst PI_O_4 = 7.85398163397448279e-1\n\n/**\n * The angle of a point from the x axis, `atan2(y, x)`, the same in every engine (fdlibm's)\n *\n * @beta\n */\nexport function atan2(y: number, x: number): number {\n\tif (Number.isNaN(x) || Number.isNaN(y)) return NaN\n\tif (x === 1) return atan(y)\n\tconst yNegative = y < 0 || Object.is(y, -0)\n\tconst xNegative = x < 0 || Object.is(x, -0)\n\tif (y === 0) return xNegative ? (yNegative ? -PI : PI) : y\n\tif (x === 0) return yNegative ? -PI_O_2 : PI_O_2\n\tif (!Number.isFinite(x)) {\n\t\tif (!Number.isFinite(y)) {\n\t\t\tconst angle = xNegative ? 3 * PI_O_4 : PI_O_4\n\t\t\treturn yNegative ? -angle : angle\n\t\t}\n\t\tconst angle = xNegative ? PI : 0\n\t\treturn yNegative ? -angle : angle\n\t}\n\tif (!Number.isFinite(y)) return yNegative ? -PI_O_2 : PI_O_2\n\tconst ratio = Math.abs(y / x)\n\tlet z: number\n\tif (ratio > 1.152921504606847e18) z = PI_O_2 + 0.5 * PI_LO\n\telse if (xNegative && ratio < 8.673617379884035e-19) z = 0\n\telse z = atan(ratio)\n\tif (!xNegative) return yNegative ? -z : z\n\treturn yNegative ? z - PI_LO - PI : PI - (z - PI_LO)\n}\n\n/**\n * The length of `(x, y)`, `√(x² + y²)`, the same in every engine (`Math.hypot` is not: it scales its arguments as each\n * engine likes). For the lengths of a game, which are neither near 1e154 nor near 1e-154\n *\n * @beta\n */\nexport const hypot = (x: number, y: number): number => Math.sqrt(x * x + y * y)\n\n// ---- exp\n\nconst LN2 = 6.93147180559945286227e-1\n/** Terms of the series: at a remainder under half of ln 2, the next term is under 1e-24 of the sum, well under a double's last place */\nconst EXP_TERMS = 18\n\n/**\n * e^x, the same in every engine (`Math.exp` is not: each has its own): `x` is split into a count of ln 2 and a\n * remainder under half of one, the remainder's exponential is its Taylor series (adding and multiplying alone, which\n * are exact everywhere), and the result is that doubled or halved the count of times. Within a few units in the last\n * place of `Math.exp`'s; the point is sameness, not speed. What a response curve of the computer player's is made of\n * (`curve.saturate`, AI plan B1)\n */\nexport function exp(x: number): number {\n\tif (x !== x) return NaN\n\tif (x > 709.782712893384) return Infinity\n\tif (x < -745.1332191019412) return 0\n\tconst k = Math.round(x / LN2)\n\tconst r = x - k * LN2\n\tlet term = 1\n\tlet sum = 1\n\tfor (let i = 1; i <= EXP_TERMS; i++) {\n\t\tterm *= r / i\n\t\tsum += term\n\t}\n\t// 2^k by doubling or halving: a count of exact steps, never `**`\n\tif (k > 0) for (let i = 0; i < k; i++) sum *= 2\n\telse for (let i = 0; i < -k; i++) sum *= 0.5\n\treturn sum\n}\n\n/**\n * The simulation's maths, the same in every engine: what a game's rules use in the place of `Math`'s, so that its\n * worlds come out the same in a page, on a server and in a replay (`sin`, `cos`, `atan`, `atan2`, `hypot`, `exp`)\n *\n * @beta\n */\nexport const exactMath = { sin, cos, atan, atan2, hypot, exp } as const\n","import { atan2 } from './exactMath'\n/**\n * A point on the ground plane. The simulation is 2D; height always comes from the terrain.\n *\n * @beta\n */\nexport interface Vec2 {\n\tx: number\n\tz: number\n}\n\n/** @internal */\nexport const TAU = Math.PI * 2\n\n/** @beta */\nexport const vec2 = (x = 0, z = 0): Vec2 => ({ x, z })\n\n/** @beta */\nexport const clamp = (v: number, min: number, max: number) => (v < min ? min : v > max ? max : v)\n\n/** @beta */\nexport const lerp = (a: number, b: number, t: number) => a + (b - a) * t\n\n/**\n * 0 at `from` and before, 1 at `to` and after, eased in and out between: a shader's `smoothstep`\n *\n * @beta\n */\nexport const smoothstep = (from: number, to: number, x: number) => {\n\tconst t = clamp((x - from) / (to - from), 0, 1)\n\treturn t * t * (3 - 2 * t)\n}\n\n/**\n * A number in 0..1 for two whole numbers, the same each time and in every engine (it is integer arithmetic)\n *\n * @beta\n */\nexport function hashInts(a: number, b: number): number {\n\tlet h = Math.imul(a ^ 0x9e3779b9, 0x85ebca6b) ^ Math.imul(b, 0xc2b2ae35)\n\th ^= h >>> 16\n\th = Math.imul(h, 0x7feb352d)\n\th ^= h >>> 15\n\treturn (h >>> 0) / 0xffffffff\n}\n\n/**\n * cyrb53: a 53-bit hash of text, the same in every engine (it is integer arithmetic)\n *\n * @internal\n */\nexport function hashText(text: string): string {\n\tlet h1 = 0xdeadbeef\n\tlet h2 = 0x41c6ce57\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst c = text.charCodeAt(i)\n\t\th1 = Math.imul(h1 ^ c, 2654435761)\n\t\th2 = Math.imul(h2 ^ c, 1597334677)\n\t}\n\th1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)\n\th2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)\n\treturn (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0')\n}\n\n/** @beta */\nexport const distSq = (a: Vec2, b: Vec2) => {\n\tconst dx = a.x - b.x\n\tconst dz = a.z - b.z\n\treturn dx * dx + dz * dz\n}\n\n/** @beta */\nexport const dist = (a: Vec2, b: Vec2) => Math.sqrt(distSq(a, b))\n\n/**\n * Facing angle (radians) of the direction from `a` to `b`. 0 faces +z, increasing towards +x.\n *\n * @internal\n */\nexport const angleTo = (a: Vec2, b: Vec2) => atan2(b.x - a.x, b.z - a.z)\n\n/**\n * Shortest signed difference between two angles, in (-PI, PI].\n *\n * @internal\n */\nexport const angleDiff = (from: number, to: number) => {\n\tlet d = (to - from) % TAU\n\tif (d > Math.PI) d -= TAU\n\telse if (d <= -Math.PI) d += TAU\n\treturn d\n}\n\n/** @internal */\nexport const rotateTowards = (from: number, to: number, maxStep: number) => {\n\tconst d = angleDiff(from, to)\n\tif (Math.abs(d) <= maxStep) return to\n\treturn from + Math.sign(d) * maxStep\n}\n\n/** @beta */\nexport const lerpAngle = (a: number, b: number, t: number) => a + angleDiff(a, b) * t\n\n/**\n * Axis aligned rectangle on the ground plane, described by its center and half sizes.\n *\n * @beta\n */\nexport interface Rect {\n\tx: number\n\tz: number\n\thw: number\n\thd: number\n}\n\n/**\n * Distance from a point to the edge of a rectangle. 0 when the point is inside.\n *\n * @internal\n */\nexport const distToRect = (p: Vec2, r: Rect) => {\n\tconst dx = Math.max(Math.abs(p.x - r.x) - r.hw, 0)\n\tconst dz = Math.max(Math.abs(p.z - r.z) - r.hd, 0)\n\treturn Math.sqrt(dx * dx + dz * dz)\n}\n\n/**\n * Closest point to `p` on the border of `r` grown by `margin`. Points inside are pushed out through the nearest side.\n *\n * @internal\n */\nexport const closestPointOnRect = (p: Vec2, r: Rect, margin = 0): Vec2 => {\n\tconst hw = r.hw + margin\n\tconst hd = r.hd + margin\n\tconst lx = p.x - r.x\n\tconst lz = p.z - r.z\n\tif (Math.abs(lx) < hw && Math.abs(lz) < hd) {\n\t\t// inside: exit through the closest side\n\t\tif (hw - Math.abs(lx) < hd - Math.abs(lz)) return { x: r.x + (lx < 0 ? -hw : hw), z: p.z }\n\t\treturn { x: p.x, z: r.z + (lz < 0 ? -hd : hd) }\n\t}\n\treturn { x: r.x + clamp(lx, -hw, hw), z: r.z + clamp(lz, -hd, hd) }\n}\n","import type { Entity, PlayerId } from './entity'\nimport { exactMath } from './exactMath'\nimport { dist, type Vec2 } from './math'\nimport type { World } from './world'\n\n/*\n * What a player starts a map with (campaign plan RC1): a hall and workers put down at their start location, for players\n * the map places nothing for. As data (`StartData`: the hall, the workers, what else, all by unit type id, which is\n * what a race made in the editor's Data panel has, and what `checkRaces` can check), or as code (`StartCode`: a\n * function that puts down whatever it likes). `startingBase` is what the data form does, for code to call as well\n */\n\n/**\n * A start in code: puts down a base at the start location, whatever it likes\n *\n * @beta\n */\nexport interface StartCode {\n\t/** Puts down a base at the start location. Only for players the map places nothing for */\n\tspawn(world: World, player: PlayerId, at: Vec2): void\n}\n\n/**\n * A start as data: a hall at the start location and workers on the side of the closest gold mine, as in a classic melee\n * game (`startingBase` puts it down). Every id is a unit type of the game's (`checkRaces` says where one is not)\n *\n * @beta\n */\nexport interface StartData {\n\t/** The unit type put down at the start location: a town hall */\n\thall: string\n\t/** The workers put down beside it, facing the closest gold mine */\n\tworkers: { type: string; count: number }\n\t/** What else is put down with the workers, in the same row after them: a race's first fighter */\n\tunits?: { type: string; count: number }[]\n\t/**\n\t * What the race builds on the closest gold mine to gather it, put down there already standing (the undead's cursed\n\t * mine). With it, the closest mine is found at any distance; without, the workers face a mine within 20 cells\n\t */\n\tonMine?: string\n\t/** How far from the hall the workers stand: 5 cells when left out */\n\tdistance?: number\n\t/** The angle between two workers in the row, in radians: 0.35 when left out */\n\tspread?: number\n}\n\n/**\n * What each player gets at the beginning of a game on a map, for players the map places nothing for: as data\n * (`StartData`: a hall, workers and what else by unit type, editable in the Data panel) or as code (`StartCode`). What\n * they start with of each resource is in its `ResourceDef`\n *\n * @beta\n */\nexport type StartDef = StartCode | StartData\n\n/** Whether a start is the data form */\nexport const isStartData = (start: StartDef): start is StartData => !('spawn' in start)\n\n/** How far the workers stand from their hall, and the angle between two of them, when the data does not say */\nconst DISTANCE = 5\nconst SPREAD = 0.35\n\n/**\n * Puts down what a start as data says (`StartData`): the hall at the point, what the race builds on the closest gold\n * mine (`onMine`) on it, and the workers and the other units in a row on the side of the hall that faces the mine,\n * facing it. With no mine in reach, the row faces north. A classic melee start; a race's `start` as data does this\n *\n * @beta\n */\nexport function startingBase(world: World, player: PlayerId, at: Vec2, start: StartData): void {\n\tconst hall = world.spawn(start.hall, player, at)\n\tlet nearest: Entity | undefined\n\tfor (const entity of world.entities.values()) {\n\t\tif (entity.def.resource?.kind !== 'gold') continue\n\t\tif (!nearest || dist(entity.pos, hall.pos) < dist(nearest.pos, hall.pos)) nearest = entity\n\t}\n\t// the workers face a mine within 20 cells; a race that gathers at a building of its own puts that on the closest one at any distance\n\tconst mine = nearest && (dist(nearest.pos, hall.pos) <= 20 || start.onMine) ? nearest : undefined\n\tif (mine && start.onMine) world.spawn(start.onMine, player, mine.pos)\n\tconst angle = mine ? exactMath.atan2(mine.pos.x - hall.pos.x, mine.pos.z - hall.pos.z) : 0\n\tconst types: string[] = []\n\tfor (const { type, count } of [start.workers, ...(start.units ?? [])]) for (let i = 0; i < count; i++) types.push(type)\n\tconst distance = start.distance ?? DISTANCE\n\tconst spread = start.spread ?? SPREAD\n\ttypes.forEach((type, i) => {\n\t\tconst side = (i - (types.length - 1) / 2) * spread\n\t\tworld.spawn(\n\t\t\ttype,\n\t\t\tplayer,\n\t\t\t{ x: hall.pos.x + exactMath.sin(angle + side) * distance, z: hall.pos.z + exactMath.cos(angle + side) * distance },\n\t\t\t{ facing: angle }\n\t\t)\n\t})\n}\n\n/**\n * Puts down a player's start at a point, whichever form it is in: the code's `spawn`, or the base the data describes\n * (`startingBase`). Nothing for no start\n *\n * @beta\n */\nexport function spawnStart(world: World, start: StartDef | undefined, player: PlayerId, at: Vec2): void {\n\tif (!start) return\n\tif (isStartData(start)) startingBase(world, player, at, start)\n\telse start.spawn(world, player, at)\n}\n\n/** The unit type ids a start as data names, each with where it is said (`start.hall`, `start.units[1].type`); none for code */\nexport function startIds(start: StartDef | undefined): { where: string; id: string }[] {\n\tif (!start || !isStartData(start)) return []\n\tconst out = [\n\t\t{ where: 'start.hall', id: start.hall },\n\t\t{ where: 'start.workers.type', id: start.workers.type },\n\t\t...(start.units ?? []).map((unit, index) => ({ where: `start.units[${index}].type`, id: unit.type }))\n\t]\n\tif (start.onMine !== undefined) out.push({ where: 'start.onMine', id: start.onMine })\n\treturn out\n}\n","/**\n * What the engine asks of an entity's current order (`orderSays`): its behaviour's to say (`OrderBehavior.committed`,\n * `waiting`, `channelling`, `building`), where it once read those fields of any order's state by name\n */\nimport type { Entity } from '#engine/entity'\nimport type { OrderFact } from '#engine/registry'\nimport type { World } from '#engine/world'\n/**\n * What an entity's current order says of a fact (`OrderFact`): false for an entity with no order, or an order whose\n * behaviour says nothing of it\n *\n * @beta\n */\nexport function orderSays(world: World, entity: Entity, fact: OrderFact): boolean {\n\tconst order = entity.orders[0]\n\tif (!order) return false\n\treturn world.registry.orders.find(order.type)?.[fact]?.(order) === true\n}\n","import type { Entity, PlayerId } from './entity'\nimport type { MapFieldDef } from './mapFields'\nimport type { Registry } from './registry'\nimport type { World } from './world'\n\n/*\n * How one of the engine's own parts becomes a component (master plan FD1, done for the shop; OB1 for the inventory\n * (`inventorySlots`) and the harvester (`gathering`); OB2 for a site (`constructionSite`) and what a building makes\n * (`productionQueue`); OB3 for the hero (`heroState`, filed by owner); OB4 follows for the hero rules, a pack):\n *\n * 1. Define it where its rules live (`shopStock` in `items.ts`): `defineComponent<State, Sent>('core.<part>', { replicate,\n * snapshot, same, index })`, the snapshot shaped for the screen (`StockInfo[]`, `InventoryInfo`), `same` comparing it\n * field by field, `index: 'owner'` where a player's own are asked for (heroes), `true` where every one is (shops).\n * 2. The entity's field goes (`Entity.shop`); `spawn` sets the component (`entity.set`); every reader is\n * `entity.get(component)` (or a reader of the part's: `slotsOf`, `harvesterOf`), every walk `world.index.with(component)`.\n * 3. The snapshot's typed fields go; readers use `snapshotOf(state, component)` (the client's entity a getter over it:\n * `inventory`, `carries`, `load`). Nothing is kept for the old shape: no alias, no deprecated field.\n * 4. Saves need nothing: an entity's components are saved with it. `checkSave`'s walk of ids reads the component. No\n * format step for saves made before: the engine and its games are still being made.\n * 5. The index's own set for the part goes (`shopSet`).\n * 6. The HUD and the computer player read the snapshot through `snapshotOf`; the inspector's parts list loses the field.\n * 7. `npm run api -- --local`, the report read; `tick.bench.ts`, `client-frame.bench.ts`, `hud.bench.ts` flat.\n */\n\n/**\n * Components are typed state a game module or a mod keeps where the engine has no field for it: on an entity\n * (`entity.get(key)`), for the whole world (`world.state(key)`) or for each player (`player.state(key)`). The engine's\n * own parts are components too (`core.`: what a shop sells, an illusion's source), so that a game pays for what it uses\n * and nothing else.\n *\n * A component is plain data, so that it goes into a save with the rest of the world (see `saveWorld`): numbers,\n * text, lists and plain objects, with other entities by id.\n *\n * `T` is what the component holds; `S` is what a player's snapshot carries of it (`snapshot`), `T` itself when it is\n * sent as it is\n *\n * @beta\n */\nexport interface Component<T, S = T> {\n\treadonly id: string\n\t/**\n\t * Where an entity keeps it (`Entity.get`): a number of its own, given as it is defined, the same for every\n\t * definition of one id\n\t *\n\t * @internal\n\t */\n\treadonly slot: number\n\t/** What it starts as. Needed for world and player state, which is there from the moment it is asked for */\n\treadonly default?: () => T\n\t/**\n\t * Who gets an entity's component in their snapshot (`EntityState.components`), for a game's view to show:\n\t * the player it belongs to, their allies too, or everyone who sees the entity. Nobody when left out\n\t */\n\treadonly replicate?: Audience\n\t/**\n\t * `false` for what is the app's, not the game's rules (where the screen is played from, a tool's own): kept in the\n\t * app's saves, but left out of a scenario (`scenarioOfWorld`), which is loaded where only the game is (a test)\n\t */\n\treadonly portable?: boolean\n\t/**\n\t * What a player's snapshot carries of it, worked out for each player told (`replicate`): a part of it, rounded,\n\t * or shaped for the screen (a shop's stock with how far the next one is, not the seconds left). A copy of the whole\n\t * value when left out. What it returns is plain data; `undefined` sends nothing to that player\n\t *\n\t * @beta\n\t */\n\tsnapshot?(value: T, entity: Entity, view: SnapshotView): S | undefined\n\t/**\n\t * Whether two snapshots of it say the same, for the delta a player is sent (`same`): field by field, as the\n\t * component knows its shape. Compared as text (`JSON.stringify`) when left out, which costs with a big value\n\t *\n\t * @beta\n\t */\n\tsame?(a: S, b: S): boolean\n\t/**\n\t * Filed in the world's index (`world.index.with(key)`, always kept), and by owner too (`'owner'`:\n\t * `world.index.with(key, player)`) for what a player asks for often (their heroes), so a system goes through what\n\t * has the component and nothing else\n\t *\n\t * @beta\n\t */\n\treadonly index?: boolean | 'owner'\n\t/**\n\t * A field of the map editor's for it: what is placed on a map starts with the component set to what the field says\n\t * (`MapObject.data[id]`, under the component's own id), the editor's Inspector shows it for what `for` names, and\n\t * the game has it from the moment the world is made, with nothing to copy over in a `mapObject` hook\n\t *\n\t * @beta\n\t */\n\treadonly field?: ComponentFieldDef\n\t/**\n\t * What an entity starts with of it, as it is made (`World.spawn`), by its type: a building that makes things gets\n\t * its queue, a unit that carries its slots. Run for every entity made, the engine's parts first and in their order,\n\t * before the `made` hook; what it does not want of an entity, it leaves alone\n\t *\n\t * @beta\n\t */\n\treadonly onSpawn?: (entity: Entity, world: World) => void\n\t/**\n\t * What is called off of it as the entity leaves its owner: it dies (before the `death` hook), or is given to\n\t * another (`World.setOwner`). Run for an entity that has it\n\t *\n\t * @beta\n\t */\n\treadonly onLeave?: (entity: Entity, world: World) => void\n\t/**\n\t * Whether a structure that has it stands open now, in nobody's way (a gate opened): what puts the world back from a\n\t * save leaves it out of the ways as it was. The part that opens and shuts it takes it out and puts it back as it\n\t * goes (`World.nav`). Run for an entity that has it\n\t *\n\t * @beta\n\t */\n\tpassable?(value: T, entity: Entity): boolean\n\t/**\n\t * What a save keeps of it, where that is not its value as it is (plain data: numbers, text, lists, plain objects): a\n\t * `Map` as its entries, an effect as where it is in its ability. Its value as it is when left out, which has to be\n\t * plain data then\n\t *\n\t * @beta\n\t */\n\tsave?(value: T, world: World): unknown\n\t/** It again, of what `save` gave, as a save is loaded: the save's value as it is when left out @beta */\n\tload?(saved: unknown, registry: Registry): T\n\t/**\n\t * The ids of the game's definitions a save of it names (of what `save` gave, or its value): what a save is checked\n\t * for before a world is made of it, so that one naming what the game no longer has is refused all at once, saying\n\t * what (`SaveMissing`)\n\t *\n\t * @beta\n\t */\n\trefs?(saved: unknown): SavedRefs\n}\n\n/**\n * The ids of the game's definitions a component's saved value names, by kind (`Component.refs`)\n *\n * @beta\n */\nexport interface SavedRefs {\n\tunits?: readonly string[]\n\tabilities?: readonly string[]\n\tbuffs?: readonly string[]\n\titems?: readonly string[]\n\tupgrades?: readonly string[]\n}\n\n/** @beta */\nexport type Audience = 'owner' | 'allies' | 'everyone'\n\n/**\n * A map field of a component's: as a game's own field on a map (`MapFieldDef`), its id the component's\n *\n * @beta\n */\nexport type ComponentFieldDef = Omit<MapFieldDef, 'id'>\n\n/**\n * Who a snapshot is being made for, as a component shapes its part of it\n *\n * @beta\n */\nexport interface SnapshotView {\n\treadonly world: World\n\t/** The player it is made for; `undefined` for an observer */\n\treadonly player: PlayerId | undefined\n\t/** Whether the entity is the player's own */\n\treadonly own: boolean\n\t/** Whether the entity's owner is the player, or an ally of theirs (an observer is everyone's) */\n\treadonly ally: boolean\n\treadonly observer: boolean\n\t/** Whether the player's team can see another entity right now (`SessionView.knows`): what else of it the part may name */\n\treadonly knows: (entity: Entity) => boolean\n\t/** Whether an owner is the player or an ally of theirs (`SessionView.isAlly`) */\n\treadonly isAlly: (owner: PlayerId) => boolean\n\t/** Whether the player's team sees a spot of the map right now (`SessionView.sees`) */\n\treadonly sees: (x: number, z: number) => boolean\n}\n\n/**\n * What `defineComponent` takes: everything of a component but its id\n *\n * @beta\n */\nexport type ComponentOptions<T, S = T> = Omit<Component<T, S>, 'id' | 'slot'>\n\n/**\n * Each component's number by its id (`slot`): the code's, one id one number in a process, so that a module loaded\n * again (a dev server's) reads what its world holds of it, and `entity.get` is one load. Numbers and nothing else: a\n * world finds its game's components in its registry (`Registry.component`), which lists the engine's own and the\n * game's (`GameModule.components`), and nothing of another game of the process\n */\nconst slots = new Map<string, number>()\n\n/**\n * A typed key for state of a game's own: `const wave = defineComponent<WaveState>('td.waves', { default: () => ... })`.\n * Give it a prefix of the game's or the mod's: the engine's own are `core.`. A game lists its own\n * (`GameModule.components`), and its world finds them by id in its registry: another game of the process may have one\n * of the same id, and a module loaded again (as a dev server does) defines it again.\n *\n * With `snapshot` and `same` the component shapes what players are sent of it and how a change is found; with `index`\n * it is filed for systems to go through; with `field` the map editor sets it\n *\n * @beta\n */\nexport function defineComponent<T, S = T>(id: string, options: ComponentOptions<T, S> = {}): Component<T, S> {\n\t// every field there, in one order, whatever the options say: every component one shape, so that reading its id (as\n\t// `entity.get` does, many times a tick, with every kind of component) is one load and not a search through shapes\n\tlet slot = slots.get(id)\n\tif (slot === undefined) slots.set(id, (slot = slots.size))\n\tconst component: Component<T, S> = {\n\t\tid,\n\t\tslot,\n\t\tdefault: undefined,\n\t\treplicate: undefined,\n\t\tportable: undefined,\n\t\tsnapshot: undefined,\n\t\tsame: undefined,\n\t\tindex: undefined,\n\t\tfield: undefined,\n\t\tsave: undefined,\n\t\tload: undefined,\n\t\trefs: undefined,\n\t\tpassable: undefined,\n\t\t...options\n\t}\n\treturn component\n}\n\n/**\n * What a snapshot carries of a component, typed: `snapshotOf(entity.state, shopStock)` on a screen, or in a computer\n * player's view. `undefined` when the player was not told it\n *\n * @beta\n */\nexport function snapshotOf<T, S>(state: { components?: Record<string, unknown> }, component: Component<T, S>): S | undefined {\n\treturn state.components?.[component.id] as S | undefined\n}\n\n/**\n * State kept by component, for the world or a player. Asking for one that is not there yet makes it from the\n * component's default\n */\nexport class StateStore {\n\t/** By component id. Plain data, for a save */\n\treadonly values: Record<string, unknown> = {}\n\n\tget<T>(key: Component<T, unknown>): T {\n\t\tif (!(key.id in this.values)) {\n\t\t\tif (!key.default) throw new Error(`State \"${key.id}\" has no default: give it one in defineComponent, or set it first`)\n\t\t\tthis.values[key.id] = key.default()\n\t\t}\n\t\treturn this.values[key.id] as T\n\t}\n\n\tset<T>(key: Component<T, unknown>, value: T): void {\n\t\tthis.values[key.id] = value\n\t}\n\n\thas(key: Component<unknown, unknown>): boolean {\n\t\treturn key.id in this.values\n\t}\n}\n","/**\n * What a unit carries (`UnitTypeDef.inventory`): its slots of items, the component the stats, the abilities and the\n * shops read. Here alone, of nothing but components, so that what reads it (the stats, on every hit) loads nothing of\n * the shops (`items.ts`)\n */\nimport { defineComponent } from './components'\nimport type { Entity, ItemInstance } from './entity'\nimport type { CarriedItem, InventoryInfo } from './session/protocol'\n\n/**\n * The slots of what a unit carries (`UnitTypeDef.inventory`), null for an empty one: set as it is spawned (and as its\n * type changes), for a type with slots. Sent to everyone who sees it as `InventoryInfo`: the items it carries, and to\n * its owner and their allies the slots, for commands\n *\n * @beta\n */\nexport const inventorySlots = defineComponent<(ItemInstance | null)[], InventoryInfo>('core.inventory', {\n\trefs: (slots) => ({ items: (slots as (ItemInstance | null)[]).flatMap((carried) => (carried ? [carried.item] : [])) }),\n\t// its slots, empty, for a type that carries\n\tonSpawn: (entity) => {\n\t\tif (entity.def.inventory)\n\t\t\tentity.set(\n\t\t\t\tinventorySlots,\n\t\t\t\tArray.from({ length: entity.def.inventory }, () => null)\n\t\t\t)\n\t},\n\treplicate: 'everyone',\n\tsnapshot(slots, _entity, { ally }) {\n\t\tconst items: string[] = []\n\t\tfor (const slot of slots) if (slot) items.push(slot.item)\n\t\tif (!ally) return items.length ? { items } : undefined\n\t\treturn {\n\t\t\titems,\n\t\t\tslots: slots.map(\n\t\t\t\t(slot): CarriedItem | null =>\n\t\t\t\t\tslot && {\n\t\t\t\t\t\tid: slot.id,\n\t\t\t\t\t\titem: slot.item,\n\t\t\t\t\t\tcharges: slot.charges,\n\t\t\t\t\t\tcooldown: slot.state?.cooldown ?? 0,\n\t\t\t\t\t\t...(slot.state?.charges !== undefined && { uses: slot.state.charges })\n\t\t\t\t\t}\n\t\t\t)\n\t\t}\n\t},\n\tsame: (a, b) =>\n\t\ta.items.length === b.items.length &&\n\t\ta.items.every((item, i) => item === b.items[i]) &&\n\t\t(a.slots === undefined) === (b.slots === undefined) &&\n\t\t(!a.slots ||\n\t\t\t(a.slots.length === b.slots!.length &&\n\t\t\t\ta.slots.every((slot, i) => {\n\t\t\t\t\tconst other = b.slots![i]\n\t\t\t\t\treturn (\n\t\t\t\t\t\tslot === other ||\n\t\t\t\t\t\t(!!slot &&\n\t\t\t\t\t\t\t!!other &&\n\t\t\t\t\t\t\tslot.id === other.id &&\n\t\t\t\t\t\t\tslot.item === other.item &&\n\t\t\t\t\t\t\tslot.charges === other.charges &&\n\t\t\t\t\t\t\tslot.cooldown === other.cooldown &&\n\t\t\t\t\t\t\tslot.uses === other.uses)\n\t\t\t\t\t)\n\t\t\t\t})))\n})\n\n/**\n * The slots of what a unit carries, null for an empty one: none for a type that carries nothing (`inventorySlots`)\n *\n * @beta\n */\nexport const slotsOf = (entity: Entity): (ItemInstance | null)[] | undefined => entity.get(inventorySlots)\n\n/** @beta */\nexport const freeSlot = (entity: Entity) => slotsOf(entity)?.findIndex((slot) => slot === null) ?? -1\n","import type { AbilityAiView } from './ai/micro'\nimport type { AiHints } from './ai/roles'\nimport type { AbilityTextContext, AbilityValueDef, TextSegment } from './abilities/text'\nimport type { EntityState } from './session/protocol'\n/**\n * Static game data. Everything a game module (melee, custom map, mod) defines about\n * its units lives in plain objects like these, the engine never hardcodes a unit.\n */\n\nimport type { GameRules } from './rules'\nimport type { AbilityState, BuffInstance, Entity } from './entity'\nimport type { Vec2 } from './math'\nimport type { World } from './world'\n\n/**\n * A value that can grow with the level of an ability: one number, or one per level\n *\n * @beta\n */\nexport type Scaled = number | number[]\n\n/**\n * The value at a level. Levels past the end of the list get the last one\n *\n * @beta\n */\nexport function at(value: Scaled | undefined, level: number, fallback = 0): number {\n\tif (value === undefined) return fallback\n\tif (typeof value === 'number') return value\n\treturn value[Math.min(Math.max(level, 1), value.length) - 1] ?? fallback\n}\n\n/**\n * The stats the engine reads: what a unit has of health, mana and their regeneration, how it moves, sees and attacks,\n * and its armor and magic resist (the two kinds of damage there are besides true). Levels, items, buffs and research\n * change them. A game adds stats of its own with `GameModule.stats`, a pack its own (`GamePack.stats`: the MOBA\n * stats of `withMobaStats`).\n *\n * @beta\n */\nexport interface CoreStats {\n\t// ---- offense\n\t/** What a basic attack deals, before the armor of the target */\n\tattackDamage: number\n\t/** Attacks per second */\n\tattackSpeed: number\n\t/** Measured between the edges of attacker and target */\n\tattackRange: number\n\n\t// ---- defense\n\thealth: number\n\t/** Against physical damage: 100 of it halve what arrives */\n\tarmor: number\n\t/** The same against magic damage */\n\tmagicResist: number\n\n\t// ---- sustain and resources\n\t/** Per second */\n\thealthRegen: number\n\tmana: number\n\t/** Per second */\n\tmanaRegen: number\n\n\t// ---- utility\n\t/** Units per second. Who has none cannot move */\n\tmoveSpeed: number\n\t/** How far it sees. At night the unit type says how far that is */\n\tsight: number\n}\n\n/** @internal */\nexport type CoreStatKey = keyof CoreStats\n\n/**\n * All of a unit's stats: the engine's, and the game's own by their ids\n *\n * @beta\n */\nexport type Stats = CoreStats & Record<string, number>\n\n/**\n * A stat: one of the engine's (`CoreStatKey`), or one a game defined. Checked when the game is built\n *\n * @beta\n */\nexport type StatKey = string\n\n/**\n * A stat of a game's own, next to the engine's\n *\n * @beta\n */\nexport interface StatDef {\n\tid: string\n\tname: string\n\t/** Shown when the pointer is over it */\n\tdescription?: string\n\t/** What every unit has of it unless its type says. 0 when left out */\n\tdefault?: number\n\t/** It never goes below or above these, whatever changes it */\n\tmin?: number\n\tmax?: number\n\t/** How it is shown: a whole number, a decimal, or a part of one as a percentage. A whole number when left out */\n\tformat?: 'number' | 'decimal' | 'percent'\n}\n\n/** @internal */\nexport const CORE_STAT_KEYS: CoreStatKey[] = [\n\t'attackDamage',\n\t'attackSpeed',\n\t'attackRange',\n\t'health',\n\t'armor',\n\t'magicResist',\n\t'healthRegen',\n\t'mana',\n\t'manaRegen',\n\t'moveSpeed',\n\t'sight'\n]\n\n/** @beta */\nexport const noStats = (): CoreStats => ({\n\tattackDamage: 0,\n\tattackSpeed: 0,\n\tattackRange: 0,\n\thealth: 0,\n\tarmor: 0,\n\tmagicResist: 0,\n\thealthRegen: 0,\n\tmana: 0,\n\tmanaRegen: 0,\n\tmoveSpeed: 0,\n\tsight: 0\n})\n\n/**\n * How the days go by. Hours run from 0 to 24\n *\n * @beta\n */\nexport interface DayCycle {\n\t/** Seconds a whole day and night take */\n\tlength: number\n\t/** Hour of the day the game starts at */\n\tstart: number\n\t/** Hour the sun comes up */\n\tdawn: number\n\t/** Hour it goes down */\n\tdusk: number\n}\n\n/**\n * Hour of the day after so many seconds of play. Noon in a game without days\n *\n * @beta\n */\nexport function hourOf(day: DayCycle | null, seconds: number): number {\n\tif (!day) return 12\n\treturn (day.start + (seconds / day.length) * 24) % 24\n}\n\n/** @beta */\nexport const isNight = (day: DayCycle | null, hour: number): boolean => !!day && (hour < day.dawn || hour >= day.dusk)\n\n/**\n * Something that changes stats: `stats` is added, `percent` makes them bigger or smaller by a part of what\n * they are with everything added. Parts from different places add up: two times +10% are +20%.\n *\n * @beta\n */\nexport interface StatChange {\n\tstats?: Partial<Stats>\n\tpercent?: Partial<Stats>\n}\n\n/**\n * A change that grows with the level of the ability it comes from\n *\n * @beta\n */\nexport interface ScaledStatChange {\n\tstats?: Partial<Record<StatKey, Scaled>>\n\tpercent?: Partial<Record<StatKey, Scaled>>\n}\n\n/**\n * Physical damage is held off by armor, magic damage by magic resist, true damage by nothing\n *\n * @beta\n */\nexport type DamageType = 'physical' | 'magic' | 'true'\n\n/**\n * What makes a unit a hero: it gains levels, grows with them and learns abilities\n *\n * @beta\n */\nexport interface HeroDef {\n\t/** What every level after the first adds */\n\tgrowth: StatChange\n\t/** Abilities the hero can put points into */\n\tlearns: string[]\n\t/** Abilities it has from the start and does not learn: the two spells every hero brings along. No mana, and nothing shortens their cooldown */\n\tspells?: string[]\n\t/** The level it stops at. 10 when left out */\n\tmaxLevel?: number\n\t/** A buff whose stacks are shown next to its health and mana, as so many points out of as many as it can have */\n\tmeter?: string\n\t/**\n\t * Its primary attribute, in a game with the attributes pack (`withAttributes`): each point of it adds to its attack\n\t * as well. `AttributesOptions.primaryOf` says it in code\n\t */\n\tprimary?: 'strength' | 'agility' | 'intelligence'\n}\n\n/** @beta */\nexport type EntityKind = 'unit' | 'building' | 'resource'\n\n/**\n * Where something is: on the ground, or above it\n *\n * @beta\n */\nexport type Layer = 'ground' | 'air'\n\n/**\n * The stats an attack reads how hard, how fast and how far it hits from (`AttackDef.stats`): the unit's\n * `attackDamage`, `attackSpeed` and `attackRange` for what is left out\n *\n * @beta\n */\nexport interface AttackStats {\n\t/** What a hit deals, before the armour of the target. `attackDamage` when left out */\n\tdamage?: StatKey\n\t/** Hits a second. `attackSpeed` when left out */\n\tspeed?: StatKey\n\t/** How far it reaches, between the edges. `attackRange` when left out */\n\trange?: StatKey\n}\n\n/**\n * One of the ways a unit attacks (`UnitTypeDef.attacks`): what it hits, how its blow lands. How hard, how fast and how\n * far are stats: the unit's `attackDamage`, `attackSpeed` and `attackRange`, or stats of the game's own that the attack\n * names (`stats`: a second weapon's)\n *\n * @beta\n */\nexport interface AttackDef {\n\t/**\n\t * The stats its numbers are, by id: a stat of the game's (`GameModule.stats`) for a weapon whose damage, speed or\n\t * range is not the unit's first's. What changes those stats (research, items, buffs) changes this attack alone\n\t */\n\tstats?: AttackStats\n\t/** Physical when left out */\n\tdamageType?: DamageType\n\t/** Seconds from the start of the swing until damage lands (or the projectile leaves), at the attack speed the unit starts with */\n\tdamagePoint: number\n\t/** Enemies closer than this are attacked automatically */\n\tacquisitionRange: number\n\t/**\n\t * How near is too near, edge to edge: what is closer than this the attack does not hit (a siege weapon's dead zone).\n\t * Another of the unit's attacks takes over there where one reaches (`GameRules.combat.pickAttack`); with none, a unit\n\t * told to attack steps back out of it first, and one left to itself does not pick what is that near. None when left out\n\t */\n\tminRange?: number\n\t/**\n\t * Fires as the unit walks (a horse archer, a tank's turret): told to move, it hits what it passes within the attack's\n\t * range without stopping or turning to it, at the attack's speed. Every other order fights as any attack does\n\t * (it stops to). Not when left out\n\t */\n\tonTheMove?: boolean\n\t/** Set for ranged attacks */\n\tprojectileSpeed?: number\n\t/**\n\t * What this attack can hit: kinds of things, and where they are. Everything on the ground when left out.\n\t * What flies is only hit by attacks that name `air`, and an attack that names `air` alone does not hit the ground\n\t */\n\ttargets?: (EntityKind | Layer)[]\n\t/**\n\t * Radius around the point of impact in which everyone is hit, friends too: in full in the inner half, by half further out.\n\t * Shots of such an attack land where they were aimed, they do not follow their target\n\t */\n\tsplash?: number\n\t/** Can be told to attack a spot on the ground */\n\tground?: boolean\n\t/** Brings down what is `fellable` in the area it hits */\n\tfells?: boolean\n\t/**\n\t * How what this attack kills dies, for the screen (`'shot'`, `'crushed'`, `'burnt'`): the death's `how`, which the\n\t * view shows its way (`UnitLook.death`). A word, or one decided for each blow. The `death` hook has the last say\n\t */\n\thow?:\n\t\t| string\n\t\t| ((hit: { attacker: Entity; target?: Entity; damage: number; type: DamageType; crit: boolean; tags?: readonly string[] }) => string | undefined)\n\t/**\n\t * The attack's type against the target's armour type, by the game's damage table (`GameRules.combat.damageTable`): `pierce`,\n\t * `siege`… Left out, the attack is multiplied by nothing\n\t */\n\tattackType?: string\n}\n\n/**\n * The id of a resource, as its game module defines it (`ResourceDef`)\n *\n * @beta\n */\nexport type ResourceKind = string\n\n/**\n * Something players have amounts of and pay with, like gold, lumber or crystals. A game module lists its own\n *\n * @beta\n */\nexport interface ResourceDef {\n\tid: ResourceKind\n\tname: string\n\t/** What every player starts a game with. Nothing when left out */\n\tstart?: number\n\t/** What workers gather of it is cut by the upkeep of the army, see `UpkeepTier` */\n\tupkeep?: boolean\n}\n\n/**\n * What something costs: an amount of each resource it takes, by resource id. What is left out costs nothing\n *\n * @beta\n */\nexport type Cost = Record<ResourceKind, number>\n\n/**\n * How a type goes up once it is put down (`UnitTypeDef.construction`): `builder`, `self` (also `buildsItself`) or\n * `instant`\n *\n * @internal\n */\nexport function constructionOf(def: Pick<UnitTypeDef, 'construction' | 'buildsItself'>): 'builder' | 'self' | 'instant' {\n\treturn def.construction ?? (def.buildsItself ? 'self' : 'builder')\n}\n\n/** @beta */\nexport interface UnitTypeDef {\n\tid: string\n\tname: string\n\t/**\n\t * The definition this one is a copy of, made from the data (`copyOf` in a `data.json`, the editor's Copy as new):\n\t * what it is drawn, heard and pictured as where the game gives it no look of its own\n\t */\n\tbasedOn?: string\n\tkind: EntityKind\n\t/** Collision radius */\n\tradius: number\n\t/** Size in grid cells. Required for buildings and resources */\n\tfootprint?: { w: number; d: number }\n\t/** What it starts with. What is left out is 0, a critical strike is worth 175% */\n\tstats: Partial<Stats> & { health: number }\n\t/** Mana it comes into the world with. All of it when left out */\n\tinitialMana?: number\n\t/** Vision radius by day */\n\tsight: number\n\t/** Vision radius at night. A part of the one by day when left out */\n\tsightNight?: number\n\t/** Flies: over cliffs, trees and buildings, out of reach of whatever cannot hit the air */\n\tflying?: boolean\n\t/**\n\t * Goes on deep water and nowhere else: a boat. Sent onto land, it goes to the water nearest where it was sent. On\n\t * the ground, as far as what can hit it goes\n\t */\n\tnaval?: boolean\n\t/**\n\t * A waygate, in a game with the portals pack (`withPortals`): a unit told to it walks in and is at once where it\n\t * leads (its `waygate` field, a point of the map; `setWaygate` in code)\n\t */\n\twaygate?: boolean\n\t/**\n\t * Rocks, a barricade, a gate to break down, in a game with the destructibles pack (`withDestructibles`): it stands in\n\t * the way as any building does until it is brought down, and any unit whose attack reaches it attacks it when told\n\t * to, never of its own accord\n\t */\n\tdestructible?: boolean\n\t/**\n\t * Carries others: a boat, a wagon. Units of its side get in by being told to (right-clicking it), are out of the\n\t * world while in, and get out on the land nearest it (the `unload` order). It takes `capacity` of them, of the\n\t * kinds `takes` says (every unit that walks when left out). What it carries dies with it\n\t */\n\t/**\n\t * Carries others: a boat, or a building they go into (a garrison). `takes` says who may get in; `armed`, for a\n\t * building with an attack, is the attack damage each one inside adds, and it attacks only while someone is inside,\n\t * as an orc burrow does. What a building holds comes out when it falls; what a boat holds goes down with it\n\t */\n\ttransport?: {\n\t\tcapacity: number\n\t\ttakes?: (def: UnitTypeDef) => boolean\n\t\t/** Attack damage each one inside adds; or in code, all of what they add, by who is inside (none for nobody) */\n\t\tarmed?: number | ((world: World, building: Entity, inside: Entity[]) => number)\n\t}\n\t/** Radians per second */\n\tturnRate?: number\n\t/**\n\t * How it attacks, as the classic RTS two weapons: against each target the first that reaches it (its `targets`), or\n\t * the one the game picks (`GameRules.combat.pickAttack`). It swings one at a time: a hit's cooldown is that attack's,\n\t * whichever swings next. None for what does not attack\n\t */\n\tattacks?: AttackDef[]\n\thero?: HeroDef\n\t/** How dangerous it is, for creeps. Shown to the player, and added up per camp */\n\tlevel?: number\n\t/** Gold for whoever kills it, rolled between the two */\n\tbounty?: [min: number, max: number]\n\t/**\n\t * Whether it leaves a corpse when it dies, for spells to use (see `raiseDead`). Units do, unless this says no:\n\t * machines, spirits. Decided for each death in code: false for none, true or seconds for one (how long it lies)\n\t */\n\tcorpse?: boolean | ((world: World, entity: Entity) => boolean | number)\n\t/**\n\t * Immune to spells: abilities do not touch it, of friends or enemies, unless they say they get through\n\t * (`piercesImmunity`). Decided in code whenever it is asked: while it stands on holy ground. The player's screen only\n\t * knows the plain `true` of it, to grey out a target; the simulation goes by the code\n\t */\n\tspellImmune?: boolean | ((world: World, entity: Entity) => boolean)\n\t/** Experience heroes get for killing it. Follows from its cost when left out */\n\txp?: number\n\t/** Building types the player has to have before this can be built or trained */\n\trequires?: string[]\n\t/**\n\t * The race it is of (`GameModule.races`): only its players may build or train it. Everyone's when left out: creeps,\n\t * what is shared. What a player may have is the game's to change (the `available` hook)\n\t */\n\trace?: string\n\t/** Building types this one counts as, for requirements. A keep is a town hall too */\n\tprovides?: string[]\n\t/**\n\t * Type this building can be upgraded into, where it stands; or the types, for one that may become one of several (a\n\t * keep that turns into a castle or a citadel, `upgradesOf`). The first is what an upgrade is into where none is named\n\t */\n\tupgradesTo?: string | string[]\n\t/** Slots for items. Heroes have six */\n\tinventory?: number\n\t/** Items this building sells */\n\tsells?: string[]\n\t/**\n\t * Units it hires out to whoever has one of theirs there, by type: a tavern's heroes, a dock's boats. Their cost,\n\t * and a hero only once (see `hire`). Neutral, it hires to everyone\n\t */\n\thires?: string[]\n\t/**\n\t * What it may leave behind when it dies, each with its chance from 0 to 1. Or code: the items it leaves, decided as\n\t * it dies (one random level-3 item; more for a stronger killer)\n\t */\n\tdrops?: { item: string; chance: number }[] | ((world: World, entity: Entity, killer?: Entity) => string[])\n\t/** Brings fallen heroes back */\n\trevives?: boolean\n\t/** Ids of the abilities the unit has */\n\tabilities?: string[]\n\tcost?: Cost\n\t/** Supply (food) it takes up for as long as it lives, and while it is being trained */\n\tsupply?: number\n\t/** What it takes of the game's other pools of supply, by name (`GameRules.supply.pools`): `{ command: 1 }` */\n\tsupplies?: Record<string, number>\n\t/** Seconds to build or train */\n\tbuildTime?: number\n\tsupplyProvided?: number\n\t/** What it provides of the game's other pools of supply, by name (`GameRules.supply.pools`), once it stands finished */\n\tsuppliesProvided?: Record<string, number>\n\tharvester?: {\n\t\tcapacity: number\n\t\tgatherTime: number\n\t\t/**\n\t\t * The kinds of resource it gathers: all of them when left out. The undead's acolytes gold and nothing else, ghouls\n\t\t * lumber. The `canHarvest` hook has the last word (`canHarvest`)\n\t\t */\n\t\tkinds?: ResourceKind[]\n\t}\n\t/** Building types this unit can construct */\n\tbuilds?: string[]\n\t/** Unit types this building can train */\n\ttrains?: string[]\n\t/** Upgrades that can be researched here */\n\tresearches?: string[]\n\t/** Accepts harvested resources: all of them, or only the ones listed */\n\tdropOff?: boolean | ResourceKind[]\n\t/**\n\t * Goes up on a resource of this kind, over it, of the same footprint: the undead's cursed gold mine. The resource is\n\t * its owner's alone from then on (`canHarvest`); one that takes what is gathered there (`dropOff`) has its owner's\n\t * workers gather at it from around it, handing in where they stand, as many at once as `gatherers` says. It goes\n\t * down with the resource, which stands again where it is destroyed\n\t */\n\tbuiltOn?: ResourceKind\n\t/** Workers that gather at once at it, when it stands on a resource (`builtOn`): 5 when left out */\n\tgatherers?: number\n\t/**\n\t * Goes up on its own once it is put down, as the undead summon theirs: the builder is free at once, and nobody\n\t * helps (`GameRules.production.buildRate` of one builder, all the way). The same as `construction: 'self'`\n\t */\n\tbuildsItself?: boolean\n\t/**\n\t * How it goes up once it is put down: with builders at it (`builder`, the more the faster, as `buildRate` says), on\n\t * its own with the builder free at once (`self`, the undead's), or whole at once (`instant`: a wall piece, a\n\t * ward). `builder` when left out (`self` with `buildsItself`)\n\t *\n\t * @beta\n\t */\n\tconstruction?: 'builder' | 'self' | 'instant'\n\t/**\n\t * How fast it goes up with so many builders at it, 1 being one builder's: the game's rule (`GameRules.production.buildRate`) for\n\t * every type when left out\n\t *\n\t * @beta\n\t */\n\tbuildRate?: (builders: number, world: World, structure: Entity) => number\n\tresource?: {\n\t\tkind: ResourceKind\n\t\tamount: number\n\t\t/** Workers that fit inside at once, for resources that are entered */\n\t\tslots: number\n\t\t/** Workers go inside to gather, like into a gold mine, instead of working on it from next to it */\n\t\tentered?: boolean\n\t\t/** Seconds a load takes, when that is not what the worker usually needs */\n\t\tgatherTime?: number\n\t}\n\t/** Key used in the command card when building or training this type */\n\thotkey?: string\n\t/** Higher values are picked first when acquiring targets */\n\tthreat?: number\n\tinvulnerable?: boolean\n\t/** Takes damage like anything else but never dies of it: it is left with a little health, like something to practise on */\n\tundying?: boolean\n\t/** Seconds after it was last hurt that it is whole again, all at once */\n\trecovers?: number\n\t/** Nobody picks a fight with it on their own: it is only attacked when someone is told to */\n\tignored?: boolean\n\t/** Destroyed by attacks that fell, like a tree by a catapult, whatever else it withstands */\n\tfellable?: boolean\n\t/**\n\t * A piece of wall (`withWalls`): it joins with the pieces of its family beside it, and its shape (`single`, `end`,\n\t * `straight`, `corner`, `tee`, `cross`) is its look. A gate (`gate`) joins as a piece does, turned along its line,\n\t * and its owner opens and shuts it for everyone (`wallGateCommand`): its look `open` or `shut`. Pieces join by their\n\t * footprints, so a gate wider than a cell sits in a line of pieces of one: one of a cell lets nobody through, the\n\t * ground about a wall being kept off by the radius of what walks (a gatehouse of 3 by 3 lets through what is 1 wide) @beta\n\t */\n\twall?: { family: string; gate?: boolean }\n\t/** Seconds it lasts before it is gone by itself, like a ward */\n\tlifetime?: number\n\t/** Enemies cannot see it, `after` seconds after it came into the world, unless something reveals it to them */\n\tinvisible?: { after?: number }\n\t/** Goes down after this many attacks and spells, whatever they deal: its health counts hits */\n\thits?: number\n\t/**\n\t * What the computer player takes it for (`AiHints`): its roles (`worker`, `hall`, `soldier`...), the game's words\n\t * about it, what it answers. Declared where what the kit infers from the rest of the definition is wrong or cannot\n\t * be known; inferred otherwise (`inferRoles` in `@v12-engine/engine/ai`)\n\t */\n\tai?: AiHints\n\t/** Its armour type, the column of the game's damage table (`GameRules.combat.damageTable`): `light`, `heavy`, `fortified`… */\n\tarmourType?: string\n}\n\n/**\n * How an ability is aimed\n *\n * @beta\n */\nexport type AbilityTarget = 'none' | 'unit' | 'point' | 'direction' | 'passive'\n\n/**\n * What every effect may say, whatever its type: who of what it reaches it applies to (`effectTargets`)\n *\n * @beta\n */\nexport interface EffectCommon {\n\t/** Only hits what carries this buff */\n\tifBuff?: string\n\t/** Only hits heroes */\n\tonly?: 'heroes'\n\t/** Only hits these kinds of things. Everything but resources when left out */\n\tkinds?: EntityKind[]\n\t/** Where what it hits has to be: on the ground, in the air. Both when left out */\n\tlayers?: Layer[]\n\t/** Makes the effect hit everything around the point of impact. Required for auras, and the size of a missile */\n\tradius?: Scaled\n\t/** Who an effect with a radius applies to. Follows from the kind of effect when left out */\n\taffects?: 'enemies' | 'allies' | 'all'\n\t/** Applies to the caster, wherever the ability was aimed */\n\ton?: 'caster'\n}\n\n/**\n * The fields the engine's effects read, by name: each type of effect has those of them it reads (`EffectTypes`, a\n * `Pick` of these), and a game's own type picks of them or says its own\n *\n * @beta\n */\nexport interface EffectFields {\n\t/** For `teleport`: where to, however far: the caster's side's home (`homeOf`), where it was aimed, or by its target */\n\tto?: 'home' | 'point' | 'target'\n\tamount?: Scaled\n\t/** Id of the buff to put on the targets */\n\tbuff?: string\n\t/** Unit type, for effects that bring one into the world */\n\tunit?: string\n\t/** For `onHit`: only while the attacker carries this buff */\n\twhileBuff?: string\n\t/** For `charged`: what happens when the ability is not charged */\n\totherwise?: EffectDef[]\n\t/** For missiles: buildings and trees in its way stop it, without anything happening to them */\n\tblocked?: boolean\n\t/** For `onKill`: only when it was an attack of the carrier that killed */\n\tattack?: boolean\n\t/** For `refresh`: the ability that is ready again, when it is not the one the effect belongs to */\n\tability?: string\n\t/** For `dash`: how high the caster rises on the way, which makes it a leap. For whoever draws it */\n\tleap?: number\n\t/**\n\t * For a leap: how much higher than where it takes off the ground on its way may stand. What stands higher\n\t * is a wall to it: it comes down in front of it. Over anything when left out\n\t */\n\tclimb?: number\n\t/** Seconds the buff lasts, when that is different from its usual duration */\n\tduration?: Scaled\n\t/**\n\t * What the stats of the caster add to the amount: `{ abilityPower: 0.6 }` adds 60% of its ability power.\n\t * `level` is for every level of the hero past the first\n\t */\n\tscaling?: Scaling\n\t/** For damage. Magic when left out */\n\tdamageType?: DamageType\n\t/** For damage: how what it kills dies, for the screen, over the ability's own `how` */\n\thow?: string\n\t/** For missiles: seconds they take shape where they were cast before they set off. The caster is free to go */\n\tdelay?: Scaled\n\t/** For missiles: how fast they travel, in units per second, and how far */\n\tspeed?: number\n\tdistance?: Scaled\n\t/** For missiles: how many are sent, spread over an angle in radians. What one of them hit the others pass by */\n\tcount?: Scaled\n\tspread?: number\n\t/** For missiles: flies after the unit the ability was cast on, and only hits that one */\n\thoming?: boolean\n\t/** For missiles: flies to the spot the ability was aimed at and stops there, `distance` away at the most */\n\ttoPoint?: boolean\n\t/** For missiles: how far the team of the caster sees around it */\n\tsight?: number\n\t/**\n\t * What happens to what is hit. For missiles: everything they pass through. For `onHit`: the target of an attack.\n\t * For `dash`: what is around where it ends. For `after`: what is there when the time is up. For `zone`: what is inside, over and over\n\t */\n\teffects?: EffectDef[]\n\t/** For missiles that were not stopped, and for zones: what happens where and when they end */\n\tonEnd?: EffectDef[]\n\t/**\n\t * For `after`: the name its arrival goes by for whoever draws it and plays its sound, where one ability sets off\n\t * several that do not look alike: the last of a barrage. The ability's own when left out\n\t */\n\timpact?: string\n\t/** For missiles: goes on after it hit something. False for the ones that are used up by the first thing in their way */\n\tpierce?: boolean\n\t/**\n\t * For missiles: thrown, not shot. It goes `height` up in the middle of its way and comes down at its end, `time`\n\t * seconds after it set off however far that is (`speed` otherwise). It flies over everything, and what is within\n\t * its `radius` where it comes down is what it hits\n\t */\n\tarc?: { height: number; time?: number }\n\t/**\n\t * For missiles: where it would be done (it reached its target, was used up by what it hit, came down, or came to\n\t * the end of its way) it springs on to the nearest thing it may hit within `range` that it has not hit yet, and\n\t * flies after that one, `count` times. Every spring takes `falloff` of the amounts off what it does (0.25: a\n\t * quarter less each time). Its `onEnd` is where it is done for good\n\t */\n\tbounce?: { count: Scaled; range: number; falloff?: number }\n\t/** For `buff`: adds one to how many of it the target carries instead of renewing it, up to what the buff allows */\n\tstack?: boolean\n\t/** For `exchange`: the resource the caster's owner trades away, by id */\n\tsell?: string\n\t/** For `exchange`: the resource the caster's owner trades for, by id */\n\tbuy?: string\n\t/** For `exchange`: how much of `buy` comes for each one of `sell` (0.5: 100 lumber for 50 gold) */\n\trate?: number\n}\n\n/**\n * The types of effect there are, each with the fields it reads: the engine's, and a game's own, added by declaration\n * merging as it defines them (`declare module '@v12-engine/engine' { interface EffectTypes { arrowStun: { ... } } }`,\n * with `defineEffect`)\n *\n * @beta\n */\nexport interface EffectTypes {\n\t/** Hurts what it reaches: `amount`, with what of the caster's stats adds to it (`scaling`), of a type (magic when left out) */\n\tdamage: Pick<EffectFields, 'amount' | 'scaling' | 'damageType' | 'how'>\n\t/** Heals what it reaches, more for the caster's heal and shield power */\n\theal: Pick<EffectFields, 'amount' | 'scaling'>\n\t/** Gives mana to what it reaches */\n\tmana: Pick<EffectFields, 'amount' | 'scaling'>\n\t/** Puts a buff on what it reaches: for its own time or `duration`, one more of it with `stack` */\n\tbuff: { buff: string } & Pick<EffectFields, 'duration' | 'stack'>\n\t/** Sends a missile: how fast, how far, how many, and what it does to what it passes through and where it ends */\n\tmissile: Pick<\n\t\tEffectFields,\n\t\t| 'speed'\n\t\t| 'distance'\n\t\t| 'count'\n\t\t| 'spread'\n\t\t| 'homing'\n\t\t| 'toPoint'\n\t\t| 'delay'\n\t\t| 'sight'\n\t\t| 'blocked'\n\t\t| 'pierce'\n\t\t| 'arc'\n\t\t| 'bounce'\n\t\t| 'effects'\n\t\t| 'onEnd'\n\t>\n\t/** A passive's buff on what is around the carrier, kept up by the ability system */\n\taura: { buff: string }\n\t/** Brings a unit of the caster's into the world where it landed, for `duration` seconds or for good */\n\tspawn: { unit: string } & Pick<EffectFields, 'duration'>\n\t/** Puts a buff on the caster for as long as it likes, or takes it off */\n\ttoggle: { buff: string }\n\t/** The caster's team sees the spot for a while */\n\treveal: Pick<EffectFields, 'duration'>\n\t/** A passive's: `effects` happen to the target of every attack of the carrier, while it carries `whileBuff` */\n\tonHit: Pick<EffectFields, 'whileBuff' | 'effects'>\n\t/** The caster is ready to strike again at once */\n\tresetAttack: object\n\t/** The caster is elsewhere at once, `distance` away at the most */\n\tblink: Pick<EffectFields, 'distance'>\n\t/** The caster is elsewhere at once, however far (`to`) */\n\tteleport: Pick<EffectFields, 'to'>\n\t/** The caster rushes to the spot (a leap with `leap`), and `effects` happen around where it ends */\n\tdash: Pick<EffectFields, 'distance' | 'leap' | 'climb' | 'speed' | 'effects' | 'buff'>\n\t/** Throws what it reaches `distance` away from the caster */\n\tknockback: Pick<EffectFields, 'distance' | 'speed' | 'leap'>\n\t/** An ability of the caster is ready again: `ability`, or the one the effect belongs to */\n\trefresh: Pick<EffectFields, 'ability'>\n\t/** A passive's: `effects` happen around whoever the carrier kills (by an attack, with `attack`) */\n\tonKill: Pick<EffectFields, 'attack' | 'effects'>\n\t/** A passive's: `effects` happen to the carrier whenever it casts */\n\tonCast: Pick<EffectFields, 'effects'>\n\t/** `effects` when the ability went off charged, `otherwise` when it did not */\n\tcharged: Pick<EffectFields, 'effects' | 'otherwise'>\n\t/** `effects` happen at the spot, `delay` seconds from now */\n\tafter: Pick<EffectFields, 'delay' | 'effects' | 'impact'>\n\t/** For `duration` seconds `effects` happen to what is at the spot, over and over, and `onEnd` at the end */\n\tzone: Pick<EffectFields, 'duration' | 'effects' | 'onEnd'>\n\t/** Finds what is invisible around the spot: the caster's team sees it for `duration` seconds */\n\tdetect: Pick<EffectFields, 'duration'>\n\t/** Raises `count` of the corpses around the spot as units of `unit`, for `duration` seconds or for good */\n\traiseDead: { unit: string } & Pick<EffectFields, 'duration' | 'count'>\n\t/**\n\t * Makes `count` copies of the target, for `duration` seconds: they deal `dealt` of its damage (a third when left out)\n\t * and take `taken` times what they are dealt (twice when left out)\n\t */\n\tillusion: Pick<EffectFields, 'count' | 'duration'> & { dealt?: number; taken?: number }\n\t/** Takes the buffs off what it reaches, and hurts what is summoned by `amount` */\n\tdispel: Pick<EffectFields, 'amount'>\n\t/**\n\t * Trades `amount` of a resource of the caster's owner (`sell`) for another (`buy`), `rate` of it for each one sold:\n\t * a marketplace's (`presetMarket`, `exchange` in code). Nothing of it with less than `amount` to sell\n\t */\n\texchange: { sell: string; buy: string; rate: number; amount: Scaled }\n\t/**\n\t * A tome's, in a game with the tomes pack (`withTomes`): what it reaches gains `gain` for good (a point of strength),\n\t * a hero `xp` experience and `levels` levels\n\t */\n\ttome: { gain?: StatChange; xp?: number; levels?: number }\n\t/**\n\t * Mana burn, in a game with its pack (`withManaBurn`): takes `amount` of the mana of what it reaches, and hurts it by\n\t * as much as it took, times `ratio` (1 when left out), magic damage unless `damageType` says\n\t */\n\tmanaBurn: Pick<EffectFields, 'amount' | 'scaling' | 'damageType'> & { ratio?: number }\n\t/**\n\t * A town portal, in a game with the portals pack (`withPortals`): the caster and as many as `count` (12 when left out)\n\t * of its own units within `radius` (7) of it are at once at its side's home nearest where it was aimed (`homeOf`)\n\t */\n\ttownPortal: Pick<EffectFields, 'count'>\n}\n\n/**\n * One thing an ability does: its `type`, which picks the handler and says which fields it has (`EffectTypes`)\n *\n * @beta\n */\nexport type EffectDef = { [K in keyof EffectTypes]: { type: K } & EffectCommon & EffectTypes[K] }[keyof EffectTypes]\n\n/**\n * An effect seen as any type may be, every field of the engine's by its name: for what reads effects of every type\n * alike (an ability's tooltip numbers, the rules' check of what they name). A handler reads its own type's\n * (`EffectOf`)\n *\n * @beta\n */\nexport type AnyEffect = { type: keyof EffectTypes } & EffectCommon & Partial<EffectFields>\n\n/**\n * An effect as any type may be (`AnyEffect`), its fields by name\n *\n * @beta\n */\nexport const anyEffect = (effect: EffectDef): AnyEffect => effect as AnyEffect\n\n/**\n * The effects inside an effect, whatever its type: what it does to what it hits (`effects`), when it is not charged\n * (`otherwise`), and at its end (`onEnd`)\n *\n * @internal\n */\nexport function innerEffects(effect: EffectDef): EffectDef[] {\n\tconst { effects, otherwise, onEnd } = anyEffect(effect)\n\treturn [...(effects ?? []), ...(otherwise ?? []), ...(onEnd ?? [])]\n}\n\n/**\n * An effect of one type\n *\n * @beta\n */\nexport type EffectOf<K extends keyof EffectTypes> = { type: K } & EffectCommon & EffectTypes[K]\n\n/**\n * The ground an ability covers: what the player aims with, and what is shown when it goes off\n *\n * @beta\n */\nexport type AimShape =\n\t| { shape: 'circle'; radius: number }\n\t| { shape: 'line'; length: number; width: number }\n\t/** A fan from the caster: `angle` is how wide it opens, in radians */\n\t| { shape: 'cone'; length: number; angle: number }\n\n/** @beta */\nexport interface AbilityDef {\n\tid: string\n\tname: string\n\t/**\n\t * How what its damage kills dies, for the screen (`'burnt'`, `'frozen'`, `'blasted'`): the death's `how`, which the\n\t * view shows its way. A word, or one decided for each blow: by its level, its caster, what it hit. An effect's own\n\t * (`EffectDef.how`) goes over it; the `death` hook has the last say\n\t */\n\thow?: string | ((hit: { caster: Entity; target: Entity; level: number; amount: number }) => string | undefined)\n\t/**\n\t * The definition this one is a copy of, made from the data (`copyOf` in a `data.json`, the editor's Copy as new):\n\t * what it is drawn, heard and pictured as where the game gives it no look of its own\n\t */\n\tbasedOn?: string\n\t/**\n\t * What it does, in words: a template with values in braces, worked out for the caster as it is now (\"Deals {damage}\n\t * magic damage\" shows \"Deals 80 (50 + 60% ability power) magic damage\"). The values are its own (`values`), or found\n\t * in its effects: `damage`, `heal`, `shield`, `amount`, `duration`, `radius`, `range`, `cooldown`, `charges`, `refill`,\n\t * `mana`, `count`, `distance` (see `abilityValues`)\n\t */\n\tdescription?: string\n\t/** Values of its own to put in its description, by name: an amount and what of the caster scales it, or worked out in code */\n\tvalues?: Record<string, AbilityValueDef>\n\t/** What it does, said in code instead of `description`: words with `{values}` in them, or words and values already put together */\n\tdescribe?: (context: AbilityTextContext) => string | TextSegment[]\n\thotkey?: string\n\t/**\n\t * none: happens at once. unit, point: needs a target, and the caster walks into range of it.\n\t * direction: goes off from where the caster stands, towards where it was aimed. passive: always on, cannot be cast\n\t */\n\ttarget: AbilityTarget\n\t/** What may be targeted, for abilities cast on a unit */\n\ttargets?: { allies?: boolean; enemies?: boolean; self?: boolean; kinds?: EntityKind[]; layers?: Layer[]; heroes?: boolean }\n\tmanaCost?: Scaled\n\t/** Health it costs, as a part of all the caster can have. It cannot be cast with less than that left */\n\thealthCost?: Scaled\n\t/** Seconds before it can be used again */\n\tcooldown?: Scaled\n\t/**\n\t * Uses it holds, for one used so many times before it waits: `count` of them at the most, one more back every\n\t * `refill` seconds while it holds fewer (shortened as the cooldown is). Each use spends one; with none left it is not\n\t * ready. Its `cooldown`, where it has one, is then the time between two uses. Full when it is learned\n\t */\n\tcharges?: { count: Scaled; refill: Scaled }\n\t/** How far away the target may be */\n\trange?: Scaled\n\t/** The target may be as far away as the caster's attacks reach, and `range` farther */\n\tattackRange?: boolean\n\t/**\n\t * What kind of thing it is, for those who can keep out of its way: a buff that `avoids` one of these\n\t * lets nothing of the ability happen to who carries it. `ground` is for what comes out of the ground or along it\n\t */\n\ttags?: string[]\n\t/** Levels a hero can put into it. 3 when left out */\n\tmaxLevel?: number\n\t/** Hero level needed for the first level of the ability. Ultimates ask for 6 */\n\trequiresLevel?: number\n\t/** Hero levels between two levels of the ability. 2 when left out */\n\tlevelStep?: number\n\t/**\n\t * Seconds between starting to cast and the effect. The caster stands still for as long and cannot be\n\t * called away: what it is told to do in the meantime, it does right after. None when left out\n\t */\n\tcastTime?: number\n\t/** Gets through a unit's immunity to spells (see `UnitTypeDef.spellImmune`), as an ultimate may. Or for the targets its function says */\n\tpiercesImmunity?: boolean | ((world: World, target: Entity) => boolean)\n\t/** The ground it covers, when that is not what its effects say: see `aimOf` */\n\taim?: { shape: 'circle'; radius: Scaled } | { shape: 'line'; length: Scaled; width: Scaled } | { shape: 'cone'; length: Scaled; angle: number }\n\t/** Units use it on their own when they have nothing else to do. The player can switch this off */\n\tautocast?: boolean\n\t/**\n\t * A buff of the caster that charges the ability when it has as many stacks as it can: the ability shows it, its\n\t * `charged` effects do their other thing, and casting it takes the buff away\n\t */\n\tcharge?: string\n\teffects: EffectDef[]\n\t/** What an ability that is cast does all the time besides, once it is learned: buffs, auras, `onHit` */\n\tpassive?: EffectDef[]\n\t/**\n\t * Autocast in code, for any kind of ability: where to use it now, or nothing. Asked when the unit has nothing to\n\t * do, the ability is switched to autocast, ready and paid for. Without it, only abilities cast on a unit autocast,\n\t * on the worst-off target their core effects would do good to\n\t */\n\tautoAim?: (world: World, caster: Entity, state: AbilityState) => { target?: number; point?: Vec2 } | null | undefined\n\t/**\n\t * How a computer player uses it, from what it sees (see `AiView`): where, or `null` for not now. What the engine\n\t * works out from its core effects when it gives nothing; an ability of the game's own effects has to say\n\t */\n\tai?: (view: AbilityAiView, caster: EntityState, level: number) => { point: Vec2; target?: number } | null | undefined\n\t/** How far away the target may be, in code: the range on high ground, say. `range` is what the screen shows */\n\trangeOf?: (world: World, caster: Entity, level: number) => number\n\t/** Seconds of the wind-up, in code: shortened by haste, say. `castTime` when left out */\n\tcastTimeOf?: (world: World, caster: Entity, level: number) => number\n\t/**\n\t * Kept up once it went off: the caster stands, for `duration` seconds, doing it every `every` seconds (effects, or\n\t * code), until it is done or interrupted (another order, a stun), when `interrupted` runs. An ice storm\n\t */\n\tchannel?: {\n\t\tduration: number | ((world: World, caster: Entity, level: number) => number)\n\t\tevery?: number\n\t\teffects?: EffectDef[]\n\t\trun?: (world: World, caster: Entity, level: number, target: Entity | undefined, point: Vec2) => void\n\t\tinterrupted?: (world: World, caster: Entity, level: number) => void\n\t\t/** What it does once kept up to the end, and only then: a recall's teleport home */\n\t\tfinished?: EffectDef[]\n\t\t/** Broken off when the caster is hurt, as a recall is: any damage, from anyone */\n\t\tbreaksOnDamage?: boolean\n\t}\n}\n\n/**\n * What an ability does all the time: all of a passive one, and the passive part of the others\n *\n * @internal\n */\nexport const passiveEffects = (ability: AbilityDef): EffectDef[] => (ability.target === 'passive' ? ability.effects : (ability.passive ?? []))\n\n/**\n * What the stats of the caster add to an amount. `level` is for every level of a hero past the first,\n * `bonusAttackDamage` for the attack damage it has on top of what its type and its levels give it\n *\n * @beta\n */\nexport type Scaling = Partial<Record<StatKey | 'level' | 'bonusAttackDamage', Scaled>>\n\n/**\n * Something lasting on a unit that changes what it can do\n *\n * @beta\n */\nexport interface BuffDef extends ScaledStatChange {\n\tid: string\n\tname: string\n\t/**\n\t * The definition this one is a copy of, made from the data (`copyOf` in a `data.json`, the editor's Copy as new):\n\t * what it is drawn, heard and pictured as where the game gives it no look of its own\n\t */\n\tbasedOn?: string\n\tdescription?: string\n\t/** Seconds. Lasts until removed when left out */\n\tduration?: number\n\t/** A debuff: by default it goes on enemies */\n\tharmful?: boolean\n\t/** The unit cannot do anything. A function says so for one carrier, one moment */\n\tstun?: boolean | BuffCheck\n\t/** Thrown into the air for as long as it lasts. Comes with a stun, the rest is for the eye */\n\tairborne?: boolean\n\t/** Knocked down: it lies on the ground for as long as it lasts, and gets up at the end. For the eye, like `airborne` */\n\tdown?: boolean\n\t/** Brings what flies down: it counts as being on the ground, for whatever is aimed at it */\n\tgrounds?: boolean\n\t/**\n\t * Its carrier is invisible to enemies for as long as it lasts, unless they find it (`detect`): a Wind Walk. A function\n\t * says so for one carrier, one moment\n\t */\n\tinvisible?: boolean | BuffCheck\n\t/** The unit cannot move from the spot. It can still fight and cast. A function says so for one carrier, one moment */\n\troot?: boolean | BuffCheck\n\t/**\n\t * The unit cannot use its abilities. What it carries and the spells every hero has still work. A function says\n\t * which abilities it keeps it from (`(ability) => ability.tags?.includes('fire')`): the screen asks it too\n\t */\n\tsilence?: boolean | ((ability: AbilityDef) => boolean)\n\t/** Damage it takes in place of the unit, for as long as the buff lasts and there is something left of it */\n\tshield?: Scaled\n\t/** What the stats of whoever gave the shield add to it */\n\tshieldScaling?: Scaling\n\t/** The shield is as good as new once the unit has not been hurt for this many seconds */\n\trecharge?: number\n\t/** Tags of abilities that do nothing to who carries it, for as long as it does: `ground` for someone up in the air */\n\tavoids?: string[]\n\t/** Who carries it does not attack while it lasts: burrowed, or disarmed. Or while its function says */\n\tdisarm?: boolean | BuffCheck\n\t/** Who carries it is immune to spells while it lasts, as an avatar is (see `UnitTypeDef.spellImmune`). Or while its function says */\n\tspellImmune?: boolean | BuffCheck\n\t/**\n\t * Whether a dispel takes it off (see the effect `dispel`). Yes when left out: no for what nothing should end early.\n\t * Decided in code for each dispel: by who dispels it (`by`), its level\n\t */\n\tdispellable?: boolean | ((world: World, carrier: Entity, instance: BuffInstance, by: Entity) => boolean)\n\t/** How many of it one unit can carry at most. What puts it on says whether it adds one (`stack`) */\n\tmaxStacks?: number\n\t/** What happens around who carried it when its time is up, in the name of who put it there. Not when it is taken off */\n\tonEnd?: EffectDef[]\n\t/** Its stats count once for every stack it has (`stacks`), rather than once: \"each stack, -5% move speed\" */\n\tperStack?: boolean\n\t/**\n\t * Stats of its own, worked out in code, on top of what it declares: \"+2 armor for each ally near\". Asked when the\n\t * carrier's stats are added up, which is only when something they come from changed: what this depends on beyond\n\t * the buff (allies near, the time) calls `invalidateStats` when it changes\n\t */\n\tchange?: (world: World, carrier: Entity, instance: BuffInstance) => StatChange | undefined\n\t/**\n\t * What happens when it is put on a unit that has it already. `strongest` (the default): the higher level wins,\n\t * the longer among equals. `refresh`: the time starts over, the level the new one's. `perSource`: one of it for\n\t * every unit that puts it on, each of its own (two poisons from two casters). `independent`: a new one every time.\n\t * A function decides from the one there and the one coming: `replace` it, `renew` its time, `add` another, or `keep`\n\t */\n\tstacking?:\n\t\t'strongest' | 'refresh' | 'perSource' | 'independent' | ((existing: BuffInstance, incoming: IncomingBuff) => 'replace' | 'renew' | 'add' | 'keep')\n\t/** What happens as it is put on: effects in the name of who put it there (while they live), or code */\n\tonApply?: EffectDef[] | BuffHandler\n\t/** What happens every `every` seconds while it lasts: effects in the name of who put it there (while they live), or code, which runs whoever is left */\n\tonTick?: { every: number; effects?: EffectDef[]; run?: BuffHandler }\n\t/** Code run when it comes off, run out (`expired`) or taken off. Not for the buffs of something that dies */\n\tonRemove?: (world: World, carrier: Entity, instance: BuffInstance, expired: boolean) => void\n}\n\n/** Whether a buff does what it says (stuns, roots) to one carrier, at this moment */\nexport type BuffCheck = (world: World, carrier: Entity, instance: BuffInstance) => boolean\n\n/** Code a buff runs on its carrier: as it is put on, or every so often */\nexport type BuffHandler = (world: World, carrier: Entity, instance: BuffInstance) => void\n\n/** A buff about to be put on, as a `stacking` function sees it */\nexport interface IncomingBuff {\n\tlevel: number\n\t/** Seconds */\n\tduration: number\n\t/** Who puts it on, by id: 0 for nobody */\n\tsource: number\n}\n\n/**\n * Where an item is in a shop. The client's tiers, or a game's own (`GameView.shopTiers`)\n *\n * @beta\n */\nexport type ItemTier = 'consumable' | 'starter' | 'basic' | 'epic' | 'legendary' | (string & {})\n\n/** @beta */\nexport interface ItemDef {\n\tid: string\n\tname: string\n\t/** How good it is, 1 and up (campaign plan GP3): what an item table draws by (`{ level: 3 }`) */\n\tlevel?: number\n\t/** Its kind of item, a word of the game's (`permanent`, `charged`, `powerup`): what an item table draws by too */\n\tclass?: string\n\t/**\n\t * The definition this one is a copy of, made from the data (`copyOf` in a `data.json`, the editor's Copy as new):\n\t * what it is drawn, heard and pictured as where the game gives it no look of its own\n\t */\n\tbasedOn?: string\n\tdescription?: string\n\tcost: Cost\n\t/** Uses before it is gone. Items without charges stay */\n\tcharges?: number\n\t/** Id of the ability the item gives: using the item casts it, without mana */\n\tability?: string\n\t/** Id of an ability whose passive part works for whoever carries the item */\n\tpassive?: string\n\t/** Items it is made of. Those the buyer carries are used up and taken off the price, which is for all of it */\n\tfrom?: string[]\n\t/** Where it goes in a shop: consumable, starter, basic, epic, legendary */\n\ttier?: ItemTier\n\t/** Applies for as long as the item is carried */\n\tbonus?: StatChange\n\t/** How many a shop has at most, and the seconds it takes to get one back. As many as anyone wants when left out */\n\tstock?: { max: number; restock: number }\n\thotkey?: string\n\t/**\n\t * Used as it is picked up, by walking over it or by the order, and never carried: a rune, a tome. Its ability is cast by\n\t * whoever picked it. In a game with the runes pack (`withRunes`, whose `powerUp` says it in code)\n\t */\n\tpowerUp?: boolean\n}\n\n/**\n * A big army is paid for with income: past a certain supply, less arrives of what workers gather of the resources with `upkeep`\n *\n * @beta\n */\nexport interface UpkeepTier {\n\t/** Applies when the player uses more supply than this */\n\tabove: number\n\tname: string\n\t/** Part of what is gathered that still arrives, 0..1 */\n\tincome: number\n}\n\n/**\n * What a level of research changes\n *\n * @beta\n */\nexport interface UpgradeEffect extends StatChange {\n\t/** Unit types that benefit, or a function of the type. Everything the player owns when left out */\n\tunits?: string[] | ((def: UnitTypeDef) => boolean)\n}\n\n/**\n * Research that improves a player's units for the rest of the game\n *\n * @beta\n */\nexport interface UpgradeDef {\n\tid: string\n\tname: string\n\t/**\n\t * The definition this one is a copy of, made from the data (`copyOf` in a `data.json`, the editor's Copy as new):\n\t * what it is drawn, heard and pictured as where the game gives it no look of its own\n\t */\n\tbasedOn?: string\n\tdescription?: string\n\t/** Paid for every level */\n\tcost: Cost\n\t/** Seconds per level */\n\tresearchTime: number\n\tmaxLevel?: number\n\t/** Building types needed, one list per level. Levels past the end of the list need nothing */\n\trequires?: string[][]\n\t/** The race it is of (`GameModule.races`): only its players may research it. Everyone's when left out */\n\trace?: string\n\thotkey?: string\n\teffects: UpgradeEffect[]\n\t/**\n\t * What it does besides stats, in code, to each unit of the player's: as a level is researched (to the units there\n\t * are), and as a unit comes into the world while the player has it. Gives an ability, lets a unit hit what flies.\n\t * Run again for every level: what it does is up to it to not do twice\n\t */\n\tapply?: (world: World, entity: Entity, level: number) => void\n}\n\n/**\n * The types a building can be upgraded into (`UnitTypeDef.upgradesTo`), as a list: one for most, none for one that\n * turns into nothing\n *\n * @beta\n */\nexport const upgradesOf = (def: Pick<UnitTypeDef, 'upgradesTo'>): readonly string[] =>\n\tdef.upgradesTo === undefined ? [] : typeof def.upgradesTo === 'string' ? [def.upgradesTo] : def.upgradesTo\n\n/** @beta */\nexport const footprintOf = (def: UnitTypeDef) => def.footprint ?? { w: Math.ceil(def.radius * 2), d: Math.ceil(def.radius * 2) }\n\n/**\n * Whether things of this type only stand there, like trees and gold mines: they never move, act or change by\n * themselves, so the systems that run every tick have nothing to do for them. A map can have thousands of\n * them and they cost nothing per tick. Only things that belong to nobody (the neutral player) are treated\n * as scenery, see `World.spawn`: a player's building counts for supply, sight and victory.\n *\n * @internal\n */\nexport function isScenery(def: UnitTypeDef): boolean {\n\treturn (\n\t\tdef.kind !== 'unit' &&\n\t\t!def.attacks?.length &&\n\t\t!def.hero &&\n\t\t!def.abilities?.length &&\n\t\t!def.inventory &&\n\t\t!def.sells?.length &&\n\t\t!def.trains?.length &&\n\t\t!def.researches?.length &&\n\t\t!upgradesOf(def).length &&\n\t\tdef.lifetime === undefined &&\n\t\t!def.invisible &&\n\t\tdef.recovers === undefined &&\n\t\t!def.stats.healthRegen &&\n\t\t!def.stats.manaRegen\n\t)\n}\n\n/**\n * What base stats are worked out under: the rules of a game, and what its own stats start at. A `Registry` is one\n *\n * @beta\n */\nexport interface StatSource {\n\treadonly rules: Readonly<GameRules>\n\t/** Every stat of the game at 0, its own at their default */\n\treadonly statDefaults: Readonly<Stats>\n}\n\n/** Base stats worked out before, by the game they were worked out for (a unit type may be in more than one game) */\nconst cache = new WeakMap<StatSource, { days: WeakMap<UnitTypeDef, Readonly<Stats>>; nights: WeakMap<UnitTypeDef, Readonly<Stats>> }>()\n\n/**\n * The stats a unit type starts with, all of them, in a game: `world.registry`, or `session.registry` on a player's\n * screen. By day unless it says otherwise\n *\n * @beta\n */\nexport function baseStats(def: UnitTypeDef, game: StatSource, night = false): Readonly<Stats> {\n\tconst { rules } = game\n\tlet cached = cache.get(game)\n\tif (!cached) cache.set(game, (cached = { days: new WeakMap(), nights: new WeakMap() }))\n\tconst bases = night ? cached.nights : cached.days\n\tlet stats = bases.get(def)\n\tif (!stats) {\n\t\tconst sight = night ? (def.sightNight ?? Math.round(def.sight * rules.fog.nightSight)) : def.sight\n\t\tstats = Object.freeze({ ...game.statDefaults, sight, ...def.stats }) as Readonly<Stats>\n\t\tbases.set(def, stats)\n\t}\n\treturn stats\n}\n\n/**\n * The ground an ability covers at a level: a line for what it sends on its way, a circle for what hits an area.\n * Undefined for abilities that are about one unit, or about nothing in particular.\n *\n * @beta\n */\nexport function aimOf(ability: AbilityDef, level: number): AimShape | undefined {\n\tconst { aim } = ability\n\tif (aim) {\n\t\tif (aim.shape === 'circle') return { shape: 'circle', radius: at(aim.radius, level) }\n\t\tif (aim.shape === 'cone') return { shape: 'cone', length: at(aim.length, level), angle: aim.angle }\n\t\treturn { shape: 'line', length: at(aim.length, level), width: at(aim.width, level) }\n\t}\n\tconst missile = ability.effects.find((effect) => effect.type === 'missile')\n\tif (missile) return { shape: 'line', length: at(missile.distance, level, 10), width: at(missile.radius, level, 1) }\n\tlet radius = 0\n\tfor (const effect of ability.effects) if (effect.type !== 'aura') radius = Math.max(radius, at(effect.radius, level))\n\treturn radius > 0 ? { shape: 'circle', radius } : undefined\n}\n","import { inventorySlots, slotsOf } from './inventory'\nimport { at, baseStats, type DamageType, type ScaledStatChange, type StatChange, type StatKey, type Stats } from './defs'\nimport type { Entity } from './entity'\nimport { clamp } from './math'\nimport type { Registry } from './registry'\nimport type { World } from './world'\n\n/** Adds up everything that changes the stats of one unit */\nclass Sum {\n\treadonly flat: Stats\n\t/** Parts by stat, for the stats something changes by a part */\n\treadonly percent: Record<string, number> = {}\n\t/** Slows are kept apart from what makes faster: resistance only weakens the former */\n\tslow = 0\n\n\tconstructor(base: Readonly<Stats>) {\n\t\tthis.flat = { ...base }\n\t}\n\n\tadd(change: StatChange, times = 1): void {\n\t\tfor (const key in change.stats) this.flat[key as StatKey] += change.stats[key as StatKey]! * times\n\t\tfor (const key in change.percent) this.part(key as StatKey, change.percent[key as StatKey]! * times)\n\t}\n\n\taddScaled(change: ScaledStatChange, level: number, times = 1): void {\n\t\tfor (const key in change.stats) this.flat[key as StatKey] += at(change.stats[key as StatKey], level) * times\n\t\tfor (const key in change.percent) this.part(key as StatKey, at(change.percent[key as StatKey], level) * times)\n\t}\n\n\tget(key: StatKey): number {\n\t\treturn (this.flat[key] ?? 0) * Math.max(1 + (this.percent[key] ?? 0), 0)\n\t}\n\n\tprivate part(key: StatKey, value: number): void {\n\t\tif (key === 'moveSpeed' && value < 0) this.slow += value\n\t\telse this.percent[key] = (this.percent[key] ?? 0) + value\n\t}\n\n\t/** The stats, kept within what the rules of the game allow, and its own stats within their bounds */\n\tresult(game: Registry): Stats {\n\t\tconst { flat, percent } = this\n\t\tconst stats = flat\n\t\tfor (const key in percent) {\n\t\t\tconst part = percent[key]\n\t\t\tif (part !== 0) stats[key] *= Math.max(1 + part, 0)\n\t\t}\n\t\tgame.rules.combat.clampStats(stats, game.rules)\n\t\tconst slowed = this.slow === 0 ? 1 : Math.max(1 + game.rules.combat.slowTaken(stats, this.slow), 0)\n\t\tstats.moveSpeed = Math.max(stats.moveSpeed * slowed, 0)\n\t\tfor (const { id, min, max } of game.stats) stats[id] = clamp(stats[id], min ?? -Infinity, max ?? Infinity)\n\t\tstats.health = Math.max(Math.round(stats.health), 1)\n\t\tstats.mana = Math.max(Math.round(stats.mana), 0)\n\t\treturn stats\n\t}\n}\n\n/**\n * What adds up a unit's stats in the sum: what a stat source is handed (`StatPart.add`)\n *\n * @beta\n */\nexport interface StatSum {\n\t/** Adds a change to the stats, `times` over (1 when left out) */\n\tadd(change: StatChange, times?: number): void\n\t/** What a stat comes to so far: all that was added to it, by the parts it was made bigger or smaller by */\n\tget(stat: StatKey): number\n}\n\n/**\n * A part of the stats a pack adds (`GamePack.stats`): a hero's growth by its level, in the heroes pack. `stamp` is a\n * number that changes whenever what it adds does, and is 0 when it adds nothing: the stats are added up again when it\n * changes, however it changed (a game that sets a hero's level itself says nothing, and need not)\n *\n * @beta\n */\nexport interface StatPart {\n\treadonly id: string\n\tstamp(entity: Entity): number\n\tadd(world: World, entity: Entity, sum: StatSum): void\n\t/**\n\t * What it makes of the stats once everything else is added (research, the packs' parts, items, buffs, the `stats`\n\t * hook), read with `sum.get`: a hero's strength into health, in the attributes pack (`withAttributes`)\n\t */\n\tderive?(world: World, entity: Entity, sum: StatSum): void\n}\n\n/** Whether anything changes the stats a unit started with */\nfunction changed(world: World, entity: Entity): boolean {\n\tif (entity.buffs.length > 0 || entity.has(inventorySlots) || world.hooks.has('stats')) return true\n\tfor (const source of world.registry.statParts) if (source.stamp(entity) !== 0) return true\n\treturn world.player(entity.owner).upgrades.size > 0\n}\n\n/** Adds up the stats of an entity from scratch. Use `statsOf`, which only does this when something changed */\nfunction computeStats(world: World, entity: Entity, night: boolean): Readonly<Stats> {\n\tconst base = baseStats(entity.def, world.registry, night)\n\tif (!changed(world, entity)) return base\n\n\tconst sum = new Sum(base)\n\tfor (const [id, level] of world.player(entity.owner).upgrades) {\n\t\tfor (const effect of world.registry.upgrade(id).effects) {\n\t\t\tif (!effect.units || (typeof effect.units === 'function' ? effect.units(entity.def) : effect.units.includes(entity.def.id)))\n\t\t\t\tsum.add(effect, level)\n\t\t}\n\t}\n\t// what the packs add: a hero's growth by its level\n\tfor (const source of world.registry.statParts) source.add(world, entity, sum)\n\tfor (const instance of slotsOf(entity) ?? []) {\n\t\tconst bonus = instance && world.registry.item(instance.item).bonus\n\t\tif (bonus) sum.add(bonus)\n\t}\n\tfor (const instance of entity.buffs) {\n\t\tconst def = world.registry.buff(instance.id)\n\t\tsum.addScaled(def, instance.level, def.perStack ? (instance.stacks ?? 1) : 1)\n\t\tconst own = def.change?.(world, entity, instance)\n\t\tif (own) sum.add(own)\n\t}\n\t// and whatever the game adds in code: \"+2 armor for each ally near\"\n\tif (world.hooks.has('stats')) world.hooks.run('stats', { entity, base, add: (change, times) => sum.add(change, times) })\n\t// what the packs make of it all: strength into health\n\tfor (const source of world.registry.statParts) source.derive?.(world, entity, sum)\n\treturn sum.result(world.registry)\n}\n\n/**\n * Says the stats of an entity, or of every entity when none is said, are to be added up again the next time they are\n * asked for: what a `stats` hook or a buff's `change` reads changed (an ally came near, a flag of the game's). What\n * the engine knows about (buffs, items, levels, research, the time of day) it notices by itself\n *\n * @beta\n */\nexport function invalidateStats(world: World, entity?: Entity): void {\n\tif (entity) entity.statsCache = null\n\telse world.statsVersion++\n}\n\n/**\n * The stats of an entity the last time they were worked out, and everything they were worked out from.\n *\n * Stats are asked for all the time: on every hit (for both sides), every target search, every fog update.\n * Adding them up means going through the owner's research, what the unit carries and every buff on it,\n * and allocates. Checking whether any of that changed is a handful of comparisons and allocates nothing,\n * so `statsOf` does that first and only adds up again when something did.\n *\n * The inputs are compared, rather than the cache being thrown away wherever they change, so that nothing\n * can change a buff or an item and forget to say so: game modules and mods change them directly.\n *\n * Not game state: it can be dropped at any time (and is never saved or sent), it is rebuilt on the next ask.\n */\nexport interface StatsCache {\n\tstats: Readonly<Stats>\n\t/** `changedStats` of `stats`, once someone asked. The same object for as long as the stats stay the same */\n\tchanged?: Partial<Stats>\n\tchangedFor?: Readonly<Stats>\n\n\tdef: Entity['def']\n\tnight: boolean\n\towner: number\n\t/** What each of the packs' stat sources stamped it with (`StatPart.stamp`), in their order */\n\tstamps: number[]\n\tupgradesVersion: number\n\t/** `World.statsVersion` when it was worked out: `invalidateStats` for every entity moves it on */\n\tstatsVersion: number\n\t/** Ids of what it carries, in slot order, empty slots left out */\n\titems: string[]\n\t/** Id, level and stacks of every buff, in order */\n\tbuffIds: string[]\n\tbuffLevels: number[]\n\tbuffStacks: number[]\n}\n\n/** Whether the packs' stat sources stamp the entity as they did when its stats were worked out */\nfunction sameStamps(stamps: number[], world: World, entity: Entity): boolean {\n\tconst sources = world.registry.statParts\n\tfor (let i = 0; i < sources.length; i++) if (sources[i].stamp(entity) !== stamps[i]) return false\n\treturn true\n}\n\n/** Whether the stats in the cache were worked out from what the entity is right now */\nfunction stillHolds(cache: StatsCache, world: World, entity: Entity, night: boolean): boolean {\n\tif (\n\t\tcache.def !== entity.def ||\n\t\tcache.night !== night ||\n\t\tcache.owner !== entity.owner ||\n\t\t!sameStamps(cache.stamps, world, entity) ||\n\t\tcache.upgradesVersion !== world.player(entity.owner).upgradesVersion ||\n\t\tcache.statsVersion !== world.statsVersion\n\t) {\n\t\treturn false\n\t}\n\tconst { buffs } = entity\n\tif (buffs.length !== cache.buffIds.length) return false\n\tfor (let i = 0; i < buffs.length; i++) {\n\t\tconst buff = buffs[i]\n\t\tif (buff.id !== cache.buffIds[i] || buff.level !== cache.buffLevels[i] || (buff.stacks ?? 0) !== cache.buffStacks[i]) return false\n\t}\n\tlet carried = 0\n\tfor (const item of slotsOf(entity) ?? []) {\n\t\tif (!item) continue\n\t\tif (item.item !== cache.items[carried]) return false\n\t\tcarried++\n\t}\n\treturn carried === cache.items.length\n}\n\nfunction buildCache(world: World, entity: Entity, night: boolean): StatsCache {\n\tconst items: string[] = []\n\tfor (const item of slotsOf(entity) ?? []) if (item) items.push(item.item)\n\treturn {\n\t\tstats: computeStats(world, entity, night),\n\t\tdef: entity.def,\n\t\tnight,\n\t\towner: entity.owner,\n\t\tstamps: world.registry.statParts.map((source) => source.stamp(entity)),\n\t\tupgradesVersion: world.player(entity.owner).upgradesVersion,\n\t\tstatsVersion: world.statsVersion,\n\t\titems,\n\t\tbuffIds: entity.buffs.map((buff) => buff.id),\n\t\tbuffLevels: entity.buffs.map((buff) => buff.level),\n\t\tbuffStacks: entity.buffs.map((buff) => buff.stacks ?? 0)\n\t}\n}\n\n/**\n * The stats of an entity as they are right now: what its type starts with at this time of day, and on top of that\n * its levels, the research of its owner, what it carries and the buffs on it.\n *\n * The result is shared and must not be changed. It stays the same object for as long as the stats stay the same.\n *\n * @beta\n */\nexport function statsOf(world: World, entity: Entity): Readonly<Stats> {\n\tconst night = world.night\n\tconst cache = entity.statsCache\n\tif (cache && stillHolds(cache, world, entity, night)) {\n\t\tif (world.checks.stats) checkCache(world, entity, night, cache.stats)\n\t\treturn cache.stats\n\t}\n\tentity.statsCache = buildCache(world, entity, night)\n\treturn entity.statsCache.stats\n}\n\nfunction checkCache(world: World, entity: Entity, night: boolean, cached: Readonly<Stats>): void {\n\tconst fresh = computeStats(world, entity, night)\n\tfor (const key in fresh) {\n\t\tconst k = key as StatKey\n\t\tif (fresh[k] !== cached[k]) {\n\t\t\tthrow new Error(`Stale stats cache: ${entity.def.id}#${entity.id} has ${key} ${cached[k]}, should be ${fresh[k]}`)\n\t\t}\n\t}\n}\n\n/**\n * The stats that are not what the type of the entity starts with by day, or undefined when all of them are\n *\n * @internal\n */\nexport function changedStats(world: World, entity: Entity): Partial<Stats> | undefined {\n\tconst base = baseStats(entity.def, world.registry)\n\tconst stats = statsOf(world, entity)\n\tif (stats === base) return undefined\n\t// the same stats give the same answer, as the same object: whoever keeps it (the client does) can tell nothing changed\n\tconst cache = entity.statsCache!\n\tif (cache.changedFor === stats) return cache.changed\n\tlet result: Partial<Stats> | undefined\n\tfor (const key in stats) {\n\t\tif (stats[key as StatKey] !== base[key as StatKey]) (result ??= {})[key as StatKey] = stats[key as StatKey]\n\t}\n\tcache.changed = result\n\tcache.changedFor = stats\n\treturn result\n}\n\n/**\n * Brings the most health and mana an entity can have in line with its stats.\n * What is gained is added to what it has, what is lost is only taken when it has more than it can hold.\n *\n * @beta\n */\nexport function refreshVitals(world: World, entity: Entity): void {\n\tconst stats = statsOf(world, entity)\n\tif (stats.health !== entity.maxHp) {\n\t\tentity.hp = Math.min(entity.hp + Math.max(stats.health - entity.maxHp, 0), stats.health)\n\t\tentity.maxHp = stats.health\n\t}\n\tif (stats.mana !== entity.maxMana) {\n\t\tentity.mana = Math.min(entity.mana + Math.max(stats.mana - entity.maxMana, 0), stats.mana)\n\t\tentity.maxMana = stats.mana\n\t}\n}\n\n/**\n * What is left of damage once the armor or the magic resist of the target had its say, as a part of it: 100 of it\n * halve what arrives, and below 0 it adds. The engine's formula: the game's is `world.rules.combat.mitigation`, which\n * is this unless the game says (penetration: `withMobaStats`)\n *\n * @beta\n */\nexport function mitigation(type: DamageType, target: Readonly<Stats>): number {\n\tif (type === 'true') return 1\n\treturn resisted(type === 'physical' ? target.armor : target.magicResist)\n}\n\n/**\n * What is left of damage against a resistance: 100 of it halve what arrives, below 0 it adds\n *\n * @internal\n */\nexport const resisted = (resist: number): number => (resist >= 0 ? 100 / (100 + resist) : 2 - 100 / (100 - resist))\n\n/**\n * How long an attack of the entity takes: from the start of the swing to the hit, and from one swing to the next. Of\n * its first attack, or the one at that place (`UnitTypeDef.attacks`), by the speed stat it reads (`AttackDef.stats`)\n *\n * @beta\n */\nexport function attackTiming(world: World, entity: Entity, weapon = 0): { swing: number; period: number } {\n\tconst attack = entity.def.attacks?.[weapon]\n\tconst speed = attack?.stats?.speed ?? 'attackSpeed'\n\tconst base = baseStats(entity.def, world.registry)[speed] ?? 0\n\treturn swingTiming(attack?.damagePoint ?? 0, base, statsOf(world, entity)[speed] ?? 0) ?? { swing: 0, period: Infinity }\n}\n\n/**\n * Seconds an ability of the entity takes to be ready again\n *\n * @beta\n */\nexport function cooldownOf(world: World, entity: Entity, seconds: number): number {\n\treturn world.rules.combat.cooldown(seconds, statsOf(world, entity))\n}\n\n/**\n * How long an attack takes, from the start of the swing to the hit, and from one swing to the next, for a unit\n * whose type attacks `base` times a second and that now attacks `speed` times. Undefined for what does not attack\n *\n * @beta\n */\nexport function swingTiming(damagePoint: number, base: number, speed: number): { swing: number; period: number } | undefined {\n\tif (!speed || !base) return undefined\n\tconst period = 1 / speed\n\t// the swing gets faster with the attack\n\treturn { swing: Math.min((damagePoint * base) / speed, period), period }\n}\n","import type { SessionView } from './replication'\nimport type { World } from './world'\n\ntype Handler<T> = (payload: T) => void\n\n/**\n * Who of the players gets an event of a game's own on their screen (see `defineEvent`): everyone, or those a\n * function picks, from what the event says and what the seat may know (`SessionView`: its player, `knows`, `sees`)\n *\n * @beta\n */\nexport type EventAudience<T> = 'everyone' | ((payload: T, view: SessionView) => boolean)\n\n/**\n * A typed key for an event of a game's own, made with `defineEvent`\n *\n * @beta\n */\nexport interface EventKey<T> {\n\treadonly id: string\n\t/** Sent to the screens of these players, in their snapshots. Only to whoever listens in the world when left out */\n\treadonly replicate?: EventAudience<T>\n\t/** Only there for the type of the payload */\n\treadonly payload?: T\n}\n\n/** Every event of a game's own by id, for the session: it sends the replicated ones to the screen */\nconst defined = new Map<string, EventKey<unknown>>()\n\n/**\n * An event of a game's own: `const through = defineEvent<{ unit: string }>('td.invaderThrough', { replicate: 'everyone' })`.\n * Emitted on `world.events` like the engine's (`world.events.emit(through, { unit })`), held to the end of the tick\n * like them, and listened to with `defineListener`. Ids are shared by every game: give them a prefix of the game's.\n *\n * A replicated event goes to the players' screens, where `GameView.on` and the renderers get it: what it says has\n * to be plain data then (numbers, text, lists, plain objects), with entities by id, as it may cross a network\n *\n * @beta\n */\nexport function defineEvent<T>(id: string, options: { replicate?: EventAudience<T> } = {}): EventKey<T> {\n\tconst key: EventKey<T> = { id, ...options }\n\t// the last of an id, for an event a game uses without listing it (`Registry.event`): each game finds its own listed first\n\tdefined.set(id, key as EventKey<unknown>)\n\treturn key\n}\n\n/**\n * One of the engine's events (`engineEvents.ts`): a key as a game's own is, but not one of a game's (`isGameEvent`),\n * and told to the players only by what replicates it (`replicateEvent`)\n *\n * @internal\n */\nexport const engineEvent = <T>(id: string): EventKey<T> => ({ id })\n\n/**\n * The event of a game's own defined with this id, in this process, if any\n *\n * @internal\n */\nexport const eventById = (id: string): EventKey<unknown> | undefined => defined.get(id)\n\n/** Whether an event is one of a game's own, rather than one of the engine's */\nexport const isGameEvent = (id: PropertyKey): boolean => typeof id === 'string' && defined.has(id)\n\n/**\n * The events of games' own that go to the screen, of every game of the process. A world's own are its registry's\n * (`world.registry.replicatedEvents()`): what its game lists (`GameModule.events`), and the engine's\n *\n * @internal\n */\nexport const replicatedEvents = (): EventKey<unknown>[] => [...defined.values()].filter((key) => key.replicate)\n\n/**\n * How a game reacts to an event: the engine's (`'entityDied'`, `'enteredArea'`) or one of its own. Listeners are\n * given in `GameModule.listeners`, and the world subscribes them when it is made, in their order: a new game, a\n * loaded save and every player's machine get the same ones. They run at the end of the tick, once everything in it\n * is settled, and may change the world: what happens then is part of that tick. One with the id of another takes\n * its place, in a mod\n *\n * @beta\n */\nexport interface ListenerDef {\n\tid: string\n\tevent: EventKey<any>\n\trun(world: World, payload: any): void\n}\n\n/**\n * Typed help for writing a listener: `defineListener({ event: enteredArea, id: 'td.gate', run(world, { area, entity }) { ... } })`\n *\n * @beta\n */\nexport function defineListener<T>(def: { id: string; event: EventKey<T>; run(world: World, payload: T): void }): ListenerDef {\n\treturn def\n}\n\n/**\n * Minimal typed event emitter: each event by its key (`EventKey`), which types what it says.\n *\n * While held (`hold`), what is emitted waits in a queue and goes out on `release`, in the order it happened.\n * The world holds its events for the length of a tick, so that whoever listens sees how things stand once\n * the tick is over, and cannot change anything halfway through it.\n */\nexport class Emitter {\n\tprivate handlers = new Map<PropertyKey, Set<Handler<any>>>()\n\tprivate held = false\n\tprivate queue: { type: PropertyKey; payload: unknown }[] = []\n\t/** True while what was held back goes out (`release`) */\n\treleasing = false\n\tprivate readonly taps = new Set<(type: PropertyKey, payload: unknown) => void>()\n\tprivate readonly watchers = new Set<(type: PropertyKey, payload: unknown) => void>()\n\n\t/**\n\t * Calls back for every event as it goes out, before whoever listens to it: the event log of the debug tools, a\n\t * logger. Any number of them. Returns what stops it\n\t */\n\ttap(listener: (type: PropertyKey, payload: unknown) => void): () => void {\n\t\tthis.taps.add(listener)\n\t\treturn () => this.taps.delete(listener)\n\t}\n\n\t/**\n\t * Calls back for every event as it goes out, whatever it is, after whoever listens to it by name: for what cannot\n\t * know ahead which events there will be, as a player's seat that passes on a game's own. Returns what stops it\n\t */\n\twatch(watcher: (type: PropertyKey, payload: unknown) => void): () => void {\n\t\tthis.watchers.add(watcher)\n\t\treturn () => this.watchers.delete(watcher)\n\t}\n\n\t/** Listens to an event, the engine's (`engineEvents.ts`) or a game's own. Returns what stops it */\n\ton<T>(key: EventKey<T>, handler: Handler<T>): () => void {\n\t\tconst { id } = key\n\t\tlet set = this.handlers.get(id)\n\t\tif (!set) this.handlers.set(id, (set = new Set()))\n\t\tset.add(handler)\n\t\treturn () => set.delete(handler)\n\t}\n\n\temit<T>(key: EventKey<T>, payload: T): void {\n\t\tconst { id } = key\n\t\tif (this.held) {\n\t\t\tthis.queue.push({ type: id, payload })\n\t\t\treturn\n\t\t}\n\t\tthis.deliver(id, payload)\n\t}\n\n\t/** Holds back what is emitted from now on, until `release` */\n\thold(): void {\n\t\tthis.held = true\n\t}\n\n\t/** Sends out everything held back, and stops holding */\n\trelease(): void {\n\t\tthis.held = false\n\t\t// what a listener emits while this goes on is sent at once, after what it is reacting to\n\t\tconst queue = this.queue\n\t\tthis.queue = []\n\t\tthis.releasing = true\n\t\ttry {\n\t\t\tfor (const { type, payload } of queue) this.deliver(type, payload)\n\t\t} finally {\n\t\t\tthis.releasing = false\n\t\t}\n\t}\n\n\tprivate deliver(type: PropertyKey, payload: unknown): void {\n\t\tfor (const tap of this.taps) tap(type, payload)\n\t\tconst set = this.handlers.get(type)\n\t\tif (set) for (const handler of set) handler(payload)\n\t\tfor (const watcher of this.watchers) watcher(type, payload)\n\t}\n\n\tclear(): void {\n\t\tthis.handlers.clear()\n\t\tthis.watchers.clear()\n\t\tthis.queue = []\n\t}\n}\n","/**\n * The engine's events (design review E7): a key each, as a game's own are (`defineEvent`), emitted on `world.events`\n * and listened to with `defineListener` the same way. What each says is its payload, typed by the key; its id is its\n * name, as the debug tools' event log shows it\n */\nimport { engineEvent } from './events'\nimport type { WorldEvents } from './world'\n\n/**\n * Something was made in the world: a unit trained or spawned, a building put down, a tree of the map\n *\n * @beta\n */\nexport const entitySpawned = engineEvent<WorldEvents['entitySpawned']>('entitySpawned')\n\n/**\n * Something left the world for good: a corpse gone, a building taken down, a unit removed by the rules\n *\n * @beta\n */\nexport const entityRemoved = engineEvent<WorldEvents['entityRemoved']>('entityRemoved')\n\n/**\n * Something died: what killed it, and how. `cause`: the blow, for what died of damage. `how`: what the rules made\n * of the death in the `death` hook, for the screen to show (`'exploded'`, `'burned'`)\n *\n * @beta\n */\nexport const entityDied = engineEvent<WorldEvents['entityDied']>('entityDied')\n\n/**\n * A buff was put on, or put on again (`renewed`, with the level it had before: `previousLevel`)\n *\n * @beta\n */\nexport const buffApplied = engineEvent<WorldEvents['buffApplied']>('buffApplied')\n\n/**\n * A buff came off: it ran out (`expired`), or was taken off. Not for the buffs of something that dies\n *\n * @beta\n */\nexport const buffRemoved = engineEvent<WorldEvents['buffRemoved']>('buffRemoved')\n\n/**\n * Something took damage: who dealt it, how much, of which type, whether a critical strike, and by an attack or an ability\n *\n * @beta\n */\nexport const damaged = engineEvent<WorldEvents['damaged']>('damaged')\n\n/**\n * An attack went wide. Where it would have landed, and whom it was for\n *\n * @beta\n */\nexport const missed = engineEvent<WorldEvents['missed']>('missed')\n\n/**\n * Something was given health back, and by whom\n *\n * @beta\n */\nexport const healed = engineEvent<WorldEvents['healed']>('healed')\n\n/**\n * A unit began an attack: its swing, at its target where it has one\n *\n * @beta\n */\nexport const attackStarted = engineEvent<WorldEvents['attackStarted']>('attackStarted')\n\n/**\n * An attack's projectile set off\n *\n * @beta\n */\nexport const projectileSpawned = engineEvent<WorldEvents['projectileSpawned']>('projectileSpawned')\n\n/**\n * An attack's projectile landed or was taken away\n *\n * @beta\n */\nexport const projectileRemoved = engineEvent<WorldEvents['projectileRemoved']>('projectileRemoved')\n\n/**\n * An attack that hits an area came down\n *\n * @beta\n */\nexport const impact = engineEvent<WorldEvents['impact']>('impact')\n\n/**\n * A building's site was put down: what it will be, while it goes up\n *\n * @beta\n */\nexport const constructionStarted = engineEvent<WorldEvents['constructionStarted']>('constructionStarted')\n\n/**\n * A building went up whole and works\n *\n * @beta\n */\nexport const constructionFinished = engineEvent<WorldEvents['constructionFinished']>('constructionFinished')\n\n/**\n * A construction was called off by its owner: it dies next, with the reason `cancelled`\n *\n * @beta\n */\nexport const constructionCancelled = engineEvent<WorldEvents['constructionCancelled']>('constructionCancelled')\n\n/**\n * A building started to turn into another type (`UnitTypeDef.upgradesTo`), over `time` seconds\n *\n * @beta\n */\nexport const morphStarted = engineEvent<WorldEvents['morphStarted']>('morphStarted')\n\n/**\n * That was called off, or the building died before it was done\n *\n * @beta\n */\nexport const morphCancelled = engineEvent<WorldEvents['morphCancelled']>('morphCancelled')\n\n/**\n * A building trained a unit: the building, and the unit made\n *\n * @beta\n */\nexport const unitTrained = engineEvent<WorldEvents['unitTrained']>('unitTrained')\n\n/**\n * An entity became another type: `from`, what it was\n *\n * @beta\n */\nexport const entityMorphed = engineEvent<WorldEvents['entityMorphed']>('entityMorphed')\n\n/**\n * A player lost: their units and buildings are gone, or the rules said so\n *\n * @beta\n */\nexport const playerDefeated = engineEvent<WorldEvents['playerDefeated']>('playerDefeated')\n\n/**\n * A player gave up (see `surrender`): `playerDefeated` follows\n *\n * @beta\n */\nexport const playerSurrendered = engineEvent<WorldEvents['playerSurrendered']>('playerSurrendered')\n\n/**\n * A player asked for a pause, and the rules let them (see `askPause`): whoever runs the world pauses it, for `seconds` at most\n *\n * @beta\n */\nexport const pauseAsked = engineEvent<WorldEvents['pauseAsked']>('pauseAsked')\n\n/**\n * The game ended, with the winning team (`0` for none)\n *\n * @beta\n */\nexport const gameOver = engineEvent<WorldEvents['gameOver']>('gameOver')\n\n/**\n * The game ended on an error in its rules (`world.failure`): it is not stepped again\n *\n * @beta\n */\nexport const worldFailed = engineEvent<WorldEvents['worldFailed']>('worldFailed')\n\n/**\n * A unit got into a transport (`UnitTypeDef.transport`), or out of one\n *\n * @beta\n */\nexport const boarded = engineEvent<WorldEvents['boarded']>('boarded')\n\n/**\n * A unit was hired at a place that hires (`UnitTypeDef.hires`)\n *\n * @beta\n */\nexport const unitHired = engineEvent<WorldEvents['unitHired']>('unitHired')\n\n/**\n * A passenger left its transport\n *\n * @beta\n */\nexport const unloaded = engineEvent<WorldEvents['unloaded']>('unloaded')\n\n/**\n * A hero went up a level\n *\n * @beta\n */\nexport const heroLevelUp = engineEvent<WorldEvents['heroLevelUp']>('heroLevelUp')\n\n/**\n * A hero earned experience (`grantXp`): how much, after `beforeXp`, and the level it is at after it\n *\n * @beta\n */\nexport const xpGained = engineEvent<WorldEvents['xpGained']>('xpGained')\n\n/**\n * A unit's mana changed by something it did or was given: spent on a cast (`amount` below 0, `ability` the one cast)\n * or given by an effect (above 0). Not its regeneration, which would be every tick\n *\n * @beta\n */\nexport const manaChanged = engineEvent<WorldEvents['manaChanged']>('manaChanged')\n\n/**\n * A pool of a game's own on a unit (rage, energy, charges) changed: emitted by the game's rules\n * (`world.events.emit('resourceChanged', …)`), heard by the screens of the unit's owner and allies (`resource`)\n *\n * @beta\n */\nexport const resourceChanged = engineEvent<WorldEvents['resourceChanged']>('resourceChanged')\n\n/**\n * A hero came back to life (at an altar, or by the rules)\n *\n * @beta\n */\nexport const heroRevived = engineEvent<WorldEvents['heroRevived']>('heroRevived')\n\n/**\n * A unit began casting an ability, at a point where it has one. `duration`: seconds of the wind-up\n *\n * @beta\n */\nexport const castStarted = engineEvent<WorldEvents['castStarted']>('castStarted')\n\n/**\n * A channelled ability started to be kept up, or ended: done, or `interrupted`\n *\n * @beta\n */\nexport const channelStarted = engineEvent<WorldEvents['channelStarted']>('channelStarted')\n\n/**\n * A channelled ability stopped: run to its end, or broken off (`interrupted`)\n *\n * @beta\n */\nexport const channelEnded = engineEvent<WorldEvents['channelEnded']>('channelEnded')\n\n/**\n * An ability's missile set off\n *\n * @beta\n */\nexport const missileSpawned = engineEvent<WorldEvents['missileSpawned']>('missileSpawned')\n\n/**\n * An ability's missile reached what it was sent at\n *\n * @beta\n */\nexport const missileHit = engineEvent<WorldEvents['missileHit']>('missileHit')\n\n/**\n * An ability's missile is gone: it hit, or ran out\n *\n * @beta\n */\nexport const missileRemoved = engineEvent<WorldEvents['missileRemoved']>('missileRemoved')\n\n/**\n * An ability went off: who cast it, at what level, at whom or where\n *\n * @beta\n */\nexport const abilityCast = engineEvent<WorldEvents['abilityCast']>('abilityCast')\n\n/**\n * What an ability set off arrived: a missile hit, a rush ended, the time was up\n *\n * @beta\n */\nexport const abilityImpact = engineEvent<WorldEvents['abilityImpact']>('abilityImpact')\n\n/**\n * A building finished researching an upgrade: which, and its level now\n *\n * @beta\n */\nexport const researchFinished = engineEvent<WorldEvents['researchFinished']>('researchFinished')\n\n/**\n * An item was put on the ground\n *\n * @beta\n */\nexport const itemDropped = engineEvent<WorldEvents['itemDropped']>('itemDropped')\n\n/**\n * An item was picked up from the ground\n *\n * @beta\n */\nexport const itemPicked = engineEvent<WorldEvents['itemPicked']>('itemPicked')\n\n/**\n * Every creep of a camp is gone. It comes back after a while, when it says so (see `Camp.respawn`)\n *\n * @beta\n */\nexport const campCleared = engineEvent<WorldEvents['campCleared']>('campCleared')\n\n/**\n * A camp cleared came back, its creeps where they stood (see `respawnCamp`)\n *\n * @beta\n */\nexport const campReturned = engineEvent<WorldEvents['campReturned']>('campReturned')\n\n/**\n * A player marked a spot for their allies, or for everyone (see `ping`)\n *\n * @beta\n */\nexport const pinged = engineEvent<WorldEvents['pinged']>('pinged')\n\n/**\n * A player gave an ally resources (see `give`): how much went, and how much came after the tax\n *\n * @beta\n */\nexport const traded = engineEvent<WorldEvents['traded']>('traded')\n\n/**\n * A player traded one resource for another at a rate (see `exchange`): how much of what went, and how much of what came\n *\n * @beta\n */\nexport const exchanged = engineEvent<WorldEvents['exchanged']>('exchanged')\n\n/**\n * A player said a line (see `chat`): to their side, or to everyone\n *\n * @beta\n */\nexport const chatted = engineEvent<WorldEvents['chatted']>('chatted')\n\n/**\n * What a unit carries changed: an item given, taken, bought, sold, used up, or a hero carried in with theirs\n *\n * @beta\n */\nexport const inventoryChanged = engineEvent<WorldEvents['inventoryChanged']>('inventoryChanged')\n\n/**\n * A player was paid for a kill: the unit killed, who was paid, how much\n *\n * @beta\n */\nexport const bounty = engineEvent<WorldEvents['bounty']>('bounty')\n\n/**\n * A worker struck what it is mending\n *\n * @beta\n */\nexport const worked = engineEvent<WorldEvents['worked']>('worked')\n\n/**\n * A worker struck the tree it is working on\n *\n * @beta\n */\nexport const chopped = engineEvent<WorldEvents['chopped']>('chopped')\n\n/**\n * A worker handed in what it carried: `amount` as it went into the purse, `upkeep` what upkeep took of it at the door\n *\n * @beta\n */\nexport const resourcesDeposited = engineEvent<WorldEvents['resourcesDeposited']>('resourcesDeposited')\n\n/**\n * A player paid for something (`spend`), or was given back what they paid (`refund`, `giveBack`): `on` what (`unit`,\n * `upgrade`, `structure`, `item`, `hire`, `repair`... or a game's own word), and its id\n *\n * @beta\n */\nexport const resourcesSpent = engineEvent<WorldEvents['resourcesSpent']>('resourcesSpent')\n\n/**\n * 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 * field missing or of the wrong kind), or naming another player's unit, or a unit there never was. What a race makes\n * (an order to a unit that has just died) is not one. A server counts these against whoever sent them (`onCheat`);\n * a game's own commands may emit it too\n */\n/**\n * A command turned away (`RejectedKind`: why, for what counts them, as a server's cheat counter does), with the\n * reason in words for the log\n *\n * @beta\n */\nexport const commandRejected = engineEvent<WorldEvents['commandRejected']>('commandRejected')\n\n/**\n * 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 *\n * @beta\n */\nexport const commandHandled = engineEvent<WorldEvents['commandHandled']>('commandHandled')\n\n/**\n * Feedback for a player, like \"Not enough gold\": what the client finds the words for\n *\n * @beta\n */\nexport const messageSent = engineEvent<WorldEvents['messageSent']>('messageSent')\n\n/**\n * A unit walked into an area of the game (`GameModule.areas`)\n *\n * @beta\n */\nexport const enteredArea = engineEvent<WorldEvents['enteredArea']>('enteredArea')\n\n/**\n * A unit walked out of one. What dies in an area is not said to leave it\n *\n * @beta\n */\nexport const leftArea = engineEvent<WorldEvents['leftArea']>('leftArea')\n\n/**\n * An objective of a player was given (`was` undefined), got further along, was done or failed\n *\n * @beta\n */\nexport const objectiveChanged = engineEvent<WorldEvents['objectiveChanged']>('objectiveChanged')\n\n/**\n * Someone said a line, to some players or everyone (see `world.dialog`)\n *\n * @beta\n */\nexport const lineSaid = engineEvent<WorldEvents['lineSaid']>('lineSaid')\n\n/**\n * A line was skipped by whom it was said to: it ends early for them\n *\n * @beta\n */\nexport const lineEnded = engineEvent<WorldEvents['lineEnded']>('lineEnded')\n\n/**\n * A player went over to another team (`setTeam`)\n *\n * @beta\n */\nexport const teamChanged = engineEvent<WorldEvents['teamChanged']>('teamChanged')\n\n/**\n * The rules marked a moment to start again from, like the start of a wave: a session keeps a save of it\n *\n * @beta\n */\nexport const checkpoint = engineEvent<WorldEvents['checkpoint']>('checkpoint')\n\n/**\n * The rules play one of the view's cinematics on the screens of some players, or everyone's (see `playCinematic`)\n *\n * @beta\n */\nexport const cinematicCue = engineEvent<WorldEvents['cinematicCue']>('cinematicCue')\n\n/**\n * The rules cue the cinematic playing on some screens, or everyone's (see `cueCinematic`)\n *\n * @beta\n */\nexport const cinematicCued = engineEvent<WorldEvents['cinematicCued']>('cinematicCued')\n\n/**\n * A cinematic the rules played is over on a player's screen, as their screen said (see `cinematic`'s `wait`)\n *\n * @beta\n */\nexport const cinematicEnded = engineEvent<WorldEvents['cinematicEnded']>('cinematicEnded')\n\n/**\n * A player picked an answer of a cinematic's choice, as their screen said (see `cinematicChose`)\n *\n * @beta\n */\nexport const cinematicChoice = engineEvent<WorldEvents['cinematicChoice']>('cinematicChoice')\n\n/**\n * 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 *\n * @beta\n */\nexport const effectStarted = engineEvent<WorldEvents['effectStarted']>('effectStarted')\n\n/**\n * The rules stop an effect they played (see `world.stopEffect`)\n *\n * @beta\n */\nexport const effectStopped = engineEvent<WorldEvents['effectStopped']>('effectStopped')\n\n/**\n * One hidden in a layer of cells moved in it, or stepped into it (`ConcealmentOptions.rustle`): told to the teams\n * 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 * layer draws there\n *\n * @beta\n */\nexport const rustled = engineEvent<WorldEvents['rustled']>('rustled')\n\n/**\n * Cells of a layer (`Terrain.cells`) were set to a value (`setCells`): told to the players who see them, the others as\n * they come into sight (`cellsSeen`)\n *\n * @beta\n */\nexport const cellsChanged = engineEvent<WorldEvents['cellsChanged']>('cellsChanged')\n\n/**\n * A part of the ground was reshaped (`World.reshapeGround`): told to every player\n *\n * @beta\n */\nexport const groundReshaped = engineEvent<WorldEvents['groundReshaped']>('groundReshaped')\n\n/**\n * Cells of a layer that changed out of a team's sight came into it (`TeamMemory.cells`): told to that team's players\n *\n * @beta\n */\nexport const cellsSeen = engineEvent<WorldEvents['cellsSeen']>('cellsSeen')\n\n/** What the map looks like beyond its ground changed (`setEnvironment`): as it is now, told to every player */\n/** `over`: the seconds the screens ease into it over, where the rules said\n *\n * @beta\n */\nexport const environmentChanged = engineEvent<WorldEvents['environmentChanged']>('environmentChanged')\n","/**\n * What each team remembers of the map (`teamMemory`): kept in the world for a player who comes back and a game loaded\n * from a save, written by the sessions that show the map (`session/local.ts`), read by the debug tools and the\n * determinism check. Of nothing but components, so that what reads it loads nothing of a session\n */\nimport { defineComponent } from '#engine/components'\nimport type { EntityId } from '#engine/entity'\nimport type { EntityState } from './protocol'\n\n/**\n * What a team remembers of the map: enemy structures out of sight as they were last seen, and camps found empty\n *\n * @beta\n */\nexport interface TeamMemory {\n\t/** Structures out of sight, the way they looked when last seen, by id */\n\tstructures: Record<EntityId, EntityState>\n\t/** The camps the team has seen empty, by id */\n\tcleared: number[]\n\t/**\n\t * Whether what stands on a map explored from the start and is no player's (trees, mines, neutral buildings) has been\n\t * put among `structures`, as it stood when the team first looked (`FogOfWar.exploredFromStart`)\n\t *\n\t * @beta\n\t */\n\tstartKnown?: boolean\n\t/**\n\t * Cells of the game's layers the rules changed out of the team's sight (`world.setCells`), as the team last knew\n\t * them: by layer, the value by cell. Told as they are now when they come into sight (`cellsSeen`), and gone from here\n\t *\n\t * @beta\n\t */\n\tcells?: Record<string, Record<number, number>>\n}\n\n/**\n * What each team remembers of the map, by team. Kept in the world, not in a player's connection: a player who comes\n * back to their seat, or a game loaded from a save, remembers what was seen before. Plain data, for the save\n *\n * @internal\n */\nexport const teamMemory = defineComponent<Record<number, TeamMemory>>('core.memory', { default: () => ({}) })\n","/**\n * What a player is told of a world, written with what it tells of (design review E7): an event of the world becomes an\n * event on a player's screen by the rule beside the code that emits it (`replicateEvent`), and a part of the snapshot is\n * captured by the feature it is of (`SnapshotPart`). A seat (`LocalSession`) runs what its game has of them\n * (`Registry.replications`, `Registry.snapshotParts`: the engine's, then the packs'), for what its player may know\n * (`SessionView`)\n */\nimport type { Entity, PlayerId } from './entity'\nimport type { EventKey } from './events'\nimport type { SessionEvent, SessionEvents, Snapshot } from './session/protocol'\nimport type { World } from './world'\nimport { type TeamMemory, teamMemory } from './session/memory'\n\n/**\n * A seat's side of a world: whose it is, and what they may know of it now. What the rules that tell a player of the\n * world ask (`replicateEvent`, `SnapshotPart`, an event of a game's own's `replicate`), and what a seat keeps for them\n * (`keep`)\n *\n * @beta\n */\nexport class SessionView {\n\t/** Who only watches, and sees everything (`LocalSession.observer`) */\n\treadonly observer: boolean\n\t/** Whether the seat is a computer player's, which is told only what a brain reads (`LocalSession.forComputer`) */\n\treadonly forComputer: boolean\n\t/** How many effects of the rules are kept for their stop to be told (`LocalSession` options' `mostEffects`) */\n\treadonly mostEffects: number\n\t/** What the seat was told since its last snapshot, for the next one */\n\tevents: SessionEvent[] = []\n\tprivate readonly kept = new Map<object, unknown>()\n\n\tconstructor(\n\t\treadonly world: World,\n\t\t/** The seat's player: from whose side it sees, an observer's too */\n\t\treadonly player: PlayerId,\n\t\toptions: { observer?: boolean; forComputer?: boolean; mostEffects?: number } = {}\n\t) {\n\t\tthis.observer = options.observer ?? false\n\t\tthis.forComputer = options.forComputer ?? false\n\t\tthis.mostEffects = options.mostEffects ?? 1024\n\t}\n\n\t/** The player's team: theirs now, as the rules may move them to another (`setTeam`) */\n\tget team(): number {\n\t\treturn this.world.player(this.player).team\n\t}\n\n\t/** Whether an owner is the player or an ally of theirs: an observer's is everyone */\n\treadonly isAlly = (owner: PlayerId): boolean => this.observer || this.world.areAllies(owner, this.player)\n\n\t/** Whether the player's team sees a spot of the map right now: an observer sees all of it */\n\treadonly sees = (x: number, z: number): boolean => this.observer || this.world.fog.isVisible(this.team, x, z)\n\n\t/** Whether the player's team can see the entity right now: its side's always */\n\treadonly knows = (entity: Entity): boolean => this.isAlly(entity.owner) || (!entity.hidden && this.world.isVisibleTo(entity, this.team))\n\n\t/** An observer's own memory: it sees everything, which is no team's to remember */\n\tprivate readonly ownMemory: TeamMemory = { structures: {}, cleared: [] }\n\n\t/**\n\t * What the player's team remembers of what it saw (`teamMemory`: the structures out of sight as last seen, the camps\n\t * seen empty), or an observer's own. Looked up again each time: the player may have moved to another team since\n\t */\n\tget memory(): TeamMemory {\n\t\tif (this.observer) return this.ownMemory\n\t\tconst all = this.world.state(teamMemory)\n\t\treturn (all[this.team] ??= { structures: {}, cleared: [] })\n\t}\n\n\t/** What the seat keeps under a key for what tells it things (the effects it was shown, the score last told): made the first time */\n\tkeep<S>(key: object, make: () => S): S {\n\t\tlet kept = this.kept.get(key) as S | undefined\n\t\tif (kept === undefined) this.kept.set(key, (kept = make()))\n\t\treturn kept\n\t}\n\n\t/** Takes what the seat was told since the last snapshot */\n\ttakeEvents(): SessionEvent[] {\n\t\tconst events = this.events\n\t\tthis.events = []\n\t\treturn events\n\t}\n}\n\n/**\n * The event on a screen of a kind\n *\n * @beta\n */\nexport type SessionEventOf<K extends keyof SessionEvents> = SessionEvents[K]\n\n/**\n * How an event of the world is told to a player (`replicateEvent`): what the seat hears it as, and what it says of it\n * to the player, if anything\n *\n * @beta\n */\nexport interface ReplicatedEvent {\n\t/** The kind of event on the screen: a computer's seat hears only the kinds a brain reads (`COMPUTER_EVENTS`) */\n\treadonly as: SessionEvent['type']\n\t/** The world's event it tells of: one of the engine's (`engineEvents`) or a game's own (`defineEvent`) */\n\treadonly event: EventKey<unknown>\n\t/** What the player is told of it: nothing for what they may not know */\n\ttell(payload: unknown, view: SessionView): SessionEvent | undefined\n}\n\n/**\n * How an event of the world is told to a player, written beside what emits it: `replicateEvent(healed, 'heal', (heal,\n * view) => view.knows(heal.target) ? { type: 'heal', ... } : undefined)`. Listed by the engine for its own, by a pack in\n * `GamePack.replications`\n *\n * @beta\n */\nexport function replicateEvent<T, A extends keyof SessionEvents>(\n\tevent: EventKey<T>,\n\tas: A,\n\ttell: (payload: T, view: SessionView) => SessionEventOf<A> | undefined\n): ReplicatedEvent {\n\treturn { event: event as EventKey<unknown>, as, tell: tell as ReplicatedEvent['tell'] }\n}\n\n/**\n * A part of the snapshot a player is sent, captured by the feature it is of: the projectiles, the items on the\n * ground, the score. Before the entities (`head`) or after the players; left out of the snapshot where it gives\n * nothing (`undefined`). Listed by the engine for its own, by a pack in `GamePack.snapshotParts` (a key of its own\n * added to `Snapshot` by declaration merging)\n *\n * @beta\n */\nexport interface SnapshotPart<K extends keyof Snapshot = keyof Snapshot> {\n\treadonly key: K\n\t/** Before the entities and the players, where the tick's own facts are (the hour, the outcome) */\n\treadonly head?: boolean\n\tcapture(view: SessionView): Snapshot[K] | undefined\n}\n\n/**\n * A part of the snapshot, typed by its key\n *\n * @internal\n */\nexport function snapshotPart<K extends keyof Snapshot>(\n\tkey: K,\n\tcapture: (view: SessionView) => Snapshot[K] | undefined,\n\thead?: boolean\n): SnapshotPart {\n\treturn { key, capture, ...(head && { head }) } as SnapshotPart\n}\n\n/** What the seat was told since its last snapshot (`Snapshot.events`) */\nexport const eventsPart = snapshotPart('events', (view) => view.takeEvents())\n","/**\n * Effects landing: each of a list run by its handler (`registry.effect`), and the word to everyone that they did; and a\n * buff's own effects (`onApply`, `onTick`, `onEnd`) in the name of who put it there. What the effects (`effects.ts`)\n * and the buffs (`buffs.ts`) both do, each of them importing this and not the other: an effect puts a buff on, and a\n * buff runs effects\n */\nimport { abilityImpact } from '#engine/engineEvents'\nimport { type AbilityDef, at, type EffectDef } from '#engine/defs'\nimport type { BuffInstance, Entity } from '#engine/entity'\nimport type { World } from '#engine/world'\nimport type { EffectContext } from './effects'\nimport { replicateEvent } from '../replication'\n\n/** The widest of what a list of effects covers, for whoever draws it */\nconst reach = (effects: EffectDef[] | undefined, level: number) => (effects ?? []).reduce((max, effect) => Math.max(max, at(effect.radius, level)), 0)\n\n/** Runs each effect of a list by its handler (`registry.effect`) */\nexport function run(context: EffectContext, effects: EffectDef[] | undefined): void {\n\tfor (const effect of effects ?? []) context.world.registry.effect(effect.type)(context, effect)\n}\n\n/** What something an ability set off does where it arrives, and the word to everyone that it did */\nexport function land(context: EffectContext, effects: EffectDef[] | undefined, impact?: string): void {\n\tconst { world, caster, ability, level, target, point } = context\n\trun(context, effects)\n\tworld.events.emit(abilityImpact, { caster, ability, level, target, point, radius: reach(effects, level), impact })\n}\n\n/**\n * Effects of a buff on its carrier (`onApply`, `onTick`), in the name of who put it there, while they live: from the\n * ability it came from, or from the buff itself for one put on otherwise\n */\nexport function buffEffects(world: World, carrier: Entity, instance: BuffInstance, effects: EffectDef[]): void {\n\tconst source = world.get(instance.source)\n\tif (!source?.alive) return\n\tconst def = world.registry.buff(instance.id)\n\tconst ability =\n\t\tinstance.ability && world.registry.abilities.has(instance.ability)\n\t\t\t? world.registry.ability(instance.ability)\n\t\t\t: ({ id: instance.id, name: def.name, target: 'unit' } as AbilityDef)\n\tconst point = { x: carrier.pos.x, z: carrier.pos.z }\n\tland({ world, caster: source, ability, level: instance.level, target: carrier, point, stacks: instance.stacks ?? 0 }, effects)\n}\n\n/**\n * What a buff that ran out leaves behind: its `onEnd`, in the name of who put it there\n *\n * @beta\n */\nexport function buffEnded(world: World, carrier: Entity, instance: BuffInstance): void {\n\tconst def = world.registry.buff(instance.id)\n\tconst source = world.get(instance.source)\n\tif (!def.onEnd || !source?.alive || !instance.ability || !world.registry.abilities.has(instance.ability)) return\n\tconst ability = world.registry.ability(instance.ability)\n\tconst point = { x: carrier.pos.x, z: carrier.pos.z }\n\tland({ world, caster: source, ability, level: instance.level, target: carrier, point, stacks: instance.stacks ?? 0 }, def.onEnd)\n}\n\n/** Where a spell lands, to those who see the caster or the spot */\nexport const toldStrike = replicateEvent(abilityImpact, 'strike', ({ caster, ability, level, target, point, radius, impact }, view) => {\n\tif (!view.knows(caster) && !view.sees(point.x, point.z)) return undefined\n\treturn {\n\t\ttype: 'strike',\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\timpact\n\t}\n})\n","import {\n\ttype AbilityDef,\n\tanyEffect,\n\tat,\n\ttype BuffDef,\n\ttype EffectDef,\n\tinnerEffects,\n\ttype Scaled,\n\ttype Scaling,\n\ttype StatKey,\n\ttype Stats\n} from '#engine/defs'\n\n/*\n * What an ability says it does, worked out for the one who has it: \"deals 80 (50 + 60% ability power)\", not \"deals\n * 50/100/150 plus 60% of ability power\". Its description is a template with values in braces (`{damage}`), each worked\n * out from the caster's stats as they are now, the same way the simulation does it (`scaled`, `stats.ts`). The values\n * are the ability's own (`AbilityDef.values`), or found in its effects (`damage`, `heal`, `duration`...); and an ability\n * can say all of it in code instead (`AbilityDef.describe`).\n */\n\n/**\n * What the caster brings to an ability's numbers: its stats now, its level as a hero, and the attack damage of its own\n *\n * @beta\n */\nexport interface CasterFacts {\n\tstats: Readonly<Stats>\n\t/** 1 for what is not a hero */\n\theroLevel: number\n\t/** The attack damage it has from its type and its levels, without what it carries or what is on it */\n\townAttackDamage: number\n}\n\n/**\n * What the text of an ability is worked out from: the ability at a level, its caster, and the buffs it puts on\n *\n * @beta\n */\nexport interface AbilityTextContext {\n\tability: AbilityDef\n\t/** The level of the ability: 1 for one that has no levels */\n\tlevel: number\n\tcaster: CasterFacts\n\t/** A buff by id, for how long the ones the ability puts on last */\n\tbuff?: (id: string) => BuffDef | undefined\n\t/** A value of the ability, by name, worked out (see `abilityValues`) */\n\tvalue(name: string): AbilityValue | undefined\n}\n\n/**\n * A part of a value that comes from a stat of the caster: 60% of ability power\n *\n * @beta\n */\nexport interface ValuePart {\n\t/** The stat, `level` for each level of a hero past the first, `bonusAttackDamage` for what is added to its own */\n\tstat: StatKey | 'level' | 'bonusAttackDamage'\n\t/** How much of it: 0.6 */\n\tratio: number\n\t/** What that comes to now */\n\tamount: number\n}\n\n/**\n * A number of an ability, worked out: its total, and what it is made of\n *\n * @beta\n */\nexport interface AbilityValue {\n\ttotal: number\n\t/** What it is without the stats of the caster */\n\tbase: number\n\tparts: ValuePart[]\n\t/** What follows the number: `s` for seconds, `%`. Nothing when left out */\n\tunit?: string\n}\n\n/**\n * How a game gives a value of an ability: an amount and what scales it, or worked out in code\n *\n * @beta\n */\nexport type AbilityValueDef =\n\t{ amount?: Scaled; scaling?: Scaling; unit?: string; percent?: boolean } | ((context: AbilityTextContext) => number | AbilityValue)\n\n/**\n * A piece of the text of an ability: words, or a value to show as one (bold, its parts in their colours)\n *\n * @beta\n */\nexport type TextSegment = string | { name: string; value: AbilityValue }\n\n/**\n * An amount with what the stats of the caster add to it, and the parts that come from each: the same arithmetic as\n * the simulation (`scaled`)\n *\n * @internal\n */\nexport function scaledParts(amount: number, scaling: Scaling | undefined, level: number, caster: CasterFacts): AbilityValue {\n\tconst parts: ValuePart[] = []\n\tlet total = amount\n\tif (scaling) {\n\t\tfor (const key in scaling) {\n\t\t\tconst stat = key as ValuePart['stat']\n\t\t\tconst ratio = at(scaling[stat], level)\n\t\t\tif (!ratio) continue\n\t\t\tconst of =\n\t\t\t\tstat === 'level'\n\t\t\t\t\t? caster.heroLevel - 1\n\t\t\t\t\t: stat === 'bonusAttackDamage'\n\t\t\t\t\t\t? Math.max(caster.stats.attackDamage - caster.ownAttackDamage, 0)\n\t\t\t\t\t\t: caster.stats[stat]\n\t\t\tconst part = of * ratio\n\t\t\ttotal += part\n\t\t\tparts.push({ stat, ratio, amount: part })\n\t\t}\n\t}\n\treturn { total, base: amount, parts }\n}\n\n/** The effects of an ability, those inside others (a missile's, a delay's) too, in order */\nfunction* allEffects(effects: readonly EffectDef[] | undefined): Iterable<EffectDef> {\n\tfor (const effect of effects ?? []) {\n\t\tyield effect\n\t\tyield* allEffects(innerEffects(effect))\n\t}\n}\n\n/**\n * The values of an ability at a level, for a caster, by name: its own (`AbilityDef.values`), and what its effects say\n * when it does not name them itself: `damage`, `heal`, `shield` and `amount` (the first effect of each kind with an\n * amount), `duration`, `radius`, `range`, `cooldown`, `charges` and `refill`, `mana`, `count` and `distance`\n *\n * @beta\n */\nexport function abilityValues(\n\tability: AbilityDef,\n\tlevel: number,\n\tcaster: CasterFacts,\n\tbuff?: (id: string) => BuffDef | undefined\n): Map<string, AbilityValue> {\n\tconst values = new Map<string, AbilityValue>()\n\tconst context: AbilityTextContext = { ability, level, caster, buff, value: (name) => values.get(name) }\n\tconst plain = (total: number, unit?: string): AbilityValue => ({ total, base: total, parts: [], unit })\n\tconst found = (name: string, value: AbilityValue | undefined) => {\n\t\tif (value && !values.has(name)) values.set(name, value)\n\t}\n\n\t// what the effects say, first\n\tfor (const effect of [...allEffects([...ability.effects, ...(ability.passive ?? [])])].map(anyEffect)) {\n\t\tif (effect.amount !== undefined || effect.scaling) {\n\t\t\tconst value = scaledParts(at(effect.amount, level), effect.scaling, level, caster)\n\t\t\tif (effect.type === 'damage' || effect.type === 'heal') found(effect.type, value)\n\t\t\tfound('amount', value)\n\t\t}\n\t\tif (effect.duration !== undefined) found('duration', plain(at(effect.duration, level), 's'))\n\t\telse if (effect.buff && buff) {\n\t\t\tconst lasting = buff(effect.buff)?.duration\n\t\t\tif (lasting !== undefined) found('duration', plain(at(lasting as Scaled, level), 's'))\n\t\t}\n\t\tconst radius = (effect as { radius?: Scaled }).radius\n\t\tif (radius !== undefined) found('radius', plain(at(radius, level)))\n\t\tif (effect.count !== undefined) found('count', plain(at(effect.count, level)))\n\t\tif (effect.distance !== undefined) found('distance', plain(at(effect.distance, level)))\n\t}\n\tif (ability.range !== undefined) found('range', plain(at(ability.range, level)))\n\tif (ability.cooldown !== undefined) found('cooldown', plain(at(ability.cooldown, level), 's'))\n\tif (ability.charges) {\n\t\tfound('charges', plain(at(ability.charges.count, level)))\n\t\tfound('refill', plain(at(ability.charges.refill, level), 's'))\n\t}\n\tif (ability.manaCost !== undefined) found('mana', plain(at(ability.manaCost, level)))\n\n\t// the ability's own, over what was found: in the order given, so one may use another\n\tfor (const [name, def] of Object.entries(ability.values ?? {})) {\n\t\tlet value: AbilityValue\n\t\tif (typeof def === 'function') {\n\t\t\tconst made = def(context)\n\t\t\tvalue = typeof made === 'number' ? plain(made) : made\n\t\t} else {\n\t\t\tvalue = scaledParts(at(def.amount, level), def.scaling, level, caster)\n\t\t\tif (def.percent) {\n\t\t\t\tvalue = {\n\t\t\t\t\ttotal: value.total * 100,\n\t\t\t\t\tbase: value.base * 100,\n\t\t\t\t\tparts: value.parts.map((part) => ({ ...part, ratio: part.ratio * 100, amount: part.amount * 100 }))\n\t\t\t\t}\n\t\t\t\tvalue.unit = '%'\n\t\t\t}\n\t\t\tif (def.unit) value.unit = def.unit\n\t\t}\n\t\tvalues.set(name, value)\n\t}\n\treturn values\n}\n\n/**\n * What the ability says it does, for this caster now: its description with each `{value}` worked out (or its own\n * `describe`), as words and values. A name it has no value for is left as it is written, braces and all\n *\n * @beta\n */\nexport function describeAbility(ability: AbilityDef, level: number, caster: CasterFacts, buff?: (id: string) => BuffDef | undefined): TextSegment[] {\n\tconst values = abilityValues(ability, level, caster, buff)\n\tconst context: AbilityTextContext = { ability, level, caster, buff, value: (name) => values.get(name) }\n\tconst said = ability.describe ? ability.describe(context) : (ability.description ?? '')\n\tif (typeof said !== 'string') return said\n\tconst segments: TextSegment[] = []\n\tlet from = 0\n\tfor (const match of said.matchAll(/\\{([a-zA-Z][\\w.]*)\\}/g)) {\n\t\tconst value = values.get(match[1])\n\t\tif (!value) continue\n\t\tif (match.index > from) segments.push(said.slice(from, match.index))\n\t\tsegments.push({ name: match[1], value })\n\t\tfrom = match.index + match[0].length\n\t}\n\tif (from < said.length) segments.push(said.slice(from))\n\treturn segments\n}\n\n/**\n * How a stat is called in the text of an ability\n *\n * @beta\n */\nexport const STAT_WORDS: Partial<Record<ValuePart['stat'], string>> = {\n\tabilityPower: 'ability power',\n\tattackDamage: 'attack damage',\n\tbonusAttackDamage: 'bonus attack damage',\n\thealth: 'max health',\n\tmana: 'max mana',\n\tarmor: 'armor',\n\tmagicResist: 'magic resist',\n\tmoveSpeed: 'move speed',\n\tattackSpeed: 'attack speed',\n\tlevel: 'per level'\n}\n\n/**\n * A number as an ability's text shows it: whole, or with one decimal when it is small and has one\n *\n * @beta\n */\nexport function formatNumber(value: number): string {\n\tconst rounded = Math.abs(value) < 10 ? Math.round(value * 10) / 10 : Math.round(value)\n\treturn String(rounded)\n}\n\n/**\n * A value in words: `80`, or `80 (50 + 60% ability power)` when stats add to it\n *\n * @beta\n */\nexport function valueText(value: AbilityValue): string {\n\tconst total = `${formatNumber(value.total)}${value.unit ?? ''}`\n\tif (value.parts.length === 0) return total\n\tconst parts = value.parts.map((part) =>\n\t\tpart.stat === 'level' ? `${formatNumber(part.ratio)} per level` : `${formatNumber(part.ratio * 100)}% ${STAT_WORDS[part.stat] ?? part.stat}`\n\t)\n\t// nothing of its own: all of it comes from the stats\n\treturn `${total} (${[...(value.base ? [formatNumber(value.base)] : []), ...parts].join(' + ')})`\n}\n\n/**\n * The text of an ability as plain words: for a tooltip of words only, a log, a test\n *\n * @beta\n */\nexport function abilityText(segments: readonly TextSegment[]): string {\n\treturn segments.map((segment) => (typeof segment === 'string' ? segment : valueText(segment.value))).join('')\n}\n","import { constructionCancelled, constructionFinished, constructionStarted, worked } from '#engine/engineEvents'\nimport { defineComponent, snapshotOf } from '#engine/components'\nimport { constructionOf } from '#engine/defs'\nimport type { ConstructionState, Entity } from '#engine/entity'\nimport type { EntityState } from '#engine/session/protocol'\nimport type { System } from '#engine/registry'\nimport { replicateEvent } from '../replication'\n\n/** Whether two parts done of a whole say the same to a screen: to a hundredth, what a bar shows and the wire sends */\nexport const sameHundredth = (a: number, b: number) => Math.round(a * 100) === Math.round(b * 100)\n\n/**\n * A structure being built: how far it is, how long it takes, who works on it (`UnitTypeDef.construction`). Set as a\n * site is put down (`SpawnOptions.underConstruction`), taken off once it stands; a structure's only (a unit given it is\n * not seen as one). Everyone who sees it is told how far it is (0..1)\n *\n * @beta\n */\nexport const constructionSite = defineComponent<ConstructionState, number>('core.construction', {\n\treplicate: 'everyone',\n\tsnapshot: (site) => site.progress,\n\t// a delta sent for every hundredth, not every tick\n\tsame: sameHundredth\n})\n\n/**\n * What a structure being built has done and needs: none once it stands, or for what was put down whole (`constructionSite`)\n *\n * @beta\n */\nexport const underConstruction = (entity: Entity): ConstructionState | undefined => entity.get(constructionSite)\n\n/**\n * How far a structure in a snapshot is built, 0..1: undefined for one that stands (a screen's, a computer player's view)\n *\n * @beta\n */\nexport const builtSoFar = (state: EntityState): number | undefined => snapshotOf(state, constructionSite)\n\nexport const constructionSystem: System = {\n\tname: 'construction',\n\tphase: 'resolve',\n\t// only the sites: not every unit and building of the map (OB5)\n\tover: constructionSite,\n\teach(world, entity, dt) {\n\t\tconst site = entity.isStructure ? underConstruction(entity) : undefined\n\t\tif (!site || !entity.alive) return\n\t\t// what goes up on its own does so as with one builder at it\n\t\tif (constructionOf(entity.def) === 'self') site.builders = 1\n\t\tif (site.builders > 0) {\n\t\t\tconst { buildRate } = entity.def\n\t\t\tconst rate = buildRate ? buildRate(site.builders, world, entity) : world.rules.production.buildRate(world, entity, site.builders)\n\t\t\tconst step = Math.min((dt * rate) / site.buildTime, 1 - site.progress)\n\t\t\tsite.progress += step\n\t\t\t// sites start with a part of their health (`GameRules.production.constructionHealth`) and gain the rest while being built\n\t\t\tentity.hp = Math.min(entity.hp + step * entity.maxHp * (1 - world.rules.production.constructionHealth), entity.maxHp)\n\t\t\tsite.builders = 0\n\t\t}\n\t\tif (site.progress >= 1 - 1e-9) {\n\t\t\t// what adding up the steps fell short of by rounding: a site nobody hurt is whole when it is done\n\t\t\tif (entity.maxHp - entity.hp < 1e-6 * entity.maxHp) entity.hp = entity.maxHp\n\t\t\tentity.remove(constructionSite)\n\t\t\tworld.events.emit(constructionFinished, entity)\n\t\t}\n\t}\n}\n\n/** A structure begun, to those who see it: with how long it takes */\nexport const toldConstructionStarted = replicateEvent(constructionStarted, 'constructionStarted', (entity, view) =>\n\tview.knows(entity) ? { type: 'constructionStarted', id: entity.id, buildTime: underConstruction(entity)?.buildTime ?? 0 } : undefined\n)\n\n/** A structure finished, to those who see it */\nexport const toldBuilt = replicateEvent(constructionFinished, 'built', (entity, view) =>\n\tview.knows(entity) ? { type: 'built', id: entity.id } : undefined\n)\n\n/** A structure called off while being built, to those who see it */\nexport const toldConstructionCancelled = replicateEvent(constructionCancelled, 'constructionCancelled', (entity, view) =>\n\tview.knows(entity) ? { type: 'constructionCancelled', id: entity.id } : undefined\n)\n\n/** A blow of a builder's hammer, to those who see the builder */\nexport const toldWork = replicateEvent(worked, 'work', ({ worker }, view) => (view.knows(worker) ? { type: 'work', id: worker.id } : undefined))\n","import { type Cost, type EffectDef, type ResourceKind, type UnitTypeDef } from './defs'\nimport { type Component, defineComponent } from './components'\n// (read as a structure asks whether it stands, never as the modules load: the systems' module comes round to this one)\nimport { constructionSite } from './systems/construction'\nimport type { Rect, Vec2 } from './math'\nimport type { StatsCache } from './stats'\nimport type { OrderParams } from './registry'\n\n/** @beta */\nexport type EntityId = number\n/** @beta */\nexport type PlayerId = number\n\n/**\n * An order a unit carries out or has queued. `State` is what its behaviour keeps in it (`OrderBehavior<State>`): empty\n * as the order is given, so every field of it is one that may not be there yet\n *\n * @beta\n */\nexport interface Order<State extends object = Record<string, any>, Init extends object = OrderParams> {\n\tid: number\n\ttype: string\n\t/** What it was given, as its type takes it (`OrderInits`): plain data, saved with the order */\n\tinit: Init\n\t/** Shared by every unit that received the order from the same command */\n\tgroupId: number\n\tstarted: boolean\n\t/** Scratch space owned by the order behavior: plain data, saved with the order */\n\tstate: State\n}\n\n/** @beta */\nexport interface AbilityState {\n\tid: string\n\t/** 0 for an ability a hero has not learned yet */\n\tlevel: number\n\t/** Seconds until it can be used again */\n\tcooldown: number\n\t/**\n\t * Uses left, of an ability with charges (`AbilityDef.charges`): all it holds when left out, and `chargesLeft` says\n\t * how many that is. Set while it holds fewer\n\t */\n\tcharges?: number\n\t/** Seconds until the next use is back, while it holds fewer than it can */\n\trefill?: number\n\tautocast: boolean\n\t/** Where it was last aimed */\n\tpoint?: Vec2\n}\n\n/** @beta */\nexport interface BuffInstance {\n\tid: string\n\t/** Level of the ability it came from */\n\tlevel: number\n\t/** Seconds left. Infinity for buffs that stay */\n\tremaining: number\n\telapsed: number\n\t/** Entity that put it there */\n\tsource: EntityId\n\t/** What is left of the shield it gives */\n\tshield?: number\n\t/** How many of it there are, for buffs that pile up */\n\tstacks?: number\n\t/** The ability it came from, for buffs that do something when their time is up */\n\tability?: string\n\t/**\n\t * Kept up by an ability of its source's for as long as it holds (a passive's buff, an aura's): put on again every\n\t * round for a moment, with no time of its own to show (`EntityState.buffTimes` says -1)\n\t */\n\tkept?: boolean\n\t/** State of the game's own about this one buff: a counter, what it has done so far. Plain data: it is saved */\n\tdata?: Record<string, unknown>\n}\n\n/**\n * An item someone carries\n *\n * @beta\n */\nexport interface ItemInstance {\n\tid: number\n\titem: string\n\t/** Uses left, for items that run out */\n\tcharges: number\n\t/** Cooldown of the ability the item gives */\n\tstate?: AbilityState\n\t/** State of the game's own about this one item: kills it has seen, what it has stored. Plain data: it is saved */\n\tdata?: Record<string, unknown>\n}\n\n/**\n * What a shop has of one of its wares (`shopStock`, a component of the entity's)\n *\n * @beta\n */\nexport interface StockState {\n\titem: string\n\tcount: number\n\t/** Seconds until the next one arrives */\n\trestock: number\n}\n\n/** @beta */\nexport type MoveStatus = 'idle' | 'moving' | 'arrived' | 'failed'\n\n/** @beta */\nexport interface MovementState {\n\tspeed: number\n\t/** The fastest it goes for now, whatever its speed: a group's slowest, as it moves together (`OrderParams.together`) */\n\tcap?: number\n\tstatus: MoveStatus\n\tgoal: Vec2\n\t/** When set the goal follows this entity */\n\tgoalEntity: EntityId\n\t/** Arrive once this close to the goal (edge distance for entity goals) */\n\trange: number\n\tgroupId: number\n\t/** Last destination handed to the navigation */\n\tnavGoal: Vec2\n\tnavVersion: number\n\t/** Corner of the path the unit is heading for. Progress is measured towards it, so a long way round is not mistaken for standing still */\n\tcorner: Vec2\n\t/** Closest the unit has been to its corner, used to detect that it stopped making progress */\n\tbestDistance: number\n\tstalledTime: number\n\t/**\n\t * Seconds it has gone well under its speed on its way, held up by others (not counting getting going, or slowing\n\t * to arrive): what has those in its way asked to step aside (see `GameRules.movement.lookAhead`)\n\t */\n\tslowTime?: number\n\t/**\n\t * The point it goes round standing units by, on its way to the next corner of its path, when that is not much\n\t * longer (`GameRules.movement.goesAround`, the `detour` hook): none while it goes straight\n\t */\n\tdetour?: Vec2\n\t/** Where it heads on from `detour`: the corner of its path it went round the knot towards */\n\tdetourAim?: Vec2\n\t/** On a step aside for another (`MoveOptions.aside`): it goes round nobody and asks nobody to make way */\n\taside?: boolean\n\t/** Whether it was sent on past `detour`, towards its path, as it neared it */\n\tdetourPast?: boolean\n\t/** Whether the last move failed by getting stuck on the way (in a crowd, say), not for there being no way there */\n\tstuck?: boolean\n\tanchored: boolean\n\tghost: boolean\n\t/** Direction the unit turns to while it stands still. Null when it may face wherever it ended up */\n\tfinalFacing: number | null\n\t/**\n\t * The route its side planned to the goal, corner by corner, with what the side knows (`GameModule.paths: 'seen'`):\n\t * walked a stretch at a time. None where routes know everything, or there is no route\n\t */\n\troute?: Vec2[]\n\t/** The corner of `route` it heads past next */\n\trouteAt?: number\n\t/** What its side knew when the route was planned (`SidePaths.version`): it is planned again once that changes */\n\trouteVersion?: number\n\t/** Where along `route` the navigation was last sent it: a stretch no longer than it can see */\n\tstretch?: Vec2\n}\n\n/**\n * What moves of an entity: where it goes, how fast, how it is doing (`MovementState`). Units that walk, swim or fly\n * have it from their type's speed; a building, a tree, or a unit an upgrade stopped has none. Filed (`index`), for the\n * movement system to go through\n *\n * @beta\n */\nexport const moving = defineComponent<MovementState>('core.moving', { index: true })\n\n/** @beta */\nexport interface CombatState {\n\t/** Seconds until the next attack may start */\n\tcooldown: number\n\t/** Seconds until the running swing lands. 0 when not swinging */\n\tswing: number\n\tswingTarget: EntityId\n\t/**\n\t * Which of its attacks the running swing, or the last, is of, by place (`UnitTypeDef.attacks`): the first when left\n\t * out, as for every unit with one. It swings one at a time, and waits out the cooldown of the one that hit\n\t */\n\tweapon?: number\n\t/** Target picked by the unit itself rather than by an order */\n\tautoTarget: EntityId\n\tlastAttacker: EntityId\n\t/** Where an idle unit returns to after chasing */\n\tguard: Vec2 | null\n\t/** Does not pick fights of its own accord until it gets an order (set by a game's rules; `stop` no longer sets it) */\n\tpassive: boolean\n\t/** What it is fighting or closing in on, whoever picked it: 0 for nothing (see `engagement.ts`) */\n\tengaged?: EntityId\n\t/** The spot it holds around that, as an angle seen from it. Null when it has none: it flies, it hits a building */\n\tslot?: number | null\n\t/** Targets it left alone because it could not get at them, and until when, in world time */\n\tshunned?: [EntityId, number][]\n}\n\n/**\n * How an entity fights (`CombatState`): its cooldown, its swing, what it is engaged with. What attacks has it from its\n * type's attack; an upgrade that takes the attack away takes it. Filed (`index`), for the combat system to go through\n *\n * @beta\n */\nexport const fighting = defineComponent<CombatState>('core.fighting', { index: true })\n\n/** @beta */\nexport interface HarvesterState {\n\tcarrying: number\n\t/** What it is that the worker carries, or last gathered. Null for one that has not gathered anything yet */\n\tkind: ResourceKind | null\n\t/** Last resource this worker gathered from */\n\tresource: EntityId\n}\n\n/** @beta */\nexport interface ResourceState {\n\tamount: number\n\toccupants: number\n\t/** The building that stands on it (`UnitTypeDef.builtOn`), by id: none when nothing does */\n\tunder?: EntityId\n}\n\n/**\n * What is left of what can be gathered from an entity, and who is at it (`ResourceState`): a mine's gold, a tree's\n * lumber. What its type gives (`UnitTypeDef.resource`) as it is made. Filed (`index`), for what looks for the nearest\n *\n * @beta\n */\nexport const deposit = defineComponent<ResourceState>('core.deposit', { index: true })\n\n/** @beta */\nexport interface ConstructionState {\n\t/** 0..1 */\n\tprogress: number\n\tbuildTime: number\n\t/** Builders that worked on it during the current tick */\n\tbuilders: number\n\t/** What was paid for it, when that is not what its type costs. A cancelled site gives part of this back */\n\tpaid?: Cost\n}\n\n/** @beta */\nexport interface ProductionItem {\n\tkind: 'unit' | 'upgrade' | 'revive' | 'morph'\n\t/** Unit type, upgrade id, the id of the hero to bring back, or the type the building turns into */\n\tid: string\n\t/** What was paid, when that does not follow from the id */\n\tpaid?: Cost\n\t/** Seconds of work done */\n\tprogress: number\n\tduration: number\n}\n\n/** Seconds by team, kept in a save as its entries: what `exposure` and `detection` are */\nconst byTeam = { save: (value: Map<number, number>) => [...value], load: (saved: unknown) => new Map(saved as [number, number][]) }\n\n/**\n * Seconds an entity stays in sight of other teams, by team, for having attacked them: seen where it stands, in the fog\n * and in a bush. Filed (`index`), for the fog to light those that have it\n *\n * @beta\n */\nexport const exposure = defineComponent<Map<number, number>>('core.exposure', { index: true, ...byTeam })\n\n/**\n * Seconds the teams that found an invisible entity with something that reveals it can go on seeing it, by team. Filed\n * (`index`), for the fog to light those that have it\n *\n * @beta\n */\nexport const detection = defineComponent<Map<number, number>>('core.detection', { index: true, ...byTeam })\n\n/**\n * A rush to a spot: nothing stops it, and what it does happens where it ends\n *\n * @beta\n */\nexport interface Dash {\n\tx: number\n\tz: number\n\t/** Where it started */\n\tfrom: Vec2\n\t/** Units per second */\n\tspeed: number\n\tability: string\n\tlevel: number\n\teffects: EffectDef[]\n\t/** How high it rises on the way: a leap, over whatever is in between */\n\theight?: number\n\t/** A buff it carries for as long as the rush lasts */\n\tbuff?: string\n}\n\n/** @beta */\nexport interface RallyPoint {\n\tpoint: Vec2\n\ttarget: EntityId\n}\n\n/** @beta */\nexport interface ProductionState {\n\tqueue: ProductionItem[]\n\trally: RallyPoint | null\n}\n\n/**\n * Anything in the world: a unit, a building, a tree.\n *\n * Fields marked `readonly` are kept in step with things elsewhere (the navigation, the spatial index, the lookups\n * of the world), so they are changed through the world's functions only: `World.setOwner`, `World.setHidden`,\n * `World.setLifetime`, `World.place`, `startDash`, `morph` (each through the entity's own internal writes: `moveTo`,\n * `retype`, `changeOwner`…). The rest, like health, mana or cooldowns, a game\n * module may change as it likes: nothing is worked out from them that would not notice.\n *\n * @beta\n */\nexport class Entity {\n\treadonly alive: boolean = true\n\t/** Hidden entities are inside something (a gold mine) and do not take part in the world */\n\treadonly hidden: boolean = false\n\t/**\n\t * Only stands there, like a tree: left out of the systems that run every tick, see `isScenery`.\n\t * Becomes false for good once something gives it anything to do (`World.wake`)\n\t */\n\treadonly scenery: boolean = false\n\n\treadonly pos: Readonly<Vec2>\n\treadonly prevPos: Vec2\n\tfacing = 0\n\tprevFacing = 0\n\t/** How big it is drawn, for the look of a map. Nothing in the rules goes by it */\n\tscale = 1\n\t/** Which of the models of its type it is drawn with, for the look of a map. Nothing in the rules goes by it either */\n\tlook?: string\n\t/** Velocity of the last tick */\n\treadonly velocity: Vec2 = { x: 0, z: 0 }\n\n\thp: number\n\t/** Teams that have seen this entity at least once, one bit per team as `FogOfWar.teamBit` hands them out. Ask `World.hasSeen` */\n\tseenBy = 0\n\t/** When it was last hurt, in seconds of the game. Long ago for what never was */\n\thurtAt = -Infinity\n\t/** Seconds until it is gone by itself, for what does not last */\n\treadonly expires: number | null = null\n\t/** Seconds it was given to last, for what does not */\n\tlifetime = 0\n\t/** Seconds until enemies cannot see it any more, for what is invisible. 0 once they cannot */\n\tunseenIn: number | null = null\n\n\t/**\n\t * What it was told to do, the first what it does now and the rest in turn: read here, given and ended through the\n\t * orders' functions (`giveOrder`, `clearOrders`, `completeOrder`), which write it with the entity's own `addOrder`,\n\t * `keepOrders` and `removeOrder`\n\t */\n\treadonly orders: readonly Order[] = []\n\n\t/** Invisible to enemies right now, unless they have found it */\n\tget unseen(): boolean {\n\t\treturn this.unseenIn === 0\n\t}\n\n\tmaxHp: number\n\tmana = 0\n\tmaxMana: number\n\t/** Does nothing by itself until something wakes it, and is drawn sleeping: creeps at night */\n\tasleep = false\n\t/** A fallen hero that is on its way back */\n\treviving = false\n\t/**\n\t * What it can cast, with their levels and cooldowns: each state is the game's to change (`cooldown`, `autocast`),\n\t * the list the engine's (a type's own, what a hero learns), written with the entity's own internal methods\n\t */\n\treadonly abilities: readonly AbilityState[] = []\n\t/** What is on it: each instance the game's to change, the list put on and taken off by `applyBuff`, `removeBuff` */\n\treadonly buffs: readonly BuffInstance[] = []\n\n\t/** The resource it stands on (`UnitTypeDef.builtOn`), by id: none for what stands on the ground */\n\ton?: EntityId\n\t/** Min corner of the footprint in grid cells, for buildings and resources */\n\tcell?: { x: number; z: number }\n\n\t/** Bookkeeping of the spatial index: the last query that found it. Not game state */\n\tspatialStamp = 0\n\t/** Stats as last worked out, see `statsOf`. Derived from the rest, never saved or sent */\n\tstatsCache: StatsCache | null = null\n\n\t/**\n\t * State of game modules and mods by each component's number (`Component.slot`): the one store of it (design review\n\t * E4), for `get` and `has` one load from a list. Plain data, which goes into a save (by id: `components`)\n\t *\n\t * @internal\n\t */\n\tslots: unknown[] = []\n\t/**\n\t * Its components, in the order it was given them: the order a save, a snapshot and the index go through them in,\n\t * so that a world hashes and saves the same whatever numbers its process gave its components\n\t *\n\t * @internal\n\t */\n\treadonly held: Component<unknown, unknown>[] = []\n\t/** The index of the world it is in, told when it gets or loses a component. Not game state */\n\tindex: { componentChanged(entity: Entity, id: string, has: boolean): void } | null = null\n\n\tconstructor(\n\t\treadonly id: EntityId,\n\t\t/** Changes when a building is upgraded into another type */\n\t\treadonly def: UnitTypeDef,\n\t\treadonly owner: PlayerId,\n\t\tposition: Vec2\n\t) {\n\t\tthis.pos = { x: position.x, z: position.z }\n\t\tthis.prevPos = { x: position.x, z: position.z }\n\t\t// what its type starts with: no game rule changes health or mana\n\t\tthis.hp = this.maxHp = def.stats.health\n\t\tthis.maxMana = def.stats.mana ?? 0\n\t}\n\n\t/**\n\t * The engine's writes of what is read-only to everyone else, each kept in step by the world's function that calls it\n\t * (`World.place`, `World.setOwner`, `World.setHidden`, `World.setLifetime`, `morph`, a death, a hero brought back).\n\t * A game changes these through those functions, never here\n\t *\n\t * @internal\n\t */\n\tmoveTo(x: number, z: number): void {\n\t\tconst pos = this.pos as Vec2\n\t\tpos.x = x\n\t\tpos.z = z\n\t}\n\n\t/** @internal See `moveTo`: its type, which a building's upgrade or a morph changes */\n\tretype(def: UnitTypeDef): void {\n\t\t;(this as { def: UnitTypeDef }).def = def\n\t}\n\n\t/** @internal See `moveTo`: whose it is (`World.setOwner`) */\n\tchangeOwner(owner: PlayerId): void {\n\t\t;(this as { owner: PlayerId }).owner = owner\n\t}\n\n\t/** @internal See `moveTo`: whether it is in the world (a death, a hero brought back) */\n\tsetAlive(alive: boolean): void {\n\t\t;(this as { alive: boolean }).alive = alive\n\t}\n\n\t/** @internal See `moveTo`: whether it is inside something (`World.setHidden`) */\n\tsetInside(hidden: boolean): void {\n\t\t;(this as { hidden: boolean }).hidden = hidden\n\t}\n\n\t/** @internal See `moveTo`: whether it only stands there (`isScenery`, `World.wake`) */\n\tsetScenery(scenery: boolean): void {\n\t\t;(this as { scenery: boolean }).scenery = scenery\n\t}\n\n\t/** @internal See `moveTo`: seconds until it is gone by itself, none for what lasts (`World.setLifetime`). Gives them back */\n\texpireIn(seconds: number | null): number | null {\n\t\treturn ((this as { expires: number | null }).expires = seconds)\n\t}\n\n\t/** @internal See `moveTo`: an order put at the end of its queue */\n\taddOrder(order: Order): void {\n\t\t;(this.orders as Order[]).push(order)\n\t}\n\n\t/** @internal See `moveTo`: its queue cut to its first `count` orders, none when left out */\n\tkeepOrders(count = 0): void {\n\t\t;(this.orders as Order[]).length = Math.min(count, this.orders.length)\n\t}\n\n\t/** @internal See `moveTo`: an order out of its queue, wherever it is: whether it was there */\n\tremoveOrder(order: Order): boolean {\n\t\tconst at = this.orders.indexOf(order)\n\t\tif (at >= 0) (this.orders as Order[]).splice(at, 1)\n\t\treturn at >= 0\n\t}\n\n\t/** @internal See `moveTo`: what it can cast, all of it (a morph, an upgrade) */\n\tsetAbilities(abilities: AbilityState[]): void {\n\t\t;(this as { abilities: readonly AbilityState[] }).abilities = abilities\n\t}\n\n\t/** @internal See `moveTo`: one more it can cast (a hero learning one) */\n\taddAbility(ability: AbilityState): void {\n\t\t;(this.abilities as AbilityState[]).push(ability)\n\t}\n\n\t/** @internal See `moveTo`: a buff put on (`applyBuff`) */\n\taddBuff(buff: BuffInstance): void {\n\t\t;(this.buffs as BuffInstance[]).push(buff)\n\t}\n\n\t/** @internal See `moveTo`: the buff at an index taken off (`removeBuff`, one run out): it, if there was one */\n\tdropBuff(index: number): BuffInstance | undefined {\n\t\treturn (this.buffs as BuffInstance[]).splice(index, 1)[0]\n\t}\n\n\t/** @internal See `moveTo`: every buff off at once (a death, a hero brought back) */\n\tclearBuffs(): void {\n\t\t;(this.buffs as BuffInstance[]).length = 0\n\t}\n\n\t/** @internal See `moveTo`: a field a save kept (`ENTITY_SAVE`), as a save is loaded */\n\trestore(field: string, value: unknown): void {\n\t\t;(this as unknown as Record<string, unknown>)[field] = value\n\t}\n\n\t/** A component of a game module or a mod, see `defineComponent` */\n\tget<T>(key: Component<T, unknown>): T | undefined {\n\t\treturn this.slots[key.slot] as T | undefined\n\t}\n\n\thas(key: Component<unknown>): boolean {\n\t\treturn this.slots[key.slot] !== undefined\n\t}\n\n\t/** Gives it the component, or a new value of it. `undefined` takes it away (`remove`) */\n\tset<T>(key: Component<T, unknown>, value: T): void {\n\t\tif (value === undefined) return this.remove(key)\n\t\tconst had = this.slots[key.slot] !== undefined\n\t\tthis.slots[key.slot] = value\n\t\tif (had) return\n\t\tthis.held.push(key as Component<unknown, unknown>)\n\t\tthis.index?.componentChanged(this, key.id, true)\n\t}\n\n\tremove(key: Component<unknown>): void {\n\t\tif (this.slots[key.slot] === undefined) return\n\t\tthis.slots[key.slot] = undefined\n\t\t// by its number: a module loaded again (a dev server's) defines another object of the same component\n\t\tthis.held.splice(\n\t\t\tthis.held.findIndex((each) => each.slot === key.slot),\n\t\t\t1\n\t\t)\n\t\tthis.index?.componentChanged(this, key.id, false)\n\t}\n\n\t/** Its components, in the order it was given them: each one's value is `get(component)` */\n\theldComponents(): readonly Component<unknown, unknown>[] {\n\t\treturn this.held\n\t}\n\n\t/**\n\t * Its components' values by id, in the order it was given them: made each time it is asked, for what reads them\n\t * by id now and then (a save, the inspector). What does it often goes through `heldComponents`\n\t */\n\tget components(): Readonly<Record<string, unknown>> {\n\t\tconst values: Record<string, unknown> = {}\n\t\tfor (const component of this.held) values[component.id] = this.slots[component.slot]\n\t\treturn values\n\t}\n\n\tget isBuilding() {\n\t\treturn this.def.kind === 'building'\n\t}\n\n\tget isUnit() {\n\t\treturn this.def.kind === 'unit'\n\t}\n\n\tget isResource() {\n\t\treturn this.def.kind === 'resource'\n\t}\n\n\t/** Up in the air, where the ground and what stands on it are not in the way */\n\tget flying() {\n\t\treturn this.def.flying === true\n\t}\n\n\tget isStructure() {\n\t\treturn this.def.kind !== 'unit'\n\t}\n\n\t/** Completed and able to do its job */\n\tget operational() {\n\t\t// (a site is a structure's, and what moves is most of what asks)\n\t\tif (!this.alive) return false\n\t\tif (this.def.kind === 'unit') return true\n\t\treturn this.slots[constructionSite.slot] === undefined\n\t}\n\n\tget currentOrder(): Order | undefined {\n\t\treturn this.orders[0]\n\t}\n\n\t/** Ground area covered by a structure */\n\tget rect(): Rect {\n\t\tconst fp = this.def.footprint\n\t\tif (fp) return { x: this.pos.x, z: this.pos.z, hw: fp.w / 2, hd: fp.d / 2 }\n\t\treturn { x: this.pos.x, z: this.pos.z, hw: this.def.radius, hd: this.def.radius }\n\t}\n}\n\n/**\n * Anything with a place and a size: an entity, or what a client knows of one\n *\n * @beta\n */\nexport interface Placed {\n\tpos: Vec2\n\tdef: UnitTypeDef\n}\n\n/**\n * Distance from a point to the edge of an entity\n *\n * @beta\n */\nexport function distanceToEdge(point: Vec2, target: Placed): number {\n\tif (target.def.footprint) {\n\t\tconst fp = target.def.footprint\n\t\tconst dx = Math.max(Math.abs(point.x - target.pos.x) - fp.w / 2, 0)\n\t\tconst dz = Math.max(Math.abs(point.z - target.pos.z) - fp.d / 2, 0)\n\t\treturn Math.sqrt(dx * dx + dz * dz)\n\t}\n\tconst dx = point.x - target.pos.x\n\tconst dz = point.z - target.pos.z\n\treturn Math.max(Math.sqrt(dx * dx + dz * dz) - target.def.radius, 0)\n}\n\n/**\n * Distance between the edges of two entities\n *\n * @beta\n */\nexport function edgeDistance(a: Placed, b: Placed): number {\n\treturn Math.max(distanceToEdge(a.pos, b) - a.def.radius, 0)\n}\n","import { resourcesSpent as resourcesSpentEvent } from '#engine/engineEvents'\nimport { type Component, StateStore } from './components'\nimport type { Registry } from './registry'\nimport type { Cost, ResourceKind } from './defs'\nimport type { PlayerId } from './entity'\nimport type { World } from './world'\n\n/** @beta */\nexport interface PlayerInit {\n\tid: PlayerId\n\tname: string\n\t/** Players on the same team are allies and share vision */\n\tteam: number\n\t/** RGB, 0..1 */\n\tcolor: [number, number, number]\n\t/** What the player starts with, by resource id */\n\tresources?: Purse\n\t/** Neutral players own things like gold mines. Nobody is hostile towards them */\n\tneutral?: boolean\n\t/** The player the creeps belong to: hostile to everyone, and not someone who can win or lose */\n\tcreeps?: boolean\n\t/**\n\t * The race they play (`GameModule.races`), or `random` for one drawn as the game starts. The game's first when left\n\t * out, in a game with races; none for the neutral players and the creeps\n\t */\n\trace?: string\n}\n\n/** @beta */\nexport class Player {\n\treadonly id: PlayerId\n\treadonly name: string\n\t/** Changed by `world.setTeam`, which the fog and everyone's sight follow */\n\tteam: number\n\treadonly color: [number, number, number]\n\treadonly neutral: boolean\n\treadonly creeps: boolean\n\t/** The race they play (`raceOf`): changed by `setRace` only. None in a game without races */\n\trace: string | undefined\n\t/** What the player has of each resource, by resource id */\n\treadonly resources: Purse\n\tsupplyUsed = 0\n\tsupplyCap = 0\n\t/** The game's other pools of supply, by name (`GameRules.supply.pools`): what is used and the cap of each */\n\tsupplies: Record<string, { used: number; cap: number }> = {}\n\t/** Has had a building, and with that something to lose */\n\testablished = false\n\t/** Out of the game */\n\tdefeated = false\n\tprivate readonly finished = new Map<string, number>()\n\t/** Bumped whenever a research finishes. Whatever is worked out from `upgrades` (like the stats of units) can check this to tell whether it still holds */\n\tupgradesVersion = 0\n\t/** Upgrades in some production queue right now */\n\treadonly researching = new Set<string>()\n\t/** State of game modules and mods for this player, see `state` */\n\treadonly states = new StateStore()\n\n\tconstructor(init: PlayerInit) {\n\t\tthis.id = init.id\n\t\tthis.name = init.name\n\t\tthis.team = init.team\n\t\tthis.color = init.color\n\t\tthis.neutral = init.neutral ?? false\n\t\tthis.creeps = init.creeps ?? false\n\t\tthis.race = init.race\n\t\tthis.resources = { ...init.resources }\n\t}\n\n\t/** Finished research: upgrade id to level. Changed through `setUpgrade` only, which keeps `upgradesVersion` honest */\n\tget upgrades(): ReadonlyMap<string, number> {\n\t\treturn this.finished\n\t}\n\n\t/** State of a game module or a mod for this player: made from the component's default when first asked for */\n\tstate<T>(key: Component<T, unknown>): T {\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\tsetUpgrade(upgrade: string, level: number): void {\n\t\tthis.finished.set(upgrade, level)\n\t\tthis.upgradesVersion++\n\t}\n}\n\n/**\n * Amounts of resources, by resource id: what a player has. A resource left out is none of it\n *\n * @beta\n */\nexport type Purse = Record<ResourceKind, number>\n\n/**\n * The resource a purse is short of for a cost, or undefined when it can afford it\n *\n * @beta\n */\nexport function shortOf(purse: Readonly<Purse>, cost: Cost | undefined): ResourceKind | undefined {\n\tif (!cost) return undefined\n\tfor (const kind in cost) if ((purse[kind] ?? 0) < cost[kind]) return kind\n\treturn undefined\n}\n\n/** @beta */\nexport function pay(purse: Purse, cost: Cost | undefined): void {\n\tfor (const kind in cost) purse[kind] = (purse[kind] ?? 0) - cost[kind]\n}\n\n/**\n * Gives back what something cost, or a part of it\n *\n * @beta\n */\nexport function refund(purse: Purse, cost: Cost | undefined, part = 1): void {\n\tfor (const kind in cost) purse[kind] = (purse[kind] ?? 0) + Math.floor(cost[kind] * part)\n}\n\n/**\n * Adds an amount of a resource\n *\n * @beta\n */\nexport function earn(purse: Purse, kind: ResourceKind, amount: number): void {\n\tpurse[kind] = (purse[kind] ?? 0) + amount\n}\n\n/**\n * What a player pays for, as `resourcesSpent` says it: a unit, an upgrade, a structure, a morph, a revive (production),\n * an item, a hire, a repair, a trade at a market (`exchange`), or a game's own word\n *\n * @beta\n */\nexport type SpentOn = 'unit' | 'upgrade' | 'structure' | 'morph' | 'revive' | 'item' | 'hire' | 'repair' | 'trade' | (string & {})\n\n/**\n * Has a player pay a cost, and says so (`resourcesSpent`, what the score counts as spent): `on` what, and its id. For a\n * game's own purchases too, so that they count as the engine's do. The purse is not checked: `shortOf` first\n *\n * @beta\n */\nexport function spend(world: World, player: PlayerId, cost: Cost | undefined, on: SpentOn, id?: string): void {\n\tif (!cost) return\n\tpay(world.player(player).resources, cost)\n\tfor (const kind in cost) {\n\t\tif (cost[kind] === 0) continue\n\t\tworld.events.emit(resourcesSpentEvent, { player, cost, on, id, refund: false })\n\t\treturn\n\t}\n}\n\n/**\n * Gives a player back what something cost, or a part of it (`refund`), and says so (`resourcesSpent` with `refund`):\n * what the score takes off what was spent\n *\n * @beta\n */\nexport function giveBack(world: World, player: PlayerId, cost: Cost | undefined, part: number, on: SpentOn, id?: string): void {\n\tif (!cost) return\n\tconst back: Cost = {}\n\tlet any = false\n\tfor (const kind in cost) {\n\t\tback[kind] = Math.floor(cost[kind] * part)\n\t\tif (back[kind] !== 0) any = true\n\t}\n\trefund(world.player(player).resources, back)\n\tif (any) world.events.emit(resourcesSpentEvent, { player, cost: back, on, id, refund: true })\n}\n\n/**\n * What a cost asks of the game's money, see `Registry.currency`. Shops deal in that alone\n *\n * @beta\n */\nexport function currencyOf(registry: Registry, cost: Cost | undefined): number {\n\treturn registry.currency ? (cost?.[registry.currency] ?? 0) : 0\n}\n","import { messageSent } from '#engine/engineEvents'\nimport { replicateEvent } from './replication'\n/**\n * What the simulation tells a player, like \"Not enough gold\", is a key and some params, never words. The words are\n * the business of the player's screen: the client has English for the engine's keys, and a game's view gives its own\n * (`GameView.hud.messages`) or other words for the engine's. That keeps the engine free of any one language, and lets\n * a game say \"build more farms\" where the engine only knows about supply.\n *\n * Params that name something are ids (a resource, a unit type, an upgrade), for the screen to find the name of.\n *\n * @beta\n */\nexport interface Message {\n\tkey: string\n\tparams?: MessageParams\n}\n\n/** @beta */\nexport type MessageParams = Record<string, string | number | string[]>\n\n/**\n * A message, or a bare key for one without params. What hooks give as the reason something is called off\n *\n * @beta\n */\nexport type MessageRef = Message | string\n\n/** @beta */\nexport const toMessage = (message: MessageRef): Message => (typeof message === 'string' ? { key: message } : message)\n\n/**\n * The messages the engine sends, and their params. The client has words for each of these.\n * A game can send keys of its own as well.\n *\n * @beta\n */\nexport interface EngineMessages {\n\t/** Cannot afford something: `resource` is the id of what is short */\n\tnotEnough: { resource: string }\n\t/** A prefab asked for by a name the game has not (`debug.spawnPrefab`) */\n\tunknownPrefab: { prefab: string }\n\t/** The unit types the player still needs to build to make or research something, by id */\n\trequires: { units: string[] }\n\tqueueFull: {}\n\talreadyHaveHero: {}\n\ttooManyHeroes: {}\n\t/** Out of supply, and could build more of what provides it. `pool` for one of the game's own (`GameRules.supply.pools`) */\n\tsupplyBlocked: { pool?: string }\n\t/** Out of supply, and at the most anyone can have (`GameRules.supply.max`, a pool's `max`) */\n\tsupplyLimit: { pool?: string }\n\talreadyResearching: {}\n\tresearchDone: { upgrade: string }\n\t/** `unit` is the id of the hero's type */\n\theroLevel: { unit: string; level: number }\n\tdefeated: {}\n\t/** Another player gave up. `player` is their name */\n\tsurrendered: { player: string }\n\t/** Every pause of the player's is used */\n\tnoPausesLeft: {}\n\tcannotBuildThere: {}\n\t/** The navigation has no room for another building in the way (`RecastNavigationOptions.maxObstacles`) */\n\ttooManyBuildings: {}\n\tcannotReachSite: {}\n\tcannotReach: {}\n\t/** A worker with something to bring back and nowhere to bring it. `resource` is its id */\n\tnowhereToReturn: { resource: string }\n\tcannotGather: { resource: string }\n\tbuildOnResource: { resource: string }\n\tinventoryFull: {}\n\ttheirInventoryFull: {}\n\toutOfStock: {}\n\t/** Buying needs one of the player's heroes at the shop, with a free slot */\n\theroAtShop: {}\n\t/** Hiring needs one of the player's units at the place that hires */\n\tunitAtShop: {}\n\t/** A hero is hired once: the player has it already. `unit` is its type */\n\talreadyHired: { unit: string }\n\tnoShopNear: {}\n\tcannotDoThat: {}\n\tnotReady: {}\n\tnotEnoughMana: {}\n\tnotEnoughHealth: {}\n\tsilenced: {}\n\t/** An ability used on something it is not for */\n\tcannotTargetThat: {}\n\tcannotTargetFriends: {}\n\tcannotTargetSelf: {}\n\tcannotTargetAir: {}\n\tmustTargetAir: {}\n\tmustTargetHero: {}\n\t/** An ability used on what is immune to spells */\n\ttargetSpellImmune: {}\n\t/** Pinged too often: the rest go nowhere for a moment */\n\ttooManyPings: {}\n\t/** Said too much too quickly: the rest goes nowhere for a moment */\n\ttooManyLines: {}\n\t/** Sent commands faster than the game takes them (a server's rate, `World.commandLimit`): the rest went nowhere */\n\ttooManyCommands: {}\n\t/** Resources given to someone who is not an ally */\n\tnotAnAlly: {}\n\t/** Resources given to an ally, and received from one (see `give`) */\n\tsent: { amount: number; resource: string; player: string }\n\treceived: { amount: number; resource: string; player: string }\n\t/** One resource traded for another at a rate (see `exchange`): `amount` of `resource` went, `received` of `for` came */\n\texchanged: { amount: number; resource: string; received: number; for: string }\n\t/** A field of a definition the game does not let be changed, or a value it does not take (`debug.redefine`) */\n\tdataRefused: { why: string }\n}\n\n/**\n * A message of the engine's own, with its params checked\n *\n * @beta\n */\nexport const engineMessage = <K extends keyof EngineMessages>(\n\tkey: K,\n\t// a message whose params may all be left out takes them or not\n\t...params: {} extends EngineMessages[K] ? [] | [EngineMessages[K]] : [EngineMessages[K]]\n): Message => (params.length ? { key, params: params[0] as MessageParams } : { key })\n\n/** A message, to whom it is for */\nexport const toldMessage = replicateEvent(messageSent, 'message', (message, view) =>\n\tmessage.player === view.player\n\t\t? { type: 'message', message: message.message, kind: message.kind, ...(message.seconds !== undefined && { seconds: message.seconds }) }\n\t\t: undefined\n)\n","/**\n * Rules the simulation and a player's screen both need, written once. Each works on plain facts that a world\n * entity and a client's view of one can both give, so the screen greys out a button for the very reason the\n * simulation would refuse it, and a game's own rules (items 9 to 11) reach both alike.\n *\n * The simulation has the last word all the same: the screen may know less than it does (a buff it is not told\n * of, a step it has not seen yet), and only uses these to say something sooner.\n */\nimport { type AbilityDef, at, type Cost, type EntityKind, type Layer, type UnitTypeDef } from './defs'\nimport { currencyOf } from './player'\nimport { engineMessage, type Message } from './messages'\nimport { type Purse, shortOf } from './player'\nimport type { Registry } from './registry'\n\n// ---- targets\n\n/**\n * Who a target is to the one using an ability on it\n *\n * @beta\n */\nexport type Relation = 'self' | 'ally' | 'enemy' | 'neutral'\n\n/**\n * What there is to know about a target, for whether an ability may be used on it\n *\n * @beta\n */\nexport interface TargetFacts {\n\tkind: EntityKind\n\tlayer: Layer\n\thero: boolean\n\tinvulnerable: boolean\n\trelation: Relation\n\t/** Immune to spells (see `UnitTypeDef.spellImmune`): no ability touches it but its own, and those that get through */\n\tspellImmune?: boolean\n}\n\n/**\n * Why an ability may not be used on a target, or undefined when it may\n *\n * @beta\n */\nexport function targetRefusal(ability: AbilityDef, target: TargetFacts): Message | undefined {\n\tconst rules = ability.targets ?? {}\n\tif (!(rules.kinds ?? ['unit']).includes(target.kind)) return engineMessage('cannotTargetThat')\n\tif (rules.layers && !rules.layers.includes(target.layer)) return engineMessage(target.layer === 'air' ? 'cannotTargetAir' : 'mustTargetAir')\n\tif (rules.heroes && !target.hero) return engineMessage('mustTargetHero')\n\t// one that gets through in code: the simulation knows it, and says so in its facts of the target\n\tif (target.spellImmune && target.relation !== 'self' && ability.piercesImmunity !== true) return engineMessage('targetSpellImmune')\n\tswitch (target.relation) {\n\t\tcase 'self':\n\t\t\treturn (rules.self ?? rules.allies ?? false) ? undefined : engineMessage('cannotTargetSelf')\n\t\tcase 'ally':\n\t\t\treturn rules.allies ? undefined : engineMessage('cannotTargetFriends')\n\t\t// neutral things are fair game for whatever can hit enemies\n\t\tcase 'enemy':\n\t\tcase 'neutral':\n\t\t\treturn rules.enemies && !target.invulnerable ? undefined : engineMessage('cannotTargetThat')\n\t}\n}\n\n/**\n * How far away the target of an ability may be: what it says, and for some as far as the caster's attacks reach on top\n *\n * @beta\n */\nexport const abilityReach = (ability: AbilityDef, level: number, attackRange: number): number =>\n\tat(ability.range, level) + (ability.attackRange ? attackRange : 0)\n\n// ---- abilities\n\n/**\n * What there is to know about an ability and its user, for whether it can be used right now\n *\n * @beta\n */\nexport interface ReadyFacts {\n\t/** 0 for one not learned yet */\n\tlevel: number\n\t/** Seconds until it can be used again */\n\tcooldown: number\n\t/** Uses left, of an ability with charges (`chargesLeft`): none, and it is not ready */\n\tcharges?: number\n\tmana: number\n\thp: number\n\tmaxHp: number\n\t/** It comes from something carried: items ask for no mana, and silence does not stop them */\n\titem?: boolean\n\t/** One of the spells the hero brought along rather than learned: silence does not stop those either */\n\tspell?: boolean\n\tsilenced?: boolean\n\t/** The debug switch that makes abilities cost nothing */\n\tnoManaCosts?: boolean\n\t/** What the simulation's `canCast` hook decided instead, when it told the screen: a reason, or null for none */\n\tdecided?: Message | null\n}\n\n/**\n * How many uses an ability with charges has left (`AbilityDef.charges`), at its level: what its state says, or all it\n * holds when that says nothing. Undefined for an ability without charges\n *\n * @beta\n */\nexport function chargesLeft(ability: AbilityDef, state: { level: number; charges?: number }): number | undefined {\n\tif (!ability.charges) return undefined\n\treturn state.charges ?? Math.max(Math.round(at(ability.charges.count, Math.max(state.level, 1))), 1)\n}\n\n/**\n * Why an ability cannot be used right now, or undefined when it can\n *\n * @beta\n */\nexport function abilityRefusal(ability: AbilityDef, facts: ReadyFacts): Message | undefined {\n\tif (facts.decided !== undefined) return facts.decided ?? undefined\n\tif (facts.level < 1) return engineMessage('cannotDoThat')\n\tif (facts.cooldown > 0 || facts.charges === 0) return engineMessage('notReady')\n\tif (facts.item) return undefined\n\tif (!facts.noManaCosts && at(ability.manaCost, facts.level) > facts.mana) return engineMessage('notEnoughMana')\n\tif (ability.healthCost !== undefined && facts.hp <= at(ability.healthCost, facts.level) * facts.maxHp) return engineMessage('notEnoughHealth')\n\tif (!facts.spell && facts.silenced) return engineMessage('silenced')\n\treturn undefined\n}\n\n// ---- making things\n\n/**\n * What there is to know about a player, for whether they can make something\n *\n * @beta\n */\nexport interface PlayerFacts {\n\tresources: Readonly<Purse>\n\tsupplyUsed: number\n\tsupplyCap: number\n\t/** The game's other pools of supply, by name (`GameRules.supply.pools`): left out in a game with none */\n\tsupplies?: Readonly<Record<string, { used: number; cap: number }>>\n\t/** Unit types they have, finished, which is what requirements ask for */\n\ttech: ReadonlySet<string> | readonly string[]\n\t/** Types of the heroes they have, fallen ones and ones being made included */\n\theroes: readonly string[]\n\t/**\n\t * What the simulation's `requirement` hook decided, where it differs from what the requirements say: by unit or\n\t * structure type, and `upgrade:<id>` for the next level of research. A reason, or null for \"may, for all that\"\n\t */\n\tunlocks?: Record<string, Message | null>\n\t/** The race they play (`raceOf`): left out in a game without races */\n\trace?: string\n\t/**\n\t * What the simulation's `available` hook decided, where it differs from what their race says (`availableTo`): by\n\t * unit or structure type, and `upgrade:<id>`\n\t */\n\tavailability?: Record<string, boolean>\n}\n\n/**\n * Whether a worker gathers a kind of resource at all (`harvester.kinds`): the game's `canHarvest` hook may refuse it a\n * resource all the same (`canHarvest`)\n *\n * @beta\n */\nexport const gathers = (def: Pick<UnitTypeDef, 'harvester'>, kind: string): boolean =>\n\t!!def.harvester && (!def.harvester.kinds || def.harvester.kinds.includes(kind))\n\n/**\n * Whether something of a race (`UnitTypeDef.race`, `UpgradeDef.race`) is a player's to make as their race goes: what is\n * of no race is everyone's, and a player of none (the neutral players, the creeps, any in a game without races) may\n * make anything. The `available` hook has the last word (`isAvailable`)\n *\n * @beta\n */\nexport const availableTo = (def: { readonly race?: string }, race: string | undefined): boolean =>\n\tdef.race === undefined || race === undefined || def.race === race\n\n/**\n * Whether a player may make something at all, as the simulation decided (`availability`, by `key`) or else as their\n * race goes: what is not is left off their buttons\n *\n * @beta\n */\nexport function availableToPlayer(def: { readonly race?: string }, player: Pick<PlayerFacts, 'race' | 'availability'>, key: string): boolean {\n\treturn player.availability?.[key] ?? availableTo(def, player.race)\n}\n\n/**\n * Why something may not be made as far as what it requires goes: as the simulation decided (`unlocks`), or by the finished buildings it requires\n *\n * @beta\n */\nexport function requirementRefusal(\n\trequires: readonly string[] | undefined,\n\tplayer: Pick<PlayerFacts, 'tech' | 'unlocks'>,\n\tkey: string\n): Message | undefined {\n\tconst decided = player.unlocks?.[key]\n\tif (decided !== undefined) return decided ?? undefined\n\tconst lacking = missingTech(requires, player.tech)\n\treturn lacking.length ? engineMessage('requires', { units: lacking }) : undefined\n}\n\n/**\n * The requirements a player does not meet, by unit type\n *\n * @internal\n */\nexport function missingTech(requires: readonly string[] | undefined, tech: PlayerFacts['tech']): string[] {\n\t// asked about every button of a card, ten times a second, and nearly always nothing is missing: nothing is made then\n\tif (!requires?.length) return NOTHING_MISSING\n\tlet lacking: string[] | undefined\n\tfor (const id of requires) if (!('has' in tech ? tech.has(id) : tech.includes(id))) (lacking ??= []).push(id)\n\treturn lacking ?? NOTHING_MISSING\n}\n\n/** What `missingTech` gives when nothing is missing: the same one every time, and frozen, so nobody adds to it */\nconst NOTHING_MISSING = Object.freeze([]) as unknown as string[]\n\n/**\n * What stands in the way of a cost, or undefined when the player can pay it\n *\n * @beta\n */\nexport function costRefusal(resources: Readonly<Purse>, cost: Cost | undefined): Message | undefined {\n\tconst short = shortOf(resources, cost)\n\treturn short ? engineMessage('notEnough', { resource: short }) : undefined\n}\n\n/**\n * Why a player cannot have a unit made, or undefined when they can, as far as they and the unit type go: whether\n * the building has room, and what a game's hooks say (they can change the cost), is for the simulation. In the order the\n * player is told\n *\n * @beta\n */\nexport function trainRefusal(\n\tregistry: Registry,\n\tdef: UnitTypeDef,\n\tplayer: PlayerFacts,\n\toptions?: { cost?: boolean; tech?: boolean }\n): Message | undefined {\n\tconst locked = options?.tech === false ? undefined : requirementRefusal(def.requires, player, def.id)\n\tif (locked) return locked\n\tconst { rules } = registry\n\tif (def.hero) {\n\t\tif (player.heroes.includes(def.id)) return engineMessage('alreadyHaveHero')\n\t\tif (player.heroes.length >= registry.rules.heroes.maxHeroes) return engineMessage('tooManyHeroes')\n\t}\n\tconst supply = def.supply ?? 0\n\tif (supply > 0 && player.supplyUsed + supply > player.supplyCap) {\n\t\treturn engineMessage(player.supplyCap >= rules.supply.max ? 'supplyLimit' : 'supplyBlocked')\n\t}\n\t// and of each of the game's other pools it takes of\n\tfor (const name in def.supplies) {\n\t\tconst taken = def.supplies[name]\n\t\tconst pool = player.supplies?.[name]\n\t\tconst most = rules.supply.pools?.[name]?.max\n\t\tif (taken > 0 && pool && pool.used + taken > pool.cap)\n\t\t\treturn engineMessage(most !== undefined && pool.cap >= most ? 'supplyLimit' : 'supplyBlocked', { pool: name })\n\t}\n\t// the simulation checks the cost itself, once the game's hooks have had their say about it\n\treturn options?.cost === false ? undefined : costRefusal(player.resources, def.cost)\n}\n\n// ---- items and attacks\n\n/**\n * What a shop pays for an item: a part of its price, and of what is left of it for what runs out\n *\n * @beta\n */\nexport function sellValue(registry: Registry, item: string, charges: number): number {\n\tconst def = registry.item(item)\n\tconst part = def.charges ? charges / def.charges : 1\n\treturn Math.round(currencyOf(registry, def.cost) * registry.rules.economy.sellPrice * part)\n}\n","/**\n * Charges: an ability used so many times before it waits (`AbilityDef.charges`). A use spends one, and one comes back\n * every `refill` seconds while it holds fewer than it can. What a state says nothing of is full, so an ability learned,\n * a level gone up and a save from before it all start full without anyone filling them in\n */\nimport { type AbilityDef, at } from '#engine/defs'\nimport type { AbilityState, Entity } from '#engine/entity'\nimport { chargesLeft } from '#engine/shared'\nimport { cooldownOf } from '#engine/stats'\nimport type { World } from '#engine/world'\n\n/** Seconds a use takes to come back: shortened as the cooldown is, but for what is carried or brought along (`plain`) */\nfunction refillOf(world: World, caster: Entity, ability: AbilityDef, level: number, plain: boolean): number {\n\tconst seconds = at(ability.charges?.refill, level)\n\treturn plain ? seconds : cooldownOf(world, caster, seconds)\n}\n\n/** One of the spells a hero brought along rather than learned: nothing shortens those */\nconst brought = (caster: Entity, id: string) => caster.def.hero?.spells?.includes(id) ?? false\n\n/** Full again: what it says of its uses goes, so that it holds all it can */\nfunction fill(state: AbilityState): void {\n\tdelete state.charges\n\tdelete state.refill\n}\n\n/**\n * Spends a use of an ability with charges, as it goes off: the refill starts, where it was not running already.\n * `plain` for what nothing shortens (an item's, a spell brought along). Nothing for one without charges, and nothing\n * while the debug switch for no cooldowns is on\n */\nexport function spendUse(world: World, caster: Entity, ability: AbilityDef, state: AbilityState, plain: boolean): void {\n\tconst left = chargesLeft(ability, state)\n\tif (left === undefined || world.cheats.noCooldowns) return\n\tstate.charges = Math.max(left - 1, 0)\n\tif (!((state.refill ?? 0) > 0)) state.refill = refillOf(world, caster, ability, state.level, plain)\n}\n\n/**\n * The seconds of a tick go by for the uses of an ability (`pass`: Infinity fills them at once): one back every\n * `refill`, until it holds all it can. `item` for the ability of something carried\n */\nexport function refillUses(world: World, caster: Entity, state: AbilityState, pass: number, item = false): void {\n\tif (state.charges === undefined) return\n\tconst ability = world.registry.abilities.has(state.id) ? world.registry.ability(state.id) : undefined\n\tconst max = ability && chargesLeft(ability, { level: state.level })\n\tif (!ability || max === undefined || pass === Infinity) return fill(state)\n\tstate.refill = (state.refill ?? 0) - pass\n\twhile (state.refill <= 0) {\n\t\tstate.charges++\n\t\tif (state.charges >= max) return fill(state)\n\t\tconst next = refillOf(world, caster, ability, state.level, item || brought(caster, ability.id))\n\t\tif (next <= 0) return fill(state)\n\t\tstate.refill += next\n\t}\n}\n\n/** Ready again at once, with all the uses it holds: a hero revived, the `refresh` effect */\nexport function readyAgain(state: AbilityState): void {\n\tstate.cooldown = 0\n\tfill(state)\n}\n\n/**\n * Gives an entity's ability with charges uses back, up to all it holds: `count` of them, or all when left out. What a\n * game's effect or hook does where the data's `refill` is not the way (a kill gives one back). Its cooldown stays\n *\n * @beta\n */\nexport function restoreCharges(world: World, entity: Entity, ability: string, count = Infinity): void {\n\tconst state = entity.abilities.find((known) => known.id === ability)\n\tif (!state || state.charges === undefined) return\n\tconst max = world.registry.abilities.has(ability) ? chargesLeft(world.registry.ability(ability), { level: state.level }) : undefined\n\tif (max === undefined || state.charges + count >= max) return fill(state)\n\tstate.charges += Math.max(Math.floor(count), 0)\n}\n","import type { Entity } from '#engine/entity'\nimport type { AgentParams } from './navigation'\n\n/** What the navigation is told of a unit when it takes it on as an agent: one place for every site that adds one again */\nexport function agentParamsOf(entity: Entity, speed: number): AgentParams {\n\treturn { radius: entity.def.radius, speed, flying: entity.flying, naval: entity.def.naval }\n}\n","/**\n * What a building makes (`productionQueue`): its queue and its rally point, and what a player's screen is told of it.\n * The state alone, of nothing but components, so that what reads or sets it (a unit turning into another type, the\n * tech) loads nothing of the production system (`production.ts`)\n */\nimport { morphCancelled } from '#engine/engineEvents'\nimport { upgradesOf } from '#engine/defs'\nimport { defineComponent, snapshotOf } from '#engine/components'\nimport type { Entity, ProductionItem, ProductionState } from '#engine/entity'\nimport { giveBack as refundTo } from '#engine/player'\nimport type { World } from '#engine/world'\nimport type { EntityState, ProductionInfo, QueueItemState } from '#engine/session/protocol'\nimport { sameHundredth } from './construction'\nimport { replicateEvent } from '../replication'\n\nconst NOTHING: readonly QueueItemState[] = []\n\nconst sameItem = (a: QueueItemState, b: QueueItemState) => a.kind === b.kind && a.id === b.id && sameHundredth(a.progress, b.progress)\n\n/**\n * What a building makes (`UnitTypeDef.trains`, `researches`, `upgradesTo`, `revives`): its queue, and where what comes\n * out goes. Set as it is spawned (and as its type changes), for a type that makes anything. Its owner and their allies\n * are told the queue and the rally point; everyone who sees it how far it is in turning into another type\n * (`ProductionInfo`)\n *\n * @beta\n */\nexport const productionQueue = defineComponent<ProductionState, ProductionInfo>('core.production', {\n\trefs: (saved) => {\n\t\tconst { queue } = saved as ProductionState\n\t\treturn {\n\t\t\tupgrades: queue.filter((queued) => queued.kind === 'upgrade').map((queued) => queued.id),\n\t\t\tunits: queue.filter((queued) => queued.kind !== 'upgrade' && queued.kind !== 'revive').map((queued) => queued.id)\n\t\t}\n\t},\n\t// a queue, empty, for a structure that makes anything\n\tonSpawn: (entity) => {\n\t\tconst { def } = entity\n\t\tif (def.kind !== 'unit' && (def.trains?.length || def.researches?.length || upgradesOf(def).length))\n\t\t\tentity.set(productionQueue, { queue: [], rally: null })\n\t},\n\t// what it was making given back to whose it was, as it falls or is given away\n\tonLeave: (entity, world) => cancelAllProduction(world, entity),\n\treplicate: 'everyone',\n\tsnapshot(production, _entity, { world, ally }) {\n\t\tconst info: ProductionInfo = {}\n\t\t// a building turning into another: how far, for everyone who sees it\n\t\tconst first = production.queue[0]\n\t\tif (first?.kind === 'morph') {\n\t\t\tinfo.upgrade = first.progress / first.duration\n\t\t\tinfo.upgradeTo = first.id\n\t\t}\n\t\tif (ally) {\n\t\t\tif (production.queue.length)\n\t\t\t\tinfo.queue = production.queue.map((item) => ({ kind: item.kind, id: item.id, progress: item.progress / item.duration }))\n\t\t\tconst rally = world.get(production.rally?.target)?.pos ?? production.rally?.point\n\t\t\tif (rally) info.rally = { x: rally.x, z: rally.z }\n\t\t}\n\t\treturn info.upgradeTo !== undefined || info.queue || info.rally ? info : undefined\n\t},\n\t// a delta for every hundredth of what is under way, not every tick\n\tsame: (a, b) =>\n\t\ta.upgradeTo === b.upgradeTo &&\n\t\t(a.upgrade === undefined ? b.upgrade === undefined : b.upgrade !== undefined && sameHundredth(a.upgrade, b.upgrade)) &&\n\t\ta.rally?.x === b.rally?.x &&\n\t\ta.rally?.z === b.rally?.z &&\n\t\t(a.queue?.length ?? 0) === (b.queue?.length ?? 0) &&\n\t\t(a.queue ?? []).every((item, i) => sameItem(item, b.queue![i]))\n})\n\n/**\n * What a building makes, and where it goes: none for a type that makes nothing (`productionQueue`)\n *\n * @beta\n */\nexport const productionOf = (entity: Entity): ProductionState | undefined => entity.get(productionQueue)\n\n/**\n * What a building in a snapshot makes, the first being made: empty for one that makes nothing, or another's (a\n * screen's, a computer player's view)\n *\n * @beta\n */\nexport const queueOf = (state: EntityState): readonly QueueItemState[] => snapshotOf(state, productionQueue)?.queue ?? NOTHING\n\n/**\n * The type a building in a snapshot is turning into, and how far, 0..1: undefined for one that is not\n *\n * @beta\n */\nexport function upgradeOf(state: EntityState): { to: string; progress: number } | undefined {\n\tconst info = snapshotOf(state, productionQueue)\n\treturn info?.upgradeTo === undefined ? undefined : { to: info.upgradeTo, progress: info.upgrade ?? 0 }\n}\n\n/** What a building had queued, given back: the money paid, a hero no longer coming back, research no longer under way */\nexport function giveBack(world: World, building: Entity, item: ProductionItem): void {\n\tconst player = world.player(building.owner)\n\tconst { registry } = world\n\tif (item.kind === 'revive') {\n\t\tconst hero = world.entities.get(Number(item.id))\n\t\tif (hero) hero.reviving = false\n\t} else if (item.kind === 'upgrade') {\n\t\tplayer.researching.delete(item.id)\n\t} else if (item.kind === 'morph') {\n\t\tworld.events.emit(morphCancelled, { entity: building, into: item.id })\n\t}\n\tconst paid = item.paid ?? (item.kind === 'upgrade' ? registry.upgrade(item.id).cost : registry.unit(item.id).cost)\n\trefundTo(world, player.id, paid, 1, item.kind, item.id)\n}\n\n/** Gives back everything a building had queued, for when it is destroyed */\nexport function cancelAllProduction(world: World, building: Entity): void {\n\tconst production = productionOf(building)\n\tif (!production) return\n\tfor (const item of production.queue) giveBack(world, building, item)\n\tproduction.queue.length = 0\n}\n\n/** A building's becoming another called off, to those who see it */\nexport const toldUpgradeCancelled = replicateEvent(morphCancelled, 'upgradeCancelled', ({ entity, into }, view) =>\n\tview.knows(entity) ? { type: 'upgradeCancelled', id: entity.id, to: into } : undefined\n)\n","import { heroLevelUp, heroRevived, xpGained } from '#engine/engineEvents'\nimport { defineComponent, snapshotOf } from './components'\nimport type { Cost } from './defs'\nimport { type Entity, fighting, moving, type PlayerId } from './entity'\nimport type { Vec2 } from './math'\nimport { refreshVitals, statsOf } from './stats'\nimport { readyAgain } from './abilities/charges'\nimport type { World } from './world'\nimport { agentParamsOf } from './navigation/agentParams'\nimport { engineMessage } from './messages'\nimport type { EntityState, LearnableInfo, XpInfo } from './session/protocol'\nimport { currencyOf } from './player'\nimport type { GamePack } from './packs/pack'\nimport { replicateEvent } from './replication'\nimport type { HeroSummary } from './session/protocol'\nimport { productionOf } from './systems/productionQueue'\n\n/**\n * The id of the heroes pack (`withHeroes`): `hasPack(game, HEROES)`\n *\n * @beta\n */\nexport const HEROES = 'core.heroes'\n\n/**\n * The numbers and formulas of heroes, the heroes pack's (`withHeroes(rules)`): how many heroes a player may\n * have, how much experience a level takes, what bringing one back costs. The classic RTS numbers for\n * those left out\n *\n * @beta\n */\nexport interface HeroRules {\n\t/** Heroes a player can have at once, fallen ones and ones being trained included */\n\tmaxHeroes: number\n\t/** The level heroes stop at, unless their type says otherwise (`HeroDef.maxLevel`) */\n\tmaxHeroLevel: number\n\t/** Heroes this close to a kill get a share of the experience */\n\txpRange: number\n\t/** Experience needed in total to be of a level. Level 1 must need none */\n\txpForLevel(level: number): number\n\t/** Experience a kill is worth, for units whose type does not say (`UnitTypeDef.xp`) */\n\tkillXp(world: World, dead: Entity): number\n\t/** What it costs to bring a fallen hero back, in the game's money, and how long it takes in seconds */\n\trevive(world: World, hero: Entity): { cost: Cost; time: number }\n\t/** Ability points a hero gets for reaching a level. One, when left out */\n\tpointsForLevel(level: number): number\n}\n\n/**\n * The heroes pack's rules where a game says nothing: the classic RTS numbers\n *\n * @internal\n */\nexport const defaultHeroRules: Readonly<HeroRules> = Object.freeze({\n\tmaxHeroes: 3,\n\tmaxHeroLevel: 10,\n\txpRange: 20,\n\t// 200, 500, 900, 1400, ...\n\txpForLevel: (level: number) => 50 * (level - 1) * (level + 2),\n\tkillXp(world: World, dead: Entity) {\n\t\tconst hero = heroOf(dead)\n\t\tif (hero) return 100 * hero.level\n\t\tif (!dead.isUnit) return 0\n\t\t// a quarter of what it cost in the game's money\n\t\treturn Math.max(Math.round(currencyOf(world.registry, dead.def.cost) / 4), 10)\n\t},\n\trevive(world: World, hero: Entity) {\n\t\tconst level = heroOf(hero)?.level ?? 1\n\t\tconst { currency } = world.registry\n\t\tconst paid = currencyOf(world.registry, hero.def.cost)\n\t\tconst cost: Cost = currency ? { [currency]: Math.min(Math.round(paid * (0.4 + 0.1 * level)), 700) } : {}\n\t\treturn { cost, time: Math.min((hero.def.buildTime ?? 30) * 0.5 + 4 * level, 110) }\n\t},\n\tpointsForLevel: () => 1\n})\n\n/**\n * The heroes pack, as `withHeroes` makes it: its rules beside its parts\n *\n * @beta\n */\nexport interface HeroesPack extends GamePack {\n\t/** What the game says of heroes, over the engine's (`defaultHeroRules`): what the pack was made with (`GameRules.heroes`) */\n\toptions: Partial<HeroRules>\n}\n\n/**\n * What a hero has earned: its level, its experience, the points it has to put into abilities (`heroState`)\n *\n * @beta\n */\nexport interface HeroState {\n\tlevel: number\n\t/** Experience in total */\n\txp: number\n\t/** Points that can be put into abilities */\n\tpoints: number\n}\n\n/**\n * What a player is told of a hero (`heroState`): its level, to everyone who sees it; its experience to its side, and to\n * everyone where the rules share it (`GameRules.hud.shareXp`); the points it has to spend and what it can learn, to its\n * side\n *\n * @beta\n */\nexport interface HeroSent {\n\tlevel: number\n\t/** Its experience: its side's, and everyone's where the rules share it */\n\txp?: XpInfo\n\t/** Points it has to put into abilities: its side's */\n\tpoints?: number\n\t/** The abilities it can put points into, how far and whether now: its side's */\n\tlearnable?: LearnableInfo[]\n}\n\n/** A hero's experience: what it has, what its level took and what the next takes */\nfunction xpOf(world: World, entity: Entity, hero: HeroState): XpInfo {\n\treturn {\n\t\txp: Math.floor(hero.xp),\n\t\tlevelXp: world.rules.heroes.xpForLevel(hero.level),\n\t\tnextXp: world.rules.heroes.xpForLevel(Math.min(hero.level + 1, maxLevelOf(world, entity)))\n\t}\n}\n\nconst sameXp = (a: XpInfo | undefined, b: XpInfo | undefined) =>\n\ta === b || (!!a && !!b && a.xp === b.xp && a.levelXp === b.levelXp && a.nextXp === b.nextXp)\n\n/**\n * A hero: what it has earned (`HeroState`). Set as a unit of a type that says it is one (`UnitTypeDef.hero`) is made,\n * filed by owner (`world.index.with(heroState, player)`, `heroesOf`). What is a hero is what has it: a fallen hero stays\n * in the world's entities, out of the world, to be brought back\n *\n * @beta\n */\nexport const heroState = defineComponent<HeroState, HeroSent>('core.hero', {\n\treplicate: 'everyone',\n\tindex: 'owner',\n\tsnapshot(hero, entity, { world, ally }) {\n\t\tconst sent: HeroSent = { level: hero.level }\n\t\tconst def = entity.def.hero\n\t\tif (!def) return sent\n\t\tconst shareXp = world.rules.hud.shareXp\n\t\tconst shared =\n\t\t\tshareXp !== undefined && (typeof shareXp === 'function' ? (shareXp as (world: World, entity: Entity) => boolean)(world, entity) : shareXp)\n\t\tif (ally || shared) sent.xp = xpOf(world, entity, hero)\n\t\tif (!ally) return sent\n\t\tsent.points = hero.points\n\t\tsent.learnable = def.learns.map((id) => ({\n\t\t\tid,\n\t\t\tlevel: entity.abilities.find((ability) => ability.id === id)?.level ?? 0,\n\t\t\tmaxLevel: world.registry.ability(id).maxLevel ?? 3,\n\t\t\tneeds: levelNeeded(world, entity, id),\n\t\t\tavailable: canLearn(world, entity, id)\n\t\t}))\n\t\treturn sent\n\t},\n\tsame: (a, b) =>\n\t\ta.level === b.level &&\n\t\tsameXp(a.xp, b.xp) &&\n\t\ta.points === b.points &&\n\t\t(a.learnable === b.learnable ||\n\t\t\t(!!a.learnable &&\n\t\t\t\t!!b.learnable &&\n\t\t\t\ta.learnable.length === b.learnable.length &&\n\t\t\t\ta.learnable.every((info, i) => {\n\t\t\t\t\tconst other = b.learnable![i]\n\t\t\t\t\treturn (\n\t\t\t\t\t\tinfo.id === other.id &&\n\t\t\t\t\t\tinfo.level === other.level &&\n\t\t\t\t\t\tinfo.maxLevel === other.maxLevel &&\n\t\t\t\t\t\tinfo.needs === other.needs &&\n\t\t\t\t\t\tinfo.available === other.available\n\t\t\t\t\t)\n\t\t\t\t})))\n})\n\n/**\n * What a hero has earned: none for what is no hero (`heroState`)\n *\n * @beta\n */\nexport const heroOf = (entity: Entity): HeroState | undefined => entity.get(heroState)\n\n/**\n * What a player was told of a hero in their snapshot (`heroState`): its level to everyone, its experience, points and\n * what it can learn to its side. None for what is no hero\n *\n * @beta\n */\nexport const heroOfState = (state: EntityState): HeroSent | undefined => snapshotOf(state, heroState)\n\n/**\n * The level a hero stops at\n *\n * @beta\n */\nexport const maxLevelOf = (world: World, entity: Entity) => entity.def.hero?.maxLevel ?? world.rules.heroes.maxHeroLevel\n\n/**\n * Gives a hero experience: `from` what was killed, when that is where it comes from. The `beforeXp` hook has its say\n *\n * @beta\n */\nexport function grantXp(world: World, entity: Entity, amount: number, from?: Entity): void {\n\tconst hero = heroOf(entity)\n\tconst max = maxLevelOf(world, entity)\n\tconst { xpForLevel, pointsForLevel } = world.rules.heroes\n\tif (!hero || !entity.alive || hero.level >= max) return\n\tif (world.hooks.has('beforeXp')) amount = world.hooks.run('beforeXp', { hero: entity, from, amount }).amount\n\tif (amount <= 0) return\n\thero.xp += amount\n\twhile (hero.level < max && hero.xp >= xpForLevel(hero.level + 1)) {\n\t\thero.level++\n\t\thero.points += pointsForLevel(hero.level)\n\t\trefreshVitals(world, entity)\n\t\tworld.events.emit(heroLevelUp, { hero: entity, level: hero.level })\n\t\tworld.message(entity.owner, engineMessage('heroLevel', { unit: entity.def.id, level: hero.level }), 'info')\n\t}\n\tif (hero.level >= max) hero.xp = xpForLevel(max)\n\tworld.events.emit(xpGained, { hero: entity, amount, level: hero.level, from })\n}\n\n/**\n * Puts a hero at a level as if it had got there: the points to spend, the stats that grew, the experience of that\n * level. No message, no event and no `beforeXp`: for a hero that starts a map at that level, not one that earns it.\n * Never down\n *\n * @beta\n */\nexport function setHeroLevel(world: World, entity: Entity, level: number): void {\n\tconst hero = heroOf(entity)\n\tif (!hero) return\n\tconst to = Math.min(Math.floor(level), maxLevelOf(world, entity))\n\tif (to <= hero.level) return\n\twhile (hero.level < to) {\n\t\thero.level++\n\t\thero.points += world.rules.heroes.pointsForLevel(hero.level)\n\t}\n\thero.xp = world.rules.heroes.xpForLevel(to)\n\trefreshVitals(world, entity)\n}\n\n/**\n * Experience a kill is worth\n *\n * @beta\n */\nexport function xpWorth(world: World, entity: Entity): number {\n\treturn entity.def.xp ?? world.rules.heroes.killXp(world, entity)\n}\n\n/**\n * Hero level needed to put the next point into an ability\n *\n * @beta\n */\nexport function levelNeeded(world: World, hero: Entity, ability: string): number {\n\tconst def = world.registry.ability(ability)\n\tconst state = hero.abilities.find((a) => a.id === ability)\n\treturn (def.requiresLevel ?? 1) + (def.levelStep ?? 2) * (state?.level ?? 0)\n}\n\n/**\n * Whether a hero may put a point into an ability now: by points, levels and its learning, and the `canLearn` hook\n *\n * @beta\n */\nexport function canLearn(world: World, hero: Entity, ability: string): boolean {\n\tconst state = heroOf(hero)\n\tif (!state || !hero.alive || state.points <= 0) return false\n\tif (!hero.def.hero?.learns.includes(ability) || !world.registry.abilities.has(ability)) return false\n\tconst learned = hero.abilities.find((a) => a.id === ability)\n\tif (!learned || learned.level >= (world.registry.ability(ability).maxLevel ?? 3)) return false\n\tconst allowed = state.level >= levelNeeded(world, hero, ability)\n\treturn world.hooks.has('canLearn') ? world.hooks.run('canLearn', { hero, ability, allowed }).allowed : allowed\n}\n\n/** @beta */\nexport function learn(world: World, hero: Entity, ability: string): boolean {\n\tif (!canLearn(world, hero, ability)) return false\n\tconst state = hero.abilities.find((a) => a.id === ability)!\n\tstate.level++\n\theroOf(hero)!.points--\n\tif (state.level === 1) state.autocast = world.registry.ability(ability).autocast ?? false\n\treturn true\n}\n\n/**\n * Heroes a player has, fallen ones included\n *\n * @beta\n */\nexport function heroesOf(world: World, player: number): Entity[] {\n\treturn [...world.index.with(heroState, player)]\n}\n\n/**\n * What it costs to bring a hero back, in the game's money, and how long it takes\n *\n * @beta\n */\nexport function reviveCost(world: World, hero: Entity): { cost: Cost; time: number } {\n\treturn world.rules.heroes.revive(world, hero)\n}\n\n/**\n * Puts a fallen hero back into the world\n *\n * @beta\n */\nexport function reviveHero(world: World, hero: Entity, at: Vec2): void {\n\tif (hero.alive || !hero.has(heroState)) return\n\tconst point = (hero.flying ? world.air : world.nav).closestPoint(at, 8) ?? at\n\thero.setAlive(true)\n\thero.setInside(false)\n\thero.reviving = false\n\thero.hp = hero.maxHp\n\thero.mana = hero.maxMana\n\thero.clearBuffs()\n\thero.keepOrders()\n\tfor (const ability of hero.abilities) readyAgain(ability)\n\thero.moveTo(point.x, point.z)\n\thero.prevPos.x = point.x\n\thero.prevPos.z = point.z\n\tconst m = hero.get(moving)\n\tif (m) {\n\t\tm.status = 'idle'\n\t\tm.anchored = false\n\t\tm.ghost = false\n\t\tm.finalFacing = null\n\t\tm.speed = statsOf(world, hero).moveSpeed\n\t\tworld.nav.addAgent(hero.id, point, agentParamsOf(hero, m.speed))\n\t}\n\tif (hero.get(fighting))\n\t\tObject.assign(hero.get(fighting)!, { cooldown: 0, swing: 0, swingTarget: 0, autoTarget: 0, lastAttacker: 0, guard: null, passive: false })\n\tworld.events.emit(heroRevived, hero)\n}\n\n/**\n * A fallen hero waiting to come back: when it fell, and how long it waits, in seconds of the game\n *\n * @internal\n */\nexport const respawning = defineComponent<{ since: number; wait: number }>('core.respawning')\n\n/**\n * How long until a fallen hero comes back by itself, in seconds: none for one that is not waiting\n *\n * @beta\n */\nexport function respawnIn(world: World, hero: Entity): number | undefined {\n\tconst waiting = hero.get(respawning)\n\treturn waiting && !hero.alive ? Math.max(0, waiting.since + waiting.wait - world.time) : undefined\n}\n\n/** A hero back, to those who see it */\nexport const toldRevived = replicateEvent(heroRevived, 'revived', (hero, view) => (view.knows(hero) ? { type: 'revived', id: hero.id } : undefined))\n\n/** A hero's new level, to those who see it */\nexport const toldLevelUp = replicateEvent(heroLevelUp, 'levelUp', ({ hero, level }, view) =>\n\tview.knows(hero) ? { type: 'levelUp', id: hero.id, level } : undefined\n)\n\n/** Experience gained: its side's alone, an enemy sees a bar move, not why */\nexport const toldXp = replicateEvent(xpGained, 'xp', ({ hero, amount, level }, view) =>\n\tview.isAlly(hero.owner) ? { type: 'xp', id: hero.id, amount, level } : undefined\n)\n\n/**\n * A player's heroes, as their portraits show them (`PlayerState.own.heroes`): their level, health and mana, and how far\n * a fallen one is through being brought back, at an altar or by itself\n *\n * @beta\n */\nexport function heroSummaries(world: World, player: PlayerId): HeroSummary[] {\n\tconst reviving = new Map<number, number>()\n\tfor (const entity of world.index.ownedBy(player)) {\n\t\tconst production = productionOf(entity)\n\t\tif (!production) continue\n\t\tfor (const item of production.queue) if (item.kind === 'revive') reviving.set(Number(item.id), item.progress / item.duration)\n\t}\n\treturn heroesOf(world, player).map((entity) => ({\n\t\tid: entity.id,\n\t\ttype: entity.def.id,\n\t\tlevel: heroOf(entity)!.level,\n\t\talive: entity.alive,\n\t\thp: entity.alive ? entity.hp / entity.maxHp : 0,\n\t\tmana: entity.alive && entity.maxMana > 0 ? entity.mana / entity.maxMana : 0,\n\t\tpoints: heroOf(entity)!.points,\n\t\treviving: reviving.get(entity.id) ?? respawnProgress(world, entity),\n\t\t...(respawnIn(world, entity) !== undefined && { respawnIn: respawnIn(world, entity) }),\n\t\treviveCost: entity.alive ? undefined : reviveCost(world, entity).cost\n\t}))\n}\n\n/** How far a fallen hero is through its wait to come back by itself, 0..1: none for one that is not waiting */\nfunction respawnProgress(world: World, hero: Entity): number | undefined {\n\tconst waiting = hero.get(respawning)\n\tif (!waiting || hero.alive) return undefined\n\treturn waiting.wait > 0 ? Math.min(1, (world.time - waiting.since) / waiting.wait) : 1\n}\n","/**\n * What an ability's numbers come to for the unit that casts it: the parts that grow with its stats, its level as a hero,\n * its own attack (`Scaling`). Above the stats (`stats.ts`), which know nothing of heroes: a hero's level is the heroes\n * pack's\n */\nimport { type CasterFacts, scaledParts } from './text'\nimport { baseStats, type Scaling } from '#engine/defs'\nimport type { Entity } from '#engine/entity'\nimport { heroOf } from '#engine/hero'\nimport { statsOf } from '#engine/stats'\nimport type { World } from '#engine/world'\n\n/**\n * An amount with what the stats of the caster, and the levels of a hero, add to it\n *\n * @beta\n */\nexport function scaled(world: World, caster: Entity, amount: number, scaling: Scaling | undefined, level: number): number {\n\tif (!scaling) return amount\n\t// the same arithmetic as what an ability says it does (`describeAbility`): the two never disagree\n\treturn scaledParts(amount, scaling, level, casterFacts(world, caster)).total\n}\n\n/**\n * What an entity brings to the numbers of its abilities, now (see `CasterFacts`)\n *\n * @beta\n */\nexport function casterFacts(world: World, caster: Entity): CasterFacts {\n\treturn { stats: statsOf(world, caster), heroLevel: heroOf(caster)?.level ?? 1, ownAttackDamage: ownAttackDamage(world, caster) }\n}\n\n/** The attack damage an entity has from its type and its levels, with nothing it carries or that is on it */\nfunction ownAttackDamage(world: World, entity: Entity): number {\n\tconst grown = ((heroOf(entity)?.level ?? 1) - 1) * (entity.def.hero?.growth.stats?.attackDamage ?? 0)\n\treturn baseStats(entity.def, world.registry).attackDamage + grown\n}\n","import { buffApplied, buffRemoved } from '#engine/engineEvents'\nimport { type AbilityDef, at, type BuffCheck, type BuffDef, type Layer, type Scaled } from '#engine/defs'\nimport type { BuffInstance, Entity } from '#engine/entity'\nimport { buffEffects } from './land'\nimport { scaled } from './scaled'\nimport type { World } from '#engine/world'\nimport { replicateEvent } from '../replication'\n\n/**\n * Auras keep their buff alive by renewing it. It wears off this long after leaving the aura\n *\n * @beta\n */\nexport const AURA_LINGER = 0.75\n\n/** @beta */\nexport function hasBuff(entity: Entity, buff: string): boolean {\n\treturn entity.buffs.some((instance) => instance.id === buff)\n}\n\n/**\n * Puts a buff on an entity. Buffs do not stack with themselves: a second one of the\n * same kind renews the first when it lasts longer.\n *\n * @beta\n */\nexport function applyBuff(world: World, target: Entity, buff: string, duration?: number, source?: Entity, level = 1, ability?: string): void {\n\tif (!target.alive) return\n\tconst def = world.registry.buff(buff)\n\tlet remaining = duration ?? def.duration ?? Infinity\n\tif (world.hooks.has('beforeBuff')) {\n\t\tconst before = world.hooks.run('beforeBuff', { target, buff: def, source, level, duration: remaining, cancelled: false })\n\t\tif (before.cancelled) return\n\t\tlevel = before.level\n\t\tremaining = before.duration\n\t}\n\tconst shield = def.shield === undefined ? undefined : fullShield(world, def, source ?? target, level)\n\tconst from = source?.id ?? 0\n\tconst policy = def.stacking ?? 'strongest'\n\t// the one of it there is already, that this one is about: none for those that are each of their own\n\tconst existing =\n\t\tpolicy === 'independent'\n\t\t\t? undefined\n\t\t\t: target.buffs.find((instance) => instance.id === buff && (policy !== 'perSource' || instance.source === from))\n\tif (existing) {\n\t\tconst decision =\n\t\t\ttypeof policy === 'function'\n\t\t\t\t? policy(existing, { level, duration: remaining, source: from })\n\t\t\t\t: policy === 'refresh'\n\t\t\t\t\t? 'replace'\n\t\t\t\t\t: // the stronger one wins, the longer one among equals\n\t\t\t\t\t\tlevel > existing.level\n\t\t\t\t\t\t? 'replace'\n\t\t\t\t\t\t: level === existing.level && remaining > existing.remaining\n\t\t\t\t\t\t\t? 'renew'\n\t\t\t\t\t\t\t: 'keep'\n\t\tif (decision === 'keep') return\n\t\tconst previousLevel = existing.level\n\t\t// put on again for a time of its own: an aura that keeps it up says so again after (`keptUp`)\n\t\tif (existing.kept) delete existing.kept\n\t\tif (decision === 'replace') {\n\t\t\t// only what the renewer brings: an aura renewing a cast buff keeps its `ability` (its `onEnd`)\n\t\t\tObject.assign(existing, { level, remaining, source: from })\n\t\t\tif (shield !== undefined) existing.shield = shield\n\t\t\tif (ability !== undefined) existing.ability = ability\n\t\t} else if (decision === 'renew') {\n\t\t\texisting.remaining = remaining\n\t\t\t// a shield that is put on again is as good as new\n\t\t\tif (shield !== undefined) existing.shield = Math.max(existing.shield ?? 0, shield)\n\t\t}\n\t\tif (decision !== 'add') {\n\t\t\tworld.events.emit(buffApplied, { target, buff, level: existing.level, source, renewed: true, previousLevel })\n\t\t\treturn\n\t\t}\n\t}\n\t// a buff runs out tick by tick, which scenery does not get\n\tworld.wake(target)\n\tconst instance: BuffInstance = { id: buff, level, remaining, elapsed: 0, source: from, shield, ability }\n\ttarget.addBuff(instance)\n\tworld.events.emit(buffApplied, { target, buff, level, source, renewed: false })\n\tif (typeof def.onApply === 'function') def.onApply(world, target, instance)\n\telse if (def.onApply) buffEffects(world, target, instance, def.onApply)\n}\n\n/** What the shield of a buff holds when it is new */\nexport function fullShield(world: World, def: BuffDef, source: Entity, level: number): number {\n\treturn scaled(world, source, at(def.shield, level), def.shieldScaling, level) * world.rules.combat.healPower(world, source)\n}\n\n/**\n * Takes a buff off, before its time is up: the one of it `source` put on, for buffs each source has their own of, or\n * the first. The `buffEnd` hook hears of it, and the buff's `onRemove`\n *\n * @beta\n */\nexport function removeBuff(world: World, entity: Entity, buff: string, source?: Entity): void {\n\tconst index = entity.buffs.findIndex((instance) => instance.id === buff && (!source || instance.source === source.id))\n\tif (index < 0) return\n\tconst instance = entity.dropBuff(index)!\n\tworld.registry.buff(instance.id).onRemove?.(world, entity, instance, false)\n\tworld.hooks.run('buffEnd', { entity, buff: instance, expired: false })\n\tworld.events.emit(buffRemoved, { entity, buff: instance.id, expired: false })\n}\n\n/**\n * Whether nothing of an ability happens to an entity: it carries a buff that keeps it out of the way of\n * that kind of thing, like someone up in the air when the ground shakes\n */\n/** Whether a flag of a buff holds for its carrier now: as it is declared, or as its function says */\nconst holds = (world: World, carrier: Entity, instance: BuffInstance, flag: boolean | BuffCheck | undefined) =>\n\ttypeof flag === 'function' ? flag(world, carrier, instance) : !!flag\n\n/** Whether an ability gets through a unit's immunity to spells: always, never, or as its function says for the unit */\nexport const pierces = (world: World, ability: AbilityDef, target: Entity): boolean =>\n\ttypeof ability.piercesImmunity === 'function' ? ability.piercesImmunity(world, target) : !!ability.piercesImmunity\n\n/** Whether a buff a unit carries keeps it from attacking now (`BuffDef.disarm`) */\nexport const isDisarmed = (world: World, entity: Entity): boolean =>\n\tentity.buffs.some((instance) => holds(world, entity, instance, world.registry.buff(instance.id).disarm))\n\n/**\n * Whether a unit is immune to spells: by its type, or a buff it carries (an avatar), as declared or as code decides\n *\n * @beta\n */\nexport function isSpellImmune(world: World, entity: Entity): boolean {\n\tconst own = entity.def.spellImmune\n\tif (typeof own === 'function' ? own(world, entity) : own) return true\n\treturn entity.buffs.some((instance) => holds(world, entity, instance, world.registry.buff(instance.id).spellImmune))\n}\n\n/** @beta */\nexport function avoids(world: World, entity: Entity, ability: AbilityDef): boolean {\n\t// immune to spells: nothing of one happens to it, unless it gets through\n\tif (!pierces(world, ability, entity) && isSpellImmune(world, entity)) return true\n\tconst { tags } = ability\n\tif (!tags?.length || !entity.buffs.length) return false\n\treturn entity.buffs.some((instance) => world.registry.buff(instance.id).avoids?.some((tag) => tags.includes(tag)))\n}\n\n/** Whether a buff keeps a unit from doing what it wants: stuns and slows. Tenacity cuts those short */\nexport function isCrowdControl(def: BuffDef): boolean {\n\tif (!def.harmful) return false\n\tif (def.stun || def.airborne || def.grounds || def.root || def.silence) return true\n\tconst slower = (value: Scaled | undefined) => value !== undefined && at(value, 1) < 0\n\treturn slower(def.percent?.moveSpeed) || slower(def.percent?.attackSpeed)\n}\n\n/** @beta */\nexport const isStunned = (world: World, entity: Entity) =>\n\tentity.buffs.some((instance) => {\n\t\tconst def = world.registry.buff(instance.id)\n\t\treturn def.airborne || holds(world, entity, instance, def.stun)\n\t})\n\n/**\n * Held to the spot: it can do everything but walk\n *\n * @beta\n */\nexport const isRooted = (world: World, entity: Entity) =>\n\tentity.buffs.some((instance) => holds(world, entity, instance, world.registry.buff(instance.id).root))\n\n/**\n * Kept from using its abilities: from this one, when it says which (a silence of fire spells only). Without an\n * ability, whether anything keeps it from using some\n *\n * @beta\n */\nexport const isSilenced = (world: World, entity: Entity, ability?: AbilityDef) =>\n\tentity.buffs.some((instance) => silences(world.registry.buff(instance.id).silence, ability))\n\n/**\n * Whether a buff's `silence` keeps its carrier from an ability, or from any when none is said. For both ends\n *\n * @beta\n */\nexport const silences = (silence: BuffDef['silence'], ability?: AbilityDef): boolean =>\n\ttypeof silence === 'function' ? (ability ? silence(ability) : true) : !!silence\n\n/**\n * Where an entity is right now. What flies is in the air, unless something holds it down\n *\n * @beta\n */\nexport function layerOf(world: World, entity: Entity): Layer {\n\tif (!entity.flying) return 'ground'\n\treturn entity.buffs.some((instance) => world.registry.buff(instance.id).grounds) ? 'ground' : 'air'\n}\n\n/**\n * What is left of the shields on an entity\n *\n * @beta\n */\nexport function shieldOf(entity: Entity): number {\n\tlet total = 0\n\tfor (const instance of entity.buffs) total += instance.shield ?? 0\n\treturn total\n}\n\n/** Lets the shields of an entity take damage. Returns what they could not hold */\nexport function absorb(entity: Entity, amount: number): number {\n\tlet left = amount\n\tfor (const instance of entity.buffs) {\n\t\tif (!instance.shield || left <= 0) continue\n\t\tconst taken = Math.min(instance.shield, left)\n\t\tinstance.shield -= taken\n\t\tleft -= taken\n\t}\n\treturn left\n}\n\n/**\n * A buff put on, to those who see who has it. Put on again, only where its level changed: an aura renews its buff\n * every round, and what is left of it is the snapshot's (`EntityState.buffTimes`)\n */\nexport const toldBuffOn = replicateEvent(buffApplied, 'buff', ({ target, buff, level, source, renewed, previousLevel }, view) =>\n\tview.knows(target) && !(renewed && previousLevel === level)\n\t\t? { type: 'buff', id: target.id, buff, on: true, level, renewed, source: source && view.knows(source) ? source.id : undefined }\n\t\t: undefined\n)\n\n/** A buff gone, to those who see who had it */\nexport const toldBuffOff = replicateEvent(buffRemoved, 'buff', ({ entity, buff }, view) =>\n\tview.knows(entity) ? { type: 'buff', id: entity.id, buff, on: false } : undefined\n)\n","import { layerOf } from '#engine/abilities/buffs'\nimport type { AttackDef, AttackStats, Layer, Stats, UnitTypeDef } from '#engine/defs'\nimport { edgeDistance, type Entity } from '#engine/entity'\nimport { statsOf } from '#engine/stats'\nimport type { World } from '#engine/world'\n\n/*\n * A unit's attacks (`UnitTypeDef.attacks`, the classic RTS two weapons): what each reaches, which one it uses against\n * a target, and its numbers by the stats it reads. Apart from the combat system, for what counts room and reach\n * (`engagement.ts`, the stances pack) to ask without loading it\n */\n\nconst KINDS = ['unit', 'building', 'resource']\n\n/**\n * Whether an attack that is for these targets is for this one\n *\n * @beta\n */\nexport function reaches(targets: AttackDef['targets'], target: { def: UnitTypeDef }, layer?: Layer): boolean {\n\tconst flying = layer ? layer === 'air' : target.def.flying === true\n\tif (!targets) return !flying\n\tif (flying ? !targets.includes('air') : targets.includes('air') && !targets.includes('ground')) return false\n\t// kinds only count when some are named\n\treturn targets.includes(target.def.kind) || !targets.some((entry) => KINDS.includes(entry))\n}\n\n/**\n * The stats an attack reads when it names none of its own (`AttackDef.stats`)\n *\n * @internal\n */\nexport const ATTACK_STATS: Readonly<Required<AttackStats>> = Object.freeze({ damage: 'attackDamage', speed: 'attackSpeed', range: 'attackRange' })\n\n/**\n * How hard, how fast or how far an attack hits, from the attacker's stats: the stat the attack names\n * (`AttackDef.stats`), or the unit's own (`attackDamage`, `attackSpeed`, `attackRange`). The unit's own for no attack\n *\n * @beta\n */\nexport function attackStat(stats: Readonly<Stats>, attack: AttackDef | undefined, which: keyof AttackStats): number {\n\treturn stats[attack?.stats?.[which] ?? ATTACK_STATS[which]] ?? 0\n}\n\n/**\n * The first of an attacker's attacks that reaches the target where it is (its `targets`), by place, or -1 for none:\n * the engine's `GameRules.combat.pickAttack`\n *\n * @beta\n */\nexport function defaultPickAttack(world: World, attacker: Entity, target: Entity): number {\n\tconst attacks = attacker.def.attacks\n\tif (!attacks) return -1\n\tconst layer = target.flying ? layerOf(world, target) : 'ground'\n\t// the first that reaches where it is and of which it is not too near (`AttackDef.minRange`); else the first that\n\t// reaches where it is, too near or not (the unit steps back to use it)\n\tlet reaching = -1\n\tlet distance = -1\n\tfor (let i = 0; i < attacks.length; i++) {\n\t\tif (!reaches(attacks[i].targets, target, layer)) continue\n\t\tconst near = attacks[i].minRange\n\t\tif (!near) return i\n\t\tif (distance < 0) distance = edgeDistance(attacker, target)\n\t\tif (distance >= near) return i\n\t\tif (reaching < 0) reaching = i\n\t}\n\treturn reaching\n}\n\n/**\n * Whether a target is too near for one of an attacker's attacks (`AttackDef.minRange`), by place in its attacks: within\n * its dead zone, edge to edge\n *\n * @beta\n */\nexport function tooNear(attacker: Entity, target: Entity, weapon: number): boolean {\n\tconst near = attacker.def.attacks?.[weapon]?.minRange\n\treturn !!near && edgeDistance(attacker, target) < near\n}\n\n/**\n * Which of an attacker's attacks it uses against a target, by place in `UnitTypeDef.attacks`, as the game's rules pick\n * it (`GameRules.combat.pickAttack`): -1 for none, its attacks reach not where the target is\n *\n * @beta\n */\nexport function pickAttack(world: World, attacker: Entity, target: Entity): number {\n\treturn attacker.def.attacks?.length ? world.rules.combat.pickAttack(world, attacker, target) : -1\n}\n\n/**\n * The farthest any attack of a type looks for enemies by itself (`AttackDef.acquisitionRange`): the engine's\n * `GameRules.combat.acquisitionRange`. 0 for what does not attack\n *\n * @beta\n */\nexport function farthestAcquisition(def: UnitTypeDef): number {\n\tlet most = 0\n\tfor (const attack of def.attacks ?? []) if (attack.acquisitionRange > most) most = attack.acquisitionRange\n\treturn most\n}\n\n/**\n * How far the farthest of a unit's attacks reaches, by its stats (its `attackRange`, or a stat an attack names): what\n * it may hit anything from. 0 for what does not attack\n *\n * @beta\n */\nexport function farthestReach(def: UnitTypeDef, stats: Readonly<Stats>): number {\n\tconst attacks = def.attacks\n\tif (!attacks?.length) return 0\n\tlet most = attackStat(stats, attacks[0], 'range')\n\tfor (let i = 1; i < attacks.length; i++) most = Math.max(most, attackStat(stats, attacks[i], 'range'))\n\treturn most\n}\n\n/**\n * How far an attacker's attack reaches a target: the range of the one it uses against it (`pickAttack`), the first's\n * when none does\n *\n * @beta\n */\nexport function rangeAgainst(world: World, attacker: Entity, target: Entity): number {\n\tconst attacks = attacker.def.attacks\n\tconst attack = attacks && attacks.length > 1 ? attacks[Math.max(pickAttack(world, attacker, target), 0)] : attacks?.[0]\n\treturn attackStat(statsOf(world, attacker), attack, 'range')\n}\n\n/**\n * The first of a type's attacks that can be told to attack the ground (`AttackDef.ground`), by place, or -1 for none\n *\n * @beta\n */\nexport function groundAttack(def: UnitTypeDef): number {\n\treturn def.attacks?.findIndex((attack) => attack.ground) ?? -1\n}\n","import type { Entity, EntityId } from './entity'\nimport type { Vec2 } from './math'\nimport { statsOf } from './stats'\nimport { rangeAgainst } from './attacks'\nimport type { World } from './world'\nimport { atan2, cos, sin } from './exactMath'\nimport { moving, fighting } from './entity'\n\n/*\n * Who fights whom, and where around them: so that a crowd spreads around what it fights instead of queueing behind\n * the first to get there, picks another enemy when one is full, and does not stand still behind its own.\n *\n * An attacker fighting or closing in on a target is engaged with it (`CombatState.engaged`). Around every target there\n * is room for so many attackers at once (`GameRules.combat.engageRoom`), counted apart for each layer they fight from\n * (`GameRules.combat.engageLayer`: the ground, the air, the water, or a game's own) and for how far they reach: the melee in\n * one ring, short bows in a wider one, long guns in one wider still. Melee and the like take a spot of their own on\n * their ring (`CombatState.slot`), and walk there, which is what makes them surround it. A unit that picked a target\n * itself and cannot get at it for a while (`GameRules.combat.giveUpChase`) lets it go, and leaves it alone for a few seconds.\n *\n * All of it is the engine's way until a game says otherwise: the rules, the `targetScore` hook (which is told how full\n * a target is) and the `approach` hook (where an attacker goes to fight). And all of it can be asked about, from here.\n */\n\n/**\n * Where an attacker fights from: `ground`, `air` and `water` for the engine, any other name for a game's own\n *\n * @beta\n */\nexport type EngageLayer = 'ground' | 'air' | 'water' | (string & {})\n\n/** How wide one ring of reach is: attackers whose ranges are this close fight from the same ring */\nconst BAND = 1.5\n/** Spots on a ring at most: past that, room is there for everyone */\nconst MOST_SLOTS = 48\n/**\n * Seconds a target that could not be got at is left alone (see `shun`)\n *\n * @beta\n */\nexport const SHUN_TIME = 4\n\n/**\n * The ring an attacker fights from, by its reach: 0 for the melee\n *\n * @beta\n */\nexport function bandOf(world: World, attacker: Entity): number {\n\treturn Math.floor(statsOf(world, attacker).attackRange / BAND)\n}\n\n/**\n * The layer an attacker fights from, as the game's rules say (`GameRules.combat.engageLayer`)\n *\n * @beta\n */\nexport function engageLayer(world: World, attacker: Entity): EngageLayer {\n\treturn world.rules.combat.engageLayer(world, attacker)\n}\n\n/**\n * The engine's: from the air for what flies, from the water for boats, from the ground for the rest\n *\n * @beta\n */\nexport function defaultEngageLayer(_world: World, attacker: Entity): EngageLayer {\n\treturn attacker.flying ? 'air' : attacker.def.naval ? 'water' : 'ground'\n}\n\n/**\n * The engine's room around a target for attackers like this one: as many as stand side by side around it, on the ring\n * they fight from. Few for the melee around a footman, many around a town hall, all of them for long guns\n *\n * @beta\n */\nexport function defaultEngageRoom(world: World, target: Entity, attacker: Entity): number {\n\tconst reach = rangeAgainst(world, attacker, target)\n\tconst width = attacker.def.radius * 2 + 0.15\n\tconst footprint = target.def.footprint\n\tconst edge = footprint ? 2 * (footprint.w + footprint.d) : 2 * Math.PI * target.def.radius\n\treturn Math.max(1, Math.floor((edge + 2 * Math.PI * (attacker.def.radius + reach)) / width))\n}\n\n/**\n * How many attackers like this one may fight the target at once, as the game's rules say (`GameRules.combat.engageRoom`)\n *\n * @beta\n */\nexport function roomFor(world: World, target: Entity, attacker: Entity): number {\n\treturn world.rules.combat.engageRoom(world, target, attacker)\n}\n\n/** Who is engaged with whom, worked out again once a tick, when first asked */\nconst index = new WeakMap<World, { tick: number; by: Map<EntityId, Entity[]> }>()\n\nfunction engagements(world: World): Map<EntityId, Entity[]> {\n\tlet cached = index.get(world)\n\tif (cached?.tick === world.tick) return cached.by\n\tif (!cached) index.set(world, (cached = { tick: world.tick, by: new Map() }))\n\tcached.tick = world.tick\n\tcached.by.clear()\n\tfor (const entity of world.actors.values()) {\n\t\tconst target = entity.get(fighting)?.engaged\n\t\tif (!target || !entity.alive) continue\n\t\tconst list = cached.by.get(target)\n\t\tif (list) list.push(entity)\n\t\telse cached.by.set(target, [entity])\n\t}\n\treturn cached.by\n}\n\n/** Takes the attacker off the list of what it was engaged with, in this tick's index */\nfunction unlist(world: World, attacker: Entity): void {\n\tconst id = attacker.get(fighting)?.engaged\n\tconst cached = index.get(world)\n\tif (!id || cached?.tick !== world.tick) return\n\tconst list = cached.by.get(id)\n\tconst at = list?.indexOf(attacker) ?? -1\n\tif (at >= 0) list!.splice(at, 1)\n}\n\n/**\n * Everyone fighting the target or closing in on it: of one layer only, when one is named\n *\n * @beta\n */\nexport function attackersOf(world: World, target: Entity, layer?: EngageLayer): Entity[] {\n\tconst all = engagements(world).get(target.id) ?? []\n\treturn layer === undefined ? [...all] : all.filter((attacker) => engageLayer(world, attacker) === layer)\n}\n\n/**\n * How many attackers like this one (the same layer, the same ring) the target has already, the attacker left out\n *\n * @beta\n */\nexport function engagedLike(world: World, target: Entity, attacker: Entity): number {\n\tconst all = engagements(world).get(target.id)\n\tif (!all) return 0\n\tconst layer = engageLayer(world, attacker)\n\tconst band = bandOf(world, attacker)\n\tlet count = 0\n\tfor (const other of all) if (other !== attacker && engageLayer(world, other) === layer && bandOf(world, other) === band) count++\n\treturn count\n}\n\n/**\n * Whether the target has no room left for another attacker like this one\n *\n * @beta\n */\nexport function isCrowded(world: World, target: Entity, attacker: Entity): boolean {\n\treturn engagedLike(world, target, attacker) >= roomFor(world, target, attacker)\n}\n\n/**\n * What the attacker is fighting or closing in on, if anything\n *\n * @beta\n */\nexport function engagedWith(world: World, attacker: Entity): Entity | undefined {\n\tconst id = attacker.get(fighting)?.engaged\n\treturn id ? world.get(id) : undefined\n}\n\n/**\n * Marks the attacker engaged with the target, giving it a spot around it when it fights from close by (and has none\n * there yet). The engine does this as a unit fights or closes in; a game's own fighting can too\n *\n * @beta\n */\nexport function engageWith(world: World, attacker: Entity, target: Entity): void {\n\tconst combat = attacker.get(fighting)\n\tif (!combat) return\n\tif (combat.engaged === target.id && combat.slot !== null) return\n\tif (combat.engaged !== target.id) {\n\t\t// others picking in the same tick see it at once\n\t\tunlist(world, attacker)\n\t\tconst by = engagements(world)\n\t\tconst list = by.get(target.id)\n\t\tif (list) list.push(attacker)\n\t\telse by.set(target.id, [attacker])\n\t}\n\tcombat.engaged = target.id\n\tcombat.slot = null\n\t// what flies goes over, what hits a building goes to its nearest side: no spot to keep\n\tif (attacker.flying || target.def.footprint) return\n\tcombat.slot = chooseSlot(world, attacker, target)\n}\n\n/**\n * Lets go of whatever the attacker was engaged with, and of its spot there\n *\n * @beta\n */\nexport function release(attacker: Entity, world?: World): void {\n\tconst combat = attacker.get(fighting)\n\tif (!combat) return\n\tif (world && combat.engaged) unlist(world, attacker)\n\tcombat.engaged = 0\n\tcombat.slot = null\n}\n\n/**\n * A free spot around the target for the attacker, as an angle seen from the target: the one nearest the side it comes\n * from, of those on its ring that no one like it holds. Where it is, when every one is held\n */\nfunction chooseSlot(world: World, attacker: Entity, target: Entity): number {\n\t// `+ 0` makes a -0 (the round of a small negative, an angle of nothing below the axis) 0: a save writes -0 as 0, and a\n\t// loaded game must hold what the game it was saved from holds\n\tconst from = atan2(attacker.pos.x - target.pos.x, attacker.pos.z - target.pos.z) + 0\n\tconst count = Math.min(roomFor(world, target, attacker), MOST_SLOTS)\n\tif (count <= 1) return from\n\tconst step = (Math.PI * 2) / count\n\tconst held = new Set<number>()\n\tconst layer = engageLayer(world, attacker)\n\tconst band = bandOf(world, attacker)\n\tfor (const other of engagements(world).get(target.id) ?? []) {\n\t\tconst slot = other.get(fighting)?.slot\n\t\tif (other === attacker || slot === null || slot === undefined) continue\n\t\tif (engageLayer(world, other) !== layer || bandOf(world, other) !== band) continue\n\t\theld.add(((Math.round(slot / step) % count) + count) % count)\n\t}\n\tconst nearest = Math.round(from / step)\n\t// out from the nearest, one side and then the other\n\tfor (let i = 0; i <= count / 2; i++) {\n\t\tfor (const at of i === 0 ? [nearest] : [nearest + i, nearest - i]) {\n\t\t\tif (!held.has(((at % count) + count) % count)) return at * step + 0\n\t\t}\n\t}\n\treturn from\n}\n\n/**\n * Where the attacker goes to fight the target from: its spot around it, out where its weapon reaches, or the target\n * itself without one. The game's `approach` hook has the last word\n *\n * @beta\n */\nexport function spotFor(world: World, attacker: Entity, target: Entity): Vec2 {\n\tconst slot = attacker.get(fighting)?.engaged === target.id ? attacker.get(fighting)!.slot : null\n\tlet point: Vec2 = target.pos\n\tif (slot !== null && slot !== undefined) {\n\t\t// on its side of the target and well inside its reach, so that it walks on until it is in reach: units keep a\n\t\t// little more apart than they are wide, and a spot right at the edge of its reach is one it may never get to\n\t\tconst reach = rangeAgainst(world, attacker, target)\n\t\tconst out = Math.max(target.def.radius + attacker.def.radius + reach * 0.5 - 0.5, target.def.radius * 0.5)\n\t\tpoint = { x: target.pos.x + sin(slot) * out, z: target.pos.z + cos(slot) * out }\n\t}\n\tif (!world.hooks.has('approach')) return point\n\treturn world.hooks.run('approach', { attacker, target, point }).point\n}\n\n/**\n * Whether the attacker has been closing in on the target for longer than the game lets it (`GameRules.combat.giveUpChase`) without getting closer\n *\n * @beta\n */\nexport function isBlocked(world: World, attacker: Entity, target: Entity): boolean {\n\tconst m = attacker.get(moving)\n\tif (!m || m.goalEntity !== target.id) return false\n\tconst stalled = m.status === 'failed' ? Infinity : m.status === 'moving' ? m.stalledTime : 0\n\treturn stalled > world.rules.combat.giveUpChase(world, attacker, target)\n}\n\n/**\n * Has the attacker leave the target alone for a while: not picked by itself again until then\n *\n * @beta\n */\nexport function shun(world: World, attacker: Entity, target: Entity, seconds = SHUN_TIME): void {\n\tconst combat = attacker.get(fighting)\n\tif (!combat) return\n\tconst until = world.time + seconds\n\tcombat.shunned = (combat.shunned ?? []).filter(([id, end]) => id !== target.id && end > world.time)\n\tcombat.shunned.push([target.id, until])\n}\n\n/**\n * Whether the attacker leaves the target alone for now (see `shun`)\n *\n * @beta\n */\nexport function isShunned(world: World, attacker: Entity, target: Entity): boolean {\n\tconst shunned = attacker.get(fighting)?.shunned\n\tif (!shunned?.length) return false\n\tfor (const [id, until] of shunned) if (id === target.id && until > world.time) return true\n\treturn false\n}\n","import { distanceToEdge, edgeDistance, type Entity } from '#engine/entity'\nimport { closestPointOnRect, dist, rotateTowards, type Vec2 } from '#engine/math'\nimport type { AgentState, Navigation } from '#engine/navigation/navigation'\nimport type { System } from '#engine/registry'\nimport type { World } from '#engine/world'\nimport { spotFor } from '#engine/engagement'\nimport { atan2, hypot } from '#engine/exactMath'\nimport { type MovementState, moving, fighting } from '../entity'\n\n/**\n * How close to a point counts as having reached it\n *\n * @internal\n */\nexport const ARRIVE_RANGE = 0.2\nconst DEFAULT_TURN_RATE = 12\n\n/** @beta */\nexport interface MoveOptions {\n\t/** Arrive once this close to the goal. `ARRIVE_RANGE` when left out */\n\trange?: number\n\tgroupId?: number\n\t/** Direction to turn to after arriving */\n\tfacing?: number\n\t/**\n\t * A step aside for another (`stepAside`), or any short move that is nobody's business: the unit goes round nobody\n\t * and asks nobody to make way on it, so that one step does not set off the next\n\t */\n\taside?: boolean\n}\n\n/**\n * Point a unit should walk to in order to reach the target: next to its edge for structures, its spot around it for\n * one fighting it (see `engagement.ts`)\n */\nexport function approachPoint(world: World, entity: Entity, target: Entity): Vec2 {\n\t// what flies goes right over it\n\tif (entity.flying) return target.pos\n\tif (target.def.footprint) return closestPointOnRect(entity.pos, target.rect, entity.def.radius + 0.15)\n\treturn entity.get(fighting)?.engaged === target.id ? spotFor(world, entity, target) : target.pos\n}\n\n/**\n * How far along its route a unit is sent at a time (`GameModule.paths: 'seen'`): as far as it sees, between 4 and 12.\n * The navigation finds its way over that stretch with every building in it; one that changes the way is in sight, so\n * its side sees it, and the route is planned again with it\n */\nconst stretchOf = (entity: Entity): number => Math.min(Math.max(entity.def.sight ?? 8, 4), 12)\n\n/** The team whose knowledge a ground unit's route is planned with, or none where routes know everything */\n/** The movement of a unit this system runs for: it picks those that have one, so a unit without is a fault, said as such */\nfunction movementOf(entity: Entity): MovementState {\n\tconst m = entity.get(moving)\n\tif (!m) throw new Error(`${entity.def.id} ${entity.id} is moved but has no movement`)\n\treturn m\n}\n\nfunction sideOf(world: World, entity: Entity): number | undefined {\n\tconst paths = world.sidePaths\n\tif (!paths || entity.flying || entity.def.naval) return undefined\n\tconst team = world.player(entity.owner).team\n\treturn paths.has(team) ? team : undefined\n}\n\n/** Plans a unit's route to its goal with what its side knows: none where its side knows no way, or the goal is in sight */\nfunction planRoute(world: World, entity: Entity, team: number): void {\n\tconst m = movementOf(entity)\n\t// (planned only for a team `sideOf` found paths for)\n\tconst paths = world.sidePaths\n\tif (!paths) return\n\tm.routeVersion = paths.version(team)\n\tm.routeAt = 1\n\t// a goal within sight is walked to as it is: all of the way there is in sight (a melee spot, a step aside)\n\tif (dist(entity.pos, m.navGoal) <= stretchOf(entity)) {\n\t\tm.route = undefined\n\t\treturn\n\t}\n\tconst route = paths.route(team, entity.pos, m.navGoal)\n\tm.route = route && route.length > 1 ? route.map(({ x, z }) => ({ x, z })) : undefined\n}\n\n/** How far a point is from a segment */\nfunction distToSegment(p: Vec2, a: Vec2, b: Vec2): number {\n\tconst dx = b.x - a.x\n\tconst dz = b.z - a.z\n\tconst length = dx * dx + dz * dz\n\tconst t = length > 0 ? Math.min(Math.max(((p.x - a.x) * dx + (p.z - a.z) * dz) / length, 0), 1) : 0\n\treturn hypot(p.x - (a.x + dx * t), p.z - (a.z + dz * t))\n}\n\n/** The point a stretch ahead of a unit along its route; its goal itself once that is within the stretch */\nfunction stretchPoint(entity: Entity): Vec2 {\n\tconst m = movementOf(entity)\n\tconst route = m.route\n\tif (!route) return m.navGoal\n\t// where along the route it is: the leg nearest it, from where it was on, and the corner that leg ends at next. A\n\t// unit pushed aside, or cutting a corner, is on the route where it is nearest it\n\tlet leg = Math.max((m.routeAt ?? 1) - 1, 0)\n\tlet nearest = Infinity\n\tfor (let i = leg; i < route.length - 1; i++) {\n\t\tconst d = distToSegment(entity.pos, route[i], route[i + 1])\n\t\tif (d < nearest - 1e-9) {\n\t\t\tnearest = d\n\t\t\tleg = i\n\t\t}\n\t}\n\tconst at = Math.min(leg + 1, route.length - 1)\n\tm.routeAt = at\n\tlet left = stretchOf(entity)\n\tlet from: Vec2 = entity.pos\n\tfor (let i = at; i < route.length; i++) {\n\t\tconst length = dist(from, route[i])\n\t\tif (length >= left) {\n\t\t\tconst t = left / length\n\t\t\treturn { x: from.x + (route[i].x - from.x) * t, z: from.z + (route[i].z - from.z) * t }\n\t\t}\n\t\tleft -= length\n\t\tfrom = route[i]\n\t}\n\treturn m.navGoal\n}\n\n/** Sends the navigation where the unit is to walk now: its goal, or a stretch along its route */\nfunction walk(world: World, entity: Entity): boolean {\n\tconst m = movementOf(entity)\n\tconst to = m.route ? stretchPoint(entity) : m.navGoal\n\tm.stretch = m.route ? { x: to.x, z: to.z } : undefined\n\treturn world.nav.setDestination(entity.id, to)\n}\n\n/** Sends a walking unit on as it was, after something held it (a builder waiting for room): its stretch, or its goal */\nexport function walkOn(world: World, entity: Entity): void {\n\tif (entity.get(moving)?.status === 'moving') walk(world, entity)\n}\n\nfunction beginMove(world: World, entity: Entity, navGoal: Vec2): void {\n\tconst m = movementOf(entity)\n\tm.bestDistance = Infinity\n\tm.finalFacing = null\n\tm.stalledTime = 0\n\tm.slowTime = 0\n\tm.detour = undefined\n\tm.navGoal.x = navGoal.x\n\tm.navGoal.z = navGoal.z\n\tm.navVersion = world.nav.version\n\tm.stuck = false\n\tif (m.anchored) {\n\t\tm.anchored = false\n\t\tworld.nav.setAnchored(entity.id, false)\n\t}\n\tconst team = sideOf(world, entity)\n\tif (team === undefined) m.route = undefined\n\telse planRoute(world, entity, team)\n\tm.status = walk(world, entity) ? 'moving' : 'failed'\n}\n\n/**\n * Sends a unit walking to a point, the way around what is in the way. How it goes is in `entity.movement.status`:\n * `moving` on the way, `arrived` once there, `failed` when there is no way there or it got stuck. An order calls\n * this once and then watches the status; calling it again with the same goal starts the walk over\n *\n * @beta\n */\nexport function moveTo(world: World, entity: Entity, goal: Vec2, options: MoveOptions = {}): void {\n\tconst m = entity.get(moving)\n\tif (!m || entity.hidden) return\n\tm.goal.x = goal.x\n\tm.goal.z = goal.z\n\tm.goalEntity = 0\n\tm.range = options.range ?? ARRIVE_RANGE\n\tm.groupId = options.groupId ?? 0\n\tm.aside = options.aside || undefined\n\tbeginMove(world, entity, goal)\n\tm.finalFacing = options.facing ?? null\n}\n\n/**\n * Walks towards an entity until within `range` of its edge. Safe to call every tick.\n *\n * @beta\n */\nexport function moveToEntity(world: World, entity: Entity, target: Entity, range: number): void {\n\tconst m = entity.get(moving)\n\tif (!m || entity.hidden) return\n\tif (m.status === 'moving' && m.goalEntity === target.id && m.range === range) return\n\tm.goalEntity = target.id\n\tm.range = range\n\tm.groupId = 0\n\tm.aside = undefined\n\tbeginMove(world, entity, approachPoint(world, entity, target))\n}\n\n/**\n * Whether the unit is on its way to this very point\n *\n * @internal\n */\nexport function isMovingTo(entity: Entity, goal: Vec2): boolean {\n\tconst m = entity.get(moving)\n\treturn !!m && m.status === 'moving' && m.goalEntity === 0 && m.goal.x === goal.x && m.goal.z === goal.z\n}\n\n/**\n * Stops a unit where it is. Its status is `idle` after\n *\n * @beta\n */\nexport function halt(world: World, entity: Entity): void {\n\tconst m = entity.get(moving)\n\tif (!m) return\n\tif (m.status === 'moving') world.nav.clearDestination(entity.id)\n\tm.status = 'idle'\n\tm.goalEntity = 0\n\tm.groupId = 0\n\tm.detour = undefined\n}\n\n/**\n * Anchored units stand their ground instead of being pushed around by units walking past.\n *\n * @beta\n */\nexport function setAnchored(world: World, entity: Entity, anchored: boolean): void {\n\tconst m = entity.get(moving)\n\tif (!m || m.anchored === anchored) return\n\tif (anchored && m.status === 'moving') halt(world, entity)\n\tm.anchored = anchored\n\tworld.nav.setAnchored(entity.id, anchored)\n}\n\n/**\n * Ghosts walk through other units. Classic RTS games do this for workers hauling resources so mining never jams.\n *\n * @beta\n */\nexport function setGhost(world: World, entity: Entity, ghost: boolean): void {\n\tconst m = entity.get(moving)\n\tif (!m || m.ghost === ghost) return\n\tm.ghost = ghost\n\tworld.nav.setGhost(entity.id, ghost)\n}\n\n/**\n * Turns a unit a little towards a point, as far as it turns in `dt` seconds. For orders that aim at something\n *\n * @beta\n */\nexport function faceTowards(entity: Entity, point: Vec2, dt: number): void {\n\tconst m = entity.get(moving)\n\tif (m) m.finalFacing = null\n\tconst desired = atan2(point.x - entity.pos.x, point.z - entity.pos.z)\n\tentity.facing = rotateTowards(entity.facing, desired, (entity.def.turnRate ?? DEFAULT_TURN_RATE) * dt)\n}\n\nfunction arrive(world: World, entity: Entity): void {\n\tworld.nav.clearDestination(entity.id)\n\tmovementOf(entity).status = 'arrived'\n}\n\n/** True when the unit is bumping into a member of its own group that already reached its spot. */\nfunction blockedByArrivedGroupMate(world: World, entity: Entity): boolean {\n\tconst m = movementOf(entity)\n\tif (!m.groupId) return false\n\tworld.spatial.query(entity.pos.x, entity.pos.z, entity.def.radius + 1, neighbours)\n\tfor (const other of neighbours) {\n\t\tconst om = other.get(moving)\n\t\tif (other === entity || !om || other.flying !== entity.flying) continue\n\t\tif (om.groupId !== m.groupId || om.status !== 'arrived') continue\n\t\tif (distanceToEdge(entity.pos, other) - entity.def.radius < 0.25) return true\n\t}\n\treturn false\n}\n\n/** Seconds a unit has to be held up before the ones in its way are asked to move */\nconst MAKE_WAY_AFTER = 0.2\n/** Ticks between two requests by the same unit */\nconst MAKE_WAY_INTERVAL = 8\n/** Ticks between two looks ahead by the same unit, for units standing in its way */\nconst LOOK_AHEAD_INTERVAL = 4\n/** Room a unit keeps between itself and the units it goes round, past touching them */\nconst DETOUR_CLEARANCE = 0.3\n/**\n * How far past the point beside a knot a unit going round it is sent on, towards its corner, once it is nearly there\n * (`DETOUR_PAST_AT`): an agent slows down as it comes to where it was sent, and this way it is on its way again, at\n * speed, before that\n */\nconst DETOUR_PAST = 1.5\nconst DETOUR_PAST_AT = 1.2\n/** Under this part of its speed, a unit on its way counts as held up */\nconst SLOW_PART = 0.6\n/** Units standing in a knot past this many are not gone round: the way round them is for the path to find */\nconst KNOT_MOST = 24\n\n/**\n * Whether another unit stands in a mover's way: there, standing still, and on the same crowd, where each steers\n * round the other and neither walks through. What moves is steered round by the navigation; what is a ghost is walked\n * through; what flies, sails or is of another size goes its own way. What the mover walks to, or stands where it is\n * going, is not in its way either: it stops by it, close enough (a follower by the one it follows, a unit sent where\n * another stands), rather than send it off\n *\n * @beta\n */\nexport function standsInWay(world: World, mover: Entity, other: Entity): boolean {\n\tconst om = other.get(moving)\n\tif (other === mover || !om || other.hidden || !other.alive) return false\n\tif (om.status === 'moving' || om.ghost) return false\n\tconst m = mover.get(moving)\n\tif (m && (other.id === m.goalEntity || dist(other.pos, m.navGoal) < m.range + mover.def.radius + other.def.radius)) return false\n\treturn world.nav.sameCrowd?.(mover.id, other.id) ?? true\n}\n\n/** How far a point is from a segment */\nfunction segmentDistance(px: number, pz: number, ax: number, az: number, bx: number, bz: number): number {\n\tconst dx = bx - ax\n\tconst dz = bz - az\n\tconst length = dx * dx + dz * dz\n\tconst t = length > 0 ? Math.min(Math.max(((px - ax) * dx + (pz - az) * dz) / length, 0), 1) : 0\n\treturn hypot(px - (ax + dx * t), pz - (az + dz * t))\n}\n\n/**\n * Where an ally in a mover's way steps to: aside, off the mover's way, the shorter way out of it first. The way is the\n * leg the mover is on, to its corner, and the leg after (`agent.nx`): a step off the first onto the second, round a\n * building's corner, would be no step at all. Where a side is not to be stood on (a wall), the other; where neither,\n * nowhere\n */\nfunction asidePoint(world: World, mover: Entity, other: Entity, dx: number, dz: number, agent: AgentState): Vec2 | null {\n\tconst rx = other.pos.x - mover.pos.x\n\tconst rz = other.pos.z - mover.pos.z\n\tconst reach = mover.def.radius + other.def.radius\n\tconst clear = reach + 0.5\n\t// distance from the line the mover wants to walk\n\tconst offset = rx * dz - rz * dx\n\tconst first = Math.abs(offset) > 0.05 ? Math.sign(offset) : other.id % 2 ? 1 : -1\n\tconst nav = world.navFor(other)\n\tconst { pos } = mover\n\tfor (const side of [first, -first]) {\n\t\t// as far as it takes to be off both legs, in steps, not past a few of them\n\t\tfor (let step = clear - Math.abs(offset); step <= clear * 3; step += 0.5) {\n\t\t\tconst x = other.pos.x + dz * side * step\n\t\t\tconst z = other.pos.z - dx * side * step\n\t\t\tif (segmentDistance(x, z, pos.x, pos.z, agent.cx, agent.cz) < clear - 0.05) continue\n\t\t\tif (segmentDistance(x, z, agent.cx, agent.cz, agent.nx, agent.nz) < clear - 0.05) continue\n\t\t\tconst snapped = nav.closestPoint({ x, z }, 1)\n\t\t\tif (!snapped || dist(snapped, { x, z }) > 0.3) break\n\t\t\treturn { x, z }\n\t\t}\n\t}\n\treturn null\n}\n\n/**\n * Asks an ally standing in a unit's way to step aside, as the rules allow (`GameRules.movement.makesWay`, the `makeWay` hook).\n * `direction` is the way the unit is heading, a unit long; `agent` where its path goes, for the step to be off it.\n * True when it goes\n *\n * @beta\n */\nexport function stepAside(world: World, mover: Entity, other: Entity, direction: Vec2, agent: AgentState): boolean {\n\tconst om = other.get(moving)\n\tif (!om || !world.areAllies(mover.owner, other.owner) || !world.rules.movement.makesWay(world, mover, other)) return false\n\tconst m = mover.get(moving)\n\tif (m?.groupId && om.groupId === m.groupId) return false\n\tlet point = asidePoint(world, mover, other, direction.x, direction.z, agent)\n\tif (world.hooks.has('makeWay')) point = world.hooks.run('makeWay', { mover, other, direction, point }).point\n\tif (!point) return false\n\tmoveTo(world, other, point, { facing: om.finalFacing ?? other.facing, aside: true })\n\treturn true\n}\n\nconst neighbours: Entity[] = []\nconst inWay: Entity[] = []\nconst knot: Entity[] = []\nconst direction: Vec2 = { x: 0, z: 0 }\nconst agent: AgentState = { x: 0, z: 0, vx: 0, vz: 0, cx: 0, cz: 0, nx: 0, nz: 0 }\n\n/**\n * Asks friendly units that are standing around in front of a unit to step aside.\n * Avoidance alone cannot get a unit out of a tight group of idle ones: they would have to move, and nothing tells them to.\n *\n * @beta\n */\nexport function makeWay(world: World, entity: Entity): void {\n\tconst m = movementOf(entity)\n\tif (!world.nav.readAgent(entity.id, agent)) return\n\tconst to = m.detour ?? m.navGoal\n\tlet dx = to.x - entity.pos.x\n\tlet dz = to.z - entity.pos.z\n\tconst length = hypot(dx, dz)\n\tif (length < 0.01) return\n\tdx /= length\n\tdz /= length\n\tdirection.x = dx\n\tdirection.z = dz\n\n\tworld.spatial.query(entity.pos.x, entity.pos.z, entity.def.radius + 1.5, neighbours)\n\t// moving others changes the list the query hands out\n\tfor (const other of [...neighbours]) {\n\t\tif (!standsInWay(world, entity, other)) continue\n\t\tconst rx = other.pos.x - entity.pos.x\n\t\tconst rz = other.pos.z - entity.pos.z\n\t\tconst reach = entity.def.radius + other.def.radius\n\t\tconst ahead = rx * dx + rz * dz\n\t\tif (ahead < -0.1 || ahead > reach + 1) continue\n\t\t// against it, not beside it\n\t\tconst offset = rx * dz - rz * dx\n\t\tif (Math.abs(offset) > reach) continue\n\t\tstepAside(world, entity, other, direction, agent)\n\t}\n}\n\n/** Whether a unit walking a segment would touch any of the knot */\nfunction segmentClear(radius: number, ax: number, az: number, bx: number, bz: number): boolean {\n\tfor (const other of knot) {\n\t\tif (segmentDistance(other.pos.x, other.pos.z, ax, az, bx, bz) < radius + other.def.radius + 0.05) return false\n\t}\n\treturn true\n}\n\n/**\n * Whether the way from a point to another is straight, as far as the navigation is concerned: its path is no longer\n * than the line, give or take. A way round a knot that bends round a building is no way round the knot\n */\nfunction straightWay(nav: Navigation, from: Vec2, to: Vec2): boolean {\n\tconst path = nav.findPath(from, to)\n\tif (!path || path.length === 0) return false\n\tlet length = dist(from, path[0])\n\tfor (let i = 1; i < path.length; i++) length += dist(path[i - 1], path[i])\n\tlength += dist(path[path.length - 1], to)\n\treturn length <= dist(from, to) * 1.05 + 0.3\n}\n\nconst standingThere: Entity[] = []\n\n/**\n * Whether a unit could stand at a point: walkable there, and nobody standing on it, or stepping aside onto it. Null\n * when it could; otherwise the unit in the way there, or the mover itself for ground it cannot walk\n */\nfunction standable(world: World, nav: Navigation, entity: Entity, x: number, z: number): Entity | null {\n\tconst snapped = nav.closestPoint({ x, z }, 1)\n\tif (!snapped || dist(snapped, { x, z }) > 0.3) return entity\n\tworld.spatial.query(x, z, entity.def.radius + 1, standingThere)\n\tfor (const other of standingThere) {\n\t\tif (other === entity || !other.get(moving) || other.hidden) continue\n\t\tconst room = entity.def.radius + other.def.radius + 0.05\n\t\tif (standsInWay(world, entity, other) && hypot(other.pos.x - x, other.pos.z - z) < room) return other\n\t\t// on its way to stand there: a step aside for someone\n\t\tconst om = other.get(moving)!\n\t\tif (om.aside && om.status === 'moving' && hypot(om.goal.x - x, om.goal.z - z) < room) return other\n\t}\n\treturn null\n}\n\n/**\n * Looks ahead of a unit on its way for units standing in it (within `GameRules.movement.lookAhead`): a way round the knot\n * they make is taken where it is not much longer (`GameRules.movement.goesAround`, the `detour` hook); otherwise those of\n * them that make way (`GameRules.movement.makesWay`) are asked to step aside before the unit reaches them. The way round is\n * beside the knot, on the side it sticks out less, at the knot's middle; the unit heads there, and on to its path\n * from there. The number of units sent to this per tick is spread by their ids (`LOOK_AHEAD_INTERVAL`)\n *\n * @beta\n */\nexport function lookAhead(world: World, entity: Entity, agent: AgentState): void {\n\tconst m = movementOf(entity)\n\tconst look = world.rules.movement.lookAhead(world, entity)\n\tif (look <= 0) return\n\tconst { pos } = entity\n\tconst radius = entity.def.radius\n\tlet dx = agent.cx - pos.x\n\tlet dz = agent.cz - pos.z\n\tconst toCorner = hypot(dx, dz)\n\tif (toCorner < radius) return\n\tdx /= toCorner\n\tdz /= toCorner\n\tconst reach = Math.min(toCorner, look)\n\n\tworld.spatial.query(pos.x + (dx * reach) / 2, pos.z + (dz * reach) / 2, reach / 2 + 3, neighbours)\n\tinWay.length = 0\n\tfor (const other of neighbours) {\n\t\tif (!standsInWay(world, entity, other)) continue\n\t\tconst rx = other.pos.x - pos.x\n\t\tconst rz = other.pos.z - pos.z\n\t\tconst touch = radius + other.def.radius\n\t\tconst ahead = rx * dx + rz * dz\n\t\t// ahead of it, not beside it or behind, and not past where it looks\n\t\tif (ahead < radius || ahead > reach + touch) continue\n\t\t// in its way, not merely brushed past: the navigation steers round that much\n\t\tconst offset = rx * dz - rz * dx\n\t\tif (Math.abs(offset) > touch - 0.05) continue\n\t\tinWay.push(other)\n\t}\n\tif (inWay.length === 0) return\n\n\t// the knot: those in the way, and those standing against them, against those...: the way round goes round it all\n\tknot.length = 0\n\tfor (const other of inWay) knot.push(other)\n\tfor (let i = 0; i < knot.length && knot.length < KNOT_MOST; i++) {\n\t\tconst member = knot[i]\n\t\tfor (const other of neighbours) {\n\t\t\tif (knot.includes(other) || !standsInWay(world, entity, other)) continue\n\t\t\tif (hypot(other.pos.x - member.pos.x, other.pos.z - member.pos.z) < member.def.radius + other.def.radius + 0.3) knot.push(other)\n\t\t}\n\t}\n\n\tlet detour: Vec2 | null = null\n\tif (knot.length < KNOT_MOST) {\n\t\tconst nav = world.navFor(entity)\n\t\t// from the point beside the knot, on to the corner; or to the corner after it, where the knot stands at the corner\n\t\t// (against a building's corner): round the knot onto the next leg\n\t\tlet aimX = agent.cx\n\t\tlet aimZ = agent.cz\n\t\t// the knot grows by whoever stands where the way round it would go, and the way round is looked for again\n\t\tfor (let grown = 0; grown < 4 && !detour; grown++) {\n\t\t\tlet left = -Infinity\n\t\t\tlet right = Infinity\n\t\t\tlet along = 0\n\t\t\tfor (const other of knot) {\n\t\t\t\tconst rx = other.pos.x - pos.x\n\t\t\t\tconst rz = other.pos.z - pos.z\n\t\t\t\tconst offset = rx * dz - rz * dx\n\t\t\t\tleft = Math.max(left, offset + other.def.radius)\n\t\t\t\tright = Math.min(right, offset - other.def.radius)\n\t\t\t\talong += rx * dx + rz * dz\n\t\t\t}\n\t\t\talong = Math.max(along / knot.length, radius)\n\t\t\t// the side it sticks out less on first, then the other, each pushed further out while the way there touches it\n\t\t\tconst sides = Math.abs(left) <= Math.abs(right) ? [left, right] : [right, left]\n\t\t\tlet blocker: Entity | null = null\n\t\t\tfor (const side of sides) {\n\t\t\t\tconst out = side > 0 ? 1 : -1\n\t\t\t\tfor (let push = 0; push < 3 && !detour; push++) {\n\t\t\t\t\tconst offset = side + out * (radius + DETOUR_CLEARANCE + push * 0.5)\n\t\t\t\t\tconst x = pos.x + dx * along + dz * offset\n\t\t\t\t\tconst z = pos.z + dz * along - dx * offset\n\t\t\t\t\tconst there = standable(world, nav, entity, x, z)\n\t\t\t\t\tif (there) {\n\t\t\t\t\t\tif (there !== entity && !knot.includes(there)) blocker ??= there\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst beside = { x, z }\n\t\t\t\t\tif (!segmentClear(radius, pos.x, pos.z, x, z) || !straightWay(nav, pos, beside)) continue\n\t\t\t\t\tif (segmentClear(radius, x, z, agent.cx, agent.cz) && straightWay(nav, beside, { x: agent.cx, z: agent.cz })) {\n\t\t\t\t\t\taimX = agent.cx\n\t\t\t\t\t\taimZ = agent.cz\n\t\t\t\t\t} else if (\n\t\t\t\t\t\t(agent.nx !== agent.cx || agent.nz !== agent.cz) &&\n\t\t\t\t\t\tsegmentClear(radius, x, z, agent.nx, agent.nz) &&\n\t\t\t\t\t\tstraightWay(nav, beside, { x: agent.nx, z: agent.nz })\n\t\t\t\t\t) {\n\t\t\t\t\t\taimX = agent.nx\n\t\t\t\t\t\taimZ = agent.nz\n\t\t\t\t\t} else continue\n\t\t\t\t\tdetour = beside\n\t\t\t\t}\n\t\t\t\tif (detour) break\n\t\t\t}\n\t\t\tif (!detour && blocker && knot.length < KNOT_MOST) knot.push(blocker)\n\t\t\telse if (!detour) break\n\t\t}\n\t\tif (detour) {\n\t\t\tconst straight = aimX === agent.cx && aimZ === agent.cz ? toCorner : toCorner + hypot(agent.nx - agent.cx, agent.nz - agent.cz)\n\t\t\tconst longer = hypot(detour.x - pos.x, detour.z - pos.z) + hypot(aimX - detour.x, aimZ - detour.z) - straight\n\t\t\tconst around = [...knot]\n\t\t\tif (!world.rules.movement.goesAround(world, entity, around, longer, straight)) detour = null\n\t\t\tif (world.hooks.has('detour')) detour = world.hooks.run('detour', { entity, around, straight, longer, point: detour }).point\n\t\t\tif (detour) {\n\t\t\t\tm.detour = detour\n\t\t\t\tm.detourAim = { x: aimX, z: aimZ }\n\t\t\t\tm.detourPast = false\n\t\t\t\tworld.nav.setDestination(entity.id, detour)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t// no way round: those in the way that make way are asked to, before the unit reaches them\n\tdirection.x = dx\n\tdirection.z = dz\n\tfor (const other of [...inWay]) stepAside(world, entity, other, direction, agent)\n}\n\n/**\n * Over how many ticks the chasers look for new paths after the navigation changed: an eighth of them each tick\n *\n * @beta\n */\nexport const REPATH_SPREAD = 8\n\n/** Keeps chasers pointed at targets that moved, and lets go of the ones gone out of reach */\nfunction followTargets(world: World): void {\n\tconst { nav } = world\n\tfor (const entity of world.index.with(moving)) {\n\t\tconst m = entity.get(moving)\n\t\tif (!m || m.status !== 'moving' || !m.goalEntity) continue\n\t\tconst target = world.get(m.goalEntity)\n\t\tif (!target || target.hidden) {\n\t\t\tnav.clearDestination(entity.id)\n\t\t\tm.status = 'failed'\n\t\t\tcontinue\n\t\t}\n\t\tconst point = approachPoint(world, entity, target)\n\t\t// a change of the navigation has every chaser look again: a few each tick, by their ids, so that a building put\n\t\t// down does not have a thousand paths looked for in one tick. By the world's own count, so it stays the same\n\t\t// game everywhere\n\t\tconst stale = m.navVersion !== nav.version && (entity.id + world.tick) % REPATH_SPREAD === 0\n\t\tif (dist(point, m.navGoal) > 0.75 || stale) beginMove(world, entity, point)\n\t}\n}\n\n/** Where the navigation moved each unit to, read back into the world: and from there, how each is getting on */\nfunction readAgents(world: World, dt: number): void {\n\tfor (const entity of world.index.with(moving)) {\n\t\tconst m = entity.get(moving)\n\t\tif (!m || !entity.alive || entity.hidden) continue\n\t\tif (!world.nav.readAgent(entity.id, agent)) continue\n\t\tmoveAlong(world, entity, m, dt)\n\t}\n}\n\n/** A unit the navigation moved (`agent`, just read): where it is, which way it faces, and how it is getting on */\nfunction moveAlong(world: World, entity: Entity, m: MovementState, dt: number): void {\n\t// the navigation moved it: this is where the world learns where it went\n\tentity.moveTo(agent.x, agent.z)\n\tentity.velocity.x = agent.vx\n\tentity.velocity.z = agent.vz\n\tif (m.status !== 'moving') return lineUp(entity, m, dt)\n\n\tif (agent.vx * agent.vx + agent.vz * agent.vz > 0.2) {\n\t\tconst desired = atan2(agent.vx, agent.vz)\n\t\tentity.facing = rotateTowards(entity.facing, desired, (entity.def.turnRate ?? DEFAULT_TURN_RATE) * dt)\n\t}\n\tconst distance = distanceLeft(world, entity, m)\n\tif (distance === undefined) return\n\tif (distance <= m.range) return arrive(world, entity)\n\tsteerAround(world, entity, m)\n\tfollowRoute(world, entity, m)\n\twatchProgress(world, entity, m, distance, dt)\n}\n\n/** Groups bump into each other on arrival and end up looking anywhere: a unit that stopped turns to face the way it was told */\nfunction lineUp(entity: Entity, m: MovementState, dt: number): void {\n\tif (m.finalFacing === null) return\n\tentity.facing = rotateTowards(entity.facing, m.finalFacing, (entity.def.turnRate ?? DEFAULT_TURN_RATE) * dt)\n\tif (entity.facing === m.finalFacing) m.finalFacing = null\n}\n\n/** How far a unit on its way has still to go: to the edge of what it goes to, or to its point. None for a target gone */\nfunction distanceLeft(world: World, entity: Entity, m: MovementState): number | undefined {\n\tif (!m.goalEntity) return dist(entity.pos, m.goal)\n\tconst target = world.get(m.goalEntity)\n\treturn target ? edgeDistance(entity, target) : undefined\n}\n\n/**\n * Round a knot of standing units: sent on past the point beside them as it nears it, and back on its way once it is\n * past that point, or held up there\n */\nfunction steerAround(world: World, entity: Entity, m: MovementState): void {\n\tif (!m.detour) return\n\tconst near = dist(entity.pos, m.detour)\n\tconst aim = m.detourAim ?? m.navGoal\n\tconst passed = (entity.pos.x - m.detour.x) * (aim.x - m.detour.x) + (entity.pos.z - m.detour.z) * (aim.z - m.detour.z) > 0\n\tif ((m.detourPast && passed) || near <= 0.5 || m.stalledTime > 0.5 || (m.slowTime ?? 0) > 0.3) {\n\t\tm.detour = undefined\n\t\twalk(world, entity)\n\t} else if (!m.detourPast && near <= DETOUR_PAST_AT) {\n\t\tm.detourPast = true\n\t\tconst to = m.detourAim ?? m.stretch ?? m.navGoal\n\t\tlet px = to.x - m.detour.x\n\t\tlet pz = to.z - m.detour.z\n\t\tconst past = hypot(px, pz)\n\t\tif (past > DETOUR_PAST) {\n\t\t\tpx *= DETOUR_PAST / past\n\t\t\tpz *= DETOUR_PAST / past\n\t\t}\n\t\tworld.nav.setDestination(entity.id, { x: m.detour.x + px, z: m.detour.z + pz })\n\t}\n}\n\n/**\n * On a route its side planned: planned again once the side knows more (a few units a tick, by their ids), and sent on\n * a stretch further once halfway along the one it is on\n */\nfunction followRoute(world: World, entity: Entity, m: MovementState): void {\n\tif (m.detour || !(m.route || m.routeVersion !== undefined)) return\n\tconst team = sideOf(world, entity)\n\tlet again = false\n\tif (team !== undefined && m.routeVersion !== world.sidePaths!.version(team) && (entity.id + world.tick) % REPATH_SPREAD === 0) {\n\t\tplanRoute(world, entity, team)\n\t\tagain = true\n\t}\n\tif (again || (m.stretch && dist(entity.pos, m.stretch) < stretchOf(entity) / 2)) {\n\t\tconst next = m.route ? stretchPoint(entity) : m.navGoal\n\t\tif (again || !m.stretch || dist(next, m.stretch) > 0.5) walk(world, entity)\n\t}\n}\n\n/**\n * Whether a unit on its way gets anywhere: held up by others (asked aside, gone round), stalled (arrived where close is\n * good enough, or given up after a while)\n */\nfunction watchProgress(world: World, entity: Entity, m: MovementState, distance: number, dt: number): void {\n\t// a new corner to head for is not progress in itself, getting closer to it is\n\tconst progress = dist(entity.pos, { x: agent.cx, z: agent.cz })\n\tif (agent.cx !== m.corner.x || agent.cz !== m.corner.z) {\n\t\tm.corner.x = agent.cx\n\t\tm.corner.z = agent.cz\n\t\tm.bestDistance = progress\n\t}\n\t// held up by others: going well under its speed, once it got going and while it is not slowing to arrive\n\tconst slow = m.speed > 0 && hypot(agent.vx, agent.vz) < m.speed * SLOW_PART && distance > m.range + entity.def.radius * 2 + 0.3\n\tm.slowTime = slow && m.bestDistance < Infinity ? (m.slowTime ?? 0) + dt : 0\n\n\t// what stands in its way further on: gone round, or asked aside, before it gets there. Not while it goes round a\n\t// knot: the way it was sent was clear when it took it, and it would ask the knot aside as it passes. Nor on a\n\t// step aside, which is nobody's business\n\tif (!m.detour && !m.aside && (world.tick + entity.id) % LOOK_AHEAD_INTERVAL === 0) lookAhead(world, entity, agent)\n\n\tif (progress < m.bestDistance - 0.1) {\n\t\tm.bestDistance = progress\n\t\tm.stalledTime = 0\n\t\tif (!m.aside && (m.slowTime ?? 0) > MAKE_WAY_AFTER && (world.tick + entity.id) % MAKE_WAY_INTERVAL === 0) makeWay(world, entity)\n\t\treturn\n\t}\n\tm.stalledTime += dt\n\tif (!m.aside && m.stalledTime > MAKE_WAY_AFTER && (world.tick + entity.id) % MAKE_WAY_INTERVAL === 0) makeWay(world, entity)\n\n\tif (!m.goalEntity) {\n\t\t// Someone is standing on the destination. Close enough is good enough, otherwise groups jostle forever.\n\t\tif (m.stalledTime > 0.25 && distance < m.range + 4 && blockedByArrivedGroupMate(world, entity)) arrive(world, entity)\n\t\telse if (m.stalledTime > 0.6 && distance < 1.25) arrive(world, entity)\n\t}\n\tif (m.status === 'moving' && m.stalledTime > 3) {\n\t\tif (!m.goalEntity && distance < 3) arrive(world, entity)\n\t\telse {\n\t\t\tworld.nav.clearDestination(entity.id)\n\t\t\tm.status = 'failed'\n\t\t\tm.stuck = true\n\t\t}\n\t}\n}\n\nexport const movementSystem: System = {\n\tname: 'movement',\n\tphase: 'move',\n\tupdate(world, dt) {\n\t\tfollowTargets(world)\n\t\tworld.nav.update(dt)\n\t\treadAgents(world, dt)\n\t}\n}\n","import { attackStarted, impact, missed, projectileRemoved, projectileSpawned } from '#engine/engineEvents'\nimport { isDisarmed, layerOf } from '#engine/abilities/buffs'\nimport type { AttackDef } from '#engine/defs'\nimport { distanceToEdge, edgeDistance, type Entity, type PlayerId } from '#engine/entity'\nimport { angleDiff, dist, type Vec2 } from '#engine/math'\nimport type { CanAttack, TargetScore } from '#engine/hooks'\nimport type { System } from '#engine/registry'\nimport { attackTiming, statsOf } from '#engine/stats'\nimport type { Projectile, World } from '#engine/world'\nimport { faceTowards, halt, moveTo, moveToEntity, setAnchored } from './movement'\nimport { engagedLike, engageWith, isShunned, release, roomFor } from '#engine/engagement'\nimport { atan2 } from '#engine/exactMath'\nimport { moving, fighting, type CombatState } from '../entity'\nimport { attackStat, farthestReach, groundAttack, pickAttack, rangeAgainst, reaches, tooNear } from '#engine/attacks'\n\n/** Extra reach allowed once a swing has started, so targets stepping back slightly still get hit */\n/**\n * How far past its range a swing already begun still lands (`engage`, and the stances pack, which lets go where the engine would chase)\n *\n * @internal\n */\nexport const SWING_SLACK = 0.75\nconst FACING_TOLERANCE = 0.4\n/** The navmesh keeps units a little away from walls, so structures can be hit from slightly further */\n/**\n * How much farther an attack reaches a structure, whose edge is its footprint's (`engage`, and the stances pack)\n *\n * @internal\n */\nexport const STRUCTURE_REACH = 0.4\n/** The least a swing takes: a hit is never in the tick its swing began */\nconst MIN_SWING = 1e-6\n\n/** What a swing is aimed at when it is aimed at the ground. No entity has this id */\nconst GROUND = -1\n/**\n * How often an attack up a cliff goes wide\n *\n * @internal\n */\nexport const UPHILL_MISS = 0.25\n\nexport type EngageResult = 'invalid' | 'attacking' | 'chasing' | 'outOfRange'\n\n/**\n * Handed to the `canAttack` handlers, again and again, so that asking allocates nothing: one for each question under\n * way, as a handler may ask again (could the target hit back?) while its caller's handlers are still being run\n */\nconst askings: CanAttack[] = []\n/** How many questions are under way, one inside the other */\nlet asked = 0\n\n/**\n * Whether an attacker may attack a target: its attack reaches it, it is an enemy, and the `canAttack` hook agrees.\n * `ordered`: a player told it to (an attack order), which a game may let it do to its own side (`CanAttack.ordered`)\n *\n * @beta\n */\nexport function canAttack(world: World, attacker: Entity, target: Entity, ordered = false): boolean {\n\t// what nothing can change: no attack, nothing there to hit\n\tif (!attacker.def.attacks?.length || !target.alive || target.hidden || target === attacker || target.def.invulnerable || target.isResource)\n\t\treturn false\n\t// burrowed, or disarmed by a buff\n\tif (attacker.buffs.length && isDisarmed(world, attacker)) return false\n\t// an enemy first: the cheaper, and half of who is around is not\n\tconst allowed = world.areEnemies(attacker.owner, target.owner) && world.rules.combat.pickAttack(world, attacker, target) >= 0\n\tif (!world.hooks.has('canAttack')) return allowed\n\tconst asking = (askings[asked] ??= { attacker: undefined!, target: undefined!, allowed: false, ordered: false })\n\tasking.attacker = attacker\n\tasking.target = target\n\tasking.allowed = allowed\n\tasking.ordered = ordered\n\tasked++\n\ttry {\n\t\treturn world.hooks.run('canAttack', asking).allowed\n\t} finally {\n\t\tasked--\n\t}\n}\n\n/**\n * Whether one of an attacker's attacks can hit a target where it is, whoever's it is: the ground, the air, the kinds it\n * names (`pickAttack`). For a `canAttack` handler that lets a unit attack what is not an enemy\n *\n * @beta\n */\nexport function attackReaches(world: World, attacker: Entity, target: Entity): boolean {\n\treturn pickAttack(world, attacker, target) >= 0\n}\n\nexport function canSee(world: World, viewer: Entity, target: Entity): boolean {\n\treturn world.isVisibleTo(target, world.player(viewer.owner).team)\n}\n\n/**\n * Whether the target stands on higher ground than the attacker. Nothing is uphill from the air\n *\n * @beta\n */\nexport function shootsUphill(world: World, attacker: Entity, target: Entity): boolean {\n\tif (layerOf(world, attacker) === 'air') return false\n\tconst { terrain } = world\n\treturn terrain.levelAt(target.pos.x, target.pos.z) > terrain.levelAt(attacker.pos.x, attacker.pos.z)\n}\n\n/**\n * What one search goes through: the entities around, and what is handed to the `targetScore` handlers for every\n * candidate, again and again, so that no search allocates. One per search under way: a handler may search again (who\n * the target would go for) while its caller's list is being gone through\n */\ninterface Search {\n\tcandidates: Entity[]\n\tscoring: TargetScore\n\t/** What it found, given back as it is (`searchTarget`): read before the next search at the same depth */\n\tfound: TargetFound\n}\n\n/**\n * What a search for a target found: the best, and whether it passed over one it would have taken but for leaving it\n * alone for now (`shun`): what asking again with `shunned` would have found something for, without looking again\n */\nexport interface TargetFound {\n\ttarget: Entity | undefined\n\tpassedOver: boolean\n}\nconst searches: Search[] = []\n/** How many searches are under way, one inside the other */\nlet searching = 0\n\n/** What a target with no room left for an attacker loses in its score: a free one of the same kind comes first, however far */\nconst CROWDED = 1000\n\n/**\n * Best enemy within `range` of the entity (its acquisition range by default), as the `targetScore` hook sees it. Those\n * it leaves alone for now (`shun`) are not, unless `shunned` says to count them too: to know whether a fight is still on\n */\nexport const acquireTarget = (world: World, entity: Entity, range?: number, shunned = false): Entity | undefined =>\n\tsearchTarget(world, entity, range, shunned).target\n\n/**\n * Best enemy it can hit from where it stands: within the range of the attack it would use against each (`pickAttack`),\n * and `slack` more. For one that holds its ground\n *\n * @beta\n */\nexport function acquireInRange(world: World, entity: Entity, slack = 0): Entity | undefined {\n\tconst attacks = entity.def.attacks\n\tif (!attacks?.length) return undefined\n\tconst stats = statsOf(world, entity)\n\t// one attack: its range is the reach. More: as far as the farthest, each target then by its own\n\tif (attacks.length === 1) return searchTarget(world, entity, attackStat(stats, attacks[0], 'range') + slack).target\n\treturn searchTarget(world, entity, farthestReach(entity.def, stats) + slack, false, slack).target\n}\n\n/** Nothing found, by an entity that does not attack */\nconst NOTHING: Readonly<TargetFound> = Object.freeze({ target: undefined, passedOver: false })\n\n/**\n * `acquireTarget`, and whether it passed over a target it leaves alone for now (`TargetFound`). What it gives back is\n * the search's own, used again by the next search: read it at once\n */\nexport function searchTarget(world: World, entity: Entity, range?: number, shunned = false, inRange?: number): Readonly<TargetFound> {\n\tif (!entity.def.attacks?.length) return NOTHING\n\tconst reach = range ?? world.rules.combat.acquisitionRange(world, entity)\n\tconst search = (searches[searching] ??= {\n\t\tcandidates: [],\n\t\tscoring: { attacker: undefined!, target: undefined!, distance: 0, engaged: 0, room: 0, score: 0 },\n\t\tfound: { target: undefined, passedOver: false }\n\t})\n\tsearching++\n\ttry {\n\t\treturn bestTarget(world, entity, reach, shunned, search, inRange)\n\t} finally {\n\t\tsearching--\n\t\tsearch.candidates.length = 0\n\t}\n}\n\n/** By world, then by owner: whether another owner is on the owner's side, for the grid to leave out cells of theirs alone */\nconst sidesOf = new WeakMap<World, Map<PlayerId, (other: PlayerId) => boolean>>()\n\nfunction sideTest(world: World, owner: PlayerId): (other: PlayerId) => boolean {\n\tlet byOwner = sidesOf.get(world)\n\tif (!byOwner) sidesOf.set(world, (byOwner = new Map()))\n\tlet side = byOwner.get(owner)\n\t// asked as the search goes, so that a change of sides this tick is what it goes by\n\tif (!side) byOwner.set(owner, (side = (other) => world.areAllies(owner, other)))\n\treturn side\n}\n\n/** `inRange`: only what the attack it would use reaches, and that much more (`acquireInRange`) */\nfunction bestTarget(\n\tworld: World,\n\tentity: Entity,\n\treach: number,\n\tshunned: boolean,\n\t{ candidates, scoring, found }: Search,\n\tinRange?: number\n): TargetFound {\n\tconst hooked = world.hooks.has('targetScore')\n\tworld.spatial.query(entity.pos.x, entity.pos.z, reach + entity.def.radius, candidates, sideTest(world, entity.owner))\n\tlet best: Entity | undefined\n\tlet bestScore = -Infinity\n\tlet passed = false\n\t// its own side's are never what it picks by itself (`CanAttack.ordered`): passed over before anything is asked of\n\t// them, as most of what stands around a unit in a crowd is its own (EN1). Asked once for each owner in a row\n\tconst { owner } = entity\n\tlet sideOf = owner\n\tlet ownSide = true\n\t// an attack with a dead zone (`AttackDef.minRange`): what is in it is not picked by itself\n\tconst nearest = entity.def.attacks?.some((attack) => attack.minRange) ?? false\n\tfor (const other of candidates) {\n\t\tif (other.def.ignored) continue\n\t\tif (other.owner !== sideOf) {\n\t\t\tsideOf = other.owner\n\t\t\townSide = world.areAllies(owner, sideOf)\n\t\t}\n\t\tif (ownSide) continue\n\t\t// the cheapest first: the grid gives the square around, much of it out of reach\n\t\tconst distance = edgeDistance(entity, other)\n\t\tif (distance > reach || !canAttack(world, entity, other) || !canSee(world, entity, other)) continue\n\t\tif (inRange !== undefined && distance > rangeAgainst(world, entity, other) + inRange) continue\n\t\tif (nearest && tooNear(entity, other, Math.max(pickAttack(world, entity, other), 0))) continue\n\t\tif (!shunned && isShunned(world, entity, other)) {\n\t\t\tpassed = true\n\t\t\tcontinue\n\t\t}\n\t\t// things that fight back first, then whatever is closest; one already surrounded by its like only when nothing\n\t\t// else is to be had\n\t\tconst threat = other.def.threat ?? (other.def.attacks?.length ? 2 : other.isBuilding ? 0 : 1)\n\t\tconst engaged = other.id === entity.get(fighting)?.engaged ? 0 : engagedLike(world, other, entity)\n\t\tconst room = roomFor(world, other, entity)\n\t\tlet score = threat * 1000 - distance - (engaged >= room ? CROWDED : 0)\n\t\tif (hooked) {\n\t\t\tscoring.attacker = entity\n\t\t\tscoring.target = other\n\t\t\tscoring.distance = distance\n\t\t\tscoring.engaged = engaged\n\t\t\tscoring.room = room\n\t\t\tscoring.score = score\n\t\t\tscore = world.hooks.run('targetScore', scoring).score\n\t\t}\n\t\tif (score > bestScore) {\n\t\t\tbestScore = score\n\t\t\tbest = other\n\t\t}\n\t}\n\tfound.target = best\n\tfound.passedOver = passed\n\treturn found\n}\n\nexport function cancelSwing(entity: Entity): void {\n\tif (!entity.get(fighting)) return\n\tentity.get(fighting)!.swing = 0\n\tentity.get(fighting)!.swingTarget = 0\n}\n\n/** What an attack arrives with */\ntype Hit = Pick<Projectile, 'damage' | 'type' | 'crit' | 'tags' | 'how' | 'weapon'>\n\n/** The attack type (by the damage table) of a blow of the source's attack at that place */\nconst attackTypeOf = (source: Entity | undefined, weapon = 0) => source?.def.attacks?.[weapon]?.attackType\n\nconst caught: Entity[] = []\n\n/** What an attack that hits an area does where it comes down */\nfunction explode(world: World, point: Vec2, hit: Hit, splash: NonNullable<Projectile['splash']>, owner: PlayerId, source?: Entity): void {\n\tconst { radius, fells, targets } = splash\n\t// the list is copied: what dies in here may set off more of the same\n\tfor (const other of [...world.spatial.query(point.x, point.z, radius, caught)]) {\n\t\tif (!other.alive || other.hidden) continue\n\t\tconst distance = distanceToEdge(point, other)\n\t\tif (distance > radius) continue\n\t\tif (other.def.fellable) {\n\t\t\tif (fells) world.kill(other, source, false, 'felled')\n\t\t\tcontinue\n\t\t}\n\t\tif (other.def.invulnerable) continue\n\t\tif (!reaches(targets, other, other.flying ? layerOf(world, other) : 'ground')) continue\n\t\t// friend or foe, whoever stands there, as the rules share it out: by default all but the one who fired\n\t\tconst share = world.rules.combat.splash(world, source, other, distance, radius)\n\t\tif (share <= 0) continue\n\t\tworld.damage(other, hit.damage * share, source, {\n\t\t\tdamageType: hit.type,\n\t\t\tcrit: hit.crit,\n\t\t\tattack: true,\n\t\t\ttags: hit.tags,\n\t\t\thow: hit.how,\n\t\t\tattackType: attackTypeOf(source, hit.weapon)\n\t\t})\n\t}\n\tworld.events.emit(impact, { x: point.x, z: point.z, radius, owner })\n}\n\nconst splashOf = (attack: AttackDef, radius = attack.splash) =>\n\tradius ? { radius, fells: attack.fells ?? false, targets: attack.targets } : undefined\n\n/** The attack of the entity at that place goes off: at the target, or at a spot on the ground */\nfunction landHit(world: World, attacker: Entity, weapon: number, target: Entity | undefined, point: Vec2 = target!.pos): void {\n\tconst attack = attacker.def.attacks?.[weapon]\n\t// (an attack that goes off is a type's that has one)\n\tif (!attack) return\n\tconst stats = statsOf(world, attacker)\n\t// a critical strike, as the game has them (none in the engine's rules), then whether it goes wide\n\tconst critical = world.rules.combat.critical(world, attacker, stats)\n\tlet crit = critical !== undefined\n\tconst chance = target ? world.rules.combat.missChance(world, attacker, target) : 0\n\tlet miss = chance > 0 && world.rng.next() < chance\n\tlet damage = attackStat(stats, attack, 'damage') * (critical ?? 1)\n\tlet type = attack.damageType ?? 'physical'\n\tlet splash = splashOf(attack)\n\tlet speed = attack.projectileSpeed ?? 0\n\tlet look: string | undefined\n\tlet tags: string[] | undefined\n\t// how what it kills dies, for the screen: the attack's word, or one it decides for this blow\n\tlet how = typeof attack.how === 'function' ? attack.how({ attacker, target, damage, type, crit, tags }) : attack.how\n\t// what the game makes of it, as it goes off: a bounce, a flaming arrow, a blow called off\n\tif (world.hooks.has('beforeAttack')) {\n\t\tconst before = world.hooks.run('beforeAttack', {\n\t\t\tattacker,\n\t\t\ttarget,\n\t\t\tpoint,\n\t\t\tweapon,\n\t\t\tdamage,\n\t\t\ttype,\n\t\t\tcrit,\n\t\t\tmiss,\n\t\t\tsplash: splash?.radius,\n\t\t\tprojectileSpeed: speed,\n\t\t\tlook,\n\t\t\ttags,\n\t\t\thow,\n\t\t\tcancelled: false\n\t\t})\n\t\tif (before.cancelled) return\n\t\t;({ damage, type, crit, miss, look, tags, how } = before)\n\t\tspeed = before.projectileSpeed\n\t\tsplash = splashOf(attack, before.splash)\n\t}\n\tif (speed > 0) {\n\t\tconst projectile: Projectile = {\n\t\t\tid: world.newId(),\n\t\t\tsource: attacker.id,\n\t\t\towner: attacker.owner,\n\t\t\t// what hits an area lands where it was aimed\n\t\t\ttarget: splash || !target ? 0 : target.id,\n\t\t\tx: attacker.pos.x,\n\t\t\tz: attacker.pos.z,\n\t\t\tprevX: attacker.pos.x,\n\t\t\tprevZ: attacker.pos.z,\n\t\t\tsx: attacker.pos.x,\n\t\t\tsz: attacker.pos.z,\n\t\t\ttx: point.x,\n\t\t\ttz: point.z,\n\t\t\tspeed,\n\t\t\tdamage,\n\t\t\ttype,\n\t\t\tcrit,\n\t\t\tmiss,\n\t\t\tsplash,\n\t\t\tkind: attacker.def.id,\n\t\t\tlook,\n\t\t\ttags,\n\t\t\t...(how && { how }),\n\t\t\t// a shot of the first attack says none\n\t\t\t...(weapon > 0 && { weapon })\n\t\t}\n\t\tworld.projectiles.push(projectile)\n\t\tworld.events.emit(projectileSpawned, projectile)\n\t} else if (miss) {\n\t\tworld.events.emit(missed, { x: point.x, z: point.z, source: attacker, target })\n\t} else if (splash) {\n\t\texplode(world, point, { damage, type, crit, tags, how, weapon }, splash, attacker.owner, attacker)\n\t} else if (target) {\n\t\tworld.damage(target, damage, attacker, { damageType: type, crit, attack: true, tags, how, attackType: attack.attackType })\n\t}\n}\n\n/**\n * A swing of the attack at that place begun: its time to the hit less how late in the tick the swing was due (the\n * cooldown run past 0), so that the attacks keep to the attack speed instead of each waiting out a part of a tick (bug\n * 17). At least a moment, so that the hit is the next tick's. Which attack swings is kept for a unit with more than one\n */\nfunction startSwing(world: World, entity: Entity, combat: CombatState, weapon: number): void {\n\tcombat.swing = Math.max(attackTiming(world, entity, weapon).swing + Math.min(combat.cooldown, 0), MIN_SWING)\n\tcombat.cooldown = 0\n\tif (weapon > 0 || combat.weapon !== undefined) combat.weapon = weapon\n}\n\n/**\n * A swing landed: the time to the next, of whichever attack, is the period of the one that swung less its swing, less\n * how far past the hit this tick went. Gives the attack that swung, by place\n */\nfunction endSwing(world: World, entity: Entity, combat: CombatState): number {\n\tconst weapon = combat.weapon ?? 0\n\tconst { swing, period } = attackTiming(world, entity, weapon)\n\tcombat.cooldown = Math.max(period - swing + combat.swing, 0)\n\tcombat.swing = 0\n\tcombat.swingTarget = 0\n\treturn weapon\n}\n\nexport type BombardResult = 'attacking' | 'outOfRange'\n\n/** One tick of attacking a spot on the ground, for attacks that can. Getting into range is up to the caller */\nexport function bombard(world: World, entity: Entity, point: Vec2, dt: number): BombardResult {\n\tconst combat = entity.get(fighting)\n\tconst weapon = groundAttack(entity.def)\n\t// (only a unit that can attack the ground is asked to bombard)\n\tif (!combat || weapon < 0) return 'outOfRange'\n\tconst swinging = combat.swing > 0 && combat.swingTarget === GROUND\n\tconst range = attackStat(statsOf(world, entity), entity.def.attacks![swinging ? (combat.weapon ?? 0) : weapon], 'range')\n\tif (dist(entity.pos, point) - entity.def.radius > range + (swinging ? SWING_SLACK : 0)) {\n\t\tcancelSwing(entity)\n\t\treturn 'outOfRange'\n\t}\n\tconst m = entity.get(moving)\n\tif (m) {\n\t\tif (m.status === 'moving') halt(world, entity)\n\t\tsetAnchored(world, entity, true)\n\t}\n\tfaceTowards(entity, point, dt)\n\n\tif (swinging) {\n\t\tcombat.swing -= dt\n\t\tif (combat.swing <= 0) landHit(world, entity, endSwing(world, entity, combat), undefined, point)\n\t\treturn 'attacking'\n\t}\n\tconst facing = atan2(point.x - entity.pos.x, point.z - entity.pos.z)\n\tif (combat.cooldown <= 0 && Math.abs(angleDiff(entity.facing, facing)) < FACING_TOLERANCE) {\n\t\tstartSwing(world, entity, combat, weapon)\n\t\tcombat.swingTarget = GROUND\n\t\tworld.events.emit(attackStarted, { attacker: entity, weapon })\n\t}\n\treturn 'attacking'\n}\n\n/**\n * Drives one tick of fighting a target: close the distance, turn, swing, hit.\n * Every order that fights (attack, attack-move, hold, idle auto-attack) goes through here.\n */\nexport function engage(world: World, entity: Entity, target: Entity | undefined, dt: number, chase: boolean, ordered = false): EngageResult {\n\tconst combat = entity.get(fighting)\n\tconst attacks = entity.def.attacks\n\tif (!combat || !attacks?.length || !target || !canAttack(world, entity, target, ordered) || !canSee(world, entity, target)) {\n\t\tcancelSwing(entity)\n\t\trelease(entity, world)\n\t\treturn 'invalid'\n\t}\n\tengageWith(world, entity, target)\n\n\tconst distance = edgeDistance(entity, target)\n\tconst swinging = combat.swing > 0 && combat.swingTarget === target.id\n\t// the attack it uses against it (its first, where a game lets it attack what none reaches); a swing begun goes on as it began\n\tconst weapon = attacks.length === 1 ? 0 : swinging ? (combat.weapon ?? 0) : Math.max(world.rules.combat.pickAttack(world, entity, target), 0)\n\tconst range = attackStat(statsOf(world, entity), attacks[weapon], 'range') + (target.isStructure ? STRUCTURE_REACH : 0)\n\t// too near for the attack it has against it (`AttackDef.minRange`): told to, it steps back out of its dead zone;\n\t// by itself it lets it be\n\tconst near = !swinging ? attacks[weapon].minRange : undefined\n\tif (near && distance < near) {\n\t\tcancelSwing(entity)\n\t\tif (!ordered || !chase || !entity.get(moving)) {\n\t\t\trelease(entity, world)\n\t\t\treturn 'outOfRange'\n\t\t}\n\t\tconst away = dist(entity.pos, target.pos) || 1\n\t\t// to the middle of the band it can hit from, straight away from the target\n\t\tconst to = Math.min(near + 0.5, (near + range) / 2) + entity.def.radius + target.def.radius\n\t\tconst step = { x: target.pos.x + ((entity.pos.x - target.pos.x) / away) * to, z: target.pos.z + ((entity.pos.z - target.pos.z) / away) * to }\n\t\tconst m = entity.get(moving)!\n\t\tif (m.status !== 'moving' || m.goalEntity || dist(m.goal, step) > 0.5) moveTo(world, entity, step)\n\t\treturn 'chasing'\n\t}\n\tif (distance > range + (swinging ? SWING_SLACK : 0)) {\n\t\tcancelSwing(entity)\n\t\tif (!chase || !entity.get(moving)) {\n\t\t\trelease(entity, world)\n\t\t\treturn 'outOfRange'\n\t\t}\n\t\tmoveToEntity(world, entity, target, Math.max(range - 0.15, 0.05))\n\t\treturn 'chasing'\n\t}\n\n\tconst m = entity.get(moving)\n\tif (m) {\n\t\tif (m.status === 'moving') halt(world, entity)\n\t\tsetAnchored(world, entity, true)\n\t}\n\tfaceTowards(entity, target.pos, dt)\n\n\tif (swinging) {\n\t\tcombat.swing -= dt\n\t\tif (combat.swing <= 0) landHit(world, entity, endSwing(world, entity, combat), target)\n\t\treturn 'attacking'\n\t}\n\n\tconst facing = atan2(target.pos.x - entity.pos.x, target.pos.z - entity.pos.z)\n\tif (combat.cooldown <= 0 && Math.abs(angleDiff(entity.facing, facing)) < FACING_TOLERANCE) {\n\t\tstartSwing(world, entity, combat, weapon)\n\t\tcombat.swingTarget = target.id\n\t\tworld.events.emit(attackStarted, { attacker: entity, target, weapon })\n\t}\n\treturn 'attacking'\n}\n\n/**\n * One tick of an attack that fires as the unit walks (`AttackDef.onTheMove`): what it shot at last tick while it can\n * still be hit from where the unit is, else the best in range (looked for every fourth tick), swung at without a stop\n * or a turn. Gives back what it is shooting at, none for nothing\n *\n * @beta\n */\nexport function fireOnTheMove(world: World, entity: Entity, current: number | undefined, dt: number): number | undefined {\n\tconst combat = entity.get(fighting)\n\tconst attacks = entity.def.attacks\n\tif (!combat || !attacks?.some((attack) => attack.onTheMove)) return undefined\n\tif (attacks.length && entity.buffs.length && isDisarmed(world, entity)) return undefined\n\tconst usable = (target: Entity | undefined): target is Entity => {\n\t\tif (!target || !canAttack(world, entity, target) || !canSee(world, entity, target)) return false\n\t\tconst weapon = attacks.length === 1 ? 0 : Math.max(pickAttack(world, entity, target), 0)\n\t\tif (!attacks[weapon].onTheMove || tooNear(entity, target, weapon)) return false\n\t\treturn edgeDistance(entity, target) <= attackStat(statsOf(world, entity), attacks[weapon], 'range')\n\t}\n\tlet target = current === undefined ? undefined : world.get(current)\n\tif (!usable(target)) {\n\t\tif (combat.swing > 0 && combat.swingTarget === current) cancelSwing(entity)\n\t\ttarget = (world.tick + entity.id) % 4 === 0 ? acquireInRange(world, entity) : undefined\n\t\tif (!usable(target)) return undefined\n\t}\n\tif (combat.swing > 0 && combat.swingTarget === target.id) {\n\t\tcombat.swing -= dt\n\t\tif (combat.swing <= 0) landHit(world, entity, endSwing(world, entity, combat), target)\n\t\treturn target.id\n\t}\n\tif (combat.cooldown <= 0) {\n\t\tconst weapon = attacks.length === 1 ? 0 : Math.max(pickAttack(world, entity, target), 0)\n\t\tstartSwing(world, entity, combat, weapon)\n\t\tcombat.swingTarget = target.id\n\t\tworld.events.emit(attackStarted, { attacker: entity, target, weapon })\n\t}\n\treturn target.id\n}\n\n/** Stops fighting: aborts the swing and lets the unit be pushed around again. */\nexport function disengage(world: World, entity: Entity): void {\n\tcancelSwing(entity)\n\trelease(entity, world)\n\tsetAnchored(world, entity, false)\n}\n\nexport const combatSystem: System = {\n\tname: 'combat',\n\tphase: 'resolve',\n\tupdate(world, dt) {\n\t\tfor (const entity of world.index.with(fighting)) {\n\t\t\tconst combat = entity.get(fighting)\n\t\t\tif (!combat) continue\n\t\t\t// what is left over past 0 is the part of this tick the next swing was already due in: kept for the next tick's\n\t\t\t// swing, dropped where no swing took it\n\t\t\tif (combat.cooldown > 0) combat.cooldown -= dt\n\t\t\telse if (combat.cooldown < 0) combat.cooldown = 0\n\t\t}\n\n\t\tconst { projectiles } = world\n\t\tfor (let i = projectiles.length - 1; i >= 0; i--) {\n\t\t\tconst p = projectiles[i]\n\t\t\tconst target = world.get(p.target)\n\t\t\tif (target && !target.hidden) {\n\t\t\t\tp.tx = target.pos.x\n\t\t\t\tp.tz = target.pos.z\n\t\t\t}\n\t\t\tp.prevX = p.x\n\t\t\tp.prevZ = p.z\n\t\t\tconst remaining = dist({ x: p.x, z: p.z }, { x: p.tx, z: p.tz })\n\t\t\tconst step = p.speed * dt\n\t\t\tif (remaining <= step + (target ? target.def.radius * 0.5 : 0)) {\n\t\t\t\tif (p.miss) world.events.emit(missed, { x: p.tx, z: p.tz, source: world.get(p.source), target })\n\t\t\t\telse if (p.splash) explode(world, { x: p.tx, z: p.tz }, p, p.splash, p.owner, world.get(p.source))\n\t\t\t\telse if (target) {\n\t\t\t\t\tconst source = world.get(p.source)\n\t\t\t\t\tworld.damage(target, p.damage, source, {\n\t\t\t\t\t\tdamageType: p.type,\n\t\t\t\t\t\tcrit: p.crit,\n\t\t\t\t\t\tattack: true,\n\t\t\t\t\t\ttags: p.tags,\n\t\t\t\t\t\thow: p.how,\n\t\t\t\t\t\tattackType: attackTypeOf(source, p.weapon)\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tprojectiles.splice(i, 1)\n\t\t\t\tworld.events.emit(projectileRemoved, p)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tp.x += ((p.tx - p.x) / remaining) * step\n\t\t\tp.z += ((p.tz - p.z) / remaining) * step\n\t\t}\n\t}\n}\n","/**\n * A copy of a value that is plain data all the way down: numbers, text, lists and plain objects, which is what a\n * file and a wire can carry. Throws when something in it is not (a `Map`, a class, a function), saying where:\n * `what` is whose data it is (\"Save\", \"Map\"), `where` the path so far, `advice` what to do about it\n *\n * @beta\n */\nexport function plain(value: unknown, where: string, what: string, advice = ''): unknown {\n\tif (value === null || value === undefined || typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean') return value\n\tif (Array.isArray(value)) return value.map((item, i) => plain(item, `${where}[${i}]`, what, advice))\n\tif (typeof value === 'object') {\n\t\tconst prototype = Object.getPrototypeOf(value)\n\t\tif (prototype !== Object.prototype && prototype !== null) {\n\t\t\tthrow new Error(`${what}: ${where} is a ${prototype?.constructor?.name ?? 'thing'}, not plain data${advice && `: ${advice}`}`)\n\t\t}\n\t\tconst copy: Record<string, unknown> = {}\n\t\tfor (const [key, item] of Object.entries(value)) if (item !== undefined) copy[key] = plain(item, `${where}.${key}`, what, advice)\n\t\treturn copy\n\t}\n\tthrow new Error(`${what}: ${where} is a ${typeof value}, not plain data`)\n}\n\n/**\n * The plain data of a value, and the paths of what was left out of it for not being plain (`settings.economy.workersPer`):\n * a plain object's fields each kept or left out, a list as a whole. For what keeps the data of something that may hold\n * code beside it (a computer player's options)\n */\nexport function plainParts(value: unknown, where = ''): { kept: unknown; dropped: string[] } {\n\tconst prototype = typeof value === 'object' && value !== null && !Array.isArray(value) ? Object.getPrototypeOf(value) : undefined\n\tif (prototype === Object.prototype || prototype === null) {\n\t\tconst kept: Record<string, unknown> = {}\n\t\tconst dropped: string[] = []\n\t\tfor (const [key, item] of Object.entries(value as object)) {\n\t\t\tif (item === undefined) continue\n\t\t\tconst part = plainParts(item, where ? `${where}.${key}` : key)\n\t\t\tif (part.kept !== undefined) kept[key] = part.kept\n\t\t\tdropped.push(...part.dropped)\n\t\t}\n\t\treturn { kept, dropped }\n\t}\n\ttry {\n\t\treturn { kept: plain(value, where, 'Plain parts'), dropped: [] }\n\t} catch {\n\t\treturn { kept: undefined, dropped: [where] }\n\t}\n}\n","/**\n * Checks the engine can run on itself, for tests and development. Each one redoes or re-verifies work\n * that the engine normally skips or caches, and throws as soon as the shortcut gave a different answer.\n * They are slow; a real game leaves them off. A world's are its own (`world.checks`, `CreateWorldOptions.checks`);\n * these are what a world that says nothing starts with (`setDebugChecks`), and what a computer player's brain, which\n * has no world, reads\n *\n * @beta\n */\nexport interface DebugChecks {\n\tstats: boolean\n\tscenery: boolean\n\tindex: boolean\n\tsight: boolean\n\tevents: boolean\n\tai: boolean\n}\n\n/** The process's: what a world that says nothing starts with */\nexport const debugChecks: DebugChecks = {\n\t/** `statsOf` adds the stats up from scratch on every call and compares them with what it had cached */\n\tstats: false,\n\t/** Every tick, scenery (see `isScenery`) is checked for having anything that per-tick systems would have to see to */\n\tscenery: false,\n\t/** Every tick, `World.index` is checked against the entities: whose they are, which are heroes, which are shops */\n\tindex: false,\n\t/** Every snapshot a session puts together is checked to have in sight exactly what testing every entity of the world would give */\n\tsight: false,\n\t/** What a game's replicated events say is checked to be plain data, which could cross a network */\n\tevents: false,\n\t/** Every think of every computer player's brain is checked against the invariants of `ai/checks.ts`: the first broken one throws */\n\tai: false\n}\n\n/**\n * A world's checks, of what it was made with (`CreateWorldOptions.checks`): all on or off, some of them (the rest the\n * process's), or the process's (`setDebugChecks`) when nothing is said\n */\nexport function checksOf(given: boolean | Partial<DebugChecks> | undefined): DebugChecks {\n\tif (typeof given === 'boolean') return { stats: given, scenery: given, index: given, sight: given, events: given, ai: given }\n\treturn { ...debugChecks, ...given }\n}\n\n/**\n * Turns every check on or off for the worlds made from now on that say nothing of their own (`CreateWorldOptions.checks`),\n * and for computer players' brains\n *\n * @beta\n */\nexport function setDebugChecks(enabled: boolean): void {\n\tdebugChecks.stats = enabled\n\tdebugChecks.scenery = enabled\n\tdebugChecks.index = enabled\n\tdebugChecks.sight = enabled\n\tdebugChecks.events = enabled\n\tdebugChecks.ai = enabled\n}\n\n/**\n * Throws when a value is not plain data: numbers, text, booleans, lists and plain objects of them. An entity, a\n * map or a function in an event would only work while the screen and the simulation share a page\n */\nexport function assertPlainData(value: unknown, what: string, path = ''): void {\n\tif (value === null || value === undefined) return\n\tconst type = typeof value\n\tif (type === 'number' || type === 'string' || type === 'boolean') return\n\tif (type !== 'object') throw new Error(`${what}: ${path || 'it'} is a ${type}, which is not plain data`)\n\tif (Array.isArray(value)) {\n\t\tvalue.forEach((item, index) => assertPlainData(item, what, `${path}[${index}]`))\n\t\treturn\n\t}\n\tconst proto = Object.getPrototypeOf(value)\n\tif (proto !== Object.prototype && proto !== null) {\n\t\tconst name = (value as object).constructor?.name ?? 'object'\n\t\tthrow new Error(`${what}: ${path || 'it'} is a ${name}, which is not plain data. Give entities by id`)\n\t}\n\tfor (const [key, item] of Object.entries(value)) assertPlainData(item, what, path ? `${path}.${key}` : key)\n}\n","import { defineComponent } from './components'\nimport { assertPlainData } from './debug'\nimport type { PlayerId } from './entity'\nimport { type Message, type MessageRef, toMessage } from './messages'\nimport type { System } from './registry'\nimport type { World } from './world'\n\n/**\n * Something a game does after a while, or every so often: a wave coming, a spell wearing off, a line of dialog.\n * Made with `defineTimer` and given in `GameModule.timers`, the way listeners are, so that a loaded save finds the\n * code by id: what is waiting in the world is data, which timer and with what, never a function\n *\n * @beta\n */\nexport interface TimerDef<T = any> {\n\t/** Shared by every game, like other ids: give it a prefix of the game's (`'td.waveComes'`) */\n\treadonly id: string\n\trun(world: World, data: T, timer: TimerInfo): void\n}\n\n/**\n * Typed help: `defineTimer<{ wave: number }>('td.waveComes', (world, { wave }) => ...)`\n *\n * @beta\n */\nexport function defineTimer<T = undefined>(id: string, run: (world: World, data: T, timer: TimerInfo) => void): TimerDef<T> {\n\treturn { id, run }\n}\n\n/** A timer as it waits in the world. Plain data: it goes into a save */\ninterface Waiting {\n\t/** Unique in the world, for `cancel` and `left` */\n\tid: number\n\ttimer: string\n\tdata: unknown\n\t/** The tick it goes off at */\n\tat: number\n\t/** Ticks between two times, for one that repeats */\n\tevery?: number\n\t/** How many times it still goes off, for one that repeats a number of times. Forever when left out */\n\ttimes?: number\n}\n\n/**\n * A timer as the debug tools show it: seconds until it goes off, and between two times\n *\n * @beta\n */\nexport interface WaitingTimer {\n\tid: number\n\ttimer: string\n\tdata: unknown\n\tleft: number\n\tevery?: number\n\ttimes?: number\n}\n\n/**\n * How a timer repeats, and what it is given, for one whose handler takes something\n *\n * @beta\n */\nexport type EveryOptions<T> = { times?: number; first?: number } & (T extends undefined ? { data?: undefined } : { data: T })\n\n/**\n * What a timer's handler is told about the time it went off\n *\n * @beta\n */\nexport interface TimerInfo {\n\tid: number\n\t/** How many more times it goes off after this one: 0 for the last, undefined for one that repeats forever */\n\tleft?: number\n}\n\n/**\n * A timer the rules show a player (`world.timers.show`): its words, and the tick it goes off at, for the screen to count\n * down to\n *\n * @beta\n */\nexport interface ShownTimer {\n\tid: number\n\tlabel: Message\n\tat: number\n}\n\n/** The timers each player is shown, by the id of each and its words: kept in the world, so that a save has them */\nexport const shownTimers = defineComponent<Record<number, { id: number; label: Message }[]>>('core.shownTimers', { default: () => ({}) })\n\n/** The timers waiting in a world, kept in it so that a save has them */\nexport const waiting = defineComponent<{ next: number; list: Waiting[] }>('core.timers', { default: () => ({ next: 1, list: [] }) })\n\n/** The timers waiting in the state of a save, by the id of their definition: what a game must still have to load it */\nexport const waitingTimers = (state: Record<string, unknown>): string[] =>\n\t((state[waiting.id] as { list?: Waiting[] } | undefined)?.list ?? []).map((due) => due.timer)\n\n/**\n * The timers of a world. Time is counted in ticks, which every machine counts the same, never with the clock:\n * a timer goes off at the start of the tick it is due, after the players' commands and before anything else, in the\n * order they are due and then the order they were set\n *\n * @beta\n */\nexport class Timers {\n\tprivate readonly defs = new Map<string, TimerDef>()\n\n\tconstructor(\n\t\tprivate readonly world: World,\n\t\tdefs: readonly TimerDef[]\n\t) {\n\t\tfor (const def of defs) {\n\t\t\tif (this.defs.has(def.id)) throw new Error(`Timer \"${def.id}\" is there twice`)\n\t\t\tthis.defs.set(def.id, def)\n\t\t}\n\t}\n\n\t/** Goes off once, `seconds` from now. Returns its id, for `cancel` and `left` */\n\tafter<T>(seconds: number, timer: TimerDef<T>, ...data: T extends undefined ? [] : [T]): number {\n\t\treturn this.add(timer, data[0], this.ticks(seconds))\n\t}\n\n\t/**\n\t * Goes off every `seconds`: the first time `seconds` from now, or after `first` seconds; `times` times, or until\n\t * cancelled. Returns its id\n\t */\n\tevery<T>(seconds: number, timer: TimerDef<T>, options: EveryOptions<T>): number {\n\t\tconst every = Math.max(1, this.ticks(seconds))\n\t\tif (options.times !== undefined && options.times < 1) return 0\n\t\treturn this.add(timer, options.data, options.first === undefined ? every : this.ticks(options.first), every, options.times)\n\t}\n\n\t/** Stops a timer from going off again. Whether it was still waiting */\n\tcancel(id: number): boolean {\n\t\tconst { list } = this.state()\n\t\tconst index = list.findIndex((entry) => entry.id === id)\n\t\tif (index < 0) return false\n\t\tlist.splice(index, 1)\n\t\treturn true\n\t}\n\n\t/**\n\t * Shows a player a timer (campaign plan CP5): its words and when it goes off, counted down on their screen (the HUD's\n\t * timers) for as long as it waits. A timer that repeats is shown to each time it next goes off\n\t */\n\tshow(player: PlayerId, id: number, options: { label: MessageRef }): void {\n\t\tconst all = { ...this.world.state(shownTimers) }\n\t\tall[player] = [...(all[player] ?? []).filter((shown) => shown.id !== id), { id, label: toMessage(options.label) }]\n\t\tthis.world.setState(shownTimers, all)\n\t}\n\n\t/** Shows a player a timer no more */\n\thide(player: PlayerId, id: number): void {\n\t\tconst all = { ...this.world.state(shownTimers) }\n\t\tif (!all[player]) return\n\t\tall[player] = all[player].filter((shown) => shown.id !== id)\n\t\tthis.world.setState(shownTimers, all)\n\t}\n\n\t/** The timers a player is shown that still wait, with the tick each goes off at next */\n\tshownTo(player: PlayerId): ShownTimer[] {\n\t\tconst shown = this.world.states.has(shownTimers) ? this.world.state(shownTimers)[player] : undefined\n\t\tif (!shown?.length) return []\n\t\tconst { list } = this.state()\n\t\treturn shown.flatMap(({ id, label }) => {\n\t\t\tconst entry = list.find((candidate) => candidate.id === id)\n\t\t\treturn entry ? [{ id, label, at: entry.at }] : []\n\t\t})\n\t}\n\n\t/** Seconds until the timer next goes off, or undefined when it is not waiting any more */\n\tleft(id: number): number | undefined {\n\t\tconst entry = this.state().list.find((candidate) => candidate.id === id)\n\t\treturn entry && (entry.at - this.world.tick) / this.world.tickRate\n\t}\n\n\t/** Whether the timer is still waiting */\n\thas(id: number): boolean {\n\t\treturn this.state().list.some((entry) => entry.id === id)\n\t}\n\n\t/** What is waiting, in the order it was set: a copy, for the debug tools */\n\tlist(): WaitingTimer[] {\n\t\tconst { tickRate, tick } = this.world\n\t\treturn this.state().list.map((entry) => ({\n\t\t\tid: entry.id,\n\t\t\ttimer: entry.timer,\n\t\t\tdata: structuredClone(entry.data),\n\t\t\tleft: (entry.at - tick) / tickRate,\n\t\t\tevery: entry.every === undefined ? undefined : entry.every / tickRate,\n\t\t\ttimes: entry.times\n\t\t}))\n\t}\n\n\t/** Sets off what is due. The `timers` system calls it at the start of every tick */\n\tupdate(): void {\n\t\tconst state = this.state()\n\t\tconst now = this.world.tick\n\t\t// one at a time, and the list looked at again each time: a timer that goes off may set or cancel others\n\t\tfor (;;) {\n\t\t\tlet due: Waiting | undefined\n\t\t\tfor (const entry of state.list) if (entry.at <= now && (!due || entry.at < due.at || (entry.at === due.at && entry.id < due.id))) due = entry\n\t\t\tif (!due) return\n\t\t\tconst def = this.defs.get(due.timer)\n\t\t\tif (!def) throw new Error(`Timer \"${due.timer}\" went off, and the game has no such timer: give it in GameModule.timers`)\n\t\t\tconst last = due.times === 1 || due.every === undefined\n\t\t\tif (last) state.list.splice(state.list.indexOf(due), 1)\n\t\t\telse {\n\t\t\t\tdue.at += due.every!\n\t\t\t\tif (due.times !== undefined) due.times--\n\t\t\t}\n\t\t\t// one switched off for having thrown (`World.caught`) no longer goes off: what was set is let go\n\t\t\tif (this.world.disabled.has(`timer:${due.timer}`)) continue\n\t\t\ttry {\n\t\t\t\tdef.run(this.world, due.data, { id: due.id, left: last ? 0 : due.times })\n\t\t\t} catch (error) {\n\t\t\t\tthis.world.caught(error, { kind: 'timer', id: due.timer })\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate add(timer: TimerDef, data: unknown, after: number, every?: number, times?: number): number {\n\t\tif (!this.defs.has(timer.id)) throw new Error(`Timer \"${timer.id}\" is not the game's: give it in GameModule.timers, so that a save can find it`)\n\t\tif (this.world.checks.events) assertPlainData(data, `Timer \"${timer.id}\"`)\n\t\tconst state = this.state()\n\t\tconst id = state.next++\n\t\t// due at the start of a later tick: never the one that is going on\n\t\tstate.list.push({ id, timer: timer.id, data, at: this.world.tick + Math.max(1, after), every, times })\n\t\treturn id\n\t}\n\n\tprivate ticks(seconds: number): number {\n\t\treturn Math.round(seconds * this.world.tickRate)\n\t}\n\n\tprivate state() {\n\t\treturn this.world.state(waiting)\n\t}\n}\n\n/** Sets off the timers that are due, at the start of the tick, after the players' commands */\nexport const timerSystem: System = {\n\tname: 'timers',\n\tphase: 'commands',\n\tupdate(world) {\n\t\tworld.timers.update()\n\t}\n}\n","import { defineComponent } from './components'\nimport { assertPlainData } from './debug'\nimport { type EventKey, type ListenerDef, defineListener } from './events'\nimport type { System } from './registry'\nimport { defineTimer, type TimerDef } from './timers'\nimport type { World } from './world'\n\n/** An event a step can wait for: one of the engine's by name, or a game's own */\ntype AnyEvent = EventKey<any>\n\n/** Doing something: runs, and the sequence goes on to the next step at once. `run` is the id of the sequence running it */\ntype Act<D> = (world: World, data: D, run: number) => void\n\n/** Waiting a number of seconds */\ninterface Wait {\n\tkind: 'wait'\n\tseconds: number\n}\n\n/** Waiting for an event, and for what it says to pass a test when there is one */\ninterface WaitFor<D> {\n\tkind: 'waitFor'\n\tevent: AnyEvent\n\t/**\n\t * `run` is the id of the sequence waiting, as an `Act` has it. Not called `test`, as `WaitUntil`'s is: a step's type\n\t * would be inferred from the other's then (`waitFor` in a sequence of data had its data typed `never`)\n\t */\n\tpasses?: (world: World, payload: any, data: D, run: number) => boolean\n}\n\n/** Waiting until something holds. Asked every tick, so keep it cheap */\ninterface WaitUntil<D> {\n\tkind: 'waitUntil'\n\t/** `run` is the id of the sequence waiting, as an `Act` has it */\n\ttest: (world: World, data: D, run: number) => boolean\n}\n\n/**\n * One step of a sequence\n *\n * @beta\n */\nexport type Step<D> = Act<D> | Wait | WaitFor<D> | WaitUntil<D>\n\n/**\n * Waits `seconds` before the next step\n *\n * @beta\n */\nexport const wait = (seconds: number): Wait => ({ kind: 'wait', seconds })\n\n/**\n * Waits for an event, the engine's (`'constructionFinished'`) or a game's own, and for `test` to pass on what it\n * says when there is one. Heard at the end of the tick, like listeners hear events\n *\n * @beta\n */\nexport function waitFor<T, D = any>(event: EventKey<T>, test?: (world: World, payload: T, data: D, run: number) => boolean): WaitFor<D> {\n\treturn { kind: 'waitFor', event, passes: test }\n}\n\n/**\n * Waits until `test` holds: asked at the end of every tick\n *\n * @beta\n */\nexport const waitUntil = <D = any>(test: (world: World, data: D, run: number) => boolean): WaitUntil<D> => ({ kind: 'waitUntil', test })\n\n/**\n * What a mission or a cutscene is mostly made of: do this, wait two seconds, then that, then wait until the gate\n * holds five invaders. Made with `defineSequence` and given in `GameModule.sequences`, so that a save finds the steps\n * by id: what is kept in the world of a running sequence is which one, which step, and its data, never a function.\n * That is why it is not an `async` function: one of those cannot be saved halfway through\n *\n * @beta\n */\nexport interface SequenceDef<D = any> {\n\t/** Shared by every game, like other ids: give it a prefix of the game's (`'td.briefing'`) */\n\treadonly id: string\n\treadonly steps: readonly Step<D>[]\n}\n\n/**\n * Typed help: `defineSequence<{ hero: number }>('td.briefing', [(world) => ..., wait(3), waitFor(constructionFinished)])`.\n * A helper that is several steps (`talk`, `cinematic(id, { wait })`) may be given as its list, spread or not\n *\n * @beta\n */\nexport function defineSequence<D = undefined>(id: string, steps: (Step<D> | readonly Step<D>[])[]): SequenceDef<D> {\n\treturn { id, steps: steps.flat() as Step<D>[] }\n}\n\n/** A sequence as it runs in the world. Plain data: it goes into a save */\ninterface Running {\n\tid: number\n\tsequence: string\n\t/** The step it is at: the one it waits on, while it waits */\n\tstep: number\n\tdata: unknown\n\t/** The timer it waits for, on a `wait` step */\n\ttimer?: number\n}\n\nexport const running = defineComponent<{ next: number; list: Running[] }>('core.sequences', { default: () => ({ next: 1, list: [] }) })\n\n/** The sequences running in the state of a save, by the id of their definition: what a game must still have to load it */\nexport const runningSequences = (state: Record<string, unknown>): string[] =>\n\t((state[running.id] as { list?: Running[] } | undefined)?.list ?? []).map((run) => run.sequence)\n\n/** Takes a sequence that waited out its seconds on to its next step */\nconst resume = defineTimer<{ run: number }>('core.sequenceResume', (world, { run }) => world.sequences.resume(run))\n\n/** The engine's timers, which every world has next to its game's */\nexport const coreTimers: TimerDef[] = [resume]\n\n/**\n * The sequences of a world\n *\n * @beta\n */\nexport class Sequences {\n\tprivate readonly defs = new Map<string, SequenceDef>()\n\n\tconstructor(\n\t\tprivate readonly world: World,\n\t\tdefs: readonly SequenceDef[]\n\t) {\n\t\tfor (const def of defs) {\n\t\t\tif (this.defs.has(def.id)) throw new Error(`Sequence \"${def.id}\" is there twice`)\n\t\t\tthis.defs.set(def.id, def)\n\t\t}\n\t}\n\n\t/**\n\t * Listeners for the events the sequences of a game wait for, one for each event: the world subscribes them with\n\t * the game's own\n\t */\n\tstatic listenersFor(defs: readonly SequenceDef[]): ListenerDef[] {\n\t\tconst events = new Map<string, AnyEvent>()\n\t\tfor (const def of defs) {\n\t\t\tfor (const step of def.steps) {\n\t\t\t\tif (typeof step === 'function' || step.kind !== 'waitFor') continue\n\t\t\t\tevents.set(step.event.id, step.event)\n\t\t\t}\n\t\t}\n\t\treturn [...events].map(([id, event]) =>\n\t\t\tdefineListener({ id: `core.sequences:${id}`, event, run: (world, payload) => world.sequences.heard(id, payload) })\n\t\t)\n\t}\n\n\t/** Starts a sequence: its first steps run at once, up to the first that waits. Returns its id, for `stop` */\n\tstart<D>(sequence: SequenceDef<D>, ...data: D extends undefined ? [] : [D]): number {\n\t\tif (!this.defs.has(sequence.id))\n\t\t\tthrow new Error(`Sequence \"${sequence.id}\" is not the game's: give it in GameModule.sequences, so that a save can find it`)\n\t\tif (this.world.checks.events) assertPlainData(data[0], `Sequence \"${sequence.id}\"`)\n\t\tconst state = this.state()\n\t\tconst run: Running = { id: state.next++, sequence: sequence.id, step: 0, data: data[0] }\n\t\tstate.list.push(run)\n\t\tthis.advance(run)\n\t\treturn run.id\n\t}\n\n\t/** Stops a sequence where it is. Whether it was running */\n\tstop(id: number): boolean {\n\t\tconst { list } = this.state()\n\t\tconst index = list.findIndex((run) => run.id === id)\n\t\tif (index < 0) return false\n\t\tconst [run] = list.splice(index, 1)\n\t\tif (run.timer !== undefined) this.world.timers.cancel(run.timer)\n\t\treturn true\n\t}\n\n\t/** Whether a sequence is still running */\n\trunning(id: number): boolean {\n\t\treturn this.state().list.some((run) => run.id === id)\n\t}\n\n\t/** Cuts the `wait` a sequence is on short, and takes it on at once: a line of dialog skipped. Whether it was waiting */\n\thurry(id: number): boolean {\n\t\tconst run = this.state().list.find((candidate) => candidate.id === id)\n\t\tif (run?.timer === undefined) return false\n\t\tthis.world.timers.cancel(run.timer)\n\t\tthis.resume(id)\n\t\treturn true\n\t}\n\n\t/** Takes a sequence whose `wait` is over on. For the engine's timer */\n\tresume(id: number): void {\n\t\tconst run = this.state().list.find((candidate) => candidate.id === id)\n\t\tif (!run) return\n\t\trun.timer = undefined\n\t\trun.step++\n\t\tthis.advance(run)\n\t}\n\n\t/** An event that sequences may wait for went off. For the engine's listeners */\n\theard(event: string, payload: unknown): void {\n\t\tfor (const run of [...this.state().list]) {\n\t\t\tconst step = this.stepOf(run)\n\t\t\tif (typeof step === 'function' || step?.kind !== 'waitFor') continue\n\t\t\tif (step.event.id !== event) continue\n\t\t\tif (step.passes && !step.passes(this.world, payload, run.data, run.id)) continue\n\t\t\trun.step++\n\t\t\tthis.advance(run)\n\t\t}\n\t}\n\n\t/** Asks the sequences waiting until something holds whether it does. The `sequences` system does, every tick */\n\tupdate(): void {\n\t\tfor (const run of [...this.state().list]) {\n\t\t\tconst step = this.stepOf(run)\n\t\t\tif (typeof step === 'function' || step?.kind !== 'waitUntil' || !step.test(this.world, run.data, run.id)) continue\n\t\t\trun.step++\n\t\t\tthis.advance(run)\n\t\t}\n\t}\n\n\t/** Runs the steps from where the sequence is, up to the next one that waits, or the end */\n\tprivate advance(run: Running): void {\n\t\tconst def = this.defOf(run)\n\t\twhile (run.step < def.steps.length) {\n\t\t\tif (!this.running(run.id)) return\n\t\t\tconst step = def.steps[run.step]\n\t\t\tif (typeof step === 'function') {\n\t\t\t\tstep(this.world, run.data, run.id)\n\t\t\t\trun.step++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (step.kind === 'wait') {\n\t\t\t\trun.timer = this.world.timers.after(step.seconds, resume, { run: run.id })\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (step.kind === 'waitUntil' && step.test(this.world, run.data, run.id)) {\n\t\t\t\trun.step++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// waiting: for an event, or until something holds\n\t\t\treturn\n\t\t}\n\t\tthis.stop(run.id)\n\t}\n\n\tprivate stepOf(run: Running): Step<unknown> | undefined {\n\t\treturn this.defOf(run).steps[run.step]\n\t}\n\n\tprivate defOf(run: Running): SequenceDef {\n\t\tconst def = this.defs.get(run.sequence)\n\t\tif (!def) throw new Error(`Sequence \"${run.sequence}\" is running, and the game has no such sequence: give it in GameModule.sequences`)\n\t\treturn def\n\t}\n\n\tprivate state() {\n\t\treturn this.world.state(running)\n\t}\n}\n\n/** Asks the sequences that wait until something holds, at the end of every tick */\nexport const sequenceSystem: System = {\n\tname: 'sequences',\n\tphase: 'cleanup',\n\tupdate(world) {\n\t\tworld.sequences.update()\n\t}\n}\n","import {\n\tcinematicChoice as cinematicChoiceEvent,\n\tcinematicCue as cinematicCueEvent,\n\tcinematicCued as cinematicCuedEvent,\n\tcinematicEnded as cinematicEndedEvent,\n\tenteredArea\n} from '#engine/engineEvents'\nimport { defineComponent } from './components'\nimport { defineListener } from './events'\nimport type { Audience } from './dialog'\nimport type { PlayerId } from './entity'\nimport { plain } from './plain'\nimport { type Step, waitUntil } from './sequences'\nimport type { World } from './world'\nimport { replicateEvent } from './replication'\n\n/**\n * Cinematics are the screen's: the camera, the HUD making way, the player's hands off. What they are is in a game's\n * view, by id (`GameView.cinematics.defs`). The rules say when one plays, so that it comes at the moment of the game it is\n * about (the start of the mission, a boss coming, the last wave beaten), the same moment for everyone, and a save\n * knows it was played: `playCinematic` now, or `cinematic` as a step of a sequence.\n *\n * The rules and the screen talk both ways. The rules cue a cinematic playing (`cueCinematic`: the gate is open, go on)\n * and a script or the data waits for the cue (`cut.untilCue`, a hook `cue:<name>`). The screen tells the rules when one\n * they played is over, and how (the `cinematic` command, as the player who saw it): the engine says so as\n * `cinematicEnded`, which a sequence waits for (`waitFor(cinematicEndedEvent)`, or `cinematic(id, { wait: 'ended' })`).\n * Being a command, it is in a replay, so what a story does after a cinematic is the same on every screen and every\n * time; the screen's cinematic is not in a replay, as screens are not\n */\n\n/**\n * A cinematic the rules play, as the engine's `cinematic` event carries it to the screens\n *\n * @beta\n */\nexport interface CinematicCue {\n\t/** Which of the view's cinematics */\n\tid: string\n\t/** Who sees it. Everyone when left out */\n\tto?: PlayerId[]\n\t/**\n\t * The game waits while it plays. Only where the simulation runs on the player's machine (single player): a screen\n\t * whose game runs elsewhere plays it with the game going on, as a server does not stop for one player\n\t */\n\thold: boolean\n\t/** The player may skip it */\n\tskippable: boolean\n\t/** What the rules hand the cinematic: the road of this map to fly down. Plain data, as it goes to every screen */\n\tparams?: Record<string, unknown>\n}\n\n/**\n * How a cinematic the rules played ended on a player's screen: played to its end, skipped, stopped (the game left, code\n * stopped it), made way for another, or never played (one already playing would not make way)\n *\n * @beta\n */\nexport type CinematicOutcome = 'ended' | 'skipped' | 'stopped' | 'replaced' | 'ignored'\n\n/** The outcomes a screen may report, for the command's check */\nexport const CINEMATIC_OUTCOMES = ['ended', 'skipped', 'stopped', 'replaced', 'ignored'] as const\n\n/**\n * A cue the rules send to the cinematic playing on some screens (`cueCinematic`), as the engine's `cinematicCued` event\n * carries it\n *\n * @beta\n */\nexport interface CinematicCueSent {\n\t/** Its name, as the cinematic waits for it (`cut.untilCue('gate')`, a hook `cue:gate`) */\n\tcue: string\n\t/** Who it goes to. Everyone when left out */\n\tto?: PlayerId[]\n\t/** What it carries to the cinematic. Plain data */\n\tparams?: Record<string, unknown>\n}\n\n/**\n * A cinematic the rules played is over on a player's screen (the engine's `cinematicEnded` event), as that player's\n * screen said with the `cinematic` command\n *\n * @beta\n */\nexport interface CinematicEnded {\n\t/** Whose screen it ended on */\n\tplayer: PlayerId\n\t/** Which of the view's cinematics */\n\tcinematic: string\n\t/** How it ended there */\n\toutcome: CinematicOutcome\n}\n\n/** @beta */\nexport interface CinematicOptions {\n\t/** Who sees it: a player, some, or everyone. Everyone when left out */\n\tto?: Audience\n\t/** The game waits while it plays, in single player. False when left out */\n\thold?: boolean\n\t/** The player may skip it. True when left out */\n\tskippable?: boolean\n\t/**\n\t * What the cinematic is handed (`Cinematic` is given it): what the rules know and the screen does not, like the\n\t * road of the map being played. Plain data\n\t */\n\tparams?: Record<string, unknown>\n}\n\n/**\n * Plays one of the view's cinematics on the screens of the players it is for, now\n *\n * @beta\n */\nexport function playCinematic(world: World, id: string, options: CinematicOptions = {}): void {\n\tconst { to = 'everyone', hold = false, skippable = true, params } = options\n\tworld.events.emit(cinematicCueEvent, {\n\t\tid,\n\t\tto: audience(to),\n\t\thold,\n\t\tskippable,\n\t\t...(params && { params: plain(params, `params of the cinematic \"${id}\"`, 'Cinematic') as Record<string, unknown> })\n\t})\n}\n\n/** Who a cue or a cinematic goes to, as a list: everyone's is left out */\nconst audience = (to: Audience): PlayerId[] | undefined => (to === 'everyone' ? undefined : Array.isArray(to) ? to : [to])\n\n/**\n * Cues the cinematic playing on the screens of the players it is for (everyone when left out): one waiting for it\n * (`cut.untilCue(name)`) goes on, and the view's hooks of it (`cue:<name>`) run. Nothing happens where none plays, or\n * the one playing does not listen for it. `params` is plain data the cue carries\n *\n * @beta\n */\nexport function cueCinematic(world: World, cue: string, options: { to?: Audience; params?: Record<string, unknown> } = {}): void {\n\tconst { to = 'everyone', params } = options\n\tworld.events.emit(cinematicCuedEvent, {\n\t\tcue,\n\t\tto: audience(to),\n\t\t...(params && { params: plain(params, `params of the cue \"${cue}\"`, 'Cinematic') as Record<string, unknown> })\n\t})\n}\n\n/**\n * A step of a sequence that cues the cinematic playing (see `cueCinematic`): `[wait(4), cinematicCue('gateOpen')]`\n *\n * @beta\n */\nexport const cinematicCue =\n\t<D = undefined>(cue: string, options?: { to?: Audience; params?: Record<string, unknown> }): Step<D> =>\n\t(world) =>\n\t\tcueCinematic(world, cue, options)\n\n/**\n * What a sequence waits for after a cinematic it played: its end for the player it was for (`ended`), the first of the\n * players' ends (`any`), or every player's (`all`). `ended` for a cinematic of several players is `all`\n *\n * @beta\n */\nexport type CinematicWait = 'ended' | 'any' | 'all'\n\n/** The sequences waiting for a cinematic to end on players' screens: in the world, so that a save keeps the count */\nexport const waits = defineComponent<{ list: { run: number; cinematic: string; waiting: PlayerId[]; any: boolean }[] }>('core.cinematicWaits', {\n\tdefault: () => ({ list: [] })\n})\n\n/**\n * A player's screen says a cinematic the rules played is over (the `cinematic` command): the engine says so to the rules\n * (`cinematicEnded`), and a sequence that waits for it counts it\n */\nexport function cinematicEnded(world: World, player: PlayerId, cinematic: string, outcome: CinematicOutcome): void {\n\tif (world.states.has(waits)) {\n\t\tfor (const entry of world.state(waits).list) {\n\t\t\tif (entry.cinematic !== cinematic || !entry.waiting.includes(player)) continue\n\t\t\tentry.waiting = entry.any ? [] : entry.waiting.filter((other) => other !== player)\n\t\t}\n\t}\n\tworld.events.emit(cinematicEndedEvent, { player, cinematic, outcome })\n}\n\n/**\n * A player picked an answer of a choice of a cinematic on their screen (the engine's `cinematicChoice` event), as their\n * screen said with the `cinematicChoice` command: the rules branch on it (`waitFor(cinematicChoiceEvent, ...)`), so that\n * the story's branch is the same on every screen and in a replay\n *\n * @beta\n */\nexport interface CinematicChoice {\n\t/** Whose screen it was picked on */\n\tplayer: PlayerId\n\t/** Which of the view's cinematics */\n\tcinematic: string\n\t/** The choice's name in the cinematic (`choice` when it gave none), and the answer's id */\n\tquestion: string\n\tchoice: string\n\t/** Whether nobody picked and the time ran out on its default */\n\ttimedOut: boolean\n}\n\n/** A player's pick of a choice of a cinematic, as their screen said: heard by the rules as `cinematicChoice` */\nexport function cinematicChose(world: World, choice: CinematicChoice): void {\n\tworld.events.emit(cinematicChoiceEvent, choice)\n}\n\n/**\n * The players a cinematic goes to that have a screen to say it ended: the ones of `to` (everyone's when left out) the\n * computer does not play, and not the neutral ones\n */\nfunction screensOf(world: World, to: PlayerId[] | undefined): PlayerId[] {\n\tconst computers = new Set(world.computers.list())\n\tconst out: PlayerId[] = []\n\tfor (const player of world.players.values()) {\n\t\tif (player.neutral || computers.has(player.id) || (to && !to.includes(player.id))) continue\n\t\tout.push(player.id)\n\t}\n\treturn out\n}\n\n/**\n * A step of a sequence that plays one of the view's cinematics: `defineSequence('td.start', [cinematic('td.intro', {\n * hold: true }), ...talk(...)])`. It does not wait for it (with `hold`, the game, and the sequence with it, waits),\n * unless told to: `wait: 'ended'` goes on once the player it was for has seen it end (or skipped it), `any` once one\n * of the players it went to has, `all` once every one of them has. Only players with a screen are waited for (not the\n * computer's); one who left a game of several never says, so a sequence for many waits for `any` where that matters.\n * With a wait it is two steps, which `defineSequence` takes as they are\n *\n * @beta\n */\nexport function cinematic<D = undefined>(id: string, options?: CinematicOptions & { wait?: undefined }): Step<D>\n/**\n * With `wait`: the cinematic played, then a wait for its end (see the other form), as two steps\n *\n * @beta\n */\nexport function cinematic<D = undefined>(id: string, options: CinematicOptions & { wait: CinematicWait }): Step<D>[]\nexport function cinematic<D = undefined>(id: string, options: CinematicOptions & { wait?: CinematicWait } = {}): Step<D> | Step<D>[] {\n\tconst { wait, ...rest } = options\n\tconst play: Step<D> = (world) => playCinematic(world, id, rest)\n\tif (!wait) return play\n\tconst begin: Step<D> = (world, _data, run) => {\n\t\tconst state = world.state(waits)\n\t\t// what a sequence stopped before its cinematic ended left behind goes\n\t\tstate.list = state.list.filter((entry) => entry.run !== run && world.sequences.running(entry.run))\n\t\tstate.list.push({ run, cinematic: id, waiting: screensOf(world, audience(rest.to ?? 'everyone')), any: wait === 'any' })\n\t\tplayCinematic(world, id, rest)\n\t}\n\tconst over = waitUntil<D>((world, _data, run) => {\n\t\tconst state = world.state(waits)\n\t\tconst entry = state.list.find((candidate) => candidate.run === run)\n\t\tif (entry && entry.waiting.length > 0) return false\n\t\tstate.list = state.list.filter((candidate) => candidate !== entry)\n\t\treturn true\n\t})\n\treturn [begin, over]\n}\n\n/** A cinematic played, to whom it is for: everyone when it names nobody */\nexport const toldCinematic = replicateEvent(cinematicCueEvent, 'cinematic', ({ id, to, hold, skippable, params }, view) =>\n\t!to || to.includes(view.player) ? { type: 'cinematic', cinematic: id, hold, skippable, ...(params && { params }) } : undefined\n)\n\n/** A cue of the rules to a cinematic playing, to whom it is for */\nexport const toldCinematicCue = replicateEvent(cinematicCuedEvent, 'cinematicCue', ({ cue, to, params }, view) =>\n\t!to || to.includes(view.player) ? { type: 'cinematicCue', cue, ...(params && { params }) } : undefined\n)\n\n/**\n * The regions whose cinematic has played (`MapRegion.cinematic`), by name: kept in the world, so that a save knows\n *\n * @internal\n */\nexport const regionCinematicsPlayed = defineComponent<Record<string, true>>('core.regionCinematics', { default: () => ({}) })\n\n/**\n * A region of the map with a cinematic (`MapRegion.cinematic`, ED4) plays it for everyone, once, the first time a unit\n * of a player (not the neutral, nor a building) walks in, unless the game plays it its own way (`play: 'code'`)\n *\n * @beta\n */\nexport const regionCinematic = defineListener({\n\tid: 'core.regionCinematic',\n\tevent: enteredArea,\n\trun(world, { area, entity }) {\n\t\tconst region = world.map.regions.find((each) => each.name === area)\n\t\tconst cinematic = region?.cinematic\n\t\tif (!cinematic || cinematic.play === 'code' || world.player(entity.owner).neutral) return\n\t\tconst played = world.state(regionCinematicsPlayed)\n\t\tif (played[area]) return\n\t\tworld.setState(regionCinematicsPlayed, { ...played, [area]: true })\n\t\tplayCinematic(world, cinematic.id)\n\t}\n})\n","/**\n * An effect of an ability as a save keeps it (`EffectRef`): where it is in the definition of the ability, found again\n * as a save is loaded, or a copy of one made up on the spot. What saves of missiles, zones and dashes are made with\n */\nimport type { EffectDef } from './defs'\nimport { plain } from './plain'\nimport type { Registry } from './registry'\n\n/** An effect of an ability: where it is in the definition of the ability, or a copy for one made up on the spot */\nexport type EffectRef = { path: (string | number)[] } | { value: unknown }\n\n/** Where an effect is in the definition of an ability, found by identity; a copy of it when it is not in there */\nexport function effectRef(registry: Registry, ability: string, effect: EffectDef | EffectDef[]): EffectRef {\n\tconst path = registry.abilities.has(ability) ? find(registry.ability(ability), effect, []) : undefined\n\treturn path ? { path } : { value: plain(effect, `effect of ${ability}`, 'Save', 'keep ids and plain objects in game state') }\n}\n\nfunction find(within: unknown, wanted: unknown, path: (string | number)[]): (string | number)[] | undefined {\n\tif (within === wanted) return path\n\tif (typeof within !== 'object' || within === null) return undefined\n\tfor (const [key, value] of Object.entries(within)) {\n\t\tif (typeof value !== 'object' || value === null) continue\n\t\tconst found = find(value, wanted, [...path, Array.isArray(within) ? Number(key) : key])\n\t\tif (found) return found\n\t}\n\treturn undefined\n}\n\n/** The effect a save kept (`effectRef`): found in the ability again, or the copy */\nexport function resolveEffect(registry: Registry, ability: string, ref: EffectRef): never {\n\tif ('value' in ref) return structuredClone(ref.value) as never\n\tlet at: unknown = registry.ability(ability)\n\tfor (const key of ref.path) at = (at as Record<string | number, unknown>)?.[key]\n\tif (at === undefined) throw new Error(`Save: an effect of \"${ability}\" is not where it was. Was the ability changed since?`)\n\treturn at as never\n}\n","/**\n * An entity on a rush (`Dash`): a charge, a leap, a blink that travels. Made by the effect that starts it, taken off\n * as it lands; kept in a save with its effects as where they are in its ability\n */\nimport { defineComponent } from './components'\nimport { effectRef, type EffectRef, resolveEffect } from './effectRefs'\nimport type { Dash } from './entity'\n\n/**\n * An entity on a rush (`Dash`): where it goes, how fast, what it does as it lands. Filed (`index`), for what moves\n * those on one\n *\n * @beta\n */\nexport const dashing = defineComponent<Dash>('core.dashing', {\n\tindex: true,\n\t// an effect kept as where it is in its ability: the ability has to be there\n\trefs: (saved) =>\n\t\t(saved as { effects: EffectRef }).effects && 'path' in (saved as { effects: EffectRef }).effects ? { abilities: [(saved as Dash).ability] } : {},\n\tsave: (dash, world) => ({ ...dash, effects: effectRef(world.registry, dash.ability, dash.effects) }),\n\tload: (saved, registry) => {\n\t\tconst dash = saved as Dash & { effects: EffectRef }\n\t\treturn { ...dash, effects: resolveEffect(registry, dash.ability, dash.effects) }\n\t}\n})\n","import type { EffectCommon, EffectFields } from '#engine/defs'\nimport type { EditableField } from '#engine/gameData'\n\n/*\n * What the fields of the engine's effects hold, for the editor's Data panel (campaign plan RC2): an effect's type says\n * which of them it reads (`defineEffect`'s `fields`), and the panel offers those of a row of that type\n */\n\n/** The fields every effect may have, whatever its type (`EffectCommon`): offered on every row of effects */\nexport const COMMON_EFFECT_FIELDS: Readonly<Record<keyof EffectCommon, EditableField>> = {\n\tradius: { path: 'radius', kind: 'number', min: 0, hint: 'Hits everything this far around where it lands, not only the target' },\n\taffects: {\n\t\tpath: 'affects',\n\t\toptions: ['enemies', 'allies', 'all'],\n\t\thint: 'Who an effect with a radius applies to: as its type has it when left out'\n\t},\n\ton: { path: 'on', options: ['caster'], hint: 'Applies to the caster, wherever the ability was aimed' },\n\tifBuff: { path: 'ifBuff', kind: 'id', of: 'buffs', hint: 'Only hits what carries this buff' },\n\tonly: { path: 'only', options: ['heroes'], hint: 'Only hits heroes' },\n\tkinds: { path: 'kinds', kind: 'list', hint: 'Only hits these kinds of things (unit, building, …): everything but resources when left out' },\n\tlayers: { path: 'layers', kind: 'list', hint: 'Only hits what is there (ground, air): both when left out' }\n}\n\n/**\n * The engine's fields of an effect by name (`EffectFields`), as the Data panel shows them; `effects`, `onEnd` and\n * `otherwise` are lists of effects. Those of a few values (a missile's `arc`) are a field for each, null for one that\n * is no single value\n */\nexport const EFFECT_FIELDS: Readonly<Record<keyof EffectFields, EditableField | readonly EditableField[] | null>> = {\n\tto: { path: 'to', options: ['home', 'point', 'target'], hint: \"Where to: the side's home, where it was aimed, or by its target\" },\n\tamount: { path: 'amount', kind: 'number', hint: 'How much: of damage, of health, of mana' },\n\tbuff: { path: 'buff', kind: 'id', of: 'buffs', hint: 'The buff put on' },\n\tunit: { path: 'unit', kind: 'id', of: 'units', hint: 'The unit type it brings into the world' },\n\twhileBuff: { path: 'whileBuff', kind: 'id', of: 'buffs', hint: 'Only while the attacker carries this buff' },\n\totherwise: { path: 'otherwise', kind: 'rows', hint: 'What happens when the ability went off not charged' },\n\tblocked: { path: 'blocked', kind: 'boolean', hint: 'Buildings and trees in its way stop it' },\n\tattack: { path: 'attack', kind: 'boolean', hint: 'Only when an attack of the carrier killed' },\n\tability: { path: 'ability', kind: 'id', of: 'abilities', hint: 'The ability ready again: the one the effect belongs to when left out' },\n\tleap: { path: 'leap', kind: 'number', min: 0, hint: 'How high it rises on the way, which makes it a leap' },\n\tclimb: { path: 'climb', kind: 'number', min: 0, hint: 'How much higher than where it takes off the ground on its way may stand' },\n\tduration: { path: 'duration', kind: 'number', min: 0, hint: 'Seconds it lasts: its usual time when left out' },\n\t// what the caster's stats add, by stat: its numbers are fields where an effect has them, none offered where it has not\n\tscaling: null,\n\tdamageType: { path: 'damageType', options: ['physical', 'magic', 'true'], hint: 'Magic when left out' },\n\thow: { path: 'how', kind: 'text', hint: 'How what it kills dies, for the screen' },\n\tdelay: { path: 'delay', kind: 'number', min: 0, hint: 'Seconds before it goes' },\n\tspeed: { path: 'speed', kind: 'number', min: 0, hint: 'Units per second' },\n\tdistance: { path: 'distance', kind: 'number', min: 0, hint: 'How far' },\n\tcount: { path: 'count', kind: 'integer', min: 1, hint: 'How many' },\n\tspread: { path: 'spread', kind: 'number', min: 0, hint: 'The angle the missiles are spread over, in radians' },\n\thoming: { path: 'homing', kind: 'boolean', hint: 'Flies after the unit it was cast on, and only hits that one' },\n\ttoPoint: { path: 'toPoint', kind: 'boolean', hint: 'Flies to the spot it was aimed at and stops there' },\n\tsight: { path: 'sight', kind: 'number', min: 0, hint: 'How far the caster’s team sees around it' },\n\teffects: { path: 'effects', kind: 'rows', hint: 'What happens to what it reaches' },\n\tonEnd: { path: 'onEnd', kind: 'rows', hint: 'What happens where and when it ends' },\n\timpact: { path: 'impact', kind: 'text', hint: 'The name its arrival goes by, for whoever draws it' },\n\tpierce: { path: 'pierce', kind: 'boolean', hint: 'Goes on after it hit something' },\n\tarc: [\n\t\t{\n\t\t\tpath: 'arc.height',\n\t\t\tkind: 'number',\n\t\t\tmin: 0,\n\t\t\thint: 'Thrown: how high it goes in the middle of its way. It flies over everything and hits where it comes down'\n\t\t},\n\t\t{ path: 'arc.time', kind: 'number', min: 0, hint: 'Seconds it is in the air, however far it goes: its speed when left out' }\n\t],\n\tbounce: [\n\t\t{ path: 'bounce.count', kind: 'integer', min: 0, hint: 'How many times it springs on to the nearest it has not hit yet' },\n\t\t{ path: 'bounce.range', kind: 'number', min: 0, hint: 'How far away the next one it springs on to may be' },\n\t\t{ path: 'bounce.falloff', kind: 'number', min: 0, max: 1, hint: 'What part of its amounts each spring takes off (0.25: a quarter)' }\n\t],\n\tstack: { path: 'stack', kind: 'boolean', hint: 'Adds one to how many of the buff the target carries, up to what the buff allows' },\n\tsell: { path: 'sell', kind: 'text', hint: 'The resource traded away, by id' },\n\tbuy: { path: 'buy', kind: 'text', hint: 'The resource traded for, by id' },\n\trate: { path: 'rate', kind: 'number', min: 0, hint: 'How much of what is bought comes for each one sold' }\n}\n","import { manaChanged, missileHit, missileRemoved } from '#engine/engineEvents'\nimport { slotsOf } from '#engine/inventory'\nimport { dashing } from '../dashing'\nimport {\n\ttype AbilityDef,\n\tat,\n\ttype EffectCommon,\n\ttype EffectDef,\n\ttype EffectFields,\n\ttype EffectOf,\n\ttype EffectTypes,\n\tpassiveEffects\n} from '#engine/defs'\nimport type { EditableField } from '#engine/gameData'\nimport { EFFECT_FIELDS } from './effectFields'\nimport { type Dash, distanceToEdge, type Entity } from '#engine/entity'\nimport { dist, type Vec2 } from '#engine/math'\nimport { halt, setGhost } from '#engine/systems/movement'\nimport type { Missile, World } from '#engine/world'\nimport { agentParamsOf } from '#engine/navigation/agentParams'\nimport { avoids, hasBuff, layerOf, removeBuff } from './buffs'\nimport { land, run } from './land'\nimport { atan2 } from '#engine/exactMath'\nimport { heroState } from '#engine/hero'\nimport { moving } from '../entity'\nimport { replicateEvent, snapshotPart } from '../replication'\nimport type { MissileState } from '../session/protocol'\n\n/** @beta */\nexport interface EffectContext {\n\tworld: World\n\tcaster: Entity\n\tability: AbilityDef\n\t/** Level the ability was cast at */\n\tlevel: number\n\t/** The unit the ability was cast on, if any */\n\ttarget?: Entity\n\t/** Where the ability landed: the target, the chosen spot, or the caster */\n\tpoint: Vec2\n\t/** How far what carried the effect here has come, for what a missile does */\n\tdistance?: number\n\t/**\n\t * What part of their amounts the effects come to (`damage`, `heal`, `mana`): less on every spring of a missile that\n\t * bounces (`EffectFields.bounce`). All of it when left out; a game's own effect with an amount multiplies by it too\n\t */\n\tshare?: number\n\t/** How many of the buff that ran out there were, for what happens when it does */\n\tstacks?: number\n\t/** The ability went off charged, see `charge` on the ability */\n\tcharged?: boolean\n\t/**\n\t * For an effect that is kept up all the time (a passive asked every round): the seconds since it was last asked.\n\t * Something that works per second multiplies by this, rather than counting on how often it is asked\n\t */\n\tinterval?: number\n}\n\n/**\n * Carries out an effect, whatever its type: what the registry hands for a type (`registry.effect`), to call with an\n * effect of that type\n *\n * @beta\n */\nexport type EffectHandler = (context: EffectContext, effect: EffectDef) => void\n\n/**\n * A kind of effect: its type and what it does (`defineEffect`). The engine's are the game's from the start; a game\n * lists its own in `GameModule.effects`, and one of a type the engine has takes its place\n *\n * @beta\n */\nexport interface EffectKind<K extends keyof EffectTypes = keyof EffectTypes> {\n\treadonly type: K\n\t/** Carries out an effect of the type, for a cast (or a passive asked, a missile's hit...) */\n\trun(context: EffectContext, effect: EffectOf<K>): void\n\t/** An effect of the type, for an ability's list: `pull.of({ distance: 3 })` is `{ type: 'pull', distance: 3 }` */\n\tof(fields: EffectCommon & EffectTypes[K]): EffectOf<K>\n\t/**\n\t * The fields an effect of the type reads, besides those every effect has (`EffectCommon`): what the editor's Data\n\t * panel offers on a row of the type (campaign plan RC2). None said, it offers those a row has\n\t */\n\treadonly fields?: readonly EditableField[]\n}\n\n/**\n * What a kind of effect says besides what it does (`defineEffect`): the fields it reads, each the name of one of the\n * engine's (`EffectFields`) or said in full, its path the field's name in the effect (`{ path: 'pull', kind: 'number' }`)\n *\n * @beta\n */\nexport interface EffectKindOptions {\n\tfields?: readonly (keyof EffectFields | EditableField)[]\n}\n\n/**\n * A kind of effect, its type and what it does together: `defineEffect('pull', (context, effect) => ...)`, listed in\n * `GameModule.effects`. Its fields are said by declaring the type in `EffectTypes`\n * (`declare module '@v12-engine/engine' { interface EffectTypes { pull: { distance: number } } }`), so that a handler\n * reads them typed, and an ability's effect of the type is checked for them\n *\n * @beta\n */\nexport function defineEffect<K extends keyof EffectTypes>(\n\ttype: K,\n\trun: (context: EffectContext, effect: EffectOf<K>) => void,\n\toptions: EffectKindOptions = {}\n): EffectKind<K> {\n\tconst fields = options.fields?.flatMap((field) => (typeof field === 'string' ? (EFFECT_FIELDS[field] ?? []) : [field]))\n\treturn { type, run, of: (fields) => ({ ...fields, type }) as EffectOf<K>, ...(fields && { fields }) }\n}\n\nconst found: Entity[] = []\n\n/**\n * Who an effect applies to\n *\n * @beta\n */\nexport function effectTargets(context: EffectContext, effect: EffectDef, fallback: 'enemies' | 'allies'): Entity[] {\n\tconst { world, caster, target, point } = context\n\tif (effect.on === 'caster') return [caster]\n\tconst { layers } = effect\n\tconst radius = at(effect.radius, context.level)\n\tconst fits = (entity: Entity) =>\n\t\t(!effect.ifBuff || hasBuff(entity, effect.ifBuff)) &&\n\t\t(effect.only !== 'heroes' || entity.has(heroState)) &&\n\t\t(!effect.kinds || effect.kinds.includes(entity.def.kind))\n\tif (!radius) {\n\t\tconst one = target ?? caster\n\t\tif (one !== caster && avoids(world, one, context.ability)) return []\n\t\treturn (!layers || layers.includes(layerOf(world, one))) && fits(one) ? [one] : []\n\t}\n\n\tconst affects = effect.affects ?? fallback\n\tconst result: Entity[] = []\n\tfor (const entity of world.spatial.query(point.x, point.z, radius, found)) {\n\t\tif (!entity.alive || entity.hidden || entity.isResource) continue\n\t\tif (distanceToEdge(point, entity) > radius) continue\n\t\tif (layers && !layers.includes(layerOf(world, entity))) continue\n\t\tif (affects === 'enemies' && !world.areEnemies(caster.owner, entity.owner)) continue\n\t\tif (affects === 'allies' && !world.areAllies(caster.owner, entity.owner)) continue\n\t\tif (entity !== caster && avoids(world, entity, context.ability)) continue\n\t\tif (fits(entity)) result.push(entity)\n\t}\n\treturn result\n}\n\n/**\n * What the attacks of a unit do on top of their damage: the `onHit` effects among what its abilities, and\n * the items it carries, do all the time. Called for every attack that lands\n */\nexport function onHit(world: World, attacker: Entity, target: Entity): void {\n\tconst apply = (ability: AbilityDef, level: number) => {\n\t\tfor (const effect of passiveEffects(ability)) {\n\t\t\tif (effect.type !== 'onHit' || (effect.whileBuff && !hasBuff(attacker, effect.whileBuff))) continue\n\t\t\trun({ world, caster: attacker, ability, level, target, point: { x: target.pos.x, z: target.pos.z } }, effect.effects)\n\t\t}\n\t}\n\tfor (const state of attacker.abilities) if (state.level > 0) apply(world.registry.ability(state.id), state.level)\n\tfor (const instance of slotsOf(attacker) ?? []) {\n\t\tconst passive = instance && world.registry.item(instance.item).passive\n\t\tif (passive) apply(world.registry.ability(passive), 1)\n\t}\n}\n\n/** Whether an ability of the caster is charged: its `charge` buff is on it with as many stacks as it can have */\nexport function isCharged(world: World, caster: Entity, ability: AbilityDef): boolean {\n\tif (!ability.charge) return false\n\tconst instance = caster.buffs.find((carried) => carried.id === ability.charge)\n\treturn !!instance && (instance.stacks ?? 0) >= (world.registry.buff(ability.charge).maxStacks ?? 1)\n}\n\n/**\n * What the passives of the caster do whenever it casts an ability: for a hero, one of the abilities it learns.\n * Called once the ability went off, and not for one that went off charged: what spends a charge does not count to the next\n */\nexport function onCast(world: World, caster: Entity, cast: AbilityDef): void {\n\tif (caster.def.hero && !caster.def.hero.learns.includes(cast.id)) return\n\tfor (const state of caster.abilities) {\n\t\tif (state.level < 1) continue\n\t\tconst ability = world.registry.ability(state.id)\n\t\tfor (const effect of passiveEffects(ability)) {\n\t\t\tif (effect.type !== 'onCast') continue\n\t\t\trun({ world, caster, ability, level: state.level, point: { x: caster.pos.x, z: caster.pos.z } }, effect.effects)\n\t\t}\n\t}\n}\n\n/**\n * Takes someone off the ground for a leap or a throw. Up there it is nobody's obstacle: it pushes no one\n * on its way over them, and goes straight over what cannot be walked\n */\n/**\n * Sends an entity rushing to a spot (`dash.x`, `dash.z`): nothing stops it on the way, its orders wait, and what\n * `dash.effects` do happens where it ends. A leap (`dash.height`) takes it off the ground until it comes down\n *\n * @beta\n */\nexport function startDash(world: World, entity: Entity, dash: Omit<Dash, 'from'>): void {\n\tif (entity.isStructure) throw new Error(`${entity.def.id}#${entity.id} is a structure: it cannot rush anywhere`)\n\tworld.wake(entity)\n\tentity.set(dashing, { ...dash, from: { x: entity.pos.x, z: entity.pos.z } })\n\tif (dash.height) takeOff(world, entity)\n}\n\nfunction takeOff(world: World, entity: Entity): void {\n\tif (!entity.get(moving)) return\n\thalt(world, entity)\n\tworld.nav.removeAgent(entity.id)\n}\n\n/** Back on the ground, where it came down */\nfunction touchDown(world: World, entity: Entity): void {\n\tconst m = entity.get(moving)\n\tif (!m) return\n\tworld.nav.addAgent(entity.id, entity.pos, agentParamsOf(entity, m.speed))\n\t// the agent is new, so it lost its flags\n\tconst { ghost } = m\n\tm.ghost = false\n\tm.anchored = false\n\tm.status = 'idle'\n\tsetGhost(world, entity, ghost)\n\t// what it was doing starts over from here: on its way again, after whom it was after\n\tconst order = entity.orders[0]\n\tif (order) order.started = false\n}\n\n/**\n * What killing someone sets off: the `onKill` effects among what the abilities of the killer do all the time.\n * `attack` says whether it was one of its attacks that killed\n */\nexport function onKill(world: World, killer: Entity, victim: Entity, attack: boolean): void {\n\tfor (const state of killer.abilities) {\n\t\tif (state.level < 1) continue\n\t\tconst ability = world.registry.ability(state.id)\n\t\tfor (const effect of passiveEffects(ability)) {\n\t\t\tif (effect.type !== 'onKill' || (effect.attack && !attack) || (effect.only === 'heroes' && !victim.has(heroState))) continue\n\t\t\trun({ world, caster: killer, ability, level: state.level, target: victim, point: { x: victim.pos.x, z: victim.pos.z } }, effect.effects)\n\t\t}\n\t}\n}\n\nconst crossed: Entity[] = []\n/** Seconds between two rounds of a zone seeing to what is inside */\nconst ZONE_INTERVAL = 0.25\n\nfunction removeMissile(world: World, index: number): void {\n\tconst [missile] = world.missiles.splice(index, 1)\n\tworld.events.emit(missileRemoved, missile)\n}\n\n/** Whether a missile may hit an entity, as its effect says: who it is for, of what kind, where, and once */\nfunction mayHit(world: World, missile: Missile, caster: Entity, ability: AbilityDef, entity: Entity): boolean {\n\tconst { effect } = missile\n\tif (!entity.alive || entity.hidden || entity.isResource || entity === caster || missile.hit.has(entity.id)) return false\n\tif (effect.layers && !effect.layers.includes(layerOf(world, entity))) return false\n\tif (effect.kinds && !effect.kinds.includes(entity.def.kind)) return false\n\tif (avoids(world, entity, ability)) return false\n\tconst affects = effect.affects ?? 'enemies'\n\tif (affects === 'enemies' && !world.areEnemies(missile.owner, entity.owner)) return false\n\tif (affects === 'allies' && !world.areAllies(missile.owner, entity.owner)) return false\n\treturn true\n}\n\n/** What a missile's effects come to after it sprang on as many times as it has: `falloff` less each time */\nfunction shareOf(missile: Missile): number | undefined {\n\tconst falloff = missile.effect.bounce?.falloff\n\tif (!missile.bounces || !falloff) return undefined\n\tlet share = 1\n\tfor (let i = 0; i < missile.bounces; i++) share *= Math.max(1 - falloff, 0)\n\treturn share\n}\n\n/** What a missile does to one it hits: its effects, as much of them as is left after its springs */\nfunction strike(world: World, missile: Missile, caster: Entity, ability: AbilityDef, target: Entity): void {\n\tmissile.hit.add(target.id)\n\tconst point = { x: target.pos.x, z: target.pos.z }\n\tland({ world, caster, ability, level: missile.level, target, point, distance: missile.travelled, share: shareOf(missile) }, missile.effect.effects)\n\tworld.events.emit(missileHit, { missile, target })\n}\n\n/**\n * Where a missile that bounces would be done, it springs on (`EffectFields.bounce`): after the nearest one within its\n * range of where it is that it may hit and has not, the lowest id among those as near. False when it has sprung as many\n * times as it may, or there is nobody to spring on to\n */\nfunction springOn(world: World, missile: Missile, caster: Entity, ability: AbilityDef): boolean {\n\tconst { bounce, arc } = missile.effect\n\tif (!bounce || missile.bounces >= Math.round(at(bounce.count, missile.level))) return false\n\tlet next: Entity | undefined\n\tlet nearest = Infinity\n\tfor (const entity of world.spatial.query(missile.x, missile.z, bounce.range, crossed)) {\n\t\tif (!mayHit(world, missile, caster, ability, entity)) continue\n\t\tconst gap = distanceToEdge(missile, entity)\n\t\tif (gap > bounce.range || gap > nearest || (gap === nearest && next && entity.id > next.id)) continue\n\t\tnearest = gap\n\t\tnext = entity\n\t}\n\tif (!next) return false\n\tmissile.target = next.id\n\tmissile.bounces++\n\tmissile.leg = 0\n\tmissile.left = Infinity\n\tmissile.stopped = false\n\t// thrown again in the same time, however far the next one is\n\tif (arc?.time && arc.time > 0) missile.speed = dist(missile, next.pos) / arc.time\n\treturn true\n}\n\n/** How high a missile's arc carries it, `leg` along a way that has `left` to go: highest halfway */\nconst arcHeight = (arc: EffectFields['arc'], leg: number, left: number): number => {\n\tif (!arc || !(leg + left > 0) || !Number.isFinite(left)) return 0\n\tconst way = leg / (leg + left)\n\treturn 4 * arc.height * way * (1 - way)\n}\n\n/** Moves the missiles of abilities along, and lets them do what they do to what they pass through and where they come down */\nexport function updateMissiles(world: World, dt: number): void {\n\tconst { missiles } = world\n\tfor (let i = missiles.length - 1; i >= 0; i--) {\n\t\tconst missile = missiles[i]\n\t\tif (missile.delay > 0) {\n\t\t\t// taking shape: it goes nowhere and touches nobody yet\n\t\t\tmissile.delay -= dt\n\t\t\tmissile.prevX = missile.x\n\t\t\tmissile.prevZ = missile.z\n\t\t\tcontinue\n\t\t}\n\t\tconst caster = world.entities.get(missile.source)\n\t\tconst { effect } = missile\n\t\tconst ability = world.registry.abilities.has(missile.ability) ? world.registry.ability(missile.ability) : undefined\n\t\tmissile.prevX = missile.x\n\t\tmissile.prevZ = missile.z\n\n\t\tif (missile.target) {\n\t\t\t// after its target, wherever that goes, until it has it\n\t\t\tconst target = world.get(missile.target)\n\t\t\tif (!target || target.hidden || !caster || !ability) {\n\t\t\t\tremoveMissile(world, i)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst gap = dist(missile, target.pos)\n\t\t\tconst step = missile.speed * dt\n\t\t\tif (gap > 0.01) {\n\t\t\t\tmissile.dx = (target.pos.x - missile.x) / gap\n\t\t\t\tmissile.dz = (target.pos.z - missile.z) / gap\n\t\t\t}\n\t\t\tif (gap <= step + target.def.radius * 0.5) {\n\t\t\t\tmissile.x = target.pos.x\n\t\t\t\tmissile.z = target.pos.z\n\t\t\t\tmissile.travelled += gap\n\t\t\t\tmissile.leg += gap\n\t\t\t\tmissile.height = 0\n\t\t\t\tstrike(world, missile, caster, ability, target)\n\t\t\t\tif (!springOn(world, missile, caster, ability)) removeMissile(world, i)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmissile.x += missile.dx * step\n\t\t\tmissile.z += missile.dz * step\n\t\t\tmissile.travelled += step\n\t\t\tmissile.leg += step\n\t\t\tmissile.height = arcHeight(effect.arc, missile.leg, gap - step)\n\t\t\tcontinue\n\t\t}\n\n\t\tconst step = Math.min(missile.speed * dt, missile.left)\n\t\tmissile.x += missile.dx * step\n\t\tmissile.z += missile.dz * step\n\t\tmissile.left -= step\n\t\tmissile.travelled += step\n\t\tmissile.leg += step\n\t\tmissile.height = arcHeight(effect.arc, missile.leg, missile.left)\n\n\t\t// what is thrown flies over everyone and everything, and comes down on what is where it lands\n\t\tif (!effect.arc) {\n\t\t\t// what has nothing to do to anyone passes everyone by\n\t\t\tif (caster && ability && effect.effects?.length) {\n\t\t\t\tfor (const entity of [...world.spatial.query(missile.x, missile.z, missile.radius, crossed)]) {\n\t\t\t\t\tif (!mayHit(world, missile, caster, ability, entity) || distanceToEdge(missile, entity) > missile.radius) continue\n\t\t\t\t\tstrike(world, missile, caster, ability, entity)\n\t\t\t\t\tif (effect.pierce === false) {\n\t\t\t\t\t\t// used up by it, unless it springs on from it\n\t\t\t\t\t\tif (!springOn(world, missile, caster, ability)) {\n\t\t\t\t\t\t\tmissile.left = 0\n\t\t\t\t\t\t\tmissile.stopped = true\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (missile.target) continue\n\t\t\t// buildings and trees stand in its way, whoever's they are, and nothing happens to them\n\t\t\tif (effect.blocked && !missile.stopped) {\n\t\t\t\tfor (const entity of world.spatial.query(missile.x, missile.z, missile.radius, crossed)) {\n\t\t\t\t\tif (!entity.alive || entity.hidden || entity.def.kind === 'unit' || distanceToEdge(missile, entity) > missile.radius) continue\n\t\t\t\t\tmissile.left = 0\n\t\t\t\t\tmissile.stopped = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (missile.left <= 0) {\n\t\t\tif (effect.arc && caster && ability && effect.effects?.length) {\n\t\t\t\tfor (const entity of [...world.spatial.query(missile.x, missile.z, missile.radius, crossed)]) {\n\t\t\t\t\tif (mayHit(world, missile, caster, ability, entity) && distanceToEdge(missile, entity) <= missile.radius)\n\t\t\t\t\t\tstrike(world, missile, caster, ability, entity)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!missile.stopped && caster && ability && springOn(world, missile, caster, ability)) continue\n\t\t\tif (caster && ability && effect.onEnd && !missile.stopped) {\n\t\t\t\tconst point = { x: missile.x, z: missile.z }\n\t\t\t\tland({ world, caster, ability, level: missile.level, point, distance: missile.travelled, share: shareOf(missile) }, effect.onEnd)\n\t\t\t}\n\t\t\tremoveMissile(world, i)\n\t\t}\n\t}\n}\n\n/** What abilities left behind to happen later, and the ground they go on working on */\nexport function updateLingering(world: World, dt: number): void {\n\tconst { delayed, zones } = world\n\tfor (let i = delayed.length - 1; i >= 0; i--) {\n\t\tconst entry = delayed[i]\n\t\tentry.left -= dt\n\t\tif (entry.left > 0) continue\n\t\tdelayed.splice(i, 1)\n\t\tland({ world, caster: entry.caster, ability: entry.ability, level: entry.level, point: entry.point }, entry.effects, entry.impact)\n\t}\n\tfor (let i = zones.length - 1; i >= 0; i--) {\n\t\tconst zone = zones[i]\n\t\tconst context = { world, caster: zone.caster, ability: zone.ability, level: zone.level, point: { x: zone.x, z: zone.z } }\n\t\tzone.left -= dt\n\t\tzone.next -= dt\n\t\tif (zone.left <= 0) {\n\t\t\tzones.splice(i, 1)\n\t\t\tland(context, zone.effect.onEnd)\n\t\t} else if (zone.next <= 0) {\n\t\t\tzone.next = ZONE_INTERVAL\n\t\t\trun(context, zone.effect.effects)\n\t\t}\n\t}\n}\n\n/** Carries those who rush somewhere towards where they are going. Nothing holds them up, and what it does happens when they arrive */\nexport function updateDashes(world: World, dt: number): void {\n\tfor (const entity of world.index.with(dashing)) {\n\t\tconst dash = entity.get(dashing)\n\t\tif (!dash || !entity.alive) continue\n\t\tconst gap = dist(entity.pos, dash)\n\t\tconst step = dash.speed * dt\n\t\tif (gap > step) {\n\t\t\tworld.place(entity, { x: entity.pos.x + ((dash.x - entity.pos.x) / gap) * step, z: entity.pos.z + ((dash.z - entity.pos.z) / gap) * step })\n\t\t\tcontinue\n\t\t}\n\t\tworld.place(entity, dash)\n\t\tentity.remove(dashing)\n\t\tif (dash.buff) removeBuff(world, entity, dash.buff)\n\t\tif (dash.height) touchDown(world, entity)\n\t\tif (!world.registry.abilities.has(dash.ability)) continue\n\t\tconst ability = world.registry.ability(dash.ability)\n\t\tland({ world, caster: entity, ability, level: dash.level, point: { x: entity.pos.x, z: entity.pos.z } }, dash.effects)\n\t}\n}\n\n/** A missile reaching what it hits, to those who see what it hits */\nexport const toldMissileHit = replicateEvent(missileHit, 'missileHit', ({ missile, target }, view) =>\n\tview.knows(target) ? { type: 'missileHit', missile: missile.id, target: target.id } : undefined\n)\n\n/** Mana given or taken: its side's alone */\nexport const toldMana = replicateEvent(manaChanged, 'mana', ({ entity, amount, ability }, view) =>\n\tview.isAlly(entity.owner) ? { type: 'mana', id: entity.id, amount, ability } : undefined\n)\n\n/** The missiles of abilities in flight the player is told of: their side's, and those where they see (`Snapshot.missiles`); none to a computer */\nexport const missilesPart = snapshotPart('missiles', (view) => {\n\tconst missiles: MissileState[] = []\n\tif (view.forComputer) return missiles\n\tconst { world } = view\n\tfor (const m of world.missiles) {\n\t\tif (!view.isAlly(m.owner) && !view.sees(m.x, m.z)) continue\n\t\tconst source = world.get(m.source)\n\t\tmissiles.push({\n\t\t\tid: m.id,\n\t\t\tability: m.ability,\n\t\t\tlevel: m.level,\n\t\t\tsource: source && view.knows(source) ? source.id : undefined,\n\t\t\tx: m.x,\n\t\t\tz: m.z,\n\t\t\tradius: m.radius,\n\t\t\theading: atan2(m.dx, m.dz),\n\t\t\tforming: m.delay > 0 ? 1 - m.delay / m.forms : undefined,\n\t\t\tprogress: Number.isFinite(m.left) ? m.travelled / (m.travelled + m.left || 1) : undefined,\n\t\t\tarc: m.height || undefined\n\t\t})\n\t}\n\treturn missiles\n})\n","import type { Vec2 } from './math'\n\n/**\n * Checkers for what comes in from the outside, like the commands of a player. On a server that is whatever\n * anyone sends, so nothing is taken on trust: a checker either hands back the value as the type it promises,\n * or throws `Invalid` saying what is wrong with it, and where (`td.intro.lanes[2].items[0].at is a number`): the\n * commands of a player, a cinematic's file, a lane's own items and the game's other files are checked by these alike.\n *\n * ```ts\n * const fields = { building: id, unitType: string, queue: optional(bool) }\n * type Fields = Checked<typeof fields> // { building: number; unitType: string; queue?: boolean }\n * ```\n *\n * @beta\n */\nexport type Check<T> = (value: unknown, path: string) => T\n\n/**\n * A set of named checkers: what an object must have\n *\n * @beta\n */\nexport type Fields = Record<string, Check<unknown>>\n\ntype Out<C> = C extends Check<infer T> ? T : never\n/** The fields a checker lets be left out: the ones it may hand back `undefined` for */\ntype OptionalKeys<F extends Fields> = { [K in keyof F]: undefined extends Out<F[K]> ? K : never }[keyof F]\n\n/**\n * The type a set of checkers hands back. Fields that may be left out are optional\n *\n * @beta\n */\nexport type Checked<F extends Fields> = {\n\t[K in keyof F as K extends OptionalKeys<F> ? never : K]: Out<F[K]>\n} & {\n\t[K in OptionalKeys<F>]?: Exclude<Out<F[K]>, undefined>\n}\n\n/** @beta */\nexport class Invalid extends Error {}\n\nconst fail = (path: string, wanted: string): never => {\n\tthrow new Invalid(`${path} is ${wanted}`)\n}\n\n/**\n * Whether a value is a plain object (not a list, not null): what most of a file's fields are\n *\n * @beta\n */\nexport const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** The longest string accepted. Ids and names are short; nothing needs more */\nconst MAX_STRING = 200\n/** The most ids accepted in one list: more than anyone can select */\nconst MAX_IDS = 1000\n\n/** @beta */\nexport const bool: Check<boolean> = (value, path) => (typeof value === 'boolean' ? value : fail(path, 'true or false'))\n\n/**\n * Any finite number\n *\n * @beta\n */\nexport const number: Check<number> = (value, path) => (typeof value === 'number' && Number.isFinite(value) ? value : fail(path, 'a number'))\n\n/**\n * A whole number, 0 or more\n *\n * @beta\n */\nexport const index: Check<number> = (value, path) =>\n\tNumber.isInteger(value) && (value as number) >= 0 ? (value as number) : fail(path, 'a whole number, 0 or more')\n\n/**\n * The id of an entity or a player\n *\n * @beta\n */\nexport const id: Check<number> = (value, path) => (Number.isInteger(value) && (value as number) >= 0 ? (value as number) : fail(path, 'an id'))\n\n/**\n * Any number of seconds: a finite number, not below 0\n *\n * @beta\n */\nexport const seconds: Check<number> = (value, path) => {\n\tconst n = number(value, path)\n\treturn n >= 0 ? n : fail(path, 'a number of seconds, not below 0')\n}\n\n/**\n * Words of any length: what a file says (a line of dialog, a name), not what a player sends (`string`)\n *\n * @beta\n */\nexport const text: Check<string> = (value, path) => (typeof value === 'string' ? value : fail(path, 'text'))\n\n/**\n * A colour as the client draws it: `[r, g, b]`, each a number\n *\n * @beta\n */\nexport const rgb: Check<[number, number, number]> = (value, path) =>\n\tArray.isArray(value) && value.length === 3 && value.every((n) => typeof n === 'number' && Number.isFinite(n))\n\t\t? [value[0], value[1], value[2]]\n\t\t: fail(path, 'a colour: [r, g, b]')\n\n/**\n * A list of anything, or none for one left out: each of its values checked by the caller, by its own path\n *\n * @beta\n */\nexport const list: Check<unknown[]> = (value, path) => (value === undefined ? [] : Array.isArray(value) ? value : fail(path, 'a list'))\n\n/** @beta */\nexport const string: Check<string> = (value, path) =>\n\ttypeof value === 'string' && value.length <= MAX_STRING ? value : fail(path, `text of at most ${MAX_STRING} characters`)\n\n/** @beta */\nexport const ids: Check<number[]> = (value, path) => {\n\tif (!Array.isArray(value) || value.length > MAX_IDS) fail(path, `a list of at most ${MAX_IDS} ids`)\n\treturn (value as unknown[]).map((item, i) => id(item, `${path}[${i}]`))\n}\n\n/** @beta */\nexport const point: Check<Vec2> = (value, path) => {\n\tif (typeof value !== 'object' || value === null) fail(path, 'a point: { x, z }')\n\tconst { x, z } = value as Record<string, unknown>\n\treturn { x: number(x, `${path}.x`), z: number(z, `${path}.z`) }\n}\n\n/**\n * What may be left out\n *\n * @beta\n */\nexport function optional<T>(check: Check<T>): Check<T | undefined> {\n\treturn (value, path) => (value === undefined ? undefined : check(value, path))\n}\n\n/**\n * One of a few fixed values\n *\n * @beta\n */\nexport function oneOf<const T extends readonly (string | number)[]>(...values: T): Check<T[number]> {\n\treturn (value, path) => (values.includes(value as T[number]) ? (value as T[number]) : fail(path, `one of ${values.join(', ')}`))\n}\n\n/**\n * An object with these fields. Fields that are not asked for are dropped, so nothing unchecked gets through\n *\n * @beta\n */\nexport function object<F extends Fields>(fields: F): Check<Checked<F>> {\n\treturn (value, path) => {\n\t\tif (typeof value !== 'object' || value === null || Array.isArray(value)) fail(path, 'an object')\n\t\tconst source = value as Record<string, unknown>\n\t\tconst result: Record<string, unknown> = {}\n\t\tfor (const key in fields) {\n\t\t\tconst checked = fields[key](source[key], path ? `${path}.${key}` : key)\n\t\t\tif (checked !== undefined) result[key] = checked\n\t\t}\n\t\treturn result as Checked<F>\n\t}\n}\n","import type { Entity, EntityId } from './entity'\nimport type { Vec2 } from './math'\nimport type { Navigation } from './navigation/navigation'\nimport type { World } from './world'\nimport { cos, hypot, sin } from './exactMath'\n\nconst GAP = 0.35\n\n/**\n * What a formation lays units out with: the group, where it is sent, the way there, and the room each unit takes.\n * Points are in the world; `right` and `forward` are the formation's own axes, each a unit long, for a shape that is\n * drawn facing the way of travel: a place `right * x + forward * z` from the target\n *\n * @beta\n */\nexport interface FormationContext {\n\treadonly world: World\n\t/** The units laid out: those that walk, or those that fly, apart */\n\treadonly units: readonly Entity[]\n\treadonly target: Vec2\n\t/** The navigation they go on, to find where they can stand */\n\treadonly nav: Navigation\n\t/** The middle of where the units are */\n\treadonly centre: Vec2\n\t/** The way from where they are to the target, a unit long (forward, where they face at the end) */\n\treadonly forward: Vec2\n\t/** To the right of `forward`, a unit long */\n\treadonly right: Vec2\n\t/** Room a unit takes: twice the biggest radius among them, and a gap of `FORMATION_GAP` */\n\treadonly spacing: number\n\t/** A point in the world, `x` to the right of the target and `z` forward of it */\n\tplace(x: number, z: number): Vec2\n\t/** The nearest point a unit can stand on, or the target where there is none within 4 */\n\tsnap(point: Vec2): Vec2\n}\n\n/**\n * How units ordered to a point together are laid out around it (`OrderInit.formation`, `GameRules.movement.formation`): a\n * shape, which the engine fits the units to, or the places themselves. The engine's own are `rows`, `circle`,\n * `square` and `none` (`coreFormations`); a game adds its own (`GameModule.formations`), and changes any laid out\n * with the `formation` hook\n *\n * @beta\n */\nexport interface FormationDef {\n\tid: string\n\t/** What the player sees it called */\n\tname: string\n\t/**\n\t * The shape, as `count` places `spacing` apart, in the formation's own space: `x` to the right, `z` forward, the\n\t * first places at the front. Units are fitted to them so that their ways cross as little as can be\n\t * (`fitToPlaces`): those ahead to the places at the front\n\t */\n\tshape?(count: number, spacing: number, context: FormationContext): Vec2[]\n\t/**\n\t * The places themselves, by the unit's id, when the shape is not enough: one that goes by who the units are, or\n\t * where they stand. A unit given none goes to the target itself. Over `shape` where both are given\n\t */\n\tpoints?(context: FormationContext): Map<EntityId, Vec2>\n}\n\n/**\n * The gap between two units standing next to each other in a formation\n *\n * @beta\n */\nexport const FORMATION_GAP = GAP\n\n/** The places of a shape in the world, each snapped onto where a unit can stand */\nfunction placed(context: FormationContext, shape: readonly Vec2[]): Vec2[] {\n\treturn shape.map(({ x, z }) => context.snap(context.place(x, z)))\n}\n\n/**\n * Fits units to places so that their ways cross as little as can be: the places in order, the front first, each to\n * the unit nearest it, measured from where the group is to where it goes (the unit's place in the group against the\n * place's in the formation). A unit left without a place goes to the target\n *\n * @beta\n */\nexport function fitToPlaces(context: FormationContext, places: readonly Vec2[]): Map<EntityId, Vec2> {\n\tconst { units, centre, target } = context\n\tconst points = new Map<EntityId, Vec2>()\n\tconst left = [...units].sort((a, b) => a.id - b.id)\n\tfor (const place of places) {\n\t\tif (left.length === 0) break\n\t\tconst px = place.x - target.x\n\t\tconst pz = place.z - target.z\n\t\tlet nearest = 0\n\t\tlet best = Infinity\n\t\tfor (let i = 0; i < left.length; i++) {\n\t\t\tconst unit = left[i]\n\t\t\tconst d = hypot(unit.pos.x - centre.x - px, unit.pos.z - centre.z - pz)\n\t\t\tif (d < best) {\n\t\t\t\tbest = d\n\t\t\t\tnearest = i\n\t\t\t}\n\t\t}\n\t\tpoints.set(left[nearest].id, place)\n\t\tleft.splice(nearest, 1)\n\t}\n\tfor (const unit of left) points.set(unit.id, target)\n\treturn points\n}\n\n/**\n * The engine's usual formation: a tight group keeps its shape as it is, and a scattered one lines up in rows across\n * the way of travel, as many across as there are rows, the units ahead in the front rows\n *\n * @beta\n */\nexport const rowsFormation: FormationDef = {\n\tid: 'rows',\n\tname: 'Rows',\n\tpoints(context) {\n\t\tconst { units, target, centre, spacing, forward, right, snap } = context\n\t\tconst points = new Map<EntityId, Vec2>()\n\t\tlet spread = 0\n\t\tfor (const unit of units) spread = Math.max(spread, hypot(unit.pos.x - centre.x, unit.pos.z - centre.z))\n\t\tconst travel = hypot(target.x - centre.x, target.z - centre.z)\n\t\tconst compact = spacing * Math.sqrt(units.length)\n\t\tif (spread <= compact && travel > spread) {\n\t\t\tfor (const unit of units) points.set(unit.id, snap({ x: target.x + unit.pos.x - centre.x, z: target.z + unit.pos.z - centre.z }))\n\t\t\treturn points\n\t\t}\n\t\tconst columns = Math.ceil(Math.sqrt(units.length))\n\t\tconst rows = Math.ceil(units.length / columns)\n\t\t// front rows go to the units that are already ahead, to keep paths from crossing\n\t\tconst ahead = (u: Entity) => (u.pos.x - centre.x) * forward.x + (u.pos.z - centre.z) * forward.z\n\t\tconst sideways = (u: Entity) => (u.pos.x - centre.x) * right.x + (u.pos.z - centre.z) * right.z\n\t\tconst ordered = [...units].sort((a, b) => ahead(b) - ahead(a) || a.id - b.id)\n\t\tfor (let row = 0; row < rows; row++) {\n\t\t\tconst members = ordered.slice(row * columns, (row + 1) * columns).sort((a, b) => sideways(a) - sideways(b) || a.id - b.id)\n\t\t\tconst back = (row - (rows - 1) / 2) * spacing\n\t\t\tfor (let i = 0; i < members.length; i++) {\n\t\t\t\tconst side = (i - (members.length - 1) / 2) * spacing\n\t\t\t\tpoints.set(members[i].id, snap(context.place(side, -back)))\n\t\t\t}\n\t\t}\n\t\treturn points\n\t}\n}\n\n/** How many places a ring of a radius has room for, `spacing` apart */\nconst ringRoom = (radius: number, spacing: number) => Math.max(Math.floor((2 * Math.PI * radius) / spacing), 1)\n\n/**\n * The places of rings around the middle, the first ring a `spacing` out and each further one a `spacing` further,\n * the outermost first: as many rings as it takes to hold them all, the outer ones full, and the middle last.\n * `room` says how many places a ring `radius` out has, and `ring` gives the places of one, the first at the front\n */\nfunction rings(\n\tcount: number,\n\tspacing: number,\n\troom: (radius: number, spacing: number) => number,\n\tring: (radius: number, on: number) => Vec2[]\n): Vec2[] {\n\tif (count <= 1) return [{ x: 0, z: 0 }]\n\tlet outer = 0\n\tfor (let held = 1; held < count; outer++) held += room((outer + 1) * spacing, spacing)\n\tconst places: Vec2[] = []\n\tlet left = count\n\tfor (let i = outer; i >= 1 && left > 0; i--) {\n\t\tconst on = Math.min(room(i * spacing, spacing), left)\n\t\tplaces.push(...ring(i * spacing, on))\n\t\tleft -= on\n\t}\n\tif (left > 0) places.push({ x: 0, z: 0 })\n\treturn places\n}\n\n/** The places of a ring, evenly, the first at the front, clockwise */\nfunction circleRing(radius: number, on: number): Vec2[] {\n\tconst places: Vec2[] = []\n\tfor (let i = 0; i < on; i++) {\n\t\tconst angle = (i / on) * 2 * Math.PI\n\t\tplaces.push({ x: radius * sin(angle), z: radius * cos(angle) })\n\t}\n\treturn places\n}\n\n/**\n * A circle: a ring around the target, the first place at the front, and rings within it where one is not enough for\n * them all. The rings are a `spacing` apart, the first a `spacing` out: as many as it takes, the outer ones full\n *\n * @beta\n */\nexport const circleFormation: FormationDef = {\n\tid: 'circle',\n\tname: 'Circle',\n\tshape: (count, spacing) => rings(count, spacing, ringRoom, circleRing)\n}\n\n/** How many places the edge of a square of a half side has room for, `spacing` apart */\nconst squareRoom = (half: number, spacing: number) => Math.max(Math.round((2 * half) / spacing) * 4, 1)\n\n/** The places along the edge of a square, evenly, from the middle of its front, clockwise */\nfunction squareEdge(half: number, count: number): Vec2[] {\n\tconst places: Vec2[] = []\n\tconst perimeter = 8 * half\n\tfor (let i = 0; i < count; i++) {\n\t\t// along the edge from the front's middle: front to the right, right side down, back leftwards, left side up\n\t\tlet along = ((i / count) * perimeter) % perimeter\n\t\tif (along < half) places.push({ x: along, z: half })\n\t\telse if ((along -= half) < 2 * half) places.push({ x: half, z: half - along })\n\t\telse if ((along -= 2 * half) < 2 * half) places.push({ x: half - along, z: -half })\n\t\telse if ((along -= 2 * half) < 2 * half) places.push({ x: -half, z: -half + along })\n\t\telse places.push({ x: -half + (along - 2 * half), z: half })\n\t}\n\treturn places\n}\n\n/**\n * A square: units along the edges of one around the target, the first place at the front's middle, and squares\n * within it where one is not enough for them all. The squares are a `spacing` apart, the first a `spacing` out: as\n * many as it takes, the outer ones full\n *\n * @beta\n */\nexport const squareFormation: FormationDef = {\n\tid: 'square',\n\tname: 'Square',\n\tshape: (count, spacing) => rings(count, spacing, squareRoom, squareEdge)\n}\n\n/**\n * No formation: every unit to the point itself, as units sent one by one go\n *\n * @beta\n */\nexport const noneFormation: FormationDef = {\n\tid: 'none',\n\tname: 'None',\n\tshape: (count) => Array.from({ length: count }, () => ({ x: 0, z: 0 }))\n}\n\n/**\n * The engine's formations: `rows` (the usual), `circle`, `square` and `none`\n *\n * @beta\n */\nexport const coreFormations: readonly FormationDef[] = [rowsFormation, circleFormation, squareFormation, noneFormation]\n\n/**\n * What a formation is laid out with, for a group sent to a target on a navigation\n *\n * @internal\n */\nexport function formationContext(world: World, units: readonly Entity[], target: Vec2, nav: Navigation): FormationContext {\n\tlet cx = 0\n\tlet cz = 0\n\tlet radius = 0\n\tfor (const unit of units) {\n\t\tcx += unit.pos.x\n\t\tcz += unit.pos.z\n\t\tradius = Math.max(radius, unit.def.radius)\n\t}\n\tcx /= units.length\n\tcz /= units.length\n\tconst travel = hypot(target.x - cx, target.z - cz)\n\tconst forward = { x: travel > 0.001 ? (target.x - cx) / travel : 0, z: travel > 0.001 ? (target.z - cz) / travel : 1 }\n\tconst right = { x: forward.z, z: -forward.x }\n\treturn {\n\t\tworld,\n\t\tunits,\n\t\ttarget,\n\t\tnav,\n\t\tcentre: { x: cx, z: cz },\n\t\tforward,\n\t\tright,\n\t\tspacing: radius * 2 + GAP,\n\t\tplace: (x, z) => ({ x: target.x + right.x * x + forward.x * z, z: target.z + right.z * x + forward.z * z }),\n\t\tsnap: (p) => nav.closestPoint(p, 4) ?? target\n\t}\n}\n\n/**\n * Individual destinations for a group ordered to the same point, in a formation (`rowsFormation` when none is\n * given), and what the `formation` hook makes of them. Units that walk and units that fly are laid out apart, each\n * on their own navigation (`world.navFor`)\n *\n * @beta\n */\nexport function formationPoints(world: World, units: readonly Entity[], target: Vec2, formation: FormationDef = rowsFormation): Map<EntityId, Vec2> {\n\tif (units.length === 0) return new Map()\n\tconst context = formationContext(world, units, target, world.navFor(units[0]))\n\tlet points: Map<EntityId, Vec2>\n\tif (units.length === 1) points = new Map([[units[0].id, target]])\n\telse if (formation.points) points = formation.points(context)\n\telse if (formation.shape) points = fitToPlaces(context, placed(context, formation.shape(units.length, context.spacing, context)))\n\telse throw new Error(`The formation \"${formation.id}\" has neither a shape nor points`)\n\tif (world.hooks.has('formation')) world.hooks.run('formation', { units, target, formation, points })\n\treturn points\n}\n","import { inventoryChanged as inventoryChangedEvent, itemDropped, itemPicked } from '#engine/engineEvents'\nimport { defineComponent } from './components'\nimport { freeSlot, inventorySlots, slotsOf } from './inventory'\nimport type { ItemDef } from './defs'\nimport type { Entity, ItemInstance, Placed, StockState } from './entity'\nimport type { StockInfo } from './session/protocol'\nimport { sellValue } from './shared'\nimport { refreshVitals } from './stats'\nimport { dist, type Vec2 } from './math'\nimport { currencyOf, earn, shortOf, spend } from './player'\nimport type { World } from './world'\nimport { engineMessage } from './messages'\nimport { replicateEvent, snapshotPart } from './replication'\n\n/**\n * A hero has to stand this close to a shop to buy from it\n *\n * @internal\n */\nexport const SHOP_RANGE = 6\n/**\n * And this close to something on the ground to pick it up, or to someone to hand it over\n *\n * @internal\n */\nexport const REACH = 1.2\n\n/**\n * An item lying on the ground\n *\n * @beta\n */\nexport interface GroundItem {\n\tid: number\n\titem: string\n\tcharges: number\n\tx: number\n\tz: number\n}\n\n/** @beta */\nexport function createItem(world: World, item: string, charges?: number): ItemInstance {\n\tconst def = world.registry.item(item)\n\treturn {\n\t\tid: world.newId(),\n\t\titem,\n\t\tcharges: charges ?? def.charges ?? 0,\n\t\tstate: def.ability ? { id: def.ability, level: 1, cooldown: 0, autocast: false } : undefined\n\t}\n}\n\n/** Call after the inventory changed: what is carried changes what the carrier can do, and the game is told */\nfunction inventoryChanged(world: World, entity: Entity): void {\n\trefreshVitals(world, entity)\n\tworld.events.emit(inventoryChangedEvent, { entity })\n}\n\n/**\n * Puts an item into the first free slot. False when there is none\n *\n * @beta\n */\nexport function giveItem(world: World, entity: Entity, instance: ItemInstance): boolean {\n\tconst slot = freeSlot(entity)\n\tconst slots = slotsOf(entity)\n\tif (slot < 0 || !slots) return false\n\tslots[slot] = instance\n\tinventoryChanged(world, entity)\n\treturn true\n}\n\n/** @beta */\nexport function takeItem(world: World, entity: Entity, instanceId: number): ItemInstance | undefined {\n\tconst slots = slotsOf(entity)\n\tconst slot = slots?.findIndex((instance) => instance?.id === instanceId) ?? -1\n\tif (slot < 0) return undefined\n\tconst instance = slots![slot]!\n\tslots![slot] = null\n\tinventoryChanged(world, entity)\n\treturn instance\n}\n\n/** @beta */\nexport function findItem(entity: Entity, instanceId: number | undefined): ItemInstance | undefined {\n\treturn slotsOf(entity)?.find((instance) => instance?.id === instanceId) ?? undefined\n}\n\n/** @beta */\nexport function dropOnGround(world: World, instance: ItemInstance, at: Vec2): GroundItem {\n\tconst point = world.nav.closestPoint(at, 6) ?? at\n\tconst item = { id: instance.id, item: instance.item, charges: instance.charges, x: point.x, z: point.z }\n\tworld.items.push(item)\n\tworld.events.emit(itemDropped, item)\n\treturn item\n}\n\n/** @beta */\nexport function pickUp(world: World, entity: Entity, groundId: number): boolean {\n\tconst index = world.items.findIndex((item) => item.id === groundId)\n\tif (index < 0 || freeSlot(entity) < 0) return false\n\tif (world.hooks.has('beforePickUp')) {\n\t\tconst before = world.hooks.run('beforePickUp', { entity, item: world.items[index].item, ground: groundId, cancelled: false })\n\t\tif (before.cancelled) {\n\t\t\tif (before.reason) world.message(entity.owner, before.reason)\n\t\t\treturn false\n\t\t}\n\t}\n\tconst [item] = world.items.splice(index, 1)\n\tconst instance = createItem(world, item.item, item.charges)\n\tinstance.id = item.id\n\tgiveItem(world, entity, instance)\n\tworld.events.emit(itemPicked, { entity, item: instance })\n\treturn true\n}\n\n/**\n * One use of an item that has charges. The last one takes the item with it\n *\n * @beta\n */\nexport function spendCharge(world: World, entity: Entity, instance: ItemInstance): void {\n\tif (!world.registry.item(instance.item).charges) return\n\tinstance.charges--\n\tif (instance.charges <= 0) takeItem(world, entity, instance.id)\n}\n\n/** Part of its price an item is bought back for */\n\n/**\n * Whether someone stands close enough to a shop to trade with it. Anything with a place will do: an entity, or what a screen knows of one\n *\n * @beta\n */\nexport const atShop = (entity: Placed, shop: Placed) => dist(entity.pos, shop.pos) <= SHOP_RANGE + shop.def.radius\n\n/**\n * What buying an item comes to for someone who carries these things: the items it is made of that are there are\n * used up and taken off the price, and so are the parts of the ones that are not\n *\n * @beta\n */\nexport function priceOf(registry: World['registry'], item: string, carried: readonly string[]): { price: number; uses: string[] } {\n\tconst left = [...carried]\n\tconst uses: string[] = []\n\tconst listed = (id: string) => currencyOf(registry, registry.item(id).cost)\n\tconst remaining = (id: string): number => {\n\t\tconst def: ItemDef = registry.item(id)\n\t\tlet price = listed(id)\n\t\tfor (const part of def.from ?? []) {\n\t\t\tconst index = left.indexOf(part)\n\t\t\tif (index >= 0) {\n\t\t\t\tleft.splice(index, 1)\n\t\t\t\tuses.push(part)\n\t\t\t\tprice -= listed(part)\n\t\t\t} else {\n\t\t\t\tprice -= listed(part) - remaining(part)\n\t\t\t}\n\t\t}\n\t\treturn Math.max(price, 0)\n\t}\n\treturn { price: remaining(item), uses }\n}\n\nconst carriedBy = (entity: Entity) => (slotsOf(entity) ?? []).flatMap((instance) => (instance ? [instance.item] : []))\n\n/** Whether the entity has room for the item, counting what buying it would use up */\nfunction fits(world: World, entity: Entity, item: string): boolean {\n\treturn freeSlot(entity) >= 0 || priceOf(world.registry, item, carriedBy(entity)).uses.length > 0\n}\n\n/**\n * What a shop has of each of its wares (`UnitTypeDef.sells`): how many are left and the seconds until the next one.\n * Set as the shop is spawned, counted down by the abilities system while the shop stands; filed in the index\n * (`world.index.with(shopStock)`); sent to everyone who sees the shop as `StockInfo` (how far the next one is, 0..1, not\n * the seconds), the delta comparing ware by ware\n *\n * @beta\n */\nexport const shopStock = defineComponent<StockState[], StockInfo[]>('core.shop', {\n\trefs: (stock) => ({ items: (stock as StockState[]).map((entry) => entry.item) }),\n\treplicate: 'everyone',\n\tindex: true,\n\tsnapshot(stock, _entity, { world }) {\n\t\treturn stock.map((entry) => {\n\t\t\tconst def = world.registry.item(entry.item).stock\n\t\t\t// what there is no end of has no count\n\t\t\tif (!def) return { item: entry.item, restock: 0 }\n\t\t\tconst full = entry.count >= def.max\n\t\t\treturn { item: entry.item, count: entry.count, restock: full ? 0 : Math.round((1 - entry.restock / def.restock) * 100) / 100 }\n\t\t})\n\t},\n\tsame: (a, b) => a.length === b.length && a.every((ware, i) => ware.item === b[i].item && ware.count === b[i].count && ware.restock === b[i].restock)\n})\n\n/** The player's hero that is closest to a shop and has room for the item, or for anything when none is named, if one is close enough */\nexport function shopper(world: World, shop: Entity, player: number, item?: string): Entity | undefined {\n\tlet best: Entity | undefined\n\tlet bestDistance = Infinity\n\tfor (const entity of world.index.ownedBy(player)) {\n\t\tif (!entity.alive || entity.hidden || !entity.has(inventorySlots)) continue\n\t\tconst distance = dist(entity.pos, shop.pos)\n\t\tif (!atShop(entity, shop) || distance >= bestDistance) continue\n\t\tif (item ? !fits(world, entity, item) : freeSlot(entity) < 0) continue\n\t\tbestDistance = distance\n\t\tbest = entity\n\t}\n\treturn best\n}\n\n/**\n * Sells an item to a hero standing at the shop: the one that is named, or the closest one with room.\n * Tells the player why when it cannot\n *\n * @beta\n */\nexport function buy(world: World, shop: Entity, item: string, player: number, buyer?: Entity): boolean {\n\tconst stock = shop.get(shopStock)?.find((entry) => entry.item === item)\n\tif (!stock || !shop.operational || !world.registry.items.has(item)) return false\n\tconst def: ItemDef = world.registry.item(item)\n\tconst purse = world.player(player).resources\n\tif (def.stock && stock.count <= 0) {\n\t\tworld.message(player, engineMessage('outOfStock'))\n\t\treturn false\n\t}\n\tconst named = buyer?.alive && !buyer.hidden && buyer.has(inventorySlots) && atShop(buyer, shop) && fits(world, buyer, item) ? buyer : undefined\n\tconst hero = named ?? shopper(world, shop, player, item)\n\tif (!hero) {\n\t\tworld.message(player, engineMessage('heroAtShop'))\n\t\treturn false\n\t}\n\tconst { price, uses } = priceOf(world.registry, item, carriedBy(hero))\n\tlet cost = world.registry.currency ? { ...def.cost, [world.registry.currency]: price } : def.cost\n\t// what the game makes of it: a discount, only heroes of a kind\n\tif (world.hooks.has('beforeBuy')) {\n\t\tconst before = world.hooks.run('beforeBuy', { buyer: hero, shop, item, cost: { ...cost }, cancelled: false })\n\t\tif (before.cancelled) {\n\t\t\tif (before.reason) world.message(player, before.reason)\n\t\t\treturn false\n\t\t}\n\t\tcost = before.cost\n\t}\n\tconst short = shortOf(purse, cost)\n\tif (short) {\n\t\tworld.message(player, engineMessage('notEnough', { resource: short }))\n\t\treturn false\n\t}\n\tspend(world, player, cost, 'item', item)\n\tif (def.stock) stock.count--\n\tfor (const part of uses) {\n\t\tconst used = slotsOf(hero)!.find((instance) => instance?.item === part)\n\t\tif (used) takeItem(world, hero, used.id)\n\t}\n\tconst instance = createItem(world, item)\n\tgiveItem(world, hero, instance)\n\tworld.events.emit(itemPicked, { entity: hero, item: instance })\n\treturn true\n}\n\n/**\n * Whether a shop the player can trade with is close enough to the entity\n *\n * @beta\n */\nexport function shopNear(world: World, entity: Entity): Entity | undefined {\n\tfor (const shop of world.index.with(shopStock)) {\n\t\tif (shop.alive && shop.operational && !world.areEnemies(shop.owner, entity.owner) && atShop(entity, shop)) return shop\n\t}\n\treturn undefined\n}\n\n/**\n * Gives an item back at a shop nearby, for a part of its price. What has charges is worth as much as is left of it\n *\n * @beta\n */\nexport function sell(world: World, entity: Entity, instanceId: number): boolean {\n\tconst instance = findItem(entity, instanceId)\n\tif (!instance || !entity.alive || entity.hidden) return false\n\tif (!shopNear(world, entity)) {\n\t\tworld.message(entity.owner, engineMessage('noShopNear'))\n\t\treturn false\n\t}\n\ttakeItem(world, entity, instance.id)\n\tif (world.registry.currency)\n\t\tearn(world.player(entity.owner).resources, world.registry.currency, sellValue(world.registry, instance.item, instance.charges))\n\treturn true\n}\n\n/** What a dead unit leaves behind: by its table of chances, or as its code decides */\nexport function dropLoot(world: World, entity: Entity, killer?: Entity): void {\n\tconst { drops } = entity.def\n\tif (typeof drops === 'function') {\n\t\tfor (const item of drops(world, entity, killer)) dropOnGround(world, createItem(world, item), entity.pos)\n\t\treturn\n\t}\n\tfor (const drop of drops ?? []) {\n\t\tif (world.rng.next() < drop.chance) dropOnGround(world, createItem(world, drop.item), entity.pos)\n\t}\n}\n\n/** An item picked up, to those who see who picked it */\nexport const toldPicked = replicateEvent(itemPicked, 'picked', ({ entity, item }, view) =>\n\tview.knows(entity) ? { type: 'picked', id: entity.id, item: item.item } : undefined\n)\n\n/** The items on the ground where the player sees (`Snapshot.items`) */\nexport const itemsPart = snapshotPart('items', ({ world, sees }) =>\n\tworld.items.filter((item) => sees(item.x, item.z)).map(({ id, item, x, z }) => ({ id, item, x, z }))\n)\n","import type { Entity, Order } from '#engine/entity'\nimport { orderSays } from './facts'\nimport type { OrderInit, OrderParams } from '#engine/registry'\nimport { disengage } from '#engine/systems/combat'\nimport { halt } from '#engine/systems/movement'\nimport type { World } from '#engine/world'\nimport { fighting } from '../entity'\n\n/** Classic RTS games cap queues as well. Mostly a guard against runaway shift-clicking */\nexport const MAX_QUEUED_ORDERS = 32\n\nexport function createOrder(world: World, init: OrderInit, groupId = 0): Order {\n\treturn {\n\t\tid: world.newId(),\n\t\ttype: init.type,\n\t\tinit: orderParams(init),\n\t\tgroupId,\n\t\tstarted: false,\n\t\tstate: {}\n\t}\n}\n\n/**\n * What an order keeps of what it was given: its fields as plain data of its own (a point copied, not the command's),\n * those that are there alone, in one order (what a save and the determinism hash meet)\n */\nfunction orderParams(init: OrderInit): OrderParams {\n\tconst params: OrderParams = {}\n\tif (init.target !== undefined) params.target = init.target\n\tif (init.point) params.point = { x: init.point.x, z: init.point.z }\n\tif (init.unitType !== undefined) params.unitType = init.unitType\n\tif (init.ability !== undefined) params.ability = init.ability\n\tif (init.item !== undefined) params.item = init.item\n\tif (init.facing !== undefined) params.facing = init.facing\n\tif (init.path !== undefined) params.path = init.path\n\tif (init.towards === 'first' || init.towards === 'last') params.towards = init.towards\n\tif (init.speedCap !== undefined && Number.isFinite(init.speedCap)) params.speedCap = init.speedCap\n\treturn params\n}\n\nfunction endOrder(world: World, entity: Entity, order: Order): void {\n\tif (order.started) world.registry.order(order.type).end?.(world, entity, order)\n}\n\n/** Back to a neutral stance between orders: not walking, not mid swing, free to be pushed. */\nexport function resetStance(world: World, entity: Entity): void {\n\thalt(world, entity)\n\tdisengage(world, entity)\n\tif (entity.get(fighting)) {\n\t\tentity.get(fighting)!.autoTarget = 0\n\t\tentity.get(fighting)!.guard = null\n\t}\n}\n\n/** Drops everything the entity was doing */\nexport function clearOrders(world: World, entity: Entity): void {\n\tconst current = entity.orders[0]\n\tentity.keepOrders()\n\tif (current) endOrder(world, entity, current)\n\tresetStance(world, entity)\n}\n\n/** Whether the entity is in the middle of something it cannot be called away from, like casting (`OrderBehavior.committed`) */\nexport const isCommitted = (world: World, entity: Entity) => orderSays(world, entity, 'committed')\n\n/**\n * Drops what the entity was doing, as far as it lets itself be called away:\n * what it is committed to is finished first, only what was to come after is dropped.\n */\nexport function interrupt(world: World, entity: Entity): void {\n\tif (isCommitted(world, entity)) entity.keepOrders(1)\n\telse clearOrders(world, entity)\n}\n\n/**\n * Gives an order. Queued orders wait their turn, anything else replaces what the unit is doing,\n * or comes right after it when the unit is committed to it.\n */\nexport function giveOrder(world: World, entity: Entity, order: Order, queue = false): void {\n\tif (world.hooks.run('beforeOrder', { entity, order, queued: queue, rejected: false }).rejected) return\n\tworld.wake(entity)\n\tif (entity.get(fighting)) entity.get(fighting)!.passive = false\n\tif (queue) {\n\t\tif (entity.orders.length < MAX_QUEUED_ORDERS) entity.addOrder(order)\n\t\treturn\n\t}\n\t// told to attack what it was already swinging at, of its own accord or on the way somewhere: the swing goes on\n\tconst combat = entity.get(fighting)\n\tconst swing = combat && order.type === 'attack' && order.init.target !== undefined && combat.swingTarget === order.init.target ? combat.swing : 0\n\tinterrupt(world, entity)\n\tentity.addOrder(order)\n\tif (combat && swing > 0) {\n\t\tcombat.swing = swing\n\t\tcombat.swingTarget = order.init.target!\n\t}\n}\n\n/** Removes the order at the front of the queue once it finished */\nexport function completeOrder(world: World, entity: Entity, order: Order): void {\n\tendOrder(world, entity, order)\n\tentity.removeOrder(order)\n\tresetStance(world, entity)\n}\n","import { abilityCast, castStarted, channelEnded, channelStarted, manaChanged } from '#engine/engineEvents'\nimport { isSilenced, isSpellImmune, isStunned, layerOf, pierces, removeBuff } from '#engine/abilities/buffs'\nimport { dashing } from '../dashing'\nimport { isCharged } from '#engine/abilities/effects'\nimport { type AbilityDef, at } from '#engine/defs'\nimport { type AbilityState, edgeDistance, type Entity, type ItemInstance } from '#engine/entity'\nimport { findItem, spendCharge } from '#engine/items'\nimport { dist, type Vec2 } from '#engine/math'\nimport type { OrderBehavior, OrderInits } from '#engine/registry'\nimport { canSee } from '#engine/systems/combat'\nimport { faceTowards, halt, moveTo, moveToEntity, setAnchored } from '#engine/systems/movement'\nimport { cooldownOf, statsOf } from '#engine/stats'\nimport type { World } from '#engine/world'\nimport { engineMessage, type Message, toMessage } from '#engine/messages'\nimport { clearOrders } from './queue'\nimport { abilityReach, abilityRefusal, chargesLeft, targetRefusal, type TargetFacts } from '#engine/shared'\nimport { spendUse } from '#engine/abilities/charges'\nimport { atan2 } from '#engine/exactMath'\nimport { heroState } from '#engine/hero'\nimport { moving } from '../entity'\n\n/**\n * Whether an ability may be used on a target: as its `targets` say, and the `canTarget` hook\n *\n * @beta\n */\nexport function validTarget(world: World, caster: Entity, ability: AbilityDef, target: Entity): boolean {\n\tif (!target.alive || target.hidden) return false\n\tconst refusal = targetRefusal(ability, targetFacts(world, caster, target, ability))\n\tif (!world.hooks.has('canTarget')) return !refusal\n\treturn !world.hooks.run('canTarget', { caster, ability, target, refusal }).refusal\n}\n\n/**\n * What a target is to a caster, for `targetRefusal`\n *\n * @beta\n */\nexport function targetFacts(world: World, caster: Entity, target: Entity, ability?: AbilityDef): TargetFacts {\n\tconst relation =\n\t\ttarget === caster\n\t\t\t? 'self'\n\t\t\t: world.areAllies(caster.owner, target.owner)\n\t\t\t\t? 'ally'\n\t\t\t\t: world.areEnemies(caster.owner, target.owner)\n\t\t\t\t\t? 'enemy'\n\t\t\t\t\t: 'neutral'\n\treturn {\n\t\tkind: target.def.kind,\n\t\tlayer: layerOf(world, target),\n\t\thero: target.has(heroState),\n\t\tinvulnerable: !!target.def.invulnerable,\n\t\trelation,\n\t\t// immune, unless this ability gets through, as its code may say for this target\n\t\tspellImmune: isSpellImmune(world, target) && !(ability && pierces(world, ability, target))\n\t}\n}\n\n/**\n * How far away the target of an ability may be: what it says, and for some as far as the caster's attacks reach on top\n *\n * @beta\n */\nexport function castRange(world: World, caster: Entity, ability: AbilityDef, level: number): number {\n\tif (ability.rangeOf) return ability.rangeOf(world, caster, level)\n\treturn abilityReach(ability, level, ability.attackRange ? statsOf(world, caster).attackRange : 0)\n}\n\n/**\n * Seconds of the wind-up of an ability: in code, or as it says\n *\n * @beta\n */\nexport const castTimeOf = (world: World, caster: Entity, ability: AbilityDef, level: number): number =>\n\tability.castTimeOf?.(world, caster, level) ?? ability.castTime ?? 0\n\n/** What a cast order uses: an ability of the caster, or the one of an item it carries */\nfunction source(\n\tworld: World,\n\tentity: Entity,\n\tfrom: { ability?: string; item?: number }\n): { ability: AbilityDef; state: AbilityState; item?: ItemInstance } | undefined {\n\tif (from.item !== undefined) {\n\t\tconst item = findItem(entity, from.item)\n\t\tif (!item?.state || !world.registry.abilities.has(item.state.id)) return undefined\n\t\treturn { ability: world.registry.ability(item.state.id), state: item.state, item }\n\t}\n\tif (!from.ability || !world.registry.abilities.has(from.ability)) return undefined\n\tconst state = entity.abilities.find((a) => a.id === from.ability)\n\treturn state && { ability: world.registry.ability(from.ability), state }\n}\n\n/**\n * Whether the ability is one of the spells the hero brought along, as opposed to what it learned\n *\n * @beta\n */\nexport const isSpell = (entity: Entity, ability: AbilityDef) => entity.def.hero?.spells?.includes(ability.id) ?? false\n\n/**\n * Why an ability cannot be used right now, or undefined when it can. Items ask for no mana, and silence does not stop them\n *\n * @beta\n */\nexport function notReady(world: World, entity: Entity, ability: AbilityDef, item?: ItemInstance): Message | undefined {\n\tconst refusal = declaredRefusal(world, entity, ability, item)\n\tif (!world.hooks.has('canCast')) return refusal\n\tconst level = (item ? item.state : entity.abilities.find((a) => a.id === ability.id))?.level ?? 0\n\tconst decided = world.hooks.run('canCast', { caster: entity, ability, level, item, refusal }).refusal\n\treturn decided === undefined ? undefined : toMessage(decided)\n}\n\n/**\n * Why an ability cannot be used right now as its declared costs and the caster's state go: what the screen knows\n *\n * @internal\n */\nexport function declaredRefusal(world: World, entity: Entity, ability: AbilityDef, item?: ItemInstance): Message | undefined {\n\tconst state = item ? item.state : entity.abilities.find((a) => a.id === ability.id)\n\treturn abilityRefusal(ability, {\n\t\tlevel: state?.level ?? 0,\n\t\tcooldown: state?.cooldown ?? 0,\n\t\tcharges: state && chargesLeft(ability, state),\n\t\tmana: entity.mana,\n\t\thp: entity.hp,\n\t\tmaxHp: entity.maxHp,\n\t\titem: !!item,\n\t\tspell: isSpell(entity, ability),\n\t\tsilenced: entity.buffs.length > 0 && isSilenced(world, entity, ability),\n\t\tnoManaCosts: world.cheats.noManaCosts\n\t})\n}\n\n/**\n * Pays for an ability and lets it happen. In order:\n * 1. the `beforeCast` hook, which can change the mana cost and the cooldown, or call it off;\n * 2. the caster pays, the cooldown starts, and one of its charges is spent where it has them;\n * 3. the effects of the ability happen;\n * 4. the `afterCast` hook, for what follows: the caster's passives that react to its casts.\n */\nexport function fire(world: World, caster: Entity, ability: AbilityDef, target: Entity | undefined, item?: ItemInstance): void {\n\tconst state = item?.state ?? caster.abilities.find((a) => a.id === ability.id)!\n\tconst { level } = state\n\tconst aimed = target?.pos ?? state.point ?? caster.pos\n\tconst point = { x: aimed.x, z: aimed.z }\n\t// haste is for what the caster learned, not for what it carries or brought along\n\tconst plain = !!item || isSpell(caster, ability)\n\tconst cooldown = world.cheats.noCooldowns ? 0 : plain ? at(ability.cooldown, level) : cooldownOf(world, caster, at(ability.cooldown, level))\n\tconst manaCost = item || world.cheats.noManaCosts ? 0 : at(ability.manaCost, level)\n\tconst before = world.hooks.run('beforeCast', { caster, ability, level, target, point, item, manaCost, cooldown, cancelled: false })\n\tif (before.cancelled) {\n\t\tif (before.reason) world.message(caster.owner, before.reason)\n\t\treturn\n\t}\n\tif (before.manaCost > caster.mana) {\n\t\tworld.message(caster.owner, engineMessage('notEnoughMana'))\n\t\treturn\n\t}\n\tif (!item) {\n\t\tcaster.mana -= before.manaCost\n\t\tcaster.hp -= at(ability.healthCost, level) * caster.maxHp\n\t\tif (before.manaCost > 0) world.events.emit(manaChanged, { entity: caster, amount: -before.manaCost, ability: ability.id })\n\t}\n\tstate.cooldown = before.cooldown\n\tspendUse(world, caster, ability, state, plain)\n\tconst charged = !item && isCharged(world, caster, ability)\n\tconst context = { world, caster, ability, level, target, point, charged }\n\tfor (const effect of ability.effects) world.registry.effect(effect.type)(context, effect)\n\tworld.events.emit(abilityCast, { caster, ability, level, target, point, charged: charged || undefined })\n\t// what spends a charge does not count to the next one\n\tif (charged) removeBuff(world, caster, ability.charge!)\n\tif (item) spendCharge(world, caster, item)\n\tworld.hooks.run('afterCast', { caster, ability, level, target, point, item, charged })\n}\n\n/**\n * Casts what goes off on the spot without the caster dropping what it is doing: a hero drinks a potion while it walks,\n * and leaps in the middle of a run. `point` is where it is aimed, for what goes off towards somewhere.\n * False when it cannot be cast this way, and takes an order\n */\nexport function castAside(world: World, caster: Entity, from: { ability?: string; item?: number }, point?: Vec2): boolean {\n\tconst used = source(world, caster, from)\n\tif (!used || used.state.level < 1) return false\n\tconst { ability, item } = used\n\tconst aimed = ability.target === 'direction' && !!point\n\t// what is kept up (a channel) is an order the caster stands in, not something done on the side\n\tif ((ability.target !== 'none' && !aimed) || ability.castTime || ability.channel || isStunned(world, caster) || caster.get(dashing)) return false\n\tconst problem = notReady(world, caster, ability, item)\n\tif (problem) {\n\t\tworld.message(caster.owner, problem)\n\t\treturn true\n\t}\n\tif (aimed && dist(caster.pos, point) > 0.05) caster.facing = atan2(point.x - caster.pos.x, point.z - caster.pos.z)\n\tused.state.point = aimed ? point : undefined\n\tworld.events.emit(castStarted, { caster, ability, point: aimed ? point : undefined, duration: 0 })\n\tfire(world, caster, ability, undefined, item)\n\treturn true\n}\n\n/**\n * What `cast` keeps in its order: the seconds of its wind-up left (from when it is in range), whether it walked to its\n * point already, whether it is past turning back (`isCommitted`), what it channels, and whether the ability carries the\n * caster off (a dash)\n *\n * @beta\n */\nexport interface CastState {\n\t/** Seconds of its wind-up left, from when it is in range */\n\twindup?: number\n\t/** It walked to its point already */\n\twalked?: boolean\n\t/** Past turning back (`isCommitted`) */\n\tlocked?: boolean\n\t/** What it channels, once it fired */\n\tchannel?: CastChannel\n\t/** The ability carries the caster off (a dash): the order is over when it lands */\n\trushing?: boolean\n}\n\n/** Use an ability: walk into range, turn towards the target, wind up, fire */\nexport const castOrder: OrderBehavior<CastState, OrderInits['cast']> = {\n\ttype: 'cast',\n\tcommitted: (order) => order.state.locked === true,\n\tchannelling: (order) => !!order.state.channel,\n\taccepts(world, entity, init) {\n\t\tconst used = source(world, entity, init)\n\t\tif (!used || used.state.level < 1) return false\n\t\tconst { ability } = used\n\t\tswitch (ability.target) {\n\t\t\tcase 'passive':\n\t\t\t\treturn false\n\t\t\tcase 'unit': {\n\t\t\t\tconst target = world.get(init.target)\n\t\t\t\treturn !!target && validTarget(world, entity, ability, target)\n\t\t\t}\n\t\t\tcase 'point':\n\t\t\tcase 'direction':\n\t\t\t\treturn !!init.point\n\t\t\tdefault:\n\t\t\t\treturn true\n\t\t}\n\t},\n\tupdate(world, entity, order, dt) {\n\t\t// it went off and carries the caster somewhere: the order is over when it gets there\n\t\tif (order.state.rushing) return entity.get(dashing) ? 'running' : 'done'\n\t\tif (order.state.channel) return channelling(world, entity, order.state.channel, dt)\n\t\tconst used = source(world, entity, order.init)\n\t\t// the item was used up, dropped or handed over in the meantime\n\t\tif (!used) return 'done'\n\t\tconst { ability, item } = used\n\t\tconst { state } = order\n\t\tconst target = ability.target === 'unit' ? world.get(order.init.target) : undefined\n\n\t\tif (ability.target === 'unit') {\n\t\t\tif (!target || !validTarget(world, entity, ability, target) || !canSee(world, entity, target)) return 'done'\n\t\t}\n\n\t\tif (state.windup === undefined) {\n\t\t\tconst problem = notReady(world, entity, ability, item)\n\t\t\tif (problem) {\n\t\t\t\tworld.message(entity.owner, problem)\n\t\t\t\treturn 'failed'\n\t\t\t}\n\n\t\t\tconst range = castRange(world, entity, ability, used.state.level)\n\t\t\tconst m = entity.get(moving)\n\t\t\tif (target && target !== entity && edgeDistance(entity, target) > range) {\n\t\t\t\tif (!m) return 'failed'\n\t\t\t\tmoveToEntity(world, entity, target, Math.max(range - 0.25, 0.1))\n\t\t\t\treturn 'running'\n\t\t\t}\n\t\t\tif (ability.target === 'point' && dist(entity.pos, order.init.point!) > range) {\n\t\t\t\tif (!m) return 'failed'\n\t\t\t\tif (m.status !== 'moving') {\n\t\t\t\t\tif (state.walked && m.status === 'failed') return 'failed'\n\t\t\t\t\tstate.walked = true\n\t\t\t\t\tmoveTo(world, entity, order.init.point!, { range: Math.max(range - 0.25, 0.1) })\n\t\t\t\t}\n\t\t\t\treturn 'running'\n\t\t\t}\n\n\t\t\tif (m) {\n\t\t\t\tif (m.status === 'moving') halt(world, entity)\n\t\t\t\tsetAnchored(world, entity, true)\n\t\t\t}\n\t\t\tstate.windup = castTimeOf(world, entity, ability, used.state.level)\n\t\t\t// from here on there is no turning back\n\t\t\tstate.locked = state.windup > 0\n\t\t\tworld.events.emit(castStarted, { caster: entity, ability, point: target?.pos ?? order.init.point, duration: state.windup })\n\t\t}\n\n\t\tconst aim = target?.pos ?? order.init.point\n\t\tif (aim && target !== entity) faceTowards(entity, aim, dt)\n\t\tstate.windup -= dt\n\t\tif (state.windup > 0) return 'running'\n\n\t\t// paid at the moment of casting: a lot can happen during the wind-up\n\t\tconst problem = notReady(world, entity, ability, item)\n\t\tif (problem) {\n\t\t\tworld.message(entity.owner, problem)\n\t\t\treturn 'failed'\n\t\t}\n\t\tused.state.point = order.init.point\n\t\tfire(world, entity, ability, target, item)\n\t\tif (ability.channel && !entity.get(dashing) && entity.alive) {\n\t\t\tconst { level } = used.state\n\t\t\tconst { duration } = ability.channel\n\t\t\tconst seconds = typeof duration === 'function' ? duration(world, entity, level) : duration\n\t\t\tconst point = target?.pos ?? order.init.point ?? entity.pos\n\t\t\tstate.locked = false\n\t\t\tstate.channel = { ability: ability.id, level, target: target?.id, point: { x: point.x, z: point.z }, left: seconds, elapsed: 0 }\n\t\t\tworld.events.emit(channelStarted, { caster: entity, ability, duration: seconds })\n\t\t\treturn 'running'\n\t\t}\n\t\tif (!entity.get(dashing)) return 'done'\n\t\tstate.rushing = true\n\t\tstate.locked = true\n\t\treturn 'running'\n\t},\n\tend(world, entity, order) {\n\t\tsetAnchored(world, entity, false)\n\t\tconst { channel } = order.state\n\t\t// called away, stunned, or dead before it was done\n\t\tif (channel && !channel.done && world.registry.abilities.has(channel.ability)) {\n\t\t\tchannel.done = true\n\t\t\tconst ability = world.registry.ability(channel.ability)\n\t\t\tability.channel?.interrupted?.(world, entity, channel.level)\n\t\t\tworld.events.emit(channelEnded, { caster: entity, ability, interrupted: true })\n\t\t}\n\t}\n}\n\n/** A channelled ability being kept up: plain data, in the order's state, so that a save has it */\n/**\n * An ability being channelled, kept in the cast order (`CastState.channel`)\n *\n * @beta\n */\nexport interface CastChannel {\n\t/** The ability, and its level */\n\tability: string\n\tlevel: number\n\t/** What it is aimed at, and where */\n\ttarget?: number\n\tpoint: Vec2\n\t/** Seconds still to go, and gone */\n\tleft: number\n\telapsed: number\n\t/** Over: kept up to its end, or broken off */\n\tdone?: boolean\n}\n\n/** A tick of keeping a channelled ability up: what it does every so often, and the end of it */\nfunction channelling(world: World, caster: Entity, channel: CastChannel, dt: number): 'running' | 'done' {\n\tif (!world.registry.abilities.has(channel.ability)) return 'done'\n\tconst ability = world.registry.ability(channel.ability)\n\tconst kept = ability.channel!\n\tconst target = world.get(channel.target)\n\t// how many times `every` went by in this tick, from the time before it: worked out back from after it, rounding\n\t// could lose one\n\tconst before = channel.elapsed\n\tchannel.elapsed += dt\n\tchannel.left -= dt\n\tconst every = kept.every ?? 0\n\tconst times = every > 0 ? Math.floor(channel.elapsed / every) - Math.floor(before / every) : 0\n\tfor (let n = 0; n < times && caster.alive; n++) {\n\t\tconst context = { world, caster, ability, level: channel.level, target, point: channel.point }\n\t\tfor (const effect of kept.effects ?? []) world.registry.effect(effect.type)(context, effect)\n\t\tkept.run?.(world, caster, channel.level, target, channel.point)\n\t}\n\tif (channel.left > 0) return 'running'\n\tchannel.done = true\n\t// kept up to the end: what it does then, and only then\n\tif (kept.finished?.length && caster.alive) {\n\t\tconst context = { world, caster, ability, level: channel.level, target, point: channel.point }\n\t\tfor (const effect of kept.finished) world.registry.effect(effect.type)(context, effect)\n\t}\n\tworld.events.emit(channelEnded, { caster, ability, interrupted: false })\n\treturn 'done'\n}\n\n/**\n * A caster was hurt: a channelled ability it keeps up that breaks on damage (`channel.breaksOnDamage`, a recall) is\n * broken off, as another order would\n */\nexport function hurtWhileChannelling(world: World, caster: Entity): void {\n\tconst order = caster.orders[0]\n\tconst channel = order?.type === 'cast' ? (order.state.channel as CastChannel | undefined) : undefined\n\tif (!channel || channel.done || !world.registry.abilities.has(channel.ability)) return\n\tif (world.registry.ability(channel.ability).channel?.breaksOnDamage) clearOrders(world, caster)\n}\n","import type { Terrain } from './terrain'\n\n/**\n * Min cell of a footprint centered as close as possible to the given point\n *\n * @beta\n */\nexport const footprintCell = (x: number, z: number, w: number, d: number) => ({ x: Math.round(x - w / 2), z: Math.round(z - d / 2) })\n\nexport interface GridOptions {\n\t/** Steepest slope (radians) that can be built on */\n\tmaxBuildSlope?: number\n}\n\n/**\n * Placement grid. One cell per world unit, tracking where structures stand and\n * where the ground is flat enough to build.\n *\n * @beta\n */\nexport class BuildGrid {\n\treadonly width: number\n\treadonly depth: number\n\t/** Id of the structure occupying each cell, 0 when free */\n\tprivate readonly occupant: Int32Array\n\tprivate readonly buildable: Uint8Array\n\n\t/** The steepest a cell is built on */\n\tprivate readonly maxBuildSlope: number\n\n\tconstructor(\n\t\tprivate readonly terrain: Terrain,\n\t\toptions: GridOptions = {}\n\t) {\n\t\tthis.maxBuildSlope = options.maxBuildSlope ?? 0.3\n\t\tthis.width = terrain.width\n\t\tthis.depth = terrain.depth\n\t\tthis.occupant = new Int32Array(this.width * this.depth)\n\t\tthis.buildable = new Uint8Array(this.width * this.depth)\n\t\tthis.groundChanged({ x: 0, z: 0, width: this.width, depth: this.depth })\n\t}\n\n\t/**\n\t * Works out again where can be built, in a rectangle of cells and the ring about it (a slope is of the vertices about a\n\t * cell): after the ground was reshaped there (`World.reshapeGround`). What stands there stays where it is\n\t */\n\tgroundChanged(rect: { x: number; z: number; width: number; depth: number }): void {\n\t\tconst { terrain } = this\n\t\tconst x0 = Math.max(rect.x - 1, 0)\n\t\tconst z0 = Math.max(rect.z - 1, 0)\n\t\tconst x1 = Math.min(rect.x + rect.width + 1, this.width)\n\t\tconst z1 = Math.min(rect.z + rect.depth + 1, this.depth)\n\t\tfor (let z = z0; z < z1; z++) {\n\t\t\tfor (let x = x0; x < x1; x++) {\n\t\t\t\tconst edge = x < 1 || z < 1 || x >= this.width - 1 || z >= this.depth - 1 || !terrain.inPlay(x, z) || terrain.blocked[z * this.width + x] > 0\n\t\t\t\tconst wet = terrain.water[z * this.width + x] !== 0\n\t\t\t\tthis.buildable[z * this.width + x] = !edge && !wet && terrain.slopeAt(x + 0.5, z + 0.5) <= this.maxBuildSlope ? 1 : 0\n\t\t\t}\n\t\t}\n\t}\n\n\tinBounds(x: number, z: number): boolean {\n\t\treturn x >= 0 && z >= 0 && x < this.width && z < this.depth\n\t}\n\n\toccupantAt(x: number, z: number): number {\n\t\treturn this.inBounds(x, z) ? this.occupant[z * this.width + x] : -1\n\t}\n\n\tisBuildable(x: number, z: number): boolean {\n\t\treturn this.inBounds(x, z) && this.buildable[z * this.width + x] === 1\n\t}\n\n\tisFree(x: number, z: number): boolean {\n\t\treturn this.isBuildable(x, z) && this.occupant[z * this.width + x] === 0\n\t}\n\n\t/** Min cell of a footprint centered as close as possible to the given point */\n\tcellFor(x: number, z: number, w: number, d: number): { x: number; z: number } {\n\t\treturn footprintCell(x, z, w, d)\n\t}\n\n\tcanPlace(cellX: number, cellZ: number, w: number, d: number): boolean {\n\t\tlet min = Infinity\n\t\tlet max = -Infinity\n\t\tfor (let z = cellZ; z < cellZ + d; z++) {\n\t\t\tfor (let x = cellX; x < cellX + w; x++) {\n\t\t\t\tif (!this.isFree(x, z)) return false\n\t\t\t}\n\t\t}\n\t\tfor (let z = cellZ; z <= cellZ + d; z++) {\n\t\t\tfor (let x = cellX; x <= cellX + w; x++) {\n\t\t\t\tconst h = this.terrain.vertexHeight(x, z)\n\t\t\t\tif (h < min) min = h\n\t\t\t\tif (h > max) max = h\n\t\t\t}\n\t\t}\n\t\treturn max - min <= 0.2 * Math.max(w, d) + 0.4\n\t}\n\n\toccupy(cellX: number, cellZ: number, w: number, d: number, id: number): void {\n\t\tfor (let z = cellZ; z < cellZ + d; z++) {\n\t\t\tfor (let x = cellX; x < cellX + w; x++) {\n\t\t\t\tif (this.inBounds(x, z)) this.occupant[z * this.width + x] = id\n\t\t\t}\n\t\t}\n\t}\n\n\trelease(cellX: number, cellZ: number, w: number, d: number, id: number): void {\n\t\tfor (let z = cellZ; z < cellZ + d; z++) {\n\t\t\tfor (let x = cellX; x < cellX + w; x++) {\n\t\t\t\tif (this.inBounds(x, z) && this.occupant[z * this.width + x] === id) this.occupant[z * this.width + x] = 0\n\t\t\t}\n\t\t}\n\t}\n}\n","import { chopped, resourcesDeposited } from '#engine/engineEvents'\nimport { defineComponent } from '#engine/components'\nimport type { ResourceKind } from '#engine/defs'\nimport { edgeDistance, type Entity, type EntityId, type HarvesterState, type Order, type ResourceState } from '#engine/entity'\nimport type { GatheringInfo } from '#engine/session/protocol'\nimport { closestPointOnRect, dist, distSq, type Vec2 } from '#engine/math'\nimport type { OrderBehavior, OrderInits, OrderStatus } from '#engine/registry'\nimport { faceTowards, halt, moveTo, moveToEntity, setAnchored, setGhost } from '#engine/systems/movement'\nimport { earn } from '#engine/player'\nimport type { World } from '#engine/world'\nimport { engineMessage, type MessageRef, toMessage } from '#engine/messages'\nimport { cos, hypot, sin } from '#engine/exactMath'\nimport { moving, deposit } from '../entity'\n\n/** Edge distance at which a worker can get to work on a resource or hand in what it carries */\nconst REACH = 0.7\nconst RESOURCE_SEARCH_RADIUS = 30\n/** How close to its spot a worker has to be to start on a tree */\nconst SPOT_RANGE = 0.45\n/** How near a tree's spot a worker whose walk is over has to be to work it: next to it, where someone stands on the spot */\nconst NEXT_TO_SPOT = 1.3\n/** How many trees out of reach an order remembers, not to go for them again */\nconst OUT_OF_REACH_KEPT = 8\n/** Places to wait at a full mine, side by side: workers past that many share them */\nconst WAITING_PLACES = 5\n/** How close to its place a worker waits: on it, nearly, or it would stand in the next one's */\nconst WAIT_RANGE = 0.15\n/** Seconds between two blows of the axe */\nconst CHOP_INTERVAL = 1\n\n/**\n * The step a worker is at: walking to its resource, gathering, bringing the load home\n *\n * @internal\n */\nexport type HarvestPhase = 'toResource' | 'gathering' | 'toDropOff'\n\n/**\n * What a worker carries and where it gathers (`UnitTypeDef.harvester`): set as it is spawned (and as its type changes),\n * for a type that gathers. Its owner and their allies are told what it carries (`GatheringInfo`)\n *\n * @beta\n */\nexport const gathering = defineComponent<HarvesterState, GatheringInfo>('core.harvester', {\n\t// a worker's load, nothing carried yet\n\tonSpawn: (entity) => {\n\t\tif (entity.def.kind === 'unit' && entity.def.harvester) entity.set(gathering, { carrying: 0, kind: null, resource: 0 })\n\t},\n\treplicate: 'allies',\n\tsnapshot: (state) => ({ carrying: state.carrying, kind: state.kind }),\n\tsame: (a, b) => a.carrying === b.carrying && a.kind === b.kind\n})\n\n/**\n * What a worker carries and where it gathers: none for a type that does not gather (`gathering`)\n *\n * @beta\n */\nexport const harvesterOf = (entity: Entity): HarvesterState | undefined => entity.get(gathering)\n\n/** Whether a building takes in a resource. Any drop-off will do for a worker that has not gathered anything yet */\nconst accepts = (building: Entity, kind: ResourceKind | null | undefined) => {\n\tconst { dropOff } = building.def\n\tif (!kind) return !!dropOff\n\treturn dropOff === true || (Array.isArray(dropOff) && dropOff.includes(kind))\n}\n\n/** Closest building of the player that takes the resource */\nexport function findDropOff(world: World, entity: Entity, kind: ResourceKind | null | undefined = harvesterOf(entity)?.kind): Entity | undefined {\n\tlet best: Entity | undefined\n\tlet bestDistance = Infinity\n\tfor (const other of world.index.ownedBy(entity.owner)) {\n\t\tif (!other.operational || !accepts(other, kind)) continue\n\t\tconst d = distSq(entity.pos, other.pos)\n\t\tif (d < bestDistance) {\n\t\t\tbestDistance = d\n\t\t\tbest = other\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * Whether a worker may gather from a resource: one of a kind it gathers (`harvester.kinds`), and then as the game's\n * `canHarvest` hook says\n *\n * @beta\n */\nexport function canHarvest(world: World, worker: Entity, source: Entity): boolean {\n\treturn harvestRefusal(world, worker, source) === null\n}\n\n/** Why a worker may not gather from a resource (`canHarvest`): null where it may, and undefined where nothing is said */\nfunction harvestRefusal(world: World, worker: Entity, source: Entity): MessageRef | undefined | null {\n\tconst kind = source.def.resource?.kind\n\tconst kinds = worker.def.harvester?.kinds\n\tif (!kind || !worker.def.harvester) return undefined\n\t// a resource someone has built on is theirs alone (`UnitTypeDef.builtOn`)\n\tconst above = world.get(source.get(deposit)?.under)\n\tconst allowed = (!kinds || kinds.includes(kind)) && (!above?.alive || above.owner === worker.owner)\n\tif (!world.hooks.has('canHarvest')) return allowed ? null : engineMessage('cannotGather', { resource: kind })\n\tconst decided = world.hooks.run('canHarvest', {\n\t\tworker,\n\t\tsource,\n\t\tallowed,\n\t\t...(!allowed && { reason: engineMessage('cannotGather', { resource: kind }) })\n\t})\n\treturn decided.allowed ? null : decided.reason\n}\n/** Whether another worker fits. Resources that are worked on from outside, like trees, are claimed by whoever is on their way */\nconst hasRoom = (source: Entity) => source.get(deposit)!.occupants < Math.max(source.def.resource!.slots, 1)\n\n/** Whether a worker can get next to it. Trees inside a forest have to wait for the ones around them to fall */\nfunction reachable(world: World, source: Entity): boolean {\n\tconst cell = source.cell\n\tconst fp = source.def.footprint\n\tif (!cell || !fp) return true\n\tfor (let i = 0; i < fp.w; i++)\n\t\tif (world.grid.occupantAt(cell.x + i, cell.z - 1) === 0 || world.grid.occupantAt(cell.x + i, cell.z + fp.d) === 0) return true\n\tfor (let j = 0; j < fp.d; j++)\n\t\tif (world.grid.occupantAt(cell.x - 1, cell.z + j) === 0 || world.grid.occupantAt(cell.x + fp.w, cell.z + j) === 0) return true\n\treturn false\n}\n\n/** Where to stand to work on a source from outside: in front of its free side that is closest to the worker */\nfunction workSpot(world: World, entity: Entity, source: Entity): Vec2 {\n\tconst { cell, pos } = source\n\tconst fp = source.def.footprint\n\tconst reach = entity.def.radius + 0.2\n\tlet best: Vec2 | undefined\n\tlet bestDistance = Infinity\n\tif (cell && fp) {\n\t\tconst sides = [\n\t\t\t{ x: -1, z: 0, free: world.grid.occupantAt(cell.x - 1, cell.z) === 0 },\n\t\t\t{ x: 1, z: 0, free: world.grid.occupantAt(cell.x + fp.w, cell.z) === 0 },\n\t\t\t{ x: 0, z: -1, free: world.grid.occupantAt(cell.x, cell.z - 1) === 0 },\n\t\t\t{ x: 0, z: 1, free: world.grid.occupantAt(cell.x, cell.z + fp.d) === 0 }\n\t\t]\n\t\tfor (const side of sides) {\n\t\t\tif (!side.free) continue\n\t\t\tconst spot = { x: pos.x + side.x * (fp.w / 2 + reach), z: pos.z + side.z * (fp.d / 2 + reach) }\n\t\t\tconst distance = distSq(entity.pos, spot)\n\t\t\tif (distance < bestDistance) {\n\t\t\t\tbestDistance = distance\n\t\t\t\tbest = spot\n\t\t\t}\n\t\t}\n\t}\n\tbest ??= closestPointOnRect(entity.pos, source.rect, reach)\n\treturn world.nav.closestPoint(best, 3) ?? best\n}\n\n/** How far `findResource` looks at first. Most of the time the next tree is right there */\nconst RESOURCE_SEARCH_STEPS = [6, 12]\nconst nearby: Entity[] = []\n\n/**\n * Closest resource with something left within `radius` of the point, of a kind when one is named.\n * `free` only takes what another worker can still get at. Among equally close ones, the oldest.\n */\nexport function findResource(\n\tworld: World,\n\tnear: Vec2,\n\tradius: number,\n\tkind?: ResourceKind,\n\tfree = false,\n\tworker?: Entity,\n\tskip?: readonly EntityId[]\n): Entity | undefined {\n\t// look close by first and further only when there is nothing: everything within the distance looked at comes back,\n\t// so whatever is found within it is the closest there is\n\tfor (const step of RESOURCE_SEARCH_STEPS) {\n\t\tif (step >= radius) break\n\t\tconst found = closestResource(world, near, step, kind, free, worker, skip)\n\t\tif (found) return found\n\t}\n\treturn closestResource(world, near, radius, kind, free, worker, skip)\n}\n\nfunction closestResource(\n\tworld: World,\n\tnear: Vec2,\n\tradius: number,\n\tkind: ResourceKind | undefined,\n\tfree: boolean,\n\tworker?: Entity,\n\tskip?: readonly EntityId[]\n): Entity | undefined {\n\tlet best: Entity | undefined\n\tlet bestDistance = radius * radius\n\tfor (const other of world.spatial.query(near.x, near.z, radius, nearby)) {\n\t\tif (!other.alive || !other.get(deposit) || other.get(deposit)!.amount <= 0) continue\n\t\tif (kind && other.def.resource!.kind !== kind) continue\n\t\tif (skip?.includes(other.id)) continue\n\t\tif (free && !other.def.resource!.entered && (!hasRoom(other) || !reachable(world, other))) continue\n\t\tconst d = distSq(near, other.pos)\n\t\tif (d > bestDistance || (d === bestDistance && best && other.id > best.id)) continue\n\t\t// what this worker may gather from, asked last: it can be a game's hook\n\t\tif (worker && !canHarvest(world, worker, other)) continue\n\t\tif (d < bestDistance || (d === bestDistance && best && other.id < best.id)) {\n\t\t\tbestDistance = d\n\t\t\tbest = other\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * What a worker hands in at where it gathers: the building of its owner's that stands on the resource and takes it\n * (`UnitTypeDef.builtOn`, a cursed mine), finished. None for a resource gathered the ordinary way\n */\nfunction gatheringAt(world: World, worker: Entity, source: Entity): Entity | undefined {\n\tconst above = world.get(source.get(deposit)?.under)\n\tif (!above?.alive || !above.operational || above.owner !== worker.owner) return undefined\n\treturn accepts(above, source.def.resource!.kind) ? above : undefined\n}\n\n/** Where the `slot`th of `of` workers gathering at a building stands: round its edge, spread out evenly */\nfunction spotAround(world: World, worker: Entity, building: Entity, slot: number, of: number): Vec2 {\n\tconst angle = (slot / Math.max(of, 1)) * Math.PI * 2\n\tconst far = { x: building.pos.x + sin(angle) * 50, z: building.pos.z + cos(angle) * 50 }\n\tconst spot = closestPointOnRect(far, building.rect, worker.def.radius + 0.2)\n\treturn world.nav.closestPoint(spot, 3) ?? spot\n}\n\n/** Hands in what a worker carries: cut by upkeep for what has it, then as the game's `beforeDeposit` says */\nfunction dropOff(world: World, entity: Entity): void {\n\tconst harvester = harvesterOf(entity)!\n\t// what it carries came from somewhere, so it knows what it is\n\tconst kind = harvester.kind!\n\t// upkeep is taken at the door, from the resources that have it\n\tconst income = world.registry.resource(kind)?.upkeep ? world.rules.economy.upkeep(world, entity.owner).income : 1\n\tlet amount = Math.round(harvester.carrying * income)\n\tconst upkeep = income < 1 ? Math.round(harvester.carrying) - amount : 0\n\t// what the game makes of it: more from a mine near the keep, nothing in a famine\n\tif (world.hooks.has('beforeDeposit')) {\n\t\tconst before = world.hooks.run('beforeDeposit', { worker: entity, player: entity.owner, kind, amount, cancelled: false })\n\t\tamount = before.cancelled ? 0 : before.amount\n\t}\n\tearn(world.player(entity.owner).resources, kind, amount)\n\tworld.events.emit(resourcesDeposited, { entity, player: entity.owner, kind, amount, ...(upkeep > 0 && { upkeep }) })\n\tharvester.carrying = 0\n}\n\n/**\n * What harvesting keeps through every step of it, and from one load to the next: the kind it gathers and where it last\n * did, the resource it holds a place at (`claimed`, a tree, a place round a building on a resource), the building it\n * gathers at (`inPlace`), the place it walks to and the one it waits at, whether it walked to its place already, the\n * seconds to its next swing (`chop`: the rhythm goes on from one load to the next), the hall it brings its loads to\n *\n * @beta\n */\nexport interface HarvestKept {\n\tkind?: ResourceKind\n\tat?: Vec2\n\tclaimed?: EntityId\n\tinPlace?: EntityId\n\tspot?: Vec2\n\twaitSpot?: Vec2\n\twalked?: boolean\n\t/** The trees it walked to and could not get next to, the last few: not gone for again by this order */\n\toutOfReach?: EntityId[]\n\tchop?: number\n\tdropOff?: EntityId\n}\n\n/**\n * Walking to its resource, and to its place at it (`HarvestState`)\n *\n * @beta\n */\nexport interface HarvestToResource extends HarvestKept {\n\tphase: 'toResource'\n}\n\n/**\n * At work (`HarvestState`): the seconds of it left, and what it works (`working`) or is inside of (a mine's, `inside`)\n *\n * @beta\n */\nexport interface HarvestGathering extends HarvestKept {\n\tphase: 'gathering'\n\ttimer: number\n\tworking?: EntityId\n\tinside?: EntityId\n}\n\n/**\n * Bringing the load home (`HarvestState`): whether it is its last, the resource used up\n *\n * @beta\n */\nexport interface HarvestToDropOff extends HarvestKept {\n\tphase: 'toDropOff'\n\tlast?: boolean\n}\n\n/**\n * What `harvest` and `return` keep in their orders: the step it is at, with what that step keeps beside what every\n * step does (`HarvestKept`). A step's own fields stay in the order as it goes on to the next (a save has them as they\n * were), and are read only in their step\n *\n * @beta\n */\nexport type HarvestState = HarvestToResource | HarvestGathering | HarvestToDropOff\n\n/** The fields a step has of its own, beside its phase and what every step keeps */\ntype OwnOf<P extends HarvestPhase> = Omit<Extract<HarvestState, { phase: P }>, 'phase' | keyof HarvestKept>\n\n/** On to the next step, with what it starts with: in the order, where its fields were */\nfunction goOn<P extends HarvestPhase>(state: HarvestState, phase: P, own: OwnOf<P>): void {\n\tObject.assign(state, own)\n\tstate.phase = phase\n}\n\n/** Gives up the tree the worker had for itself */\nfunction release(world: World, state: HarvestKept): void {\n\tconst claimed = world.entities.get(state.claimed ?? 0)\n\tstate.claimed = 0\n\tconst resource = claimed?.get(deposit)\n\tif (resource) resource.occupants = Math.max(resource.occupants - 1, 0)\n}\n\n/**\n * Where a worker waits for a mine with no room: next to its edge on the side of the town hall, a place each (by the\n * worker's id: the one in front of the hall, then one side, then the other), so that waiting workers stand side by side\n */\nfunction waitingSpot(world: World, entity: Entity, mine: Entity): Vec2 {\n\tconst margin = entity.def.radius + 0.2\n\tconst towards = findDropOff(world, entity)?.pos ?? entity.pos\n\tconst front = closestPointOnRect(towards, mine.rect, margin)\n\tconst slot = entity.id % WAITING_PLACES\n\tconst along = (slot % 2 ? 1 : -1) * Math.ceil(slot / 2) * (entity.def.radius * 2 + 0.15)\n\tconst outX = front.x - mine.pos.x\n\tconst outZ = front.z - mine.pos.z\n\tconst length = hypot(outX, outZ) || 1\n\t// along the edge, and back onto it where that goes round a corner\n\treturn closestPointOnRect({ x: front.x - (outZ / length) * along, z: front.z + (outX / length) * along }, mine.rect, margin)\n}\n\n/** Into a mine: out of sight, a place in it taken */\nfunction enter(world: World, entity: Entity, state: HarvestToResource, resource: ResourceState): void {\n\tstate.waitSpot = undefined\n\tresource.occupants++\n\tworld.setHidden(entity, true)\n}\n\nfunction leave(world: World, entity: Entity, state: HarvestGathering): void {\n\tconst mine = world.entities.get(state.inside ?? 0)\n\tstate.inside = 0\n\tconst resource = mine?.get(deposit)\n\tif (resource) resource.occupants = Math.max(resource.occupants - 1, 0)\n\n\t// come out on the side facing the town hall\n\tconst towards = findDropOff(world, entity)?.pos ?? entity.pos\n\tconst exit = mine ? closestPointOnRect(towards, mine.rect, entity.def.radius + 0.2) : entity.pos\n\tworld.setHidden(entity, false, exit)\n}\n\n/** Stops where it stands, if it was on its way */\nfunction stop(world: World, entity: Entity): void {\n\tif (entity.get(moving)!.status === 'moving') halt(world, entity)\n}\n\n/** Walks to a spot to wait at, and waits there: what a worker does for a place that has no room */\nfunction wait(world: World, entity: Entity, spot: Vec2): void {\n\tif (dist(entity.pos, spot) > WAIT_RANGE) {\n\t\tif (entity.get(moving)!.status !== 'moving') moveTo(world, entity, spot, { range: WAIT_RANGE * 0.5 })\n\t} else stop(world, entity)\n}\n\n/**\n * To the spot in front of a tree and nowhere else, or workers on neighbouring trees end up in each other: still on its\n * way (`true`), or there, or next to it where someone stands on it (`false`)\n */\nfunction walkingToSpot(world: World, entity: Entity, state: HarvestKept, spot: Vec2): boolean {\n\tconst away = dist(entity.pos, spot)\n\tif (away <= SPOT_RANGE) return false\n\tif (entity.get(moving)!.status === 'moving') return true\n\t// someone is standing there: next to it will do\n\tif (state.walked && away < NEXT_TO_SPOT) return false\n\tstate.walked = true\n\tmoveTo(world, entity, spot, { range: SPOT_RANGE * 0.6 })\n\treturn true\n}\n\n/** At work from here on: in the way like anyone else (it is on the road that workers pass through each other) */\nfunction setToWork(world: World, entity: Entity): void {\n\tstop(world, entity)\n\tsetGhost(world, entity, false)\n\tsetAnchored(world, entity, true)\n}\n\n/**\n * A worker at a resource its owner's building stands on (`UnitTypeDef.builtOn`): a place round the building, as many\n * as it has room for (`gatherers`), waited for in line beside it when they are all taken; then to work\n */\nfunction gatherInPlace(world: World, entity: Entity, state: HarvestToResource, source: Entity, resource: ResourceState, at: Entity): OrderStatus {\n\tconst most = at.def.gatherers ?? 5\n\tif (state.claimed !== source.id) {\n\t\trelease(world, state)\n\t\tif (resource.occupants >= most) {\n\t\t\twait(world, entity, (state.waitSpot ??= waitingSpot(world, entity, at)))\n\t\t\treturn 'running'\n\t\t}\n\t\tstate.waitSpot = undefined\n\t\tstate.spot = spotAround(world, entity, at, resource.occupants, most)\n\t\tresource.occupants++\n\t\tstate.claimed = source.id\n\t\tstate.walked = false\n\t}\n\tstate.inPlace = at.id\n\tif (walkingToSpot(world, entity, state, state.spot!)) return 'running'\n\tsetToWork(world, entity)\n\tfaceTowards(entity, at.pos, 1)\n\tconst working = source.id\n\tharvesterOf(entity)!.resource = source.id\n\tgoOn(state, 'gathering', { working, timer: source.def.resource!.gatherTime ?? entity.def.harvester!.gatherTime })\n\treturn 'running'\n}\n\n/** Walking to the resource and to its place at it, then to work; on to the next of its kind where it is used up */\nfunction toResource(world: World, entity: Entity, order: Order<HarvestState>, state: HarvestToResource, harvester: HarvesterState): OrderStatus {\n\tconst source = world.get(order.init.target)\n\tconst resource = source?.get(deposit)\n\tif (!source || !resource || resource.amount <= 0) {\n\t\trelease(world, state)\n\t\t// used up: on to the next one of the same kind\n\t\tconst kind = state.kind ?? source?.def.resource?.kind\n\t\tconst near = state.at ?? source?.pos ?? entity.pos\n\t\tconst next =\n\t\t\tfindResource(world, near, RESOURCE_SEARCH_RADIUS, kind, true, entity) ?? findResource(world, near, RESOURCE_SEARCH_RADIUS, kind, false, entity)\n\t\tif (next) {\n\t\t\torder.init.target = next.id\n\t\t\treturn 'running'\n\t\t}\n\t\tif (harvester.carrying > 0) {\n\t\t\tgoOn(state, 'toDropOff', { last: true })\n\t\t\treturn 'running'\n\t\t}\n\t\treturn 'done'\n\t}\n\tconst def = source.def.resource!\n\tconst gatherTime = def.gatherTime ?? entity.def.harvester!.gatherTime\n\tstate.kind = def.kind\n\tstate.at = { x: source.pos.x, z: source.pos.z }\n\t// gathered where its owner's building stands on it: from round it, handed in on the spot\n\tconst at = gatheringAt(world, entity, source)\n\tif (at) return gatherInPlace(world, entity, state, source, resource, at)\n\tstate.inPlace = 0\n\t// a place round a building that has gone is given up\n\tif (def.entered && state.claimed) release(world, state)\n\tif (!def.entered) {\n\t\tif (state.claimed !== source.id) {\n\t\t\t// a tree each: whoever finds theirs taken goes for the next one\n\t\t\trelease(world, state)\n\t\t\tif (!hasRoom(source)) {\n\t\t\t\tconst next = findResource(world, source.pos, RESOURCE_SEARCH_RADIUS, def.kind, true, entity)\n\t\t\t\tif (next) {\n\t\t\t\t\torder.init.target = next.id\n\t\t\t\t\treturn 'running'\n\t\t\t\t}\n\t\t\t}\n\t\t\tresource.occupants++\n\t\t\tstate.claimed = source.id\n\t\t\tstate.spot = workSpot(world, entity, source)\n\t\t\tstate.walked = false\n\t\t}\n\t\t// the walk over, the tree not reached, and nobody else at it to wait behind: it cannot be got to from here (behind\n\t\t// a cliff, deep in the wood). The nearest other one to where it stands, those it gave up on left out; nothing of\n\t\t// the kind within reach, it stops\n\t\tconst walk = entity.get(moving)!\n\t\tif (\n\t\t\tstate.walked &&\n\t\t\tresource.occupants <= 1 &&\n\t\t\twalk.status !== 'moving' &&\n\t\t\twalk.goalEntity === 0 &&\n\t\t\tdist(walk.goal, state.spot!) < 0.01 &&\n\t\t\tdist(entity.pos, state.spot!) >= NEXT_TO_SPOT\n\t\t) {\n\t\t\trelease(world, state)\n\t\t\tconst skipped = (state.outOfReach ??= [])\n\t\t\tskipped.push(source.id)\n\t\t\tif (skipped.length > OUT_OF_REACH_KEPT) skipped.shift()\n\t\t\tconst next = findResource(world, entity.pos, RESOURCE_SEARCH_RADIUS, def.kind, true, entity, skipped)\n\t\t\tif (next) {\n\t\t\t\torder.init.target = next.id\n\t\t\t\treturn 'running'\n\t\t\t}\n\t\t\tif (harvester.carrying > 0) {\n\t\t\t\tgoOn(state, 'toDropOff', { last: true })\n\t\t\t\treturn 'running'\n\t\t\t}\n\t\t\treturn 'done'\n\t\t}\n\t\tif (walkingToSpot(world, entity, state, state.spot!)) return 'running'\n\t\t// trees and the like are worked on from next to them\n\t\tsetToWork(world, entity)\n\t\tconst working = source.id\n\t\tharvester.resource = source.id\n\t\tgoOn(state, 'gathering', { working, timer: gatherTime })\n\t\treturn 'running'\n\t}\n\tif (edgeDistance(entity, source) > REACH) {\n\t\tmoveToEntity(world, entity, source, REACH - 0.2)\n\t\treturn 'running'\n\t}\n\tif (resource.occupants >= def.slots) {\n\t\t// busy, wait in line: beside the others, not on top of them. Workers pass through each other on the road,\n\t\t// so nothing would push them apart, and the screen would draw them all in one place\n\t\twait(world, entity, (state.waitSpot ??= waitingSpot(world, entity, source)))\n\t\treturn 'running'\n\t}\n\tenter(world, entity, state, resource)\n\tharvester.resource = source.id\n\tgoOn(state, 'gathering', { inside: source.id, timer: gatherTime })\n\treturn 'running'\n}\n\n/** At work: a swing now and then, a load once the time is up; then home with it, or back for more */\nfunction gather(world: World, entity: Entity, state: HarvestGathering, harvester: HarvesterState, dt: number): OrderStatus {\n\tconst source = world.get(state.inside || state.working)\n\tif (source && !state.inside && !state.inPlace) {\n\t\tfaceTowards(entity, source.pos, dt)\n\t\t// every blow can be seen and heard\n\t\tstate.chop = (state.chop ?? CHOP_INTERVAL * 0.5) - dt\n\t\tif (state.chop <= 0) {\n\t\t\tstate.chop += CHOP_INTERVAL\n\t\t\tworld.events.emit(chopped, { worker: entity, source })\n\t\t}\n\t}\n\tstate.timer -= dt\n\tconst resource = source?.get(deposit)\n\tif (resource && state.timer > 0) return 'running'\n\tif (source && resource) {\n\t\tconst kind = source.def.resource!.kind\n\t\t// a load of one thing: what was carried of the other is dropped\n\t\tif (harvester.kind !== kind) harvester.carrying = 0\n\t\tconst amount = Math.min(entity.def.harvester!.capacity - harvester.carrying, resource.amount)\n\t\tresource.amount -= amount\n\t\tharvester.carrying += amount\n\t\tharvester.kind = kind\n\t}\n\t// at a building on the resource: handed in where it stands, and on to the next load\n\tconst at = state.inPlace && source ? gatheringAt(world, entity, source) : undefined\n\tif (at && harvester.carrying > 0) dropOff(world, entity)\n\tif (state.inside) leave(world, entity, state)\n\telse if (!at) {\n\t\tsetAnchored(world, entity, false)\n\t\tsetGhost(world, entity, true)\n\t}\n\tstate.working = 0\n\tif (source && resource && resource.amount <= 0) world.kill(source, undefined, false, 'depleted')\n\tif (harvester.carrying > 0) goOn(state, 'toDropOff', {})\n\telse goOn(state, 'toResource', {})\n\treturn 'running'\n}\n\n/** Home with the load, to the nearest hall that takes it; then back for more, or done where it was the last */\nfunction toDropOff(world: World, entity: Entity, state: HarvestToDropOff, harvester: HarvesterState): OrderStatus {\n\tlet hall = world.get(state.dropOff)\n\tif (!hall?.operational || !accepts(hall, harvester.kind)) {\n\t\thall = findDropOff(world, entity)\n\t\tstate.dropOff = hall?.id ?? 0\n\t}\n\tif (!hall) {\n\t\tworld.message(entity.owner, engineMessage('nowhereToReturn', { resource: harvester.kind ?? '' }))\n\t\treturn 'failed'\n\t}\n\tif (edgeDistance(entity, hall) > REACH) {\n\t\tmoveToEntity(world, entity, hall, REACH - 0.2)\n\t\treturn 'running'\n\t}\n\tdropOff(world, entity)\n\t// the closest place to hand in may be another one next time\n\tstate.dropOff = 0\n\tif (state.last) return 'done'\n\tgoOn(state, 'toResource', {})\n\treturn 'running'\n}\n\nfunction update(world: World, entity: Entity, order: Order<HarvestState>, dt: number): OrderStatus {\n\tconst { state } = order\n\tconst harvester = harvesterOf(entity)!\n\tswitch (state.phase) {\n\t\tcase 'toResource':\n\t\t\treturn toResource(world, entity, order, state, harvester)\n\t\tcase 'gathering':\n\t\t\treturn gather(world, entity, state, harvester, dt)\n\t\tcase 'toDropOff':\n\t\t\treturn toDropOff(world, entity, state, harvester)\n\t}\n}\n\nfunction end(world: World, entity: Entity, order: Order<HarvestState>): void {\n\tconst { state } = order\n\trelease(world, state)\n\t// inside a mine only while at work there\n\tif (state.phase === 'gathering' && state.inside) leave(world, entity, state)\n\tsetAnchored(world, entity, false)\n\tsetGhost(world, entity, false)\n}\n\n/** Gather from a resource, bring it home, repeat */\nexport const harvestOrder: OrderBehavior<HarvestState, OrderInits['harvest']> = {\n\ttype: 'harvest',\n\taccepts(world, entity, init) {\n\t\tconst source = world.get(init.target)\n\t\tif (!entity.has(gathering) || !source?.get(deposit)) return false\n\t\tconst refusal = harvestRefusal(world, entity, source)\n\t\tif (refusal === null) return true\n\t\t// told why, where the game says\n\t\tif (refusal) world.message(entity.owner, toMessage(refusal))\n\t\treturn false\n\t},\n\tstart(world, entity, order) {\n\t\tconst harvester = harvesterOf(entity)\n\t\tconst kind = world.get(order.init.target)?.def.resource?.kind\n\t\t// full hands are emptied first. A full load of something else is handed in rather than thrown away\n\t\tconst full = harvester!.carrying >= entity.def.harvester!.capacity\n\t\torder.state.phase = full ? 'toDropOff' : 'toResource'\n\t\torder.state.kind = kind\n\t\tsetGhost(world, entity, true)\n\t},\n\tupdate,\n\tend\n}\n\n/** Hand in what the worker carries, then go back to gathering */\nexport const returnOrder: OrderBehavior<HarvestState, OrderInits['return']> = {\n\ttype: 'return',\n\taccepts: (_world, entity) => (harvesterOf(entity)?.carrying ?? 0) > 0,\n\tstart(world, entity, order) {\n\t\torder.init.target ??= harvesterOf(entity)!.resource\n\t\torder.state.phase = 'toDropOff'\n\t\tsetGhost(world, entity, true)\n\t},\n\tupdate,\n\tend\n}\n","/** The id of a set closest to one that is not in it, when one is close enough to have been meant: what a check says was meant */\nexport function nearestId(id: string, known: Iterable<string>): string | undefined {\n\tlet best: string | undefined\n\tlet least = Math.max(2, Math.floor(id.length / 3)) + 1\n\tfor (const other of known) {\n\t\tconst distance = editDistance(id.toLowerCase(), other.toLowerCase())\n\t\tif (distance < least) {\n\t\t\tleast = distance\n\t\t\tbest = other\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * How many letters have to be changed, added or taken away to make one word of another: what says which id was meant\n *\n * @beta\n */\nexport function editDistance(a: string, b: string): number {\n\tlet row = Array.from({ length: b.length + 1 }, (_, i) => i)\n\tfor (let i = 1; i <= a.length; i++) {\n\t\tconst next = [i]\n\t\tfor (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))\n\t\trow = next\n\t}\n\treturn row[b.length]\n}\n","import type { ResourceKind, UnitTypeDef, UpgradeDef } from './defs'\nimport { Entity, type PlayerId } from './entity'\nimport type { GameModule } from './game'\nimport type { HookDef } from './hooks'\nimport type { Player } from './player'\nimport type { Registry } from './registry'\nimport { nearestId } from './nearest'\nimport { availableTo } from './shared'\nimport { type StartDef, startIds } from './start'\nimport type { World } from './world'\n\n/**\n * A side a player can play, with a roster of its own: melee's humans and undead. Optional: a game that lists none\n * (`GameModule.races`) has no race anywhere, no choice of one in the lobby and nothing kept from anyone. A unit type or\n * an upgrade of a race (`UnitTypeDef.race`, `UpgradeDef.race`) is only its players' to make; one of none, everyone's.\n * Each player has one (`raceOf`): chosen in the lobby (a seat setting the server offers by itself, `seatSettingsOf`),\n * given to the world as it is made (`PlayerInit.race`, `MapWorldOptions.races`), or changed by the rules (`setRace`)\n *\n * @beta\n */\nexport interface RaceDef {\n\tid: string\n\t/** What players are shown: in the lobby, on the scores */\n\tname: string\n\t/**\n\t * The definition this one is a copy of, made from the data (`copyOf` in a `data.json`, the editor's Copy as new):\n\t * what it is drawn, heard and pictured as where the game gives it no look of its own\n\t */\n\tbasedOn?: string\n\t/** What it is like, for a tooltip */\n\tdescription?: string\n\t/** Its picture, by the id the game's view knows icons by */\n\ticon?: string\n\t/**\n\t * What its players start with of each resource, by resource id, over what the game starts everyone with\n\t * (`ResourceDef.start`). Not for a player given resources of their own (`PlayerInit.resources`, a map's)\n\t */\n\tresources?: Partial<Record<ResourceKind, number>>\n\t/**\n\t * What its players get at the start of a game on a map, in place of the game's (`GameModule.start`): its own hall and\n\t * workers, as data (`StartData`: what a race made in the Data panel has, `start.hall` and the rest editable there)\n\t * or as code (`StartCode`)\n\t */\n\tstart?: StartDef\n\t/**\n\t * Run for each of its players once a world is made from a map, after everything the map puts down and the starts:\n\t * what its players begin with that is not a unit (a ground of its own around its halls, a state)\n\t */\n\tonStart?(world: World, player: PlayerId): void\n\t/**\n\t * Hook handlers of its own, run only for what is of its players (`RaceHookDef`): how it gathers, where it may build.\n\t * With these a race plays differently with no test of the race in the game's code\n\t */\n\thooks?: RaceHookDef[]\n\t/**\n\t * What a race made as a copy of another (`basedOn`: `copyOf` in a `data.json`, the editor's Copy as new) keeps of the\n\t * original's code: its `hooks` and its `onStart`, each kept unless said `false` here. A copy keeps both when this is\n\t * left out, so a race copied from the undead gathers at a cursed mine and builds on blight as they do; one that\n\t * says `hooks: false` plays by the game's rules alone. Its `start` is data, the copy's own to change; a `start` in\n\t * code is kept whole. Two toggles in the Data panel, on a copy\n\t */\n\tinherits?: { hooks?: boolean; onStart?: boolean }\n}\n\n/**\n * A hook handler of a race (`RaceDef.hooks`): run only where the event is of one of the race's players. Whose an event\n * is, is `of(event)` where it is given, or else its `player`, or else the owner of the first there is of its `entity`,\n * `caster`, `attacker`, `worker`, `buyer`, `hero`, `producer`, `source`, `target`: the one doing it before the one it\n * is done to (a damage is its source's)\n *\n * @beta\n */\nexport type RaceHookDef = HookDef & {\n\t/** The player an event is of, where it is not the one found by default */\n\tof?: (event: any) => PlayerId | undefined\n}\n\n/** Fields of a hook's event that are an entity, in the order whose an event is looked for */\nconst ACTORS = ['entity', 'caster', 'attacker', 'worker', 'buyer', 'hero', 'producer', 'source', 'target'] as const\n\n/** The player a hook's event is of (see `RaceHookDef`): undefined for one of nobody's */\nexport function playerOfEvent(event: unknown): PlayerId | undefined {\n\tif (typeof event !== 'object' || event === null) return undefined\n\tconst fields = event as Record<string, unknown>\n\tif (typeof fields.player === 'number') return fields.player\n\tfor (const key of ACTORS) {\n\t\tconst actor = fields[key]\n\t\tif (actor instanceof Entity) return actor.owner\n\t}\n\treturn undefined\n}\n\n/** Each race's hook handlers, each to run only for what is of the race's players */\nexport function raceHooks(game: GameModule): HookDef[] {\n\tconst hooks: HookDef[] = []\n\tfor (const race of game.races ?? []) {\n\t\t// a copy that says it keeps none of the original's hooks\n\t\tif (race.inherits?.hooks === false) continue\n\t\tfor (const { of, ...hook } of race.hooks ?? []) {\n\t\t\tconst whose = of ?? playerOfEvent\n\t\t\thooks.push({\n\t\t\t\t...hook,\n\t\t\t\trun(world, event) {\n\t\t\t\t\tconst player = whose(event)\n\t\t\t\t\tif (player !== undefined && world.players.get(player)?.race === race.id) hook.run(world, event)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\treturn hooks\n}\n\n/**\n * A race, as the game lists it (`GameModule.races`)\n *\n * @beta\n */\nexport const defineRace = (def: RaceDef): RaceDef => def\n\n/**\n * What is chosen for a seat or a player to have a race drawn for them as the game starts, from the world's own\n * numbers: the same on every machine\n *\n * @beta\n */\nexport const RANDOM_RACE = 'random'\n\n/**\n * The race a player plays: none in a game without races, and none for the neutral players and the creeps\n *\n * @beta\n */\nexport const raceOf = (world: World, player: PlayerId): string | undefined => world.players.get(player)?.race\n\n/**\n * Makes a player play another race from now on: a campaign's mission, a game's own way of choosing. What they have\n * stays theirs; what they may make is the new race's. Throws for a race the game does not have, or for the neutral\n * players and the creeps\n *\n * @beta\n */\nexport function setRace(world: World, player: PlayerId, race: string): void {\n\tconst who = world.player(player)\n\tif (who.neutral || who.creeps) throw new Error(`Player ${player} plays no race: the neutral players and the creeps have none`)\n\tif (!world.registry.races.has(race)) throw new Error(`\"${race}\" is not a race of the game (${raceList(world.registry)})`)\n\twho.race = race\n}\n\n/**\n * Whether a player may make a unit type or research an upgrade at all, as their race goes (`UnitTypeDef.race`), and\n * then as the game's `available` hook says: what they may not is not on their buttons, and an order for it is\n * refused. What it requires is another question (`unlocked`), asked only of what is available\n *\n * @beta\n */\nexport function isAvailable(world: World, player: PlayerId, kind: 'unit' | 'upgrade', id: string): boolean {\n\tconst { registry } = world\n\tif (kind === 'unit' ? !registry.units.has(id) : !registry.upgrades.has(id)) return false\n\tconst def: UnitTypeDef | UpgradeDef = kind === 'unit' ? registry.unit(id) : registry.upgrade(id)\n\tconst race = raceOf(world, player)\n\tconst available = availableTo(def, race)\n\tif (!world.hooks.has('available')) return available\n\treturn world.hooks.run('available', { player, kind, id, race, available }).available\n}\n\n/**\n * The races players get as a world is made: what each was given, one drawn for those given `random`, and the game's\n * first for a player given none. Nobody's in a game without races. Throws for a race the game does not have\n */\nexport function settleRaces(players: Iterable<Player>, registry: Registry, draw: (count: number) => number, among?: readonly string[]): void {\n\tconst races = registry.races.all()\n\t// what random draws from: those of the game named, all where none are\n\tconst drawn = races.filter((race) => among?.includes(race.id))\n\tconst pool = drawn.length ? drawn : races\n\tfor (const player of players) {\n\t\tconst given = player.race\n\t\tif (player.neutral || player.creeps || !races.length) {\n\t\t\tif (given !== undefined && given !== RANDOM_RACE && !registry.races.has(given))\n\t\t\t\tthrow new Error(`Player ${player.id} is given the race \"${given}\", and ${races.length ? 'plays none' : 'the game has no races'}`)\n\t\t\tplayer.race = undefined\n\t\t\tcontinue\n\t\t}\n\t\tif (given === RANDOM_RACE) player.race = pool[draw(pool.length)].id\n\t\telse if (given === undefined) player.race = races[0].id\n\t\telse if (!registry.races.has(given))\n\t\t\tthrow new Error(`Player ${player.id} is given the race \"${given}\", which is not a race of the game (${raceList(registry)})`)\n\t}\n}\n\n/**\n * Throws for races that cannot be: one there twice, one called `random`, a unit type or upgrade of a race the game does\n * not have, a resource a race starts with that the game has not, or a start as data (a race's, or the game's) that names\n * a unit type the game has not, saying which was meant where one is close. Run as a registry is made (`createRegistry`,\n * every world's); for a game's own tests\n *\n * @beta\n */\nexport function checkRaces(game: GameModule): void {\n\tconst known = new Set<string>()\n\tfor (const race of game.races ?? []) {\n\t\tif (race.id === RANDOM_RACE) throw new Error(`A race cannot be called \"${RANDOM_RACE}\": it is what is chosen for one drawn as the game starts`)\n\t\tif (known.has(race.id)) throw new Error(`The race \"${race.id}\" is there twice`)\n\t\tknown.add(race.id)\n\t}\n\tconst check = (what: string, race: string | undefined) => {\n\t\tif (race !== undefined && !known.has(race))\n\t\t\tthrow new Error(\n\t\t\t\t`${what} is of the race \"${race}\", which ${known.size ? `is not a race of the game (${[...known].join(', ')})` : 'the game does not have: it has no races'}`\n\t\t\t)\n\t}\n\tfor (const unit of game.units) check(`Unit type \"${unit.id}\"`, unit.race)\n\tfor (const upgrade of game.upgrades ?? []) check(`Upgrade \"${upgrade.id}\"`, upgrade.race)\n\tconst resources = new Set((game.resources ?? []).map((resource) => resource.id))\n\tfor (const race of game.races ?? []) {\n\t\tfor (const kind in race.resources)\n\t\t\tif (!resources.has(kind)) throw new Error(`The race \"${race.id}\" starts with \"${kind}\", which is not a resource of the game`)\n\t}\n\t// a start as data names unit types the game has to have\n\tconst units = new Set(game.units.map((unit) => unit.id))\n\tconst starts = [\n\t\t{ whose: 'The game', start: game.start },\n\t\t...(game.races ?? []).map((race) => ({ whose: `The race \"${race.id}\"`, start: race.start }))\n\t]\n\tfor (const { whose, start } of starts) {\n\t\tfor (const { where, id } of startIds(start)) {\n\t\t\tif (units.has(id)) continue\n\t\t\tconst meant = nearestId(id, units)\n\t\t\tthrow new Error(`${whose} starts with \"${id}\" (${where}), which is no unit type of the game${meant ? `. Did you mean \"${meant}\"?` : ''}`)\n\t\t}\n\t}\n}\n\n/**\n * Gives each player of a world just made what their race starts them with (`RaceDef.resources`), but those given\n * resources of their own\n */\nexport function raceResources(world: World, players: readonly { id: PlayerId; resources?: unknown }[]): void {\n\tfor (const init of players) {\n\t\tconst player = world.players.get(init.id)\n\t\tif (!player?.race || init.resources) continue\n\t\tconst own = world.registry.race(player.race).resources\n\t\tfor (const kind in own) player.resources[kind] = own[kind]!\n\t}\n}\n\nconst raceList = (registry: Registry): string => (registry.races.size ? registry.races.keys().join(', ') : 'it has none')\n","import { entityMorphed } from '#engine/engineEvents'\nimport { type Entity, type PlayerId, moving, fighting } from './entity'\nimport { productionQueue } from './systems/productionQueue'\nimport { statsOf } from './stats'\nimport { type UnitTypeDef, upgradesOf } from './defs'\nimport { dropOnGround } from './items'\nimport { inventorySlots, slotsOf } from './inventory'\nimport { gathering } from './orders/harvest'\nimport { clearOrders } from './orders/queue'\nimport type { World } from './world'\nimport { engineMessage, type Message, toMessage } from './messages'\nimport { isAvailable } from './races'\nimport { replicateEvent } from './replication'\nimport { availableTo } from './shared'\nimport { agentParamsOf } from './navigation/agentParams'\n\n/**\n * Types of the finished buildings a player has, with what those count as\n *\n * @beta\n */\nexport function techOf(world: World, player: PlayerId): Set<string> {\n\tconst tech = new Set<string>()\n\tfor (const entity of world.index.ownedBy(player)) {\n\t\tif (!entity.alive || !entity.isBuilding || !entity.operational) continue\n\t\ttech.add(entity.def.id)\n\t\tfor (const other of entity.def.provides ?? []) tech.add(other)\n\t}\n\treturn tech\n}\n\n/**\n * What of a list of requirements a player does not have\n *\n * @beta\n */\nexport function missing(world: World, player: PlayerId, requires: string[] | undefined, tech = techOf(world, player)): string[] {\n\treturn (requires ?? []).filter((id) => !tech.has(id))\n}\n\n/**\n * Checks requirements and tells the player what is missing. True when there is nothing in the way\n *\n * @beta\n */\nexport function meets(world: World, player: PlayerId, requires: string[] | undefined): boolean {\n\tconst lacking = missing(world, player, requires)\n\tif (lacking.length === 0) return true\n\tworld.message(player, engineMessage('requires', { units: lacking }))\n\treturn false\n}\n\n/**\n * Why a player may not make something as far as what it requires goes, or nothing: the finished buildings it\n * requires, and then the `requirement` hook (see `Requirement`). For a unit or structure type, or a level of research\n *\n * @beta\n */\nexport function unlockRefusal(\n\tworld: World,\n\tplayer: PlayerId,\n\tkind: 'unit' | 'upgrade',\n\tid: string,\n\trequires: string[] | undefined,\n\tlevel?: number\n): Message | undefined {\n\tconst lacking = missing(world, player, requires)\n\tconst refusal = lacking.length ? engineMessage('requires', { units: lacking }) : undefined\n\tif (!world.hooks.has('requirement')) return refusal\n\tconst decided = world.hooks.run('requirement', { player, kind, id, level, missing: lacking, refusal }).refusal\n\treturn decided ? toMessage(decided) : undefined\n}\n\n/**\n * Checks that something is the player's to make at all (`isAvailable`: their race, the `available` hook), then what it\n * requires, by `unlockRefusal`, and tells the player what stands in the way. True when nothing does\n *\n * @beta\n */\nexport function unlocked(\n\tworld: World,\n\tplayer: PlayerId,\n\tkind: 'unit' | 'upgrade',\n\tid: string,\n\trequires: string[] | undefined,\n\tlevel?: number\n): boolean {\n\tif (!isAvailable(world, player, kind, id)) {\n\t\tworld.message(player, engineMessage('cannotDoThat'))\n\t\treturn false\n\t}\n\tconst refusal = unlockRefusal(world, player, kind, id, requires, level)\n\tif (refusal) world.message(player, refusal)\n\treturn !refusal\n}\n\n/**\n * Turns an entity into another type, where it stands: a building upgraded, a unit transformed (a druid into a bear, a\n * siege tank set up). Everything of the type is the new one's: stats, how it moves (and on the ground or in the air),\n * whether it fights, gathers or carries, its abilities (those of the old type it keeps are kept as they were, at their\n * levels and cooldowns), and what it makes. What it went through stays: health lost, mana, buffs, experience, items.\n * The parts of the game it had none of are given it as `spawn` gives them (`Component.onSpawn`), and the `morphed` hook\n * runs: what a pack gives it of its own for its new type (the heroes pack: a hero's level, a shop's wares)\n *\n * @beta\n */\nexport function morph(world: World, entity: Entity, into: string): void {\n\tconst def = world.registry.unit(into)\n\tconst old = entity.def\n\tconst from = old.id\n\tconst hurt = entity.maxHp - entity.hp\n\t// filed again: what it turns into may sell things, or not\n\tworld.index.remove(entity)\n\tentity.retype(def)\n\tworld.index.add(entity)\n\tconst { health, moveSpeed } = statsOf(world, entity)\n\tentity.maxHp = health\n\tentity.hp = Math.max(health - hurt, 1)\n\t// a unit that makes things too: what `spawn` gives a structure only\n\tif ((def.trains?.length || def.researches?.length || upgradesOf(def).length) && !entity.has(productionQueue))\n\t\tentity.set(productionQueue, { queue: [], rally: null })\n\tif (def.kind === 'unit' && old.kind === 'unit') transform(world, entity, old, moveSpeed)\n\t// what each part of the game gives one of the new type as it is made, where it has none of it yet: a hold, slots, a\n\t// game's own (`Component.onSpawn`); what it has already (a hold with passengers, its slots) stays as it is\n\tfor (const part of world.registry.spawning) if (!entity.has(part)) part.onSpawn!(entity, world)\n\t// what a pack gives it of its own for its new type: a hero's level, a shop's wares (`withHeroes`)\n\tif (world.hooks.has('morphed')) world.hooks.run('morphed', { entity, from })\n\tworld.events.emit(entityMorphed, { entity, from })\n}\n\n/** What changes of a unit that becomes another unit type, beyond its stats */\nfunction transform(world: World, entity: Entity, old: UnitTypeDef, speed: number): void {\n\tconst { def } = entity\n\t// how it moves: on the ground or in the air, how big it is\n\tconst m = entity.get(moving)\n\tconst reshaped = old.flying !== def.flying || old.radius !== def.radius || old.naval !== def.naval\n\tif (m && (reshaped || !speed)) world.nav.removeAgent(entity.id)\n\tif (m && speed && reshaped) world.nav.addAgent(entity.id, entity.pos, agentParamsOf(entity, speed))\n\tif (!speed) entity.remove(moving)\n\telse if (m) {\n\t\t// an agent kept is told its new speed too\n\t\tif (!reshaped && m.speed !== speed) world.nav.setSpeed(entity.id, speed)\n\t\tm.speed = speed\n\t}\n\t// whether it fights, and gathers\n\tif (def.attacks?.length) {\n\t\tif (!entity.has(fighting))\n\t\t\tentity.set(fighting, { cooldown: 0, swing: 0, swingTarget: 0, autoTarget: 0, lastAttacker: 0, guard: null, passive: false })\n\t} else entity.remove(fighting)\n\tif (!def.harvester) entity.remove(gathering)\n\telse if (!entity.has(gathering)) entity.set(gathering, { carrying: 0, kind: null, resource: 0 })\n\t// its abilities: those of the new type, the ones it had already as they were; what a hero learned stays\n\tconst kept = new Map(entity.abilities.map((state) => [state.id, state]))\n\tconst learned = new Set([...(old.hero?.learns ?? []), ...(old.hero?.spells ?? []), ...(def.hero?.learns ?? []), ...(def.hero?.spells ?? [])])\n\tentity.setAbilities([\n\t\t...(def.abilities ?? []).map((id) => kept.get(id) ?? { id, level: 1, cooldown: 0, autocast: world.registry.ability(id).autocast ?? false }),\n\t\t...entity.abilities.filter((state) => learned.has(state.id) && !(def.abilities ?? []).includes(state.id))\n\t])\n\t// what it carries: the slots of the new type, what does not fit left on the ground\n\tif (def.inventory !== old.inventory) {\n\t\tconst items = (slotsOf(entity) ?? []).filter((item) => item !== null)\n\t\tif (def.inventory)\n\t\t\tentity.set(\n\t\t\t\tinventorySlots,\n\t\t\t\tArray.from({ length: def.inventory }, (_, i) => items[i] ?? null)\n\t\t\t)\n\t\telse entity.remove(inventorySlots)\n\t\tfor (const item of items.slice(def.inventory ?? 0)) dropOnGround(world, item, entity.pos)\n\t}\n\t// what it was doing may not be for what it is now\n\tclearOrders(world, entity)\n}\n\n/** What became another, to those who see it */\nexport const toldMorphed = replicateEvent(entityMorphed, 'morphed', ({ entity, from }, view) =>\n\tview.knows(entity) ? { type: 'morphed', id: entity.id, from } : undefined\n)\n\n/**\n * What the `requirement` hook decided for a player, where it is not what the requirements say: what their screen could\n * not work out for itself (`PlayerState.own.unlocks`). Nothing where the hook agrees with them all\n *\n * @beta\n */\nexport function decidedUnlocks(world: World, player: PlayerId): Record<string, Message | null> | undefined {\n\tconst tech = techOf(world, player)\n\tlet decided: Record<string, Message | null> | undefined\n\tconst compare = (key: string, kind: 'unit' | 'upgrade', id: string, requires: string[] | undefined, level?: number) => {\n\t\tconst lacking = missing(world, player, requires, tech)\n\t\tconst declared = lacking.length ? 'requires' : undefined\n\t\tconst refusal = unlockRefusal(world, player, kind, id, requires, level)\n\t\tif (refusal?.key !== declared || (refusal && declared && refusal.params?.units?.toString() !== lacking.toString()))\n\t\t\t(decided ??= {})[key] = refusal ?? null\n\t}\n\tfor (const def of world.registry.units.all()) compare(def.id, 'unit', def.id, def.requires)\n\tfor (const def of world.registry.upgrades.all()) {\n\t\tconst level = world.player(player).upgrades.get(def.id) ?? 0\n\t\tif (level < (def.maxLevel ?? 1)) compare(`upgrade:${def.id}`, 'upgrade', def.id, def.requires?.[level], level + 1)\n\t}\n\treturn decided\n}\n\n/**\n * What the `available` hook decided for a player, where it is not what their race says: what their screen could not\n * work out for itself (`PlayerState.own.availability`). Nothing where the hook agrees\n *\n * @beta\n */\nexport function decidedAvailability(world: World, player: PlayerId): Record<string, boolean> | undefined {\n\tconst race = world.player(player).race\n\tlet decided: Record<string, boolean> | undefined\n\tfor (const def of world.registry.units.all()) {\n\t\tconst available = isAvailable(world, player, 'unit', def.id)\n\t\tif (available !== availableTo(def, race)) (decided ??= {})[def.id] = available\n\t}\n\tfor (const def of world.registry.upgrades.all()) {\n\t\tconst available = isAvailable(world, player, 'upgrade', def.id)\n\t\tif (available !== availableTo(def, race)) (decided ??= {})[`upgrade:${def.id}`] = available\n\t}\n\treturn decided\n}\n","import { morphStarted, researchFinished, unitTrained } from '#engine/engineEvents'\nimport { gathering } from '#engine/orders/harvest'\nimport type { Entity } from '#engine/entity'\nimport { heroesOf, heroState, reviveCost, reviveHero } from '#engine/hero'\nimport { closestPointOnRect, type Vec2 } from '#engine/math'\nimport { createOrder, giveOrder } from '#engine/orders/queue'\nimport { morph, techOf, unlocked } from '#engine/tech'\nimport { type PlayerFacts, trainRefusal } from '#engine/shared'\nimport { type Cost, upgradesOf } from '#engine/defs'\nimport type { ProductionKind } from '#engine/hooks'\nimport { shortOf, spend } from '#engine/player'\nimport type { System } from '#engine/registry'\nimport type { World } from '#engine/world'\nimport { engineMessage } from '#engine/messages'\nimport { atan2 } from '#engine/exactMath'\nimport { giveBack, productionOf, productionQueue } from './productionQueue'\nimport { deposit } from '../entity'\nimport { replicateEvent } from '../replication'\n\nfunction hasRoom(world: World, building: Entity): boolean {\n\tif (productionOf(building)!.queue.length < world.rules.production.queue) return true\n\tworld.message(building.owner, engineMessage('queueFull'))\n\treturn false\n}\n\n/**\n * Lets the `beforeProduce` hook have its say about something about to be made, then has the player pay for it.\n * What it ends up costing and how long it takes, or undefined when it is not made (and the player was told why).\n * `producer` is the building it is made in, or the worker putting down a structure\n */\nexport function startProducing(\n\tworld: World,\n\tproducer: Entity,\n\tkind: ProductionKind,\n\tid: string,\n\tcost: Cost | undefined,\n\ttime: number\n): { cost: Cost; time: number } | undefined {\n\tconst player = world.player(producer.owner)\n\tconst event = world.hooks.run('beforeProduce', { player: player.id, producer, kind, id, cost: { ...cost }, time, cancelled: false })\n\tif (event.cancelled) {\n\t\tif (event.reason) world.message(player.id, event.reason)\n\t\treturn undefined\n\t}\n\tconst short = shortOf(player.resources, event.cost)\n\tif (short) {\n\t\tworld.message(player.id, engineMessage('notEnough', { resource: short }))\n\t\treturn undefined\n\t}\n\tspend(world, player.id, event.cost, kind, id)\n\treturn event\n}\n\n/** Queues a unit for training. Returns false (and tells the player why) when that is not possible. */\nexport function enqueueProduction(world: World, building: Entity, unitType: string): boolean {\n\tconst production = productionOf(building)\n\tif (!production || !building.operational || !building.def.trains?.includes(unitType)) return false\n\tconst def = world.registry.unit(unitType)\n\tconst player = world.player(building.owner)\n\tif (!hasRoom(world, building)) return false\n\tif (!unlocked(world, player.id, 'unit', unitType, def.requires)) return false\n\t// the same rule the player's screen goes by (what it requires was asked above, the game's hook with it)\n\tconst refusal = trainRefusal(world.registry, def, playerFacts(world, player.id), { cost: false, tech: false })\n\tif (refusal) {\n\t\tworld.message(player.id, refusal)\n\t\treturn false\n\t}\n\t// what it will take, as the game's rule says of a unit not made yet\n\tconst supply = world.rules.supply.of(world, { def, owner: player.id, queued: true })\n\tconst made = startProducing(world, building, 'unit', unitType, def.cost, def.buildTime ?? 1)\n\tif (!made) return false\n\t// reserve it right away, so several commands in the same tick cannot overshoot the cap\n\tplayer.supplyUsed += supply\n\tfor (const name in def.supplies) if (player.supplies[name]) player.supplies[name].used += def.supplies[name]\n\tproduction.queue.push({ kind: 'unit', id: unitType, paid: made.cost, progress: 0, duration: made.time })\n\treturn true\n}\n\n/**\n * What there is to know about a player for whether they can make something, see `trainRefusal`\n *\n * @beta\n */\nexport function playerFacts(world: World, playerId: number): PlayerFacts {\n\tconst player = world.player(playerId)\n\t// every hero counts: alive, fallen, or in a queue\n\tconst heroes = heroesOf(world, playerId).map((hero) => hero.def.id)\n\tfor (const other of world.index.ownedBy(playerId)) {\n\t\tconst production = productionOf(other)\n\t\tif (!production) continue\n\t\tfor (const item of production.queue) if (item.kind === 'unit' && world.registry.unit(item.id).hero) heroes.push(item.id)\n\t}\n\treturn {\n\t\tresources: player.resources,\n\t\tsupplyUsed: player.supplyUsed,\n\t\tsupplyCap: player.supplyCap,\n\t\t...(Object.keys(player.supplies).length > 0 && { supplies: player.supplies }),\n\t\ttech: techOf(world, playerId),\n\t\theroes,\n\t\t...(player.race !== undefined && { race: player.race })\n\t}\n}\n\n/**\n * Levels of an upgrade a player has, counting the one being researched\n *\n * @beta\n */\nexport function upgradeLevel(world: World, playerId: number, upgrade: string): { level: number; researching: boolean } {\n\tconst player = world.player(playerId)\n\treturn { level: player.upgrades.get(upgrade) ?? 0, researching: player.researching.has(upgrade) }\n}\n\n/** Queues an upgrade. One level at a time, and only in one building at once. */\nexport function enqueueResearch(world: World, building: Entity, upgrade: string): boolean {\n\tconst production = productionOf(building)\n\tif (!production || !building.operational || !building.def.researches?.includes(upgrade)) return false\n\tconst def = world.registry.upgrade(upgrade)\n\tconst player = world.player(building.owner)\n\tconst { level, researching } = upgradeLevel(world, player.id, upgrade)\n\tif (researching) {\n\t\tworld.message(player.id, engineMessage('alreadyResearching'))\n\t\treturn false\n\t}\n\tif (level >= (def.maxLevel ?? 1)) return false\n\tif (!unlocked(world, player.id, 'upgrade', upgrade, def.requires?.[level], level + 1)) return false\n\tif (!hasRoom(world, building)) return false\n\tconst made = startProducing(world, building, 'upgrade', upgrade, def.cost, def.researchTime)\n\tif (!made) return false\n\tplayer.researching.add(upgrade)\n\tproduction.queue.push({ kind: 'upgrade', id: upgrade, paid: made.cost, progress: 0, duration: made.time })\n\treturn true\n}\n\n/** Queues bringing a fallen hero back */\nexport function enqueueRevive(world: World, building: Entity, heroId: number): boolean {\n\tconst production = productionOf(building)\n\tconst hero = world.entities.get(heroId)\n\tif (!production || !building.operational || !building.def.revives) return false\n\tif (!hero?.has(heroState) || hero.alive || hero.owner !== building.owner || hero.reviving) return false\n\tconst { cost, time } = reviveCost(world, hero)\n\tif (!hasRoom(world, building)) return false\n\tconst made = startProducing(world, building, 'revive', String(heroId), cost, time)\n\tif (!made) return false\n\thero.reviving = true\n\tproduction.queue.push({ kind: 'revive', id: String(heroId), paid: made.cost, progress: 0, duration: made.time })\n\treturn true\n}\n\n/**\n * Queues upgrading a building into a type it can become (`UnitTypeDef.upgradesTo`): `into`, one of them, or the first\n * where none is named. One at a time\n */\nexport function enqueueMorph(world: World, building: Entity, into = upgradesOf(building.def)[0]): boolean {\n\tconst production = productionOf(building)\n\tif (!production || !building.operational || into === undefined || !upgradesOf(building.def).includes(into)) return false\n\tif (production.queue.some((item) => item.kind === 'morph')) return false\n\tconst def = world.registry.unit(into)\n\tif (!unlocked(world, building.owner, 'unit', into, def.requires) || !hasRoom(world, building)) return false\n\tconst made = startProducing(world, building, 'morph', into, def.cost, def.buildTime ?? 1)\n\tif (!made) return false\n\tproduction.queue.push({ kind: 'morph', id: into, paid: made.cost, progress: 0, duration: made.time })\n\tworld.events.emit(morphStarted, { entity: building, into, time: made.time })\n\treturn true\n}\n\nexport function cancelProduction(world: World, building: Entity, index: number): boolean {\n\tconst production = productionOf(building)\n\tconst item = production?.queue[index]\n\tif (!production || !item) return false\n\tproduction.queue.splice(index, 1)\n\tgiveBack(world, building, item)\n\treturn true\n}\n\n/** Where what a building produced comes out: on the side of its rally point */\nfunction exitOf(world: World, building: Entity, radius: number): { exit: Vec2; towards: Vec2 } {\n\tconst rally = productionOf(building)!.rally\n\tconst towards = world.get(rally?.target)?.pos ?? rally?.point ?? { x: building.pos.x, z: building.pos.z - 100 }\n\treturn { exit: closestPointOnRect(towards, building.rect, radius + 0.3), towards }\n}\n\nfunction finishUnit(world: World, building: Entity, unitType: string): void {\n\tconst def = world.registry.unit(unitType)\n\tconst rally = productionOf(building)!.rally\n\tconst rallyTarget = world.get(rally?.target)\n\tconst { exit, towards } = exitOf(world, building, def.radius)\n\tconst unit = world.spawn(unitType, building.owner, exit, { facing: atan2(towards.x - exit.x, towards.z - exit.z) })\n\tworld.events.emit(unitTrained, { building, unit })\n\tworld.hooks.run('produced', { producer: building, kind: 'unit', id: unitType, unit })\n\tif (!rally) return\n\n\tif (rallyTarget?.get(deposit) && unit.has(gathering)) giveOrder(world, unit, createOrder(world, { type: 'harvest', target: rallyTarget.id }))\n\telse if (rallyTarget && rallyTarget.isUnit) giveOrder(world, unit, createOrder(world, { type: 'move', target: rallyTarget.id }))\n\telse giveOrder(world, unit, createOrder(world, { type: 'move', point: rally.point }))\n}\n\nfunction finishUpgrade(world: World, building: Entity, upgrade: string): void {\n\tconst player = world.player(building.owner)\n\tconst level = (player.upgrades.get(upgrade) ?? 0) + 1\n\tplayer.setUpgrade(upgrade, level)\n\tplayer.researching.delete(upgrade)\n\t// what it does besides stats, to every unit the player has\n\tconst { apply } = world.registry.upgrade(upgrade)\n\tif (apply) for (const entity of [...world.index.ownedBy(player.id)]) if (entity.alive) apply(world, entity, level)\n\tworld.events.emit(researchFinished, { building, upgrade, level })\n\tworld.hooks.run('produced', { producer: building, kind: 'upgrade', id: upgrade, level })\n\tworld.message(player.id, engineMessage('researchDone', { upgrade }), 'info')\n}\n\nexport const productionSystem: System = {\n\tname: 'production',\n\tphase: 'resolve',\n\t// only what trains, researches or turns into something: not every unit and tree of the map (OB5)\n\tover: productionQueue,\n\teach(world, entity, dt) {\n\t\tconst production = productionOf(entity)\n\t\tif (!production || !entity.operational || entity.scenery) return\n\t\tconst item = production.queue[0]\n\t\tif (!item) return\n\t\titem.progress += dt\n\t\tif (item.progress < item.duration) return\n\t\tproduction.queue.shift()\n\t\tif (item.kind === 'unit') finishUnit(world, entity, item.id)\n\t\telse if (item.kind === 'upgrade') finishUpgrade(world, entity, item.id)\n\t\telse if (item.kind === 'morph') {\n\t\t\tmorph(world, entity, item.id)\n\t\t\tworld.hooks.run('produced', { producer: entity, kind: 'morph', id: item.id, unit: entity })\n\t\t} else {\n\t\t\tconst hero = world.entities.get(Number(item.id))\n\t\t\tif (hero) {\n\t\t\t\treviveHero(world, hero, exitOf(world, entity, hero.def.radius).exit)\n\t\t\t\tworld.hooks.run('produced', { producer: entity, kind: 'revive', id: item.id, unit: hero })\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** A unit made, to those who see it */\nexport const toldTrained = replicateEvent(unitTrained, 'trained', ({ building, unit }, view) =>\n\tview.knows(unit) ? { type: 'trained', id: unit.id, building: view.knows(building) ? building.id : undefined } : undefined\n)\n\n/** Research done: to its side */\nexport const toldResearched = replicateEvent(researchFinished, 'researched', ({ building, upgrade, level }, view) =>\n\tview.isAlly(building.owner) ? { type: 'researched', upgrade, level, building: building.id } : undefined\n)\n\n/** A building starting to become another, to those who see it */\nexport const toldUpgradeStarted = replicateEvent(morphStarted, 'upgradeStarted', ({ entity, into, time }, view) =>\n\tview.knows(entity) ? { type: 'upgradeStarted', id: entity.id, to: into, time } : undefined\n)\n","import { constructionFinished, worked as workedEvent } from '#engine/engineEvents'\nimport { constructionOf, type Cost, footprintOf, type UnitTypeDef } from '#engine/defs'\nimport { constructionSite, underConstruction } from '#engine/systems/construction'\nimport { edgeDistance, type Entity, type EntityId, type PlayerId } from '#engine/entity'\nimport { closestPointOnRect, distToRect, type Rect, type Vec2 } from '#engine/math'\nimport type { OrderBehavior, OrderInits, OrderStatus } from '#engine/registry'\nimport { faceTowards, halt, moveTo, moveToEntity, setAnchored, setGhost, walkOn } from '#engine/systems/movement'\nimport { footprintCell } from '#engine/grid'\nimport { shortOf, spend } from '#engine/player'\nimport { startProducing } from '#engine/systems/production'\nimport { unlocked } from '#engine/tech'\nimport type { World } from '#engine/world'\nimport { engineMessage, type MessageRef } from '#engine/messages'\nimport { moving, deposit } from '../entity'\n\n/** Edge distance from which a worker can work on a building */\nconst WORK_RANGE = 0.8\n/** A builder that cannot get any closer than this because of units in the way starts building anyway */\nconst CROWDED_RANGE = 3\n\n/**\n * Ground a structure of this type covers when placed at `point`\n *\n * @beta\n */\nexport function siteOf(def: UnitTypeDef, point: Vec2): Rect & { cellX: number; cellZ: number } {\n\tconst fp = footprintOf(def)\n\tconst cell = footprintCell(point.x, point.z, fp.w, fp.d)\n\treturn { x: cell.x + fp.w / 2, z: cell.z + fp.d / 2, hw: fp.w / 2, hd: fp.d / 2, cellX: cell.x, cellZ: cell.z }\n}\n\n/**\n * Why this structure cannot be placed here right now, or undefined when it can. The ground has to be free,\n * then the `canPlace` hook has its say. With `fog`, ground the player has never seen counts as taken too:\n * that is for the player's own preview, which must not give away what is in the dark\n *\n * @beta\n */\nexport function placementProblem(world: World, def: UnitTypeDef, point: Vec2, player?: PlayerId, fog = false): MessageRef | undefined {\n\tconst fp = footprintOf(def)\n\tconst site = siteOf(def, point)\n\tif (def.builtOn !== undefined) {\n\t\t// over a resource of its kind, one nothing stands on yet: its ground is the resource's\n\t\tconst source = resourceAt(world, def, point)\n\t\tif (!source) return engineMessage('buildOnResource', { resource: def.builtOn })\n\t\tif (world.get(source.get(deposit)!.under)?.alive) return engineMessage('cannotBuildThere')\n\t} else if (!world.grid.canPlace(site.cellX, site.cellZ, fp.w, fp.d)) return engineMessage('cannotBuildThere')\n\t// what is built is in the way of who walks: where the navigation has no room for it, nothing more is built\n\tif (def.kind === 'building' && world.nav.obstacleRoom() <= 0) return engineMessage('tooManyBuildings')\n\tif (fog && player !== undefined) {\n\t\tconst { team } = world.player(player)\n\t\tconst explored =\n\t\t\tworld.fog.isExplored(team, site.x - site.hw + 0.5, site.z - site.hd + 0.5) &&\n\t\t\tworld.fog.isExplored(team, site.x + site.hw - 0.5, site.z - site.hd + 0.5) &&\n\t\t\tworld.fog.isExplored(team, site.x - site.hw + 0.5, site.z + site.hd - 0.5) &&\n\t\t\tworld.fog.isExplored(team, site.x + site.hw - 0.5, site.z + site.hd - 0.5)\n\t\tif (!explored) return engineMessage('cannotBuildThere')\n\t}\n\tif (!world.hooks.has('canPlace')) return undefined\n\tconst event = world.hooks.run('canPlace', { def, site, player, allowed: true })\n\treturn event.allowed ? undefined : (event.reason ?? engineMessage('cannotBuildThere'))\n}\n\nconst near: Entity[] = []\n\n/**\n * The resource a building that goes up on one (`UnitTypeDef.builtOn`) would stand on when placed at `point`: one of its\n * kind that covers the very same ground. None where there is none\n *\n * @beta\n */\nexport function resourceAt(world: World, def: UnitTypeDef, point: Vec2): Entity | undefined {\n\tif (def.builtOn === undefined) return undefined\n\tconst site = siteOf(def, point)\n\tfor (const other of world.spatial.query(site.x, site.z, Math.max(site.hw, site.hd) + 1, near)) {\n\t\tif (!other.alive || other.def.resource?.kind !== def.builtOn || !other.cell) continue\n\t\tconst fp = footprintOf(other.def)\n\t\tif (other.cell.x === site.cellX && other.cell.z === site.cellZ && fp.w === site.hw * 2 && fp.d === site.hd * 2) return other\n\t}\n\treturn undefined\n}\n\n/**\n * Which cells of the ground a structure would cover at `point` are in the way, row by row from its corner (`w` across,\n * `d` rows: `siteOf`'s cell first): taken (`free` says no), or not explored (`explored` says no, where it is asked).\n * What a preview draws cell by cell (RV88); `placementProblem` says the whole, the game's own say among it. None for a\n * structure built on a resource, whose ground is the resource's\n *\n * @beta\n */\nexport function placementCells(\n\tdef: UnitTypeDef,\n\tpoint: Vec2,\n\tfree: (cellX: number, cellZ: number) => boolean,\n\texplored?: (cellX: number, cellZ: number) => boolean\n): boolean[] | undefined {\n\tif (def.builtOn !== undefined) return undefined\n\tconst { w, d } = footprintOf(def)\n\tconst { cellX, cellZ } = siteOf(def, point)\n\tconst blocked: boolean[] = []\n\tfor (let z = cellZ; z < cellZ + d; z++) for (let x = cellX; x < cellX + w; x++) blocked.push(!free(x, z) || (!!explored && !explored(x, z)))\n\treturn blocked\n}\n\n/**\n * Whether this structure can be placed here right now, see `placementProblem`\n *\n * @beta\n */\nexport function canPlaceStructure(world: World, def: UnitTypeDef, point: Vec2, player?: PlayerId, fog = false): boolean {\n\treturn placementProblem(world, def, point, player, fog) === undefined\n}\n\nconst inside: Entity[] = []\n\n/** Moves units standing on a construction site out of the way */\nfunction clearSite(world: World, site: Rect): void {\n\tworld.spatial.query(site.x, site.z, Math.max(site.hw, site.hd) * 1.5 + 1, inside)\n\tfor (const unit of inside) {\n\t\tif (!unit.get(moving) || unit.hidden || unit.flying) continue\n\t\tif (distToRect(unit.pos, site) >= unit.def.radius) continue\n\t\tconst outside = closestPointOnRect(unit.pos, site, unit.def.radius + 0.3)\n\t\tconst point = world.nav.closestPoint(outside, 6) ?? outside\n\t\tworld.place(unit, point)\n\t\t// teleporting drops the path\n\t\twalkOn(world, unit)\n\t}\n}\n\nfunction workOn(world: World, entity: Entity, building: Entity | undefined, state: WorkState, dt: number): OrderStatus {\n\tconst site = building && underConstruction(building)\n\tif (!site) return 'done'\n\tif (edgeDistance(entity, building) > WORK_RANGE) {\n\t\tmoveToEntity(world, entity, building, WORK_RANGE * 0.5)\n\t\treturn 'running'\n\t}\n\tif (entity.get(moving)!.status === 'moving') halt(world, entity)\n\tsetAnchored(world, entity, true)\n\tfaceTowards(entity, building.pos, dt)\n\tsite.builders++\n\t// a blow of its hammer now and then, for the screen (`worked`), as a repair has\n\tconst hammer = (state.hammer ?? HAMMER_INTERVAL * 0.5) - dt\n\tif (hammer <= 0) world.events.emit(workedEvent, { worker: entity, target: building })\n\tstate.hammer = hammer <= 0 ? hammer + HAMMER_INTERVAL : hammer\n\treturn 'running'\n}\n\n/**\n * What `construct` keeps: the seconds to its builder's next blow of the hammer\n *\n * @beta\n */\nexport interface WorkState {\n\t/** Seconds to its next blow, for the screen (`worked`) */\n\thammer?: number\n}\n\n/**\n * What `build` keeps: whether it walked to the site already, and the building once it is put down\n *\n * @beta\n */\nexport interface BuildState extends WorkState {\n\t/** It walked to the site already */\n\twalked?: boolean\n\t/** It walks through the others: its walk to the site failed once, held up among them (workers round a mine) */\n\tghost?: boolean\n\t/** The building, once it is put down */\n\tbuilding?: EntityId\n}\n\n/**\n * What `repair` keeps: whether it walked to it already, what of the cost it still owes, the seconds to its next swing\n *\n * @beta\n */\nexport interface RepairState {\n\t/** It walked to it already */\n\twalked?: boolean\n\t/** What of the cost of the repair it owes still */\n\towed?: Cost\n\t/** Seconds to its next swing */\n\thammer?: number\n}\n\nexport const buildOrder: OrderBehavior<BuildState, OrderInits['build']> = {\n\ttype: 'build',\n\tbuilding: (order) => !!order.state.building,\n\taccepts(world, entity, init) {\n\t\treturn !!init.point && !!init.unitType && !!entity.def.builds?.includes(init.unitType) && world.registry.units.has(init.unitType)\n\t},\n\tupdate(world, entity, order, dt) {\n\t\tconst { state } = order\n\t\tif (state.building) return workOn(world, entity, world.get(state.building), state, dt)\n\n\t\tconst def = world.registry.unit(order.init.unitType!)\n\t\tconst site = siteOf(def, order.init.point!)\n\t\tconst m = entity.get(moving)!\n\n\t\tconst gap = distToRect(entity.pos, site) - entity.def.radius\n\t\tif (gap > WORK_RANGE) {\n\t\t\tif (m.status === 'moving') return 'running'\n\t\t\t// held up right in front of it by units standing on the site: close enough, they get moved aside\n\t\t\tconst crowded = state.walked && gap <= CROWDED_RANGE\n\t\t\tif (!crowded) {\n\t\t\t\tif (state.walked && m.status === 'failed') {\n\t\t\t\t\t// held up among others (the workers anchored round a mine): once more, walking through them, as a hauling worker does\n\t\t\t\t\tif (!state.ghost) {\n\t\t\t\t\t\tstate.ghost = true\n\t\t\t\t\t\tsetGhost(world, entity, true)\n\t\t\t\t\t\tmoveTo(world, entity, closestPointOnRect(entity.pos, site, entity.def.radius + 0.15), { range: 0.3 })\n\t\t\t\t\t\treturn 'running'\n\t\t\t\t\t}\n\t\t\t\t\tworld.message(entity.owner, engineMessage('cannotReachSite'))\n\t\t\t\t\treturn 'failed'\n\t\t\t\t}\n\t\t\t\tstate.walked = true\n\t\t\t\tmoveTo(world, entity, closestPointOnRect(entity.pos, site, entity.def.radius + 0.15), { range: 0.3 })\n\t\t\t\treturn 'running'\n\t\t\t}\n\t\t}\n\n\t\tif (state.ghost) setGhost(world, entity, false)\n\t\tif (!unlocked(world, entity.owner, 'unit', def.id, def.requires)) return 'failed'\n\t\tconst problem = placementProblem(world, def, order.init.point!, entity.owner)\n\t\tif (problem) {\n\t\t\tworld.message(entity.owner, problem)\n\t\t\treturn 'failed'\n\t\t}\n\t\tconst made = startProducing(world, entity, 'structure', def.id, def.cost, def.buildTime ?? 1)\n\t\tif (!made) return 'failed'\n\t\thalt(world, entity)\n\t\tclearSite(world, site)\n\t\tconst how = constructionOf(def)\n\t\t// what appears at once is whole: no site, no builders\n\t\tconst building = world.spawn(\n\t\t\tdef.id,\n\t\t\tentity.owner,\n\t\t\torder.init.point!,\n\t\t\thow === 'instant' ? {} : { underConstruction: { buildTime: made.time, paid: made.cost } }\n\t\t)\n\t\tstate.building = building.id\n\t\t// what is there at once is built as it is put down\n\t\tif (how === 'instant') world.events.emit(constructionFinished, building)\n\t\t// what goes up on its own, or is there at once, leaves its builder free\n\t\treturn how === 'builder' ? 'running' : 'done'\n\t},\n\tend(world, entity, order) {\n\t\tsetAnchored(world, entity, false)\n\t\tif (order.state.ghost) setGhost(world, entity, false)\n\t}\n}\n\n/** Work on an existing construction site: resuming an abandoned one or helping another builder */\nexport const constructOrder: OrderBehavior<WorkState, OrderInits['construct']> = {\n\ttype: 'construct',\n\taccepts(world, entity, init) {\n\t\tconst target = world.get(init.target)\n\t\treturn (\n\t\t\t!!entity.def.builds?.length &&\n\t\t\t!!target?.has(constructionSite) &&\n\t\t\tconstructionOf(target.def) === 'builder' &&\n\t\t\tworld.areAllies(entity.owner, target.owner)\n\t\t)\n\t},\n\tupdate(world, entity, order, dt) {\n\t\treturn workOn(world, entity, world.get(order.init.target), order.state, dt)\n\t},\n\tend(world, entity) {\n\t\tsetAnchored(world, entity, false)\n\t}\n}\n\n/** Mending a building from nothing takes this much longer than building it did */\nconst REPAIR_TIME = 1.5\n/** Seconds between two blows of the hammer */\nconst HAMMER_INTERVAL = 1\n\n/**\n * Whether a worker of the player could mend it\n *\n * @beta\n */\nexport function canRepair(world: World, player: number, target: Entity): boolean {\n\treturn target.isBuilding && target.operational && target.hp < target.maxHp && world.areAllies(player, target.owner)\n}\n\n/** Mend a damaged building. It is paid for as the work goes on */\nexport const repairOrder: OrderBehavior<RepairState, OrderInits['repair']> = {\n\ttype: 'repair',\n\taccepts(world, entity, init) {\n\t\tconst target = world.get(init.target)\n\t\treturn !!entity.def.builds?.length && !!entity.get(moving) && !!target && canRepair(world, entity.owner, target)\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 || !canRepair(world, entity.owner, target)) return 'done'\n\t\tif (edgeDistance(entity, target) > WORK_RANGE) {\n\t\t\tif (entity.get(moving)!.status === 'failed' && state.walked) return 'failed'\n\t\t\tstate.walked = true\n\t\t\tmoveToEntity(world, entity, target, WORK_RANGE * 0.5)\n\t\t\treturn 'running'\n\t\t}\n\t\tif (entity.get(moving)!.status === 'moving') halt(world, entity)\n\t\tsetAnchored(world, entity, true)\n\t\tfaceTowards(entity, target.pos, dt)\n\n\t\tconst time = (target.def.buildTime ?? 20) * REPAIR_TIME\n\t\tconst mended = Math.min((target.maxHp / time) * dt, target.maxHp - target.hp)\n\t\tconst part = (mended / target.maxHp) * world.rules.economy.repairCost\n\t\tconst purse = world.player(entity.owner).resources\n\t\t// what is owed adds up until it is a whole coin, log, or whatever the building cost\n\t\tconst owed: Cost = (state.owed ??= {})\n\t\tconst due: Cost = {}\n\t\tfor (const kind in target.def.cost) {\n\t\t\towed[kind] = (owed[kind] ?? 0) + target.def.cost[kind] * part\n\t\t\tdue[kind] = Math.floor(owed[kind])\n\t\t}\n\t\tconst short = shortOf(purse, due)\n\t\tif (short) {\n\t\t\tworld.message(entity.owner, engineMessage('notEnough', { resource: short }))\n\t\t\treturn 'failed'\n\t\t}\n\t\tspend(world, entity.owner, due, 'repair', target.def.id)\n\t\tfor (const kind in due) owed[kind] -= due[kind]\n\t\ttarget.hp += mended\n\n\t\tstate.hammer = (state.hammer ?? HAMMER_INTERVAL * 0.5) - dt\n\t\tif (state.hammer <= 0) {\n\t\t\tstate.hammer += HAMMER_INTERVAL\n\t\t\tworld.events.emit(workedEvent, { worker: entity, target })\n\t\t}\n\t\treturn target.hp >= target.maxHp ? 'done' : 'running'\n\t},\n\tend(world, entity) {\n\t\tsetAnchored(world, entity, false)\n\t}\n}\n","import type { ChatAudience } from './talk'\nimport type { AbilityDef, BuffDef, Cost, DamageType, StatChange, Stats, UnitTypeDef } from './defs'\nimport type { Camp } from './camps'\nimport type { BuffInstance, Entity, EntityId, ItemInstance, Order, PlayerId } from './entity'\nimport type { FormationDef } from './formation'\nimport type { AreaDef } from './areas'\nimport type { GameMap, MapCamp, MapObject, MapRegion } from './map'\nimport type { Rect, Vec2 } from './math'\nimport type { MessageRef } from './messages'\nimport type { DeathCause, DeathReason, World } from './world'\n\n/**\n * Hooks are how game modules and mods take part in what the engine does, while it does it: make an attack\n * hit harder, keep a unit from dying, pay for a kill, refuse an order. A hook is a list of handlers that run\n * in order, each getting the same event object; handlers before damage or death can change it or call it off.\n *\n * Events (`World.events`) are different: they tell whoever watches (a player's session, a test) what has\n * happened, once the tick is over, and cannot change anything. Code that is part of the rules uses hooks.\n */\n\n/**\n * Damage about to be dealt, before armor and shields. Change `amount` or `type`, or set `cancelled`\n *\n * @beta\n */\nexport interface BeforeDamage {\n\treadonly target: Entity\n\treadonly source?: Entity\n\tamount: number\n\ttype: DamageType\n\t/** A basic attack, not an ability */\n\treadonly attack: boolean\n\treadonly crit: boolean\n\t/** The ability that deals it, by id. Left out for a basic attack */\n\treadonly ability?: string\n\t/** Words of the game's own about it, see `DamageOptions.tags` */\n\treadonly tags?: readonly string[]\n\tcancelled: boolean\n}\n\n/**\n * What a hit is multiplied by for the attack's type against the target's armour type (`GameRules.combat.damageTable`),\n * before armour and shields: change `multiplier` to say otherwise. Asked only when the game has a table, or a hook\n * of its own for it\n */\nexport interface DamageMultiplier {\n\treadonly target: Entity\n\treadonly source?: Entity\n\t/** The attack's type, as the attack or the ability said it (`AttackDef.attackType`, `DamageOptions.attackType`) */\n\treadonly attackType?: string\n\t/** The target's armour type (`UnitTypeDef.armourType`) */\n\treadonly armourType?: string\n\t/** A basic attack, not an ability */\n\treadonly attack: boolean\n\tmultiplier: number\n}\n\n/**\n * Damage that was dealt. The target may have died of it\n *\n * @beta\n */\nexport interface AfterDamage {\n\treadonly target: Entity\n\treadonly source?: Entity\n\t/** What came off its health, after armor and shields */\n\treadonly dealt: number\n\t/** The part of that it had health for: overkill left out */\n\treadonly taken: number\n\treadonly type: DamageType\n\treadonly attack: boolean\n\treadonly crit: boolean\n\treadonly ability?: string\n\treadonly tags?: readonly string[]\n}\n\n/**\n * Health about to be given back. Change `amount`, or set `cancelled`\n *\n * @beta\n */\nexport interface BeforeHeal {\n\treadonly target: Entity\n\treadonly source?: Entity\n\tamount: number\n\tcancelled: boolean\n}\n\n/**\n * Something is about to die. Set `prevented` to keep it alive: it is then up to the handler what health it has\n *\n * @beta\n */\nexport interface BeforeDeath {\n\treadonly entity: Entity\n\treadonly killer?: Entity\n\t/** An attack of the killer did it */\n\treadonly attack: boolean\n\t/** It ran out of health, rather than being removed by the rules (felled, expired, cancelled) */\n\treadonly fromDamage: boolean\n\t/** The blow that did it, when it ran out of health */\n\treadonly cause?: DeathCause\n\t/** Why it dies (`DeathReason`): `damage`, or what the rules said (`cancelled`, `expired`, a game's own word) */\n\treadonly reason: DeathReason\n\tprevented: boolean\n}\n\n/**\n * Something dies. In `death` it still stands where it was; in `afterDeath` it is gone from the world\n *\n * @beta\n */\nexport interface Death {\n\treadonly entity: Entity\n\treadonly killer?: Entity\n\treadonly attack: boolean\n\t/** The blow that did it, when it ran out of health: its damage type, the ability, how much too much */\n\treadonly cause?: DeathCause\n\t/** Why it dies (`DeathReason`): `damage`, or what the rules said (`cancelled`, `expired`, a game's own word) */\n\treadonly reason: DeathReason\n\t/**\n\t * What the rules make of the death, for the screen (`'exploded'`, `'burned'`): what the blow says (`AttackDef.how`,\n\t * `AbilityDef.how`) to start with, changed in the `death` hook as the game likes. The view gets it with the death\n\t * (`SessionEvent` `death`) to show it its way (`UnitLook.death`). Nothing when left out\n\t */\n\thow?: string\n}\n\n/**\n * An order about to be given to a unit. Set `rejected` to refuse it\n *\n * @beta\n */\nexport interface BeforeOrder {\n\treadonly entity: Entity\n\treadonly order: Order\n\t/** Added to the end of what it does, rather than in place of it */\n\treadonly queued: boolean\n\trejected: boolean\n}\n\n/**\n * How much a unit wants to attack something, as it looks for a target by itself. Higher is picked first:\n * raise or lower `score`, or make it `-Infinity` to pass the target over. Towers of a tower defense go for\n * the creep furthest along its way like this; a taunt makes everyone go for one unit.\n *\n * Runs for every candidate of every search, which is often: the same object is handed out again and again,\n * so keep nothing of it.\n *\n * @beta\n */\nexport interface TargetScore {\n\tattacker: Entity\n\ttarget: Entity\n\t/** Edge to edge */\n\tdistance: number\n\t/** Attackers like this one (its layer, its reach) the target has already, and how many it has room for (`GameRules.combat.engageRoom`) */\n\tengaged: number\n\troom: number\n\t/** What the engine makes of it: things that fight back first, then the closest, and a full one only when nothing else is near */\n\tscore: number\n}\n\n/**\n * Where an attacker goes to fight a target from: its spot around it (see `engagement.ts`), or the target itself, in\n * `point`, to change. A flank for cavalry, behind for assassins. Asked every time the target moves a little: keep it cheap\n */\nexport interface Approach {\n\treadonly attacker: Entity\n\treadonly target: Entity\n\tpoint: Vec2\n}\n\n/**\n * An ally standing in a unit's way is asked to step aside, to `point` (see `GameRules.movement.makesWay`, `lookAhead`): change\n * where it goes, or make it null to leave it standing. `mover` is on its way, heading the way of `direction`\n *\n * @beta\n */\nexport interface MakeWay {\n\treadonly mover: Entity\n\treadonly other: Entity\n\t/** Where the mover is heading, a unit long */\n\treadonly direction: Vec2\n\tpoint: Vec2 | null\n}\n\n/**\n * A unit is about to go round units standing in its way (`around`), by `point`, which is `longer` ground units more\n * than the `straight` way to the next corner of its path (see `GameRules.movement.goesAround`): change the point, or make it\n * null to have it go straight through, asking them aside. Asked as it comes up to them: keep it cheap\n *\n * @beta\n */\nexport interface Detour {\n\treadonly entity: Entity\n\treadonly around: readonly Entity[]\n\treadonly straight: number\n\treadonly longer: number\n\tpoint: Vec2 | null\n}\n\n/**\n * Units ordered to a point together have their places in a formation worked out (`FormationDef`, `formationPoints`):\n * change any in `points`, by the unit's id, or add or remove some. `units` are those that walk, or those that fly:\n * each is laid out apart\n *\n * @beta\n */\nexport interface Formation {\n\treadonly units: readonly Entity[]\n\treadonly target: Vec2\n\treadonly formation: FormationDef\n\treadonly points: Map<EntityId, Vec2>\n}\n\n/**\n * Whether a structure may be placed. Set `allowed` to false, with a `reason` the player is told\n *\n * @beta\n */\nexport interface CanPlace {\n\treadonly def: UnitTypeDef\n\t/** The ground it would cover */\n\treadonly site: Rect\n\t/** Who would build it. Left out when the engine asks for itself */\n\treadonly player?: PlayerId\n\tallowed: boolean\n\treason?: MessageRef\n}\n\n/**\n * An ability about to go off, before it is paid for. Change what it costs, or call it off with a `reason`.\n * Whether the caster has the mana was already checked against the ability's own cost before it wound up:\n * a lower cost here does not let it cast with less than that\n *\n * @beta\n */\nexport interface BeforeCast {\n\treadonly caster: Entity\n\treadonly ability: AbilityDef\n\treadonly level: number\n\treadonly target?: Entity\n\treadonly point: Vec2\n\t/** What it is cast from, for an item's ability */\n\treadonly item?: ItemInstance\n\tmanaCost: number\n\t/** Seconds until it can be used again */\n\tcooldown: number\n\tcancelled: boolean\n\treason?: MessageRef\n}\n\n/**\n * An ability that went off\n *\n * @beta\n */\nexport interface AfterCast {\n\treadonly caster: Entity\n\treadonly ability: AbilityDef\n\treadonly level: number\n\treadonly target?: Entity\n\treadonly point: Vec2\n\treadonly item?: ItemInstance\n\t/** It went off charged, and spent the charge */\n\treadonly charged: boolean\n}\n\n/**\n * A buff about to be put on, or put on again. Change how long it lasts or how strong it is, or call it off (immunity)\n *\n * @beta\n */\nexport interface BeforeBuff {\n\treadonly target: Entity\n\treadonly buff: BuffDef\n\treadonly source?: Entity\n\tlevel: number\n\t/** Seconds, after tenacity. Infinity for one that stays */\n\tduration: number\n\tcancelled: boolean\n}\n\n/**\n * A buff that came off: it ran out (`expired`), or was taken off. Not called for the buffs of something that dies\n *\n * @beta\n */\nexport interface BuffEnd {\n\treadonly entity: Entity\n\treadonly buff: BuffInstance\n\treadonly expired: boolean\n}\n\n/** @beta */\nexport type ProductionKind = 'unit' | 'upgrade' | 'morph' | 'revive' | 'structure'\n\n/**\n * Something about to be made: a unit trained, an upgrade researched, a building upgraded, a hero brought back,\n * a structure put down by a worker. Change what it costs and how long it takes, or call it off with a `reason`\n *\n * @beta\n */\nexport interface BeforeProduce {\n\treadonly player: PlayerId\n\t/** The building it is made in, or the worker putting down a structure */\n\treadonly producer: Entity\n\treadonly kind: ProductionKind\n\t/** Unit type, upgrade, the type a building becomes, the id of a hero, or a structure type */\n\treadonly id: string\n\tcost: Cost\n\t/** Seconds it takes */\n\ttime: number\n\tcancelled: boolean\n\treason?: MessageRef\n}\n\n/** Every hook, and what its handlers get */\n/**\n * A unit with nothing to do, this tick: no orders. Set `handled` and do what it does instead of what idle units do\n * (fight back, go for enemies that come close, which is only for those that fight): a healer that goes to the\n * wounded, a worker that goes back to work. Asked often: keep it cheap\n *\n * @beta\n */\nexport interface Idle {\n\treadonly entity: Entity\n\treadonly dt: number\n\t/** Whether it fights by itself: it has an attack and is not told to stand down. The engine only does that */\n\treadonly fights: boolean\n\thandled: boolean\n}\n\n/**\n * Whether an attacker may attack a target: what the engine makes of it (its attack's targets, whether they are\n * enemies) is in `allowed`, to change. A buff that lets a unit hit what flies; a truce. Asked very often, the same\n * object handed out again and again: keep nothing of it\n */\nexport interface CanAttack {\n\tattacker: Entity\n\ttarget: Entity\n\tallowed: boolean\n\t/**\n\t * Whether a player told the attacker to attack this one (an attack order): what a game lets of its own side, as a\n\t * deny (`denying`). Never when a unit picks a target by itself or fights back, so nothing turns on its own side\n\t * unless told: a unit looking for a target by itself is not asked about its own side's at all (they are passed over\n\t * before the hook, as most of what stands around a unit in a crowd is its own)\n\t */\n\tordered: boolean\n}\n\n/**\n * An attack going off, as the engine has it: change what it does, or call it off. `target` is left out for an attack\n * at the ground. `splash` is the radius of an attack that hits an area; `projectileSpeed` 0 is a blow, more a shot\n * (`look` what the shot looks like, for the screen). Damage, the critical strike and the miss are already rolled\n */\nexport interface BeforeAttack {\n\treadonly attacker: Entity\n\treadonly target?: Entity\n\treadonly point: Vec2\n\t/** Which of the attacker's attacks goes off, by place (`UnitTypeDef.attacks`) */\n\treadonly weapon: number\n\tdamage: number\n\ttype: DamageType\n\tcrit: boolean\n\tmiss: boolean\n\tsplash?: number\n\tprojectileSpeed: number\n\tlook?: string\n\t/** Words of the game's own about it, which the damage carries, see `DamageOptions.tags` */\n\ttags?: string[]\n\t/** How what it kills dies, for the screen (`AttackDef.how`, worked out for this blow): changed as the game likes */\n\thow?: string\n\tcancelled: boolean\n}\n\n/**\n * The stats of an entity being added up, once what the engine knows of (its type, levels, research, items, buffs) is\n * in: `add` more, as a stat change (`{ stats: { armor: 2 } }`, `{ percent: { moveSpeed: 0.1 } }`). Asked only when\n * something they come from changed: call `invalidateStats` when what a handler reads changes\n */\nexport interface StatsHook {\n\treadonly entity: Entity\n\t/** What its type starts with */\n\treadonly base: Readonly<Stats>\n\tadd(change: StatChange, times?: number): void\n}\n\n/**\n * Whether an ability can be used now: what the engine makes of it (level, cooldown, mana, silence) in `refusal`, to\n * clear (\"free while Clearcasting\") or to set (\"not while carrying the flag\"). The cost itself is `beforeCast`'s: one\n * that is let through for free sets its `manaCost` to 0 there too. The player's screen is told what this decided for\n * the abilities of their own units\n */\nexport interface CanCast {\n\treadonly caster: Entity\n\treadonly ability: AbilityDef\n\treadonly level: number\n\t/** What it is used from, for an item's ability */\n\treadonly item?: ItemInstance\n\trefusal?: MessageRef\n}\n\n/**\n * Whether an ability may be used on a target: what the engine makes of it (the ability's `targets`) in `refusal`, to\n * clear (\"can target allied buildings below half health\") or to set. The screen only knows the declared targets: what\n * this changes, the simulation says when the order comes\n */\nexport interface CanTarget {\n\treadonly caster: Entity\n\treadonly ability: AbilityDef\n\treadonly target: Entity\n\trefusal?: MessageRef\n}\n\n/**\n * Whether a team sees an entity of someone else's: what the fog and invisibility make of it in `visible`, to change.\n * Units in brush seen only from up close; a watchtower. Asked very often: keep it cheap\n */\nexport interface Visible {\n\treadonly entity: Entity\n\treadonly team: number\n\tvisible: boolean\n}\n\n/**\n * Whether a player may make something, as far as what it requires goes: a unit, a level of research (`level`), what a\n * building upgrades to, a structure. What the engine makes of it (the finished buildings it requires: `missing`) is in\n * `refusal`, to clear or set: \"needs Blacksmith upgrade 2\", \"needs a level 5 hero\", \"locked until the objective\". The\n * player's screen is told what this decided, for what they could make\n */\nexport interface Requirement {\n\treadonly player: PlayerId\n\treadonly kind: 'unit' | 'upgrade'\n\treadonly id: string\n\t/** The level being researched, for an upgrade */\n\treadonly level?: number\n\t/** Required building types the player does not have */\n\treadonly missing: readonly string[]\n\trefusal?: MessageRef\n}\n\n/**\n * Whether a player may make a unit type or research an upgrade at all, before what it requires (see `isAvailable`):\n * by default (`available`), what is of no race or of theirs (`race`). Set it otherwise for a game's own way: what a\n * mode takes away, a roster that grows as a campaign goes, a unit only one player may have. What is not available is\n * not on the player's buttons, and an order for it is refused; their screen is told where this decided otherwise\n *\n * @beta\n */\nexport interface Available {\n\treadonly player: PlayerId\n\treadonly kind: 'unit' | 'upgrade'\n\treadonly id: string\n\t/** The race the player plays, if the game has races */\n\treadonly race: string | undefined\n\tavailable: boolean\n}\n\n/**\n * A player about to ping the map or say a line (see `ping`, `chat`): change the words (`text`) or who hears them (`to`),\n * or call it off: a muted player, a word filter, no talking in a cinematic. On the rules' side, for every screen alike\n */\nexport interface BeforeTalk {\n\treadonly player: PlayerId\n\treadonly kind: 'ping' | 'chat'\n\t/** A line's words */\n\ttext?: string\n\t/** Who a line or a ping is for */\n\tto?: ChatAudience\n\t/** Where a ping is, and of what kind */\n\treadonly point?: Vec2\n\treadonly pingKind?: string\n\tcancelled: boolean\n}\n\n/**\n * Resources about to be given to an ally (see `give`): change how much arrives (`received`), or call it off with a\n * `reason`: no trading in the first minutes, a cap on what goes to one player\n */\nexport interface BeforeTrade {\n\treadonly from: PlayerId\n\treadonly to: PlayerId\n\treadonly resource: string\n\treadonly sent: number\n\treceived: number\n\tcancelled: boolean\n\treason?: MessageRef\n}\n\n/**\n * A player is about to give up (see `surrender`): call it off with a `reason`, as a game that does not let them before a time\n *\n * @beta\n */\nexport interface BeforeSurrender {\n\treadonly player: PlayerId\n\tcancelled: boolean\n\treason?: MessageRef\n}\n\n/**\n * A player asks for a pause (see `askPause`): how many they have left before this one (`left`), and how long it lasts\n * at most (`seconds`, which can be changed); call it off with a `reason`\n *\n * @beta\n */\nexport interface BeforePause {\n\treadonly player: PlayerId\n\treadonly left: number\n\tseconds: number\n\tcancelled: boolean\n\treason?: MessageRef\n}\n\n/**\n * A player's cap of a pool of supply, once what their buildings provide is added up (see the supply system): change\n * `cap` (a starting amount, an upgrade, a rule of the game's own). The game's most (`GameRules.supply.max`, a pool's\n * `max`) still holds after\n *\n * @beta\n */\nexport interface SupplyCap {\n\treadonly player: PlayerId\n\t/** `supply` for the one there always is, or the name of one of the game's own (`GameRules.supply.pools`) */\n\treadonly pool: string\n\tcap: number\n}\n\n/**\n * Whether a worker may gather from a resource: by default, a resource of a kind it gathers (`harvester.kinds`). Refuse\n * it for a game's own rule: a mine only its owner's cursed mine stands on, a tree of a sacred grove. Asked when it is\n * told to, and of every resource it would go on to by itself\n *\n * @beta\n */\nexport interface CanHarvest {\n\treadonly worker: Entity\n\treadonly source: Entity\n\tallowed: boolean\n\t/** What the player is told when it is refused */\n\treason?: MessageRef\n}\n\n/** Resources a worker hands in: change `amount` (more from mines near the keep), or call it off */\nexport interface BeforeDeposit {\n\treadonly worker: Entity\n\treadonly player: PlayerId\n\treadonly kind: string\n\tamount: number\n\tcancelled: boolean\n}\n\n/** An item about to be bought at a shop: change what it costs, or call it off with a `reason` */\nexport interface BeforeBuy {\n\treadonly buyer: Entity\n\treadonly shop: Entity\n\treadonly item: string\n\tcost: Cost\n\tcancelled: boolean\n\treason?: MessageRef\n}\n\n/** An item about to be picked up off the ground (`ground` its id there): call it off with a `reason` */\nexport interface BeforePickUp {\n\treadonly entity: Entity\n\treadonly item: string\n\treadonly ground: number\n\tcancelled: boolean\n\treason?: MessageRef\n}\n\n/** An item about to be put down: call it off with a `reason` (a cursed blade) */\nexport interface BeforeDrop {\n\treadonly entity: Entity\n\treadonly item: ItemInstance\n\tcancelled: boolean\n\treason?: MessageRef\n}\n\n/** Experience about to go to a hero: change `amount` (the killer gets more), or make it 0. `from` is what was killed, when that is where it comes from */\nexport interface BeforeXp {\n\treadonly hero: Entity\n\treadonly from?: Entity\n\tamount: number\n}\n\n/** Whether a hero may put a point into an ability: what the engine makes of it in `allowed`, to change. The screen hears of it with what the hero can learn */\nexport interface CanLearn {\n\treadonly hero: Entity\n\treadonly ability: string\n\tallowed: boolean\n}\n\n/** Something was made: a unit trained (`unit`), research done (`level`), a building upgraded, a hero brought back */\nexport interface Produced {\n\treadonly producer: Entity\n\treadonly kind: ProductionKind\n\treadonly id: string\n\treadonly unit?: Entity\n\treadonly level?: number\n}\n\n/**\n * Something that has just become another type where it stands (`morph`): a building upgraded, a unit transformed. Its\n * new type's parts are set (stats, abilities, slots, and every `Component.onSpawn` of a part it did not have yet): what\n * a pack gives it of its own for the type it is now, as the heroes pack makes a hero of what became a hero's type and\n * stocks what became a shop. Run before the `entityMorphed` event\n *\n * @beta\n */\nexport interface Morphed {\n\t/** What changed type, as it is now */\n\treadonly entity: Entity\n\t/** The type it was */\n\treadonly from: string\n}\n\n/**\n * What was placed on a map, and the entity it has become\n *\n * @beta\n */\nexport interface FromMapObject {\n\treadonly entity: Entity\n\t/** As the map has it: where, whose, its name */\n\treadonly object: Readonly<MapObject>\n\t/** The game's own fields for it (see `defineMapField`), with what was not set at its default */\n\treadonly data: Readonly<Record<string, unknown>>\n}\n\n/**\n * A camp that was placed on a map, and the camp it has become\n *\n * @beta\n */\nexport interface FromMapCamp {\n\treadonly camp: Camp\n\treadonly from: Readonly<MapCamp>\n\t/** The game's own fields for camps, see `FromMapObject.data` */\n\treadonly data: Readonly<Record<string, unknown>>\n}\n\n/**\n * Something that has died, before it leaves the world: whether it stays (`stays`), out of the world, in the world's\n * entities, to be brought back. No when nothing says so; the heroes pack says yes for a hero (`withHeroes`), and a\n * handler after it (a higher `priority`) can say no for a game where heroes fall for good\n *\n * @beta\n */\nexport interface FallenHero {\n\t/** What died */\n\treadonly entity: Entity\n\t/** What killed it, when something did */\n\treadonly killer?: Entity\n\t/** Whether it stays, out of the world, to be brought back: no, unless a handler says yes */\n\tstays: boolean\n}\n\n/**\n * A region of a map, and the area it has become\n *\n * @beta\n */\nexport interface FromMapRegion {\n\treadonly area: AreaDef\n\treadonly region: Readonly<MapRegion>\n\t/** The game's own fields for regions, see `FromMapObject.data` */\n\treadonly data: Readonly<Record<string, unknown>>\n}\n\n/**\n * A world made from a map, everything the map places in it there and every race's start done: what a pack or the game\n * starts of its own from the map's data, as the map objectives pack gives the objectives a map gives at the start\n * (`mapObjectives`). Not for a world loaded from a save, which has them already\n *\n * @beta\n */\nexport interface FromMap {\n\t/** The map it was made from */\n\treadonly map: Readonly<GameMap>\n}\n\n/** @beta */\nexport interface HookEvents {\n\tbeforeDamage: BeforeDamage\n\tdamageMultiplier: DamageMultiplier\n\tafterDamage: AfterDamage\n\tbeforeHeal: BeforeHeal\n\tbeforeDeath: BeforeDeath\n\tdeath: Death\n\tafterDeath: Death\n\t/** Whether what died stays in the world's entities, out of the world, to be brought back (`FallenHero`). @beta */\n\tfallenHero: FallenHero\n\t/**\n\t * Something just made, its type's parts set (abilities, an inventory, an attack), not in the world yet: what a pack\n\t * gives it of its own, as the heroes pack makes a hero of a hero's type (`makeHero`) and stocks a shop. @beta\n\t */\n\tmade: Entity\n\t/** Something became another type where it stands (`morph`): what a pack gives it of its own for the new type (`Morphed`). @beta */\n\tmorphed: Morphed\n\t/** Something came into the world, and is in it now */\n\tspawn: Entity\n\t/** Something left the world for good, at the end of the tick it died in */\n\tremove: Entity\n\tbeforeOrder: BeforeOrder\n\ttargetScore: TargetScore\n\tapproach: Approach\n\tmakeWay: MakeWay\n\tdetour: Detour\n\tformation: Formation\n\tcanPlace: CanPlace\n\tbeforeCast: BeforeCast\n\tafterCast: AfterCast\n\tbeforeBuff: BeforeBuff\n\tbuffEnd: BuffEnd\n\tbeforeProduce: BeforeProduce\n\tidle: Idle\n\tcanAttack: CanAttack\n\tbeforeAttack: BeforeAttack\n\tstats: StatsHook\n\tcanCast: CanCast\n\tcanTarget: CanTarget\n\tvisible: Visible\n\trequirement: Requirement\n\tavailable: Available\n\tbeforeDeposit: BeforeDeposit\n\tcanHarvest: CanHarvest\n\tbeforeTalk: BeforeTalk\n\tbeforeTrade: BeforeTrade\n\tbeforeSurrender: BeforeSurrender\n\tsupplyCap: SupplyCap\n\tbeforePause: BeforePause\n\tbeforeBuy: BeforeBuy\n\tbeforePickUp: BeforePickUp\n\tbeforeDrop: BeforeDrop\n\tbeforeXp: BeforeXp\n\tcanLearn: CanLearn\n\tproduced: Produced\n\t/** Something placed on a map has become an entity, as the world is made from the map: what the game does with its own fields */\n\tmapObject: FromMapObject\n\t/** A camp placed on a map is in the world, see `mapObject` */\n\tmapCamp: FromMapCamp\n\t/** A region of a map is an area of the world, see `mapObject` */\n\tmapRegion: FromMapRegion\n\t/** The world made from a map is all there, about to start (`FromMap`): what a pack starts from the map's own data. @beta */\n\tmapStart: FromMap\n}\n\n/** @beta */\nexport type HookName = keyof HookEvents\n\n/** @beta */\nexport type HookHandler<K extends HookName> = (world: World, event: HookEvents[K]) => void\n\n/**\n * A hook of a game's own, made with `defineHookType`: a moment of its rules others can take part in, the way the\n * engine's hooks are for its own\n *\n * @beta\n */\nexport interface HookKey<T> {\n\treadonly id: string\n\t/** Only there for the type of the event */\n\treadonly event?: T\n}\n\n/**\n * A hook of a game's own: `const lifeLost = defineHookType<{ invader: Entity; lives: number; cancelled: boolean }>('td.lifeLost')`.\n * The game runs it where the moment is (`world.hooks.run(lifeLost, { ... })`) and reads back what the handlers made\n * of the event; handlers are written with `defineHook({ hook: lifeLost, ... })`, by the game or by a mod on it.\n * Ids are shared by every game: give them a prefix of the game's\n *\n * @beta\n */\nexport function defineHookType<T>(id: string): HookKey<T> {\n\treturn { id }\n}\n\n/**\n * A hook: one of the engine's by name, or a game's own\n *\n * @beta\n */\nexport type AnyHook = HookName | HookKey<any>\n\n/**\n * A handler and the hook it is for. Its `id` is how others take it out or put something in its place\n *\n * @beta\n */\nexport type HookDef = {\n\thook: AnyHook\n\tid: string\n\t/** Lower runs first. 0 when left out; handlers with the same priority run in the order they were added */\n\tpriority?: number\n\trun: (world: World, event: any) => void\n}\n\n/**\n * Typed help for writing a hook: `defineHook({ hook: 'death', id: 'bounty', run(world, { entity }) { ... } })`\n *\n * @beta\n */\nexport function defineHook<K extends HookName>(def: { hook: K; id: string; priority?: number; run: HookHandler<K> }): HookDef\n/** @beta */\nexport function defineHook<T>(def: { hook: HookKey<T>; id: string; priority?: number; run: (world: World, event: T) => void }): HookDef\nexport function defineHook(def: HookDef): HookDef {\n\treturn def\n}\n\n/** The name a hook goes by in the lists */\nconst nameOf = (hook: AnyHook): string => (typeof hook === 'string' ? hook : hook.id)\n\ninterface Entry {\n\tid: string\n\tpriority: number\n\trun: (world: World, event: never) => void\n}\n\n/**\n * The handlers of every hook of one world\n *\n * @beta\n */\nexport class Hooks {\n\tprivate readonly lists = new Map<string, Entry[]>()\n\n\tconstructor(private readonly world: World) {}\n\n\t/** Adds a handler. One with the same id on the same hook is replaced */\n\tadd(def: HookDef): void {\n\t\tconst name = nameOf(def.hook)\n\t\tlet list = this.lists.get(name)\n\t\tif (!list) this.lists.set(name, (list = []))\n\t\tconst index = list.findIndex((entry) => entry.id === def.id)\n\t\tconst entry: Entry = { id: def.id, priority: def.priority ?? 0, run: def.run as Entry['run'] }\n\t\tif (index >= 0) list[index] = entry\n\t\telse list.push(entry)\n\t\t// a stable sort: equal priorities keep the order they were added in\n\t\tlist.sort((a, b) => a.priority - b.priority)\n\t}\n\n\tremove(hook: AnyHook, id: string): void {\n\t\tconst list = this.lists.get(nameOf(hook))\n\t\tconst index = list?.findIndex((entry) => entry.id === id) ?? -1\n\t\tif (index >= 0) list!.splice(index, 1)\n\t}\n\n\t/** Whether a hook has any handlers. For hooks run very often, to not even put the event together when nobody listens */\n\thas(hook: AnyHook): boolean {\n\t\treturn (this.lists.get(nameOf(hook))?.length ?? 0) > 0\n\t}\n\n\t/** Ids of the handlers of a hook, in the order they run */\n\thandlers(hook: AnyHook): string[] {\n\t\treturn (this.lists.get(nameOf(hook)) ?? []).map((entry) => entry.id)\n\t}\n\n\t/** Runs the handlers of a hook on the event, in order, and hands the event back for the caller to read */\n\trun<K extends HookName>(hook: K, event: HookEvents[K]): HookEvents[K]\n\trun<T>(hook: HookKey<T>, event: T): T\n\trun(hook: AnyHook, event: unknown): unknown {\n\t\tconst list = this.lists.get(nameOf(hook))\n\t\tif (!list) return event\n\t\tconst name = nameOf(hook)\n\t\tthis.world.trace?.hook(name, list, typeof hook !== 'string', event)\n\t\tfor (let i = 0; i < list.length; i++) {\n\t\t\tconst entry = list[i]\n\t\t\ttry {\n\t\t\t\t;(entry.run as (world: World, event: unknown) => void)(this.world, event)\n\t\t\t} catch (error) {\n\t\t\t\t// what the world says of errors (`World.caught`): it throws, or the handler is switched off and the rest run\n\t\t\t\tthis.world.caught(error, { kind: 'hook', id: entry.id, hook: name })\n\t\t\t\tconst at = list.indexOf(entry)\n\t\t\t\tif (at >= 0) list.splice(at, 1)\n\t\t\t\ti = Math.min(i, at) - 1\n\t\t\t}\n\t\t}\n\t\treturn event\n\t}\n}\n","import { boarded, entityDied, unloaded } from '#engine/engineEvents'\nimport { defineComponent } from './components'\nimport { defineListener } from './events'\nimport { edgeDistance, type Entity, moving } from './entity'\nimport type { Vec2 } from './math'\nimport type { OrderBehavior, OrderInits, System } from './registry'\nimport { defineHook, type HookDef } from './hooks'\nimport { invalidateStats } from './stats'\nimport { halt, moveTo, moveToEntity } from './systems/movement'\nimport type { World } from './world'\nimport { cos, hypot, sin } from './exactMath'\nimport { createOrder, giveOrder } from './orders/queue'\n\n/**\n * What a transport carries, and whether it is near enough the land to let them out: kept for its side to see, the\n * card's unload button reads it (see `UnitTypeDef.transport`)\n *\n * @beta\n */\nexport interface Cargo {\n\tpassengers: number[]\n\t/** There is land within reach to let them out on */\n\tashore: boolean\n}\n\n/** @beta */\nexport const cargo = defineComponent<Cargo>('core.cargo', {\n\treplicate: 'allies',\n\t// a hold, empty, for what carries: what the transports' system goes through (OB5)\n\tonSpawn: (entity) => {\n\t\tif (entity.def.transport) entity.set(cargo, { passengers: [], ashore: false })\n\t}\n})\n\n/**\n * How far from its edge a transport reaches to take someone in, and to let them out on the land\n *\n * @internal\n */\nexport const BOARD_REACH = 1.5\n/** @internal */\nexport const UNLOAD_REACH = 3.5\n/** How much further a boat reaches: the walkable bank stops short of the deep water it floats on */\nconst SHORE_GAP = 2.5\n\n/** How far from its edge a transport takes someone in */\nconst boardReach = (transport: Entity) => BOARD_REACH + (transport.def.naval ? SHORE_GAP : 0)\n\nconst passengersOf = (transport: Entity): number[] => transport.get(cargo)?.passengers ?? []\n\n/**\n * How many more a transport has room for\n *\n * @beta\n */\nexport function roomIn(transport: Entity): number {\n\tconst capacity = transport.def.transport?.capacity ?? 0\n\treturn Math.max(capacity - passengersOf(transport).length, 0)\n}\n\n/**\n * Whether a unit can get into a transport: one of its side's that has room, and a unit that walks. What flies, what\n * sails and what carries others do not get in\n *\n * @beta\n */\nexport function canBoard(world: World, passenger: Entity, transport: Entity): boolean {\n\tif (passenger === transport || !transport.def.transport || !transport.alive || passenger.hidden) return false\n\tif (passenger.def.kind !== 'unit' || !passenger.get(moving) || passenger.flying || passenger.def.naval || passenger.def.transport) return false\n\tif (!world.areAllies(passenger.owner, transport.owner)) return false\n\tconst takes = transport.def.transport.takes\n\tif (takes && !takes(passenger.def)) return false\n\treturn roomIn(transport) > 0\n}\n\n/**\n * Puts a unit into a transport at once, wherever the two are. False when it cannot get in\n *\n * @beta\n */\nexport function board(world: World, passenger: Entity, transport: Entity): boolean {\n\tif (!canBoard(world, passenger, transport)) return false\n\thalt(world, passenger)\n\tworld.setHidden(passenger, true)\n\ttransport.set(cargo, { passengers: [...passengersOf(transport), passenger.id], ashore: transport.get(cargo)?.ashore ?? false })\n\t// one more inside: an armed garrison hits harder\n\tinvalidateStats(world, transport)\n\tworld.events.emit(boarded, { passenger, transport })\n\treturn true\n}\n\n/**\n * The land nearest a point, within reach of it: where what is carried gets out. Nothing out on open water\n *\n * @internal\n */\nexport function shoreNear(world: World, at: Vec2, reach = UNLOAD_REACH): Vec2 | null {\n\treturn world.nav.closestPoint(at, reach)\n}\n\n/**\n * Lets out what a transport carries, on the land nearest it (or nearest `near`, within reach of the transport), spread\n * around it. How many got out: none when there is no land in reach\n *\n * @beta\n */\nexport function unload(world: World, transport: Entity, near?: Vec2): number {\n\tconst passengers = passengersOf(transport)\n\tif (!passengers.length) return 0\n\tconst reach = UNLOAD_REACH + transport.def.radius\n\tconst land =\n\t\t(near && hypot(near.x - transport.pos.x, near.z - transport.pos.z) <= reach ? shoreNear(world, near, 2) : null) ??\n\t\tshoreNear(world, transport.pos, reach)\n\tif (!land) return 0\n\tlet out = 0\n\tpassengers.forEach((id, i) => {\n\t\tconst passenger = world.entities.get(id)\n\t\tif (!passenger) return\n\t\t// a ring around where they come ashore, so they do not all stand on one spot\n\t\tconst turn = (i / Math.max(passengers.length, 1)) * Math.PI * 2\n\t\tconst spread = i === 0 ? 0 : 0.9 + Math.floor(i / 6) * 0.8\n\t\tworld.setHidden(passenger, false, { x: land.x + cos(turn) * spread, z: land.z + sin(turn) * spread })\n\t\tworld.events.emit(unloaded, { passenger, transport })\n\t\tout++\n\t})\n\ttransport.set(cargo, { passengers: [], ashore: true })\n\tinvalidateStats(world, transport)\n\treturn out\n}\n\n/**\n * What `board` keeps: the tick it last set out for its transport\n *\n * @beta\n */\nexport interface BoardState {\n\t/** The tick it last set out for its transport */\n\ttried?: number\n}\n\n/**\n * What `unload` keeps: whether it set its passengers down already\n *\n * @beta\n */\nexport interface UnloadState {\n\t/** It set them down already */\n\tsent?: boolean\n}\n\n/**\n * Getting into a transport: the unit walks to it, as near as the land goes when it is on the water, and gets in once\n * it is within reach. Done when it is in; failed when there is no room, or no way to it\n *\n * @internal\n */\nexport const boardOrder: OrderBehavior<BoardState, OrderInits['board']> = {\n\ttype: 'board',\n\taccepts(world, entity, init) {\n\t\tconst transport = world.get(init.target)\n\t\treturn !!transport && canBoard(world, entity, transport)\n\t},\n\tupdate(world, entity, order) {\n\t\tconst transport = world.get(order.init.target)\n\t\tif (!transport || !canBoard(world, entity, transport)) return 'failed'\n\t\tif (edgeDistance(entity, transport) <= boardReach(transport)) return board(world, entity, transport) ? 'done' : 'failed'\n\t\tconst m = entity.get(moving)!\n\t\tif (m.status === 'moving') return 'running'\n\t\tif (m.status === 'failed' && order.state.tried === world.tick - 1) return 'failed'\n\t\torder.state.tried = world.tick\n\t\t// a boat out on the water: to the shore nearest it\n\t\tif (transport.def.naval) {\n\t\t\tconst shore = shoreNear(world, transport.pos, transport.def.radius + boardReach(transport) + 4)\n\t\t\tif (!shore) return 'failed'\n\t\t\tif (hypot(shore.x - entity.pos.x, shore.z - entity.pos.z) < 0.5) return 'failed'\n\t\t\tmoveTo(world, entity, shore)\n\t\t} else moveToEntity(world, entity, transport, BOARD_REACH * 0.5)\n\t\treturn 'running'\n\t}\n}\n\n/**\n * What `load` keeps: the tick it last set out for its passenger, and where it was then\n *\n * @beta\n */\nexport interface LoadState {\n\t/** The tick it last set out for its passenger */\n\ttried?: number\n\t/** Where it was when it last set out */\n\tfrom?: Vec2\n}\n\n/**\n * Taking a unit in, from the transport's side: it goes to the unit and takes it in once it is within reach. A boat\n * goes as near as the water does; when it can get no nearer, a passenger of its own side is told to come aboard\n * (`board`), and that is done. Failed when there is no room, or the unit cannot get in\n *\n * @internal\n */\nexport const loadOrder: OrderBehavior<LoadState, OrderInits['load']> = {\n\ttype: 'load',\n\taccepts(world, entity, init) {\n\t\tconst passenger = world.get(init.target)\n\t\treturn !!passenger && canBoard(world, passenger, entity)\n\t},\n\tupdate(world, entity, order) {\n\t\tconst passenger = world.get(order.init.target)\n\t\tif (!passenger || !canBoard(world, passenger, entity)) return 'failed'\n\t\tif (edgeDistance(entity, passenger) <= boardReach(entity)) return board(world, passenger, entity) ? 'done' : 'failed'\n\t\tconst m = entity.get(moving)\n\t\tif (!m) return 'failed'\n\t\tif (m.status === 'moving') return 'running'\n\t\tconst from = order.state.from\n\t\t// stopped where it stopped last time: it gets no nearer\n\t\tif (order.state.tried !== undefined && from && hypot(from.x - entity.pos.x, from.z - entity.pos.z) < 0.5) {\n\t\t\tif (!entity.def.naval || passenger.owner !== entity.owner) return 'failed'\n\t\t\tgiveOrder(world, passenger, createOrder(world, { type: 'board', target: entity.id }))\n\t\t\treturn 'done'\n\t\t}\n\t\torder.state.tried = world.tick\n\t\torder.state.from = { x: entity.pos.x, z: entity.pos.z }\n\t\tmoveToEntity(world, entity, passenger, BOARD_REACH * 0.5)\n\t\treturn 'running'\n\t}\n}\n\n/**\n * Letting out what a transport carries: where it is, when there is land in reach; or at a point, sailing (or driving)\n * as near it as it goes first, and letting them out on the land nearest it. Failed when there is no land to let them\n * out on\n *\n * @internal\n */\nexport const unloadOrder: OrderBehavior<UnloadState, OrderInits['unload']> = {\n\ttype: 'unload',\n\taccepts(_world, entity) {\n\t\treturn !!entity.def.transport && passengersOf(entity).length > 0\n\t},\n\tupdate(world, entity, order) {\n\t\tif (!passengersOf(entity).length) return 'done'\n\t\tconst point = order.init.point\n\t\tif (!point || !entity.get(moving)) return unload(world, entity) ? 'done' : 'failed'\n\t\tif (hypot(point.x - entity.pos.x, point.z - entity.pos.z) <= UNLOAD_REACH + entity.def.radius)\n\t\t\treturn unload(world, entity, point) ? 'done' : 'failed'\n\t\tconst m = entity.get(moving)!\n\t\tif (m.status === 'moving') return 'running'\n\t\tif (order.state.sent) return unload(world, entity, point) ? 'done' : 'failed'\n\t\torder.state.sent = true\n\t\tmoveTo(world, entity, point)\n\t\treturn 'running'\n\t}\n}\n\n/** Keeps each transport's word of whether it is near the land, for its card. A few times a second */\nexport const transportSystem: System = {\n\tname: 'transports',\n\tphase: 'cleanup',\n\tevery: 6,\n\t// only what carries (given its hold as it is made: `World.spawn`, `morph`), not every unit and tree (OB5)\n\tover: cargo,\n\teach(world, entity) {\n\t\tif (!entity.def.transport || !entity.alive || entity.scenery) return\n\t\tconst held = entity.get(cargo)!\n\t\tconst ashore = !!shoreNear(world, entity.pos, UNLOAD_REACH + entity.def.radius)\n\t\tif (held.ashore !== ashore) entity.set(cargo, { passengers: held.passengers, ashore })\n\t\t// what got out some other way, or is gone\n\t\tif (held.passengers.some((id) => !world.entities.get(id)?.hidden)) {\n\t\t\tentity.set(cargo, { passengers: held.passengers.filter((id) => world.entities.get(id)?.hidden), ashore })\n\t\t}\n\t}\n}\n\n/** A transport that dies takes down what it carries with it: a boat. A building that falls lets them out */\nexport const transportSank = defineListener({\n\tid: 'core.transportSank',\n\tevent: entityDied,\n\trun(world, { entity, killer }) {\n\t\tif (entity.isStructure) {\n\t\t\tunload(world, entity)\n\t\t\treturn\n\t\t}\n\t\tfor (const id of passengersOf(entity)) {\n\t\t\tconst passenger = world.entities.get(id)\n\t\t\tif (passenger?.alive) world.kill(passenger, killer)\n\t\t}\n\t}\n})\n\n/**\n * An armed garrison (`transport.armed`): it attacks only while someone is inside, and each one inside adds to its attack\n * damage\n *\n * @internal\n */\nexport const garrisonHooks: HookDef[] = [\n\tdefineHook({\n\t\thook: 'canAttack',\n\t\tid: 'emptyGarrison',\n\t\trun(_world, event) {\n\t\t\tif (event.allowed && event.attacker.def.transport?.armed !== undefined && !passengersOf(event.attacker).length) event.allowed = false\n\t\t}\n\t}),\n\tdefineHook({\n\t\thook: 'stats',\n\t\tid: 'garrisonDamage',\n\t\trun(world, { entity, add }) {\n\t\t\tconst armed = entity.def.transport?.armed\n\t\t\tconst inside = armed === undefined ? [] : passengersOf(entity)\n\t\t\tif (!inside.length) return\n\t\t\t// as declared, so much for each; or as the game works it out, from who is inside\n\t\t\tif (typeof armed === 'function') {\n\t\t\t\tconst passengers = inside.map((id) => world.entities.get(id)).filter((passenger): passenger is Entity => !!passenger)\n\t\t\t\tadd({ stats: { attackDamage: armed(world, entity, passengers) } })\n\t\t\t} else if (armed) add({ stats: { attackDamage: armed } }, inside.length)\n\t\t}\n\t})\n]\n","import { constructionOf } from './defs'\nimport { constructionSite } from './systems/construction'\nimport type { Entity } from './entity'\nimport type { Vec2 } from './math'\nimport { canRepair } from './orders/build'\nimport { canHarvest, harvesterOf } from './orders/harvest'\nimport type { OrderInit } from './registry'\nimport { canAttack } from './systems/combat'\nimport { canBoard } from './transport'\nimport type { World } from './world'\nimport { moving, deposit } from './entity'\n\n/**\n * The right-click: picks the order a unit should get for whatever was clicked.\n * Returns undefined when there is nothing sensible for this unit to do.\n */\nexport function smartOrder(world: World, entity: Entity, point: Vec2, target?: Entity): OrderInit | undefined {\n\tif (!entity.get(moving)) return undefined\n\tif (target && target !== entity) {\n\t\tif (canAttack(world, entity, target)) return { type: 'attack', target: target.id }\n\t\t// trees are in the way of those who can bring them down\n\t\tif (target.def.fellable && entity.def.attacks?.some((attack) => attack.fells && attack.ground)) return { type: 'attackGround', target: target.id }\n\t\tconst harvester = harvesterOf(entity)\n\t\tif (harvester) {\n\t\t\tif (target.get(deposit)) return { type: 'harvest', target: target.id }\n\t\t\t// what stands on a resource (a cursed mine) is clicked for it: what is drawn over the mine is what is clicked\n\t\t\tconst under = world.get(target.on)\n\t\t\tif (under?.get(deposit) && canHarvest(world, entity, under)) return { type: 'harvest', target: under.id }\n\t\t\tif (target.def.dropOff && target.owner === entity.owner && target.operational && harvester.carrying > 0) return { type: 'return' }\n\t\t}\n\t\tif (\n\t\t\tentity.def.builds?.length &&\n\t\t\ttarget.has(constructionSite) &&\n\t\t\tconstructionOf(target.def) === 'builder' &&\n\t\t\tworld.areAllies(entity.owner, target.owner)\n\t\t) {\n\t\t\treturn { type: 'construct', target: target.id }\n\t\t}\n\t\tif (entity.def.builds?.length && canRepair(world, entity.owner, target)) return { type: 'repair', target: target.id }\n\t\tif (world.areEnemies(entity.owner, target.owner)) return { type: 'move', point: { x: target.pos.x, z: target.pos.z } }\n\t\t// a transport of their side with room: in they get\n\t\tif (target.def.transport && canBoard(world, entity, target)) return { type: 'board', target: target.id }\n\t\t// a transport clicking one of its side's that can get in: it goes and takes it in\n\t\tif (entity.def.transport && canBoard(world, target, entity)) return { type: 'load', target: target.id }\n\t\t// friends that walk are stayed with, everything else is walked up to\n\t\tif (target.get(moving) && world.areAllies(entity.owner, target.owner)) return { type: 'follow', target: target.id }\n\t\treturn { type: 'move', target: target.id }\n\t}\n\treturn { type: 'move', point }\n}\n","import { chatted as chattedEvent, pinged as pingedEvent } from '#engine/engineEvents'\nimport { defineComponent } from './components'\nimport type { PlayerId } from './entity'\nimport type { Registry } from './registry'\nimport type { Vec2 } from './math'\nimport { engineMessage } from './messages'\nimport type { BeforeTalk } from './hooks'\nimport type { World } from './world'\nimport { replicateEvent } from './replication'\n\n/*\n * What players say to each other, besides the game: pings on the map, and (see `chat`) lines of text. Commands like\n * any other, so that they go over a wire and into a replay; limited in how often, as anyone may send them\n */\n\n/**\n * When each player's last ones of each kind went out (`ping:1`, the world's times): the world's, and saved with it, so\n * that a player who used up the limit is still refused in the game loaded from a save, as in the game that went on\n */\nexport const sent = defineComponent<Record<string, number[]>>('core.talkSent', { default: () => ({}) })\n\n/**\n * Whether a player may send another of a kind now: and counts it, when they may\n *\n * @beta\n */\nexport function allowed(world: World, player: PlayerId, kind: string, limit: { most: number; within: number }): boolean {\n\tconst byPlayer = world.state(sent)\n\tconst key = `${kind}:${player}`\n\tconst times = (byPlayer[key] ?? []).filter((time) => world.time - time < limit.within)\n\tbyPlayer[key] = times\n\tif (times.length >= limit.most) return false\n\ttimes.push(world.time)\n\treturn true\n}\n\n/**\n * The kinds of ping hero arena games have: a game's are its rules' (`GameRules.talk.pings.kinds`), `look` first\n *\n * @beta\n */\nexport const PING_KINDS = ['look', 'danger', 'assist', 'onMyWay'] as const\n/**\n * A kind of ping: one of `GameRules.talk.pings.kinds`\n *\n * @beta\n */\nexport type PingKind = string\n\n/**\n * Whether the rules let a player say this (`beforeTalk`): the event as the handlers left it, or nothing when one of\n * them called it off\n */\nfunction heard<T extends Omit<BeforeTalk, 'cancelled'>>(world: World, talk: T): (T & { cancelled: boolean }) | undefined {\n\tconst event = { ...talk, cancelled: false }\n\tif (world.hooks.has('beforeTalk')) world.hooks.run('beforeTalk', event)\n\treturn event.cancelled ? undefined : event\n}\n\n/**\n * The kinds of ping a game's rules let go (`GameRules.talk.pings.kinds`), as they are now: its list, or what it works\n * out from the registry (a file of the game's the editor writes)\n *\n * @beta\n */\nexport function pingKinds(registry: Registry): readonly string[] {\n\tconst { kinds } = registry.rules.talk.pings\n\treturn typeof kinds === 'function' ? kinds(registry) : kinds\n}\n\n/**\n * A player marks a spot of the map (`pinged`) for their allies (`to: 'allies'`, when left out) or for everyone\n * (`'all'`): told to them and to who watches, as sessions do. Of a kind the game's rules have\n * (`GameRules.talk.pings.kinds`), as many in a while as they let (`GameRules.talk`), and as the `beforeTalk` hook lets it,\n * which may change who hears it\n *\n * @beta\n */\nexport function ping(\n\tworld: World,\n\tplayer: PlayerId,\n\tpoint: Vec2,\n\tkind: string = pingKinds(world.registry)[0] ?? 'look',\n\tto: string = 'allies',\n\tby?: string\n): void {\n\tif (!pingKinds(world.registry).includes(kind)) return\n\tif (!isAudience(to)) return\n\tif (!allowed(world, player, 'ping', world.rules.talk.pings)) return world.message(player, engineMessage('tooManyPings'))\n\tconst event = heard(world, { player, kind: 'ping', point, pingKind: kind, to })\n\tif (!event) return\n\tworld.events.emit(pingedEvent, { player, point: { x: point.x, z: point.z }, kind, to: event.to ?? to, ...watcher(to, by) })\n}\n\n/** Whether a word is who a line or a ping is for */\nconst isAudience = (to: string): to is ChatAudience => to === 'allies' || to === 'all' || to === 'observers'\n\n/** How long the name of who watches may be, as their lines say it */\nconst WATCHER_NAME = 24\n\n/** The name of who watches, as their line or ping says it: only theirs, to who watches */\nconst watcher = (to: string, by: string | undefined) => (to === 'observers' && by?.trim() ? { by: by.trim().slice(0, WATCHER_NAME) } : {})\n\n/**\n * How long a line may be, unless the game's rules say otherwise (`GameRules.talk`)\n *\n * @internal\n */\nexport const CHAT_LENGTH = 160\n\n/**\n * Who a line of chat or a ping is for: the player's side, everyone in the game, or who watches alone (`observers`:\n * what one who watches says, which no player hears; a host gives every line of theirs this, `SessionHost`)\n *\n * @beta\n */\nexport type ChatAudience = 'allies' | 'all' | 'observers'\n\n/**\n * A player says a line (`chatted`): to their side, or to everyone, and to who watches either way. Spaces run\n * together, and cut to the game's length (`GameRules.talk`); nothing for an empty line, a message for too many in a\n * while; and as the `beforeTalk` hook lets it, which may change the words or who hears them\n *\n * @beta\n */\nexport function chat(world: World, player: PlayerId, text: string, to: string = 'allies', by?: string): void {\n\tif (!isAudience(to)) return\n\tconst said = text.replace(/\\s+/g, ' ').trim().slice(0, world.rules.talk.lines.length)\n\tif (!said) return\n\tif (!allowed(world, player, 'chat', world.rules.talk.lines)) return world.message(player, engineMessage('tooManyLines'))\n\tconst event = heard(world, { player, kind: 'chat', text: said, to })\n\tif (!event?.text) return\n\tworld.events.emit(chattedEvent, { player, text: event.text, to: event.to ?? to, ...watcher(to, by) })\n}\n\n/** Whether a screen hears what was said or pinged: everyone what is to all, who watches everything, a side its own; what who watches says, only who watches */\nconst hears = (to: ChatAudience, player: PlayerId, view: { observer: boolean; isAlly(player: PlayerId): boolean }) =>\n\tto === 'observers' ? view.observer : to === 'all' || view.observer || view.isAlly(player)\n\n/** A ping: to everyone where it is to all, else to the pinger's side; one who watches pinged, to who watches */\nexport const toldPing = replicateEvent(pingedEvent, 'ping', ({ player, point, kind, to, by }, view) =>\n\thears(to, player, view) ? { type: 'ping', player, x: point.x, z: point.z, kind, to, ...(by !== undefined && { by }) } : undefined\n)\n\n/** A line of chat: to everyone where it is to all, else to the speaker's side; one who watches said it, to who watches */\nexport const toldChat = replicateEvent(chattedEvent, 'chat', ({ player, text, to, by }, view) =>\n\thears(to, player, view) ? { type: 'chat', player, text, to, ...(by !== undefined && { by }) } : undefined\n)\n","import { exchanged as exchangedEvent, traded as tradedEvent } from '#engine/engineEvents'\nimport type { PlayerId } from './entity'\nimport { engineMessage } from './messages'\nimport { earn, spend } from './player'\nimport type { BeforeTrade } from './hooks'\nimport type { World } from './world'\n\n/*\n * Allies helping each other: a player gives some of what they have to an ally, less what the game's rules take\n * (`GameRules.economy.tradeTax`), as the classic allies menu does. A command like any other. And a market: a player\n * trades one resource of theirs for another at a rate (`exchange`, the `exchange` effect, `presetMarket`)\n */\n\n/**\n * Gives `amount` of a resource from one player to an ally (`traded`), both told. Nothing to who is not an ally, more\n * than the giver has, or a resource the game does not have; and as the `beforeTrade` hook says: how much arrives, or not\n *\n * @beta\n */\nexport function give(world: World, from: PlayerId, to: PlayerId, resource: string, amount: number): void {\n\tif (from === to || !world.players.has(to) || !world.registry.resource(resource)) return\n\tconst receiver = world.player(to)\n\tif (receiver.neutral || !world.areAllies(from, to)) return world.message(from, engineMessage('notAnAlly'))\n\tconst sent = Math.floor(amount)\n\tif (sent <= 0) return\n\tconst purse = world.player(from).resources\n\tif ((purse[resource] ?? 0) < sent) return world.message(from, engineMessage('notEnough', { resource }))\n\t// the game's say: how much arrives, or none of it\n\tconst trade = { from, to, resource, sent, received: Math.floor(sent * (1 - (world.rules.economy.tradeTax ?? 0))), cancelled: false } as BeforeTrade\n\tif (world.hooks.has('beforeTrade')) world.hooks.run('beforeTrade', trade)\n\tif (trade.cancelled) return world.message(from, trade.reason ?? engineMessage('cannotDoThat'))\n\tconst received = Math.max(Math.floor(trade.received), 0)\n\tpurse[resource] = (purse[resource] ?? 0) - sent\n\tearn(receiver.resources, resource, received)\n\tworld.events.emit(tradedEvent, { from, to, resource, sent, received })\n\tworld.message(from, engineMessage('sent', { amount: sent, resource, player: receiver.name }), 'info')\n\tworld.message(to, engineMessage('received', { amount: received, resource, player: world.player(from).name }), 'info')\n}\n\n/**\n * Shares with an ally, or no longer: control of the player's units (`shareControl`), and what the player's team sees\n * (`shareVision`, when the ally is of another team: a team sees as one already). Nothing for who is not an ally\n *\n * @beta\n */\nexport function shareWith(world: World, player: PlayerId, ally: PlayerId, what: { vision?: boolean; control?: boolean }): void {\n\tif (player === ally || !world.players.has(ally)) return\n\tif (world.player(ally).neutral || !world.areAllies(player, ally)) return world.message(player, engineMessage('notAnAlly'))\n\tconst sameTeam = world.player(player).team === world.player(ally).team\n\tworld.sides.share(player, ally, { control: what.control, vision: sameTeam ? undefined : what.vision })\n}\n\n/**\n * Trades `amount` of one resource of a player's (`sold`) for another (`bought`) at a rate: `rate` of it for each one\n * sold, rounded down (`exchanged`), the player told. What the `exchange` effect does (a marketplace's ability,\n * `presetMarket`), for a game's own rules. Nothing of a resource the game does not have, of one for itself, or more\n * than the player has. Gives back how much came\n *\n * @beta\n */\nexport function exchange(world: World, player: PlayerId, sold: string, bought: string, amount: number, rate: number): number {\n\tif (sold === bought || !world.players.has(player) || !world.registry.resource(sold) || !world.registry.resource(bought)) return 0\n\tconst sent = Math.floor(amount)\n\tif (sent <= 0 || !(rate > 0)) return 0\n\tconst purse = world.player(player).resources\n\tif ((purse[sold] ?? 0) < sent) {\n\t\tworld.message(player, engineMessage('notEnough', { resource: sold }))\n\t\treturn 0\n\t}\n\t// a hair over, so that a rate written as a decimal (100 at 0.29) comes to what it says and not one under\n\tconst received = Math.floor(sent * rate + 1e-9)\n\t// what was sold counts as spent, as the score has it\n\tspend(world, player, { [sold]: sent }, 'trade', bought)\n\tearn(purse, bought, received)\n\tworld.events.emit(exchangedEvent, { player, sold, sent, bought, received })\n\tworld.message(player, engineMessage('exchanged', { amount: sent, resource: sold, received, for: bought }), 'info')\n\treturn received\n}\n","import { gameOver, playerDefeated } from '#engine/engineEvents'\nimport type { System } from '#engine/registry'\nimport type { World } from '#engine/world'\nimport { engineMessage } from '#engine/messages'\nimport { snapshotPart } from '../replication'\n\n/** Puts a player out of the game: they are told, and see the whole map from then on */\nexport function defeat(world: World, playerId: number): void {\n\tconst player = world.player(playerId)\n\tplayer.defeated = true\n\t// nothing left to hide from someone who is out\n\tworld.fog.setRevealed(player.team, world.sides.teamDefeated(player.team))\n\tworld.events.emit(playerDefeated, player)\n\tworld.message(playerId, engineMessage('defeated'), 'info')\n}\n\n/**\n * The rule of a melee game: whoever has no building left is out, and the last team in the game wins.\n * Players only take part once they have had a building, so a world with nothing but a few units\n * in it, like most tests, has no losers. Game modules with other ways to win bring their own system.\n *\n * @beta\n */\nexport const lastTeamStanding: System = {\n\tname: 'victory',\n\tphase: 'cleanup',\n\t// a look at who is still in the game, twice a second or so\n\tevery: 15,\n\tupdate(world) {\n\t\tif (world.winner !== null) return\n\n\t\tconst buildings = new Set<number>()\n\t\tfor (const entity of world.actors.values()) {\n\t\t\tif (entity.alive && entity.isBuilding) buildings.add(entity.owner)\n\t\t}\n\t\tfor (const player of world.players.values()) {\n\t\t\tif (player.neutral || player.creeps || player.defeated) continue\n\t\t\tif (buildings.has(player.id)) player.established = true\n\t\t\telse if (player.established) defeat(world, player.id)\n\t\t}\n\n\t\tconst teams = new Set<number>()\n\t\tconst standing = new Set<number>()\n\t\tfor (const player of world.players.values()) {\n\t\t\tif (!player.established) continue\n\t\t\tteams.add(player.team)\n\t\t\tif (!player.defeated) standing.add(player.team)\n\t\t}\n\t\tif (teams.size < 2 || standing.size !== 1) return\n\t\tconst [winner] = standing\n\t\tworld.winner = winner\n\t\tworld.events.emit(gameOver, { winner })\n\t}\n}\n\n/** Whether the player's team won, lost or plays on (`Snapshot.outcome`): an observer neither wins nor loses */\nexport const outcomePart = snapshotPart(\n\t'outcome',\n\t(view) => {\n\t\tconst { world } = view\n\t\tif (view.observer) return 'playing'\n\t\tconst team = view.team\n\t\treturn world.winner === team ? 'victory' : world.winner !== null || world.sides.teamDefeated(team) ? 'defeat' : 'playing'\n\t},\n\ttrue\n)\n","import { pauseAsked as pauseAskedEvent, playerSurrendered } from '#engine/engineEvents'\nimport { defineComponent } from './components'\nimport type { PlayerId } from './entity'\nimport type { BeforePause, BeforeSurrender } from './hooks'\nimport { engineMessage } from './messages'\nimport { defeat } from './systems/victory'\nimport type { World } from './world'\n\n/*\n * Giving up, and asking for a pause (S53). Giving up is the defeat there already is, reached another way: the player\n * is out, told so, and the others are told who gave up. A pause is asked of whoever runs the world (a server: its host\n * stops stepping it), as the world cannot stop itself and still hear that it is to go on; how many each player has\n * used is kept in the world, so in a save, and the game's hooks decide (`beforeSurrender`, `beforePause`).\n */\n\n/** How many pauses each player has used, by player */\nexport const pauses = defineComponent<{ used: Record<number, number> }>('core.pauses', { default: () => ({ used: {} }) })\n\n/**\n * How many pauses a player has left (`GameRules.talk.pauses.each`, less what they used)\n *\n * @beta\n */\nexport function pausesLeft(world: World, player: PlayerId): number {\n\treturn Math.max(0, world.rules.talk.pauses.each - (world.state(pauses).used[player] ?? 0))\n}\n\n/** Whether a player may give up or pause: one in the game, not out of it, in a game not over */\nfunction playing(world: World, player: PlayerId): boolean {\n\tconst who = world.player(player)\n\treturn !who.neutral && !who.creeps && !who.defeated && world.winner === null\n}\n\n/**\n * A player gives up: out of the game as if beaten, once the game's `beforeSurrender` lets them. The rest of their\n * side plays on; a side with nobody left loses, as the game's own way to win says (`lastTeamStanding` counts one who\n * gave up as one who was in the game)\n *\n * @beta\n */\nexport function surrender(world: World, player: PlayerId): void {\n\tif (!playing(world, player)) return\n\tconst asked: BeforeSurrender = { player, cancelled: false }\n\tif (world.hooks.has('beforeSurrender')) world.hooks.run('beforeSurrender', asked)\n\tif (asked.cancelled) return world.message(player, asked.reason ?? engineMessage('cannotDoThat'))\n\tconst who = world.player(player)\n\t// in the game, for the rule of the last side standing: one who never had a building is counted too\n\twho.established = true\n\tworld.events.emit(playerSurrendered, { player })\n\tdefeat(world, player)\n\tfor (const other of world.players.values()) {\n\t\tif (other.id !== player && !other.neutral) world.message(other.id, engineMessage('surrendered', { player: who.name }), 'info')\n\t}\n}\n\n/**\n * A player asks for the game to be paused: one of their pauses (`GameRules.talk.pauses.each`), for at most\n * `GameRules.talk.pauses.seconds`, once the game's `beforePause` lets them. Whoever runs the world pauses it on the event\n * (`pauseAsked`): a server does; a game played in the page pauses with its menu instead\n *\n * @internal\n */\nexport function askPause(world: World, player: PlayerId): void {\n\tif (!playing(world, player)) return\n\tconst left = pausesLeft(world, player)\n\tif (left <= 0) return world.message(player, engineMessage('noPausesLeft'))\n\tconst asked: BeforePause = { player, left, seconds: world.rules.talk.pauses.seconds, cancelled: false }\n\tif (world.hooks.has('beforePause')) world.hooks.run('beforePause', asked)\n\tif (asked.cancelled) return world.message(player, asked.reason ?? engineMessage('cannotDoThat'))\n\tconst { used } = world.state(pauses)\n\tworld.setState(pauses, { used: { ...used, [player]: (used[player] ?? 0) + 1 } })\n\tworld.events.emit(pauseAskedEvent, { player, seconds: Math.max(0, asked.seconds), left: left - 1 })\n}\n","import type { Entity } from '#engine/entity'\nimport { dist } from '#engine/math'\nimport { acquireInRange, acquireTarget, canAttack, canSee, disengage, engage } from '#engine/systems/combat'\nimport { moveTo } from '#engine/systems/movement'\nimport type { World } from '#engine/world'\nimport { engageWith, isBlocked, shun } from '#engine/engagement'\nimport { moving, fighting } from '../entity'\n\n/** How far past its acquisition range an idle unit chases before walking back */\nconst LEASH = 6\n\n/**\n * What units do without orders: attack enemies that come close, fight back\n * when attacked, and return to where they stood afterwards.\n */\nexport function idle(world: World, entity: Entity, dt: number): void {\n\tconst combat = entity.get(fighting)\n\tconst fights = !!combat && !!entity.def.attacks?.length && !combat.passive\n\t// a game can have units of its own idle their own way, like creeps that guard their camp, or a healer that goes\n\t// to the wounded: those that do not fight too\n\tif (world.hooks.has('idle') && world.hooks.run('idle', { entity, dt, fights, handled: false }).handled) return\n\tif (!fights || !combat) return\n\tconst m = entity.get(moving)\n\n\tif (combat.autoTarget) {\n\t\tconst target = world.get(combat.autoTarget)\n\t\tconst tooFar = !!combat.guard && dist(entity.pos, combat.guard) > world.rules.combat.acquisitionRange(world, entity) + LEASH\n\t\tlet result = tooFar ? 'invalid' : engage(world, entity, target, dt, !!m)\n\t\t// held up on the way to it: something else then\n\t\tif (result === 'chasing' && target && isBlocked(world, entity, target)) {\n\t\t\tshun(world, entity, target)\n\t\t\tresult = 'invalid'\n\t\t}\n\t\tif (result === 'attacking' || result === 'chasing') return\n\n\t\tcombat.autoTarget = 0\n\t\tdisengage(world, entity)\n\t\tconst next = tooFar ? undefined : acquireTarget(world, entity)\n\t\tif (next) {\n\t\t\tengageWith(world, entity, next)\n\t\t\tcombat.autoTarget = next.id\n\t\t} else if (m && combat.guard && dist(entity.pos, combat.guard) > 1) moveTo(world, entity, combat.guard)\n\t\treturn\n\t}\n\n\tif ((world.tick + entity.id) % 4 !== 0) return\n\n\tconst returning = !!combat.guard && m?.status === 'moving'\n\t// on the way back only react to what is right in its face, or it would never get home\n\tlet found = returning ? acquireInRange(world, entity, 1) : acquireTarget(world, entity)\n\tif (!found && combat.lastAttacker) {\n\t\tconst attacker = world.get(combat.lastAttacker)\n\t\tif (attacker && canAttack(world, entity, attacker) && canSee(world, entity, attacker)) found = attacker\n\t\tcombat.lastAttacker = 0\n\t}\n\tif (found) {\n\t\tengageWith(world, entity, found)\n\t\tcombat.guard ??= { x: entity.pos.x, z: entity.pos.z }\n\t\tcombat.autoTarget = found.id\n\t} else if (!returning) {\n\t\tcombat.guard = null\n\t}\n}\n","import { clearOrders } from '#engine/orders/queue'\nimport { orderSays } from '../orders/facts'\nimport { constructionSite } from './construction'\nimport { isStunned } from '#engine/abilities/buffs'\nimport { idle } from '#engine/orders/idle'\nimport { completeOrder } from '#engine/orders/queue'\nimport type { Entity, Order } from '#engine/entity'\nimport type { System } from '#engine/registry'\nimport type { World } from '#engine/world'\nimport { cancelSwing } from './combat'\nimport { halt } from './movement'\nimport { dashing } from '../dashing'\n\n/** Runs the order at the front of every queue */\nexport const orderSystem: System = {\n\tname: 'orders',\n\tphase: 'decide',\n\tupdate(world, dt) {\n\t\tfor (const entity of world.actors.values()) {\n\t\t\t// (a site is a structure's: what moves is never one, and is most of what there is)\n\t\t\tif (!entity.alive || (entity.isStructure && entity.has(constructionSite))) continue\n\t\t\tif (isStunned(world, entity)) {\n\t\t\t\t// out cold: whatever it was doing waits, but what it was keeping up is broken off\n\t\t\t\tif (orderSays(world, entity, 'channelling')) clearOrders(world, entity)\n\t\t\t\thalt(world, entity)\n\t\t\t\tcancelSwing(entity)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// in the air, on a leap or thrown: what it was doing goes on when it is down again\n\t\t\tif (entity.get(dashing)?.height) continue\n\t\t\tconst order = entity.orders[0]\n\t\t\tif (!order) {\n\t\t\t\tif (!entity.hidden) idle(world, entity, dt)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttry {\n\t\t\t\trunOrder(world, entity, order, dt)\n\t\t\t} catch (error) {\n\t\t\t\t// what the world says of errors (`World.caught`): it throws, or the order is taken off the unit\n\t\t\t\tworld.caught(error, { kind: 'order', id: order.type, entity: entity.id })\n\t\t\t\tdropOrder(world, entity, order)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Takes an order that threw off its unit, without asking the order anything more: it stands where it is */\nfunction dropOrder(world: World, entity: Entity, order: Order): void {\n\tentity.removeOrder(order)\n\tif (entity.alive) halt(world, entity)\n}\n\n/** One tick of an order: started when it has not been, and taken off the queue when it is over */\nexport function runOrder(world: World, entity: Entity, order: Order, dt: number): void {\n\tconst behavior = world.registry.order(order.type)\n\tif (!order.started) {\n\t\torder.started = true\n\t\tbehavior.start?.(world, entity, order)\n\t}\n\tconst status = behavior.update(world, entity, order, dt)\n\tif (status !== 'running' && entity.alive) completeOrder(world, entity, order)\n}\n","import { commandHandled as commandHandledEvent, commandRejected as commandRejectedEvent, constructionCancelled } from '#engine/engineEvents'\nimport type { Message } from './messages'\nimport type { RejectedKind } from './errors'\nimport { productionOf } from './systems/productionQueue'\nimport { statsOf } from './stats'\nimport { constructionSite, underConstruction } from './systems/construction'\nimport { isStunned } from './abilities/buffs'\nimport type { Entity, EntityId, PlayerId } from './entity'\nimport { bool, type Checked, type Fields, id, ids, index, Invalid, number, object, oneOf, optional, point, string } from './fields'\nimport { formationPoints } from './formation'\nimport { distSq, type Vec2 } from './math'\nimport { castAside, notReady } from './orders/cast'\nimport { createOrder, giveOrder, interrupt } from './orders/queue'\nimport { giveBack } from './player'\nimport type { OrderInit } from './registry'\nimport { smartOrder } from './smart'\nimport { chat, ping } from './talk'\nimport { give, shareWith } from './trade'\nimport { askPause, surrender } from './endings'\nimport { canAttack } from './systems/combat'\nimport { runOrder } from './systems/orders'\nimport { CINEMATIC_OUTCOMES, cinematicChose, cinematicEnded } from './cinematics'\nimport { cancelProduction, enqueueMorph, enqueueProduction, enqueueResearch } from './systems/production'\nimport type { World } from './world'\nimport { atan2 } from './exactMath'\nimport { fighting, moving } from './entity'\nimport { replicateEvent } from './replication'\n\n/**\n * Commands are everything a player can ask for: plain data, and the only way input reaches the simulation,\n * which keeps the door open for replays, the AI and multiplayer.\n *\n * A command type is a `CommandDef`: the fields it carries, and what it does. What arrives is checked against the\n * fields before anything happens, because on a server it is whatever anyone sends. The engine's own commands are\n * defined the same way as a game module's (`GameModule.commands`).\n *\n * @beta\n */\nexport interface CommandDef<F extends Fields = Fields> {\n\ttype: string\n\t/** What it carries, besides its type and the player who sent it. See `fields.ts` for the checkers */\n\tfields: F\n\t/** Carries it out, for `player`. Whether the player owns or can see what it names is for this to check */\n\texecute(world: World, player: PlayerId, command: Checked<F>): void\n\t/**\n\t * Carried out at once when given between two ticks, a paused game's too, not at the start of the next (`World.issue`):\n\t * talk, a line of chat or a ping, which a game that waits is still to hear. Counted by the talk's own rate, not the\n\t * commands a tick may have; a replay keeps it where it was given (RV14)\n\t */\n\toutsideTick?: boolean\n}\n\ndeclare const modCommandBrand: unique symbol\n\n/**\n * A command of a game module, as its definition's `make` puts it together. Sessions send it like the engine's own\n *\n * @beta\n */\nexport type ModCommand = { readonly type: string; readonly [modCommandBrand]: true }\n\n/**\n * A command type, with `make` to put one together for a session to send\n *\n * @beta\n */\nexport type DefinedCommand<T extends string, F extends Fields> = CommandDef<F> & {\n\ttype: T\n\tmake(fields: Checked<F>): ModCommand\n}\n\n/**\n * Defines a command type, for a game module's `commands`: its type, its fields (see `fields.ts`), and what it does.\n * `command` is typed by the fields.\n *\n * ```ts\n * const sellTower = defineCommand('sellTower', { tower: id }, (world, player, command) => { ... })\n * session.send(sellTower.make({ tower: 12 }))\n * ```\n *\n * @beta\n */\nexport function defineCommand<const T extends string, F extends Fields>(\n\ttype: T,\n\tfields: F,\n\texecute: (world: World, player: PlayerId, command: Checked<F>) => void,\n\toptions: { outsideTick?: boolean } = {}\n): DefinedCommand<T, F> {\n\t// what every command carries of its own: a field of the same name would be written over on the way in\n\tfor (const own of ['type', 'player', 'seq']) {\n\t\tif (own in fields)\n\t\t\tthrow new Error(`Command \"${type}\": \"${own}\" is what every command carries (who sent it, and the like), name the field otherwise`)\n\t}\n\treturn {\n\t\ttype,\n\t\tfields,\n\t\texecute,\n\t\t...(options.outsideTick && { outsideTick: true }),\n\t\tmake: (values) => ({ ...values, type }) as unknown as ModCommand\n\t}\n}\n\n/** What a command looks like on its way in: its type, who sent it, and its fields */\ntype CommandOf<D> = D extends DefinedCommand<infer T, infer F> ? { type: T; player: PlayerId } & Checked<F> : never\n\n/** Part of the cost returned when a construction site is cancelled */\n\n/** The buildings something is to be made in: the selected ones, of which the least busy gets it. `building` for just one */\n/** @internal */\nexport const producers = { building: optional(id), buildings: optional(ids) }\n\n/**\n * Of the player's buildings that were named, the one that will get to something first: finished, able to make it,\n * and with the shortest queue that has room. As in classic RTS games, a group of barracks shares the work. When none has\n * room, the first that could make it, which then says its queue is full\n *\n * @internal\n */\nexport function leastBusy(\n\tworld: World,\n\tplayer: PlayerId,\n\tcommand: { building?: EntityId; buildings?: EntityId[] },\n\tfits: (entity: Entity) => boolean\n): Entity | undefined {\n\tconst named = [...(command.building !== undefined ? [command.building] : []), ...(command.buildings ?? [])]\n\tlet best: Entity | undefined\n\tlet first: Entity | undefined\n\tfor (const entity of owned(world, player, named)) {\n\t\tconst production = productionOf(entity)\n\t\tif (!production || !entity.operational || !fits(entity)) continue\n\t\tfirst ??= entity\n\t\tconst length = production.queue.length\n\t\tif (length < world.rules.production.queue && (!best || length < productionOf(best)!.queue.length)) best = entity\n\t}\n\treturn best ?? first\n}\n\n/**\n * The units a command names that the player may command: their own, and what another shares control of with them\n * (`world.mayCommand`). One of another's, or one there never was, is what their own client never sends: it is\n * turned away (`commandRejected`), and the rest goes on. One that has died meanwhile is let be\n *\n * @internal\n */\nexport function owned(world: World, player: PlayerId, ids: EntityId[]): Entity[] {\n\tconst result: Entity[] = []\n\tfor (const id of ids) {\n\t\tconst entity = world.get(id)\n\t\tif (entity && world.mayCommand(player, entity)) result.push(entity)\n\t\telse if (entity) world.events.emit(commandRejectedEvent, { player, kind: 'notTheirs', reason: `unit ${id} is not theirs` })\n\t\telse if (!world.made(id)) world.events.emit(commandRejectedEvent, { player, kind: 'noSuchUnit', reason: `there is no unit ${id}` })\n\t}\n\treturn result\n}\n\n/** Direction from the middle of a group to where it was sent, so the whole group ends up facing the same way */\nfunction travelDirection(entities: Entity[], point: Vec2): number | undefined {\n\tlet x = 0\n\tlet z = 0\n\tfor (const entity of entities) {\n\t\tx += entity.pos.x\n\t\tz += entity.pos.z\n\t}\n\tx = point.x - x / entities.length\n\tz = point.z - z / entities.length\n\treturn x * x + z * z > 0.04 ? atan2(x, z) : undefined\n}\n\n/**\n * Entity a player may point at: one their team sees, a structure they have seen before, or, on a map explored from\n * the start, a structure of nobody's (a tree, a mine). Commands naming anything else are probing for what the player\n * cannot know.\n *\n * @internal\n */\nexport function known(world: World, player: PlayerId, id: EntityId | undefined): Entity | undefined {\n\tconst entity = world.get(id)\n\tif (!entity) return undefined\n\tconst { team } = world.player(player)\n\tif (world.areAllies(entity.owner, player) || world.isVisibleTo(entity, team)) return entity\n\tif (!entity.isStructure) return undefined\n\tif (world.sight.hasSeen(entity, team)) return entity\n\t// on a map explored from the start, what stands on it and is no player's (trees, mines, the creeps' own) is known\n\t// from the first snapshot, out of sight, as the session tells it (`TeamMemory.startKnown`): an order on it stands\n\tconst owner = world.players.get(entity.owner)\n\treturn world.fog.exploredFromStart && (owner?.neutral || owner?.creeps) ? entity : undefined\n}\n\n/** What a unit is told to do, as a command carries it. See `OrderInit` */\nconst orderInit = object({\n\ttype: string,\n\ttarget: optional(id),\n\tpoint: optional(point),\n\tunitType: optional(string),\n\tability: optional(string),\n\titem: optional(index),\n\tfacing: optional(number),\n\tpath: optional(string),\n\ttowards: optional(oneOf('first', 'last')),\n\tformation: optional(string),\n\ttogether: optional(bool)\n})\n\n// ---- the engine's commands\n\n/** @internal */\nexport const orderCommand = defineCommand(\n\t'order',\n\t{ entities: ids, order: orderInit, queue: optional(bool) },\n\t(world, player, { entities: chosen, order: init, queue = false }) => {\n\t\tif (!world.registry.orders.has(init.type)) return\n\t\tif (init.target && !known(world, player, init.target)) return\n\t\tconst behavior = world.registry.order(init.type)\n\t\tlet entities = owned(world, player, chosen).filter((entity) => !entity.has(constructionSite) && behavior.accepts(world, entity, init))\n\t\t// what is carried and used on the spot does not stop whoever carries it\n\t\tif (init.type === 'cast' && init.item !== undefined && !queue) entities = entities.filter((entity) => !castAside(world, entity, init))\n\t\t// told to attack what it is attacking already: it goes on as it was, and only what was to come after is dropped\n\t\tif (init.type === 'attack' && init.target !== undefined && !queue) {\n\t\t\tentities = entities.filter((entity) => {\n\t\t\t\tconst current = entity.orders[0]\n\t\t\t\tif (current?.type !== 'attack' || current.init.target !== init.target) return true\n\t\t\t\tentity.keepOrders(1)\n\t\t\t\treturn false\n\t\t\t})\n\t\t}\n\t\tif (entities.length === 0) return\n\n\t\tconst groupId = world.newId()\n\t\tconst facing = init.facing ?? (init.point && !init.target ? travelDirection(entities, init.point) : undefined)\n\t\t// those who walk line up on the ground, those who fly above it\n\t\tconst points = new Map<EntityId, Vec2>()\n\t\tif (behavior.formation && init.point && !init.target && entities.length > 1) {\n\t\t\tconst id = init.formation ?? world.rules.movement.formation(world, entities, init)\n\t\t\t// a formation nobody knows is no formation: the units go as the rules have them, rather than nowhere\n\t\t\tconst formation = world.registry.formations.has(id)\n\t\t\t\t? world.registry.formation(id)\n\t\t\t\t: world.registry.formation(world.rules.movement.formation(world, entities, init))\n\t\t\tconst flyers = entities.filter((entity) => entity.flying)\n\t\t\tconst walkers = entities.filter((entity) => !entity.flying)\n\t\t\tfor (const [id, point] of formationPoints(world, walkers, init.point, formation)) points.set(id, point)\n\t\t\tfor (const [id, point] of formationPoints(world, flyers, init.point, formation)) points.set(id, point)\n\t\t}\n\t\t// a group that goes together goes at its slowest's pace: what the slowest of them goes, as they are now\n\t\tconst together = init.type === 'move' && !init.target && entities.length > 1 && (init.together ?? false)\n\t\tconst speedCap = together ? Math.min(...entities.map((entity) => statsOf(world, entity).moveSpeed)) : undefined\n\t\tfor (const entity of entities) {\n\t\t\tconst point = points.get(entity.id) ?? init.point\n\t\t\tgiveOrder(world, entity, createOrder(world, { ...init, point, facing, ...(speedCap !== undefined && { speedCap }) }, groupId), queue)\n\t\t}\n\t}\n)\n\n/** @internal */\nexport const rallyCommand = defineCommand('rally', { buildings: ids, point, target: optional(id) }, (world, player, command) => {\n\tconst target = known(world, player, command.target)\n\tfor (const building of owned(world, player, command.buildings)) {\n\t\tconst production = productionOf(building)\n\t\tif (!production) continue\n\t\t// clicking the building itself clears the rally point\n\t\tif (target === building) production.rally = null\n\t\telse production.rally = { point: { x: command.point.x, z: command.point.z }, target: target?.id ?? 0 }\n\t}\n})\n\n/**\n * The right-click: every unit does what makes sense for it, buildings set their rally point\n *\n * @internal\n */\nexport const smartCommand = defineCommand(\n\t'smart',\n\t{ entities: ids, point, target: optional(id), queue: optional(bool), formation: optional(string) },\n\t(world, player, { point, queue, formation, ...command }) => {\n\t\tconst target = known(world, player, command.target)\n\t\tconst entities = owned(world, player, command.entities)\n\t\tconst units = entities.filter((entity) => entity.get(moving))\n\t\tif (units.length === 0) {\n\t\t\trallyCommand.execute(world, player, { buildings: entities.map((entity) => entity.id), point, target: target?.id })\n\t\t\treturn\n\t\t}\n\t\t// units that end up with the same order are commanded together, so they move as a group\n\t\tconst groups = new Map<string, { order: OrderInit; ids: EntityId[] }>()\n\t\tfor (const unit of units) {\n\t\t\tconst order = smartOrder(world, unit, point, target)\n\t\t\tif (!order) continue\n\t\t\tif (formation !== undefined) order.formation = formation\n\t\t\t// moves of a group together, where the rules say (not attack-moves: those fight their way, each as it can)\n\t\t\tif (order.type === 'move' && world.rules.movement.together) order.together = true\n\t\t\tconst key = `${order.type}:${order.target ?? ''}`\n\t\t\tlet group = groups.get(key)\n\t\t\tif (!group) groups.set(key, (group = { order, ids: [] }))\n\t\t\tgroup.ids.push(unit.id)\n\t\t}\n\t\tfor (const group of groups.values()) orderCommand.execute(world, player, { entities: group.ids, order: group.order, queue })\n\t}\n)\n\n/**\n * Attack the target, for whoever can. Everyone else, or without a target: attack-move to the point\n *\n * @internal\n */\nexport const attackCommand = defineCommand(\n\t'attack',\n\t{ entities: ids, point, target: optional(id), queue: optional(bool), formation: optional(string) },\n\t(world, player, { point, queue, formation, ...command }) => {\n\t\tconst target = known(world, player, command.target)\n\t\tconst units = owned(world, player, command.entities).filter((entity) => entity.get(moving) || entity.get(fighting))\n\t\tconst attackers = target ? units.filter((unit) => canAttack(world, unit, target, true)) : []\n\t\tif (target && attackers.length) {\n\t\t\torderCommand.execute(world, player, { entities: attackers.map((unit) => unit.id), order: { type: 'attack', target: target.id }, queue })\n\t\t\treturn\n\t\t}\n\t\torderCommand.execute(world, player, { entities: units.map((unit) => unit.id), order: { type: 'attackMove', point }, queue })\n\t}\n)\n\n/**\n * Use an ability. Abilities that need a target are cast by one unit, the one that can and is closest\n *\n * @internal\n */\nexport const castCommand = defineCommand(\n\t'cast',\n\t{ entities: ids, ability: string, point: optional(point), target: optional(id), queue: optional(bool) },\n\t(world, player, command) => {\n\t\tconst { queue } = command\n\t\tif (!world.registry.abilities.has(command.ability)) return\n\t\tconst ability = world.registry.ability(command.ability)\n\t\tconst target = known(world, player, command.target)\n\t\tif (command.target && !target) return\n\t\tconst init: OrderInit = { type: 'cast', ability: ability.id, target: target?.id, point: command.point }\n\t\tconst behavior = world.registry.order('cast')\n\t\tconst casters = owned(world, player, command.entities).filter((entity) => behavior.accepts(world, entity, init))\n\t\tif (casters.length === 0) return\n\n\t\t// what goes off on the spot goes off now: a move given in the same breath must not get in first\n\t\tconst instant = !queue && !ability.castTime && (ability.target === 'none' || ability.target === 'direction')\n\t\tconst give = (caster: Entity) => {\n\t\t\tconst order = createOrder(world, init)\n\t\t\tgiveOrder(world, caster, order, queue)\n\t\t\tif (instant && !isStunned(world, caster)) runOrder(world, caster, order, 0)\n\t\t}\n\t\tif (ability.target === 'none') {\n\t\t\tfor (const caster of casters) {\n\t\t\t\tif (queue) give(caster)\n\t\t\t\t// on the spot, in the middle of whatever the caster is doing\n\t\t\t\telse if (!notReady(world, caster, ability) && !castAside(world, caster, { ability: ability.id })) give(caster)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tconst aim = target?.pos ?? command.point\n\t\tconst ready = casters.filter((caster) => !notReady(world, caster, ability))\n\t\tconst pool = ready.length ? ready : casters\n\t\tlet best = pool[0]\n\t\tfor (const caster of pool) {\n\t\t\tif (aim && distSq(caster.pos, aim) < distSq(best.pos, aim)) best = caster\n\t\t}\n\t\t// towards somewhere, at once: in the middle of whatever the caster is doing, like the ones cast on the spot\n\t\tif (instant && !notReady(world, best, ability) && castAside(world, best, { ability: ability.id }, command.point)) return\n\t\t// with nobody ready the order still goes out, so the player hears why it failed\n\t\tgive(best)\n\t}\n)\n\n/** @internal */\nexport const autocastCommand = defineCommand('autocast', { entities: ids, ability: string, enabled: bool }, (world, player, command) => {\n\tfor (const entity of owned(world, player, command.entities)) {\n\t\tconst state = entity.abilities.find((ability) => ability.id === command.ability)\n\t\tif (state) state.autocast = command.enabled\n\t}\n})\n\n/**\n * Stops what units are doing, as the classic Stop does: a plain interrupt. They fight what comes near again at once; a\n * unit that is to stand down and take no fights is put in a stance (`stanceCommand`, `withStances`)\n *\n * @beta\n */\nexport const stopCommand = defineCommand('stop', { entities: ids }, (world, player, command) => {\n\tfor (const entity of owned(world, player, command.entities)) interrupt(world, entity)\n})\n\n/** @internal */\nexport const trainCommand = defineCommand('train', { ...producers, unitType: string }, (world, player, command) => {\n\tconst building = leastBusy(world, player, command, (entity) => !!entity.def.trains?.includes(command.unitType))\n\tif (building) enqueueProduction(world, building, command.unitType)\n})\n\n/** @internal */\nexport const researchCommand = defineCommand('research', { ...producers, upgrade: string }, (world, player, command) => {\n\tconst building = leastBusy(world, player, command, (entity) => !!entity.def.researches?.includes(command.upgrade))\n\tif (building) enqueueResearch(world, building, command.upgrade)\n})\n\n/**\n * Upgrades a building into a type it can become: `into`, one of its `upgradesTo`, or the first where none is named\n *\n * @internal\n */\nexport const upgradeBuildingCommand = defineCommand('upgradeBuilding', { building: id, into: optional(string) }, (world, player, command) => {\n\tconst [building] = owned(world, player, [command.building])\n\tif (building) enqueueMorph(world, building, command.into)\n})\n\n/** @internal */\nexport const cancelTrainCommand = defineCommand('cancelTrain', { building: id, index }, (world, player, command) => {\n\tconst [building] = owned(world, player, [command.building])\n\tif (building) cancelProduction(world, building, command.index)\n})\n\n/** @internal */\nexport const cancelConstructionCommand = defineCommand('cancelConstruction', { building: id }, (world, player, command) => {\n\tconst [building] = owned(world, player, [command.building])\n\tconst site = building && underConstruction(building)\n\tif (!site) return\n\tgiveBack(world, player, site.paid ?? building.def.cost, world.rules.production.cancelRefund, 'structure', building.def.id)\n\tworld.events.emit(constructionCancelled, building)\n\tworld.kill(building, undefined, false, 'cancelled')\n})\n\n/** The player skips the line of dialog they hear: a conversation goes on to its next line. See `world.dialog` */\nexport const skipLineCommand = defineCommand('skipLine', {}, (world, player) => world.dialog.skip(player))\n\n/** A player marks a spot of the map for their allies: `look`, `danger`, `assist` or `onMyWay` (see `ping`) */\nexport const pingCommand = defineCommand(\n\t'ping',\n\t{ point, kind: optional(string), to: optional(string), by: optional(string) },\n\t(world, player, command) => ping(world, player, command.point, command.kind, command.to, command.by),\n\t{ outsideTick: true }\n)\n\n/** A player says a line of chat: to `allies` (when left out), or to `all` (see `chat`) */\nexport const chatCommand = defineCommand(\n\t'chat',\n\t{ text: string, to: optional(string), by: optional(string) },\n\t(world, player, command) => chat(world, player, command.text, command.to, command.by),\n\t{ outsideTick: true }\n)\n\n/** A player gives an ally some of a resource they have (see `give`) */\nexport const giveCommand = defineCommand('give', { to: id, resource: string, amount: number }, (world, player, command) =>\n\tgive(world, player, command.to, command.resource, command.amount)\n)\n\n/** A player shares control of their units, or their team's sight, with an ally, or no longer (see `shareWith`) */\nexport const shareCommand = defineCommand('share', { with: id, vision: optional(bool), control: optional(bool) }, (world, player, command) =>\n\tshareWith(world, player, command.with, { vision: command.vision, control: command.control })\n)\n\n/**\n * A player gives up: out of the game, as if beaten (see `surrender`)\n *\n * @internal\n */\nexport const surrenderCommand = defineCommand('surrender', {}, (world, player) => surrender(world, player))\n\n/**\n * A player asks for the game to be paused, one of their pauses (see `askPause`): whoever runs it pauses it\n *\n * @internal\n */\nexport const pauseCommand = defineCommand('pause', {}, (world, player) => askPause(world, player))\n\n/**\n * A player's screen says a cinematic the rules played on it is over, and how (see `cinematic`'s `wait`): sent by the\n * client as the cinematic ends, so that the rules hear it in the same tick on every machine and in a replay\n *\n * @internal\n */\nexport const cinematicCommand = defineCommand('cinematic', { cinematic: string, outcome: oneOf(...CINEMATIC_OUTCOMES) }, (world, player, command) =>\n\tcinematicEnded(world, player, command.cinematic, command.outcome)\n)\n\n/**\n * A player's screen says which answer of a cinematic's choice they picked (C3): heard by the rules in the same tick on\n * every machine and in a replay, as `cinematicChoice`\n *\n * @internal\n */\nexport const cinematicChoiceCommand = defineCommand(\n\t'cinematicChoice',\n\t{ cinematic: string, question: string, choice: string, timedOut: optional(bool) },\n\t(world, player, command) =>\n\t\tcinematicChose(world, { player, cinematic: command.cinematic, question: command.question, choice: command.choice, timedOut: !!command.timedOut })\n)\n\n/**\n * The commands the engine knows, which every game has\n *\n * @beta\n */\nexport const coreCommands = [\n\torderCommand,\n\tsmartCommand,\n\tattackCommand,\n\tcastCommand,\n\tautocastCommand,\n\tstopCommand,\n\ttrainCommand,\n\tresearchCommand,\n\tupgradeBuildingCommand,\n\tcancelTrainCommand,\n\trallyCommand,\n\tcancelConstructionCommand,\n\tskipLineCommand,\n\tpingCommand,\n\tchatCommand,\n\tgiveCommand,\n\tshareCommand,\n\tsurrenderCommand,\n\tpauseCommand,\n\tcinematicCommand,\n\tcinematicChoiceCommand\n] as const\n\n/**\n * The commands a world takes, by who defines them: the engine's (`core`), and each pack's, which adds its own by\n * declaration merging, as the heroes pack does:\n *\n * ```ts\n * declare module '@v12-engine/engine' {\n * \tinterface Commands {\n * \t\tmypack: (typeof myPackCommands)[number]\n * \t}\n * }\n * ```\n *\n * @beta\n */\nexport interface Commands {\n\tcore: (typeof coreCommands)[number]\n}\n\n/**\n * A command a world takes, as it comes in: its type, who sent it, and its fields. The engine's, and its packs'\n * (`Commands`)\n *\n * @beta\n */\nexport type Command = CommandOf<Commands[keyof Commands]>\n\n/**\n * Any command on its way in: the engine's own, or a game module's\n *\n * @beta\n */\nexport type IssuedCommand = (Command | (ModCommand & { player: PlayerId })) & {\n\t/** The sender's own number for it, told back with how it went (`commandHandled`): what a screen waits on */\n\tseq?: number\n}\n\n/** Type and sender, the part every command has */\nconst head = object({ type: string, player: id })\n\n/**\n * Checks a command and carries it out. A command that is not what it says it is (an unknown type, a field missing\n * or of the wrong kind, a player that is not in the game) is turned away with `commandRejected`, and changes nothing\n */\nexport function executeCommand(world: World, raw: unknown): void {\n\tlet def: CommandDef\n\tlet player: PlayerId\n\tlet fields: Checked<Fields>\n\tlet kind: RejectedKind = 'badFields'\n\ttry {\n\t\tconst { type, player: sender } = head(raw, 'command')\n\t\tconst found = world.registry.command(type)\n\t\tkind = 'unknownType'\n\t\tif (!found) throw new Invalid(`there is no command \"${type}\"`)\n\t\tkind = 'noSuchPlayer'\n\t\tif (!world.players.has(sender)) throw new Invalid(`there is no player ${sender}`)\n\t\tkind = 'badFields'\n\t\tdef = found\n\t\tplayer = sender\n\t\tfields = object(def.fields)(raw, '')\n\t} catch (error) {\n\t\tif (!(error instanceof Invalid)) throw error\n\t\tconst { type, player, seq } = (typeof raw === 'object' && raw ? raw : {}) as Record<string, unknown>\n\t\tconst sender = typeof player === 'number' ? player : undefined\n\t\tworld.events.emit(commandRejectedEvent, { player: sender, type: typeof type === 'string' ? type : undefined, kind, reason: error.message })\n\t\tif (sender !== undefined && typeof seq === 'number')\n\t\t\tworld.events.emit(commandHandledEvent, { player: sender, seq, refusal: { key: error.message } })\n\t\treturn\n\t}\n\tconst seq = (raw as { seq?: unknown }).seq\n\t// who is out has no say any more\n\tif (world.player(player).defeated) {\n\t\tif (typeof seq === 'number') world.events.emit(commandHandledEvent, { player, seq, refusal: { key: 'defeated' } })\n\t\treturn\n\t}\n\t// what the rules refuse it with as it is carried out, they tell the player: the first of it is the answer\n\tconst handling = { player, refusal: undefined as Message | undefined }\n\tworld.handling = handling\n\ttry {\n\t\tdef.execute(world, player, fields)\n\t} catch (error) {\n\t\t// what the world says of errors (`World.caught`): it throws, or the command is refused and the tick goes on\n\t\tworld.caught(error, { kind: 'command', id: def.type, player })\n\t\thandling.refusal ??= { key: 'failed' }\n\t} finally {\n\t\tworld.handling = undefined\n\t}\n\tif (typeof seq === 'number') world.events.emit(commandHandledEvent, { player, seq, refusal: handling.refusal })\n}\n\n/** What became of a command: to whoever sent it */\nexport const toldCommand = replicateEvent(commandHandledEvent, 'command', ({ player, seq, refusal }, view) =>\n\tplayer === view.player ? { type: 'command', seq, ...(refusal ? { refusal } : {}) } : undefined\n)\n","import { at } from './defs'\nimport { defineComponent } from './components'\nimport type { Entity, PlayerId } from './entity'\nimport { defineHook, type HookDef } from './hooks'\nimport type { Vec2 } from './math'\nimport { refreshVitals } from './stats'\nimport { defineEffect, type EffectKind } from './abilities/effects'\nimport type { World } from './world'\nimport { cos, hypot, sin } from './exactMath'\nimport { heroOf } from './hero'\nimport { snapshotPart } from './replication'\n\n/*\n * Corpses, and what is brought into the world by a spell: units raised from the dead, and illusions. What dies of flesh\n * leaves a corpse for a while, which spells use up (`raiseDead`); what a spell brings is `summoned`, which dispelling\n * hurts; an illusion is a copy of a unit that deals a part of its damage and takes more, that its side can tell from\n * the real one and nobody else can\n */\n\n/**\n * What is left of a unit that died, for a while (see `corpses`)\n *\n * @beta\n */\nexport interface Corpse {\n\t/** The id the unit had: the screen keeps its body lying for as long as the corpse is there */\n\tid: number\n\ttype: string\n\towner: PlayerId\n\tx: number\n\tz: number\n\t/** When it is gone, in seconds of the game */\n\tuntil: number\n}\n\n/**\n * The corpses of a world. Saved with it\n *\n * @beta\n */\nexport const corpses = defineComponent<Corpse[]>('core.corpses', { default: () => [] })\n\n/**\n * On a unit a spell brought: who brought it. Dispelling hurts what carries it\n *\n * @beta\n */\nexport const summoned = defineComponent<{ by: number }>('core.summoned', { replicate: 'everyone' })\n\n/**\n * On an illusion: whose copy it is, the part of its damage it deals, and how much more it takes. Told to its side\n * only: to everyone else it is the real one\n *\n * @beta\n */\nexport const illusion = defineComponent<{ of: number; dealt: number; taken: number }>('core.illusion', { replicate: 'allies' })\n\n/** Whether a unit leaves a corpse: one of flesh (`UnitTypeDef.corpse`), and not one a spell brought */\n/**\n * How long a unit's corpse lies, in seconds, or nothing for none: a unit of flesh does, for the game's time, unless a\n * spell brought it; its type may say no, or decide for this death (`UnitTypeDef.corpse`)\n */\nfunction corpseTime(world: World, entity: Entity): number | undefined {\n\tif (!entity.isUnit || entity.has(summoned) || entity.has(illusion)) return undefined\n\tconst declared = entity.def.corpse\n\tconst decided = typeof declared === 'function' ? declared(world, entity) : (declared ?? true)\n\tif (decided === false) return undefined\n\tconst seconds = decided === true ? world.rules.combat.corpseTime : decided\n\treturn seconds > 0 ? seconds : undefined\n}\n\n/**\n * Takes up to `most` corpses nearest a point, within `radius`, out of the world, and gives them\n *\n * @beta\n */\nexport function takeCorpses(world: World, point: Vec2, radius: number, most: number): Corpse[] {\n\tconst all = world.state(corpses)\n\tconst near = all\n\t\t.filter((corpse) => hypot(corpse.x - point.x, corpse.z - point.z) <= radius)\n\t\t.sort((a, b) => hypot(a.x - point.x, a.z - point.z) - hypot(b.x - point.x, b.z - point.z))\n\t\t.slice(0, most)\n\tworld.setState(\n\t\tcorpses,\n\t\tall.filter((corpse) => !near.includes(corpse))\n\t)\n\treturn near\n}\n\n/**\n * Corpses rot away in their time. Once a second\n *\n * @internal\n */\nexport const corpseSystem = {\n\tname: 'corpses',\n\tphase: 'cleanup' as const,\n\tevery: 30,\n\tupdate(world: World): void {\n\t\tconst all = world.state(corpses)\n\t\tif (all.some((corpse) => corpse.until <= world.time))\n\t\t\tworld.setState(\n\t\t\t\tcorpses,\n\t\t\t\tall.filter((corpse) => corpse.until > world.time)\n\t\t\t)\n\t}\n}\n\n/**\n * What happens around the dead, and what illusions do: a corpse where a unit of flesh fell; nothing to gain for killing\n * an illusion (see the core hooks of `features.ts`); and an illusion's blows and the blows it takes, changed\n *\n * @internal\n */\nexport const summonHooks: HookDef[] = [\n\tdefineHook({\n\t\thook: 'death',\n\t\tid: 'corpse',\n\t\trun(world, { entity }) {\n\t\t\tconst seconds = corpseTime(world, entity)\n\t\t\tif (seconds === undefined) return\n\t\t\tworld\n\t\t\t\t.state(corpses)\n\t\t\t\t.push({ id: entity.id, type: entity.def.id, owner: entity.owner, x: entity.pos.x, z: entity.pos.z, until: world.time + seconds })\n\t\t}\n\t}),\n\tdefineHook({\n\t\thook: 'beforeDamage',\n\t\tid: 'illusions',\n\t\trun(_world, event) {\n\t\t\tconst dealt = event.source?.get(illusion)?.dealt\n\t\t\tconst taken = event.target.get(illusion)?.taken\n\t\t\tif (dealt !== undefined) event.amount *= dealt\n\t\t\tif (taken !== undefined) event.amount *= taken\n\t\t}\n\t})\n]\n\n/**\n * Whether killing an entity gains its killer nothing: an illusion\n *\n * @beta\n */\nexport const worthless = (entity: Entity) => entity.has(illusion)\n\n/** @internal */\nexport const summonEffects: EffectKind[] = [\n\t/**\n\t * Corpses near where it landed rise as `unit`s of the caster's, for `duration` seconds: `count` of them at most\n\t * (2 when left out), within `radius` (6)\n\t */\n\tdefineEffect(\n\t\t'raiseDead',\n\t\t(context, effect) => {\n\t\t\tconst { world, caster, point, level } = context\n\t\t\tif (!effect.unit) return\n\t\t\tconst lifetime = effect.duration === undefined ? undefined : at(effect.duration, level)\n\t\t\tfor (const corpse of takeCorpses(world, point, at(effect.radius, level, 6), Math.round(at(effect.count, level, 2)))) {\n\t\t\t\tconst risen = world.spawn(effect.unit, caster.owner, corpse, { facing: caster.facing, lifetime })\n\t\t\t\trisen.set(summoned, { by: caster.id })\n\t\t\t}\n\t\t},\n\t\t{ fields: ['unit', 'duration', 'count'] }\n\t),\n\n\t/**\n\t * Copies of the unit it was cast on (the caster, when none) appear around it, `count` of them (1), for `duration`\n\t * seconds (30): they deal `dealt` of its damage (a third) and take `taken` times as much (twice). A hero's\n\t * copies are of its level, with its health and mana as they are\n\t */\n\tdefineEffect(\n\t\t'illusion',\n\t\t(context, effect) => {\n\t\t\tconst { world, caster, level } = context\n\t\t\tconst original = context.target ?? caster\n\t\t\tconst count = Math.round(at(effect.count, level, 1))\n\t\t\tconst lifetime = at(effect.duration, level, 30)\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\tconst angle = (i / count) * Math.PI * 2 + world.rng.next()\n\t\t\t\tconst at2 = { x: original.pos.x + sin(angle) * 1.5, z: original.pos.z + cos(angle) * 1.5 }\n\t\t\t\tconst copy = world.spawn(original.def.id, caster.owner, at2, { facing: original.facing, lifetime })\n\t\t\t\tcopy.set(illusion, { of: original.id, dealt: effect.dealt ?? 1 / 3, taken: effect.taken ?? 2 })\n\t\t\t\tconst was = heroOf(original)\n\t\t\t\tconst hero = heroOf(copy)\n\t\t\t\tif (was && hero) {\n\t\t\t\t\thero.level = was.level\n\t\t\t\t\thero.xp = was.xp\n\t\t\t\t\trefreshVitals(world, copy)\n\t\t\t\t}\n\t\t\t\tcopy.hp = copy.maxHp * (original.hp / original.maxHp)\n\t\t\t\tcopy.mana = Math.min(original.mana, copy.maxMana)\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tfields: [\n\t\t\t\t'count',\n\t\t\t\t'duration',\n\t\t\t\t{ path: 'dealt', kind: 'number', min: 0, hint: 'What of its damage the copies deal: a third when left out' },\n\t\t\t\t{ path: 'taken', kind: 'number', min: 0, hint: 'Times what they are dealt the copies take: twice when left out' }\n\t\t\t]\n\t\t}\n\t)\n]\n\n/** The corpses where the player sees (`Snapshot.corpses`): none to a computer, and left out where there are none */\nexport const corpsesPart = snapshotPart('corpses', (view) => {\n\tif (view.forComputer) return undefined\n\tconst seen = view.world\n\t\t.state(corpses)\n\t\t.filter((corpse) => view.sees(corpse.x, corpse.z))\n\t\t.map(({ id, type, x, z }) => ({ id, type, x, z }))\n\treturn seen.length ? seen : undefined\n})\n","import { clamp, type Vec2 } from './math'\nimport { atan2, hypot } from './exactMath'\n\n/**\n * A spot, and the way it faces: where a wave comes in, where a hero stands, where a camera looks from\n *\n * @beta\n */\nexport interface Spot extends Vec2 {\n\t/** Radians, the way entities face: 0 is along +z */\n\tfacing: number\n}\n\n/**\n * A line on the map, through points in order, with a width: a road, a patrol route, the way a wave walks. What the\n * rules ask of one a game would otherwise write each time: how long it is, where along it something is, how far a\n * point is from it, whether a point is on it\n *\n * @beta\n */\nexport class Path {\n\t/** How far along the path each of its points is */\n\tprivate readonly along: number[]\n\n\tconstructor(\n\t\t/** Its points, in order. Not to be changed: the path works out its length from them once */\n\t\treadonly points: readonly Vec2[],\n\t\t/** How wide it is: a point is on it when it is no more than half of this from its middle */\n\t\treadonly width: number\n\t) {\n\t\tthis.along = [0]\n\t\tfor (let i = 1; i < points.length; i++) this.along.push(this.along[i - 1] + hypot(points[i].x - points[i - 1].x, points[i].z - points[i - 1].z))\n\t}\n\n\t/** How long it is, from its first point to its last */\n\tget length(): number {\n\t\treturn this.along[this.along.length - 1] ?? 0\n\t}\n\n\tget start(): Vec2 {\n\t\treturn { ...this.points[0] }\n\t}\n\n\tget end(): Vec2 {\n\t\treturn { ...this.points[this.points.length - 1] }\n\t}\n\n\t/**\n\t * Where on the path something is that has gone `distance` along it from its start, facing the way it goes. Before\n\t * the start is the start, past the end the end\n\t */\n\tat(distance: number): Spot {\n\t\tconst { points, along } = this\n\t\tif (points.length === 1) return { ...points[0], facing: 0 }\n\t\tconst d = clamp(distance, 0, this.length)\n\t\tlet i = 1\n\t\twhile (i < points.length - 1 && along[i] < d) i++\n\t\tconst a = points[i - 1]\n\t\tconst b = points[i]\n\t\tconst stretch = along[i] - along[i - 1]\n\t\tconst t = stretch > 0 ? (d - along[i - 1]) / stretch : 0\n\t\treturn { x: a.x + (b.x - a.x) * t, z: a.z + (b.z - a.z) * t, facing: atan2(b.x - a.x, b.z - a.z) }\n\t}\n\n\t/** The nearest point of its middle line to a point, and how far along the path that is */\n\tnearest(point: Vec2): { at: Vec2; distance: number; along: number } {\n\t\tconst { points, along } = this\n\t\tif (points.length === 1) return { at: { ...points[0] }, distance: hypot(point.x - points[0].x, point.z - points[0].z), along: 0 }\n\t\tlet best = { at: { ...points[0] }, distance: Infinity, along: 0 }\n\t\tfor (let i = 1; i < points.length; i++) {\n\t\t\tconst a = points[i - 1]\n\t\t\tconst b = points[i]\n\t\t\tconst dx = b.x - a.x\n\t\t\tconst dz = b.z - a.z\n\t\t\tconst lengthSq = dx * dx + dz * dz\n\t\t\tconst t = lengthSq > 0 ? clamp(((point.x - a.x) * dx + (point.z - a.z) * dz) / lengthSq, 0, 1) : 0\n\t\t\tconst at = { x: a.x + dx * t, z: a.z + dz * t }\n\t\t\tconst distance = hypot(point.x - at.x, point.z - at.z)\n\t\t\tif (distance < best.distance) best = { at, distance, along: along[i - 1] + (along[i] - along[i - 1]) * t }\n\t\t}\n\t\treturn best\n\t}\n\n\t/** How far a point is from the middle of the path */\n\tdistanceTo(point: Vec2): number {\n\t\treturn this.nearest(point).distance\n\t}\n\n\t/** Whether a point is on the path: no more than half its width from its middle */\n\tcontains(point: Vec2): boolean {\n\t\treturn this.distanceTo(point) <= this.width / 2\n\t}\n\n\t/** Whether the middle of a cell of the map is on the path: what it paints, and keeps clear */\n\tcontainsCell(cx: number, cz: number): boolean {\n\t\treturn this.contains({ x: cx + 0.5, z: cz + 0.5 })\n\t}\n}\n","import { at } from '#engine/defs'\nimport type { Entity } from '#engine/entity'\nimport { summoned } from '#engine/summons'\nimport type { World } from '#engine/world'\nimport { removeBuff } from './buffs'\nimport { defineEffect, type EffectKind, effectTargets } from './effects'\n\n/*\n * Dispelling and spell immunity. A dispel takes what is good off enemies and what is bad off friends, and hurts what a\n * spell brought into the world; a unit immune to spells is not touched by abilities, those of its friends too, unless\n * an ability says it gets through (`AbilityDef.piercesImmunity`)\n */\n\n/**\n * Takes buffs off a unit, as a dispel does: the good ones of an enemy of `by`, the bad ones of a friend. Those that say\n * they cannot be (`BuffDef.dispellable: false`) stay. How many it took\n *\n * @beta\n */\nexport function dispelBuffs(world: World, entity: Entity, by: Entity): number {\n\tconst enemy = world.areEnemies(by.owner, entity.owner)\n\tlet taken = 0\n\tfor (const instance of [...entity.buffs]) {\n\t\tconst def = world.registry.buff(instance.id)\n\t\tif (!!def.harmful === enemy) continue\n\t\tconst dispellable = typeof def.dispellable === 'function' ? def.dispellable(world, entity, instance, by) : def.dispellable !== false\n\t\tif (!dispellable) continue\n\t\tremoveBuff(world, entity, instance.id)\n\t\ttaken++\n\t}\n\treturn taken\n}\n\n/** @internal */\nexport const dispelEffects: EffectKind[] = [\n\t/**\n\t * Takes the good buffs off enemies and the bad ones off friends, where it lands (`radius`, or the target alone), and\n\t * deals `amount` to every unit there a spell brought (`summoned`), which is magic\n\t */\n\tdefineEffect(\n\t\t'dispel',\n\t\t(context, effect) => {\n\t\t\tconst { world, caster, level } = context\n\t\t\tconst hurt = at(effect.amount, level)\n\t\t\tfor (const entity of effectTargets(context, { ...effect, affects: effect.affects ?? 'all' }, 'enemies')) {\n\t\t\t\tif (!entity.isUnit) continue\n\t\t\t\tdispelBuffs(world, entity, caster)\n\t\t\t\tif (hurt > 0 && entity.has(summoned) && world.areEnemies(caster.owner, entity.owner))\n\t\t\t\t\tworld.damage(entity, hurt, caster, { damageType: 'magic', ability: context.ability.id })\n\t\t\t}\n\t\t},\n\t\t{ fields: ['amount'] }\n\t)\n]\n","/**\n * Buffs: the engine's effects that put one on (`EffectTypes.buff`), switch one on and off (`toggle`), and keep one up\n * around the carrier (`aura`)\n */\nimport { at } from '#engine/defs'\nimport { applyBuff, hasBuff, removeBuff } from '../buffs'\nimport { defineEffect, effectTargets } from '../effects'\n\nexport const buffEffect = defineEffect(\n\t'buff',\n\t(context, effect) => {\n\t\tif (!effect.buff) return\n\t\tconst fallback = context.world.registry.buff(effect.buff).harmful ? 'enemies' : 'allies'\n\t\tfor (const entity of effectTargets(context, effect, fallback)) {\n\t\t\tif (!entity.isUnit) continue\n\t\t\tconst duration = effect.duration === undefined ? undefined : at(effect.duration, context.level)\n\t\t\tapplyBuff(context.world, entity, effect.buff, duration, context.caster, context.level, context.ability.id)\n\t\t\tif (!effect.stack) continue\n\t\t\t// one more of it, as many as the buff allows\n\t\t\tconst instance = entity.buffs.find((carried) => carried.id === effect.buff)\n\t\t\tif (instance) instance.stacks = Math.min((instance.stacks ?? 0) + 1, context.world.registry.buff(effect.buff).maxStacks ?? Infinity)\n\t\t}\n\t},\n\t{ fields: ['buff', 'duration', 'stack'] }\n)\n\n/**\n * Puts `buff` on the caster for as long as it likes, or takes it off when it has it: a stance, burrowing. Cast again to\n * come back out\n */\nexport const toggleEffect = defineEffect(\n\t'toggle',\n\t(context, effect) => {\n\t\tconst { world, caster } = context\n\t\tif (!effect.buff) return\n\t\tif (hasBuff(caster, effect.buff)) removeBuff(world, caster, effect.buff)\n\t\telse applyBuff(world, caster, effect.buff, Infinity, caster, context.level, context.ability.id)\n\t},\n\t{ fields: ['buff'] }\n)\n\n/** auras are kept up by the ability system, there is nothing to do at the moment of casting */\nexport const auraEffect = defineEffect('aura', () => {}, { fields: ['buff'] })\n","/**\n * Damage: the engine's effect that hurts what it reaches (`EffectTypes.damage`)\n */\nimport { at } from '#engine/defs'\nimport { defineEffect, effectTargets } from '../effects'\nimport { scaled } from '../scaled'\n\nexport const damageEffect = defineEffect(\n\t'damage',\n\t(context, effect) => {\n\t\tconst { world, caster, level } = context\n\t\tconst amount = scaled(world, caster, at(effect.amount, level), effect.scaling, level) * (context.share ?? 1)\n\t\t// spells are magic, unless they say otherwise\n\t\t// how what it kills dies, for the screen: the effect's word, or the ability's, decided for each it hits\n\t\tconst { how } = context.ability\n\t\tfor (const entity of effectTargets(context, effect, 'enemies'))\n\t\t\tworld.damage(entity, amount, caster, {\n\t\t\t\tdamageType: effect.damageType ?? 'magic',\n\t\t\t\tability: context.ability.id,\n\t\t\t\thow: effect.how ?? (typeof how === 'function' ? how({ caster, target: entity, level, amount }) : how)\n\t\t\t})\n\t},\n\t{ fields: ['amount', 'scaling', 'damageType', 'how'] }\n)\n","/**\n * Healing and mana: the engine's effects that give back (`EffectTypes.heal`, `mana`)\n */\nimport { manaChanged } from '#engine/engineEvents'\nimport { at } from '#engine/defs'\nimport { defineEffect, effectTargets } from '../effects'\nimport { scaled } from '../scaled'\n\nexport const healEffect = defineEffect(\n\t'heal',\n\t(context, effect) => {\n\t\tconst { world, caster, level } = context\n\t\tconst power = world.rules.combat.healPower(world, caster)\n\t\tconst amount = scaled(world, caster, at(effect.amount, level), effect.scaling, level) * power * (context.share ?? 1)\n\t\tfor (const entity of effectTargets(context, effect, 'allies')) {\n\t\t\tif (entity.isUnit && !entity.def.invulnerable) world.heal(entity, amount, caster)\n\t\t}\n\t},\n\t{ fields: ['amount', 'scaling'] }\n)\n\nexport const manaEffect = defineEffect(\n\t'mana',\n\t(context, effect) => {\n\t\tconst { world, caster, level } = context\n\t\tconst amount = scaled(world, caster, at(effect.amount, level), effect.scaling, level) * (context.share ?? 1)\n\t\tfor (const entity of effectTargets(context, effect, 'allies')) {\n\t\t\tconst given = Math.min(entity.mana + amount, entity.maxMana) - entity.mana\n\t\t\tentity.mana += given\n\t\t\tif (given !== 0) world.events.emit(manaChanged, { entity, amount: given, ability: context.ability.id, source: caster })\n\t\t}\n\t},\n\t{ fields: ['amount', 'scaling'] }\n)\n","/**\n * Missiles: the engine's effect that sends what flies (`EffectTypes.missile`), shot or thrown in an arc; what they do\n * on the way, and where they spring on to, is `updateMissiles`'\n */\nimport { missileSpawned } from '#engine/engineEvents'\nimport { at } from '#engine/defs'\nimport { dist } from '#engine/math'\nimport { atan2, cos, hypot, sin } from '#engine/exactMath'\nimport type { Missile } from '#engine/world'\nimport { defineEffect } from '../effects'\n\nexport const missileEffect = defineEffect(\n\t'missile',\n\t(context, effect) => {\n\t\tconst { world, caster, ability, level, point, target } = context\n\t\tconst aim = effect.homing && target ? target.pos : point\n\t\tconst dx = aim.x - caster.pos.x\n\t\tconst dz = aim.z - caster.pos.z\n\t\tconst length = hypot(dx, dz)\n\t\t// aimed at its own feet: the way it looks then\n\t\tconst heading = length > 0.01 ? atan2(dx, dz) : caster.facing\n\t\tconst count = Math.max(Math.round(at(effect.count, level, 1)), 1)\n\t\tconst range = at(effect.distance, level, effect.toPoint ? Infinity : 10)\n\t\tconst hit = new Set<number>()\n\t\tconst homing = effect.homing && target\n\t\tconst left = homing ? Infinity : effect.toPoint ? Math.min(length, range) : range\n\t\t// thrown in a time of its own: as fast as it takes to come down then, at its target or at the end of its way\n\t\tconst time = effect.arc?.time\n\t\tconst way = homing ? dist(caster.pos, target.pos) : left\n\t\tconst speed = time && time > 0 && Number.isFinite(way) ? way / time : (effect.speed ?? 10)\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst angle = heading + (count > 1 ? (effect.spread ?? 0) * (i / (count - 1) - 0.5) : 0)\n\t\t\tconst missile: Missile = {\n\t\t\t\tid: world.newId(),\n\t\t\t\towner: caster.owner,\n\t\t\t\tsource: caster.id,\n\t\t\t\tability: ability.id,\n\t\t\t\tlevel,\n\t\t\t\tx: caster.pos.x,\n\t\t\t\tz: caster.pos.z,\n\t\t\t\tprevX: caster.pos.x,\n\t\t\t\tprevZ: caster.pos.z,\n\t\t\t\tdx: sin(angle),\n\t\t\t\tdz: cos(angle),\n\t\t\t\tspeed,\n\t\t\t\tleft,\n\t\t\t\tdelay: at(effect.delay, level),\n\t\t\t\tforms: at(effect.delay, level),\n\t\t\t\tradius: at(effect.radius, level, 1),\n\t\t\t\teffect,\n\t\t\t\thit,\n\t\t\t\ttarget: homing ? target.id : 0,\n\t\t\t\ttravelled: 0,\n\t\t\t\tleg: 0,\n\t\t\t\theight: 0,\n\t\t\t\tbounces: 0,\n\t\t\t\tstopped: false\n\t\t\t}\n\t\t\tworld.missiles.push(missile)\n\t\t\tworld.events.emit(missileSpawned, missile)\n\t\t}\n\t},\n\t{\n\t\tfields: ['speed', 'distance', 'count', 'spread', 'homing', 'toPoint', 'delay', 'sight', 'blocked', 'pierce', 'arc', 'bounce', 'effects', 'onEnd']\n\t}\n)\n","/**\n * A side's home (`homeOf`): where its heroes come back (`withRespawn`) and are recalled to (an ability's `teleport` to\n * `home`). Of nothing but the world, so that an ability's effects and the heroes' respawn each read it alone\n */\nimport type { Entity, PlayerId } from './entity'\nimport { distSq, type Vec2 } from './math'\nimport type { World } from './world'\n\n/**\n * A side's home, where its heroes come back and are recalled to: the map's point named `home.<team>` (`home.1`), or\n * else the structure of the player's side nearest `near` (its core, its hall), or else nothing\n *\n * @beta\n */\nexport function homeOf(world: World, player: PlayerId, near?: Vec2): Vec2 | undefined {\n\tconst team = world.player(player).team\n\tconst name = `home.${team}`\n\tif (world.map.points.some((point) => point.name === name)) return world.map.point(name)\n\tlet best: Entity | undefined\n\tlet bestDistance = Infinity\n\tfor (const entity of world.entities.values()) {\n\t\tif (!entity.alive || !entity.isStructure || !world.areAllies(entity.owner, player)) continue\n\t\tconst d = near ? distSq(entity.pos, near) : entity.id\n\t\tif (d < bestDistance) {\n\t\t\tbestDistance = d\n\t\t\tbest = entity\n\t\t}\n\t}\n\treturn best && { x: best.pos.x, z: best.pos.z }\n}\n","/**\n * Moves: the engine's effects that put the caster elsewhere (`EffectTypes.blink`, `teleport`), rush it there (`dash`),\n * or throw what it hits (`knockback`)\n */\nimport { at } from '#engine/defs'\nimport { dashing } from '#engine/dashing'\nimport { moving } from '#engine/entity'\nimport { atan2, hypot } from '#engine/exactMath'\nimport { homeOf } from '#engine/home'\nimport { dist, type Vec2 } from '#engine/math'\nimport type { World } from '#engine/world'\nimport { applyBuff } from '../buffs'\nimport { defineEffect, effectTargets, startDash } from '../effects'\n\n/** How finely the way of a leap is looked over for ground that stands too high */\nconst LEAP_STEP = 0.5\n\n/** The last spot on the way from one place to another before the ground rises above `top` */\nfunction beforeWall(world: World, from: Vec2, to: Vec2, top: number): Vec2 {\n\tconst steps = Math.ceil(dist(from, to) / LEAP_STEP)\n\tlet last = { x: from.x, z: from.z }\n\tfor (let i = 1; i <= steps; i++) {\n\t\tconst t = i / steps\n\t\tconst point = { x: from.x + (to.x - from.x) * t, z: from.z + (to.z - from.z) * t }\n\t\tif (world.terrain.heightAt(point.x, point.z) > top) return last\n\t\tlast = point\n\t}\n\treturn last\n}\n\n/** The caster is somewhere else at once: towards where it was aimed, as far as `distance` lets it */\nexport const blinkEffect = defineEffect(\n\t'blink',\n\t(context, effect) => {\n\t\tconst { world, caster, point, level } = context\n\t\tconst dx = point.x - caster.pos.x\n\t\tconst dz = point.z - caster.pos.z\n\t\tconst length = hypot(dx, dz)\n\t\tif (length < 0.01) return\n\t\tconst step = Math.min(length, at(effect.distance, level, 5))\n\t\tconst aim = { x: caster.pos.x + (dx / length) * step, z: caster.pos.z + (dz / length) * step }\n\t\tconst spot = (caster.flying ? world.air : world.nav).closestPoint(aim, 3) ?? caster.pos\n\t\tworld.place(caster, spot)\n\t\tcaster.prevPos.x = spot.x\n\t\tcaster.prevPos.z = spot.z\n\t\t// where it went is where the ability landed, for whoever draws it\n\t\tpoint.x = spot.x\n\t\tpoint.z = spot.z\n\t},\n\t{ fields: ['distance'] }\n)\n\n/**\n * The caster is somewhere else at once, however far (`to`): its side's home (`homeOf`, a recall), where it was aimed\n * (`point`, when left out), or by its target. Nothing where there is no such place\n */\nexport const teleportEffect = defineEffect(\n\t'teleport',\n\t(context, effect) => {\n\t\tconst { world, caster, point, target } = context\n\t\tconst to = effect.to ?? 'point'\n\t\tconst aim = to === 'home' ? homeOf(world, caster.owner, caster.pos) : to === 'target' ? target?.pos : point\n\t\tif (!aim) return\n\t\tconst spot = (caster.flying ? world.air : world.nav).closestPoint(aim, 6) ?? aim\n\t\tworld.place(caster, spot)\n\t\tcaster.prevPos.x = spot.x\n\t\tcaster.prevPos.z = spot.z\n\t\tpoint.x = spot.x\n\t\tpoint.z = spot.z\n\t},\n\t{ fields: ['to'] }\n)\n\n/** The caster rushes to the spot, through whatever is in the way. `effects` happen around where it ends */\nexport const dashEffect = defineEffect(\n\t'dash',\n\t(context, effect) => {\n\t\tconst { world, caster, ability, level, point } = context\n\t\t// no farther than `distance`, towards where it was aimed\n\t\tconst gap = dist(caster.pos, point)\n\t\tconst far = Math.min(gap, at(effect.distance, level, Infinity))\n\t\tlet aim =\n\t\t\tgap > far ? { x: caster.pos.x + ((point.x - caster.pos.x) / gap) * far, z: caster.pos.z + ((point.z - caster.pos.z) / gap) * far } : point\n\t\tconst nav = caster.flying ? world.air : world.nav\n\t\tlet spot = nav.closestPoint(aim, 4) ?? aim\n\t\tif (effect.leap && effect.climb !== undefined) {\n\t\t\t// a wall too high to get over: down in front of it, and not on top of it by way of the nearest place to stand\n\t\t\tconst top = world.terrain.heightAt(caster.pos.x, caster.pos.z) + effect.climb\n\t\t\taim = beforeWall(world, caster.pos, aim, top)\n\t\t\tspot = nav.closestPoint(aim, 2) ?? aim\n\t\t\tif (world.terrain.heightAt(spot.x, spot.z) > top) spot = aim\n\t\t}\n\t\tif (dist(caster.pos, spot) > 0.05) caster.facing = atan2(spot.x - caster.pos.x, spot.z - caster.pos.z)\n\t\tstartDash(world, caster, {\n\t\t\tx: spot.x,\n\t\t\tz: spot.z,\n\t\t\tspeed: effect.speed ?? 18,\n\t\t\tability: ability.id,\n\t\t\tlevel,\n\t\t\teffects: effect.effects ?? [],\n\t\t\theight: effect.leap,\n\t\t\tbuff: effect.buff\n\t\t})\n\t\t// what it is while it is on its way, like out of reach of the ground\n\t\tif (effect.buff) applyBuff(world, caster, effect.buff, Infinity, caster, level)\n\t},\n\t{ fields: ['distance', 'leap', 'climb', 'speed', 'effects', 'buff'] }\n)\n\n/** Throws the targets `distance` away from the caster. Nothing stops them on the way, and who is rushing somewhere is not thrown */\nexport const knockbackEffect = defineEffect(\n\t'knockback',\n\t(context, effect) => {\n\t\tconst { world, caster, ability, level } = context\n\t\tconst far = at(effect.distance, level, 4)\n\t\tfor (const entity of effectTargets(context, effect, 'enemies')) {\n\t\t\tif (!entity.isUnit || !entity.get(moving) || entity.get(dashing)) continue\n\t\t\tconst dx = entity.pos.x - caster.pos.x\n\t\t\tconst dz = entity.pos.z - caster.pos.z\n\t\t\tconst gap = hypot(dx, dz) || 1\n\t\t\tconst to = { x: entity.pos.x + (dx / gap) * far, z: entity.pos.z + (dz / gap) * far }\n\t\t\tconst spot = (entity.flying ? world.air : world.nav).closestPoint(to, 4) ?? to\n\t\t\tstartDash(world, entity, { x: spot.x, z: spot.z, speed: effect.speed ?? 22, ability: ability.id, level, effects: [], height: effect.leap })\n\t\t}\n\t},\n\t{ fields: ['distance', 'speed', 'leap'] }\n)\n","/**\n * What an ability does around its casting: the passives set off by attacks, kills and casts (`EffectTypes.onHit`,\n * `onKill`, `onCast`, run where those happen), an attack or an ability ready again (`resetAttack`, `refresh`), and what\n * a charged cast does (`charged`)\n */\nimport { fighting } from '#engine/entity'\nimport { defineEffect } from '../effects'\nimport { run } from '../land'\nimport { readyAgain } from '../charges'\n\n/** `onHit` is about attacks, not about the moment of casting: see the function of that name */\nexport const onHitEffect = defineEffect('onHit', () => {}, { fields: ['whileBuff', 'effects'] })\n\n/** For passives: `effects` happen around whoever the carrier kills. The killing sets it off, see `onKill` */\nexport const onKillEffect = defineEffect('onKill', () => {}, { fields: ['attack', 'effects'] })\n\n/** For passives: `effects` happen to the carrier whenever it casts. The casting sets it off, see `onCast` */\nexport const onCastEffect = defineEffect('onCast', () => {}, { fields: ['effects'] })\n\n/** The caster is ready to strike again at once */\nexport const resetAttackEffect = defineEffect(\n\t'resetAttack',\n\t({ caster }) => {\n\t\tif (caster.get(fighting)) caster.get(fighting)!.cooldown = 0\n\t},\n\t{ fields: [] }\n)\n\n/** An ability of the caster is ready again, with all the charges it holds: the one named, or the one the effect belongs to */\nexport const refreshEffect = defineEffect(\n\t'refresh',\n\t(context, effect) => {\n\t\tconst state = context.caster.abilities.find((known) => known.id === (effect.ability ?? context.ability.id))\n\t\tif (state) readyAgain(state)\n\t},\n\t{ fields: ['ability'] }\n)\n\n/**\n * `effects` when the ability went off charged, `otherwise` when it did not. With `on: 'caster'` what it does\n * charged happens where the caster stands, wherever it was aimed\n */\nexport const chargedEffect = defineEffect(\n\t'charged',\n\t(context, effect) => {\n\t\tif (!context.charged) return run(context, effect.otherwise)\n\t\tconst { caster } = context\n\t\trun(effect.on === 'caster' ? { ...context, point: { x: caster.pos.x, z: caster.pos.z } } : context, effect.effects)\n\t},\n\t{ fields: ['effects', 'otherwise'] }\n)\n","/**\n * Sight: the engine's effects that show a spot (`EffectTypes.reveal`) and find what is invisible (`detect`)\n */\nimport { at } from '#engine/defs'\nimport { detection, distanceToEdge, type Entity } from '#engine/entity'\nimport { defineEffect } from '../effects'\n\nconst near: Entity[] = []\n\n/** The caster's team sees the spot for a while, with nothing standing there */\nexport const revealEffect = defineEffect(\n\t'reveal',\n\t(context, effect) => {\n\t\tconst { world, caster, point, level } = context\n\t\tworld.reveal(world.player(caster.owner).team, point, at(effect.radius, level, 8), at(effect.duration, level, 5))\n\t},\n\t{ fields: ['duration'] }\n)\n\n/** Finds what is invisible around the spot: the caster's team sees it for as long as `duration` says */\nexport const detectEffect = defineEffect(\n\t'detect',\n\t(context, effect) => {\n\t\tconst { world, caster, point, level } = context\n\t\tconst team = world.player(caster.owner).team\n\t\tconst radius = at(effect.radius, level, 10)\n\t\tconst seconds = at(effect.duration, level, 8)\n\t\tfor (const entity of world.spatial.query(point.x, point.z, radius, near)) {\n\t\t\tif (!entity.alive || !world.sight.isInvisible(entity) || !world.areEnemies(caster.owner, entity.owner)) continue\n\t\t\tif (distanceToEdge(point, entity) > radius) continue\n\t\t\tlet found = entity.get(detection)\n\t\t\tif (!found) entity.set(detection, (found = new Map()))\n\t\t\tfound.set(team, Math.max(found.get(team) ?? 0, seconds))\n\t\t}\n\t},\n\t{ fields: ['duration'] }\n)\n","/**\n * The engine's effect that brings a unit into the world (`EffectTypes.spawn`)\n */\nimport { at } from '#engine/defs'\nimport { defineEffect } from '../effects'\n\n/** Brings a unit of the caster's into the world where it landed, like a ward. `duration` is how long it lasts */\nexport const spawnEffect = defineEffect(\n\t'spawn',\n\t(context, effect) => {\n\t\tconst { world, caster, point, level } = context\n\t\tif (!effect.unit) return\n\t\tconst lifetime = effect.duration === undefined ? undefined : at(effect.duration, level)\n\t\tworld.spawn(effect.unit, caster.owner, point, { facing: caster.facing, lifetime })\n\t},\n\t{ fields: ['unit', 'duration'] }\n)\n","/**\n * Later and over time: the engine's effects that go off after a while (`EffectTypes.after`) and over and over in a\n * place (`zone`)\n */\nimport { at } from '#engine/defs'\nimport { defineEffect } from '../effects'\n\n/** `effects` happen at the spot, `delay` seconds from now */\nexport const afterEffect = defineEffect(\n\t'after',\n\t(context, effect) => {\n\t\tconst { world, caster, ability, level, point } = context\n\t\tworld.delayed.push({\n\t\t\tleft: at(effect.delay, level),\n\t\t\tcaster,\n\t\t\tability,\n\t\t\tlevel,\n\t\t\tpoint: { x: point.x, z: point.z },\n\t\t\teffects: effect.effects ?? [],\n\t\t\timpact: effect.impact\n\t\t})\n\t},\n\t{ fields: ['delay', 'effects', 'impact'] }\n)\n\n/** For `duration` seconds `effects` happen to what is at the spot, over and over, and `onEnd` to what is there at the end */\nexport const zoneEffect = defineEffect(\n\t'zone',\n\t(context, effect) => {\n\t\tconst { world, caster, ability, level, point } = context\n\t\tworld.zones.push({ id: world.newId(), caster, ability, level, x: point.x, z: point.z, left: at(effect.duration, level, 1), next: 0, effect })\n\t},\n\t{ fields: ['duration', 'effects', 'onEnd'] }\n)\n","/**\n * A market's: the caster's owner trades one resource for another at a rate (`EffectTypes.exchange`, `exchange` in\n * `trade.ts`)\n */\nimport { at } from '#engine/defs'\nimport { exchange } from '#engine/trade'\nimport { defineEffect } from '../effects'\n\nexport const exchangeEffect = defineEffect(\n\t'exchange',\n\t(context, effect) => {\n\t\tconst { world, caster, level } = context\n\t\texchange(world, caster.owner, effect.sell, effect.buy, at(effect.amount, level), effect.rate)\n\t},\n\t{ fields: ['sell', 'buy', 'amount', 'rate'] }\n)\n","/**\n * The engine's kinds of effect, as the game is put together with them (`assembleGame`): a game's own of the same type\n * comes after and takes the place of one\n */\nimport type { EffectKind } from '../effects'\nimport { auraEffect, buffEffect, toggleEffect } from './buff'\nimport { damageEffect } from './damage'\nimport { healEffect, manaEffect } from './heal'\nimport { missileEffect } from './missile'\nimport { blinkEffect, dashEffect, knockbackEffect, teleportEffect } from './moves'\nimport { chargedEffect, onCastEffect, onHitEffect, onKillEffect, refreshEffect, resetAttackEffect } from './passives'\nimport { detectEffect, revealEffect } from './sight'\nimport { spawnEffect } from './spawn'\nimport { afterEffect, zoneEffect } from './timed'\nimport { exchangeEffect } from './trade'\n\n/** @internal */\nexport const coreEffects: readonly EffectKind[] = [\n\tdamageEffect,\n\thealEffect,\n\tmanaEffect,\n\tbuffEffect,\n\tmissileEffect,\n\tauraEffect,\n\tspawnEffect,\n\ttoggleEffect,\n\trevealEffect,\n\tonHitEffect,\n\tresetAttackEffect,\n\tblinkEffect,\n\tteleportEffect,\n\tdashEffect,\n\tknockbackEffect,\n\trefreshEffect,\n\tonKillEffect,\n\tonCastEffect,\n\tchargedEffect,\n\tafterEffect,\n\tzoneEffect,\n\tdetectEffect,\n\texchangeEffect\n]\n","/**\n * The log: what the engine, a server, the client and a game say about what they do, as entries of plain data that go\n * to whoever asked for them (a sink). A world has its own (`world.log`), whose entries say which game and which tick\n * they are from; every logger passes its entries up to the one it was made under, so that a sink at the top\n * (`rootLogger.to`, or a server's own) sees all of them.\n *\n * The log says, and nothing else: it reads nothing of the simulation's chances, changes nothing in a world, and is\n * not kept in a save. Two runs of a game are the same whether anyone listens or not.\n */\n\n/**\n * How much an entry matters: `debug` for whoever looks closely, `error` for what went wrong\n *\n * @beta\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/** @beta */\nexport const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'warn', 'error']\n\n/**\n * One thing said. Plain data: it crosses a session, a worker and a file as it is\n *\n * @beta\n */\nexport interface LogEntry {\n\tlevel: LogLevel\n\t/** What part said it: `server`, `game`, `assets`, a mod's own */\n\tcategory: string\n\tmessage: string\n\t/** What it is about, by name: an entity's id, a player, a file, an error (`errorFields`) */\n\tfields?: Record<string, unknown>\n\t/** The game it was said in, and its tick, where it was said in one */\n\tgame?: string\n\ttick?: number\n\t/** When, in milliseconds of the clock (`Date.now`). Never read by the simulation */\n\ttime: number\n}\n\n/**\n * Where entries go: the console, a file, a panel, a service\n *\n * @beta\n */\nexport type LogSink = (entry: LogEntry) => void\n\n/**\n * What a logger adds to each of its entries: the game and the tick of a world, the fields of a part\n *\n * @beta\n */\nexport type LogContext = () => Partial<Pick<LogEntry, 'game' | 'tick'>> & { fields?: Record<string, unknown> }\n\n/** @beta */\nexport interface LoggerOptions {\n\t/** The logger this one passes its entries up to. None for one that stands alone */\n\tparent?: Logger\n\t/** The least an entry must matter to be said here: everything when left out */\n\tlevel?: LogLevel\n\tcontext?: LogContext\n}\n\n/**\n * An error as plain data, for an entry's fields: what it is called, what it says, and where it was thrown\n *\n * @beta\n */\nexport function errorFields(error: unknown): { name: string; message: string; stack?: string } {\n\tif (error instanceof Error) return { name: error.name, message: error.message, ...(error.stack && { stack: error.stack }) }\n\treturn { name: 'Error', message: String(error) }\n}\n\n/**\n * An entry as one line of text: `warn [server] tick 120 of td: a connection took in too slowly {bytes: 12}`\n *\n * @beta\n */\nexport function logLine(entry: LogEntry): string {\n\tconst where = entry.game !== undefined ? ` ${entry.tick !== undefined ? `tick ${entry.tick} of ` : ''}${entry.game}:` : ''\n\tconst fields = entry.fields && Object.keys(entry.fields).length ? ` ${JSON.stringify(entry.fields)}` : ''\n\treturn `${entry.level} [${entry.category}]${where} ${entry.message}${fields}`\n}\n\n/**\n * Writes entries to the console, each by its level. An error among the fields is shown as the console shows errors\n *\n * @beta\n */\nexport const consoleSink: LogSink = (entry) => {\n\tconst { error, ...fields } = entry.fields ?? {}\n\tconst line = logLine({ ...entry, fields })\n\tconst write =\n\t\tentry.level === 'error' ? console.error : entry.level === 'warn' ? console.warn : entry.level === 'debug' ? console.debug : console.log\n\tconst thrown = error && typeof error === 'object' && 'stack' in error ? (error as { stack?: string }).stack : undefined\n\tif (thrown) write(line, `\\n${thrown}`)\n\telse write(line)\n}\n\n/** @beta */\nexport class Logger {\n\t/** The least an entry must matter to be said: what is under it is dropped here, and goes no further */\n\tlevel: LogLevel\n\tprivate readonly parent?: Logger\n\tprivate readonly context?: LogContext\n\tprivate readonly sinks = new Set<LogSink>()\n\n\tconstructor(options: LoggerOptions = {}) {\n\t\tthis.parent = options.parent\n\t\tthis.level = options.level ?? 'debug'\n\t\tthis.context = options.context\n\t}\n\n\t/** Sends this logger's entries, and those of every logger under it, to a sink. Returns what stops it */\n\tto(sink: LogSink): () => void {\n\t\tthis.sinks.add(sink)\n\t\treturn () => this.sinks.delete(sink)\n\t}\n\n\t/** A logger under this one: its entries carry what `context` adds, and are passed up here */\n\tchild(options: Omit<LoggerOptions, 'parent'> | LogContext = {}): Logger {\n\t\treturn new Logger({ parent: this, ...(typeof options === 'function' ? { context: options } : options) })\n\t}\n\n\t/** Whether an entry of this level would be said: for not putting together what nobody will read */\n\tsays(level: LogLevel): boolean {\n\t\treturn LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(this.level)\n\t}\n\n\tlog(level: LogLevel, category: string, message: string, fields?: Record<string, unknown>): void {\n\t\tif (!this.says(level)) return\n\t\tthis.pass({ level, category, message, ...(fields && { fields }), time: Date.now() })\n\t}\n\n\tdebug(category: string, message: string, fields?: Record<string, unknown>): void {\n\t\tthis.log('debug', category, message, fields)\n\t}\n\tinfo(category: string, message: string, fields?: Record<string, unknown>): void {\n\t\tthis.log('info', category, message, fields)\n\t}\n\twarn(category: string, message: string, fields?: Record<string, unknown>): void {\n\t\tthis.log('warn', category, message, fields)\n\t}\n\terror(category: string, message: string, fields?: Record<string, unknown>): void {\n\t\tthis.log('error', category, message, fields)\n\t}\n\n\t/**\n\t * Takes an entry made elsewhere (a world's, by the client that shows it; a server's, sent to a tool) as if it was\n\t * said here: to this logger's sinks, and up. What it already says of its game and its tick is kept\n\t */\n\tpass(entry: LogEntry): void {\n\t\tif (!this.says(entry.level)) return\n\t\tconst added = this.context?.()\n\t\tconst full: LogEntry = added\n\t\t\t? {\n\t\t\t\t\t...entry,\n\t\t\t\t\t...(entry.game === undefined && added.game !== undefined && { game: added.game }),\n\t\t\t\t\t...(entry.tick === undefined && added.tick !== undefined && { tick: added.tick }),\n\t\t\t\t\t...(added.fields && { fields: { ...added.fields, ...entry.fields } })\n\t\t\t\t}\n\t\t\t: entry\n\t\t// a sink that throws is not a reason for what was being done to stop: the log is never the cause of a failure\n\t\tfor (const sink of this.sinks) {\n\t\t\ttry {\n\t\t\t\tsink(full)\n\t\t\t} catch {\n\t\t\t\tthis.sinks.delete(sink)\n\t\t\t}\n\t\t}\n\t\tthis.parent?.pass(full)\n\t}\n}\n\n/**\n * The logger everything is under when nothing else is said: a world's, a server's, the client's. It writes to the\n * console (`rootConsole.stop()` ends that, for a page or a server that keeps its log elsewhere), from `info` up\n *\n * @beta\n */\nexport const rootLogger = new Logger({ level: 'info' })\n\n/**\n * The root logger's writing to the console: stopped and started again\n *\n * @beta\n */\nexport const rootConsole = (() => {\n\tlet stop: (() => void) | null = rootLogger.to(consoleSink)\n\treturn {\n\t\tget on(): boolean {\n\t\t\treturn stop !== null\n\t\t},\n\t\tstop(): void {\n\t\t\tstop?.()\n\t\t\tstop = null\n\t\t},\n\t\tstart(): void {\n\t\t\tstop ??= rootLogger.to(consoleSink)\n\t\t}\n\t}\n})()\n\n/**\n * The last entries, kept: what a console panel shows, and what goes with a report of a crash\n *\n * @beta\n */\nexport interface LogRing {\n\tsink: LogSink\n\t/** The entries kept, the oldest first */\n\tentries(): readonly LogEntry[]\n\tclear(): void\n\t/** Calls back for each entry as it comes. Returns what stops it */\n\tonEntry(listener: LogSink): () => void\n}\n\n/**\n * Keeps the last `size` entries (500 when left out) of whatever its sink is given\n *\n * @beta\n */\nexport function createLogRing(size = 500): LogRing {\n\tlet kept: LogEntry[] = []\n\tconst listeners = new Set<LogSink>()\n\treturn {\n\t\tsink(entry) {\n\t\t\tkept.push(entry)\n\t\t\tif (kept.length > size) kept = kept.slice(kept.length - size)\n\t\t\tfor (const listener of listeners) listener(entry)\n\t\t},\n\t\tentries: () => kept,\n\t\tclear() {\n\t\t\tkept = []\n\t\t},\n\t\tonEntry(listener) {\n\t\t\tlisteners.add(listener)\n\t\t\treturn () => listeners.delete(listener)\n\t\t}\n\t}\n}\n","import type { DamageTable } from './rules'\nimport type { AiProfile } from './ai/profiles'\nimport { dispelEffects } from './abilities/dispel'\nimport type { EffectKind } from './abilities/effects'\nimport { coreEffects } from './abilities/effects/core'\nimport { COMMON_EFFECT_FIELDS } from './abilities/effectFields'\nimport { defineComponent } from './components'\nimport type { Definitions } from './definitions'\nimport {\n\ttype AbilityDef,\n\ttype BuffDef,\n\tCORE_STAT_KEYS,\n\ttype ItemDef,\n\ttype ResourceDef,\n\ttype UnitTypeDef,\n\ttype UpgradeDef,\n\ttype UpkeepTier\n} from './defs'\nimport { defineEvent } from './events'\nimport { type Check, Invalid, string } from './fields'\nimport type { GameModule } from './game'\nimport { rootLogger } from './log'\nimport type { RaceDef } from './races'\nimport type { Registry } from './registry'\nimport { replicateEvent } from './replication'\nimport { summonEffects } from './summons'\n\n/*\n * The game's data in the editor (S61): the numbers and words of a game's definitions (a unit's health, an ability's\n * cooldown) changed in the editor's Data panel, tried at once in a game played there, and kept in the game's\n * `data.json`, which the game reads over what its code says (`withData`). The code stays where a definition is made\n * and what it does; which of its fields can be changed there is the game's to say (`GameModule.editable`): a\n * definition has no schema of its own to read.\n */\n\n/**\n * The kinds of definition a game's data is kept for, by the field of the game module they are listed in\n *\n * @beta\n */\nexport const DATA_KINDS = ['units', 'abilities', 'buffs', 'items', 'upgrades', 'races'] as const\n/** @beta */\nexport type DataKind = (typeof DATA_KINDS)[number]\n\n/**\n * What a definition of each kind must have besides its id and its name, as the type says (`UnitTypeDef.radius`...),\n * with what one made of nothing starts as (`NEW_DEFINITION`: the Data panel's New, from empty). A unit type is a unit\n * unless its `kind` says otherwise\n *\n * @beta\n */\nexport const REQUIRED_FIELDS: Readonly<Record<DataKind, Readonly<DataValues>>> = {\n\tunits: { kind: 'unit', radius: 0.5, stats: { health: 100 }, sight: 8 },\n\tabilities: { target: 'none', effects: [] },\n\tbuffs: {},\n\titems: { cost: {} },\n\tupgrades: { cost: {}, researchTime: 30, effects: [] },\n\traces: {}\n}\n\n/**\n * What a definition in a `data.json` says to be one of its own, made of nothing, where the game has none by its id\n * (`{ \"new\": true, \"name\": \"Peon\", \"stats\": { \"health\": 220 } }`): what its kind must have (`REQUIRED_FIELDS`), its\n * name its id until it says, with what else is said over it. A unit type's `kind` is taken from it too\n *\n * @beta\n */\nexport const NEW_DEFINITION = 'new'\n\n/**\n * A definition made of nothing, by an id: what its kind must have (`REQUIRED_FIELDS`), named by its id\n *\n * @beta\n */\nexport function blankDefinition<K extends DataKind>(kind: K, id: string, unitKind?: string): DataDefs[K] {\n\tconst required = structuredClone(REQUIRED_FIELDS[kind]) as Record<string, unknown>\n\tif (kind === 'units' && unitKind) required.kind = unitKind\n\treturn { id, name: id, ...required } as unknown as DataDefs[K]\n}\n\n/** The kinds of thing a unit type made of nothing may be (`UnitTypeDef.kind`) */\nconst UNIT_KINDS = ['unit', 'building', 'resource']\n\n/**\n * A definition of each kind\n *\n * @beta\n */\nexport interface DataDefs {\n\tunits: UnitTypeDef\n\tabilities: AbilityDef\n\tbuffs: BuffDef\n\titems: ItemDef\n\tupgrades: UpgradeDef\n\traces: RaceDef\n}\n\n/**\n * What a field of the data can hold: a number, words, yes or no\n *\n * @beta\n */\nexport type DataValue = number | string | boolean\n\n/**\n * What a field can be set to: one of those, a list of words (ids: the abilities of a unit, what a building trains), or a\n * list of things whole (the effects of an ability: a `rows` field)\n *\n * @beta\n */\nexport type FieldValue = DataValue | string[] | DataValues[]\n\n/**\n * What a definition in a `data.json` is a copy of, when the game has none by its id: `{ \"copyOf\": \"footman\", \"name\":\n * \"Champion\" }` is a footman by another name. The copy is the definition it names, with what else is said over it,\n * and knows what it is a copy of (`basedOn`)\n *\n * @beta\n */\nexport const COPY_OF = 'copyOf'\n\n/**\n * Values of a definition, as its own fields nest them: `{ stats: { health: 420 }, cost: { gold: 135 } }`. What a\n * `data.json` keeps of each definition, and what `world.redefine` is given. A list of things by place (a unit's attacks)\n * is written as a list or as its places (`{ attacks: { 0: { damagePoint: 0.5 } } }`), each over the thing there. A list\n * of things changed whole (an ability's effects, the units a race's start adds: a `rows` field) written as places goes\n * over the things there, and written as a list is the list: those things, in that order, each in full\n *\n * @beta\n */\nexport interface DataValues {\n\t[field: string]: DataValue | DataValue[] | DataValues | DataValues[]\n}\n\n/**\n * The values of a game's definitions, by kind and id: what its `data.json` holds. `removed` takes definitions of the\n * game's out, by kind (the Data panel's Delete): what still names one is the rules' check's to say (`checkRules`)\n *\n * @beta\n */\nexport type GameData = Partial<Record<DataKind, Record<string, DataValues>>> & {\n\tremoved?: Partial<Record<DataKind, string[]>>\n\t/**\n\t * How the game's computers play each race (campaign plan AR4), by race id: each a whole profile, in the place of the\n\t * code's (`GameModule.ai.races`). What the editor's Data panel writes of a race's AI\n\t */\n\tai?: { races?: Record<string, AiProfile> }\n\t/** The rules as data (campaign plan RC7), laid over the game's (`DataRules`): what the Data panel's Rules writes */\n\trules?: DataRules\n}\n\n/**\n * The rules a `data.json` may say (campaign plan RC7), each over the game's: the damage table whole, the supply's and\n * the heroes' numbers, the resources and the upkeep's tiers whole (in place of `GameModule.resources`, `upkeep`)\n *\n * @beta\n */\nexport interface DataRules {\n\tcombat?: { damageTable?: DamageTable }\n\tsupply?: { max?: number; pools?: Record<string, { name: string; max: number }> }\n\theroes?: { maxHeroes?: number; maxHeroLevel?: number; xpRange?: number }\n\tresources?: ResourceDef[]\n\tupkeep?: UpkeepTier[]\n}\n\n/**\n * Why rules said as data are not, where they are first wrong: nothing for rules that are\n *\n * @beta\n */\nexport function dataRulesProblem(rules: unknown): string | undefined {\n\tif (!isRecord(rules)) return 'rules is no object'\n\tconst known = new Set(['combat', 'supply', 'heroes', 'resources', 'upkeep'])\n\tconst other = Object.keys(rules).find((key) => !known.has(key))\n\tif (other) return `rules.${other} is nothing the rules say as data`\n\tconst number = (value: unknown) => typeof value === 'number' && Number.isFinite(value)\n\tconst table = isRecord(rules.combat) ? rules.combat.damageTable : undefined\n\tif (table !== undefined) {\n\t\tconst words = (list: unknown) => Array.isArray(list) && list.every((each) => typeof each === 'string')\n\t\tif (!isRecord(table) || !words(table.attacks) || !words(table.armours)) return 'rules.combat.damageTable has attacks and armours, lists of words'\n\t\tconst rows = table.table\n\t\tif (!Array.isArray(rows) || rows.length !== (table.attacks as string[]).length) return 'rules.combat.damageTable.table has a row an attack type'\n\t\tif (rows.some((row) => !Array.isArray(row) || row.length !== (table.armours as string[]).length || !row.every(number)))\n\t\t\treturn 'rules.combat.damageTable.table has a number an armour type in each row'\n\t}\n\tfor (const part of ['supply', 'heroes'] as const) {\n\t\tconst said = rules[part]\n\t\tif (said === undefined) continue\n\t\tif (!isRecord(said)) return `rules.${part} is no object`\n\t\tfor (const [key, value] of Object.entries(said)) if (key !== 'pools' && !number(value)) return `rules.${part}.${key} is no number`\n\t}\n\tfor (const part of ['resources', 'upkeep'] as const) {\n\t\tconst said = rules[part]\n\t\tif (said !== undefined && (!Array.isArray(said) || !said.every(isRecord))) return `rules.${part} is no list`\n\t}\n\treturn undefined\n}\n\n/** The game with the rules a `data.json` says laid over its own */\nfunction withDataRules(game: GameModule, rules: DataRules): GameModule {\n\tconst out: GameModule = { ...game }\n\tconst own = game.rules ?? {}\n\tconst next: Record<string, unknown> = { ...own }\n\tif (rules.combat?.damageTable) next.combat = { ...own.combat, damageTable: rules.combat.damageTable }\n\tif (rules.supply) next.supply = { ...own.supply, ...rules.supply }\n\tif (rules.heroes) next.heroes = { ...own.heroes, ...rules.heroes }\n\tif (rules.combat?.damageTable || rules.supply || rules.heroes) out.rules = next as GameModule['rules']\n\tif (rules.resources) out.resources = rules.resources\n\tif (rules.upkeep) out.upkeep = rules.upkeep\n\treturn out\n}\n\n/**\n * A field of a definition the editor may change, and how it shows it\n *\n * @beta\n */\nexport interface EditableField {\n\t/** Where it is in the definition, by its fields: `stats.health`, `cost.gold`, `bounty.0` (a place in a list) */\n\tpath: string\n\t/** What it is called in the editor: the last part of its path, when left out */\n\tname?: string\n\t/**\n\t * What it holds. What the definition has there now, when left out (a number where it has nothing). A `list` is of\n\t * words, in order: ids of the kind `of` says, when it says. An `id` is one id of the kind `of` says (the hall a race\n\t * starts with), picked from what the game has of that kind. `rows` is a list of things, each with fields of its own\n\t * (`effects.0.amount`), added, taken out and put in another order whole: an ability's effects\n\t */\n\tkind?: 'number' | 'integer' | 'text' | 'boolean' | 'choice' | 'list' | 'id' | 'rows'\n\t/** Of a `list` or an `id`: the kind of definition its words are ids of (`abilities` for a unit's abilities) */\n\tof?: DataKind\n\t/**\n\t * Of a `list`: one id or a list of them (a building's `upgradesTo`). Shown as a list either way; a list of one is\n\t * kept as the one id\n\t */\n\tone?: boolean\n\tmin?: number\n\tmax?: number\n\tstep?: number\n\t/** What a `choice` can be */\n\toptions?: readonly string[]\n\t/** Of `rows` of effects: the types a row can be, those the game has (`defineEffect`). A row of no type when left out */\n\ttypes?: readonly string[]\n\t/** The heading it is shown under: the first part of its path, when left out (`stats`, `cost`) */\n\tgroup?: string\n\t/** A line about it, shown when the pointer is over it */\n\thint?: string\n}\n\n/**\n * A field as the editor shows it: everything said\n *\n * @beta\n */\nexport interface DataField extends EditableField {\n\tname: string\n\tkind: NonNullable<EditableField['kind']>\n\tgroup: string\n}\n\n/**\n * Which fields of a kind of definition can be changed: `all` of them (every number, word and yes or no in the\n * definition, as it has them, but its id and kind), some (their paths, or fields said in full), or none (nothing, or\n * an empty list). A function says it for each definition, as it is now: null for none\n *\n * @beta\n */\nexport type EditableFields<D = unknown> =\n\t'all' | readonly (string | EditableField)[] | ((def: D) => 'all' | readonly (string | EditableField)[] | null)\n\n/**\n * What of a game's data the editor can change, by kind (`GameModule.editable`). `all` for every field of every definition\n *\n * @beta\n */\nexport type EditableData = 'all' | { [K in DataKind]?: EditableFields<DataDefs[K]> }\n\n/** Fields that are never changed from the editor: what a definition is known by, what kind of thing it is and of */\nconst FIXED = new Set(['id', 'kind', 'basedOn', NEW_DEFINITION])\n\n/**\n * The lists of ids of each kind of definition, and what they are ids of: what `all` makes editable as lists, and the\n * kind a list field names when the game does not say. Those `always` are there to fill in though a definition has none\n */\nconst LISTS: Partial<Record<DataKind, Record<string, { of: DataKind; one?: true; always?: (def: Record<string, unknown>) => boolean }>>> = {\n\tunits: {\n\t\tabilities: { of: 'abilities', always: () => true },\n\t\trequires: { of: 'units', always: () => true },\n\t\tprovides: { of: 'units' },\n\t\tbuilds: { of: 'units', always: (def) => def.kind === 'unit' && !!def.harvester },\n\t\ttrains: { of: 'units', always: (def) => def.kind === 'building' },\n\t\tresearches: { of: 'upgrades', always: (def) => def.kind === 'building' },\n\t\tsells: { of: 'items' },\n\t\thires: { of: 'units' },\n\t\t// one type, or several (GP6)\n\t\tupgradesTo: { of: 'units', one: true },\n\t\t'hero.learns': { of: 'abilities' },\n\t\t'hero.spells': { of: 'abilities' }\n\t},\n\titems: { from: { of: 'items' } }\n}\n\n/** The lists of things whose fields are changed by place (`attacks.1.acquisitionRange`), and only by place: a unit's attacks */\nconst BY_PLACE: Partial<Record<DataKind, readonly string[]>> = { units: ['attacks'] }\n\n/** A list of things changed whole as well as by place (`ROWS`): what its things are, and when it is offered though a definition has none */\ninterface RowsSpec {\n\t/** Its things are effects (`EffectDef`): each of a type the game has, with the fields the type reads */\n\teffects?: true\n\t/** The fields of each of its things, by their path in it, for things of no type */\n\trow?: (game: Pick<GameModule, 'stats'> | null | undefined) => readonly EditableField[]\n\t/** Offered empty where the definition has no list there, when this says */\n\twhen?: (def: Record<string, unknown>) => boolean\n\thint?: string\n}\n\n/**\n * The lists of things changed whole in the editor (campaign plan RC2), each thing a row: added, taken out, put in\n * another order, its fields by place (`effects.0.amount`). The effects of abilities, of buffs, the changes of an\n * upgrade, the units a race's start adds. Offered where every thing in them is data (no function among them)\n */\nconst ROWS: Partial<Record<DataKind, Record<string, RowsSpec>>> = {\n\tabilities: {\n\t\teffects: { effects: true, when: (def) => def.target !== 'passive', hint: 'What it does, in order' },\n\t\tpassive: { effects: true, when: (def) => def.target === 'passive', hint: 'What it does all the time' }\n\t},\n\tbuffs: {\n\t\tonApply: { effects: true, when: () => true, hint: 'What happens as it is put on, in the name of who put it there' },\n\t\t'onTick.effects': { effects: true, when: (def) => isRecord(def.onTick), hint: 'What happens every so often while it lasts' }\n\t},\n\tupgrades: {\n\t\teffects: {\n\t\t\trow: (game) => [\n\t\t\t\t{ path: 'units', kind: 'list', of: 'units', hint: 'The unit types that benefit: every one of the player’s when left out' },\n\t\t\t\t...[...CORE_STAT_KEYS, ...(game?.stats ?? []).map((stat) => stat.id)].map((stat): EditableField => ({\n\t\t\t\t\tpath: `stats.${stat}`,\n\t\t\t\t\tkind: 'number',\n\t\t\t\t\thint: `What a level adds to ${stat}`\n\t\t\t\t}))\n\t\t\t],\n\t\t\thint: 'What each level changes'\n\t\t}\n\t},\n\traces: {\n\t\t'start.units': {\n\t\t\trow: () => [\n\t\t\t\t{ path: 'type', kind: 'id', of: 'units', hint: 'The unit type' },\n\t\t\t\t{ path: 'count', kind: 'integer', min: 1, hint: 'How many' }\n\t\t\t],\n\t\t\twhen: (def) => isRecord(def.start) && typeof def.start.spawn !== 'function',\n\t\t\thint: 'What else it starts with, by unit type'\n\t\t}\n\t}\n}\n\n/** How deep lists of things go in a thing of a list (a missile's effects in an ability's): deeper ones stay the code's */\nconst MAX_ROWS_DEPTH = 2\n\n/**\n * The fields that are one id of a kind of definition, by path (a `*` for a place in a list), and what they are ids of:\n * what `all` makes an `id` field, picked in the editor from what the game has. A race's start as data (`StartData`)\n */\nconst IDS: Partial<Record<DataKind, Record<string, DataKind>>> = {\n\traces: { 'start.hall': 'units', 'start.workers.type': 'units', 'start.onMine': 'units' }\n}\n\n/**\n * Fields offered though a definition has nothing there, for `all`, where `when` says: a copy of a race says what it\n * keeps of the original's code (`RaceDef.inherits`), kept unless it says otherwise\n */\nconst FILLED_IN: Partial<Record<DataKind, (EditableField & { when: (def: Record<string, unknown>) => boolean })[]>> = {\n\t// uses an ability holds (GP5), offered though it has none, for what is cast\n\tabilities: [\n\t\t{\n\t\t\tpath: 'charges.count',\n\t\t\tkind: 'integer',\n\t\t\tmin: 1,\n\t\t\thint: 'Uses it holds, for one used so many times before it waits: its cooldown is then between two uses',\n\t\t\twhen: (def) => def.target !== 'passive'\n\t\t},\n\t\t{\n\t\t\tpath: 'charges.refill',\n\t\t\tkind: 'number',\n\t\t\tmin: 0,\n\t\t\thint: 'Seconds until a use is back, while it holds fewer than it can',\n\t\t\twhen: (def) => def.target !== 'passive'\n\t\t}\n\t],\n\t// what an item table draws by (GP3), offered though an item says neither\n\titems: [\n\t\t{ path: 'level', kind: 'integer', min: 1, hint: 'How good it is: what an item table draws by (a level)', when: () => true },\n\t\t{ path: 'class', kind: 'text', hint: 'Its kind of item, a word of the game’s: what an item table draws by (a class)', when: () => true }\n\t],\n\traces: [\n\t\t{\n\t\t\tpath: 'inherits.hooks',\n\t\t\tkind: 'boolean',\n\t\t\thint: \"Keeps the hooks of the race this is a copy of: how it gathers, where it builds. Off, it plays by the game's rules alone\",\n\t\t\twhen: (def) => !!def.basedOn\n\t\t},\n\t\t{\n\t\t\tpath: 'inherits.onStart',\n\t\t\tkind: 'boolean',\n\t\t\thint: 'Keeps the onStart of the race this is a copy of: what its players begin with that is not a unit (a ground of its own)',\n\t\t\twhen: (def) => !!def.basedOn\n\t\t}\n\t]\n}\n\n/** The kind of definition a path is an id of, as `IDS` says, or undefined */\nfunction idKindOf(kind: DataKind, path: string): DataKind | undefined {\n\tconst ids = IDS[kind]\n\tif (!ids) return undefined\n\tif (path in ids) return ids[path]\n\tconst general = path.replace(/\\.\\d+(?=\\.|$)/g, '.*')\n\treturn ids[general]\n}\n\n/** The list by place a path is in, and the place: `attacks.1.acquisitionRange` is in `attacks` at 1 */\nfunction placeOf(kind: DataKind, path: string): { list: string; place: number } | undefined {\n\tfor (const list of BY_PLACE[kind] ?? []) {\n\t\tif (!path.startsWith(`${list}.`)) continue\n\t\tconst place = Number(path.slice(list.length + 1).split('.')[0])\n\t\tif (Number.isInteger(place)) return { list, place }\n\t}\n\treturn undefined\n}\n\nconst isWords = (value: unknown): value is string[] => Array.isArray(value) && value.every((each) => typeof each === 'string')\nconst MAX_DEPTH = 4\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\nconst isValue = (value: unknown): value is DataValue =>\n\ttypeof value === 'boolean' || typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value))\n\n/**\n * What is at a path of a definition, or undefined\n *\n * @beta\n */\nexport function valueAt(def: unknown, path: string): unknown {\n\tlet at: unknown = def\n\tfor (const part of path.split('.')) {\n\t\tif (typeof at !== 'object' || at === null) return undefined\n\t\tat = (at as Record<string, unknown>)[part]\n\t}\n\treturn at\n}\n\n/**\n * Values with one field set, nested as the path says: `nested('stats.health', 420)` is `{ stats: { health: 420 } }`\n *\n * @beta\n */\nexport function nested(path: string, value: FieldValue): DataValues {\n\tconst parts = path.split('.')\n\tlet out: DataValues = { [parts.pop()!]: value }\n\twhile (parts.length) out = { [parts.pop()!]: out }\n\treturn out\n}\n\n/**\n * Every number, word and yes or no of a definition, by path, and its lists of ids as lists: what `all` makes editable.\n * A list of numbers (a bounty's two ends) is by place, and so are the things of a list `byPlace` names (a unit's\n * attacks); another list of things (drops) or of lists stays the code's\n */\nfunction leaves(def: unknown, lists: Record<string, unknown> = {}, prefix = '', depth = 0, byPlace: readonly string[] = []): string[] {\n\tif (depth > MAX_DEPTH) return []\n\tconst out: string[] = []\n\tconst entries = Array.isArray(def) ? def.map((value, i) => [String(i), value] as const) : Object.entries(def as object)\n\tfor (const [key, value] of entries) {\n\t\tif (depth === 0 && FIXED.has(key)) continue\n\t\tconst path = prefix ? `${prefix}.${key}` : key\n\t\tif (isValue(value)) out.push(path)\n\t\telse if (path in lists && isWords(value)) out.push(path)\n\t\telse if (\n\t\t\tArray.isArray(value) ? value.every((each) => typeof each === 'number') || (byPlace.includes(path) && value.every(isRecord)) : isRecord(value)\n\t\t)\n\t\t\tout.push(...leaves(value, lists, path, depth + 1, byPlace))\n\t}\n\treturn out\n}\n\nconst kindOf = (value: unknown): DataField['kind'] => (typeof value === 'boolean' ? 'boolean' : typeof value === 'string' ? 'text' : 'number')\n\nfunction fieldOf(kind: DataKind, def: unknown, field: string | EditableField): DataField {\n\tconst given = typeof field === 'string' ? { path: field } : field\n\tconst parts = given.path.split('.')\n\tconst list = LISTS[kind]?.[given.path]\n\tconst value = valueAt(def, given.path)\n\tconst listed =\n\t\tgiven.kind === 'list' ||\n\t\t(given.kind === undefined && (isWords(value) || (value === undefined && !!list) || (!!list?.one && typeof value === 'string')))\n\tconst idOf = given.kind === 'id' || given.kind === undefined ? idKindOf(kind, given.path) : undefined\n\tconst place = placeOf(kind, given.path)\n\treturn {\n\t\t...given,\n\t\t// a field of a thing in a list by place is named by what is left of its path: `type`, `count`\n\t\tname: given.name ?? (place ? given.path.slice(`${place.list}.${place.place}.`.length) : parts[parts.length - 1]),\n\t\tkind: given.kind ?? (given.options ? 'choice' : listed ? 'list' : idOf ? 'id' : kindOf(value)),\n\t\t// a thing of a list by place under its own heading: `attacks 2`, `start units 1`\n\t\tgroup: given.group ?? (place ? `${place.list.split('.').join(' ')} ${place.place + 1}` : parts.length > 1 ? parts[0] : listed ? 'lists' : ''),\n\t\t...(listed && (given.of ?? list?.of) && { of: given.of ?? list!.of }),\n\t\t...(listed && (given.one ?? list?.one) && { one: true }),\n\t\t...(!listed && (given.of ?? idOf) && { of: given.of ?? idOf })\n\t}\n}\n\n/** Whether a value is data all through, no function anywhere in it: as a list must be to be changed whole and kept in a file */\nconst isData = (value: unknown, depth = 0): boolean =>\n\tdepth <= 8 &&\n\t(value === undefined ||\n\t\tisValue(value) ||\n\t\t(Array.isArray(value) && value.every((each) => isData(each, depth + 1))) ||\n\t\t(isRecord(value) && Object.values(value).every((each) => isData(each, depth + 1))))\n\n/** The game a definition's fields are worked out for: what it lets be changed, its kinds of effect and its stats */\ntype FieldsGame = Pick<GameModule, 'editable' | 'effects' | 'stats'>\n\n/** The kinds of effect a game has, by type: the engine's, and its own (`GameModule.effects`), one of its own over the engine's of its type */\nfunction effectKindsOf(game: Pick<GameModule, 'effects'> | null | undefined): Map<string, EffectKind> {\n\tconst kinds = new Map<string, EffectKind>()\n\tfor (const kind of [...coreEffects, ...summonEffects, ...dispelEffects, ...(game?.effects ?? [])]) kinds.set(kind.type, kind)\n\treturn kinds\n}\n\n/**\n * The fields an effect of a type has, by their path in it: those its type reads (`defineEffect`'s `fields`), then those\n * every effect may have (`EffectCommon`). Only those every effect may have, for a type the game has not\n *\n * @beta\n */\nexport function effectFields(game: Pick<GameModule, 'effects'> | null | undefined, type: string): EditableField[] {\n\treturn [...(effectKindsOf(game).get(type)?.fields ?? []), ...Object.values(COMMON_EFFECT_FIELDS)]\n}\n\n/**\n * The types of effect a game has (`defineEffect`): the engine's and its own, in order of their names\n *\n * @beta\n */\nexport function effectTypesOf(game: Pick<GameModule, 'effects'> | null | undefined): string[] {\n\treturn [...effectKindsOf(game).keys()].sort()\n}\n\n/**\n * A list of things changed whole (`ROWS`), and the fields of each of its things by place under a heading of its own\n * (`effects 1`): its type for an effect, then what it has, then what its type or the list says it may have. The lists\n * inside a thing (a missile's effects) the same, a few deep\n */\nfunction rowsFields(\n\tgame: FieldsGame | null | undefined,\n\tspec: RowsSpec,\n\tpath: string,\n\theading: string,\n\trows: readonly unknown[],\n\tdepth = 0\n): DataField[] {\n\tconst types = spec.effects ? effectTypesOf(game) : undefined\n\tconst out: DataField[] = [\n\t\t{ path, name: path.split('.').pop()!, kind: 'rows', group: heading, ...(types && { types }), ...(spec.hint && { hint: spec.hint }) }\n\t]\n\trows.forEach((row, place) => {\n\t\tif (!isRecord(row)) return\n\t\tconst at = `${path}.${place}`\n\t\tconst group = `${heading} ${place + 1}`\n\t\tconst declared = spec.effects ? effectFields(game, String(row.type)) : (spec.row?.(game) ?? [])\n\t\tconst lists = Object.fromEntries(declared.filter((field) => field.kind === 'list').map((field) => [field.path, field]))\n\t\tconst own = (field: EditableField, value: unknown): DataField => ({\n\t\t\t...field,\n\t\t\tpath: `${at}.${field.path}`,\n\t\t\tname: field.name ?? field.path,\n\t\t\tkind: field.kind ?? (field.options ? 'choice' : isWords(value) ? 'list' : kindOf(value)),\n\t\t\tgroup: field.group ?? group\n\t\t})\n\t\t// its type, picked in the editor among the game's: words in the file, so that one the game has not is the rules' check's to say (`checkRules`)\n\t\tif (spec.effects) out.push({ path: `${at}.type`, name: 'type', kind: 'text', group, hint: 'What kind of effect it is' })\n\t\tconst present = leaves(row, lists).filter((each) => !spec.effects || each !== 'type')\n\t\tfor (const each of present) out.push(own(declared.find((field) => field.path === each) ?? { path: each }, valueAt(row, each)))\n\t\tfor (const field of declared) {\n\t\t\tconst value = valueAt(row, field.path)\n\t\t\tif (field.kind !== 'rows') {\n\t\t\t\t// one number for every level where it has one by level (`Scaled`): its levels are fields by place as well\n\t\t\t\tconst byLevel = (field.kind === 'number' || field.kind === 'integer') && Array.isArray(value)\n\t\t\t\tif (value === undefined || byLevel) out.push(own(field, undefined))\n\t\t\t} else if (depth < MAX_ROWS_DEPTH && (value === undefined || (Array.isArray(value) && isData(value))))\n\t\t\t\tout.push(\n\t\t\t\t\t...rowsFields(\n\t\t\t\t\t\tgame,\n\t\t\t\t\t\t{ effects: true, hint: field.hint },\n\t\t\t\t\t\t`${at}.${field.path}`,\n\t\t\t\t\t\t`${group} ${field.path}`,\n\t\t\t\t\t\t(value as unknown[]) ?? [],\n\t\t\t\t\t\tdepth + 1\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t}\n\t})\n\treturn out\n}\n\n/** The lists of things changed whole of a definition (`ROWS`), with their things' fields: those it has, all data, and those offered empty */\nfunction allRows(game: FieldsGame | null | undefined, kind: DataKind, def: unknown): DataField[] {\n\treturn Object.entries(ROWS[kind] ?? {}).flatMap(([path, spec]) => {\n\t\tconst rows = valueAt(def, path)\n\t\tconst offered = rows === undefined ? !!spec.when?.(def as Record<string, unknown>) : Array.isArray(rows) && isData(rows)\n\t\treturn offered ? rowsFields(game, spec, path, path.split('.').join(' '), (rows as unknown[]) ?? []) : []\n\t})\n}\n\n/**\n * An upgrade's requirements by level (`UpgradeDef.requires`, a list for each): a list of ids for each of its levels,\n * those it has and up to its last\n */\nfunction levelLists(def: UpgradeDef): DataField[] {\n\tconst levels = Math.max(def.maxLevel ?? 1, def.requires?.length ?? 0)\n\treturn Array.from({ length: Math.min(levels, MAX_LIST) }, (_, level) => ({\n\t\tpath: `requires.${level}`,\n\t\tname: `level ${level + 1}`,\n\t\tkind: 'list' as const,\n\t\tof: 'units' as const,\n\t\tgroup: 'requires',\n\t\thint: `The buildings needed for level ${level + 1}: all of them`\n\t}))\n}\n\n/**\n * The fields of a definition the editor may change, as the game says (`GameModule.editable`), each with what it\n * holds and the heading it goes under. None for a game that says nothing of that kind\n *\n * @beta\n */\nexport function editableFields<K extends DataKind>(\n\tgame: (Pick<GameModule, 'editable'> & Partial<Pick<GameModule, 'effects' | 'stats'>>) | null | undefined,\n\tkind: K,\n\tdef: DataDefs[K]\n): DataField[] {\n\tconst editable = game?.editable\n\tif (!editable) return []\n\tlet said: EditableFields<DataDefs[K]> | undefined | null = editable === 'all' ? 'all' : (editable[kind] as EditableFields<DataDefs[K]> | undefined)\n\tif (typeof said === 'function') said = said(def)\n\tif (!said) return []\n\tif (said === 'all') {\n\t\tconst lists: NonNullable<(typeof LISTS)[DataKind]> = LISTS[kind] ?? {}\n\t\tconst paths = leaves(def, lists, '', 0, BY_PLACE[kind])\n\t\t// the lists a definition of its kind is filled in with though it has none yet: abilities for a unit with none\n\t\tfor (const [path, list] of Object.entries(lists))\n\t\t\tif (!paths.includes(path) && valueAt(def, path) === undefined && list.always?.(def as unknown as Record<string, unknown>)) paths.push(path)\n\t\tconst fields = paths.map((path) => fieldOf(kind, def, path))\n\t\t// and those offered though the definition has nothing there, where they apply\n\t\tfor (const { when, ...field } of FILLED_IN[kind] ?? [])\n\t\t\tif (!paths.includes(field.path) && when(def as unknown as Record<string, unknown>)) fields.push(fieldOf(kind, def, field))\n\t\t// the lists of things changed whole, and an upgrade's requirements by level\n\t\tfields.push(...allRows(game, kind, def))\n\t\tif (kind === 'upgrades') fields.push(...levelLists(def as UpgradeDef))\n\t\treturn fields\n\t}\n\treturn said.flatMap((field) => {\n\t\tconst path = typeof field === 'string' ? field : field.path\n\t\tconst spec = ROWS[kind]?.[path]\n\t\tif (!spec) return [fieldOf(kind, def, field)]\n\t\tconst rows = valueAt(def, path)\n\t\tif (rows !== undefined && !(Array.isArray(rows) && isData(rows))) return []\n\t\treturn rowsFields(game, spec, path, path.split('.').join(' '), (rows as unknown[]) ?? [])\n\t})\n}\n\n/** How many words a list field holds at most, and how long each is */\nconst MAX_LIST = 64\nconst MAX_WORD = 100\n\n/** Whether something is values as a data file has them: numbers, words, yes or no, lists of them and of things, a few deep */\nfunction isValues(value: unknown, depth = 0): value is DataValues {\n\treturn isRecord(value) && depth <= 6 && Object.entries(value).every(([key, each]) => /^[\\w$]+$/.test(key) && isEntry(each, depth + 1))\n}\nconst isEntry = (value: unknown, depth: number): boolean =>\n\t(isValue(value) && (typeof value !== 'string' || value.length <= 200)) ||\n\t(Array.isArray(value) && value.length <= MAX_LIST && value.every((each) => isEntry(each, depth + 1))) ||\n\tisValues(value, depth)\n\n/** Whether something is a list of things as a `rows` field takes it whole */\nconst isRows = (value: unknown): value is DataValues[] => Array.isArray(value) && value.length <= MAX_LIST && value.every((row) => isValues(row))\n\n/**\n * A value as a field takes it, or the reason it does not\n *\n * @beta\n */\nexport function fitValue(field: DataField, value: unknown): { value: FieldValue } | { error: string } {\n\tswitch (field.kind) {\n\t\tcase 'rows':\n\t\t\treturn isRows(value) && (!field.types || value.every((row) => typeof row.type === 'string'))\n\t\t\t\t? { value: value.map((row) => ({ ...row })) }\n\t\t\t\t: { error: `${field.path} is a list of things${field.types ? ', each of a type' : ''}` }\n\t\tcase 'list': {\n\t\t\t// one id where it may be one (`one`): as given, or a list of one\n\t\t\tconst words = field.one && typeof value === 'string' ? [value] : value\n\t\t\treturn isWords(words) && words.length <= MAX_LIST && words.every((each) => each.length <= MAX_WORD)\n\t\t\t\t? { value: field.one && words.length === 1 ? words[0] : [...words] }\n\t\t\t\t: { error: `${field.path} is a list of words` }\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn typeof value === 'boolean' ? { value } : { error: `${field.path} is yes or no` }\n\t\tcase 'text':\n\t\t\treturn typeof value === 'string' ? { value } : { error: `${field.path} is words` }\n\t\tcase 'id':\n\t\t\treturn typeof value === 'string' && value.length <= MAX_WORD\n\t\t\t\t? { value }\n\t\t\t\t: { error: `${field.path} is an id${field.of ? ` of the ${field.of}` : ''}` }\n\t\tcase 'choice':\n\t\t\treturn typeof value === 'string' && (!field.options || field.options.includes(value))\n\t\t\t\t? { value }\n\t\t\t\t: { error: `${field.path} is one of ${(field.options ?? []).join(', ')}` }\n\t\tdefault: {\n\t\t\tif (typeof value !== 'number' || !Number.isFinite(value)) return { error: `${field.path} is a number` }\n\t\t\tlet set = field.kind === 'integer' ? Math.round(value) : value\n\t\t\tif (field.min !== undefined) set = Math.max(set, field.min)\n\t\t\tif (field.max !== undefined) set = Math.min(set, field.max)\n\t\t\treturn { value: set }\n\t\t}\n\t}\n}\n\n/** Whether a list in the data is one of things by place (a unit's attacks) or of numbers (a bounty's two ends): walked by place, as a record of indices is */\nconst byPlace = (value: unknown): value is unknown[] =>\n\tArray.isArray(value) && value.length > 0 && (value.every(isRecord) || value.every((each) => typeof each === 'number'))\n\n/**\n * Every path of values, with what is there: a list of things or numbers by place (`attacks.0.damagePoint`), a list of\n * words whole, and a list of things whole where `whole` says (a `rows` field's)\n */\nfunction pathsOf(values: DataValues, whole: (path: string) => boolean = () => false, prefix = ''): { path: string; value: unknown }[] {\n\treturn Object.entries(values).flatMap(([key, value]) => {\n\t\tconst path = prefix ? `${prefix}.${key}` : key\n\t\treturn isRecord(value) || (byPlace(value) && !whole(path)) ? pathsOf(value as DataValues, whole, path) : [{ path, value }]\n\t})\n}\n\n/** Whether a record is one of places in a list: every key a whole number */\nconst places = (value: Record<string, unknown>): boolean => Object.keys(value).length > 0 && Object.keys(value).every((key) => /^\\d+$/.test(key))\n\n/**\n * A definition with values over it: a copy, the parts the values go into copied too, the rest (its functions, its\n * lists of things) shared with the one it was made from. Values by place (`{ attacks: { 0: { damagePoint: 0.5 } } }`)\n * go into the list there, or make one where there is none. Nothing of the definition given is changed\n *\n * @beta\n */\nexport function withValues<D>(def: D, values: DataValues): D {\n\tconst over = (into: unknown, from: DataValues): unknown => {\n\t\tconst copy: Record<string, unknown> = Array.isArray(into) ? ([...into] as unknown as Record<string, unknown>) : { ...(into as object) }\n\t\tfor (const [key, value] of Object.entries(from)) {\n\t\t\tif (!isRecord(value)) {\n\t\t\t\tcopy[key] = value\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst there = copy[key]\n\t\t\tconst inner = isRecord(there) || Array.isArray(there) ? there : places(value) ? [] : {}\n\t\t\tcopy[key] = over(inner, value as DataValues)\n\t\t}\n\t\treturn copy\n\t}\n\treturn over(def, values) as D\n}\n\n/**\n * Values merged: what `b` says over what `a` says, at any depth. Places said over a list go into it (`{ 0: { amount:\n * 50 } }` over a list of effects); a list said is the list\n *\n * @beta\n */\nexport function mergeValues(a: DataValues, b: DataValues): DataValues {\n\tconst out: DataValues = { ...a }\n\tfor (const [key, value] of Object.entries(b)) {\n\t\tconst before = out[key]\n\t\tif (isRecord(value) && isRecord(before)) out[key] = mergeValues(before as DataValues, value as DataValues)\n\t\telse if (isRecord(value) && Array.isArray(before) && places(value)) {\n\t\t\tconst list: unknown[] = [...before]\n\t\t\tfor (const [place, each] of Object.entries(value))\n\t\t\t\tlist[Number(place)] =\n\t\t\t\t\tisRecord(each) && isRecord(list[Number(place)]) ? mergeValues(list[Number(place)] as DataValues, each as DataValues) : each\n\t\t\tout[key] = list as DataValues[]\n\t\t} else out[key] = value\n\t}\n\treturn out\n}\n\n/**\n * Only the values of the fields that can be changed, each as its field takes it. What is not is left out and said:\n * a field the game no longer lets be changed, a value of another kind\n *\n * @beta\n */\nexport function editableValues(fields: readonly DataField[], values: DataValues, said: (why: string) => void = () => {}): DataValues {\n\tlet out: DataValues = {}\n\tconst rows = new Set(fields.filter((field) => field.kind === 'rows').map((field) => field.path))\n\tfor (const { path, value } of pathsOf(values, (path) => rows.has(path))) {\n\t\tconst field = fields.find((each) => each.path === path)\n\t\tif (!field) {\n\t\t\tsaid(`${path} cannot be changed from the data`)\n\t\t\tcontinue\n\t\t}\n\t\tconst fit = fitValue(field, value)\n\t\tif ('error' in fit) said(fit.error)\n\t\telse out = mergeValues(out, nested(path, fit.value))\n\t}\n\treturn out\n}\n\n/**\n * The game with what its `data.json` says over what its code says: `export default withData(game, dataFile)`. Only\n * the fields the game lets be changed (`GameModule.editable`) are taken, and of the kind each holds; anything else in\n * the file is left out, and said in the log. The game given is not changed\n *\n * @beta\n */\nexport function withData(game: GameModule, file: unknown): GameModule {\n\tif (!isRecord(file)) return game\n\tconst out: GameModule = { ...game }\n\tconst warn = (why: string) => rootLogger.warn('game', `${game.id}'s data.json: ${why}`)\n\tfor (const kind of DATA_KINDS) {\n\t\tconst values = file[kind]\n\t\tif (values === undefined) continue\n\t\tconst defs = game[kind] as { id: string }[] | undefined\n\t\tif (!isRecord(values) || !defs) {\n\t\t\twarn(`there are no ${kind} to set`)\n\t\t\tcontinue\n\t\t}\n\t\tconst seen = new Set(Object.keys(values))\n\t\t/** What is said of a definition as its fields take it, what it is a copy of (or that it is new) left out */\n\t\tconst over = (def: { id: string }, own: Record<string, unknown>) => {\n\t\t\tconst { [COPY_OF]: _, [NEW_DEFINITION]: isNew, ...rest } = own\n\t\t\t// a unit type made of nothing says its kind, which is taken as it is made\n\t\t\tif (isNew === true) delete rest.kind\n\t\t\tconst fields = editableFields(game, kind, def as never)\n\t\t\treturn withValues(\n\t\t\t\tdef,\n\t\t\t\teditableValues(fields, rest as DataValues, (why) => warn(`${kind}.${def.id}: ${why}`))\n\t\t\t)\n\t\t}\n\t\tconst made = defs.map((def) => {\n\t\t\tconst own = values[def.id]\n\t\t\tif (!isRecord(own)) return def\n\t\t\tseen.delete(def.id)\n\t\t\treturn over(def, own)\n\t\t})\n\t\t// definitions of its own made of nothing\n\t\tfor (const id of seen) {\n\t\t\tconst own = values[id]\n\t\t\tif (!isRecord(own) || own[NEW_DEFINITION] !== true) continue\n\t\t\tmade.push(over(blankDefinition(kind, id, unitKindOf(own.kind)), own))\n\t\t\tseen.delete(id)\n\t\t}\n\t\t// copies, of the game's or of copies before them: as many rounds as it takes, each making those it can\n\t\tfor (let progress = true; progress;) {\n\t\t\tprogress = false\n\t\t\tfor (const id of seen) {\n\t\t\t\tconst own = values[id]\n\t\t\t\tconst from = isRecord(own) ? own[COPY_OF] : undefined\n\t\t\t\tconst base = typeof from === 'string' ? made.find((def) => def.id === from) : undefined\n\t\t\t\tif (!base) continue\n\t\t\t\tmade.push(over({ ...base, id, basedOn: from as string } as { id: string }, own as Record<string, unknown>))\n\t\t\t\tseen.delete(id)\n\t\t\t\tprogress = true\n\t\t\t}\n\t\t}\n\t\t;(out as unknown as Record<string, unknown>)[kind] = made\n\t\tfor (const id of seen) {\n\t\t\tconst from = isRecord(values[id]) ? (values[id] as Record<string, unknown>)[COPY_OF] : undefined\n\t\t\twarn(typeof from === 'string' ? `${kind}.${id} is a copy of \"${from}\", which the game has not` : `the game has no ${kind} \"${id}\"`)\n\t\t}\n\t}\n\t// how the computers play each race: the file's profile of a race in the place of the code's\n\tconst ai = file.ai\n\tif (ai !== undefined) {\n\t\tconst races = isRecord(ai) ? ai.races : undefined\n\t\tif (!isRecord(ai) || (races !== undefined && !isRecord(races))) warn('ai is no { races: { <race>: <profile> } }')\n\t\telse if (isRecord(races)) {\n\t\t\tconst own = { ...game.ai?.races }\n\t\t\tfor (const [race, profile] of Object.entries(races)) {\n\t\t\t\tif (!isRecord(profile)) {\n\t\t\t\t\twarn(`ai.races.${race} is no profile`)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (!(out.races ?? []).some((def) => def.id === race)) warn(`ai.races: the game has no race \"${race}\"`)\n\t\t\t\town[race] = profile as AiProfile\n\t\t\t}\n\t\t\tout.ai = { ...game.ai, races: own }\n\t\t}\n\t}\n\t// the rules as data, over the game's\n\tif (file.rules !== undefined) {\n\t\tconst wrong = dataRulesProblem(file.rules)\n\t\tif (wrong) warn(wrong)\n\t\telse Object.assign(out, withDataRules(out, file.rules as DataRules))\n\t}\n\t// the definitions taken out, after the copies of them are made\n\tconst removed = file.removed\n\tif (isRecord(removed)) {\n\t\tfor (const [kind, ids] of Object.entries(removed)) {\n\t\t\tconst list = (out as unknown as Record<string, { id: string }[] | undefined>)[kind]\n\t\t\tif (!DATA_KINDS.includes(kind as DataKind) || !list || !isWords(ids)) {\n\t\t\t\twarn(`removed.${kind} is no list of ${kind} of the game`)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor (const id of ids) if (!list.some((def) => def.id === id)) warn(`removed.${kind}: the game has no ${kind} \"${id}\"`)\n\t\t\t;(out as unknown as Record<string, unknown>)[kind] = list.filter((def) => !ids.includes(def.id))\n\t\t}\n\t}\n\treturn out\n}\n\n/** The kind of thing a unit type made of nothing is, as its data says: a unit when it says none the game knows */\nconst unitKindOf = (said: unknown): string | undefined => (typeof said === 'string' && UNIT_KINDS.includes(said) ? said : undefined)\n\n/**\n * What a world's definitions were changed to while it runs (`world.redefine`), by kind and id: kept with the world\n * and in its save, so that a load has them again\n *\n * @beta\n */\nexport const redefinitions = defineComponent<GameData>('core.redefinitions', { default: () => ({}) })\n\n/**\n * A definition changed while the game runs: what it is now\n *\n * @beta\n */\nexport const definitionChanged = defineEvent<{ kind: DataKind; id: string; values?: DataValues }>('core.definitionChanged')\n\n/**\n * Puts a definition with values over it into the registry, in the place of the one there: what is made of it from\n * then on is made of the new one. False for a definition the game does not have\n *\n * @beta\n */\nexport function redefineIn(registry: Registry, kind: DataKind, id: string, values: DataValues): boolean {\n\t// a copy of another, by an id the game has nothing by: made, and the rest of what is said put over it\n\tconst copyOf = values[COPY_OF]\n\tif (typeof copyOf === 'string' && !definitionIn(registry, kind, id)) {\n\t\tif (!copyDefinition(registry, kind, copyOf, id)) return false\n\t\tconst { [COPY_OF]: _, ...rest } = values\n\t\treturn Object.keys(rest).length ? redefineIn(registry, kind, id, rest) : true\n\t}\n\t// one of its own made of nothing, the same\n\tif (values[NEW_DEFINITION] === true && !definitionIn(registry, kind, id)) {\n\t\tif (!id) return false\n\t\t;(registry.kinds[kind] as Definitions<DataDefs[DataKind]>).define(blankDefinition(kind, id, unitKindOf(values.kind)))\n\t\tconst { [NEW_DEFINITION]: _, kind: __, ...rest } = values\n\t\treturn Object.keys(rest).length ? redefineIn(registry, kind, id, rest) : true\n\t}\n\tif (COPY_OF in values || NEW_DEFINITION in values) {\n\t\tconst { [COPY_OF]: _, [NEW_DEFINITION]: __, ...rest } = values\n\t\tvalues = rest\n\t}\n\tconst defs = registry.kinds[kind] as Definitions<DataDefs[DataKind]>\n\tconst def = defs.find(id)\n\tif (!def) return false\n\tdefs.define(withValues(def, values))\n\treturn true\n}\n\n/**\n * A new definition, a copy of one the registry has, by an id it has nothing by: what it is drawn as is the one it is\n * a copy of (`basedOn`) until the game gives it a look of its own. False for one it does not have, or an id it has\n *\n * @beta\n */\nexport function copyDefinition(registry: Registry, kind: DataKind, from: string, id: string): boolean {\n\tconst base = definitionIn(registry, kind, from)\n\tif (!base || definitionIn(registry, kind, id) || !id) return false\n\tconst copy = { ...base, id, basedOn: from }\n\t;(registry.kinds[kind] as Definitions<DataDefs[DataKind]>).define(copy as DataDefs[DataKind])\n\treturn true\n}\n\n/**\n * Takes a definition out of the registry (the Data panel's Delete): what is made of it from then on is not. False for\n * one it has not. Not for a world that runs: its units of the type are there\n *\n * @beta\n */\nexport function removeDefinition(registry: Registry, kind: DataKind, id: string): boolean {\n\treturn (registry.kinds[kind] as Definitions<DataDefs[DataKind]>).remove(id)\n}\n\n/**\n * The definition of a kind and id in the registry, as it is now, or undefined\n *\n * @beta\n */\nexport function definitionIn<K extends DataKind>(registry: Registry, kind: K, id: string): DataDefs[K] | undefined {\n\treturn (registry.kinds[kind] as Definitions<DataDefs[K]>).find(id)\n}\n\n/**\n * Every definition of a kind the registry has\n *\n * @beta\n */\nexport function definitionsIn<K extends DataKind>(registry: Registry, kind: K): DataDefs[K][] {\n\treturn (registry.kinds[kind] as Definitions<DataDefs[K]>).all()\n}\n\n/** Puts what a save kept of the definitions changed while it ran back into the registry: before its entities are made */\nexport function restoreRedefinitions(registry: Registry, kept: unknown): void {\n\tif (!isRecord(kept)) return\n\tfor (const kind of DATA_KINDS) {\n\t\tconst byId = kept[kind]\n\t\tif (!isRecord(byId)) continue\n\t\tfor (const [id, values] of Object.entries(byId)) if (isRecord(values)) redefineIn(registry, kind, id, values as DataValues)\n\t}\n}\n\n/** A path into a definition: names and places, joined by dots */\n/** A path into a definition, as the Data panel names a field: `stats.health` */\nexport const pathCheck: Check<string> = (value, path) => {\n\tconst text = string(value, path)\n\tif (!/^[A-Za-z_$][\\w$]*(\\.[\\w$]+)*$/.test(text)) throw new Invalid(`${path} is a path like stats.health`)\n\treturn text\n}\n\n/** A value of a field the Data panel may set: a number, words, yes or no, a list of words, or a list of things whole */\nexport const valueCheck: Check<FieldValue> = (value, path) => {\n\tif (isValue(value) && (typeof value !== 'string' || value.length <= 200)) return value\n\tif (isWords(value) && value.length <= MAX_LIST && value.every((each) => each.length <= MAX_WORD)) return value\n\tif (isRows(value)) return value\n\tthrow new Invalid(`${path} is a number, words, yes or no, a list of words, or a list of things`)\n}\n\n/** A definition changed while the game runs (`world.redefine`): to everyone, whose screens read the definitions */\nexport const toldRedefined = replicateEvent(definitionChanged, 'redefined', ({ kind, id, values }) =>\n\tvalues ? { type: 'redefined', kind, definition: id, values: structuredClone(values) } : undefined\n)\n","/*\n * A map's data as the engine reads it: the ground's layers, who plays, what stands on it, its names, and the constants they go by (design review E8a: `map.ts` in parts)\n */\nimport type { GameData } from '../gameData'\nimport type { AreaShape } from '../areas'\nimport type { PlayerId } from '../entity'\nimport type { GeneratedWith } from '../generate'\nimport type { Vec2 } from '../math'\nimport type { MapDoodadLight, MapEnvironment } from './look'\n\n/**\n * A map: the ground and what stands on it when the game begins, as data. The editor makes them, scenes play them.\n *\n * The ground is kept in layers that are edited apart and put together into a `Terrain`: the height of the land,\n * cliff levels, ramps between levels, water and paint. The layers are what a map file stores, the terrain is\n * derived from them whenever one changes.\n *\n * @beta\n */\nexport interface GameMap {\n\tname: string\n\tdescription: string\n\t/**\n\t * The game the map was made for, by the id of its module (`GameModule.id`): a world is not made from it for\n\t * another. For any game when left out, like the maps made before maps said\n\t */\n\tgame?: string\n\twidth: number\n\tdepth: number\n\t/** How much higher a level stands than the one below */\n\tcliffHeight: number\n\t/** Height of the land per vertex, row by row, before cliffs and water */\n\tground: Float32Array\n\t/** Cliff level per cell */\n\tlevels: Uint8Array\n\t/** 1 where a cell is part of a ramp: the levels around it are joined by a slope instead of a cliff */\n\tramps: Uint8Array\n\t/** `WATER_*` per cell */\n\twater: Uint8Array\n\t/** Paint per cell: 0 for none, otherwise 1 and up into `tileset` */\n\ttiles: Uint8Array\n\t/**\n\t * The game's own layers of cells (`CellLayerDef`), by id: where the bushes are. A value per cell, row by row. Left\n\t * out, or a layer left out, for none\n\t */\n\tcells?: Record<string, Uint8Array>\n\t/**\n\t * What is kept off each cell by hand, as the editor's pathing brush paints it: `BLOCKS_BUILD` (no building there),\n\t * `BLOCKS_WALK` (nothing walks or builds there), 0 for nothing. With what doodads keep off, into `Terrain.blocked`:\n\t * no-build zones, invisible walls. Left out for none. While the game runs, a game blocks the way with obstacles\n\t * (`world.nav.addObstacle`) and keeps buildings off with the `canPlace` hook\n\t */\n\tpathing?: Uint8Array\n\t/**\n\t * The tiles the paint of `tiles` is, by name: index 1 is the first. The game's own list, as the map is opened with\n\t * a game (`adoptTileset`); names the game does not have come after it, kept for the file\n\t */\n\ttileset: string[]\n\t/** The players who can take part. Neutral and the creeps are always there on top of these */\n\tplayers: MapPlayer[]\n\tobjects: MapObject[]\n\tcamps: MapCamp[]\n\t/** Parts of the map the rules watch by name: who walks in and out (see `MapRegion`) */\n\tregions: MapRegion[]\n\t/** Spots the rules know by name: where a wave comes in, where a hero waits (see `MapPoint`) */\n\tpoints: MapPoint[]\n\t/** Lines the rules know by name: a road, a patrol route (see `MapPath`) */\n\tpaths: MapPath[]\n\t/** Scenery, which the rules do not know of but where it blocks (see `MapDoodad`) */\n\tdoodads: MapDoodad[]\n\t/** Views of the map saved under names (see `MapCamera`) */\n\tcameras: MapCamera[]\n\t/** Groups what is placed can be drawn from when the game starts, and tables of what drops (see `MapRandomGroup`) */\n\trandomGroups?: MapRandomGroup[]\n\titemTables?: MapItemTable[]\n\t/**\n\t * The map's own definitions (campaign plan RC8), a `data.json` as the game's has it (`GameData`): laid over the\n\t * game's data as a world is made from the map, before its rules are checked. A footman of 200 health on this map\n\t * alone. Its rules hash has them, so a save of it is not one of another map with other definitions\n\t */\n\tdefinitions?: GameData\n\t/** Its teams, named, and what their players share (see `MapForce`). Teams by number only when left out */\n\tforces?: MapForce[]\n\t/** The races a lobby offers its players who have none fixed (`MapPlayer.race`), by id. All of the game's when left out */\n\traces?: string[]\n\t/** Who made it */\n\tauthor?: string\n\t/** The map's checks it does not want, by their rules' ids (`MapProblem.rule`): a desert map with no path to its mines */\n\tsilence?: string[]\n\t/** Who it is for, as lists show it: \"2 players\", \"2 v 2\" */\n\tmeantFor?: string\n\t/**\n\t * Whether the whole map starts explored for everyone, the fog over it all the same: its ground, and what stands on it\n\t * and belongs to no player (trees, mines, neutral buildings), seen from the first moment. Yes or no over the game's\n\t * (`FogRules.startExplored`); the game's when left out\n\t */\n\texplored?: boolean\n\t/** What the loading screen says while it loads */\n\tloading?: string\n\t/** A picture of it, for lists of maps: a small PNG as a data URL, made from its ground in the editor */\n\tpreview?: string\n\t/** What the map looks like beyond its ground: its water, light, sky (see `MapEnvironment`) */\n\tenvironment?: MapEnvironment\n\t/** The hour the game starts at, and whether it moves (see `MapDay`) */\n\tday?: MapDay\n\t/** How it was made, where a generator made it (`generateMap`): the seed and the options, for the same again or another */\n\tgenerated?: GeneratedWith\n\t/**\n\t * The part of the map play happens in, in cells, when it is not all of it: nothing on foot goes outside it, nothing\n\t * is built there, the camera keeps to it, and the screen darkens what is beyond. Scenery around the edge\n\t */\n\tbounds?: CellRect\n\t/**\n\t * What the game keeps with the map, for its rules to read: a difficulty, the waves of this level. Plain data,\n\t * as in a save. The engine never looks inside\n\t */\n\tdata: Record<string, unknown>\n\t/**\n\t * What the map's editor keeps with it of its own (what is hidden or locked, its groups, its views, the instances of\n\t * prefabs): saved with the map as plain data, read by no game, world or rule, and taken away for play\n\t * (`withoutEditor`). The engine never looks inside: the editor says what it holds\n\t */\n\teditor?: Record<string, unknown>\n\t/**\n\t * What the file held that this reader does not know, as it was: written back when the map is saved, so that a map\n\t * from a newer editor loses nothing by passing through an older one\n\t */\n\textra?: Record<string, unknown>\n}\n\n/** @beta */\nexport interface MapPlayer {\n\tid: PlayerId\n\tname: string\n\tteam: number\n\tcolor: [number, number, number]\n\t/** Where their base goes, for a game that gives everyone a start */\n\tstart?: Vec2\n\t/** Where their view starts, by the name of a camera of the map (`MapCamera`). Over their start when it has one */\n\tcamera?: string\n\t/**\n\t * Who plays them: a person, the computer, or nobody (an open slot left empty). The game's to say when left out: the\n\t * game reads it (`world.map.player(id)`), the engine does nothing with it\n\t */\n\tcontroller?: 'person' | 'computer' | 'nobody'\n\t/** What they start with, by resource id, over what the game gives everyone */\n\tresources?: Record<string, number>\n\t/**\n\t * The race they play, fixed by the map (a campaign's), of the game's races (`GameModule.races`), or `random`: not\n\t * chosen in a lobby. Left to the lobby, or the game's first, when left out\n\t */\n\trace?: string\n\t/** What the game's own fields for players were set to (`defineMapField` with `for: 'player'`) */\n\tdata?: Record<string, unknown>\n}\n\n/**\n * A team of a map, with a name, and what its players share: for the game to read (`world.map.forces`)\n *\n * @beta\n */\nexport interface MapForce {\n\t/** The team, as its players have it (`MapPlayer.team`) */\n\tteam: number\n\tname: string\n\t/** Its players see what each other sees. Teams always do in this engine: kept for the game to read */\n\tsharedVision?: boolean\n\t/** Its players can give orders to each other's units: for the game to read */\n\tsharedControl?: boolean\n}\n\n/**\n * A view of the map saved under a name: what the camera looks at, from how far, which way and how steeply. For\n * cinematics (`cut.camera('gate')`), a player's first view, and code (`client.lookFrom('gate')`). The screen's\n *\n * @beta\n */\nexport interface MapCamera {\n\t/** The editor's, see `MapRegion.id` */\n\tid: number\n\tname: string\n\tx: number\n\tz: number\n\tdistance: number\n\t/** Radians around the vertical axis, 0 looking north, and between the view and the ground */\n\tyaw: number\n\tpitch: number\n}\n\n/**\n * Something that stands on the map when the game begins: a unit, a building, a tree, a mine\n *\n * @beta\n */\nexport interface MapObject {\n\tid: number\n\ttype: string\n\towner: PlayerId\n\tx: number\n\tz: number\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. Left out: one picked for it */\n\tlook?: string\n\t/**\n\t * The random group it is drawn from when the game starts (`MapRandomGroup`, by name): `type` is what the editor\n\t * shows until then\n\t */\n\trandom?: string\n\t/** The item table it drops from when it dies (`MapItemTable`, by name) */\n\tdrops?: string\n\t/**\n\t * A name of its own, for the rules to find it by (`world.named('gate')`). No two things on a map have the same,\n\t * whatever they are\n\t */\n\tname?: string\n\t/** The health it starts with, as a part of what it can have: 0.5 is half. All of it when left out */\n\thealth?: number\n\t/** The mana it starts with, as a part of what it can have. What its type starts with when left out */\n\tmana?: number\n\t/** For a hero: the level it starts at */\n\tlevel?: number\n\t/** For a hero: what it has learned already, as the level of each ability by id. As far as its level lets it */\n\tabilities?: Record<string, number>\n\t/** The items it carries, by the id of each, as far as it has room */\n\titems?: string[]\n\t/** For a resource: how much there is of it. What its type holds when left out */\n\tamount?: number\n\t/** For a building: it starts as a site that is still to be built */\n\tunderConstruction?: boolean\n\t/** Seconds until it is gone, for what is not there to stay */\n\tlifetime?: number\n\t/**\n\t * What it is doing as the game begins, its own orders and no player's, one after the other (campaign plan MS2): a\n\t * guard walking a patrol route, a caravan on its road. Nothing but what a unit does by itself when left out\n\t */\n\torders?: MapObjectOrder[]\n\t/**\n\t * What the game's own fields were set to, by the id of each (see `defineMapField`). The engine does not look\n\t * inside: the `mapObject` hook hands it to the game\n\t */\n\tdata?: Record<string, unknown>\n}\n\n/**\n * An order a unit of the map is given as the game begins (`MapObject.orders`): to go somewhere (`move`), to walk to\n * and fro fighting what it meets (`patrol`), to stand somewhere and fight what comes near, coming back after\n * (`guard`), to stand its ground (`hold`); to a point, or along a path of the map by its name, bend after bend (a\n * patrol along one walks it back and forth)\n *\n * @beta\n */\nexport interface MapObjectOrder {\n\tkind: 'move' | 'patrol' | 'guard' | 'hold'\n\tpath?: string\n\tpoint?: Vec2\n}\n\n/**\n * A named part of the map, which becomes an area of the world made from it (`AreaDef`): the rules hear who walks in\n * and out (`enteredArea`, `leftArea`) and ask who is in it (`world.areas`), by its name\n *\n * @beta\n */\nexport interface MapRegion {\n\t/** The editor's, to tell regions apart while one is renamed. The world knows it by its name */\n\tid: number\n\t/** What the rules know it by. No two things on a map have the same, whatever they are */\n\tname: string\n\tshape: AreaShape\n\t/** What it is drawn in, in the editor, to tell it from the others. The editor picks one when left out */\n\tcolor?: [number, number, number]\n\t/** What the game's own fields for regions were set to, see `MapObject.data`: the `mapRegion` hook hands it to the game */\n\tdata?: Record<string, unknown>\n\t/**\n\t * A cinematic the region plays (ED4): for everyone, once, the first time a unit of a player walks in, unless the game\n\t * plays it its own way (`play: 'code'`: the region says which, `world.map.regions`, and the game's rules play it)\n\t */\n\tcinematic?: MapRegionCinematic\n}\n\n/**\n * The cinematic a region of the map plays (`MapRegion.cinematic`): which, by its id (`GameView.cinematics.defs`), and who\n * plays it: the engine, as a unit of a player first walks in (`'enter'`, when left out), or the game's own code\n * (`'code'`)\n *\n * @beta\n */\nexport interface MapRegionCinematic {\n\t/** The cinematic, by its id: the game's (`GameView.cinematics.defs`) */\n\tid: string\n\t/** Who plays it: the engine as a unit of a player first walks in (`'enter'`, when left out), or the game's code */\n\tplay?: 'enter' | 'code'\n}\n\n/**\n * A named spot of the map, facing a way: `world.map.point('spawn')`\n *\n * @beta\n */\nexport interface MapPoint {\n\t/** The editor's, see `MapRegion.id` */\n\tid: number\n\t/** What the rules know it by. No two things on a map have the same, whatever they are */\n\tname: string\n\tx: number\n\tz: number\n\t/** Radians, the way entities face: 0 is along +z */\n\tfacing: number\n\t/** What it is drawn in, in the editor */\n\tcolor?: [number, number, number]\n}\n\n/**\n * Scenery: a model on the map that is no entity of the rules, with no health, owner or place in a snapshot. A rock, a\n * fence, a ruined arch, free to lean, float and stretch. What it keeps off the cells under it (`blocks`) the terrain\n * has, for the paths of units and for building\n *\n * @beta\n */\nexport interface MapDoodad {\n\t/** The editor's, see `MapRegion.id` */\n\tid: number\n\t/** The model, by its path in `models/`: the map's own, the game's, or a shared one */\n\tmodel: string\n\tx: number\n\tz: number\n\t/** How high above the ground under it */\n\ty?: number\n\t/** Radians: which way it faces, the way entities do (0 is along +z), then how far it leans forward and to the side */\n\tyaw: number\n\tpitch?: number\n\troll?: number\n\t/** How much bigger or smaller it is drawn than it was made, across, up and deep */\n\tscale: [number, number, number]\n\t/** A colour it is drawn in, over its own */\n\ttint?: [number, number, number]\n\t/** What code knows it by (`client.doodads.named`). Doodads are the screen's: the rules never see them */\n\tname?: string\n\t/** What it keeps off the cells within `radius` of its middle: building there, or walking and building. Nothing when left out */\n\tblocks?: 'build' | 'walk'\n\t/**\n\t * A bridge: walked on, over deep water too, at its height (`y`) above the water. Nothing is built on it. Within\n\t * `radius` of its middle\n\t */\n\tbridge?: boolean\n\t/**\n\t * A gate: it keeps walking off the cells within `radius` while it is shut, and the rules open and shut it by its\n\t * name while the game runs (`setGate`). Shut when the game starts, unless `open`\n\t */\n\tgate?: boolean\n\topen?: boolean\n\t/** How far around its middle it blocks, in cells */\n\tradius?: number\n\t/**\n\t * A clip of its model it plays over and over (a windmill's sails, a flag, a chest held open), by its name: none when\n\t * left out, or as the game says of its model (`SceneryDef.animation`). It is drawn on its own while it plays\n\t */\n\tanimation?: string\n\t/**\n\t * Merged with the scenery near it, to be drawn in one go (`DoodadView`): yes when left out, as far as its model can be.\n\t * No keeps it a copy of its model's mesh: for a game's code that reaches for it\n\t */\n\tbatch?: boolean\n\t/**\n\t * This one's lights otherwise than its model's (`GameView.ground.scenery`): put out (`on: false`), another colour, brighter,\n\t * further. Laid over every light its model gives\n\t */\n\tlight?: MapDoodadLight\n\t/**\n\t * How this one is drawn by distance, over its model's (`MapDetail`): pinned to a level by its index (`level`: 0 always at\n\t * full), or levels of its own. As its model when left out\n\t */\n\tdetail?: MapDoodadDetail\n}\n\n/**\n * One way a thing is drawn, and when, as a map says it (`MapDetail.models`, `MapDoodad.detail`): the client's\n * `DetailLevel` without what only code can say. A level applies when any of its conditions holds; of a thing's levels the\n * last that applies is drawn, the first being its full self\n *\n * @beta\n */\nexport interface MapDetailLevel {\n\t/** What is drawn: a picture of the model (`impostor`), or nothing (`none`). The model, or `model`, when left out */\n\tdraw?: 'impostor' | 'none'\n\t/** Another model, by its path in `models/`, in place of the thing's own */\n\tmodel?: string\n\t/** Or a lighter version of the full model made from it: this part of its triangles (0.25) */\n\tratio?: number\n\t/** From this far from the camera, in cells */\n\tfrom?: number\n\t/** Or: once the thing is at most this tall on the screen, in pixels */\n\tunder?: number\n\t/** Or: while the camera is over a region of the map, by its name; or not over it (`!name`) */\n\tregion?: string\n\t/**\n\t * How its file is loaded: with the model (`eager`), once something comes near wanting it (`lazy`, when left out: within\n\t * half again its distance), by code alone (`never`), or as the camera comes over a region of the map, by its name\n\t */\n\tload?: 'eager' | 'lazy' | 'never' | { region: string }\n\t/**\n\t * The level its shadow is drawn at, by index: a lighter one is cheaper, and nobody sees a leaf's shadow. One of nothing\n\t * casts none. As the shadows' bias says when left out (`MapDetail.shadowBias`), else the level it is drawn at\n\t */\n\tshadow?: number\n}\n\n/**\n * How one doodad is drawn by distance (`MapDoodad.detail`)\n *\n * @beta\n */\nexport interface MapDoodadDetail {\n\t/** Always at this level, by its index: 0 at full */\n\tlevel?: number\n\t/** Its own levels, over its model's */\n\tlevels?: MapDetailLevel[]\n}\n\n/**\n * How much detail things are drawn with by their distance on a map (`MapEnvironment.detail`), over the game's\n * (`GameView.scene.detail`): a forest map drawn lighter. The screen's: the rules never see it\n *\n * @beta\n */\nexport interface MapDetail {\n\t/** Every distance a level starts from, times this: under 1 lighter sooner, over 1 later. The game's when left out */\n\tscale?: number\n\t/** Past this far from the camera, in cells, no scenery, tree or mine is drawn at all, nor casts a shadow. None when left out */\n\tcull?: number\n\t/**\n\t * How many levels coarser than it is drawn at a thing casts its shadow, where its level does not say (`shadow`): 1\n\t * draws a tree's shadow at its next lighter level. The game's when left out\n\t */\n\tshadowBias?: number\n\t/** The levels of every model that has none said of it, over the game's (`GameView.scene.detail.levels`) */\n\tlevels?: MapDetailLevel[]\n\t/** A model's levels, by its path in `models/`, over its own and the game's */\n\tmodels?: Record<string, MapDetailLevel[]>\n}\n\n/**\n * A group a placed thing is drawn from when the game starts (random groups, as classic map editors have them): one of these types by\n * weight, or any creep of a level (\"a level 3 creep\")\n *\n * @beta\n */\nexport interface MapRandomGroup {\n\tname: string\n\t/** One of these, more likely by its weight */\n\tchoices?: { type: string; weight: number }[]\n\t/** Or any unit type with a bounty, of this level */\n\tlevel?: number\n}\n\n/**\n * What something drops when it dies (item tables, as classic map editors have them): one item by weight, or none\n *\n * @beta\n */\nexport interface MapItemTable {\n\tname: string\n\titems: MapItemTableEntry[]\n\t/** How likely it is to drop anything, 0..1. Always when left out */\n\tchance?: number\n}\n\n/**\n * A line of an item table (`MapItemTable.items`): an item by id, or any item of a level, a class, or both (campaign\n * plan GP3: `{ level: 3, weight: 2 }`), its weight shared among those of the game that match\n *\n * @beta\n */\nexport interface MapItemTableEntry {\n\titem?: string\n\tlevel?: number\n\tclass?: string\n\tweight: number\n}\n\n/**\n * What a doodad keeps off a cell, in `Terrain.blocked`: building, walking too, or building on a bridge one walks on\n *\n * @beta\n */\nexport const BLOCKS_BUILD = 1\n/** @beta */\nexport const BLOCKS_WALK = 2\n/** @internal */\nexport const BRIDGE = 3\n\n/**\n * A named line of the map, through points in order, with a width: `world.map.path('road')` (see `Path`)\n *\n * @beta\n */\nexport interface MapPath {\n\t/** The editor's, see `MapRegion.id` */\n\tid: number\n\t/** What the rules know it by. No two things on a map have the same, whatever they are */\n\tname: string\n\tpoints: Vec2[]\n\t/** How wide it is, in cells: what it paints and keeps clear, and what `Path.contains` says is on it */\n\twidth: number\n\t/** A tile of the game's, by id, that the ground under it is painted with, over the map's own paint */\n\tpaint?: string\n\t/** Nothing may be built on it: a road the invaders need to get through */\n\tkeepClear?: boolean\n\t/** What it is drawn in, in the editor */\n\tcolor?: [number, number, number]\n\t/**\n\t * A road's or a river's bed under it, carved in the ground and painted each time the terrain is worked out (the\n\t * map's own heights stay as they are, so the bed follows the path wherever its points go): `PathProfile`\n\t */\n\tprofile?: PathProfile\n}\n\n/**\n * The bed a path carves, as a road or a river: its middle as smooth along it as a road is (the land along it averaged\n * over four cells each way), lowered by `depth`, level across `width`, eased into the land over `banks` cells each\n * side; painted with `ground`, and with water in it for a river\n *\n * @beta\n */\nexport interface PathProfile {\n\t/** How wide the bed is, in cells: the path's own width when left out */\n\twidth?: number\n\t/** How far below the land along it the bed is (0, a road; a river's bed with its water), in the heights' units */\n\tdepth?: number\n\t/** A tile of the game's the bed is painted with, by id (over the path's `paint`) */\n\tground?: string\n\t/** Over how many cells each side the bed is eased into the land: 2 when left out */\n\tbanks?: number\n\t/** Water in the bed: deep where `depth` is 1 or more, else shallow (a river, a ford) */\n\twater?: boolean\n}\n\n/**\n * The time of day of a map, in a game with days (`GameModule.day`). The rules': what is done at night is done by it\n *\n * @beta\n */\nexport interface MapDay {\n\t/** The hour the game starts at. The game's when left out */\n\tstart?: number\n\t/** The hour stays where it starts: always night, always noon */\n\tstill?: boolean\n}\n\n/**\n * Creeps that guard a spot\n *\n * @beta\n */\nexport interface MapCamp {\n\tid: number\n\tx: number\n\tz: number\n\t/** Unit types, the first one stands in the middle */\n\tunits: string[]\n\t/** A name of its own, for the rules to find it by (`campNamed(world, 'ogres')`), see `MapObject.name` */\n\tname?: string\n\t/** What the game's own fields for camps were set to, see `MapObject.data`: the `mapCamp` hook hands it to the game */\n\tdata?: Record<string, unknown>\n\t/** Seconds after it is cleared that it comes back (see `Camp.respawn`). The game's rule when left out */\n\trespawn?: number\n}\n\n/**\n * The format map files are written in. It goes up when a file of the format before would be read wrongly: a field\n * that changes what it means, or one a reader must not ignore. A step in `MIGRATIONS` then brings older files up to\n * it. A field that is merely new, and can be left out, needs no new format: a reader that does not know it carries\n * it along (`GameMap.extra`, and whatever an object, a player or a camp holds besides what is known)\n *\n * @internal\n */\nexport const MAP_FORMAT = 3\n/**\n * Owner of trees, mines and whatever belongs to nobody\n *\n * @beta\n */\nexport const MAP_NEUTRAL: PlayerId = 0\n/**\n * Owner of the creeps\n *\n * @beta\n */\nexport const MAP_CREEPS: PlayerId = 90\n/**\n * Players a map may have at most, whatever the game: each could be a team of its own, and the fog of war keeps 32\n * teams apart (`MAX_FOG_TEAMS`). How many a game allows is its own (`GameModule.maxPlayers`, 8 when it says nothing)\n *\n * @beta\n */\nexport const MAX_MAP_PLAYERS = 32\n/**\n * Players a game allows on a map when it does not say (`GameModule.maxPlayers`)\n *\n * @internal\n */\nexport const DEFAULT_MAX_PLAYERS = 8\n/**\n * Highest cliff level\n *\n * @beta\n */\nexport const MAX_LEVEL = 4\n/**\n * Cells a ramp reaches out on either side of where its slope is: long enough to walk up\n *\n * @internal\n */\nexport const RAMP_REACH = 3\n\n/** @beta */\nexport const PLAYER_COLORS: [number, number, number][] = [\n\t[0.16, 0.38, 0.95],\n\t[0.85, 0.14, 0.12],\n\t[0.1, 0.72, 0.62],\n\t[0.55, 0.2, 0.8],\n\t[0.95, 0.85, 0.15],\n\t[0.95, 0.55, 0.12],\n\t[0.25, 0.75, 0.2],\n\t[0.9, 0.45, 0.7],\n\t// past eight, as the classic twenty-four go on: each told apart from the eight and from each other\n\t[0.58, 0.58, 0.6],\n\t[0.5, 0.75, 0.95],\n\t[0.06, 0.38, 0.27],\n\t[0.45, 0.28, 0.1],\n\t[0.55, 0.05, 0.12],\n\t[0.05, 0.08, 0.45],\n\t[0.25, 0.85, 0.85],\n\t[0.72, 0.6, 0.95],\n\t[0.92, 0.82, 0.62],\n\t[0.98, 0.65, 0.5],\n\t[0.6, 0.95, 0.65],\n\t[0.82, 0.78, 0.98],\n\t[0.18, 0.18, 0.2],\n\t[0.95, 0.95, 0.95],\n\t[0.05, 0.6, 0.3],\n\t[0.6, 0.45, 0.2]\n]\n\n/** @beta */\nexport const playerSlot = (id: number): MapPlayer => ({ id, name: `Player ${id}`, team: id, color: PLAYER_COLORS[(id - 1) % PLAYER_COLORS.length] })\n\n/** @beta */\nexport interface NewMapOptions {\n\tname?: string\n\twidth: number\n\tdepth: number\n\t/** Height of the land everywhere */\n\theight?: number\n\tplayers?: number\n\t/** The game it is for, see `GameMap.game` */\n\tgame?: string\n\t/** The tiles it can be painted with, by name: the game's (`registry.tiles`). None when left out */\n\ttileset?: string[]\n}\n\n/**\n * Flat grass, two players and nothing on it\n *\n * @beta\n */\nexport function createMap(options: NewMapOptions): GameMap {\n\tconst { width, depth, height = 1, players = 2 } = options\n\tconst cells = width * depth\n\treturn {\n\t\tname: options.name ?? 'New map',\n\t\tdescription: '',\n\t\t...(options.game !== undefined && { game: options.game }),\n\t\twidth,\n\t\tdepth,\n\t\tcliffHeight: 3,\n\t\tground: new Float32Array((width + 1) * (depth + 1)).fill(height),\n\t\tlevels: new Uint8Array(cells),\n\t\tramps: new Uint8Array(cells),\n\t\twater: new Uint8Array(cells),\n\t\ttiles: new Uint8Array(cells),\n\t\ttileset: [...(options.tileset ?? [])],\n\t\tplayers: Array.from({ length: players }, (_, i) => playerSlot(i + 1)),\n\t\tobjects: [],\n\t\tcamps: [],\n\t\tregions: [],\n\t\tpoints: [],\n\t\tpaths: [],\n\t\tdoodads: [],\n\t\tcameras: [],\n\t\tdata: {}\n\t}\n}\n\n/**\n * A rectangle of a map, in cells\n *\n * @beta\n */\nexport interface CellRect {\n\tx: number\n\tz: number\n\twidth: number\n\tdepth: number\n}\n\n/**\n * The smallest a map can be made, each way: the editor's, and the size a map file is read at\n *\n * @internal\n */\nexport const MIN_MAP_SIZE = 8\n/**\n * The largest, the same for the editor and a map file. 512 until a game needs more (S37 is what makes more cost little)\n *\n * @beta\n */\nexport const MAX_MAP_SIZE = 512\n","/**\n * What the ground of a map can be painted with, named by the game: grass, road, sand. A cell holds the index of its\n * paint: 0 for none, left to the slope and the height, and 1 and up for the game's tiles in the order it gives them\n * (`GameModule.tiles`). The rules read and paint by name (`registry.tile('road')`); what each looks like is the\n * view's (`GameView.ground.tiles`).\n *\n * A map file says the name of each index it was painted with (`GameMap.tileset`), so that a map keeps its paint when\n * the game adds tiles or puts them in another order: it is brought in line with the game's list by name\n *\n * @beta\n */\nexport interface TileDef {\n\t/** Shared by every game, like other ids */\n\tid: string\n\t/** What the editor's palette calls it */\n\tname: string\n\t/**\n\t * How fast one on foot goes over it, as a multiplier of its speed: mud at 0.5, a road at 1.2. 1 when left out. What\n\t * flies or sails is not slowed; the game's own `moveSpeed` rule keeps the last word (`groundSpeedAt`)\n\t */\n\tspeed?: number\n}\n\n/**\n * Typed help for writing a tile\n *\n * @beta\n */\nexport const defineTile = (def: TileDef): TileDef => def\n\n/**\n * The most tiles a game can have: a cell holds its tile in a byte, and 0 is none\n *\n * @beta\n */\nexport const MAX_TILES = 255\n\n/**\n * The tiles every map was painted with before maps said which: the client's list as it was then, by index. A map\n * file of format 1 means these\n *\n * @internal\n */\nexport const LEGACY_TILESET: readonly string[] = ['grass', 'darkGrass', 'dirt', 'road', 'sand', 'rock', 'snow']\n\n/**\n * The index of each tile of `from` in `to`, by name: what turns paint made with one list into paint of the other.\n * A name `to` does not have is 0, no paint\n *\n * @internal\n */\nexport function tileRemap(from: readonly string[], to: readonly string[]): Uint8Array {\n\tconst table = new Uint8Array(from.length + 1)\n\tfrom.forEach((id, i) => (table[i + 1] = to.indexOf(id) + 1))\n\treturn table\n}\n","/*\n * What a map looks like beyond its ground, as data the engine carries and never reads: light, fog, sky, water, weather, tiles' looks (design review E8a: `map.ts` in parts)\n */\nimport { environmentChanged } from '#engine/engineEvents'\nimport { replicateEvent } from '../replication'\nimport { MAX_TILES } from '../tiles'\n\n/**\n * What a map looks like beyond its ground (design review E8c): the engine carries it (in the map, its file, a save,\n * what players are told as it changes: `world.setEnvironment`) and reads none of it but the map's own tiles, which are\n * paint like the game's. An open interface: the client adds what it draws by (its water, light, sky, fog, weather,\n * lights and the rest), as a game adds its commands (`Commands`)\n *\n * @beta\n */\nexport interface MapEnvironment {\n\t/** Ground of the map's own to paint with, past the game's tiles (see `MapTile`): the rules' paint, by id */\n\ttiles?: MapTile[]\n}\n\n/**\n * A ground of a map's own, to paint with as a game's tiles are (`MapEnvironment.tiles`): to the rules, paint by its id.\n * An open interface: the client adds its look (its picture, colour, pattern)\n *\n * @beta\n */\nexport interface MapTile {\n\t/** Its id in the map's paint (`GameMap.tileset`): none of the game's tiles' */\n\tid: string\n\t/** What the editor's palette calls it */\n\tname: string\n}\n\n/**\n * The ids of a map's own tiles (`MapEnvironment.tiles`)\n *\n * @beta\n */\nexport const mapTileIds = (environment: MapEnvironment | undefined): string[] => (environment?.tiles ?? []).map((tile) => tile.id)\n\n/**\n * The tiles a world from a map is painted with: the game's, then the map's own that are none of them, as many as a map\n * can hold. The order a played ground's paint is in, and its looks\n *\n * @beta\n */\nexport function playTileset(gameTiles: readonly string[], environment: MapEnvironment | undefined): string[] {\n\tconst own = mapTileIds(environment).filter((id) => !gameTiles.includes(id))\n\treturn [...gameTiles, ...own].slice(0, MAX_TILES)\n}\n\n/** The map's light, fog and sky changed (`world.setEnvironment`): to everyone */\nexport const toldEnvironment = replicateEvent(environmentChanged, 'environment', ({ environment, over }) => ({\n\ttype: 'environment',\n\tenvironment: structuredClone(environment),\n\t...(over && { over })\n}))\n\n/**\n * The light a doodad carries (`MapDoodad.light`), over the one its kind of doodad gives: an open interface the client\n * fills in with what a light of the map is (`MapLightSource`, less where it stands and its name)\n *\n * @beta\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface MapDoodadLight {}\n","/**\n * Small seeded PRNG (mulberry32). The simulation never touches Math.random so runs are reproducible.\n *\n * @beta\n */\nexport class Rng {\n\tprivate state: number\n\n\tconstructor(seed: number) {\n\t\tthis.state = seed >>> 0\n\t}\n\n\t/** Float in [0, 1) */\n\tnext(): number {\n\t\tthis.state = (this.state + 0x6d2b79f5) >>> 0\n\t\tlet t = this.state\n\t\tt = Math.imul(t ^ (t >>> 15), t | 1)\n\t\tt ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n\t\treturn ((t ^ (t >>> 14)) >>> 0) / 4294967296\n\t}\n\n\t/** Where it is in its sequence, for a save. `restore` with it carries on with the very same numbers */\n\tsave(): number {\n\t\treturn this.state\n\t}\n\n\trestore(state: number): void {\n\t\tthis.state = state >>> 0\n\t}\n\n\trange(min: number, max: number): number {\n\t\treturn min + (max - min) * this.next()\n\t}\n\n\t/** Integer in [min, max] */\n\tint(min: number, max: number): number {\n\t\treturn Math.floor(this.range(min, max + 1))\n\t}\n}\n","import { clamp, smoothstep, TAU, type Vec2 } from './math'\nimport { Rng } from './rng'\nimport { atan, atan2, cos, hypot, sin } from './exactMath'\n\n/** @beta */\nexport interface TerrainMesh {\n\tpositions: Float32Array\n\tindices: Uint32Array\n}\n\n/**\n * What covers a cell: nothing, water that can be waded through, or water nothing on foot crosses\n *\n * @beta\n */\nexport const WATER_NONE = 0\n/** @beta */\nexport const WATER_SHALLOW = 1\n/** @beta */\nexport const WATER_DEEP = 2\n\n/**\n * Water and paint of a terrain, next to its shape. Left out for plain ground\n *\n * @beta\n */\nexport interface TerrainSurface {\n\t/** `WATER_*` per cell, row by row */\n\twater?: Uint8Array\n\t/** Height of the surface of the water per vertex, for drawing it. Only means something around wet cells */\n\twaterHeights?: Float32Array\n\t/** What the ground is painted with per cell, row by row. 0 is left to the slope, what the rest are is up to the client */\n\ttiles?: Uint8Array\n\t/** What scenery keeps off each cell (`BLOCKS_BUILD`, `BLOCKS_WALK`), row by row: see `MapDoodad.blocks` */\n\tblocked?: Uint8Array\n\t/** The game's own layers of cells (`CellLayerDef`), by id: a value per cell, row by row */\n\tcells?: Record<string, Uint8Array>\n}\n\n/**\n * Heightfield ground. World space spans [0, width] x [0, depth] with one height sample per unit.\n * Rendering, navigation and the simulation all read from this same data.\n *\n * Next to the height, every cell has a level: the ground floor is 0, each cliff up is one more. The height is\n * what things stand on and where the eye sees a cliff, the level is what the rules go by: who sees whom\n * and who shoots uphill. Ramps belong to the lower level until halfway up.\n *\n * @beta\n */\nexport class Terrain {\n\treadonly vertsX: number\n\treadonly vertsZ: number\n\t/** Level per cell, row by row. The fog works out what is seen from them once: `world.fog.levelsChanged()` after writing to them in a running world */\n\treadonly levels: Uint8Array\n\t/** `WATER_*` per cell, row by row */\n\treadonly water: Uint8Array\n\t/** Height of the surface of the water per vertex */\n\treadonly waterHeights: Float32Array\n\t/** Paint per cell, row by row */\n\treadonly tiles: Uint8Array\n\t/** What scenery keeps off each cell, row by row: 1 building there, 2 walking and building (see `MapDoodad.blocks`) */\n\treadonly blocked: Uint8Array\n\t/**\n\t * The game's own layers of cells, by id (`CellLayerDef`): where the bushes are, what burns. A value per cell, row by\n\t * row; a layer nobody has painted is not there, and reads 0 everywhere (`cellAt`)\n\t */\n\treadonly cells: Record<string, Uint8Array>\n\t/**\n\t * The part of the map play happens in, in cells, when it is not all of it (`GameMap.bounds`): nothing on foot goes\n\t * outside it, nothing is built there, and the camera keeps to it. The edge beyond is scenery\n\t */\n\tbounds?: { x: number; z: number; width: number; depth: number }\n\n\tconstructor(\n\t\treadonly width: number,\n\t\treadonly depth: number,\n\t\treadonly heights: Float32Array,\n\t\tlevels?: Uint8Array,\n\t\tsurface: TerrainSurface = {}\n\t) {\n\t\tthis.vertsX = width + 1\n\t\tthis.vertsZ = depth + 1\n\t\tconst cells = width * depth\n\t\tif (heights.length !== this.vertsX * this.vertsZ) throw new Error('Terrain: heights do not match the size')\n\t\tif (levels && levels.length !== cells) throw new Error('Terrain: levels do not match the size')\n\t\tif (surface.water && surface.water.length !== cells) throw new Error('Terrain: water does not match the size')\n\t\tif (surface.tiles && surface.tiles.length !== cells) throw new Error('Terrain: tiles do not match the size')\n\t\tthis.levels = levels ?? new Uint8Array(cells)\n\t\tthis.water = surface.water ?? new Uint8Array(cells)\n\t\tthis.waterHeights = surface.waterHeights ?? new Float32Array(heights.length)\n\t\tthis.tiles = surface.tiles ?? new Uint8Array(cells)\n\t\tif (surface.blocked && surface.blocked.length !== cells) throw new Error('Terrain: what is blocked does not match the size')\n\t\tthis.blocked = surface.blocked ?? new Uint8Array(cells)\n\t\tthis.cells = {}\n\t\tfor (const [id, layer] of Object.entries(surface.cells ?? {})) {\n\t\t\tif (layer.length !== cells) throw new Error(`Terrain: the cells of ${id} do not match the size`)\n\t\t\tthis.cells[id] = layer\n\t\t}\n\t}\n\n\t/** The value of a layer of cells (`cells`) at a point: 0 off the ground, or where the layer is not there */\n\tcellAt(layer: string, x: number, z: number): number {\n\t\tconst cells = this.cells[layer]\n\t\tif (!cells || x < 0 || z < 0 || x >= this.width || z >= this.depth) return 0\n\t\treturn cells[Math.floor(z) * this.width + Math.floor(x)]\n\t}\n\n\t/** A layer of cells, made empty when it is not there yet */\n\tcellLayer(layer: string): Uint8Array {\n\t\treturn (this.cells[layer] ??= new Uint8Array(this.width * this.depth))\n\t}\n\n\t/**\n\t * Becomes another terrain, of whatever size, in place: what holds on to this one (the camera, what draws the ground)\n\t * sees the new one. For the editor, when a map is resized\n\t */\n\treplace(other: Terrain): void {\n\t\tObject.assign(this, {\n\t\t\twidth: other.width,\n\t\t\tdepth: other.depth,\n\t\t\tvertsX: other.vertsX,\n\t\t\tvertsZ: other.vertsZ,\n\t\t\theights: other.heights,\n\t\t\tlevels: other.levels,\n\t\t\twater: other.water,\n\t\t\twaterHeights: other.waterHeights,\n\t\t\ttiles: other.tiles,\n\t\t\tblocked: other.blocked,\n\t\t\tcells: other.cells,\n\t\t\tbounds: other.bounds\n\t\t})\n\t}\n\n\t/** Whether a cell is in the part of the map play happens in (`bounds`) */\n\tinPlay(cx: number, cz: number): boolean {\n\t\tconst { bounds } = this\n\t\treturn !bounds || (cx >= bounds.x && cz >= bounds.z && cx < bounds.x + bounds.width && cz < bounds.z + bounds.depth)\n\t}\n\n\t/** `WATER_*` of the cell a point is in */\n\twaterAt(x: number, z: number): number {\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\treturn this.water[cz * this.width + cx]\n\t}\n\n\tvertexHeight(ix: number, iz: number): number {\n\t\treturn this.heights[clamp(iz, 0, this.depth) * this.vertsX + clamp(ix, 0, this.width)]\n\t}\n\n\t/** Level of the cell a point is in */\n\tlevelAt(x: number, z: number): number {\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\treturn this.levels[cz * this.width + cx]\n\t}\n\n\tcontains(x: number, z: number): boolean {\n\t\treturn x >= 0 && z >= 0 && x <= this.width && z <= this.depth\n\t}\n\n\t/** Height at any point, interpolated over the same triangles `buildMesh` produces. */\n\theightAt(x: number, z: number): number {\n\t\tx = clamp(x, 0, this.width)\n\t\tz = clamp(z, 0, this.depth)\n\t\tconst ix = Math.min(Math.floor(x), this.width - 1)\n\t\tconst iz = Math.min(Math.floor(z), this.depth - 1)\n\t\tconst fx = x - ix\n\t\tconst fz = z - iz\n\t\tconst i = iz * this.vertsX + ix\n\t\tconst a = this.heights[i]\n\t\tconst b = this.heights[i + 1]\n\t\tconst c = this.heights[i + this.vertsX]\n\t\tconst d = this.heights[i + this.vertsX + 1]\n\t\tif (fx + fz <= 1) return a + (b - a) * fx + (c - a) * fz\n\t\treturn d + (c - d) * (1 - fx) + (b - d) * (1 - fz)\n\t}\n\n\t/** Surface normal (unnormalized y is always positive). */\n\tnormalAt(x: number, z: number, out: { x: number; y: number; z: number }): void {\n\t\tconst e = 0.5\n\t\tconst dx = this.heightAt(x + e, z) - this.heightAt(x - e, z)\n\t\tconst dz = this.heightAt(x, z + e) - this.heightAt(x, z - e)\n\t\tconst len = Math.sqrt(dx * dx + dz * dz + 1)\n\t\tout.x = -dx / len\n\t\tout.y = 1 / len\n\t\tout.z = -dz / len\n\t}\n\n\t/** Steepness in radians, 0 = flat. */\n\tslopeAt(x: number, z: number): number {\n\t\tconst e = 0.5\n\t\tconst dx = this.heightAt(x + e, z) - this.heightAt(x - e, z)\n\t\tconst dz = this.heightAt(x, z + e) - this.heightAt(x, z - e)\n\t\treturn atan(Math.sqrt(dx * dx + dz * dz))\n\t}\n\n\t/** First intersection of a ray with the ground, or null. */\n\traycast(ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, maxDist = 500): { x: number; y: number; z: number } | null {\n\t\tconst step = 0.5\n\t\tlet prevT = 0\n\t\tlet prevAbove = oy - this.heightAt(ox, oz) > 0 || !this.contains(ox, oz)\n\t\tfor (let t = step; t <= maxDist; t += step) {\n\t\t\tconst x = ox + dx * t\n\t\t\tconst z = oz + dz * t\n\t\t\tconst inside = this.contains(x, z)\n\t\t\tconst above = !inside || oy + dy * t > this.heightAt(x, z)\n\t\t\tif (prevAbove && !above) {\n\t\t\t\t// crossed the surface between prevT and t\n\t\t\t\tlet lo = prevT\n\t\t\t\tlet hi = t\n\t\t\t\tfor (let i = 0; i < 12; i++) {\n\t\t\t\t\tconst mid = (lo + hi) / 2\n\t\t\t\t\tconst mx = ox + dx * mid\n\t\t\t\t\tconst mz = oz + dz * mid\n\t\t\t\t\tif (oy + dy * mid > this.heightAt(mx, mz)) lo = mid\n\t\t\t\t\telse hi = mid\n\t\t\t\t}\n\t\t\t\tconst x2 = ox + dx * hi\n\t\t\t\tconst z2 = oz + dz * hi\n\t\t\t\treturn { x: x2, y: this.heightAt(x2, z2), z: z2 }\n\t\t\t}\n\t\t\tprevAbove = above\n\t\t\tprevT = t\n\t\t}\n\t\treturn null\n\t}\n\n\t/** @param walkable leaves out what nothing on foot may cross, for the navigation */\n\tbuildMesh(walkable = false): TerrainMesh {\n\t\tconst { vertsX, vertsZ, width, depth } = this\n\t\tconst positions = new Float32Array(vertsX * vertsZ * 3)\n\t\tfor (let iz = 0; iz < vertsZ; iz++) {\n\t\t\tfor (let ix = 0; ix < vertsX; ix++) {\n\t\t\t\tconst i = iz * vertsX + ix\n\t\t\t\tpositions[i * 3] = ix\n\t\t\t\tpositions[i * 3 + 1] = this.heights[i]\n\t\t\t\tpositions[i * 3 + 2] = iz\n\t\t\t}\n\t\t}\n\t\tconst indices = new Uint32Array(width * depth * 6)\n\t\tlet n = 0\n\t\tfor (let iz = 0; iz < depth; iz++) {\n\t\t\tfor (let ix = 0; ix < width; ix++) {\n\t\t\t\t// deep water is crossed on a bridge (3), and nothing crosses what blocks walking (2)\n\t\t\t\tconst blocked = this.blocked[iz * width + ix]\n\t\t\t\tif (walkable && ((this.water[iz * width + ix] === WATER_DEEP && blocked !== 3) || blocked === 2 || !this.inPlay(ix, iz))) continue\n\t\t\t\tconst a = iz * vertsX + ix\n\t\t\t\tconst b = a + 1\n\t\t\t\tconst c = a + vertsX\n\t\t\t\tconst d = c + 1\n\t\t\t\tindices[n++] = a\n\t\t\t\tindices[n++] = c\n\t\t\t\tindices[n++] = b\n\t\t\t\tindices[n++] = b\n\t\t\t\tindices[n++] = c\n\t\t\t\tindices[n++] = d\n\t\t\t}\n\t\t}\n\t\treturn { positions, indices: n === indices.length ? indices : indices.slice(0, n) }\n\t}\n\n\t/** Whether any cell is deep water: what boats go on */\n\tget hasDeepWater(): boolean {\n\t\treturn this.water.includes(WATER_DEEP)\n\t}\n\n\t/**\n\t * The deep water as a mesh, at its surface: where what goes on water can go (`UnitTypeDef.naval`). Under a bridge\n\t * too. Empty where the map has no deep water\n\t */\n\tbuildWaterMesh(): TerrainMesh {\n\t\tconst { vertsX, vertsZ, width, depth } = this\n\t\tconst positions = new Float32Array(vertsX * vertsZ * 3)\n\t\tfor (let iz = 0; iz < vertsZ; iz++) {\n\t\t\tfor (let ix = 0; ix < vertsX; ix++) {\n\t\t\t\tconst i = iz * vertsX + ix\n\t\t\t\tpositions[i * 3] = ix\n\t\t\t\tpositions[i * 3 + 1] = this.waterHeights[i]\n\t\t\t\tpositions[i * 3 + 2] = iz\n\t\t\t}\n\t\t}\n\t\tconst indices: number[] = []\n\t\tfor (let iz = 0; iz < depth; iz++) {\n\t\t\tfor (let ix = 0; ix < width; ix++) {\n\t\t\t\tif (this.water[iz * width + ix] !== WATER_DEEP || !this.inPlay(ix, iz)) continue\n\t\t\t\tconst a = iz * vertsX + ix\n\t\t\t\tindices.push(a, a + vertsX, a + 1, a + 1, a + vertsX, a + vertsX + 1)\n\t\t\t}\n\t\t}\n\t\treturn { positions, indices: Uint32Array.from(indices) }\n\t}\n\n\t/** The height of the water's surface at a point, over the same triangles as the ground */\n\twaterHeightAt(x: number, z: number): number {\n\t\tx = clamp(x, 0, this.width)\n\t\tz = clamp(z, 0, this.depth)\n\t\tconst ix = Math.min(Math.floor(x), this.width - 1)\n\t\tconst iz = Math.min(Math.floor(z), this.depth - 1)\n\t\tconst fx = x - ix\n\t\tconst fz = z - iz\n\t\tconst i = iz * this.vertsX + ix\n\t\tconst a = this.waterHeights[i]\n\t\tconst b = this.waterHeights[i + 1]\n\t\tconst c = this.waterHeights[i + this.vertsX]\n\t\tconst d = this.waterHeights[i + this.vertsX + 1]\n\t\tif (fx + fz <= 1) return a + (b - a) * fx + (c - a) * fz\n\t\treturn d + (c - d) * (1 - fx) + (b - d) * (1 - fz)\n\t}\n}\n\n/**\n * A way up a plateau\n *\n * @beta\n */\nexport interface RampSpec {\n\t/** The ramp comes down on the side of the plateau that faces this point */\n\ttowards: Vec2\n\t/** How wide it is, in world units */\n\twidth?: number\n}\n\n/**\n * High ground: a roughly round area lifted by whole levels, with cliffs all around except where a ramp leads up\n *\n * @beta\n */\nexport interface PlateauSpec {\n\tx: number\n\tz: number\n\tradius: number\n\t/** How many levels it rises above what is around it. One when left out */\n\tlevels?: number\n\tramps?: RampSpec[]\n}\n\n/** @beta */\nexport interface TerrainGenOptions {\n\twidth: number\n\tdepth: number\n\tseed: number\n\t/** Height of the rolling hills */\n\thillHeight?: number\n\t/** Size of the hills in world units */\n\thillScale?: number\n\t/** Steep unwalkable rock formations */\n\trocks?: { x: number; z: number; radius: number; height: number }[]\n\t/** Areas levelled to a constant height, for bases */\n\tflats?: { x: number; z: number; radius: number }[]\n\t/** High ground with cliffs and ramps */\n\tplateaus?: PlateauSpec[]\n\t/** How much higher one level stands than the one below */\n\tcliffHeight?: number\n}\n\n/** A ramp is this many times as long as it is high. Gentle enough to walk, too steep to build on */\nconst RAMP_SLOPE = 2.5\nconst RAMP_WIDTH = 6\n\n/**\n * How far up the plateau a point is: 1 on top, 0 below, in between on a ramp.\n * The edge wobbles a little so plateaus are not perfect circles.\n */\nfunction plateauShape(plateau: PlateauSpec, cliffHeight: number, rng: Rng): (x: number, z: number) => number {\n\tconst { levels = 1 } = plateau\n\tconst length = levels * cliffHeight * RAMP_SLOPE\n\tconst wobble = [rng.next() * TAU, rng.next() * TAU]\n\tconst edgeAt = (angle: number) => plateau.radius * (1 + 0.05 * sin(3 * angle + wobble[0]) + 0.03 * sin(5 * angle + wobble[1]))\n\tconst ramps = (plateau.ramps ?? []).map((ramp) => {\n\t\tconst angle = atan2(ramp.towards.x - plateau.x, ramp.towards.z - plateau.z)\n\t\treturn { sin: sin(angle), cos: cos(angle), halfWidth: (ramp.width ?? RAMP_WIDTH) / 2, edge: edgeAt(angle) }\n\t})\n\treturn (x, z) => {\n\t\tconst dx = x - plateau.x\n\t\tconst dz = z - plateau.z\n\t\tfor (const ramp of ramps) {\n\t\t\tconst across = Math.abs(dx * ramp.cos - dz * ramp.sin)\n\t\t\tconst along = dx * ramp.sin + dz * ramp.cos\n\t\t\t// the ramp straddles the edge, half of it on top of the plateau and half below\n\t\t\tconst top = ramp.edge - length / 2\n\t\t\tif (across > ramp.halfWidth || along < top) continue\n\t\t\treturn 1 - smoothstep(0, 1, (along - top) / length)\n\t\t}\n\t\treturn hypot(dx, dz) < edgeAt(atan2(dx, dz)) ? 1 : 0\n\t}\n}\n\n/** @beta */\nexport function generateTerrain(options: TerrainGenOptions): Terrain {\n\tconst { width, depth, seed, hillHeight = 2.5, hillScale = 28, rocks = [], flats = [], plateaus = [], cliffHeight = 3 } = options\n\tconst rng = new Rng(seed)\n\n\tconst latticeSize = 64\n\tconst lattice = new Float32Array(latticeSize * latticeSize)\n\tfor (let i = 0; i < lattice.length; i++) lattice[i] = rng.next()\n\t// after the hills, so that adding a plateau leaves the rest of the map as it was\n\tconst shapes = plateaus.map((plateau) => ({ levels: plateau.levels ?? 1, shape: plateauShape(plateau, cliffHeight, rng) }))\n\tconst latticeAt = (x: number, z: number) =>\n\t\tlattice[(((z % latticeSize) + latticeSize) % latticeSize) * latticeSize + (((x % latticeSize) + latticeSize) % latticeSize)]\n\tconst noise = (x: number, z: number) => {\n\t\tconst ix = Math.floor(x)\n\t\tconst iz = Math.floor(z)\n\t\tconst fx = smoothstep(0, 1, x - ix)\n\t\tconst fz = smoothstep(0, 1, z - iz)\n\t\tconst top = latticeAt(ix, iz) + (latticeAt(ix + 1, iz) - latticeAt(ix, iz)) * fx\n\t\tconst bottom = latticeAt(ix, iz + 1) + (latticeAt(ix + 1, iz + 1) - latticeAt(ix, iz + 1)) * fx\n\t\treturn top + (bottom - top) * fz\n\t}\n\n\tconst vertsX = width + 1\n\tconst heights = new Float32Array(vertsX * (depth + 1))\n\tfor (let iz = 0; iz <= depth; iz++) {\n\t\tfor (let ix = 0; ix <= width; ix++) {\n\t\t\tlet h = 0\n\t\t\tlet amplitude = 1\n\t\t\tlet frequency = 1 / hillScale\n\t\t\tlet total = 0\n\t\t\tfor (let octave = 0; octave < 3; octave++) {\n\t\t\t\th += noise(ix * frequency, iz * frequency) * amplitude\n\t\t\t\ttotal += amplitude\n\t\t\t\tamplitude *= 0.4\n\t\t\t\tfrequency *= 2.3\n\t\t\t}\n\t\t\th = (h / total) * hillHeight\n\n\t\t\tfor (const flat of flats) {\n\t\t\t\tconst d = hypot(ix - flat.x, iz - flat.z)\n\t\t\t\tconst flatHeight = hillHeight * 0.5\n\t\t\t\tconst blend = smoothstep(0, 1, (d - flat.radius) / (flat.radius * 0.6))\n\t\t\t\th = flatHeight + (h - flatHeight) * blend\n\t\t\t}\n\t\t\t// the hills go on on top of the plateaus, which is why these come after the flats\n\t\t\tfor (const { levels, shape } of shapes) h += shape(ix, iz) * levels * cliffHeight\n\t\t\tfor (const rock of rocks) {\n\t\t\t\tconst d = hypot(ix - rock.x, iz - rock.z)\n\t\t\t\tif (d < rock.radius) h += rock.height * smoothstep(0, 1, 1 - d / rock.radius)\n\t\t\t}\n\t\t\theights[iz * vertsX + ix] = h\n\t\t}\n\t}\n\n\tconst levels = new Uint8Array(width * depth)\n\tif (shapes.length) {\n\t\tfor (let cz = 0; cz < depth; cz++) {\n\t\t\tfor (let cx = 0; cx < width; cx++) {\n\t\t\t\tlet level = 0\n\t\t\t\tfor (const shape of shapes) if (shape.shape(cx + 0.5, cz + 0.5) >= 0.5) level += shape.levels\n\t\t\t\tlevels[cz * width + cx] = level\n\t\t\t}\n\t\t}\n\t}\n\treturn new Terrain(width, depth, heights, levels)\n}\n","import { hypot } from '../exactMath'\nimport { clamp, smoothstep } from '../math'\nimport { WATER_DEEP, WATER_SHALLOW } from '../terrain'\nimport type { GameMap, MapPath, PathProfile } from './types'\n\n/*\n * Roads and rivers carved as the terrain is worked out (EQ19): a path with a profile (`MapPath.profile`) lowers and\n * levels the ground under it from the map's own land, which stays as it is painted, so the bed follows the path's\n * points wherever they go, and an edit of a few cells works out a few cells again (`updateMapTerrain`'s area). The same\n * in every engine: square roots, sums and smoothsteps, no sines.\n */\n\n/**\n * How deep the ground is under water, by its kind (none, shallow, deep)\n *\n * @internal\n */\nexport const WATER_DEPTH = [0, 0.45, 1.6]\n\n/**\n * How far along a path its land is averaged each way, in cells: what makes a road as smooth along it as a road is\n *\n * @beta\n */\nexport const PROFILE_SMOOTH = 4\n\n/**\n * How far a path's profile reaches from its line, in cells: half its bed and its banks\n *\n * @beta\n */\nexport function profileReach(path: Pick<MapPath, 'width' | 'profile'>): number {\n\tconst profile = path.profile ?? {}\n\treturn Math.max(profile.width ?? path.width, 1) / 2 + Math.max(profile.banks ?? 2, 0)\n}\n\n/** How deep the water in a profile's bed is */\nconst waterOf = (profile: PathProfile) => (!profile.water ? 0 : (profile.depth ?? 0) >= 1 ? WATER_DEEP : WATER_SHALLOW)\n\n/** How far the land along a path is read, in cells: every half a cell from each point */\nconst STEP = 0.5\n\n/**\n * A path's line as the carve reads it: its segments, how far along each begins, and its land along it smoothed (from\n * each point every half a cell, so a moved point changes the samples of its own two segments alone)\n */\ninterface Line {\n\tpoints: { x: number; z: number }[]\n\tstarts: number[]\n\talong: number[]\n\theight: number[]\n}\n\n/** The map's own land at a point, between its corners: the heights a carve starts from */\nfunction landAt(map: GameMap, x: number, z: number): number {\n\tconst vx = map.width + 1\n\tconst fx = clamp(x, 0, map.width)\n\tconst fz = clamp(z, 0, map.depth)\n\tconst ix = Math.min(Math.floor(fx), map.width - 1)\n\tconst iz = Math.min(Math.floor(fz), map.depth - 1)\n\tconst tx = fx - ix\n\tconst tz = fz - iz\n\tconst g = map.ground\n\tconst a = g[iz * vx + ix] + (g[iz * vx + ix + 1] - g[iz * vx + ix]) * tx\n\tconst b = g[(iz + 1) * vx + ix] + (g[(iz + 1) * vx + ix + 1] - g[(iz + 1) * vx + ix]) * tx\n\treturn a + (b - a) * tz\n}\n\nfunction lineOf(map: GameMap, path: MapPath): Line {\n\tconst { points } = path\n\tconst starts = [0]\n\tconst along: number[] = []\n\tconst raw: number[] = []\n\tfor (let i = 0; i < points.length - 1; i++) {\n\t\tconst a = points[i]\n\t\tconst b = points[i + 1]\n\t\tconst length = hypot(b.x - a.x, b.z - a.z)\n\t\tstarts.push(starts[i] + length)\n\t\tfor (let d = 0; d < length; d += STEP) {\n\t\t\tconst t = d / length\n\t\t\talong.push(starts[i] + d)\n\t\t\traw.push(landAt(map, a.x + (b.x - a.x) * t, a.z + (b.z - a.z) * t))\n\t\t}\n\t}\n\tconst last = points[points.length - 1]\n\talong.push(starts[starts.length - 1])\n\traw.push(landAt(map, last.x, last.z))\n\t// each sample the mean of those within PROFILE_SMOOTH of it along the path\n\tconst height = new Array<number>(raw.length)\n\tlet from = 0\n\tlet to = 0\n\tlet sum = 0\n\tfor (let k = 0; k < raw.length; k++) {\n\t\twhile (to < raw.length && along[to] <= along[k] + PROFILE_SMOOTH) sum += raw[to++]\n\t\twhile (along[from] < along[k] - PROFILE_SMOOTH) sum -= raw[from++]\n\t\theight[k] = sum / (to - from)\n\t}\n\treturn { points, starts, along, height }\n}\n\n/** The smoothed land at a distance along a line */\nfunction heightAlong(line: Line, at: number): number {\n\tconst { along, height } = line\n\tif (at <= along[0]) return height[0]\n\tif (at >= along[along.length - 1]) return height[height.length - 1]\n\tlet lo = 0\n\tlet hi = along.length - 1\n\twhile (hi - lo > 1) {\n\t\tconst mid = (lo + hi) >> 1\n\t\tif (along[mid] <= at) lo = mid\n\t\telse hi = mid\n\t}\n\tconst span = along[hi] - along[lo] || 1\n\treturn height[lo] + (height[hi] - height[lo]) * ((at - along[lo]) / span)\n}\n\n/** The nearest point of a line to a point within `reach`: how far, and how far along; nothing beyond `reach` */\nfunction nearest(line: Line, x: number, z: number, reach: number): { distance: number; along: number } | undefined {\n\tlet best = reach\n\tlet along = -1\n\tconst { points, starts } = line\n\tfor (let i = 0; i < points.length - 1; i++) {\n\t\tconst a = points[i]\n\t\tconst b = points[i + 1]\n\t\t// (a segment whose box is out of reach is not looked at)\n\t\tif (x < Math.min(a.x, b.x) - best || x > Math.max(a.x, b.x) + best || z < Math.min(a.z, b.z) - best || z > Math.max(a.z, b.z) + best) continue\n\t\tconst dx = b.x - a.x\n\t\tconst dz = b.z - a.z\n\t\tconst span = dx * dx + dz * dz\n\t\tconst t = span ? clamp(((x - a.x) * dx + (z - a.z) * dz) / span, 0, 1) : 0\n\t\tconst d = hypot(x - (a.x + dx * t), z - (a.z + dz * t))\n\t\tif (d <= best) {\n\t\t\tbest = d\n\t\t\talong = starts[i] + t * (starts[i + 1] - starts[i])\n\t\t}\n\t}\n\treturn along < 0 ? undefined : { distance: best, along }\n}\n\n/**\n * The ground the paths with a profile carve, for the corners `x0..x1` × `z0..z1` (row by row), and the water they put\n * in the cells `x0 - 1..x1` × `z0 - 1..z1` (row by row; 0 where they put none): nothing where no profile reaches\n *\n * @internal\n */\nexport function profiledGround(\n\tmap: GameMap,\n\tx0: number,\n\tz0: number,\n\tx1: number,\n\tz1: number\n): { ground: Float64Array; water: Uint8Array | undefined } | undefined {\n\tconst profiled = map.paths.filter((path) => path.profile && path.points.length > 1)\n\tif (!profiled.length) return undefined\n\tconst vx = map.width + 1\n\tconst row = x1 - x0 + 1\n\tlet ground: Float64Array | undefined\n\tlet water: Uint8Array | undefined\n\tconst cellRow = x1 - x0 + 2\n\t/** The corners as the map has them, the first time a profile reaches one */\n\tconst corners = (): Float64Array => {\n\t\tif (ground) return ground\n\t\tground = new Float64Array(row * (z1 - z0 + 1))\n\t\tfor (let z = z0; z <= z1; z++) for (let x = x0; x <= x1; x++) ground[(z - z0) * row + (x - x0)] = map.ground[z * vx + x]\n\t\treturn ground\n\t}\n\tfor (const path of profiled) {\n\t\tconst profile = path.profile!\n\t\tconst reach = profileReach(path)\n\t\tconst xs = path.points.map((p) => p.x)\n\t\tconst zs = path.points.map((p) => p.z)\n\t\tif (Math.max(...xs) + reach < x0 - 1 || Math.min(...xs) - reach > x1 || Math.max(...zs) + reach < z0 - 1 || Math.min(...zs) - reach > z1) continue\n\t\tconst line = lineOf(map, path)\n\t\tconst half = Math.max(profile.width ?? path.width, 1) / 2\n\t\tconst banks = Math.max(profile.banks ?? 2, 0)\n\t\tconst kind = waterOf(profile)\n\t\t// with water in it, the water is part of the depth: the bed is lowered by the rest\n\t\tconst lowered = Math.max((profile.depth ?? 0) - WATER_DEPTH[kind], 0)\n\t\tconst vx0 = Math.max(Math.floor(Math.min(...xs) - reach), x0)\n\t\tconst vz0 = Math.max(Math.floor(Math.min(...zs) - reach), z0)\n\t\tconst vx1 = Math.min(Math.ceil(Math.max(...xs) + reach), x1)\n\t\tconst vz1 = Math.min(Math.ceil(Math.max(...zs) + reach), z1)\n\t\tfor (let iz = vz0; iz <= vz1; iz++) {\n\t\t\tfor (let ix = vx0; ix <= vx1; ix++) {\n\t\t\t\tconst near = nearest(line, ix, iz, reach)\n\t\t\t\tif (!near) continue\n\t\t\t\tconst carved = corners()\n\t\t\t\t// on the bed all of it; over the banks less and less, eased\n\t\t\t\tconst weight = near.distance <= half ? 1 : 1 - smoothstep(0, 1, (near.distance - half) / (banks || 1))\n\t\t\t\tconst at = (iz - z0) * row + (ix - x0)\n\t\t\t\tconst bed = heightAlong(line, near.along) - lowered\n\t\t\t\tcarved[at] += (bed - carved[at]) * weight\n\t\t\t}\n\t\t}\n\t\tif (!kind) continue\n\t\tfor (let cz = Math.max(vz0 - 1, z0 - 1, 0); cz <= Math.min(vz1, z1, map.depth - 1); cz++) {\n\t\t\tfor (let cx = Math.max(vx0 - 1, x0 - 1, 0); cx <= Math.min(vx1, x1, map.width - 1); cx++) {\n\t\t\t\tconst near = nearest(line, cx + 0.5, cz + 0.5, half)\n\t\t\t\tif (!near) continue\n\t\t\t\tcorners()\n\t\t\t\twater ??= new Uint8Array(cellRow * (z1 - z0 + 2))\n\t\t\t\tconst at = (cz - z0 + 1) * cellRow + (cx - x0 + 1)\n\t\t\t\twater[at] = Math.max(water[at], kind)\n\t\t\t}\n\t\t}\n\t}\n\treturn ground && { ground, water }\n}\n","/*\n * The terrain a map describes, made from its layers, and its paint brought in line with a game's tiles (design review E8a: `map.ts` in parts)\n */\nimport { hypot } from '../exactMath'\nimport { clamp } from '../math'\nimport { Path } from '../paths'\nimport { Terrain } from '../terrain'\nimport { MAX_TILES, tileRemap } from '../tiles'\nimport { BLOCKS_BUILD, BLOCKS_WALK, BRIDGE, type CellRect, type GameMap, RAMP_REACH } from './types'\nimport { profiledGround, WATER_DEPTH } from './pathProfile'\n/** How far below the banks the water stands */\nconst WATER_SURFACE = 0.18\n\n/**\n * The terrain a map describes\n *\n * @beta\n */\nexport function mapTerrain(map: GameMap): Terrain {\n\tconst terrain = new Terrain(map.width, map.depth, new Float32Array(map.ground.length), new Uint8Array(map.levels.length), {\n\t\twater: new Uint8Array(map.water.length),\n\t\ttiles: new Uint8Array(map.tiles.length)\n\t})\n\tupdateMapTerrain(map, terrain)\n\treturn terrain\n}\n\n/**\n * What the doodads of a map keep off its cells, and what is kept off them by hand (`GameMap.pathing`), into the\n * terrain (`Terrain.blocked`): the most any of them keeps off. With `area` (cells), there alone: what the layers changed\n * there (a brush's step), the doodads elsewhere as they were; the whole map where a doodad itself changed\n *\n * @beta\n */\nexport function blockByDoodads(map: Pick<GameMap, 'doodads' | 'width' | 'depth' | 'pathing'>, terrain: Terrain, area?: CellRect): void {\n\tconst { blocked } = terrain\n\tconst x0 = area ? Math.max(Math.floor(area.x), 0) : 0\n\tconst z0 = area ? Math.max(Math.floor(area.z), 0) : 0\n\tconst x1 = area ? Math.min(Math.ceil(area.x + area.width), map.width) : map.width\n\tconst z1 = area ? Math.min(Math.ceil(area.z + area.depth), map.depth) : map.depth\n\tif (x1 <= x0 || z1 <= z0) return\n\t// by hand first: a bridge laid over it after is still a bridge, but over a wall painted there nothing walks\n\tconst byHand = map.pathing && map.pathing.length === blocked.length ? map.pathing : undefined\n\tfor (let cz = z0; cz < z1; cz++)\n\t\tfor (let c = cz * map.width + x0; c < cz * map.width + x1; c++) blocked[c] = byHand ? Math.min(byHand[c], BLOCKS_WALK) : 0\n\tfor (const doodad of map.doodads ?? []) {\n\t\tif (!doodad.radius) continue\n\t\t// (one whose reach is all outside the area is as it was)\n\t\tif (doodad.x + doodad.radius < x0 || doodad.x - doodad.radius > x1 || doodad.z + doodad.radius < z0 || doodad.z - doodad.radius > z1) continue\n\t\t// a gate keeps building off; walking it keeps off while the game runs, as it is shut (`setGate`)\n\t\tconst kind = doodad.bridge ? BRIDGE : doodad.gate ? BLOCKS_BUILD : doodad.blocks === 'walk' ? BLOCKS_WALK : doodad.blocks ? BLOCKS_BUILD : 0\n\t\tif (!kind) continue\n\t\tconst { radius } = doodad\n\t\tfor (let cz = Math.max(Math.floor(doodad.z - radius), z0); cz < Math.min(Math.ceil(doodad.z + radius), z1); cz++) {\n\t\t\tfor (let cx = Math.max(Math.floor(doodad.x - radius), x0); cx < Math.min(Math.ceil(doodad.x + radius), x1); cx++) {\n\t\t\t\t// a cell whose middle is within reach\n\t\t\t\tif (hypot(cx + 0.5 - doodad.x, cz + 0.5 - doodad.z) > radius) continue\n\t\t\t\tconst c = cz * map.width + cx\n\t\t\t\t// a bridge over what blocks is a bridge: it is how one gets over\n\t\t\t\tblocked[c] = kind === BRIDGE || blocked[c] === BRIDGE ? (blocked[c] === BLOCKS_WALK ? BLOCKS_WALK : BRIDGE) : Math.max(blocked[c], kind)\n\t\t\t}\n\t\t}\n\t}\n\t// what is walked on a bridge is its deck: the ground under it as high as the water, and its height over that\n\tconst row = map.width + 1\n\tfor (const doodad of map.doodads ?? []) {\n\t\tif (!doodad.bridge || !doodad.radius) continue\n\t\tif (doodad.x + doodad.radius < x0 || doodad.x - doodad.radius > x1 || doodad.z + doodad.radius < z0 || doodad.z - doodad.radius > z1) continue\n\t\tfor (let cz = Math.max(Math.floor(doodad.z - doodad.radius), 0); cz < Math.min(Math.ceil(doodad.z + doodad.radius), map.depth); cz++) {\n\t\t\tfor (let cx = Math.max(Math.floor(doodad.x - doodad.radius), 0); cx < Math.min(Math.ceil(doodad.x + doodad.radius), map.width); cx++) {\n\t\t\t\tif (hypot(cx + 0.5 - doodad.x, cz + 0.5 - doodad.z) > doodad.radius) continue\n\t\t\t\tfor (const v of [cz * row + cx, cz * row + cx + 1, (cz + 1) * row + cx, (cz + 1) * row + cx + 1]) {\n\t\t\t\t\tconst deck = Math.max(terrain.waterHeights[v], terrain.heights[v]) + (doodad.y ?? 0)\n\t\t\t\t\tif (terrain.heights[v] < deck) terrain.heights[v] = deck\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * How far a change to a cell reaches into the terrain: a ramp's slope is the average of the levels within\n * `RAMP_REACH`, and a ramp cell's level is its corners'\n */\nconst REACH = RAMP_REACH + 1\n\n/**\n * Brings a terrain of the same size in line with the layers of a map, in place, for editing. With `area`, only what\n * a change to those cells can have changed: the cells and the corners of cells within reach of it. Returns the cells\n * whose terrain was worked out again, for whoever draws it to draw again: their corners are the vertices that changed\n *\n * @beta\n */\nexport function updateMapTerrain(map: GameMap, terrain: Terrain, area?: CellRect): CellRect {\n\tconst { width, depth, cliffHeight, levels, ramps, water, ground } = map\n\tif (terrain.width !== width || terrain.depth !== depth) throw new Error('updateMapTerrain: the terrain is not the size of the map')\n\tterrain.bounds = map.bounds && { ...map.bounds }\n\tconst vx = width + 1\n\t// the cells, and the vertices at their corners, that can have changed\n\tconst x0 = area ? Math.max(Math.floor(area.x) - REACH, 0) : 0\n\tconst z0 = area ? Math.max(Math.floor(area.z) - REACH, 0) : 0\n\tconst x1 = area ? Math.min(Math.ceil(area.x + area.width) + REACH, width) : width\n\tconst z1 = area ? Math.min(Math.ceil(area.z + area.depth) + REACH, depth) : depth\n\tconst rowLength = x1 - x0 + 1\n\t// the roads and rivers of the paths with a profile, carved from the land here (`MapPath.profile`)\n\tconst carved = profiledGround(map, x0, z0, x1, z1)\n\tconst cellRow = rowLength + 1\n\tconst waterAt = (c: number, cx: number, cz: number): number =>\n\t\tcarved?.water ? Math.max(water[c], carved.water[(cz - z0 + 1) * cellRow + (cx - x0 + 1)]) : water[c]\n\t// the level of each vertex: the highest cell around it, or on a ramp the average of all cells within reach\n\tconst vertexLevels = new Float32Array(rowLength * (z1 - z0 + 1))\n\tfor (let iz = z0; iz <= z1; iz++) {\n\t\tfor (let ix = x0; ix <= x1; ix++) {\n\t\t\tlet top = 0\n\t\t\tlet onRamp = false\n\t\t\tlet depthSum = 0\n\t\t\t// water lies at the foot of a cliff, never up its face\n\t\t\tlet wetLevel = Infinity\n\t\t\tfor (let cz = iz - 1; cz <= iz; cz++) {\n\t\t\t\tfor (let cx = ix - 1; cx <= ix; cx++) {\n\t\t\t\t\tif (cx < 0 || cz < 0 || cx >= width || cz >= depth) continue\n\t\t\t\t\tconst c = cz * width + cx\n\t\t\t\t\ttop = Math.max(top, levels[c])\n\t\t\t\t\tif (ramps[c]) onRamp = true\n\t\t\t\t\tconst wet = waterAt(c, cx, cz)\n\t\t\t\t\tdepthSum += WATER_DEPTH[wet] ?? 0\n\t\t\t\t\tif (wet) wetLevel = Math.min(wetLevel, levels[c])\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst v = iz * vx + ix\n\t\t\tconst level = onRamp ? averageLevel(map, ix, iz) : top\n\t\t\tvertexLevels[(iz - z0) * rowLength + (ix - x0)] = level\n\t\t\tconst under = carved ? carved.ground[(iz - z0) * rowLength + (ix - x0)] : ground[v]\n\t\t\tconst land = under + level * cliffHeight\n\t\t\tterrain.heights[v] = land - depthSum / 4\n\t\t\tterrain.waterHeights[v] = under + Math.min(wetLevel, level) * cliffHeight - WATER_SURFACE\n\t\t}\n\t}\n\tconst levelAt = (ix: number, iz: number) => vertexLevels[(iz - z0) * rowLength + (ix - x0)]\n\tfor (let cz = z0; cz < z1; cz++) {\n\t\tfor (let cx = x0; cx < x1; cx++) {\n\t\t\tconst c = cz * width + cx\n\t\t\tterrain.water[c] = waterAt(c, cx, cz)\n\t\t\tterrain.tiles[c] = map.tiles[c]\n\t\t\tfor (const id in map.cells) terrain.cellLayer(id)[c] = map.cells[id][c]\n\t\t\tif (!ramps[c]) {\n\t\t\t\tterrain.levels[c] = levels[c]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// a ramp belongs to the level below until halfway up\n\t\t\tconst middle = (levelAt(cx, cz) + levelAt(cx + 1, cz) + levelAt(cx, cz + 1) + levelAt(cx + 1, cz + 1)) / 4\n\t\t\tterrain.levels[c] = Math.floor(middle + 0.5)\n\t\t}\n\t}\n\tconst touched = { x: x0, z: z0, width: x1 - x0, depth: z1 - z0 }\n\tpaintPaths(map, terrain.tiles, touched)\n\t// last: what doodads block, and the decks of bridges over the heights just worked out, where they were\n\tblockByDoodads(map, terrain, area && touched)\n\treturn touched\n}\n\n/**\n * Paints the ground under the paths that say so, over the paint of the map: the tiles are those of the map's tileset.\n * Within `area` only, when it is given\n */\nfunction paintPaths(map: GameMap, tiles: Uint8Array, area: CellRect = { x: 0, z: 0, width: map.width, depth: map.depth }): void {\n\tconst width = area.x + area.width\n\tconst depth = area.z + area.depth\n\tfor (const def of map.paths) {\n\t\t// a profile's ground over the path's paint, as wide as its bed\n\t\tconst bed = def.profile?.ground !== undefined\n\t\tconst paint = bed ? def.profile!.ground : def.paint\n\t\tconst wide = bed ? (def.profile!.width ?? def.width) : def.width\n\t\tconst tile = paint === undefined ? 0 : map.tileset.indexOf(paint) + 1\n\t\tif (!tile || !def.points.length) continue\n\t\tconst path = new Path(def.points, wide)\n\t\t// only the cells within reach of its points, not the whole map\n\t\tconst reach = wide / 2 + 1\n\t\tconst xs = def.points.map((point) => point.x)\n\t\tconst zs = def.points.map((point) => point.z)\n\t\tfor (let cz = Math.max(Math.floor(Math.min(...zs) - reach), area.z); cz < Math.min(Math.ceil(Math.max(...zs) + reach), depth); cz++) {\n\t\t\tfor (let cx = Math.max(Math.floor(Math.min(...xs) - reach), area.x); cx < Math.min(Math.ceil(Math.max(...xs) + reach), width); cx++) {\n\t\t\t\tif (path.containsCell(cx, cz)) tiles[cz * map.width + cx] = tile\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Average level of the cells within ramp reach of a vertex */\nfunction averageLevel(map: GameMap, ix: number, iz: number): number {\n\tconst { width, depth, levels } = map\n\tlet sum = 0\n\tlet count = 0\n\tfor (let cz = Math.max(iz - RAMP_REACH, 0); cz < Math.min(iz + RAMP_REACH, depth); cz++) {\n\t\tfor (let cx = Math.max(ix - RAMP_REACH, 0); cx < Math.min(ix + RAMP_REACH, width); cx++) {\n\t\t\tsum += levels[cz * width + cx]\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count ? sum / count : 0\n}\n\n/**\n * Cell of a map a point is in\n *\n * @internal\n */\nexport const mapCell = (map: GameMap, x: number, z: number): number =>\n\tclamp(Math.floor(z), 0, map.depth - 1) * map.width + clamp(Math.floor(x), 0, map.width - 1)\n\n// ---- tiles\n\n/**\n * Brings the paint of a map in line with a game's tiles, in place: afterwards index 1 is the game's first tile, and\n * so on. What was painted with a tile the game does not have keeps it, under an index after the game's: the map\n * loses nothing, and the file has it still. Returns the names of those, which no world is given\n *\n * @beta\n */\nexport function adoptTileset(map: GameMap, tiles: readonly string[]): string[] {\n\tconst used = new Set(map.tiles)\n\tconst strangers = map.tileset.filter((id, i) => !tiles.includes(id) && used.has(i + 1))\n\tconst tileset = [...tiles, ...strangers]\n\tif (tileset.length > MAX_TILES) throw new Error(`Map: ${tileset.length} tiles are more than a map can hold`)\n\tif (tileset.length !== map.tileset.length || tileset.some((id, i) => id !== map.tileset[i])) {\n\t\tconst remap = tileRemap(map.tileset, tileset)\n\t\tfor (let c = 0; c < map.tiles.length; c++) map.tiles[c] = remap[map.tiles[c]] ?? 0\n\t\tmap.tileset = tileset\n\t}\n\treturn strangers\n}\n\n/**\n * The paint of a map as a game's tiles have it: what is painted with a tile the game does not have is no paint\n *\n * @internal\n */\nexport function tilesFor(map: GameMap, tiles: readonly string[]): Uint8Array {\n\tconst remap = tileRemap(map.tileset, tiles)\n\treturn map.tiles.map((tile) => remap[tile] ?? 0)\n}\n","/** Bytes as text that survives JSON: base64 */\nexport function packBytes(bytes: Uint8Array): string {\n\tlet text = ''\n\tfor (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n\treturn btoa(text)\n}\n\n/** Bytes back from `packBytes`. Undefined when there are not `length` of them */\nexport function unpackBytes(text: string, length: number): Uint8Array | undefined {\n\tconst binary = atob(text)\n\tif (binary.length !== length) return undefined\n\tconst bytes = new Uint8Array(length)\n\tfor (let i = 0; i < length; i++) bytes[i] = binary.charCodeAt(i)\n\treturn bytes\n}\n\n/** The bytes of numbers kept in a typed array, as text, see `packBytes` */\nexport const packArray = (array: Float32Array | Int32Array | Uint8Array) =>\n\tpackBytes(new Uint8Array(array.buffer, array.byteOffset, array.byteLength))\n","/**\n * A terrain as plain data and back: in a save (`save.ts`), in a map's ground (`ground.ts`), and sent to a remote player\n * as the game starts. Of nothing but the terrain and its bytes, so that what keeps a terrain loads nothing of a save\n */\nimport { packArray, packBytes, unpackBytes } from './bytes'\nimport { Terrain } from './terrain'\n\n/**\n * A terrain as plain data: in a save, and sent to a remote player as the game starts\n *\n * @beta\n */\nexport interface TerrainSave {\n\twidth: number\n\tdepth: number\n\t/**\n\t * Each layer as packed bytes (see `packBytes`), or, where every cell holds the same, that value: a map without water\n\t * or cliffs, of one ground, says so in a few characters rather than a few hundred thousand\n\t */\n\theights: string | number\n\tlevels: string | number\n\twater: string | number\n\twaterHeights: string | number\n\ttiles: string | number\n\t/** What scenery keeps off each cell. Left out by saves from before there was any */\n\tblocked?: string | number\n\t/** The game's layers of cells (`Terrain.cells`), by id, as the other layers. Left out when there are none */\n\tcells?: Record<string, string | number>\n\t/** The part of the map play happens in, when it is not all of it */\n\tbounds?: { x: number; z: number; width: number; depth: number }\n}\n\n/** The one value every element of a layer holds, or nothing when they are not all the same */\nfunction uniform(layer: Float32Array | Uint8Array): number | undefined {\n\tconst first = layer[0] ?? 0\n\tfor (let i = 1; i < layer.length; i++) if (layer[i] !== first) return undefined\n\treturn first\n}\n\nconst packLayer = (layer: Float32Array | Uint8Array): string | number =>\n\tuniform(layer) ?? (layer instanceof Float32Array ? packArray(layer) : packBytes(layer))\n\n/**\n * A terrain as plain data, see `TerrainSave`\n *\n * @internal\n */\nexport function saveTerrain(terrain: Terrain): TerrainSave {\n\treturn {\n\t\twidth: terrain.width,\n\t\tdepth: terrain.depth,\n\t\theights: packLayer(terrain.heights),\n\t\tlevels: packLayer(terrain.levels),\n\t\twater: packLayer(terrain.water),\n\t\twaterHeights: packLayer(terrain.waterHeights),\n\t\ttiles: packLayer(terrain.tiles),\n\t\tblocked: packLayer(terrain.blocked),\n\t\t...(Object.keys(terrain.cells).length && {\n\t\t\tcells: Object.fromEntries(Object.entries(terrain.cells).map(([id, layer]) => [id, packLayer(layer)]))\n\t\t}),\n\t\t...(terrain.bounds && { bounds: { ...terrain.bounds } })\n\t}\n}\n\n/**\n * A terrain back from `saveTerrain`\n *\n * @internal\n */\nexport function loadTerrain(save: TerrainSave): Terrain {\n\tconst { width, depth } = save\n\tconst cells = width * depth\n\tconst verts = (width + 1) * (depth + 1)\n\tconst packed = (key: keyof TerrainSave, length: number) => {\n\t\tconst unpacked = unpackBytes(save[key] as string, length)\n\t\tif (!unpacked) throw new Error(`Save: the ${key} of the terrain is not the size of it`)\n\t\treturn unpacked\n\t}\n\t// a layer of one value is that value in every cell\n\tconst bytes = (key: keyof TerrainSave, length: number) => {\n\t\tconst value = save[key]\n\t\treturn typeof value === 'number' ? new Uint8Array(length).fill(value) : packed(key, length)\n\t}\n\tconst floats = (key: keyof TerrainSave) => {\n\t\tconst value = save[key]\n\t\treturn typeof value === 'number' ? new Float32Array(verts).fill(value) : new Float32Array(packed(key, verts * 4).buffer)\n\t}\n\tconst terrain = new Terrain(width, depth, floats('heights'), bytes('levels', cells), {\n\t\twater: bytes('water', cells),\n\t\twaterHeights: floats('waterHeights'),\n\t\ttiles: bytes('tiles', cells),\n\t\tblocked: save.blocked === undefined ? undefined : bytes('blocked', cells),\n\t\tcells: Object.fromEntries(\n\t\t\tObject.entries(save.cells ?? {}).map(([id, value]) => {\n\t\t\t\tif (typeof value === 'number') return [id, new Uint8Array(cells).fill(value)]\n\t\t\t\tconst unpacked = unpackBytes(value, cells)\n\t\t\t\tif (!unpacked) throw new Error(`Save: the cells of ${id} are not the size of the terrain`)\n\t\t\t\treturn [id, unpacked]\n\t\t\t})\n\t\t)\n\t})\n\tif (save.bounds) terrain.bounds = { ...save.bounds }\n\treturn terrain\n}\n","import { packArray, packBytes, unpackBytes } from './bytes'\nimport type { GameModule } from './game'\nimport { type GameMap, mapTerrain, playTileset, tilesFor } from './map'\nimport { loadTerrain, saveTerrain, type TerrainSave } from './terrainSave'\nimport { Terrain } from './terrain'\n\n/*\n * The ground not in every save and welcome (S36). A world made from a map the game has (`GameModule.maps`) keeps the\n * ground it started on, and a save or a welcome names that map (by its name, and a hash of the ground it makes) and\n * carries only the cells of the ground that changed since: a few bytes, where the whole ground of a map of 1024 cells\n * a side is about 15 MB. A world made from bare terrain, or from a map the game does not have, keeps all of it, as\n * before. Whoever reads it finds the map among the game's own; a player who has not got it is sent the ground once,\n * in parts (`RemoteSession`).\n */\n\n/**\n * The ground of a save or a welcome: all of it, or the map it started as and what changed of it\n *\n * @beta\n */\nexport type SavedGround = TerrainSave | GroundChanges\n\n/**\n * The ground as a map the game has, and the cells of it that changed: in a save and in a welcome\n *\n * @beta\n */\nexport interface GroundChanges {\n\t/** The map it started as, by its name (`GameMap.name`) and a hash of the ground it makes (`groundHash`) */\n\tmap: string\n\thash: string\n\twidth: number\n\tdepth: number\n\t/** For each layer that changed: which cells (packed as 32-bit numbers), and what each holds now */\n\tchanges: Partial<Record<GroundLayer, { count: number; at: string; to: string }>>\n\t/** The same for the game's layers of cells (`Terrain.cells`), by id */\n\tcells?: Record<string, { count: number; at: string; to: string }>\n\t/** The part of the map play happens in, as it is now */\n\tbounds?: { x: number; z: number; width: number; depth: number }\n}\n\nconst LAYERS = ['heights', 'levels', 'water', 'waterHeights', 'tiles', 'blocked'] as const\n/** @beta */\nexport type GroundLayer = (typeof LAYERS)[number]\n\n/**\n * Whether a save's ground is the changes of a map, not the whole of it\n *\n * @beta\n */\nexport const isGroundChanges = (ground: SavedGround): ground is GroundChanges => typeof (ground as GroundChanges).map === 'string'\n\n/**\n * The ground a world is made on from a map, painted as the game's tiles go, then the map's own (`MapTile`): what\n * `createWorldFromMap` makes\n *\n * @internal\n */\nexport function startingTerrain(map: GameMap, game: Pick<GameModule, 'tiles'>): Terrain {\n\tconst tileIds = playTileset(\n\t\t(game.tiles ?? []).map((tile) => tile.id),\n\t\tmap.environment\n\t)\n\treturn mapTerrain({ ...map, tiles: tilesFor(map, tileIds), tileset: tileIds })\n}\n\n/**\n * A hash of a ground, every layer of it and its size: two grounds of the same hash are the same ground\n *\n * @beta\n */\nexport function groundHash(terrain: Terrain): string {\n\tlet a = 0x811c9dc5\n\tlet b = 0x01000193 ^ 0x5bd1e995\n\tconst mix = (word: number) => {\n\t\ta = Math.imul(a ^ word, 0x01000193)\n\t\tb = Math.imul(b ^ word, 0x5bd1e995)\n\t}\n\tmix(terrain.width)\n\tmix(terrain.depth)\n\tconst layers: (Float32Array | Uint8Array)[] = LAYERS.map((key) => terrain[key])\n\t// the game's layers of cells, by id, where any cell holds something: an empty layer is no layer\n\tfor (const id of Object.keys(terrain.cells).sort()) {\n\t\tconst cells = terrain.cells[id]\n\t\tif (!cells.some((value) => value !== 0)) continue\n\t\tfor (let i = 0; i < id.length; i++) mix(id.charCodeAt(i))\n\t\tlayers.push(cells)\n\t}\n\tfor (const layer of layers) {\n\t\tconst bytes = new Uint8Array(layer.buffer, layer.byteOffset, layer.byteLength)\n\t\tconst words = Math.floor(bytes.length / 4)\n\t\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n\t\tfor (let i = 0; i < words; i++) mix(view.getUint32(i * 4, true))\n\t\tfor (let i = words * 4; i < bytes.length; i++) mix(bytes[i])\n\t\tmix(0xffffffff)\n\t}\n\treturn (a >>> 0).toString(16).padStart(8, '0') + (b >>> 0).toString(16).padStart(8, '0')\n}\n\n/**\n * The ground a world started on, from a map: kept with the world (`World.ground`), not in its save\n *\n * @beta\n */\nexport interface GroundBase {\n\tmap: string\n\t/** A hash of the ground (`groundHash`): worked out the first time it is asked for */\n\treadonly hash: string\n\tterrain: Terrain\n}\n\n/**\n * A ground a world starts on, as a map made it, with its hash worked out when it is first asked for\n *\n * @internal\n */\nexport function startedOn(map: string, terrain: Terrain): GroundBase {\n\tlet hash: string | undefined\n\treturn {\n\t\tmap,\n\t\tterrain,\n\t\tget hash() {\n\t\t\treturn (hash ??= groundHash(terrain))\n\t\t}\n\t}\n}\n\n/**\n * The ground a map the game ships makes, and its hash: worked out once for each of those maps, which are not changed\n * once given (a map being edited is, and is not one of them)\n */\nconst bases = new WeakMap<GameMap, Map<string, GroundBase>>()\n/** @internal */\nexport function groundBase(map: GameMap, game: Pick<GameModule, 'tiles'>): GroundBase {\n\tconst key = playTileset(\n\t\t(game.tiles ?? []).map((tile) => tile.id),\n\t\tmap.environment\n\t).join()\n\tlet known = bases.get(map)\n\tif (!known) bases.set(map, (known = new Map()))\n\tlet base = known.get(key)\n\tif (!base) {\n\t\tconst terrain = startingTerrain(map, game)\n\t\tknown.set(key, (base = startedOn(map.name, terrain)))\n\t}\n\treturn base\n}\n\n/**\n * The map of a name whose ground has a hash, among some maps: the one a save or a welcome names\n *\n * @internal\n */\nexport function findGround(maps: readonly GameMap[], name: string, hash: string, game: Pick<GameModule, 'tiles'>): GroundBase | undefined {\n\tfor (const map of maps) if (map.name === name && groundBase(map, game).hash === hash) return groundBase(map, game)\n\treturn undefined\n}\n\n/**\n * The ground of a world as a save keeps it: the changes since the map it started as, where the game has that map as\n * it was (the same name and the same ground), else all of it\n *\n * @internal\n */\nexport function savedGround(\n\tterrain: Terrain,\n\tbase: GroundBase | undefined,\n\tmaps: readonly GameMap[] | undefined,\n\tgame: Pick<GameModule, 'tiles'>\n): SavedGround {\n\tif (!base || !maps?.length || !findGround(maps, base.map, base.hash, game)) return saveTerrain(terrain)\n\tconst from = base.terrain\n\tif (from.width !== terrain.width || from.depth !== terrain.depth) return saveTerrain(terrain)\n\tconst changes: GroundChanges['changes'] = {}\n\tfor (const key of LAYERS) {\n\t\tconst now = terrain[key]\n\t\tconst was = from[key]\n\t\tconst at: number[] = []\n\t\tfor (let i = 0; i < now.length; i++) if (now[i] !== was[i]) at.push(i)\n\t\tif (!at.length) continue\n\t\tconst values = now instanceof Float32Array ? Float32Array.from(at, (i) => now[i]) : Uint8Array.from(at, (i) => now[i])\n\t\tchanges[key] = {\n\t\t\tcount: at.length,\n\t\t\tat: packArray(Int32Array.from(at)),\n\t\t\tto: values instanceof Float32Array ? packArray(values) : packBytes(values)\n\t\t}\n\t}\n\tconst cells: NonNullable<GroundChanges['cells']> = {}\n\tfor (const id of new Set([...Object.keys(terrain.cells), ...Object.keys(from.cells)])) {\n\t\tconst now = terrain.cells[id]\n\t\tconst was = from.cells[id]\n\t\tconst at: number[] = []\n\t\tfor (let i = 0; i < terrain.width * terrain.depth; i++) if ((now?.[i] ?? 0) !== (was?.[i] ?? 0)) at.push(i)\n\t\tif (at.length) cells[id] = { count: at.length, at: packArray(Int32Array.from(at)), to: packBytes(Uint8Array.from(at, (i) => now?.[i] ?? 0)) }\n\t}\n\treturn {\n\t\tmap: base.map,\n\t\thash: base.hash,\n\t\twidth: terrain.width,\n\t\tdepth: terrain.depth,\n\t\tchanges,\n\t\t...(Object.keys(cells).length && { cells }),\n\t\t...(terrain.bounds && { bounds: { ...terrain.bounds } })\n\t}\n}\n\n/**\n * Why the ground of a save or a welcome cannot be read: the map it names is not one of the game's, as it was\n *\n * @internal\n */\nexport class MissingGround extends Error {\n\tconstructor(\n\t\treadonly map: string,\n\t\treadonly hash: string\n\t) {\n\t\tsuper(`The ground is the map \"${map}\" as it was (${hash}), which this game does not have: it was changed or taken out since`)\n\t}\n}\n\n/**\n * A ground back from a save or a welcome, and what it started as where it names a map: that map among `maps`, with\n * the changes put on it. Throws `MissingGround` where none of them is that map as it was\n *\n * @internal\n */\nexport function groundOf(\n\tsaved: SavedGround,\n\tmaps: readonly GameMap[] | undefined,\n\tgame: Pick<GameModule, 'tiles'>\n): { terrain: Terrain; base?: GroundBase } {\n\tif (!isGroundChanges(saved)) return { terrain: loadTerrain(saved) }\n\tconst base = maps ? findGround(maps, saved.map, saved.hash, game) : undefined\n\tif (!base) throw new MissingGround(saved.map, saved.hash)\n\treturn { terrain: withChanges(base.terrain, saved), base }\n}\n\n/**\n * A copy of a ground, the changes put on it\n *\n * @internal\n */\nexport function withChanges(from: Terrain, ground: GroundChanges): Terrain {\n\tconst terrain = cloneTerrain(from)\n\tfor (const key of LAYERS) {\n\t\tconst change = ground.changes[key]\n\t\tif (!change) continue\n\t\tconst layer = terrain[key]\n\t\tconst atBytes = unpackBytes(change.at, change.count * 4)\n\t\tconst toBytes = unpackBytes(change.to, change.count * (layer instanceof Float32Array ? 4 : 1))\n\t\tif (!atBytes || !toBytes) throw new Error(`Save: the changes of the ${key} of the ground are not what they say`)\n\t\tconst at = new Int32Array(atBytes.buffer)\n\t\tconst to = layer instanceof Float32Array ? new Float32Array(toBytes.buffer) : toBytes\n\t\tfor (let i = 0; i < at.length; i++) {\n\t\t\tif (at[i] < 0 || at[i] >= layer.length) throw new Error(`Save: a change of the ${key} is off the ground`)\n\t\t\tlayer[at[i]] = to[i]\n\t\t}\n\t}\n\tfor (const [id, change] of Object.entries(ground.cells ?? {})) {\n\t\tconst layer = terrain.cellLayer(id)\n\t\tconst atBytes = unpackBytes(change.at, change.count * 4)\n\t\tconst to = unpackBytes(change.to, change.count)\n\t\tif (!atBytes || !to) throw new Error(`Save: the changes of the cells of ${id} are not what they say`)\n\t\tconst at = new Int32Array(atBytes.buffer)\n\t\tfor (let i = 0; i < at.length; i++) {\n\t\t\tif (at[i] < 0 || at[i] >= layer.length) throw new Error(`Save: a change of the cells of ${id} is off the ground`)\n\t\t\tlayer[at[i]] = to[i]\n\t\t}\n\t}\n\tterrain.bounds = ground.bounds ? { ...ground.bounds } : undefined\n\treturn terrain\n}\n\n/**\n * A copy of a ground, every layer its own\n *\n * @internal\n */\nexport function cloneTerrain(from: Terrain): Terrain {\n\tconst terrain = new Terrain(from.width, from.depth, from.heights.slice(), from.levels.slice(), {\n\t\twater: from.water.slice(),\n\t\twaterHeights: from.waterHeights.slice(),\n\t\ttiles: from.tiles.slice(),\n\t\tblocked: from.blocked.slice(),\n\t\tcells: Object.fromEntries(Object.entries(from.cells).map(([id, layer]) => [id, layer.slice()]))\n\t})\n\tif (from.bounds) terrain.bounds = { ...from.bounds }\n\treturn terrain\n}\n\n/**\n * A part of the ground as it is, to put in another of the same size (`applyTerrainPatch`): a rectangle of cells and\n * every layer of it, the vertices at its corners included. What the editor's Play here sends of the map's ground as it\n * is edited (`debug.ground`, EQ10), and what a session is told of it (`ground`)\n *\n * @beta\n */\nexport interface TerrainPatch {\n\t/** The first cell, and how many across and down */\n\tx: number\n\tz: number\n\twidth: number\n\tdepth: number\n\t/** Per vertex, row by row: `(width + 1) * (depth + 1)` of them */\n\theights: number[]\n\twaterHeights: number[]\n\t/** Per cell, row by row: `width * depth` of them */\n\tlevels: number[]\n\twater: number[]\n\ttiles: number[]\n\tblocked: number[]\n\t/** The game's layers of cells (`Terrain.cells`), by id, per cell: those in either ground */\n\tcells?: Record<string, number[]>\n}\n\n/**\n * The cells of two grounds of one size that are not the same, as the smallest rectangle around them; none where they\n * are the same. Every layer, the game's layers of cells too. Two of other sizes: all of `after`\n *\n * @beta\n */\nexport function groundDifference(before: Terrain, after: Terrain): { x: number; z: number; width: number; depth: number } | undefined {\n\tif (before.width !== after.width || before.depth !== after.depth) return { x: 0, z: 0, width: after.width, depth: after.depth }\n\tlet x0 = Infinity\n\tlet z0 = Infinity\n\tlet x1 = -1\n\tlet z1 = -1\n\tconst take = (x: number, z: number) => {\n\t\tif (x < x0) x0 = x\n\t\tif (z < z0) z0 = z\n\t\tif (x > x1) x1 = x\n\t\tif (z > z1) z1 = z\n\t}\n\tconst { width, depth, vertsX } = after\n\t// a vertex is a corner of the cells about it: the one up and left of it, where there is one, else the one there\n\tfor (const layer of ['heights', 'waterHeights'] as const) {\n\t\tconst a = before[layer]\n\t\tconst b = after[layer]\n\t\tfor (let i = 0; i < b.length; i++) {\n\t\t\tif (a[i] === b[i]) continue\n\t\t\tconst vx = i % vertsX\n\t\t\tconst vz = Math.floor(i / vertsX)\n\t\t\ttake(Math.min(vx, width - 1), Math.min(vz, depth - 1))\n\t\t\ttake(Math.max(vx - 1, 0), Math.max(vz - 1, 0))\n\t\t}\n\t}\n\tconst cellLayers = [...(['levels', 'water', 'tiles', 'blocked'] as const).map((layer) => [before[layer], after[layer]] as const)]\n\tfor (const id of new Set([...Object.keys(before.cells), ...Object.keys(after.cells)]))\n\t\tcellLayers.push([before.cells[id] ?? new Uint8Array(width * depth), after.cells[id] ?? new Uint8Array(width * depth)])\n\tfor (const [a, b] of cellLayers) {\n\t\tfor (let i = 0; i < b.length; i++) if (a[i] !== b[i]) take(i % width, Math.floor(i / width))\n\t}\n\treturn x1 < 0 ? undefined : { x: x0, z: z0, width: x1 - x0 + 1, depth: z1 - z0 + 1 }\n}\n\n/**\n * A rectangle of cells of a ground as it is (`TerrainPatch`): to be put in another\n *\n * @beta\n */\nexport function terrainPatch(terrain: Terrain, rect: { x: number; z: number; width: number; depth: number }): TerrainPatch {\n\tconst { x, z, width, depth } = rect\n\tconst vertices = (values: Float32Array) => {\n\t\tconst out: number[] = []\n\t\tfor (let vz = z; vz <= z + depth; vz++) for (let vx = x; vx <= x + width; vx++) out.push(values[vz * terrain.vertsX + vx])\n\t\treturn out\n\t}\n\tconst cells = (values: Uint8Array) => {\n\t\tconst out: number[] = []\n\t\tfor (let cz = z; cz < z + depth; cz++) for (let cx = x; cx < x + width; cx++) out.push(values[cz * terrain.width + cx])\n\t\treturn out\n\t}\n\tconst layers = Object.entries(terrain.cells)\n\treturn {\n\t\tx,\n\t\tz,\n\t\twidth,\n\t\tdepth,\n\t\theights: vertices(terrain.heights),\n\t\twaterHeights: vertices(terrain.waterHeights),\n\t\tlevels: cells(terrain.levels),\n\t\twater: cells(terrain.water),\n\t\ttiles: cells(terrain.tiles),\n\t\tblocked: cells(terrain.blocked),\n\t\t...(layers.length > 0 && { cells: Object.fromEntries(layers.map(([id, values]) => [id, cells(values)])) })\n\t}\n}\n\n/**\n * What is wrong with a patch for a ground (`TerrainPatch`): out of it, or of layers of other lengths. Nothing when it fits\n *\n * @beta\n */\nexport function terrainPatchProblem(terrain: Terrain, patch: TerrainPatch): string | undefined {\n\tconst { x, z, width, depth } = patch\n\tif (![x, z, width, depth].every(Number.isInteger) || x < 0 || z < 0 || width < 1 || depth < 1) return 'the patch is no rectangle of cells'\n\tif (x + width > terrain.width || z + depth > terrain.depth) return `the patch goes past the ground, ${terrain.width} by ${terrain.depth} cells`\n\tconst vertices = (width + 1) * (depth + 1)\n\tconst cells = width * depth\n\tif (patch.heights.length !== vertices || patch.waterHeights.length !== vertices) return `the patch has not ${vertices} heights`\n\tfor (const layer of [patch.levels, patch.water, patch.tiles, patch.blocked, ...Object.values(patch.cells ?? {})])\n\t\tif (layer.length !== cells) return `a layer of the patch has not ${cells} cells`\n\treturn undefined\n}\n\n/**\n * Puts a patch (`TerrainPatch`) in a ground, in place: its heights, water, paint and levels, and the game's layers of\n * cells (a layer the patch has that the ground has not is made). Nothing else: what the rules make of the ground is\n * `World.reshapeGround`'s. Throws where it does not fit (`terrainPatchProblem`)\n *\n * @beta\n */\nexport function applyTerrainPatch(terrain: Terrain, patch: TerrainPatch): void {\n\tconst problem = terrainPatchProblem(terrain, patch)\n\tif (problem) throw new Error(`applyTerrainPatch: ${problem}`)\n\tconst { x, z, width, depth } = patch\n\tlet i = 0\n\tfor (let vz = z; vz <= z + depth; vz++) {\n\t\tfor (let vx = x; vx <= x + width; vx++, i++) {\n\t\t\tconst at = vz * terrain.vertsX + vx\n\t\t\tterrain.heights[at] = patch.heights[i]\n\t\t\tterrain.waterHeights[at] = patch.waterHeights[i]\n\t\t}\n\t}\n\tconst layers: [Uint8Array, number[]][] = [\n\t\t[terrain.levels, patch.levels],\n\t\t[terrain.water, patch.water],\n\t\t[terrain.tiles, patch.tiles],\n\t\t[terrain.blocked, patch.blocked],\n\t\t...Object.entries(patch.cells ?? {}).map(([id, values]): [Uint8Array, number[]] => [terrain.cellLayer(id), values])\n\t]\n\tfor (const [into, values] of layers) {\n\t\tlet j = 0\n\t\tfor (let cz = z; cz < z + depth; cz++) for (let cx = x; cx < x + width; cx++, j++) into[cz * terrain.width + cx] = values[j]\n\t}\n}\n","import { footprintOf, type UnitTypeDef } from './defs'\nimport type { GameMap, MapCamp, MapObject, MapPlayer, MapRegion } from './map'\nimport type { GameMeasure } from './mapMeasure'\nimport type { Vec2 } from './math'\nimport type { Registry } from './registry'\n\n/**\n * A thing on a map, by its kind and id: what a problem is about, which the editor selects. `thing` is one of a kind of\n * the game's own (`MapThing`), with the kind's name\n *\n * @beta\n */\nexport type MapTarget =\n\t| { object: number }\n\t| { camp: number }\n\t| { region: number }\n\t| { point: number }\n\t| { path: number }\n\t| { doodad: number }\n\t| { light: number }\n\t| { effect: number }\n\t| { decal: number }\n\t| { sound: number }\n\t| { mistArea: number }\n\t| { weatherArea: number }\n\t| { cloudPatch: number }\n\t| { player: number }\n\t| { thing: number; kind: string }\n\n/**\n * A thing of a kind of a game's own on a map: something the game's editor puts down for its rules to read (a spawner,\n * a waypoint, ground kept clear), where the engine's own kinds (objects, camps, regions, points, paths, doodads) do\n * not say it. Kept with the map under the kind's name (`GameMap.data[kind]`, a list of them), which the engine never\n * looks inside: the rules read them (`world.map.things(kind)`, `mapThings`)\n *\n * @beta\n */\nexport interface MapThing {\n\t/** Its own among the things of its kind */\n\tid: number\n\tx: number\n\tz: number\n\t/** The way it faces, in radians. 0 when left out */\n\tfacing?: number\n\t/** A name of its own, to find it by: no two things of a map have the same, whatever they are */\n\tname?: string\n\t/** The game's own fields of it, by their ids: what was set, without what is at its default */\n\tdata?: Record<string, unknown>\n}\n\n/**\n * The things of a kind of a game's own on a map (`MapThing`), as the map keeps them: none for a kind it has nothing\n * of. What is kept under that name and is no thing (no id, no place) is left out, so that a file changed by hand breaks\n * no rule that reads it\n *\n * @beta\n */\nexport function mapThings(map: { data: Record<string, unknown> }, kind: string): MapThing[] {\n\tconst kept = map.data[kind]\n\tif (!Array.isArray(kept)) return []\n\treturn kept.filter(\n\t\t(thing): thing is MapThing =>\n\t\t\ttypeof thing === 'object' &&\n\t\t\tthing !== null &&\n\t\t\tNumber.isInteger((thing as MapThing).id) &&\n\t\t\tNumber.isFinite((thing as MapThing).x) &&\n\t\t\tNumber.isFinite((thing as MapThing).z)\n\t)\n}\n\n/**\n * Something wrong with a map, as a game sees it: said before the map is played\n *\n * @beta\n */\nexport interface MapProblem {\n\tmessage: string\n\t/** It cannot be played like this. A warning when left out: it can, but probably should not */\n\terror?: boolean\n\t/** Where on the map it is, for the editor to show */\n\tat?: Vec2\n\t/**\n\t * The rule it breaks, by id (`off-map`, `deep-water`…, or a game's own): what silences it, for a map\n\t * (`GameMap.silence`) or a game (`MapEditorDef.silence`). A game's own check that says none is `game`\n\t */\n\trule?: string\n\t/** What it is about: a click on it in the editor selects it */\n\tabout?: MapTarget\n\t/**\n\t * Where it is shown when it is about something of a panel's rather than the map's (a clip of a cinematic): a click on\n\t * it opens that panel at that entry (`editor.panels.reveal(panel, entry)`, as the search of everything does)\n\t */\n\treveal?: { panel: string; entry: string }\n}\n\n/**\n * What a game brings to the map editor, beyond its units: the fields of its own, what can be scattered, its players,\n * and what it takes for a map to be one of its maps. Each that is decided from something can be given as a function\n *\n * @beta\n */\nexport interface MapEditorDef {\n\t/** Fields of the game's own on what is placed on a map, shown in the inspector (see `defineMapField`) */\n\tfields?: MapFieldDef[]\n\t/**\n\t * Unit types the scatter brush puts down many of at once, like a forest. Resources one cell big when left out:\n\t * trees. What is scattered belongs to nobody\n\t */\n\tscatter?: string[] | ((registry: Registry) => string[])\n\t/** Whether the game has creep camps to place. It does when it has a unit type with a bounty, when left out */\n\tcamps?: boolean\n\t/**\n\t * The players of every map of the game, when the game decides who they are, as a tower defense does: the editor\n\t * shows those and only lets their starts be set. Open slots to add and take away when left out\n\t */\n\tplayers?: MapPlayer[] | ((map: GameMap) => MapPlayer[])\n\t/** A line under the players, saying what the game makes of them: who is the player, who gets a base */\n\tplayersNote?: string\n\t/**\n\t * What is wrong with a map as a map of this game: no start for anyone, no way through. Errors keep it from being\n\t * played from the editor; warnings are said\n\t */\n\tcheck?: (map: GameMap, registry: Registry) => MapProblem[]\n\t/** The editor's checks the game does not want, by their rules' ids (`MapProblem.rule`), for every map of it */\n\tsilence?: string[]\n\t/** What the game measures of a map of its own, for the editor's report (`measureMap`): the length of the road */\n\tmeasure?: (map: GameMap, registry: Registry) => GameMeasure[]\n\t/**\n\t * The palette's groups of unit types, each saying whose what is put down from it is and whether it makes camps.\n\t * Units, heroes, buildings, resources (nobody's) and creeps (the creeps', making camps) when left out\n\t */\n\tpalette?: (registry: Registry) => MapPaletteGroup[]\n\t/**\n\t * What the erase brush can be set to take, besides everything and camps. Units, buildings, resources and trees (a\n\t * resource one cell big) when left out\n\t */\n\terase?: MapEraseKind[]\n\t/**\n\t * What the starts must be able to walk to, which the checks look for (`unreachable`): a resource two cells big or\n\t * more when left out, a gold mine and not a tree\n\t */\n\treach?: (def: UnitTypeDef) => boolean\n\t/** The lowest and the highest the ground is raised to. -4 to 16 when left out */\n\theights?: readonly [number, number]\n\t/**\n\t * Where else the game names a thing of a map (a unit type in its waves, a region in a mission's goals): what the\n\t * editor lists under Used by and selects with Find references, beyond what it finds on the map itself (placed\n\t * objects, camps, random groups, the game's fields, prefabs, cinematics). Given the thing asked about and the map\n\t *\n\t * @beta\n\t */\n\treferences?: (ref: MapRef, map: GameMap, registry: Registry) => MapRefUse[]\n}\n\n/**\n * Something of a game or a map that others name: a unit type, a doodad's model, a prefab, a region, a point or a path\n * (by name), a thing named on the map, a cinematic, a file of the game's\n *\n * @beta\n */\nexport type MapRef =\n\t| { type: string }\n\t| { model: string }\n\t| { prefab: string }\n\t| { region: string }\n\t| { point: string }\n\t| { path: string }\n\t| { name: string }\n\t| { cinematic: string }\n\t| { asset: string }\n\n/**\n * What on the map a use is: what a click on it selects\n *\n * @beta\n */\nexport type MapRefTarget =\n\t| { object: number }\n\t| { camp: number }\n\t| { region: number }\n\t| { point: number }\n\t| { path: number }\n\t| { doodad: number }\n\t| { light: number }\n\t| { effect: number }\n\t| { decal: number }\n\t| { sound: number }\n\t| { mistArea: number }\n\t| { weatherArea: number }\n\t| { cloudPatch: number }\n\t| { thing: number; kind: string }\n\n/**\n * One place a thing is named: what names it, where, and what on the map that is\n *\n * @beta\n */\nexport interface MapRefUse {\n\t/** What names it: `placed`, `camp`, `random group`, `field Spawns`, `prefab`, `cinematic`, or the game's own word */\n\twhat: string\n\t/** Where: the map's name, a group's, a prefab's, a cinematic's id, a wave's */\n\twhere: string\n\ttarget?: MapRefTarget\n}\n\n/**\n * A group of the palette (`MapEditorDef.palette`)\n *\n * @beta\n */\nexport interface MapPaletteGroup {\n\tname: string\n\ttypes: UnitTypeDef[]\n\t/**\n\t * Whose what is put down from it is, by player id (`MAP_CREEPS`, `MAP_NEUTRAL`): the player picked above it when\n\t * left out, and nobody for a resource\n\t */\n\towner?: number\n\t/** Its units are what camps are made of: the camp tool picks from them */\n\tcamps?: boolean\n}\n\n/**\n * A kind of thing the erase brush can be set to take (`MapEditorDef.erase`)\n *\n * @beta\n */\nexport interface MapEraseKind {\n\tid: string\n\t/** What the brush's choice calls it */\n\tname: string\n\ttakes: (def: UnitTypeDef) => boolean\n}\n\n/**\n * What the starts must reach when a game does not say: what is mined, not what is cut\n *\n * @internal\n */\nexport const reachedByDefault = (def: UnitTypeDef): boolean => def.kind === 'resource' && footprintOf(def).w >= 2\n\n/**\n * The heights the ground goes from and to when a game does not say\n *\n * @beta\n */\nexport const DEFAULT_HEIGHTS: readonly [number, number] = [-4, 16]\n\n/** What a field of a game's own holds, and so how the editor lets it be set */\n/**\n * What a field holds: a number, words, yes or no, one of a few, a unit type, a player; a region, a point or a path of\n * the map (kept by id, so that a rename does not lose it; handed to the game by name); a colour (`[r, g, b]`, 0 to 1);\n * a list of words; a vector on the ground (`{ x, z }`)\n *\n * @beta\n */\nexport type MapFieldKind = 'number' | 'text' | 'toggle' | 'choice' | 'unit' | 'player' | 'region' | 'point' | 'path' | 'color' | 'list' | 'vector'\n\n/** The kinds of field that name a thing of the map, by its id */\nexport const TARGET_FIELDS = ['region', 'point', 'path'] as const\n\n/**\n * A field of a game's own on what is placed on a map: the wave a spawner sends, whether a gate starts open, what a\n * guard does. The editor shows it in the inspector for what it is a field of, and keeps what it was set to with the\n * object (`MapObject.data`). The engine does nothing with it: the `mapObject` hook hands it to the game as the world\n * is made, which is where the game says what it means. Given in `GameModule.editor.fields`\n *\n * @beta\n */\nexport interface MapFieldDef {\n\t/** The key it is kept under. Shared by the fields of every mod on the game: give a mod's a prefix */\n\tid: string\n\t/** What the inspector calls it */\n\tname: string\n\t/** A line more, shown when the pointer rests on it */\n\thint?: string\n\t/**\n\t * The fields it is laid out beside in the inspector, by a name they share (`'Position'`): the consecutive fields of\n\t * one group two a line, under its name. Alone when left out\n\t */\n\tgroup?: string\n\tkind: MapFieldKind\n\t/**\n\t * What it is a field of: objects of these unit types, or of the types a function says yes to (every hero, every\n\t * building that trains something); or camps, or regions; or the map itself (kept in `GameMap.data`, read as\n\t * `world.map.data`), or its players (`MapPlayer.data`, read as `world.map.player(id).data`)\n\t */\n\tfor: string[] | ((def: UnitTypeDef) => boolean) | 'camp' | 'region' | 'map' | 'player'\n\t/** What it is when nothing was set. The game is given this then, and the file does not hold it */\n\tdefault?: unknown\n\t/** For a number: the least and the most it can be, and what the arrows step by */\n\tmin?: number\n\tmax?: number\n\tstep?: number\n\t/** For a choice: what there is to choose from, as data or worked out from the game */\n\toptions?: readonly MapFieldOption[] | ((registry: Registry) => readonly MapFieldOption[])\n}\n\n/**\n * One of the things a choice field can be: the value kept, and what the inspector calls it when that is not the value\n *\n * @beta\n */\nexport type MapFieldOption = string | { value: string; label: string }\n\n/**\n * Typed help for writing a field\n *\n * @beta\n */\nexport const defineMapField = (def: MapFieldDef): MapFieldDef => def\n\n/** The game's fields: its own (`GameModule.editor.fields`) and those of the components it lists (`Component.field`), under the component's id */\nconst fieldsOf = (registry: Registry): readonly MapFieldDef[] => {\n\tconst own = registry.module?.editor?.fields ?? []\n\tlet all: MapFieldDef[] | undefined\n\tfor (const component of registry.listedComponents()) {\n\t\tif (component.field) (all ??= [...own]).push({ ...component.field, id: component.id })\n\t}\n\treturn all ?? own\n}\n\n/**\n * The game's fields for a placed object, by the type it is of. None for a type the game does not have\n *\n * @beta\n */\nexport function objectFields(registry: Registry, type: string): MapFieldDef[] {\n\tif (!registry.units.has(type)) return []\n\tconst def = registry.unit(type)\n\treturn fieldsOf(registry).filter((field) =>\n\t\ttypeof field.for === 'function' ? field.for(def) : Array.isArray(field.for) && field.for.includes(type)\n\t)\n}\n\n/**\n * The game's fields for a camp\n *\n * @beta\n */\nexport const campFields = (registry: Registry): MapFieldDef[] => fieldsOf(registry).filter((field) => field.for === 'camp')\n\n/**\n * The game's fields for a region\n *\n * @beta\n */\nexport const regionFields = (registry: Registry): MapFieldDef[] => fieldsOf(registry).filter((field) => field.for === 'region')\n\n/**\n * The fields of the map itself, and of its players\n *\n * @beta\n */\nexport const mapFields = (registry: Registry): MapFieldDef[] => fieldsOf(registry).filter((field) => field.for === 'map')\n/** @beta */\nexport const playerFields = (registry: Registry): MapFieldDef[] => fieldsOf(registry).filter((field) => field.for === 'player')\n\n/**\n * What a choice field can be set to, as values with what each is called\n *\n * @beta\n */\nexport function fieldOptions(registry: Registry, field: MapFieldDef): { value: string; label: string }[] {\n\tconst options = typeof field.options === 'function' ? field.options(registry) : (field.options ?? [])\n\treturn options.map((option) => (typeof option === 'string' ? { value: option, label: option } : option))\n}\n\n/** What the fields of something placed are, with what was not set at its default: what the game is handed */\nexport function fieldValues(fields: readonly MapFieldDef[], data: Record<string, unknown> | undefined, map?: GameMap): Record<string, unknown> {\n\t// what is kept with it and is no field (any more) comes along too: a game may read what an older version of it wrote\n\tconst values: Record<string, unknown> = { ...data }\n\tfor (const field of fields) {\n\t\tif (values[field.id] === undefined && field.default !== undefined) values[field.id] = field.default\n\t\t// a region, a point or a path is kept by id, and handed to the game by its name: what the game finds it by\n\t\tif (map && (TARGET_FIELDS as readonly string[]).includes(field.kind) && typeof values[field.id] === 'number')\n\t\t\tvalues[field.id] = targetName(map, field.kind as (typeof TARGET_FIELDS)[number], values[field.id] as number)\n\t}\n\treturn values\n}\n\n/** The name of a region, a point or a path of a map by its id: undefined for one the map has not (any more) */\nexport function targetName(map: GameMap, kind: (typeof TARGET_FIELDS)[number], id: number): string | undefined {\n\tconst list = kind === 'region' ? map.regions : kind === 'point' ? map.points : map.paths\n\treturn list.find((thing) => thing.id === id)?.name\n}\n\n/**\n * The game's fields of an object or a camp of a map, as the game is handed them\n *\n * @internal\n */\nexport const mapObjectData = (registry: Registry, object: MapObject, map?: GameMap): Record<string, unknown> =>\n\tfieldValues(objectFields(registry, object.type), object.data, map)\n/** @internal */\nexport const mapCampData = (registry: Registry, camp: MapCamp, map?: GameMap): Record<string, unknown> =>\n\tfieldValues(campFields(registry), camp.data, map)\n/** @internal */\nexport const mapRegionData = (registry: Registry, region: MapRegion, map?: GameMap): Record<string, unknown> =>\n\tfieldValues(regionFields(registry), region.data, map)\n/** @internal */\nexport const mapPlayerData = (registry: Registry, player: MapPlayer, map?: GameMap): Record<string, unknown> =>\n\tfieldValues(playerFields(registry), player.data, map)\n","import { entityDied } from '#engine/engineEvents'\nimport { defineComponent } from './components'\nimport { defineListener } from './events'\nimport { createItem, dropOnGround } from './items'\nimport type { MapItemTable, MapRandomGroup } from './map'\nimport type { Registry } from './registry'\nimport type { Rng } from './rng'\n\n/** One of a list by weight, or nothing for an empty list */\nfunction byWeight<T extends { weight: number }>(list: readonly T[], rng: Rng): T | undefined {\n\tconst total = list.reduce((sum, entry) => sum + Math.max(entry.weight, 0), 0)\n\tif (total <= 0) return undefined\n\tlet at = rng.next() * total\n\tfor (const entry of list) {\n\t\tat -= Math.max(entry.weight, 0)\n\t\tif (at < 0) return entry\n\t}\n\treturn list[list.length - 1]\n}\n\n/**\n * The unit types a random group can be drawn from, as the game has them\n *\n * @internal\n */\nexport function groupChoices(group: MapRandomGroup, registry: Registry): { type: string; weight: number }[] {\n\tif (group.choices?.length) return group.choices.filter((choice) => registry.units.has(choice.type) && choice.weight > 0)\n\tif (group.level === undefined) return []\n\t// any creep of the level: a unit type with a bounty\n\treturn registry.units\n\t\t.all()\n\t\t.filter((def) => def.kind === 'unit' && def.bounty && (def.level ?? 1) === group.level)\n\t\t.map((def) => ({ type: def.id, weight: 1 }))\n}\n\n/**\n * A unit type drawn from a random group, as the game starts: nothing when it has none to draw from\n *\n * @internal\n */\nexport const drawFromGroup = (group: MapRandomGroup, registry: Registry, rng: Rng): string | undefined =>\n\tbyWeight(groupChoices(group, registry), rng)?.type\n\n/**\n * An item drawn from a table as something dies: nothing when it drops nothing this time\n *\n * @internal\n */\nexport function drawFromTable(table: MapItemTable, registry: Registry, rng: Rng): string | undefined {\n\tif (table.chance !== undefined && rng.next() >= table.chance) return undefined\n\treturn byWeight(tableItems(table, registry), rng)?.item\n}\n\n/**\n * The items a table draws from, each with its weight: an item by id as it is, a line of a level or a class its\n * weight shared among the game's items that match (in the game's order: the same draw from the same seed)\n *\n * @internal\n */\nexport function tableItems(table: MapItemTable, registry: Registry): { item: string; weight: number }[] {\n\tconst out: { item: string; weight: number }[] = []\n\tfor (const entry of table.items) {\n\t\tif (entry.item !== undefined) {\n\t\t\tif (registry.items.has(entry.item)) out.push({ item: entry.item, weight: entry.weight })\n\t\t\tcontinue\n\t\t}\n\t\tif (entry.level === undefined && entry.class === undefined) continue\n\t\tconst matching = registry.items\n\t\t\t.all()\n\t\t\t.filter((def) => (entry.level === undefined || (def.level ?? 1) === entry.level) && (entry.class === undefined || def.class === entry.class))\n\t\tfor (const def of matching) out.push({ item: def.id, weight: entry.weight / matching.length })\n\t}\n\treturn out\n}\n\n/**\n * The item table a thing placed on a map drops from when it dies (`MapObject.drops`), by name\n *\n * @internal\n */\nexport const mapDrops = defineComponent<string>('core.mapDrops')\n\n/** What a thing placed on a map drops when it dies: one item from its table, on the ground where it fell */\nexport const dropFromTable = defineListener({\n\tid: 'core.dropFromTable',\n\tevent: entityDied,\n\trun(world, { entity }) {\n\t\tconst name = entity.get(mapDrops)\n\t\tif (!name) return\n\t\tconst table = world.map.itemTable(name)\n\t\tconst item = table && drawFromTable(table, world.registry, world.rng)\n\t\tif (item) dropOnGround(world, createItem(world, item), entity.pos)\n\t}\n})\n","import { deposit, type Entity } from './entity'\nimport { learn, setHeroLevel } from './hero'\nimport { inventorySlots } from './inventory'\nimport { createItem, giveItem } from './items'\nimport type { GameMap, MapObject, MapObjectOrder } from './map'\nimport { mapObjectData } from './mapFields'\nimport { clamp } from './math'\nimport { createOrder, giveOrder } from './orders/queue'\nimport { mapDrops } from './randomGroups'\nimport type { World } from './world'\n\n/*\n * What stands on a map put in the world: as the world is made of the map (`createWorldFromMap`), and one at a time\n * after, as the editor's Play here puts down what was placed on the map while it plays (`debug.mapObject`, EQ10)\n */\n\n/**\n * Makes an entity what the map says it starts as, beyond where it stands and whose it is: hurt, at a level, with\n * items. In an order that lets each count on the one before: the level first, which the health follows from\n */\nfunction startAs(world: World, entity: Entity, object: MapObject): void {\n\tif (object.level !== undefined) setHeroLevel(world, entity, object.level)\n\t// a point at a time, as a player would: what the level does not allow yet is left out\n\tfor (const [ability, level] of Object.entries(object.abilities ?? {})) {\n\t\tfor (let i = 0; i < level; i++) if (!learn(world, entity, ability)) break\n\t}\n\tfor (const item of object.items ?? []) {\n\t\tif (world.registry.items.has(item) && entity.has(inventorySlots)) giveItem(world, entity, createItem(world, item))\n\t}\n\tif (object.amount !== undefined && entity.get(deposit)) entity.get(deposit)!.amount = Math.max(object.amount, 0)\n\tif (object.health !== undefined) entity.hp = Math.max(Math.round(entity.maxHp * clamp(object.health, 0, 1)), 1)\n\tif (object.mana !== undefined) entity.mana = Math.round(entity.maxMana * clamp(object.mana, 0, 1))\n}\n\n/**\n * Puts an object of the map in the world as the map has it: where it stands, whose, turned, as big, named, hurt, at a\n * level, with items and its drops, the game's fields on it and the game told (`mapObject`), and kept as the entity of\n * that object (`World.mapEntities`). Not its orders: those are given once everything stands (`giveMapOrders`). Its\n * type as said: one drawn from a random group is drawn before\n *\n * @internal\n */\nexport function spawnMapObject(world: World, object: MapObject, map?: GameMap): Entity {\n\tconst entity = world.spawn(object.type, object.owner, object, {\n\t\tfacing: object.facing,\n\t\tscale: object.scale,\n\t\tlook: object.look,\n\t\tname: object.name,\n\t\tlifetime: object.lifetime,\n\t\tunderConstruction: object.underConstruction\n\t})\n\tstartAs(world, entity, object)\n\tif (object.drops) entity.set(mapDrops, object.drops)\n\tconst data = mapObjectData(world.registry, object, map)\n\t// a component with a field of the map's starts as the object says, or as the field's default\n\tfor (const component of world.registry.listedComponents()) {\n\t\tif (component.field && component.id in data) entity.set(component, structuredClone(data[component.id]))\n\t}\n\t// the game's turn: what its own fields mean is its to say\n\tif (world.hooks.has('mapObject')) world.hooks.run('mapObject', { entity, object, data })\n\tworld.mapEntities.set(object.id, entity.id)\n\treturn entity\n}\n\n/**\n * A unit of the map given what it does as the game begins (`MapObject.orders`): its own orders, one after the other,\n * as no player's command. What it cannot be given (a path the map has not) is left out\n *\n * @internal\n */\nexport function giveMapOrders(world: World, entity: Entity, orders: readonly MapObjectOrder[]): void {\n\tlet queue = false\n\tfor (const { kind, path, point } of orders) {\n\t\tconst init =\n\t\t\tkind === 'hold'\n\t\t\t\t? { type: 'hold' as const }\n\t\t\t\t: path\n\t\t\t\t\t? { type: kind === 'patrol' ? ('patrolPath' as const) : ('followPath' as const), path }\n\t\t\t\t\t: point\n\t\t\t\t\t\t? { type: kind === 'patrol' ? ('patrol' as const) : ('move' as const), point: { x: point.x, z: point.z } }\n\t\t\t\t\t\t: undefined\n\t\t// a guard with nowhere to go guards where it stands: what an idle unit does\n\t\tif (!init) continue\n\t\tconst order = createOrder(world, init as never)\n\t\tif (!world.registry.order(init.type).accepts(world, entity, init as never)) continue\n\t\tgiveOrder(world, entity, order, queue)\n\t\tqueue = true\n\t}\n}\n","import { type CommandDef, defineCommand, type DefinedCommand } from './commands'\nimport { footprintOf } from './defs'\nimport type { PlayerId } from './entity'\nimport { bool, type Check, type Checked, type Fields, id, ids, Invalid, isObject, number, object, oneOf, optional, point, string } from './fields'\nimport { grantXp, heroesOf, setHeroLevel } from './hero'\nimport { createItem, giveItem } from './items'\nimport { gameOver } from './engineEvents'\nimport { defeat } from './systems/victory'\nimport { earn } from './player'\nimport type { World } from './world'\nimport { teamMemory } from './session/memory'\nimport {\n\tblankDefinition,\n\tCOPY_OF,\n\tDATA_KINDS,\n\tdefinitionIn,\n\teditableFields,\n\tfitValue,\n\tnested,\n\tNEW_DEFINITION,\n\tpathCheck,\n\tvalueCheck\n} from './gameData'\nimport { hypot } from './exactMath'\nimport { replicateEvent, snapshotPart } from './replication'\nimport { groundReshaped } from './engineEvents'\nimport { type TerrainPatch, terrainPatchProblem } from './ground'\nimport type { MapObject } from './map'\nimport { giveMapOrders, spawnMapObject } from './mapObjects'\nimport { corpses } from './summons'\n\n/*\n * The debug tools as commands: cheats, the fog lifted, the time of day, the speed, things created and cleared, and\n * resources, experience and deaths given out. Commands like any other, so that they work the same wherever the\n * simulation runs, a server included; and only from players the session lets use them (`world.debugPlayers`): a seat\n * in the page that asked for it, a server started to allow it. Everyone else is told no\n */\n\n/**\n * A debug command of a game's or a scene's own: one that goes through only for players allowed the debug tools\n * (`world.debugPlayers`), and tells others so. Otherwise like `defineCommand`\n *\n * @beta\n */\nexport function defineDebugCommand<const T extends string, F extends Fields>(\n\ttype: T,\n\tfields: F,\n\texecute: (world: World, player: PlayerId, command: Checked<F>) => void\n): DefinedCommand<T, F> {\n\treturn defineCommand(type, fields, (world, player, command) => {\n\t\tif (!world.debugPlayers.has(player)) {\n\t\t\tworld.message(player, { key: 'debugNotAllowed' })\n\t\t\treturn\n\t\t}\n\t\texecute(world, player, command)\n\t})\n}\n\n/**\n * A prefab of the game's put down where it says, for the sender, turned as said: to try one out, and for the editor's Play\n *\n * @beta\n */\nexport const spawnPrefabCommand = defineDebugCommand(\n\t'debug.spawnPrefab',\n\t{ prefab: string, at: point, facing: optional(number) },\n\t(world, player, command) => {\n\t\tif (!world.registry.prefabs.has(command.prefab)) return world.message(player, { key: 'unknownPrefab', params: { prefab: command.prefab } })\n\t\tworld.spawnPrefab(command.prefab, { at: command.at, owner: player, facing: command.facing })\n\t}\n)\n\n/**\n * A switch for trying things out: abilities used again at once, abilities that cost no mana, the units of those who may\n * use the debug tools unharmed (`World.cheats`)\n *\n * @beta\n */\nexport const cheatCommand = defineDebugCommand(\n\t'debug.cheat',\n\t{ cheat: oneOf('noCooldowns', 'noManaCosts', 'invulnerable'), on: bool },\n\t(world, _player, command) => {\n\t\tworld.cheats[command.cheat] = command.on\n\t}\n)\n\n/**\n * Lifts the fog for the sender's team, or puts it back: in the simulation itself, so that units react to what is shown\n *\n * @beta\n */\nexport const revealCommand = defineDebugCommand('debug.reveal', { on: bool }, (world, player, command) => {\n\tworld.fog.setRevealed(world.player(player).team, command.on)\n})\n\n/**\n * The whole map explored for everyone, as a map that starts explored has it (`FogRules.startExplored`): the fog stays,\n * over what is not seen now, but the ground is dim, not black, and what stands on it and is no player's is known. Or no\n * longer: each team has explored what it sees now, and forgets what it does not\n *\n * @beta\n */\nexport const exploreCommand = defineDebugCommand('debug.explore', { on: bool }, (world, _player, command) => {\n\tworld.fog.exploreFromStart(command.on)\n\tfor (const [team, memory] of Object.entries(world.state(teamMemory))) {\n\t\t// what stands on it put among what each team knows again, at its next look (`TeamMemory.startKnown`)\n\t\tmemory.startKnown = false\n\t\tif (command.on) continue\n\t\tfor (const [id, state] of Object.entries(memory.structures))\n\t\t\tif (!world.fog.isVisible(Number(team), state.x, state.z)) delete memory.structures[Number(id)]\n\t}\n})\n\n/**\n * The time of day, in a game with days and nights\n *\n * @beta\n */\nexport const hourCommand = defineDebugCommand('debug.hour', { hour: number }, (world, _player, command) => {\n\tif (world.registry.day) world.clock.setHour(((command.hour % 24) + 24) % 24)\n})\n\n/**\n * How fast the game goes, 0 to pause, 8 at most: whoever runs it (a session in the page, a server) goes by it\n *\n * @beta\n */\nexport const speedCommand = defineDebugCommand('debug.speed', { speed: number }, (world, _player, command) => {\n\tworld.cheats.speed = Math.min(Math.max(command.speed, 0), 8)\n})\n\n/**\n * Creates something at a point, for a player: a building or a resource where there is room, or a group of units\n * (`count`, 50 at most). `hidden`: what can be invisible is out of sight from the start\n *\n * @beta\n */\nexport const spawnCommand = defineDebugCommand(\n\t'debug.spawn',\n\t{ unitType: string, owner: id, point, count: optional(number), hidden: optional(bool) },\n\t(world, player, command) => {\n\t\tif (!world.registry.units.has(command.unitType) || !world.players.has(command.owner)) return\n\t\tconst def = world.registry.unit(command.unitType)\n\t\tconst at = command.point\n\t\tif (def.kind !== 'unit') {\n\t\t\tconst fp = footprintOf(def)\n\t\t\tconst cell = world.grid.cellFor(at.x, at.z, fp.w, fp.d)\n\t\t\tif (!world.grid.canPlace(cell.x, cell.z, fp.w, fp.d)) world.message(player, { key: 'noRoomHere' })\n\t\t\telse world.spawn(def.id, command.owner, at)\n\t\t\treturn\n\t\t}\n\t\tconst count = Math.min(Math.max(Math.round(command.count ?? 1), 1), 50)\n\t\tconst columns = Math.ceil(Math.sqrt(count))\n\t\tconst spacing = def.radius * 2 + 0.4\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst column = (i % columns) - (columns - 1) / 2\n\t\t\tconst row = Math.floor(i / columns) - (Math.ceil(count / columns) - 1) / 2\n\t\t\tconst entity = world.spawn(def.id, command.owner, { x: at.x + column * spacing, z: at.z - row * spacing })\n\t\t\tif (command.hidden && entity.unseenIn !== null) entity.unseenIn = 0\n\t\t}\n\t}\n)\n\n/**\n * A brush: fills a circle with what stands on the grid (trees, rocks), thinner towards its edge, wherever there is room;\n * or, with `erase`, clears it of that type\n *\n * @beta\n */\nexport const paintCommand = defineDebugCommand(\n\t'debug.paint',\n\t{ unitType: string, owner: id, point, radius: number, erase: bool },\n\t(world, _player, command) => {\n\t\tif (!world.registry.units.has(command.unitType)) return\n\t\tconst def = world.registry.unit(command.unitType)\n\t\tconst { point: at } = command\n\t\tconst radius = Math.min(Math.max(command.radius, 0.5), 20)\n\t\tif (command.erase) {\n\t\t\tfor (const entity of [...world.entities.values()]) {\n\t\t\t\tif (entity.def.id === def.id && hypot(entity.pos.x - at.x, entity.pos.z - at.z) <= radius) world.kill(entity, undefined, false, 'removed')\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (def.kind === 'unit' || !world.players.has(command.owner)) return\n\t\tconst fp = footprintOf(def)\n\t\tfor (let z = Math.floor(at.z - radius); z <= at.z + radius; z += fp.d) {\n\t\t\tfor (let x = Math.floor(at.x - radius); x <= at.x + radius; x += fp.w) {\n\t\t\t\tconst centre = { x: x + fp.w / 2, z: z + fp.d / 2 }\n\t\t\t\tconst distance = hypot(centre.x - at.x, centre.z - at.z)\n\t\t\t\tif (distance > radius) continue\n\t\t\t\t// thinner towards the edge, the same way for the same cell so that a stroke does not fill up by going over it\n\t\t\t\tconst chance = ((x * 73856093) ^ (z * 19349663)) >>> 0\n\t\t\t\tif (distance > radius * 0.6 && chance % 100 < ((distance / radius - 0.6) / 0.4) * 70) continue\n\t\t\t\tif (!world.grid.canPlace(x, z, fp.w, fp.d)) continue\n\t\t\t\tworld.spawn(def.id, command.owner, centre)\n\t\t\t}\n\t\t}\n\t}\n)\n\n/**\n * Gives the sender this much of every resource\n *\n * @beta\n */\nexport const giveCommand = defineDebugCommand('debug.give', { amount: number }, (world, player, command) => {\n\tfor (const resource of world.registry.resources) earn(world.player(player).resources, resource.id, command.amount)\n})\n\n/**\n * Gives the sender's heroes this much experience\n *\n * @beta\n */\nexport const experienceCommand = defineDebugCommand('debug.experience', { amount: number }, (world, player, command) => {\n\tfor (const hero of heroesOf(world, player)) if (hero.alive) grantXp(world, hero, command.amount)\n})\n\n/**\n * Puts units at a point, side by side, wherever they stood: structures stay where they were built. The way there is\n * not their concern (`World.place`)\n *\n * @internal\n */\nexport const teleportCommand = defineDebugCommand('debug.teleport', { entities: ids, point }, (world, _player, command) => {\n\tconst units = command.entities.flatMap((entityId) => {\n\t\tconst entity = world.get(entityId)\n\t\treturn entity?.alive && entity.isUnit ? [entity] : []\n\t})\n\tconst columns = Math.ceil(Math.sqrt(units.length))\n\tunits.forEach((entity, i) => {\n\t\tconst spacing = entity.def.radius * 2 + 0.4\n\t\tconst column = (i % columns) - (columns - 1) / 2\n\t\tconst row = Math.floor(i / columns) - (Math.ceil(units.length / columns) - 1) / 2\n\t\tworld.place(entity, { x: command.point.x + column * spacing, z: command.point.z - row * spacing })\n\t})\n})\n\n/**\n * Gives what it names to another player (`World.setOwner`): what it was doing is called off\n *\n * @internal\n */\nexport const setOwnerCommand = defineDebugCommand('debug.setOwner', { entities: ids, owner: id }, (world, _player, command) => {\n\tif (!world.players.has(command.owner)) return\n\tfor (const entityId of command.entities) {\n\t\tconst entity = world.get(entityId)\n\t\tif (entity?.alive) world.setOwner(entity, command.owner)\n\t}\n})\n\n/**\n * Puts an item of the game's in the first free slot of what carries things\n *\n * @beta\n */\nexport const giveItemCommand = defineDebugCommand('debug.giveItem', { entity: id, item: string }, (world, _player, command) => {\n\tconst entity = world.get(command.entity)\n\tif (!entity?.alive || !world.registry.items.has(command.item)) return\n\tgiveItem(world, entity, createItem(world, command.item))\n})\n\n/**\n * Researches an upgrade for the sender, to the level asked (its last when left out), at once and for nothing: what it\n * does to the units there are runs for each level it gains\n *\n * @internal\n */\nexport const researchCommand = defineDebugCommand('debug.research', { upgrade: string, level: optional(number) }, (world, player, command) => {\n\tif (!world.registry.upgrades.has(command.upgrade)) return\n\tconst def = world.registry.upgrade(command.upgrade)\n\tconst who = world.player(player)\n\tconst to = Math.min(Math.max(Math.round(command.level ?? def.maxLevel ?? 1), 0), def.maxLevel ?? 1)\n\tfor (let level = (who.upgrades.get(command.upgrade) ?? 0) + 1; level <= to; level++) {\n\t\twho.setUpgrade(command.upgrade, level)\n\t\tif (def.apply) for (const entity of [...world.index.ownedBy(player)]) if (entity.alive) def.apply(world, entity, level)\n\t}\n\twho.researching.delete(command.upgrade)\n})\n\n/**\n * Raises heroes to a level (never down, and no further than they can go: `setHeroLevel`)\n *\n * @beta\n */\nexport const setLevelCommand = defineDebugCommand('debug.setLevel', { entities: ids, level: number }, (world, _player, command) => {\n\tfor (const entityId of command.entities) {\n\t\tconst entity = world.get(entityId)\n\t\tif (entity?.alive) setHeroLevel(world, entity, command.level)\n\t}\n})\n\n/**\n * Wins the game for the sender's team: the others are out, and it is over. A game with a way to win of its own is\n * ended all the same\n *\n * @beta\n */\nexport const winCommand = defineDebugCommand('debug.win', {}, (world, player) => {\n\tif (world.winner !== null) return\n\tconst team = world.player(player).team\n\tfor (const other of world.players.values()) {\n\t\tif (other.neutral || other.creeps) continue\n\t\tother.established = true\n\t\tif (other.team !== team && !other.defeated) defeat(world, other.id)\n\t}\n\tworld.winner = team\n\tworld.events.emit(gameOver, { winner: team })\n})\n\n/**\n * Puts the sender out of the game, as if beaten: the others play on, or win by the game's own rule\n *\n * @beta\n */\nexport const loseCommand = defineDebugCommand('debug.lose', {}, (world, player) => {\n\tconst who = world.player(player)\n\tif (who.neutral || who.creeps || who.defeated || world.winner !== null) return\n\twho.established = true\n\tdefeat(world, player)\n})\n\n/**\n * Kills what it names, whoever's it is: what cannot be hurt included, but not scenery the map is made of\n *\n * @beta\n */\nexport const killCommand = defineDebugCommand('debug.kill', { entities: ids }, (world, _player, command) => {\n\tfor (const entityId of command.entities) {\n\t\tconst entity = world.get(entityId)\n\t\tif (entity?.alive && !entity.def.invulnerable) world.kill(entity, undefined, false, 'removed')\n\t}\n})\n\n/**\n * Changes a field of a definition while the game runs, as the editor's Data panel tries it: only one the game lets be\n * changed (`GameModule.editable`), and for players allowed the debug tools\n *\n * @beta\n */\nexport const redefineCommand = defineDebugCommand(\n\t'debug.redefine',\n\t{ kind: oneOf(...DATA_KINDS), id: string, path: pathCheck, value: valueCheck },\n\t(world, player, command) => {\n\t\tconst def = definitionIn(world.registry, command.kind, command.id)\n\t\t// a copy made, of one the game lets be changed\n\t\tif (!def && command.path === COPY_OF && typeof command.value === 'string') {\n\t\t\tconst base = definitionIn(world.registry, command.kind, command.value)\n\t\t\tif (base && editableFields(world.registry.module, command.kind, base).length)\n\t\t\t\tworld.redefine(command.kind, command.id, { [COPY_OF]: command.value })\n\t\t\treturn\n\t\t}\n\t\t// one of its own made of nothing, of a kind the game lets be changed\n\t\tif (!def && command.path === NEW_DEFINITION && command.value === true) {\n\t\t\tif (editableFields(world.registry.module, command.kind, blankDefinition(command.kind, command.id)).length)\n\t\t\t\tworld.redefine(command.kind, command.id, { [NEW_DEFINITION]: true })\n\t\t\treturn\n\t\t}\n\t\tif (!def) return\n\t\tconst field = editableFields(world.registry.module, command.kind, def).find((each) => each.path === command.path)\n\t\tconst fit = field ? fitValue(field, command.value) : { error: `${command.path} cannot be changed` }\n\t\tif ('error' in fit) world.message(player, { key: 'dataRefused', params: { why: fit.error } })\n\t\telse world.redefine(command.kind, command.id, nested(command.path, fit.value))\n\t}\n)\n\n/** The most of anything a value of a map's own may hold, and as deep: a field of the game's, not a file */\nconst PLAIN_MOST = 10_000\nconst PLAIN_DEPTH = 16\n\n/** What the map's own fields hold (`MapObject.data`): numbers, words, switches, lists and objects of them, and nothing else */\nconst plain: Check<unknown> = (value, path) => {\n\tlet count = 0\n\tconst copy = (each: unknown, at: string, depth: number): unknown => {\n\t\tif (++count > PLAIN_MOST || depth > PLAIN_DEPTH) throw new Invalid(`${path} is more than a field of the map holds`)\n\t\tif (each === null || typeof each === 'boolean' || typeof each === 'string') return each\n\t\tif (typeof each === 'number') return number(each, at)\n\t\tif (Array.isArray(each)) return each.map((item, i) => copy(item, `${at}[${i}]`, depth + 1))\n\t\tif (isObject(each)) return Object.fromEntries(Object.entries(each).map(([key, item]) => [key, copy(item, `${at}.${key}`, depth + 1)]))\n\t\tthrow new Invalid(`${at} is not a value of the map's`)\n\t}\n\treturn copy(value, path, 0)\n}\n\n/** A list of what a check takes, so long at most */\nconst listOf =\n\t<T>(check: Check<T>, most: number): Check<T[]> =>\n\t(value, path) => {\n\t\tif (!Array.isArray(value) || value.length > most) throw new Invalid(`${path} is a list of at most ${most}`)\n\t\treturn value.map((item, i) => check(item, `${path}[${i}]`))\n\t}\n\n/** What a cell of the ground holds: 0 to 255 */\nconst byte: Check<number> = (value, path) => {\n\tif (!Number.isInteger(value) || (value as number) < 0 || (value as number) > 255) throw new Invalid(`${path} is a whole number of 0 to 255`)\n\treturn value as number\n}\n\n/** The most cells a patch of the ground has: a map of 2048 a side */\nconst MOST_CELLS = 2049 * 2049\n\n/** A patch of the ground (`TerrainPatch`), each layer the size the ground says, checked as it is put in */\nconst terrainPatchCheck: Check<TerrainPatch> = (value, path) => {\n\tconst checked = object({\n\t\tx: id,\n\t\tz: id,\n\t\twidth: id,\n\t\tdepth: id,\n\t\theights: listOf(number, MOST_CELLS),\n\t\twaterHeights: listOf(number, MOST_CELLS),\n\t\tlevels: listOf(byte, MOST_CELLS),\n\t\twater: listOf(byte, MOST_CELLS),\n\t\ttiles: listOf(byte, MOST_CELLS),\n\t\tblocked: listOf(byte, MOST_CELLS),\n\t\tcells: optional((layers, at): Record<string, number[]> => {\n\t\t\tif (!isObject(layers)) throw new Invalid(`${at} is the layers of cells by id`)\n\t\t\treturn Object.fromEntries(\n\t\t\t\tObject.entries(layers).map(([layer, cells]) => [string(layer, at), listOf(byte, MOST_CELLS)(cells, `${at}.${layer}`)])\n\t\t\t)\n\t\t})\n\t})(value, path)\n\treturn checked as TerrainPatch\n}\n\n/** An object of the map (`MapObject`), as the editor has it: what of it the world reads, checked. Not turned, and as big as its type, when it does not say */\nconst mapObjectCheck: Check<MapObject> = (value, path) =>\n\t({\n\t\tfacing: 0,\n\t\tscale: 1,\n\t\t...object({\n\t\t\tid,\n\t\t\ttype: string,\n\t\t\towner: id,\n\t\t\tx: number,\n\t\t\tz: number,\n\t\t\tfacing: optional(number),\n\t\t\tscale: optional(number),\n\t\t\tlook: optional(string),\n\t\t\tdrops: optional(string),\n\t\t\tname: optional(string),\n\t\t\thealth: optional(number),\n\t\t\tmana: optional(number),\n\t\t\tlevel: optional(number),\n\t\t\tabilities: optional(plain),\n\t\t\titems: optional(listOf(string, 100)),\n\t\t\tamount: optional(number),\n\t\t\tunderConstruction: optional(bool),\n\t\t\tlifetime: optional(number),\n\t\t\torders: optional(plain),\n\t\t\tdata: optional(plain)\n\t\t})(value, path)\n\t}) as MapObject\n\n/**\n * An object placed on the map put in the world as the map's are as the world is made (`spawnMapObject`): its type,\n * owner, where it stands and how it is turned, and the rest the map says of it (its health, level, items, the game's\n * fields, its orders), kept as the entity of that object (`World.mapEntities`): what the editor's Play here sends as\n * something is placed on the map while it plays (EQ10). A building where there is no room is refused, as `debug.spawn`\n * refuses it\n *\n * @beta\n */\nexport const mapObjectCommand = defineDebugCommand('debug.mapObject', { object: mapObjectCheck }, (world, player, command) => {\n\tconst { object } = command\n\tif (!world.registry.units.has(object.type) || !world.players.has(object.owner)) return\n\tconst def = world.registry.unit(object.type)\n\tif (def.kind !== 'unit') {\n\t\tconst fp = footprintOf(def)\n\t\tconst cell = world.grid.cellFor(object.x, object.z, fp.w, fp.d)\n\t\tif (!world.grid.canPlace(cell.x, cell.z, fp.w, fp.d)) return world.message(player, { key: 'noRoomHere' })\n\t}\n\tconst entity = spawnMapObject(world, object)\n\tif (Array.isArray(object.orders) && object.orders.length) giveMapOrders(world, entity, object.orders)\n})\n\n/**\n * Moves what an object of the map became (`World.mapEntities`, by the object's id) where it stands on the map now,\n * turned as it is: a unit is put there (`World.place`), the way there not its concern. A structure is not moved: the\n * editor takes it away and puts it down again\n *\n * @beta\n */\nexport const placeCommand = defineDebugCommand('debug.place', { object: id, point, facing: optional(number) }, (world, _player, command) => {\n\tconst entity = world.get(world.mapEntities.get(command.object))\n\tif (!entity?.alive || entity.isStructure) return\n\tworld.place(entity, command.point)\n\tif (command.facing !== undefined) entity.facing = command.facing\n})\n\n/**\n * Takes what objects of the map became (`World.mapEntities`, by the objects' ids) out of the world, whatever they\n * are, scenery included: no corpse is left. What the editor's Play here sends as something is taken off the map\n *\n * @beta\n */\nexport const unplaceCommand = defineDebugCommand('debug.unplace', { objects: ids }, (world, _player, command) => {\n\tconst gone = new Set<number>()\n\tfor (const object of command.objects) {\n\t\tconst entity = world.get(world.mapEntities.get(object))\n\t\tworld.mapEntities.delete(object)\n\t\tif (!entity?.alive) continue\n\t\tworld.kill(entity, undefined, false, 'removed')\n\t\tgone.add(entity.id)\n\t}\n\tconst lying = world.state(corpses)\n\tif (lying.some((corpse) => gone.has(corpse.id)))\n\t\tworld.setState(\n\t\t\tcorpses,\n\t\t\tlying.filter((corpse) => !gone.has(corpse.id))\n\t\t)\n})\n\n/**\n * Reshapes a part of the ground as the patch has it (`World.reshapeGround`): what the editor's Play here sends of the\n * map's ground as its heights, cliffs, water and paint are edited while it plays. A patch that does not fit the ground\n * is refused\n *\n * @beta\n */\nexport const groundCommand = defineDebugCommand('debug.ground', { patch: terrainPatchCheck }, (world, player, command) => {\n\tconst problem = terrainPatchProblem(world.terrain, command.patch)\n\tif (problem) return world.message(player, { key: 'dataRefused', params: { why: problem } })\n\tworld.reshapeGround(command.patch)\n})\n\n/** The ground reshaped (`World.reshapeGround`): to everyone, as it is now */\nexport const toldGround = replicateEvent(groundReshaped, 'ground', ({ patch }) => ({ type: 'ground', patch: structuredClone(patch) }))\n\n/**\n * The debug commands of the engine, which every game has; they go through only for who may use them\n *\n * @beta\n */\nexport const debugCommands: CommandDef[] = [\n\tcheatCommand,\n\trevealCommand,\n\texploreCommand,\n\thourCommand,\n\tspeedCommand,\n\tspawnCommand,\n\tpaintCommand,\n\tgiveCommand,\n\texperienceCommand,\n\tkillCommand,\n\tspawnPrefabCommand,\n\tteleportCommand,\n\tsetOwnerCommand,\n\tgiveItemCommand,\n\tresearchCommand,\n\tsetLevelCommand,\n\twinCommand,\n\tloseCommand,\n\tmapObjectCommand,\n\tplaceCommand,\n\tunplaceCommand,\n\tgroundCommand\n] as unknown as CommandDef[]\n\n/** What a player who may use the debug commands is told of them (`Snapshot.debug`): the switches on, and whether the map started explored */\nexport const debugPart = snapshotPart(\n\t'debug',\n\t({ world, player }) => (world.debugPlayers.has(player) ? { ...world.cheats, explored: world.fog.exploredFromStart } : undefined),\n\ttrue\n)\n"],"mappings":";;;;;;;;;;;;AAYA,IAAM,uBAAO,IAAI,yBAAS,IAAI,YAAY,CAAC,CAAC;AAC5C,SAAS,SAAS,GAAmB;CACpC,KAAK,WAAW,GAAG,CAAC;CACpB,OAAO,KAAK,SAAS,CAAC;AACvB;AAIA,IAAM,KAAK;AACX,IAAM,KAAK;AACX,IAAM,KAAK;AACX,IAAM,KAAK;AACX,IAAM,KAAK;AACX,IAAM,KAAK;;AAGX,SAAS,UAAU,GAAW,GAAW,MAA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