# core/engine (vanilla-engine 0.4.0)

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

Engine.
- The original grabs a canvas and runs frames with request_animation_frame.
  In the Rust version the platform layer (crate::platform) handles the window, GL context, input events and presenting the screen,
  and EngineRunner here runs only the scenes and frame flow without knowing the platform. (desktop: platform/desktop.rs, web: platform/web.rs)
- Scenes are passed &Engine. Scenes take the managers (time, view, input) from it. Places that do not receive the engine take the global engine with Engine::get_engine(), like the original Engine.getEngine(). (core/globalengine.rs)
- The Graphic is handed over through attach_graphic after the platform creates the GL context and is held by the engine. Like the original getGraphic, it is taken with get_graphic and get_graphic_mut in any scene hook.
  The scene's draw family takes the graphic argument as before. That argument is the engine's graphic taken out for a moment with Option::take and passed in. (to pass &Engine and &mut Graphic together
  the graphic has to be outside the engine, so meanwhile engine.get_graphic() is None and the graphic argument is that graphic. with_graphic is the same. Neither RefCell nor unsafe is used)
- As in the original, the audio manager is created and held at construction. The AudioContext (sound device) is created on first use. There is no per-frame audio work.
  On the web the platform calls resume_on_user_gesture on click / touchstart / keydown, and resume on focus / visibilitychange.
- The original SceneManager.getAllLoadedScenes is get_all_loaded_scenes, which returns handles (SceneId) instead of scene objects. (while each scene runs with &Engine, other scenes cannot be borrowed)
- As in the original, loading a scene fits the root to the view size (between create and load), and even after the tracked assets have all finished, shows the loading screen 0.3 seconds longer and calls initialize.
- Text input focus (is_text_input_focused) looks at the document focus as in the original, and desktop, which has no document, looks at the focus of the engine input field.
- Unloading a single scene (unload_scene) stands in for the original SceneManager.unloadScene. The original refers to it by the scene object, the Rust version by the SceneId returned by load_scene,
  and like unload_all_scenes it unloads after the current frame ends. A scene not yet created (loaded in the same frame) is removed without calling create or destroy.
- Page events (PageEvent): in the original each module attaches listeners to document / window. In the Rust version the platform notifies the engine,
  and the engine passes it on the spot to the listeners received through add_page_event_listener. (SoundSystem receives occlusion and focus through this)
  Web: visibilitychange (Hidden, Visible), blur (Blurred), focus (Focused), pointerdown (PointerDown).
  Desktop: window occlusion (Occluded, reported by macOS and X11), minimization (how Windows reports it), app suspension (mobile) and Wayland frame callbacks not arriving for more than 3 seconds are Hidden; also focus, and mouse button and finger presses.
- Page restore hooks: as in the original setupAllDocumentEvents, wakes the sound again, clears input, then calls each scene.
  Web: visible of visibilitychange → on_page_visibility_restored, document resume and pageshow (persisted) → on_page_process_restored.
  pageshow does the same recovery as resume. (the original called the undefined dispatchPageProcessRestored and threw, which was fixed the same way in the original too)
  Desktop: on_page_visibility_restored when window occlusion ends, on_page_process_restored when the app is resumed after being suspended.
  (winit on Windows, Mac and Linux does not send suspended, so on_page_process_restored is not called on desktop)
- async/await: the engine contains a single-threaded executor (core/task.rs). spawn_task and spawn_scene_task, like original async functions, run at the call site
  up to the first await, and the remaining tasks are polled once per frame before the scenes' tick, only those that were woken. Engine functions that return a Promise in the original
  also have a form that can be awaited. (load_scene_async, unload_scene_async, unload_all_scenes_async, read_clipboard_text_async, request_frame_capture_async,
  and alert_async, confirm_async, prompt_async (the original engine.alertAsync and the others). While a question dialog is open, tasks are not polled either, as in the original)
- Unloading a scene calls finalize and unload like the original SceneManager.unloadScene, and waits for the tasks unload tracked with track_task to finish.
  (meanwhile it stays in the list and receives tick and draw, as in the original) When done it is removed from the list, and if the scene still has tasks, like the original Promise chain
  the scene value is kept alive until they all finish. (it receives no tick or draw, and SceneContext::with gives that scene) A scene unloaded while loading, like the original loadScene,
  still receives initialize once loading finishes. When everything is done, destroy is called and it is dropped.

Every frame (update_engine):
1. graphic.apply_settings()      # viewport/projection update + state reset + clear screen
2. time_manager.update()         # compute time_delta
3. input_manager.tick()
4. Poll woken tasks (begin_poll_frame, poll_woken_tasks and unload finishing until the woken queue is empty)
5. For each scene tick → pre_draw → draw → post_draw (→ draw_gizmos)
6. Stats output (optional) → clear one-shot input flags (including finishing the text input line) → flush batches → (screen capture for verification)
The platform presents the screen after update_engine.

## EngineConfiguration (struct) (Default)

Engine configuration.
- Change only the fields you need from the defaults of EngineConfiguration::new() and pass it to Engine::new.

Example: Set the reference resolution, view scale mode and asset folder

```rust
use std::path::PathBuf;
use vanilla::{Engine, EngineConfiguration, Vector2, ViewScaleMode};

let mut engine_configuration = EngineConfiguration::new();
engine_configuration.title = String::from("My Game");
engine_configuration.reference_resolution_size = Vector2::create(1920.0, 1080.0);
engine_configuration.view_scale_mode = ViewScaleMode::StretchShortExpandLong;
engine_configuration.asset_directory_paths = vec![PathBuf::from("examples/assets")];
engine_configuration.maximum_frame_per_second = 60.0;
engine_configuration.antialias = true;
assert!(engine_configuration.use_vertical_sync);
let engine = Engine::new(engine_configuration);
assert_eq!(engine.get_engine_configuration().title, "My Game");
assert_eq!(engine.resolve_asset_path("atlas/icons.png"), PathBuf::from("examples/assets/atlas/icons.png"));
```

- `pub reference_resolution_size: Vector2` (field, since 0.3.2): Reference resolution. (if the view scale mode is not none, scenes draw in this coordinate system)
  - returns Vector2
- `pub view_scale_mode: ViewScaleMode` (field, since 0.3.2): View scale mode.
  - returns ViewScaleMode
- `pub title: String` (field, since 0.3.2): Window title. (the desktop window title; on the web, if not empty and not the default, it is written to the document title (document.title) at startup as in the original)
  - returns String
- `pub window_size: Vector2` (field, since 0.3.2): Initial window size. (logical size, the reference resolution if 0)
  - returns Vector2
- `pub is_resizable: bool` (field, since 0.3.2): Whether the window can be resized.
  - returns bool
- `pub use_statistics: bool` (field, since 0.3.2): Shows FPS / draw calls at the top left of the screen.
  - returns bool
- `pub use_dev_tools: bool` (field, since 0.4.0): Whether GameSceneBase creates the developer tools (F2 hierarchy/inspector). (the original useDevTools, default true)
  - returns bool
- `pub maximum_frame_per_second: f64` (field, since 0.3.2): Maximum FPS. No limit if 0. (with vertical sync on, follows the display refresh rate)
  - returns f64
- `pub use_vertical_sync: bool` (field, since 0.3.2): Vertical sync.
  - returns bool
- `pub default_font_paths: Vec<PathBuf>` (field, since 0.3.2): Files of the default font chain. (desktop, if empty (default), looks up the names of the original SYSTEM_FONT_STRING in order among the operating system fonts and chains them)
  - If given, chains all readable files in order. Characters missing from an earlier font are drawn with a later font. (same as the original font list) For TTC the face is chosen by weight, and for variable fonts the weight becomes an axis value.
  - returns Vec<PathBuf>
- `pub default_bold_font_paths: Vec<PathBuf>` (field, since 0.3.2): Bold files of the default font chain. (the weight 700 face of the font in the same position as default_font_paths, desktop)
  - returns Vec<PathBuf>
- `pub fallback_font_paths: Vec<PathBuf>` (field, since 0.4.0): Fallback font candidate paths. (desktop, if empty (default), like the original browser, characters missing from every font are drawn with a fallback font chosen by the operating system. Mac CoreText, Windows DirectWrite, Linux fontconfig)
  - If given, without asking the operating system, when a character missing from every registered font appears, they are loaded from the front and used as fallback fonts.
    Color emoji fonts (files with color glyph tables) are loaded first when an emoji presentation character appears, and last when needed for other characters.
  - returns Vec<PathBuf>
- `pub asset_directory_paths: Vec<PathBuf>` (field, since 0.3.2): Asset folder candidates. (resolve_asset_path searches from the front)
  - returns Vec<PathBuf>
- `pub window_icon_path: String` (field, since 0.3.2): Window icon PNG. (relative path from the asset folder, the default icon if empty)
  - returns String
- `pub default_font_bytes: Option<Vec<u8>>` (field, since 0.3.2): Default font file contents. (used before the path candidates if present. On the web, which cannot read files, it is downloaded in advance and passed)
  - returns Option<Vec<u8>>
- `pub default_bold_font_bytes: Option<Vec<u8>>` (field, since 0.3.2): Bold default font file contents.
  - returns Option<Vec<u8>>
- `pub canvas_id: String` (field, since 0.3.2): Canvas id to draw to on the web. (created and attached to body if missing)
  - returns String
