-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathClientGameRunner.ts
More file actions
1285 lines (1160 loc) · 38.2 KB
/
Copy pathClientGameRunner.ts
File metadata and controls
1285 lines (1160 loc) · 38.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Config } from "src/core/configuration/Config";
import { translateText } from "../client/Utils";
import { EventBus } from "../core/EventBus";
import {
ClientID,
GameID,
GameRecord,
GameStartInfo,
LobbyInfoEvent,
PlayerCosmeticRefs,
PlayerRecord,
ServerMessage,
} from "../core/Schemas";
import { createPartialGameRecord, findClosestBy, replacer } from "../core/Util";
import {
BuildableUnit,
PlayerType,
Structures,
UnitType,
} from "../core/game/Game";
import { TileRef } from "../core/game/GameMap";
import { GameMapLoader } from "../core/game/GameMapLoader";
import {
ErrorUpdate,
GameUpdateType,
GameUpdateViewData,
HashUpdate,
WinUpdate,
} from "../core/game/GameUpdates";
import { GameView, PlayerView } from "../core/game/GameView";
import { loadTerrainMap, TerrainMapData } from "../core/game/TerrainMapLoader";
import {
DARK_MODE_KEY,
GRAPHICS_KEY,
USER_SETTINGS_CHANGED_EVENT,
UserSettings,
} from "../core/game/UserSettings";
import { WorkerClient } from "../core/worker/WorkerClient";
import { getPersistentID } from "./Auth";
import {
AutoUpgradeEvent,
DoBoatAttackEvent,
DoBreakAllianceEvent,
DoGroundAttackEvent,
DoRequestAllianceEvent,
DoRetaliateAttackEvent,
InputHandler,
MouseMoveEvent,
MouseUpEvent,
TickMetricsEvent,
ToggleRenderDebugGuiEvent,
} from "./InputHandler";
import { endGame, startGame, startTime } from "./LocalPersistantStats";
import { terrainMapFileLoader } from "./TerrainMapFileLoader";
import { GoToPlayerEvent } from "./TransformHandler";
import {
MoveWarshipIntentEvent,
SendAllianceExtensionIntentEvent,
SendAllianceRequestIntentEvent,
SendAttackIntentEvent,
SendBoatAttackIntentEvent,
SendBreakAllianceIntentEvent,
SendHashEvent,
SendSpawnIntentEvent,
SendUpgradeStructureIntentEvent,
Transport,
} from "./Transport";
import { createCanvas } from "./Utils";
import { WebGLFrameBuilder } from "./WebGLFrameBuilder";
import { createRenderer, GameRenderer } from "./hud/GameRenderer";
import {
applyDarkModeOverride,
applyGraphicsOverrides,
createDebugGui,
createRenderSettings,
deepAssign,
GameView as WebGLGameView,
} from "./render/gl";
import { ALL_UNIT_TYPES, UnitState } from "./render/types";
import { SoundManager } from "./sound/SoundManager";
import { themeProvider } from "./theme/ThemeProvider";
import { getEffectiveDpr } from "./utilities/Dpr";
export interface LobbyConfig {
cosmetics: PlayerCosmeticRefs;
playerName: string;
playerClanTag: string | null;
playerRole: string | null;
gameID: GameID;
turnstileToken: string | null;
// GameStartInfo only exists when playing a singleplayer game.
gameStartInfo?: GameStartInfo;
// GameRecord exists when replaying an archived game.
gameRecord?: GameRecord;
}
export interface JoinLobbyResult {
stop: (force?: boolean) => boolean;
prestart: Promise<void>;
join: Promise<void>;
}
export function joinLobby(
eventBus: EventBus,
lobbyConfig: LobbyConfig,
): JoinLobbyResult {
// Mutable clientID state — assigned by server (multiplayer) or derived from gameStartInfo (singleplayer)
let clientID: ClientID | undefined;
let resolvePrestart: () => void;
let resolveJoin: () => void;
const prestartPromise = new Promise<void>((r) => (resolvePrestart = r));
const joinPromise = new Promise<void>((r) => (resolveJoin = r));
console.log(`joining lobby: gameID: ${lobbyConfig.gameID}`);
const userSettings: UserSettings = new UserSettings();
themeProvider.reset(); // fresh colour allocators for this game
startGame(lobbyConfig.gameID, lobbyConfig.gameStartInfo?.config ?? {});
const transport = new Transport(lobbyConfig, eventBus);
let currentGameRunner: ClientGameRunner | null = null;
const onconnect = () => {
// Always send join - server will detect reconnection via persistentID
console.log(`Joining game lobby ${lobbyConfig.gameID}`);
transport.joinGame();
};
let terrainLoad: Promise<TerrainMapData> | null = null;
const onmessage = (message: ServerMessage) => {
if (message.type === "lobby_info") {
// Server tells us our assigned clientID
clientID = message.myClientID;
eventBus.emit(new LobbyInfoEvent(message.lobby, message.myClientID));
return;
}
if (message.type === "prestart") {
console.log(
`lobby: game prestarting: ${JSON.stringify(message, replacer)}`,
);
terrainLoad = loadTerrainMap(
message.gameMap,
message.gameMapSize,
terrainMapFileLoader,
);
resolvePrestart();
}
if (message.type === "start") {
// Trigger prestart for singleplayer games
resolvePrestart();
console.log(
`lobby: game started: ${JSON.stringify(message, replacer, 2)}`,
);
// Server tells us our assigned clientID (also sent on start for late joins)
clientID = message.myClientID;
resolveJoin();
// For multiplayer games, GameStartInfo is not known until game starts.
lobbyConfig.gameStartInfo = message.gameStartInfo;
createClientGame(
lobbyConfig,
clientID,
eventBus,
transport,
userSettings,
terrainLoad,
terrainMapFileLoader,
)
.then((r) => {
currentGameRunner = r;
r.start();
})
.catch((e) => {
console.error("error creating client game", e);
currentGameRunner = null;
const startingModal = document.querySelector(
"game-starting-modal",
) as HTMLElement;
if (startingModal) {
startingModal.classList.add("hidden");
}
showErrorModal(
e.message,
e.stack,
lobbyConfig.gameID,
clientID,
true,
false,
"error_modal.connection_error",
);
});
}
if (message.type === "error") {
if (message.error === "full-lobby") {
document.dispatchEvent(
new CustomEvent("leave-lobby", {
detail: { lobby: lobbyConfig.gameID, cause: "full-lobby" },
bubbles: true,
composed: true,
}),
);
} else if (message.error === "kick_reason.host_left") {
alert(translateText("kick_reason.host_left"));
document.dispatchEvent(
new CustomEvent("leave-lobby", {
detail: { lobby: lobbyConfig.gameID, cause: "host-left" },
bubbles: true,
composed: true,
}),
);
} else {
showErrorModal(
message.error,
message.message,
lobbyConfig.gameID,
clientID,
true,
false,
"error_modal.connection_error",
);
}
}
};
transport.connect(onconnect, onmessage);
return {
stop: (force: boolean = false) => {
if (!force && currentGameRunner?.shouldPreventWindowClose()) {
console.log("Player is active, prevent leaving game");
return false;
}
console.log("leaving game");
if (currentGameRunner) {
currentGameRunner.stop();
currentGameRunner = null;
} else {
transport.leaveGame();
}
return true;
},
prestart: prestartPromise,
join: joinPromise,
};
}
// Build the WebGL view + its glCanvas. Must run before createRenderer so the
// controllers can be wired directly to the view.
function createWebGLView(
terrainMap: TerrainMapData,
config: Config,
): {
view: WebGLGameView;
glCanvas: HTMLCanvasElement;
cachedWebGLFrameCallback: { current: FrameRequestCallback | null };
} {
const gameMap = terrainMap.gameMap;
const mapWidth = gameMap.width();
const mapHeight = gameMap.height();
const terrainBytes = new Uint8Array(mapWidth * mapHeight);
for (let y = 0; y < mapHeight; y++) {
for (let x = 0; x < mapWidth; x++) {
terrainBytes[y * mapWidth + x] = gameMap.terrainByte(gameMap.ref(x, y));
}
}
const glCanvas = createCanvas();
glCanvas.id = "webgl-debug-canvas";
glCanvas.style.pointerEvents = "none";
document.body.insertBefore(glCanvas, document.body.firstChild);
// Capture the WebGL renderer's animation-frame callback rather than letting
// it run its own RAF loop. Two independent RAF loops race: when the user
// pans, the WebGL renderer can draw with one-frame-stale camera state
// because its RAF fires before canvas2D's RAF (which would have synced the
// camera). Driving WebGL's draw synchronously from canvas2D's onPreRender
// hook locks them to the same frame.
const cachedWebGLFrameCallback: { current: FrameRequestCallback | null } = {
current: null,
};
const captureRaf = (cb: FrameRequestCallback): number => {
cachedWebGLFrameCallback.current = cb;
return 0;
};
const captureCaf = (_id: number): void => {
cachedWebGLFrameCallback.current = null;
};
const palette = new Float32Array(4096 * 2 * 4);
const view = new WebGLGameView(
glCanvas,
{
mapWidth,
mapHeight,
unitTypes: [...ALL_UNIT_TYPES],
players: [],
// Pre-allocate renderer textures for up to 1024 players. We add players
// dynamically via view.addPlayers() as they come in from the simulation,
// but the NamePass / palette / relation matrix all need a static upper
// bound at construction time.
maxPlayers: 1024,
},
terrainBytes,
palette,
config,
captureRaf,
captureCaf,
);
(window as unknown as { __webglView?: unknown }).__webglView = view;
return { view, glCanvas, cachedWebGLFrameCallback };
}
function mountWebGLFrameLoop(
terrainMap: TerrainMapData,
view: WebGLGameView,
glCanvas: HTMLCanvasElement,
cachedWebGLFrameCallback: { current: FrameRequestCallback | null },
transformHandler: import("./TransformHandler").TransformHandler,
gameView: GameView,
eventBus: EventBus,
): { builder: WebGLFrameBuilder } {
const gameMap = terrainMap.gameMap;
const mapWidth = gameMap.width();
const mapHeight = gameMap.height();
// Cache canvas dimensions to avoid forced reflows every frame. Reading
// clientWidth/clientHeight flushes pending layout — at 60fps that's a
// measurable cost. Only update on resize events from the observer.
let cachedCanvasW = glCanvas.clientWidth;
let cachedCanvasH = glCanvas.clientHeight;
const resizeObs = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
if (width > 0 && height > 0) {
cachedCanvasW = width;
cachedCanvasH = height;
}
}
});
resizeObs.observe(glCanvas);
const syncCamera = (): void => {
const scale = transformHandler.scale;
const dpr = getEffectiveDpr();
const centerX =
transformHandler.offsetX +
mapWidth / 2 +
(cachedCanvasW - mapWidth) / (2 * scale);
const centerY =
transformHandler.offsetY +
mapHeight / 2 +
(cachedCanvasH - mapHeight) / (2 * scale);
view.setCameraState(centerX, centerY, scale * dpr);
// Invoke the WebGL renderer's frame callback synchronously, with the just-
// updated camera state. The callback re-arms itself via captureRaf, so
// we'll get a fresh callback ready for the next canvas2D frame.
const cb = cachedWebGLFrameCallback.current;
cachedWebGLFrameCallback.current = null;
cb?.(performance.now());
};
// Move-target chevrons: when the player issues a warship move, show the
// animated chevron pass at the target tile. The renderer needs the target's
// tile x/y and the warship's owner smallID (so the chevrons use the right
// color).
eventBus.on(MoveWarshipIntentEvent, (e) => {
const tile = e.tile;
const tx = gameView.x(tile);
const ty = gameView.y(tile);
// Resolve owner via the first unit in the move set.
const firstUnit = gameView.unit(e.unitIds[0]);
if (firstUnit === undefined) return;
view.showMoveIndicator(tx, ty, firstUnit.owner().smallID());
});
// Self-driving RAF: syncCamera reads the latest camera state from
// TransformHandler, pushes it to WebGL, and synchronously invokes the
// renderer's captured frame callback (which draws). One RAF = one
// synchronized camera-update + WebGL render.
let lastRafTime = performance.now();
const driveFrame = (now: number): void => {
const dt = now - lastRafTime;
lastRafTime = now;
if (dt > 20) console.log(`[rAF gap] ${dt.toFixed(1)}ms`);
const cpuStart = performance.now();
syncCamera();
const cpuMs = performance.now() - cpuStart;
if (cpuMs > 10) console.log(`[CPU frame] ${cpuMs.toFixed(1)}ms`);
requestAnimationFrame(driveFrame);
};
requestAnimationFrame(driveFrame);
const builder = new WebGLFrameBuilder(view);
// When context is lost and restored, WebGL loses all textures and geometry.
// Force a full re-upload of the simulation state.
view.on("contextrestored", () => {
builder.clearCaches();
// Full upload of terrain, territory & trail state
const mapSize = mapWidth * mapHeight;
const allRefs = new Array(mapSize);
const allTerrain = new Uint8Array(mapSize);
for (let i = 0; i < mapSize; i++) {
allRefs[i] = i;
allTerrain[i] = gameView.terrainByte(i);
}
view.applyTerrainDelta(allRefs, allTerrain);
const frameData = gameView.frameData();
view.uploadTileAndTrailState(frameData.tileState, frameData.trailState);
// Structures and railroads normally skip GPU upload unless marked dirty, now force
view.updateStructures(frameData.units as Map<number, UnitState>);
view.uploadRailroadState(frameData.railroadState);
builder.update(gameView);
});
return { builder };
}
async function createClientGame(
lobbyConfig: LobbyConfig,
clientID: ClientID | undefined,
eventBus: EventBus,
transport: Transport,
userSettings: UserSettings,
terrainLoad: Promise<TerrainMapData> | null,
mapLoader: GameMapLoader,
): Promise<ClientGameRunner> {
if (lobbyConfig.gameStartInfo === undefined) {
throw new Error("missing gameStartInfo");
}
const config = new Config(
lobbyConfig.gameStartInfo.config,
userSettings,
lobbyConfig.gameRecord !== undefined,
);
let gameMap: TerrainMapData;
if (terrainLoad) {
gameMap = await terrainLoad;
} else {
gameMap = await loadTerrainMap(
lobbyConfig.gameStartInfo.config.gameMap,
lobbyConfig.gameStartInfo.config.gameMapSize,
mapLoader,
);
}
const worker = new WorkerClient(lobbyConfig.gameStartInfo, clientID);
await worker.initialize();
const gameView = new GameView(
worker,
config,
gameMap,
clientID,
lobbyConfig.playerName,
lobbyConfig.playerClanTag,
lobbyConfig.gameStartInfo.gameID,
lobbyConfig.gameStartInfo.players,
);
// Transparent fullscreen overlay used purely as the pointer-event /
// bounding-rect target for InputHandler + TransformHandler. The actual
// map drawing happens on the WebGL canvas created in createWebGLView.
const inputOverlay = document.createElement("div");
inputOverlay.id = "game-input-overlay";
inputOverlay.style.position = "fixed";
inputOverlay.style.left = "0";
inputOverlay.style.top = "0";
inputOverlay.style.width = "100%";
inputOverlay.style.height = "100%";
inputOverlay.style.touchAction = "none";
document.body.appendChild(inputOverlay);
const soundManager = new SoundManager(eventBus, userSettings);
try {
const { view, glCanvas, cachedWebGLFrameCallback } = createWebGLView(
gameMap,
config,
);
view.setShowPatterns(userSettings.territoryPatterns());
globalThis.addEventListener(
`${USER_SETTINGS_CHANGED_EVENT}:settings.territoryPatterns`,
(e) => view.setShowPatterns((e as CustomEvent<string>).detail === "true"),
);
const graphicsListenerAbort = new AbortController();
const regenerateRenderSettings = (): void => {
const live = view.getSettings();
deepAssign(live, createRenderSettings());
applyGraphicsOverrides(live, userSettings.graphicsOverrides());
applyDarkModeOverride(live, userSettings.darkMode());
};
regenerateRenderSettings();
globalThis.addEventListener(
`${USER_SETTINGS_CHANGED_EVENT}:${GRAPHICS_KEY}`,
regenerateRenderSettings,
{ signal: graphicsListenerAbort.signal },
);
globalThis.addEventListener(
`${USER_SETTINGS_CHANGED_EVENT}:${DARK_MODE_KEY}`,
regenerateRenderSettings,
{ signal: graphicsListenerAbort.signal },
);
let debugGui: ReturnType<typeof createDebugGui> | null = null;
eventBus.on(ToggleRenderDebugGuiEvent, () => {
if (debugGui === null) {
debugGui = createDebugGui(view.getSettings());
debugGui.open();
} else {
debugGui.destroy();
debugGui = null;
}
});
const gameRenderer = createRenderer(
inputOverlay,
gameView,
eventBus,
lobbyConfig.playerRole,
view,
);
const { builder: webglBuilder } = mountWebGLFrameLoop(
gameMap,
view,
glCanvas,
cachedWebGLFrameCallback,
gameRenderer.transformHandler,
gameView,
eventBus,
);
console.log(
`creating private game got difficulty: ${lobbyConfig.gameStartInfo.config.difficulty}`,
);
return new ClientGameRunner(
lobbyConfig,
clientID,
eventBus,
gameRenderer,
new InputHandler(gameView, gameRenderer.uiState, inputOverlay, eventBus),
transport,
worker,
gameView,
soundManager,
userSettings,
webglBuilder,
graphicsListenerAbort,
);
} catch (err) {
soundManager.dispose();
throw err;
}
}
export class ClientGameRunner {
private myPlayer: PlayerView | null = null;
private isActive = false;
private turnsSeen = 0;
private lastMousePosition: { x: number; y: number } | null = null;
private lastMessageTime: number = 0;
private connectionCheckInterval: NodeJS.Timeout | null = null;
private goToPlayerTimeout: NodeJS.Timeout | null = null;
private lastTickReceiveTime: number = 0;
private currentTickDelay: number | undefined = undefined;
constructor(
private lobby: LobbyConfig,
private clientID: ClientID | undefined,
private eventBus: EventBus,
private renderer: GameRenderer,
private input: InputHandler,
private transport: Transport,
private worker: WorkerClient,
private gameView: GameView,
private soundManager: SoundManager,
private userSettings: UserSettings,
private webglBuilder: WebGLFrameBuilder | null = null,
private graphicsListenerAbort: AbortController | null = null,
) {
this.lastMessageTime = Date.now();
}
/**
* Determines whether window closing should be prevented.
*
* Used to show a confirmation dialog when the user attempts to close
* the window or navigate away during an active game session.
*
* @returns {boolean} `true` if the window close should be prevented
* (when the player is alive in the game), `false` otherwise
* (when the player is not alive or doesn't exist)
*/
public shouldPreventWindowClose(): boolean {
// Show confirmation dialog if player is alive in the game
return !!this.myPlayer?.isAlive();
}
private async saveGame(update: WinUpdate) {
if (!this.clientID) {
return;
}
const players: PlayerRecord[] = [
{
persistentID: getPersistentID(),
username: this.lobby.playerName,
clanTag: this.lobby.playerClanTag ?? null,
clientID: this.clientID,
stats: update.allPlayersStats[this.clientID],
},
];
if (this.lobby.gameStartInfo === undefined) {
throw new Error("missing gameStartInfo");
}
const record = createPartialGameRecord(
this.lobby.gameStartInfo.gameID,
this.lobby.gameStartInfo.config,
players,
// Not saving turns locally
[],
startTime(),
Date.now(),
update.winner,
this.lobby.gameStartInfo.lobbyCreatedAt,
this.lobby.gameStartInfo.visibleAt,
);
endGame(record);
}
public start() {
this.soundManager.playBackgroundMusic();
console.log("starting client game");
this.isActive = true;
this.lastMessageTime = Date.now();
setTimeout(() => {
this.connectionCheckInterval = setInterval(
() => this.onConnectionCheck(),
1000,
);
}, 20000);
this.eventBus.on(MouseUpEvent, this.inputEvent.bind(this));
this.eventBus.on(MouseMoveEvent, this.onMouseMove.bind(this));
this.eventBus.on(AutoUpgradeEvent, this.autoUpgradeEvent.bind(this));
this.eventBus.on(
DoBoatAttackEvent,
this.doBoatAttackUnderCursor.bind(this),
);
this.eventBus.on(
DoGroundAttackEvent,
this.doGroundAttackUnderCursor.bind(this),
);
this.eventBus.on(
DoRetaliateAttackEvent,
this.doRetaliateAttackMostRecent.bind(this),
);
this.eventBus.on(
DoRequestAllianceEvent,
this.doRequestAllianceUnderCursor.bind(this),
);
this.eventBus.on(
DoBreakAllianceEvent,
this.doBreakAllianceUnderCursor.bind(this),
);
this.renderer.initialize();
this.input.initialize();
this.worker.start((gu: GameUpdateViewData | ErrorUpdate) => {
if (this.lobby.gameStartInfo === undefined) {
throw new Error("missing gameStartInfo");
}
if ("errMsg" in gu) {
showErrorModal(
gu.errMsg,
gu.stack ?? "missing",
this.lobby.gameStartInfo.gameID,
this.clientID,
);
console.error(gu.stack);
this.stop();
return;
}
this.transport.turnComplete();
gu.updates[GameUpdateType.Hash].forEach((hu: HashUpdate) => {
this.eventBus.emit(new SendHashEvent(hu.tick, hu.hash));
});
this.gameView.update(gu);
this.webglBuilder?.update(this.gameView);
this.renderer.tick();
// Emit tick metrics event for performance overlay
this.eventBus.emit(
new TickMetricsEvent(gu.tickExecutionDuration, this.currentTickDelay),
);
// Reset tick delay for next measurement
this.currentTickDelay = undefined;
if (gu.updates[GameUpdateType.Win].length > 0) {
this.saveGame(gu.updates[GameUpdateType.Win][0]);
}
});
const onconnect = () => {
console.log("Connected to game server!");
this.transport.rejoinGame(this.turnsSeen);
};
let hasGoneToPlayer = false;
const onmessage = (message: ServerMessage) => {
this.lastMessageTime = Date.now();
if (message.type === "start") {
console.log("starting game! in client game runner");
if (this.gameView.config().isRandomSpawn()) {
const goToPlayer = () => {
const myPlayer = this.gameView.myPlayer();
if (this.gameView.inSpawnPhase() && !myPlayer?.hasSpawned()) {
this.goToPlayerTimeout = setTimeout(goToPlayer, 1000);
return;
}
if (!myPlayer) {
return;
}
if (!this.gameView.inSpawnPhase() && !myPlayer.hasSpawned()) {
showErrorModal(
"spawn_failed",
translateText("error_modal.spawn_failed.description"),
this.lobby.gameID,
this.clientID,
true,
false,
translateText("error_modal.spawn_failed.title"),
);
return;
}
this.eventBus.emit(new GoToPlayerEvent(myPlayer, 10));
};
goToPlayer();
}
for (const turn of message.turns) {
if (turn.turnNumber < this.turnsSeen) {
continue;
}
while (turn.turnNumber - 1 > this.turnsSeen) {
this.worker.sendTurn({
turnNumber: this.turnsSeen,
intents: [],
});
this.turnsSeen++;
}
this.worker.sendTurn(turn);
this.turnsSeen++;
}
}
if (message.type === "desync") {
if (this.lobby.gameStartInfo === undefined) {
throw new Error("missing gameStartInfo");
}
showErrorModal(
`desync from server: ${JSON.stringify(message)}`,
"",
this.lobby.gameStartInfo.gameID,
this.clientID,
true,
false,
"error_modal.desync_notice",
);
}
if (message.type === "error") {
showErrorModal(
message.error,
message.message,
this.lobby.gameID,
this.clientID,
true,
false,
"error_modal.connection_error",
);
}
if (message.type === "turn") {
if (
!this.gameView.inSpawnPhase() &&
!hasGoneToPlayer &&
this.gameView.myPlayer() &&
this.userSettings.goToPlayer()
) {
hasGoneToPlayer = true;
this.eventBus.emit(new GoToPlayerEvent(this.gameView.myPlayer()!, 8));
}
// Track when we receive the turn to calculate delay
const now = Date.now();
if (this.lastTickReceiveTime > 0) {
// Calculate delay between receiving turn messages
this.currentTickDelay = now - this.lastTickReceiveTime;
}
this.lastTickReceiveTime = now;
if (this.turnsSeen !== message.turn.turnNumber) {
console.error(
`got wrong turn have turns ${this.turnsSeen}, received turn ${message.turn.turnNumber}`,
);
} else {
this.worker.sendTurn(
// Filter out pause intents in replays
this.gameView.config().isReplay()
? {
...message.turn,
intents: message.turn.intents.filter(
(i) => i.type !== "toggle_pause",
),
}
: message.turn,
);
this.turnsSeen++;
}
}
};
this.transport.updateCallback(onconnect, onmessage);
console.log("sending join game");
// Rejoin game from the start so we don't miss any turns.
this.transport.rejoinGame(0);
}
public stop() {
this.soundManager.dispose();
this.graphicsListenerAbort?.abort();
if (!this.isActive) return;
this.isActive = false;
this.worker.cleanup();
this.transport.leaveGame();
if (this.connectionCheckInterval) {
clearInterval(this.connectionCheckInterval);
this.connectionCheckInterval = null;
}
if (this.goToPlayerTimeout) {
clearTimeout(this.goToPlayerTimeout);
this.goToPlayerTimeout = null;
}
}
private inputEvent(event: MouseUpEvent) {
if (!this.isActive || this.renderer.uiState.ghostStructure !== null) {
return;
}
const cell = this.renderer.transformHandler.screenToWorldCoordinates(
event.x,
event.y,
);
if (!this.gameView.isValidCoord(cell.x, cell.y)) {
return;
}
console.log(`clicked cell ${cell}`);
const tile = this.gameView.ref(cell.x, cell.y);
if (
this.gameView.isLand(tile) &&
!this.gameView.hasOwner(tile) &&
this.gameView.inSpawnPhase() &&
!this.gameView.config().isRandomSpawn()
) {
this.eventBus.emit(new SendSpawnIntentEvent(tile));
return;
}
if (this.gameView.inSpawnPhase()) {
return;
}
if (this.myPlayer === null) {
if (!this.clientID) return;
const myPlayer = this.gameView.playerByClientID(this.clientID);
if (myPlayer === null) return;
this.myPlayer = myPlayer;
}
this.myPlayer.actions(tile, [UnitType.TransportShip]).then((actions) => {
if (actions.canAttack) {
this.eventBus.emit(
new SendAttackIntentEvent(
this.gameView.owner(tile).id(),
this.myPlayer!.troops() * this.renderer.uiState.attackRatio,
),
);
} else if (this.canAutoBoat(actions.buildableUnits, tile)) {
this.sendBoatAttackIntent(tile);
}
});
}
private autoUpgradeEvent(event: AutoUpgradeEvent) {
if (!this.isActive) {
return;
}
const cell = this.renderer.transformHandler.screenToWorldCoordinates(
event.x,
event.y,
);
if (!this.gameView.isValidCoord(cell.x, cell.y)) {
return;
}
const tile = this.gameView.ref(cell.x, cell.y);
if (this.myPlayer === null) {
if (!this.clientID) return;
const myPlayer = this.gameView.playerByClientID(this.clientID);
if (myPlayer === null) return;
this.myPlayer = myPlayer;
}
if (this.gameView.inSpawnPhase()) {
return;
}
this.findAndUpgradeNearestBuilding(tile);
}
private findAndUpgradeNearestBuilding(clickedTile: TileRef) {
this.myPlayer!.actions(clickedTile, Structures.types).then((actions) => {
const upgradeUnits: {
unitId: number;
unitType: UnitType;
distance: number;
}[] = [];
for (const bu of actions.buildableUnits) {
if (bu.canUpgrade !== false) {
const existingUnit = this.gameView
.units()
.find((unit) => unit.id() === bu.canUpgrade);
if (existingUnit) {
const distance = this.gameView.manhattanDist(
clickedTile,
existingUnit.tile(),
);
upgradeUnits.push({
unitId: bu.canUpgrade,
unitType: bu.type,
distance: distance,
});
}
}
}
if (upgradeUnits.length === 0) {
return;
}
// Upgrade the closest affordable building. But if there's an unaffordable
// building (any type) that's closer to clickedTile than the best candidate,
// do nothing — the player clicked on that unaffordable building intending
// to upgrade it, and we must not spend their gold on a different building.
const bestUpgrade = findClosestBy(upgradeUnits, (u) => u.distance);
if (!bestUpgrade) {
return;
}
// Check if any unaffordable building is closer than bestUpgrade
for (const bu of actions.buildableUnits) {
if (bu.canUpgrade === false && bu.type !== bestUpgrade.unitType) {
const myPlayerID = this.myPlayer!.id();
const closestOfType = this.gameView
.nearbyUnits(
clickedTile,
this.gameView.config().structureMinDist(),
bu.type,
)
.filter(({ unit }) => unit.owner().id() === myPlayerID)
.sort((a, b) => a.distSquared - b.distSquared)[0];
if (closestOfType) {
const dist = this.gameView.manhattanDist(
clickedTile,
closestOfType.unit.tile(),
);
if (dist <= bestUpgrade.distance) {
// An unaffordable building of type bu.type is at least as close
// as bestUpgrade — player clicked on it, not on bestUpgrade.