From 0eed9f54481da86a584465ff0b33509ac6d7c5a9 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:41:19 +0000 Subject: [PATCH 01/13] Add: Specify the players subsystem Assisted-by: Claude Code:claude-opus-5-5 --- specs/players.md | 613 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 613 insertions(+) create mode 100644 specs/players.md diff --git a/specs/players.md b/specs/players.md new file mode 100644 index 0000000..0612a03 --- /dev/null +++ b/specs/players.md @@ -0,0 +1,613 @@ +# players + +## 1. Role + +Players is the per-player state the simulation keeps besides the economy: each player's 30-tick update and +the end of the match, the victory and defeat conditions of a campaign mission, a unit handed to another +player, the killing of all of a player's units, the transfer of energy and metal between players, and the +console's and dialogs' changes to a player (its store, its type, the local and viewed player, the cheat +toggles, the end of the game). The engine runs a player's turn in the players phase in three parts around +other subsystems' work (the head, the body and the tail), then the finish once per tick. Other modules and +the engine reach players with events through `Apply`. Players' own writes into units go out as effects to +units, its grants of resources as events to economy. + +## 2. Interface + +### Slots (`interfaces/players.h`, version 5.4) + +| Slot | When the engine calls it | +| --- | --- | +| `Apply` | for each event of players' inbox: before each run below, at each phase boundary, and at once for a synchronous route or an event published outside the tick (`docs/schedule.md`, "Routes"; `data/routes.csv`) | +| `UpdatePlayerHead` | in the players phase, for each player slot 0 to 9 in order | +| `UpdatePlayerBody` | in the same player's turn, when its head returned 1, after the other subsystems' work of the turn (`docs/schedule.md`, the pass `players`) | +| `UpdatePlayerTail` | in the same turn, when the body returned 1 or 2, after economy's settlement and the viewed player's radar passes | +| `UpdatePlayersFinish` | once per tick, after the tenth player's turn | +| `UpdatePlayers`, `UpdatePlayersOnStream` | the whole players pass, when the engine runs it outside the tick loop (`UpdatePlayersOnStream` with the load stream at the load of a match, `docs/schedule.md`, "The load"; `UpdatePlayers` from the in-game dialogs) | +| `DeactivateConditions` | when a unit command stops the conditions of the mission | +| `RegionSize`, `Init` | once per match, at its load, before any event and before the first tick | +| `Shutdown` | once per match, when it is unloaded | + +### The engine's slots + +The kit's entry (`wasm/modules.json`, `modules`, the entry named `players`) names 17 slots under `engine`. By +ABI section 6, "Engine slots", each stays in the engine: the host calls the engine's native slot, the module +doesn't export it, and the native slot reads and writes the module's state in the block, the region included +(section 3). They are the 15 "load class" slots (`LoadDefaultAIScript`, `InitPlayers`, `FreePlayers`, +`InitPlayerResources`, `LoadPlayerControllers`, `LoadPlayers`, `SavePlayers`, `RebuildAIFeatureCells`, +`SetupPlayerSlot`, `LoadConditions`, `SaveConditions`, `RegisterConditions`, `FreeConditions`, +`DeleteConditions`, `NewConditions`), `UpdateBlink` (presentation) and `WriteState` (a dump query, ABI 9.3, +"What stays in the engine"). ozgb/btm#43 moves load-class slots into modules later. This spec describes +only what those slots leave in the block that the module's slots read (section 3). + +### The manifest entry + +The kit's entry for players is the module's entry, and this spec follows it exactly: + +- `name` and `interface`: `players`. +- `majors`: `players` 5, `mission` 2, `units` 7, `map` 9, `features` 5, `network` 2, `los_radar` 5, + `economy` 5, `services` 4. +- `data_base` 524288 and `table_base` 368: the module's window is the 32768 bytes (the manifest's `window`) + from 524288, and its table range the 32 entries (`table_slots`) from 368 (ABI 2). +- `exports`, in this order: `Apply`, `UpdatePlayers`, `DeactivateConditions`, `UpdatePlayersOnStream`, + `UpdatePlayerHead`, `UpdatePlayerBody`, `UpdatePlayerTail`, `UpdatePlayersFinish`, `RegionSize`, `Init`, + `Shutdown`. +- `data`: `g_game`, `g_simGlobals`, `g_extTdf`, `g_blockBase`, `g_region` (ABI 8.2). The module reads + `g_game`, `g_simGlobals`, `g_blockBase` and `g_region`; `g_region` is the address of its region in every + slot after `Init`, so the module keeps no pointer of its own. +- Slot kinds (the entry's `slots`): + +| Slot | Kinds | +| --- | --- | +| `Apply` | `[linear, int] -> int` (the event, its size) | +| `UpdatePlayers`, `UpdatePlayersFinish` | `[] -> void` | +| `DeactivateConditions` | `[block] -> void` (the conditions object) | +| `UpdatePlayersOnStream` | `[int] -> void` (the stream: 0 main, 1 load) | +| `UpdatePlayerHead` | `[int] -> int` | +| `UpdatePlayerBody` | `[int, int] -> int` (the player, the stream) | +| `UpdatePlayerTail` | `[int] -> void` | +| `RegionSize` | `[linear] -> int` (a `PlayersMapInfo`) | +| `Init` | `[linear, block, int] -> void` (the `PlayersMapInfo`, the region, its size) | +| `Shutdown` | `[] -> block` | + +- `imports`, every one listed and nothing else (ABI 9.1): + +| Import | Kinds | Used for | +| --- | --- | --- | +| `mission.GetGameType` | `[] -> int` | the game type: 1 campaign, 2 skirmish, 3 multiplayer | +| `mission.GetMissionParams` | `[linear] -> void` | the respawn's lava test (a `MissionParams` of the module's own) | +| `units.CreateUnit` | `[int, int, linear, int, int, int] -> block` | the respawned commander | +| `units.FindUnitTypeId` | `[linear] -> int` | a unit type by name (conditions, the respawn) | +| `map.UnitsInRange` | `[linear, int, int, linear, int] -> int` | the units inside a radius condition's circle | +| `map.GetCellMeanHeight` | `[linear] -> int` | the respawn's lava test | +| `features.FindFeatureAtPos` | `[linear, linear, linear] -> int` | the respawn's test for a feature | +| `network.BroadcastPlayerInfo` | `[] -> void` | a defeated local player put in watch mode | +| `network.SendShareMetal` | `[int, int, f32] -> void` | an announced transfer of energy (section 4, Q1) | +| `network.SendShareEnergy` | `[int, int, f32] -> void` | an announced transfer of metal (Q1) | +| `network.BroadcastPlayerEconomy` | `[block] -> void` | the viewed player's economy, in a multiplayer game | +| `los_radar.ClampWorldPosToTerrain` | `[int, int, linear] -> void` | a radius condition's centre, once | +| `economy.Spend` | `[linear] -> int` | the giver's spend of an announced transfer (an `EconomySpend` of the module's own) | +| `services.RecordSimEvent` | `[int, int, linear, int] -> void` | the sim events of section 2, "Events" | +| `services.Emit` | `[linear, int] -> void` | every effect and event the module publishes | + +- `publishes`, the kinds and sizes `Emit` takes (ABI 9.3): 0 (`ECONOMY_RESET`, 12), 4 (`ECONOMY_INCOME`, 24), + 128 (`LOS_RADAR_UPDATE_UNIT`, 8), 133 (`LOS_RADAR_RECALCULATE`, 8), 208 (`PLAYERS_EFFECT_KILL_UNIT`, 12), 209 + (`PLAYERS_EFFECT_SEND_UNIT`, 12), 210 (`PLAYERS_EFFECT_CAPTURE_UNIT`, 48). The module's slots publish 4, 133, + 208, 209 and 210; 0 and 128 are published only by engine slots. Every route of these kinds is synchronous + except economy's two (`data/routes.csv`), so an effect to units or los_radar has been applied when `Emit` + returns, and its writes are in the block for what the module reads after it. +- `blocked`: the entry's reason says that the footprint service (`services.ScheduleMapCanPlaceUnitFootprint`), + the lookup of the host slot and the four tables of saved-game account names have no import. By ABI 4.2 an entry with `blocked` has no `.wasm` and no budgets (`fuel_budget`, `size_budget`), and + the host runs the native default for every slot. A module built from this spec meters itself by rule + version 1 (ABI section 11) and exports `__fuel_set` and `__fuel_get`; its budgets come with a later entry. + Section 2, "Kit gaps", says which parts of this spec meet which part of that reason. +- Hooks: every slot of `interfaces/players.h` says "Hooks: none"; the event kind `PLAYERS_GIVE_UNIT` names + `UnitTransfer`. The kit defines no hook in the module ABI and the import list has none, so the module raises + none; no recording shows one. + +### Routes and the recordings + +A recording shows the module's `Emit` as `i services.SchedPublish 4 ` (the recorded call of ABI 9.3, +"Routes in the recordings"; 4 is players' outbox) and its `economy.Spend` as `i services.ScheduleEconomySpend`. +An `o rng.seed` or `w Game.playerIndex` line after a publish is what the synchronous delivery of the effect +changed, not a write of the module. A `c` line under `map.UnitsInRange` doesn't occur: the module takes ids, +not a callback. + +### Arguments outside the block + +- **The event** of `Apply` is the payload struct of its kind in `interfaces/players.h`, laid out with no + padding (ABI 6.1): `PlayersEventHeader` (8 bytes: `kind`, `unit` as a block offset), then the kind's fields. + Sizes: `PLAYERS_GIVE_UNIT` 48, `PLAYERS_KILL_UNITS` 12, `PLAYERS_TRANSFER` 28, `PLAYERS_SET_STORE` 24, + `PLAYERS_SET_TYPE` 16, `PLAYERS_END_GAME` 12, `PLAYERS_SET_CHEATS` 16, `PLAYERS_SET_CONTROL` and + `PLAYERS_SET_VIEW` 12, every other kind of the header (the header alone) 8, and the effect kinds 208, 209 + and 210 their payloads' 12, 12 and 48. +- **`PlayersMapInfo`** (`RegionSize`, `Init`): one `int`, `playerCount`. The module doesn't read it. +- **What the module builds for an import** lives on its stack or in its window: the `EconomySpend` of + `economy.Spend` (24 bytes: `kind` 3, `player`, `unit` 0, `resources`, `energy`, `metal`), the effects and + events it gives `Emit`, the argument array of `services.RecordSimEvent`, the `Vec3` of a position, the + `MissionParams` (124 bytes; the module reads `lavaWorld`, the sixth 32-bit field, at offset 20), the id + buffer of `map.UnitsInRange` (256 unsigned 16-bit ids) and the NUL-terminated names given to + `units.FindUnitTypeId`. A name given to `units.FindUnitTypeId` may also be the field itself in the block + (a condition's `name`, a `SideDef.commander`): the recording shows the text. +- **The `Vec3` of a radius condition** is the condition's own `pos` in the block: `los_radar.ClampWorldPosToTerrain` + writes it in place, and `map.UnitsInRange` reads it there. + +### Events + +The module's slots record these kinds through `services.RecordSimEvent`, with flags 0; the kit's +`docs/sim-events.md` gives their arguments and phases: + +- `SIM_EVENT_SOUND`, arguments `[0, 0]` (sound name 0, the victory condition sound, and play flag 0): when a + victory condition is satisfied for the first time, in the cases of section 4, "Conditions" (it is recorded + only while the condition's `celebrated` is 0, which it then sets to 1). +- `SIM_EVENT_FOCUS_COMMANDER`, arguments `[1]`: when the commander of the local player is respawned + (section 4, "The respawn"). +- `SIM_EVENT_WATCH_PROMPT`, arguments `[p]`: when the defeated local player *p* of a multiplayer game is put + in watch mode and no active AI player is left (section 4, "Watch mode"). +- `SIM_EVENT_WATCH_MODE_NOTICE`, arguments `[p]`: on the same path, when an active AI player is left and at + least one combat player. + +The terms "unit flag 0x10000000", "unit flag 0x4000", "map flag 1", "map flag 2" and "info flag 0x40" are +those of `docs/sim-events.md`, Terms. + +### Kit gaps + +What this spec needs and the kit doesn't give; the maintainer routes them: + +- **K1, the class of a condition.** A condition (section 3) is told apart by its first word, the vtable + pointer of its class, which the engine's load-class slots write and the kit gives no value for (the + layout's `MissionCondition` has `vptr` true and no field for it; the recordings name the class, + `VictoryKillAllOfType#1`, but never the word). Every slot that runs a condition needs the class. Until the + kit gives the 18 words (or a class number in the block), this spec states each class's behaviour, and a + module can't pick it from the block alone. +- **K2, the respawn's imports.** The respawn (section 4) asks `map.CanPlaceUnitFootprint` (the recorded + `services.ScheduleMapCanPlaceUnitFootprint`) and draws from `services.RandomInt`; the entry lists neither. + This is the first part of the entry's `blocked` reason. No recording reaches the respawn. +- **K3, the host slot.** The entry's `blocked` reason names it as a call with no import. Section 4 defines + the host slot from block fields, so the module needs no import for it; only the respawn and watch mode read + it, and no recording reaches either. +- **K4, the saved game's account names** (the tables of the `blocked` reason) serve only the engine + slots `LoadConditions` and `SaveConditions`; no exported slot needs them. +- **K5, the whole pass.** `UpdatePlayers` and `UpdatePlayersOnStream` are exported, but the players pass + calls other subsystems' slots (pathfinding, movement, ai, los_radar, units, economy; `docs/schedule.md`, the + passes `players` and `players.los`), and the entry lists none of them as an import. No recording holds + either slot. +- **K6, a condition list that is empty.** A campaign check of an empty list adds a condition to it (section + 4, "Checks"), which needs a block allocation (`services.SimAlloc`, not in the entry) and the class word of + K1. No recording has an empty list. +- **K7, `PLAYERS_DEACTIVATE_CONDITIONS` with no conditions**: the header lists no refusal for it. This spec + makes it change nothing with outcome 0 (section 4, `Apply`). +- **K8, a respawn whose `units.CreateUnit` gives null.** The reference reads the new unit for its incomes + without a test, so the case has no defined result; the kit says nothing of it either. + +## 3. State + +### Owned + +**The region** (`RegionSize`, `Init`; ABI 8.2 `g_region`), 84 bytes, little-endian. Its layout is fixed by the +engine slots, which write it too (`InitPlayers` sets each player's clocks at the start of a match, `LoadPlayers` +restores them, `SavePlayers` stores them): + +| Bytes | Field | +| --- | --- | +| 0 to 1 | the *countdown*, a signed 16-bit number; below 0 means not running | +| 2 to 3 | unused, 0 | +| 4 to 43 | the *update clock* of players 0 to 9, ten unsigned 32-bit ticks (player *p* at 4 + 4*p*) | +| 44 to 83 | the *win clock* of players 0 to 9, ten 32-bit ticks; the module's slots never read or write it | + +**`Player`** (the array `Game.players`, 331 bytes apart from offset 7011; index 10 is the record past the ten +players, `Game.players_1b63`): `rank` (byte), `energy`, `metal` (floats; written by `PLAYERS_SET_STORE`), +`type` (byte), `energyStorageBonus`, `metalStorageBonus` (floats) and bit 0 of `flags` (the respawn). + +**`PlayerInfo`** (a player's `info`, a `Ref`): `kind` (byte, `PLAYERS_SET_TYPE`) and `bit6` (info flag 0x40). + +**`Game`:** `endGameFlags` (16 bits: bit 2 *ended*, bit 5 *won*, bit 6 *lost*), `endGameVictory` (byte), +`localPlayer`, `playerIndex` (bytes, the local and the viewed player), `uiOptionFlags` (16 bits) and bits 0 and +1 of `mapFlags` (map flags 1 and 2). + +**`SimGlobals.g_economyPacketTick`** (32 bits): the count of the viewed player's tails in a multiplayer game. + +**The conditions** (`Game.list_391ed`, a `Ref`, null when there are none): the record +`MissionConditions` (140 bytes): `victory` and `defeat` (16 `Ref` each), `victoryCount`, +`defeatCount` (at most 16) and `active`. Each condition starts with the class word (K1), then `satisfied` and +`celebrated` at 4 and 8. The classes, by their `layout.json` record, and the fields the module writes: + +| Class | List | Fields after `celebrated` | +| --- | --- | --- | +| `VictoryKillEnemyCommander` | victory | none | +| `VictoryDestroyAllUnits` | victory | none | +| `VictoryKillAllMobileUnits` | victory | `numUnits` (16) | +| `VictoryBuildUnitType` | victory | `name` (16, 32 bytes), `id` (48, 16 bits) | +| `VictoryCaptureUnitType` | victory | `name` (12) | +| `VictoryKillAllOfType` | victory | `name` (16), `id` (48), `count` (50, 32 bits) | +| `VictoryKillUnitType` | victory | `name` (12), `numLeftToKill` (44) | +| `VictoryMoveUnitToRadius` | victory | `name` (16), `pos` (48, a `Vec3`), `radius` (60) | +| `VictoryUnitTypePassesX` | victory | `name` (16), `x` (48) | +| `VictoryUnitTypePassesZ` | victory | `name` (16), `z` (48) | +| `VictoryTimerRunsOut` | victory | `endTick` (12, unsigned) | +| `DefeatCommanderKilled` | defeat | none | +| `DefeatAllUnitsKilled` | defeat | none | +| `DefeatAllUnitsKilledOfType` | defeat | `name` (16), `id` (48), `count` (50) | +| `DefeatUnitTypeKilled` | defeat | `name` (12), `numLeftToKill` (44) | +| `DefeatDeathTimerRunsOut` | defeat | `endTick` (12) | +| `DefeatAnyUnitPassesX` | defeat | `x` (16) | +| `DefeatAnyUnitPassesZ` | defeat | `z` (16) | + +Offsets are bytes from the condition's start; `id` and `count` are unaligned. A `name` is NUL-terminated +(empty for "any type" in the radius and passes classes). The module never writes a class word, a `name`, an +`x`, a `z`, a `radius` or an `endTick`. A radius condition's `pos` holds the centre's x and z as given, and y +the marker 0x12345678 until the centre is put on the ground (section 4). + +### Read + +- `Game`: `ticks` (unsigned for every comparison), `players`, `numPlayers` (unsigned 16 bits), + `commanderDeath` (int: 2 is the respawn of a commander, "Deathmatch"), `baseX`, `baseY`, `width`, `height` + (ints), `seaLevel` (unsigned byte), `units` and `defs` (`Ref`s to the unit table, 280 bytes a unit, and the + unit types, 585 bytes a type), `sideDefs` (`SideDef[5]`, 562 bytes each; its `commander` is the name of the + side's commander type), `field_1df2` (16 bits at 7666, the same word as `Game.players[1].unitCount`), + `SimGlobals.g_quirks.rankCompactionPerTick` (`interfaces/quirks.h`; 0 in every recording). +- `Player`: `active` (int), `type`, `index`, `rejectReason` (bytes), `info`, `unitsBegin`, `unitsEnd` (`Ref`s), + `unitCount` (unsigned 16 bits), `unitsCreated` (int), `allied`, `alliedBy` (11 bytes each, indexed by player). +- `PlayerInfo`: `side` (byte), `host` (bit 0 of `flags_97`), `bit6` (info flag 0x40, watch mode), `watching` + (bit 7 of `flags_9b`, the host's "watching allowed"), `f9d_1` (bit 1 of `flags_9d`, allied victory), + `energy`, `metal` (unsigned 16 bits: the host's start resources, in hundreds). +- `Unit`: `flags` (bit 28 unit flag 0x10000000 alive, bit 14 unit flag 0x4000 dying, bit 5 (0x20), bit 30 of a + carrier (0x40000000)), `player` (`Ref`), `playerIndex` (byte), `def` (`Ref`), + `unitDefIndex` (16 bits; 0 is an empty slot), `motion` (`Ref`, null for a unit that doesn't move), `buildLeft` + (float), `postTransferHoldoff` (int), `carrier` (`Ref`), `cell` (`Point16`, signed `x`, `y`). +- `UnitDef.unitname` (32 bytes, NUL-terminated). + +### Words used here + +- A player *plays* when its `active` is not 0, its `type` is 1, 2 or 3 and its `index` is not 10. +- A player is *still in* when it plays and its `unitCount` is not 0 or its `unitsCreated` is 0. +- *Active AI players*: the players 0 to 9 that are still in and whose `type` is 2. +- *Combat players*: the players 0 to 9 that are still in, whose `type` is 1, or 3 with `info.kind` 1, and whose + info flag 0x40 is clear. +- A player is *counted for rank* when it plays, is not (`unitCount` 0 with `unitsCreated` not 0), and its info + flag 0x40 is clear. +- The *host slot*: the lowest player 0 to 9 whose `type` is not 0 and whose `info.host` is set, else 10. +- *L* is `Game.localPlayer`; *local* means player *L*. +- A player's *slice* is the unit table from its `unitsBegin` to its `unitsEnd`, both included, 280 bytes apart. + A *scan* of a slice visits, in table order, each unit whose `unitDefIndex` is not 0 and stops after the first + visit that says stop. +- Two names *match* when they are equal after mapping `A` to `Z` to `a` to `z` (ASCII, nothing else). +- *A unit can be counted* when its bit 5 (0x20) is set, its `buildLeft` is +0.0 or −0.0, its + `postTransferHoldoff` is 0, and its `carrier` is null or a unit whose bit 30 (0x40000000) is set. +- *Celebrate* a condition: when its `celebrated` is 0, record `SIM_EVENT_SOUND` and set `celebrated` to 1. +- *Advance the countdown* with *v* (0 or 1): when the countdown is below 0 it becomes 4; otherwise it becomes + one less, and when that is below 0 the match *ends with v*: `endGameFlags` gets bit 2 and bit 5 (*v* 1) or + bit 6 (*v* 0), and `endGameVictory` becomes *v*. + +### Between ticks + +The region, the conditions and the fields above. Nothing else: the module keeps no statics between calls. + +## 4. Behaviour + +Within one call, only the order of import calls is observable. The block writes are compared at the end of +the call, so the order they are listed in carries no meaning, except where a later read in the same call sees +an earlier write or an effect's synchronous delivery, as said. + +### `RegionSize(info)` + +Returns 84. No import, no write. + +### `Init(info, region, size)` + +The region is zero on entry. The countdown becomes −1 (bytes 0 and 1 are 0xff); nothing else is written. The +engine passes the size `RegionSize` gave. + +### `Shutdown()` + +Returns the region `Init` was given (as its address, which the host checks is in the block); no import, no +write. Without an `Init` it returns 0. + +### `UpdatePlayerHead(player)` + +*p* is the low byte of `player`. Returns 1 when *p* is below 10 and player *p* plays, else 0. No import, no +write. + +### `UpdatePlayerBody(player, stream)` + +*p* is the low byte of `player`. The engine passes 0 to 9 only; for a *p* above 9 the reference has no +defined result, and this spec makes the slot return 0 and change nothing (ozgb/btm#25). The stream is not +used. + +1. When player *p*'s update clock is above `Game.ticks` (unsigned), the result is 0 and nothing else happens. +2. Otherwise the clock adds 30 (32 bits, wrapping). When *p* is not *L*, the part below is skipped. +3. For *p* = *L*, the first import is `mission.GetGameType`, *g*. The outcomes, with the imports after that + first one in order (*V* is a victory check and *D* a defeat check, "Checks" below, each with its imports): + +| Case | Imports after the first | Effect | +| --- | --- | --- | +| *g* = 1, *V* is 1 | *V* | advance the countdown with 1 | +| *g* = 1, *V* is 0, *D* is 1 | *V*, *D* | advance the countdown with 0 | +| *g* = 1, *V* and *D* are 0 | *V*, *D* | none | +| *g* ≠ 1, player *L* is active and its info flag 0x40 is set, *V* is 1 | *V* | advance the countdown with 1 | +| *g* ≠ 1, the flag case above, *V* is 0 | *V* | none | +| *g* ≠ 1, player *L* is not active or its info flag 0x40 is clear, *D* is 0, *V* is 1 | *D*, *V* | advance the countdown with 1 | +| the same, *D* is 0, *V* is 0 | *D*, *V* | none | +| the same, *D* is 1, the countdown is below 0 | *D* | the countdown becomes 4 | +| the same, *D* is 1, the countdown is 1 or more | *D* | the countdown becomes one less | +| the same, *D* is 1, the countdown is 0, `Game.commanderDeath` is 2 | *D*, the respawn's | the countdown becomes −1; the respawn (below) | +| the same, *D* is 1, the countdown is 0, `Game.commanderDeath` is not 2 | *D*, watch mode's | the countdown becomes −1; watch mode (below) | + +4. The result, read after the writes above: 2 when player *p* is still in, its `type` is 1 or 2, bit 2 of + `endGameFlags` is clear and the countdown is below 0; else 1. + +**Watch mode** (player *L*, defeated; *h* is the host slot): the next import is `mission.GetGameType`, *g2*. + +| Case | Imports after *g2*, in order | Effect | +| --- | --- | --- | +| *g2* = 3, *L*'s `rejectReason` is 0, `Game.players[h].info.watching` is set or an active AI player exists; no active AI player | `Emit` RECALCULATE, `network.BroadcastPlayerInfo`, `RecordSimEvent` WATCH_PROMPT | *L*'s info flag 0x40 is set; map flags 1 and 2 are cleared | +| the same, with an active AI player and a combat player | `Emit` RECALCULATE, `network.BroadcastPlayerInfo`, `RecordSimEvent` WATCH_MODE_NOTICE | as above, and `endGameVictory` becomes 0 | +| the same, with an active AI player and no combat player | `Emit` RECALCULATE, `network.BroadcastPlayerInfo` | as the first row | +| any other | none | `endGameFlags` gets bit 2, `endGameVictory` becomes 0, and bit 6 too when *L*'s `rejectReason` is 0 | + +RECALCULATE is a `LosRadarRecalculate` (`kind` 133, `reset` 1, 8 bytes); the two events carry `[L]`. The +counts of active AI and combat players are taken after *L*'s info flag 0x40 is set. + +**The respawn** (player *L*; *h* is the host slot and *H* is `Game.players[h].info`, the record past the ten +players when *h* is 10), with these imports in order: + +1. `units.FindUnitTypeId` with `Game.sideDefs[s].commander`, *s* the `side` of player *L*'s info; *t* is the + result's low 16 bits, and *d* the unit type *t* of `Game.defs`. +2. Up to 9999 tries of a position *P*: *cx* = `baseX` / 10 and *cz* = `baseY` / 10 (section 5); + `services.RandomInt(baseX − 2·cx)` gives *a*, then `services.RandomInt(baseY − 2·cz)` gives *b*; + *P* = ((*a* + *cx*) · 65536, 0, (*b* + *cz*) · 65536). Then nine `map.CanPlaceUnitFootprint(d, 0, cell, 1)`, + the cell (*X*, *Z*) for *Z* from *P*.z − *Hh* and *X* from *P*.x − *Hw*, each in three steps of *Hh* and *Hw* + (*Hh* = `height`·65536, *Hw* = `width`·65536), *Z* the outer loop, the cell's `x` and `y` the 16-bit + truncations of the unsigned values shifted right by 20 (section 5). *P* is taken when all nine answer + non-zero and then the low 16 bits of `features.FindFeatureAtPos(P, 0, 0)` are 0xffff and either `mission.GetMissionParams` + gives `lavaWorld` 0, or `lavaWorld` is not 0 and `map.GetCellMeanHeight(P)` is above `seaLevel`. A try whose + footprint count is below 9 makes neither of the last calls, and one whose feature test fails doesn't ask + for the mission's figures. After the 9999th try the last *P* is taken. +3. `units.CreateUnit(L, t, P, 1, 1, 0)` gives the unit *u*. Whatever it gives, player *L*'s `flags` gets bit 0, + its `energyStorageBonus` becomes the float of max(*H*.energy·100, 200) and its `metalStorageBonus` the float + of max(*H*.metal·100, 200). Then, for a *u* that is not null, `Emit` INCOME (`EconomyIncome`, 24 bytes: `kind` 4, `player` + *u*.`playerIndex`, `unit` the block offset of *u*, `resources` 1, `energy` float(*H*.energy)·100.0, `metal` + 0.0), `Emit` INCOME (`resources` 2, `energy` 0.0, `metal` float(*H*.metal)·100.0), `Emit` RECALCULATE + (`reset` 1), and `RecordSimEvent` FOCUS_COMMANDER `[1]`. What follows a null *u* is not defined by the + reference or any recording (K8). + +### Checks + +A victory check *V* and a defeat check *D* read the conditions object *C* = `Game.list_391ed`. When *C*.`active` +is 0 the check gives 0 with no import. Otherwise its first import is `mission.GetGameType`, *g*: + +| *g* | *V* | *D* | +| --- | --- | --- | +| 1 | each victory condition in list order, stopping at the first that isn't met; 1 when all are met | each defeat condition in list order, stopping at the first that is met; 1 when one is | +| 2 | 1 when every player *i* other than *L* with `players[L].allied[i]` 0 has `unitCount` 0 | 1 when player *L*'s `unitCount` is 0 | +| 3 | the allied victory below | as for 2 | +| other | 0 | 0 | + +An empty list, in a check of game type 1, first gets one condition: `VictoryDestroyAllUnits` for the victory +list, `DefeatAllUnitsKilled` for the defeat list, both with `satisfied` and `celebrated` 0 and the count 1 (K6). + +**The allied victory** is 0 when `Game.commanderDeath` is 2. Otherwise, for each player *i* from 0 to 9 other +than *L* that plays and whose info flag 0x40 is clear: the result is 0 when its `unitsCreated` is 0; when its +`unitCount` is not 0, the result is 0 unless its `info.f9d_1` and player *L*'s are set, `players[L].allied[i]` +and `players[L].alliedBy[i]` are not 0, and `players[i].allied[j]` is not 0 for every player *j* 0 to 9 that +is still in (*L* and *i* included). After every *i*, the result is 1. + +**A condition is met** (game type 1), by class, with its imports and writes: + +| Class | Met when | Imports and writes | +| --- | --- | --- | +| `VictoryDestroyAllUnits` | `Game.field_1df2` is 0 | when met: celebrate | +| `VictoryBuildUnitType` | `satisfied` is not 0, or becomes so | when `satisfied` is 0: if `id` is 0, `units.FindUnitTypeId(name)` and `id` becomes its 16-bit result; then a scan of player 0's slice: a unit whose `unitDefIndex` equals `id` and whose `buildLeft` is ±0.0 sets `satisfied` to 1 and celebrates; the scan stops once `satisfied` is not 0 | +| `VictoryMoveUnitToRadius` | `satisfied` is not 0 after the visits | when `pos.y` is 0x12345678: `los_radar.ClampWorldPosToTerrain` with the x and z of `pos` and `pos` itself as the output. Then `map.UnitsInRange(pos, radius, k, ids, 256)` with *k* 0, 256, 512 and so on, while each answer is 256; each id *n* of an answer, in order, visits unit *n* of `Game.units`: a unit with `playerIndex` 0, whose type matches `name` (any type when `name` is empty) and that can be counted sets `satisfied` to 1 and celebrates. The visits never stop early | +| `VictoryUnitTypePassesX` (`Z`) | `satisfied` is not 0, or becomes so | when `satisfied` is 0, a scan of player 0's slice: a unit whose type matches `name` (any when empty) and whose `cell.x` (`cell.y`) is within 2 of `x` (`z`) sets `satisfied` and celebrates; stop once set | +| `VictoryTimerRunsOut`, `DefeatDeathTimerRunsOut` | `Game.ticks` ≥ `endTick`, both unsigned | none | +| `DefeatAllUnitsKilled` | no unit of player 0's slice can be counted | `satisfied` becomes 1, then a scan of player 0's slice sets it to 0 at the first unit that can be counted, and stops there | +| `DefeatAnyUnitPassesX` (`Z`) | `satisfied` is not 0, or becomes so | when `satisfied` is 0, a scan of player 1's slice: a unit whose `cell.x` (`cell.y`) is within 2 of `x` (`z`) sets `satisfied` to 1 (no sound); stop once set | +| every other class | `satisfied` is not 0 | none | + +A unit's type matches when `name` matches its `def.unitname`. *Within 2*: |*c* − *x*| ≤ 2, with the cell's +coordinate sign-extended and the difference a 32-bit signed number. + +### Conditions + +The events `PLAYERS_UNIT_DIED` and `PLAYERS_GIVE_UNIT` tell every condition of the victory list, in order, +then every condition of the defeat list, of the unit *u*. Only these classes act; *d* is *u*.`def`, and the +commander name is `Game.sideDefs[s].commander` with *s* the `side` of *u*.`player`'s info: + +| Notice | Class | When | Effect | +| --- | --- | --- | --- | +| died | `VictoryKillEnemyCommander` | *u*.`playerIndex` is 1 and *d*.`unitname` matches the commander name | `satisfied` 1; celebrate | +| died | `VictoryKillAllMobileUnits` | *u*.`playerIndex` is 1 and *u*.`motion` is not null | `numUnits` becomes 0, then a scan of player 1's slice adds 1 for each unit with a `motion`, stopping once `numUnits` is above 1; when `numUnits` is at most 1: `satisfied` 1, celebrate | +| died | `VictoryKillAllOfType` | `satisfied` is 0, *u*.`playerIndex` is 1 and `name` matches *d*.`unitname` | `units.FindUnitTypeId(name)`, `id` becomes its 16-bit result, `count` becomes 0, then a scan of player 1's slice adds 1 for each unit whose `unitDefIndex` equals `id`, stopping once `count` is above 1; when `count` is at most 1: `satisfied` 1, celebrate | +| died | `VictoryKillUnitType` | `numLeftToKill` is above 0, *u*.`playerIndex` is 1 and `name` matches *d*.`unitname` | `numLeftToKill` becomes one less; when that is at most 0: `satisfied` 1, celebrate | +| died | `DefeatCommanderKilled` | *u*.`playerIndex` is 0 and *d*.`unitname` matches the commander name | `satisfied` 1 | +| died | `DefeatUnitTypeKilled` | `name` matches *d*.`unitname`, any player (Q3) | `numLeftToKill` becomes one less; when that is at most 0: `satisfied` 1 | +| died | `DefeatAllUnitsKilledOfType` | `name` matches *d*.`unitname`, any player | `units.FindUnitTypeId(name)`, `id` becomes its result, `count` 0, then a scan of player 0's slice and then one of player 1's, each adding 1 per unit whose `unitDefIndex` equals `id` and stopping once `count` is above 1 (so the second scan visits at most one unit when the first ended above 1, Q4); when `count` is at most 1: `satisfied` 1 | +| captured | `VictoryCaptureUnitType` | *u*.`playerIndex` is 1 and `name` matches *d*.`unitname` | `satisfied` 1; celebrate | + +No class acts on `PLAYERS_UNIT_CREATED`. + +### `Apply(event, size)` + +The result is the outcome. A `size` below 8, or below the size of the event's kind (section 2), gives 0 with +no change and no import. *u* is the unit at block offset `event.unit` (null for 0), and *C* the conditions +object. By kind: + +| Kind | Refused (outcome 0, no change) when | Effect, imports in order | Outcome | +| --- | --- | --- | --- | +| `PLAYERS_GIVE_UNIT` | *u* is null, `player` is above 9 (unsigned), or *C* is null | the hand-over below | 0 or 1 | +| `PLAYERS_KILL_UNITS` | `player` is above 10 (unsigned) | the kill below | 1 | +| `PLAYERS_UNIT_CREATED` | *u* or *C* is null | none | 1 | +| `PLAYERS_UNIT_DIED` | *u* or *C* is null | the died notice of "Conditions" | 1 | +| `PLAYERS_TRANSFER` | `from` or `to` is above 10 (unsigned), or `resource` is not 0 or 1 | the transfer below | 0 or 1 | +| `PLAYERS_SET_STORE` | `player` is above 9, or `resource` is not 0 or 1 | the store *S* (`energy` for 0, `metal` for 1) of the player becomes `amount` when `add` is 0, else *S* + `amount` (section 5) | 1 | +| `PLAYERS_SET_TYPE` | `player` is above 9 | the player's `type` becomes the low byte of `type`; when the 32-bit `type` is not 3, its `info.kind` becomes that byte too | 1 | +| `PLAYERS_END_GAME` | `victory` is not 0 or 1 | `endGameVictory` becomes `victory`; `endGameFlags` gets bit 2 and bit 5 (1) or bit 6 (0) | 1 | +| `PLAYERS_DEACTIVATE_CONDITIONS` | *C* is null (K7) | *C*.`active` becomes 0 | 1 | +| `PLAYERS_SET_CHEATS` | `clear` or `set` has a bit outside 0x788 | `uiOptionFlags` becomes (`uiOptionFlags` with the bits of `clear` cleared) with the bits of `set` set | 1 | +| `PLAYERS_LEAVE_GAME` | never | `endGameFlags` gets bit 2 | 1 | +| `PLAYERS_SET_CONTROL` | `player` is above 9, or the player doesn't play | `localPlayer` and `playerIndex` become `player` | 1 | +| `PLAYERS_SET_VIEW` | as SET_CONTROL | `playerIndex` becomes `player` | 1 | +| `PLAYERS_COMPACT_RANKS` | `g_quirks.rankCompactionPerTick` is not 0 | the rank pass below | 1 | +| any other kind | always | none | 0 | + +A field the table doesn't use is not read: the `unit` of a kind that names none is ignored. + +**The hand-over** of *u* to player *r* = `player`, with *o* = *u*.`player`: + +| Case, by the first row that matches | Imports | Outcome | +| --- | --- | --- | +| *o* is player *r* (the same record) | none | 0 | +| *u* is not alive (unit flag 0x10000000 clear) or is dying (unit flag 0x4000 set) | none | 0 | +| *o* is active with `type` 1 or 2, and *r* is not active | the captured notice | 0 | +| *o* is active with `type` 1 or 2, and *r* has `type` 3 | the captured notice, `Emit` SEND_UNIT | 1 | +| *r* is not active, or its `type` is not 1 or 2 | the captured notice | 0 | +| any other | the captured notice, `Emit` CAPTURE_UNIT | 1 | + +The captured notice (section "Conditions") comes before the `Emit`, and its `RecordSimEvent`, when it has one, +is the first import. SEND_UNIT is a `PlayersSendUnit` (12 bytes: 209, *u*'s offset, *r*); CAPTURE_UNIT a +`PlayersCaptureUnit` (48 bytes: 210, *u*'s offset, *r*, then the event's `record`, all nine words copied as +they are). + +**The kill** of player *k*'s units (*k* = `player`, 10 being the record past the ten players): nothing happens +when the player's `unitCount` is 0 or its `unitsBegin` is null. Otherwise `unitsEnd` is read once, and each unit +from `unitsBegin` to it, in table order, that is alive and not dying when its turn comes gives one `Emit` +KILL_UNIT (`PlayersKillUnit`, 12 bytes: 208, the unit's offset, `selfDestruct`): `selfDestruct` is 0 when the +unit's `player` is active with `type` 1 or 2, else 1. Each KILL_UNIT is delivered before `Emit` returns, so a +later unit's flags are read after the kills before it took effect. + +**The transfer** (`from` *f*, `to` *t*, `amount` *a*, `announce` *n*, nonzero meaning announced): + +| Case | Imports | Outcome | +| --- | --- | --- | +| *f* or *t* is 10 | none | 0 | +| *n* is not 0, and *a*, lowered to the giver's store (`energy` for resource 0, `metal` for 1) when it is above it (section 5), is 0.0 | none | 0 | +| *n* is not 0, and the lowered *a* is not 0.0 | `economy.Spend`, `Emit` INCOME, the network send | 1 | +| *n* is 0, *a* = 0.0 | none | 0 | +| *n* is 0, *a* ≠ 0.0 | `Emit` INCOME | 1 | + +The spend is an `EconomySpend` for player *f*, unit 0, with `resources` 1 and `energy` *a* (resource 0), or +`resources` 2 and `metal` *a* (resource 1), the other amount 0.0; its result is ignored. INCOME is an +`EconomyIncome` (24 bytes: 4, player *t*, unit 0, the same `resources` and amounts). The network send is +`network.SendShareMetal(f, t, a)` for resource 0 and `network.SendShareEnergy(f, t, a)` for resource 1 (Q1). +The module writes no store: the spend and the income are economy's. + +**The rank pass**: for each place *i* from 0 while *i* < `numPlayers`: when no player 0 to 9 counted for rank +has `rank` *i*, every player counted for rank whose `rank` is above *i* gets `rank` one less. The pass goes on to +*i* + 1 either way (Q2). No import. + +### `UpdatePlayerTail(player)` + +*p* is the low byte of `player`. When *p* is `Game.playerIndex`: `mission.GetGameType`; when it gives 3, +`g_economyPacketTick` adds 1 (32 bits, wrapping), and when the new value's low two bits are 0, +`network.BroadcastPlayerEconomy` with the address of player *p*'s record. Otherwise nothing. + +### `UpdatePlayersFinish()` + +When `g_quirks.rankCompactionPerTick` is not 0, the rank pass runs first. Then `mission.GetGameType`; when it +gives 3, `Game.commanderDeath` is not 2 and there is no combat player, advance the countdown with 0. + +### `DeactivateConditions(conditions)` + +The `active` of the given object becomes 0; a null object changes nothing. No import. + +### `UpdatePlayers()`, `UpdatePlayersOnStream(stream)` + +The players pass of `docs/schedule.md` (the passes `players` and `players.los`), with *stream* (the main +stream for `UpdatePlayers`) given to each body: for each player 0 to 9, the head, and when it gives 1 the other +subsystems' steps of the turn, the body, economy's settlement when the body gives 2, the viewed player's radar +steps, and the tail when the body gives 1 or 2; then the finish. The steps of this module are the slots above. +The other subsystems' steps need imports the entry doesn't list (K5); no recording holds either slot. + +## 5. Exactness + +- **Random draws:** none in any recorded call. Only the respawn draws, from `services.RandomInt` (the + generator of `rng.seed`, not a game logic stream), two draws per try, x first; the ranges are + `baseX − 2·(baseX / 10)` and `baseY − 2·(baseY / 10)`, 32-bit signed, the division truncating toward 0. + `RandomInt` of a range below 2 gives 0. +- **The respawn's arithmetic:** (*a* + *cx*)·65536 and (*b* + *cz*)·65536 are 32-bit, wrapping. The footprint + cells start at *P*.z − *Hh* and *P*.x − *Hw*, computed as unsigned 32-bit differences, add *Hh* or *Hw* per + step (wrapping), and are shifted right by 20 as unsigned numbers; the cell's `x` and `y` keep the low 16 bits. + max(·, 200) is a signed 32-bit comparison of *H*.energy·100 (a 16-bit value times 100, an int). The storage + bonuses are the exact float of that int. The incomes are float(*H*.energy) × 100.0 in 32-bit float, rounded + to nearest even. +- **The countdown** is signed 16-bit: 0 less one is −1, stored as 0xffff. +- **Clocks and counters:** the update clock adds 30, `g_economyPacketTick` adds 1, both 32-bit wrapping. The + clock's test is unsigned: clock > `Game.ticks`. +- **Transfers:** the clamp is the 32-bit float comparison *a* > store (false for a NaN on either side, so a NaN + amount is kept); the zero test is *a* = 0.0 in float, true for +0.0 and −0.0 and false for a NaN. The amount + passed on is the clamped float, bit for bit. +- **SET_STORE:** *S* + `amount` is one 32-bit float addition, rounded to nearest even. +- **Integer comparisons:** `player`, `from`, `to` and the cheat bits are tested as unsigned 32-bit numbers. + `unitCount` and `numPlayers` are unsigned 16 bits; `rank` is an unsigned byte compared with the place *i*. + `numLeftToKill`, `numUnits` and `count` are signed 32-bit; `numLeftToKill` of `DefeatUnitTypeKilled` can go + below 0. +- **Ids:** `units.FindUnitTypeId` returns an unsigned 16-bit value (ABI 7: zero-extended); `id` stores its low 16 + bits, and a unit's `unitDefIndex` is compared with `id` as 16-bit values. +- **`buildLeft`** is compared with 0.0 as a float: −0.0 counts as 0, a NaN does not. + +## 6. Quirks + +- **Q1.** `network.SendShareMetal` announces a transfer of energy and `network.SendShareEnergy` one of metal, + as `interfaces/network.h` names its resource kinds. +- **Q2.** The rank pass looks at each place once, so a run of gaps or a rank past `numPlayers` takes more than + one pass to close; one `PLAYERS_COMPACT_RANKS` is one pass. +- **Q3.** `DefeatUnitTypeKilled` counts the deaths of matching units of any player, and its `numLeftToKill` + keeps going down past 0. +- **Q4.** `DefeatAllUnitsKilledOfType` scans player 1's slice after player 0's even when the count is already + above 1, so that scan visits one unit and may add one more to `count`. +- **Q5.** The respawn's footprint test offsets the position by the whole map's `height` and `width` in + position units, not by a cell: of the nine cells most lie off the map. +- **Q6.** `VictoryDestroyAllUnits` is met while player 1 has no units, whatever the other players hold, and it + never sets its `satisfied`. + +## 7. Examples + +Each is taken from the kit's recordings and recomputed from this spec's definitions. + +1. `tests/replay/players/console-economy.txt`, call at tick 10 of `Apply`: `PLAYERS_SET_STORE`, player 0, + resource 0, `add` 1, `amount` f32:0x447a0000 (1000.0), size 24; `Player#0.energy` is f32:0x447a0000. + *S* + `amount` = 2000.0: `w Player#0.energy f32:0x44fa0000`, result 1, no import. +2. The same file, tick 40, `PLAYERS_TRANSFER` from 0 to 1, resource 1 (metal), `amount` f32:0x42c80000 + (100.0), announced. `Player#0.metal` is f32:0x424c0000 (51.0), so *a* becomes 51.0: `economy.Spend` (the line + `i services.ScheduleEconomySpend = 1`), `Emit` INCOME of 24 bytes (`i services.SchedPublish 4 24`), then + `i network.SendShareEnergy 0 1 f32:0x424c0000`; result 1. At tick 50, resource 0 with `Player#0.energy` + 1000.0 keeps 100.0 and sends `network.SendShareMetal 0 1 f32:0x42c80000`. +3. `tests/replay/players/mission-defeat-all-units.txt`, tick 360, `UpdatePlayerBody(0)`: game type 1, clock 360 + (not above the tick), countdown 0, `active` 1. The clock becomes 390 (`4:86`, 0x186). *V*: one + `GetGameType`, `VictoryDestroyAllUnits` not met (`Game.field_1df2` is not 0). *D*: one `GetGameType`; + `DefeatAllUnitsKilled` finds no unit of player 0 that can be counted, so it is met. The countdown goes from 0 + to −1 (`0:ffff`) and the match ends with 0: `endGameFlags` 0 → 68 (bits 2 and 6). Three `GetGameType` in all; + result 1, since bit 2 is now set. +4. `tests/replay/players/allied-victory.txt`, tick 330, `UpdatePlayerBody(0)`, game type 3, countdown 1: *D* is + 0 (player 0's `unitCount` is not 0), *V* (the allied victory) is 1, so the countdown becomes 0 (`0:00`); clock + 330 → 360 (`4:68`, 0x168); result 1. `UpdatePlayerTail(0)` then: `GetGameType` 3, `g_economyPacketTick` 11 → + 12, whose low two bits are 0, so `network.BroadcastPlayerEconomy Player#0`. At tick 360 the countdown goes + from 0 to −1 and the match ends with 1: `endGameFlags` 36 (bits 2 and 5), `endGameVictory` 1. +5. `tests/replay/players/mission-capture.txt`, tick 499, `Apply` of `PLAYERS_GIVE_UNIT`, `Unit#282` to player + 0, size 48. *o* is `Player#1` (active, `type` 2) and *r* `Player#0` (active, `type` 1); the unit is alive + (`flags` 0x30280321, bit 28 set, bit 14 clear). The captured notice: `VictoryCaptureUnitType#1` (`name` + "CORGEO") matches `UnitDef#123` "CORGEO" and `playerIndex` 1, so `satisfied` and `celebrated` become 1 with + `i services.RecordSimEvent 2 0 [0,0] 2`; then `Emit` CAPTURE_UNIT, 48 bytes (`i services.SchedPublish 4 + 48`); result 1. The `UNIT_DIED` of `Unit#282` in the same tick runs `DefeatAllUnitsKilledOfType#1`: + `units.FindUnitTypeId "CORGEO" = 123`, `id` 123, and the scans give `count` 2. +6. `tests/replay/players/skirmish2.txt`, tick 29 and 30, `UpdatePlayerHead`: players 0 and 1 (`active` 1, + `type` 2, `index` 0 and 1) give 1, players 2 to 9 (`active` 0) give 0. At tick 30 player 0's body (clock 30) + gives 2: it is still in, `type` 2, `endGameFlags` bit 2 clear, countdown −1. +7. `tests/replay/players/mission-defeat-passes-x.txt`, tick 0, `UpdatePlayerBody(0)`: the + `VictoryMoveUnitToRadius#1` centre (8000, 4700) has the marker y, so + `los_radar.ClampWorldPosToTerrain 8000 4700` writes (524288000, 5505024, 310771712) to `pos`; one + `map.UnitsInRange` with skip 0 and capacity 256 answers 14, under 256, so it is the only one; none of the 14 + units meets the condition. + +Not covered by any recording: `UpdatePlayers`, `UpdatePlayersOnStream`, `DeactivateConditions` and `Shutdown`; +the respawn and watch mode; `PLAYERS_SET_CHEATS`, `PLAYERS_LEAVE_GAME`, `PLAYERS_COMPACT_RANKS` and every +refusal of `Apply`; SEND_UNIT and the refusals of the hand-over; an unannounced transfer and the zero amount; +the classes `VictoryKillEnemyCommander`, `VictoryKillAllMobileUnits`, `VictoryBuildUnitType`, +`VictoryUnitTypePassesX`, `VictoryUnitTypePassesZ`, `VictoryTimerRunsOut`, `DefeatUnitTypeKilled`, +`DefeatDeathTimerRunsOut` and `DefeatAnyUnitPassesZ`, and a radius condition met; an empty condition list; a +second `map.UnitsInRange` call; the rank pass of `UpdatePlayersFinish`. + +## 8. Kit version + +`interfaces-v66` and `reference-traces-v55` (commit 74bdf5ef6), with players at `interfaces/players.h` version +5.4. From e36ec211877454b6c6e2b3e291264a02ca1e0532 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:20:51 +0000 Subject: [PATCH 02/13] Update: Move the players spec to interfaces-v68 Assisted-by: Claude Code:claude-opus-5-5 --- specs/players.md | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/specs/players.md b/specs/players.md index 0612a03..8123d80 100644 --- a/specs/players.md +++ b/specs/players.md @@ -79,6 +79,7 @@ The kit's entry for players is the module's entry, and this spec follows it exac | `units.FindUnitTypeId` | `[linear] -> int` | a unit type by name (conditions, the respawn) | | `map.UnitsInRange` | `[linear, int, int, linear, int] -> int` | the units inside a radius condition's circle | | `map.GetCellMeanHeight` | `[linear] -> int` | the respawn's lava test | +| `map.CanPlaceUnitFootprint` | `[block, int, linear, int] -> int` | the respawn's footprint test (a `Point16` cell of the module's own) | | `features.FindFeatureAtPos` | `[linear, linear, linear] -> int` | the respawn's test for a feature | | `network.BroadcastPlayerInfo` | `[] -> void` | a defeated local player put in watch mode | | `network.SendShareMetal` | `[int, int, f32] -> void` | an announced transfer of energy (section 4, Q1) | @@ -86,6 +87,7 @@ The kit's entry for players is the module's entry, and this spec follows it exac | `network.BroadcastPlayerEconomy` | `[block] -> void` | the viewed player's economy, in a multiplayer game | | `los_radar.ClampWorldPosToTerrain` | `[int, int, linear] -> void` | a radius condition's centre, once | | `economy.Spend` | `[linear] -> int` | the giver's spend of an announced transfer (an `EconomySpend` of the module's own) | +| `services.RandomInt` | `[int] -> int` | the respawn's position | | `services.RecordSimEvent` | `[int, int, linear, int] -> void` | the sim events of section 2, "Events" | | `services.Emit` | `[linear, int] -> void` | every effect and event the module publishes | @@ -95,11 +97,10 @@ The kit's entry for players is the module's entry, and this spec follows it exac 208, 209 and 210; 0 and 128 are published only by engine slots. Every route of these kinds is synchronous except economy's two (`data/routes.csv`), so an effect to units or los_radar has been applied when `Emit` returns, and its writes are in the block for what the module reads after it. -- `blocked`: the entry's reason says that the footprint service (`services.ScheduleMapCanPlaceUnitFootprint`), - the lookup of the host slot and the four tables of saved-game account names have no import. By ABI 4.2 an entry with `blocked` has no `.wasm` and no budgets (`fuel_budget`, `size_budget`), and - the host runs the native default for every slot. A module built from this spec meters itself by rule - version 1 (ABI section 11) and exports `__fuel_set` and `__fuel_get`; its budgets come with a later entry. - Section 2, "Kit gaps", says which parts of this spec meet which part of that reason. +- `blocked`: true. By ABI 4.2 an entry with `blocked` has no `.wasm` and no budgets (`fuel_budget`, + `size_budget`), and the host runs the native default for every slot. A module built from this spec meters + itself by rule version 1 (ABI section 11) and exports `__fuel_set` and `__fuel_get`; its budgets come with a + later entry. - Hooks: every slot of `interfaces/players.h` says "Hooks: none"; the event kind `PLAYERS_GIVE_UNIT` names `UnitTransfer`. The kit defines no hook in the module ABI and the import list has none, so the module raises none; no recording shows one. @@ -107,7 +108,8 @@ The kit's entry for players is the module's entry, and this spec follows it exac ### Routes and the recordings A recording shows the module's `Emit` as `i services.SchedPublish 4 ` (the recorded call of ABI 9.3, -"Routes in the recordings"; 4 is players' outbox) and its `economy.Spend` as `i services.ScheduleEconomySpend`. +"Routes in the recordings"; 4 is players' outbox), its `economy.Spend` as `i services.ScheduleEconomySpend`, and its `map.CanPlaceUnitFootprint` as +`i services.ScheduleMapCanPlaceUnitFootprint`. An `o rng.seed` or `w Game.playerIndex` line after a publish is what the synchronous delivery of the effect changed, not a write of the module. A `c` line under `map.UnitsInRange` doesn't occur: the module takes ids, not a callback. @@ -151,7 +153,7 @@ those of `docs/sim-events.md`, Terms. ### Kit gaps -What this spec needs and the kit doesn't give; the maintainer routes them: +What this spec needs and the kit doesn't give; the maintainer routes them (K2 and K3 were closed by the kit at `interfaces-v68`, so the numbers skip them): - **K1, the class of a condition.** A condition (section 3) is told apart by its first word, the vtable pointer of its class, which the engine's load-class slots write and the kit gives no value for (the @@ -159,13 +161,7 @@ What this spec needs and the kit doesn't give; the maintainer routes them: `VictoryKillAllOfType#1`, but never the word). Every slot that runs a condition needs the class. Until the kit gives the 18 words (or a class number in the block), this spec states each class's behaviour, and a module can't pick it from the block alone. -- **K2, the respawn's imports.** The respawn (section 4) asks `map.CanPlaceUnitFootprint` (the recorded - `services.ScheduleMapCanPlaceUnitFootprint`) and draws from `services.RandomInt`; the entry lists neither. - This is the first part of the entry's `blocked` reason. No recording reaches the respawn. -- **K3, the host slot.** The entry's `blocked` reason names it as a call with no import. Section 4 defines - the host slot from block fields, so the module needs no import for it; only the respawn and watch mode read - it, and no recording reaches either. -- **K4, the saved game's account names** (the tables of the `blocked` reason) serve only the engine +- **K4, the saved game's account names** serve only the engine slots `LoadConditions` and `SaveConditions`; no exported slot needs them. - **K5, the whole pass.** `UpdatePlayers` and `UpdatePlayersOnStream` are exported, but the players pass calls other subsystems' slots (pathfinding, movement, ai, los_radar, units, economy; `docs/schedule.md`, the @@ -609,5 +605,5 @@ second `map.UnitsInRange` call; the rank pass of `UpdatePlayersFinish`. ## 8. Kit version -`interfaces-v66` and `reference-traces-v55` (commit 74bdf5ef6), with players at `interfaces/players.h` version +`interfaces-v68` and `reference-traces-v55` (commit 906e69ae4), with players at `interfaces/players.h` version 5.4. From 347996a6be58866c8c6ca414aedb18441607fee7 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:39:05 +0000 Subject: [PATCH 03/13] Fix: Answer the players phase 1 review Assisted-by: Claude Code:claude-opus-5-5 --- specs/players.md | 62 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 41 insertions(+), 21 deletions(-) diff --git a/specs/players.md b/specs/players.md index 8123d80..ccfa71d 100644 --- a/specs/players.md +++ b/specs/players.md @@ -110,9 +110,17 @@ The kit's entry for players is the module's entry, and this spec follows it exac A recording shows the module's `Emit` as `i services.SchedPublish 4 ` (the recorded call of ABI 9.3, "Routes in the recordings"; 4 is players' outbox), its `economy.Spend` as `i services.ScheduleEconomySpend`, and its `map.CanPlaceUnitFootprint` as `i services.ScheduleMapCanPlaceUnitFootprint`. -An `o rng.seed` or `w Game.playerIndex` line after a publish is what the synchronous delivery of the effect -changed, not a write of the module. A `c` line under `map.UnitsInRange` doesn't occur: the module takes ids, -not a callback. +An `o rng.seed` line after a publish is what the synchronous delivery of the effect changed in the game, +which the replayer sets from the line (`docs/replay-format.md`, "A random draw inside an import"). The replayer +makes no delivery, so no recording shows an effect's own writes, and a publish is compared by its outbox and +size alone (`docs/replay-format.md`, "Against the WASM module"); the fields of every effect, event and spend this +spec gives are judged by the scenario traces, through what their subscribers do. The `w Game.playerIndex` +and `w Game.localPlayer` lines of the first `Apply` of a file are fields of the slot's write set that have no +known value yet (`docs/replay-format.md`, "Lines"), not writes of the module; their values are the ones +already in the block. A field the recorded write set leaves out (the `active` of `PLAYERS_DEACTIVATE_CONDITIONS`) +has no `w` line, and a later call's `r` line shows its value. A `c` line under `map.UnitsInRange` doesn't occur: +the module takes ids, not a callback. A unit id *n* names slot *n* of the unit table (`Game.units` plus 280·*n*), +which a recording writes `Unit#n`. ### Arguments outside the block @@ -138,14 +146,14 @@ not a callback. The module's slots record these kinds through `services.RecordSimEvent`, with flags 0; the kit's `docs/sim-events.md` gives their arguments and phases: -- `SIM_EVENT_SOUND`, arguments `[0, 0]` (sound name 0, the victory condition sound, and play flag 0): when a +- `SIM_EVENT_SOUND` (kind 2), arguments `[0, 0]` (sound name 0, the victory condition sound, and play flag 0): when a victory condition is satisfied for the first time, in the cases of section 4, "Conditions" (it is recorded only while the condition's `celebrated` is 0, which it then sets to 1). -- `SIM_EVENT_FOCUS_COMMANDER`, arguments `[1]`: when the commander of the local player is respawned +- `SIM_EVENT_FOCUS_COMMANDER` (kind 19), arguments `[1]`: when the commander of the local player is respawned (section 4, "The respawn"). -- `SIM_EVENT_WATCH_PROMPT`, arguments `[p]`: when the defeated local player *p* of a multiplayer game is put +- `SIM_EVENT_WATCH_PROMPT` (kind 25), arguments `[p]`: when the defeated local player *p* of a multiplayer game is put in watch mode and no active AI player is left (section 4, "Watch mode"). -- `SIM_EVENT_WATCH_MODE_NOTICE`, arguments `[p]`: on the same path, when an active AI player is left and at +- `SIM_EVENT_WATCH_MODE_NOTICE` (kind 26), arguments `[p]`: on the same path, when an active AI player is left and at least one combat player. The terms "unit flag 0x10000000", "unit flag 0x4000", "map flag 1", "map flag 2" and "info flag 0x40" are @@ -228,7 +236,10 @@ players, `Game.players_1b63`): `rank` (byte), `energy`, `metal` (floats; written | `DefeatAnyUnitPassesX` | defeat | `x` (16) | | `DefeatAnyUnitPassesZ` | defeat | `z` (16) | -Offsets are bytes from the condition's start; `id` and `count` are unaligned. A `name` is NUL-terminated +Offsets are bytes from the condition's start; `id` and `count` are unaligned. In a class whose first field +after `celebrated` is at 16, and in `DefeatAllUnitsKilled` (16 bytes, no such field), bytes 12 to 15 hold a +second class word, which the module never reads or writes; `layout.json` leaves those bytes unnamed, and +the word's value is unknown as K1's is. A `name` is NUL-terminated (empty for "any type" in the radius and passes classes). The module never writes a class word, a `name`, an `x`, a `z`, a `radius` or an `endTick`. A radius condition's `pos` holds the centre's x and z as given, and y the marker 0x12345678 until the centre is put on the ground (section 4). @@ -335,22 +346,27 @@ used. | Case | Imports after *g2*, in order | Effect | | --- | --- | --- | -| *g2* = 3, *L*'s `rejectReason` is 0, `Game.players[h].info.watching` is set or an active AI player exists; no active AI player | `Emit` RECALCULATE, `network.BroadcastPlayerInfo`, `RecordSimEvent` WATCH_PROMPT | *L*'s info flag 0x40 is set; map flags 1 and 2 are cleared | -| the same, with an active AI player and a combat player | `Emit` RECALCULATE, `network.BroadcastPlayerInfo`, `RecordSimEvent` WATCH_MODE_NOTICE | as above, and `endGameVictory` becomes 0 | -| the same, with an active AI player and no combat player | `Emit` RECALCULATE, `network.BroadcastPlayerInfo` | as the first row | -| any other | none | `endGameFlags` gets bit 2, `endGameVictory` becomes 0, and bit 6 too when *L*'s `rejectReason` is 0 | +| *W* holds, and there is no active AI player | `Emit` RECALCULATE, `network.BroadcastPlayerInfo`, `RecordSimEvent` WATCH_PROMPT | *L*'s info flag 0x40 is set; map flags 1 and 2 are cleared | +| *W* holds, with an active AI player and a combat player | `Emit` RECALCULATE, `network.BroadcastPlayerInfo`, `RecordSimEvent` WATCH_MODE_NOTICE | as above, and `endGameVictory` becomes 0 | +| *W* holds, with an active AI player and no combat player | `Emit` RECALCULATE, `network.BroadcastPlayerInfo` | as the first row | +| *W* doesn't hold | none | `endGameFlags` gets bit 2, `endGameVictory` becomes 0, and bit 6 too when *L*'s `rejectReason` is 0 | + +*W* holds when *g2* is 3, *L*'s `rejectReason` is 0, and `Game.players[h].info.watching` is set or there is at +least one active AI player. RECALCULATE is a `LosRadarRecalculate` (`kind` 133, `reset` 1, 8 bytes); the two events carry `[L]`. The -counts of active AI and combat players are taken after *L*'s info flag 0x40 is set. +count of combat players is taken after *L*'s info flag 0x40 is set (the count of active AI players doesn't +read the flag). **The respawn** (player *L*; *h* is the host slot and *H* is `Game.players[h].info`, the record past the ten players when *h* is 10), with these imports in order: 1. `units.FindUnitTypeId` with `Game.sideDefs[s].commander`, *s* the `side` of player *L*'s info; *t* is the - result's low 16 bits, and *d* the unit type *t* of `Game.defs`. + result's low 16 bits, and *d* the unit type *t* of `Game.defs` (`Game.defs` plus 585·*t*, for any *t*, 0 + included). 2. Up to 9999 tries of a position *P*: *cx* = `baseX` / 10 and *cz* = `baseY` / 10 (section 5); `services.RandomInt(baseX − 2·cx)` gives *a*, then `services.RandomInt(baseY − 2·cz)` gives *b*; - *P* = ((*a* + *cx*) · 65536, 0, (*b* + *cz*) · 65536). Then nine `map.CanPlaceUnitFootprint(d, 0, cell, 1)`, + *P* = ((*a* + *cx*) · 65536, 0, (*b* + *cz*) · 65536). Then nine `map.CanPlaceUnitFootprint(d, 0, cell, 1)`, all nine on every try, the cell (*X*, *Z*) for *Z* from *P*.z − *Hh* and *X* from *P*.x − *Hw*, each in three steps of *Hh* and *Hw* (*Hh* = `height`·65536, *Hw* = `width`·65536), *Z* the outer loop, the cell's `x` and `y` the 16-bit truncations of the unsigned values shifted right by 20 (section 5). *P* is taken when all nine answer @@ -374,12 +390,13 @@ is 0 the check gives 0 with no import. Otherwise its first import is `mission.Ge | *g* | *V* | *D* | | --- | --- | --- | | 1 | each victory condition in list order, stopping at the first that isn't met; 1 when all are met | each defeat condition in list order, stopping at the first that is met; 1 when one is | -| 2 | 1 when every player *i* other than *L* with `players[L].allied[i]` 0 has `unitCount` 0 | 1 when player *L*'s `unitCount` is 0 | +| 2 | 1 when every player *i* from 0 to 9 other than *L* with `players[L].allied[i]` 0 has `unitCount` 0, whether or not it plays | 1 when player *L*'s `unitCount` is 0 | | 3 | the allied victory below | as for 2 | | other | 0 | 0 | An empty list, in a check of game type 1, first gets one condition: `VictoryDestroyAllUnits` for the victory -list, `DefeatAllUnitsKilled` for the defeat list, both with `satisfied` and `celebrated` 0 and the count 1 (K6). +list, `DefeatAllUnitsKilled` for the defeat list, both with `satisfied` and `celebrated` 0, as entry 0 of the list, and the list's count (`victoryCount` or +`defeatCount`) becomes 1 (K6). **The allied victory** is 0 when `Game.commanderDeath` is 2. Otherwise, for each player *i* from 0 to 9 other than *L* that plays and whose info flag 0x40 is clear: the result is 0 when its `unitsCreated` is 0; when its @@ -393,10 +410,10 @@ is still in (*L* and *i* included). After every *i*, the result is 1. | --- | --- | --- | | `VictoryDestroyAllUnits` | `Game.field_1df2` is 0 | when met: celebrate | | `VictoryBuildUnitType` | `satisfied` is not 0, or becomes so | when `satisfied` is 0: if `id` is 0, `units.FindUnitTypeId(name)` and `id` becomes its 16-bit result; then a scan of player 0's slice: a unit whose `unitDefIndex` equals `id` and whose `buildLeft` is ±0.0 sets `satisfied` to 1 and celebrates; the scan stops once `satisfied` is not 0 | -| `VictoryMoveUnitToRadius` | `satisfied` is not 0 after the visits | when `pos.y` is 0x12345678: `los_radar.ClampWorldPosToTerrain` with the x and z of `pos` and `pos` itself as the output. Then `map.UnitsInRange(pos, radius, k, ids, 256)` with *k* 0, 256, 512 and so on, while each answer is 256; each id *n* of an answer, in order, visits unit *n* of `Game.units`: a unit with `playerIndex` 0, whose type matches `name` (any type when `name` is empty) and that can be counted sets `satisfied` to 1 and celebrates. The visits never stop early | +| `VictoryMoveUnitToRadius` | `satisfied` is not 0 after the visits | when `pos.y` is 0x12345678: `los_radar.ClampWorldPosToTerrain` with the x and z of `pos` and `pos` itself as the output. Then `map.UnitsInRange(pos, radius, k, ids, 256)` with *k* 0, 256, 512 and so on, while each answer is 256; each id *n* of an answer, in order, visits unit slot *n* of `Game.units`: a unit with `playerIndex` 0, whose type matches `name` (any type when `name` is empty) and that can be counted sets `satisfied` to 1 and celebrates. Every id of every answer is visited | | `VictoryUnitTypePassesX` (`Z`) | `satisfied` is not 0, or becomes so | when `satisfied` is 0, a scan of player 0's slice: a unit whose type matches `name` (any when empty) and whose `cell.x` (`cell.y`) is within 2 of `x` (`z`) sets `satisfied` and celebrates; stop once set | | `VictoryTimerRunsOut`, `DefeatDeathTimerRunsOut` | `Game.ticks` ≥ `endTick`, both unsigned | none | -| `DefeatAllUnitsKilled` | no unit of player 0's slice can be counted | `satisfied` becomes 1, then a scan of player 0's slice sets it to 0 at the first unit that can be counted, and stops there | +| `DefeatAllUnitsKilled` | no unit of player 0's slice can be counted | `satisfied` becomes 1 when it is met, 0 when it isn't | | `DefeatAnyUnitPassesX` (`Z`) | `satisfied` is not 0, or becomes so | when `satisfied` is 0, a scan of player 1's slice: a unit whose `cell.x` (`cell.y`) is within 2 of `x` (`z`) sets `satisfied` to 1 (no sound); stop once set | | every other class | `satisfied` is not 0 | none | @@ -468,7 +485,7 @@ they are). when the player's `unitCount` is 0 or its `unitsBegin` is null. Otherwise `unitsEnd` is read once, and each unit from `unitsBegin` to it, in table order, that is alive and not dying when its turn comes gives one `Emit` KILL_UNIT (`PlayersKillUnit`, 12 bytes: 208, the unit's offset, `selfDestruct`): `selfDestruct` is 0 when the -unit's `player` is active with `type` 1 or 2, else 1. Each KILL_UNIT is delivered before `Emit` returns, so a +unit's `player` is active with `type` 1 or 2, else 1 (`type` 3 included). Each KILL_UNIT is delivered before `Emit` returns, so a later unit's flags are read after the kills before it took effect. **The transfer** (`from` *f*, `to` *t*, `amount` *a*, `announce` *n*, nonzero meaning announced): @@ -601,7 +618,10 @@ refusal of `Apply`; SEND_UNIT and the refusals of the hand-over; an unannounced the classes `VictoryKillEnemyCommander`, `VictoryKillAllMobileUnits`, `VictoryBuildUnitType`, `VictoryUnitTypePassesX`, `VictoryUnitTypePassesZ`, `VictoryTimerRunsOut`, `DefeatUnitTypeKilled`, `DefeatDeathTimerRunsOut` and `DefeatAnyUnitPassesZ`, and a radius condition met; an empty condition list; a -second `map.UnitsInRange` call; the rank pass of `UpdatePlayersFinish`. +second `map.UnitsInRange` call; the rank pass of `UpdatePlayersFinish`; in `UpdatePlayerBody`, game type 1 +with *V* 1, a game type other than 1 with *L*'s info flag 0x40 set, and every row in which *D* is 1 outside +game type 1 (the countdown rows, the respawn and watch mode); a check of a game type other than 1 to 3; and +a *p* above 9. ## 8. Kit version From 8b7e81331552cb0f4c7c3a8e0cf9256d24e1c404 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:15:00 +0000 Subject: [PATCH 04/13] Fix: Answer the second players phase 1 review Assisted-by: Claude Code:claude-opus-5-5 --- specs/players.md | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/specs/players.md b/specs/players.md index ccfa71d..758af4e 100644 --- a/specs/players.md +++ b/specs/players.md @@ -102,8 +102,8 @@ The kit's entry for players is the module's entry, and this spec follows it exac itself by rule version 1 (ABI section 11) and exports `__fuel_set` and `__fuel_get`; its budgets come with a later entry. - Hooks: every slot of `interfaces/players.h` says "Hooks: none"; the event kind `PLAYERS_GIVE_UNIT` names - `UnitTransfer`. The kit defines no hook in the module ABI and the import list has none, so the module raises - none; no recording shows one. + `UnitTransfer`, whose point is the `Apply` of a `PLAYERS_GIVE_UNIT` (ABI 6, "Hook points"). The kit defines no + way to raise a hook and the import list has none, so the module raises none; no recording shows one. ### Routes and the recordings @@ -119,7 +119,9 @@ and `w Game.localPlayer` lines of the first `Apply` of a file are fields of the known value yet (`docs/replay-format.md`, "Lines"), not writes of the module; their values are the ones already in the block. A field the recorded write set leaves out (the `active` of `PLAYERS_DEACTIVATE_CONDITIONS`) has no `w` line, and a later call's `r` line shows its value. A `c` line under `map.UnitsInRange` doesn't occur: -the module takes ids, not a callback. A unit id *n* names slot *n* of the unit table (`Game.units` plus 280·*n*), +the module takes ids, not a callback. The recordings name some fields by other spellings of the same bytes: a radius condition's `pos` as `posX`, +`posY` and `posZ`, and the `PlayerInfo` bits by their words `flags_97_wide`, `flags` and `flags_9d_wide`. A +unit id *n* names slot *n* of the unit table (`Game.units` plus 280·*n*), which a recording writes `Unit#n`. ### Arguments outside the block @@ -273,7 +275,8 @@ the marker 0x12345678 until the centre is put on the ground (section 4). - A player is *counted for rank* when it plays, is not (`unitCount` 0 with `unitsCreated` not 0), and its info flag 0x40 is clear. - The *host slot*: the lowest player 0 to 9 whose `type` is not 0 and whose `info.host` is set, else 10. -- *L* is `Game.localPlayer`; *local* means player *L*. +- *L* is `Game.localPlayer`; *local* means player *L*. The engine keeps *L* from 0 to 9; for another *L* the + reference has no defined result. - A player's *slice* is the unit table from its `unitsBegin` to its `unitsEnd`, both included, 280 bytes apart. A *scan* of a slice visits, in table order, each unit whose `unitDefIndex` is not 0 and stops after the first visit that says stop. @@ -367,11 +370,14 @@ players when *h* is 10), with these imports in order: 2. Up to 9999 tries of a position *P*: *cx* = `baseX` / 10 and *cz* = `baseY` / 10 (section 5); `services.RandomInt(baseX − 2·cx)` gives *a*, then `services.RandomInt(baseY − 2·cz)` gives *b*; *P* = ((*a* + *cx*) · 65536, 0, (*b* + *cz*) · 65536). Then nine `map.CanPlaceUnitFootprint(d, 0, cell, 1)`, all nine on every try, - the cell (*X*, *Z*) for *Z* from *P*.z − *Hh* and *X* from *P*.x − *Hw*, each in three steps of *Hh* and *Hw* - (*Hh* = `height`·65536, *Hw* = `width`·65536), *Z* the outer loop, the cell's `x` and `y` the 16-bit - truncations of the unsigned values shifted right by 20 (section 5). *P* is taken when all nine answer - non-zero and then the low 16 bits of `features.FindFeatureAtPos(P, 0, 0)` are 0xffff and either `mission.GetMissionParams` - gives `lavaWorld` 0, or `lavaWorld` is not 0 and `map.GetCellMeanHeight(P)` is above `seaLevel`. A try whose + for the nine cells (*X*, *Z*) with *Z* taking *P*.z − *Hh*, *P*.z and *P*.z + *Hh* in that order and, for each, + *X* taking *P*.x − *Hw*, *P*.x and *P*.x + *Hw* (*Hh* = `height`·65536, *Hw* = `width`·65536); the cell is a + `Point16` of the module's own, passed by its address, with `x` from *X* and `y` from *Z*, each the 16-bit + truncation of the unsigned value shifted right by 20 (section 5). *P* is taken when all nine answer + non-zero and then the low 16 bits of `features.FindFeatureAtPos(P, 0, 0)` are 0xffff (*P* as the address of + the module's own `Vec3`, and both other arguments null) and either `mission.GetMissionParams` + gives `lavaWorld` 0 (a `MissionParams` of the module's own, which the import fills whole), or `lavaWorld` is + not 0 and `map.GetCellMeanHeight(P)` (the same `Vec3`) is above `seaLevel`. A try whose footprint count is below 9 makes neither of the last calls, and one whose feature test fails doesn't ask for the mission's figures. After the 9999th try the last *P* is taken. 3. `units.CreateUnit(L, t, P, 1, 1, 0)` gives the unit *u*. Whatever it gives, player *L*'s `flags` gets bit 0, @@ -384,7 +390,8 @@ players when *h* is 10), with these imports in order: ### Checks -A victory check *V* and a defeat check *D* read the conditions object *C* = `Game.list_391ed`. When *C*.`active` +A victory check *V* and a defeat check *D* read the conditions object *C* = `Game.list_391ed`. The reference has +no defined result for a null *C* here; this spec makes the check give 0 with no import (ozgb/btm#25). When *C*.`active` is 0 the check gives 0 with no import. Otherwise its first import is `mission.GetGameType`, *g*: | *g* | *V* | *D* | @@ -604,8 +611,8 @@ Each is taken from the kit's recordings and recomputed from this spec's definiti 48`); result 1. The `UNIT_DIED` of `Unit#282` in the same tick runs `DefeatAllUnitsKilledOfType#1`: `units.FindUnitTypeId "CORGEO" = 123`, `id` 123, and the scans give `count` 2. 6. `tests/replay/players/skirmish2.txt`, tick 29 and 30, `UpdatePlayerHead`: players 0 and 1 (`active` 1, - `type` 2, `index` 0 and 1) give 1, players 2 to 9 (`active` 0) give 0. At tick 30 player 0's body (clock 30) - gives 2: it is still in, `type` 2, `endGameFlags` bit 2 clear, countdown −1. + `type` 2, `index` 0 and 1) give 1, players 2 to 9 (`active` 0) give 0. At tick 30 the bodies of players 0 and 1 (clock 30) + both give 2; for player 0: it is still in, `type` 2, `endGameFlags` bit 2 clear, countdown −1. 7. `tests/replay/players/mission-defeat-passes-x.txt`, tick 0, `UpdatePlayerBody(0)`: the `VictoryMoveUnitToRadius#1` centre (8000, 4700) has the marker y, so `los_radar.ClampWorldPosToTerrain 8000 4700` writes (524288000, 5505024, 310771712) to `pos`; one @@ -621,7 +628,9 @@ the classes `VictoryKillEnemyCommander`, `VictoryKillAllMobileUnits`, `VictoryBu second `map.UnitsInRange` call; the rank pass of `UpdatePlayersFinish`; in `UpdatePlayerBody`, game type 1 with *V* 1, a game type other than 1 with *L*'s info flag 0x40 set, and every row in which *D* is 1 outside game type 1 (the countdown rows, the respawn and watch mode); a check of a game type other than 1 to 3; and -a *p* above 9. +a *p* above 9; the advance of the countdown in `UpdatePlayersFinish`; `PLAYERS_SET_TYPE` with `type` 3; +`PLAYERS_END_GAME` with `victory` 0; `PLAYERS_KILL_UNITS` for player 10 and a KILL_UNIT with `selfDestruct` 1; +a transfer with a NaN amount or store, or with `from` equal to `to`; and an `Apply` whose `size` is too small. ## 8. Kit version From 777e43a0c54e221f1945a92404bd4c07eb5a15c3 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:16:52 +0000 Subject: [PATCH 05/13] Fix: Answer the third players phase 1 review Assisted-by: Claude Code:claude-opus-5-5 --- specs/players.md | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/specs/players.md b/specs/players.md index 758af4e..86807d6 100644 --- a/specs/players.md +++ b/specs/players.md @@ -120,7 +120,8 @@ known value yet (`docs/replay-format.md`, "Lines"), not writes of the module; th already in the block. A field the recorded write set leaves out (the `active` of `PLAYERS_DEACTIVATE_CONDITIONS`) has no `w` line, and a later call's `r` line shows its value. A `c` line under `map.UnitsInRange` doesn't occur: the module takes ids, not a callback. The recordings name some fields by other spellings of the same bytes: a radius condition's `pos` as `posX`, -`posY` and `posZ`, and the `PlayerInfo` bits by their words `flags_97_wide`, `flags` and `flags_9d_wide`. A +`posY` and `posZ`, and the `PlayerInfo` bits by their words `flags_97_wide` (bit 0 `host`), `flags` (bit 6 `bit6`, bit 7 +`watching`) and `flags_9d_wide` (bit 1 `f9d_1`). A unit id *n* names slot *n* of the unit table (`Game.units` plus 280·*n*), which a recording writes `Unit#n`. @@ -200,8 +201,8 @@ restores them, `SavePlayers` stores them): | 4 to 43 | the *update clock* of players 0 to 9, ten unsigned 32-bit ticks (player *p* at 4 + 4*p*) | | 44 to 83 | the *win clock* of players 0 to 9, ten 32-bit ticks; the module's slots never read or write it | -**`Player`** (the array `Game.players`, 331 bytes apart from offset 7011; index 10 is the record past the ten -players, `Game.players_1b63`): `rank` (byte), `energy`, `metal` (floats; written by `PLAYERS_SET_STORE`), +**`Player`** (the array `Game.players`, 331 bytes apart from offset 7011; the record past the ten players is +element 10 of `Game.players_1b63`, the 11-element array at the same offset): `rank` (byte), `energy`, `metal` (floats; written by `PLAYERS_SET_STORE`), `type` (byte), `energyStorageBonus`, `metalStorageBonus` (floats) and bit 0 of `flags` (the respawn). **`PlayerInfo`** (a player's `info`, a `Ref`): `kind` (byte, `PLAYERS_SET_TYPE`) and `bit6` (info flag 0x40). @@ -296,7 +297,8 @@ The region, the conditions and the fields above. Nothing else: the module keeps Within one call, only the order of import calls is observable. The block writes are compared at the end of the call, so the order they are listed in carries no meaning, except where a later read in the same call sees -an earlier write or an effect's synchronous delivery, as said. +an earlier write, and except that every write this spec places before an `Emit` is in the block when that +`Emit` delivers its effect, since the subscriber reads the block (watch mode and the respawn, below). ### `RegionSize(info)` @@ -357,12 +359,14 @@ used. *W* holds when *g2* is 3, *L*'s `rejectReason` is 0, and `Game.players[h].info.watching` is set or there is at least one active AI player. -RECALCULATE is a `LosRadarRecalculate` (`kind` 133, `reset` 1, 8 bytes); the two events carry `[L]`. The -count of combat players is taken after *L*'s info flag 0x40 is set (the count of active AI players doesn't +RECALCULATE is a `LosRadarRecalculate` (`kind` 133, `reset` 1, 8 bytes); the two events carry `[L]`. *L*'s +info flag 0x40 and the map flags are written before the RECALCULATE `Emit`, which los_radar delivers at once and which +reads them; `endGameVictory` is written after the last import. The count of combat players is taken after +*L*'s info flag 0x40 is set (the count of active AI players doesn't read the flag). -**The respawn** (player *L*; *h* is the host slot and *H* is `Game.players[h].info`, the record past the ten -players when *h* is 10), with these imports in order: +**The respawn** (player *L*; *h* is the host slot and *H* is `Game.players[h].info`, for *h* 10 the `info` of +the record past the ten players, element 10 of `Game.players_1b63`), with these imports in order: 1. `units.FindUnitTypeId` with `Game.sideDefs[s].commander`, *s* the `side` of player *L*'s info; *t* is the result's low 16 bits, and *d* the unit type *t* of `Game.defs` (`Game.defs` plus 585·*t*, for any *t*, 0 @@ -382,7 +386,8 @@ players when *h* is 10), with these imports in order: for the mission's figures. After the 9999th try the last *P* is taken. 3. `units.CreateUnit(L, t, P, 1, 1, 0)` gives the unit *u*. Whatever it gives, player *L*'s `flags` gets bit 0, its `energyStorageBonus` becomes the float of max(*H*.energy·100, 200) and its `metalStorageBonus` the float - of max(*H*.metal·100, 200). Then, for a *u* that is not null, `Emit` INCOME (`EconomyIncome`, 24 bytes: `kind` 4, `player` + of max(*H*.metal·100, 200), all three after `units.CreateUnit` returns and before the first `Emit`. Then, for a +*u* that is not null, `Emit` INCOME (`EconomyIncome`, 24 bytes: `kind` 4, `player` *u*.`playerIndex`, `unit` the block offset of *u*, `resources` 1, `energy` float(*H*.energy)·100.0, `metal` 0.0), `Emit` INCOME (`resources` 2, `energy` 0.0, `metal` float(*H*.metal)·100.0), `Emit` RECALCULATE (`reset` 1), and `RecordSimEvent` FOCUS_COMMANDER `[1]`. What follows a null *u* is not defined by the @@ -417,7 +422,7 @@ is still in (*L* and *i* included). After every *i*, the result is 1. | --- | --- | --- | | `VictoryDestroyAllUnits` | `Game.field_1df2` is 0 | when met: celebrate | | `VictoryBuildUnitType` | `satisfied` is not 0, or becomes so | when `satisfied` is 0: if `id` is 0, `units.FindUnitTypeId(name)` and `id` becomes its 16-bit result; then a scan of player 0's slice: a unit whose `unitDefIndex` equals `id` and whose `buildLeft` is ±0.0 sets `satisfied` to 1 and celebrates; the scan stops once `satisfied` is not 0 | -| `VictoryMoveUnitToRadius` | `satisfied` is not 0 after the visits | when `pos.y` is 0x12345678: `los_radar.ClampWorldPosToTerrain` with the x and z of `pos` and `pos` itself as the output. Then `map.UnitsInRange(pos, radius, k, ids, 256)` with *k* 0, 256, 512 and so on, while each answer is 256; each id *n* of an answer, in order, visits unit slot *n* of `Game.units`: a unit with `playerIndex` 0, whose type matches `name` (any type when `name` is empty) and that can be counted sets `satisfied` to 1 and celebrates. Every id of every answer is visited | +| `VictoryMoveUnitToRadius` | `satisfied` is not 0 after the visits | when `pos.y` is 0x12345678: `los_radar.ClampWorldPosToTerrain` with the x and z of `pos` and `pos` itself as the output. Then `map.UnitsInRange(pos, radius, k, ids, 256)` with *k* 0, 256, 512 and so on, while each answer is 256; each id *n* of the ids an answer gives (as many as its result), in order, visits unit slot *n* of `Game.units`: a unit with `playerIndex` 0, whose type matches `name` (any type when `name` is empty) and that can be counted sets `satisfied` to 1 and celebrates. Every id of every answer is visited | | `VictoryUnitTypePassesX` (`Z`) | `satisfied` is not 0, or becomes so | when `satisfied` is 0, a scan of player 0's slice: a unit whose type matches `name` (any when empty) and whose `cell.x` (`cell.y`) is within 2 of `x` (`z`) sets `satisfied` and celebrates; stop once set | | `VictoryTimerRunsOut`, `DefeatDeathTimerRunsOut` | `Game.ticks` ≥ `endTick`, both unsigned | none | | `DefeatAllUnitsKilled` | no unit of player 0's slice can be counted | `satisfied` becomes 1 when it is met, 0 when it isn't | @@ -468,7 +473,7 @@ object. By kind: | `PLAYERS_SET_CONTROL` | `player` is above 9, or the player doesn't play | `localPlayer` and `playerIndex` become `player` | 1 | | `PLAYERS_SET_VIEW` | as SET_CONTROL | `playerIndex` becomes `player` | 1 | | `PLAYERS_COMPACT_RANKS` | `g_quirks.rankCompactionPerTick` is not 0 | the rank pass below | 1 | -| any other kind | always | none | 0 | +| any other kind (`ECONOMY_EFFECT_SHARE` included: the engine turns economy's SHARE into the announced `PLAYERS_TRANSFER` below before it reaches `Apply`) | always | none | 0 | A field the table doesn't use is not read: the `unit` of a kind that names none is ignored. @@ -561,7 +566,8 @@ The other subsystems' steps need imports the entry doesn't list (K5); no recordi `unitCount` and `numPlayers` are unsigned 16 bits; `rank` is an unsigned byte compared with the place *i*. `numLeftToKill`, `numUnits` and `count` are signed 32-bit; `numLeftToKill` of `DefeatUnitTypeKilled` can go below 0. -- **Ids:** `units.FindUnitTypeId` returns an unsigned 16-bit value (ABI 7: zero-extended); `id` stores its low 16 +- **Ids:** `units.FindUnitTypeId` returns an unsigned 16-bit value (ABI 7: zero-extended), 0 for a name with no + type (`interfaces/units.h`), which the module uses as it is; `id` stores its low 16 bits, and a unit's `unitDefIndex` is compared with `id` as 16-bit values. - **`buildLeft`** is compared with 0.0 as a float: −0.0 counts as 0, a NaN does not. From 75abbc877f9d6bbd2fc22827b967f853297789d1 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:24:02 +0000 Subject: [PATCH 06/13] Update: Pin the players spec to interfaces-v110 Assisted-by: Claude:claude-opus-5-5 --- specs/players.md | 199 +++++++++++++++++++++++++++++++---------------- 1 file changed, 133 insertions(+), 66 deletions(-) diff --git a/specs/players.md b/specs/players.md index 86807d6..c0bf02c 100644 --- a/specs/players.md +++ b/specs/players.md @@ -22,7 +22,7 @@ units, its grants of resources as events to economy. | `UpdatePlayerBody` | in the same player's turn, when its head returned 1, after the other subsystems' work of the turn (`docs/schedule.md`, the pass `players`) | | `UpdatePlayerTail` | in the same turn, when the body returned 1 or 2, after economy's settlement and the viewed player's radar passes | | `UpdatePlayersFinish` | once per tick, after the tenth player's turn | -| `UpdatePlayers`, `UpdatePlayersOnStream` | the whole players pass, when the engine runs it outside the tick loop (`UpdatePlayersOnStream` with the load stream at the load of a match, `docs/schedule.md`, "The load"; `UpdatePlayers` from the in-game dialogs) | +| `UpdatePlayers`, `UpdatePlayersOnStream` | the whole players pass: `UpdatePlayers` once a tick in the players phase (`docs/schedule.md`, the phase `players`), and `UpdatePlayersOnStream` with the load stream at the load of a match (`docs/schedule.md`, "The load") | | `DeactivateConditions` | when a unit command stops the conditions of the mission | | `RegionSize`, `Init` | once per match, at its load, before any event and before the first tick | | `Shutdown` | once per match, when it is unloaded | @@ -45,7 +45,7 @@ The kit's entry for players is the module's entry, and this spec follows it exac - `name` and `interface`: `players`. - `majors`: `players` 5, `mission` 2, `units` 7, `map` 9, `features` 5, `network` 2, `los_radar` 5, - `economy` 5, `services` 4. + `pathfinding` 4, `movement` 5, `ai` 6, `economy` 5, `services` 4. - `data_base` 524288 and `table_base` 368: the module's window is the 32768 bytes (the manifest's `window`) from 524288, and its table range the 32 entries (`table_slots`) from 368 (ABI 2). - `exports`, in this order: `Apply`, `UpdatePlayers`, `DeactivateConditions`, `UpdatePlayersOnStream`, @@ -77,6 +77,7 @@ The kit's entry for players is the module's entry, and this spec follows it exac | `mission.GetMissionParams` | `[linear] -> void` | the respawn's lava test (a `MissionParams` of the module's own) | | `units.CreateUnit` | `[int, int, linear, int, int, int] -> block` | the respawned commander | | `units.FindUnitTypeId` | `[linear] -> int` | a unit type by name (conditions, the respawn) | +| `units.RefreshFactoryIndex` | `[int] -> void` | the pass, per player | | `map.UnitsInRange` | `[linear, int, int, linear, int] -> int` | the units inside a radius condition's circle | | `map.GetCellMeanHeight` | `[linear] -> int` | the respawn's lava test | | `map.CanPlaceUnitFootprint` | `[block, int, linear, int] -> int` | the respawn's footprint test (a `Point16` cell of the module's own) | @@ -86,9 +87,22 @@ The kit's entry for players is the module's entry, and this spec follows it exac | `network.SendShareEnergy` | `[int, int, f32] -> void` | an announced transfer of metal (Q1) | | `network.BroadcastPlayerEconomy` | `[block] -> void` | the viewed player's economy, in a multiplayer game | | `los_radar.ClampWorldPosToTerrain` | `[int, int, linear] -> void` | a radius condition's centre, once | +| `los_radar.UpdateUnitLineOfSight` | `[block] -> void` | the pass, per live unit of a player | +| `los_radar.RecordRadarUnits` | `[] -> void` | the pass, the viewed player | +| `los_radar.UpdateSensorRadarAndCloak` | `[] -> void` | the pass, the viewed player | +| `los_radar.RecordRadarMapped` | `[] -> void` | the pass, the viewed player | +| `los_radar.RefreshUnitIndex` | `[int] -> void` | the pass, per player | +| `pathfinding.Step` | `[] -> void` | the pass, first | +| `pathfinding.Poll` | `[linear, int, linear, int] -> int` | the pass, the path events (a 28-byte event buffer and a 64-point waypoint buffer of the module's own) | +| `movement.ApplyPathEvent` | `[linear, int, linear] -> void` | the pass, each path event | +| `ai.UpdatePlayerAI` | `[int] -> void` | the pass, per player | +| `ai.UpdateSquads` | `[int] -> void` | the pass, per player | | `economy.Spend` | `[linear] -> int` | the giver's spend of an announced transfer (an `EconomySpend` of the module's own) | +| `economy.UpdatePlayerEconomy` | `[int] -> void` | the pass, a player whose body gives 2 | | `services.RandomInt` | `[int] -> int` | the respawn's position | +| `services.SimAlloc` | `[int] -> linear` | the condition an empty list gets (section 4, "Checks") | | `services.RecordSimEvent` | `[int, int, linear, int] -> void` | the sim events of section 2, "Events" | +| `services.SchedPassDeliver` | `[int] -> void` | the pass, before each step (section 4, the pass) | | `services.Emit` | `[linear, int] -> void` | every effect and event the module publishes | - `publishes`, the kinds and sizes `Emit` takes (ABI 9.3): 0 (`ECONOMY_RESET`, 12), 4 (`ECONOMY_INCOME`, 24), @@ -98,7 +112,8 @@ The kit's entry for players is the module's entry, and this spec follows it exac except economy's two (`data/routes.csv`), so an effect to units or los_radar has been applied when `Emit` returns, and its writes are in the block for what the module reads after it. - `blocked`: true. By ABI 4.2 an entry with `blocked` has no `.wasm` and no budgets (`fuel_budget`, - `size_budget`), and the host runs the native default for every slot. A module built from this spec meters + `size_budget`), and the host runs the native default for every slot; the gate judges a module of it on the + recordings of `tests/replay/players/` alone, without budgets. A module built from this spec meters itself by rule version 1 (ABI section 11) and exports `__fuel_set` and `__fuel_get`; its budgets come with a later entry. - Hooks: every slot of `interfaces/players.h` says "Hooks: none"; the event kind `PLAYERS_GIVE_UNIT` names @@ -107,14 +122,18 @@ The kit's entry for players is the module's entry, and this spec follows it exac ### Routes and the recordings -A recording shows the module's `Emit` as `i services.SchedPublish 4 ` (the recorded call of ABI 9.3, -"Routes in the recordings"; 4 is players' outbox), its `economy.Spend` as `i services.ScheduleEconomySpend`, and its `map.CanPlaceUnitFootprint` as -`i services.ScheduleMapCanPlaceUnitFootprint`. -An `o rng.seed` line after a publish is what the synchronous delivery of the effect changed in the game, -which the replayer sets from the line (`docs/replay-format.md`, "A random draw inside an import"). The replayer -makes no delivery, so no recording shows an effect's own writes, and a publish is compared by its outbox and -size alone (`docs/replay-format.md`, "Against the WASM module"); the fields of every effect, event and spend this -spec gives are judged by the scenario traces, through what their subscribers do. The `w Game.playerIndex` +A recording shows the module's `Emit` as `i services.Emit () `, the payload written as the +value of the payload struct of its kind (`docs/replay-format.md`, "Services", the `effect` form): INCOME as +`(4,1,null,2,f32:0x00000000,f32:0x424c0000)` (`null` for `unit` 0), KILL_UNIT as `(208,Unit#251,0)`, +CAPTURE_UNIT as `(210,Unit#282,0,0,0,0,0,0,0,0,0,0)`. The replayer compares every field of the payload and the +size, so each field this spec gives an effect or event is judged. Its `economy.Spend` is recorded as +`i services.ScheduleEconomySpend` (the spend's fields are not on the line), and its +`map.CanPlaceUnitFootprint` as `i services.ScheduleMapCanPlaceUnitFootprint`. +An `o rng.seed` line after a publish or an import of the pass is what the synchronous delivery of the effect, or +the import, changed in the game, which the replayer sets from the line (`docs/replay-format.md`, "A random draw +inside an import"); an `o Game.` line after an import of the pass is the same for a `Game` field +(`docs/replay-format.md`, "The phase driver"). The replayer makes no delivery, so no recording shows an +effect's own writes. The `w Game.playerIndex` and `w Game.localPlayer` lines of the first `Apply` of a file are fields of the slot's write set that have no known value yet (`docs/replay-format.md`, "Lines"), not writes of the module; their values are the ones already in the block. A field the recorded write set leaves out (the `active` of `PLAYERS_DEACTIVATE_CONDITIONS`) @@ -138,7 +157,8 @@ which a recording writes `Unit#n`. `economy.Spend` (24 bytes: `kind` 3, `player`, `unit` 0, `resources`, `energy`, `metal`), the effects and events it gives `Emit`, the argument array of `services.RecordSimEvent`, the `Vec3` of a position, the `MissionParams` (124 bytes; the module reads `lavaWorld`, the sixth 32-bit field, at offset 20), the id - buffer of `map.UnitsInRange` (256 unsigned 16-bit ids) and the NUL-terminated names given to + buffer of `map.UnitsInRange` (256 unsigned 16-bit ids), the pass's path event buffer (28 bytes, a + `PathfindingFinished`) and waypoint buffer (64 `PathPoint`s, 256 bytes) and the NUL-terminated names given to `units.FindUnitTypeId`. A name given to `units.FindUnitTypeId` may also be the field itself in the block (a condition's `name`, a `SideDef.commander`): the recording shows the text. - **The `Vec3` of a radius condition** is the condition's own `pos` in the block: `los_radar.ClampWorldPosToTerrain` @@ -164,27 +184,15 @@ those of `docs/sim-events.md`, Terms. ### Kit gaps -What this spec needs and the kit doesn't give; the maintainer routes them (K2 and K3 were closed by the kit at `interfaces-v68`, so the numbers skip them): +What this spec needs and the kit doesn't give. K1, K5 and K6 (the class words, the pass and the empty list) +were closed by the kit at `interfaces-v110`, and K2 and K3 at `interfaces-v68`, so the numbers skip them: -- **K1, the class of a condition.** A condition (section 3) is told apart by its first word, the vtable - pointer of its class, which the engine's load-class slots write and the kit gives no value for (the - layout's `MissionCondition` has `vptr` true and no field for it; the recordings name the class, - `VictoryKillAllOfType#1`, but never the word). Every slot that runs a condition needs the class. Until the - kit gives the 18 words (or a class number in the block), this spec states each class's behaviour, and a - module can't pick it from the block alone. - **K4, the saved game's account names** serve only the engine slots `LoadConditions` and `SaveConditions`; no exported slot needs them. -- **K5, the whole pass.** `UpdatePlayers` and `UpdatePlayersOnStream` are exported, but the players pass - calls other subsystems' slots (pathfinding, movement, ai, los_radar, units, economy; `docs/schedule.md`, the - passes `players` and `players.los`), and the entry lists none of them as an import. No recording holds - either slot. -- **K6, a condition list that is empty.** A campaign check of an empty list adds a condition to it (section - 4, "Checks"), which needs a block allocation (`services.SimAlloc`, not in the entry) and the class word of - K1. No recording has an empty list. - **K7, `PLAYERS_DEACTIVATE_CONDITIONS` with no conditions**: the header lists no refusal for it. This spec makes it change nothing with outcome 0 (section 4, `Apply`). -- **K8, a respawn whose `units.CreateUnit` gives null.** The reference reads the new unit for its incomes - without a test, so the case has no defined result; the kit says nothing of it either. +- **K8, a respawn whose `units.CreateUnit` gives null** has no defined result in the reference, and no + gate can judge one, so this spec leaves it open (section 4, "The respawn"). ## 3. State @@ -215,35 +223,42 @@ element 10 of `Game.players_1b63`, the 11-element array at the same offset): `ra **The conditions** (`Game.list_391ed`, a `Ref`, null when there are none): the record `MissionConditions` (140 bytes): `victory` and `defeat` (16 `Ref` each), `victoryCount`, -`defeatCount` (at most 16) and `active`. Each condition starts with the class word (K1), then `satisfied` and -`celebrated` at 4 and 8. The classes, by their `layout.json` record, and the fields the module writes: +`defeatCount` (at most 16) and `active`. Each condition starts with its class word, then `satisfied` and +`celebrated` at 4 and 8. The class word is a copy of an entry of the class word table (ABI section 7.1, "The +class word table starts the `load_data` region"; `class_words` of `layout.json`): entry *i* is the 32-bit word +at 0x10100000 + 4·*i*. A condition's class is the class of the entry (with no `base`) whose word equals its +first word. The classes, their entry, by their `layout.json` record, and the fields the module writes: -| Class | List | Fields after `celebrated` | -| --- | --- | --- | -| `VictoryKillEnemyCommander` | victory | none | -| `VictoryDestroyAllUnits` | victory | none | -| `VictoryKillAllMobileUnits` | victory | `numUnits` (16) | -| `VictoryBuildUnitType` | victory | `name` (16, 32 bytes), `id` (48, 16 bits) | -| `VictoryCaptureUnitType` | victory | `name` (12) | -| `VictoryKillAllOfType` | victory | `name` (16), `id` (48), `count` (50, 32 bits) | -| `VictoryKillUnitType` | victory | `name` (12), `numLeftToKill` (44) | -| `VictoryMoveUnitToRadius` | victory | `name` (16), `pos` (48, a `Vec3`), `radius` (60) | -| `VictoryUnitTypePassesX` | victory | `name` (16), `x` (48) | -| `VictoryUnitTypePassesZ` | victory | `name` (16), `z` (48) | -| `VictoryTimerRunsOut` | victory | `endTick` (12, unsigned) | -| `DefeatCommanderKilled` | defeat | none | -| `DefeatAllUnitsKilled` | defeat | none | -| `DefeatAllUnitsKilledOfType` | defeat | `name` (16), `id` (48), `count` (50) | -| `DefeatUnitTypeKilled` | defeat | `name` (12), `numLeftToKill` (44) | -| `DefeatDeathTimerRunsOut` | defeat | `endTick` (12) | -| `DefeatAnyUnitPassesX` | defeat | `x` (16) | -| `DefeatAnyUnitPassesZ` | defeat | `z` (16) | +| Class | Entry | List | Fields after `celebrated` | +| --- | --- | --- | --- | +| `VictoryKillEnemyCommander` | 39 | victory | none | +| `VictoryDestroyAllUnits` | 34 | victory | none | +| `VictoryKillAllMobileUnits` | 35 | victory | `numUnits` (16) | +| `VictoryBuildUnitType` | 31 | victory | `name` (16, 32 bytes), `id` (48, 16 bits) | +| `VictoryCaptureUnitType` | 33 | victory | `name` (12) | +| `VictoryKillAllOfType` | 37 | victory | `name` (16), `id` (48), `count` (50, 32 bits) | +| `VictoryKillUnitType` | 40 | victory | `name` (12), `numLeftToKill` (44) | +| `VictoryMoveUnitToRadius` | 41 | victory | `name` (16), `pos` (48, a `Vec3`), `radius` (60) | +| `VictoryUnitTypePassesX` | 44 | victory | `name` (16), `x` (48) | +| `VictoryUnitTypePassesZ` | 46 | victory | `name` (16), `z` (48) | +| `VictoryTimerRunsOut` | 43 | victory | `endTick` (12, unsigned) | +| `DefeatCommanderKilled` | 14 | defeat | none | +| `DefeatAllUnitsKilled` | 6 | defeat | none | +| `DefeatAllUnitsKilledOfType` | 8 | defeat | `name` (16), `id` (48), `count` (50) | +| `DefeatUnitTypeKilled` | 16 | defeat | `name` (12), `numLeftToKill` (44) | +| `DefeatDeathTimerRunsOut` | 15 | defeat | `endTick` (12) | +| `DefeatAnyUnitPassesX` | 10 | defeat | `x` (16) | +| `DefeatAnyUnitPassesZ` | 12 | defeat | `z` (16) | Offsets are bytes from the condition's start; `id` and `count` are unaligned. In a class whose first field after `celebrated` is at 16, and in `DefeatAllUnitsKilled` (16 bytes, no such field), bytes 12 to 15 hold a -second class word, which the module never reads or writes; `layout.json` leaves those bytes unnamed, and -the word's value is unknown as K1's is. A `name` is NUL-terminated -(empty for "any type" in the radius and passes classes). The module never writes a class word, a `name`, an +second class word: the table's entry for that class with a `base` (`UnitScanVisitor`, or +`RadiusUnitVisitor` for `VictoryMoveUnitToRadius`; entries 7, 9, 11, 13, 32, 36, 38, 42, 45 and 47). The +module reads it never, and writes it only in the condition it makes (section 4, "Checks"). A condition +whose first word is no entry of these 18 has no defined result in the reference; this spec treats it as a +class that acts on no notice and is met when its `satisfied` is not 0 (ozgb/btm#25). A `name` is NUL-terminated +(empty for "any type" in the radius and passes classes). The module writes a class word only in a condition it +makes, and never writes a `name`, an `x`, a `z`, a `radius` or an `endTick`. A radius condition's `pos` holds the centre's x and z as given, and y the marker 0x12345678 until the centre is put on the ground (section 4). @@ -406,9 +421,12 @@ is 0 the check gives 0 with no import. Otherwise its first import is `mission.Ge | 3 | the allied victory below | as for 2 | | other | 0 | 0 | -An empty list, in a check of game type 1, first gets one condition: `VictoryDestroyAllUnits` for the victory -list, `DefeatAllUnitsKilled` for the defeat list, both with `satisfied` and `celebrated` 0, as entry 0 of the list, and the list's count (`victoryCount` or -`defeatCount`) becomes 1 (K6). +An empty list (its count 0), in a check of game type 1, first gets one condition, made with the import +`services.SimAlloc` straight after the check's `mission.GetGameType`: for the victory list `SimAlloc(12)`, a +`VictoryDestroyAllUnits` (word 0 the class word table's entry 34); for the defeat list `SimAlloc(16)`, a +`DefeatAllUnitsKilled` (word 0 entry 6, word 3, bytes 12 to 15, entry 7). Its `satisfied` and `celebrated` stay +0 (the allocation is zeroed). Its address becomes entry 0 of the list, and the list's count (`victoryCount` or +`defeatCount`) becomes 1; the check then runs the list as for any other. **The allied victory** is 0 when `Game.commanderDeath` is 2. Otherwise, for each player *i* from 0 to 9 other than *L* that plays and whose info flag 0x40 is clear: the result is 0 when its `unitsCreated` is 0; when its @@ -537,11 +555,42 @@ The `active` of the given object becomes 0; a null object changes nothing. No im ### `UpdatePlayers()`, `UpdatePlayersOnStream(stream)` -The players pass of `docs/schedule.md` (the passes `players` and `players.los`), with *stream* (the main -stream for `UpdatePlayers`) given to each body: for each player 0 to 9, the head, and when it gives 1 the other -subsystems' steps of the turn, the body, economy's settlement when the body gives 2, the viewed player's radar -steps, and the tail when the body gives 1 or 2; then the finish. The steps of this module are the slots above. -The other subsystems' steps need imports the entry doesn't list (K5); no recording holds either slot. +The players pass of `docs/schedule.md` (the phase `players`), with *stream* 0 (the main stream) for +`UpdatePlayers` and the argument for `UpdatePlayersOnStream`. *Deliver m* is the import +`services.SchedPassDeliver(m)`, with the scheduler module ids of `docs/replay-format.md`, "The phase driver" +(economy 1, units 2, players 4, ai 10, los_radar 11). A delivery to players (4) runs the events queued for +players through this module's `Apply`, inside the import, in the order they were published; a recording shows +each as a `c players.Apply` line under the import's `i` line (no stored recording has one). The pass's head, +body, tail and finish have exactly the behaviour, imports and writes of `UpdatePlayerHead`, +`UpdatePlayerBody`, `UpdatePlayerTail` and `UpdatePlayersFinish` above, at the places below, and add no import +line of their own. + +The imports, in order: + +1. `pathfinding.Step`. +2. The path events: the module zeroes its 28-byte event buffer, then `pathfinding.Poll(event, 28, points, 64)` + with its 64-point waypoint buffer (not cleared) gives *n*. When *n*, as a signed 32-bit number, is below 20 + (the size of a `PathfindingEventHeader`), the path events end. Otherwise + `movement.ApplyPathEvent(event, min(n, 28), points)` (*n* compared unsigned), and this step repeats from the + zeroing. +3. For each player *p* from 0 to 9: + 1. Deliver 4; the head of *p*. When it gives 0, *p*'s turn ends here. + 2. Deliver 10, `ai.UpdateSquads(p)`; deliver 11, `los_radar.RefreshUnitIndex(p)`; deliver 2, + `units.RefreshFactoryIndex(p)`; deliver 10, `ai.UpdatePlayerAI(p)`. + 3. The line of sight: when player *p*'s `unitsBegin` (read once, here) is not null, for each unit *u* of the + unit table from `unitsBegin` while *u* is not past `unitsEnd` (read again before each unit), 280 bytes + apart: when *u*'s unit flag 0x10000000 is set, deliver 11 and `los_radar.UpdateUnitLineOfSight(u)`. The + test is that flag alone (an empty slot has it clear). + 4. When *p* equals `Game.playerIndex` (read here): deliver 11, `los_radar.RecordRadarUnits`. + 5. Deliver 4; the body of *p* with *stream*, giving *b*. When *b* is 0, *p*'s turn ends here. + 6. When *b* is 2: deliver 1, `economy.UpdatePlayerEconomy(p)`. + 7. When *p* equals `Game.playerIndex` (read again here): deliver 11, + `los_radar.UpdateSensorRadarAndCloak`; deliver 11, `los_radar.RecordRadarMapped`. + 8. Deliver 4; the tail of *p*. +4. Deliver 4; the finish. + +A delivery or an import of another subsystem can change the block, and each read above is made at its place +in the order: the recordings set what those calls changed from their `o` lines. ## 5. Exactness @@ -595,7 +644,8 @@ Each is taken from the kit's recordings and recomputed from this spec's definiti *S* + `amount` = 2000.0: `w Player#0.energy f32:0x44fa0000`, result 1, no import. 2. The same file, tick 40, `PLAYERS_TRANSFER` from 0 to 1, resource 1 (metal), `amount` f32:0x42c80000 (100.0), announced. `Player#0.metal` is f32:0x424c0000 (51.0), so *a* becomes 51.0: `economy.Spend` (the line - `i services.ScheduleEconomySpend = 1`), `Emit` INCOME of 24 bytes (`i services.SchedPublish 4 24`), then + `i services.ScheduleEconomySpend = 1`), `Emit` INCOME of 24 bytes to player 1, `resources` 2, `energy` 0.0 + and `metal` 51.0 (`i services.Emit (4,1,null,2,f32:0x00000000,f32:0x424c0000) 24`), then `i network.SendShareEnergy 0 1 f32:0x424c0000`; result 1. At tick 50, resource 0 with `Player#0.energy` 1000.0 keeps 100.0 and sends `network.SendShareMetal 0 1 f32:0x42c80000`. 3. `tests/replay/players/mission-defeat-all-units.txt`, tick 360, `UpdatePlayerBody(0)`: game type 1, clock 360 @@ -613,8 +663,8 @@ Each is taken from the kit's recordings and recomputed from this spec's definiti 0, size 48. *o* is `Player#1` (active, `type` 2) and *r* `Player#0` (active, `type` 1); the unit is alive (`flags` 0x30280321, bit 28 set, bit 14 clear). The captured notice: `VictoryCaptureUnitType#1` (`name` "CORGEO") matches `UnitDef#123` "CORGEO" and `playerIndex` 1, so `satisfied` and `celebrated` become 1 with - `i services.RecordSimEvent 2 0 [0,0] 2`; then `Emit` CAPTURE_UNIT, 48 bytes (`i services.SchedPublish 4 - 48`); result 1. The `UNIT_DIED` of `Unit#282` in the same tick runs `DefeatAllUnitsKilledOfType#1`: + `i services.RecordSimEvent 2 0 [0,0] 2`; then `Emit` CAPTURE_UNIT, 48 bytes, with *r* 0 and the event's nine + `record` words, all 0 (`i services.Emit (210,Unit#282,0,0,0,0,0,0,0,0,0,0) 48`); result 1. The `UNIT_DIED` of `Unit#282` in the same tick runs `DefeatAllUnitsKilledOfType#1`: `units.FindUnitTypeId "CORGEO" = 123`, `id` 123, and the scans give `count` 2. 6. `tests/replay/players/skirmish2.txt`, tick 29 and 30, `UpdatePlayerHead`: players 0 and 1 (`active` 1, `type` 2, `index` 0 and 1) give 1, players 2 to 9 (`active` 0) give 0. At tick 30 the bodies of players 0 and 1 (clock 30) @@ -625,7 +675,24 @@ Each is taken from the kit's recordings and recomputed from this spec's definiti `map.UnitsInRange` with skip 0 and capacity 256 answers 14, under 256, so it is the only one; none of the 14 units meets the condition. -Not covered by any recording: `UpdatePlayers`, `UpdatePlayersOnStream`, `DeactivateConditions` and `Shutdown`; +8. `tests/replay/players/orders-move-attack.txt`, `UpdatePlayers` at tick 180: `pathfinding.Step`, then one + `pathfinding.Poll` answering 0 (below 20), so no path event. Player 0 (`Game.playerIndex` 0, `localPlayer` + 0): deliver 4, the head gives 1; deliver 10, `ai.UpdateSquads 0`, deliver 11, `los_radar.RefreshUnitIndex 0`, + deliver 2, `units.RefreshFactoryIndex 0`, deliver 10, `ai.UpdatePlayerAI 0`; its one live unit, deliver 11, + `los_radar.UpdateUnitLineOfSight Unit#1`; deliver 11, `los_radar.RecordRadarUnits`; deliver 4, the body: + clock 180 (`4:b4`) is not above the tick, so it becomes 210 (`4:d2`); game type 2, *D* (one more + `GetGameType`) 0 and *V* (one more) 0, so three `GetGameType`, and the body gives 2; deliver 1, + `economy.UpdatePlayerEconomy 0`; deliver 11, `los_radar.UpdateSensorRadarAndCloak`, deliver 11, + `los_radar.RecordRadarMapped`; deliver 4, the tail: `GetGameType` 2, nothing else. Player 1 the same up + to its body (`Unit#251`, no `RecordRadarUnits`), whose clock becomes 210 (`8:d2`) and which gives 2 with + no import, as 1 is not *L*: deliver 1, `economy.UpdatePlayerEconomy 1`, deliver 4 and the tail, which does + nothing. Players 2 to 9: deliver 4 each, the head gives 0. Then deliver 4 and the finish's `GetGameType`. + At tick 181 `Poll` answers 24 (a STARTED event, `movement.ApplyPathEvent` with size 24), then 28 (a FINISHED + event with its four waypoints, size 28), then 0; each body gives 0, as each clock, 210, is above 181, so + neither turn goes past its body. + +Not covered by any recording: `UpdatePlayersOnStream`, `DeactivateConditions` and `Shutdown`; a +`c players.Apply` delivery inside the pass; a `Poll` answer above 28; the respawn and watch mode; `PLAYERS_SET_CHEATS`, `PLAYERS_LEAVE_GAME`, `PLAYERS_COMPACT_RANKS` and every refusal of `Apply`; SEND_UNIT and the refusals of the hand-over; an unannounced transfer and the zero amount; the classes `VictoryKillEnemyCommander`, `VictoryKillAllMobileUnits`, `VictoryBuildUnitType`, @@ -640,5 +707,5 @@ a transfer with a NaN amount or store, or with `from` equal to `to`; and an `App ## 8. Kit version -`interfaces-v68` and `reference-traces-v55` (commit 906e69ae4), with players at `interfaces/players.h` version +`interfaces-v110` and `reference-traces-v65` (commit b9fe223ca), with players at `interfaces/players.h` version 5.4. From e73fb6492d08ae994b6ac69a0a4090040db1e1f2 Mon Sep 17 00:00:00 2001 From: Cy Bailey <41227554+CubeB@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:36:56 +0000 Subject: [PATCH 07/13] Fix: Take the optional phase 2 wording points Assisted-by: Claude:claude-opus-5-5 --- specs/players.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/specs/players.md b/specs/players.md index c0bf02c..4564454 100644 --- a/specs/players.md +++ b/specs/players.md @@ -18,10 +18,10 @@ units, its grants of resources as events to economy. | Slot | When the engine calls it | | --- | --- | | `Apply` | for each event of players' inbox: before each run below, at each phase boundary, and at once for a synchronous route or an event published outside the tick (`docs/schedule.md`, "Routes"; `data/routes.csv`) | -| `UpdatePlayerHead` | in the players phase, for each player slot 0 to 9 in order | -| `UpdatePlayerBody` | in the same player's turn, when its head returned 1, after the other subsystems' work of the turn (`docs/schedule.md`, the pass `players`) | -| `UpdatePlayerTail` | in the same turn, when the body returned 1 or 2, after economy's settlement and the viewed player's radar passes | -| `UpdatePlayersFinish` | once per tick, after the tenth player's turn | +| `UpdatePlayerHead` | in the players phase, for each player slot 0 to 9 in order (inside `UpdatePlayers`, section 4) | +| `UpdatePlayerBody` | in the same player's turn, when its head returned 1, after the other subsystems' work of the turn (inside `UpdatePlayers`, section 4) | +| `UpdatePlayerTail` | in the same turn, when the body returned 1 or 2, after economy's settlement and the viewed player's radar passes (inside `UpdatePlayers`, section 4) | +| `UpdatePlayersFinish` | once per tick, after the tenth player's turn (inside `UpdatePlayers`, section 4) | | `UpdatePlayers`, `UpdatePlayersOnStream` | the whole players pass: `UpdatePlayers` once a tick in the players phase (`docs/schedule.md`, the phase `players`), and `UpdatePlayersOnStream` with the load stream at the load of a match (`docs/schedule.md`, "The load") | | `DeactivateConditions` | when a unit command stops the conditions of the mission | | `RegionSize`, `Init` | once per match, at its load, before any event and before the first tick | @@ -571,7 +571,7 @@ The imports, in order: 2. The path events: the module zeroes its 28-byte event buffer, then `pathfinding.Poll(event, 28, points, 64)` with its 64-point waypoint buffer (not cleared) gives *n*. When *n*, as a signed 32-bit number, is below 20 (the size of a `PathfindingEventHeader`), the path events end. Otherwise - `movement.ApplyPathEvent(event, min(n, 28), points)` (*n* compared unsigned), and this step repeats from the + `movement.ApplyPathEvent(event, min(n, 28), points)`, and this step repeats from the zeroing. 3. For each player *p* from 0 to 9: 1. Deliver 4; the head of *p*. When it gives 0, *p*'s turn ends here. @@ -580,7 +580,7 @@ The imports, in order: 3. The line of sight: when player *p*'s `unitsBegin` (read once, here) is not null, for each unit *u* of the unit table from `unitsBegin` while *u* is not past `unitsEnd` (read again before each unit), 280 bytes apart: when *u*'s unit flag 0x10000000 is set, deliver 11 and `los_radar.UpdateUnitLineOfSight(u)`. The - test is that flag alone (an empty slot has it clear). + test is that flag alone. 4. When *p* equals `Game.playerIndex` (read here): deliver 11, `los_radar.RecordRadarUnits`. 5. Deliver 4; the body of *p* with *stream*, giving *b*. When *b* is 0, *p*'s turn ends here. 6. When *b* is 2: deliver 1, `economy.UpdatePlayerEconomy(p)`. From aeb44ba7b11bf524afd9bd404d19d06a895f3d23 Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 12:53:06 +0000 Subject: [PATCH 08/13] Add: Implement the players module Assisted-by: Claude Code:claude-sonnet-5-5 --- players/.gitignore | 2 + players/Cargo.lock | 7 + players/Cargo.toml | 14 + players/build.sh | 8 + players/ld-wrap.sh | 9 + players/src/lib.rs | 1311 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 1351 insertions(+) create mode 100644 players/.gitignore create mode 100644 players/Cargo.lock create mode 100644 players/Cargo.toml create mode 100755 players/build.sh create mode 100755 players/ld-wrap.sh create mode 100644 players/src/lib.rs diff --git a/players/.gitignore b/players/.gitignore new file mode 100644 index 0000000..89ff056 --- /dev/null +++ b/players/.gitignore @@ -0,0 +1,2 @@ +*.wasm +target/ diff --git a/players/Cargo.lock b/players/Cargo.lock new file mode 100644 index 0000000..9f61314 --- /dev/null +++ b/players/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "players" +version = "0.1.0" diff --git a/players/Cargo.toml b/players/Cargo.toml new file mode 100644 index 0000000..c4754e0 --- /dev/null +++ b/players/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "players" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[profile.release] +panic = "abort" +opt-level = "s" +lto = true +codegen-units = 1 +debug = false diff --git a/players/build.sh b/players/build.sh new file mode 100755 index 0000000..a62e04a --- /dev/null +++ b/players/build.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# Builds players.wasm (metered by the data kit's fuel pass) next to this script. +set -e +cd "$(dirname "$0")" +cargo rustc --release --target wasm32-unknown-unknown -- -C linker=$PWD/ld-wrap.sh -C target-cpu=mvp -C target-feature=+sign-ext,+bulk-memory \ + -C link-arg=--import-memory -C link-arg=--import-table -C link-arg=--global-base=524288 -C link-arg=--table-base=368 \ + -C link-arg=--no-entry -C link-arg=-zstack-size=4096 -C link-arg=--gc-sections +python3 -I /data/tools/wasm_fuel.py target/wasm32-unknown-unknown/release/players.wasm -o players.wasm diff --git a/players/ld-wrap.sh b/players/ld-wrap.sh new file mode 100755 index 0000000..ada6ff2 --- /dev/null +++ b/players/ld-wrap.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# rustc passes --stack-first and --allow-undefined; the ABI forbids both. +# ABI 3.1 wants --no-stack-first; a linker whose help doesn't list it already puts the stack after the data. +for a in "$@"; do + shift + case "$a" in --stack-first|--allow-undefined|--export=__heap_base|--export=__data_end) ;; *) set -- "$@" "$a";; esac +done +if wasm-ld --help | grep -q -e '--no-stack-first'; then set -- "$@" --no-stack-first; fi +exec wasm-ld "$@" diff --git a/players/src/lib.rs b/players/src/lib.rs new file mode 100644 index 0000000..de5c686 --- /dev/null +++ b/players/src/lib.rs @@ -0,0 +1,1311 @@ +#![no_std] + +use core::ptr::{read_unaligned, read_volatile, write_unaligned}; + +#[link(wasm_import_module = "mission")] +extern "C" { + #[link_name = "GetGameType"] + fn get_game_type() -> i32; + #[link_name = "GetMissionParams"] + fn get_mission_params(p: *mut u32); +} +#[link(wasm_import_module = "units")] +extern "C" { + #[link_name = "CreateUnit"] + fn create_unit(player: i32, ty: i32, pos: *const u32, a: i32, b: i32, c: i32) -> u32; + #[link_name = "FindUnitTypeId"] + fn find_unit_type_id(name: u32) -> i32; + #[link_name = "RefreshFactoryIndex"] + fn refresh_factory_index(p: i32); +} +#[link(wasm_import_module = "map")] +extern "C" { + #[link_name = "UnitsInRange"] + fn units_in_range(pos: u32, radius: i32, skip: i32, ids: *mut u16, cap: i32) -> i32; + #[link_name = "GetCellMeanHeight"] + fn get_cell_mean_height(pos: *const u32) -> i32; + #[link_name = "CanPlaceUnitFootprint"] + fn can_place_unit_footprint(def: u32, a: i32, cell: *const u32, b: i32) -> i32; +} +#[link(wasm_import_module = "features")] +extern "C" { + #[link_name = "FindFeatureAtPos"] + fn find_feature_at_pos(pos: *const u32, a: u32, b: u32) -> i32; +} +#[link(wasm_import_module = "network")] +extern "C" { + #[link_name = "BroadcastPlayerInfo"] + fn broadcast_player_info(); + #[link_name = "SendShareMetal"] + fn send_share_metal(from: i32, to: i32, amount: f32); + #[link_name = "SendShareEnergy"] + fn send_share_energy(from: i32, to: i32, amount: f32); + #[link_name = "BroadcastPlayerEconomy"] + fn broadcast_player_economy(player: u32); +} +#[link(wasm_import_module = "los_radar")] +extern "C" { + #[link_name = "ClampWorldPosToTerrain"] + fn clamp_world_pos_to_terrain(x: i32, z: i32, out: u32); + #[link_name = "UpdateUnitLineOfSight"] + fn update_unit_line_of_sight(unit: u32); + #[link_name = "RecordRadarUnits"] + fn record_radar_units(); + #[link_name = "UpdateSensorRadarAndCloak"] + fn update_sensor_radar_and_cloak(); + #[link_name = "RecordRadarMapped"] + fn record_radar_mapped(); + #[link_name = "RefreshUnitIndex"] + fn refresh_unit_index(p: i32); +} +#[link(wasm_import_module = "pathfinding")] +extern "C" { + #[link_name = "Step"] + fn pathfinding_step(); + #[link_name = "Poll"] + fn pathfinding_poll(ev: *mut u32, evsize: i32, points: *mut u32, npoints: i32) -> i32; +} +#[link(wasm_import_module = "movement")] +extern "C" { + #[link_name = "ApplyPathEvent"] + fn apply_path_event(ev: *const u32, size: i32, points: *const u32); +} +#[link(wasm_import_module = "ai")] +extern "C" { + #[link_name = "UpdatePlayerAI"] + fn update_player_ai(p: i32); + #[link_name = "UpdateSquads"] + fn update_squads(p: i32); +} +#[link(wasm_import_module = "economy")] +extern "C" { + #[link_name = "Spend"] + fn economy_spend(spend: *const u32) -> i32; + #[link_name = "UpdatePlayerEconomy"] + fn update_player_economy(p: i32); +} +#[link(wasm_import_module = "services")] +extern "C" { + #[link_name = "RandomInt"] + fn random_int(range: i32) -> i32; + #[link_name = "SimAlloc"] + fn sim_alloc(size: i32) -> u32; + #[link_name = "RecordSimEvent"] + fn record_sim_event(kind: i32, flags: i32, args: *const u32, count: i32); + #[link_name = "SchedPassDeliver"] + fn sched_pass_deliver(module: i32); + #[link_name = "Emit"] + fn emit(effect: *const u32, size: i32); +} + +#[no_mangle] +pub static mut g_game: u32 = 0; +#[no_mangle] +pub static mut g_simGlobals: u32 = 0; +#[no_mangle] +pub static mut g_extTdf: u32 = 0; +#[no_mangle] +pub static mut g_blockBase: u32 = 0; +#[no_mangle] +pub static mut g_region: u32 = 0; + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo) -> ! { + loop {} +} + +// Game +const PLAYERS: u32 = 7011; +const F1DF2: u32 = 7666; +const NUM_PLAYERS: u32 = 10812; +const LOCAL: u32 = 10818; +const PINDEX: u32 = 10819; +const BASE_X: u32 = 82467; +const BASE_Y: u32 = 82471; +const WIDTH: u32 = 82483; +const HEIGHT: u32 = 82487; +const SEA: u32 = 82559; +const MAP_FLAGS: u32 = 82561; +const UNITS: u32 = 82775; +const DEFS: u32 = 82843; +const CMD_DEATH: u32 = 229110; +const UI_OPT: u32 = 229167; +const SIDEDEFS: u32 = 229181; +const TICKS: u32 = 232007; +const CONDS: u32 = 233965; +const END_FLAGS: u32 = 234043; +const END_VICT: u32 = 234061; +// SimGlobals +const ECON_TICK: u32 = 48140; +const RANK_QUIRK: u32 = 49240; +// Player +const P_ACTIVE: u32 = 0; +const P_REJECT: u32 = 34; +const P_INFO: u32 = 39; +const P_UBEGIN: u32 = 103; +const P_UEND: u32 = 107; +const P_TYPE: u32 = 115; +const P_ENERGY: u32 = 140; +const P_METAL: u32 = 152; +const P_ESB: u32 = 220; +const P_MSB: u32 = 224; +const P_ALLIED: u32 = 264; +const P_ALLIED_BY: u32 = 275; +const P_UCREATED: u32 = 320; +const P_UCOUNT: u32 = 324; +const P_INDEX: u32 = 326; +const P_RANK: u32 = 328; +const P_FLAGS: u32 = 329; +// PlayerInfo +const I_KIND: u32 = 148; +const I_SIDE: u32 = 149; +const I_F97: u32 = 151; +const I_F9B: u32 = 155; +const I_F9D: u32 = 157; +const I_ENERGY: u32 = 161; +const I_METAL: u32 = 163; +// Unit +const U_MOTION: u32 = 0; +const U_CELL: u32 = 118; +const U_CARRIER: u32 = 134; +const U_DEF: u32 = 146; +const U_PLAYER: u32 = 150; +const U_DEFIDX: u32 = 166; +const U_HOLDOFF: u32 = 251; +const U_PIDX: u32 = 255; +const U_BUILD_LEFT: u32 = 260; +const U_FLAGS: u32 = 272; +// Conditions +const C_SAT: u32 = 4; +const C_CEL: u32 = 8; +const MC_VCOUNT: u32 = 64; +const MC_DEFEAT: u32 = 68; +const MC_DCOUNT: u32 = 132; +const MC_ACTIVE: u32 = 136; + +const CLASS_TABLE: u32 = 0x1010_0000; + +// Classes, by the entry of the class word table. +const K_VKILL_CMDR: u32 = 39; +const K_VDESTROY_ALL: u32 = 34; +const K_VKILL_MOBILE: u32 = 35; +const K_VBUILD: u32 = 31; +const K_VCAPTURE: u32 = 33; +const K_VKILL_OF_TYPE: u32 = 37; +const K_VKILL_TYPE: u32 = 40; +const K_VRADIUS: u32 = 41; +const K_VPASS_X: u32 = 44; +const K_VPASS_Z: u32 = 46; +const K_VTIMER: u32 = 43; +const K_DCMDR: u32 = 14; +const K_DALL_KILLED: u32 = 6; +const K_DALL_OF_TYPE: u32 = 8; +const K_DTYPE: u32 = 16; +const K_DTIMER: u32 = 15; +const K_DPASS_X: u32 = 10; +const K_DPASS_Z: u32 = 12; +const K_NONE: u32 = 0xffff; +const KINDS: [u32; 18] = [ + K_VKILL_CMDR, K_VDESTROY_ALL, K_VKILL_MOBILE, K_VBUILD, K_VCAPTURE, K_VKILL_OF_TYPE, K_VKILL_TYPE, + K_VRADIUS, K_VPASS_X, K_VPASS_Z, K_VTIMER, K_DCMDR, K_DALL_KILLED, K_DALL_OF_TYPE, K_DTYPE, K_DTIMER, + K_DPASS_X, K_DPASS_Z, +]; + +#[inline(always)] +unsafe fn r8(a: u32) -> u32 { + read_unaligned(a as *const u8) as u32 +} +#[inline(always)] +unsafe fn r16(a: u32) -> u32 { + read_unaligned(a as *const u16) as u32 +} +#[inline(always)] +unsafe fn r32(a: u32) -> u32 { + read_unaligned(a as *const u32) +} +#[inline(always)] +unsafe fn w8(a: u32, v: u32) { + write_unaligned(a as *mut u8, v as u8) +} +#[inline(always)] +unsafe fn w16(a: u32, v: u32) { + write_unaligned(a as *mut u16, v as u16) +} +#[inline(always)] +unsafe fn w32(a: u32, v: u32) { + write_unaligned(a as *mut u32, v) +} +#[inline(always)] +unsafe fn rf(a: u32) -> f32 { + f32::from_bits(r32(a)) +} + +#[inline(always)] +unsafe fn game() -> u32 { + read_volatile(&raw const g_game) +} +#[inline(always)] +unsafe fn sg() -> u32 { + read_volatile(&raw const g_simGlobals) +} +#[inline(always)] +unsafe fn base() -> u32 { + read_volatile(&raw const g_blockBase) +} +#[inline(always)] +unsafe fn region() -> u32 { + read_volatile(&raw const g_region) +} +/// A block offset as an address; null stays null. +#[inline(always)] +unsafe fn rf_ref(off: u32) -> u32 { + if off == 0 { + 0 + } else { + base().wrapping_add(off) + } +} +#[inline(always)] +unsafe fn off_of(addr: u32) -> u32 { + if addr == 0 { + 0 + } else { + addr.wrapping_sub(base()) + } +} +#[inline(always)] +unsafe fn gr32(off: u32) -> u32 { + r32(game() + off) +} +#[inline(always)] +unsafe fn player(p: u32) -> u32 { + game() + PLAYERS + 331 * p +} +#[inline(always)] +unsafe fn info_of(p: u32) -> u32 { + rf_ref(r32(player(p) + P_INFO)) +} +/// Unit slot n of the unit table. +#[inline(always)] +unsafe fn unit_slot(n: u32) -> u32 { + rf_ref(gr32(UNITS)).wrapping_add(280u32.wrapping_mul(n)) +} +#[inline(always)] +unsafe fn plays(p: u32) -> bool { + let a = player(p); + let t = r8(a + P_TYPE); + r32(a + P_ACTIVE) != 0 && (t == 1 || t == 2 || t == 3) && r8(a + P_INDEX) != 10 +} +#[inline(always)] +unsafe fn still_in(p: u32) -> bool { + let a = player(p); + plays(p) && (r16(a + P_UCOUNT) != 0 || r32(a + P_UCREATED) == 0) +} +#[inline(always)] +unsafe fn info_flag40(p: u32) -> bool { + r8(info_of(p) + I_F9B) & 0x40 != 0 +} +unsafe fn count_ai() -> u32 { + let mut n = 0; + for p in 0..10 { + if still_in(p) && r8(player(p) + P_TYPE) == 2 { + n += 1; + } + } + n +} +unsafe fn count_combat() -> u32 { + let mut n = 0; + for p in 0..10 { + if still_in(p) { + let t = r8(player(p) + P_TYPE); + if (t == 1 || (t == 3 && r8(info_of(p) + I_KIND) == 1)) && !info_flag40(p) { + n += 1; + } + } + } + n +} +unsafe fn host_slot() -> u32 { + for p in 0..10 { + if r8(player(p) + P_TYPE) != 0 && r8(info_of(p) + I_F97) & 1 != 0 { + return p; + } + } + 10 +} + +// ---- the match's end and the countdown ---- + +#[inline(always)] +unsafe fn countdown() -> i32 { + read_unaligned(region() as *const i16) as i32 +} +#[inline(always)] +unsafe fn set_countdown(v: i32) { + w16(region(), v as u32) +} +unsafe fn end_match(v: u32) { + let f = r16(game() + END_FLAGS) | 4 | if v != 0 { 0x20 } else { 0x40 }; + w16(game() + END_FLAGS, f); + w8(game() + END_VICT, v); +} +unsafe fn advance(v: u32) { + let c = countdown(); + if c < 0 { + set_countdown(4); + } else { + set_countdown(c - 1); + if c - 1 < 0 { + end_match(v); + } + } +} + +// ---- conditions ---- + +unsafe fn class_of(c: u32) -> u32 { + let w = r32(c); + for &k in KINDS.iter() { + if r32(CLASS_TABLE + 4 * k) == w { + return k; + } + } + K_NONE +} + +unsafe fn celebrate(c: u32) { + if r32(c + C_CEL) == 0 { + let args = [0u32, 0u32]; + record_sim_event(2, 0, args.as_ptr(), 2); + w32(c + C_CEL, 1); + } +} + +unsafe fn lc(b: u32) -> u32 { + if (b'A' as u32..=b'Z' as u32).contains(&b) { + b + 32 + } else { + b + } +} +unsafe fn names_match(a: u32, b: u32) -> bool { + for i in 0..32 { + let x = lc(r8(a + i)); + let y = lc(r8(b + i)); + if x != y { + return false; + } + if x == 0 { + return true; + } + } + true +} + +/// Visits the units of a player's slice in table order, each one with a nonzero unitDefIndex, until `f` says stop. +unsafe fn scan bool>(p: u32, mut f: F) { + let pl = player(p); + let b = r32(pl + P_UBEGIN); + if b == 0 { + return; + } + let e = r32(pl + P_UEND); + let mut u = b; + while u <= e { + let ua = rf_ref(u); + if r16(ua + U_DEFIDX) != 0 && f(ua) { + break; + } + u = u.wrapping_add(280); + } +} + +unsafe fn can_be_counted(u: u32) -> bool { + if r32(u + U_FLAGS) & 0x20 == 0 { + return false; + } + if rf(u + U_BUILD_LEFT) != 0.0 { + return false; + } + if r32(u + U_HOLDOFF) != 0 { + return false; + } + let c = r32(u + U_CARRIER); + c == 0 || r32(rf_ref(c) + U_FLAGS) & 0x4000_0000 != 0 +} + +unsafe fn type_matches(u: u32, name: u32) -> bool { + r8(name) == 0 || names_match(name, rf_ref(r32(u + U_DEF)) + 32) +} + +unsafe fn commander_name(u: u32) -> u32 { + let pl = rf_ref(r32(u + U_PLAYER)); + let side = r8(rf_ref(r32(pl + P_INFO)) + I_SIDE); + game() + SIDEDEFS + 562u32.wrapping_mul(side) + 34 +} + +unsafe fn near(a: u32, b: u32) -> bool { + let d = (a as i32).wrapping_sub(b as i32); + d >= -2 && d <= 2 +} + +/// Whether the victory/defeat condition `c` of game type 1 is met. +unsafe fn met(c: u32) -> bool { + let k = class_of(c); + match k { + K_VDESTROY_ALL => { + let m = r16(game() + F1DF2) == 0; + if m { + celebrate(c); + } + m + } + K_VBUILD => { + if r32(c + C_SAT) == 0 { + if r16(c + 48) == 0 { + let id = find_unit_type_id(c + 16) as u32 & 0xffff; + w16(c + 48, id); + } + let id = r16(c + 48); + scan(0, |u| { + if r16(u + U_DEFIDX) == id && rf(u + U_BUILD_LEFT) == 0.0 { + w32(c + C_SAT, 1); + celebrate(c); + } + r32(c + C_SAT) != 0 + }); + } + r32(c + C_SAT) != 0 + } + K_VRADIUS => { + if r32(c + 48 + 4) == 0x1234_5678 { + clamp_world_pos_to_terrain(r32(c + 48) as i32, r32(c + 48 + 8) as i32, c + 48); + } + let mut ids = [0u16; 256]; + let mut skip = 0; + loop { + let n = units_in_range(c + 48, r32(c + 60) as i32, skip, ids.as_mut_ptr(), 256); + let cnt = if n < 0 { 0 } else if n > 256 { 256 } else { n as usize }; + for i in 0..cnt { + let u = unit_slot(ids[i] as u32); + if r8(u + U_PIDX) == 0 && type_matches(u, c + 16) && can_be_counted(u) { + w32(c + C_SAT, 1); + celebrate(c); + } + } + if n != 256 { + break; + } + skip += 256; + } + r32(c + C_SAT) != 0 + } + K_VPASS_X | K_VPASS_Z => { + if r32(c + C_SAT) == 0 { + let (co, tg) = if k == K_VPASS_X { (U_CELL, r32(c + 48)) } else { (U_CELL + 2, r32(c + 48)) }; + scan(0, |u| { + if type_matches(u, c + 16) && near(read_unaligned((u + co) as *const i16) as i32 as u32, tg) { + w32(c + C_SAT, 1); + celebrate(c); + return true; + } + false + }); + } + r32(c + C_SAT) != 0 + } + K_VTIMER | K_DTIMER => r32(game() + TICKS) >= r32(c + 12), + K_DALL_KILLED => { + let mut any = false; + scan(0, |u| { + if can_be_counted(u) { + any = true; + } + any + }); + w32(c + C_SAT, if any { 0 } else { 1 }); + !any + } + K_DPASS_X | K_DPASS_Z => { + if r32(c + C_SAT) == 0 { + let co = if k == K_DPASS_X { U_CELL } else { U_CELL + 2 }; + let tg = r32(c + 16); + scan(1, |u| { + if near(read_unaligned((u + co) as *const i16) as i32 as u32, tg) { + w32(c + C_SAT, 1); + return true; + } + false + }); + } + r32(c + C_SAT) != 0 + } + _ => r32(c + C_SAT) != 0, + } +} + +unsafe fn conds() -> u32 { + rf_ref(gr32(CONDS)) +} + +/// A victory check (`victory` true) or a defeat check. +unsafe fn check(victory: bool, l: u32) -> bool { + let cs = conds(); + if cs == 0 || r32(cs + MC_ACTIVE) == 0 { + return false; + } + let g = get_game_type(); + match g { + 1 => { + let (list, cnt) = if victory { (cs, cs + MC_VCOUNT) } else { (cs + MC_DEFEAT, cs + MC_DCOUNT) }; + if r32(cnt) == 0 { + if victory { + let a = sim_alloc(12); + w32(a, r32(CLASS_TABLE + 4 * 34)); + w32(list, off_of(a)); + } else { + let a = sim_alloc(16); + w32(a, r32(CLASS_TABLE + 4 * 6)); + w32(a + 12, r32(CLASS_TABLE + 4 * 7)); + w32(list, off_of(a)); + } + w32(cnt, 1); + } + let n = r32(cnt).min(16); + if victory { + for i in 0..n { + if !met(rf_ref(r32(list + 4 * i))) { + return false; + } + } + true + } else { + for i in 0..n { + if met(rf_ref(r32(list + 4 * i))) { + return true; + } + } + false + } + } + 2 | 3 => { + if !victory { + return r16(player(l) + P_UCOUNT) == 0; + } + if g == 2 { + let la = player(l); + for i in 0..10 { + if i != l && r8(la + P_ALLIED + i) == 0 && r16(player(i) + P_UCOUNT) != 0 { + return false; + } + } + true + } else { + allied_victory(l) + } + } + _ => false, + } +} + +unsafe fn allied_victory(l: u32) -> bool { + if r32(game() + CMD_DEATH) == 2 { + return false; + } + for i in 0..10 { + if i == l || !plays(i) || info_flag40(i) { + continue; + } + let pi = player(i); + if r32(pi + P_UCREATED) == 0 { + return false; + } + if r16(pi + P_UCOUNT) != 0 { + let la = player(l); + if r8(info_of(i) + I_F9D) & 2 == 0 + || r8(info_of(l) + I_F9D) & 2 == 0 + || r8(la + P_ALLIED + i) == 0 + || r8(la + P_ALLIED_BY + i) == 0 + { + return false; + } + for j in 0..10 { + if still_in(j) && r8(pi + P_ALLIED + j) == 0 { + return false; + } + } + } + } + true +} + +/// The died (`captured` false) or captured notice of the unit `u` to every condition. +unsafe fn notice(u: u32, captured: bool) { + let cs = conds(); + let vc = r32(cs + MC_VCOUNT).min(16); + let dc = r32(cs + MC_DCOUNT).min(16); + for i in 0..(vc + dc) { + let c = if i < vc { rf_ref(r32(cs + 4 * i)) } else { rf_ref(r32(cs + MC_DEFEAT + 4 * (i - vc))) }; + notice_one(c, u, captured); + } +} + +unsafe fn notice_one(c: u32, u: u32, captured: bool) { + let k = class_of(c); + let d = rf_ref(r32(u + U_DEF)); + let uname = d + 32; + let pidx = r8(u + U_PIDX); + if captured { + if k == K_VCAPTURE && pidx == 1 && names_match(c + 12, uname) { + w32(c + C_SAT, 1); + celebrate(c); + } + return; + } + match k { + K_VKILL_CMDR => { + if pidx == 1 && names_match(uname, commander_name(u)) { + w32(c + C_SAT, 1); + celebrate(c); + } + } + K_VKILL_MOBILE => { + if pidx == 1 && r32(u + U_MOTION) != 0 { + w32(c + 16, 0); + scan(1, |v| { + if r32(v + U_MOTION) != 0 { + w32(c + 16, r32(c + 16).wrapping_add(1)); + } + (r32(c + 16) as i32) > 1 + }); + if (r32(c + 16) as i32) <= 1 { + w32(c + C_SAT, 1); + celebrate(c); + } + } + } + K_VKILL_OF_TYPE => { + if r32(c + C_SAT) == 0 && pidx == 1 && names_match(c + 16, uname) { + let id = find_unit_type_id(c + 16) as u32 & 0xffff; + w16(c + 48, id); + w32(c + 50, 0); + scan(1, |v| { + if r16(v + U_DEFIDX) == id { + w32(c + 50, r32(c + 50).wrapping_add(1)); + } + (r32(c + 50) as i32) > 1 + }); + if (r32(c + 50) as i32) <= 1 { + w32(c + C_SAT, 1); + celebrate(c); + } + } + } + K_VKILL_TYPE => { + if (r32(c + 44) as i32) > 0 && pidx == 1 && names_match(c + 12, uname) { + let n = (r32(c + 44) as i32).wrapping_sub(1); + w32(c + 44, n as u32); + if n <= 0 { + w32(c + C_SAT, 1); + celebrate(c); + } + } + } + K_DCMDR => { + if pidx == 0 && names_match(uname, commander_name(u)) { + w32(c + C_SAT, 1); + } + } + K_DTYPE => { + if names_match(c + 12, uname) { + let n = (r32(c + 44) as i32).wrapping_sub(1); + w32(c + 44, n as u32); + if n <= 0 { + w32(c + C_SAT, 1); + } + } + } + K_DALL_OF_TYPE => { + if names_match(c + 16, uname) { + let id = find_unit_type_id(c + 16) as u32 & 0xffff; + w16(c + 48, id); + w32(c + 50, 0); + for p in 0..2 { + scan(p, |v| { + if r16(v + U_DEFIDX) == id { + w32(c + 50, r32(c + 50).wrapping_add(1)); + } + (r32(c + 50) as i32) > 1 + }); + } + if (r32(c + 50) as i32) <= 1 { + w32(c + C_SAT, 1); + } + } + } + _ => {} + } +} + +// ---- effects ---- + +unsafe fn emit_recalculate() { + let e = [133u32, 1]; + emit(e.as_ptr(), 8); +} + +unsafe fn emit_income(player: u32, unit: u32, resources: u32, energy: f32, metal: f32) { + let e = [4u32, player, unit, resources, energy.to_bits(), metal.to_bits()]; + emit(e.as_ptr(), 24); +} + +// ---- the rank pass ---- + +unsafe fn counted_for_rank(p: u32) -> bool { + let a = player(p); + plays(p) && !(r16(a + P_UCOUNT) == 0 && r32(a + P_UCREATED) != 0) && !info_flag40(p) +} + +unsafe fn rank_pass() { + let n = r16(game() + NUM_PLAYERS); + for i in 0..n { + let mut held = false; + for p in 0..10 { + if counted_for_rank(p) && r8(player(p) + P_RANK) == i { + held = true; + break; + } + } + if !held { + for p in 0..10 { + if counted_for_rank(p) { + let a = player(p) + P_RANK; + let r = r8(a); + if r > i { + w8(a, r - 1); + } + } + } + } + } +} + +// ---- the per-player update ---- + +unsafe fn watch_mode(l: u32) { + let g2 = get_game_type(); + let h = host_slot(); + let la = player(l); + let ai = count_ai(); + let w = g2 == 3 && r8(la + P_REJECT) == 0 && (r8(info_of(h) + I_F9B) & 0x80 != 0 || ai != 0); + if w { + let ia = info_of(l) + I_F9B; + w8(ia, r8(ia) | 0x40); + w16(game() + MAP_FLAGS, r16(game() + MAP_FLAGS) & !3); + emit_recalculate(); + broadcast_player_info(); + if ai == 0 { + let a = [l]; + record_sim_event(25, 0, a.as_ptr(), 1); + } else if count_combat() != 0 { + let a = [l]; + record_sim_event(26, 0, a.as_ptr(), 1); + w8(game() + END_VICT, 0); + } + } else { + let mut f = r16(game() + END_FLAGS) | 4; + if r8(la + P_REJECT) == 0 { + f |= 0x40; + } + w16(game() + END_FLAGS, f); + w8(game() + END_VICT, 0); + } +} + +unsafe fn respawn(l: u32) { + let h = host_slot(); + let hinfo = info_of(h); + let s = r8(info_of(l) + I_SIDE); + let t = find_unit_type_id(game() + SIDEDEFS + 562u32.wrapping_mul(s) + 34) as u32 & 0xffff; + let d = rf_ref(gr32(DEFS)).wrapping_add(585u32.wrapping_mul(t)); + let bx = gr32(BASE_X) as i32; + let by = gr32(BASE_Y) as i32; + let cx = bx / 10; + let cz = by / 10; + let hh = gr32(HEIGHT).wrapping_mul(65536); + let hw = gr32(WIDTH).wrapping_mul(65536); + let sea = r8(game() + SEA) as i32; + let mut pos = [0u32; 3]; + let mut tries = 0; + while tries < 9999 { + tries += 1; + let a = random_int(bx.wrapping_sub(cx.wrapping_mul(2))); + let b = random_int(by.wrapping_sub(cz.wrapping_mul(2))); + pos[0] = (a.wrapping_add(cx) as u32).wrapping_mul(65536); + pos[1] = 0; + pos[2] = (b.wrapping_add(cz) as u32).wrapping_mul(65536); + let mut ok = 0; + let mut z = pos[2].wrapping_sub(hh); + for _ in 0..3 { + let mut x = pos[0].wrapping_sub(hw); + for _ in 0..3 { + let cell = [((x >> 20) & 0xffff) | (((z >> 20) & 0xffff) << 16)]; + if can_place_unit_footprint(d, 0, cell.as_ptr(), 1) != 0 { + ok += 1; + } + x = x.wrapping_add(hw); + } + z = z.wrapping_add(hh); + } + if ok == 9 && (find_feature_at_pos(pos.as_ptr(), 0, 0) as u32 & 0xffff) == 0xffff { + let mut mp = [0u32; 31]; + get_mission_params(mp.as_mut_ptr()); + if mp[5] == 0 || get_cell_mean_height(pos.as_ptr()) > sea { + break; + } + } + } + let u = create_unit(l as i32, t as i32, pos.as_ptr(), 1, 1, 0); + let la = player(l); + w16(la + P_FLAGS, r16(la + P_FLAGS) | 1); + let he = r16(hinfo + I_ENERGY) as i32; + let hm = r16(hinfo + I_METAL) as i32; + let eb = (he * 100).max(200); + let mb = (hm * 100).max(200); + w32(la + P_ESB, (eb as f32).to_bits()); + w32(la + P_MSB, (mb as f32).to_bits()); + if u != 0 { + let pi = r8(u + U_PIDX); + let uo = off_of(u); + emit_income(pi, uo, 1, (he as f32) * 100.0, 0.0); + emit_income(pi, uo, 2, 0.0, (hm as f32) * 100.0); + emit_recalculate(); + let a = [1u32]; + record_sim_event(19, 0, a.as_ptr(), 1); + } +} + +#[no_mangle] +pub unsafe extern "C" fn UpdatePlayerHead(player: i32) -> i32 { + let p = player as u32 & 0xff; + (p < 10 && plays(p)) as i32 +} + +#[no_mangle] +pub unsafe extern "C" fn UpdatePlayerBody(player: i32, _stream: i32) -> i32 { + let p = player as u32 & 0xff; + if p > 9 { + return 0; + } + let clk = region() + 4 + 4 * p; + if r32(clk) > r32(game() + TICKS) { + return 0; + } + w32(clk, r32(clk).wrapping_add(30)); + let l = r8(game() + LOCAL); + if p == l { + let g = get_game_type(); + if g == 1 { + if check(true, l) { + advance(1); + } else if check(false, l) { + advance(0); + } + } else if r32(player_addr(l) + P_ACTIVE) != 0 && info_flag40(l) { + if check(true, l) { + advance(1); + } + } else if !check(false, l) { + if check(true, l) { + advance(1); + } + } else { + let c = countdown(); + if c < 0 { + set_countdown(4); + } else if c >= 1 { + set_countdown(c - 1); + } else { + set_countdown(-1); + if r32(game() + CMD_DEATH) == 2 { + respawn(l); + } else { + watch_mode(l); + } + } + } + } + if still_in(p) && matches!(r8(player_addr(p) + P_TYPE), 1 | 2) && r16(game() + END_FLAGS) & 4 == 0 && countdown() < 0 { + 2 + } else { + 1 + } +} + +#[inline(always)] +unsafe fn player_addr(p: u32) -> u32 { + player(p) +} + +#[no_mangle] +pub unsafe extern "C" fn UpdatePlayerTail(player: i32) { + let p = player as u32 & 0xff; + if p == r8(game() + PINDEX) && get_game_type() == 3 { + let a = sg() + ECON_TICK; + let v = r32(a).wrapping_add(1); + w32(a, v); + if v & 3 == 0 { + broadcast_player_economy(player_addr(p)); + } + } +} + +#[no_mangle] +pub unsafe extern "C" fn UpdatePlayersFinish() { + if r32(sg() + RANK_QUIRK) != 0 { + rank_pass(); + } + if get_game_type() == 3 && r32(game() + CMD_DEATH) != 2 && count_combat() == 0 { + advance(0); + } +} + +#[no_mangle] +pub unsafe extern "C" fn DeactivateConditions(conditions: u32) { + if conditions != 0 { + w32(conditions + MC_ACTIVE, 0); + } +} + +#[no_mangle] +pub unsafe extern "C" fn RegionSize(_info: u32) -> i32 { + 84 +} + +#[no_mangle] +pub unsafe extern "C" fn Init(_info: u32, region: u32, _size: i32) { + w16(region, 0xffff); +} + +#[no_mangle] +pub unsafe extern "C" fn Shutdown() -> u32 { + // A volatile read of a function pointer keeps the table import and the element segment of ABI 9.1. + let f = read_volatile(&raw const KEEP_TABLE); + let _ = f; + region() +} + +static KEEP_TABLE: [unsafe extern "C" fn(); 1] = [UpdatePlayers]; + +// ---- the pass ---- + +unsafe fn pass(stream: i32) { + pathfinding_step(); + let mut pts = [0u32; 64]; + loop { + let mut ev = [0u32; 7]; + let n = pathfinding_poll(ev.as_mut_ptr(), 28, pts.as_mut_ptr(), 64); + if n < 20 { + break; + } + apply_path_event(ev.as_ptr(), if n > 28 { 28 } else { n }, pts.as_ptr()); + } + for p in 0..10u32 { + sched_pass_deliver(4); + if UpdatePlayerHead(p as i32) == 0 { + continue; + } + sched_pass_deliver(10); + update_squads(p as i32); + sched_pass_deliver(11); + refresh_unit_index(p as i32); + sched_pass_deliver(2); + refresh_factory_index(p as i32); + sched_pass_deliver(10); + update_player_ai(p as i32); + let b = r32(player(p) + P_UBEGIN); + if b != 0 { + let mut u = b; + while u <= r32(player(p) + P_UEND) { + let ua = rf_ref(u); + if r32(ua + U_FLAGS) & 0x1000_0000 != 0 { + sched_pass_deliver(11); + update_unit_line_of_sight(ua); + } + u = u.wrapping_add(280); + } + } + if p == r8(game() + PINDEX) { + sched_pass_deliver(11); + record_radar_units(); + } + sched_pass_deliver(4); + let bd = UpdatePlayerBody(p as i32, stream); + if bd == 0 { + continue; + } + if bd == 2 { + sched_pass_deliver(1); + update_player_economy(p as i32); + } + if p == r8(game() + PINDEX) { + sched_pass_deliver(11); + update_sensor_radar_and_cloak(); + sched_pass_deliver(11); + record_radar_mapped(); + } + sched_pass_deliver(4); + UpdatePlayerTail(p as i32); + } + sched_pass_deliver(4); + UpdatePlayersFinish(); +} + +#[no_mangle] +pub unsafe extern "C" fn UpdatePlayers() { + pass(0); +} + +#[no_mangle] +pub unsafe extern "C" fn UpdatePlayersOnStream(stream: i32) { + pass(stream); +} + +// ---- Apply ---- + +fn event_size(kind: u32) -> u32 { + match kind { + 192 => 48, + 193 => 12, + 196 => 28, + 197 => 24, + 198 => 16, + 199 => 12, + 201 => 16, + 203 | 204 => 12, + _ => 8, + } +} + +#[no_mangle] +pub unsafe extern "C" fn Apply(event: u32, size: u32) -> i32 { + if size < 8 { + return 0; + } + let kind = r32(event); + if size < event_size(kind) { + return 0; + } + let u = rf_ref(r32(event + 4)); + let cs = conds(); + match kind { + 192 => { + let r = r32(event + 8); + if u == 0 || r > 9 || cs == 0 { + return 0; + } + give_unit(event, u, r) + } + 193 => { + let k = r32(event + 8); + if k > 10 { + return 0; + } + kill_units(k); + 1 + } + 194 => (u != 0 && cs != 0) as i32, + 195 => { + if u == 0 || cs == 0 { + return 0; + } + notice(u, false); + 1 + } + 196 => transfer(event), + 197 => { + let p = r32(event + 8); + let res = r32(event + 12); + if p > 9 || res > 1 { + return 0; + } + let a = player(p) + if res == 0 { P_ENERGY } else { P_METAL }; + let amount = rf(event + 20); + if r32(event + 16) == 0 { + w32(a, amount.to_bits()); + } else { + w32(a, (rf(a) + amount).to_bits()); + } + 1 + } + 198 => { + let p = r32(event + 8); + if p > 9 { + return 0; + } + let t = r32(event + 12); + w8(player(p) + P_TYPE, t); + if t != 3 { + w8(info_of(p) + I_KIND, t); + } + 1 + } + 199 => { + let v = r32(event + 8); + if v > 1 { + return 0; + } + end_match(v); + 1 + } + 200 => { + if cs == 0 { + return 0; + } + w32(cs + MC_ACTIVE, 0); + 1 + } + 201 => { + let clear = r32(event + 8); + let set = r32(event + 12); + if (clear | set) & !0x788 != 0 { + return 0; + } + let a = game() + UI_OPT; + w16(a, (r16(a) & !clear) | set); + 1 + } + 202 => { + w16(game() + END_FLAGS, r16(game() + END_FLAGS) | 4); + 1 + } + 203 | 204 => { + let p = r32(event + 8); + if p > 9 || !plays(p) { + return 0; + } + if kind == 203 { + w8(game() + LOCAL, p); + } + w8(game() + PINDEX, p); + 1 + } + 205 => { + if r32(sg() + RANK_QUIRK) != 0 { + return 0; + } + rank_pass(); + 1 + } + _ => 0, + } +} + +unsafe fn give_unit(event: u32, u: u32, r: u32) -> i32 { + let o = rf_ref(r32(u + U_PLAYER)); + let ra = player(r); + if o == ra { + return 0; + } + let fl = r32(u + U_FLAGS); + if fl & 0x1000_0000 == 0 || fl & 0x4000 != 0 { + return 0; + } + let o_plays = r32(o + P_ACTIVE) != 0 && matches!(r8(o + P_TYPE), 1 | 2); + let r_active = r32(ra + P_ACTIVE) != 0; + let rt = r8(ra + P_TYPE); + notice(u, true); + let uo = off_of(u); + if o_plays && !r_active { + 0 + } else if o_plays && rt == 3 { + let e = [209u32, uo, r]; + emit(e.as_ptr(), 12); + 1 + } else if !r_active || !(rt == 1 || rt == 2) { + 0 + } else { + let mut e = [0u32; 12]; + e[0] = 210; + e[1] = uo; + e[2] = r; + for i in 0..9 { + e[3 + i] = r32(event + 12 + 4 * i as u32); + } + emit(e.as_ptr(), 48); + 1 + } +} + +unsafe fn kill_units(k: u32) { + let pa = player(k); + if r16(pa + P_UCOUNT) == 0 { + return; + } + let b = r32(pa + P_UBEGIN); + if b == 0 { + return; + } + let e = r32(pa + P_UEND); + let mut u = b; + while u <= e { + let ua = rf_ref(u); + let fl = r32(ua + U_FLAGS); + if fl & 0x1000_0000 != 0 && fl & 0x4000 == 0 { + let up = rf_ref(r32(ua + U_PLAYER)); + let self_destruct = if r32(up + P_ACTIVE) != 0 && matches!(r8(up + P_TYPE), 1 | 2) { 0 } else { 1 }; + let ev = [208u32, u, self_destruct]; + emit(ev.as_ptr(), 12); + } + u = u.wrapping_add(280); + } +} + +unsafe fn transfer(event: u32) -> i32 { + let f = r32(event + 8); + let t = r32(event + 12); + let res = r32(event + 16); + let mut a = rf(event + 20); + let n = r32(event + 24); + if f > 10 || t > 10 || res > 1 { + return 0; + } + if f == 10 || t == 10 { + return 0; + } + let (resources, e, m); + if n != 0 { + let store = rf(player(f) + if res == 0 { P_ENERGY } else { P_METAL }); + if a > store { + a = store; + } + if a == 0.0 { + return 0; + } + } else if a == 0.0 { + return 0; + } + if res == 0 { + resources = 1; + e = a; + m = 0.0; + } else { + resources = 2; + e = 0.0; + m = a; + } + if n != 0 { + let sp = [3u32, f, 0, resources, e.to_bits(), m.to_bits()]; + economy_spend(sp.as_ptr()); + emit_income(t, 0, resources, e, m); + if res == 0 { + send_share_metal(f as i32, t as i32, a); + } else { + send_share_energy(f as i32, t as i32, a); + } + } else { + emit_income(t, 0, resources, e, m); + } + 1 +} From 057d66083ea0e5df7c690e8e91bfbaf85cc963e4 Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 12:53:29 +0000 Subject: [PATCH 09/13] Docs: Add players implementation notes Assisted-by: Claude Code:claude-sonnet-5-5 --- players/IMPLEMENTATION-NOTES.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 players/IMPLEMENTATION-NOTES.md diff --git a/players/IMPLEMENTATION-NOTES.md b/players/IMPLEMENTATION-NOTES.md new file mode 100644 index 0000000..d01147f --- /dev/null +++ b/players/IMPLEMENTATION-NOTES.md @@ -0,0 +1,22 @@ +# players implementation notes + +## What was built +`players/` is a `no_std` Rust cdylib (`src/lib.rs`), built by `build.sh`: +- `ld-wrap.sh` (the same linker wrapper as wind_meteors') drops rustc's `--stack-first`, `--allow-undefined`, `__heap_base` and `__data_end`. +- Link options: data base 524288, table base 368, stack 4096. The stack falls after the data, inside the window (top 528528). +- Fuel: `/data/tools/wasm_fuel.py` runs on the linked module (rule v1); `--check` passes. +- All eleven exports and the five data words follow the manifest entry; imports are exactly the entry's list. +- All block access is unaligned raw loads and stores at the offsets of `layout.json`. The module has no statics beyond the five data words and a one-entry function-pointer table that keeps the `env.__indirect_function_table` import (read volatile in `Shutdown`). +- Buffers (path event 28 bytes, 64 waypoints, 256 unit ids, mission params) are on the stack, about 1 KiB at the deepest. +- The module is 15242 bytes. The entry is `blocked`, so there is no size or fuel budget to meet. + +## Verdicts, in order +1. req1: `equal` on all 11 recordings (`budgets: not_judged`, scenarios not judged: the entry is blocked). + +## Unclear or open points in the spec and kit +- A radius condition (`VictoryMoveUnitToRadius`) already satisfied: the spec states the clamp and the `UnitsInRange` walk without a `satisfied == 0` guard (unlike the passes and build classes), so the module repeats them on every check. No recording shows it. +- A scan of a slice whose `unitsBegin` is null is not defined; the module visits nothing. +- The condition count is capped at 16 where the lists are walked (the spec says "at most 16"). +- `PLAYERS_KILL_UNITS` is specified to test only alive and dying flags, not `unitDefIndex`; implemented as written. +- Everything the spec lists under "Not covered by any recording" (respawn, watch mode, rank pass, cheats, SEND_UNIT, unannounced transfer, etc.) is implemented from the text alone and unverified by the gate. +- `docs/module-abi.md` §3.1 asks for `--no-stack-first`; the local wasm-ld (20.1.8) doesn't list it, so the wrapper only adds it when the help does. The resulting layout (stack after data) was checked by hand. From 0ad113017c43a19384d96196091f4a98f20e359b Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 13:39:39 +0000 Subject: [PATCH 10/13] Fix: Answer the players code review Assisted-by: Claude Code:claude-sonnet-5-5 --- players/IMPLEMENTATION-NOTES.md | 13 +++++- players/src/lib.rs | 76 +++++++++++++++++++-------------- 2 files changed, 56 insertions(+), 33 deletions(-) diff --git a/players/IMPLEMENTATION-NOTES.md b/players/IMPLEMENTATION-NOTES.md index d01147f..77fe4e1 100644 --- a/players/IMPLEMENTATION-NOTES.md +++ b/players/IMPLEMENTATION-NOTES.md @@ -3,7 +3,7 @@ ## What was built `players/` is a `no_std` Rust cdylib (`src/lib.rs`), built by `build.sh`: - `ld-wrap.sh` (the same linker wrapper as wind_meteors') drops rustc's `--stack-first`, `--allow-undefined`, `__heap_base` and `__data_end`. -- Link options: data base 524288, table base 368, stack 4096. The stack falls after the data, inside the window (top 528528). +- Link options: data base 524288, table base 368, stack 4096. The stack falls after the data, inside the window (top 528544). - Fuel: `/data/tools/wasm_fuel.py` runs on the linked module (rule v1); `--check` passes. - All eleven exports and the five data words follow the manifest entry; imports are exactly the entry's list. - All block access is unaligned raw loads and stores at the offsets of `layout.json`. The module has no statics beyond the five data words and a one-entry function-pointer table that keeps the `env.__indirect_function_table` import (read volatile in `Shutdown`). @@ -11,7 +11,8 @@ - The module is 15242 bytes. The entry is `blocked`, so there is no size or fuel budget to meet. ## Verdicts, in order -1. req1: `equal` on all 11 recordings (`budgets: not_judged`, scenarios not judged: the entry is blocked). +1. req1 (first session): `equal` on all 11 recordings (`budgets: not_judged`, scenarios not judged: the entry is blocked). +2. req1 (after the review fixes, 15245 bytes; the mailbox restarted at req1): `equal` on all 11 recordings. ## Unclear or open points in the spec and kit - A radius condition (`VictoryMoveUnitToRadius`) already satisfied: the spec states the clamp and the `UnitsInRange` walk without a `satisfied == 0` guard (unlike the passes and build classes), so the module repeats them on every check. No recording shows it. @@ -20,3 +21,11 @@ - `PLAYERS_KILL_UNITS` is specified to test only alive and dying flags, not `unitDefIndex`; implemented as written. - Everything the spec lists under "Not covered by any recording" (respawn, watch mode, rank pass, cheats, SEND_UNIT, unannounced transfer, etc.) is implemented from the text alone and unverified by the gate. - `docs/module-abi.md` §3.1 asks for `--no-stack-first`; the local wasm-ld (20.1.8) doesn't list it, so the wrapper only adds it when the help does. The resulting layout (stack after data) was checked by hand. + +## Answers to /srv/inbox/review.md +1. Null `info`: reads give 0 and writes are skipped (`info8`, and guards in SET_TYPE, watch mode and the respawn's host figures). The spec defines no null case; this keeps the module off address 0. +2. A null `services.SimAlloc` result: the check returns 0 and stores nothing. +3. `Apply`'s size is read as `i32`; a negative size is refused like a size below 8. +4. The slice walks stop when `u + 280` would wrap. +5. `event_size` has arms for 208, 209 (12) and 210 (48); `player_addr` is removed. +6. The stack top is 528544 (notes corrected). The wrapper adds `--no-stack-first` when the linker lists it; not run against 22.1.8 here. diff --git a/players/src/lib.rs b/players/src/lib.rs index de5c686..e7cae86 100644 --- a/players/src/lib.rs +++ b/players/src/lib.rs @@ -285,6 +285,11 @@ unsafe fn player(p: u32) -> u32 { unsafe fn info_of(p: u32) -> u32 { rf_ref(r32(player(p) + P_INFO)) } +/// A byte of player p's info; 0 when the info is null. +unsafe fn info8(p: u32, off: u32) -> u32 { + let i = info_of(p); + if i == 0 { 0 } else { r8(i + off) } +} /// Unit slot n of the unit table. #[inline(always)] unsafe fn unit_slot(n: u32) -> u32 { @@ -303,7 +308,7 @@ unsafe fn still_in(p: u32) -> bool { } #[inline(always)] unsafe fn info_flag40(p: u32) -> bool { - r8(info_of(p) + I_F9B) & 0x40 != 0 + info8(p, I_F9B) & 0x40 != 0 } unsafe fn count_ai() -> u32 { let mut n = 0; @@ -319,7 +324,7 @@ unsafe fn count_combat() -> u32 { for p in 0..10 { if still_in(p) { let t = r8(player(p) + P_TYPE); - if (t == 1 || (t == 3 && r8(info_of(p) + I_KIND) == 1)) && !info_flag40(p) { + if (t == 1 || (t == 3 && info8(p, I_KIND) == 1)) && !info_flag40(p) { n += 1; } } @@ -328,7 +333,7 @@ unsafe fn count_combat() -> u32 { } unsafe fn host_slot() -> u32 { for p in 0..10 { - if r8(player(p) + P_TYPE) != 0 && r8(info_of(p) + I_F97) & 1 != 0 { + if r8(player(p) + P_TYPE) != 0 && info8(p, I_F97) & 1 != 0 { return p; } } @@ -412,7 +417,7 @@ unsafe fn scan bool>(p: u32, mut f: F) { } let e = r32(pl + P_UEND); let mut u = b; - while u <= e { + while u <= e && u.wrapping_add(280) > u { let ua = rf_ref(u); if r16(ua + U_DEFIDX) != 0 && f(ua) { break; @@ -562,10 +567,16 @@ unsafe fn check(victory: bool, l: u32) -> bool { if r32(cnt) == 0 { if victory { let a = sim_alloc(12); + if a == 0 { + return false; + } w32(a, r32(CLASS_TABLE + 4 * 34)); w32(list, off_of(a)); } else { let a = sim_alloc(16); + if a == 0 { + return false; + } w32(a, r32(CLASS_TABLE + 4 * 6)); w32(a + 12, r32(CLASS_TABLE + 4 * 7)); w32(list, off_of(a)); @@ -623,8 +634,8 @@ unsafe fn allied_victory(l: u32) -> bool { } if r16(pi + P_UCOUNT) != 0 { let la = player(l); - if r8(info_of(i) + I_F9D) & 2 == 0 - || r8(info_of(l) + I_F9D) & 2 == 0 + if info8(i, I_F9D) & 2 == 0 + || info8(l, I_F9D) & 2 == 0 || r8(la + P_ALLIED + i) == 0 || r8(la + P_ALLIED_BY + i) == 0 { @@ -798,10 +809,12 @@ unsafe fn watch_mode(l: u32) { let h = host_slot(); let la = player(l); let ai = count_ai(); - let w = g2 == 3 && r8(la + P_REJECT) == 0 && (r8(info_of(h) + I_F9B) & 0x80 != 0 || ai != 0); + let w = g2 == 3 && r8(la + P_REJECT) == 0 && (info8(h, I_F9B) & 0x80 != 0 || ai != 0); if w { - let ia = info_of(l) + I_F9B; - w8(ia, r8(ia) | 0x40); + let il = info_of(l); + if il != 0 { + w8(il + I_F9B, r8(il + I_F9B) | 0x40); + } w16(game() + MAP_FLAGS, r16(game() + MAP_FLAGS) & !3); emit_recalculate(); broadcast_player_info(); @@ -826,7 +839,7 @@ unsafe fn watch_mode(l: u32) { unsafe fn respawn(l: u32) { let h = host_slot(); let hinfo = info_of(h); - let s = r8(info_of(l) + I_SIDE); + let s = info8(l, I_SIDE); let t = find_unit_type_id(game() + SIDEDEFS + 562u32.wrapping_mul(s) + 34) as u32 & 0xffff; let d = rf_ref(gr32(DEFS)).wrapping_add(585u32.wrapping_mul(t)); let bx = gr32(BASE_X) as i32; @@ -869,8 +882,8 @@ unsafe fn respawn(l: u32) { let u = create_unit(l as i32, t as i32, pos.as_ptr(), 1, 1, 0); let la = player(l); w16(la + P_FLAGS, r16(la + P_FLAGS) | 1); - let he = r16(hinfo + I_ENERGY) as i32; - let hm = r16(hinfo + I_METAL) as i32; + let he = if hinfo == 0 { 0 } else { r16(hinfo + I_ENERGY) } as i32; + let hm = if hinfo == 0 { 0 } else { r16(hinfo + I_METAL) } as i32; let eb = (he * 100).max(200); let mb = (hm * 100).max(200); w32(la + P_ESB, (eb as f32).to_bits()); @@ -887,14 +900,14 @@ unsafe fn respawn(l: u32) { } #[no_mangle] -pub unsafe extern "C" fn UpdatePlayerHead(player: i32) -> i32 { - let p = player as u32 & 0xff; +pub unsafe extern "C" fn UpdatePlayerHead(pl: i32) -> i32 { + let p = pl as u32 & 0xff; (p < 10 && plays(p)) as i32 } #[no_mangle] -pub unsafe extern "C" fn UpdatePlayerBody(player: i32, _stream: i32) -> i32 { - let p = player as u32 & 0xff; +pub unsafe extern "C" fn UpdatePlayerBody(pl: i32, _stream: i32) -> i32 { + let p = pl as u32 & 0xff; if p > 9 { return 0; } @@ -912,7 +925,7 @@ pub unsafe extern "C" fn UpdatePlayerBody(player: i32, _stream: i32) -> i32 { } else if check(false, l) { advance(0); } - } else if r32(player_addr(l) + P_ACTIVE) != 0 && info_flag40(l) { + } else if r32(player(l) + P_ACTIVE) != 0 && info_flag40(l) { if check(true, l) { advance(1); } @@ -936,27 +949,22 @@ pub unsafe extern "C" fn UpdatePlayerBody(player: i32, _stream: i32) -> i32 { } } } - if still_in(p) && matches!(r8(player_addr(p) + P_TYPE), 1 | 2) && r16(game() + END_FLAGS) & 4 == 0 && countdown() < 0 { + if still_in(p) && matches!(r8(player(p) + P_TYPE), 1 | 2) && r16(game() + END_FLAGS) & 4 == 0 && countdown() < 0 { 2 } else { 1 } } -#[inline(always)] -unsafe fn player_addr(p: u32) -> u32 { - player(p) -} - #[no_mangle] -pub unsafe extern "C" fn UpdatePlayerTail(player: i32) { - let p = player as u32 & 0xff; +pub unsafe extern "C" fn UpdatePlayerTail(pl: i32) { + let p = pl as u32 & 0xff; if p == r8(game() + PINDEX) && get_game_type() == 3 { let a = sg() + ECON_TICK; let v = r32(a).wrapping_add(1); w32(a, v); if v & 3 == 0 { - broadcast_player_economy(player_addr(p)); + broadcast_player_economy(player(p)); } } } @@ -1027,7 +1035,7 @@ unsafe fn pass(stream: i32) { let b = r32(player(p) + P_UBEGIN); if b != 0 { let mut u = b; - while u <= r32(player(p) + P_UEND) { + while u <= r32(player(p) + P_UEND) && u.wrapping_add(280) > u { let ua = rf_ref(u); if r32(ua + U_FLAGS) & 0x1000_0000 != 0 { sched_pass_deliver(11); @@ -1084,13 +1092,16 @@ fn event_size(kind: u32) -> u32 { 199 => 12, 201 => 16, 203 | 204 => 12, + 208 | 209 => 12, + 210 => 48, _ => 8, } } #[no_mangle] -pub unsafe extern "C" fn Apply(event: u32, size: u32) -> i32 { - if size < 8 { +pub unsafe extern "C" fn Apply(event: u32, size: i32) -> i32 { + let size = size as u32; + if size < 8 || size > 0x7fff_ffff { return 0; } let kind = r32(event); @@ -1147,7 +1158,10 @@ pub unsafe extern "C" fn Apply(event: u32, size: u32) -> i32 { let t = r32(event + 12); w8(player(p) + P_TYPE, t); if t != 3 { - w8(info_of(p) + I_KIND, t); + let ip = info_of(p); + if ip != 0 { + w8(ip + I_KIND, t); + } } 1 } @@ -1249,7 +1263,7 @@ unsafe fn kill_units(k: u32) { } let e = r32(pa + P_UEND); let mut u = b; - while u <= e { + while u <= e && u.wrapping_add(280) > u { let ua = rf_ref(u); let fl = r32(ua + U_FLAGS); if fl & 0x1000_0000 != 0 && fl & 0x4000 == 0 { From 8f540805a652b6054a2ac17d190d6c2e99250310 Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 14:03:11 +0000 Subject: [PATCH 11/13] Fix: Guard null names in condition notices Assisted-by: Claude Code:claude-sonnet-5-5 --- players/IMPLEMENTATION-NOTES.md | 7 +++++-- players/build.sh | 2 +- players/src/lib.rs | 29 ++++++++++++++++++++++++----- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/players/IMPLEMENTATION-NOTES.md b/players/IMPLEMENTATION-NOTES.md index 77fe4e1..db12c06 100644 --- a/players/IMPLEMENTATION-NOTES.md +++ b/players/IMPLEMENTATION-NOTES.md @@ -8,7 +8,7 @@ - All eleven exports and the five data words follow the manifest entry; imports are exactly the entry's list. - All block access is unaligned raw loads and stores at the offsets of `layout.json`. The module has no statics beyond the five data words and a one-entry function-pointer table that keeps the `env.__indirect_function_table` import (read volatile in `Shutdown`). - Buffers (path event 28 bytes, 64 waypoints, 256 unit ids, mission params) are on the stack, about 1 KiB at the deepest. -- The module is 15242 bytes. The entry is `blocked`, so there is no size or fuel budget to meet. +- The module is 15283 bytes. The entry is `blocked`, so there is no size or fuel budget to meet. ## Verdicts, in order 1. req1 (first session): `equal` on all 11 recordings (`budgets: not_judged`, scenarios not judged: the entry is blocked). @@ -23,9 +23,12 @@ - `docs/module-abi.md` §3.1 asks for `--no-stack-first`; the local wasm-ld (20.1.8) doesn't list it, so the wrapper only adds it when the help does. The resulting layout (stack after data) was checked by hand. ## Answers to /srv/inbox/review.md -1. Null `info`: reads give 0 and writes are skipped (`info8`, and guards in SET_TYPE, watch mode and the respawn's host figures). The spec defines no null case; this keeps the module off address 0. +1. Null `info`: reads give 0 and writes are skipped (`info8`, and guards in SET_TYPE, watch mode and the respawn's host figures). A second review found `commander_name` and the unit-type name unguarded: both now return 0 (null player, info or def, or a side of 5 or more), and a name match against 0 is false. The spec defines no null case; this keeps the module off address 0. 2. A null `services.SimAlloc` result: the check returns 0 and stores nothing. 3. `Apply`'s size is read as `i32`; a negative size is refused like a size below 8. 4. The slice walks stop when `u + 280` would wrap. 5. `event_size` has arms for 208, 209 (12) and 210 (48); `player_addr` is removed. 6. The stack top is 528544 (notes corrected). The wrapper adds `--no-stack-first` when the linker lists it; not run against 22.1.8 here. + +## Second review (findings 1-6) +1-3: fixed as above; notes corrected. 4: `tg` read once. 5: left as is (the defeat and victory rules differ per class; the repetition is small). 6: `build.sh` quotes the linker path; `--no-stack-first` is added when the local wasm-ld lists it (20.1.8 doesn't; 22.1.8 does). diff --git a/players/build.sh b/players/build.sh index a62e04a..a3adf1a 100755 --- a/players/build.sh +++ b/players/build.sh @@ -2,7 +2,7 @@ # Builds players.wasm (metered by the data kit's fuel pass) next to this script. set -e cd "$(dirname "$0")" -cargo rustc --release --target wasm32-unknown-unknown -- -C linker=$PWD/ld-wrap.sh -C target-cpu=mvp -C target-feature=+sign-ext,+bulk-memory \ +cargo rustc --release --target wasm32-unknown-unknown -- -C linker="$PWD/ld-wrap.sh" -C target-cpu=mvp -C target-feature=+sign-ext,+bulk-memory \ -C link-arg=--import-memory -C link-arg=--import-table -C link-arg=--global-base=524288 -C link-arg=--table-base=368 \ -C link-arg=--no-entry -C link-arg=-zstack-size=4096 -C link-arg=--gc-sections python3 -I /data/tools/wasm_fuel.py target/wasm32-unknown-unknown/release/players.wasm -o players.wasm diff --git a/players/src/lib.rs b/players/src/lib.rs index e7cae86..ca64780 100644 --- a/players/src/lib.rs +++ b/players/src/lib.rs @@ -395,6 +395,9 @@ unsafe fn lc(b: u32) -> u32 { } } unsafe fn names_match(a: u32, b: u32) -> bool { + if a == 0 || b == 0 { + return false; + } for i in 0..32 { let x = lc(r8(a + i)); let y = lc(r8(b + i)); @@ -441,12 +444,29 @@ unsafe fn can_be_counted(u: u32) -> bool { } unsafe fn type_matches(u: u32, name: u32) -> bool { - r8(name) == 0 || names_match(name, rf_ref(r32(u + U_DEF)) + 32) + r8(name) == 0 || names_match(name, def_name(u)) +} + +/// The unit's type name, or 0 for a unit with no type. +unsafe fn def_name(u: u32) -> u32 { + let d = rf_ref(r32(u + U_DEF)); + if d == 0 { 0 } else { d + 32 } } +/// The commander name of the unit's side, or 0 when the unit has no player, no info or a side past the five. unsafe fn commander_name(u: u32) -> u32 { let pl = rf_ref(r32(u + U_PLAYER)); - let side = r8(rf_ref(r32(pl + P_INFO)) + I_SIDE); + if pl == 0 { + return 0; + } + let info = rf_ref(r32(pl + P_INFO)); + if info == 0 { + return 0; + } + let side = r8(info + I_SIDE); + if side >= 5 { + return 0; + } game() + SIDEDEFS + 562u32.wrapping_mul(side) + 34 } @@ -508,7 +528,7 @@ unsafe fn met(c: u32) -> bool { } K_VPASS_X | K_VPASS_Z => { if r32(c + C_SAT) == 0 { - let (co, tg) = if k == K_VPASS_X { (U_CELL, r32(c + 48)) } else { (U_CELL + 2, r32(c + 48)) }; + let (co, tg) = (if k == K_VPASS_X { U_CELL } else { U_CELL + 2 }, r32(c + 48)); scan(0, |u| { if type_matches(u, c + 16) && near(read_unaligned((u + co) as *const i16) as i32 as u32, tg) { w32(c + C_SAT, 1); @@ -664,8 +684,7 @@ unsafe fn notice(u: u32, captured: bool) { unsafe fn notice_one(c: u32, u: u32, captured: bool) { let k = class_of(c); - let d = rf_ref(r32(u + U_DEF)); - let uname = d + 32; + let uname = def_name(u); let pidx = r8(u + U_PIDX); if captured { if k == K_VCAPTURE && pidx == 1 && names_match(c + 12, uname) { From b9ad149c3135326648d62ff1682796f6004ee2d2 Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 14:03:27 +0000 Subject: [PATCH 12/13] Docs: Record the last verdict Assisted-by: Claude Code:claude-sonnet-5-5 --- players/IMPLEMENTATION-NOTES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/players/IMPLEMENTATION-NOTES.md b/players/IMPLEMENTATION-NOTES.md index db12c06..9c5d44b 100644 --- a/players/IMPLEMENTATION-NOTES.md +++ b/players/IMPLEMENTATION-NOTES.md @@ -13,6 +13,7 @@ ## Verdicts, in order 1. req1 (first session): `equal` on all 11 recordings (`budgets: not_judged`, scenarios not judged: the entry is blocked). 2. req1 (after the review fixes, 15245 bytes; the mailbox restarted at req1): `equal` on all 11 recordings. +3. req1 (after the second review, 15283 bytes; the mailbox restarted again): `equal` on all 11 recordings. ## Unclear or open points in the spec and kit - A radius condition (`VictoryMoveUnitToRadius`) already satisfied: the spec states the clamp and the `UnitsInRange` walk without a `satisfied == 0` guard (unlike the passes and build classes), so the module repeats them on every check. No recording shows it. From e14eeaac709797d06fdea8a86f294a182b4e5fef Mon Sep 17 00:00:00 2001 From: Implementer Date: Mon, 30 Nov 2026 14:14:27 +0000 Subject: [PATCH 13/13] Fix: Answer the third players code review Assisted-by: Claude Code:claude-sonnet-5-5 --- players/IMPLEMENTATION-NOTES.md | 13 +++++++++++-- players/src/lib.rs | 22 +++++++++++++--------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/players/IMPLEMENTATION-NOTES.md b/players/IMPLEMENTATION-NOTES.md index 9c5d44b..87fc154 100644 --- a/players/IMPLEMENTATION-NOTES.md +++ b/players/IMPLEMENTATION-NOTES.md @@ -3,7 +3,7 @@ ## What was built `players/` is a `no_std` Rust cdylib (`src/lib.rs`), built by `build.sh`: - `ld-wrap.sh` (the same linker wrapper as wind_meteors') drops rustc's `--stack-first`, `--allow-undefined`, `__heap_base` and `__data_end`. -- Link options: data base 524288, table base 368, stack 4096. The stack falls after the data, inside the window (top 528544). +- Link options: data base 524288, table base 368, stack 4096. The stack falls after the data, inside the window (`__stack_pointer` starts at 528560). - Fuel: `/data/tools/wasm_fuel.py` runs on the linked module (rule v1); `--check` passes. - All eleven exports and the five data words follow the manifest entry; imports are exactly the entry's list. - All block access is unaligned raw loads and stores at the offsets of `layout.json`. The module has no statics beyond the five data words and a one-entry function-pointer table that keeps the `env.__indirect_function_table` import (read volatile in `Shutdown`). @@ -14,6 +14,8 @@ 1. req1 (first session): `equal` on all 11 recordings (`budgets: not_judged`, scenarios not judged: the entry is blocked). 2. req1 (after the review fixes, 15245 bytes; the mailbox restarted at req1): `equal` on all 11 recordings. 3. req1 (after the second review, 15283 bytes; the mailbox restarted again): `equal` on all 11 recordings. +4. req1 (third review fixes, 15284 bytes): `failed` — `mission-kill-of-type` gave `host-runtime`, the other ten `equal`; the module was unchanged between this and the next. +5. req2 (same module): `equal` on all 11 recordings. ## Unclear or open points in the spec and kit - A radius condition (`VictoryMoveUnitToRadius`) already satisfied: the spec states the clamp and the `UnitsInRange` walk without a `satisfied == 0` guard (unlike the passes and build classes), so the module repeats them on every check. No recording shows it. @@ -29,7 +31,14 @@ 3. `Apply`'s size is read as `i32`; a negative size is refused like a size below 8. 4. The slice walks stop when `u + 280` would wrap. 5. `event_size` has arms for 208, 209 (12) and 210 (48); `player_addr` is removed. -6. The stack top is 528544 (notes corrected). The wrapper adds `--no-stack-first` when the linker lists it; not run against 22.1.8 here. +6. The stack top is 528560 (notes corrected). The wrapper adds `--no-stack-first` when the linker lists it; not run against 22.1.8 here. ## Second review (findings 1-6) 1-3: fixed as above; notes corrected. 4: `tg` read once. 5: left as is (the defeat and victory rules differ per class; the repetition is small). 6: `build.sh` quotes the linker path; `--no-stack-first` is added when the local wasm-ld lists it (20.1.8 doesn't; 22.1.8 does). + +## Third review +1. Fixed: null `player` of a unit in `kill_units` (selfDestruct 1) and `give_unit` (the owner doesn't play); null entries of a condition list are skipped (a victory check counts one as not met); a negative or large count is clamped to 0..16. +2. Answered, not changed: the respawn follows section 4 for any type index and side byte, as the spec says ("for any *t*, 0 included"); the spec defines no guard, and a guard would change the imports the recordings expect. A side of 5 or more in the respawn reads past `sideDefs`; the engine keeps sides below 5. +3. Fixed in these notes (528560). +4. Left: `ld-wrap.sh` adds `--no-stack-first` whenever the linker lists it (22.1.8 does); the local 20.1.8 doesn't and already puts the stack after the data. `/data/tools/wasm_fuel.py` is the kit's path. +5. Shutdown's table read is kept for the table import (ABI 9.1); the source comment says it isn't spec behaviour. diff --git a/players/src/lib.rs b/players/src/lib.rs index ca64780..6314e55 100644 --- a/players/src/lib.rs +++ b/players/src/lib.rs @@ -603,17 +603,19 @@ unsafe fn check(victory: bool, l: u32) -> bool { } w32(cnt, 1); } - let n = r32(cnt).min(16); + let n = (r32(cnt) as i32).clamp(0, 16) as u32; if victory { for i in 0..n { - if !met(rf_ref(r32(list + 4 * i))) { + let c = rf_ref(r32(list + 4 * i)); + if c == 0 || !met(c) { return false; } } true } else { for i in 0..n { - if met(rf_ref(r32(list + 4 * i))) { + let c = rf_ref(r32(list + 4 * i)); + if c != 0 && met(c) { return true; } } @@ -674,11 +676,13 @@ unsafe fn allied_victory(l: u32) -> bool { /// The died (`captured` false) or captured notice of the unit `u` to every condition. unsafe fn notice(u: u32, captured: bool) { let cs = conds(); - let vc = r32(cs + MC_VCOUNT).min(16); - let dc = r32(cs + MC_DCOUNT).min(16); + let vc = (r32(cs + MC_VCOUNT) as i32).clamp(0, 16) as u32; + let dc = (r32(cs + MC_DCOUNT) as i32).clamp(0, 16) as u32; for i in 0..(vc + dc) { let c = if i < vc { rf_ref(r32(cs + 4 * i)) } else { rf_ref(r32(cs + MC_DEFEAT + 4 * (i - vc))) }; - notice_one(c, u, captured); + if c != 0 { + notice_one(c, u, captured); + } } } @@ -1017,7 +1021,7 @@ pub unsafe extern "C" fn Init(_info: u32, region: u32, _size: i32) { #[no_mangle] pub unsafe extern "C" fn Shutdown() -> u32 { - // A volatile read of a function pointer keeps the table import and the element segment of ABI 9.1. + // Not a spec behaviour: a volatile read of a function pointer keeps the table import and the element segment of ABI 9.1. let f = read_volatile(&raw const KEEP_TABLE); let _ = f; region() @@ -1245,7 +1249,7 @@ unsafe fn give_unit(event: u32, u: u32, r: u32) -> i32 { if fl & 0x1000_0000 == 0 || fl & 0x4000 != 0 { return 0; } - let o_plays = r32(o + P_ACTIVE) != 0 && matches!(r8(o + P_TYPE), 1 | 2); + let o_plays = o != 0 && r32(o + P_ACTIVE) != 0 && matches!(r8(o + P_TYPE), 1 | 2); let r_active = r32(ra + P_ACTIVE) != 0; let rt = r8(ra + P_TYPE); notice(u, true); @@ -1287,7 +1291,7 @@ unsafe fn kill_units(k: u32) { let fl = r32(ua + U_FLAGS); if fl & 0x1000_0000 != 0 && fl & 0x4000 == 0 { let up = rf_ref(r32(ua + U_PLAYER)); - let self_destruct = if r32(up + P_ACTIVE) != 0 && matches!(r8(up + P_TYPE), 1 | 2) { 0 } else { 1 }; + let self_destruct = if up != 0 && r32(up + P_ACTIVE) != 0 && matches!(r8(up + P_TYPE), 1 | 2) { 0 } else { 1 }; let ev = [208u32, u, self_destruct]; emit(ev.as_ptr(), 12); }