diff --git a/specs/scripts.md b/specs/scripts.md new file mode 100644 index 0000000..295bb32 --- /dev/null +++ b/specs/scripts.md @@ -0,0 +1,923 @@ +# scripts + +## 1. Role + +A scripted unit runs compiled COB code: eight threads per unit, each a stack machine over a word code +array, that wait, sleep, start and signal each other, move and turn the pieces of the unit's model, +read and set a handful of the unit's values, and draw from the game's random stream. Scripts holds the +threads, the statics and the piece animation records of every unit's script, the piece state a script +poses (a unit's model state, or a feature's), and the piece queries other subsystems ask: where a piece +is, what angles it has, where a weapon aims from, where the nano piece is and where the unit's sweet +spot is. It also starts scripts for the rest of the engine and answers queries synchronously. + +## 2. Interface + +### Slots (`interfaces/scripts.h`, version 3.0) + +| Slot | When the engine calls it | +| --- | --- | +| `Apply` | for each event of the module's inbox, once, with the event and its payload size | +| `StartScriptWithArgsByIndex` | when a unit's script must start by the index of a name, on behalf of another machine, with up to four arguments | +| `QueryScript` | when the engine needs the answer of a named query script, in the same statement | +| `FindScript` | when the engine needs the index of a named script | +| `GetPieceOffset` | when the engine needs a piece's offset from the unit | +| `GetPiecePosition` | when the engine needs a piece's world position | +| `GetPieceAngles` | when the engine needs a piece's angles | +| `GetNanoPiecePosition` | when an order needs the world position of the unit's nano piece | +| `GetAimFromPosition` | when a weapon needs the position it aims from | +| `GetSweetSpot` | when targeting needs the point weapons aim at on a unit | +| `PoseUnitModel` | when the simulation needs a unit's model posed from its current angles and animation | +| `CreateObjectState` | when a model's piece state must be built for a feature, or a unit without a script | +| `FreeObjectState` | when a piece state and the pictures cached for it are freed, as a unit dies | +| `UpdateObjectState` | when presentation poses a model it is about to draw | +| `ObjectStateSize` | when a caller must size the piece state of a model before publishing INIT_STATE | +| `NewUnitScript` | when a unit is created and its script allocated | +| `SetCob` | when a unit type's compiled script data is given to a unit's script | +| `CreatePlayerObjectState` | when a scripted unit's piece state is built | +| `SetObjectState` | when a unit's script is given its piece state | +| `RunScripts` | once per unit with a script and per unit pass, with the ticks elapsed since its last call | +| `DeleteScript` | when a unit's script is destroyed, as its unit dies | + +The engine slots, which the module does not export and the engine's own code answers, are +`SaveScriptState`, `LoadScriptState` and `WriteState`; section 4 states what they do. + +### The manifest entry + +The kit's manifest (`wasm/modules.json`) carries this module's entry with a `blocked` reason, so the entry +has neither `fuel_budget` nor `size_budget` and the host runs the native default for every slot of it. The gate +judges a module of the entry on its recordings alone, with no scenario, fuel budget or size budget +(`docs/module-abi.md`, sections 4.2 and 15). The module is still built to the entry as this section gives it: + +- `name` and `interface`: `scripts`. +- `exports`, in this order: `Apply`, `StartScriptWithArgsByIndex`, `QueryScript`, `FindScript`, + `GetPieceOffset`, `GetPiecePosition`, `GetPieceAngles`, `GetNanoPiecePosition`, + `GetAimFromPosition`, `GetSweetSpot`, `PoseUnitModel`, `CreateObjectState`, `FreeObjectState`, + `UpdateObjectState`, `ObjectStateSize`, `NewUnitScript`, `SetCob`, `CreatePlayerObjectState`, + `SetObjectState`, `RunScripts`, `DeleteScript`. +- `engine`: `SaveScriptState`, `LoadScriptState` and `WriteState`. +- `data`: `g_game`, `g_simGlobals`, `g_extTdf`, `g_blockBase` (ABI 8.2). The module reads all four: + `g_game` for the game record, `g_simGlobals` for the random seed (`rng.seed` is + `SimGlobals.g_randomSeed`), `g_blockBase` for every `Ref`, and `g_extTdf` only as its export. +- `majors`: `scripts` 3, and for its import groups `map` 9, `los_radar` 5, `services` 4. +- `data_base` and `table_base`: `0x90000` and 432, from the entry (ABI 2). The window is 32768 bytes + and the table range 32 entries. +- `fuel_budget` and `size_budget`: none, as the entry is `blocked`. The module still meters itself by rule + version 1 and exports `__fuel_set` and `__fuel_get` (ABI 11). +- `publishes`: `{"164": 12, "263": 16, "264": 16, "357": 20, "386": 16}`, the five effect kinds of + section 4 (`docs/schedule.md`, "Routes"; `data/routes.csv`). +- Slot kinds: + +| Slot | Kinds | +| --- | --- | +| `Apply` | `[linear, int] -> int` | +| `StartScriptWithArgsByIndex` | `[linear, int, linear, int, int, int, int, int, int] -> int` | +| `QueryScript` | `[block, linear, linear, linear, linear, linear] -> int` | +| `FindScript` | `[block, linear] -> int` | +| `GetPieceOffset`, `GetPiecePosition`, `GetPieceAngles` | `[block, int, linear] -> void` | +| `GetNanoPiecePosition`, `GetSweetSpot` | `[linear, linear] -> void` | +| `GetAimFromPosition` | `[linear, linear, int] -> void` | +| `PoseUnitModel`, `UpdateObjectState` | `[linear] -> void` | +| `ObjectStateSize` | `[linear] -> int` | +| `CreateObjectState` | `[linear] -> block` | +| `FreeObjectState` | `[block] -> void` | +| `NewUnitScript` | `[block] -> void` | +| `SetCob` | `[block, linear] -> void` | +| `SetObjectState` | `[block, block] -> void` | +| `CreatePlayerObjectState` | `[linear, linear, block] -> block` | +| `RunScripts` | `[block, int] -> void` | +| `DeleteScript` | `[linear] -> void` | +- Imports, every one listed and nothing else: + +| Import | Kinds | Used for | +| --- | --- | --- | +| `map.GetGroundHeight` | `[linear] -> int` | unit value 16 | +| `map.CanPlaceUnitFootprint` | `[block, int, linear, int] -> int` | the drop operation of section 4 | +| `los_radar.IsUnitVisibleToPlayer` | `[block, block] -> int` | the visibility test of the effect command | +| `services.SimAlloc` | `[int] -> linear` | a unit's script | +| `services.SimAllocTagged` | `[linear, int] -> linear` | a model state and the point lists of its pieces | +| `services.SimFree` | `[linear] -> void` | freeing them again | +| `services.SimRealloc` | `[linear, int] -> linear` | the statics and piece records of `SetCob` | +| `services.RecordSimEvent` | `[int, int, linear, int] -> void` | the five sim events of the effect command | +| `services.RandomInt` | `[int] -> int` | listed by the entry; no recording calls it, and the module makes every draw of section 5 from `rng.seed` itself, a range below 2 included, so the draw never calls it; how the module keeps the listed import in its import section is its own affair | +| `services.GetCobChecksum` | `[linear] -> int` | the checksum `SetCob` stores (section 2, "Arguments outside the block") | +| `services.Emit` | `[linear, int] -> void` | publishing the five effects of section 4 | + +- Hooks: none. The header annotates every slot "Hooks: none". + +A recording carries the scheduler's own name for one of these calls: `services.ScheduleMapCanPlaceUnitFootprint` is +`map.CanPlaceUnitFootprint` (`docs/module-abi.md`, "Routes in the recordings"). + +### Arguments outside the block + +- **The event** of `Apply` is a record in the module's memory that starts with a `ScriptsEventHeader` and + continues with the fields of its kind (`ScriptsStart`, `ScriptsDetachPiece` or `ScriptsState`, each + of which includes the header), and `size` is the record's length in bytes, header included: 76 for + `ScriptsStart` and 16 for the other two. Every offset this spec gives inside an event counts from the + first byte of the header. The event is an intent, validated as section 4 says; a rejected one changes nothing and + has outcome 0. +- **The script data** (`SetCob`, `CreatePlayerObjectState`) is a unit type's compiled script, which the + host maps into the `load_data` region (ABI 7.1) as the game holds it once loaded. The argument is + the `linear` address of its first byte, never an address inside it; in a recording it is written as + the holder, `UnitDef#N`. `CobScript.table` holds the same address once `SetCob` has run, stored as + the address and not as a block offset. A module reads the data and never writes it. The table there + is 44 bytes of 32-bit words: the format version (0), `count` (4), `pieceCount` (8), a word this + module never reads (12), `staticCount` (16) and the number of pairs (20); then five linear + addresses: `entries` (24), `names` (28), the model's piece names (32), `code` (36) and the pairs + (40). `entries` is an array of `count` indices into `code`, one per script; `names` is an array of + `count` addresses of NUL-terminated names; the piece names are an array of `pieceCount` addresses of + NUL-terminated names; `code` is an array of 32-bit words read by index, none of them an address. The + pairs are 8 bytes each, a word and an address that this module never reads. No other address in the + data is one the module may follow. + The file's checksum is not in the data and a module cannot compute it. `services.GetCobChecksum(data)` + returns it for the address `CobScript.table` holds, and `SetCob` stores it (section 4). The import is + a pure query: its answer depends on its argument alone and it changes nothing, so the gate answers it + by its argument and compares neither how many times a module asks nor where the calls fall among the + other imports (`docs/module-abi.md`, sections 9.3 and 15); a recording shows it as `i + services.GetCobChecksum UnitDef#N = `. A null argument answers 0. +- **A callback** arrives as the `linear` address of an object the engine owns, 0 for none; the value + a channel stores and AIM_DONE publishes is that object's block offset, 0 for none (ABI 7.1). The + module converts between the two and never calls through the object. A callback object is virtual, + and its offset is the offset of an object whose first word is a table pointer; the module reads + nothing of it. +- **A model** arrives as the engine loaded it, mirrored into the shared memory; the module reads its + nodes and never loads or mirrors its file. +- **`out`** (`GetPieceOffset`, `GetPiecePosition`, `GetNanoPiecePosition`, `GetAimFromPosition`, + `GetSweetSpot`) is a `Vec3` of three 32-bit integers in the caller's memory, written whole. + `GetPieceAngles` writes an `Angles16`: three 16-bit values, bank, heading and pitch in that order, bank and + pitch signed and heading unsigned (`layout.json`; a recording prints heading 0x8000 as 32768). +- **Text** given to the slots (`QueryScript` and `FindScript`'s name, the names inside the script data) + is NUL-terminated bytes in the caller's memory; the comparison is byte for byte, case sensitive. + `Apply`'s START name is a 32-byte field that need not be terminated. + +### Events + +The module records five sim event kinds, each when a script's EMIT_SFX operation emits the effect +number that kind names, at the piece's position, and only when the unit is visible to the player the +machine views (`los_radar.IsUnitVisibleToPlayer`); a unit that is not visible records nothing. The +arguments, flags and phases are as `docs/sim-events.md` gives them: + +- `SIM_EVENT_THRUST_PARTICLES`: the effect that streams a jet plume, with lifetime 6 or 7; +- `SIM_EVENT_WAKE_PARTICLES`: the effect that trails a wake, with period 16 or 8; two of its numbers + swap the two positions; +- `SIM_EVENT_BUBBLES`, `SIM_EVENT_WHITE_SMOKE`, `SIM_EVENT_BLACK_SMOKE`: the effects that raise + bubbles, puff white smoke and puff black smoke. The numbers each kind answers to, and its arguments, + are as `docs/sim-events.md`, Terms, gives them. + +The module records each through `services.RecordSimEvent` with flags 0, the arguments in the order +`docs/sim-events.md` gives them, and their count: nine for THRUST_PARTICLES, eight for WAKE_PARTICLES and +BUBBLES, and four for WHITE_SMOKE and BLACK_SMOKE. + +`Apply` takes only the four kinds of 416 to 419. The routed effects of other interfaces that carry +scripts' intent (kinds 17, 48, 49, 112, 278, 279, 311 and 347, `data/routes.csv`) are translated by +the engine into those events before delivery, as the reference's seam translates them. The kit +defines no payload mapping for that translation, so this spec cannot state it; that is a kit gap, +filed with the others. + +### Effects + +The module publishes five effects through `Emit`, each at the moment section 4 gives; the payload +starts with the interface's event header, whose `kind` the effect's kind is, and the second argument of +`Emit` is its size: + +| Effect | Kind | Payload | Fields | +| --- | --- | --- | --- | +| SET_YARD, to map | 164 | `MapSetYard`, 12 bytes | the unit; `open`, the value the script set (any 32-bit value) | +| AIM_DONE, to weapons | 263 | `WeaponsAimDone`, 16 bytes | the unit is 0; the callback; what the aim script returned | +| EXPLODE_PIECE, to weapons | 264 | `WeaponsExplodePiece`, 16 bytes | the unit; the piece; the flags of the explode operation | +| ATTACH_TO_PIECE, to units | 357 | `UnitsAttachToPiece`, 20 bytes | the unit; the target, 0 to detach; the target's piece, -1 when none; the mode | +| SCRIPT_VALUE, to units | 386 | `UnitsScriptValue`, 16 bytes | the unit; the value's number; the value | + +A malformed effect changes nothing and does not trap (ozgb/btm#25). For each kind, the fields that +must be valid are: SET_YARD, a unit offset that is a unit; AIM_DONE, a callback that is not 0; +EXPLODE_PIECE, a unit offset that is a unit and a piece below the model's piece count; ATTACH_TO_PIECE, +a unit offset that is a unit, and, when the target is not 0, a target offset that is a unit; and +SCRIPT_VALUE, a unit offset that is a unit. The module publishes none that a valid script does not +produce: a null unit or a callback it never had is never published. It publishes the fields as its +script gives them (a piece index, flags or a value are passed unchanged) and checks none of them, except the tests the attach and drop operations make of the unit and its +carrier and the piece index of EXPLODE_PIECE, which section 4 puts outside the contract (a module may drop one +that is outside the model's piece count or publish it). + +## 3. State + +### Owned + +All of it is in the block, allocated with `SimAlloc` or `SimAllocTagged` and reached through the +`Ref` fields that hold it; a `Ref` is a 32-bit block offset, 0 for null (ABI 7.1). + +**`CobScript`** (1344 bytes; the base of a unit's script): + +| Field | Offset | Meaning | +| --- | --- | --- | +| `scale` | 4 | ticks per second the script's speeds are divided by: 30 | +| `table` | 8 | the address of the unit type's script data, 0 before one is set | +| `checksum` | 12 | the unit type's script-file checksum | +| `statics` | 16 | `Ref`: `staticCount` words the script reads and writes | +| `pieces` | 20 | `Ref`: `pieceCount` animation records | +| `changed` | 24 | 1 while a piece is animating, so the piece animation step runs | +| `channels` | 28 | eight `Channel` records (1312 bytes) | +| `activeCount` | 1340 | the number of channels that are not free | + +**`UnitScript`** (1348 bytes): `CobScript`, then `state` at 1344, `Ref`: the unit's model +state. The unit that owns a script is the `owner` of this state, and "the unit" in section 4 means it. +In `layout.json` the unit's own `state` field and this one are typed with the names `SpotState` and +`ObjectState`; the record behind each is the `ModelState` below (a recording names it `ModelState#N`), +which a `SpotState` extends with fields these slots do not touch. + +**`Channel`** (164 bytes): + +| Field | Offset | Meaning | +| --- | --- | --- | +| `state` | 0 | 0 free; 0x01000000 runnable; 0x02100000 waiting for a turn to stop; 0x02200000 waiting for a move to stop; 0x02400000 sleeping; 0x02800000 waiting for a child thread to end | +| `pc` | 4 | the index in `code` of the next opcode | +| `sp` | 8 | the stack pointer; -1 is an empty stack | +| `delay` | 12 | the ticks left of a sleep | +| `piece` | 16 | the piece a turn or move wait watches | +| `axis` | 20 | the axis of that wait | +| `waiting` | 24 | the index of the child a 0x02800000 wait waits for | +| `signal` | 28 | the signal word a KILL operation matches | +| `callback` | 32 | `Ref`: the aim callback told when the thread returns | +| `stack` | 36 | 32 words; a word is pushed at `sp` after `sp` adds 1, and popped from `sp` before `sp` subtracts 1 | + +The waiting substate is `state & 0x00f00000` and the state class is `state & 0xff000000`; the fields +`delay`, `piece` and `axis` are meaningful only in the substate that uses them. + +**`Piece`** (76 bytes): `active` at 0, then six arrays of three words, `move` at 4, `moveSpeed` at 16, +`turn` at 28, `turnSpeed` at 40, `spin` at 52, `acceleration` at 64. A `turn` of −1 on an axis means the piece +spins on it instead of turning to a target. + +**`SavedPiece`** (108 bytes): the six piece arrays at 0 to 71, `translation` at 72, `rotation` at 84, +`visible` at 96, `cached` at 100, `shaded` at 104; the form a saved game stores. + +**`ModelState`** (88 bytes minimum; `SpotState` for a feature's spot, 118): `count` at 0, the number of +piece records; `cacheDrawCount` at 4; `animDirty` at 8; `owner` at 12, `Ref`; `bitmap` at 16; +`shadow` at 20; `pos` at 24, a `Vector3s`; `root` at 30, `Ref`; `pieces` at 34, `count` +`ModelPiece` records of 54 bytes. A feature's spot record has the same first 88 bytes, then its own +fields; the slots here read only the shared prefix. + +**`ModelPiece`** (54 bytes): `object` at 0, the `Object3do` node; `rot_x` at 4, `rot_y` at 8, +`rot_z` at 12, the piece's translation in each axis; `short_10` at 16, `short_12` at 18, `short_14` at +20, its rotation about each axis; `offset` at 22, a `Vec3`, the posed offset; `points` at 34, +`Ref`, the posed vertices; `modified` at 38; `flags` at 40, a `ModelPieceFlags` word; `sibling` +at 42, `child` at 46 and `parent` at 50, `Ref`. + +**`ModelPieceFlags`** (2 bytes): bit 0 `visible`, bit 1 `colored`, bit 2 `lit`, bits 3 to 15 `rest`. +This subsystem reads bits 1 and 2 as the piece's `cached` and `shaded` bits; the layout's names for +them are `colored` and `lit`. + +**The script data** (section 2, "Arguments outside the block"): a unit type's compiled script, a 44-byte +table of 32-bit words (`count` at 4, `pieceCount` 8, `staticCount` 16, `entries` 24, `names` 28, the +model's piece names 32, `code` 36) in the `load_data` region. It is load data, which the module reads +and never writes; the checksum of the file it came from comes from `services.GetCobChecksum`. + +**List and copy rules.** A null `Ref` stores the value 0; any other stores `address - g_blockBase`. +A record the slot allocates is not initialised beyond what section 4 says, so its bytes are whatever +the allocation gives them; the recordings show fresh allocations as zero. A copy of a record copies +its bytes; a `Ref` inside it is copied as the offset it is. + +### Read + +- `Game`: `playerIndex` (the player the machine views), `seaLevel` (the height the bubble effect + rises to), `units` (the base of the unit table, indexed by a 16-bit unit id for unit values 9 to 11 + and for the attach and drop operations) and `poolCount` (`WriteState`; section 4). +- Each `Unit` a slot is given or reaches: `activateFlags`, `cell`, `footprint`, `id`, `cobStateFlags`, + `cargo`, `cargoNext`, `carrier`, `bank`, `heading`, `pitch`, `flags`, `health`, `buildLeft`, `def`, + `pos`, `script`, `state`. +- `UnitDef`: `modelMaxY`, `maxHealth`. +- `Feature.object` (for INIT_STATE), the model of the feature type. +- `Object3do`: `vertexCount`, `box_x`, `box_y`, `box_z`, `vertices`, `sibling`, `child`, `name`. +- `Game.players[Game.playerIndex]` is passed to `los_radar.IsUnitVisibleToPlayer` as an address; the + module does not read the player record itself. +- The random stream `rng.seed` (`g_randomSeed`): read and written as section 5 says. + +### Bits of the unit's words + +| Bits | Mask | Meaning here | +| --- | --- | --- | +| bit 0 of `activateFlags` | 0x01 | unit value 1, `activate_bit0` | +| bit 1 of `activateFlags` | 0x02 | unit value 20, `activate_bit1` | +| `bit0`, `bit1`, `bit2`, `bit3` of `cobStateFlags` | 0x01, 0x02, 0x04, 0x08 | unit values 5, 6, 18 and 19 | +| bits 18 and 19 of `flags` | 0x000c0000 | unit value 2 | +| bits 20 and 21 of `flags` | 0x00300000 | unit value 3 | +| bit 28 of `flags` | 0x10000000 | the unit is alive, which ATTACH, DROP and unit values 9 to 11 test | + +### Between ticks + +Nothing outside these fields: the script objects, their statics and piece records, the model states +and their pieces, and the unit's `script`, `state` and script bits. A channel that is free has state +0; its other fields keep the values the thread left. The module keeps no allocation of its own +between ticks. + +## 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 write reads +an earlier one. + +### `Apply(event, size)` + +The outcome is 0 and nothing changes when, in this order: `size` is below the 8 bytes of +`ScriptsEventHeader`; `kind` is not 416 to 419; `size` is below the kind's record (76 bytes for +START, 16 for each of the other three); the named object is null (the unit of START and DETACH_PIECE, +the piece state of FREE_STATE and INIT_STATE); or, for START, `form` is not 0, 1 or 2. Otherwise the +outcome is 1 and the kind's row applies: + +| Kind | Effects | +| --- | --- | +| START (416) | With the unit's `script`: when it is null, the outcome is 0 and nothing changes. Otherwise a thread starts as the form says (below), and the outcome is 1. | +| DETACH_PIECE (417) | When `pose` is 1, the unit's model is posed first: the state's `pos` becomes the unit's angles, `animDirty` 1, the root's `modified` 0, and the pose of section 4 runs, ending with `animDirty` 0. Then bit 0 of the flags word at `state + 34 + piece*54 + 40` is cleared. Outcome 1. | +| FREE_STATE (418) | The piece state is freed: each piece's `points` with `SimFree`, the pictures cached for it, and the state itself. Outcome 1. | +| INIT_STATE (419) | The state is set to 0 and its pieces are added from the model of `Game.features[feature].object` by the piece-state build rule of section 4, and `animDirty` becomes 1. Outcome 1. | + +The START forms, with *name* the event's 32-byte name copied into a 32-byte buffer that holds at most +31 of its bytes and a 0, *callback* the word at 48 of the event as a callback, *update* the word at +52, *count* the word at 56 and `args` the four words at 60: + +| Form | Effect | +| --- | --- | +| 0, by name | The thread of the first script whose name equals *name* starts; when it starts, its callback is *callback*, and when *update* is not 0 every channel runs with elapsed 0 and the piece animation step runs with 0. If no script has that name or no channel is free, nothing starts and nothing is published. | +| 1, by name with arguments | The with-arguments start of section 4 with the index of the first script whose name equals *name* (a name no script has gives index −1, so no thread starts and, when the callback is not 0, AIM_DONE is published with result 0), the callback, *update*, *count* and *args*. | +| 2, by index with arguments | The with-arguments start of section 4 with *index*, the callback, *update*, *count* and *args*. | + +The outcome is 1 for forms 0, 1 and 2 whether or not a thread started, and 0 only for a unit whose +`script` is null or a form outside 0 to 2. + +### StartScriptWithArgsByIndex + +The with-arguments start of a script data index, a callback, an update flag, a count and four words: +the thread whose script entry is *index* starts (the thread start of section 4). When no channel is +free, or *index* is below 0 or not below the script data's `count`, nothing starts: when *callback* +is not 0, AIM_DONE is published with that callback and result 0, and the result is 0. + +When it starts: the channel's callback is *callback*; the four words *a*, *b*, *c* and *d* are pushed +in that order, so they sit at `stack[0]` to `stack[3]`, and `sp` becomes `count - 1`; then, when +*update* is not 0, every channel runs with elapsed 0 and the piece animation step runs with 0. The +result is 1. `count` 0 to 4 are the only values the callers pass; a `count` above 4 exposes stack the +push did not write. + +### QueryScript + +**A query run** of a name and one input word: the thread whose script name equals *name* starts (the +thread start of section 4). When it cannot start (no free channel or no matching name), the run does +nothing and its result is 0. When it starts, *input* is stored in `stack[0]`, `stack[1]` to +`stack[3]` are 0; `sp` becomes 3; the thread runs at once with elapsed 0; and the answer is +`stack[0]` as the run left it. The channel is left as the run left it. + +`QueryScript` takes the script, the name and four argument pointers and runs the query of *name* with four input words, +the value of a null argument pointer being 0: they are stored in `stack[0]` to `stack[3]`, `sp` +becomes 3, the thread runs at once with elapsed 0, and each non-null argument pointer then receives +`stack[0]`, `stack[1]`, `stack[2]` and `stack[3]`. The result is 1 when the thread started, and 0, +with nothing written, not even through the argument pointers, when it did not. + +**The bounds of the arguments.** The piece-offset rule gives (0, 0, 0) for a null unit or model +state and for a piece outside 0 to `count`−1, and `GetPieceAngles` defines a piece of −1. Everything +else is the caller's: the effect command's piece index, DETACH_PIECE's piece, INIT_STATE's feature +index, a model with fewer vertices than a slot reads, and script data that does not describe +its own counts are outside the contract, and a module need not check them. So are the faults of a +script's code: a null model given to `CreateObjectState`, `CreatePlayerObjectState` or `ObjectStateSize`, or a feature whose model is null at INIT_STATE; an opcode's piece, axis or statics index out of range (EXPLODE_PIECE's and the effect command's piece included: whether the module publishes or drops one outside the model's piece count is not judged), a stack that underflows or +overflows its 32 words, a `pc` outside `code`, and a script run while its model state is null or its +state has no owner (the operations that touch the pieces, the unit, an effect or a unit value need +both). + +### `FindScript(script, name)` + +The lowest index *i* below the script data's `count` whose name equals *name* byte for byte; -1 when +there is none. Nothing is written. + +### The piece offset + +*The piece offset* of a piece *p* of a unit whose model state is *state*: when *state* is null or *p* +is below 0 or not below *state.count*, it is (0, 0, 0). Otherwise the running point starts as the +record's `object.box_x` plus its `rot_x`, `object.box_y` plus its `rot_y`, and `object.box_z` plus its +`rot_z`; then for each record *q* from *p*'s `parent` up to the root: the angles are the three 16-bit +halves bank = `q.short_14`, heading = `q.short_12` and pitch = `q.short_10`, the unit's `bank`, +`heading` and `pitch` being added to them for a record with no parent (the root, or another top-level piece); the running point is rotated by those angles +(the three-angle rotation, section 5); and (`q.object.box_x + q.rot_x`, `q.object.box_y + q.rot_y`, +`q.object.box_z + q.rot_z`) is added to it. The offset is then (x, y, −z) of the running point. + +The nodes are read as the game holds a model once loaded, which mirrors it: the x and z of each node's box +and of each of its vertices are the negation of the file's (`docs/module-abi.md`, section 7.1, for the +vertices). A recording's `x` lines give the file's bytes, so a box read from them has the opposite x and z +of what a module reads from its copy. + +### The piece-offset rule and `GetPieceOffset(unit, piece, out)` + +*out* is the piece offset of *piece* (section 4). + +### `GetPiecePosition(unit, piece, out)` + +*out* is the unit's `pos` plus the piece offset of *piece*, component by component. + +### `GetPieceAngles(unit, piece, out)` + +With *u* the unit's angles: + +- when *piece* is 0 or more: bank is `u.bank` plus `pieces[piece].short_14`, heading is `u.heading` + plus `pieces[piece].short_12`, and pitch is `u.pitch` plus `pieces[piece].short_10`; +- when *piece* is −1: bank is `u.bank` plus the low 16 bits of the state's `count`, heading and pitch + are the unit's; +- below −1 is outside the contract. + +All additions wrap at 16 bits (Q2). + +### `GetNanoPiecePosition(unit, out)` + +The query run of `QueryNanoPiece` with input 0 gives the piece. *out* is the unit's `pos` plus the +piece offset of that piece. + +### `GetAimFromPosition(unit, out, weapon)` + +The query run of `AimFromPrimary`, `AimFromSecondary` or `AimFromTertiary` for *weapon* 0, 1 or 2 with +input −1 gives a piece. When it is −1, the query run of `QueryPrimary`, `QuerySecondary` or +`QueryTertiary` with input 0 gives the piece instead. *out* is the unit's `pos` plus the piece offset +of that piece. A *weapon* outside 0 to 2 is outside the contract. + +### `GetSweetSpot(unit, out)` + +The query run of `SweetSpot` with input 0 gives the piece. Then the unit's model is posed from its +game state (section 4), and *out* is the centre of that piece: with the piece's vertices *v*[0] to +*v*[*n*−1] from `pieces[piece].points`, *n* being `pieces[piece].object.vertexCount`, and the minimum +and maximum of x, y and z taken over those vertices and 0 (each minimum and maximum starts at 0), +*out* is + +```text +((max.x + min.x) / 2 + unit.pos.x, (max.y + min.y) / 2 + unit.pos.y, (max.z + min.z) / 2 + unit.pos.z) +``` + +where each division truncates toward zero. Posing the model first is the default behaviour; the quirk +`units.render-pose-reads` would read the renderer's copy instead and is off, so this spec states the +default (Q5). + +### `PoseUnitModel(unit)` + +When the unit's model state is null, nothing happens. Otherwise its `pos` becomes the unit's angles +(the six bytes of bank, heading and pitch), its `animDirty` becomes 1, its root piece's `modified` +becomes 0, the model is posed by the pose rule, and `animDirty` becomes 0. + +### The piece-state build rule and `CreateObjectState(model)` + +**A model's node count.** The count of a node is 1 when it has no child, and its child's count plus 1 +when it has one; a node's siblings add their own counts. The state's size is 34 plus 54 times the +root's count. That many bytes are allocated with `SimAllocTagged` and the tag `"Object State"`, the +whole record is set to 0, and the pieces are added from the model (below); `animDirty` becomes 1 and +the state's address is the result. + +**Adding a model's pieces.** The nodes are taken in a pre-order walk: a node, then its child's +subtree, then its sibling's subtree. For each, the record at index `count` of the pieces gets: +`object` the node; `modified` 0; `flags` 2 or 3 (bit 1 `colored`, and bit 0 `visible` when the node's +`vertexCount` is 3 or more) plus 4 (bit 2 `lit`); `points` a block of `vertexCount * 12` bytes from +`SimAllocTagged` with the tag `"Point List"`, holding a copy of the node's vertices; and `sibling`, +`child` and `parent` the records the node's sibling, child and parent are added as (0 when none). The +root is the record added for the model's root node, and `count` becomes the number of records. + +### `FreeObjectState(state)` + +For each piece from 0 to `count`−1, its `points` is freed with `SimFree` (a null one is not freed, +section 5), then the pictures cached for the state are released (presentation's; a module holds +none), then the state itself is freed with `SimFree`. Nothing is written. + +### The update rule and `UpdateObjectState(view)` + +The view is the unit record itself: its model state is the `Ref` at 158 and its angles are +the six bytes at 100 (bank, heading, pitch). + +*state* is the view's model state. When the view's angles are far from the state's `pos` (any of x, y +and z differs by 8 or more as a 16-bit signed difference), `pos` becomes the view's angles, +`animDirty` 1, the root's `modified` 0, and, when the root's `colored` bit is set, `cacheDrawCount` 0. +Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDirty` becomes 0. + +**The pose rule.** The pieces are restored first: a piece whose `modified` is 0 has its +`points` replaced by a copy of its object's `vertices` (`vertexCount * 12` bytes), its `offset` set +to (0,0,0) and its `modified` 0. A piece is also restored, whatever its `modified`, when its parent +was restored in this pass; a piece with no parent (the root and the model's other top-level pieces) +is restored only when its `modified` is 0. Equivalently, a piece is restored when it or any of its ancestors has `modified` 0 when the pass begins, whatever order the pass takes the records in. Then every piece under the root (the root's own subtree: a top-level piece that is not the root is not posed) is visited once for itself and once +for each of its ancestors from its parent up to the root: each visit, when the piece's `modified` is +0, rotates the piece's `offset` and each of its `points` vertices by the visiting piece's angles and +then adds the visiting piece's delta to each of them. The visiting piece's angles are its bank +`short_14`, heading `short_12` and pitch `short_10`, with the state's `pos` added first when it is +the root; its delta is +`rot_x + object.box_x`, `rot_y + object.box_y` and `rot_z + object.box_z`. The pose leaves `modified` +as the restore left it. + +### `ObjectStateSize(model)` + +The size `CreateObjectState` allocates, as section 4 gives it, without allocating or writing anything. + +### `NewUnitScript(unit)` + +A `UnitScript` of 1348 bytes is allocated with `SimAlloc` and stored in the unit's `script`. Its +fields are written as a new script is: `scale` 30, `table` 0, `statics` 0, `pieces` 0, `activeCount` 0, +and each of the eight channels' `state` 0. Offset 0 holds the `CobScript` class word: the entry named +`CobScript` (index 5, offset 0) in the class word table that starts the `load_data` region (ABI 7.1; `class_words` of +`layout.json`), copied as it is. Its other bytes are what +the allocation gives them. + +### `SetCob(script, data)` + +`script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise, in this order: + +- `script.checksum` becomes the result of `services.GetCobChecksum(data)` (section 2; the recordings show + the call first, and the gate does not compare where it falls); +- `script.pieces` becomes the result of `services.SimRealloc(script.pieces, pieceCount * 76)` (a null + `pieces` allocates; a size of 0 frees the block and gives null); +- `script.statics` becomes the result of `services.SimRealloc(script.statics, staticCount * 4)`: an extent + the statics block already held keeps its bytes, and a new extent is 0; +- the whole extent of the `pieces` block, `pieceCount * 76` bytes, is set to 0 (when `pieces` is not null). + +### `CreatePlayerObjectState(model, data, owner)` + +As `CreateObjectState(model)`, with these differences: the record's `owner` becomes *owner*; and, +after the pieces are added and before the links are rebuilt, the records are reordered so that record +*i* holds the object whose name matches, ignoring case, the *i*-th of the script data's `pieceCount` names: +for each *i* from 0 to `pieceCount`−1, the lowest *j* from *i* to `count`−1 whose name matches is +found, and when *i* differs from *j* the two 54-byte records are swapped; a name with no match moves +nothing for that *i*. Then the links are rebuilt from the object graph: each record's `sibling`, +`child` and `parent` become the records whose objects are its object's `sibling`, `child` and +`parent`, and 0 when the object has none; the root becomes the record whose object is the model's +root. The result is the state's address. + +### `SetObjectState(script, state)` + +The script's `state` becomes *state*. Nothing else. + +### `RunScripts(script, elapsed)` + +When `activeCount` is not 0, each of the eight channels runs in order (the thread run), then the +piece animation step runs with *elapsed*. With `activeCount` 0 only the piece animation step runs. + +The thread run of a channel and an elapsed count, with *c* the channel: + +1. A channel whose state class is 0 is skipped. In the waiting class 0x02000000, the substate decides + whether the wait is over: a turn wait (0x02100000) ends when `turnSpeed` at the channel's `axis` of the + script's animation record `pieces[piece]` (the channel's `piece`; a `Piece`, not a model piece) is 0, a move wait (0x02200000) when that record's `moveSpeed` at that axis is 0, and a + sleep (0x02400000) subtracts *elapsed* from `delay` and ends when it is 0 or less; each that ends + sets the state to 0x01000000. The 0x02800000 wait has no condition here. +2. A channel whose state class is 0x01000000 runs opcodes until it stops, ends or waits. A channel + ends through RETURN or KILL (below); either makes every channel whose state matches 0x02800000 + under the mask 0xfff00000 and whose `waiting` is its index become 0x01000000. + +The opcode is the word at `code[pc]`, and the dispatch is on `opcode & 0x100ff000`; the table below +gives each case. The stack pointer adds 1 when a word is pushed (the word written at the new +position) and subtracts 1 when a word is taken (the word read at the old position); *op1* and *op2* +are the words at `code[pc+1]` and `code[pc+2]`; *a* is the word taken first (the top) and *b* the one +taken next. All arithmetic is 32-bit and wraps. + +| Case | Behaviour | +| --- | --- | +| 0x10001000 (MOVE) | piece = *op1*, axis = *op2*: `move[axis]` = *a*, `moveSpeed[axis]` = *b* / 30; when `move[axis]` is below the model piece's translation (`rot_x`, `rot_y` or `rot_z`), `moveSpeed[axis]` is negated; `active` 1, `changed` 1; `pc += 3`. | +| 0x10002000 (TURN) | piece, axis: `turn[axis]` = *a* & 0xffff, `acceleration[axis]` 0, `turnSpeed[axis]` = *b* / 30; delta = `turn[axis]` − the model piece's rotation on that axis as an unsigned 16-bit +value (`short_10`, `short_12`, `short_14`); when delta is 0, `turnSpeed[axis]` 0, else when (|delta| > 0x8000) differs from (delta < 0), `turnSpeed[axis]` is negated; `active` 1, `changed` 1; `pc += 3`. | +| 0x10003000 (SPIN) | piece, axis: `turn[axis]` = −1, `spin[axis]` = *a* / 30, `acceleration[axis]` = *b* / 30; when `acceleration[axis]` is 0, `turnSpeed[axis]` = `spin[axis]`; `active` 1, `changed` 1; `pc += 3`. | +| 0x10004000 (STOP_SPIN) | piece, axis: `spin[axis]` 0, `acceleration[axis]` = −(*a* / 30); when `acceleration[axis]` is 0, `turnSpeed[axis]` 0; `pc += 3`. | +| 0x10005000 (SHOW) | the piece *op1* becomes visible: when its bit 0 was clear, it is set, the piece's `modified` becomes 0, and when its `cached` bit is set the state's `cacheDrawCount` becomes 0; `pc += 2`. | +| 0x10006000 (HIDE) | as SHOW with bit 0 cleared; `pc += 2`. | +| 0x10007000 (CACHE) | the piece *op1*'s `cached` bit becomes 1 and the state's `bitmap` becomes 0; `pc += 2`. | +| 0x10008000 (UNCACHE) | the piece *op1*'s `cached` bit becomes 0 and the state's `bitmap` becomes 0; `pc += 2`. | +| 0x10009000 (EXPLODE_LEGACY) | *a* and *b* are taken and discarded; `pc += 2`. | +| 0x1000a000 (PLAY_SOUND) | nothing; `pc += 2`. | +| 0x1000b000 (SET_PIECE_TRANSLATION) | piece, axis: `move[axis]` = *a*, `moveSpeed[axis]` 0, and the model piece's translation on that axis is set (the setter of section 4); `pc += 3`. | +| 0x1000c000 (SET_PIECE_ROTATION) | piece, axis: `turn[axis]` = *a* & 0xffff, `acceleration[axis]` 0, `turnSpeed[axis]` 0, and the model piece's rotation on that axis is set (the setter of section 4); `pc += 3`. | +| 0x1000d000 (SHADE) | the piece *op1*'s `shaded` bit becomes 1 and the state's `bitmap` becomes 0; `pc += 2`. | +| 0x1000e000 (DONTSHADE) | the piece *op1*'s `shaded` bit becomes 0 and the state's `bitmap` becomes 0; `pc += 2`. | +| 0x1000f000 (EMIT_SFX) | *a* is taken, and the effect command runs with piece *op1* and effect *a*; `pc += 2`. | +| 0x10011000 (TURN_NOW) | state 0x02100000, `axis` *op2*, `piece` *op1*, `pc += 3`, and the channel stops this call. | +| 0x10012000 (MOVE_NOW) | state 0x02200000, `axis` *op2*, `piece` *op1*, `pc += 3`, and the channel stops this call. | +| 0x10013000 (SLEEP) | state 0x02400000, `delay` = 30 × *a* / 1000, `pc += 1`, and the channel stops this call. | +| 0x10021000 (PUSH) | when `opcode & 7` is 1 the value is *op1*; 2, `stack[op1]`; 4, `statics[op1]`; the value is pushed; `pc += 2`. | +| 0x10022000 (POP) | `sp` adds 1; `pc += 1`. | +| 0x10023000 (STORE) | when `opcode & 7` is 2, *a* is taken and `stack[op1]` becomes it; 4, *a* is taken and `statics[op1]` becomes it; any other mode takes nothing; `pc += 2`. | +| 0x10024000 (DROP) | `sp` subtracts 1; `pc += 1`. | +| 0x10031000 (ADD) | push *b* + *a*; `pc += 1`. | +| 0x10032000 (SUB) | push *b* − *a*; `pc += 1`. | +| 0x10033000 (MUL) | push *b* × *a*; `pc += 1`. | +| 0x10034000 (DIV) | push *b* / *a*, truncated toward zero; `pc += 1`. | +| 0x10035000 (BIT_AND) | push *b* & *a*; `pc += 1`. | +| 0x10036000 (BIT_OR) | push *b* | *a*; `pc += 1`. | +| 0x10037000 (BIT_XOR) | push *b* ^ *a*; `pc += 1`. | +| 0x10038000 (BIT_NOT) | push ~*a*; `pc += 1`. | +| 0x10041000 (RANDOM) | push the draw of section 5 over the range *a* − *b* + 1, plus *b*; `pc += 1`. | +| 0x10042000 (GET_UNIT_VALUE) | push unit value *a* (below); `pc += 1`. | +| 0x10043000 (GET_UNIT_VALUE_4) | *a*, *b*, *d*, *e*, *f* are taken in that order and the unit value *f* is pushed, for the arguments *e*, *d*, *b*, *a* (below); `pc += 1`. | +| 0x10044000 (IS_CARRYING_UNIT) | push 1 when the unit's `cargo` chain holds a unit whose `id` is *a*, else 0; `pc += 1`. | +| 0x10045000 (GET_TRANSPORTER_ID) | push the `id` of the unit's `carrier`, or 0 when it has none; `pc += 1`. | +| 0x10051000 (LESS) | push 1 when *b* < *a* (signed), else 0; `pc += 1`. | +| 0x10052000 (LESS_EQUAL) | *b* ≤ *a*; `pc += 1`. | +| 0x10053000 (GREATER) | *b* > *a*; `pc += 1`. | +| 0x10054000 (GREATER_EQUAL) | *b* ≥ *a*; `pc += 1`. | +| 0x10055000 (EQUAL) | *b* == *a*; `pc += 1`. | +| 0x10056000 (NOT_EQUAL) | *b* != *a*; `pc += 1`. | +| 0x10057000 (LOGICAL_AND) | *b* && *a*, as 1 or 0; `pc += 1`. | +| 0x10058000 (LOGICAL_OR) | *b* || *a*, as 1 or 0; `pc += 1`. | +| 0x10059000 (LOGICAL_XOR) | *a* is taken, then the next word, and their bitwise xor is pushed; `pc += 1`. | +| 0x1005a000 (LOGICAL_NOT) | push 1 when *a* is 0, else 0; `pc += 1`. | +| 0x10061000 (START) | *op1* is the child's script index and *op2* the count: the child thread starts by that index (the thread start of section 4), and when it started, the top *count* words are moved into its `stack[count-1]` down to `stack[0]` (the words taken one by one, so the first pushed becomes `stack[0]`), and its `signal` becomes the parent's; the child's `sp` stays −1, so it reads its arguments by index; `pc += 3`. When the child cannot start, nothing is taken and nothing is moved. | +| 0x10062000 (START_WAIT) | as START, and then the parent's `waiting` becomes the child's index (a child that could not start gives −1, which nothing ever wakes), its state 0x02800000, `pc += 3`, and the parent stops this call. | +| 0x10063000 (SET_ARG) | *op2* words are taken and discarded; `pc += 3`. | +| 0x10064000 (JUMP) | `pc` becomes *op1*. | +| 0x10065000 (RETURN) | when the channel's callback is not 0, *a* is taken and AIM_DONE is published with the callback and *a*; otherwise the stack is untouched. Then state 0, `activeCount` subtracts 1, the wake rule of the thread run runs for the channel, and the channel stops this call. | +| 0x10066000 (JUMP_IF_ZERO) | *a*: when it is 0, `pc` becomes *op1*, else `pc += 2`. | +| 0x10067000 (KILL) | *a* is the mask; for each channel 0 to 7 whose state is not 0 and whose `signal` shares a bit with the mask, its state becomes 0, `activeCount` subtracts 1, the wake rule runs for it, and when it is this channel the run stops this call; `pc += 1`. | +| 0x10068000 (SET_SIGNAL) | `signal` = *a*; `pc += 1`. | +| 0x10071000 (EXPLODE_PIECE) | *a* flags; EXPLODE_PIECE is published with the unit, piece *op1* and *a*; `pc += 2`. | +| 0x10082000 (SET_UNIT_VALUE) | *a*, then *b*: unit value *b* is set to *a* (below); `pc += 1`. | +| 0x10083000 (ATTACH_UNIT) | *a*, *b*, *d* are taken: the attach operation with id *d*, piece *b* and mode *a*; `pc += 1`. | +| 0x10084000 (DROP_UNIT) | *a*: the drop operation with id *a*; `pc += 1`. | +| any other | state 0, `activeCount` subtracts 1, and the channel stops this call; nothing is woken. | + +**A thread start** by index: the first channel with state 0 becomes runnable, `pc` = the entry offset +of *index*, `sp` −1, `callback` 0, `signal` 1, `activeCount` adds 1, and the index is returned; when +*index* is below 0 or not below the script data's `count`, or no channel is free, nothing starts and +−1 is returned. + +**The setter of a model piece.** Setting a model piece's translation or rotation on an axis writes +the new value only when it differs from the value there; a write sets the piece's `modified` 0 and +the state's `animDirty` 1, and when the piece's `cached` bit is set, the state's `cacheDrawCount` 0. +Setting its visible bit writes nothing when the bit already has that value; a write sets `modified` 0, +and when the piece is cached, `cacheDrawCount` 0 (but not `animDirty`). + +**Unit values**, with *u* the unit the script belongs to. The read's number and arguments are: for +GET_UNIT_VALUE the number is *a* and its four arguments are 0; for GET_UNIT_VALUE_4 the number is *f* +and the arguments are *e*, *d*, *b*, *a* in that order. In the table, *a* and *b* are the first and +second arguments. + +| Value | Result | +| --- | --- | +| 1 | `u.activateFlags` bit 0 | +| 2 | bits 18 and 19 of `u.flags` (0 to 3) | +| 3 | bits 20 and 21 of `u.flags` (0 to 3) | +| 4 | `u.health` taken as a signed 16-bit value, times 100 in 32 bits, divided by `u.maxHealth` (the unit definition's, an unsigned 32-bit value) as an unsigned division of the product read as unsigned, the result as a 32-bit value; so a negative `health` gives a large quotient; `maxHealth` 0 is outside the contract | +| 5, 6 | `u.bit0`, `u.bit1` | +| 7 | the piece position of piece *a*: (`v.x & 0xffff0000`) + (`v.z >> 16`), *v* being its world position | +| 8 | that position's y | +| 9, 10, 11 | the unit at index `a & 0xffff` of the unit table (index 0 is no unit; `Game.poolCount` is not tested), when it is alive (bit 28 of its `flags`): 9, (`pos.z >> 16`) + (`pos.x & 0xffff0000`); 10, `pos.y`; 11, `def.modelMaxY`. Otherwise these give 0. | +| 12 | *a*'s two halves *hi* = `a & 0xffff0000` and *lo* = `a << 16`, *lo* negative adding 0x10000 to *hi*: the angle of the vector (*hi*, *lo*) minus `u.heading`, as an unsigned 16-bit value | +| 13 | the same *hi* and *lo*: `bx_ftol(hypot(hi, lo))` (section 5) | +| 14 | the angle of the vector (*a*, *b*), as an unsigned 16-bit value | +| 15 | `bx_ftol(hypot(a, b))` | +| 16 | a `Vec3` of x = `a & 0xffff0000`, z = `a << 16` (x adding 0x10000 when z is negative), y 0: `map.GetGroundHeight(&v) << 16` | +| 17 | 0 when `u.buildLeft` is 0.0; otherwise 1 − `bx_ftol(u.buildLeft * −99.0)`, as a 32-bit float multiply and a conversion to 32 bits | +| 18, 19 | `u.bit2`, `u.bit3` | +| 20 | `u.activateFlags` bit 1 | +| any other | 0 | + +**Setting a unit value** of *which* and *value*: when *which* is 18, SET_YARD is published first, with +the unit and *value* as `open`; then SCRIPT_VALUE is published with the unit, *which* and *value*. + +**The effect command** of a piece and an effect: when +`los_radar.IsUnitVisibleToPlayer(&Game.players[Game.playerIndex], unit)` returns 0, nothing happens +and nothing is recorded. Otherwise the model is updated by the update rule, and the two positions are +computed: when `effect & 0x100` is not 0, *v1* is the unit's position plus the piece's posed offset +(`pos.x + pieces[piece].offset.x`, `pos.y + ...y`, `pos.z − ...z`) and *v2* is unused; otherwise *v1* +and *v2* are the unit's position plus each of the piece's first two posed vertices: *v1* adds +`points[0]`, `points[1]`, and subtracts `points[2]` from z; *v2* does the same with `points[3]`, +`points[4]`, `points[5]`. Then, by `effect`: + +| Effect | Records | +| --- | --- | +| 0 | THRUST_PARTICLES from *v1* to *v2*, period 1, lifetime 6, list 7 | +| 1 | THRUST_PARTICLES from *v1* to *v2*, period 1, lifetime 7, list 7 | +| 2 | WAKE_PARTICLES from *v1* to *v2*, period 16, list 2 | +| 3 | WAKE_PARTICLES from *v1* to *v2*, period 8, list 2 | +| 4 | WAKE_PARTICLES from *v2* to *v1*, period 16, list 2 | +| 5 | WAKE_PARTICLES from *v2* to *v1*, period 8, list 2 | +| 0x101 | WHITE_SMOKE at *v1*, list 9 | +| 0x102 | BLACK_SMOKE at *v1*, list 9 | +| 0x103 | BUBBLES from *v1* to *v2*, where *v2* is *v1* with y = `Game.seaLevel << 16`, period 8, list 7 | +| any other | nothing recorded | + +The module records each row through `services.RecordSimEvent` (section 2, "Events"). The reference records a publish as an engine call of its own, which the +recordings show as a `services.SchedPublish ` line; a module publishes through `Emit`, +which the engine records as the same effect, so the replay compares the outbox and the size and not +the import's name (ABI 7.2 and 9.3), and the effect's kind and fields, as the tables of section 2 give +them, are what the receiving modules act on. + +**The attach operation** of an id, a piece *a* and a mode *b*: the unit at index *id* (taken as a 16-bit +value) of the unit table, index 0 being no unit and `Game.poolCount` not tested, when it is alive (bit 28 of `flags`) and has no carrier or this unit as its carrier: +ATTACH_TO_PIECE is published with it, the target this unit, piece *a*, mode *b*. + +**The drop operation** of an id: the unit at index *id* (a 16-bit value) of the unit table, as in the attach operation, when it is alive and +this unit is its carrier: when `map.CanPlaceUnitFootprint` with the address of the unit's `def` (a `block` argument: `g_blockBase` plus the offset the unit's `def` holds), the +unit's `id` as a 16-bit value, the address of a copy of the unit's `cell` (a `Point16`, two 16-bit values) in +the module's own memory and the flags 1 returns a value that is not 0, ATTACH_TO_PIECE is published with it, +target 0, piece −1, mode 1. No recording reaches this operation. + +**The piece animation step** of an elapsed count: returns when *elapsed* is 0 or `changed` is 0; +otherwise sets `changed` 0 and, for each piece *p* from 0 to `pieceCount`−1 whose `active` is not 0, +sets `active` 0 and for each axis *j* 0 to 2: + +1. When `moveSpeed[j]` is not 0: *v* = the model piece's translation on *j* plus `elapsed × + moveSpeed[j]`; when `moveSpeed[j]` is positive and *v* reaches or passes `move[j]`, *v* becomes + `move[j]` and `moveSpeed[j]` 0, else `active` 1; when negative and *v* reaches or passes + `move[j]`, *v* becomes `move[j]` and `moveSpeed[j]` 0, else `active` 1. The model piece's + translation on *j* is set to *v* (the setter of section 4). +2. When `acceleration[j]` is not 0: `turnSpeed[j]` adds `acceleration[j]`; when the acceleration is + positive and `turnSpeed[j]` reaches or passes `spin[j]`, `turnSpeed[j]` becomes `spin[j]` and + `acceleration[j]` 0; when negative and `turnSpeed[j]` reaches or passes `spin[j]`, both likewise. +3. When `turnSpeed[j]` is not 0: *r* is the model piece's rotation, *cur* = *r*, step = `elapsed × + turnSpeed[j]`, *r* adds step, and *want* = `turn[j]`. When *want* is not −1: for a positive speed, + when `(want − cur + 0x10000) % 0x10000 ≤ step`, *r* = *want* and `turnSpeed[j]` 0, else `active` 1; + for a negative speed, when `(cur − want + 0x10000) % 0x10000 ≤ −step`, likewise. When *want* is + −1, `active` 1. The model piece's rotation becomes *r* & 0xffff (the setter of section 4). + +When the piece is still active after the axes, `changed` becomes 1. + +### `DeleteScript(script)` + +When `pieces` is not null it is freed with `SimFree`, then `statics` when it is not null, then the +script object itself. Nothing is written to the block; the `Ref` in the unit is the engine's to +clear. + +### `SaveScriptState(script, bank)` + +The bank holds a header record of 0x528 bytes, then the statics (`staticCount × 4` bytes), then for +each piece from 0 to `pieceCount`−1 a `SavedPiece` of 0x6c bytes. The header holds the script's +`checksum`, the eight channels with their callbacks 0 and `activeCount`; a saved piece holds +`visible`, `cached` and `shaded` from the piece's flags, the six arrays, and `translation` and +`rotation` from the model's pieces. This is an engine slot; the module does not export it. + +### `LoadScriptState(script, bank)` + +When the bank's size is not `pieceCount × 0x6c + 0x528 + staticCount × 4`, the result is 0 and nothing +changes. Otherwise a header read of fewer bytes than 0x528 gives 0, and the script's `checksum` must +equal the saved one (else 0). Then the eight channels take the saved ones with their callbacks 0 and +`activeCount` the saved one, the statics take the saved ones (a statics read of fewer bytes than asked +gives 0 then and there, after the channels and the count were already taken), and the pieces take the +saved ones: each becomes `active` 1, its `visible`, `cached` and `shaded` are set, the six arrays +copied, `translation` and `rotation` set through the model's pieces, and `changed` 1. A piece read of +fewer bytes than asked gives 0. The result is 1. This is an engine slot; the module does not export +it. + +### `WriteState(writer)` + +For each unit slot *i* of `Game.units` below `Game.poolCount` whose unit exists and whose `script` is +not null, the writer begins record 55 named `scriptsState.units[i]` and writes: `scale`, `table` (a +heap pointer, written as its address), `checksum`, `changed`, `activeCount`; for each channel, its +`state` (and, when the state is not 0, `pc`, `sp`, `signal`, `callback` as a heap pointer, the first +`min(max(sp+1, 0), 32)` words of `stack`, and, in state class 0x02000000, the substate's fields: +`piece` and `axis` for the turn and move waits, `delay` for the sleep, `waiting` for the child wait); +`statics.count` (the script data's `staticCount`, 0 when the script data is null or above 4096 or the +statics are null) and the statics; and for each piece below `pieceCount` (0 when the script data is +null or above 512, or the pieces are null), `active`, the six arrays. This is an engine slot; the +module does not export it. + +## 5. Exactness + +- **The random draw** (`RANDOM`, unit value none): the draw of *range*, = *a* − *b* + 1 + computed in 32 bits. When *range* < 2 the result is 0 and the stream is not touched. Otherwise, with + *seed* = `rng.seed` as an unsigned 32-bit word, *q* = *seed* / 127773 (unsigned), *correction* = + (*q* << 31) − *q* (unsigned 32-bit, the shift keeping only *q*'s lowest bit), *seed* = *seed* × + 16807 − *correction* (unsigned 32-bit wrap); when *seed* as a signed 32-bit value is 0 or less, + *seed* adds 2147483647; `rng.seed` becomes *seed*; the result is the low 32 bits of *seed* % *range* + (unsigned), as a signed 32-bit value. This is the game logic's own stream, the one `rng.seed` names, + not one of the two block-head streams. +- **A null free**: a `SimFree` of 0 changes nothing and does not trap (ABI section 9.3). +- **Rotating a point** (used by the piece offsets, the pose and the piece getters): + the rule is `runtime/vectors/README.md`, "Rotating a point", which the kit's `rotate_point` vectors + hold to. An angle of 0 leaves the point as it is. Otherwise *t* is the angle as a signed 16-bit + number, the angle in radians is *t* × the double nearest 9.587379924285e-05 rounded to nearest, S + and C are the sine and cosine of that angle rounded to nearest with a 64-bit mantissa (the 80-bit + table of `runtime/bitexact_tables.py`), each of *x* × C, *z* × C, *x* × S and *z* × S is the exact + product rounded to the nearest double, the results are *rx* = *x* × C − *z* × S and *rz* = *z* × C + + *x* × S each a double, and each is rounded to the nearest int, ties to even, with −2147483648 when + it is outside the int range. +- **The three-angle rotation of a point** (x, y, z) by the angles bank, heading and pitch: with + rotate(p, q, a) the point rotation of p and q by angle a (section 5), the steps are + (x, y) = rotate(x, y, bank); (y, z) = rotate(y, z, pitch); and (x, z) = rotate(x, z, heading), each + step on the values the one before it left, in that order. +- **The angle of a vector** (*x*, *z*): the rule is `runtime/vectors/README.md`, "Angle of a + vector": (0, 0) gives 0; otherwise atan2(|x|, z) in [0, π], rounded to nearest with a 64-bit + mantissa and then to a double, multiplied by the double nearest 10430.37835047, rounded to the + nearest int ties to even, and negated when x is negative. +- **hypot and the conversion to int**: `hypot(x, y)` follows `runtime/vectors/README.md`, "hypot" + (each step rounded to a 64-bit mantissa and then to a double, except the squares). `bx_ftol(x)`: + the result is 0 when |x| < 1; otherwise the integer part of |x| truncated, its low 32 bits, negated + when x is negative; a value whose exponent reaches 1023 + 63 gives 0. +- **Division and shifts**: `/` truncates toward zero on a negative result; `%` has the dividend's + sign; `>>` is arithmetic on a signed value; a multiplication or addition wraps at 32 bits. Division + by 0 and the most negative value divided by −1 are outside the contract. +- **Narrow values**: a `short` and a 16-bit rotation, angles and `Vector3s` field wrap at 16 bits; a + `Ref` is a 32-bit offset and a null `Ref` stores 0. +- **Case-insensitive names**: two names match when they differ only in the case of ASCII letters; + bytes above 127 are outside the contract. +- **The pose's arithmetic** is the same three-angle rotation; each vertex and offset is a 32-bit integer. + +## 6. Quirks + +- **Q1: the query's words.** A query's four in-values are the words `stack[0]` to `stack[3]` of the + channel it starts, its `sp` is 3 and its `callback` is 0 when the thread first runs; the answers are + the words `stack[0]` to `stack[3]` after the run, whatever `sp` the run leaves. +- **Q2: a piece of −1.** `GetPieceAngles` with *piece* −1 adds the low 16 bits of the model state's + `count` to the bank, where a piece 0 or more adds its own `short_14`; its pitch and heading are the + unit's alone. A *piece* below −1 is outside the contract. +- **Q3: the operations with no effect.** EXPLODE_LEGACY takes two words and changes nothing; + PLAY_SOUND takes none and changes nothing. +- **Q4: the turn step.** A piece's rotation step in the piece animation is `elapsed × turnSpeed`, + with no further scaling. +- **Q5: the sweet spot's pose.** With the flag `units.render-pose-reads` off (the default), the slot + poses the model from the unit's game state before reading it; with it on, it reads the renderer's + copy, which depends on what has been drawn. This spec states the default. +- **Q6: a thread that ends on an unknown opcode wakes nothing.** The default case clears the state and + decrements the active count but does not wake the channels waiting on it, so a parent that waits on + it waits for ever. + +## 7. Examples + +Calls from the kit's recordings; a call's inputs are the lines it prints. All numbers are decimal +unless written with `0x`. + +1. **`Apply` START by name, from `orders-air`, call at tick 1025 of `Apply`.** Unit#3's script + CobScript#3 is a new script of UnitDef#21 (its data has `count` 19, `pieceCount` 8, `staticCount` + 4); the event is kind 416, unit Unit#3, form 0, name `"Create"`, callback null, update 1, count 0, + size 76. The script has a channel free, so the thread of `Create` starts: `activeCount` 1, channel + 0 state 0x01000000 at `pc` 320 with `sp` −1, `waiting` 1, `signal` 1; the run at once (update 1) + sets `statics` word 0 to 1, starts channel 1 (its `pc` 239 and `signal` 1 are the script's own + writes), and channel 0 waits on it. The outcome is 1. +2. **`Apply` START by index with arguments, from `orders-factory`, call at tick 19 of `Apply`.** + `FindScript(CobScript#1, "StartBuilding")` is 17 in the same recording, and the event is kind 416, + unit Unit#1, form 2, index 17, name empty, callback null, update 0, count 1, arguments 59405, 0, 0, + 0. Channel 2 is free, so it becomes runnable at `pc` 1741, `signal` 1, and the one argument is + `stack[0]` = 59405, `sp` 0; `activeCount` goes from 2 to 3. No thread runs (update 0). Outcome 1. +3. **`Apply` START by name with arguments, from `orders-air`, call at tick 1025 of `Apply`.** Unit#3, + form 1, name `"setSFXoccupy"`, update 1, count 1, arguments 4, 0, 0, 0, size 76: the thread starts, + runs at once, and the call writes nothing else. Outcome 1. +4. **A rejected event.** An event of kind 416 with `size` 75 is below `ScriptsStart`'s 76 bytes: the + outcome is 0 and nothing changes. So is one of kind 500 with size 76, one whose unit offset is 0, + one of kind 417 with `size` 15, and one of kind 418 or 419 whose state offset is 0. +5. **`QueryScript`, from `orders-air`, call at tick 1025.** `QueryScript(CobScript#2, + "QueryBuildInfo", &arg0, 0, 0, 0)` with `arg0` −1: the thread starts (a channel is free), + `stack[0]` to `stack[3]` take (−1, 0, 0, 0), `sp` 3 and the callback 0, the thread runs at once + and leaves `pc` 746, `sp` 5 and `stack[0]` 1 with the seven words above it 0; `arg0` becomes + `stack[0]` = 1 and the result is 1. +6. **`QueryScript` that changes nothing, from `console-iwin`, call at tick 30.** `QueryScript( + CobScript#2, "Killed", &arg0, &arg1, 0, 0)` with `arg0` 100 and `arg1` 0: the script has no + `Killed`, so the result is 0 and `arg0` and `arg1` keep 100 and 0. +7. **`FindScript`, from `orders-factory`, call at tick 19.** `FindScript(CobScript#1, + "StartBuilding")` is 17; a name the script data does not hold is −1. +8. **`GetPieceOffset` and `GetPiecePosition`, from `orders-air`, calls at tick 1025.** + `GetPieceOffset(Unit#3, 0)` is (0, 0, 0), because Unit#3's root piece has `rot` 0 and its object's + box 0. `GetPiecePosition(Unit#2, 1)` is (45681211, 80821, 21015042), which is Unit#2's pos + (45613056, 65536, 19922944) plus the piece's offset (68155, 15285, 1092098); that offset comes from + the piece-offset rule, with piece 1's own `object` box and `rot` (all `rot` 0) and then piece 0's + box, its angles adding Unit#2's heading −32768 to the rotation. The boxes are the node data of + `objects3d\ARMAP.3DO` (`orders-air`'s `load model UnitDef#14` line) as the loaded model holds them, + mirrored: piece 1's box is (−68155, 15285, 1092098) where the file's bytes give (68155, 15285, + −1092098), and piece 0's is (0, 0, 0). The running point starts as (−68155, 15285, 1092098), the + root's rotation by 0x8000 in heading gives (68155, 15285, −1092098), and the offset is (68155, 15285, + 1092098). +9. **`GetPieceAngles`, from `orders-air`, calls at ticks 1025, 1026 and 1027.** `GetPieceAngles( + Unit#2, 1)` is (0, 32768, 0), then (0, 32950, 0), then (0, 33132, 0): Unit#2's bank and pitch are + 0 and its heading is −32768 (0x8000); `pieces[1].short_10` and `pieces[1].short_14` are 0, so bank + is 0 and pitch is 0, and `pieces[1].short_12` is 0, 182 and 364, so heading is 0x8000 + 182 and + 0x8000 + 364 as 16-bit values (32950 and 33132). +10. **`NewUnitScript` and `SetCob`, from `orders-air`, call at tick 1025.** `NewUnitScript(Unit#3)` + allocates 1348 bytes (the import's line `services.SimAlloc 1348`) and writes Unit#3's `script` to + that CobScript, `scale` 30, `table` null, `statics` null, `pieces` null, `activeCount` 0. Then + `SetCob(CobScript#3, UnitDef#21)` (`checksum` is 0 before) makes the import lines + `services.GetCobChecksum UnitDef#21 = -2122848590`, `services.SimRealloc null 608` (the pieces) + and `services.SimRealloc null 16` (the statics), and writes `table` UnitDef#21, `checksum` −2122848590, `statics` 16 + zero bytes (4 words) and `pieces` 608 zero bytes (8 records). +11. **The checksum of example 10.** The module does not compute it: `GetCobChecksum` of the address + `CobScript#3.table` will hold, the loaded script of `UnitDef#21` (its table has 19 scripts, 8 + pieces and 4 statics), answers −2122848590 (0x8177e6b2), and `SetCob` writes that answer to `checksum` + whole. In `orders-factory`, call at tick 19, the same import for `UnitDef#68` answers −938591297. +12. **`CreatePlayerObjectState`, from `orders-air`, call at tick 1025.** `CreatePlayerObjectState( + UnitDef#21's model, UnitDef#21, Unit#3)` allocates 466 bytes (`services.SimAllocTagged "Object + State" 466`) and the eight point lists of 600, 12, 252, 24, 252, 24, 252 and 24 bytes, in that + order; 466 is 8 × 54 + 34 and the point lists are each node's `vertexCount × 12`. The result is + ModelState#3, whose `count` is 8, `owner` Unit#3 and `animDirty` 1. +13. **`FreeObjectState`, from `console-iwin`, call at tick 30.** `FreeObjectState(ModelState#2)` with + `count` 16 frees sixteen point lists and then the state, seventeen `services.SimFree` calls; no + other import is made. +14. **`RunScripts` and a sleep, from `console-iwin`, calls at ticks 29 and 30.** At tick 29 a + script's channel 0 runs a SLEEP of 200: it is left in state 0x02400000 at `pc` 1434 with `delay` 6 + (30 × 200 / 1000), and `stack[0]` 200 stays. At tick 30 with elapsed 1 the delay is 5. At tick 28 + the same channel had just started: state 0x01000000, `pc` 1431, `delay` 0. +15. **`RunScripts` and a spin, from `orders-air`, call at tick 1026.** A script sets `pieces[1]` + (bytes 76 to 151 of the piece array): `active` 1 (byte 76), `turn[1]` −1 (bytes 108 to 111), + `turnSpeed[1]` 182 (bytes 120 to 123) and `spin[1]` 182 (bytes 132 to 135), with its + `acceleration[1]` 0, and `changed` 1. The piece animation step of 1 sets the model's `pieces[1].short_12` to 182 (and its + `animDirty` to 1), then to 364 at tick 1027 (example 9). +16. **`RunScripts` that changes nothing.** A script whose `activeCount` is 0 and whose `changed` is 0 + makes no write and no import, whatever the elapsed. + +The slots and outcomes no recording covers: `StartScriptWithArgsByIndex` called directly (only +through `Apply`), `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`, `PoseUnitModel`, +`UpdateObjectState`, `ObjectStateSize`, `CreateObjectState`, `DeleteScript`, `SaveScriptState`, +`LoadScriptState`, `WriteState`, the DETACH_PIECE, FREE_STATE and INIT_STATE events, the START form +whose name matches no script and the one whose thread cannot start, the effect command (and so all five +sim events), the drop operation, recording `StartScriptWithArgsByIndex`'s failure, and most unit values (the recordings read values 4 and 17, and the write +of value 5 is recorded), and every opcode whose effect no recorded thread produces. + +## 8. Kit version + +Kit `interfaces-v103` and `reference-traces-v65`, the versions the gate judges against. Interface `scripts` 3.0. +For this subsystem they hold what `interfaces-v101` and `reference-traces-v63` hold: the headers, the manifest +entry, the layout, the schema, the ABI's rules for scripts and the recordings of `scripts` are unchanged between them +(v103 adds a view region above the load data in the memory, which this module does not touch). +The imports are against `map` 9, `los_radar` 5 and `services` 4.6. + +The kit's manifest entry is `blocked`, so it has no `fuel_budget` and no `size_budget`, and the host runs the +native default for every slot of it. The gate judges a module of the entry on its recordings, with no fuel or +size budget (`docs/module-abi.md`, sections 4.2 and 15). The gap left in the kit, which the spec works around +(section 2): + +- the translation of the routed effects of other interfaces into the four events `Apply` takes.