- `pub default_font_url: String` (field, since 0.3.2): Web default font URL. (the original defaultFontUrl. On the web, if default_font_bytes is absent, the font is fetched from here and used as the default font. Nothing is fetched if empty)
  - The default is an empty string. (the original default DOSGothic is not included) If no font is given at all, it draws with the browser system font as in the original.
  - To use a game font, give this URL, default_font_bytes, or a FontAsset.
  - Desktop does not use it and looks at default_font_paths (if empty, the system font chain found by the operating system).
  - returns String
- `pub resume_audio_on_touch_end: bool` (field, since 0.3.2): On the web, also treats touchend and pointerup as user gestures and resumes audio. (off by default, as in the original)
  - returns bool
- `pub asset_base_url: String` (field, since 0.3.2): Prefix for asset URLs on the web. (if empty, relative to the page. Desktop uses asset_directory_paths)
  - returns String
- `pub auto_resize_on_window_resize: bool` (field, since 0.4.0): Fits the canvas to the window when the window size changes. (off by default as in the original. When on, fits to the visualViewport size and applies the canvas ratio limit. When off, the web reads the canvas size set by the page)
  A desktop window is like a page whose canvas fills the window, so when off it stays at the window size, does not shrink for the on-screen keyboard, and does not apply the canvas ratio limit.
  - returns bool
- `pub preserve_drawing_buffer: bool` (field, since 0.4.0): Keeps what was drawn on the canvas even after the frame ends. (the original WebGL context option preserveDrawingBuffer, when on, the color is not cleared at the start of the frame, so it draws over the last frame's picture.
  The web passes it as a context option, desktop captures the finished frame and redraws it at the start of the next frame. platform/desktop/preserveddrawingbuffer.rs)
  - returns bool
- `pub antialias: bool` (field, since 0.4.0): Whether to turn on multisample antialiasing (MSAA) for the canvas (default framebuffer). (Original antialias, default true, decided at creation)
  - Turning it off makes the edges of shapes and 3D look jagged, but removes the per-frame resolve cost on high-resolution mobile devices.
  - On the web only on or off is chosen through the WebGL context attribute antialias, and the browser decides the sample count. On desktop, on means 4 samples and off picks a GL configuration without multisampling.
  - 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, measured on the same scene in the original)
  - Example: engine_configuration.antialias = false; (for a game that uses ToonPostProcess)
  - returns bool
- `pub track_gpu_memory: bool` (field, since 0.4.0): Whether to turn GPU memory tracking (for development) on from the start. (original trackGpuMemory, default false, decided at creation) When off, GL creation and sizing calls only look at one flag, so nothing runs per frame.
  - When on, the resources the engine creates first are counted too. To turn it on later, use Engine::enable_gpu_memory_tracking, which counts what is created after it.
  - Example: engine_configuration.track_gpu_memory = true; (when profiling)
  - returns bool
- `pub ignore_virtual_keyboard_resize: bool` (field, since 0.4.0): On-screen keyboard: while a text input is focused, keeps the size as is if the width is the same and only the height shrank. (with auto_resize_on_window_resize,
  on desktop the touch keyboard shrinks the visualViewport as in Chrome on Windows. On Mac and Linux it does not shrink, as in Chrome)
  - returns bool
- `pub max_canvas_aspect_ratio: f64` (field, since 0.4.0): Upper limit of the canvas aspect ratio. (if the window is more elongated than that, the canvas is shrunk and centered in the window, no limit if 0)
  - returns f64
- `pub rebake_text_on_font_load: bool` (field, since 0.4.0): Whether, when a font arrives late, to discard only the text baked with that font that falls within the font's character range so it is rebaked. (the original rebakeTextOnFontLoad, off by default as in the original)
  When off, text baked with another font before the download stays as is until it is pushed out of the cache. (turned on by projects that download font pieces split by character range as needed)
  - returns bool
