mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-08-07 19:21:30 +00:00
Shrink the per-tick worker → main update payload by ~90% (#4244)
Stacked on #4243 (the `perf:client` harness) — first step of fixing the every-100ms main-thread stutter: make the per-tick burst small before spreading what remains across frames. ## Problem The harness showed the main-thread burst was dominated by `structuredClone` of the `updates` object, and the clone was dominated by two kinds of per-tick churn that re-sent object payloads every tick: - `gold` / `troops` / `tilesOwned` change for nearly every alive player every tick → ~278 partial `PlayerUpdate` objects per tick (world/400 bots), ~508 on giantworldmap. - Attack troop counts tick down every tick → whole `outgoingAttacks`/`incomingAttacks` arrays re-cloned for every fighting player every tick. - `playerNameViewData` (an all-players record) was cloned every tick but only recomputed every 30 ticks. ## Change Three additions to the worker → main protocol (all transferable, zero-clone): 1. **`packedPlayerUpdates`** — `[smallID, tilesOwned, gold, troops]` float64 quads for players whose stats changed. These fields no longer appear in `PlayerUpdate` diffs (first emissions still carry the full snapshot). Gold is exact in a float64 (game values ≪ 2^53). 2. **`packedAttackUpdates`** — `[ownerSmallID, direction, index, troops]` quads. Attack arrays are only resent when membership/order/retreating changes — which is exactly the condition that keeps the patch indexes valid (a tick either resends an array or patches it, never both). 3. **`playerNameViewData` is now optional** — attached only on placement-rebuild ticks (spawn ticks, first ticks, every 30th, spawn end). The client keeps the last applied values; dead players' name placements freeze at death (matching the previous effective behavior). On the client, `GameView.populateFrame` now also rebuilds `names` / `relationMatrix` / `allianceClusters` only when their inputs changed that tick — field presence on a partial `PlayerUpdate` marks them dirty. (`playerStatus`, nuke telegraphs, and attack rings still recompute every tick; they're tick- or unit-dependent.) ## Results (perf:client, this machine; low-end devices ~5–20× slower) Default run (world, 400 bots, 1800 ticks): | stage | before | after | |---|---|---| | clone (serialize+deserialize) | 1.02ms | **0.09ms** | | GameView.update | 0.62ms | **0.29ms** | | WebGLFrameBuilder.update | 0.04ms | 0.04ms | | **TOTAL burst mean** | **1.67ms** | **0.42ms** | | TOTAL p99 / max | 3.47 / 10.3ms | **1.21 / 3.92ms** | giantworldmap/600t: 2.54 → 0.68ms mean. Player update objects: 278 → 6.5 per tick (world), 508 → 12 (giant). The remaining burst is mostly tile apply + per-tick derivations — the part that frame-spreading (next step) addresses. ## Verification - **Sim final hash unchanged** on all three reference configs (`5607618202213430`, `29309648281599524`, `39945089450032050`) — no simulation behavior change. - **View hash unchanged** on all three configs (`942106e9`, `a3aae227`, `cbaaf265`) — the rendered view state is provably identical tick-for-tick, including the name-freeze semantics. - New tests: `tests/PackedPlayerUpdates.test.ts` (drain + GameRunner cadence), packed-channel and freeze-at-death cases in `tests/client/view/GameView.test.ts`, `packAttackTroopDeltas` unit tests and updated diff contract in `tests/GameUpdateUtils.test.ts` / `tests/PlayerUpdateDiff.test.ts`. - `npm test` (1490 tests), `eslint`, `prettier`, `tsc --noEmit` all pass. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
+106
-29
@@ -4,8 +4,13 @@ import { PlayerType } from "../src/core/game/Game";
|
||||
import {
|
||||
applyStateUpdate,
|
||||
diffPlayerUpdate,
|
||||
packAttackTroopDeltas,
|
||||
} from "../src/core/game/GameUpdateUtils";
|
||||
import { GameUpdateType, PlayerUpdate } from "../src/core/game/GameUpdates";
|
||||
import {
|
||||
AttackUpdate,
|
||||
GameUpdateType,
|
||||
PlayerUpdate,
|
||||
} from "../src/core/game/GameUpdates";
|
||||
import { makePlayerUpdate } from "./util/viewStubs";
|
||||
|
||||
function makePlayerState(overrides: Partial<PlayerState> = {}): PlayerState {
|
||||
@@ -41,24 +46,30 @@ describe("diffPlayerUpdate", () => {
|
||||
});
|
||||
|
||||
it("returns a diff with only changed primitives plus type+id", () => {
|
||||
const prev = makePlayerUpdate({ gold: 100n });
|
||||
const next = makePlayerUpdate({ gold: 250n });
|
||||
const prev = makePlayerUpdate({ betrayals: 0 });
|
||||
const next = makePlayerUpdate({ betrayals: 1 });
|
||||
const diff = diffPlayerUpdate(prev, next);
|
||||
expect(diff).not.toBeNull();
|
||||
expect(diff).toEqual({
|
||||
type: GameUpdateType.Player,
|
||||
id: "player-a",
|
||||
gold: 250n,
|
||||
betrayals: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("includes every changed primitive in a single diff", () => {
|
||||
const prev = makePlayerUpdate({ gold: 100n, troops: 50, tilesOwned: 5 });
|
||||
const next = makePlayerUpdate({ gold: 200n, troops: 75, tilesOwned: 5 });
|
||||
const prev = makePlayerUpdate({ betrayals: 0, isTraitor: false });
|
||||
const next = makePlayerUpdate({ betrayals: 1, isTraitor: true });
|
||||
const diff = diffPlayerUpdate(prev, next)!;
|
||||
expect(diff.gold).toBe(200n);
|
||||
expect(diff.troops).toBe(75);
|
||||
expect(diff.tilesOwned).toBeUndefined();
|
||||
expect(diff.betrayals).toBe(1);
|
||||
expect(diff.isTraitor).toBe(true);
|
||||
expect(diff.hasSpawned).toBeUndefined();
|
||||
});
|
||||
|
||||
it("ignores tilesOwned/gold/troops — they travel via packedPlayerUpdates", () => {
|
||||
const prev = makePlayerUpdate({ gold: 100n, troops: 50, tilesOwned: 5 });
|
||||
const next = makePlayerUpdate({ gold: 200n, troops: 75, tilesOwned: 9 });
|
||||
expect(diffPlayerUpdate(prev, next)).toBeNull();
|
||||
});
|
||||
|
||||
it("detects allies array additions", () => {
|
||||
@@ -94,7 +105,22 @@ describe("diffPlayerUpdate", () => {
|
||||
expect(diffPlayerUpdate(prev, next)).toBeNull();
|
||||
});
|
||||
|
||||
it("detects outgoingAttacks element changes", () => {
|
||||
it("detects outgoingAttacks membership/retreating changes", () => {
|
||||
const prev = makePlayerUpdate({
|
||||
outgoingAttacks: [
|
||||
{ attackerID: 1, targetID: 2, troops: 10, id: "a", retreating: false },
|
||||
],
|
||||
});
|
||||
const next = makePlayerUpdate({
|
||||
outgoingAttacks: [
|
||||
{ attackerID: 1, targetID: 2, troops: 10, id: "a", retreating: true },
|
||||
],
|
||||
});
|
||||
const diff = diffPlayerUpdate(prev, next)!;
|
||||
expect(diff.outgoingAttacks).toEqual(next.outgoingAttacks);
|
||||
});
|
||||
|
||||
it("ignores attack troop-count changes — they travel via packedAttackUpdates", () => {
|
||||
const prev = makePlayerUpdate({
|
||||
outgoingAttacks: [
|
||||
{ attackerID: 1, targetID: 2, troops: 10, id: "a", retreating: false },
|
||||
@@ -105,8 +131,7 @@ describe("diffPlayerUpdate", () => {
|
||||
{ attackerID: 1, targetID: 2, troops: 20, id: "a", retreating: false },
|
||||
],
|
||||
});
|
||||
const diff = diffPlayerUpdate(prev, next)!;
|
||||
expect(diff.outgoingAttacks).toEqual(next.outgoingAttacks);
|
||||
expect(diffPlayerUpdate(prev, next)).toBeNull();
|
||||
});
|
||||
|
||||
it("detects alliance list changes", () => {
|
||||
@@ -143,14 +168,76 @@ describe("diffPlayerUpdate", () => {
|
||||
});
|
||||
|
||||
it("always includes type and id on a non-null diff", () => {
|
||||
const prev = makePlayerUpdate({ gold: 100n });
|
||||
const next = makePlayerUpdate({ gold: 200n });
|
||||
const prev = makePlayerUpdate({ betrayals: 0 });
|
||||
const next = makePlayerUpdate({ betrayals: 1 });
|
||||
const diff = diffPlayerUpdate(prev, next)!;
|
||||
expect(diff.type).toBe(GameUpdateType.Player);
|
||||
expect(diff.id).toBe(next.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("packAttackTroopDeltas", () => {
|
||||
const attack = (
|
||||
troops: number,
|
||||
id = "a",
|
||||
retreating = false,
|
||||
): AttackUpdate => ({
|
||||
attackerID: 1,
|
||||
targetID: 2,
|
||||
troops,
|
||||
id,
|
||||
retreating,
|
||||
});
|
||||
|
||||
it("emits [owner, direction, index, troops] quads for changed troop counts", () => {
|
||||
const out: number[] = [];
|
||||
packAttackTroopDeltas(
|
||||
[attack(10, "a"), attack(20, "b")],
|
||||
[attack(10, "a"), attack(15, "b")],
|
||||
7,
|
||||
1,
|
||||
out,
|
||||
);
|
||||
expect(out).toEqual([7, 1, 1, 15]);
|
||||
});
|
||||
|
||||
it("emits nothing when arrays are not membership-equal (diff resends them)", () => {
|
||||
const out: number[] = [];
|
||||
packAttackTroopDeltas(
|
||||
[attack(10, "a")],
|
||||
[attack(15, "a"), attack(5, "b")],
|
||||
7,
|
||||
0,
|
||||
out,
|
||||
);
|
||||
expect(out).toEqual([]);
|
||||
});
|
||||
|
||||
it("a retreat flip suppresses quads even when troops also changed", () => {
|
||||
// retreating is part of membership equality, so the whole array resends
|
||||
// (with fresh troops) and patches must NOT be emitted — a tick resends
|
||||
// or patches, never both.
|
||||
const out: number[] = [];
|
||||
packAttackTroopDeltas(
|
||||
[attack(10, "a", false)],
|
||||
[attack(5, "a", true)],
|
||||
7,
|
||||
0,
|
||||
out,
|
||||
);
|
||||
expect(out).toEqual([]);
|
||||
});
|
||||
|
||||
it("emits nothing for identical references or missing arrays", () => {
|
||||
const out: number[] = [];
|
||||
const arr = [attack(10)];
|
||||
packAttackTroopDeltas(arr, arr, 7, 0, out);
|
||||
packAttackTroopDeltas(undefined, arr, 7, 0, out);
|
||||
packAttackTroopDeltas(arr, undefined, 7, 0, out);
|
||||
expect(out).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyStateUpdate", () => {
|
||||
it("applies every field from a full update", () => {
|
||||
const target = makePlayerState();
|
||||
@@ -276,18 +363,10 @@ describe("applyStateUpdate", () => {
|
||||
|
||||
describe("diff + apply round-trip", () => {
|
||||
it("emitting full first + diff second reconstructs final state", () => {
|
||||
const v0 = makePlayerUpdate({
|
||||
gold: 0n,
|
||||
troops: 100,
|
||||
tilesOwned: 0,
|
||||
allies: [],
|
||||
});
|
||||
const v1 = makePlayerUpdate({
|
||||
gold: 200n,
|
||||
troops: 150,
|
||||
tilesOwned: 5,
|
||||
allies: [2],
|
||||
});
|
||||
// tilesOwned/gold/troops round-trip via packedPlayerUpdates instead
|
||||
// (covered in tests/client/view/GameView.test.ts).
|
||||
const v0 = makePlayerUpdate({ betrayals: 0, allies: [] });
|
||||
const v1 = makePlayerUpdate({ betrayals: 2, allies: [2] });
|
||||
|
||||
// Initial state: receiver applies the full update.
|
||||
const target = makePlayerState();
|
||||
@@ -298,9 +377,7 @@ describe("diff + apply round-trip", () => {
|
||||
expect(diff).not.toBeNull();
|
||||
applyStateUpdate(target, diff);
|
||||
|
||||
expect(target.gold).toBe(200);
|
||||
expect(target.troops).toBe(150);
|
||||
expect(target.tilesOwned).toBe(5);
|
||||
expect(target.betrayals).toBe(2);
|
||||
expect(target.allies).toEqual([2]);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* The worker→main tick payload: per-tick numeric stat churn travels on the
|
||||
* transferable `packedPlayerUpdates` quad buffer (drained from GameImpl),
|
||||
* and `playerNameViewData` is attached only on ticks where the worker
|
||||
* recomputed name placements. See GameUpdateViewData in GameUpdates.ts.
|
||||
*/
|
||||
import { Executor } from "../src/core/execution/ExecutionManager";
|
||||
import { SpawnExecution } from "../src/core/execution/SpawnExecution";
|
||||
import { Game, Player, PlayerInfo, PlayerType } from "../src/core/game/Game";
|
||||
import {
|
||||
GameUpdateType,
|
||||
GameUpdateViewData,
|
||||
} from "../src/core/game/GameUpdates";
|
||||
import { GameRunner } from "../src/core/GameRunner";
|
||||
import { setup } from "./util/Setup";
|
||||
|
||||
const gameID = "game_id";
|
||||
|
||||
describe("packedPlayerUpdates (GameImpl drain)", () => {
|
||||
let game: Game;
|
||||
let alice: Player;
|
||||
|
||||
beforeEach(async () => {
|
||||
game = await setup("plains", {});
|
||||
const aliceInfo = new PlayerInfo(
|
||||
"alice",
|
||||
PlayerType.Human,
|
||||
"alice_client",
|
||||
"alice_id",
|
||||
);
|
||||
game.addPlayer(aliceInfo);
|
||||
game.addExecution(new SpawnExecution(gameID, aliceInfo, game.ref(10, 10)));
|
||||
game.executeNextTick();
|
||||
game.executeNextTick();
|
||||
alice = game.player("alice_id");
|
||||
game.drainPackedPlayerUpdates(); // discard spawn-time churn
|
||||
});
|
||||
|
||||
test("a stat change is drained as a [smallID, tiles, gold, troops] quad", () => {
|
||||
alice.addGold(500n);
|
||||
game.executeNextTick();
|
||||
const packed = game.drainPackedPlayerUpdates();
|
||||
expect(packed).not.toBeNull();
|
||||
// Find alice's quad (other players may have churned too).
|
||||
let quad: number[] | undefined;
|
||||
for (let i = 0; i + 3 < packed!.length; i += 4) {
|
||||
if (packed![i] === alice.smallID()) {
|
||||
quad = Array.from(packed!.subarray(i, i + 4));
|
||||
}
|
||||
}
|
||||
expect(quad).toEqual([
|
||||
alice.smallID(),
|
||||
alice.numTilesOwned(),
|
||||
Number(alice.gold()),
|
||||
alice.troops(),
|
||||
]);
|
||||
});
|
||||
|
||||
test("drain returns null when no stats changed and resets between drains", () => {
|
||||
alice.addGold(500n);
|
||||
game.executeNextTick();
|
||||
expect(game.drainPackedPlayerUpdates()).not.toBeNull();
|
||||
// Drained — a second drain without a tick has nothing.
|
||||
expect(game.drainPackedPlayerUpdates()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("GameRunner payload cadence", () => {
|
||||
let game: Game;
|
||||
let byTick: Map<number, GameUpdateViewData>;
|
||||
let tick: () => void;
|
||||
|
||||
beforeEach(async () => {
|
||||
game = await setup(
|
||||
"plains",
|
||||
{},
|
||||
[],
|
||||
undefined,
|
||||
undefined,
|
||||
false, // keep the spawn phase under the test's control
|
||||
);
|
||||
const aliceInfo = new PlayerInfo(
|
||||
"alice",
|
||||
PlayerType.Human,
|
||||
"alice_client",
|
||||
"alice_id",
|
||||
);
|
||||
game.addPlayer(aliceInfo);
|
||||
game.addExecution(new SpawnExecution(gameID, aliceInfo, game.ref(10, 10)));
|
||||
byTick = new Map();
|
||||
const runner = new GameRunner(
|
||||
game,
|
||||
new Executor(game, gameID, "alice_client"),
|
||||
(gu) => {
|
||||
if (!("errMsg" in gu)) byTick.set(gu.tick, gu);
|
||||
},
|
||||
);
|
||||
// No runner.init(): no SpawnTimerExecution — the game stays in the spawn
|
||||
// phase until the test ends it manually.
|
||||
let turn = 0;
|
||||
tick = () => {
|
||||
runner.addTurn({ turnNumber: turn++, intents: [] });
|
||||
runner.executeNextTick();
|
||||
};
|
||||
});
|
||||
|
||||
test("playerNameViewData is attached only on placement-rebuild ticks", () => {
|
||||
tick(); // 1
|
||||
tick(); // 2
|
||||
game.endSpawnPhase();
|
||||
for (let t = 3; t <= 61; t++) tick();
|
||||
|
||||
// ticks < 3 always rebuild; every 30th tick rebuilds; everything else
|
||||
// omits the record. (The in-tick spawn-end rebuild also sets the flag,
|
||||
// but ending the spawn phase between ticks doesn't exercise it here.)
|
||||
expect(byTick.get(1)!.playerNameViewData).toBeDefined();
|
||||
expect(byTick.get(2)!.playerNameViewData).toBeDefined();
|
||||
expect(byTick.get(4)!.playerNameViewData).toBeUndefined();
|
||||
expect(byTick.get(29)!.playerNameViewData).toBeUndefined();
|
||||
expect(byTick.get(30)!.playerNameViewData).toBeDefined();
|
||||
expect(byTick.get(31)!.playerNameViewData).toBeUndefined();
|
||||
expect(byTick.get(60)!.playerNameViewData).toBeDefined();
|
||||
});
|
||||
|
||||
test("stat churn arrives as packedPlayerUpdates quads on the view data", () => {
|
||||
tick(); // 1
|
||||
tick(); // 2
|
||||
game.endSpawnPhase();
|
||||
tick(); // 3 — flush spawn churn
|
||||
|
||||
const alice = game.player("alice_id");
|
||||
alice.addGold(500n);
|
||||
tick(); // 4
|
||||
const gu = byTick.get(game.ticks())!;
|
||||
const packed = gu.packedPlayerUpdates;
|
||||
expect(packed).toBeDefined();
|
||||
expect(packed!.length % 4).toBe(0);
|
||||
let quad: number[] | undefined;
|
||||
for (let i = 0; i + 3 < packed!.length; i += 4) {
|
||||
if (packed![i] === alice.smallID()) {
|
||||
quad = Array.from(packed!.subarray(i, i + 4));
|
||||
}
|
||||
}
|
||||
expect(quad).toEqual([
|
||||
alice.smallID(),
|
||||
alice.numTilesOwned(),
|
||||
Number(alice.gold()),
|
||||
alice.troops(),
|
||||
]);
|
||||
// And the object channel no longer carries the stat fields: alice must
|
||||
// not appear in this tick's PlayerUpdates for a gold-only change.
|
||||
const playerUpdates = gu.updates[GameUpdateType.Player];
|
||||
expect(playerUpdates.find((u) => u.id === "alice_id")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -72,10 +72,10 @@ describe("Player update diffing (toUpdate)", () => {
|
||||
|
||||
test("primitive changes appear in the diff without unchanged collections", () => {
|
||||
alice.toUpdate();
|
||||
alice.addGold(123n);
|
||||
alice.markTraitor();
|
||||
const diff = alice.toUpdate();
|
||||
expect(diff).not.toBeNull();
|
||||
expect(diff!.gold).toBe(alice.gold());
|
||||
expect(diff!.isTraitor).toBe(true);
|
||||
// Unchanged collection fields must be absent from the diff.
|
||||
expect(diff!.allies).toBeUndefined();
|
||||
expect(diff!.embargoes).toBeUndefined();
|
||||
@@ -83,6 +83,52 @@ describe("Player update diffing (toUpdate)", () => {
|
||||
expect(diff!.alliances).toBeUndefined();
|
||||
});
|
||||
|
||||
test("stat churn (gold/troops/tilesOwned) travels via statsOut, not the diff", () => {
|
||||
const statsOut: number[] = [];
|
||||
alice.toUpdate(statsOut);
|
||||
statsOut.length = 0;
|
||||
|
||||
alice.addGold(123n);
|
||||
const diff = alice.toUpdate(statsOut);
|
||||
// No object diff — gold alone must not put the player on the object
|
||||
// channel (that's the whole point of the packed stats channel).
|
||||
expect(diff).toBeNull();
|
||||
expect(statsOut).toEqual([
|
||||
alice.smallID(),
|
||||
alice.numTilesOwned(),
|
||||
Number(alice.gold()),
|
||||
alice.troops(),
|
||||
]);
|
||||
|
||||
// Nothing changed → no quad, no diff.
|
||||
statsOut.length = 0;
|
||||
expect(alice.toUpdate(statsOut)).toBeNull();
|
||||
expect(statsOut).toEqual([]);
|
||||
|
||||
// A non-stat change produces an object diff but no quad.
|
||||
alice.markTraitor();
|
||||
expect(alice.toUpdate(statsOut)).not.toBeNull();
|
||||
expect(statsOut).toEqual([]);
|
||||
});
|
||||
|
||||
test("first emission carries the stats in the full snapshot, not statsOut", () => {
|
||||
const info = new PlayerInfo(
|
||||
"dora",
|
||||
PlayerType.Human,
|
||||
"dora_client",
|
||||
"dora_id",
|
||||
);
|
||||
game.addPlayer(info);
|
||||
const dora = game.player("dora_id");
|
||||
const statsOut: number[] = [];
|
||||
const full = dora.toUpdate(statsOut);
|
||||
expect(full).not.toBeNull();
|
||||
expect(full!.gold).toBe(dora.gold());
|
||||
expect(full!.troops).toBe(dora.troops());
|
||||
expect(full!.tilesOwned).toBe(dora.numTilesOwned());
|
||||
expect(statsOut).toEqual([]);
|
||||
});
|
||||
|
||||
test("adding and removing an embargo shows up in consecutive diffs", () => {
|
||||
alice.toUpdate();
|
||||
alice.addEmbargo(bob, false);
|
||||
@@ -156,17 +202,33 @@ describe("Player update diffing (toUpdate)", () => {
|
||||
alice.smallID(),
|
||||
);
|
||||
|
||||
// As the attack progresses, troop counts change and must keep flowing
|
||||
// through subsequent diffs.
|
||||
// As the attack progresses, troop counts change — but attack arrays are
|
||||
// NOT resent for troop-only changes. Troops flow as packed
|
||||
// [ownerSmallID, direction, index, troops] quads instead.
|
||||
game.drainPackedAttackUpdates(); // discard quads from earlier ticks
|
||||
const nextUpdates = game.executeNextTick();
|
||||
const nextPlayerUpdates = nextUpdates[
|
||||
GameUpdateType.Player
|
||||
] as PlayerUpdate[];
|
||||
const next = nextPlayerUpdates.find((u) => u.id === "alice_id");
|
||||
expect(next).toBeDefined();
|
||||
expect(
|
||||
next!.outgoingAttacks!.some((a) => a.targetID === bob.smallID()),
|
||||
).toBe(true);
|
||||
if (next !== undefined) {
|
||||
// Alice may appear for other field changes, but not for attack arrays.
|
||||
expect(next.outgoingAttacks).toBeUndefined();
|
||||
}
|
||||
const packed = game.drainPackedAttackUpdates();
|
||||
expect(packed).not.toBeNull();
|
||||
// Find alice's outgoing quads and check one matches her current attack.
|
||||
const aliceQuads: number[][] = [];
|
||||
for (let i = 0; i + 3 < packed!.length; i += 4) {
|
||||
if (packed![i] === alice.smallID() && packed![i + 1] === 0) {
|
||||
aliceQuads.push(Array.from(packed!.subarray(i, i + 4)));
|
||||
}
|
||||
}
|
||||
expect(aliceQuads.length).toBeGreaterThan(0);
|
||||
const aliceAttacks = alice.outgoingAttacks();
|
||||
for (const [, , index, troops] of aliceQuads) {
|
||||
expect(troops).toBe(aliceAttacks[index].troops());
|
||||
}
|
||||
});
|
||||
|
||||
test("in-worker mutation of shared empty collections fails loudly", () => {
|
||||
|
||||
@@ -27,9 +27,11 @@ function withPlayers(
|
||||
) {
|
||||
const gu = makeEmptyGu(tick);
|
||||
gu.updates[GameUpdateType.Player] = players;
|
||||
const nameViewData: NonNullable<typeof gu.playerNameViewData> = {};
|
||||
for (const p of players) {
|
||||
gu.playerNameViewData[p.id] = nameDataMap[p.id] ?? makeNameViewData();
|
||||
nameViewData[p.id] = nameDataMap[p.id] ?? makeNameViewData();
|
||||
}
|
||||
gu.playerNameViewData = nameViewData;
|
||||
return gu;
|
||||
}
|
||||
|
||||
@@ -140,6 +142,288 @@ describe("GameView.update — players", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("GameView.update — packed channels", () => {
|
||||
it("packedPlayerUpdates quads update tilesOwned/gold/troops in place", () => {
|
||||
const game = makeGameView();
|
||||
game.update(
|
||||
withPlayers(1, [
|
||||
makePlayerUpdate({ id: "alice", smallID: 1, troops: 100, gold: 5n }),
|
||||
]),
|
||||
);
|
||||
|
||||
const gu = makeEmptyGu(2);
|
||||
// [smallID, tilesOwned, gold, troops]
|
||||
gu.packedPlayerUpdates = new Float64Array([1, 42, 999, 250]);
|
||||
game.update(gu);
|
||||
|
||||
const alice = game.player("alice");
|
||||
expect(alice.numTilesOwned()).toBe(42);
|
||||
expect(alice.gold()).toBe(999n);
|
||||
expect(alice.troops()).toBe(250);
|
||||
});
|
||||
|
||||
it("packedAttackUpdates patches troop counts by direction and index", () => {
|
||||
const game = makeGameView();
|
||||
game.update(
|
||||
withPlayers(1, [
|
||||
makePlayerUpdate({
|
||||
id: "alice",
|
||||
smallID: 1,
|
||||
outgoingAttacks: [
|
||||
{
|
||||
attackerID: 1,
|
||||
targetID: 2,
|
||||
troops: 500,
|
||||
id: "a1",
|
||||
retreating: false,
|
||||
},
|
||||
{
|
||||
attackerID: 1,
|
||||
targetID: 3,
|
||||
troops: 300,
|
||||
id: "a2",
|
||||
retreating: false,
|
||||
},
|
||||
],
|
||||
incomingAttacks: [
|
||||
{
|
||||
attackerID: 4,
|
||||
targetID: 1,
|
||||
troops: 80,
|
||||
id: "a3",
|
||||
retreating: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const gu = makeEmptyGu(2);
|
||||
// [ownerSmallID, direction (0=outgoing, 1=incoming), index, troops]
|
||||
gu.packedAttackUpdates = new Float64Array([1, 0, 1, 290, 1, 1, 0, 75]);
|
||||
game.update(gu);
|
||||
|
||||
const alice = game.player("alice");
|
||||
expect(alice.outgoingAttacks().map((a) => a.troops)).toEqual([500, 290]);
|
||||
expect(alice.incomingAttacks().map((a) => a.troops)).toEqual([75]);
|
||||
});
|
||||
|
||||
it("quads for unknown smallIDs and out-of-range attack indexes are ignored", () => {
|
||||
const game = makeGameView();
|
||||
game.update(
|
||||
withPlayers(1, [makePlayerUpdate({ id: "alice", smallID: 1 })]),
|
||||
);
|
||||
const gu = makeEmptyGu(2);
|
||||
gu.packedPlayerUpdates = new Float64Array([99, 1, 1, 1]);
|
||||
gu.packedAttackUpdates = new Float64Array([1, 0, 5, 123, 99, 1, 0, 7]);
|
||||
expect(() => game.update(gu)).not.toThrow();
|
||||
});
|
||||
|
||||
it("same-tick array resend and patch on different directions both apply", () => {
|
||||
const game = makeGameView();
|
||||
game.update(
|
||||
withPlayers(1, [
|
||||
makePlayerUpdate({
|
||||
id: "alice",
|
||||
smallID: 1,
|
||||
outgoingAttacks: [
|
||||
{
|
||||
attackerID: 1,
|
||||
targetID: 2,
|
||||
troops: 500,
|
||||
id: "a1",
|
||||
retreating: false,
|
||||
},
|
||||
],
|
||||
incomingAttacks: [
|
||||
{
|
||||
attackerID: 4,
|
||||
targetID: 1,
|
||||
troops: 80,
|
||||
id: "a3",
|
||||
retreating: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
// Outgoing membership changed → full array resent with fresh troops;
|
||||
// incoming membership unchanged → troops arrive as a patch. The patch
|
||||
// must land on the long-lived incoming array and not interfere with the
|
||||
// resent outgoing array (a tick resends or patches each array, never
|
||||
// both — but different directions can mix on one tick).
|
||||
const gu = makeEmptyGu(2);
|
||||
gu.updates[GameUpdateType.Player] = [
|
||||
{
|
||||
type: GameUpdateType.Player,
|
||||
id: "alice",
|
||||
outgoingAttacks: [
|
||||
{
|
||||
attackerID: 1,
|
||||
targetID: 2,
|
||||
troops: 450,
|
||||
id: "a1",
|
||||
retreating: false,
|
||||
},
|
||||
{
|
||||
attackerID: 1,
|
||||
targetID: 3,
|
||||
troops: 100,
|
||||
id: "a2",
|
||||
retreating: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
gu.packedAttackUpdates = new Float64Array([1, 1, 0, 75]);
|
||||
game.update(gu);
|
||||
|
||||
const alice = game.player("alice");
|
||||
expect(alice.outgoingAttacks().map((a) => a.troops)).toEqual([450, 100]);
|
||||
expect(alice.incomingAttacks().map((a) => a.troops)).toEqual([75]);
|
||||
});
|
||||
|
||||
it("gold survives the float64 quad exactly, including > 2^32 values", () => {
|
||||
const game = makeGameView();
|
||||
game.update(
|
||||
withPlayers(1, [makePlayerUpdate({ id: "alice", smallID: 1 })]),
|
||||
);
|
||||
const bigGold = 2 ** 52 + 11; // integer, exactly representable in f64
|
||||
const gu = makeEmptyGu(2);
|
||||
gu.packedPlayerUpdates = new Float64Array([1, 0, bigGold, 0]);
|
||||
game.update(gu);
|
||||
expect(game.player("alice").gold()).toBe(BigInt(bigGold));
|
||||
});
|
||||
|
||||
it("nameData persists across ticks without a playerNameViewData record", () => {
|
||||
const game = makeGameView();
|
||||
game.update(
|
||||
withPlayers(1, [makePlayerUpdate({ id: "alice", smallID: 1 })], {
|
||||
alice: { x: 7, y: 9, size: 3 },
|
||||
}),
|
||||
);
|
||||
expect(game.frameData().names.get("alice")).toMatchObject({ x: 7, y: 9 });
|
||||
|
||||
// Tick without a record (worker omits it between placement rebuilds) —
|
||||
// even with a player update present, the old placement must survive.
|
||||
const gu = makeEmptyGu(2);
|
||||
gu.updates[GameUpdateType.Player] = [
|
||||
makePlayerUpdate({ id: "alice", smallID: 1 }),
|
||||
];
|
||||
game.update(gu);
|
||||
expect(game.frameData().names.get("alice")).toMatchObject({ x: 7, y: 9 });
|
||||
|
||||
// A new record updates the placement (alice is alive).
|
||||
const gu3 = makeEmptyGu(3);
|
||||
gu3.playerNameViewData = { alice: { x: 11, y: 13, size: 4 } };
|
||||
game.update(gu3);
|
||||
expect(game.frameData().names.get("alice")).toMatchObject({ x: 11, y: 13 });
|
||||
});
|
||||
|
||||
it("dead players keep their last name placement (freeze at death)", () => {
|
||||
const game = makeGameView();
|
||||
game.update(
|
||||
withPlayers(1, [makePlayerUpdate({ id: "alice", smallID: 1 })], {
|
||||
alice: { x: 7, y: 9, size: 3 },
|
||||
}),
|
||||
);
|
||||
|
||||
// Alice dies.
|
||||
const gu2 = makeEmptyGu(2);
|
||||
gu2.updates[GameUpdateType.Player] = [
|
||||
makePlayerUpdate({ id: "alice", smallID: 1, isAlive: false }),
|
||||
];
|
||||
game.update(gu2);
|
||||
|
||||
// A later record must not move her name.
|
||||
const gu3 = makeEmptyGu(3);
|
||||
gu3.playerNameViewData = { alice: { x: 0, y: 0, size: 0 } };
|
||||
game.update(gu3);
|
||||
expect(game.frameData().names.get("alice")).toMatchObject({ x: 7, y: 9 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("GameView.update — derived-data dirty flags", () => {
|
||||
function twoPlayers() {
|
||||
const game = makeGameView();
|
||||
game.update(
|
||||
withPlayers(1, [
|
||||
makePlayerUpdate({ id: "alice", smallID: 1 }),
|
||||
makePlayerUpdate({ id: "bob", smallID: 2 }),
|
||||
]),
|
||||
);
|
||||
return game;
|
||||
}
|
||||
|
||||
it("relationMatrix recomputes when allies arrive on a partial update", () => {
|
||||
const game = twoPlayers();
|
||||
const size = game.frameData().relationSize;
|
||||
expect(game.frameData().relationMatrix[1 * size + 2]).toBe(0); // neutral
|
||||
|
||||
const gu = makeEmptyGu(2);
|
||||
gu.updates[GameUpdateType.Player] = [
|
||||
{ type: GameUpdateType.Player, id: "alice", allies: [2] },
|
||||
];
|
||||
game.update(gu);
|
||||
// friendly, both directions
|
||||
expect(game.frameData().relationMatrix[1 * size + 2]).toBe(1);
|
||||
expect(game.frameData().relationMatrix[2 * size + 1]).toBe(1);
|
||||
});
|
||||
|
||||
it("relationMatrix recomputes when embargoes arrive on a partial update", () => {
|
||||
const game = twoPlayers();
|
||||
const size = game.frameData().relationSize;
|
||||
|
||||
const gu = makeEmptyGu(2);
|
||||
gu.updates[GameUpdateType.Player] = [
|
||||
{
|
||||
type: GameUpdateType.Player,
|
||||
id: "alice",
|
||||
embargoes: new Set(["bob"]),
|
||||
},
|
||||
];
|
||||
game.update(gu);
|
||||
expect(game.frameData().relationMatrix[1 * size + 2]).toBe(2); // embargo
|
||||
});
|
||||
|
||||
it("allianceClusters keep identity on clean ticks and recompute on allies change", () => {
|
||||
const game = twoPlayers();
|
||||
const before = game.frameData().allianceClusters;
|
||||
expect(before.get(1)).not.toBe(before.get(2)); // separate clusters
|
||||
|
||||
// Clean tick: no relation inputs changed → cached object, untouched.
|
||||
game.update(makeEmptyGu(2));
|
||||
expect(game.frameData().allianceClusters).toBe(before);
|
||||
|
||||
// Alliance forms → recomputed: alice and bob share a cluster root.
|
||||
const gu = makeEmptyGu(3);
|
||||
gu.updates[GameUpdateType.Player] = [
|
||||
{ type: GameUpdateType.Player, id: "alice", allies: [2] },
|
||||
{ type: GameUpdateType.Player, id: "bob", allies: [1] },
|
||||
];
|
||||
game.update(gu);
|
||||
const after = game.frameData().allianceClusters;
|
||||
expect(after).not.toBe(before);
|
||||
expect(after.get(1)).toBe(after.get(2));
|
||||
});
|
||||
|
||||
it("names map keeps identity and content on ticks without a record", () => {
|
||||
const game = makeGameView();
|
||||
game.update(
|
||||
withPlayers(1, [makePlayerUpdate({ id: "alice", smallID: 1 })], {
|
||||
alice: { x: 7, y: 9, size: 3 },
|
||||
}),
|
||||
);
|
||||
const names = game.frameData().names;
|
||||
const entry = names.get("alice");
|
||||
|
||||
game.update(makeEmptyGu(2));
|
||||
expect(game.frameData().names).toBe(names); // long-lived map
|
||||
expect(game.frameData().names.get("alice")).toBe(entry); // not rebuilt
|
||||
});
|
||||
});
|
||||
|
||||
describe("GameView.update — units", () => {
|
||||
it("creates a UnitView on first sighting and reuses it after", () => {
|
||||
const game = makeGameView();
|
||||
|
||||
@@ -424,6 +424,12 @@ async function main(): Promise<void> {
|
||||
if (gu.packedMotionPlans) {
|
||||
transfers.push(gu.packedMotionPlans.buffer);
|
||||
}
|
||||
if (gu.packedPlayerUpdates) {
|
||||
transfers.push(gu.packedPlayerUpdates.buffer);
|
||||
}
|
||||
if (gu.packedAttackUpdates) {
|
||||
transfers.push(gu.packedAttackUpdates.buffer);
|
||||
}
|
||||
start = performance.now();
|
||||
const cloned = structuredClone(gu, { transfer: transfers });
|
||||
const cloneMs = performance.now() - start;
|
||||
|
||||
@@ -204,7 +204,9 @@ export function makeEmptyGu(
|
||||
tick,
|
||||
updates,
|
||||
packedTileUpdates: new Uint32Array(0),
|
||||
playerNameViewData: {},
|
||||
// playerNameViewData deliberately absent — production omits it on every
|
||||
// tick between placement rebuilds, so the stub default must exercise the
|
||||
// absent path. Tests that need placements set it explicitly.
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user