# core/engine (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/core/engine/

Engine.

## EngineConfiguration extends Object

Engine configuration.

Example: Fill in the configuration and create the engine

```js
import { Engine, EngineConfiguration, Scene, Vector2, ViewScaleMode, ColorSpace } from "./build/vanilla.js";

const engineConfiguration = new EngineConfiguration();
engineConfiguration.canvasId = "gameCanvas";
engineConfiguration.title = "My Game";
engineConfiguration.referenceResolutionSize = Vector2.create(1920, 1080);
engineConfiguration.viewScaleMode = ViewScaleMode.stretchShortExpandLong;
engineConfiguration.autoResizeOnWindowResize = true;
engineConfiguration.maximumFramePerSecond = 60;
engineConfiguration.antialias = true;
engineConfiguration.useStatistics = true;
engineConfiguration.useDevTools = false;
engineConfiguration.colorSpace = ColorSpace.gamma;
const engine = new Engine(engineConfiguration);
engine.run(new Scene());
```

- `referenceResolutionSize` (field, since 0.0.8): Reference resolution.
  - returns Vector2
- `viewScaleMode` (field, since 0.4.0): View scale mode. (Default ViewScaleMode.stretchShort, put into the view manager when the engine is created. UIScene and GameScene switch to their own mode in initialize)
  - returns string
- `canvasId` (field, since 0.0.8): Canvas identifier. If the document has no element with that id, a new canvas is created with that id and appended to the end of body.
  - returns string
- `useStatistics` (field, since 0.0.9): Whether to show the info window.
  - returns boolean
- `autoResizeOnWindowResize` (field, since 0.0.9): Automatically applies the canvas size when the window is resized.
  - returns boolean
- `title` (field, since 0.2.0): Name.
  - returns string
- `preserveDrawingBuffer` (field, since 0.3.1): Whether to keep the drawing on the canvas after the frame ends. Projects that layer post-processing on top of the canvas turn it on.
  (Needed for another canvas to read it with texImage2D or drawImage) It costs one extra copy.
  - returns boolean
- `antialias` (field, since 0.4.0): Whether to enable multisample anti-aliasing (MSAA) on the canvas (default framebuffer). Set at creation. On (default) keeps the previous behavior.
  Off makes the edges of shapes and 3D look stepped, but removes the per-frame resolve cost on high-resolution mobile devices.
  (On the web it only chooses on or off through the WebGL context attribute antialias and the browser picks the sample count. On desktop, on means 4 samples)
  A game that uses a post process (ToonPostProcess) should build the canvas with antialias set to false, because the post process draws into its own MSAA target.
  With true, the canvas itself is MSAA, so the pass that copies to the screen and the UI blend per sample and cost more.
  (Mac mini, 2560x1440 toon post process scene, GPU throughput 6.89 → 6.49 ms, with it off 6.81 → 5.22 ms)
  Example: engineConfiguration.antialias = false; (for a game that uses ToonPostProcess)
  - returns boolean
- `maximumFramePerSecond` (field, since 0.3.2): Maximum FPS. 0 means no limit. (Follows the display refresh rate) When set, frames arriving sooner than that are skipped so it
  runs at even intervals even on devices with high refresh rates or uneven frames.
  - returns number
- `defaultFontUrl` (field, since 0.3.2): Default font address. (empty at first, same as Rust default_font_url) When given, run() fetches it in the background and adds it under the font name "default".
  - It becomes the first font of the font name "default" (the engine default font chain), followed by the system font chain SYSTEM_FONT_STRING. When empty, nothing is fetched and text is drawn with the system font.
  - The engine fetches no font of its own. Give game fonts with this address or a FontAsset.
  - returns string
- `ignoreVirtualKeyboardResize` (field, since 0.3.2): Whether to ignore resizes where the width stays the same and only the height shrinks while a text input field is focused. (On-screen keyboard on mobile)
  When off (default), on iOS Safari the visualViewport height shrinks when the keyboard appears, making the canvas and the whole screen smaller. It readjusts when the keyboard goes down.
  - returns boolean
