import { getLogger, type Logger } from '@logtape/logtape'; import { CanvasRenderer } from '../display/canvas/renderer.js'; import { addToDOM, create, removeFromDOM, setTouchAction } from '../display/canvas/util.js'; import { WebGLRenderer } from '../display/webgl/renderer.js'; import { Cache } from './cache.js'; import { RENDER_AUTO, RENDER_WEBGL } from './const.js'; import { Device } from './device.js'; import { checkOS, initialize } from './device_util.js'; import { GameObjectFactory } from './factory.js'; import { Input } from './input.js'; import { Loader } from './loader.js'; import { RequestAnimationFrame } from './raf.js'; import { ScaleManager } from './scale_manager.js'; import { SceneManager } from './scene_manager.js'; import type { SceneDefinition } from './scene_manager.js'; import { Signal } from './signal.js'; import { SoundManager } from './sound_manager.js'; import { Stage } from './stage.js'; import { Time } from './time.js'; import { TweenManager } from './tween_manager.js'; import { World } from './world.js'; import { getRegistry } from './registry.js'; /** * The options a game is created with. Everything the constructor defaults is always present on * `Game.config`; the rest is only there when the caller supplied it. */ export type GameConfig = { width: number; height: number; backgroundColor: number; canvasID: string; canvasStyle: Record | undefined; resolution: number; transparent: boolean | 'notMultiplied'; antialias: boolean; preserveDrawingBuffer: boolean; clearBeforeRender: boolean; roundPixels: boolean; renderType: number; isForceDisabledAudio: boolean; maxParallelDownloads: number; canvas?: HTMLCanvasElement; isSkipTicker?: boolean; scaleMode?: number; fullScreenScaleMode?: number; fullScreenTarget?: HTMLElement; parent?: string | HTMLElement; state?: SceneDefinition | string; logger?: Logger; }; export class Game { /** Set when the scene manager kick-starts the first scene. */ public isKickStart = false; public config!: GameConfig; public id!: number; public parent!: string | HTMLElement; public width!: number; public height!: number; public renderer!: CanvasRenderer | WebGLRenderer; public state!: SceneManager; public isBooted!: boolean; public paused!: boolean; public raf!: RequestAnimationFrame; public add!: GameObjectFactory; public cache!: Cache; public input!: Input; public load!: Loader; public scale!: ScaleManager; public sound!: SoundManager; public stage!: Stage; public time!: Time; public tweens!: TweenManager; public world!: World; public device!: Device; public logger!: Logger; public canvas!: HTMLCanvasElement; public context!: | CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext | null; public onPause!: Signal; public onResume!: Signal; public onBoot!: Signal; public isPaused!: boolean; public contextLostBinded!: EventListener | null; public contextRestoredBinded!: EventListener | null; /** * Creates a new Game instance. * @param {object} gameConfig - The configuration object for the game. * @param {number} gameConfig.width - The width of the game canvas (default: 800). * @param {number} gameConfig.height - The height of the game canvas (default: 600). * @param {string} gameConfig.backgroundColor - The background color of the canvas (default: 0x000000). * @param {string} gameConfig.canvasID - The ID of the canvas element (default: ''). * @param {object} gameConfig.canvasStyle - CSS styles to apply to the canvas. * @param {number} gameConfig.resolution - The resolution scale factor (default: 1). * @param {boolean} gameConfig.transparent - Whether the canvas should be transparent (default: false). * @param {boolean} gameConfig.antialias - Whether to enable antialiasing (default: false). * @param {boolean} gameConfig.preserveDrawingBuffer - Whether to preserve the drawing buffer (default: false). * @param {boolean} gameConfig.clearBeforeRender - Whether to clear the canvas before rendering (default: true). * @param {boolean} gameConfig.roundPixels - Whether to round pixel values (default: true). * @param {number} gameConfig.renderType - The rendering type to use (default: RENDER_AUTO). * @param {boolean} gameConfig.isForceDisabledAudio - Whether to force disable audio (default: false). * @param {number} gameConfig.maxParallelDownloads - Maximum parallel downloads (default: 16). * @param {string|HTMLElement} gameConfig.parent - The parent element to append the canvas to. * @param {object} gameConfig.state - The initial state object or class. */ public constructor(gameConfig: Partial = {}) { getRegistry(); this.id = 0; this.parent = ''; this.width = 800; this.height = 600; this.isBooted = false; this.paused = false; this.device = new Device(); this.context = null; this.onPause = new Signal(); this.onResume = new Signal(); this.onBoot = new Signal(); this.isPaused = false; this.parseConfig(gameConfig); checkOS(this.device); if (document.readyState === 'complete') { initialize(this.device); this.boot(); } else { window.addEventListener( 'load', (): void => { initialize(this.device); this.boot(); }, false ); } } /** * Boots the game and initializes all systems. */ public boot(): void { if (this.isBooted) { return; } this.isBooted = true; this.scale = new ScaleManager(this, this.config.width, this.config.height); this.stage = new Stage(this); this.initRenderer(); this.world = new World(this); this.add = new GameObjectFactory(this); this.cache = new Cache(this); this.load = new Loader(this); this.time = new Time(this); this.tweens = new TweenManager(this); this.input = new Input(this); this.sound = new SoundManager(this); this.time.boot(); this.stage.boot(); this.world.boot(); this.scale.boot(); this.input.boot(); this.sound.boot(); this.state.boot(); if (typeof window.focus === 'function') { window.focus(); } if (this.config.isSkipTicker !== true) { this.raf = new RequestAnimationFrame(this); this.raf.start(); } this.onBoot.dispatch(this); } /** * Creates the renderer canvas element. */ public createRendererCanvas(): void { this.logger.info('createRendererCanvas'); if (this.canvas as HTMLCanvasElement | undefined) { removeFromDOM(this.canvas); } this.canvas = this.config.canvas ?? create(this, this.width, this.height, this.config.canvasID, true); if (this.config.canvasStyle) { const { canvasStyle } = this.config; for (const property of Object.keys(canvasStyle)) { this.canvas.style.setProperty(property, canvasStyle[property] ?? null); } } else { this.canvas.style.setProperty('-webkit-full-screen', 'width: 100%; height: 100%'); } } /** * Initializes the renderer and sets up the rendering context. */ public initRenderer(): void { let isWebGlReady = false; if (this.config.renderType === RENDER_AUTO || this.config.renderType === RENDER_WEBGL) { try { this.createRendererCanvas(); this.logger.info('initWebGLRenderer'); this.renderer = new WebGLRenderer(this); this.context = null; this.contextLostBinded = this.contextLost.bind(this); this.contextRestoredBinded = this.contextRestored.bind(this); this.canvas.addEventListener('webglcontextlost', this.contextLostBinded, false); this.canvas.addEventListener('webglcontextrestored', this.contextRestoredBinded, false); isWebGlReady = true; } catch (error) { isWebGlReady = false; if (globalThis.PhaserRegistry?.GL_PROGRAM_INFO_LOG != null) { this.logger.warn('WebGL program info', { log: globalThis.PhaserRegistry.GL_PROGRAM_INFO_LOG }); } if (globalThis.PhaserRegistry?.GL_SHADER_INFO_LOG != null) { this.logger.warn('WebGL shader info', { log: globalThis.PhaserRegistry.GL_SHADER_INFO_LOG }); } const typedError = error instanceof Error ? error : new Error(String(error)); this.logger.fatal('Game', { error: typedError }); } } if (!isWebGlReady) { if (this.contextLostBinded) { this.canvas.removeEventListener('webglcontextlost', this.contextLostBinded, false); } if (this.contextRestoredBinded) { this.canvas.removeEventListener('webglcontextlost', this.contextRestoredBinded, false); } if (this.renderer as CanvasRenderer | WebGLRenderer | undefined) { this.renderer.destroy(); } this.createRendererCanvas(); this.logger.info('initCanvasRenderer'); this.renderer = new CanvasRenderer(this); this.context = this.renderer.context; } this.stage.smoothed = this.config.antialias; addToDOM(this.canvas, this.parent, false); setTouchAction(this.canvas); } /** * Parses a configuration element and sets it on the game config. * @param {object} config - The configuration object to parse from. * @param {string} key - The configuration key to parse. * @param {*} defaultValue - The default value if the key is not found in config. */ public parseConfigElement( config: Partial, key: K, defaultValue?: GameConfig[K] ): void { this.config[key] = (config[key] ?? defaultValue)!; } /** * Parses the configuration object and sets up game properties. * @param {object} config - The configuration object to parse. */ public parseConfig(config: Partial): void { this.logger = config.logger ?? getLogger(['phaser']); this.logger.info('parseConfig'); this.config = {} as GameConfig; this.parseConfigElement(config, 'width', 800); this.parseConfigElement(config, 'height', 600); this.parseConfigElement(config, 'backgroundColor', 0x00_00_00); this.parseConfigElement(config, 'canvasID', ''); this.parseConfigElement(config, 'canvasStyle'); this.parseConfigElement(config, 'resolution', 1); this.parseConfigElement(config, 'transparent', false); this.parseConfigElement(config, 'antialias', false); this.parseConfigElement(config, 'preserveDrawingBuffer', false); this.parseConfigElement(config, 'clearBeforeRender', true); this.parseConfigElement(config, 'roundPixels', true); this.parseConfigElement(config, 'renderType', RENDER_AUTO); this.parseConfigElement(config, 'isForceDisabledAudio', false); this.parseConfigElement(config, 'maxParallelDownloads', 16); this.parseConfigElement(config, 'canvas'); this.parseConfigElement(config, 'isSkipTicker'); this.parseConfigElement(config, 'scaleMode'); this.parseConfigElement(config, 'fullScreenScaleMode'); this.parseConfigElement(config, 'fullScreenTarget'); if (config.parent !== undefined) { this.parent = config.parent; } this.state = new SceneManager(this, config.state ?? null); } /** * Called when the WebGL context is lost. * @param {WebGLContextEvent | Event} event - The WebGL context loss event. */ public contextLost(event: Event): void { this.logger.info('contextLost', { type: event.type }); event.preventDefault(); if (this.renderer as CanvasRenderer | WebGLRenderer | undefined) { this.renderer.contextLost = true; } } /** * Called when the WebGL context is restored. * @param {WebGLContextEvent | Event} event - The WebGL context restore event. */ public contextRestored(event: Event): void { this.logger.info('contextRestored', { type: event.type }); if (this.renderer as CanvasRenderer | WebGLRenderer | undefined) { this.renderer.initContext(this); // This.cache.clearGLTextures(); this.renderer.contextLost = false; } } /** * Updates the game state. * @param {number} time - The current timestamp. */ public update(time: number): void { this.time.update(time); if (!this.isPaused) { this.scale.preUpdate(); this.state.preUpdate(); this.stage.preUpdate(); this.state.update(); this.stage.update(); this.tweens.update(); this.sound.update(); this.input.update(); this.stage.postUpdate(); } else { this.scale.pauseUpdate(); this.state.pauseUpdate(); } this.stage.updateTransform(); this.renderer.render(this.stage); } /** * Destroys the game and cleans up all resources. */ public destroy(): void { this.logger.info('destroy'); this.isPaused = true; if (!(this.cache as Cache | undefined)) { return; } if (this.raf as RequestAnimationFrame | undefined) { this.raf.stop(); } this.time.destroy(); this.state.destroy(); this.sound.destroy(); this.scale.destroy(); this.stage.destroy(); this.input.destroy(); if (this.canvas as HTMLCanvasElement | undefined) { if (this.contextLostBinded) { this.canvas.removeEventListener('webglcontextlost', this.contextLostBinded, false); } if (this.contextRestoredBinded) { this.canvas.removeEventListener('webglcontextlost', this.contextRestoredBinded, false); } } this.renderer.destroy(false); removeFromDOM(this.canvas); this.cache = null!; this.load = null!; this.time = null!; this.world = null!; this.state = null!; this.sound = null!; this.scale = null!; this.stage = null!; this.input = null!; this.canvas = null!; this.renderer = null!; } }