- `pub document_language: String` (field, since 0.4.0): Document language. (in place of html lang in the web version's index.html, Document::get_language. If empty, an empty string on desktop and as written by the page on the web)
  - returns String
- `pub document_meta_list: Vec<(String, String)>` (field, since 0.4.0): Document meta. (a list of (name, content), in place of the meta in the head of the web version's index.html. Document::get_meta_content, BuildInfo reads build-version)
  - Desktop release builds put here the version the web version writes in index.html. (such as reading build.rs's rustc-env with env!) On the web it is also written to the document if not empty.
  - returns Vec<(String, String)>
- `pub color_space: ColorSpace` (field, since 0.4.0): 3D color space. (original colorSpace, default Gamma, fixed at creation. With Linear, the toon renderer, post process, screen outline and GLB readers compute light in linear space, see the colorspace.rs header)
  - 2D (Graphic's 2D batches, text, UI) is composited in gamma space either way.
  - returns ColorSpace
- `pub fn new() -> EngineConfiguration` (constructor, since 0.3.2): Constructor.
  - returns EngineConfiguration: Default configuration. (reference resolution 1280x720, StretchShort, title VanillaEngine, window size 0 (reference resolution), resizing on, vertical sync on, maximum FPS 0 (unlimited), developer tools on, canvas id mainCanvas, antialiasing on, everything else off or empty)

## PageEventListener (type)

Page event listener. (the engine holds it by weak reference, so dropping the listener stops it from being called)

```rust
pub type PageEventListener = Rc<RefCell<dyn FnMut(PageEvent)>>
```

## GraphicContextEventListener (type)

Graphic context event listener. (The engine holds it by a weak reference, dropping the listener stops further calls)

```rust
pub type GraphicContextEventListener = Rc<RefCell<dyn FnMut(GraphicContextEvent)>>
```

## GraphicError (struct) (Clone, Debug, PartialEq, Eq)

Graphic error. (The original's { kind, name, error })

Example: Creating a graphics error and reading its kind and name

```rust
use vanilla::{GraphicError, GraphicErrorKind};

let error = GraphicError {
	kind: GraphicErrorKind::ShaderBuildFailed,
	name: String::from("ScreenEffect.blur"),
	error: String::from("link failed"),
};
assert_eq!(error.kind, GraphicErrorKind::ShaderBuildFailed);
assert_eq!(error.name, "ScreenEffect.blur");
```

- `pub kind: GraphicErrorKind` (field, since 0.4.0): Error kind.
  - returns GraphicErrorKind
- `pub name: String` (field, since 0.4.0): Name of what could not be built. ("ToonRenderer.material name" for the toon renderer, "ScreenEffect.pass name" for screen effects)
  - returns String
- `pub error: String` (field, since 0.4.0): Why it failed. (the shader info log)
  - returns String

## GraphicErrorListener (type)

Graphic error listener. (The engine holds it by a weak reference, dropping the listener stops further calls)

```rust
pub type GraphicErrorListener = Rc<RefCell<dyn FnMut(&GraphicError)>>
```

## FrameCaptureHandler (type)

Function that receives the verification screen capture. (PNG bytes of the fully drawn screen of that frame, a PNG data URL in the original)

```rust
pub type FrameCaptureHandler = Box<dyn FnOnce(&[u8])>
```

## Engine (struct)

Engine.
- Make it from a configuration and pass the first scene to run. Scene hooks receive &Engine and take out the managers (time, view, input, audio, cursor) and the graphic (get_graphic, on the desktop main thread right after Engine::new).

Example: Run the engine with a first scene (examples/quickstart.rs)

```rust
use vanilla::{Engine, EngineConfiguration, Scene, SceneBase, Vector2};

struct MainScene {
	scene_base: SceneBase,
}

impl Scene for MainScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}
}

let mut engine_configuration = EngineConfiguration::new();
engine_configuration.auto_resize_on_window_resize = true;
engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
let engine = Engine::new(engine_configuration);
let main_scene = MainScene {
	scene_base: SceneBase::new(),
};
if let Err(error) = engine.run(Box::new(main_scene)) {
	eprintln!("{}", error);
	std::process::exit(1);
}
```

Example: Make an engine before run and work with its managers and configuration (on the desktop main thread the hidden window and graphic already exist)

```rust
use vanilla::{Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
assert_eq!(engine.get_frame_number(), 1);
assert!(!engine.get_version_string().is_empty());
engine.get_time_manager_mut().set_time_scale(0.5);
assert_eq!(engine.get_time_manager().get_time_scale(), 0.5);
engine.set_maximum_frame_per_second(30.0);
assert_eq!(engine.get_maximum_frame_per_second(), 30.0);
assert_eq!(engine.get_canvas().is_some(), engine.get_graphic().is_some());
```

- `pub fn new(engine_configuration: EngineConfiguration) -> &'static Engine` (constructor, since 0.3.2): Creates the engine.
  - Makes the managers (time, view, input, cursor, audio) and sets the document language and meta from the configuration.
  - On the desktop main thread it also builds the graphic, like the original constructor. (It makes the event loop, a hidden window and the GL context, and run shows that window. If GL cannot be built or this is not the main thread, it is built when run opens the window) On the web it is built when run takes the canvas.
  - `engine_configuration` EngineConfiguration: Engine configuration. (owned by the engine, read with get_engine_configuration)
  - returns &'static Engine: A new engine. (frame number 1, no scenes. It is put in a place that lives until the program ends and given as &'static, and it becomes the global engine)
- `pub fn get_engine() -> Result<&'static crate::core::engine::Engine, crate::core::globalengine::EngineAccessError>` (static, since 0.4.0): The global engine. (the original static Engine.getEngine(), the last created engine)
  - The engine is created once and never removed. Engine::new puts it in a place that lives until the program ends, so this gives &'static Engine. (the same form as Unreal's GEngine and Godot's Engine singleton)
  - It is taken anywhere right after Engine::new: scene functions (load, tick, draw and so on), component tick and draw, widget callbacks, page event listeners, inside async tasks.
    It is the same engine as the engine argument a scene function receives.
  - All public engine functions are &self. (the fields they change use interior mutability) Borrowing the same manager again while holding what a manager's get_x_mut gave stops with a panic that names the function.
  - Called from a thread other than the one that created the engine it is Err(OtherThread), and if no engine was ever created it is Err(NotCreated).
  - returns Result<&'static crate::core::engine::Engine, crate::core::globalengine::EngineAccessError>: The taken engine, or the reason it could not be taken.

  Example: Taking the global engine in a function that does not receive the engine

  ```rust
  use vanilla::{Component, ComponentBase, ComponentContext, Engine, EngineConfiguration, NodeTree};
  
  fn read_frame_number() -> u64 {
  	let engine = Engine::get_engine().unwrap();
  	engine.get_frame_number()
  }
  
  struct FrameReader {
  	component_base: ComponentBase,
  	frame_number: u64,
  }
  
  #[vanilla::reflect]
  impl FrameReader {}
  
  #[vanilla::reflect]
  impl Component for FrameReader {
  	fn tick(&mut self, _context: &mut ComponentContext, _time_delta: f64) {
  		self.frame_number = read_frame_number();
  	}
  }
  
  let engine = Engine::new(EngineConfiguration::new());
  assert!(std::ptr::eq(Engine::get_engine().unwrap(), engine));
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let reader_id = node_tree.create_child(root_id, "reader");
  node_tree[reader_id].add_component(FrameReader {
  	component_base: ComponentBase::new(),
  	frame_number: 0,
  });
  node_tree.tick(engine, 0.016);
  let frame_number = node_tree[reader_id].get_component::<FrameReader>().unwrap().frame_number;
  assert_eq!(frame_number, engine.get_frame_number());
  ```

- `pub fn request_dev_tools_inspect(&self, node_id: crate::core::node::nodetree::NodeId)` (method, since 0.4.0): Requests inspecting a node with the developer tools. (in place of Inspect in Chrome's context menu. The DevTools of the scene holding the node opens and selects it on the next tick)
  - `node_id` crate::core::node::nodetree::NodeId: Node to inspect. (replaces a previously requested node)
- `pub fn alert(&self, message: &str) -> ModalDialogHandle` (method, since 0.4.0): Alert dialog. (in place of window.alert, the same as the original engine.alert, only OK. The handle finishes when confirmed)
  - Shows a dialog drawn by the engine and does not update the scene until it closes. (the same on the web and the desktop, core/modaldialog.rs)
  - `message` &str: Text to show in the dialog.
  - returns ModalDialogHandle: Question dialog handle. (finishes when confirmed)
- `pub fn confirm(&self, message: &str) -> ModalDialogHandle` (method, since 0.4.0): Confirm dialog. (in place of window.confirm, the same as the original engine.confirm, the handle's is_confirmed is the value of the original Promise)
  - `message` &str: Text to show in the dialog.
  - returns ModalDialogHandle: Question dialog handle. (finishes when answered with OK or Cancel)
- `pub fn prompt(&self, message: &str, default_value: &str) -> ModalDialogHandle` (method, since 0.4.0): Prompt dialog. (in place of window.prompt(message, default), the same as the original engine.prompt, the handle's get_prompt_text is the value of the original Promise, None when cancelled)
  - `message` &str: Text to show in the dialog.
  - `default_value` &str: Text to put in the input field at first. (it receives focus with everything selected)
  - returns ModalDialogHandle: Question dialog handle. (finishes when answered with OK or Cancel)
- `pub fn alert_async(&self, message: &str) -> Promise<()>` (method, since 0.4.0): A Promise that resolves when the alert dialog shown closes. (the original engine.alertAsync)
  - `message` &str: Text to show in the dialog.
  - returns Promise<()>: Promise that resolves when the dialog closes.
- `pub fn confirm_async(&self, message: &str) -> Promise<bool>` (method, since 0.4.0): A Promise that resolves when the confirm dialog shown is answered. (the original engine.confirmAsync)
  - `message` &str: Text to show in the dialog.
  - returns Promise<bool>: Promise that resolves when answered. (true for OK, false for Cancel)

  Example: Ask in an engine task and finish depending on the answer

  ```rust
  use vanilla::Engine;
  
  fn ask_exit(engine: &Engine) {
  	engine.spawn_task(|mut engine_context| async move {
  		let is_confirmed = engine_context.with(|engine| engine.confirm_async("Exit?")).await;
  		if is_confirmed {
  			engine_context.with(|engine| engine.exit_application());
  		}
  	});
  }
  ```

- `pub fn prompt_async(&self, message: &str, default_value: &str) -> Promise<Option<String>>` (method, since 0.4.0): A Promise that resolves when the prompt dialog shown is answered. (the original engine.promptAsync, None in place of the original null when cancelled)
  - `message` &str: Text to show in the dialog.
  - `default_value` &str: Text to put in the input field initially.
  - returns Promise<Option<String>>: Promise that resolves when answered. (the entered text for OK, None for Cancel)
- `pub fn is_modal_dialog_open(&self) -> bool` (method, since 0.4.0): Whether a question dialog is open. (the engine does not update the scene while it is open)
  - returns bool: true if a question dialog is open or waiting.
- `pub fn run(&'static self, scene: Box<dyn Scene>) -> Result<(), String>` (method, since 0.3.2): Start.
  - Desktop: does not return until the window is closed or exit_application is called.
  - Web: grabs the canvas and WebGL2, registers request_animation_frame, and returns right away.
  - `scene` Box<dyn Scene>: First scene. (loaded with load_scene)
  - returns Result<(), String>: Ok on normal exit. (on desktop when the window closes and the event loop ends, on the web right after registering the frame) Err(reason) if the platform fails, such as being unable to create the event loop, window or GL context.
- `pub fn load_scene(&self, mut scene: Box<dyn Scene>) -> SceneId` (method, since 0.3.2): Loads a scene. (added to the list after the current frame ends. Returns the handle to pass to unload_scene)
  - When added to the list, create is called, the root is fitted to the view size, and then load is called. initialize is called 0.3 seconds after the tracked assets and tasks have all finished.
  - `scene` Box<dyn Scene>: Scene to load. (owned by the engine)
  - returns SceneId: Handle of the scene. (numbered from 1)
- `pub fn unload_scene(&self, scene: impl Into<SceneId>)` (method, since 0.4.0): Unloads one scene. (after the current frame ends, calls finalize and unload, and removes it from the list when the tasks tracked by unload finish. Does nothing for an unknown handle)
  - Takes a handle (SceneId) or, as in the original, a scene (the common scene state &SceneBase).
  - If the scene still has tasks, the scene value is kept alive until they all finish, then destroy is called and it is dropped.
  - `scene` impl Into<SceneId>: Handle (SceneId) or common scene state (&SceneBase) of the scene to unload.

  Example: A scene unloading itself

  ```rust
  use vanilla::{Engine, Scene, SceneBase, Vector2};
  
  struct PopupScene {
  	scene_base: SceneBase,
  }
  
  impl Scene for PopupScene {
  	fn get_scene_base(&self) -> &SceneBase {
  		&self.scene_base
  	}
  
  	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
  		&mut self.scene_base
  	}
  
  	fn touch_release(&mut self, _view_input_position: Vector2) {
  		let engine = Engine::get_engine().unwrap();
  		engine.unload_scene(&self.scene_base);
  	}
  }
  ```

- `pub fn unload_all_scenes(&self)` (method, since 0.3.2): Unloads all scenes. (after the current frame ends, if called together with load_scene, unloads and then loads)
- `pub fn load_scene_async(&self, mut scene: Box<dyn Scene>) -> Promise<SceneId>` (method, since 0.4.0): Loads a scene. (the original await SceneManager.loadScene(scene), returns a Promise that resolves with the scene's handle once initialize finishes)
  - Loading is the same as load_scene. If the scene is unloaded before create in the same frame, it does not resolve. (if unloaded after create, it resolves after finishing initialize)
  - `scene` Box<dyn Scene>: Scene to load. (owned by the engine)
  - returns Promise<SceneId>: Promise that resolves with the scene's handle once initialize finishes.

  Example: Load the next scene and unload the current scene when it is ready

  ```rust
  use vanilla::{Engine, Scene, SceneId};
  
  fn change_scene(engine: &Engine, current_scene_id: SceneId, next_scene: Box<dyn Scene>) {
  	engine.spawn_task(move |mut engine_context| async move {
  		let next_scene_id = engine_context.with(|engine| engine.load_scene_async(next_scene)).await;
  		engine_context.with(|engine| engine.unload_scene_async(current_scene_id)).await;
  		println!("{:?}", next_scene_id);
  	});
  }
  ```

- `pub fn unload_scene_async(&self, scene: impl Into<SceneId>) -> Promise<()>` (method, since 0.4.0): Unloads one scene. (the original await SceneManager.unloadScene(scene), returns a Promise that resolves when unloading finishes. Resolves even for an unknown handle)
  - Calls finalize and unload at the end of the current frame, and resolves after removing it from the list once the tasks unload tracked with track_task have also finished.
  - `scene` impl Into<SceneId>: Handle (SceneId) or common scene state (&SceneBase) of the scene to unload.
  - returns Promise<()>: Promise that resolves when unloading finishes.
- `pub fn unload_all_scenes_async(&self) -> Promise<()>` (method, since 0.4.0): Unloads all scenes. (the original await SceneManager.unloadAllScenes(), returns a Promise that resolves when all scenes at that time have finished unloading)
  - returns Promise<()>: Promise that resolves when all scenes loaded at that time have finished unloading.
- `pub fn spawn_task<F, TaskFuture>(&self, task_function: F) -> TaskHandle where F: FnOnce(EngineContext) -> TaskFuture, TaskFuture: Future<Output = ()> + 'static,` (method, since 0.4.0): Spawns an engine task. (an async task living apart from scenes, borrows the engine inside the with of the EngineContext the task function receives)
  - Like calling an original async function, runs here up to the first await, and the rest runs in the frame's polling turn each time it is woken.
  - Use the returned handle to ask whether it finished, or await it.
  - `task_function` F: Function that takes an EngineContext and returns a future. (usually `|mut engine_context| async move { ... }`, the future need not be Send)
  - returns TaskHandle: Task handle. (an already finished handle if it finished in the first segment)

  Example: Runs at the spawn site up to the first await

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let task_handle = engine.spawn_task(|mut engine_context| async move {
  	engine_context.with(|engine| {
  		engine.set_maximum_frame_per_second(30.0);
  	});
  });
  assert!(task_handle.is_finished());
  assert_eq!(engine.get_maximum_frame_per_second(), 30.0);
  ```

- `pub fn spawn_scene_task<S, F, TaskFuture>(&self, scene: &mut S, task_function: F) -> TaskHandle where S: Scene + 'static, F: FnOnce(SceneContext<S>) -> TaskFuture, TaskFuture: Future<Output = ()> + 'static,` (method, since 0.4.0): Spawns a scene task. (an async task of that scene, borrows the scene (type S) and the engine inside the with of the SceneContext the task function receives)
  - This is where an original async function uses this. As in the original, runs here up to the first await, and the rest runs in the frame's polling turn each time it is woken.
    (with_graphic in the first segment also gives the engine's graphic. Spawned inside a drawing function, it is None because that function holds the graphic as its argument)
  - It keeps running even if the scene is unloaded, as in the original. (the scene value lives until the task finishes) For a scene before load_scene, only the first segment runs and it is dropped.
  - For a loading task, track it with the scene's track_task in load to delay initialize until it finishes. (tracking it in unload delays the end of unloading)
  - `scene` &mut S: Scene spawning the task. (usually self inside a hook)
  - `task_function` F: Function that takes a `SceneContext<S>` and returns a future. (usually `|mut scene_context| async move { ... }`)
  - returns TaskHandle: Task handle. (pass it to track_task or await it)

  Example: Wait for an asset in a scene task and put it in the scene

  ```rust
  use vanilla::{Engine, Scene, SceneBase, SceneContext};
  
  struct StageScene {
  	scene_base: SceneBase,
  	stage_bytes: Vec<u8>,
  }
  
  impl Scene for StageScene {
  	fn get_scene_base(&self) -> &SceneBase {
  		&self.scene_base
  	}
  
  	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
  		&mut self.scene_base
  	}
  
  	fn load(&mut self, engine: &Engine) {
  		let task_handle = engine.spawn_scene_task(self, |mut scene_context: SceneContext<StageScene>| async move {
  			let load_handle = scene_context.with(|_scene, engine| engine.request_asset_bytes("examples/assets/scenedocument.scene.json"));
  			let stage_bytes = load_handle.await.map(|bytes| bytes.to_vec()).unwrap_or_default();
  			scene_context.with(|scene, _engine| {
  				scene.stage_bytes = stage_bytes;
  			});
  		});
  		self.scene_base.track_task(&task_handle);
  	}
  }
  ```

- `pub fn spawn_deferred_task<F, TaskFuture>(&self, task_function: F) -> TaskHandle where F: FnOnce(EngineContext) -> TaskFuture, TaskFuture: Future<Output = ()> + 'static,` (method, since 0.4.0): Spawns an engine task for the next polling turn. (for places with only &Engine, like a component context. First runs in the next frame's polling turn)
  - `task_function` F: Function that takes an EngineContext and returns a future.
  - returns TaskHandle: Task handle. (a handle that is not finished before the next polling turn)

  Example: Does not run at the spawn site

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let task_handle = engine.spawn_deferred_task(|_engine_context| async move {});
  assert!(!task_handle.is_finished());
  ```

- `pub fn spawn_deferred_scene_task<S, F, TaskFuture>(&self, scene: &S, task_function: F) -> TaskHandle where S: Scene + 'static, F: FnOnce(SceneContext<S>) -> TaskFuture, TaskFuture: Future<Output = ()> + 'static,` (method, since 0.4.0): Spawns a scene task for the next polling turn. (for places with only &Engine and &scene, first runs in the next frame's polling turn)
  - If the scene is in neither the loaded scene list nor the kept-alive scene list at the next polling turn, the task is dropped.
  - `scene` &S: Scene spawning the task.
  - `task_function` F: Function that takes a `SceneContext<S>` and returns a future.
  - returns TaskHandle: Task handle. (a handle that is not finished before the next polling turn)
- `pub fn get_all_loaded_scenes(&self) -> Ref<'_, [SceneId]>` (method, since 0.4.0): Handles of all loaded scenes. (the original SceneManager.getAllLoadedScenes, in load order, scenes still loading included)
  - The original returns scene objects. The Rust version returns handles because while each scene runs with &Engine, other scenes cannot be borrowed.
    Scenes are included from when the load_scene frame ends and create is called, and unloaded scenes are removed.
  - returns Ref<'_, [SceneId]>: List of handles of loaded scenes. (in load order)
- `pub fn resolve_asset_path(&self, relative_path: &str) -> PathBuf` (method, since 0.3.2): Finds an asset path. (the first existing one among the configured asset folder candidates, relative to the first candidate if none)
  - `relative_path` &str: Path relative to the asset folder.
  - returns PathBuf: Path in the first candidate folder that has the file. (the path relative to the first candidate if found nowhere, the relative path as is if there are no candidates)
- `pub fn load_image(&self, relative_path: &str) -> Result<Rc<Image>, String>` (method, since 0.3.2): Loads an image asset. (the original new ImageAsset() + load(path); desktop loads it on the spot)
  - Also accepts "data:" URLs. (decoded by the URL's type)
  - On the web it is always Err, since it cannot load and decode on the spot. (as in the original, the browser decodes asynchronously; use ImageAsset::load or AssetLoader)
  - `relative_path` &str: Path relative to the asset folder, or a "data:" URL.
  - returns Result<Rc<Image>, String>: The loaded image. Err(reason) if the file cannot be read or decoded.

  Example: Load an atlas image from storage

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let image = engine.load_image("examples/assets/atlas/icons.png").unwrap();
  assert!(image.get_width() > 0);
  assert!(engine.load_image("examples/assets/missing.png").is_err());
  ```

- `pub fn request_asset_bytes(&self, relative_path: &str) -> AssetLoadHandle` (method, since 0.3.2): Requests asset bytes. (called by the assets' load)
  - Desktop: finds the file among the asset folder candidates, reads it on the spot and finishes.
  - Web: fetches asset_base_url + the relative path and finishes when received. (frames keep running meanwhile)
  - "data:" URLs are decoded from the URL itself like the original fetch. (desktop decodes it on the spot with base/dataurl.rs and uses its type as the response type, the web fetches without prefixing the base URL)
  - `relative_path` &str: Path relative to the asset folder, or a "data:" URL.
  - returns AssetLoadHandle: Load handle. (holds the bytes when loaded, the reason on failure. Can be awaited)

  Example: Load a file and a data: URL (on desktop it finishes on the spot)

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let load_handle = engine.request_asset_bytes("examples/assets/atlas/icons.json");
  assert!(load_handle.is_loaded());
  let data_load_handle = engine.request_asset_bytes("data:text/plain,hello");
  assert_eq!(data_load_handle.get_bytes().unwrap().as_slice(), b"hello");
  assert!(engine.request_asset_bytes("examples/assets/missing.json").is_failed());
  ```

- `pub fn request_asset_bytes_with_cache(&self, relative_path: &str, is_no_cache: bool) -> AssetLoadHandle` (method, since 0.4.0): Requests asset bytes. (with is_no_cache, the web skips the browser cache and checks again, the original TextAsset.setNoCache)
  - `relative_path` &str: Path relative to the asset folder, or a "data:" URL.
  - `is_no_cache` bool: If true, the web does not use the browser cache. (desktop always reads the file, so it does not matter)
  - returns AssetLoadHandle: Load handle.
- `pub fn request_asset_bytes_into(&self, relative_path: &str, load_handle: &AssetLoadHandle)` (method, since 0.4.0): Requests asset bytes. (finishes an already created load handle. Used by AssetLoader to fill handles it handed out in advance when their turn comes)
  - `relative_path` &str: Path relative to the asset folder, or a "data:" URL.
  - `load_handle` &AssetLoadHandle: Load handle to finish. (created with AssetLoadHandle::create_pending)

  Example: Fill a handle handed out in advance later

  ```rust
  use vanilla::{AssetLoadHandle, Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let load_handle = AssetLoadHandle::create_pending("examples/assets/atlas/icons.json");
  assert!(!load_handle.is_finished());
  engine.request_asset_bytes_into("examples/assets/atlas/icons.json", &load_handle);
  assert!(load_handle.is_loaded());
  ```

- `pub fn register_font_when_loaded(&self, family: &str, is_bold: bool, load_handle: AssetLoadHandle) -> FontLoadHandle` (method, since 0.3.2): Asks to register font bytes under a name when they arrive. (called by FontAsset. Registration happens at frame start, returns a handle that finishes when loaded)
  - `family` &str: Font name. (the name used when drawing text)
  - `is_bold` bool: If true, loads it as the weight 700 face, if false as the 400 face.
  - `load_handle` AssetLoadHandle: Load handle of the font file bytes.
  - returns FontLoadHandle: Handle that finishes when added to the font list (or when downloading or adding fails).
- `pub fn register_font_face_when_loaded(&self, family: &str, mut font_face_descriptors: FontFaceDescriptors, load_handle: AssetLoadHandle) -> FontLoadHandle` (method, since 0.4.0): Asks to add font face bytes under a name with the descriptors (weight, style, character range) when they arrive. (the original new FontFace(family, url, descriptors) + document.fonts.add)
  - If the descriptors' source_key is empty, the load handle's path is used.
  - The returned handle finishes when added to the font list (or when downloading or adding fails). (in place of the original await fontFace.load() and document.fonts.add)
  - `family` &str: Font name.
  - `font_face_descriptors` FontFaceDescriptors: Weight, style, character range, face key. (the load handle's path if the key is empty)
  - `load_handle` AssetLoadHandle: Load handle of the font file bytes.
  - returns FontLoadHandle: Handle that finishes when added to the font list (or when downloading or adding fails).
- `pub fn unregister_font_face(&self, family: &str, source_key: &str)` (method, since 0.4.0): Asks to remove a font face. (the original document.fonts.delete, the key is the source_key at registration or the path)
  - Registrations of the same face still waiting for bytes are removed immediately. (names are case-insensitive) Removal happens at the start of the next frame.
  - `family` &str: Font name.
  - `source_key` &str: Key of the face to remove.
- `pub fn set_font_face_order(&self, family: &str, source_key_list: Vec<String>)` (method, since 0.4.0): Asks to set the face order for a name. (a list of face keys, later ones draw first, TextStringTextureCache.set_font_face_order)
  - `family` &str: Font name.
  - `source_key_list` Vec<String>: List of face keys. (later faces draw first, applied at the start of the next frame)
- `pub fn clear_text_cache(&self)` (method, since 0.4.0): Asks to discard all baked text. (the original textStringTextureCache.clear, at the start of the next frame)
- `pub fn get_pending_font_face_count(&self) -> usize` (method, since 0.4.0): Number of font faces whose bytes have not arrived yet. (checked while UI fonts are waiting)
  - returns usize: Number of font faces waiting for registration. (those waiting for bytes and those to be added at the start of the next frame)
- `pub fn load_audio_asset(&self, relative_path: &str) -> Result<Rc<AudioAsset>, String>` (method, since 0.3.2): Loads an audio asset. (the original new AudioAsset() + load(path), a path relative to the asset folder or a "data:" URL)
  - Desktop: reads and decodes on the spot. Err on failure. A data: URL is decoded by sniffing the bytes as content without looking at the type. (same as the original decodeAudioData)
  - Web: starts fetching and decoding and returns the asset right away. When done, is_loaded() becomes true. (failure in get_load_error())
  - `relative_path` &str: Path relative to the asset folder, or a "data:" URL.
  - returns Result<Rc<AudioAsset>, String>: Audio asset. On desktop, Err(reason) if reading or decoding fails. (on the web only failures on the spot are Err)

  Example: Load a sound file and check its length (desktop decodes on the spot)

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let audio_asset = engine.load_audio_asset("tests/assets/audio/wav_s16_stereo.wav").unwrap();
  assert!(audio_asset.is_loaded());
  assert!(audio_asset.get_duration() > 0.0);
  assert!(engine.load_audio_asset("tests/assets/audio/missing.wav").is_err());
  ```

- `pub fn resolve_audio_asset_path(&self, relative_path: &str) -> PathBuf` (method, since 0.4.0): Resolves an audio asset path. (desktop: the path found among the asset folder candidates, web: asset_base_url + the relative path, data: URLs on the web as is)
  - `relative_path` &str: Path relative to the asset folder.
  - returns PathBuf: Path to load. (the web holds the URL in path form)
- `pub fn resume(&self)` (method, since 0.3.2): Resumes the audio context. (for returns that are not user gestures, such as focus and visibilitychange. Does nothing before a gesture)
- `pub fn resume_on_user_gesture(&self)` (method, since 0.3.2): User gesture (click / touch / keydown) handler.
  Notifies AudioManager that a user gesture occurred and tries to resume the context.
- `pub fn exit_application(&self)` (method, since 0.3.2): Requests exit. (the original exitApplication, desktop closes the window after the current frame, the web tries Capacitor App.exitApp or window.close as in the original and stops the frames)
- `pub fn open_url(&self, url: &str) -> bool` (method, since 0.4.0): Opens an outside URL. (original Engine.openUrl)
  - On the web it opens a new tab with window.open(url, "_blank", "noopener"). 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.
  - On desktop it opens with the OS default program. (macOS `open`, Windows ShellExecuteW, Linux xdg-open)
  - Only http, https, mailto and tel can be opened. Other forms (such as javascript: and file:) are not opened and return false.
  - `url` &str: URL to open. (http, https, mailto, tel)
  - returns bool: True if the open was handed to the OS or browser. (false if the URL is not allowed or could not be handed over)

  Example: A form that cannot be opened returns false

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  assert!(!engine.open_url("javascript:alert(1)"));
  assert!(!engine.open_url("file:///etc/passwd"));
  ```

- `pub fn read_local_time(&self, minute_offset: f64) -> platform::LocalTime` (method, since 0.4.0): Read the local time. (same as the original Engine.readLocalTime, the calendar time of now plus a minute offset in this machine's time zone)
  - On the web it reads with Date, on Mac and Linux with localtime_r, and on Windows with SystemTimeToTzSpecificLocalTime. Daylight saving time at the shifted moment is applied. (same as the original's new Date(Date.now() + offset))
  - `minute_offset` f64: Minutes to add to now. (negative is the past, 0 is now)
  - returns platform::LocalTime: Local time. (year, month 1 to 12, day, hour, minute, second, weekday with 0 as Sunday)

  Example: Two hours ahead differs from two hours behind

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let now = engine.read_local_time(0.0);
  assert!(now.hour < 24 && now.minute < 60 && (1..=12).contains(&now.month));
  let later = engine.read_local_time(120.0);
  let earlier = engine.read_local_time(-120.0);
  assert_ne!((later.day, later.hour), (earlier.day, earlier.hour));
  ```

- `pub fn is_exit_requested(&self) -> bool` (method, since 0.3.2): Whether exit was requested.
  - returns bool: true if exit_application was called.
- `pub fn set_visible_cursor(&self, is_visible: bool)` (method, since 0.3.2): Sets cursor visibility.
  - `is_visible` bool: If false, hides the mouse cursor over the window or canvas. (does nothing before the platform attaches)
- `pub fn resize(&self)` (method, since 0.4.0): Refits the resolution. (the original resize, calling it after changing settings makes the platform recompute the canvas and view area at the start of the next frame and call resize on each scene)
- `pub fn get_canvas(&self) -> Option<Ref<'_, PlatformWindow>>` (method, since 0.4.0): Canvas. (the original getCanvas, the canvas element being drawn on the web, the window on desktop, None before the platform attaches)
  - returns Option<Ref<'_, PlatformWindow>>: Platform window handle. (On the desktop main thread the window Engine::new built hidden; elsewhere None until run takes the window or canvas)
- `pub fn enable_gpu_memory_tracking(&self)` (method, since 0.4.0): Turns GPU memory tracking on. (original Engine.enableGpuMemoryTracking, for development)
  - Counts the textures, renderbuffers and buffers created after it is turned on. Does nothing if it is already on. To count from the start, use EngineConfiguration::track_gpu_memory.

  Example: Turn GPU memory tracking on

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  engine.enable_gpu_memory_tracking();
  assert!(engine.is_gpu_memory_tracking_enabled());
  ```

- `pub fn is_gpu_memory_tracking_enabled(&self) -> bool` (method, since 0.4.0): Whether GPU memory tracking is on. (original Engine.isGpuMemoryTrackingEnabled)
  - returns bool: true if enabled.

  Example: Off by default

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  assert!(!engine.is_gpu_memory_tracking_enabled());
  ```

- `pub fn read_gpu_memory_usage(&self) -> Option<crate::core::gpumemorytracker::GpuMemoryUsage>` (method, since 0.4.0): Reads GPU memory. (original Engine.readGpuMemoryUsage, for development, the same as Graphic::read_gpu_memory_usage)
  - If tracking is off, this call turns it on and counts what is created after it. None if there is no graphic yet.
  - returns Option<crate::core::gpumemorytracker::GpuMemoryUsage>: The total, the canvas share, and the shares by kind and by owner.

  Example: Read the total when there is a graphic

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  if let Some(usage) = engine.read_gpu_memory_usage() {
  	assert_eq!(usage.total_bytes, usage.canvas_bytes + usage.kind_table.values().map(|kind_usage| kind_usage.bytes).sum::<u64>());
  }
  assert!(engine.is_gpu_memory_tracking_enabled() || engine.get_graphic().is_none());
  ```

- `pub fn get_graphic(&self) -> Option<Ref<'_, Graphic>>` (method, since 0.4.0): Graphic. (The original getGraphic; build GL resources (textures, render targets, shader programs, toon renderers and the like) in a scene's load, initialize, tick or a component's tick)
  - Like the original constructor, on the desktop Engine::new builds a hidden window and GL context on the main thread so it is there right away. (run shows that window)
    On machines that cannot build GL (such as CI without a display) or off the main thread (unit tests) it is None until run opens the window. On the web it is None until run takes the canvas.
  - Inside draw functions (pre_draw, draw, post_draw, draw_on_load, draw_gizmos) and the closure of with_graphic it is None because the graphic is lent as an argument. (There, the graphic received as an argument is this graphic)
  - returns Option<Ref<'_, Graphic>>: The engine's graphic. (None before it is attached or while it is lent as an argument)

  Example: Building a shader program when the scene is created

  ```rust
  use vanilla::{Engine, Scene, SceneBase, ShaderProgram};
  
  const VERTEX_SHADER_SOURCE: &str = "#version 300 es
  in vec2 vertexPosition;
  void main() {
  	gl_Position = vec4(vertexPosition, 0.0, 1.0);
  }
  ";
  
  const FRAGMENT_SHADER_SOURCE: &str = "#version 300 es
  precision highp float;
  out vec4 outputColor;
  void main() {
  	outputColor = vec4(1.0);
  }
  ";
  
  struct MainScene {
  	scene_base: SceneBase,
  	shader_program: Option<ShaderProgram>,
  }
  
  impl Scene for MainScene {
  	fn get_scene_base(&self) -> &SceneBase {
  		&self.scene_base
  	}
  
  	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
  		&mut self.scene_base
  	}
  
  	fn load(&mut self, engine: &Engine) {
  		if let Some(graphic) = engine.get_graphic() {
  			self.shader_program = ShaderProgram::new(graphic.get_gl(), VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE).ok();
  		}
  	}
  }
  ```

  Example: Build a texture right after making the engine, before run (desktop; None on machines that cannot build GL)

  ```rust
  use vanilla::{Engine, EngineConfiguration, RenderTarget};
  
  let engine = Engine::new(EngineConfiguration::new());
  if let Some(graphic) = engine.get_graphic() {
  	let render_target = RenderTarget::new(graphic.get_gl(), 64, 64, false, None);
  	assert!(render_target.is_ok());
  }
  ```

- `pub fn get_graphic_mut(&self) -> Option<RefMut<'_, Graphic>>` (method, since 0.4.0): Graphic. (mutable, changes settings such as the text cache, forced gizmo display and batching outside drawing)
  - Like get_graphic, None before it is attached and while it is lent as an argument.
  - returns Option<RefMut<'_, Graphic>>: The engine's graphic. (None before it is attached or while it is lent as an argument)

  Example: Showing all gizmos from the scene's tick

  ```rust
  use vanilla::{Engine, KeyCode, Scene, SceneBase};
  
  struct MainScene {
  	scene_base: SceneBase,
  }
  
  impl Scene for MainScene {
  	fn get_scene_base(&self) -> &SceneBase {
  		&self.scene_base
  	}
  
  	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
  		&mut self.scene_base
  	}
  
  	fn tick(&mut self, time_delta: f64) {
  		let engine = Engine::get_engine().unwrap();
  		self.scene_base.tick(time_delta);
  		let is_key_g = engine.get_input_manager().is_key_pressed(KeyCode::G);
  		if let Some(mut graphic) = engine.get_graphic_mut() {
  			graphic.set_force_gizmos_visible(is_key_g);
  		}
  	}
  }
  ```

- `pub fn with_graphic<R>(&self, graphic_function: impl FnOnce(&Engine, &mut Graphic) -> R) -> Option<R>` (method, since 0.4.0): Borrows the engine and the graphic together. (when calling, outside drawing, a function that takes both the graphic and the engine as &mut)
  - Takes the graphic out of the engine for a moment (Option::take), passes it to the closure, and puts it back when the closure ends. It is the same path the engine uses to pass the graphic to drawing functions.
    Inside the closure engine.get_graphic() is None, and you use the graphic argument.
  - `graphic_function` impl FnOnce(&Engine, &mut Graphic) -> R: Closure that works with the engine and graphic.
  - returns Option<R>: The value the closure returned. (None without calling the closure if there is no graphic or while it is already lent)

  Example: Call the closure only when there is a graphic (on the desktop right after Engine::new; None on machines that cannot build GL)

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let has_graphic = engine.get_graphic().is_some();
  let result = engine.with_graphic(|_engine, graphic| graphic.get_global_alpha());
  assert_eq!(result.is_some(), has_graphic);
  ```

  Example: Using the engine's clock and the graphic together in the scene's initialize

  ```rust
  use vanilla::{Engine, Scene, SceneBase};
  
  struct MainScene {
  	scene_base: SceneBase,
  }
  
  impl Scene for MainScene {
  	fn get_scene_base(&self) -> &SceneBase {
  		&self.scene_base
  	}
  
  	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
  		&mut self.scene_base
  	}
  
  	fn initialize(&mut self, engine: &Engine) {
  		engine.with_graphic(|engine, graphic| {
  			engine.get_time_manager_mut().set_time_scale(1.0);
  			graphic.set_force_gizmos_visible(false);
  		});
  	}
  }
  ```

- `pub fn is_text_input_focused(&self) -> bool` (method, since 0.4.0): Whether a text input is focused. (the original isTextInputFocused, on the web true if the document focus is a text input, textarea or contenteditable)
  - The original's engine input field puts focus on a hidden DOM input, so this becomes true. Desktop has no document, so it looks at the focus of the engine input field.
    (same as the input manager's is_typing_in_text_field)
  - returns bool: true if a text input has focus.
- `pub fn set_title(&self, title: &str)` (method, since 0.3.2): Sets the window title.
  - `title` &str: New window title. (the document title on the web, does nothing on desktop before the window exists)
- `pub fn write_clipboard_text(&self, text: &str)` (method, since 0.3.2): Writes text to the system clipboard. (desktop arboard, web navigator.clipboard.writeText. In place of the original UIInputField.writeClipboard)
  - `text` &str: Text to write.
- `pub fn read_clipboard_text(&self) -> Option<String>` (method, since 0.3.2): Reads text from the system clipboard. (only desktop reads on the spot. The web is asynchronous so it is None, read with read_clipboard_text_with_callback)
  - returns Option<String>: Clipboard text. (None on the web or if the clipboard cannot be read)
- `pub fn read_clipboard_text_with_callback(&self, callback: impl FnOnce(String) + 'static)` (method, since 0.4.0): Reads text from the system clipboard and passes it to a callback. (in place of then on the Promise returned by the original UIInputField.readClipboard, empty string if it cannot be read or is denied)
  - The web calls it after navigator.clipboard.readText finishes, desktop reads on the spot and calls it right away.
  - `callback` impl FnOnce(String) + 'static: Function that receives the read text. (empty string if it cannot be read or is denied)

  Example: Read text to paste

  ```rust
  use vanilla::Engine;
  
  fn paste_text(engine: &Engine) {
  	engine.read_clipboard_text_with_callback(|clipboard_text| {
  		println!("{}", clipboard_text);
  	});
  }
  ```

- `pub fn read_clipboard_text_async(&self) -> Promise<Option<String>>` (method, since 0.4.0): Reads text from the system clipboard. (the original await engine.readClipboardText(), None in place of the original null if there is no clipboard or it is denied)
  - The web resolves after navigator.clipboard.readText finishes, desktop reads on the spot and resolves.
  - returns Promise<Option<String>>: Promise that resolves with the clipboard text. (None if there is no clipboard or it is denied)

  Example: Wait for clipboard text in an engine task

  ```rust
  use vanilla::Engine;
  
  fn paste_text(engine: &Engine) {
  	engine.spawn_task(|mut engine_context| async move {
  		let clipboard_text = engine_context.with(|engine| engine.read_clipboard_text_async()).await;
  		println!("{}", clipboard_text.unwrap_or_default());
  	});
  }
  ```

- `pub fn get_color_space(&self) -> ColorSpace` (method, since 0.4.0): Returns the 3D color space. (original getColorSpace, EngineConfiguration::color_space, fixed at creation so it does not change)
  - returns ColorSpace: ColorSpace::Gamma or ColorSpace::Linear.

  Example: A toon renderer built in an engine with the linear color space is linear too

  ```rust
  use vanilla::{ColorSpace, Engine, EngineConfiguration, ToonRenderer};
  
  let mut engine_configuration = EngineConfiguration::new();
  engine_configuration.color_space = ColorSpace::Linear;
  let engine = Engine::new(engine_configuration);
  assert_eq!(engine.get_color_space(), ColorSpace::Linear);
  if let Some(graphic) = engine.get_graphic() {
  	assert_eq!(graphic.get_color_space(), ColorSpace::Linear);
  	let renderer = ToonRenderer::new(graphic.get_gl()).unwrap();
  	assert_eq!(renderer.get_color_space(), ColorSpace::Linear);
  }
  ```

- `pub fn get_engine_configuration(&self) -> Ref<'_, EngineConfiguration>` (method, since 0.3.2): Returns the engine configuration.
  - returns Ref<'_, EngineConfiguration>: The configuration passed to Engine::new. (the maximum FPS changed by set_maximum_frame_per_second is also here)
- `pub fn set_maximum_frame_per_second(&self, maximum_frame_per_second: f64)` (method, since 0.4.0): Sets the maximum FPS. (can be changed at runtime, no limit if 0. 0 if less than 0 or not finite)
  - Written to EngineConfiguration.maximum_frame_per_second. The platform reads that value every frame and follows it from the next frame.
  - `maximum_frame_per_second` f64: Maximum frames per second. (no limit if 0)

  Example: Cap at 30 FPS at runtime, and invalid values become no limit

  ```rust
  use vanilla::{Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  engine.set_maximum_frame_per_second(30.0);
  assert_eq!(engine.get_maximum_frame_per_second(), 30.0);
  engine.set_maximum_frame_per_second(-5.0);
  assert_eq!(engine.get_maximum_frame_per_second(), 0.0);
  ```

- `pub fn get_maximum_frame_per_second(&self) -> f64` (method, since 0.4.0): Returns the maximum FPS. (0 means no limit)
  - returns f64: Maximum frames per second. (default 0)
- `pub fn get_time_manager(&self) -> Ref<'_, TimeManager>` (method, since 0.3.2): Time manager.
  - returns Ref<'_, TimeManager>: The engine's time manager. (frame interval, accumulated time, frames per second)
- `pub fn get_time_manager_mut(&self) -> RefMut<'_, TimeManager>` (method, since 0.3.2): Time manager. (mutable)
  - returns RefMut<'_, TimeManager>: The engine's time manager. (changes the time scale and the frame interval upper limit)
- `pub fn get_view_manager(&self) -> Ref<'_, ViewManager>` (method, since 0.3.2): View manager.
  - returns Ref<'_, ViewManager>: The engine's view manager. (view size, view area, safe area)
- `pub fn get_view_manager_mut(&self) -> RefMut<'_, ViewManager>` (method, since 0.3.2): View manager. (mutable)
  - returns RefMut<'_, ViewManager>: The engine's view manager. (changes settings such as the view scale mode and render scale upper limit)
- `pub fn get_input_manager(&self) -> Ref<'_, InputManager>` (method, since 0.3.2): Input manager.
  - returns Ref<'_, InputManager>: The engine's input manager. (keys, mouse, touch, wheel)
- `pub fn get_input_manager_mut(&self) -> RefMut<'_, InputManager>` (method, since 0.3.2): Input manager. (mutable)
  - returns RefMut<'_, InputManager>: The engine's input manager.
- `pub fn get_pointer_cursor(&self) -> Ref<'_, PointerCursor>` (method, since 0.4.0): Mouse cursor. (when on, sets the window or canvas cursor at the end of every frame)
  - returns Ref<'_, PointerCursor>: The engine's mouse cursor. (buttons call mark_over_button with &Engine)
- `pub fn get_pointer_cursor_mut(&self) -> RefMut<'_, PointerCursor>` (method, since 0.4.0): Mouse cursor. (mutable)
  - returns RefMut<'_, PointerCursor>: The engine's mouse cursor. (sets on/off, the screen cursor and image cursors)
- `pub fn is_coarse_pointer(&self) -> bool` (method, since 0.4.0): Whether the primary pointer is a finger. (CSS pointer: coarse, on desktop true on Windows tablets and Linux touchscreen devices, like Chromium)
  - returns bool: true if the primary pointer is a finger. (always false on Mac)
- `pub fn get_audio_manager(&self) -> Ref<'_, AudioManager>` (method, since 0.3.2): Audio manager. (its methods take &self, so players can be created even with the &Engine a component receives)
  - returns Ref<'_, AudioManager>: The engine's audio manager.
- `pub fn get_audio_manager_mut(&self) -> RefMut<'_, AudioManager>` (method, since 0.3.2): Audio manager. (mutable)
  - returns RefMut<'_, AudioManager>: The engine's audio manager.
- `pub fn get_platform(&self) -> Ref<'_, Platform>` (method, since 0.3.2): Platform info. (the original Platform, operating system and browser kind)
  - returns Ref<'_, Platform>: Platform info read when the engine was created.
- `pub fn is_page_hidden(&self) -> bool` (method, since 0.4.0): Whether the page is hidden. (another tab, app switch, covered window. On desktop: window occlusion (macOS, X11), minimization (Windows), app suspension, Wayland frame callbacks not arriving for more than 3 seconds)
  - returns bool: true if the last page event was Hidden. (false when Visible arrives, initially false)
- `pub fn add_page_event_listener(&self, page_event_listener: &PageEventListener)` (method, since 0.4.0): Adds a page event listener. (dropping the listener stops it from being called, can also be added with &Engine)
  - `page_event_listener` &PageEventListener: Listener to add. (the engine holds it by weak reference, the caller keeps it alive)

  Example: Receive occlusion and focus events

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, PageEvent, PageEventListener};
  
  let engine = Engine::new(EngineConfiguration::new());
  let received_list: Rc<RefCell<Vec<PageEvent>>> = Rc::new(RefCell::new(Vec::new()));
  let listener_received_list = received_list.clone();
  let page_event_listener: PageEventListener = Rc::new(RefCell::new(move |page_event: PageEvent| {
  	listener_received_list.borrow_mut().push(page_event);
  }));
  engine.add_page_event_listener(&page_event_listener);
  engine.dispatch_page_event(PageEvent::Hidden);
  assert!(engine.is_page_hidden());
  engine.dispatch_page_event(PageEvent::Visible);
  assert_eq!(*received_list.borrow(), vec![PageEvent::Hidden, PageEvent::Visible]);
  engine.remove_page_event_listener(&page_event_listener);
  engine.dispatch_page_event(PageEvent::Focused);
  assert_eq!(received_list.borrow().len(), 2);
  ```

- `pub fn remove_page_event_listener(&self, page_event_listener: &PageEventListener)` (method, since 0.4.0): Removes a page event listener. (the same listener is no longer called, dropped listeners are also removed)
  - `page_event_listener` &PageEventListener: Listener to remove. (the one passed to add_page_event_listener)
- `pub fn dispatch_page_event(&self, page_event: PageEvent)` (method, since 0.4.0): Dispatches a page event. (called by the platform, and games may call it too as in the original. Records hidden state and passes it on the spot to the live listeners)
  - If a listener is borrowed for something else, that listener skips this event.
  - `page_event` PageEvent: Event to dispatch. (Hidden records hidden state, Visible clears it)
- `pub fn add_graphic_context_event_listener(&self, graphic_context_event_listener: &GraphicContextEventListener)` (method, since 0.4.0): Adds a graphic context event listener. (The original's addGraphicContextEventListener, dropping the listener stops further calls)
  - Passes Lost when the context is lost, and Restored once it is back and the engine has rebuilt its base resources. While lost, the engine does not draw and only updates scenes.
  - `graphic_context_event_listener` &GraphicContextEventListener: Listener to add. (the engine holds it by weak reference, the caller keeps it alive)

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

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, GraphicContextEvent, GraphicContextEventListener};
  
  let engine = Engine::new(EngineConfiguration::new());
  let received_list: Rc<RefCell<Vec<GraphicContextEvent>>> = Rc::new(RefCell::new(Vec::new()));
  let listener_received_list = received_list.clone();
  let graphic_context_event_listener: GraphicContextEventListener = Rc::new(RefCell::new(move |graphic_context_event: GraphicContextEvent| {
  	listener_received_list.borrow_mut().push(graphic_context_event);
  }));
  engine.add_graphic_context_event_listener(&graphic_context_event_listener);
  engine.dispatch_graphic_context_event(GraphicContextEvent::Lost);
  engine.dispatch_graphic_context_event(GraphicContextEvent::Restored);
  assert_eq!(*received_list.borrow(), vec![GraphicContextEvent::Lost, GraphicContextEvent::Restored]);
  ```

- `pub fn remove_graphic_context_event_listener(&self, graphic_context_event_listener: &GraphicContextEventListener)` (method, since 0.4.0): Removes a graphic context event listener. (The original's removeGraphicContextEventListener, a dropped listener is removed too)
  - `graphic_context_event_listener` &GraphicContextEventListener: The listener to remove. (the one passed to add_graphic_context_event_listener)

  Example: Removing an added listener

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, GraphicContextEvent, GraphicContextEventListener};
  
  let engine = Engine::new(EngineConfiguration::new());
  let count = Rc::new(RefCell::new(0));
  let listener_count = count.clone();
  let graphic_context_event_listener: GraphicContextEventListener = Rc::new(RefCell::new(move |_graphic_context_event: GraphicContextEvent| {
  	*listener_count.borrow_mut() += 1;
  }));
  engine.add_graphic_context_event_listener(&graphic_context_event_listener);
  engine.remove_graphic_context_event_listener(&graphic_context_event_listener);
  engine.dispatch_graphic_context_event(GraphicContextEvent::Lost);
  assert_eq!(*count.borrow(), 0);
  ```

- `pub fn dispatch_graphic_context_event(&self, graphic_context_event: GraphicContextEvent)` (method, since 0.4.0): Notifies a graphic context event. (Called by the platform, passed on the spot to the live listeners)
  - A listener that is borrowed for something else skips this event.
  - `graphic_context_event` GraphicContextEvent: The event to notify.
- `pub fn add_graphic_error_listener(&self, graphic_error_listener: &GraphicErrorListener)` (method, since 0.4.0): Adds a graphic error listener. (The original's addGraphicErrorListener, dropping the listener stops further calls)
  - Reports once when the engine cannot build a shader program (a toon renderer material, a screen effect pass, a resolve_shader_program program).
    A program that failed to build is not rebuilt and is skipped when drawing, so the game uses this notification to decide a fallback drawing or an error report.
    A failure caused by losing the context is not the shader's fault, so it is neither reported nor remembered.
  - `graphic_error_listener` &GraphicErrorListener: Listener to add. (the engine holds it by weak reference, the caller keeps it alive)

  Example: Recording shader build failures

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, GraphicError, GraphicErrorKind, GraphicErrorListener};
  
  let engine = Engine::new(EngineConfiguration::new());
  let failed_name_list: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
  let listener_failed_name_list = failed_name_list.clone();
  let graphic_error_listener: GraphicErrorListener = Rc::new(RefCell::new(move |graphic_error: &GraphicError| {
  	if graphic_error.kind == GraphicErrorKind::ShaderBuildFailed {
  		listener_failed_name_list.borrow_mut().push(graphic_error.name.clone());
  	}
  }));
  engine.add_graphic_error_listener(&graphic_error_listener);
  engine.dispatch_graphic_error(&GraphicError { kind: GraphicErrorKind::ShaderBuildFailed, name: String::from("stripe"), error: String::from("compile failed") });
  assert_eq!(*failed_name_list.borrow(), vec![String::from("stripe")]);
  ```

- `pub fn remove_graphic_error_listener(&self, graphic_error_listener: &GraphicErrorListener)` (method, since 0.4.0): Removes a graphic error listener. (The original's removeGraphicErrorListener, a dropped listener is removed too)
  - `graphic_error_listener` &GraphicErrorListener: The listener to remove. (the one passed to add_graphic_error_listener)

  Example: Removing an added error listener

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, GraphicError, GraphicErrorKind, GraphicErrorListener};
  
  let engine = Engine::new(EngineConfiguration::new());
  let count = Rc::new(RefCell::new(0));
  let listener_count = count.clone();
  let graphic_error_listener: GraphicErrorListener = Rc::new(RefCell::new(move |_graphic_error: &GraphicError| {
  	*listener_count.borrow_mut() += 1;
  }));
  engine.add_graphic_error_listener(&graphic_error_listener);
  engine.remove_graphic_error_listener(&graphic_error_listener);
  engine.dispatch_graphic_error(&GraphicError { kind: GraphicErrorKind::ShaderBuildFailed, name: String::from("stripe"), error: String::new() });
  assert_eq!(*count.borrow(), 0);
  ```

- `pub fn dispatch_graphic_error(&self, graphic_error: &GraphicError)` (method, since 0.4.0): Notifies a graphic error. (Called by the engine, passed on the spot to the live listeners)
  - A listener that is borrowed for something else skips this error.
  - `graphic_error` &GraphicError: The error to notify. (kind, name, error)
- `pub fn get_frame_number(&self) -> u64` (method, since 0.3.2): Number of the current frame. (the first frame is 1 as in the original, also the frame number for verification screen captures)
  - returns u64: Current frame number. (increases by 1 at the end of each frame)
- `pub fn get_version_string(&self) -> String` (method, since 0.3.2): Engine version string.
  - returns String: Engine version. ("0.3.2" form)
- `pub fn request_frame_capture(&self, frame_number: u64, capture_handler: FrameCaptureHandler)` (method, since 0.4.0): Requests a verification screen capture. (passes the PNG bytes of the screen after that frame is fully drawn, the original requestFrameCapture passes a PNG data URL through a promise)
  - If the number has already passed, captures this frame (the next one if called between frames).
  - Can also be set with URL queries (web ?capture=120,240&captureName=shot_{frame}.png&captureExit=1) and environment variables (desktop VANILLA_CAPTURE_*).
  - `frame_number` u64: Frame number to capture. (the current frame if already passed)
  - `capture_handler` FrameCaptureHandler: Function that receives the PNG bytes of that frame's screen.

  Example: Save the 120th frame to a file

  ```rust
  use vanilla::Engine;
  
  fn capture_frame(engine: &Engine) {
  	engine.request_frame_capture(120, Box::new(|png_bytes: &[u8]| {
  		std::fs::write("capture_120.png", png_bytes).unwrap();
  	}));
  }
  ```

- `pub fn request_frame_capture_async(&self, frame_number: u64) -> Promise<Vec<u8>>` (method, since 0.4.0): Requests a verification screen capture. (the original await engine.requestFrameCapture(number), a Promise that resolves with the PNG bytes of the fully drawn screen of that frame. A PNG data URL in the original)
  - `frame_number` u64: Frame number to capture. (the current frame if already passed)
  - returns Promise<Vec<u8>>: Promise that resolves with the PNG bytes of that frame's screen.
- `pub fn measure_gpu_throughput(&self, frame_count: u32) -> Promise<Result<GpuThroughput, String>>` (method, since 0.4.0): GPU throughput measurement. (Original measureGpuThroughput; draws the current scene back to back without updating and returns the time per frame after waiting for the GPU to finish)
  - Draws the current scene frame_count times back to back through the same draw path as an engine frame, without a scene update (tick), and divides the wall-clock time until a 1-pixel read shows the GPU has finished by the frame count.
    It is the share of the slowest of the drawing side (CPU writing GL commands), the driver and GPU execution. When the GPU is the slowest, it is the time the GPU really takes to draw one frame.
  - Starts from the next engine update. After 10 warm-up frames it draws one chunk of 30 frames per update and waits for the GPU after every chunk. (It does not block for long at once; the gaps between chunks are not measured)
  - While measuring, engine time, input, frame number, canvas size fitting and capture stand still and the scene's tick is not called. If the scene's draw does not change game state, game state stays as it is. When done, the engine loop continues as before.
  - Because it draws the same state repeatedly, caches that redraw only what changed (such as shadow OnChange) do not re-bake. Presenting to the screen (compositing) happens only for the last frame of each chunk.
  - Resolves with Err when called again while measuring, before the engine loop has run, or when frame_count is 0.
  - `frame_count` u32: Number of frames to measure. (1 or more, warm-up frames are not counted)
  - returns Promise<Result<GpuThroughput, String>>: A Promise that resolves with a GpuThroughput. (Err(reason) on failure)

  Example: Measure the GPU throughput of the current scene

  ```rust
  use vanilla::{Engine, GpuThroughput};
  
  fn measure(engine: &'static Engine) {
  	engine.spawn_task(|mut engine_context| async move {
  		let result: Result<GpuThroughput, String> = engine_context.with(|engine| engine.measure_gpu_throughput(60)).await;
  		if let Ok(throughput) = result {
  			println!("{} frames, {} ms per frame", throughput.frame_count, throughput.milliseconds_per_frame);
  		}
  	});
  }
  ```

## GpuThroughput (struct) (Clone, Debug, PartialEq)

The result of the GPU throughput measurement. (What the original measureGpuThroughput returns: { frameCount, chunkFrameCount, millisecondsPerFrame, chunkMillisecondsPerFrame })

Example: Checking the time per frame from the sum of chunk times and the frame count

```rust
use vanilla::GpuThroughput;

let throughput = GpuThroughput {
	frame_count: 4,
	chunk_frame_count: 2,
	milliseconds_per_frame: 1.5,
	chunk_milliseconds_per_frame: vec![1.0, 2.0],
};
let chunk_total: f64 = throughput.chunk_milliseconds_per_frame.iter().map(|value| value * throughput.chunk_frame_count as f64).sum();
assert_eq!(chunk_total / throughput.frame_count as f64, throughput.milliseconds_per_frame);
```

- `pub frame_count: u32` (field, since 0.4.0): Number of frames measured. (warm-up frames are not counted)
  - returns u32
- `pub chunk_frame_count: u32` (field, since 0.4.0): Number of frames in one chunk.
  - returns u32
- `pub milliseconds_per_frame: f64` (field, since 0.4.0): Time per frame. (milliseconds, the sum of all chunk times / the frame count)
  - returns f64
- `pub chunk_milliseconds_per_frame: Vec<f64>` (field, since 0.4.0): Time per frame for each chunk. (milliseconds)
  - returns Vec<f64>

## EngineRunner (struct)

Engine runner. (holds the engine, graphic and scene list and runs the frames. Held and called by the platform)
- Game code does not create it directly. Engine::run creates it with the engine and the first scene and hands it to the platform.

Example: Engine::run creates the runner and runs it

```rust
use vanilla::{Engine, EngineConfiguration, Scene, SceneBase};

struct MainScene {
	scene_base: SceneBase,
}

impl Scene for MainScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}
}

let engine = Engine::new(EngineConfiguration::new());
engine.run(Box::new(MainScene { scene_base: SceneBase::new() })).unwrap();
```

## PageEvent (enum) (Clone, Copy, Debug, PartialEq, Eq)

Page event. (the platform notifies the engine, and the engine passes it on the spot to the listeners)

- `Hidden`: The page was hidden. (another tab, app switching, window occluded)
- `Visible`: The page became visible again.
- `Blurred`: The window lost focus. (blur)
- `Focused`: The window gained focus. (focus)
- `PointerDown`: The window was pressed. (pointerdown, once pressed the window has focus even without a focus notification)

## GraphicContextEvent (enum) (Clone, Copy, Debug, PartialEq, Eq)

Graphic context event. (The original's GraphicContextEvent, passed by the engine to listeners on the spot)

- `Lost`: The GL 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`: The context was restored and the engine rebuilt its base resources. (GL objects the game made, 3D renderers and render targets are dead, rebuild them now)

## GraphicErrorKind (enum) (Clone, Copy, Debug, PartialEq, Eq)

Graphic error kinds. (The original's GraphicErrorKind, the kind of GraphicError)

- `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)