- `rebakeTextOnFontLoad` (field, since 0.3.2): When a web font arrives late, whether to discard only the glyph textures baked with that font that fall within that font's character range, so they are baked again.
  When off (default), glyphs baked with another font before it arrived stay until they are pushed out of the cache.
  (Turned on by projects that fetch font pieces split by unicode-range on demand. Only those glyphs are rebaked for each received piece, so frames do not get much longer)
  - returns boolean
- `useDevTools` (field, since 0.3.2): Whether to use the developer tools (the panel and gizmos toggled with F2). When off, GameScene does not create them and F2 is not handled either.
  (When on (default), same as before. Turn it off where they must not be visible to users, like release builds)
  - returns boolean
- `maxCanvasAspectRatio` (field, since 0.3.2): How many times the short side the canvas's long side may be. 0 means no limit. (default, same as before)
  When set, if the window is more elongated than that when fitting with autoResizeOnWindowResize, the canvas is shrunk to that ratio and centered in the window. (The remaining space is the page background)
  (Set where the canvas must not fill the whole window, like portals that limit the aspect ratio of the game area)
  - returns number
- `resumeAudioOnTouchEnd` (field, since 0.3.2): Whether to also wake the audio context on release (touchend, pointerup). Set at construction.
  When off (default), wakes only on click, touchstart and keydown as before. touchstart does not grant user activation, so
  on iOS WebKit, games that only drag on the screen could not wake a context stopped (suspended, interrupted) by app switching or full-screen ads.
  (Turned on by games where dragging the canvas prevents the default behavior so no click occurs)
  - returns boolean
