diff --git a/compiler/backend/emit.ts b/compiler/backend/emit.ts index 417774f..8b9fbe6 100644 --- a/compiler/backend/emit.ts +++ b/compiler/backend/emit.ts @@ -231,7 +231,7 @@ export function unlowered(s: Stmt, decls: Map, arrays: Map> = { 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), }; const HP = 0x08 >> 2, SHIELDS = 0x60 >> 2, ENERGY = word(0xa2, 2), STATUS = 0xdc >> 2, USER_ACTION = word(0x93, 1); /** @@ -80,6 +82,8 @@ const ATTACKED = word(0x87, 1); 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. */ const ORDER_TARGET = 0x5c >> 2, MATRIX_HP = word(0x112, 2), MATRIX_POINTS = 250 * 256; +/** The order's state, beside the order in its dword: what `gather()` puts back to the start. */ +const ORDER_STATE = word(0x4e, 1); /** The most a field written holds, as the simulator stops it: points for hit points and shields, a byte, a word. */ const TOPS: Partial> = { hp: 0xffffff, shields: 0xffffff, energy: 255, kills: 255, cooldown: 255, resources: 0xffff, stim: 255, ensnare: 255, plague: 255, lockdown: 255, maelstrom: 255, irradiate: 255, stasis: 255, buildTime: 0xffff, rank: 255, matrix: 255 }; /** The Order action's orders. */ @@ -645,6 +649,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); @@ -757,6 +772,7 @@ export function unitValues(program: Program, events?: { sources: Set any(types.map((type) => cmp("==", ranged(V(id), 0, 0xffff), k(type)))); + body.push(dec(worker, k(0), 0xffff), dec(aimed, k(0), 0xffff), dec(order, k(0), 255), ...readInto(worker, e, TYPE)); + body.push(...when(all([is(worker, GATHER_WORKERS), alive(target)]), [ + ...readInto(aimed, target.e, TYPE), + ...GATHER_ORDERS.flatMap((g) => 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 "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"); diff --git a/compiler/check.ts b/compiler/check.ts index 070328f..def0306 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); }; @@ -76,7 +76,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") 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 +280,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 +298,8 @@ 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 "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 e9cf7e4..c519173 100644 --- a/compiler/declarations.ts +++ b/compiler/declarations.ts @@ -145,6 +145,11 @@ ${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; /** 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; /** @@ -199,6 +204,11 @@ ${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; } /** 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/gameSim.ts b/compiler/gameSim.ts index 18820ef..5018a34 100644 --- a/compiler/gameSim.ts +++ b/compiler/gameSim.ts @@ -205,6 +205,8 @@ 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)); } // 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/input.ts b/compiler/input.ts index 6721b41..18953d3 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; } }; @@ -254,7 +255,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") 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..ff19e6a 100644 --- a/compiler/ir.ts +++ b/compiler/ir.ts @@ -221,10 +221,10 @@ 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"; /** 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"]; /** 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"]; @@ -248,7 +248,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 +262,9 @@ 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 }; /** * One cell of the game's tables (`tables.ts`): `base + index × stride + key`, `width` bytes or one @@ -780,7 +784,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) { @@ -815,7 +819,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") 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,7 +862,7 @@ 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; diff --git a/compiler/numbers.ts b/compiler/numbers.ts index d83c3b5..9c5bed2 100644 --- a/compiler/numbers.ts +++ b/compiler/numbers.ts @@ -380,7 +380,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 +472,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") 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..e9dcb1c 100644 --- a/compiler/orders.ts +++ b/compiler/orders.ts @@ -29,3 +29,11 @@ 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] }, +]; diff --git a/compiler/ranges.ts b/compiler/ranges.ts index d694e6f..16b4928 100644 --- a/compiler/ranges.ts +++ b/compiler/ranges.ts @@ -339,6 +339,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 +436,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") 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); diff --git a/compiler/recursion.ts b/compiler/recursion.ts index cd81d5b..13d27f5 100644 --- a/compiler/recursion.ts +++ b/compiler/recursion.ts @@ -265,6 +265,7 @@ export function settleRecursion(program: Program): ProgramDiagnostic[] { return { ...e, left, right }; } 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 +321,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") 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.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/simulateIr.ts b/compiler/simulateIr.ts index 509a8cb..3d5764e 100644 --- a/compiler/simulateIr.ts +++ b/compiler/simulateIr.ts @@ -40,7 +40,7 @@ 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 { GATHER_ORDERS, GATHER_WORKERS, ORDER_OF_VERB } 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"; @@ -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" ? 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,13 @@ 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; + } 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; diff --git a/compiler/structured.ts b/compiler/structured.ts index f8e2956..e976a2c 100644 --- a/compiler/structured.ts +++ b/compiler/structured.ts @@ -11639,6 +11639,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); @@ -11768,6 +11772,13 @@ 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 "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/world.ts b/compiler/world.ts index ce49095..96b2c28 100644 --- a/compiler/world.ts +++ b/compiler/world.ts @@ -30,7 +30,9 @@ 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; + /** 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; /** Still on the map. */ alive: boolean; @@ -162,7 +164,7 @@ 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, + 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, hallucinated: false, cloaked: false, burrowed: false, invincible: false, underAttack: false, speedUpgrade: false, hasTarget: false, inTransport: false, ...init, hp, maxHp: init.maxHp ?? hp, shields, maxShields: init.maxShields ?? shields, alive: true, slot, uid, }; diff --git a/docs/ir.md b/docs/ir.md index 335bd1e..6793796 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). 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. | @@ -652,6 +652,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,7 +663,7 @@ 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` +`kills`, `orderId`, `orderTargetX`, `orderTargetY` (where the order is aimed, in pixels), `cooldown`, `resources`, and the timers `stim` `ensnare` `plague` `lockdown` `maelstrom` `irradiate` `stasis`. 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/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-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/tests/emitter.test.ts b/tests/emitter.test.ts index a849311..59ba437 100644 --- a/tests/emitter.test.ts +++ b/tests/emitter.test.ts @@ -1481,6 +1481,8 @@ 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); @@ -1605,6 +1607,65 @@ 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)]))); + }); + }); + it("reads a location's bounds and moves one edge at a time", () => { same([ " const b = bounds(1 as Location);",