-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathGameRenderer.ts
More file actions
462 lines (410 loc) · 15.6 KB
/
Copy pathGameRenderer.ts
File metadata and controls
462 lines (410 loc) · 15.6 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
import { EventBus } from "../../core/EventBus";
import { GameView } from "../../core/game/GameView";
import { GameStartingModal } from "../GameStartingModal";
import { RefreshGraphicsEvent as RedrawGraphicsEvent } from "../InputHandler";
import { PerformanceMetrics } from "../utilities/PerformanceMetrics";
import { TransformHandler } from "./TransformHandler";
import { UIState } from "./UIState";
import { AABulletLayer } from "./layers/AABulletLayer";
import { ArtilleryLayer } from "./layers/ArtilleryLayer";
import { AttackDebugOverlay } from "./layers/AttackDebugOverlay";
import { AttackWarningOverlay } from "./layers/AttackWarningOverlay";
import { BuildMenu } from "./layers/BuildMenu";
import { CargoTruckLayer } from "./layers/CargoTruckLayer";
import { ChatDisplay } from "./layers/ChatDisplay";
import { ChatModal } from "./layers/ChatModal";
import { ConstructionDebugOverlay } from "./layers/ConstructionDebugOverlay";
import { ControlPanel } from "./layers/ControlPanel";
import { ControlPanel2 } from "./layers/ControlPanel2";
import { DevHud } from "./layers/DevHud";
import { EmojiTable } from "./layers/EmojiTable";
import { EventsDisplay } from "./layers/EventsDisplay";
import { FxLayerV2 as FxLayer } from "./layers/FxLayerV2";
import { GameLeftSidebar } from "./layers/GameLeftSidebar";
import { HeadsUpMessage } from "./layers/HeadsUpMessage";
import { Layer } from "./layers/Layer";
import { Leaderboard } from "./layers/Leaderboard";
import { MultiTabModal } from "./layers/MultiTabModal";
import { NameLayer } from "./layers/NameLayer";
import { OptionsMenu } from "./layers/OptionsMenu";
import { PlayerInfoOverlay } from "./layers/PlayerInfoOverlay";
import { PlayerPanel } from "./layers/PlayerPanel";
import { PointerCoordsLayer } from "./layers/PointerCoordsLayer";
import { RadialMenu } from "./layers/RadialMenu";
import { RangeOverlayLayer } from "./layers/RangeOverlayLayer";
import { ReplayPanel } from "./layers/ReplayPanel";
import { ResearchToggleButton } from "./layers/ResearchToggleButton";
import { RoadLayer } from "./layers/RoadLayer";
import { SpawnTimer } from "./layers/SpawnTimer";
import { StructureLayer } from "./layers/StructureLayer";
import { TeamStats } from "./layers/TeamStats";
import { TechUnlockNotification } from "./layers/TechUnlockNotification";
import { TerrainLayer } from "./layers/TerrainLayer";
import { TerritoryLayer } from "./layers/TerritoryLayer";
import { TopBar } from "./layers/TopBar";
import { TradeDebugOverlay } from "./layers/TradeDebugOverlay";
import { TutorialToast } from "./layers/TutorialToast";
import { TutorialTriggers } from "./layers/TutorialTriggers";
import { UILayer } from "./layers/UILayer";
import { UnitLayer } from "./layers/UnitLayer";
import { WarScoreOverlay } from "./layers/WarScoreOverlay";
import { WinModal } from "./layers/WinModal";
// Debug flags (keep off for normal gameplay)
const DEBUG_SHOW_POINTER_COORDS = false;
export function createRenderer(
canvas: HTMLCanvasElement,
game: GameView,
eventBus: EventBus,
): GameRenderer {
// Remove persisted settings modals from previous games so they reset to default levels
document.querySelector("build-settings-modal")?.remove();
document.querySelector("unit-upgrade-settings-modal")?.remove();
// Clear persisted levels so they reset to 1 for the new game
localStorage.removeItem("buildSettings.levels");
localStorage.removeItem("unitUpgradeSettings.levels");
const transformHandler = new TransformHandler(game, eventBus, canvas);
// Prevent main menu/page scrolling during gameplay
const previousBodyOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
const uiState: UIState = {
attackRatio: 0.2, // 20% as a float
investmentRate: 0.5, // 50% default investment rate
pendingBuildUnitType: null,
multibuildEnabled: false,
upgradeMode: false,
unitLevels: {},
};
//hide when the game renders
const startingModal = document.querySelector(
"game-starting-modal",
) as GameStartingModal;
startingModal.hide();
// TODO maybe append this to dcoument instead of querying for them?
const emojiTable = document.querySelector("emoji-table") as EmojiTable;
if (!emojiTable || !(emojiTable instanceof EmojiTable)) {
console.error("EmojiTable element not found in the DOM");
}
emojiTable.transformHandler = transformHandler;
emojiTable.game = game;
emojiTable.initEventBus(eventBus);
const buildMenu = document.querySelector("build-menu") as BuildMenu;
if (!buildMenu || !(buildMenu instanceof BuildMenu)) {
console.error("BuildMenu element not found in the DOM");
}
buildMenu.game = game;
buildMenu.eventBus = eventBus;
buildMenu.uiState = uiState;
const leaderboard = document.querySelector("leader-board") as Leaderboard;
if (!leaderboard || !(leaderboard instanceof Leaderboard)) {
console.error("LeaderBoard element not found in the DOM");
}
leaderboard.eventBus = eventBus;
leaderboard.game = game;
const gameLeftSidebar = document.querySelector(
"game-left-sidebar",
) as GameLeftSidebar;
if (!gameLeftSidebar || !(gameLeftSidebar instanceof GameLeftSidebar)) {
console.error("GameLeftSidebar element not found in the DOM");
}
gameLeftSidebar.game = game;
const teamStats = document.querySelector("team-stats") as TeamStats;
if (!teamStats || !(teamStats instanceof TeamStats)) {
console.error("TeamStats element not found in the DOM");
}
teamStats.eventBus = eventBus;
teamStats.game = game;
const controlPanel = document.querySelector("control-panel") as ControlPanel;
if (!(controlPanel instanceof ControlPanel)) {
console.error("ControlPanel element not found in the DOM");
}
controlPanel.eventBus = eventBus;
controlPanel.uiState = uiState;
controlPanel.game = game;
const controlPanel2 = document.querySelector(
"control-panel2",
) as ControlPanel2;
if (!(controlPanel2 instanceof ControlPanel2)) {
console.error("ControlPanel2 element not found in the DOM");
}
controlPanel2.eventBus = eventBus;
controlPanel2.uiState = uiState;
controlPanel2.game = game;
const researchToggleButton = document.querySelector(
"research-toggle-button",
) as ResearchToggleButton;
if (!(researchToggleButton instanceof ResearchToggleButton)) {
console.error("ResearchToggleButton element not found in the DOM");
}
researchToggleButton.eventBus = eventBus;
researchToggleButton.game = game;
const techUnlockNotification = document.querySelector(
"tech-unlock-notification",
) as TechUnlockNotification;
if (!(techUnlockNotification instanceof TechUnlockNotification)) {
console.error("TechUnlockNotification element not found in the DOM");
}
techUnlockNotification.eventBus = eventBus;
techUnlockNotification.game = game;
const tutorialToast = document.querySelector(
"tutorial-toast",
) as TutorialToast;
if (!(tutorialToast instanceof TutorialToast)) {
console.error("TutorialToast element not found in the DOM");
}
tutorialToast.eventBus = eventBus;
tutorialToast.game = game;
const eventsDisplay = document.querySelector(
"events-display",
) as EventsDisplay;
if (!(eventsDisplay instanceof EventsDisplay)) {
console.error("events display not found");
}
eventsDisplay.eventBus = eventBus;
eventsDisplay.game = game;
const chatDisplay = document.querySelector("chat-display") as ChatDisplay;
if (!(chatDisplay instanceof ChatDisplay)) {
console.error("chat display not found");
}
chatDisplay.eventBus = eventBus;
chatDisplay.game = game;
const playerInfo = document.querySelector(
"player-info-overlay",
) as PlayerInfoOverlay;
if (!(playerInfo instanceof PlayerInfoOverlay)) {
console.error("player info overlay not found");
}
playerInfo.eventBus = eventBus;
playerInfo.transform = transformHandler;
playerInfo.game = game;
const winModel = document.querySelector("win-modal") as WinModal;
if (!(winModel instanceof WinModal)) {
console.error("win modal not found");
}
winModel.eventBus = eventBus;
winModel.game = game;
const optionsMenu = document.querySelector("options-menu") as OptionsMenu;
if (!(optionsMenu instanceof OptionsMenu)) {
console.error("options menu not found");
}
optionsMenu.eventBus = eventBus;
optionsMenu.game = game;
const replayPanel = document.querySelector("replay-panel") as ReplayPanel;
if (!(replayPanel instanceof ReplayPanel)) {
console.error("ReplayPanel element not found in the DOM");
}
replayPanel.eventBus = eventBus;
replayPanel.game = game;
const topBar = document.querySelector("top-bar") as TopBar;
if (!(topBar instanceof TopBar)) {
console.error("top bar not found");
}
topBar.game = game;
const playerPanel = document.querySelector("player-panel") as PlayerPanel;
if (!(playerPanel instanceof PlayerPanel)) {
console.error("player panel not found");
}
playerPanel.g = game;
playerPanel.eventBus = eventBus;
playerPanel.emojiTable = emojiTable;
playerPanel.uiState = uiState;
const chatModal = document.querySelector("chat-modal") as ChatModal;
if (!(chatModal instanceof ChatModal)) {
console.error("chat modal not found");
}
chatModal.g = game;
chatModal.eventBus = eventBus;
const multiTabModal = document.querySelector(
"multi-tab-modal",
) as MultiTabModal;
if (!(multiTabModal instanceof MultiTabModal)) {
console.error("multi-tab modal not found");
}
multiTabModal.game = game;
const headsUpMessage = document.querySelector(
"heads-up-message",
) as HeadsUpMessage;
if (!(headsUpMessage instanceof HeadsUpMessage)) {
console.error("heads-up message not found");
}
headsUpMessage.game = game;
const attackWarningOverlay = document.querySelector(
"attack-warning-overlay",
) as AttackWarningOverlay;
if (!(attackWarningOverlay instanceof AttackWarningOverlay)) {
console.error("attack-warning-overlay not found");
}
attackWarningOverlay.eventBus = eventBus;
attackWarningOverlay.game = game;
// Provide a lightweight teardown hook to restore page scroll if needed
const cleanup = () => {
document.body.style.overflow = previousBodyOverflow;
};
const structureLayer = new StructureLayer(game, eventBus, transformHandler);
// When updating these layers please be mindful of the order.
// Try to group layers by the return value of shouldTransform.
// Not grouping the layers may cause excessive calls to context.save() and context.restore().
const layers: Layer[] = [
new TerrainLayer(game, transformHandler),
new TerritoryLayer(game, eventBus, transformHandler),
new RoadLayer(game, transformHandler),
new CargoTruckLayer(game, transformHandler),
// World-space ring overlay for Defense Posts/SAMs
new RangeOverlayLayer(game, eventBus, transformHandler, uiState),
structureLayer,
new ArtilleryLayer(game, eventBus, transformHandler),
new UnitLayer(game, eventBus, transformHandler, uiState),
// UILayer placed right after UnitLayer: both use shouldTransform=true,
// keeping them adjacent avoids extra context.save/restore transitions.
new UILayer(game, eventBus, transformHandler),
new AABulletLayer(game, transformHandler),
new FxLayer(game, transformHandler),
// Draw name labels in world space (handles transforms manually)
new NameLayer(game, transformHandler, eventBus),
// Pointer coordinates (screen-space, debug only)
...(DEBUG_SHOW_POINTER_COORDS
? [new PointerCoordsLayer(game, eventBus, transformHandler)]
: []),
eventsDisplay,
chatDisplay,
attackWarningOverlay,
new RadialMenu(
eventBus,
game,
transformHandler,
emojiTable as EmojiTable,
uiState,
playerInfo,
playerPanel,
),
new SpawnTimer(game, transformHandler),
leaderboard,
gameLeftSidebar,
controlPanel,
controlPanel2,
researchToggleButton,
techUnlockNotification,
tutorialToast,
new TutorialTriggers(game, eventBus),
playerInfo,
winModel,
optionsMenu,
replayPanel,
teamStats,
topBar,
playerPanel,
headsUpMessage,
multiTabModal,
new DevHud(game, transformHandler),
new WarScoreOverlay(game),
new AttackDebugOverlay(game),
new TradeDebugOverlay(game),
new ConstructionDebugOverlay(game),
];
return new GameRenderer(
game,
eventBus,
canvas,
transformHandler,
uiState,
layers,
);
}
export class GameRenderer {
private context: CanvasRenderingContext2D;
constructor(
private game: GameView,
private eventBus: EventBus,
private canvas: HTMLCanvasElement,
public transformHandler: TransformHandler,
public uiState: UIState,
private layers: Layer[],
) {
const context = canvas.getContext("2d", { alpha: false });
if (context === null) throw new Error("2d context not supported");
this.context = context;
}
initialize() {
this.eventBus.on(RedrawGraphicsEvent, () => this.redraw());
this.layers.forEach((l) => l.init?.());
document.body.appendChild(this.canvas);
window.addEventListener("resize", () => this.resizeCanvas());
this.resizeCanvas();
//show whole map on startup
this.transformHandler.centerAll(0.9);
let rafId = requestAnimationFrame(() => this.renderGame());
this.canvas.addEventListener("contextlost", () => {
cancelAnimationFrame(rafId);
});
this.canvas.addEventListener("contextrestored", () => {
this.redraw();
rafId = requestAnimationFrame(() => this.renderGame());
});
}
resizeCanvas() {
const dpr = window.devicePixelRatio || 1;
this.canvas.width = window.innerWidth * dpr;
this.canvas.height = window.innerHeight * dpr;
this.transformHandler.updateCanvasBoundingRect();
}
redraw() {
this.layers.forEach((l) => {
if (l.redraw) {
l.redraw();
}
});
}
renderGame() {
PerformanceMetrics.getInstance().resetVisibleCount();
const start = performance.now();
const dpr = window.devicePixelRatio || 1;
// Apply DPR base transform so all drawing uses CSS-pixel coordinates
this.context.setTransform(dpr, 0, 0, dpr, 0, 0);
// Set background
this.context.fillStyle = this.game
.config()
.theme()
.backgroundColor()
.toHex();
this.context.fillRect(0, 0, window.innerWidth, window.innerHeight);
// Render layers in order, switching transform state as needed
let isTransformed = false;
for (const layer of this.layers) {
const layerStart = performance.now();
const layerNeedsTransform = layer.shouldTransform?.() ?? false;
if (layerNeedsTransform && !isTransformed) {
this.context.save();
this.transformHandler.handleTransform(this.context);
isTransformed = true;
} else if (!layerNeedsTransform && isTransformed) {
this.context.restore();
isTransformed = false;
}
layer.renderLayer?.(this.context);
const layerEnd = performance.now();
PerformanceMetrics.getInstance().updateLayerDuration(
(layer as Layer).layerName ?? layer.constructor.name,
layerEnd - layerStart,
);
}
if (isTransformed) {
this.context.restore();
}
this.transformHandler.resetChanged();
requestAnimationFrame(() => this.renderGame());
const duration = performance.now() - start;
PerformanceMetrics.getInstance().updateFrame(duration);
if (duration > 50) {
console.warn(
`tick ${this.game.ticks()} took ${duration}ms to render frame`,
);
}
}
tick() {
this.layers.forEach((l) => l.tick?.());
}
resize(width: number, height: number): void {
const dpr = window.devicePixelRatio || 1;
this.canvas.width = Math.ceil(width * dpr);
this.canvas.height = Math.ceil(height * dpr);
}
}