- `colorSpace` (field, since 0.4.0): 3D color space. (ColorSpace.gamma is the default, the same screen as before. ColorSpace.linear computes lighting in linear space with sRGB textures and the sRGB standard curve)
  Set at creation. The toon renderer, post process, screen outline and GLB reading follow this value unless given their own. 2D composites in gamma space either way. (Color Space in Unity's Player Settings)
  - returns string
- `trackGpuMemory` (field, since 0.4.0): Whether to turn on GPU memory tracking (for development) from the start. Set at creation. When off (the default), GL create calls are not intercepted, so there is no per-frame CPU cost.
  When on, the resources the engine creates first are counted too. To turn it on later use Engine.enableGpuMemoryTracking(), which counts what is created after that.
  Example: engineConfiguration.trackGpuMemory = true; (when profiling)
  - returns boolean
- `constructor()` (constructor, since 0.0.8): Constructor.

## Engine extends Object

Engine.

Example: Run the engine with one scene

```js
import { Engine, EngineConfiguration, Scene, Vector2, Rect, Colors } from "./build/vanilla.js";

class MainScene extends Scene {
	draw(graphic) {
		super.draw(graphic);
		graphic.setFillColor(Colors.white);
		graphic.drawRect(Rect.create(100, 100, 200, 120));
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
engineConfiguration.autoResizeOnWindowResize = true;
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor(engineConfiguration)` (constructor, since 0.0.8): Constructor.
  - `engineConfiguration` EngineConfiguration: Engine configuration. (throws if it is not an EngineConfiguration)
- `run(scene)` (method, since 0.0.8): Start.
  - `scene` Scene: Scene to load first. (throws if it is not a Scene)
- `resume()` (method, since 0.0.10): Resumes the audio context.
- `resumeOnUserGesture()` (method, since 0.2.1): First user gesture (click/touch/keydown) handler.
  Notifies AudioManager that a user gesture occurred and tries to resume the context.
- `resize()` (method, since 0.0.8): Resolution changed.
- `isTextInputFocused()` (method, since 0.3.2): Whether a text input field is focused. (text-type input, textarea, contenteditable)
  - returns boolean: True if a text input is focused.
- `setupAllDocumentEvents()` (method, since 0.0.8): Sets up web page based events.
- `updateTouchPoints(touchEvent)` (method, since 0.4.0): Updates the finger list. (Records touch, move and release for each changed finger of the touch event, and removes fingers not in the event's touches as cancelled)
  - `touchEvent` TouchEvent: The browser touch event.
- `updateCanvasNativeInputPosition(x, y)` (method, since 0.0.8): Updates input coordinates.
  - `x` number: Client X coordinate. (CSS pixels, clientX)
  - `y` number: Client Y coordinate. (CSS pixels, clientY)
- `drawStatistics(graphic)` (method, since 0.0.8): Outputs development information.
  - `graphic` Graphic: Graphic to draw with.
- `updateEngine(timestamp)` (method, since 0.0.8): Engine update.
  - `timestamp` number: Timestamp passed by requestAnimationFrame. (milliseconds)
- `measureGpuThroughput(frameCount = 120)` (method, since 0.4.0): Measures GPU throughput. (Time per frame for drawing the current scene repeatedly without updates and waiting until the GPU finishes drawing)
  - Draws the current scene frameCount times in a row through the same drawing path as an engine frame without scene updates (tick), waits with a 1-pixel readPixels until the GPU finishes drawing, and divides the wall-clock time by the frame count.
    It is the share of the slowest stage among the renderer (script and writing GL commands), the GPU process (decoding commands) and GPU execution. When the GPU is the slowest, it is the time the GPU actually takes to draw a frame.
    (The GPU process main thread time in a Chrome trace is CPU time for decoding commands, so it barely moves even when the amount the GPU draws changes)
  - Starts from the next rAF. After 10 warm-up frames, it splits the frames into chunks of 30, draws one chunk per rAF and waits for the GPU after each chunk. (It does not block for long at once, and the time between chunks is not measured)
  - While measuring, engine time, input, engine frame callbacks, the frame number, canvas resizing and capture stand still, and the scenes' tick is not called. If the scenes' draw does not change game state, game state stays the same.
    When it finishes, the engine loop continues as it was. (The first frame interval after resuming is within the TimeManager interval limit, as when a hidden tab comes back, 0.25 seconds by default)
  - Because the same state is drawn repeatedly, caches that redraw only what changed (such as onChange shadows) do not rebake. The cost of rebaking every frame in a moving scene is not included.
  - Drawing to the canvas default framebuffer repeatedly presents (composites) only the last frame of each chunk. Compositing cost is not included.
  - If the page is hidden and rAF stops, it waits. Calling it again while measuring, or before the engine loop runs, is rejected.
  - `frameCount` number: Number of frames to measure. (Integer of 1 or more, counted without the warm-up)
  - returns Promise<{ frameCount: number, chunkFrameCount: number, millisecondsPerFrame: number, chunkMillisecondsPerFrame: number[] }>: Measured frame count, chunk frame count, time per frame (milliseconds, sum of all chunk times / frame count), and time per frame for each chunk (milliseconds).

  Example: Measuring the GPU throughput of the current scene

  ```js
  import { Engine, EngineConfiguration, Scene, Rect, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.setFillColor("#203040");
  		graphic.drawRect(Rect.create(0, 0, 640, 360));
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  const timeBefore = engine.getTimeManager().getTime();
  const result = await Engine.getEngine().measureGpuThroughput(60);
  const timeAfter = engine.getTimeManager().getTime();
  console.log(result.frameCount, result.chunkMillisecondsPerFrame.length, result.millisecondsPerFrame > 0, timeBefore === timeAfter);
  ```

- `setVisibleCursor(visibled)` (method, since 0.0.8): Sets cursor visibility.
  - `visibled` boolean: If true, sets the body cursor to the default cursor; if false, hides it.
- `getCanvas()` (method, since 0.0.8): Returns canvas information.
  - returns HTMLCanvasElement: The canvas the engine draws to.
- `getPlatform()` (method, since 0.0.8): Returns platform information.
  - returns Platform: Platform information.
- `getTimeManager()` (method, since 0.0.8): Returns the time manager.
  - returns TimeManager: Time manager.
- `getViewManager()` (method, since 0.0.8): Returns the view manager.
  - returns ViewManager: View manager.
- `getInputManager()` (method, since 0.0.8): Returns the input manager.
  - returns InputManager: Input manager.
- `getAudioManager()` (method, since 0.0.10): Returns the audio manager.
  - returns AudioManager: The audio manager.
- `getGraphic()` (method, since 0.0.9): Returns the renderer.
  - returns Graphic: The renderer.
- `getColorSpace()` (method, since 0.4.0): Returns the 3D color space. (The value set by EngineConfiguration.colorSpace at creation, the default of the toon renderer and post process)
  - returns string: ColorSpace.gamma or ColorSpace.linear.

  Example: Pick a value per color space from the engine's color space

  ```js
  import { Engine, EngineConfiguration, ColorSpace } from "./vanilla.js";
  const engine = new Engine(new EngineConfiguration());
  const exposure = engine.getColorSpace() === ColorSpace.linear ? 1.2 : 1;
  if (engine.getColorSpace() !== ColorSpace.gamma || exposure !== 1) {
  	throw new Error("default color space is not gamma");
  }
  ```

- `getVersionString()` (method, since 0.0.8): Returns the version.
  - returns string: Engine version text. ("major.minor.patch", with "-branch" appended if there is a branch)
- `setMaximumFramePerSecond(maximumFramePerSecond)` (method, since 0.4.0): Sets the maximum FPS. (Can be changed while running, 0 means no limit)
  - Writes to EngineConfiguration.maximumFramePerSecond. The engine reads that value every frame and, if it changed, starts counting again from that frame.
  - Less than 0 or not a number is set to 0.
  - `maximumFramePerSecond` number: Maximum FPS. (0 means no limit)
- `getMaximumFramePerSecond()` (method, since 0.4.0): Returns the maximum FPS. (0 means no limit)
  - returns number: Maximum FPS. (0 means no limit)
- `getEngineConfiguration()` (method, since 0.0.9): Returns the engine configuration.
  - returns EngineConfiguration: The engine configuration given at creation.
- `exitApplication()` (method, since 0.3.0): Exits the application.
  - On Capacitor native, exits through the App plugin; on the web, tries to close the window.
    (Both may be refused depending on the environment, and failure throws no exception)
- `openUrl(url)` (method, since 0.4.0): Opens an outside URL. (new tab, same as the Rust version's Engine::open_url)
  - Web: opens it in a new tab with window.open(url, "_blank", "noopener"). The new tab cannot touch the existing page.
  - It opens only when called inside user input (click, tap, key) handling. This is the browser's popup-blocking rule. Called regardless of input (timer, frame), it is blocked and does not open.
  - Only http, https, mailto and tel can be opened. Other forms (such as javascript: and file:) are not opened and return false.
  - `url` string: URL to open. (http, https, mailto, tel)
  - returns boolean: True if the open was handed to the browser. (false if the browser blocked it or the URL is not allowed)

  Example: A form that cannot be opened returns false

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const isOpened = engine.openUrl("javascript:alert(1)");
  		console.log(isOpened);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `readLocalTime(minuteOffset = 0)` (method, since 0.4.0): Read the local time. (the calendar time of now plus a minute offset in this machine's time zone, same as the Rust edition's Engine::read_local_time)
  - On the web it is read with Date. Daylight saving time at the shifted moment is applied. (same as new Date(Date.now() + offset))
  - `minuteOffset` number: Minutes to add to now. (negative is the past, 0 is now)
  - returns { year: number, month: number, day: number, hour: number, minute: number, second: number, weekday: number }: Local time. (year, month 1 to 12, day, hour, minute, second, weekday with 0 as Sunday)

  Example: The current time and two hours ahead and behind

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const now = engine.readLocalTime();
  		const later = engine.readLocalTime(120);
  		const earlier = engine.readLocalTime(-120);
  		console.log(now.hour < 24 && now.month >= 1 && now.month <= 12, later.hour !== earlier.hour);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getFrameNumber()` (method, since 0.2.0): Returns the current frame number.
  - returns number: The current frame number. (becomes 1 when run is called and increases by 1 each time a frame finishes)
- `isExitRequested()` (method, since 0.4.0): Whether exit has been requested. (True if exitApplication was called, true even if the browser refuses to close the window)
  - returns boolean: True if exitApplication was called.
- `setTitle(title)` (method, since 0.4.0): Sets the window title. (Tab title, document.title)
  - `title` string: Window title.
- `alert(message)` (method, since 0.4.0): Alert dialog. (in place of window.alert, drawn by the engine, same as Engine::alert in the Rust edition)
  - Returns a handle that finishes when OK is pressed. (the answer is always confirmed)
  - `message` string: The message to show.
  - returns ModalDialogHandle: The dialog handle.
- `confirm(message)` (method, since 0.4.0): Confirm dialog. (in place of window.confirm, drawn by the engine, same as Engine::confirm in the Rust edition)
  - `message` string: The question to ask.
  - returns ModalDialogHandle: The dialog handle. (isConfirmed is true if confirmed)
- `prompt(message, defaultValue = "")` (method, since 0.4.0): Prompt dialog. (in place of window.prompt, drawn by the engine, same as Engine::prompt in the Rust edition)
  - `message` string: The question to ask.
  - `defaultValue` string: The default value of the input field.
  - returns ModalDialogHandle: The dialog handle. (getPromptText is the entered text if confirmed)
- `alertAsync(message)` (method, since 0.4.0): Shows an alert dialog and returns a Promise that resolves when it closes. (the Rust Engine::alert_async)
  - `message` string: The message to show.
  - returns Promise<void>: Resolves when closed.
- `confirmAsync(message)` (method, since 0.4.0): Shows a confirm dialog and returns a Promise that resolves when answered. (the Rust Engine::confirm_async)
  - `message` string: The question to ask.
  - returns Promise<boolean>: true if confirmed.
- `promptAsync(message, defaultValue = "")` (method, since 0.4.0): Shows a prompt dialog and returns a Promise that resolves when answered. (the Rust Engine::prompt_async)
  - `message` string: The question to ask.
  - `defaultValue` string: The default value of the input field.
  - returns Promise<string | null>: The entered text. (null if cancelled)
- `isModalDialogOpen()` (method, since 0.4.0): Whether a modal dialog is open. (while it is open the engine does not update scenes, same as Engine::is_modal_dialog_open in the Rust edition)
  - returns boolean: True if shown.
- `writeClipboardText(text)` (method, since 0.4.0): Writes text to the system clipboard. (navigator.clipboard.writeText, does not wait. Does nothing if blocked or unavailable)
  - `text` string: Text to write to the clipboard.
- `async readClipboardText()` (method, since 0.4.0): Reads text from the system clipboard. (navigator.clipboard.readText, a Promise since the browser is asynchronous. null if there is no text or it is blocked)
  - The browser may ask for permission or allow it only inside user input.
  - returns Promise<string | null>: The clipboard text. (null if none or blocked)

  Example: Write to and read from the clipboard

  ```js
  import { Engine, EngineConfiguration } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.writeClipboardText("score: 100");
  const readPromise = engine.readClipboardText();
  readPromise.then((text) => {
  	if (text === null) {
  		console.log("clipboard blocked");
  	}
  	else {
  		console.log(text);
  	}
  });
  ```

- `isCoarsePointer()` (method, since 0.4.0): Whether the primary pointer is a finger. (CSS pointer: coarse)
  - returns boolean: True if the primary pointer is a finger.
- `loadScene(scene)` (method, since 0.4.0): Loads a scene. (Same as SceneManager.loadScene)
  - `scene` Scene: Scene to load.
  - returns Promise<void>: A Promise that settles after load and initialize finish. (settles at once if the scene is already loaded)

  Example: Load one more scene and unload it

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  class GameScene extends Scene {
  }
  
  class PauseScene extends Scene {
  	initialize(engine) {
  		console.log("pause scene ready");
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new GameScene());
  const pauseScene = new PauseScene();
  await engine.loadScene(pauseScene);
  const isPauseSceneLoaded = pauseScene.isLoaded();
  console.log(isPauseSceneLoaded);
  await engine.unloadScene(pauseScene);
  const loadedScenes = engine.getAllLoadedScenes();
  console.log(loadedScenes.length);
  ```

- `unloadScene(scene)` (method, since 0.4.0): Unloads one scene. (Same as SceneManager.unloadScene)
  - `scene` Scene: Scene to unload.
  - returns Promise<void>: A Promise that settles after finalize and unload finish and the scene is removed from the list. (settles at once if the scene is not loaded)
- `unloadAllScenes()` (method, since 0.4.0): Unloads all scenes. (Same as SceneManager.unloadAllScenes)
  - returns Promise<void>: A Promise that settles after all loaded scenes are unloaded in order.
- `getAllLoadedScenes()` (method, since 0.4.0): Returns the list of loaded scenes. (in load order, same as get_all_loaded_scenes in the Rust version)
  - returns Scene[]: List of loaded scenes. (the array the engine holds, do not modify it)

  Example: The scene passed to run is in the list

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  console.log(engine.getAllLoadedScenes().length);
  ```

- `isPageHidden()` (method, since 0.4.0): Whether the page is hidden. (Another tab, app switching)
  - returns boolean: True if the page is hidden.
- `addPageEventListener(pageEventListener)` (method, since 0.4.0): Adds a page event listener. ((pageEvent) => void, receives a PageEvent value)
  - `pageEventListener` Function: (pageEvent) => void. The same function is added only once.

  Example: Pause when the page is hidden

  ```js
  import { Engine, EngineConfiguration, Scene, PageEvent } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new Scene());
  const timeManager = engine.getTimeManager();
  const pageEventListener = (pageEvent) => {
  	if (pageEvent === PageEvent.hidden) {
  		timeManager.setTimeScale(0);
  	}
  	else if (pageEvent === PageEvent.visible) {
  		timeManager.setTimeScale(1);
  	}
  };
  engine.addPageEventListener(pageEventListener);
  const isPageHidden = engine.isPageHidden();
  console.log(isPageHidden);
  ```

- `removePageEventListener(pageEventListener)` (method, since 0.4.0): Removes a page event listener.
  - `pageEventListener` Function: A listener added before. (does nothing if not found)
- `addGraphicContextEventListener(graphicContextEventListener)` (method, since 0.4.0): Adds a graphic context event listener. ((graphicContextEvent) => void, receives a GraphicContextEvent value)
  - `graphicContextEventListener` Function: (graphicContextEvent) => void. The same function is added only once.

  Example: Rebuilding the game's GL objects when the context is restored

  ```js
  import { Engine, EngineConfiguration, Scene, GraphicContextEvent } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  let isRebuildNeeded = false;
  engine.addGraphicContextEventListener((graphicContextEvent) => {
  	if (graphicContextEvent === GraphicContextEvent.restored) {
  		isRebuildNeeded = true;
  	}
  });
  console.log(isRebuildNeeded);
  ```

- `removeGraphicContextEventListener(graphicContextEventListener)` (method, since 0.4.0): Removes a graphic context event listener.
  - `graphicContextEventListener` Function: A listener added before. (does nothing if not found)

  Example: Removing an added listener

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  const graphicContextEventListener = (graphicContextEvent) => {
  	console.log(graphicContextEvent);
  };
  engine.addGraphicContextEventListener(graphicContextEventListener);
  engine.removeGraphicContextEventListener(graphicContextEventListener);
  ```

- `addGraphicErrorListener(graphicErrorListener)` (method, since 0.4.0): Adds a graphic error listener. (({ kind, name, error }) => void, kind is a GraphicErrorKind value)
  - `graphicErrorListener` Function: ({ kind, name, error }) => void. The same function is added only once.

  Example: Recording shader build failures

  ```js
  import { Engine, EngineConfiguration, Scene, GraphicErrorKind } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  const failedNameList = [];
  engine.addGraphicErrorListener((graphicError) => {
  	if (graphicError.kind === GraphicErrorKind.shaderBuildFailed) {
  		failedNameList.push(graphicError.name);
  	}
  });
  console.log(failedNameList.length);
  ```

- `removeGraphicErrorListener(graphicErrorListener)` (method, since 0.4.0): Removes a graphic error listener.
  - `graphicErrorListener` Function: A listener added before. (does nothing if not found)

  Example: Removing an added error listener

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  const graphicErrorListener = (graphicError) => {
  	console.log(graphicError.kind);
  };
  engine.addGraphicErrorListener(graphicErrorListener);
  engine.removeGraphicErrorListener(graphicErrorListener);
  ```

- `dispatchGraphicError(graphicError)` (method, since 0.4.0): Notifies a graphic error. (Passes it to the listeners on the spot, a listener's exception is reported and it moves on to the next)
  - `graphicError` object: { kind: a GraphicErrorKind value, name: the name of what could not be built, error: the thrown error }
- `dispatchGraphicContextEvent(graphicContextEvent)` (method, since 0.4.0): Notifies a graphic context event. (Passes it to the listeners on the spot, a listener's exception is reported and it moves on to the next)
  - `graphicContextEvent` string: A GraphicContextEvent value.
- `enableGpuMemoryTracking()` (method, since 0.4.0): Turns on GPU memory tracking. (For development, same as Graphic.enableGpuMemoryTracking)

  Example: Turning on GPU memory tracking

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  engine.enableGpuMemoryTracking();
  console.log(engine.isGpuMemoryTrackingEnabled());
  ```

- `isGpuMemoryTrackingEnabled()` (method, since 0.4.0): Whether GPU memory tracking is on.
  - returns boolean: true if on.

  Example: Reading whether GPU memory tracking is on

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  console.log(engine.isGpuMemoryTrackingEnabled());
  ```

- `readGpuMemoryUsage()` (method, since 0.4.0): Reads GPU memory. (For development, same as Graphic.readGpuMemoryUsage)
  - returns { totalBytes: number, canvasBytes: number, kindTable: object, ownerList: Array<{ owner: string, kind: string, count: number, bytes: number }> }: Total (including the canvas share), canvas share, per-kind { count, bytes }, per-owner shares (largest first).

  Example: Reading GPU memory by kind

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.trackGpuMemory = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new Scene());
  const usage = engine.readGpuMemoryUsage();
  console.log(usage.kindTable.texture.bytes, usage.kindTable.renderbuffer.bytes, usage.kindTable.buffer.bytes);
  ```

- `dispatchPageEvent(pageEvent)` (method, since 0.4.0): Notifies a page event. (Records the hidden state and passes it to the listeners on the spot, a listener's exception is reported and it moves on to the next)
  - `pageEvent` string: A PageEvent value.
- `requestFrameCapture(frameNumber)` (method, since 0.4.0): Requests a screen capture for verification. (After that frame is fully drawn, passes the canvas as a PNG data URL)
  - If that frame number has already passed, captures this frame (the next frame if called between frames).
  - Can also be set via the URL query. (?capture=120,240 saves those frames as downloads, captureName is the file name ("{frame}" is the number), captureExit=1 calls exitApplication after the last capture)
    Capture mode set via the URL query advances time by 1/60 s per frame for deterministic captures. (real time and the maximum FPS limit are not used, same as the Rust edition VANILLA_CAPTURE_*)
  - `frameNumber` number: Frame number to capture. (the fraction is dropped; if already past, the current frame)
  - returns Promise<string>: PNG data URL.

  Example: Get frame 30 as a PNG

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new Scene());
  const capturePromise = engine.requestFrameCapture(30);
  capturePromise.then((dataUrl) => {
  	console.log(dataUrl.length);
  });
  ```

- `captureFrameIfRequested()` (method, since 0.4.0): Passes the canvas as PNG if it is a requested frame. (Called at frame end, while the drawing remains on the canvas)
- `requestFrameCapturesFromUrl()` (method, since 0.4.0): Sets up screen capture requests from the URL query. (capture, captureName, captureExit)
- `static getEngine()` (static, since 0.2.0): Returns the global instance.
  - returns Engine: The most recently created engine. (undefined if none was created)

## PageEvent (enum)

Page event. (Passed to listeners by the engine, addPageEventListener)

- `hidden` = `hidden`: The page became hidden. (Another tab, app switching)
- `visible` = `visible`: The page became visible again.
- `blurred` = `blurred`: The window lost focus. (blur)
- `focused` = `focused`: The window gained focus. (focus)
- `pointerDown` = `pointerDown`: The window was pressed. (pointerdown, once pressed the window has focus even without a focus notification)

## GraphicContextEvent (enum)

Graphic context event. (Passed to listeners by the engine, addGraphicContextEventListener)

- `lost` = `lost`: The WebGL context was lost. (Out of GPU memory, driver reset, or reclaimed in the background. While lost, the engine does not draw and only updates scenes)
- `restored` = `restored`: The context was restored and the engine rebuilt its base resources. (GL objects the game made and 3D renderers and render targets are dead, rebuild them now)

## GraphicErrorKind (enum)

Graphic error kinds. (The kind of the { kind, name, error } the engine passes to graphic error listeners, addGraphicErrorListener)

- `shaderBuildFailed` = `shaderBuildFailed`: A shader program could not be built. (A compile or link failure, the same program is neither reported again nor rebuilt. A failure caused by losing the context is not reported)
