From 91ff9c6b8cc27417ac12d05095083e94b3d7daed Mon Sep 17 00:00:00 2001 From: opencode Date: Fri, 27 Nov 2026 22:13:13 +0000 Subject: [PATCH 01/16] Docs: Add the scripts spec Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 860 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 860 insertions(+) create mode 100644 specs/scripts.md diff --git a/specs/scripts.md b/specs/scripts.md new file mode 100644 index 0000000..a4ebbd1 --- /dev/null +++ b/specs/scripts.md @@ -0,0 +1,860 @@ +# 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 without budgets, and the +reference repository's own manifest carries a `blocked` reason for it; the entry the module must have +is this one with the budgets its build picks: + +- `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`: the build picks them (ABI 11.1 and 11.3). The host sets the fuel + counter once for all of the module's slot calls of a tick (ABI 11.2), so `fuel_budget` is ten times + the most fuel any one tick of the gate's scenarios burns across every slot this module runs, queries + and piece getters included; `size_budget` is the most bytes the build's `.wasm` may be. The module + meters itself by rule version 1 and exports `__fuel_set` and `__fuel_get`. +- `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` | `[block] -> block` | +| `FreeObjectState` | `[block] -> void` | +| `NewUnitScript` | `[block] -> void` | +| `SetCob`, `SetObjectState` | `[block, block] -> void` | +| `CreatePlayerObjectState` | `[block, block, 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 | +| `los_radar.IsUnitVisibleToPlayer` | `[block, block] -> int` | the visibility test of the effect command | +| `services.SimAlloc` | `[int] -> linear` | a unit's script; the statics and piece records of `SetCob` | +| `services.SimAllocTagged` | `[linear, int] -> linear` | a model state and the point lists of its pieces | +| `services.SimFree` | `[linear] -> void` | freeing them again | +| `services.Emit` | `[linear, int] -> void` | publishing the five effects of section 4 | + +- Hooks: none. The header annotates every slot "Hooks: none". + +The kit's entry also lacks `services.RecordSimEvent`, which section 4's effect command needs to record its +five sim events; no recording reaches that command, so the entry has no such import. The kit gap is filed +as its own issue, and a module built against the kit's entry records none of those five events. The +entry also has no reallocation service, which `SetCob` needs (section 4): the reference's own +reallocation is not a recorded import, so a module that allocates the two blocks the way section 4 +says adds import lines its recordings do not have. That kit gap is filed too. + +### Arguments outside the block + +- **The event** of `Apply` is a `ScriptsEventHeader` in the module's memory, followed by the payload of + its kind (`ScriptsStart`, `ScriptsDetachPiece` or `ScriptsState`), and `size` is the payload's length + in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and + has outcome 0. +- **The script data handle** (`SetCob`, `CreatePlayerObjectState`) is a handle to a unit type's script + data (ozgb/btm#41), a `block` address that names one unit type's compiled script. It is not read as + a `ScriptTable`; the module reads these values through it, and the recording writes it as the unit + type, `UnitDef#N`: + - `count`: the number of named scripts; + - `pieceCount`: the number of pieces of the unit's model; + - `staticCount`: the number of 32-bit statics; + - `names`: the `count` NUL-terminated script names; + - `entries`: the `count` start offsets of those scripts in `code`; + - `pieceNames`: the `pieceCount` NUL-terminated names of the model's pieces, in model order; + - `code`: the 32-bit words the threads run; + - `checksum`: the four-byte checksum of the script's file, as section 5 computes it. +- **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. +- **`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. +- **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 kit's manifest entry for this module imports no `services.RecordSimEvent`, so the entry as the kit +has it cannot record them; a module built from this spec records none of the five until the entry +lists the import (the kit gap of section 2, "The manifest entry"). + +### 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` 1 or 0 | +| 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. + +## 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 handle to 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. + +**`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; `Push` writes at `++sp`, `Pop` reads and decrements | + +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`. + +**`ScriptTable`** (40 bytes): the kit's record of the script data a handle names; its fields at 4 +(`count`), 8 (`pieceCount`), 16 (`staticCount`), 24 (`entries`), 28 (`names`) and 36 (`code`) are +those of section 2, "Arguments outside the block". The compiled data itself is load-time data outside +the block; the module reads it and never writes it. + +**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 payload (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 payload 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*, 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]`; `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. + +### `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 the root; 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 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)` + +*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; the pieces below the root's first child are restored whatever their +`modified` (that child, its descendants and their siblings), and the root and the model's other +top-level pieces only when their `modified` is 0. Then every piece 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 `short_14`, +`short_12` and `short_10` as x, y and z, with the state's `pos` added first for the root; its delta is +`rot_x + object.box_x`, `rot_y + object.box_y` and `rot_z + object.box_z`. A visit does not change +`modified`. + +### `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. Its other bytes are what the allocation gives them. + +### `SetCob(script, data)` + +`script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise: + +- `script.checksum` becomes the handle's `checksum`; +- `script.pieces` becomes a block of `pieceCount * 76` bytes, set to 0; +- `script.statics` becomes a block of `staticCount * 4` bytes, and its bytes are what the block holds: + a fresh block gives zeros, and a block that grows in place keeps its old bytes. + +The reference grows the two blocks in place (section 2, "The manifest entry", the kit gap); a module +that only allocates and frees gives the same bytes for a script that had none, and differs for one +that had them. + +### `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 handle'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 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 the model piece's `turnSpeed` at the + channel's `axis` is 0, a move wait (0x02200000) when its `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. When a + channel's state becomes 0, every channel whose state matches 0x02800000 under the mask 0xfff00000 + and whose `waiting` is its index becomes 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 moves down by one when a word is pushed (the word written at the +new position) and up by one 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 (`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 entry offset and *op2* the count: a 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 last pushed becomes `stack[0]`), and its `signal` becomes the parent's; `pc += 3`. | +| 0x10062000 (START_WAIT) | as START, and then the parent's `waiting` becomes the child's index, 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 and *a*, *b*, *d*, *e* the 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 * 100 / u.maxHealth` (unsigned division; `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, 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`, wrapped to 16 bits | +| 13 | the same *hi* and *lo*: `bx_ftol(hypot(hi, lo))` (section 5) | +| 14 | the angle of the vector (*a*, *b*) wrapped to 16 bits | +| 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 posed (section 4), 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 | + +As section 2, "Events" says, the kit's entry has no `RecordSimEvent` import, so the module records +none of these five. + +**The attach operation** of an id, a piece *a* and a mode *b*: the unit whose `id` is the 16-bit *id*, +when it exists, 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 whose `id` is the 16-bit *id*, when it exists, is alive and +this unit is its carrier: when the map says the unit's footprint fits at its cell, ATTACH_TO_PIECE is +published with it, target 0, piece −1, mode 1. The map's answer is the engine's call +(`ScheduleMapCanPlaceUnitFootprint`), which this module does not import; a module built against the +kit's entry cannot make it, so it cannot drop a carried unit. The kit gap is filed as its own issue. + +**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 is sought to item 0, and a saved header record of 0x528 bytes is written: the script's +`checksum`, the eight channels with their callbacks 0, and `activeCount`. Then the statics, +`staticCount × 4` bytes. Then, for each piece from 0 to `pieceCount`−1, a `SavedPiece` of 0x6c bytes: +`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 the bank is sought to item 0, a saved header record is read (when the read returns +fewer bytes than 0x528, the result is 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, `activeCount` the saved one, +the statics are read into the script's statics (a read of fewer bytes than asked gives 0 and leaves +what was copied), and the pieces are read: each piece 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. The result is 1. The pieces are read through a buffer of `pieceCount × 0x6c` bytes +from `SimAllocTagged` with the tag `"Piece States"`, freed on success; a short read of the statics +returns 0 with nothing allocated, and a short read of the pieces returns 0 with the buffer still +allocated. 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**: the point is rotated by the bank (angle 0), then the result's second + coordinate and the original z by the pitch (angle 2), then that result's second and the first by the + heading (angle 1): each step is the rule above, 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, π], computed as the double-double + `internal.h`'s `bx_dd_atan2_nonneg` gives it, rounded to the nearest double with a 64-bit mantissa + (`bx_dd_to_x87_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. +- **The script-file checksum**: four bytes over the file's bytes, *a*, *b*, *c* and *d*, all starting + 0, for each byte at index *i*: *a* = (*a* + byte) mod 256, *b* = *b* xor byte, *c* = (*c* + (*i* xor + byte)) mod 256, *d* = *d* xor ((*i* + byte) mod 256). The value is (*d* << 24) | (*c* << 16) | + (*b* << 8) | *a*, as a signed 32-bit integer. +- **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 word for `sp` and its stack.** `QueryScript` addresses the channel's `sp` as + the query count and writes its in-values through it: the count starts at −1, each `++` of it is the + next `stack` word, so the four values land at `stack[0]` to `stack[3]`, and it is then set to 3. + The word it clears is the channel's `callback`, and the answers are read from `stack[0]` to + `stack[3]`. +- **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 and PLAY_SOUND pop their arguments or not and + change nothing; they are the 3.1c operations the engine does not implement. +- **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 model pieces are all at their object's + box and its angles are 0. `GetPiecePosition(Unit#2, 1)` is (45681211, 80821, 21015042), which is + Unit#2's pos (41943040, 65536, 16777216) plus the piece's offset (3738171, 15285, 4237826); that + offset comes from the parent chain of section 4, 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). +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)` 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 file `scripts\ARMATLAS.COB`'s 3846 bytes (`orders-air`'s + `load cob UnitDef#21` line) give, by section 5's formula, −2122848590: the four bytes are 0xb2, + 0xe6, 0x77 and 0x81, and the value is 0x8177e6b2. +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 `acceleration[1]` 182 (bytes 132 to 135), 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), recording `StartScriptWithArgsByIndex`'s failure, and every unit value (4, 7 to 17, 19, 20) +and every opcode whose effect no recorded thread produces. + +## 8. Kit version + +Kit `interfaces-v66` and `reference-traces-v55`, the versions the gate judges against, at commit +`74bdf5ef`. Interface `scripts` 3.0. The imports are against `map` 9, `los_radar` 5 and `services` +4.2. From 3d6ba033af83058b94a822e044945c057a9dcf83 Mon Sep 17 00:00:00 2001 From: opencode Date: Sat, 28 Nov 2026 14:36:40 +0000 Subject: [PATCH 02/16] Docs: Answer the scripts phase 2 review Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index a4ebbd1..e6129f5 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -212,7 +212,7 @@ state. | `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; `Push` writes at `++sp`, `Pop` reads and decrements | +| `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. @@ -332,9 +332,9 @@ push did not write. **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]`; `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. +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` @@ -503,9 +503,9 @@ The thread run of a channel and an elapsed count, with *c* the channel: channel's `axis` is 0, a move wait (0x02200000) when its `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. When a - channel's state becomes 0, every channel whose state matches 0x02800000 under the mask 0xfff00000 - and whose `waiting` is its index becomes 0x01000000. +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 moves down by one when a word is pushed (the word written at the @@ -560,7 +560,7 @@ taken next. All arithmetic is 32-bit and wraps. | 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 entry offset and *op2* the count: a 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 last pushed becomes `stack[0]`), and its `signal` becomes the parent's; `pc += 3`. | +| 0x10061000 (START) | *op1* is the child's entry offset and *op2* the count: a 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; `pc += 3`. | | 0x10062000 (START_WAIT) | as START, and then the parent's `waiting` becomes the child's index, 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*. | @@ -839,8 +839,8 @@ unless written with `0x`. 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 `acceleration[1]` 182 (bytes 132 to 135), and `changed` - 1. The piece animation step of 1 sets the model's `pieces[1].short_12` to 182 (and its + `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. From 372bb4b5cc69850f8eedadd11f9301801cf2222c Mon Sep 17 00:00:00 2001 From: opencode Date: Sat, 28 Nov 2026 15:00:44 +0000 Subject: [PATCH 03/16] Docs: Answer the scripts phase 1 review Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 157 ++++++++++++++++++++++++++++------------------- 1 file changed, 93 insertions(+), 64 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index e6129f5..40da930 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -114,22 +114,31 @@ says adds import lines its recordings do not have. That kit gap is filed too. in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and has outcome 0. - **The script data handle** (`SetCob`, `CreatePlayerObjectState`) is a handle to a unit type's script - data (ozgb/btm#41), a `block` address that names one unit type's compiled script. It is not read as - a `ScriptTable`; the module reads these values through it, and the recording writes it as the unit - type, `UnitDef#N`: - - `count`: the number of named scripts; - - `pieceCount`: the number of pieces of the unit's model; - - `staticCount`: the number of 32-bit statics; - - `names`: the `count` NUL-terminated script names; - - `entries`: the `count` start offsets of those scripts in `code`; - - `pieceNames`: the `pieceCount` NUL-terminated names of the model's pieces, in model order; - - `code`: the 32-bit words the threads run; - - `checksum`: the four-byte checksum of the script's file, as section 5 computes it. + data (ozgb/btm#41): a `block` address that names one unit type's compiled script, written in a + recording as the unit type, `UnitDef#N`. The record there is nine 32-bit words, every pointer in it a + block offset (0 null): + + | Offset | Field | Meaning | + | --- | --- | --- | + | 0 | `count` | the number of named scripts | + | 4 | `pieceCount` | the number of pieces of the unit's model | + | 8 | `staticCount` | the number of 32-bit statics | + | 12 | `checksum` | the four-byte checksum of the script's file (section 5) | + | 16 | `names` | a block offset to `count` NUL-terminated script names | + | 20 | `entries` | a block offset to `count` start indices of those scripts in `code` | + | 24 | `pieceNames` | a block offset to `pieceCount` NUL-terminated names of the model's pieces, in model order | + | 28 | `code` | a block offset to the 32-bit words the threads run | + | 32 | unused | | + + The host builds the record when it loads a unit type's script, and computes the checksum over the + file's bytes; the compiled code, names and entries are load-time data in the shared memory. - **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. @@ -155,6 +164,12 @@ The kit's manifest entry for this module imports no `services.RecordSimEvent`, s has it cannot record them; a module built from this spec records none of the five until the entry lists the import (the kit gap of section 2, "The manifest entry"). +`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 own translation does. The kit +defines no such translation (its `adapters` is empty), so the payload mapping is the engine's and +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 @@ -237,11 +252,13 @@ fields; the slots here read only the shared prefix. 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`. -**`ScriptTable`** (40 bytes): the kit's record of the script data a handle names; its fields at 4 -(`count`), 8 (`pieceCount`), 16 (`staticCount`), 24 (`entries`), 28 (`names`) and 36 (`code`) are -those of section 2, "Arguments outside the block". The compiled data itself is load-time data outside -the block; the module reads it and never writes it. +**The script data handle** (section 2, "Arguments outside the block"): nine words at a block +address; the compiled data it names is load-time data in the shared memory, which the module reads +and never writes. The kit's `ScriptTable` record is the reference's version of the same data; the +handle adds the checksum and the piece names at the offsets section 2 gives. **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 @@ -309,7 +326,7 @@ The START forms, with *name* the event's 32-byte name copied into a 32-byte buff | 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*, the callback, *update*, *count* and *args*. | +| 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 @@ -342,6 +359,11 @@ becomes 3, the thread runs at once with elapsed 0, and each non-null argument po `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.** A piece index outside 0 to the model state's `count`−1, a piece +whose object has fewer vertices than the slot reads, a feature index outside `Game.features`, a null +model, a null unit, and a script data handle whose words do not describe its blocks are outside the +contract; a module need not check them. + ### `FindScript(script, name)` The lowest index *i* below the script data's `count` whose name equals *name* byte for byte; -1 when @@ -448,8 +470,9 @@ to (0,0,0) and its `modified` 0; the pieces below the root's first child are res top-level pieces only when their `modified` is 0. Then every piece 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 `short_14`, -`short_12` and `short_10` as x, y and z, with the state's `pos` added first for the root; its delta is +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`. A visit does not change `modified`. @@ -461,18 +484,20 @@ The size `CreateObjectState` allocates, as section 4 gives it, without allocatin 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. Its other bytes are what the allocation gives them. +and each of the eight channels' `state` 0. The word at offset 0 is not game state: the reference +writes a native table pointer there, no slot reads it and no recording compares it, so a module leaves +it 0. Its other bytes are what the allocation gives them. ### `SetCob(script, data)` `script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise: - `script.checksum` becomes the handle's `checksum`; -- `script.pieces` becomes a block of `pieceCount * 76` bytes, set to 0; -- `script.statics` becomes a block of `staticCount * 4` bytes, and its bytes are what the block holds: - a fresh block gives zeros, and a block that grows in place keeps its old bytes. +- `script.pieces` becomes a block of `pieceCount * 76` bytes whose whole extent is 0; +- `script.statics` becomes a block of `staticCount * 4` bytes holding what the script's statics held + before, a byte the old block did not have holding whatever the allocation gives it. -The reference grows the two blocks in place (section 2, "The manifest entry", the kit gap); a module +The blocks grow in place in the reference (section 2, "The manifest entry", the kit gap); a module that only allocates and frees gives the same bytes for a script that had none, and differs for one that had them. @@ -508,8 +533,8 @@ The thread run of a channel and an elapsed count, with *c* the channel: 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 moves down by one when a word is pushed (the word written at the -new position) and up by one when a word is taken (the word read at the old position); *op1* and *op2* +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. @@ -560,8 +585,8 @@ taken next. All arithmetic is 32-bit and wraps. | 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 entry offset and *op2* the count: a 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; `pc += 3`. | -| 0x10062000 (START_WAIT) | as START, and then the parent's `waiting` becomes the child's index, its state 0x02800000, `pc += 3`, and the parent stops this call. | +| 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. | @@ -585,7 +610,10 @@ the state's `animDirty` 1, and when the piece's `cached` bit is set, the state's 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 and *a*, *b*, *d*, *e* the arguments: +**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 there are no arguments; 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 | | --- | --- | @@ -633,7 +661,10 @@ and *v2* are the unit's position plus each of the piece's first two posed vertic | any other | nothing recorded | As section 2, "Events" says, the kit's entry has no `RecordSimEvent` import, so the module records -none of these five. +none of these five. 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 effect's kind and fields are what is compared, not the +import's name (ABI 7.2 and 9.3). **The attach operation** of an id, a piece *a* and a mode *b*: the unit whose `id` is the 16-bit *id*, when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as its carrier: @@ -673,25 +704,23 @@ clear. ### `SaveScriptState(script, bank)` -The bank is sought to item 0, and a saved header record of 0x528 bytes is written: the script's -`checksum`, the eight channels with their callbacks 0, and `activeCount`. Then the statics, -`staticCount × 4` bytes. Then, for each piece from 0 to `pieceCount`−1, a `SavedPiece` of 0x6c bytes: +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 the bank is sought to item 0, a saved header record is read (when the read returns -fewer bytes than 0x528, the result is 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, `activeCount` the saved one, -the statics are read into the script's statics (a read of fewer bytes than asked gives 0 and leaves -what was copied), and the pieces are read: each piece 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. The result is 1. The pieces are read through a buffer of `pieceCount × 0x6c` bytes -from `SimAllocTagged` with the tag `"Piece States"`, freed on success; a short read of the statics -returns 0 with nothing allocated, and a short read of the pieces returns 0 with the buffer still -allocated. This is an engine slot; the module does not export it. +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)` @@ -726,14 +755,15 @@ module does not export it. 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**: the point is rotated by the bank (angle 0), then the result's second - coordinate and the original z by the pitch (angle 2), then that result's second and the first by the - heading (angle 1): each step is the rule above, in that order. +- **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, π], computed as the double-double - `internal.h`'s `bx_dd_atan2_nonneg` gives it, rounded to the nearest double with a 64-bit mantissa - (`bx_dd_to_x87_double`), multiplied by the double nearest 10430.37835047, rounded to the nearest int - ties to even, and negated when x is negative. + vector": (0, 0) gives 0; otherwise atan2(|x|, z) in [0, π], computed as the double-double the kit's + `runtime/internal.h` gives it (`bx_dd_atan2_nonneg`), rounded to the nearest double with a 64-bit + mantissa (`bx_dd_to_x87_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 @@ -753,16 +783,15 @@ module does not export it. ## 6. Quirks -- **Q1: the query's word for `sp` and its stack.** `QueryScript` addresses the channel's `sp` as - the query count and writes its in-values through it: the count starts at −1, each `++` of it is the - next `stack` word, so the four values land at `stack[0]` to `stack[3]`, and it is then set to 3. - The word it clears is the channel's `callback`, and the answers are read from `stack[0]` to - `stack[3]`. +- **Q1: the query's words.** `QueryScript` counts its in-values in the channel's `sp`: it starts at + −1 and each value is written one word further up, so the four values land at `stack[0]` to + `stack[3]`, and `sp` is then set to 3. The word it clears is the channel's `callback`, and the + answers are read from `stack[0]` to `stack[3]`. - **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 and PLAY_SOUND pop their arguments or not and - change nothing; they are the 3.1c operations the engine does not implement. +- **Q3: the operations with no effect.** EXPLODE_LEGACY takes two words and changes nothing; + PLAY_SOUND takes none and changes nothing. They are 3.1c operations this engine does not implement. - **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 @@ -806,12 +835,12 @@ unless written with `0x`. 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 model pieces are all at their object's - box and its angles are 0. `GetPiecePosition(Unit#2, 1)` is (45681211, 80821, 21015042), which is - Unit#2's pos (41943040, 65536, 16777216) plus the piece's offset (3738171, 15285, 4237826); that - offset comes from the parent chain of section 4, 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). + `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). 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 @@ -850,8 +879,8 @@ through `Apply`), `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`, `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), recording `StartScriptWithArgsByIndex`'s failure, and every unit value (4, 7 to 17, 19, 20) -and every opcode whose effect no recorded thread produces. +sim events), recording `StartScriptWithArgsByIndex`'s failure, and every unit value but 17 (the write +of value 5 is recorded, its read is not), and every opcode whose effect no recorded thread produces. ## 8. Kit version From 53e1c8cad4c35950bf307edd17860c21bdeab670 Mon Sep 17 00:00:00 2001 From: opencode Date: Sat, 28 Nov 2026 15:15:41 +0000 Subject: [PATCH 04/16] Docs: Answer the scripts phase 2 second review Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 76 ++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 42 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 40da930..89d05ae 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -114,24 +114,16 @@ says adds import lines its recordings do not have. That kit gap is filed too. in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and has outcome 0. - **The script data handle** (`SetCob`, `CreatePlayerObjectState`) is a handle to a unit type's script - data (ozgb/btm#41): a `block` address that names one unit type's compiled script, written in a - recording as the unit type, `UnitDef#N`. The record there is nine 32-bit words, every pointer in it a - block offset (0 null): - - | Offset | Field | Meaning | - | --- | --- | --- | - | 0 | `count` | the number of named scripts | - | 4 | `pieceCount` | the number of pieces of the unit's model | - | 8 | `staticCount` | the number of 32-bit statics | - | 12 | `checksum` | the four-byte checksum of the script's file (section 5) | - | 16 | `names` | a block offset to `count` NUL-terminated script names | - | 20 | `entries` | a block offset to `count` start indices of those scripts in `code` | - | 24 | `pieceNames` | a block offset to `pieceCount` NUL-terminated names of the model's pieces, in model order | - | 28 | `code` | a block offset to the 32-bit words the threads run | - | 32 | unused | | - - The host builds the record when it loads a unit type's script, and computes the checksum over the - file's bytes; the compiled code, names and entries are load-time data in the shared memory. + data (ozgb/btm#41). In a recording it is written as the holder, `UnitDef#N`; the kit's replay gives + the linear address of its copy of the unit type's compiled script, outside the block. The record + there is the kit's `ScriptTable`: `count` at 4, `pieceCount` at 8, `staticCount` at 16, `entries` + at 24 (block-independent start indices into `code`), `names` at 28 (`count` NUL-terminated names), + the model's piece names at 32 (`pieceCount` NUL-terminated names) and `code` at 36. The compiled + data is load-time data, which the module reads and never writes. + The file's checksum is not in the record: the reference keeps it beside the table, computed over + the file's bytes (section 5). The kit gives a module no file bytes at `SetCob` and no word for that + checksum, and its manifest kind for the argument is `block` although the table is outside the block; + both are kit gaps, raised on ozgb/byte-tactics-moddable#1197. - **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, @@ -166,9 +158,9 @@ lists the import (the kit gap of section 2, "The manifest entry"). `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 own translation does. The kit -defines no such translation (its `adapters` is empty), so the payload mapping is the engine's and -this spec cannot state it; that is a kit gap, filed with the others. +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 @@ -255,10 +247,11 @@ at 42, `child` at 46 and `parent` at 50, `Ref`. 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 handle** (section 2, "Arguments outside the block"): nine words at a block -address; the compiled data it names is load-time data in the shared memory, which the module reads -and never writes. The kit's `ScriptTable` record is the reference's version of the same data; the -handle adds the checksum and the piece names at the offsets section 2 gives. +**The script data handle** (section 2, "Arguments outside the block"): a handle to a unit type's +compiled script, whose record is the kit's `ScriptTable` (40 bytes: `count` at 4, `pieceCount` 8, +`staticCount` 16, `entries` 24, `names` 28, the model's piece names 32, `code` 36). The compiled +data is load-time data, which the module reads and never writes; the file's checksum is kept beside +the record. **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 @@ -359,10 +352,11 @@ becomes 3, the thread runs at once with elapsed 0, and each non-null argument po `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.** A piece index outside 0 to the model state's `count`−1, a piece -whose object has fewer vertices than the slot reads, a feature index outside `Game.features`, a null -model, a null unit, and a script data handle whose words do not describe its blocks are outside the -contract; a module need not check them. +**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 a script data handle that does not describe +its data are outside the contract, and a module need not check them. ### `FindScript(script, name)` @@ -484,9 +478,9 @@ The size `CreateObjectState` allocates, as section 4 gives it, without allocatin 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. The word at offset 0 is not game state: the reference -writes a native table pointer there, no slot reads it and no recording compares it, so a module leaves -it 0. Its other bytes are what the allocation gives them. +and each of the eight channels' `state` 0. The word at offset 0 is the object's table pointer: the +reference writes a native address there, no slot reads it, and no recording compares its bytes; a +module writes 0. Its other bytes are what the allocation gives them. ### `SetCob(script, data)` @@ -494,12 +488,11 @@ it 0. Its other bytes are what the allocation gives them. - `script.checksum` becomes the handle's `checksum`; - `script.pieces` becomes a block of `pieceCount * 76` bytes whose whole extent is 0; -- `script.statics` becomes a block of `staticCount * 4` bytes holding what the script's statics held - before, a byte the old block did not have holding whatever the allocation gives it. +- `script.statics` becomes a block of `staticCount * 4` bytes: a byte the statics block already held + keeps its value, and a byte beyond it holds whatever the allocation gives (zero for a new block). -The blocks grow in place in the reference (section 2, "The manifest entry", the kit gap); a module -that only allocates and frees gives the same bytes for a script that had none, and differs for one -that had them. +The kit's entry has no reallocation service, so a module allocates the two blocks and frees the old +ones; the reference's own growth leaves no recorded import (the kit gap of section 2). ### `CreatePlayerObjectState(model, data, owner)` @@ -611,7 +604,7 @@ Setting its visible bit writes nothing when the bit already has that value; a wr 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 there are no arguments; for GET_UNIT_VALUE_4 the number is *f* +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. @@ -760,9 +753,8 @@ module does not export it. (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, π], computed as the double-double the kit's - `runtime/internal.h` gives it (`bx_dd_atan2_nonneg`), rounded to the nearest double with a 64-bit - mantissa (`bx_dd_to_x87_double`), multiplied by the double nearest 10430.37835047, rounded to the + 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)`: @@ -791,7 +783,7 @@ module does not export it. `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. They are 3.1c operations this engine does not implement. + 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 From 7060e9d7b57b39cfbfcf7da2e8baa50a7df85edb Mon Sep 17 00:00:00 2001 From: opencode Date: Sun, 29 Nov 2026 01:42:33 +0000 Subject: [PATCH 05/16] Docs: Fix the scripts vptr and SetCob wording Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 89d05ae..5545018 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -478,21 +478,19 @@ The size `CreateObjectState` allocates, as section 4 gives it, without allocatin 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. The word at offset 0 is the object's table pointer: the -reference writes a native address there, no slot reads it, and no recording compares its bytes; a -module writes 0. Its other bytes are what the allocation gives them. +and each of the eight channels' `state` 0. Offset 0 holds the object's table pointer; a module writes +0 there, and it is not one of the fields a recording compares. Its other bytes are what the allocation +gives them. ### `SetCob(script, data)` `script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise: -- `script.checksum` becomes the handle's `checksum`; +- `script.checksum` becomes the checksum of the script's file (section 5), which the handle carries + (section 2 states the kit gap: the kit gives a module no word for it); - `script.pieces` becomes a block of `pieceCount * 76` bytes whose whole extent is 0; -- `script.statics` becomes a block of `staticCount * 4` bytes: a byte the statics block already held - keeps its value, and a byte beyond it holds whatever the allocation gives (zero for a new block). - -The kit's entry has no reallocation service, so a module allocates the two blocks and frees the old -ones; the reference's own growth leaves no recorded import (the kit gap of section 2). +- `script.statics` becomes a block of `staticCount * 4` bytes: an extent the statics block already + held keeps its bytes, and a new extent is 0. ### `CreatePlayerObjectState(model, data, owner)` From 9279e114e0d51b3856d0e9efbb34e624a2b7f1c2 Mon Sep 17 00:00:00 2001 From: opencode Date: Sun, 29 Nov 2026 02:07:50 +0000 Subject: [PATCH 06/16] Docs: Answer the scripts implementer questions Assisted-by: opencode:deepseek-v4.1-flash --- specs/scripts.md | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 5545018..3cd8015 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -118,8 +118,10 @@ says adds import lines its recordings do not have. That kit gap is filed too. the linear address of its copy of the unit type's compiled script, outside the block. The record there is the kit's `ScriptTable`: `count` at 4, `pieceCount` at 8, `staticCount` at 16, `entries` at 24 (block-independent start indices into `code`), `names` at 28 (`count` NUL-terminated names), - the model's piece names at 32 (`pieceCount` NUL-terminated names) and `code` at 36. The compiled - data is load-time data, which the module reads and never writes. + the model's piece names at 32 (`pieceCount` NUL-terminated names) and `code` at 36. `names` and + the piece names are linear addresses of arrays of linear addresses of the names; `entries` is an + array of `count` indices into `code`; `code` is a linear address. The compiled data is load-time + data, which the module reads and never writes. The file's checksum is not in the record: the reference keeps it beside the table, computed over the file's bytes (section 5). The kit gives a module no file bytes at `SetCob` and no word for that checksum, and its manifest kind for the argument is `block` although the table is outside the block; @@ -452,6 +454,9 @@ 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. @@ -460,8 +465,8 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi **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; the pieces below the root's first child are restored whatever their -`modified` (that child, its descendants and their siblings), and the root and the model's other -top-level pieces only when their `modified` is 0. Then every piece is visited once for itself and once +`modified` (that child, its descendants and their siblings), and a piece with no parent (the root +and the model's other top-level pieces) only when its `modified` is 0. Then every piece 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 @@ -484,7 +489,7 @@ gives them. ### `SetCob(script, data)` -`script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise: +`script.table` becomes *data*. When *data* is 0, nothing else happens. Otherwise, in this order: - `script.checksum` becomes the checksum of the script's file (section 5), which the handle carries (section 2 states the kit gap: the kit gives a module no word for it); @@ -501,7 +506,8 @@ for each *i* from 0 to `pieceCount`−1, the lowest *j* from *i* to `count`−1 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 result is the state's address. +`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)` @@ -532,7 +538,8 @@ 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 (`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`. | +| 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`. | @@ -616,9 +623,9 @@ second arguments. | 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, 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`, wrapped to 16 bits | +| 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*) wrapped to 16 bits | +| 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 | @@ -631,7 +638,7 @@ the unit and *value* as `open`; then SCRIPT_VALUE is published with the unit, *w **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 posed (section 4), and the two positions are +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 From a12614db6e767385db0e39a9c54b4ebd0c6d000a Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:58:15 +0000 Subject: [PATCH 07/16] Update: Pin the scripts spec to interfaces-v89 Move the kit to interfaces-v89 and reference-traces-v59. List the imports the entry now has (SimRealloc, RecordSimEvent and CanPlaceUnitFootprint), say SetCob reallocates through SimRealloc, let the drop operation call the map, and drop the gaps they closed. The entry is blocked, so the gate judges recordings only. Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 71 ++++++++++++++++++++++++++---------------------- 1 file changed, 39 insertions(+), 32 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 3cd8015..32e3733 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -43,9 +43,10 @@ The engine slots, which the module does not export and the engine's own code ans ### The manifest entry -The kit's manifest (`wasm/modules.json`) carries this module's entry without budgets, and the -reference repository's own manifest carries a `blocked` reason for it; the entry the module must have -is this one with the budgets its build picks: +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`, @@ -60,11 +61,8 @@ is this one with the budgets its build picks: - `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`: the build picks them (ABI 11.1 and 11.3). The host sets the fuel - counter once for all of the module's slot calls of a tick (ABI 11.2), so `fuel_budget` is ten times - the most fuel any one tick of the gate's scenarios burns across every slot this module runs, queries - and piece getters included; `size_budget` is the most bytes the build's `.wasm` may be. The module - meters itself by rule version 1 and exports `__fuel_set` and `__fuel_get`. +- `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: @@ -92,20 +90,19 @@ is this one with the budgets its build picks: | 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; the statics and piece records of `SetCob` | +| `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.Emit` | `[linear, int] -> void` | publishing the five effects of section 4 | - Hooks: none. The header annotates every slot "Hooks: none". -The kit's entry also lacks `services.RecordSimEvent`, which section 4's effect command needs to record its -five sim events; no recording reaches that command, so the entry has no such import. The kit gap is filed -as its own issue, and a module built against the kit's entry records none of those five events. The -entry also has no reallocation service, which `SetCob` needs (section 4): the reference's own -reallocation is not a recorded import, so a module that allocates the two blocks the way section 4 -says adds import lines its recordings do not have. That kit gap is filed too. +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 @@ -154,9 +151,9 @@ arguments, flags and phases are as `docs/sim-events.md` gives them: 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 kit's manifest entry for this module imports no `services.RecordSimEvent`, so the entry as the kit -has it cannot record them; a module built from this spec records none of the five until the entry -lists the import (the kit gap of section 2, "The manifest entry"). +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 @@ -493,9 +490,11 @@ gives them. - `script.checksum` becomes the checksum of the script's file (section 5), which the handle carries (section 2 states the kit gap: the kit gives a module no word for it); -- `script.pieces` becomes a block of `pieceCount * 76` bytes whose whole extent is 0; -- `script.statics` becomes a block of `staticCount * 4` bytes: an extent the statics block already - held keeps its bytes, and a new extent is 0. +- `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)` @@ -658,8 +657,7 @@ and *v2* are the unit's position plus each of the piece's first two posed vertic | 0x103 | BUBBLES from *v1* to *v2*, where *v2* is *v1* with y = `Game.seaLevel << 16`, period 8, list 7 | | any other | nothing recorded | -As section 2, "Events" says, the kit's entry has no `RecordSimEvent` import, so the module records -none of these five. The reference records a publish as an engine call of its own, which the +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 effect's kind and fields are what is compared, not the import's name (ABI 7.2 and 9.3). @@ -669,10 +667,10 @@ when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as ATTACH_TO_PIECE is published with it, the target this unit, piece *a*, mode *b*. **The drop operation** of an id: the unit whose `id` is the 16-bit *id*, when it exists, is alive and -this unit is its carrier: when the map says the unit's footprint fits at its cell, ATTACH_TO_PIECE is -published with it, target 0, piece −1, mode 1. The map's answer is the engine's call -(`ScheduleMapCanPlaceUnitFootprint`), which this module does not import; a module built against the -kit's entry cannot make it, so it cannot drop a carried unit. The kit gap is filed as its own issue. +this unit is its carrier: when `map.CanPlaceUnitFootprint` with the unit's `def` (as a block offset), 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, @@ -846,7 +844,8 @@ unless written with `0x`. 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)` writes `table` UnitDef#21, `checksum` −2122848590, `statics` 16 + `SetCob(CobScript#3, UnitDef#21)` makes the import lines `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 file `scripts\ARMATLAS.COB`'s 3846 bytes (`orders-air`'s `load cob UnitDef#21` line) give, by section 5's formula, −2122848590: the four bytes are 0xb2, @@ -876,11 +875,19 @@ through `Apply`), `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`, `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), recording `StartScriptWithArgsByIndex`'s failure, and every unit value but 17 (the write +sim events), the drop operation, recording `StartScriptWithArgsByIndex`'s failure, and every unit value but 17 (the write of value 5 is recorded, its read is not), and every opcode whose effect no recorded thread produces. ## 8. Kit version -Kit `interfaces-v66` and `reference-traces-v55`, the versions the gate judges against, at commit -`74bdf5ef`. Interface `scripts` 3.0. The imports are against `map` 9, `los_radar` 5 and `services` -4.2. +Kit `interfaces-v89` and `reference-traces-v59`, the versions the gate judges against. Interface `scripts` 3.0. +The imports are against `map` 9, `los_radar` 5 and `services` 4.5. + +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 gaps left in the kit, which the spec works around +(section 2): + +- the file checksum of a script, which a module has no word for; +- the manifest kind of the script data handle, `block`, although the table is outside the block; +- the translation of the routed effects of other interfaces into the four events `Apply` takes. From aefb925f23b9b8d0b758024214c83aa71fcba446 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:00:27 +0000 Subject: [PATCH 08/16] Fix: List RandomInt in the scripts imports The kit entry lists services.RandomInt; say that no recording calls it and the module draws from rng.seed itself. Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 1 + 1 file changed, 1 insertion(+) diff --git a/specs/scripts.md b/specs/scripts.md index 32e3733..aa6dd32 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -97,6 +97,7 @@ judges a module of the entry on its recordings alone, with no scenario, fuel bud | `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 the draw of section 5 from `rng.seed` itself | | `services.Emit` | `[linear, int] -> void` | publishing the five effects of section 4 | - Hooks: none. The header annotates every slot "Hooks: none". From 5ba7776e187cfd99518549be999dcf8e5f1ca6bf Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:13:27 +0000 Subject: [PATCH 09/16] Update: Pin the scripts spec to interfaces-v101 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 89 +++++++++++++++++++++++++----------------------- 1 file changed, 46 insertions(+), 43 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index aa6dd32..927e437 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -78,11 +78,12 @@ judges a module of the entry on its recordings alone, with no scenario, fuel bud | `GetAimFromPosition` | `[linear, linear, int] -> void` | | `PoseUnitModel`, `UpdateObjectState` | `[linear] -> void` | | `ObjectStateSize` | `[linear] -> int` | -| `CreateObjectState` | `[block] -> block` | +| `CreateObjectState` | `[linear] -> block` | | `FreeObjectState` | `[block] -> void` | | `NewUnitScript` | `[block] -> void` | -| `SetCob`, `SetObjectState` | `[block, block] -> void` | -| `CreatePlayerObjectState` | `[block, block, block] -> block` | +| `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: @@ -98,6 +99,7 @@ judges a module of the entry on its recordings alone, with no scenario, fuel bud | `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 the draw of section 5 from `rng.seed` itself | +| `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". @@ -111,19 +113,25 @@ A recording carries the scheduler's own name for one of these calls: `services.S its kind (`ScriptsStart`, `ScriptsDetachPiece` or `ScriptsState`), and `size` is the payload's length in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and has outcome 0. -- **The script data handle** (`SetCob`, `CreatePlayerObjectState`) is a handle to a unit type's script - data (ozgb/btm#41). In a recording it is written as the holder, `UnitDef#N`; the kit's replay gives - the linear address of its copy of the unit type's compiled script, outside the block. The record - there is the kit's `ScriptTable`: `count` at 4, `pieceCount` at 8, `staticCount` at 16, `entries` - at 24 (block-independent start indices into `code`), `names` at 28 (`count` NUL-terminated names), - the model's piece names at 32 (`pieceCount` NUL-terminated names) and `code` at 36. `names` and - the piece names are linear addresses of arrays of linear addresses of the names; `entries` is an - array of `count` indices into `code`; `code` is a linear address. The compiled data is load-time - data, which the module reads and never writes. - The file's checksum is not in the record: the reference keeps it beside the table, computed over - the file's bytes (section 5). The kit gives a module no file bytes at `SetCob` and no word for that - checksum, and its manifest kind for the argument is `block` although the table is outside the block; - both are kit gaps, raised on ozgb/byte-tactics-moddable#1197. +- **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, @@ -195,7 +203,7 @@ All of it is in the block, allocated with `SimAlloc` or `SimAllocTagged` and rea | Field | Offset | Meaning | | --- | --- | --- | | `scale` | 4 | ticks per second the script's speeds are divided by: 30 | -| `table` | 8 | the handle to the unit type's script data, 0 before one is set | +| `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 | @@ -247,11 +255,10 @@ at 42, `child` at 46 and `parent` at 50, `Ref`. 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 handle** (section 2, "Arguments outside the block"): a handle to a unit type's -compiled script, whose record is the kit's `ScriptTable` (40 bytes: `count` at 4, `pieceCount` 8, -`staticCount` 16, `entries` 24, `names` 28, the model's piece names 32, `code` 36). The compiled -data is load-time data, which the module reads and never writes; the file's checksum is kept beside -the record. +**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 @@ -355,8 +362,8 @@ 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 a script data handle that does not describe -its data are outside the contract, and a module need not check them. +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. ### `FindScript(script, name)` @@ -481,16 +488,16 @@ The size `CreateObjectState` allocates, as section 4 gives it, without allocatin 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 object's table pointer; a module writes -0 there, and it is not one of the fields a recording compares. Its other bytes are what the allocation -gives them. +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, so that the engine's slots recognise the object. 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 checksum of the script's file (section 5), which the handle carries - (section 2 states the kit gap: the kit gives a module no word for it); +- `script.checksum` becomes the result of `services.GetCobChecksum(data)` (section 2); - `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 @@ -501,7 +508,7 @@ gives them. 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 handle's `pieceCount` names: +*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`, @@ -764,10 +771,6 @@ module does not export it. (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. -- **The script-file checksum**: four bytes over the file's bytes, *a*, *b*, *c* and *d*, all starting - 0, for each byte at index *i*: *a* = (*a* + byte) mod 256, *b* = *b* xor byte, *c* = (*c* + (*i* xor - byte)) mod 256, *d* = *d* xor ((*i* + byte) mod 256). The value is (*d* << 24) | (*c* << 16) | - (*b* << 8) | *a*, as a signed 32-bit integer. - **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. @@ -845,12 +848,14 @@ unless written with `0x`. 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)` makes the import lines `services.SimRealloc null 608` (the pieces) + `SetCob(CobScript#3, UnitDef#21)` reads `checksum` (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 file `scripts\ARMATLAS.COB`'s 3846 bytes (`orders-air`'s - `load cob UnitDef#21` line) give, by section 5's formula, −2122848590: the four bytes are 0xb2, - 0xe6, 0x77 and 0x81, and the value is 0x8177e6b2. +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 @@ -881,14 +886,12 @@ of value 5 is recorded, its read is not), and every opcode whose effect no recor ## 8. Kit version -Kit `interfaces-v89` and `reference-traces-v59`, the versions the gate judges against. Interface `scripts` 3.0. -The imports are against `map` 9, `los_radar` 5 and `services` 4.5. +Kit `interfaces-v101` and `reference-traces-v63`, the versions the gate judges against. Interface `scripts` 3.0. +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 gaps left in the kit, which the spec works around +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 file checksum of a script, which a module has no word for; -- the manifest kind of the script data handle, `block`, although the table is outside the block; - the translation of the routed effects of other interfaces into the four events `Apply` takes. From e54b8f2f1237768cf3714e92de4f9c70c52c8d43 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:16:25 +0000 Subject: [PATCH 10/16] Update: Tighten the scripts SetCob wording Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 927e437..1dd6b13 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -490,14 +490,15 @@ A `UnitScript` of 1348 bytes is allocated with `SimAlloc` and stored in the unit 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, so that the engine's slots recognise the object. Its other bytes are what +`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); +- `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 @@ -848,7 +849,7 @@ unless written with `0x`. 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)` reads `checksum` (0 before), makes the import lines + `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). From 83ab74661dbf411bc0506e06851f609314f5fde8 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:35:32 +0000 Subject: [PATCH 11/16] Update: Answer the scripts phase 1 review Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 82 ++++++++++++++++++++++++++++++------------------ 1 file changed, 51 insertions(+), 31 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 1dd6b13..849d315 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -109,9 +109,11 @@ A recording carries the scheduler's own name for one of these calls: `services.S ### Arguments outside the block -- **The event** of `Apply` is a `ScriptsEventHeader` in the module's memory, followed by the payload of - its kind (`ScriptsStart`, `ScriptsDetachPiece` or `ScriptsState`), and `size` is the payload's length - in bytes. The event is an intent, validated as section 4 says; a rejected one changes nothing and +- **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 @@ -141,7 +143,8 @@ A recording carries the scheduler's own name for one of these calls: `services.S 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. + `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. @@ -178,7 +181,7 @@ starts with the interface's event header, whose `kind` the effect's kind is, and | Effect | Kind | Payload | Fields | | --- | --- | --- | --- | -| SET_YARD, to map | 164 | `MapSetYard`, 12 bytes | the unit; `open` 1 or 0 | +| 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 | @@ -189,7 +192,8 @@ must be valid are: SET_YARD, a unit offset that is a unit; AIM_DONE, a callback 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. +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. ## 3. State @@ -212,7 +216,10 @@ All of it is in the block, allocated with `SimAlloc` or `SimAllocTagged` and rea | `activeCount` | 1340 | the number of channels that are not free | **`UnitScript`** (1348 bytes): `CobScript`, then `state` at 1344, `Ref`: the unit's model -state. +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): @@ -307,7 +314,7 @@ 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 payload (76 bytes for +`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: @@ -320,7 +327,7 @@ outcome is 1 and the kind's row applies: | 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 payload as a callback, *update* the word at +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 | @@ -363,7 +370,11 @@ with nothing written, not even through the argument pointers, when it did not. 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. +its own counts are outside the contract, and a module need not check them. So are the faults of a +script's code: an opcode's piece, axis or statics index out of range, 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)` @@ -381,6 +392,11 @@ halves bank = `q.short_14`, heading = `q.short_12` and pitch = `q.short_10`, the (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). @@ -469,16 +485,16 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi **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; the pieces below the root's first child are restored whatever their -`modified` (that child, its descendants and their siblings), and a piece with no parent (the root -and the model's other top-level pieces) only when its `modified` is 0. Then every piece is visited once for itself and once +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. Then every piece 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`. A visit does not change -`modified`. +`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)` @@ -529,8 +545,8 @@ piece animation step runs with *elapsed*. With `activeCount` 0 only the piece an 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 the model piece's `turnSpeed` at the - channel's `axis` is 0, a move wait (0x02200000) when its `moveSpeed` at that axis is 0, and a + 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 @@ -626,7 +642,7 @@ second arguments. | 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 * 100 / u.maxHealth` (unsigned division; `maxHealth` 0 is outside the contract) | +| 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 | @@ -667,9 +683,10 @@ and *v2* are the unit's position plus each of the piece's first two posed vertic | 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 effect's kind and fields are what is compared, not the -import's name (ABI 7.2 and 9.3). +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 whose `id` is the 16-bit *id*, when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as its carrier: @@ -694,9 +711,9 @@ sets `active` 0 and for each axis *j* 0 to 2: 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 + 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. @@ -783,10 +800,9 @@ module does not export it. ## 6. Quirks -- **Q1: the query's words.** `QueryScript` counts its in-values in the channel's `sp`: it starts at - −1 and each value is written one word further up, so the four values land at `stack[0]` to - `stack[3]`, and `sp` is then set to 3. The word it clears is the channel's `callback`, and the - answers are read from `stack[0]` to `stack[3]`. +- **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. @@ -840,7 +856,11 @@ unless written with `0x`. (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). + `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 @@ -882,8 +902,8 @@ through `Apply`), `GetNanoPiecePosition`, `GetAimFromPosition`, `GetSweetSpot`, `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 every unit value but 17 (the write -of value 5 is recorded, its read is not), and every opcode whose effect no recorded thread produces. +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 From 2aa14ce36b44430200fdfa708bd8bbf0e33c685e Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:43:06 +0000 Subject: [PATCH 12/16] Update: Pin the scripts spec to interfaces-v102 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 849d315..b3b7464 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -193,7 +193,8 @@ EXPLODE_PIECE, a unit offset that is a unit and a piece below the model's 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. +script gives them (a piece index, flags or a value are passed unchanged) and checks none of them; the attach +operation's own tests of the unit and its carrier (section 4) are the exception. ## 3. State @@ -487,7 +488,7 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi `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. Then every piece is visited once for itself and once +is restored only when its `modified` is 0. Then every piece under the root 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 @@ -907,7 +908,9 @@ of value 5 is recorded), and every opcode whose effect no recorded thread produc ## 8. Kit version -Kit `interfaces-v101` and `reference-traces-v63`, the versions the gate judges against. Interface `scripts` 3.0. +Kit `interfaces-v102` and `reference-traces-v64`, 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 ABI and the recordings of `scripts` are unchanged between them. 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 From 9cdacffe5d85393f1fec925ce5138d33a3675897 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:59:31 +0000 Subject: [PATCH 13/16] Update: Answer scripts review round 1 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index b3b7464..0a6b6af 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -98,7 +98,7 @@ judges a module of the entry on its recordings alone, with no scenario, fuel bud | `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 the draw of section 5 from `rng.seed` itself | +| `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 | @@ -372,7 +372,7 @@ state and for a piece outside 0 to `count`−1, and `GetPieceAngles` defines a p 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: an opcode's piece, axis or statics index out of range, a stack that underflows or +script's code: 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). @@ -488,7 +488,7 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi `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. Then every piece under the root is visited once for itself and once +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 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 @@ -694,7 +694,7 @@ when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as ATTACH_TO_PIECE is published with it, the target this unit, piece *a*, mode *b*. **The drop operation** of an id: the unit whose `id` is the 16-bit *id*, when it exists, is alive and -this unit is its carrier: when `map.CanPlaceUnitFootprint` with the unit's `def` (as a block offset), the +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. From f762d66422dddeada5ae926bfea6d2932034d96a Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:16:26 +0000 Subject: [PATCH 14/16] Update: Answer scripts review round 2 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 0a6b6af..98f5f7b 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -193,8 +193,9 @@ EXPLODE_PIECE, a unit offset that is a unit and a piece below the model's 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; the attach -operation's own tests of the unit and its carrier (section 4) are the exception. +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 @@ -372,7 +373,7 @@ state and for a piece outside 0 to `count`−1, and `GetPieceAngles` defines a p 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: 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 +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). @@ -389,7 +390,7 @@ is below 0 or not below *state.count*, it is (0, 0, 0). Otherwise the running po 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 the root; the running point is rotated by those angles +`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. @@ -488,7 +489,7 @@ Then, when `animDirty` is not 0, the model is posed by the pose rule and `animDi `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 is visited once for itself and once +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 From 5b1ca639d7f72c0a9cbb704454ce71fec7a42563 Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:33:56 +0000 Subject: [PATCH 15/16] Update: Say how scripts find the unit of an id Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index 98f5f7b..ce51c4c 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -648,7 +648,7 @@ second arguments. | 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, 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. | +| 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 | @@ -690,11 +690,11 @@ which the engine records as the same effect, so the replay compares the outbox a 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 whose `id` is the 16-bit *id*, -when it exists, is alive (bit 28 of `flags`) and has no carrier or this unit as its carrier: +**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 whose `id` is the 16-bit *id*, when it exists, is alive and +**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, From a2c2e1d5e515c9c4f01803548b2032102e57cbff Mon Sep 17 00:00:00 2001 From: Oscar Bailey <79094698+ozgb@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:56:07 +0000 Subject: [PATCH 16/16] Update: Pin the scripts spec to interfaces-v103 Assisted-by: Claude:claude-sonnet-5-5 --- specs/scripts.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/specs/scripts.md b/specs/scripts.md index ce51c4c..295bb32 100644 --- a/specs/scripts.md +++ b/specs/scripts.md @@ -909,9 +909,10 @@ of value 5 is recorded), and every opcode whose effect no recorded thread produc ## 8. Kit version -Kit `interfaces-v102` and `reference-traces-v64`, the versions the gate judges against. Interface `scripts` 3.0. +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 ABI and the recordings of `scripts` are unchanged between them. +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