diff --git a/compiler/backend/emit.ts b/compiler/backend/emit.ts index 417774f..5bf98bf 100644 --- a/compiler/backend/emit.ts +++ b/compiler/backend/emit.ts @@ -230,8 +230,9 @@ export function unlowered(s: Stmt, decls: Map, arrays: Map, arrays: Map; if (o.kind === "var" && typeof o.id === "string" && (h.written.has(o.id) || isTemp(o.id))) pure = false; if (o.kind === "element" && h.arrays.has(o.array as string)) pure = false; - if (o.kind === "call" || o.kind === "read" || o.kind === "randomInt" || o.kind === "input" || o.kind === "unitField" || o.kind === "tableRead" || o.kind === "pop") pure = false; + if (o.kind === "call" || o.kind === "read" || o.kind === "randomInt" || o.kind === "input" || o.kind === "unitField" || o.kind === "unitDistance" || o.kind === "tableRead" || o.kind === "pop") pure = false; Object.values(o).forEach(walk); }; walk(e); diff --git a/compiler/backend/units.ts b/compiler/backend/units.ts index b2c3cf7..348b464 100644 --- a/compiler/backend/units.ts +++ b/compiler/backend/units.ts @@ -19,6 +19,8 @@ */ import type { ArrayDecl, At, BoolExpr, Call, CompareOp, FuncDecl, NumExpr, Program, Stmt, UnitExpr, UnitFilter, UnitFlag, UnitNumField, VarDecl } from "../ir"; import type { ActionRecord, ConditionRecord } from "../../vendor/triggers"; +import { CAST_ORDERS, GATHER_ORDERS, GATHER_WORKERS, STOP_ORDER } from "../orders"; +import { UNIT_DIMENSIONS } from "../tables"; import { STATEMENT_KINDS } from "./emit"; import { MOUSE_CELLS } from "./input"; @@ -32,7 +34,7 @@ const CURRENT = epd(0x6509b0); /** The game's locations: 20 bytes each, from 1. */ const MRGN = epd(0x58dc60); /** units.dat: hit points (a dword a type, 256 to a point), shields (a word a type), the group flags (a byte a type). */ -const MAX_HP = epd(0x662350), MAX_SHIELDS = epd(0x660e00), GROUPS = epd(0x6637a0); +const MAX_HP = epd(0x662350), MAX_SHIELDS = epd(0x660e00), GROUPS = epd(0x6637a0), DIMENSIONS = epd(UNIT_DIMENSIONS); /** * A filter's type that is one type, asked of a unit's type word (16 bits): the game's 0–227, and a data set's past the * classes (a mod's units from 233 on). 228 is the game's None and 229–232 the trigger's classes. @@ -71,11 +73,15 @@ const word = (byte: number, bytes: 1 | 2 | 4): Bits => { const SPRITE = 0x0c >> 2, POSITION = 0x28 >> 2, UID = word(0xa5, 1); /** The owner and the order share a dword: the owner its low byte, the order the next. */ const OWNER = word(0x4c, 1), ORDER = word(0x4d, 1), TYPE = word(0x64, 2); +/** The order's state, beside the order in its dword: what `gather()` and `cast()` put back to the start. */ +const ORDER_STATE = word(0x4e, 1); const X = word(0x28, 2), Y = word(0x2a, 2); const FIELDS: Partial> = { owner: OWNER, type: TYPE, x: X, y: Y, kills: word(0x8f, 1), orderId: ORDER, cooldown: word(0x55, 1), resources: word(0xd0, 2), stim: word(0x115, 1), ensnare: word(0x116, 1), lockdown: word(0x117, 1), irradiate: word(0x118, 1), stasis: word(0x119, 1), plague: word(0x11a, 1), maelstrom: word(0x124, 1), buildTime: word(0xac, 2), rank: word(0x8e, 1), matrix: word(0x114, 1), speed: word(0x38, 4), + orderTargetX: word(0x58, 2), orderTargetY: word(0x5a, 2), + acidSpores: word(0x126, 1), orderState: ORDER_STATE, queuedOrders: word(0x84, 1), }; const HP = 0x08 >> 2, SHIELDS = 0x60 >> 2, ENERGY = word(0xa2, 2), STATUS = 0xdc >> 2, USER_ACTION = word(0x93, 1); /** @@ -86,6 +92,8 @@ const HP = 0x08 >> 2, SHIELDS = 0x60 >> 2, ENERGY = word(0xa2, 2), STATUS = 0xdc * one "recently hit" signal a map may read. */ const ATTACKED = word(0x87, 1); +/** Optical Flare: a bit for each player whose Medic flared the unit, all cleared by Restoration. */ +const FLARED = word(0x123, 1); /** The status bits a flag is (cloaked: both of two). */ const FLAG_BITS: Partial> = { invincible: 0x04000000, hallucinated: 0x40000000, burrowed: 0x10, cloaked: 0x300, speedUpgrade: 0x10000000, inTransport: 0x40 }; /** The unit an order is aimed at (a pointer, 0 for none), and the defensive matrix's hit points (a word, 256 a point) beside its timer. */ @@ -655,6 +663,17 @@ export function unitValues(program: Program, events?: { sources: Set [set(p, h(POINTER, 2))]), + ...when(cmp(">=", V(p), k(IN_TABLE)), [set(p, bin("-", V(p), k(DEATHS / 4)))], [set(p, k(0))]), + ])); + return { e: ranged(V(p), 0, UNIT_TABLE + STRIDE * PLACES), k: null, none: true, killed: true }; + } case "unitAt": { const ptr = plain(fix(e.ptr, pre) as NumExpr, pre); fix(e.epd, pre); @@ -711,11 +730,51 @@ export function unitValues(program: Program, events?: { sources: Set=", bits(u.e, ATTACKED), k(1))]); if (f === "hasTarget") return all([alive(u), cmp(">=", peek(of(u.e, ORDER_TARGET)), k(1))]); + if (f === "opticalFlare") return all([alive(u), cmp(">=", bits(u.e, FLARED), k(1))]); const mask = FLAG_BITS[f]; if (mask === undefined) throw new Leave(); return all([alive(u), cmp("==", peek(of(u.e, STATUS), mask), k(mask))]); }; + /** + * How far apart two units are as the game measures a range (`units_distance`): the gap between their boxes, each its + * type's dimensions around its centre, along x and along y, made one length by the game's `xy_length`. 0 when either + * is none or gone. + */ + const distance = (a0: Unit, b0: Unit, pre: Stmt[]): NumExpr => { + if (isNone(a0) || isNone(b0)) return k(0); + const a = held(a0, pre), b = held(b0, pre); + const t = fresh("d"), body: Stmt[] = []; + // (Every side 256 to the right of where it is, so that none of them is below zero.) + const box = (u: Unit) => { + const [x, y, ty, left, up, right, down] = ["x", "y", "ty", "l", "u", "r", "b"].map((what) => fresh(what)); + body.push(...[x, y, ty, left, up, right, down].map((id) => dec(id, k(0), 0xffff))); + body.push(...through(of(u.e, POSITION), (h) => [set(x, h(X.mask, X.shift)), set(y, h(Y.mask, Y.shift))]), ...readInto(ty, u.e, TYPE)); + const at_ = bin("+", k(DIMENSIONS), bin("*", ranged(V(ty), 0, 0xffff), k(2))); + body.push(...through(at_, (h) => [set(left, h(0xffff)), set(up, h(0xffff0000, 16))]), ...through(bin("+", at_, k(1)), (h) => [set(right, h(0xffff)), set(down, h(0xffff0000, 16))])); + const w = (id: string) => ranged(V(id), 0, 0xffff); + return { left: bin("-", bin("+", w(x), k(256)), w(left)), top: bin("-", bin("+", w(y), k(256)), w(up)), right: bin("+", bin("+", w(x), w(right)), k(257)), bottom: bin("+", bin("+", w(y), w(down)), k(257)) }; + }; + const p = box(a), q = box(b); + const gap = (id: string, from1: NumExpr, to1: NumExpr, from2: NumExpr, to2: NumExpr): Stmt[] => { + const s = [fresh("s1"), fresh("e1"), fresh("s2"), fresh("e2")]; + const [f1, t1, f2, t2] = s.map((v) => ranged(V(v), 0, 0x20000)); + return [dec(s[0], from1, 0x20000), dec(s[1], to1, 0x20000), dec(s[2], from2, 0x20000), dec(s[3], to2, 0x20000), dec(id, k(0), 0x20000), + ...when(cmp(">", f1, t2), [set(id, bin("-", f1, t2))], when(cmp(">", f2, t1), [set(id, bin("-", f2, t1))]))]; + }; + const longer = fresh("dl"), shorter = fresh("ds"), swap = fresh("dt"); + body.push(...gap(longer, p.left, p.right, q.left, q.right), ...gap(shorter, p.top, p.bottom, q.top, q.bottom)); + const x = ranged(V(longer), 0, 0x20000), y = ranged(V(shorter), 0, 0x20000); + // The longer side first, then the game's xy_length: a share of the shorter added once the two are far enough from a line. + body.push(...when(cmp("<", x, y), [dec(swap, x, 0x20000), set(longer, y), set(shorter, ranged(V(swap), 0, 0x20000))])); + const y3 = bin("*", y, k(3)); + body.push(set(t, x), ...when(cmp("<", bin(">>>", x, k(2)), y), [ + set(t, bin("+", bin("-", bin("+", bin("-", x, bin(">>>", x, k(4))), bin(">>>", y3, k(3))), bin(">>>", x, k(6))), bin(">>>", y3, k(8)))), + ])); + pre.push(dec(t, k(0), 0x20000), ...when(all([present(a), present(b)]), body)); + return ranged(V(t), 0, 0x20000); + }; + /** The order Die: what kills a unit, as eudplib's `CUnit.die()`. */ const die = (e: NumExpr): Stmt => poke(of(e, ORDER.dword), k(0), ORDER.mask); @@ -767,12 +826,16 @@ export function unitValues(program: Program, events?: { sources: Set any(types.map((type) => cmp("==", ranged(V(id), 0, 0xffff), k(type)))); switch (v.do) { case "kill": body.push(die(e)); break; + // (The order and its state share a dword: both written at once, the state back to the start.) + case "stop": body.push(poke(of(e, ORDER.dword), k(STOP_ORDER * 2 ** ORDER.shift), (ORDER.mask | ORDER_STATE.mask) >>> 0)); break; // (eudplib's `CUnit.remove()`: the unit leaves without dying.) case "remove": body.push(poke(of(e, USER_ACTION.dword), k(4 * 2 ** USER_ACTION.shift), USER_ACTION.mask), die(e)); break; case "locate": { @@ -825,6 +888,34 @@ export function unitValues(program: Program, events?: { sources: Set when(is(aimed, g.targets), [set(order, k(g.order))])), + ])); + body.push(...when(cmp(">=", ranged(V(order), 0, 255), k(1)), [ + poke(of(e, ORDER_TARGET), bin("+", bin("*", target.e, k(4)), k(DEATHS))), + poke(of(e, ORDER_STATE.dword), k(0), ORDER_STATE.mask), + poke(of(e, ORDER.dword), bin("*", ranged(V(order), 0, 255), k(256)), ORDER.mask), + ])); + break; + } + case "cast": { + // The spell's order at the target, its state back to the start, as a player's command leaves them. + const spell = CAST_ORDERS.find((c) => c.tech === v.tech); + if (!spell || !target || isNone(target)) break; + const caster = fresh("ty"); + body.push(dec(caster, k(0), 0xffff), ...readInto(caster, e, TYPE)); + body.push(...when(all([is(caster, spell.casters), alive(target)]), [ + poke(of(e, ORDER_TARGET), bin("+", bin("*", target.e, k(4)), k(DEATHS))), + poke(of(e, ORDER.dword), k(spell.order * 2 ** ORDER.shift), (ORDER.mask | ORDER_STATE.mask) >>> 0), + ])); + break; + } case "damage": case "heal": { // Hit points down — at 0 the unit dies — or up to the type's most, in the game's own units (256 to a point). const now = fresh("hp"), ty = fresh("ty"), top = fresh("top"), step = fresh("step"); @@ -971,6 +1062,7 @@ export function unitValues(program: Program, events?: { sources: Set; return flag(unit(e.unit, pre), e.flag, pre); } case "unitSame": { const e = o as unknown as Extract; return same(unit(e.left, pre), unit(e.right, pre), pre); } + case "unitDistance": { const e = o as unknown as Extract; return distance(unit(e.from, pre), unit(e.to, pre), pre); } case "selected": { // `local.selected` (step 12): the unit in a slot of this computer's selection, re-checked before use as a kept // unit is (its uniqueness byte taken when read). The slot holds a pointer, or 0 for none. diff --git a/compiler/check.ts b/compiler/check.ts index 070328f..f908fd2 100644 --- a/compiler/check.ts +++ b/compiler/check.ts @@ -35,7 +35,7 @@ export function checkProgram(program: Program): { errors: ProgramDiagnostic[]; h /** Every expression of a statement list, calls' bodies included. */ function expressions(body: Stmt[], visit: (e: NumExpr | BoolExpr) => void, pick?: (u: UnitExpr & { kind: "pick" }) => void) { - const unit = (u: UnitExpr) => { if (u.kind === "call") call(u.call); else if (u.kind === "pick") pick?.(u); else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } }; + const unit = (u: UnitExpr): void => { if (u.kind === "call") call(u.call); else if (u.kind === "pick") pick?.(u); else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } else if (u.kind === "unitOrderTarget") unit(u.unit); }; const any = (e: NumExpr | BoolExpr | UnitExpr | TextExpr) => (isTextExpr(e) ? text(e) : isUnitExpr(e) ? unit(e) : expr(e)); const looks: TextMap = { num: (e) => { expr(e); return e; }, bool: (e) => { expr(e); return e; }, call: (c) => { call(c); return c; } }; const text = (t: TextExpr) => { mapText(t, looks); }; @@ -45,6 +45,7 @@ function expressions(body: Stmt[], visit: (e: NumExpr | BoolExpr) => void, pick? switch (e.kind) { case "unitField": case "unitPart": case "unitAlive": case "unitFlag": unit(e.unit); break; case "unitSame": unit(e.left); unit(e.right); break; + case "unitDistance": unit(e.from); unit(e.to); break; case "unary": case "cast": expr(e.expr); break; case "element": expr(e.index); break; case "binary": case "compare": expr(e.left); expr(e.right); break; @@ -76,7 +77,7 @@ function expressions(body: Stmt[], visit: (e: NumExpr | BoolExpr) => void, pick? case "textLoop": text(s.of); s.body.forEach(stmt); break; case "unitLoop": s.body.forEach(stmt); break; case "unitWrite": unit(s.unit); expr(s.value); break; - case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); break; + case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); if (s.verb.do === "gather" || s.verb.do === "cast") unit(s.verb.target); break; case "select": s.units.forEach(unit); break; case "tableWrite": any(s.value); break; case "if": expr(s.cond); s.then.forEach(stmt); s.else?.forEach(stmt); break; @@ -280,6 +281,12 @@ const THE_GAME = "(the game)"; let WINDOWS = new Map(); const whole = (array: string): string => WINDOWS.get(array) ?? array; +/** The unit variable a unit is read through, and `THE_GAME` when it is the unit another one's order is aimed at. */ +function unitReads(u: UnitExpr, into: Set): void { + if (u.kind === "unitVar") into.add(u.id); + else if (u.kind === "unitOrderTarget") { into.add(THE_GAME); unitReads(u.unit, into); } +} + /** The variables an expression reads, by id — and `THE_GAME` when it reads a value of the game or tests a condition. */ function reads(e: NumExpr | BoolExpr, into = new Set()): Set { // A text reads the variables it is made from; a list of texts the script has never changes. @@ -292,8 +299,9 @@ function reads(e: NumExpr | BoolExpr, into = new Set()): Set { case "read": case "cond": case "tableRead": into.add(THE_GAME); break; // What the players did is as it was when the frame began: nothing a loop does within the frame changes it. case "input": break; - case "unitField": case "unitAlive": case "unitFlag": into.add(THE_GAME); if (e.unit.kind === "unitVar") into.add(e.unit.id); break; - case "unitSame": for (const u of [e.left, e.right]) if (u.kind === "unitVar") into.add(u.id); break; + case "unitField": case "unitAlive": case "unitFlag": into.add(THE_GAME); unitReads(e.unit, into); break; + case "unitSame": for (const u of [e.left, e.right]) unitReads(u, into); break; + case "unitDistance": into.add(THE_GAME); for (const u of [e.from, e.to]) unitReads(u, into); break; case "randomInt": reads(e.bound, into); break; case "unary": case "cast": reads(e.expr, into); break; case "binary": case "compare": reads(e.left, into); reads(e.right, into); break; diff --git a/compiler/declarations.ts b/compiler/declarations.ts index 5c4c051..824c8ed 100644 --- a/compiler/declarations.ts +++ b/compiler/declarations.ts @@ -145,6 +145,19 @@ ${kw}interface Unit { kills: number; /** What the unit is doing: \`if (u.orderId == orders.Move)\`. orders.PlayerGuard is standing guard, orders.AttackUnit attacking. */ readonly orderId: Order; + /** The unit the order is aimed at (the one followed, attacked, mined …), or null when it is aimed at a place or at nothing. */ + readonly orderTarget: Unit | null; + /** Where the order is aimed, in pixels: where a Move goes, or the target unit's centre. */ + readonly orderTargetX: number; + readonly orderTargetY: number; + /** How far the unit has got with its order, 0 … 255: 0 as an order starts. What each number means is the order's own. */ + readonly orderState: number; + /** + * How many orders wait behind the one it is doing: what a shift-click adds, and what the game queues for itself (an + * attack-moving or patrolling Medic that stops to heal has its attack-move or patrol waiting). Orders the game shows no + * button for are not counted. + */ + readonly queuedOrders: number; /** Frames until the unit can attack or cast again, 0 … 255; writing it holds the unit's fire that long (the ground weapon's, the air weapon's and the spells' alike). */ cooldown: number; /** @@ -169,6 +182,10 @@ ${kw}interface Unit { maelstrom: number; irradiate: number; stasis: number; + /** Acid spores on the unit, 0 … 9: each Devourer hit adds one, and they wear off one by one. Read only. */ + readonly acidSpores: number; + /** Whether the unit is blinded by Optical Flare, which only a Medic's Restoration cures. Read only. */ + readonly opticalFlare: boolean; /** Whether the unit cannot be hurt. */ invincible: boolean; /** Whether the unit is a hallucination: made so, it takes double damage and dies after a while, as a Templar's do. */ @@ -199,6 +216,24 @@ ${kw}interface Unit { heal(amount: number | { percent: number }): void; /** Centre a location on the unit, its size kept: then createUnit(), moveUnit() and the rest can happen where the unit is. */ locate(location: Location): void; + /** + * Send an SCV, Probe or Drone to mine a mineral field or harvest a Refinery, Extractor or Assimilator, as a right-click + * on it does. Anything else, either way round, is left as it is. + */ + gather(target: Unit): void; + /** + * Cast a spell at a unit, as a player's command does: \`medic.cast(techs.Restoration, marine)\`. Restoration is the one + * spell so far, cast by a Medic; any other technology is an error when the script is built. Nothing checks the + * research or the energy: the game drops a cast it has no energy for, and walks the caster into range. + */ + cast(tech: Tech, target: Unit): void; + /** Stop, as the Stop button does: the unit gives up its order where it stands and takes up the next one it has queued, or stands idle. */ + stop(): void; + /** + * How far apart two units are, in pixels, as the game measures a weapon's or a spell's range: from the edge of one's + * box to the edge of the other's (0 when they touch). 0 when either is gone. + */ + distanceTo(other: Unit): number; } /** Which units a loop or a pick looks at; a part left out matches all. units.Men, units.Buildings and units.Factories work as a type. */ ${kw}interface UnitFilter { diff --git a/compiler/eudError.ts b/compiler/eudError.ts index e42a756..f37db7f 100644 --- a/compiler/eudError.ts +++ b/compiler/eudError.ts @@ -108,6 +108,10 @@ export function placeOfAddress(address: number, list?: Allowlist): string { const i = Math.floor(off / f.stride); if (i < (f.keyed ? 12 : TABLE_SIZE_OF[kind])) return `stats(): the ${kind} table's ${f.name}, entry ${i}`; } + for (const f of fields) { + const rows = f.keyed?.broodWar, off = rows ? address - rows.base : -1; + if (rows && off >= 0 && off < 12 * rows.stride) return `stats(): the ${kind} table's ${f.name}, entry ${Math.floor(off / rows.stride)}`; + } } const named = list?.entries.find((e) => !/^0x[0-9a-f]+$/i.test(e.name) && covers(e, address)); return named ? named.name : "no table TrigScript knows"; diff --git a/compiler/gameSim.ts b/compiler/gameSim.ts index 18820ef..9168065 100644 --- a/compiler/gameSim.ts +++ b/compiler/gameSim.ts @@ -205,6 +205,12 @@ class GameUnit implements SimUnit { get speedUpgrade() { return this.read("speedUpgrade", () => this.flag(0x10000000)); } get hasTarget() { return this.read("hasTarget", () => this.m.getUint32(this.at + 0x5c, true) !== 0); } get inTransport() { return this.read("inTransport", () => this.flag(0x00000040)); } + get orderTargetX() { return this.read("orderTargetX", () => this.m.getUint16(this.at + 0x58, true)); } + get orderTargetY() { return this.read("orderTargetY", () => this.m.getUint16(this.at + 0x5a, true)); } + get orderState() { return this.read("orderState", () => this.game.u8[this.at + 0x4e]); } + get queuedOrders() { return this.read("queuedOrders", () => this.game.u8[this.at + 0x84]); } + get opticalFlare() { return this.read("opticalFlare", () => this.game.u8[this.at + 0x123] !== 0); } + get acidSpores() { return this.read("acidSpores", () => this.game.u8[this.at + 0x126]); } // Not read from the game yet: the spell timers and whether the unit is under attack. stim = 0; ensnare = 0; plague = 0; lockdown = 0; maelstrom = 0; irradiate = 0; stasis = 0; /** The attack-notify timer (+0x87) running: the game raised its under-attack alert for the unit within the last second or so. */ diff --git a/compiler/generated/stdlib.ts b/compiler/generated/stdlib.ts index 544e410..c7d54f3 100644 --- a/compiler/generated/stdlib.ts +++ b/compiler/generated/stdlib.ts @@ -7,7 +7,9 @@ export const STDLIB_SOURCES: Readonly> = { "random": "/**\n * Chance: the standard library's \"trigscript/random\" (TrigScript 4).\n *\n * import { chance, range, pick, shuffle, weighted, Random } from \"trigscript/random\";\n *\n * if (chance(25)) dropLoot(); // one time in four\n * const lane = range(1, 3); // 1, 2 or 3\n * const boss = pick(BOSSES); // any one of a list\n * shuffle(order); // an array of the program, in place\n * const tier = weighted([70, 25, 5]); // 0 most of the time, 2 rarely\n *\n * const rng = new Random(seed); // the same numbers every time for the same seed\n * const x = rng.range(0, 63);\n *\n * The functions use the game's own random numbers, which every player's game draws alike, so nothing goes out of step\n * in a game of several players. `Random` is a generator of your own (xorshift), seeded: the same seed gives the same\n * numbers, game after game — a level made from a seed, a save code that holds one.\n */\nimport { random } from \"trigscript\";\n\n/** True `percent` times in a hundred (25: one time in four). */\nexport function chance(percent: number): boolean {\n return random(100) < percent;\n}\n\n/** A whole number from `min` to `max`, both included. */\nexport function range(min: number, max: number): number {\n return min + random(max - min + 1);\n}\n\n/** The total of `count` dice of `sides` sides each (3, 6: from 3 to 18). */\nexport function dice(count: number, sides: number): number {\n let total = 0;\n let i = 0;\n while (i < count) { total += 1 + random(sides); i++; }\n return total;\n}\n\n/** One of a list, any one alike; a list the script has, or an array of the program (the first's 0 when it is empty). */\nexport function pick(items: readonly T[]): T {\n return items[random(items.length)];\n}\n\n/** The place of one of the weights, each as likely as its share of their total: [70, 25, 5] gives 0 most of the time. */\nexport function weighted(weights: readonly number[]): number {\n let total = 0;\n for (const w of weights) total += w;\n let roll = random(total);\n let i = 0;\n while (i < weights.length) {\n if (roll < weights[i]) return i;\n roll -= weights[i];\n i++;\n }\n return weights.length - 1;\n}\n\n/** An array of the program in a random order, in place (Fisher–Yates: every order alike). */\nexport function shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = random(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n}\n\n/**\n * A generator of random numbers of your own, seeded: the same seed gives the same numbers, in the game and when the\n * script is tested. Make it in the program (`const rng = new Random(1234)`).\n */\nexport class Random {\n state: number;\n\n /** Seeded with any whole number (0 is taken as 1). */\n constructor(seed: number) {\n this.state = seed === 0 ? 1 : seed;\n }\n\n /** The next number, from 0 to 2 147 483 647. */\n next(): number {\n let x = this.state;\n x ^= x << 13;\n x ^= x >>> 17;\n x ^= x << 5;\n this.state = x;\n return x & 0x7fffffff;\n }\n\n /** A whole number from 0 to n − 1. */\n int(n: number): number {\n return this.next() % n;\n }\n\n /** A whole number from `min` to `max`, both included. */\n range(min: number, max: number): number {\n return min + this.int(max - min + 1);\n }\n\n /** True `percent` times in a hundred. */\n chance(percent: number): boolean {\n return this.int(100) < percent;\n }\n\n /** One of a list, any one alike. */\n pick(items: readonly T[]): T {\n return items[this.int(items.length)];\n }\n\n /** An array of the program in a random order, in place. */\n shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = this.int(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n }\n}\n", "screen": "/**\n * Pixel screens: the standard library's \"trigscript/screen\" (TrigScript 4).\n *\n * import { Screen, ScreenView, sprite } from \"trigscript/screen\";\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n *\n * program(async () => {\n * const screen = new Screen(4, 4, 24, 16); // 24 × 16 pixels, its corner on tile (4, 4)\n * let x = 10;\n * while (true) {\n * screen.clear();\n * screen.rect(0, 15, 24, 1, 5); // the ground, in colour 5\n * screen.blit(SHIP, x, 12);\n * screen.number(score, 1, 1, 2); // digits 3 × 5 pixels, in colour 2\n * screen.present(); // on the map, and so on the minimap (screen.reveal(P1) once first)\n * await nextFrame();\n * }\n * });\n *\n * A screen is a grid of pixels, each 0 (empty) or a colour from 1 to 7; drawing changes the grid, and `present()`\n * shows it: a pixel is a unit on the map, owned by the player whose colour it is, so the minimap shows the picture —\n * neighbouring pixels of one colour join into a solid block there. Only the pixels that changed since the last\n * `present()` are made or taken away, and only the pixels drawn since are looked at, so a still picture costs nothing to\n * show. Draw through the methods (`set`, `clear`, `rect`, …): a pixel written into `pixels` directly is not seen. The same grid can be shown in a\n * player's text lines too, as squares (`ScreenView` in a `ui.lines` view): one game, two screens, as the Tetris probe has it.\n *\n * A player sees the pixels only where they have vision: `screen.reveal(P1)` once gives them Map Revealers over it.\n *\n * Two looks (the constructor's last argument): \"dots\", Overlords, which fly — the minimap draws each as a dot with a gap\n * round it, the screen may be over Space; and \"solid\", Pylons, which the minimap draws as their whole two-tile\n * footprint, so pixels side by side are one block — on buildable ground (probes/lib/screen-map.mts --ground).\n *\n * What the map needs, found playing the unit-pixel probe in StarCraft: Remastered (2026-10-16): the owners of the\n * pixels (P3, P4, P5, P1, P6, P7, P8 below; their colours are theirs on the map, so give them the colours of TEXT_COLORS) must not\n * be computers — a computer moves its own units — and Remastered will not start a game without a computer, so one slot\n * (P2 here) is a computer that owns no pixel. A pixel is an Overlord, which sits on any ground and on nothing else; keep\n * the screen's tiles clear of buildings. A Pylon needs buildable ground, and none of the map's own units in the way. About 80 pixels made and taken away in a frame did not slow the game.\n */\nimport { centerLocation, createUnit, removeUnitAt, reserveLocation, textColors, P1, P3, P4, P5, P6, P7, P8, type Player, type UnitType } from \"trigscript\";\n\n/**\n * Whose units show colours 1 to 7 on the map, in the order of TEXT_COLORS: give each player that colour in the map\n * (cyan, yellow, purple, green, red, blue, orange). Green is P1's — your own units are green on the minimap anyway.\n * Not computers.\n */\nexport const OWNERS: readonly Player[] = [P3, P4, P5, P1, P6, P7, P8];\n/** The same colours in the text lines (`ScreenView`), 0 an empty square: cyan, yellow, purple, green, red, blue, orange. */\nexport const TEXT_COLORS: readonly number[] = [0, textColors.cyan, textColors.yellow, textColors.purple, textColors.green, textColors.red, textColors.blue, textColors.orange];\n\n/** Where each pixel's unit is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"screen: where each pixel is made\");\n\n/** A picture known when the script is built, to `blit` onto a screen: its size, and its pixels a row at a time (0 is see-through). */\nexport interface Sprite { readonly width: number; readonly height: number; readonly cells: readonly number[] }\n\n/**\n * A sprite from rows of text, when the script is built: \"1\" … \"7\" a pixel of that colour, anything else see-through.\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n */\nexport function sprite(rows: readonly string[]): Sprite {\n const width = Math.max(0, ...rows.map((r) => r.length));\n const cells: number[] = [];\n for (const row of rows) for (let x = 0; x < width; x++) { const c = Number(row[x]); cells.push(c >= 1 && c <= 7 ? c : 0); }\n return { width, height: rows.length, cells };\n}\n\n/** The digits 0 to 9, three pixels wide and five high, for `number()`: each fifteen pixels, a row at a time. */\nconst DIGITS: readonly number[] = [\n \"111101101101111\", \"010110010010111\", \"111001111100111\", \"111001111001111\", \"101101111001001\",\n \"111100111001111\", \"111100111101111\", \"111001001010010\", \"111101111101111\", \"111101111001111\",\n].flatMap((d) => d.split(\"\").map(Number));\n\n/** The most pixels a screen has: 32 × 32 at two tiles a pixel covers a 64 × 64 map, 64 × 32 half of a 128 × 128 one. */\nexport const MAX_PIXELS = 2048;\n\nexport class Screen {\n /** The picture being drawn: a colour a pixel, a row at a time (the first width × height of them). */\n pixels: number[] = new Array(MAX_PIXELS).fill(0);\n /** What the map shows now: the picture as it was at the last `present()`. */\n shown: number[] = new Array(MAX_PIXELS).fill(0);\n /** The pixels drawn a colour they were not since the last `present()`, in order: each one's place and its x and y. */\n drawnAt: number[] = new Array(MAX_PIXELS).fill(0);\n drawnX: number[] = new Array(MAX_PIXELS).fill(0);\n drawnY: number[] = new Array(MAX_PIXELS).fill(0);\n drawn = 0;\n /** More drawn than the list holds: `present()` looks at every pixel instead. */\n overflow = false;\n x: number;\n y: number;\n width: number;\n height: number;\n cell: number;\n /** The unit a pixel is: an Overlord (\"dots\"), or a Pylon (\"solid\"). */\n unit = 0;\n\n /**\n * A screen `width` × `height` pixels (MAX_PIXELS at most), its top left corner on tile (x, y) of the map, a pixel two\n * tiles across.\n * @param look \"dots\" (the default): a pixel is an Overlord, which the minimap draws as a dot, a gap round it — it flies,\n * so the screen may be over anything, Space too. \"solid\": a pixel is a Pylon, which the minimap draws as its whole\n * footprint, two tiles square, so pixels side by side are one block — it needs buildable ground under the screen,\n * and gives its owner Protoss supply. (Overlords a tile apart do not fit: the game will not place most of them.)\n */\n constructor(x: number, y: number, width: number, height: number, look: \"dots\" | \"solid\" = \"dots\") {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.cell = 64;\n this.unit = (look === \"solid\" ? 156 : 42) as UnitType; // Protoss Pylon, Zerg Overlord: the game's own ids, the same under a mod's names\n }\n\n /** Every pixel the colour (0, empty, unless it says). */\n clear(color: number = 0) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.put(i, x, y, color); i++; x++; }\n y++;\n }\n }\n\n /** One pixel; nothing happens outside the screen. */\n set(x: number, y: number, color: number) {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) this.put(y * this.width + x, x, y, color);\n }\n\n /** A pixel written, and listed for `present()` when its colour changed. */\n private put(i: number, x: number, y: number, color: number) {\n if (this.pixels[i] === color) return;\n this.pixels[i] = color;\n if (this.drawn < MAX_PIXELS) {\n this.drawnAt[this.drawn] = i;\n this.drawnX[this.drawn] = x;\n this.drawnY[this.drawn] = y;\n this.drawn++;\n } else this.overflow = true;\n }\n\n /** The colour of a pixel; 0 outside the screen. */\n get(x: number, y: number): number {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) return this.pixels[y * this.width + x];\n return 0;\n }\n\n /** A filled rectangle, its top left at (x, y); what is outside the screen is left out. */\n rect(x: number, y: number, width: number, height: number, color: number) {\n let j = 0;\n while (j < height) {\n let i = 0;\n while (i < width) { this.set(x + i, y + j, color); i++; }\n j++;\n }\n }\n\n /** A line from (x0, y0) to (x1, y1), both ends drawn. */\n line(x0: number, y0: number, x1: number, y1: number, color: number) {\n const dx = Math.abs(x1 - x0);\n const dy = -Math.abs(y1 - y0);\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n let err = dx + dy;\n let x = x0;\n let y = y0;\n while (true) {\n this.set(x, y, color);\n if (x === x1 && y === y1) break;\n const e2 = 2 * err;\n if (e2 >= dy) { err += dy; x += sx; }\n if (e2 <= dx) { err += dx; y += sy; }\n }\n }\n\n /** A sprite with its top left at (x, y): its see-through pixels leave what is under them. */\n blit(s: Sprite, x: number, y: number) {\n let k = 0;\n let j = 0;\n while (j < s.height) {\n let i = 0;\n while (i < s.width) {\n const c = s.cells[k];\n if (c !== 0) this.set(x + i, y + j, c);\n k++;\n i++;\n }\n j++;\n }\n }\n\n /** A whole number's digits, 3 × 5 pixels each with a pixel between, its top left at (x, y): a score on the minimap. */\n number(n: number, x: number, y: number, color: number) {\n let rest = n < 0 ? -n : n;\n let count = 1;\n let probe = rest;\n while (probe >= 10) { probe = Math.floor(probe / 10); count++; }\n let place = x + (count - 1) * 4;\n while (true) {\n const d = rest % 10;\n let k = 0;\n while (k < 15) {\n if (DIGITS[d * 15 + k] === 1) this.set(place + (k % 3), y + Math.floor(k / 3), color);\n k++;\n }\n rest = Math.floor(rest / 10);\n place -= 4;\n if (rest === 0) break;\n }\n }\n\n /**\n * Let a player see the screen: Map Revealers of theirs over it, for the rest of the game. Without them its pixels,\n * owned by other players, are hidden by the fog of war — on the map and on the minimap. Once, before the first\n * `present()`.\n * @param player Who sees it: P1 … P8, known when the script is built.\n */\n reveal(player: Player) {\n // A Map Revealer sees ten tiles round; one every six tiles leaves no gap.\n const right = this.x * 32 + this.width * this.cell;\n const bottom = this.y * 32 + this.height * this.cell;\n let py = this.y * 32 + 96;\n while (py < bottom + 96) {\n let px = this.x * 32 + 96;\n while (px < right + 96) {\n centerLocation(SPOT, px, py, 32, 32);\n createUnit(player, 101 as UnitType, 1, SPOT); // Map Revealer\n px += 192;\n }\n py += 192;\n }\n }\n\n /**\n * The picture on the map: each pixel that changed since the last time taken away and made again in its colour. Only\n * the pixels drawn since are looked at (one drawn and drawn back is passed over), unless more were drawn than the list\n * holds.\n */\n present() {\n if (this.overflow) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.show(i, x, y); i++; x++; }\n y++;\n }\n this.overflow = false;\n } else {\n for (let k = 0; k < this.drawn; k++) this.show(this.drawnAt[k], this.drawnX[k], this.drawnY[k]);\n }\n this.drawn = 0;\n }\n\n /** One pixel on the map as it is in the picture, when it is not already. */\n private show(i: number, x: number, y: number) {\n const now = this.pixels[i];\n const was = this.shown[i];\n if (now === was) return;\n const half = this.cell >> 1;\n centerLocation(SPOT, this.x * 32 + x * this.cell + half, this.y * 32 + y * this.cell + half, 32, 32);\n OWNERS.forEach((owner, k) => { if (was === k + 1) removeUnitAt(owner, this.unit, 1, SPOT); });\n OWNERS.forEach((owner, k) => { if (now === k + 1) createUnit(owner, this.unit, 1, SPOT); });\n this.shown[i] = now;\n }\n}\n\n/**\n * A screen in the text lines, a square a pixel — filled in its colour, or empty — a line a row. For a `ui.lines` view:\n * ``, the screen's size known when the script is built. Eleven lines\n * show at once, sixty squares across.\n */\nexport function ScreenView({ screen, width, height }: { screen: Screen; width: number; height: number }) {\n return <>{UP_TO_60.map((y) => y < height && {UP_TO_60.map((x) => x < width && )})};\n}\n\n/** 0 … 59: the places a view's rows and columns are counted over, the ones past its size left out when the script is built. */\nconst UP_TO_60: readonly number[] = Array.from({ length: 60 }, (_, i) => i);\n", "signals": "/**\n * Events of your own: the standard library's \"trigscript/signals\" (TrigScript 4).\n *\n * import { Signal } from \"trigscript/signals\";\n *\n * const waveCleared = new Signal();\n *\n * program(async () => {\n * waveCleared.on((wave) => { setResources(P1, \"add\", 100 * wave, \"ore\"); }); // braces: a handler gives back no action\n * waveCleared.once((wave) => print(`First wave down!`));\n * const id = waveCleared.on((wave) => print(`Wave ${wave} cleared`));\n * …\n * waveCleared.emit(3); // every handler, in the order they were added\n * waveCleared.off(id);\n * });\n *\n * A signal lets one part of a map say that something happened without knowing who listens: the shop, the score and the\n * music each add a handler, and the wave code only emits. What it carries is one value of the type it is made with —\n * a number, a boolean, a text or a unit (`new Signal()`). Its handlers are functions kept as values: they may use\n * what the block they were written in has, and they run to their end, one after another, within the frame.\n *\n * Make a signal inside the program that uses it (`const s = new Signal()` at its top): a signal is variables\n * of a program, as anything a program writes is.\n */\n\nexport class Signal {\n /** The handlers, by the number `on` gave; one taken off is undefined, and its place is given to the next one added. */\n handlers: (((value: T) => void) | undefined)[] = [];\n /** Which handlers go once they have run once. */\n onceOnly: boolean[] = [];\n\n /**\n * Add a handler: it runs at every `emit`, handed the value.\n * @returns Its number, for `off`.\n */\n on(handler: (value: T) => void): number {\n return this.add(handler, false);\n }\n\n /** Add a handler that runs at the next `emit` only. @returns Its number, for `off` before then. */\n once(handler: (value: T) => void): number {\n return this.add(handler, true);\n }\n\n /** Take a handler off, by the number `on` or `once` gave. */\n off(id: number) {\n if (id >= 0 && id < this.handlers.length) this.handlers[id] = undefined;\n }\n\n /** Run every handler, in the order they were added, each handed `value`. */\n emit(value: T) {\n let i = 0;\n while (i < this.handlers.length) {\n const h = this.handlers[i];\n if (h) {\n if (this.onceOnly[i]) this.handlers[i] = undefined;\n h(value);\n }\n i++;\n }\n }\n\n /** How many handlers it has. */\n count(): number {\n let n = 0;\n for (const h of this.handlers) if (h) n++;\n return n;\n }\n\n /** Take every handler off. */\n clear() {\n let i = 0;\n while (i < this.handlers.length) { this.handlers[i] = undefined; i++; }\n }\n\n private add(handler: (value: T) => void, once: boolean): number {\n // A place one was taken off from, or a new one at the end.\n let i = 0;\n while (i < this.handlers.length) {\n if (!this.handlers[i]) {\n this.handlers[i] = handler;\n this.onceOnly[i] = once;\n return i;\n }\n i++;\n }\n this.handlers.push(handler);\n this.onceOnly.push(once);\n return this.handlers.length - 1;\n }\n}\n", + "spells": "/**\n * Spells that cast themselves: the standard library's \"trigscript/spells\" (TrigScript 4).\n *\n * import { buildAutoRestoreProgram } from \"trigscript/spells\";\n *\n * buildAutoRestoreProgram(); // at the top of the script, once\n * buildAutoRestoreProgram({ switch: \"Medics trained\", keepEnergy: 25 }); // or tied to a switch, keeping 25 energy\n *\n * With auto-restore on, a human player's Medic that is idle, or healing on its own from idle, casts Restoration on a\n * unit of its owner's, or of a player its owner has allied, that is within the spell's range and carries Lockdown,\n * Irradiate, Plague, Ensnare, Maelstrom, Acid Spores or Optical Flare. It is a real cast: the owner must have researched\n * Restoration, the Medic must have its energy (and `keepEnergy` more), and the cast shows and costs as a player's\n * does. The nearest Medic goes to the nearest afflicted unit, one Medic to a unit; one that is moving, attack-moving,\n * holding, patrolling or casting for the player is never used, and a Medic never walks to reach a unit. Parasite\n * alone, a unit in stasis or invincible, a hallucination (Restoration kills it) and the Medic itself are left alone.\n * Computer players' Medics are left to the computer, which casts Restoration itself.\n *\n * Played in StarCraft: Remastered (2026-11-11): the order written to the Medic (CastRestoration at the unit) is cast,\n * mid-heal too, and the Medic heals on afterwards. How it tells a Medic healing from idle from one the player sent,\n * from `map trace` (2026-11-11): either way the order is MedicHeal, but an attack-move or a patrol waits behind it in\n * the Medic's queue (`queuedOrders` 1 or 2), and the queue of one healing from idle holds nothing the game counts.\n */\nimport { program, nextFrame, isHuman, switchIs, switches, allUnits, stats, units, orders, techs, weapons, P1, P2, P3, P4, P5, P6, P7, P8, type Player, type Unit } from \"trigscript\";\n\nfunction ownerIsHuman(medic: Unit): boolean {\n const owner = medic.owner;\n if (owner == P1) return isHuman(P1);\n if (owner == P2) return isHuman(P2);\n if (owner == P3) return isHuman(P3);\n if (owner == P4) return isHuman(P4);\n if (owner == P5) return isHuman(P5);\n if (owner == P6) return isHuman(P6);\n if (owner == P7) return isHuman(P7);\n if (owner == P8) return isHuman(P8);\n return false;\n}\n\nfunction ownerHasRestoration(medic: Unit): boolean {\n const owner = medic.owner;\n if (owner == P1) return stats(P1).researched[techs.Restoration];\n if (owner == P2) return stats(P2).researched[techs.Restoration];\n if (owner == P3) return stats(P3).researched[techs.Restoration];\n if (owner == P4) return stats(P4).researched[techs.Restoration];\n if (owner == P5) return stats(P5).researched[techs.Restoration];\n if (owner == P6) return stats(P6).researched[techs.Restoration];\n if (owner == P7) return stats(P7).researched[techs.Restoration];\n if (owner == P8) return stats(P8).researched[techs.Restoration];\n return false;\n}\n\nfunction playerHasAllied(player: Player, target: Unit): boolean {\n const owner = target.owner;\n if (owner == P1) return stats(player).allied[P1];\n if (owner == P2) return stats(player).allied[P2];\n if (owner == P3) return stats(player).allied[P3];\n if (owner == P4) return stats(player).allied[P4];\n if (owner == P5) return stats(player).allied[P5];\n if (owner == P6) return stats(player).allied[P6];\n if (owner == P7) return stats(player).allied[P7];\n if (owner == P8) return stats(player).allied[P8];\n return false;\n}\n\nfunction isFriendly(medic: Unit, target: Unit): boolean {\n const owner = medic.owner;\n if (target.owner == owner) return true;\n if (owner == P1) return playerHasAllied(P1, target);\n if (owner == P2) return playerHasAllied(P2, target);\n if (owner == P3) return playerHasAllied(P3, target);\n if (owner == P4) return playerHasAllied(P4, target);\n if (owner == P5) return playerHasAllied(P5, target);\n if (owner == P6) return playerHasAllied(P6, target);\n if (owner == P7) return playerHasAllied(P7, target);\n if (owner == P8) return playerHasAllied(P8, target);\n return false;\n}\n\nfunction isIdleOrHealingFromIdle(medic: Unit): boolean {\n const order = medic.orderId;\n if (order == orders.Medic) return true;\n return (order == orders.MedicHeal || order == orders.MedicHealToIdle) && medic.queuedOrders == 0;\n}\n\nfunction hasRestorableEffect(target: Unit): boolean {\n return target.lockdown > 0 || target.irradiate > 0 || target.plague > 0 || target.ensnare > 0 || target.maelstrom > 0 || target.acidSpores > 0 || target.opticalFlare;\n}\n\nfunction includes(list: Unit[], unit: Unit): boolean {\n for (const each of list) if (each == unit) return true;\n return false;\n}\n\nlet programBuilt = false;\n\n/**\n * Build the program that turns auto-restore on: every human player's idle or self-healing Medic casts Restoration on\n * the nearest afflicted unit of its owner's or an ally's within range. `switch`: a switch of the map, by its name;\n * auto-restore runs only while it is set. `keepEnergy`: the energy a Medic keeps after the cast (default 0). Called at\n * the top of a script, as programs are made when the map is built; a call after the first adds nothing.\n */\nexport function buildAutoRestoreProgram(options: { switch?: keyof typeof switches; keepEnergy?: number } = {}) {\n if (programBuilt) return;\n programBuilt = true;\n const keepEnergy = options.keepEnergy ?? 0;\n program(async () => {\n const sentMedics: Unit[] = [];\n const sentTargets: Unit[] = [];\n while (true) {\n const range = stats(weapons.Restoration).range;\n for (let i = sentMedics.length - 1; i >= 0; i--) {\n const medic = sentMedics[i], target = sentTargets[i];\n if (medic.orderId == orders.CastRestoration && medic.orderTarget == target) {\n // (State 2 is the cast under way, its energy spent: let it land.)\n if (medic.orderState == 2 || medic.distanceTo(target) <= range) continue;\n medic.stop();\n }\n sentMedics.splice(i, 1);\n sentTargets.splice(i, 1);\n }\n if (options.switch !== undefined && !switchIs(switches[options.switch], \"set\")) {\n await nextFrame();\n continue;\n }\n const energy = stats(techs.Restoration).energy + keepEnergy;\n const medics: Unit[] = [];\n const castAt: Unit[] = [];\n for (const medic of allUnits({ type: units.TerranMedic })) {\n if (medic.orderId == orders.CastRestoration) {\n const target = medic.orderTarget;\n if (target) castAt.push(target);\n } else if (isIdleOrHealingFromIdle(medic) && medic.energy >= energy && ownerIsHuman(medic) && ownerHasRestoration(medic)) {\n medics.push(medic);\n }\n }\n if (medics.length > 0) {\n const pairMedics: Unit[] = [];\n const pairTargets: Unit[] = [];\n const pairDistances: number[] = [];\n for (const target of allUnits({ type: units.Men })) {\n if (!hasRestorableEffect(target) || target.stasis > 0 || target.hallucinated || target.invincible || includes(castAt, target)) continue;\n for (const medic of medics) {\n if (medic == target || !isFriendly(medic, target)) continue;\n const distance = medic.distanceTo(target);\n if (distance > range) continue;\n pairMedics.push(medic);\n pairTargets.push(target);\n pairDistances.push(distance);\n }\n }\n while (pairMedics.length > 0) {\n let nearest = 0;\n for (let i = 1; i < pairDistances.length; i++) if (pairDistances[i] < pairDistances[nearest]) nearest = i;\n const medic = pairMedics[nearest], target = pairTargets[nearest];\n medic.cast(techs.Restoration, target);\n sentMedics.push(medic);\n sentTargets.push(target);\n for (let i = pairMedics.length - 1; i >= 0; i--) {\n if (pairMedics[i] == medic || pairTargets[i] == target) {\n pairMedics.splice(i, 1);\n pairTargets.splice(i, 1);\n pairDistances.splice(i, 1);\n }\n }\n }\n }\n await nextFrame();\n }\n });\n}\n", "timers": "/**\n * Time in a program: the standard library's \"trigscript/timers\" (TrigScript 4).\n *\n * import { every, after, Cooldown, Countdown, SECOND } from \"trigscript/timers\";\n *\n * program(async () => {\n * const spawner = every(10 * SECOND, (n) => spawnWave(n)); // every ten seconds, the wave's number handed over\n * after(3 * SECOND, () => print(\"Go!\"));\n * const shot = new Cooldown(12);\n * while (true) {\n * if (keyPressed(P1, \"Space\") && shot.use()) fire();\n * if (boss.hp <= 0) spawner.cancel();\n * await nextFrame();\n * }\n * });\n *\n * for await (const b of over(bullets, { per: 50 })) b.x += b.dx; // fifty a frame, on to the next frame after each fifty\n *\n * Time is counted in frames of the game, 24 a second on Fastest (`SECOND`). `every` and `after` run their function in a\n * task beside the program, so the program goes on at once; the Task they give back stops it (`cancel()`) and says\n * whether it still runs (`running`). Their function is kept for the task, with what it uses of the block it was written\n * in — written in a loop, each turn's is its own, as JavaScript has it — and it runs to its end within the frame (it\n * does not wait). Sixteen of one `every` or `after` written once can run at a time. `Cooldown`, `Countdown` and\n * `Stopwatch` read the game's frame counter: no task, nothing to stop.\n */\nimport { game, start, sleep, frames, nextFrame, memory, type Task } from \"trigscript\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nexport const SECOND = 24;\n\n/** The frames of game time since the game began. */\nexport function now(): number {\n return memory.game.frame;\n}\n\nconst repeating = game(async (period: number, fn: (count: number) => void, times: number) => {\n let count = 0;\n while (times <= 0 || count < times) {\n await sleep(frames(period < 1 ? 1 : period));\n count++;\n fn(count);\n }\n});\n\nconst later = game(async (delay: number, fn: () => void) => {\n await sleep(frames(delay < 1 ? 1 : delay));\n fn();\n});\n\n/**\n * Run `fn` every `period` frames, from `period` frames from now: forever, or `times` times. It is handed how many times\n * it has run, 1 the first time.\n * @param period Frames between one run and the next (24 a second).\n * @param fn What to run; it runs to its end within the frame.\n * @param times How many times, or 0 (the default) for as long as the game lasts.\n * @returns The task: `cancel()` stops it.\n */\nexport const every = game((period: number, fn: (count: number) => void, times: number = 0): Task => start(repeating(period, fn, times)));\n\n/**\n * Run `fn` once, `delay` frames from now.\n * @param delay Frames from now (24 a second).\n * @param fn What to run; it runs to its end within the frame.\n * @returns The task: `cancel()` before then and it never runs.\n */\nexport const after = game((delay: number, fn: () => void): Task => start(later(delay, fn)));\n\n/**\n * The elements of `list`, `per` of them a frame: a loop spread over frames, for work that need not be done in one —\n * a thousand bullets moved, a map's cells looked at. What a frame costs stays what `per` turns cost.\n *\n * for await (const b of over(bullets, { per: 50 })) b.x += b.dx;\n *\n * It reads the list's length as it goes, as `for…of` does: what is pushed meanwhile is reached too, and an element\n * removed before it is reached moves the rest up, so one is passed over, as with an index. Each element is the list's\n * own: what is written to it stays. The loop goes on to the next frame only between elements, never after the last.\n * @param list The array to walk.\n * @param options `per`: how many elements a frame (1 at least).\n */\nexport async function* over(list: T[], options: { per: number }) {\n const per = options.per < 1 ? 1 : options.per;\n let n = 0;\n for (let i = 0; i < list.length; i++) {\n yield list[i];\n n++;\n if (n >= per && i + 1 < list.length) {\n n = 0;\n await nextFrame();\n }\n }\n}\n\n/**\n * 0, 1, … `count` − 1, `per` of them a frame: `over` for a count rather than an array.\n *\n * for await (const y of spread(96, { per: 8 })) drawRow(y); // twelve frames for 96 rows\n * @param count How many numbers, from 0.\n * @param options `per`: how many a frame (1 at least).\n */\nexport async function* spread(count: number, options: { per: number }) {\n const per = options.per < 1 ? 1 : options.per;\n let n = 0;\n for (let i = 0; i < count; i++) {\n yield i;\n n++;\n if (n >= per && i + 1 < count) {\n n = 0;\n await nextFrame();\n }\n }\n}\n\n/**\n * Something that can be done once every so many frames: a weapon's reload, a spell's cooldown.\n *\n * const blink = new Cooldown(5 * SECOND);\n * if (keyPressed(P1, \"B\") && blink.use()) teleport();\n */\nexport class Cooldown {\n period: number;\n until = 0;\n\n /** Ready at once, then once every `period` frames. */\n constructor(period: number) {\n this.period = period;\n }\n\n /** Whether it is ready now. */\n ready(): boolean {\n return now() >= this.until;\n }\n\n /** If it is ready, use it — it is ready again `period` frames from now — and say true; else false. */\n use(): boolean {\n if (now() < this.until) return false;\n this.until = now() + this.period;\n return true;\n }\n\n /** Frames until it is ready again: 0 when it is. */\n left(): number {\n return this.until > now() ? this.until - now() : 0;\n }\n\n /** Ready again at once. */\n reset() {\n this.until = 0;\n }\n}\n\n/**\n * A length of time that runs down while the game runs: a round's clock, a bomb's fuse.\n *\n * const round = new Countdown(90 * SECOND);\n * ui.lines(P1, () => {clock(round.left())});\n * await until(() => round.done());\n */\nexport class Countdown {\n end = 0;\n\n /** Running, done `length` frames from now (0: done already). */\n constructor(length: number = 0) {\n this.end = now() + length;\n }\n\n /** Start again, done `length` frames from now. */\n restart(length: number) {\n this.end = now() + length;\n }\n\n /** Frames left: 0 once it is done. */\n left(): number {\n return this.end > now() ? this.end - now() : 0;\n }\n\n /** Whether it has run out. */\n done(): boolean {\n return now() >= this.end;\n }\n\n /** More time, or less (a number below zero). */\n add(frames: number) {\n this.end += frames;\n }\n}\n\n/** How long since it was made, or last reset: a lap's time, a survival score. */\nexport class Stopwatch {\n from = 0;\n\n constructor() {\n this.from = now();\n }\n\n /** Frames since it started. */\n elapsed(): number {\n return now() - this.from;\n }\n\n /** From 0 again. */\n reset() {\n this.from = now();\n }\n}\n", - "ui": "/**\n * A kit for the game's text lines: the standard library's \"trigscript/ui\" (TrigScript 4).\n *\n * import { Meter, Panel, MenuList, DialogBox, choose, say, clock } from \"trigscript/ui\";\n *\n * const ITEMS = [\"Marine (50)\", \"Medic (75)\", \"Leave\"];\n * const shop = { selected: 0, open: false };\n * const talk = { speaker: \"\", text: \"\", open: false };\n *\n * program(async () => {\n * ui.lines(P1, () => (\n * <>\n * \n * \n * \n * {shop.open && }\n * \n * \n * ));\n * await say(P1, talk, \"Raynor\", \"Hold the bridge until dawn.\");\n * const pick = await choose(P1, ITEMS.length, shop);\n * });\n *\n * The text lines are one player's: a view is shown to that player only, rebuilt when what it reads changes (a function\n * it calls included) and shown again once a second as it was, so a menu, a dialog and a meter cost nothing while nothing\n * changes. Give a player one `ui.lines` and\n * put everything in it, as the example does: the components are pieces of one view, and the state they show is a\n * record of yours (`shop`, `talk`) that the functions here change.\n *\n * What the text lines can show, played in StarCraft: Remastered (the UI spike, 2026-10-16): eleven lines; colour codes\n * take no width; ■ □ ● are one width; after grey on a line every later colour code is ignored, so grey goes last.\n */\nimport { keyPressed, nextFrame, sleep, frames, game, textColors, type Player, type TextColor } from \"trigscript\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nconst PER_SECOND = 24;\n\n/** \"1:05\": frames of game time as minutes and seconds (24 frames a second, on Fastest). */\nexport function clock(frames: number): string {\n const seconds = Math.floor(frames / PER_SECOND);\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")}`;\n}\n\n/** \"12,345\": a whole number with its thousands marked. */\nexport function thousands(n: number): string {\n let rest = n < 0 ? -n : n;\n let out = \"\";\n while (rest >= 1000) {\n out = `,${String(rest % 1000).padStart(3, \"0\")}${out}`;\n rest = Math.floor(rest / 1000);\n }\n return `${n < 0 ? \"-\" : \"\"}${rest}${out}`;\n}\n\n/**\n * A labelled bar on a line of its own — \"Base ■■■■■■□□□□ 900/1500\" — green above half, yellow above a quarter, red below.\n * @param label What the bar is of.\n * @param value How much there is.\n * @param max How much there can be.\n * @param width How many squares the bar is (10 unless it says).\n */\nexport function Meter({ label, value, max, width }: { label: string; value: number; max: number; width?: number }) {\n return (\n \n {label} max ? textColors.green : value * 4 > max ? textColors.yellow : textColors.red} /> {value}/{max}\n \n );\n}\n\n/**\n * A title over what is inside it: \"-- Wave 3 --\" in its colour (yellow unless it says), then the lines inside.\n * @param title The title.\n * @param color The title's colour.\n */\nexport function Panel({ title, children, color }: { title: string; children?: Children; color?: TextColor }) {\n return (\n <>\n -- {title} --\n {children}\n \n );\n}\n\n/**\n * A menu's lines: each item on a line of its own, the one at `selected` marked \"> \" and in its colour (cyan unless it\n * says). `items` is a list the script has, or an array of texts of the program.\n */\nexport function MenuList({ items, selected, color }: { items: readonly string[]; selected: number; color?: TextColor }) {\n return (\n <>\n {items.map((item, i) => (\n \n {i === selected ? \"> \" : \" \"}\n {item}\n \n ))}\n \n );\n}\n\n/**\n * Let a player choose one of `count` things: the menu opens (`menu.open`), W and S (or Up and Down) move\n * `menu.selected` (round from the last to the first), and Space chooses — the place chosen, once it is. (Not Enter:\n * in a game of several players Enter opens the chat.) Show it with `MenuList`, in the\n * player's `ui.lines`: `{shop.open && }`.\n * @param player Who chooses: P1 … P8, known when the script is built.\n * @param count How many things there are to choose from.\n * @param menu The record a view shows: which is marked, and whether the menu is open.\n */\nexport const choose = game(async (player: Player, count: number, menu: { selected: number; open: boolean }): Promise => {\n menu.open = true;\n while (true) {\n if (keyPressed(player, \"W\") || keyPressed(player, \"Up\")) menu.selected = (menu.selected + count - 1) % count;\n if (keyPressed(player, \"S\") || keyPressed(player, \"Down\")) menu.selected = (menu.selected + 1) % count;\n if (keyPressed(player, \"Space\")) break;\n await nextFrame();\n }\n menu.open = false;\n return menu.selected;\n});\n\n/**\n * A text put into `into.text` a character at a time, one every `every` frames (2 unless it says): a view that shows\n * `into.text` shows it being typed. Done when the whole text is there.\n */\nexport const typewriter = game(async (into: { text: string }, text: string, every: number = 2) => {\n let n = 0;\n while (n < text.length) {\n n++;\n into.text = text.slice(0, n);\n await sleep(frames(every));\n }\n});\n\n/**\n * Someone says something to a player: the dialog opens (`box.open`), the speaker's name and the words typed in, and it\n * closes when the player presses Space. Show it with `DialogBox`.\n * @param player Who reads it: P1 … P8, known when the script is built.\n * @param box The record a view shows.\n * @param speaker Who speaks.\n * @param text What they say.\n */\nexport const say = game(async (player: Player, box: { speaker: string; text: string; open: boolean }, speaker: string, text: string) => {\n box.open = true;\n box.speaker = speaker;\n box.text = \"\";\n await typewriter(box, text);\n while (!keyPressed(player, \"Space\")) await nextFrame();\n box.open = false;\n});\n\n/** A dialog's lines while it is open: the speaker in yellow, the words, and what to press (Space). Nothing while it is closed. */\nexport function DialogBox({ box }: { box: { speaker: string; text: string; open: boolean } }) {\n return box.open ? (\n <>\n {box.speaker}\n {box.text}\n (Space)\n \n ) : null;\n}\n\n/** A line at the end of a log that keeps the last `keep` (6 unless it says), the oldest taken off the front. */\nexport const log = game((lines: string[], text: string, keep: number = 6) => {\n lines.push(text);\n while (lines.length > keep) lines.shift();\n});\n\n/** A log's lines, oldest first, each in its colour (white unless it says). */\nexport function LogLines({ lines, color }: { lines: readonly string[]; color?: TextColor }) {\n return <>{lines.map((text) => {text})};\n}\n" + "ui": "/**\n * A kit for the game's text lines: the standard library's \"trigscript/ui\" (TrigScript 4).\n *\n * import { Meter, Panel, MenuList, DialogBox, choose, say, clock } from \"trigscript/ui\";\n *\n * const ITEMS = [\"Marine (50)\", \"Medic (75)\", \"Leave\"];\n * const shop = { selected: 0, open: false };\n * const talk = { speaker: \"\", text: \"\", open: false };\n *\n * program(async () => {\n * ui.lines(P1, () => (\n * <>\n * \n * \n * \n * {shop.open && }\n * \n * \n * ));\n * await say(P1, talk, \"Raynor\", \"Hold the bridge until dawn.\");\n * const pick = await choose(P1, ITEMS.length, shop);\n * });\n *\n * The text lines are one player's: a view is shown to that player only, rebuilt when what it reads changes (a function\n * it calls included) and shown again once a second as it was, so a menu, a dialog and a meter cost nothing while nothing\n * changes. Give a player one `ui.lines` and\n * put everything in it, as the example does: the components are pieces of one view, and the state they show is a\n * record of yours (`shop`, `talk`) that the functions here change.\n *\n * What the text lines can show, played in StarCraft: Remastered (the UI spike, 2026-10-16): eleven lines; colour codes\n * take no width; ■ □ ● are one width; after grey on a line every later colour code is ignored, so grey goes last.\n */\nimport { keyPressed, nextFrame, sleep, frames, game, textColors, type Player, type TextColor } from \"trigscript\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nconst PER_SECOND = 24;\n\n/** \"1:05\": frames of game time as minutes and seconds (24 frames a second, on Fastest). */\nexport function clock(frames: number): string {\n const seconds = Math.floor(frames / PER_SECOND);\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")}`;\n}\n\n/** \"12,345\": a whole number with its thousands marked. */\nexport function thousands(n: number): string {\n let rest = n < 0 ? -n : n;\n let out = \"\";\n while (rest >= 1000) {\n out = `,${String(rest % 1000).padStart(3, \"0\")}${out}`;\n rest = Math.floor(rest / 1000);\n }\n return `${n < 0 ? \"-\" : \"\"}${rest}${out}`;\n}\n\n/**\n * A labelled bar on a line of its own — \"Base ■■■■■■□□□□ 900/1500\" — green above half, yellow above a quarter, red below.\n * @param label What the bar is of.\n * @param value How much there is.\n * @param max How much there can be.\n * @param width How many squares the bar is (10 unless it says).\n */\nexport function Meter({ label, value, max, width }: { label: string; value: number; max: number; width?: number }) {\n return (\n \n {label} max ? textColors.green : value * 4 > max ? textColors.yellow : textColors.red} /> {value}/{max}\n \n );\n}\n\n/**\n * A title over what is inside it: \"-- Wave 3 --\" in its colour (yellow unless it says), then the lines inside.\n * @param title The title.\n * @param color The title's colour.\n */\nexport function Panel({ title, children, color }: { title: string; children?: Children; color?: TextColor }) {\n return (\n <>\n -- {title} --\n {children}\n \n );\n}\n\n/**\n * A menu's lines: each item on a line of its own, the one at `selected` marked \"> \" and in its colour (cyan unless it\n * says). `items` is a list the script has, or an array of texts of the program.\n */\nexport function MenuList({ items, selected, color }: { items: readonly string[]; selected: number; color?: TextColor }) {\n return (\n <>\n {items.map((item, i) => (\n \n {i === selected ? \"> \" : \" \"}\n {item}\n \n ))}\n \n );\n}\n\n/**\n * Let a player choose one of `count` things: the menu opens (`menu.open`), W and S (or Up and Down) move\n * `menu.selected` (round from the last to the first), and Space chooses — the place chosen, once it is. (Not Enter:\n * in a game of several players Enter opens the chat.) Show it with `MenuList`, in the\n * player's `ui.lines`: `{shop.open && }`.\n * @param player Who chooses: P1 … P8, known when the script is built.\n * @param count How many things there are to choose from.\n * @param menu The record a view shows: which is marked, and whether the menu is open.\n */\nexport const choose = game(async (player: Player, count: number, menu: { selected: number; open: boolean }): Promise => {\n menu.open = true;\n while (true) {\n if (keyPressed(player, \"W\") || keyPressed(player, \"Up\")) menu.selected = (menu.selected + count - 1) % count;\n if (keyPressed(player, \"S\") || keyPressed(player, \"Down\")) menu.selected = (menu.selected + 1) % count;\n if (keyPressed(player, \"Space\")) break;\n await nextFrame();\n }\n menu.open = false;\n return menu.selected;\n});\n\n/**\n * A text put into `into.text` a character at a time, one every `every` frames (2 unless it says): a view that shows\n * `into.text` shows it being typed. Done when the whole text is there.\n */\nexport const typewriter = game(async (into: { text: string }, text: string, every: number = 2) => {\n let n = 0;\n while (n < text.length) {\n n++;\n into.text = text.slice(0, n);\n await sleep(frames(every));\n }\n});\n\n/**\n * Someone says something to a player: the dialog opens (`box.open`), the speaker's name and the words typed in, and it\n * closes when the player presses Space. Show it with `DialogBox`.\n * @param player Who reads it: P1 … P8, known when the script is built.\n * @param box The record a view shows.\n * @param speaker Who speaks.\n * @param text What they say.\n */\nexport const say = game(async (player: Player, box: { speaker: string; text: string; open: boolean }, speaker: string, text: string) => {\n box.open = true;\n box.speaker = speaker;\n box.text = \"\";\n await typewriter(box, text);\n while (!keyPressed(player, \"Space\")) await nextFrame();\n box.open = false;\n});\n\n/** A dialog's lines while it is open: the speaker in yellow, the words, and what to press (Space). Nothing while it is closed. */\nexport function DialogBox({ box }: { box: { speaker: string; text: string; open: boolean } }) {\n return box.open ? (\n <>\n {box.speaker}\n {box.text}\n (Space)\n \n ) : null;\n}\n\n/** A line at the end of a log that keeps the last `keep` (6 unless it says), the oldest taken off the front. */\nexport const log = game((lines: string[], text: string, keep: number = 6) => {\n lines.push(text);\n while (lines.length > keep) lines.shift();\n});\n\n/** A log's lines, oldest first, each in its colour (white unless it says). */\nexport function LogLines({ lines, color }: { lines: readonly string[]; color?: TextColor }) {\n return <>{lines.map((text) => {text})};\n}\n", + "workers": "/**\n * Workers that go to work: the standard library's \"trigscript/workers\" (TrigScript 4).\n *\n * import { buildAutoMiningProgram } from \"trigscript/workers\";\n *\n * buildAutoMiningProgram(); // at the top of the script, once: on for the whole game\n *\n * With auto-mining on, a human player's new SCV, Probe or Drone whose producer's rally point is on a mineral patch\n * starts mining that patch, instead of walking there and standing. One rallied to the player's own finished gas\n * building (Refinery, Extractor, Assimilator) starts gathering gas from it. Anywhere else — the ground, a bare geyser,\n * a gas building still being built or another player's, a patch mined out — it walks to the rally point as it always\n * does. It acts once, as the worker comes out: an order the player gives afterwards stands. Computer players' workers\n * and those a trigger makes (Create Unit) are left alone, and a busy patch or gas building is the game's to sort out,\n * as when the player right-clicks it.\n *\n * Played in StarCraft: Remastered (2026-11-07 and 2026-11-08): SCVs, Probes and Drones rallied to minerals and to gas\n * all went to work. How it sees a new worker, from `map trace` (2026-11-07): an SCV comes out of training with its\n * order changing from Nothing, and a Drone from ZergBirth, on the frame the rally is applied (a Probe was not traced;\n * in play it went to work as an SCV does). A rally on a patch gives the worker Move to the patch's exact centre with no target; one on a building gives\n * Follow with the building as the target. `gather()` then gives the order a right-click would: MoveToMinerals or\n * MoveToGas.\n */\nimport { program, on, isHuman, allUnits, units, orders, P1, P2, P3, P4, P5, P6, P7, P8, type Unit } from \"trigscript\";\n\nfunction ownerIsHuman(worker: Unit): boolean {\n const owner = worker.owner;\n if (owner == P1) return isHuman(P1);\n if (owner == P2) return isHuman(P2);\n if (owner == P3) return isHuman(P3);\n if (owner == P4) return isHuman(P4);\n if (owner == P5) return isHuman(P5);\n if (owner == P6) return isHuman(P6);\n if (owner == P7) return isHuman(P7);\n if (owner == P8) return isHuman(P8);\n return false;\n}\n\nfunction gatherFromRally(worker: Unit) {\n if (!ownerIsHuman(worker)) return;\n if (worker.orderId == orders.Follow) {\n const gasBuilding = worker.orderTarget;\n if (gasBuilding) if (gasBuilding.owner == worker.owner && gasBuilding.buildTime == 0) worker.gather(gasBuilding);\n return;\n }\n if (worker.orderId != orders.Move || worker.hasTarget) return;\n const x = worker.orderTargetX, y = worker.orderTargetY;\n for (const patch of allUnits({ type: units.MineralFieldType1 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; }\n for (const patch of allUnits({ type: units.MineralFieldType2 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; }\n for (const patch of allUnits({ type: units.MineralFieldType3 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; }\n}\n\nlet programBuilt = false;\n\n/**\n * Build the program that turns auto-mining on for the whole game: every human player's new SCV, Probe or Drone rallied\n * to a mineral patch or the player's own finished gas building starts gathering from it. Called at the top of a\n * script, as programs are made when the map is built; a call after the first adds nothing.\n */\nexport function buildAutoMiningProgram() {\n if (programBuilt) return;\n programBuilt = true;\n program(async () => {\n on.order((worker, order, was) => {\n if (worker.type == units.ZergDrone) {\n if (was == orders.ZergBirth) gatherFromRally(worker);\n } else if (was == orders.Nothing) {\n if (worker.type == units.TerranSCV || worker.type == units.ProtossProbe) gatherFromRally(worker);\n }\n });\n });\n}\n" }; -export const STDLIB_EXTENSIONS: Readonly> = {"cutscene":".ts","fog":".ts","math":".ts","music":".ts","random":".ts","screen":".tsx","signals":".ts","timers":".ts","ui":".tsx"}; +export const STDLIB_EXTENSIONS: Readonly> = {"cutscene":".ts","fog":".ts","math":".ts","music":".ts","random":".ts","screen":".tsx","signals":".ts","spells":".ts","timers":".ts","ui":".tsx","workers":".ts"}; diff --git a/compiler/input.ts b/compiler/input.ts index 6721b41..d99c0bf 100644 --- a/compiler/input.ts +++ b/compiler/input.ts @@ -211,10 +211,11 @@ export function inputsOf(programs: Program[]): { sources: InputSource[]; mouse: const sources: InputSource[] = []; let mouse = false; let at: At | null = null; - const unit = (u: UnitExpr) => { + const unit = (u: UnitExpr): void => { if (u.kind === "call") call(u.call); else if (u.kind === "pick" && u.mouse !== undefined) { mouse = true; at ??= u.at; } else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } + else if (u.kind === "unitOrderTarget") unit(u.unit); }; const any = (e: NumExpr | BoolExpr | UnitExpr | TextExpr) => (isTextExpr(e) ? text(e) : isUnitExpr(e) ? unit(e) : expr(e)); const looks: TextMap = { num: (e) => { expr(e); return e; }, bool: (e) => { expr(e); return e; }, call: (c) => { call(c); return c; } }; @@ -225,6 +226,7 @@ export function inputsOf(programs: Program[]): { sources: InputSource[]; mouse: case "input": sources.push(e.input); at ??= e.at; if (e.input.source === "mouse") mouse = true; break; case "unitField": case "unitPart": case "unitAlive": case "unitFlag": unit(e.unit); break; case "unitSame": unit(e.left); unit(e.right); break; + case "unitDistance": unit(e.from); unit(e.to); break; case "unary": case "cast": expr(e.expr); break; case "element": expr(e.index); break; case "binary": case "compare": expr(e.left); expr(e.right); break; @@ -254,7 +256,7 @@ export function inputsOf(programs: Program[]): { sources: InputSource[]; mouse: case "textLoop": text(s.of); s.body.forEach(stmt); break; case "unitLoop": s.body.forEach(stmt); break; case "unitWrite": unit(s.unit); expr(s.value); break; - case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); break; + case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); if (s.verb.do === "gather" || s.verb.do === "cast") unit(s.verb.target); break; case "select": s.units.forEach(unit); break; case "tableWrite": any(s.value); break; case "centerLocation": expr(s.x); expr(s.y); if (s.size) { expr(s.size.width); expr(s.size.height); } break; diff --git a/compiler/ir.ts b/compiler/ir.ts index a1329c5..f7b991f 100644 --- a/compiler/ir.ts +++ b/compiler/ir.ts @@ -221,13 +221,14 @@ export type EventSource = "created" | "died" | "killed" | "ordered" | "morphed"; * remaining build time frames; `matrix` the defensive matrix's frames; `speed` the current speed in 256ths of a pixel a frame. */ export type UnitNumField = "hp" | "maxHp" | "shields" | "maxShields" | "energy" | "owner" | "type" | "x" | "y" | "kills" | "orderId" | "cooldown" | "resources" - | "stim" | "ensnare" | "plague" | "lockdown" | "maelstrom" | "irradiate" | "stasis" | "buildTime" | "rank" | "matrix" | "speed"; + | "stim" | "ensnare" | "plague" | "lockdown" | "maelstrom" | "irradiate" | "stasis" | "buildTime" | "rank" | "matrix" | "speed" | "orderTargetX" | "orderTargetY" + | "acidSpores" | "orderState" | "queuedOrders"; /** The ones a program may write; the rest the game keeps for itself (a position write ends the game). */ export const UNIT_WRITABLE: ReadonlySet = new Set(["hp", "shields", "energy", "kills", "cooldown", "resources", "stim", "ensnare", "plague", "lockdown", "maelstrom", "irradiate", "stasis", "buildTime", "rank", "matrix", "invincible", "hallucinated", "speedUpgrade"]); -export const UNIT_NUM_FIELDS: readonly UnitNumField[] = ["hp", "maxHp", "shields", "maxShields", "energy", "owner", "type", "x", "y", "kills", "orderId", "cooldown", "resources", "stim", "ensnare", "plague", "lockdown", "maelstrom", "irradiate", "stasis", "buildTime", "rank", "matrix", "speed"]; +export const UNIT_NUM_FIELDS: readonly UnitNumField[] = ["hp", "maxHp", "shields", "maxShields", "energy", "owner", "type", "x", "y", "kills", "orderId", "cooldown", "resources", "stim", "ensnare", "plague", "lockdown", "maelstrom", "irradiate", "stasis", "buildTime", "rank", "matrix", "speed", "orderTargetX", "orderTargetY", "acidSpores", "orderState", "queuedOrders"]; /** A true / false of a unit on the map; `invincible`, `hallucinated` and `speedUpgrade` take a write. */ -export type UnitFlag = "hallucinated" | "cloaked" | "burrowed" | "invincible" | "underAttack" | "speedUpgrade" | "hasTarget" | "inTransport"; -export const UNIT_FLAGS: readonly UnitFlag[] = ["hallucinated", "cloaked", "burrowed", "invincible", "underAttack", "speedUpgrade", "hasTarget", "inTransport"]; +export type UnitFlag = "hallucinated" | "cloaked" | "burrowed" | "invincible" | "underAttack" | "speedUpgrade" | "hasTarget" | "inTransport" | "opticalFlare"; +export const UNIT_FLAGS: readonly UnitFlag[] = ["hallucinated", "cloaked", "burrowed", "invincible", "underAttack", "speedUpgrade", "hasTarget", "inTransport", "opticalFlare"]; /** A unit on the map, or none. */ export type UnitExpr = @@ -248,7 +249,9 @@ export type UnitExpr = /** A call inlined here whose result is a unit. */ | { kind: "call"; call: Call } /** The unit in slot `index` of this computer's selection (`local.selected` is slot 0; B5), or none: a Local value. */ - | { kind: "selected"; index: number; at: At }; + | { kind: "selected"; index: number; at: At } + /** The unit `unit`'s order is aimed at (`u.orderTarget`), or none. */ + | { kind: "unitOrderTarget"; unit: UnitExpr; at: At }; /** What a unit is told to do. `to` and `target` are known when the script is built; an amount is the program's. */ export type UnitVerb = @@ -260,7 +263,13 @@ export type UnitVerb = /** Hit points down (at 0 the unit dies) or up (to the type's maximum), by points or by a percentage of the maximum. */ | { do: "damage" | "heal"; amount: NumExpr; percent: boolean } /** Centre a location on the unit, its size kept. */ - | { do: "locate"; location: number }; + | { do: "locate"; location: number } + /** A worker sent to mine a mineral field or harvest a gas building, as a right-click on it sends one. */ + | { do: "gather"; target: UnitExpr } + /** A spell cast at a unit, as a player's command gives it: `tech` is one of `CAST_ORDERS`'. */ + | { do: "cast"; tech: number; target: UnitExpr } + /** The order Stop, as the Stop button gives it. */ + | { do: "stop" }; /** * One cell of the game's tables (`tables.ts`): `base + index × stride + key`, `width` bytes or one @@ -322,6 +331,8 @@ export type NumExpr = | { kind: "randomInt"; bound: NumExpr; at: At; label: string } /** A number of a unit on the map; 0 when the unit is none or gone. */ | { kind: "unitField"; unit: UnitExpr; field: UnitNumField; at: At; label: string } + /** How far apart two units are, in pixels, as the game measures a weapon's or a spell's range: between the edges of their boxes. 0 when either is none or gone. */ + | { kind: "unitDistance"; from: UnitExpr; to: UnitExpr; at: At; label: string } /** A cell of the game's tables, unscaled: a flag reads 1 or 0. */ | { kind: "tableRead"; cell: TableCell; at: At; label: string } /** What a player did, as it reached every computer (`input.ts`): a key or a click reads 1 on its frame, the mouse its place on the map, a typed line 1 or a value it carried. */ @@ -780,7 +791,7 @@ export function eachStart(root: unknown, visit: (s: Extract - e.kind === "unitNull" || e.kind === "unitVar" || e.kind === "pick" || e.kind === "unitAt" || (e.kind === "call" && e.call.result?.kind === "unit"); + e.kind === "unitNull" || e.kind === "unitVar" || e.kind === "pick" || e.kind === "unitAt" || e.kind === "unitOrderTarget" || (e.kind === "call" && e.call.result?.kind === "unit"); export const isNumExpr = (e: NumExpr | BoolExpr | UnitExpr | TextExpr): e is NumExpr => { switch (e.kind) { @@ -789,7 +800,7 @@ export const isNumExpr = (e: NumExpr | BoolExpr | UnitExpr | TextExpr): e is Num case "var": return false; // ambiguous by shape; callers know the variable's kind case "element": case "pop": return false; // ambiguous by shape, as a variable is case "length": case "unitPart": return true; - case "unary": case "cast": case "binary": case "intrinsic": case "read": case "randomInt": case "unitField": case "tableRead": case "input": case "taskHandle": return true; + case "unary": case "cast": case "binary": case "intrinsic": case "read": case "randomInt": case "unitField": case "unitDistance": case "tableRead": case "input": case "taskHandle": return true; case "ternary": return isNumExpr(e.whenTrue); case "call": return e.call.result?.kind === "number"; default: return false; @@ -815,7 +826,7 @@ export function declarations(body: Stmt[]): VarDecl[] { case "textLoop": text(s.of); out.push(s.decl); s.body.forEach(stmt); break; case "unitLoop": out.push(s.decl); if (s.was) out.push(s.was); s.body.forEach(stmt); break; case "unitWrite": unit(s.unit); init(s.value); break; - case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); break; + case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); if (s.verb.do === "gather" || s.verb.do === "cast") unit(s.verb.target); break; case "select": s.units.forEach(unit); break; case "tableWrite": init(s.value); break; case "if": init(s.cond); s.then.forEach(stmt); s.else?.forEach(stmt); break; @@ -858,10 +869,11 @@ export function declarations(body: Stmt[]): VarDecl[] { default: break; } }; - const unit = (u: UnitExpr) => { if (u.kind === "call") call(u.call); else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } }; + const unit = (u: UnitExpr): void => { if (u.kind === "call") call(u.call); else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } else if (u.kind === "unitOrderTarget") unit(u.unit); }; const expr = (e: NumExpr) => { switch (e.kind) { case "unitField": case "unitPart": unit(e.unit); break; + case "unitDistance": unit(e.from); unit(e.to); break; case "element": expr(e.index); break; case "unary": case "cast": expr(e.expr); break; case "binary": expr(e.left); expr(e.right); break; diff --git a/compiler/numbers.ts b/compiler/numbers.ts index d83c3b5..bfaf927 100644 --- a/compiler/numbers.ts +++ b/compiler/numbers.ts @@ -173,7 +173,7 @@ export function typeNumbers(program: Program): ProgramDiagnostic[] { case "var": return !!decls.get(e.id)?.bits || never.has(e.id); case "element": case "pop": return !!arrays.get(e.array)?.bits || never.has(e.array); case "length": case "textLength": case "taskHandle": return true; - case "read": case "unitField": case "tableRead": case "input": case "randomInt": return true; + case "read": case "unitField": case "unitDistance": case "tableRead": case "input": case "randomInt": return true; case "ternary": return nonNegative(e.whenTrue) && nonNegative(e.whenFalse); case "intrinsic": return e.unsigned ? false : e.name === "min" ? e.args.every(nonNegative) : e.name === "max" ? e.args.some(nonNegative) : e.name === "sqrt"; case "binary": @@ -260,6 +260,7 @@ export function typeNumbers(program: Program): ProgramDiagnostic[] { case "randomInt": e.bound = floor(e.bound, e.at); return [e, "i32"]; case "taskHandle": return [e, "i32"]; case "unitField": unit(e.unit); return [e, "i32"]; + case "unitDistance": unit(e.from); unit(e.to); return [e, "i32"]; // A part of a unit is bits to keep, never a number to reckon with: read from 0 up, so nothing clamps or biases it. case "unitPart": unit(e.unit); return [e, "u32"]; case "ternary": { @@ -380,7 +381,7 @@ export function typeNumbers(program: Program): ProgramDiagnostic[] { }; const texts: TextMap = { num: (e) => num(e)[0], bool: (e) => bool(e), call: (c) => { call(c); return c; }, text }; - const unit = (u: UnitExpr) => { if (u.kind === "call") call(u.call); else if (u.kind === "unitAt") { u.ptr = num(u.ptr)[0]; u.epd = num(u.epd)[0]; u.uid = num(u.uid)[0]; } }; + const unit = (u: UnitExpr): void => { if (u.kind === "call") call(u.call); else if (u.kind === "unitAt") { u.ptr = num(u.ptr)[0]; u.epd = num(u.epd)[0]; u.uid = num(u.uid)[0]; } else if (u.kind === "unitOrderTarget") unit(u.unit); }; /** * A value stored into a variable: a `u8` / `u16` takes nothing below zero, anything else keeps the 32 bits as they are. @@ -472,6 +473,7 @@ export function typeNumbers(program: Program): ProgramDiagnostic[] { case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") s.verb.amount = floor(s.verb.amount, s.at); + if (s.verb.do === "gather" || s.verb.do === "cast") unit(s.verb.target); break; case "tableWrite": s.value = isTextExpr(s.value) ? text(s.value) : s.boolean ? bool(s.value as BoolExpr) : floor(s.value as NumExpr, s.at); diff --git a/compiler/orders.ts b/compiler/orders.ts index 5ec3b36..296b339 100644 --- a/compiler/orders.ts +++ b/compiler/orders.ts @@ -29,3 +29,18 @@ export const ORDER_NAMES: readonly string[] = [ /** The orders a unit is given by `u.order(…)` and the Order action: move, patrol, attack (an attack-move). */ export const ORDER_OF_VERB: Readonly> = { move: 6, patrol: 152, attack: 14 }; + +/** The workers `u.gather(…)` sends: SCV, Drone, Probe. */ +export const GATHER_WORKERS: readonly number[] = [7, 41, 64]; +/** What `u.gather(…)` makes a worker's order, by its target's type, as a right-click on it does: MoveToMinerals for a mineral field, MoveToGas for a gas building. */ +export const GATHER_ORDERS: readonly { order: number; targets: readonly number[] }[] = [ + { order: 85, targets: [176, 177, 178] }, + { order: 81, targets: [110, 149, 157] }, +]; + +/** The spells `u.cast(tech, target)` gives, by technology: the units that cast it and the order a cast at a unit is. Restoration: a Medic's CastRestoration. */ +export const CAST_ORDERS: readonly { tech: number; casters: readonly number[]; order: number }[] = [ + { tech: 24, casters: [34], order: 180 }, +]; +/** The order `u.stop()` gives, as the Stop button does. */ +export const STOP_ORDER = 1; diff --git a/compiler/ranges.ts b/compiler/ranges.ts index d694e6f..9a873f2 100644 --- a/compiler/ranges.ts +++ b/compiler/ranges.ts @@ -48,7 +48,7 @@ const UNIT_FIELD: Record = { hp: [0, 16777216], maxHp: [0, 16777215], shields: [0, 16777215], maxShields: [0, 65535], energy: [0, 255], owner: [0, 255], type: [0, 65535], x: [0, 65535], y: [0, 65535], kills: [0, 255], orderId: [0, 255], cooldown: [0, 255], resources: [0, 65535], stim: [0, 65535], ensnare: [0, 65535], plague: [0, 65535], lockdown: [0, 65535], maelstrom: [0, 65535], - irradiate: [0, 65535], stasis: [0, 65535], + irradiate: [0, 65535], stasis: [0, 65535], acidSpores: [0, 255], orderState: [0, 255], queuedOrders: [0, 255], }; const STMT_KINDS = new Set(["declare", "assignText", "storeText", "releaseText", "textLoop", "assign", "declareArray", "store", "push", "pop", "setLength", @@ -235,6 +235,7 @@ export function rangeNumbers(program: Program): void { case "read": return ANY; case "randomInt": { const b = num(e.bound, facts); return nonNeg(b) ? [0, Math.max(0, b[1] - 1)] : ANY; } case "unitField": unit(e.unit, facts); return UNIT_FIELD[e.field] ?? ANY; + case "unitDistance": unit(e.from, facts); unit(e.to, facts); return [0, 65535]; case "tableRead": return ANY; case "input": return ANY; case "ternary": bool(e.cond, facts); return join(num(e.whenTrue, withFacts(facts, e.cond, true)), num(e.whenFalse, withFacts(facts, e.cond, false)))!; @@ -339,6 +340,7 @@ export function rangeNumbers(program: Program): void { function unit(u: UnitExpr, facts: Facts): void { if (u.kind === "unitAt") { num(u.ptr, facts); num(u.epd, facts); num(u.uid, facts); } else if (u.kind === "call") call(u.call, new Map()); + else if (u.kind === "unitOrderTarget") unit(u.unit, facts); } /** @@ -435,7 +437,7 @@ export function rangeNumbers(program: Program): void { return; } case "unitWrite": unit(s.unit, facts); if (FLAGS.has(s.field)) bool(s.value as BoolExpr, facts); else num(s.value as NumExpr, facts); return; - case "unitDo": unit(s.unit, facts); if (s.verb.do === "damage" || s.verb.do === "heal") num(s.verb.amount, facts); return; + case "unitDo": unit(s.unit, facts); if (s.verb.do === "damage" || s.verb.do === "heal") num(s.verb.amount, facts); if (s.verb.do === "gather" || s.verb.do === "cast") unit(s.verb.target, facts); return; case "tableWrite": if (isTextExpr(s.value as { kind: string })) text(s.value as TextExpr, facts); else if (s.boolean) bool(s.value as BoolExpr, facts); else num(s.value as NumExpr, facts); return; case "if": { if (holdsCall(s.cond, callCache)) forget(facts); @@ -604,6 +606,7 @@ function pure(e: NumExpr): boolean { switch (e.kind) { case "const": case "var": case "length": case "read": case "taskHandle": return true; case "unitField": case "unitPart": return e.unit.kind === "unitVar" || e.unit.kind === "unitNull"; + case "unitDistance": return [e.from, e.to].every((u) => u.kind === "unitVar" || u.kind === "unitNull"); case "element": return pure(e.index); case "unary": case "cast": return pure(e.expr); case "binary": return pure(e.left) && pure(e.right); diff --git a/compiler/recursion.ts b/compiler/recursion.ts index cd81d5b..99a7015 100644 --- a/compiler/recursion.ts +++ b/compiler/recursion.ts @@ -264,7 +264,12 @@ export function settleRecursion(program: Program): ProgramDiagnostic[] { const [left, right] = operands([{ e: e.left, kind: "unit" }, { e: e.right, kind: "unit" }], pre, w) as UnitExpr[]; return { ...e, left, right }; } + case "unitDistance": { + const [from, to] = operands([{ e: e.from, kind: "unit" }, { e: e.to, kind: "unit" }], pre, w) as UnitExpr[]; + return { ...e, from, to }; + } case "intrinsic": return { ...e, args: operands(e.args.map((a) => ({ e: a, kind: "number" as const })), pre, w) as NumExpr[] }; + case "unitOrderTarget": return { ...e, unit: one(e.unit, "unit") as UnitExpr }; case "unitAt": { const [ptr, epd, uid] = operands([e.ptr, e.epd, e.uid].map((x) => ({ e: x, kind: "number" as const })), pre, w) as NumExpr[]; return { ...e, ptr, epd, uid }; @@ -320,9 +325,11 @@ export function settleRecursion(program: Program): ProgramDiagnostic[] { case "unitDo": { const items: { e: Expr; kind: Kind }[] = [{ e: s.unit, kind: "unit" }]; if (s.verb.do === "damage" || s.verb.do === "heal") items.push({ e: s.verb.amount, kind: "number" }); + if (s.verb.do === "gather" || s.verb.do === "cast") items.push({ e: s.verb.target, kind: "unit" }); const done = operands(items, pre, w); s.unit = done[0] as UnitExpr; if (s.verb.do === "damage" || s.verb.do === "heal") s.verb.amount = done[1] as NumExpr; + if (s.verb.do === "gather" || s.verb.do === "cast") s.verb.target = done[1] as UnitExpr; break; } case "tableWrite": s.value = isTextExpr(s.value) ? rewriteText(s.value, pre, w) : (value(s.value, s.boolean ? "boolean" : "number") as NumExpr | BoolExpr); break; diff --git a/compiler/runtime.ts b/compiler/runtime.ts index 664a560..2cec4eb 100644 --- a/compiler/runtime.ts +++ b/compiler/runtime.ts @@ -665,9 +665,11 @@ export function createRuntime(names: ScriptNames, collector: Collector, options: /* ── The game's tables ── */ const tableValue = (kind: TableKind, field: TableField, index: number, ident: string, key?: number): TableValue => { + const broodWar = field.keyed?.broodWar; + const row = broodWar && key !== undefined && key >= broodWar.from ? { base: broodWar.base, stride: broodWar.stride, key: key - broodWar.from } : { base: field.base, stride: field.stride, key }; const cell: TableCell = { - name: `${kind}.${field.name}`, base: field.base, stride: field.stride, index, width: field.width, - ...(key !== undefined ? { key } : {}), ...(field.bit !== undefined ? { bit: field.bit } : {}), ...(field.scale ? { scale: field.scale } : {}), + name: `${kind}.${field.name}`, base: row.base, stride: row.stride, index, width: field.width, + ...(row.key !== undefined ? { key: row.key } : {}), ...(field.bit !== undefined ? { bit: field.bit } : {}), ...(field.scale ? { scale: field.scale } : {}), ...(kind === "player" ? { player: true } : {}), ...(field.special ? { special: field.special } : {}), }; const fail = (): never => { throw new ScriptError(`${ident} is a value the game holds: it has no value when the script is built. Inside program(), assign to it, assign it to a let, or use it in the program's own arithmetic and comparisons.`); }; diff --git a/compiler/simulateIr.ts b/compiler/simulateIr.ts index 509a8cb..ac651d5 100644 --- a/compiler/simulateIr.ts +++ b/compiler/simulateIr.ts @@ -40,10 +40,10 @@ import { fixedAtan2, fixedDiv, fixedMul, fixedSin, fixedSqrt, fixedText } from "./fixedMath"; import { ActionType, Comparison, ConditionType, SetModifier, SWITCH_COUNT, SwitchAction, SwitchState, type ActionRecord, type ConditionRecord } from "../vendor/triggers"; import { emptyAction, ResourceType } from "../vendor/triggers"; -import { ORDER_OF_VERB } from "./orders"; +import { CAST_ORDERS, GATHER_ORDERS, GATHER_WORKERS, ORDER_OF_VERB, STOP_ORDER } from "./orders"; import { BUILD_BYTES, ERROR_CODES, HEAP_CELLS, HEAP_SMALLEST, STACK_DEPTH, STACK_OVERFLOW_MESSAGE, TEXT_BYTES, TEXT_FIELD_BYTES, UNIT_FLAGS, eachStart, heapCells, isTextExpr, programDeclarations, stackDepth } from "./ir"; import type { TextExpr, ArrayDecl, At, BoolExpr, Call, EventSource, NumExpr, Program, ReadSource, Stmt, TableCell, TextPart, UnitExpr, UnitFilter, UnitNumField, UnitVerb, VarDecl } from "./ir"; -import { cellMax } from "./tables"; +import { cellMax, UNIT_DIMENSIONS } from "./tables"; import { inputsOf, keyName, matchChat, parseChatPattern, type ChatPattern, type InputSource, type MouseButton } from "./input"; import { Simulation, type SimulationOptions } from "./simulate"; import { TABLE_FIELDS } from "./tables"; @@ -531,6 +531,7 @@ class ProgramRun { case "unitAt": { const ptr = (yield* this.num(e.ptr)) >>> 0; yield* this.num(e.epd); const uid = (yield* this.num(e.uid)) >>> 0; return ptr >= 1 ? this.sim.game.at(ptr - 1, uid) : null; } case "call": { yield* this.call(e.call); return e.call.result ? this.unitVars.get(e.call.result.decl.id) ?? null : null; } case "selected": return this.sim.selectedUnit(e.index); + case "unitOrderTarget": return (yield* this.living(e.unit))?.orderTarget ?? null; } } @@ -546,6 +547,7 @@ class ProgramRun { const u = yield* this.living(e); // The amount is computed whether or not there is a unit, as the game computes it. const amount = verb.do === "damage" || verb.do === "heal" ? yield* this.amount(verb.amount) : 0; + const target = verb.do === "gather" || verb.do === "cast" ? yield* this.living(verb.target) : null; if (!u) return; switch (verb.do) { case "kill": case "remove": this.sim.game.gone(u, verb.do === "kill", undefined, false); this.sim.unitEvent(this, verb.do === "kill" ? ActionType.KillUnit : ActionType.RemoveUnit, u, at); break; @@ -553,6 +555,21 @@ class ProgramRun { // (The unit takes up the order and keeps it here: the simulator moves nothing, so it never arrives.) case "order": u.orderId = ORDER_OF_VERB[verb.order]; this.sim.unitEvent(this, ActionType.Order, u, at, { location: verb.target, text: verb.order }); break; case "locate": this.sim.centre(verb.location, u.x, u.y); break; + // (The worker takes up the order and keeps it here: the simulator mines nothing.) + case "gather": { + if (!target || !GATHER_WORKERS.includes(u.type)) break; + const order = GATHER_ORDERS.find((g) => g.targets.includes(target.type))?.order; + if (order !== undefined) { u.orderId = order; u.orderTarget = target; } + break; + } + // (The caster takes up the order and keeps it here: the simulator casts nothing.) + case "cast": { + const spell = CAST_ORDERS.find((c) => c.tech === verb.tech); + if (!target || !spell?.casters.includes(u.type)) break; + u.orderId = spell.order; u.orderState = 0; u.orderTarget = target; + break; + } + case "stop": u.orderId = STOP_ORDER; u.orderState = 0; u.orderTarget = undefined; break; case "damage": case "heal": { // In the game's own units, 256 to a point, as the lowering computes it. const step = verb.percent ? Math.floor((u.maxHp * 256 * amount) / 100) : amount * 256; @@ -603,6 +620,22 @@ class ProgramRun { } case "read": return this.sim.read(e.read) | 0; case "unitField": { const u = yield* this.living(e.unit); return u ? u[e.field] | 0 : 0; } + case "unitDistance": { + const a = yield* this.living(e.from), b = yield* this.living(e.to); + if (!a || !b) return 0; + // Each unit's box from its type's dimensions (left, up, right, down), as the game's unit_sprite_bounding_box has it. + const box = (u: SimUnit) => { + const side = (key: number) => this.sim.tableRead({ name: "unit.dimensions", base: UNIT_DIMENSIONS, stride: 8, index: u.type, key, width: 2 }); + return { left: u.x - side(0), top: u.y - side(2), right: u.x + side(4) + 1, bottom: u.y + side(6) + 1 }; + }; + const p = box(a), q = box(b); + const gap = (from1: number, to1: number, from2: number, to2: number) => (from1 > to2 ? from1 - to2 : from2 > to1 ? from2 - to1 : 0); + let x = gap(p.left, p.right, q.left, q.right), y = gap(p.top, p.bottom, q.top, q.bottom); + if (x < y) [x, y] = [y, x]; + // The game's xy_length: the longer side, with a share of the shorter added once they are far enough from a line. + if (Math.floor(x / 4) < y) x = x - Math.floor(x / 16) + Math.floor((y * 3) / 8) - Math.floor(x / 64) + Math.floor((y * 3) / 256); + return x | 0; + } case "unitPart": { const u = yield* this.unit(e.unit); return u ? (e.part === "uid" ? u.uid : u.slot + 1) : 0; } case "tableRead": return this.sim.tableRead(e.cell) | 0; case "input": return this.sim.input(e.input) | 0; @@ -1660,7 +1693,7 @@ export class ProgramSimulation { centre(location: number, x: number, y: number, size?: { width: number; height: number }): void { this.game.centre(location, x, y, size); } private cellKey(c: TableCell): string { - return `${c.name}:${c.player ? this.slotOf(c.index) : c.index}${c.key !== undefined ? `:${c.key}` : ""}`; + return `${c.name}:${c.player ? this.slotOf(c.index) : c.index}${c.key !== undefined ? `:${c.base.toString(16)}:${c.key}` : ""}`; } /** A cell of the game's tables, in the script's units: what a program wrote, else the caller's answer, else 0. */ diff --git a/compiler/structured.ts b/compiler/structured.ts index 5cfa250..f7f9926 100644 --- a/compiler/structured.ts +++ b/compiler/structured.ts @@ -61,7 +61,8 @@ import { ActionFlag, ActionType, ConditionFlag, PlayerGroup } from "../vendor/tr import type { ActionRecord } from "../vendor/triggers"; import type { HoistedThunks, ProgramPlan } from "./hoist"; import { clockCall, declarationOf, isOnCall, isScriptClass, isScriptFunction, keepsState, libraryCallName, ON_EVENTS, scriptArrow } from "./hoist"; -import { ORDER_NAMES } from "./orders"; +import { CAST_ORDERS, ORDER_NAMES } from "./orders"; +import { TECH_NAMES } from "../vendor/gameNames"; import { DEAF_KEYS, KEY_NAMES, keyName, parseChatPattern, type ChatPattern, type InputSource } from "./input"; import { scriptParams } from "./api"; import { brandOfType, wholeArithmetic, wholeQuotient } from "./hoist"; @@ -11129,6 +11130,13 @@ export class Structured { this.task(e, { decl: v, kind: "number" }); return varRef(v); } + // `a.distanceTo(b)`: how far apart two units are, as the game measures a range. + if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && e.expression.name.text === "distanceTo" && this.isUnitTyped(e.expression.expression)) { + const other = e.arguments[0]; + if (!other || e.arguments.length > 1 || !this.isUnitTyped(other)) { this.c.error(e, "distanceTo() takes the other unit: a.distanceTo(b)."); return null; } + const from = this.unitExpr(e.expression.expression), to = this.unitExpr(other); + return from && to ? this.mark({ kind: "unitDistance", from, to, at: this.at(e), label: this.label(e) }, e) : null; + } const h = this.evaluate(expr); // No function: `let f: (() => void) | undefined = undefined`; no instance (B9): `let next: Node | null = null`. if (h && (h.value === undefined || h.value === null) && this.noFunction(expr)) return num(0); @@ -11643,6 +11651,10 @@ export class Structured { if (got && got.result?.kind !== "unit") { this.c.error(e, `${got.name ?? "This"} does not give a unit.`); return null; } return got ? this.mark({ kind: "call", call: got }, e) : null; } + if (ts.isPropertyAccessExpression(e) && ts.isIdentifier(e.name) && e.name.text === "orderTarget" && this.isUnitTyped(e.expression)) { + const of = this.unitExpr(e.expression); + return of ? this.mark({ kind: "unitOrderTarget", unit: of, at: this.at(e) }, e) : null; + } if (ts.isIdentifier(e) || ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e)) { const kept = this.bindingOf(e); if (kept?.kind === "unitAt") return this.unitAtPlaces(kept, e); @@ -11772,6 +11784,31 @@ export class Structured { emit({ do: "locate", location: at }); return; } + case "gather": { + const a = e.arguments[0]; + if (!a || e.arguments.length > 1 || !this.isUnitTyped(a)) { this.c.error(e, "gather() takes the mineral field or gas building to gather from."); return; } + const target = this.unitExpr(a); + if (target) emit({ do: "gather", target }); + return; + } + case "cast": { + const tech = known(0, "the technology to cast and the unit to cast it at: medic.cast(techs.Restoration, marine)"); + if (tech === undefined) return; + if (!CAST_ORDERS.some((c) => c.tech === tech)) { + const name = typeof tech === "number" ? TECH_NAMES[tech] ?? `technology ${tech}` : describe(tech); + this.c.error(e.arguments[0], `cast() casts techs.Restoration only: ${name} has no cast yet.`); + return; + } + const a = e.arguments[1]; + if (!a || e.arguments.length > 2 || !this.isUnitTyped(a)) { this.c.error(e, "cast() takes the technology and the unit to cast it at: medic.cast(techs.Restoration, marine)."); return; } + const target = this.unitExpr(a); + if (target) emit({ do: "cast", tech: tech as number, target }); + return; + } + case "stop": + if (e.arguments.length) { this.c.error(e, "stop() takes no arguments."); return; } + emit({ do: "stop" }); + return; case "damage": case "heal": { const a = e.arguments[0]; if (!a || e.arguments.length > 1) { this.c.error(e, `${m.name}() takes hit points, or { percent: 50 } of the type's maximum.`); return; } diff --git a/compiler/tables.ts b/compiler/tables.ts index f9b1b2d..2706cb2 100644 --- a/compiler/tables.ts +++ b/compiler/tables.ts @@ -38,10 +38,13 @@ export interface TableField { special?: "speed" | "color" | "name"; /** The TypeScript type of the property, when it is not `number` / `boolean`. */ type?: string; - /** A second index: `stats(P1).upgrades[upgrades.U238Shells]`. The cell is `base + index × stride + key`. */ - keyed?: { kind: TableKind; type: string }; + /** A second index: `stats(P1).upgrades[upgrades.U238Shells]`. The cell is `base + index × stride + key`, from `broodWar`'s base and stride for its keys. */ + keyed?: { kind: TableKind; type: string; broodWar?: BroodWarRows }; } +/** Brood War's techs and upgrades are rows of their own table: a key from `from` up is `key - from` in it. */ +interface BroodWarRows { from: number; base: number; stride: number } + const UNIT_FLAGS = 0x664080; const flag = (name: string, bit: number, doc: string): TableField => ({ name, doc, base: UNIT_FLAGS, stride: 4, width: "bit", bit, boolean: true }); @@ -94,11 +97,15 @@ export const TABLE_FIELDS: Record = { ], player: [ { name: "color", doc: "The colour the player's units and minimap dots are drawn in: one of colors.*, or \"teal\". Takes effect at once.", base: 0x581d76, stride: 1, width: 1, writeOnly: true, special: "color", type: "PlayerColor | ColorName" }, - { name: "upgrades", doc: "The player's level of each upgrade: stats(P1).upgrades[upgrades.TerranInfantryWeapons] = 3.", base: 0x58d2b0, stride: 46, width: 1, keyed: { kind: "upgrade", type: "Upgrade" } }, - { name: "researched", doc: "Whether the player has each technology: stats(P1).researched[techs.Lockdown] = true.", base: 0x58cf44, stride: 24, width: 1, boolean: true, keyed: { kind: "tech", type: "Tech" } }, + { name: "upgrades", doc: "The player's level of each upgrade: stats(P1).upgrades[upgrades.TerranInfantryWeapons] = 3.", base: 0x58d2b0, stride: 46, width: 1, keyed: { kind: "upgrade", type: "Upgrade", broodWar: { from: 46, base: 0x58f32c, stride: 15 } } }, + { name: "allied", doc: "Whether the player has set another player as an ally, as Set Alliance Status does: stats(P1).allied[P2]. It goes one way: P2 may not have P1. Read only.", base: 0x58d634, stride: 12, width: 1, boolean: true, readonly: true, keyed: { kind: "player", type: "Player" } }, + { name: "researched", doc: "Whether the player has each technology: stats(P1).researched[techs.Lockdown] = true.", base: 0x58cf44, stride: 24, width: 1, boolean: true, keyed: { kind: "tech", type: "Tech", broodWar: { from: 24, base: 0x58f140, stride: 20 } } }, ], }; +/** units.dat's dimensions: four words a type, how far its box reaches left, up, right and down of its centre. What the game measures a range between. */ +export const UNIT_DIMENSIONS = 0x6617c8; + /** The palette entries the game's player colours are, by the word a script may write. */ export const PLAYER_COLORS: Record = { red: 111, blue: 165, teal: 159, purple: 164, orange: 179, brown: 19, white: 255, yellow: 135, green: 117 }; /** The minimap's entry for a colour is this far from the units' in the player tables. */ diff --git a/compiler/views.ts b/compiler/views.ts index 089d9f1..17751a4 100644 --- a/compiler/views.ts +++ b/compiler/views.ts @@ -14,7 +14,7 @@ import type { ArrayDecl, FuncDecl, Program, Stmt } from "./ir"; export interface View { dirty: string; declare: Stmt; build: Stmt[] } /** What a view reads that only the game knows: never followed. */ -const GAME_READS: ReadonlySet = new Set(["input", "randomInt", "random", "read", "tableRead", "unitField", "cond", "edge", "running", "unitAlive", "unitFlag", "pick", "pop"]); +const GAME_READS: ReadonlySet = new Set(["input", "randomInt", "random", "read", "tableRead", "unitField", "unitDistance", "cond", "edge", "running", "unitAlive", "unitFlag", "pick", "pop"]); /** The statements that hold lists of statements, by the fields that hold them. */ const LISTS = ["body", "then", "else", "update"] as const; diff --git a/compiler/world.ts b/compiler/world.ts index 16e691e..ce463dc 100644 --- a/compiler/world.ts +++ b/compiler/world.ts @@ -30,8 +30,12 @@ export interface SimUnit { hp: number; maxHp: number; shields: number; maxShields: number; energy: number; kills: number; orderId: number; cooldown: number; resources: number; stim: number; ensnare: number; plague: number; lockdown: number; maelstrom: number; irradiate: number; stasis: number; - buildTime: number; rank: number; matrix: number; speed: number; + buildTime: number; rank: number; matrix: number; speed: number; orderTargetX: number; orderTargetY: number; + acidSpores: number; orderState: number; queuedOrders: number; + /** The unit its order is aimed at, if any. */ + orderTarget?: SimUnit; hallucinated: boolean; cloaked: boolean; burrowed: boolean; invincible: boolean; underAttack: boolean; speedUpgrade: boolean; hasTarget: boolean; inTransport: boolean; + opticalFlare: boolean; /** Still on the map. */ alive: boolean; /** Its place in the unit table, from 0; another unit's once this one is gone. */ @@ -162,8 +166,9 @@ export class World { const shields = init.shields ?? init.maxShields ?? 0; const unit: SimUnit = { x: 0, y: 0, energy: 0, kills: 0, orderId: 3, cooldown: 0, resources: 0, - stim: 0, ensnare: 0, plague: 0, lockdown: 0, maelstrom: 0, irradiate: 0, stasis: 0, buildTime: 0, rank: 0, matrix: 0, speed: 0, - hallucinated: false, cloaked: false, burrowed: false, invincible: false, underAttack: false, speedUpgrade: false, hasTarget: false, inTransport: false, + stim: 0, ensnare: 0, plague: 0, lockdown: 0, maelstrom: 0, irradiate: 0, stasis: 0, buildTime: 0, rank: 0, matrix: 0, speed: 0, orderTargetX: 0, orderTargetY: 0, + acidSpores: 0, orderState: 0, queuedOrders: 0, + hallucinated: false, cloaked: false, burrowed: false, invincible: false, underAttack: false, speedUpgrade: false, hasTarget: false, inTransport: false, opticalFlare: false, ...init, hp, maxHp: init.maxHp ?? hp, shields, maxShields: init.maxShields ?? shields, alive: true, slot, uid, }; this.table[slot] = unit; diff --git a/docs/ir.md b/docs/ir.md index 335bd1e..a8e660f 100644 --- a/docs/ir.md +++ b/docs/ir.md @@ -187,7 +187,7 @@ frame's `saves`, and a `slice` is never declared. | `assignUnit` | `target`, `value` | `target = value` for a unit variable. | | `unitLoop` | `decl`, `filter`, `source?`, `was?`, `event?`, `body` | `for (const u of unitsAt(…))`: the body once for every unit the filter matches, oldest first — the game's unit table from slot 0 and then from 1699 downwards, stopping once every unit in use has been met — within the frame (the compiler refuses a `sleep` inside). `decl` is the unit of the turn; `break` and `continue` are the loop's. With `source` (`on.created` / `on.died`, since version 18; `killed`, `ordered`, `morphed` since 19) the units are this frame's events pass's instead, `was` a number variable set at each turn and `event` a filter of the event's own (*Events*, below). | | `unitWrite` | `unit`, `field`, `value` | `u.hp = 40`, `u.invincible = true`. Nothing happens when the unit is none or gone. Hit points at 0 kill. | -| `unitDo` | `unit`, `verb` | `{ do: "kill" }`, `{ do: "remove" }`, `{ do: "give", to }`, `{ do: "order", order, target }` (a location), `{ do: "damage" \| "heal", amount, percent }`, `{ do: "locate", location }`. Nothing happens when the unit is none or gone; an amount is evaluated either way. | +| `unitDo` | `unit`, `verb` | `{ do: "kill" }`, `{ do: "remove" }`, `{ do: "give", to }`, `{ do: "order", order, target }` (a location), `{ do: "damage" \| "heal", amount, percent }`, `{ do: "locate", location }`, `{ do: "gather", target }` (an SCV, Drone or Probe sent to a mineral field or a gas building: the order MoveToMinerals or MoveToGas, its state 0 and its target written; anything else either way round is left alone), `{ do: "cast", tech, target }` (a spell at a unit: for Restoration, a Medic's CastRestoration, its state 0 and its target written; a caster of another type or a target gone is left alone), `{ do: "stop" }` (the order Stop, its state 0). Nothing happens when the unit is none or gone; an amount is evaluated either way. | | `tableWrite` | `cell`, `value`, `scaled?`, `boolean?` | A cell of the game's tables. `value` is a number expression, a boolean one (`boolean`), or `{ kind: "text", text }` for a name. `scaled`: the number is already what the cell stores. | | `if` | `cond`, `then`, `else?` | As it reads. | | `while` | `cond?`, `body` | `cond` absent means `while (true)`, or a condition known true when the script was built. | @@ -295,6 +295,7 @@ Numbers (`NumExpr`): | `read` | `read` — a value of the game, taken when the expression is evaluated (below) | | `randomInt` | `bound` — a whole number from 0 to `bound` − 1, fresh at every evaluation; 0 when `bound` is 0 | | `unitField` | `unit`, `field` — a number of a unit; 0 when the unit is none or gone | +| `unitDistance` | `from`, `to` — how far apart two units are as the game measures a range: the gaps between their boxes (each its type's dimensions in units.dat around its centre) along x and y, made one length by the game's `xy_length`; 0 when either is none or gone | | `tableRead` | `cell` — a cell of the game's tables in the script's units (stored ÷ `scale`, rounded down); a flag reads 1 or 0 | | `input` | `input` — what a player did, as it reached every computer (below): a key, a click and a typed line read 1 on their frame, the mouse its place on the map | | `ternary` | `cond`, `whenTrue`, `whenFalse` | @@ -318,7 +319,7 @@ Booleans (`BoolExpr`): | `unitAlive` | `unit` — `if (target)`: there is a unit and it is still on the map | | `running` | `task` (a number) — `t.running`: the task that number stands for has not ended or been cancelled | | `unitSame` | `left`, `right` — both name one unit of the game (none is never the same as anything) | -| `unitFlag` | `unit`, `flag: hallucinated | cloaked | burrowed | invincible | underAttack`; false when the unit is none or gone | +| `unitFlag` | `unit`, `flag: hallucinated | cloaked | burrowed | invincible | underAttack | speedUpgrade | hasTarget | inTransport | opticalFlare`; false when the unit is none or gone | | `edge` | `edge: rose | once`, `cond` | | `ternary` | `cond`, `whenTrue`, `whenFalse` | | `call` | `call` (its boolean result) | @@ -652,6 +653,7 @@ Units (`UnitExpr`): | `pick` | `by: first | nearest | random`, `filter`, `near?`, `mouse?`, `within?` — one of the units the filter matches: the first in that order (the oldest), the nearest to the centre of location `near` by \|dx\| + \|dy\| (the first of equals), or one drawn at random; none when nothing matches. With `mouse` (a player: a slot, or 13) in place of `near`, the nearest to that player's mouse and no farther from it than `within` pixels | | `call` | `call` whose result is a unit | | `selected` | `index` — the unit in that slot of this computer's selection (0 is the one the panel shows), or none. Differs from one computer to the next. Since version 23 | +| `unitOrderTarget` | `unit` — the unit `unit`'s order is aimed at (the one it follows, attacks or mines), or none when the order is aimed at a place or at nothing | ``` UnitFilter { type?, owner?, at? } @@ -662,8 +664,8 @@ flags, as a trigger counts them); `owner` a slot or 13; `at` a 1-based location holds the unit's centre, edges included. An absent part matches all, and a unit that is dying matches nothing. Number fields: `hp` (whole points, a started point counting, as the game shows it), `maxHp`, `shields`, `maxShields`, `energy`, `owner`, `type`, `x`, `y`, -`kills`, `orderId`, `cooldown`, `resources`, and the timers `stim` `ensnare` `plague` -`lockdown` `maelstrom` `irradiate` `stasis`. A written value stops at what the game's +`kills`, `orderId`, `orderTargetX`, `orderTargetY` (where the order is aimed, in pixels), `orderState`, `queuedOrders` (the orders waiting behind it that the game counts: those with a button), `cooldown`, `resources`, the timers `stim` `ensnare` `plague` +`lockdown` `maelstrom` `irradiate` `stasis`, and `acidSpores` (the stacks, 0–9). A written value stops at what the game's cell holds: 255 for a byte (kills, cooldown, timers, energy points), 65 535 for resources, 2²⁴ − 1 hit points. diff --git a/ledger/units/spells-auto-restore.ts b/ledger/units/spells-auto-restore.ts new file mode 100644 index 0000000..d3afeec --- /dev/null +++ b/ledger/units/spells-auto-restore.ts @@ -0,0 +1,4 @@ +// ledger: step 10, takes +// trigscript/spells: a human player's idle Medic restores the nearest afflicted unit of its owner's or an ally's in range: `buildAutoRestoreProgram()` at the top of a script. +import { buildAutoRestoreProgram } from "trigscript/spells"; +buildAutoRestoreProgram(); diff --git a/ledger/units/unit-acid-spores-read.ts b/ledger/units/unit-acid-spores-read.ts new file mode 100644 index 0000000..2e3e742 --- /dev/null +++ b/ledger/units/unit-acid-spores-read.ts @@ -0,0 +1,5 @@ +// ledger: step 10, takes +// Acid spores on a unit, read: `u.acidSpores`. +program(() => { + print(`${first({ owner: P1 })!.acidSpores}`); +}); diff --git a/ledger/units/unit-cast.ts b/ledger/units/unit-cast.ts new file mode 100644 index 0000000..a0eeded --- /dev/null +++ b/ledger/units/unit-cast.ts @@ -0,0 +1,6 @@ +// ledger: step 10, takes +// A spell cast at a unit, as a player's command gives it: `medic.cast(techs.Restoration, marine)`. +program(() => { + const marine = first({ owner: P1, type: units.TerranMarine }); + if (marine) first({ owner: P1, type: units.TerranMedic })?.cast(techs.Restoration, marine); +}); diff --git a/ledger/units/unit-distance-to.ts b/ledger/units/unit-distance-to.ts new file mode 100644 index 0000000..aded1bc --- /dev/null +++ b/ledger/units/unit-distance-to.ts @@ -0,0 +1,6 @@ +// ledger: step 10, takes +// How far apart two units are, edge to edge, as the game measures a range: `a.distanceTo(b)`. +program(() => { + const a = first({ owner: P1 }), b = first({ owner: P2 }); + if (a) if (b) if (a.distanceTo(b) <= 192) print("in range"); +}); diff --git a/ledger/units/unit-gather.ts b/ledger/units/unit-gather.ts new file mode 100644 index 0000000..fa864d0 --- /dev/null +++ b/ledger/units/unit-gather.ts @@ -0,0 +1,6 @@ +// ledger: step 10, takes +// A worker sent to mine a mineral field, as a right-click on it sends one: `scv.gather(field)`. +program(() => { + const field = first({ type: units.MineralFieldType1 }); + if (field) first({ owner: P1, type: units.TerranSCV })?.gather(field); +}); diff --git a/ledger/units/unit-optical-flare-read.ts b/ledger/units/unit-optical-flare-read.ts new file mode 100644 index 0000000..3887796 --- /dev/null +++ b/ledger/units/unit-optical-flare-read.ts @@ -0,0 +1,5 @@ +// ledger: step 10, takes +// Whether a unit is blinded by Optical Flare: `u.opticalFlare`. +program(() => { + if (first({ owner: P1 })?.opticalFlare) print("blind"); +}); diff --git a/ledger/units/unit-order-state-read.ts b/ledger/units/unit-order-state-read.ts new file mode 100644 index 0000000..464ce45 --- /dev/null +++ b/ledger/units/unit-order-state-read.ts @@ -0,0 +1,5 @@ +// ledger: step 10, takes +// How far a unit has got with its order: `u.orderState`. +program(() => { + print(`${first({ owner: P1 })!.orderState}`); +}); diff --git a/ledger/units/unit-order-target-position-read.ts b/ledger/units/unit-order-target-position-read.ts new file mode 100644 index 0000000..e32996d --- /dev/null +++ b/ledger/units/unit-order-target-position-read.ts @@ -0,0 +1,6 @@ +// ledger: step 10, takes +// Where a unit's order is aimed, in pixels: `u.orderTargetX`, `u.orderTargetY`. +program(() => { + const u = first({ owner: P1 }); + if (u) print(`going to ${u.orderTargetX},${u.orderTargetY}`); +}); diff --git a/ledger/units/unit-order-target-read.ts b/ledger/units/unit-order-target-read.ts new file mode 100644 index 0000000..c0169c3 --- /dev/null +++ b/ledger/units/unit-order-target-read.ts @@ -0,0 +1,9 @@ +// ledger: step 10, takes +// The unit a unit's order is aimed at, or none: `u.orderTarget`. +program(() => { + const u = first({ owner: P1 }); + if (u) { + const aimed = u.orderTarget; + if (aimed) print(`aimed at a unit of type ${aimed.type}`); + } +}); diff --git a/ledger/units/unit-queued-orders-read.ts b/ledger/units/unit-queued-orders-read.ts new file mode 100644 index 0000000..0e869a3 --- /dev/null +++ b/ledger/units/unit-queued-orders-read.ts @@ -0,0 +1,5 @@ +// ledger: step 10, takes +// How many orders wait behind the one a unit is doing: `u.queuedOrders`. +program(() => { + if (first({ owner: P1 })!.queuedOrders > 0) print("more to do"); +}); diff --git a/ledger/units/unit-stop.ts b/ledger/units/unit-stop.ts new file mode 100644 index 0000000..d08d340 --- /dev/null +++ b/ledger/units/unit-stop.ts @@ -0,0 +1,5 @@ +// ledger: step 10, takes +// A unit stopped where it stands, as the Stop button does: `u.stop()`. +program(() => { + first({ owner: P1 })?.stop(); +}); diff --git a/ledger/units/workers-auto-mining.ts b/ledger/units/workers-auto-mining.ts new file mode 100644 index 0000000..e3ebf41 --- /dev/null +++ b/ledger/units/workers-auto-mining.ts @@ -0,0 +1,4 @@ +// ledger: step 10, takes +// trigscript/workers: a human player's new worker rallied to a mineral patch or its own gas building gathers from it: `buildAutoMiningProgram()` at the top of a script. +import { buildAutoMiningProgram } from "trigscript/workers"; +buildAutoMiningProgram(); diff --git a/stdlib/spells.ts b/stdlib/spells.ts new file mode 100644 index 0000000..e550884 --- /dev/null +++ b/stdlib/spells.ts @@ -0,0 +1,169 @@ +/** + * Spells that cast themselves: the standard library's "trigscript/spells" (TrigScript 4). + * + * import { buildAutoRestoreProgram } from "trigscript/spells"; + * + * buildAutoRestoreProgram(); // at the top of the script, once + * buildAutoRestoreProgram({ switch: "Medics trained", keepEnergy: 25 }); // or tied to a switch, keeping 25 energy + * + * With auto-restore on, a human player's Medic that is idle, or healing on its own from idle, casts Restoration on a + * unit of its owner's, or of a player its owner has allied, that is within the spell's range and carries Lockdown, + * Irradiate, Plague, Ensnare, Maelstrom, Acid Spores or Optical Flare. It is a real cast: the owner must have researched + * Restoration, the Medic must have its energy (and `keepEnergy` more), and the cast shows and costs as a player's + * does. The nearest Medic goes to the nearest afflicted unit, one Medic to a unit; one that is moving, attack-moving, + * holding, patrolling or casting for the player is never used, and a Medic never walks to reach a unit. Parasite + * alone, a unit in stasis or invincible, a hallucination (Restoration kills it) and the Medic itself are left alone. + * Computer players' Medics are left to the computer, which casts Restoration itself. + * + * Played in StarCraft: Remastered (2026-11-11): the order written to the Medic (CastRestoration at the unit) is cast, + * mid-heal too, and the Medic heals on afterwards. How it tells a Medic healing from idle from one the player sent, + * from `map trace` (2026-11-11): either way the order is MedicHeal, but an attack-move or a patrol waits behind it in + * the Medic's queue (`queuedOrders` 1 or 2), and the queue of one healing from idle holds nothing the game counts. + */ +import { program, nextFrame, isHuman, switchIs, switches, allUnits, stats, units, orders, techs, weapons, P1, P2, P3, P4, P5, P6, P7, P8, type Player, type Unit } from "trigscript"; + +function ownerIsHuman(medic: Unit): boolean { + const owner = medic.owner; + if (owner == P1) return isHuman(P1); + if (owner == P2) return isHuman(P2); + if (owner == P3) return isHuman(P3); + if (owner == P4) return isHuman(P4); + if (owner == P5) return isHuman(P5); + if (owner == P6) return isHuman(P6); + if (owner == P7) return isHuman(P7); + if (owner == P8) return isHuman(P8); + return false; +} + +function ownerHasRestoration(medic: Unit): boolean { + const owner = medic.owner; + if (owner == P1) return stats(P1).researched[techs.Restoration]; + if (owner == P2) return stats(P2).researched[techs.Restoration]; + if (owner == P3) return stats(P3).researched[techs.Restoration]; + if (owner == P4) return stats(P4).researched[techs.Restoration]; + if (owner == P5) return stats(P5).researched[techs.Restoration]; + if (owner == P6) return stats(P6).researched[techs.Restoration]; + if (owner == P7) return stats(P7).researched[techs.Restoration]; + if (owner == P8) return stats(P8).researched[techs.Restoration]; + return false; +} + +function playerHasAllied(player: Player, target: Unit): boolean { + const owner = target.owner; + if (owner == P1) return stats(player).allied[P1]; + if (owner == P2) return stats(player).allied[P2]; + if (owner == P3) return stats(player).allied[P3]; + if (owner == P4) return stats(player).allied[P4]; + if (owner == P5) return stats(player).allied[P5]; + if (owner == P6) return stats(player).allied[P6]; + if (owner == P7) return stats(player).allied[P7]; + if (owner == P8) return stats(player).allied[P8]; + return false; +} + +function isFriendly(medic: Unit, target: Unit): boolean { + const owner = medic.owner; + if (target.owner == owner) return true; + if (owner == P1) return playerHasAllied(P1, target); + if (owner == P2) return playerHasAllied(P2, target); + if (owner == P3) return playerHasAllied(P3, target); + if (owner == P4) return playerHasAllied(P4, target); + if (owner == P5) return playerHasAllied(P5, target); + if (owner == P6) return playerHasAllied(P6, target); + if (owner == P7) return playerHasAllied(P7, target); + if (owner == P8) return playerHasAllied(P8, target); + return false; +} + +function isIdleOrHealingFromIdle(medic: Unit): boolean { + const order = medic.orderId; + if (order == orders.Medic) return true; + return (order == orders.MedicHeal || order == orders.MedicHealToIdle) && medic.queuedOrders == 0; +} + +function hasRestorableEffect(target: Unit): boolean { + return target.lockdown > 0 || target.irradiate > 0 || target.plague > 0 || target.ensnare > 0 || target.maelstrom > 0 || target.acidSpores > 0 || target.opticalFlare; +} + +function includes(list: Unit[], unit: Unit): boolean { + for (const each of list) if (each == unit) return true; + return false; +} + +let programBuilt = false; + +/** + * Build the program that turns auto-restore on: every human player's idle or self-healing Medic casts Restoration on + * the nearest afflicted unit of its owner's or an ally's within range. `switch`: a switch of the map, by its name; + * auto-restore runs only while it is set. `keepEnergy`: the energy a Medic keeps after the cast (default 0). Called at + * the top of a script, as programs are made when the map is built; a call after the first adds nothing. + */ +export function buildAutoRestoreProgram(options: { switch?: keyof typeof switches; keepEnergy?: number } = {}) { + if (programBuilt) return; + programBuilt = true; + const keepEnergy = options.keepEnergy ?? 0; + program(async () => { + const sentMedics: Unit[] = []; + const sentTargets: Unit[] = []; + while (true) { + const range = stats(weapons.Restoration).range; + for (let i = sentMedics.length - 1; i >= 0; i--) { + const medic = sentMedics[i], target = sentTargets[i]; + if (medic.orderId == orders.CastRestoration && medic.orderTarget == target) { + // (State 2 is the cast under way, its energy spent: let it land.) + if (medic.orderState == 2 || medic.distanceTo(target) <= range) continue; + medic.stop(); + } + sentMedics.splice(i, 1); + sentTargets.splice(i, 1); + } + if (options.switch !== undefined && !switchIs(switches[options.switch], "set")) { + await nextFrame(); + continue; + } + const energy = stats(techs.Restoration).energy + keepEnergy; + const medics: Unit[] = []; + const castAt: Unit[] = []; + for (const medic of allUnits({ type: units.TerranMedic })) { + if (medic.orderId == orders.CastRestoration) { + const target = medic.orderTarget; + if (target) castAt.push(target); + } else if (isIdleOrHealingFromIdle(medic) && medic.energy >= energy && ownerIsHuman(medic) && ownerHasRestoration(medic)) { + medics.push(medic); + } + } + if (medics.length > 0) { + const pairMedics: Unit[] = []; + const pairTargets: Unit[] = []; + const pairDistances: number[] = []; + for (const target of allUnits({ type: units.Men })) { + if (!hasRestorableEffect(target) || target.stasis > 0 || target.hallucinated || target.invincible || includes(castAt, target)) continue; + for (const medic of medics) { + if (medic == target || !isFriendly(medic, target)) continue; + const distance = medic.distanceTo(target); + if (distance > range) continue; + pairMedics.push(medic); + pairTargets.push(target); + pairDistances.push(distance); + } + } + while (pairMedics.length > 0) { + let nearest = 0; + for (let i = 1; i < pairDistances.length; i++) if (pairDistances[i] < pairDistances[nearest]) nearest = i; + const medic = pairMedics[nearest], target = pairTargets[nearest]; + medic.cast(techs.Restoration, target); + sentMedics.push(medic); + sentTargets.push(target); + for (let i = pairMedics.length - 1; i >= 0; i--) { + if (pairMedics[i] == medic || pairTargets[i] == target) { + pairMedics.splice(i, 1); + pairTargets.splice(i, 1); + pairDistances.splice(i, 1); + } + } + } + } + await nextFrame(); + } + }); +} diff --git a/stdlib/workers.ts b/stdlib/workers.ts new file mode 100644 index 0000000..cd28ff1 --- /dev/null +++ b/stdlib/workers.ts @@ -0,0 +1,71 @@ +/** + * Workers that go to work: the standard library's "trigscript/workers" (TrigScript 4). + * + * import { buildAutoMiningProgram } from "trigscript/workers"; + * + * buildAutoMiningProgram(); // at the top of the script, once: on for the whole game + * + * With auto-mining on, a human player's new SCV, Probe or Drone whose producer's rally point is on a mineral patch + * starts mining that patch, instead of walking there and standing. One rallied to the player's own finished gas + * building (Refinery, Extractor, Assimilator) starts gathering gas from it. Anywhere else — the ground, a bare geyser, + * a gas building still being built or another player's, a patch mined out — it walks to the rally point as it always + * does. It acts once, as the worker comes out: an order the player gives afterwards stands. Computer players' workers + * and those a trigger makes (Create Unit) are left alone, and a busy patch or gas building is the game's to sort out, + * as when the player right-clicks it. + * + * Played in StarCraft: Remastered (2026-11-07 and 2026-11-08): SCVs, Probes and Drones rallied to minerals and to gas + * all went to work. How it sees a new worker, from `map trace` (2026-11-07): an SCV comes out of training with its + * order changing from Nothing, and a Drone from ZergBirth, on the frame the rally is applied (a Probe was not traced; + * in play it went to work as an SCV does). A rally on a patch gives the worker Move to the patch's exact centre with no target; one on a building gives + * Follow with the building as the target. `gather()` then gives the order a right-click would: MoveToMinerals or + * MoveToGas. + */ +import { program, on, isHuman, allUnits, units, orders, P1, P2, P3, P4, P5, P6, P7, P8, type Unit } from "trigscript"; + +function ownerIsHuman(worker: Unit): boolean { + const owner = worker.owner; + if (owner == P1) return isHuman(P1); + if (owner == P2) return isHuman(P2); + if (owner == P3) return isHuman(P3); + if (owner == P4) return isHuman(P4); + if (owner == P5) return isHuman(P5); + if (owner == P6) return isHuman(P6); + if (owner == P7) return isHuman(P7); + if (owner == P8) return isHuman(P8); + return false; +} + +function gatherFromRally(worker: Unit) { + if (!ownerIsHuman(worker)) return; + if (worker.orderId == orders.Follow) { + const gasBuilding = worker.orderTarget; + if (gasBuilding) if (gasBuilding.owner == worker.owner && gasBuilding.buildTime == 0) worker.gather(gasBuilding); + return; + } + if (worker.orderId != orders.Move || worker.hasTarget) return; + const x = worker.orderTargetX, y = worker.orderTargetY; + for (const patch of allUnits({ type: units.MineralFieldType1 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; } + for (const patch of allUnits({ type: units.MineralFieldType2 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; } + for (const patch of allUnits({ type: units.MineralFieldType3 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; } +} + +let programBuilt = false; + +/** + * Build the program that turns auto-mining on for the whole game: every human player's new SCV, Probe or Drone rallied + * to a mineral patch or the player's own finished gas building starts gathering from it. Called at the top of a + * script, as programs are made when the map is built; a call after the first adds nothing. + */ +export function buildAutoMiningProgram() { + if (programBuilt) return; + programBuilt = true; + program(async () => { + on.order((worker, order, was) => { + if (worker.type == units.ZergDrone) { + if (was == orders.ZergBirth) gatherFromRally(worker); + } else if (was == orders.Nothing) { + if (worker.type == units.TerranSCV || worker.type == units.ProtossProbe) gatherFromRally(worker); + } + }); + }); +} diff --git a/tests/emitter.test.ts b/tests/emitter.test.ts index a849311..f0aec39 100644 --- a/tests/emitter.test.ts +++ b/tests/emitter.test.ts @@ -6,7 +6,7 @@ // lifted game, for fewer loops. import { readFileSync, writeFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import type { ArrayDecl, BoolExpr, Call, FuncDecl, NumExpr, Stmt, TextPart, VarDecl } from "../compiler/ir"; +import type { ArrayDecl, BoolExpr, Call, FuncDecl, NumExpr, Stmt, TableCell, TextPart, VarDecl } from "../compiler/ir"; import { emitBody, emitterCounts } from "../compiler/backend/emit"; import type { ConditionRecord } from "../vendor/triggers"; import { END, SWITCHES, TRIGGER_BYTES, type Dword, type Graph, type Num } from "../compiler/backend/graph"; @@ -1455,8 +1455,10 @@ describe("a map of our own, functions that call themselves", () => { describe("a map of our own, units", () => { const TABLE = 0x59cca8; /** The groups a trigger's unit classes go by, as units.dat has them for the types these tests use (Men, Buildings, Factories). */ - const GROUPS: Record = { 0: 0x08, 1: 0x08, 37: 0x08, 106: 0x30, 109: 0x10 }; - const MAX_HP: Record = { 0: 40, 1: 45, 37: 35, 106: 1500, 109: 500 }; + const GROUPS: Record = { 0: 0x08, 1: 0x08, 34: 0x08, 37: 0x08, 106: 0x30, 109: 0x10 }; + const MAX_HP: Record = { 0: 40, 1: 45, 34: 60, 37: 35, 106: 1500, 109: 500 }; + /** units.dat's dimensions (left, up, right, down) of the types whose distances these tests measure: a Marine's and a Medic's. */ + const DIMENSIONS: Record = { 0: [8, 9, 8, 10], 34: [8, 9, 8, 10] }; /** * The units laid out where the game keeps them, in the places it hands out first — place 0, then 1 699 down — and the * tables a unit's numbers come from; the simulator's world holds the same units, made in the same order. @@ -1481,14 +1483,21 @@ describe("a map of our own, units", () => { put(at + 0xa2, (u.energy ?? 0) * 256, 2); put(at + 0x38, u.speed ?? 0); put(at + 0x5c, u.hasTarget ? 0x700000 + 4 : 0); + put(at + 0x58, u.orderTargetX ?? 0, 2); + put(at + 0x5a, u.orderTargetY ?? 0, 2); put(at + 0x8e, u.rank ?? 0, 1); if (u.underAttack) put(at + 0x87, 12, 1); put(at + 0xac, u.buildTime ?? 0, 2); put(at + 0x114, u.matrix ?? 0, 1); + put(at + 0x4e, u.orderState ?? 0, 1); + put(at + 0x84, u.queuedOrders ?? 0, 1); + put(at + 0x123, u.opticalFlare ? 1 : 0, 1); + put(at + 0x126, u.acidSpores ?? 0, 1); put(at + 0xdc, (u.invincible ? 0x04000000 : 0) | (u.hallucinated ? 0x40000000 : 0) | (u.speedUpgrade ? 0x10000000 : 0) | (u.inTransport ? 0x40 : 0) | (u.burrowed ? 0x10 : 0)); }); for (const [type, hp] of Object.entries(MAX_HP)) put(0x662350 + 4 * Number(type), hp * 256); for (const [type, g] of Object.entries(GROUPS)) put(0x6637a0 + Number(type), g, 1); + for (const [type, sides] of Object.entries(DIMENSIONS)) sides.forEach((side, i) => put(0x6617c8 + 8 * Number(type) + 2 * i, side, 2)); for (const [n, b] of Object.entries(locations)) { const at = 0x58dc60 + 20 * (Number(n) - 1); [b.left, b.top, b.right, b.bottom].forEach((v, i) => put(at + 4 * i, v)); @@ -1503,7 +1512,8 @@ describe("a map of our own, units", () => { const full = units.map((u) => ({ hp: MAX_HP[u.type], maxHp: MAX_HP[u.type], orderId: 3, ...u })); const world = new Simulation([], { units: full, locations, strings: r.strings, unitClass: (type, cls) => cls === 229 || ((GROUPS[type] ?? 0) & ({ 230: 0x08, 231: 0x10, 232: 0x20 }[cls] ?? 0)) !== 0 }); // (The texts shown: a unit killed is an event of its own, with a text that says which.) - const want = simulatePrograms(r.ir, 1, { world, strings: r.strings }).events.filter((e) => e.text !== undefined && e.action.type === 9).map((e) => hex(e.text!)); + const table = (c: TableCell) => (c.name === "unit.dimensions" ? DIMENSIONS[c.index]?.[(c.key ?? 0) / 2] : undefined); + const want = simulatePrograms(r.ir, 1, { world, strings: r.strings, table }).events.filter((e) => e.text !== undefined && e.action.type === 9).map((e) => hex(e.text!)); const o = emitOwn(r); if (typeof o === "string") throw new Error(o); PRINTED.got = []; @@ -1605,6 +1615,155 @@ describe("a map of our own, units", () => { ].join("\n"), units, HOME); }); + describe("gather()", () => { + const place = (slot: number) => TABLE + 336 * slot; + // Places 0, 1 699, 1 698 …: a mineral field, an SCV moving onto its centre, a Refinery, a Probe following it, a Marine. + const GATHERING: SimUnitInit[] = [ + { type: 176, owner: 11, x: 200, y: 100, hp: 100000, maxHp: 100000 }, + { type: 7, owner: 0, x: 100, y: 100, hp: 60, maxHp: 60, orderId: 6, orderTargetX: 200, orderTargetY: 100 }, + { type: 110, owner: 0, x: 400, y: 100, hp: 750, maxHp: 750 }, + { type: 64, owner: 0, x: 400, y: 150, hp: 20, maxHp: 20, orderId: 49 }, + { type: 0, owner: 0, x: 500, y: 150, hp: 40, maxHp: 40 }, + ]; + const SCRIPT = [ + " const scv = first({ type: units.TerranSCV })!;", + " const probe = first({ type: units.ProtossProbe })!;", + " const marine = first({ type: units.TerranMarine })!;", + " const refinery = first({ type: units.TerranRefinery })!;", + " for (const m of allUnits({ type: units.MineralFieldType1 })) if (m.x == scv.orderTargetX && m.y == scv.orderTargetY) scv.gather(m);", + " probe.gather(refinery);", + " marine.gather(refinery);", + " scv.gather(marine);", + " print(`${scv.orderId} ${probe.orderId} ${marine.orderId} ${scv.orderTarget == first({ type: units.MineralFieldType1 })} ${probe.orderTarget == refinery}`);", + ].join("\n"); + + it("is MoveToMinerals at a mineral field and MoveToGas at a gas building, in the simulator as in the game", () => { + same(SCRIPT, GATHERING); + }); + + it("writes the order target, the order state and the order, and leaves anything but a worker alone", () => { + const r = compileScript(ts, { "main.ts": `program(() => {\n${SCRIPT}\n});\n` }, defaultScriptNames(), { lib: defaultLib() }); + expect(r.diagnostics).toEqual([]); + const o = emitOwn(r); + if (typeof o === "string") throw new Error(o); + const memory = memoryOf(GATHERING, {}); + // (A state the game had moved on from, which the order is to start again.) + for (const slot of [1699, 1697]) memory.set(place(slot) + 0x4c, (memory.get(place(slot) + 0x4c)! | 0x00030000) >>> 0); + const marineWord = memory.get(place(1696) + 0x4c); + // (The game's memory as the first frame left it, read before the second frame runs.) + const after = new Map(); + runOwn(o.runs[0].graph, memory, o.values, undefined, 2, (frame, _write, read) => { + if (frame === 2) for (const slot of [1699, 1697, 1696]) for (const offset of [0x4c, 0x5c]) after.set(place(slot) + offset, read(place(slot) + offset)); + }); + const dword = (slot: number, offset: number) => after.get(place(slot) + offset) ?? 0; + expect([(dword(1699, 0x4c) >>> 8) & 0xff, (dword(1699, 0x4c) >>> 16) & 0xff, dword(1699, 0x5c)]).toEqual([85, 0, place(0)]); + expect([(dword(1697, 0x4c) >>> 8) & 0xff, (dword(1697, 0x4c) >>> 16) & 0xff, dword(1697, 0x5c)]).toEqual([81, 0, place(1698)]); + expect([dword(1696, 0x4c), dword(1696, 0x5c)]).toEqual([marineWord, 0]); + }); + + it("reads the unit a Follow is aimed at", () => { + const r = compileScript(ts, { "main.ts": "program(() => {\n const probe = first({ type: units.ProtossProbe })!;\n const t = probe.orderTarget;\n if (t && t.type == units.TerranRefinery && t.owner == probe.owner && t.buildTime == 0) print(`aimed at ${t.x}`);\n if (!first({ type: units.TerranSCV })!.orderTarget) print(\"none\");\n});\n" }, defaultScriptNames(), { lib: defaultLib() }); + expect(r.diagnostics).toEqual([]); + const o = emitOwn(r); + if (typeof o === "string") throw new Error(o); + const memory = memoryOf(GATHERING, {}); + memory.set(place(1697) + 0x5c, place(1698)); + PRINTED.got = []; + runOwn(o.runs[0].graph, memory, o.values); + expect(PRINTED.got).toEqual(["aimed at 400", "none"].map((text) => shown([...new TextEncoder().encode(text)]))); + }); + }); + + describe("cast() and stop()", () => { + const place = (slot: number) => TABLE + 336 * slot; + // Places 0, 1 699, 1 698: a Medic healing, a Marine, a second Medic attack-moving. + const CASTING: SimUnitInit[] = [ + { type: 34, owner: 0, x: 100, y: 100, energy: 100, orderId: 176 }, + { type: 0, owner: 0, x: 120, y: 100 }, + { type: 34, owner: 0, x: 140, y: 100, energy: 100, orderId: 177 }, + ]; + const SCRIPT = [ + " const medic = first({ type: units.TerranMedic })!;", + " const marine = first({ type: units.TerranMarine })!;", + " let other: Unit | null = null;", + " for (const m of allUnits({ type: units.TerranMedic })) other = m;", + " medic.cast(techs.Restoration, marine);", + " marine.cast(techs.Restoration, medic);", + " if (other) other.stop();", + " if (other) print(`${medic.orderId} ${medic.orderState} ${marine.orderId} ${medic.orderTarget == marine} ${other.orderId} ${other.orderState}`);", + ].join("\n"); + + it("is CastRestoration at the target and Stop, in the simulator as in the game", () => { + same(SCRIPT, CASTING); + }); + + it("writes the order target, and the order with its state put back to the start; leaves a caster that is not a Medic alone", () => { + const r = compileScript(ts, { "main.ts": `program(() => {\n${SCRIPT}\n});\n` }, defaultScriptNames(), { lib: defaultLib() }); + expect(r.diagnostics).toEqual([]); + const o = emitOwn(r); + if (typeof o === "string") throw new Error(o); + const memory = memoryOf(CASTING, {}); + // (States the game had moved on to, which the orders are to start again.) + for (const slot of [0, 1698]) memory.set(place(slot) + 0x4c, (memory.get(place(slot) + 0x4c)! | 0x00010000) >>> 0); + const marineWord = memory.get(place(1699) + 0x4c); + const after = new Map(); + runOwn(o.runs[0].graph, memory, o.values, undefined, 2, (frame, _write, read) => { + if (frame === 2) for (const slot of [0, 1699, 1698]) for (const offset of [0x4c, 0x5c]) after.set(place(slot) + offset, read(place(slot) + offset)); + }); + const dword = (slot: number, offset: number) => after.get(place(slot) + offset) ?? 0; + expect([(dword(0, 0x4c) >>> 8) & 0xff, (dword(0, 0x4c) >>> 16) & 0xff, dword(0, 0x5c)]).toEqual([180, 0, place(1699)]); + expect([dword(1699, 0x4c), dword(1699, 0x5c)]).toEqual([marineWord, 0]); + expect([(dword(1698, 0x4c) >>> 8) & 0xff, (dword(1698, 0x4c) >>> 16) & 0xff]).toEqual([1, 0]); + }); + + it("with any other technology is an error that names it", () => { + const r = compileScript(ts, { "main.ts": "program(() => {\n const m = first({ type: units.TerranMedic })!;\n m.cast(techs.OpticalFlare, m);\n});\n" }, defaultScriptNames(), { lib: defaultLib() }); + expect(r.diagnostics.map((d) => d.message)).toEqual(["cast() casts techs.Restoration only: Optical Flare has no cast yet."]); + }); + }); + + it("reads Optical Flare, acid spores, the order's state and the orders queued where the game keeps them", () => { + same([ + " for (const u of allUnits({})) print(`${u.opticalFlare} ${u.acidSpores} ${u.orderState} ${u.queuedOrders}`);", + ].join("\n"), [ + { type: 0, owner: 0, x: 100, y: 100, opticalFlare: true, acidSpores: 3, orderState: 1, queuedOrders: 0 }, + { type: 34, owner: 0, x: 120, y: 100, orderId: 176, orderState: 2, queuedOrders: 1 }, + { type: 0, owner: 1, x: 140, y: 100, acidSpores: 9 }, + ]); + }); + + it("measures how far apart two units are as the game measures a range: between their boxes", () => { + const units: SimUnitInit[] = [ + { type: 34, owner: 0, x: 400, y: 300 }, + { type: 0, owner: 0, x: 600, y: 300 }, + { type: 0, owner: 0, x: 612, y: 300 }, + { type: 0, owner: 0, x: 500, y: 400 }, + { type: 0, owner: 0, x: 405, y: 305 }, + ]; + const r = both([ + " const medic = first({ type: units.TerranMedic })!;", + " let within = 0;", + " for (const t of allUnits({ type: units.TerranMarine })) { print(`${medic.distanceTo(t)}`); if (medic.distanceTo(t) <= 192) within += 1; }", + " print(`${within}`);", + ].join("\n"), units); + // 183 and 195 across (centres 200 and 212 apart, each box 8 wide either side); 83 by 80 is the game's 107; overlapping is 0. + const want = ["183", "195", "107", "0", "3"].map((text) => shown([...new TextEncoder().encode(text)])); + expect(r.want).toEqual(want); + expect(r.got).toEqual(want); + }); + + it("reads whether one player has another as an ally, one way", () => { + const r = compileScript(ts, { "main.ts": "program(() => {\n print(`${stats(P1).allied[P2]} ${stats(P1).allied[P3]} ${stats(P1).allied[P4]} ${stats(P2).allied[P1]}`);\n});\n" }, defaultScriptNames(), { lib: defaultLib() }); + expect(r.diagnostics).toEqual([]); + const o = emitOwn(r); + if (typeof o === "string") throw new Error(o); + // The alliance table, a byte a pair: P1's row is itself (1), P2 allied (1), P3 allied for victory (2), P4 enemy (0); P2's row has P1 as an enemy. + const memory = new Map([[0x58d634, 0x00020101], [0x58d640, 0]]); + PRINTED.got = []; + runOwn(o.runs[0].graph, memory, o.values); + expect(PRINTED.got).toEqual([shown([...new TextEncoder().encode("true true false false")])]); + }); + it("reads a location's bounds and moves one edge at a time", () => { same([ " const b = bounds(1 as Location);", diff --git a/tests/eud-error.test.ts b/tests/eud-error.test.ts index 1b45ca7..f1082e6 100644 --- a/tests/eud-error.test.ts +++ b/tests/eud-error.test.ts @@ -47,6 +47,7 @@ describe("where an address lies", () => { expect(placeOfAddress(0x640b60 + 218 * 2 + 5)).toBe("text lines, line 3 (+5)"); expect(placeOfAddress(0x6509b0)).toBe("current player"); expect(placeOfAddress(0x663888 + 2 * 5)).toBe("stats(): the unit table's minerals, entry 5"); + expect(placeOfAddress(0x58f140 + 20 * 2 + 3)).toBe("stats(): the player table's researched, entry 2"); const list: Allowlist = { version: 1, entries: [ { name: "0x700000", base: 0x700000, width: 16, read: "allowed", write: "allowed", evidence: [], from: "dump" }, { name: "the game's clock", base: 0x700000, width: 4, read: "allowed", write: "ends", evidence: ["probe 9"] }, diff --git a/tests/ownGame.test.ts b/tests/ownGame.test.ts index 81dd09c..9954661 100644 --- a/tests/ownGame.test.ts +++ b/tests/ownGame.test.ts @@ -167,6 +167,18 @@ describe("a map of our own, the game's tables", () => { expect(w.target).toBe(3 * (w.location / 0xff)); }); + it("writes Brood War's techs and upgrades into Brood War's own rows", () => { + const address = (statement: string) => { + const [w] = actions(own(statement).graph); + return (0x58a364 + 4 * w.player + [0xff, 0xff00, 0xff0000, 0xff000000].indexOf(w.location)) >>> 0; + }; + expect(address(`stats(P2).researched[techs.StimPacks] = true;`)).toBe(0x58cf44 + 24); + expect(address(`stats(P1).researched[techs.Restoration] = true;`)).toBe(0x58f140); + expect(address(`stats(P12).researched[techs.Restoration] = true;`)).toBe(0x58f140 + 20 * 11); + expect(address(`stats(P1).upgrades[upgrades.ProtossGroundArmor] = 1;`)).toBe(0x58d2b0 + 5); + expect(address(`stats(P3).upgrades[upgrades.CaduceusReactor] = 1;`)).toBe(0x58f32c + 15 * 2 + 5); + }); + it("writes a flag as its bit, and reads a scaled field divided by its scale", () => { const [w] = actions(own(`stats(units.TerranMarine).detector = true;`).graph); expect(w.location.toString(2).replace(/0/g, "")).toBe("1"); diff --git a/tests/stdlib.test.ts b/tests/stdlib.test.ts index 5d784de..1cb2e03 100644 --- a/tests/stdlib.test.ts +++ b/tests/stdlib.test.ts @@ -1,7 +1,8 @@ /** * The standard library (TrigScript 4): modules of TrigScript shipped with the compiler and imported as * "trigscript/" — fog first. What joins a script's files and when, the location a library reserves, and what the - * fog's functions compile to: a picture's brushes, read back out of the IR, light the picture's tiles. + * fog's functions compile to: a picture's brushes, read back out of the IR, light the picture's tiles. Workers' + * buildAutoMiningProgram(), spells' buildAutoRestoreProgram(). */ import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; @@ -12,7 +13,7 @@ import { defaultScriptNames, type ScriptNames } from "../compiler/names"; import { defaultLib } from "../bundle/lib.mjs"; import { STDLIB_SOURCES } from "../compiler/generated/stdlib"; import { stdlibImports } from "../compiler/stdlib"; -import type { Program, Stmt } from "../compiler/ir"; +import { bodiesOf, type Program, type Stmt } from "../compiler/ir"; import { ProgramSimulation } from "../compiler/simulateIr"; const LIB = defaultLib(); @@ -285,3 +286,71 @@ program(async () => { const hs: number[] = [80]; const sh: number[] = [1]; while expect(column).toBe(Array.from({ length: 96 }, (_, y) => (lit.has(y) ? "#" : ".")).join("")); }); }); + +describe("trigscript/workers", () => { + const IMPORTED = `import { buildAutoMiningProgram } from "trigscript/workers";\n`; + + it("buildAutoMiningProgram() at the top of a script is the library's program: a listener for new orders that gives the gather order", () => { + const r = ok(`${IMPORTED}buildAutoMiningProgram();`); + expect(r.ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts"]); + const statements = bodiesOf(r.ir[0]).flatMap((body) => walk(body)); + expect(statements.some((s) => s.kind === "unitLoop" && s.source === "ordered")).toBe(true); + expect(statements.some((s) => s.kind === "unitDo" && s.verb.do === "gather")).toBe(true); + }); + + it("imported and not called, it adds nothing", () => { + expect(ok(`${IMPORTED}program(() => {});`).ir.map((p) => p.at?.file)).toEqual(["main.ts"]); + }); + + it("stands beside the script's own on.order() listeners", () => { + const r = ok(`${IMPORTED}buildAutoMiningProgram();\non.order((u, order) => { if (order == orders.Move) print("moved"); });\nprogram(async () => { on.order((u) => { print("ordered"); }); });`); + expect(r.ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts", "main.ts", "main.ts"]); + }); + + it("called again, in the same file or another, it adds nothing", () => { + expect(ok(`${IMPORTED}buildAutoMiningProgram();\nbuildAutoMiningProgram();`).ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts"]); + const r = compileScript(ts, { "main.ts": `${IMPORTED}import "./more";\nbuildAutoMiningProgram();`, "more.ts": `${IMPORTED}buildAutoMiningProgram();` }, NAMES, { lib: LIB }); + expect(r.diagnostics).toEqual([]); + expect(r.ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts"]); + }); + + it("is on again in the next build", () => { + ok(`${IMPORTED}buildAutoMiningProgram();`); + expect(ok(`${IMPORTED}buildAutoMiningProgram();`).ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts"]); + }); +}); + +describe("trigscript/spells", () => { + const IMPORTED = `import { buildAutoRestoreProgram } from "trigscript/spells";\n`; + const statementsOf = (r: CompileResult) => bodiesOf(r.ir[0]).flatMap((body) => walk(body)); + + it("buildAutoRestoreProgram() at the top of a script is the library's program: a loop that casts Restoration and stops a Medic", () => { + const r = ok(`${IMPORTED}buildAutoRestoreProgram();`); + expect(r.ir.map((p) => p.at?.file)).toEqual(["__trigscript__/spells.ts"]); + const statements = statementsOf(r); + expect(statements.some((s) => s.kind === "unitDo" && s.verb.do === "cast" && s.verb.tech === 24)).toBe(true); + expect(statements.some((s) => s.kind === "unitDo" && s.verb.do === "stop")).toBe(true); + }); + + it("takes a switch of the map by its name, and the energy to keep", () => { + const r = ok(`${IMPORTED}buildAutoRestoreProgram({ switch: "Switch3", keepEnergy: 25 });`); + expect(r.ir.map((p) => p.at?.file)).toEqual(["__trigscript__/spells.ts"]); + // (The condition Switch, "set": Switch3 is switch 2, counted from 0.) + expect(JSON.stringify(r.ir[0])).toContain('"comparison":2,"type":11,"resource":2,'); + }); + + it("refuses a switch the map does not have", () => { + expect(compile(`${IMPORTED}buildAutoRestoreProgram({ switch: "Medics trained" });`).diagnostics.map((d) => d.message).join("\n")).toContain('"Medics trained"'); + }); + + it("imported and not called, it adds nothing", () => { + expect(ok(`${IMPORTED}program(() => {});`).ir.map((p) => p.at?.file)).toEqual(["main.ts"]); + }); + + it("called again, in the same file or another, it adds nothing", () => { + expect(ok(`${IMPORTED}buildAutoRestoreProgram();\nbuildAutoRestoreProgram({ keepEnergy: 10 });`).ir.map((p) => p.at?.file)).toEqual(["__trigscript__/spells.ts"]); + const r = compileScript(ts, { "main.ts": `${IMPORTED}import "./more";\nbuildAutoRestoreProgram();`, "more.ts": `${IMPORTED}buildAutoRestoreProgram();` }, NAMES, { lib: LIB }); + expect(r.diagnostics).toEqual([]); + expect(r.ir.map((p) => p.at?.file)).toEqual(["__trigscript__/spells.ts"]); + }); +}); diff --git a/tests/units.test.ts b/tests/units.test.ts index 1908be4..75015ab 100644 --- a/tests/units.test.ts +++ b/tests/units.test.ts @@ -201,6 +201,11 @@ describe("stats(): the game's tables", () => { expect([sim.value("cost"), sim.value("time"), sim.value("cloaked"), sim.value("other"), sim.value("level"), sim.value("has")]).toEqual([30, 1, true, 50, 3, true]); expect(sim.tables.get("unit.buildTime:0")).toBe(23); }); + it("a Brood War tech is a cell of its own, apart from the original tech at its place in the row", () => { + const sim = run(`stats(P2).researched[techs.StimPacks] = true; let restoration = stats(P1).researched[techs.Restoration]; let reactor = stats(P1).upgrades[upgrades.CaduceusReactor]; + stats(P1).researched[techs.Restoration] = true; let after = stats(P1).researched[techs.Restoration]; let stim = stats(P1).researched[techs.StimPacks];`); + expect([sim.value("restoration"), sim.value("reactor"), sim.value("after"), sim.value("stim")]).toEqual([false, 0, true, false]); + }); it("a cell holds what its width allows", () => { const sim = run(`let big = 300; stats(units.TerranMarine).armor = big; stats(units.ZergZergling).name = "Dog"; stats(CurrentPlayer).color = colors.green;`); expect(sim.tables.get("unit.armor:0")).toBe(255);