# game/gamescene (vanilla-engine 0.4.0)

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

Common base scene for games. (GameScene in the original game/gamescene.js)
- Loading screen (center image + gauge at the bottom + touch to skip, minimum display time).
- Touch input goes through TouchRecognizer. (gestures that scroll even when dragging a button inside a scroll view)
- Safe area node "safeArea" + safe area rectangle computation.
- When the view size changes, layout is called again at the next tick.
- Fills the whole canvas with the background color. (pre_draw)
- In the Rust version, instead of inheritance the scene contains a GameSceneBase, implements the GameScene trait (where the original overrides), and gets a Scene with one game_scene! line:
  ```text
    struct TitleScene { game_scene_base: GameSceneBase, logo_asset: ImageAsset }
    impl GameScene for TitleScene {
        fn get_game_scene_base(&self) -> &GameSceneBase { &self.game_scene_base }
        fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase { &mut self.game_scene_base }
        fn load_assets(&mut self) {                       // where the original overrides loadAssets (after the base requests the loading image)
            self.logo_asset.load(engine, "logo.png");
            self.game_scene_base.get_scene_base_mut().track_asset(&self.logo_asset);
        }
        fn initialize(&mut self, engine: &Engine) {                          // after the base initialize
            let safe_area_id = self.game_scene_base.get_safe_area_node_id().unwrap();   // attach content under here
        }
        fn layout(&mut self) { /* read game_scene_base.get_safe_area_rect() and place content */ }
    }
    vanilla::game_scene!(TitleScene);
  ```
  For each Scene function, the base is called first and then the GameScene function of the same name. (an override that calls super first in the original)
  Only post_draw calls the scene's first and draws the base (fade curtain, developer tools) on top. layout is called after the base recomputes the safe area.
  (on resize, and when tick sees a view size change. Also once on the first tick)
  Calling GameSceneBase functions directly from Scene functions still works. In that case the scene looks at the bool returned by tick and calls its own layout, and also calls post_draw directly.
- Differences from the original:
  - The original load (async) "waits for load_assets, then waits for the minimum time / a touch", which has been moved to the Rust asset flow.
    In load it hands over one "loading gate" read handle (held by SceneBase), and the engine opens the gate during each loading frame when the minimum time has passed or the screen is pressed.
    (the same place as the engine frame function the original load registers; it does not rely on draw_on_load, which can be overridden, so the scene does not hang even if it does not call the base draw_on_load)
    The engine calls initialize only after all handed over assets (including the gate) finish, so the result is the same as the original. (all assets read + (minimum time or touch))
- What both engines do the same way:
  - Loading time is measured with the engine clock (get_realtime_since_startup). If the engine clock has not started yet (before the first frame, 0), it is measured from the time of the first loading screen frame.
  - A press on the loading screen is read from engine input (is_touch_pressed) by the engine during each loading frame.
  - The TouchRecognizer is created in initialize like the original. (Before that get_touch_recognizer is None, undefined in the original)
    Touches are passed by tick instead of functions like the original touchPress. (SceneBase's touch raycaster and first-touch callback are not used)
- Other differences from the original:
  - Safe area: the web reads CSS env(safe-area-inset-*) as in the original. Desktop is 0 like Chrome desktop,
    and it can be set with set_safe_area_insets. (once set, that value is used on the web too)
  - set_view_scale_mode also takes the engine. (it changes the view manager through &mut, so the global engine (&Engine) cannot do it) Given the engine, it recomputes the view area right away as in the original.
  - Developer tools (DevTools) are made in initialize if EngineConfiguration::use_dev_tools is on. (same as the original) tick passes F2 and touches, and post_draw draws them.
- Changing the loading screen: set_loading_colors changes only the colors, set_loading_drawer changes the whole drawing on top of the background. (the original setLoadingColors, setLoadingDrawer)
  The set function is kept in an `Rc<RefCell>`. get_loading_drawer returns that Rc, and the caller borrows it with borrow_mut to call it.
  By default the gauge shows the elapsed minimum display time (get_loading_progress), and if progress is reported with set_loading_progress or track_asset_loader,
  it smoothly follows that progress. (LoadingProgress, get_loading_progress_state)
  - The original getLoadingProgress (returns LoadingProgress) is get_loading_progress_state, because the Rust version already has the same name (elapsed time ratio).
  - The original fills the progress to 1 when load_assets finishes (if it was ever reported). The Rust version fills it to 1 in draw_on_load when all assets handed to the scene except the loading gate finish.
    (complete_loading_progress_if_assets_finished, a scene that works across frames hands over a read handle and opens it when done)
  - For an AssetLoader handed over with track_asset_loader, draw_on_load calls update every frame.
  - The fourth value (outside color) of the original setLoadingColors is set separately with set_loading_outside_color, because Rust has no default arguments.
- Screen frame (the same features as fadeScreen, isUserInterfaceAt, setPlayInputHandler and setPlayAreaReference of vanilla.js GameScene):
  - Screen fade: in the original, if onDark returns a Promise, it stays dark until it finishes. The same form in the Rust version is fade_screen_async(on_dark).
    At the tick it becomes fully dark, it hands on_dark's future over as a scene task and runs it right there up to the first await as in the original (reaching the scene and engine through SceneContext),
    and when the future finishes it brightens. A scene implementing GameScene calls it with GameScene::fade_screen_async, and game_scene! takes care of starting it.
    A scene implementing Scene directly calls it with `GameSceneBase::fade_screen_async::<scene type>`, and after the base tick takes it out with take_screen_fade_dark_starter and starts it.
    (if not taken out, the base hands it over at the next polling turn in post_draw or the next tick)
    The synchronous form fade_screen(on_dark) calls on_dark(tree, engine) when fully dark, and if on_dark returns a ScreenFadeHold, it stays dark until that handle's release is called.
    (brightens right away if None) The callback form fade_screen_with_hold(on_dark) has on_dark keep the handle and release it when the work is done. (in place of the Promise's resolve)
    The curtain is drawn by post_draw. While the curtain is up, presses and the wheel are not accepted.
  - Input the UI did not take: calls the handler (set_play_input_handler) as in the original. press, move, release and wheel of the original handler object are variants of PlayInput.
    The handler cannot borrow the scene, so scene state is shared through `Rc<RefCell>`. For the scene to take them directly in tick, collect them with set_play_input_enabled(true) and take them with take_play_inputs.
    (coordinates relative to the top left of the safe area)
  - Wheel: as in the original, if it points inside the window layer (UIWindowLayer), the topmost window takes it first (UIWindowLayer::scroll_window_at), otherwise the scroll box at that position takes it.
  - If the safe area is not set with set_safe_area_insets, it reads ViewManager::get_safe_area_insets. (follows the forced value, URL, env and sides to ignore)

## LoadingDrawer (type)

Loading screen drawing function. (graphic, view size, visible progress 0 ~ 1, seconds since loading started. The view coordinate system is applied)

```rust
pub type LoadingDrawer = Box<dyn FnMut(&mut Graphic, Vector2, f64, f64)>
```

## ScreenFadeHold (struct) (Clone, Debug, Default)

Handle that holds the screen fade dark. (in place of the Promise returned by the original onDark, releasing any clone of the handle brightens it)

Example: Return a handle when fully dark and stay dark until it is released (with a fade time of 0 it goes fully dark in one tick)

```rust
use vanilla::{Engine, EngineConfiguration, GameSceneBase, NodeTree, ScreenFadeHold};

let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_screen_fade_seconds(0.0);
let screen_fade_hold = ScreenFadeHold::new();
let returned_hold = screen_fade_hold.clone();
assert!(game_scene_base.fade_screen(Some(Box::new(move |_node_tree: &mut NodeTree, _engine: &Engine| {
	Some(returned_hold)
}))));
game_scene_base.tick(0.016);
game_scene_base.tick(0.016);
assert_eq!(game_scene_base.get_screen_fade_alpha(), 1.0);
screen_fade_hold.release();
assert!(screen_fade_hold.is_released());
game_scene_base.tick(0.016);
game_scene_base.tick(0.016);
assert_eq!(game_scene_base.get_screen_fade_alpha(), 0.0);
assert!(!game_scene_base.is_screen_fading());
```

- `pub fn new() -> ScreenFadeHold` (constructor, since 0.4.0): Creates. (not released yet)
  - returns ScreenFadeHold: An unreleased handle.
- `pub fn release(&self)` (method, since 0.4.0): Releases. (the curtain brightens)
- `pub fn is_released(&self) -> bool` (method, since 0.4.0): Whether it has been released.
  - returns bool: true if release was called on this handle or any of its clones.

## ScreenFadeDarkStarter (struct)

Starter for the async on_dark of a screen fade. (made by fade_screen_async, and when fully dark the scene takes it out with take_screen_fade_dark_starter and starts it)
- A scene that implements Scene directly takes it out and starts it after the base tick. (game_scene!, ui_scene! do this automatically)

Example: Take it out and start it after the base tick, and it brightens when the future finishes

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

struct PuzzleScene {
	game_scene_base: GameSceneBase,
	stage_number: u32,
}

impl Scene for PuzzleScene {
	fn get_scene_base(&self) -> &SceneBase {
		self.game_scene_base.get_scene_base()
	}

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

	fn tick(&mut self, time_delta: f64) {
		self.game_scene_base.tick(time_delta);
		if let Some(screen_fade_dark_starter) = self.game_scene_base.take_screen_fade_dark_starter() {
			screen_fade_dark_starter.start(self);
		}
	}
}

let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut puzzle_scene = PuzzleScene {
	game_scene_base: GameSceneBase::new(),
	stage_number: 1,
};
puzzle_scene.game_scene_base.set_screen_fade_seconds(0.0);
assert!(puzzle_scene.game_scene_base.fade_screen_async::<PuzzleScene, _, _>(|mut scene_context: SceneContext<PuzzleScene>| async move {
	scene_context.with(|scene, _engine| {
		scene.stage_number += 1;
	});
}));
puzzle_scene.tick(0.016);
assert_eq!(puzzle_scene.stage_number, 2);
puzzle_scene.tick(0.016);
puzzle_scene.tick(0.016);
assert!(!puzzle_scene.game_scene_base.is_screen_fading());
```

- `pub fn start(self, scene: &mut dyn Scene)` (method, since 0.4.0): Starts. (hands on_dark's future over as this scene's task and runs it right there up to the first await. Brightens right away if the scene is not the type of fade_screen_async)
  - `scene` &mut dyn Scene: Scene that holds this base. (usually self inside tick, must be the S type of fade_screen_async. The task is handed to the global engine)

## ScreenFadeEvent (type)

Function called when fully dark. (takes the tree and engine. If it returns a handle, it stays dark until released)

```rust
pub type ScreenFadeEvent = Box<dyn FnOnce(&mut NodeTree, &Engine) -> Option<ScreenFadeHold>>
```

## ScreenFadeHoldEvent (type)

Callback form of the function called when fully dark. (takes the tree, engine and handle. Stays dark until the handle is released, fade_screen_with_hold)

```rust
pub type ScreenFadeHoldEvent = Box<dyn FnOnce(&mut NodeTree, &Engine, ScreenFadeHold)>
```

## PlayInputHandler (type)

Handler for input the UI did not take. (the handler object of the original setPlayInputHandler, coordinates in play area coordinates)

```rust
pub type PlayInputHandler = Box<dyn FnMut(PlayInput)>
```

## GameSceneBase (struct) (Default)

Common base scene for games.
- Handles the loading screen, touch recognition, safe area, screen fade, and play input. A scene contains it and uses it through the GameScene trait and game_scene!, or calls it directly from Scene functions.

Example: Implementing Scene directly and calling the base functions (calls the scene's layout based on the bool returned by tick)

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

struct PuzzleScene {
	game_scene_base: GameSceneBase,
	layout_count: u32,
}

impl PuzzleScene {
	fn layout(&mut self) {
		self.layout_count += 1;
	}
}

impl Scene for PuzzleScene {
	fn get_scene_base(&self) -> &SceneBase {
		self.game_scene_base.get_scene_base()
	}

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

	fn load(&mut self, engine: &Engine) {
		self.game_scene_base.load(engine);
	}

	fn draw_on_load(&mut self, graphic: &mut Graphic) {
		self.game_scene_base.draw_on_load(graphic);
	}

	fn initialize(&mut self, engine: &Engine) {
		self.game_scene_base.initialize(engine);
	}

	fn resize(&mut self, canvas_native_size: Vector2) {
		self.game_scene_base.resize(canvas_native_size);
		self.layout();
	}

	fn tick(&mut self, time_delta: f64) {
		if self.game_scene_base.tick(time_delta) {
			self.layout();
		}
		if let Some(screen_fade_dark_starter) = self.game_scene_base.take_screen_fade_dark_starter() {
			screen_fade_dark_starter.start(self);
		}
	}

	fn pre_draw(&mut self, graphic: &mut Graphic) {
		self.game_scene_base.pre_draw(graphic);
	}

	fn draw(&mut self, graphic: &mut Graphic) {
		self.game_scene_base.get_scene_base_mut().draw(graphic);
	}

	fn post_draw(&mut self, graphic: &mut Graphic) {
		self.game_scene_base.post_draw(graphic);
	}
}

let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut puzzle_scene = PuzzleScene {
	game_scene_base: GameSceneBase::new(),
	layout_count: 0,
};
puzzle_scene.initialize(engine);
puzzle_scene.tick(0.016);
assert_eq!(puzzle_scene.layout_count, 1);
assert!(puzzle_scene.game_scene_base.get_safe_area_node_id().is_some());
assert_eq!(puzzle_scene.game_scene_base.get_safe_area_rect().size, Vector2::create(800.0, 600.0));
```

- `pub fn new() -> GameSceneBase` (constructor, since 0.3.2): Creates. (minimum display 3 seconds, black background, ViewScaleMode::None)
  - Loading colors are black, #333333, #ffffff, and the fade is black for 0.35 seconds. The safe area node is created in initialize.
  - returns GameSceneBase: Base before initialize.
- `pub fn get_dev_tools(&self) -> Option<&DevTools>` (method, since 0.4.0): Returns the developer tools. (None before initialize or if EngineConfiguration::use_dev_tools is off)
  - returns Option<&DevTools>: Developer tools. None before initialize or when turned off.
- `pub fn get_dev_tools_mut(&mut self) -> Option<&mut DevTools>` (method, since 0.4.0): Returns the developer tools. (mutable)
  - returns Option<&mut DevTools>: Developer tools. (mutable) None before initialize or when turned off.
- `pub fn get_scene_base(&self) -> &SceneBase` (method, since 0.3.2): Returns the common scene state. (returned from Scene::get_scene_base)
  - returns &SceneBase: Common scene state held by the base.
- `pub fn get_scene_base_mut(&mut self) -> &mut SceneBase` (method, since 0.3.2): Returns the common scene state. (mutable)
  - returns &mut SceneBase: Common scene state held by the base. (mutable)
- `pub fn get_touch_recognizer(&self) -> Option<&TouchRecognizer>` (method, since 0.3.2): Returns the touch recognizer. (Original getTouchRaycaster, created in initialize)
  - returns Option<&TouchRecognizer>: The recognizer tick passes touches to. None before initialize. (undefined in the original)
- `pub fn get_touch_recognizer_mut(&mut self) -> Option<&mut TouchRecognizer>` (method, since 0.3.2): Returns the touch recognizer. (mutable)
  - returns Option<&mut TouchRecognizer>: The recognizer tick passes touches to. (mutable) None before initialize.
- `pub fn set_view_scale_mode(&mut self, view_scale_mode: ViewScaleMode, engine: Option<&Engine>)` (method, since 0.3.2): Sets the ViewScaleMode. (default none. Given the engine, it applies to the view area right away, otherwise it is applied in initialize)
  - `view_scale_mode` ViewScaleMode: View scale mode.
  - `engine` Option<&Engine>: Engine to apply it to right away. If None, it is applied in initialize.

  Example: Giving an engine recomputes the view area on the spot

  ```rust
  use vanilla::{Engine, EngineConfiguration, GameSceneBase, Vector2, ViewScaleMode};
  
  let engine = Engine::new(EngineConfiguration::new());
  engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_view_scale_mode(ViewScaleMode::ReferenceResolution, Some(engine));
  assert_eq!(game_scene_base.get_view_scale_mode(), ViewScaleMode::ReferenceResolution);
  assert_eq!(engine.get_view_manager().get_view_size(), Vector2::create(1280.0, 720.0));
  ```

- `pub fn get_view_scale_mode(&self) -> ViewScaleMode` (method, since 0.3.2): Returns the current ViewScaleMode.
  - returns ViewScaleMode: View scale mode set on this base. (default ViewScaleMode::None)
- `pub fn set_loading_image_url(&mut self, url: &str)` (method, since 0.3.2): Sets the path of the loading screen center image. (only the gauge without an image for empty text. Set before create)
  - `url` &str: Asset path of the loading image. (load_assets in create loads it and hands it to the scene)
- `pub fn set_loading_min_duration_ms(&mut self, milliseconds: f64)` (method, since 0.3.2): Sets the minimum display time of the loading screen. (milliseconds. Set before create)
  - `milliseconds` f64: Minimum display time. (milliseconds, default 3000, does not wait if 0 or less)
- `pub fn set_loading_drawer(&mut self, loading_drawer: Option<LoadingDrawer>)` (method, since 0.4.0): Sets the loading screen drawing function. (None for the default drawing: loading image in the center + gauge at the bottom)
  - Fills the canvas with the outside color and the view with the background color, applies the view coordinate system, then calls drawer(graphic, view size, visible progress, elapsed seconds).
  - It is drawn even before images and fonts are received, so draw with shapes and the default font. The function itself holds what it draws.
  - `loading_drawer` Option<LoadingDrawer>: Loading screen drawing function. (graphic, view size, displayed progress 0 ~ 1, elapsed seconds) None uses the default drawing.

  Example: Replace it with a single thin bar at the bottom

  ```rust
  use vanilla::{Colors, GameSceneBase, Graphic, Rect, Vector2};
  
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_loading_drawer(Some(Box::new(|graphic: &mut Graphic, view_size: Vector2, progress: f64, _elapsed_seconds: f64| {
  	graphic.set_fill_color(Colors::WHITE);
  	graphic.draw_rect(Rect::create(0.0, view_size.y - 8.0, view_size.x * progress, 8.0));
  })));
  assert!(game_scene_base.has_loading_drawer());
  ```

- `pub fn has_loading_drawer(&self) -> bool` (method, since 0.4.0): Whether there is a loading screen drawing function.
  - returns bool: true if a drawing function is set.
- `pub fn get_loading_drawer(&self) -> Option<Rc<RefCell<LoadingDrawer>>>` (method, since 0.4.0): Returns the loading screen drawing function. (None if absent, borrow it with borrow_mut to call it)
  - returns Option<Rc<RefCell<LoadingDrawer>>>: `Rc<RefCell>` holding the drawing function. None if there is none.
- `pub fn set_loading_colors(&mut self, background_color: impl Into<Color>, bar_back_color: impl Into<Color>, bar_fill_color: impl Into<Color>)` (method, since 0.4.0): Sets the loading screen colors. (background, gauge background, gauge. Outside the view also becomes the background color. Defaults are black, #333333, #ffffff)
  - `background_color` impl Into<Color>: View background color, also the color outside the view. (a Color or a string like "#rrggbb")
  - `bar_back_color` impl Into<Color>: Gauge background color.
  - `bar_fill_color` impl Into<Color>: Gauge fill color.
- `pub fn set_loading_outside_color(&mut self, outside_color: impl Into<Color>)` (method, since 0.4.0): Sets the color outside the loading screen view (the rest of the canvas). (the fourth value of the original setLoadingColors, call after set_loading_colors)
  - `outside_color` impl Into<Color>: Color outside the view. (a Color or a string like "#rrggbb")
- `pub fn set_loading_progress(&mut self, progress: f64)` (method, since 0.4.0): Reports loading progress. (0 ~ 1, never decreases. After reporting, the gauge follows this value instead of the elapsed time)
  - `progress` f64: Progress to report. (0 ~ 1)
- `pub fn get_loading_progress_state(&self) -> &LoadingProgress` (method, since 0.4.0): Loading progress state. (the reported amount and the visible amount that smoothly follows it, the original getLoadingProgress)
  - returns &LoadingProgress: Loading progress state.
- `pub fn get_loading_progress_state_mut(&mut self) -> &mut LoadingProgress` (method, since 0.4.0): Loading progress state. (mutable, for changing the follow speed)
  - returns &mut LoadingProgress: Loading progress state. (mutable)
- `pub fn track_asset_loader(&mut self, asset_loader: &AssetLoader)` (method, since 0.4.0): Hands over a batch asset load. (delays initialize until everything is received, draw_on_load calls update and reports progress)
  - After handing over, the gauge follows the load progress instead of the elapsed time.
  - `asset_loader` &AssetLoader: Load to hand over. (shared, the caller calls load)

  Example: Progress rises with the finished count of the handed over loads

  ```rust
  use vanilla::{AssetLoadHandle, AssetLoader, Engine, EngineConfiguration, GameSceneBase};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_loading_min_duration_ms(0.0);
  game_scene_base.begin_loading(0.0);
  let asset_loader = AssetLoader::new();
  asset_loader.add_image("examples/assets/atlas/icons.png");
  let generate_handle = AssetLoadHandle::create_pending("level.generate");
  asset_loader.add_load_handle(&generate_handle);
  game_scene_base.track_asset_loader(&asset_loader);
  asset_loader.load(&engine);
  game_scene_base.update_tracked_asset_loaders(&engine);
  assert_eq!(game_scene_base.get_loading_progress_state().get_progress(), 0.5);
  assert!(!game_scene_base.get_scene_base().are_tracked_assets_finished());
  generate_handle.finish(Ok(Vec::new()));
  game_scene_base.update_tracked_asset_loaders(&engine);
  assert_eq!(game_scene_base.get_loading_progress_state().get_progress(), 1.0);
  assert!(game_scene_base.get_scene_base().are_tracked_assets_finished());
  ```

- `pub fn update_tracked_asset_loaders(&mut self, engine: &Engine)` (method, since 0.4.0): Updates the handed over batch asset loads and reports progress. (finished count / total count of those handed over)
  - Does nothing if nothing was handed over. draw_on_load calls it every frame.
  - `engine` &Engine: Engine to pass to the loads' update.
- `pub fn complete_loading_progress_if_assets_finished(&mut self)` (method, since 0.4.0): Fills progress to 1 when all handed over assets except the loading gate finish. (where the original load reports 1 after waiting for load_assets, does nothing if never reported)
- `pub fn set_scene_background_color(&mut self, color: impl Into<Color>)` (method, since 0.3.2): Sets the canvas background color. (fills the whole canvas in pre_draw)
  - `color` impl Into<Color>: Background color. (a Color or a string like "#rrggbb", default black)
- `pub fn get_safe_area_node_id(&self) -> Option<NodeId>` (method, since 0.3.2): Returns the safe area node. (the scene attaches content here. None before initialize)
  - returns Option<NodeId>: The "safeArea" node under the root. None before initialize or for a base that does not create the node (UISceneBase).
- `pub fn get_safe_area_rect(&self) -> Rect` (method, since 0.3.2): Returns the last computed safe area rectangle. (view coordinates)
  - returns Rect: Area computed by the last layout. (view coordinates, 0 before it is computed)
- `pub fn set_safe_area_insets(&mut self, insets: Option<SafeAreaInsets>)` (method, since 0.3.2): Sets the safe area insets directly. (CSS pixels, None reads the view manager's get_safe_area_insets)
  - `insets` Option<SafeAreaInsets>: Top, right, bottom, left insets. (CSS pixels, used from the next layout) None reads them from the view manager.
- `pub fn load(&mut self, engine: &Engine)` (method, since 0.4.0): Creates. (called first in the scene's load. The front part of the original load + load_assets)
  - Calls begin_loading with the real time elapsed since the engine started, then calls load_assets.
  - `engine` &Engine: Engine to read the time from and request the loading image from.
- `pub fn begin_loading(&mut self, current_time: f64)` (method, since 0.3.2): Starts loading. (records the start time and hands the scene a loading gate that waits for the minimum time / a touch)
  - If the minimum display time is 0 or less, the loading gate is left open from the start.
  - The engine updates and opens the gate during each loading frame (with the engine clock and engine input). It does not rely on draw_on_load, which can be overridden, so initialize is called even if the scene does not call the base draw_on_load. (the engine frame function the original load registers)
  - `current_time` f64: Current time. (seconds, real time elapsed since the engine started)
- `pub fn load_assets(&mut self)` (method, since 0.3.2): Loads assets. (the default part of the original loadAssets: the loading image. The scene's own assets are requested in the scene's load and handed over with track_asset)
  - Does nothing if the loading image path is empty.
- `pub fn update_loading(&mut self, current_time: f64, is_touch_pressed: bool)` (method, since 0.3.2): Updates loading. (records a skip when pressed, and opens the loading gate when the minimum time has passed or it was skipped)
  - The gate is left as is before begin_loading or if it is already open.
  - The engine calls the same update during each loading frame, so the game does not need to call it. (for tests and tools that pass the time by hand)
  - `current_time` f64: Current time. (seconds, the same clock as given to begin_loading)
  - `is_touch_pressed` bool: Whether the screen was pressed this frame.

  Example: The loading gate opens only after the minimum display time has passed

  ```rust
  use vanilla::GameSceneBase;
  
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_loading_min_duration_ms(3000.0);
  game_scene_base.begin_loading(10.0);
  assert_eq!(game_scene_base.get_loading_progress(11.5), 0.5);
  game_scene_base.update_loading(12.9, false);
  assert!(!game_scene_base.get_scene_base().are_tracked_assets_finished());
  game_scene_base.update_loading(13.0, false);
  assert!(game_scene_base.get_scene_base().are_tracked_assets_finished());
  ```

  Example: Pressing opens it even before the minimum time

  ```rust
  use vanilla::GameSceneBase;
  
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.begin_loading(0.0);
  game_scene_base.update_loading(0.2, true);
  assert!(game_scene_base.is_load_touched_to_skip());
  assert!(game_scene_base.get_scene_base().are_tracked_assets_finished());
  ```

- `pub fn get_loading_progress(&self, current_time: f64) -> f64` (method, since 0.3.2): Loading gauge progress. (elapsed time / minimum display time, 0 ~ 1)
  - `current_time` f64: Current time. (seconds, the same clock as given to begin_loading)
  - returns f64: Elapsed time ratio. (0 ~ 1, 1 if the minimum display time is 0 or less)
- `pub fn is_load_touched_to_skip(&self) -> bool` (method, since 0.3.2): Whether skip was pressed.
  - returns bool: true if a press came to update_loading after begin_loading.
- `pub fn draw_on_load(&mut self, graphic: &mut Graphic)` (method, since 0.3.2): Draws the loading screen. (the engine calls it every frame until initialize. Outside color canvas + background color view + (the drawing function, or if none, loading image in the center + gauge at the bottom))
  - Before drawing, updates the handed over loads and makes the displayed progress catch up. (the engine takes the loading time and skip during each loading frame)
  - `graphic` &mut Graphic: Graphic to draw the loading screen with.
- `pub fn initialize(&mut self, engine: &Engine)` (method, since 0.3.2): Initializes. (called first in the scene's initialize. Applies the ViewScaleMode, creates the safe area node)
  - Applies the play area reference, and creates the developer tools if EngineConfiguration::use_dev_tools is on.
  - `engine` &Engine: Engine that has the view manager and configuration.
- `pub fn resize(&mut self, _canvas_native_size: Vector2)` (method, since 0.3.2): Screen size changed. (resets the play area reference and redoes the default layout. game_scene! calls the scene's layout after this)
  - `_canvas_native_size` Vector2: Logical size of the window interior. (unused, read from the view manager)
- `pub fn layout(&mut self)` (method, since 0.3.2): Layout. (recomputes the safe area rectangle and applies it to the node)
- `pub fn compute_safe_area_rect(&self) -> Rect` (method, since 0.3.2): Computes the safe area. (view coordinates)
  - Insets set directly are divided by the view scale and subtracted, otherwise the view manager's insets (already in view coordinates) are subtracted. When the play area reference is used, computes with the canvas size divided by the scale.
  - returns Rect: Safe area rectangle. (view coordinates, the size does not go below 0)
- `pub fn calculate_safe_area_rect(view_size: Vector2, target_resolution_scale: f64, insets: SafeAreaInsets) -> Rect` (static, since 0.3.2): Computes the safe area. (static. Divides the CSS pixel insets by the view scale and subtracts them from the view area)
  - `view_size` Vector2: View size. (view coordinates)
  - `target_resolution_scale` f64: View scale. (how many CSS pixels one view coordinate unit is, 1 if 0 or less)
  - `insets` SafeAreaInsets: Top, right, bottom, left insets. (CSS pixels)
  - returns Rect: Safe area rectangle. (view coordinates, the size does not go below 0)

  Example: At scale 2 the insets are halved before being subtracted

  ```rust
  use vanilla::{GameSceneBase, Rect, SafeAreaInsets, Vector2};
  
  let safe_area_rect = GameSceneBase::calculate_safe_area_rect(Vector2::create(400.0, 300.0), 2.0, SafeAreaInsets::create(40.0, 10.0, 20.0, 30.0));
  assert_eq!(safe_area_rect, Rect::create(15.0, 20.0, 380.0, 270.0));
  let collapsed_rect = GameSceneBase::calculate_safe_area_rect(Vector2::create(10.0, 10.0), 0.0, SafeAreaInsets::create(20.0, 20.0, 20.0, 20.0));
  assert_eq!(collapsed_rect, Rect::create(20.0, 20.0, 0.0, 0.0));
  ```

- `pub fn update_layout_if_view_size_changed(&mut self, engine: &Engine) -> bool` (method, since 0.3.2): Redoes the default layout if the view size changed. (true if it changed)
  - `engine` &Engine: Engine to read the view size from.
  - returns bool: true if the view size differed from the last one seen and the layout was redone. (initialize resets the seen size to 0, so it is also true on the first call after that if the view size is not 0)
- `pub fn tick(&mut self, time_delta: f64) -> bool` (method, since 0.3.2): Updates. (node → TouchRecognizer touches → tweens, then layout after checking for a view size change. true if layout was redone)
  - Checked every tick because resize alone can miss cases like a mobile address bar appearing and disappearing. (same as the original)
  - Then updates the screen fade and the developer tools. A fade starter the scene did not take out is handed to the next polling turn.
  - `time_delta` f64: Frame interval multiplied by the time scale. (seconds, used for nodes and tweens. The fade runs on unscaled time)
  - returns bool: true if the view size changed and the layout was redone. (the scene calls its own layout then)

  Example: Only the tick where the view size changed is true, and the safe area is recomputed

  ```rust
  use vanilla::{Engine, EngineConfiguration, GameSceneBase, Rect, SafeAreaInsets};
  
  let engine = Engine::new(EngineConfiguration::new());
  engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_safe_area_insets(Some(SafeAreaInsets::create(10.0, 0.0, 20.0, 5.0)));
  game_scene_base.initialize(engine);
  assert!(game_scene_base.tick(0.016));
  assert_eq!(game_scene_base.get_safe_area_rect(), Rect::create(5.0, 10.0, 795.0, 570.0));
  assert!(!game_scene_base.tick(0.016));
  engine.get_view_manager_mut().calculate_view_rect(1024, 768, 1.0);
  assert!(game_scene_base.tick(0.016));
  assert_eq!(game_scene_base.get_safe_area_rect(), Rect::create(5.0, 10.0, 1019.0, 738.0));
  ```

- `pub fn is_wheel_handled(&self) -> bool` (method, since 0.4.0): Whether a scroll box or the like took this frame's wheel. (read after tick. Using it for the game's map zoom and the like only when false keeps it from overlapping window scrolling)
  - returns bool: true if a scroll box or window consumed this frame's wheel.
- `pub fn is_dev_tools_capturing_input(&self) -> bool` (method, since 0.3.2): Whether the developer tools are taking input. (visible, and the pressed point is inside the panel)
  - returns bool: true if the developer tools are visible and the input position is inside the panel. false if there are no developer tools.
- `pub fn pre_draw(&self, graphic: &mut Graphic)` (method, since 0.3.2): Pre-draw. (fills the whole canvas with the background color and applies the view coordinate system. Including outside the safe area)
  - `graphic` &mut Graphic: Graphic to fill.
- `pub fn post_draw(&mut self, graphic: &mut Graphic)` (method, since 0.4.0): Post-draw. (draws the darkening curtain over the whole canvas including the safe area, and draws the developer tools on top)
  - A fade starter the scene did not take out is handed to the next polling turn here.
  - `graphic` &mut Graphic: Graphic to draw with.
- `pub fn draw_screen_fade(&self, graphic: &mut Graphic)` (method, since 0.4.0): Draws the darkening curtain. (over the whole canvas including the safe area, the original drawScreenFade)
  - Does not draw if the curtain's opacity is 0. Sets the view coordinate system again after drawing.
  - `graphic` &mut Graphic: Graphic to draw with.
- `pub fn fade_screen(&mut self, on_dark: Option<ScreenFadeEvent>) -> bool` (method, since 0.4.0): Darkens then brightens. (calls on_dark when fully dark, and if it returns a handle, stays dark until it is released. false if already fading)
  - tick moves the curtain and post_draw draws it. Presses and the wheel are not accepted while the curtain is up.
  - `on_dark` Option<ScreenFadeEvent>: Function to call when fully dark. (takes the tree and engine, and if it returns a handle, stays dark until it is released) None darkens and then brightens right away.
  - returns bool: true if the fade started. false if already fading.

  Example: Switch screens at full dark and brighten right away

  ```rust
  use vanilla::{Engine, EngineConfiguration, GameSceneBase, NodeTree};
  
  let engine = Engine::new(EngineConfiguration::new());
  engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_screen_fade_seconds(0.0);
  assert!(game_scene_base.fade_screen(Some(Box::new(|node_tree: &mut NodeTree, _engine: &Engine| {
  	let root_id = node_tree.get_root_id();
  	node_tree.create_child(root_id, "nextStage");
  	None
  }))));
  assert!(!game_scene_base.fade_screen(None));
  game_scene_base.tick(0.016);
  assert_eq!(game_scene_base.get_screen_fade_alpha(), 1.0);
  game_scene_base.tick(0.016);
  assert!(!game_scene_base.is_screen_fading());
  ```

- `pub fn fade_screen_with_hold(&mut self, on_dark: ScreenFadeHoldEvent) -> bool` (method, since 0.4.0): Callback form of darken then brighten. (passes a handle to on_dark when fully dark, and stays dark until that handle is released. false if already fading)
  - The handle's release is in place of the resolve of the Promise returned by the original onDark. Releasing it right when fully dark brightens it right away.
  - `on_dark` ScreenFadeHoldEvent: Function that receives the tree, engine, and handle when fully dark. (hold the handle and release it when the work is done)
  - returns bool: true if the fade started. false if already fading.

  Example: Keep the handle and release it when the work is done

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, GameSceneBase, NodeTree, ScreenFadeHold};
  
  let engine = Engine::new(EngineConfiguration::new());
  engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_screen_fade_seconds(0.0);
  let held_hold: Rc<RefCell<Option<ScreenFadeHold>>> = Rc::new(RefCell::new(None));
  let held_hold_for_event = held_hold.clone();
  assert!(game_scene_base.fade_screen_with_hold(Box::new(move |_node_tree: &mut NodeTree, _engine: &Engine, screen_fade_hold: ScreenFadeHold| {
  	*held_hold_for_event.borrow_mut() = Some(screen_fade_hold);
  })));
  game_scene_base.tick(0.016);
  game_scene_base.tick(0.016);
  assert_eq!(game_scene_base.get_screen_fade_alpha(), 1.0);
  if let Some(screen_fade_hold) = held_hold.borrow().as_ref() {
  	screen_fade_hold.release();
  }
  game_scene_base.tick(0.016);
  game_scene_base.tick(0.016);
  assert!(!game_scene_base.is_screen_fading());
  ```

- `pub fn fade_screen_async<S, F, OnDarkFuture>(&mut self, on_dark: F) -> bool where S: Scene + 'static, F: FnOnce(SceneContext<S>) -> OnDarkFuture + 'static, OnDarkFuture: Future<Output = ()> + 'static,` (method, since 0.4.0): Async form of darken then brighten. (the original fadeScreen(async () => { ... }), false if already fading)
  - At the tick it becomes fully dark, hands the future returned by on_dark over as this scene's task and runs it right there up to the first await, and brightens when the future finishes.
    Inside the future, SceneContext::with borrows the scene (type S) and the engine.
  - S is the type of the scene holding this base. (for a scene implementing GameScene, GameScene::fade_screen_async fills in S) For another type it brightens right away.
  - To start, the scene takes it out with take_screen_fade_dark_starter after the base tick and starts it. (game_scene! and ui_scene! do this automatically)
    If not taken out, the base hands it over at the next polling turn in post_draw or the next tick.
  - `on_dark` F: Function that takes a `SceneContext<S>` when fully dark and returns a future. (brightens when the future finishes or is dropped)
  - returns bool: true if the fade started. false if already fading.

  Example: Calling it with the scene type from a scene that implements Scene directly (the starter is taken out in tick, see the ScreenFadeDarkStarter example)

  ```rust
  use vanilla::{Engine, GameSceneBase, Scene, SceneBase, SceneContext, Vector2};
  
  struct PuzzleScene {
  	game_scene_base: GameSceneBase,
  	stage_number: u32,
  }
  
  impl Scene for PuzzleScene {
  	fn get_scene_base(&self) -> &SceneBase {
  		self.game_scene_base.get_scene_base()
  	}
  
  	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
  		self.game_scene_base.get_scene_base_mut()
  	}
  
  	fn touch_press(&mut self, _view_input_position: Vector2) {
  		self.game_scene_base.fade_screen_async::<PuzzleScene, _, _>(|mut scene_context: SceneContext<PuzzleScene>| async move {
  			scene_context.with(|scene, _engine| {
  				scene.stage_number += 1;
  			});
  		});
  	}
  
  	fn tick(&mut self, time_delta: f64) {
  		self.game_scene_base.tick(time_delta);
  		if let Some(screen_fade_dark_starter) = self.game_scene_base.take_screen_fade_dark_starter() {
  			screen_fade_dark_starter.start(self);
  		}
  	}
  }
  ```

- `pub fn take_screen_fade_dark_starter(&mut self) -> Option<ScreenFadeDarkStarter>` (method, since 0.4.0): Takes out the starter of a fully dark fade_screen_async. (the scene takes it out after the base tick and calls start(scene, engine), None if not yet)
  - returns Option<ScreenFadeDarkStarter>: The starter, on the first call after it goes fully dark. None if not dark yet or already taken out.
- `pub fn is_screen_fading(&self) -> bool` (method, since 0.4.0): Whether it is fading. (darkening, waiting for the handle, or brightening)
  - returns bool: true while darkening, waiting on a handle, or brightening.
- `pub fn set_screen_fade_color(&mut self, color: impl Into<Color>)` (method, since 0.4.0): Sets the color of the darkening curtain. (default black)
  - `color` impl Into<Color>: Curtain color. (a Color or a string like "#rrggbb")
- `pub fn set_screen_fade_seconds(&mut self, seconds: f64)` (method, since 0.4.0): Sets the darkening time and the brightening time. (seconds, default 0.35, immediate if 0)
  - `seconds` f64: Time to darken, also the time to brighten. (seconds, negative is treated as 0)
- `pub fn get_screen_fade_alpha(&self) -> f64` (method, since 0.4.0): Opacity of the darkening curtain. (0 ~ 1)
  - returns f64: Curtain opacity. (0 means no curtain, 1 means fully dark)
- `pub fn is_user_interface_at(&self, view_position: Vector2) -> bool` (method, since 0.4.0): Whether there is UI (a pressable node: a button, a window's dimmer and panel, a scroll box) at that point. (view coordinates)
  - `view_position` Vector2: Position to check. (view coordinates)
  - returns bool: true if there is a pressable node at that position.
- `pub fn set_play_input_enabled(&mut self, is_play_input_enabled: bool)` (method, since 0.4.0): Turns on play input collection. (turning it off discards what was collected)
  - When on, tick collects the input the UI did not take, and the scene takes it out with take_play_inputs. Presses that went to play are forgotten.
  - `is_play_input_enabled` bool: true collects, false turns it off and discards what was collected.

  Example: Collect and take out the presses and releases the UI did not take (coordinates relative to the top left of the safe area)

  ```rust
  use vanilla::{Engine, EngineConfiguration, GameSceneBase, PlayInput, SafeAreaInsets, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_safe_area_insets(Some(SafeAreaInsets::create(10.0, 0.0, 0.0, 20.0)));
  game_scene_base.initialize(engine);
  game_scene_base.tick(0.016);
  game_scene_base.set_play_input_enabled(true);
  engine.get_input_manager_mut().set_view_input_position(Vector2::create(120.0, 110.0));
  engine.get_input_manager_mut().set_touch_pressed(true);
  game_scene_base.tick(0.016);
  engine.get_input_manager_mut().set_touch_pressed(false);
  engine.get_input_manager_mut().set_touch_released(true);
  game_scene_base.tick(0.016);
  let play_inputs = game_scene_base.take_play_inputs();
  assert_eq!(play_inputs.first(), Some(&PlayInput::Press(Vector2::create(100.0, 100.0))));
  assert_eq!(play_inputs.last(), Some(&PlayInput::Release(Vector2::create(100.0, 100.0))));
  assert!(game_scene_base.take_play_inputs().is_empty());
  ```

- `pub fn set_play_input_handler(&mut self, play_input_handler: Option<PlayInputHandler>)` (method, since 0.4.0): Sets the handler for input the UI did not take. (the original setPlayInputHandler, None turns it off, presses that went to play are forgotten)
  - The handler cannot borrow the scene, so the scene state is shared through `Rc<RefCell>`.
  - `play_input_handler` Option<PlayInputHandler>: Function that receives the input the UI did not take. (play area coordinates) None turns it off.

  Example: The handler receives presses and releases

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, GameSceneBase, PlayInput, SafeAreaInsets, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_safe_area_insets(Some(SafeAreaInsets::create(0.0, 0.0, 0.0, 0.0)));
  game_scene_base.initialize(engine);
  let play_input_list: Rc<RefCell<Vec<PlayInput>>> = Rc::new(RefCell::new(Vec::new()));
  let play_input_list_for_handler = play_input_list.clone();
  game_scene_base.set_play_input_handler(Some(Box::new(move |play_input: PlayInput| {
  	play_input_list_for_handler.borrow_mut().push(play_input);
  })));
  engine.get_input_manager_mut().set_view_input_position(Vector2::create(50.0, 60.0));
  engine.get_input_manager_mut().set_touch_pressed(true);
  game_scene_base.tick(0.016);
  engine.get_input_manager_mut().set_touch_pressed(false);
  engine.get_input_manager_mut().set_touch_released(true);
  game_scene_base.tick(0.016);
  assert_eq!(*play_input_list.borrow(), vec![PlayInput::Press(Vector2::create(50.0, 60.0)), PlayInput::Release(Vector2::create(50.0, 60.0))]);
  ```

- `pub fn take_play_inputs(&mut self) -> Vec<PlayInput>` (method, since 0.4.0): Takes out the collected play inputs. (in arrival order, empties them when taken)
  - returns Vec<PlayInput>: List of collected play inputs. (an empty list if collection is off)
- `pub fn convert_view_to_play_area(&self, view_position: Vector2) -> Vector2` (method, since 0.4.0): View coordinates → play area coordinates. (the top left of the safe area is 0, 0)
  - `view_position` Vector2: Position to convert. (view coordinates)
  - returns Vector2: The position minus the top left of the last computed safe area.
- `pub fn set_play_area_reference(&mut self, fixed_length: f64, is_landscape: bool, engine: Option<&Engine>)` (method, since 0.4.0): Sets the play area reference. (stretches the reference resolution so the fixed side length of the play area without the safe area is always fixed_length)
  - Canvas length : length without the safe area = reference resolution length : fixed_length.
  - If is_landscape, the width is the fixed side, otherwise the height. The view scale mode is set to match. (width fixed StretchWidthExpandHeight, height fixed StretchHeightExpandWidth)
  - Safe area sides to ignore are passed with ViewManager::set_ignored_safe_area_sides. A fixed_length of 0 turns it off.
  - Given the engine, it applies right away. The scene calls apply_play_area_reference at the start of resize.
  - `fixed_length` f64: Fixed side length of the play area without the safe area. (view coordinates, 0 or less turns it off)
  - `is_landscape` bool: true fixes the horizontal side, false the vertical side.
  - `engine` Option<&Engine>: Engine to apply it to right away. None only sets the view scale mode and applies it in initialize.

  Example: With a fixed height of 720, the height minus the top and bottom insets is always 720

  ```rust
  use vanilla::{Engine, EngineConfiguration, GameSceneBase, SafeAreaInsets, ViewScaleMode};
  
  let engine = Engine::new(EngineConfiguration::new());
  engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
  engine.get_view_manager_mut().set_safe_area_override(Some(SafeAreaInsets::create(40.0, 0.0, 30.0, 0.0)));
  let mut game_scene_base = GameSceneBase::new();
  game_scene_base.set_play_area_reference(720.0, false, Some(engine));
  assert_eq!(engine.get_view_manager().get_view_scale_mode(), ViewScaleMode::StretchHeightExpandWidth);
  assert_eq!(game_scene_base.get_play_area_fixed_length(), 720.0);
  game_scene_base.initialize(engine);
  game_scene_base.layout();
  assert!((game_scene_base.get_safe_area_rect().size.y - 720.0).abs() < 0.01);
  ```

- `pub fn get_play_area_fixed_length(&self) -> f64` (method, since 0.4.0): Fixed side length of the play area. (not used if 0)
  - returns f64: Fixed side length. (view coordinates, 0 means the play area reference is not used)
- `pub fn apply_play_area_reference(&mut self) -> bool` (method, since 0.4.0): Applies the play area reference to the reference resolution. (computed only from the canvas and inset sizes, so calling it any number of times gives the same result. If changed, recomputes the view area and returns true)
  - returns bool: true if the reference resolution was changed. false if the play area reference is not used, the canvas size is 0, it cannot be computed, or it is already the same.
- `pub fn calculate_play_area_reference_length(fixed_length: f64, is_landscape: bool, canvas_native_size: Vector2, safe_area_insets: SafeAreaInsets, inset_scale: f64) -> f64` (static, since 0.4.0): Computes the reference resolution length for the play area reference. (static, insets in view coordinates, inset_scale is the view coordinates → canvas units scale, 0 if it cannot be computed)
  - It is fixed_length × canvas length / (canvas length - inset sum × inset_scale).
  - `fixed_length` f64: Fixed side length of the play area.
  - `is_landscape` bool: true computes horizontally (left, right insets), false vertically (top, bottom insets).
  - `canvas_native_size` Vector2: Logical canvas size.
  - `safe_area_insets` SafeAreaInsets: Safe area insets. (view coordinates)
  - `inset_scale` f64: Scale that converts insets to canvas units.
  - returns f64: Reference resolution length of the fixed side. 0 if the canvas length or the length minus the insets is 0 or less.

  Example: Subtracting insets of 70 from a height of 600 stretches the reference resolution by that much

  ```rust
  use vanilla::{GameSceneBase, SafeAreaInsets, Vector2};
  
  let reference_length = GameSceneBase::calculate_play_area_reference_length(720.0, false, Vector2::create(800.0, 600.0), SafeAreaInsets::create(40.0, 0.0, 30.0, 0.0), 1.0);
  assert!((reference_length - 720.0 * 600.0 / 530.0).abs() < 0.01);
  let landscape_length = GameSceneBase::calculate_play_area_reference_length(1920.0, true, Vector2::create(1000.0, 500.0), SafeAreaInsets::create(0.0, 25.0, 0.0, 25.0), 2.0);
  assert!((landscape_length - 1920.0 * 1000.0 / 900.0).abs() < 0.01);
  assert_eq!(GameSceneBase::calculate_play_area_reference_length(720.0, false, Vector2::create(800.0, 0.0), SafeAreaInsets::create(0.0, 0.0, 0.0, 0.0), 1.0), 0.0);
  ```

## GameScene (trait) ('static)

Game scene. (where a scene inheriting the original GameScene overrides)
- The scene contains a GameSceneBase, implements this trait, and gets a Scene with game_scene!(scene type).
- The Scene functions made by game_scene! call the base (GameSceneBase) first and then the function of the same name in this trait. (an override that calls super first in the original)
  Only post_draw calls the scene's first and draws the base (fade curtain, developer tools) on top.
- layout is called after the base recomputes the safe area. (on resize, and when tick sees a view size change. Also once on the first tick)
- load_assets is called in load after the base requests the loading image. Request the scene's assets and hand them over with get_scene_base_mut().track_asset.

Example: Contain the base, fill in only the places to override, and get a Scene with one game_scene! line

```rust
use vanilla::{Engine, EngineConfiguration, GameScene, GameSceneBase, ImageAsset, Scene};

struct TitleScene {
	game_scene_base: GameSceneBase,
	logo_asset: ImageAsset,
	layout_count: u32,
}

impl GameScene for TitleScene {
	fn get_game_scene_base(&self) -> &GameSceneBase {
		&self.game_scene_base
	}

	fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase {
		&mut self.game_scene_base
	}

	fn load_assets(&mut self) {
		let engine = Engine::get_engine().unwrap();
		self.logo_asset.load(engine, "examples/assets/atlas/icons.png");
		self.game_scene_base.get_scene_base_mut().track_asset(&self.logo_asset);
	}

	fn initialize(&mut self, _engine: &Engine) {
		let safe_area_id = self.game_scene_base.get_safe_area_node_id().expect("safe area node");
		self.game_scene_base.get_scene_base_mut().get_node_tree_mut().create_child(safe_area_id, "logo");
	}

	fn layout(&mut self) {
		self.layout_count += 1;
	}
}

vanilla::game_scene!(TitleScene);

let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut title_scene = TitleScene {
	game_scene_base: GameSceneBase::new(),
	logo_asset: ImageAsset::new(),
	layout_count: 0,
};
title_scene.game_scene_base.set_loading_min_duration_ms(0.0);
Scene::create(&mut title_scene);
Scene::load(&mut title_scene, engine);
assert!(title_scene.get_scene_base().are_tracked_assets_finished());
Scene::initialize(&mut title_scene, engine);
Scene::tick(&mut title_scene, 0.016);
assert_eq!(title_scene.layout_count, 1);
```

Example: Pass it to the engine as the first scene and run it (compile only, since it opens a window)

```rust
use vanilla::{Engine, EngineConfiguration, GameScene, GameSceneBase, Vector2};

struct MainScene {
	game_scene_base: GameSceneBase,
}

impl GameScene for MainScene {
	fn get_game_scene_base(&self) -> &GameSceneBase {
		&self.game_scene_base
	}

	fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase {
		&mut self.game_scene_base
	}
}

vanilla::game_scene!(MainScene);

let mut engine_configuration = EngineConfiguration::new();
engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
let engine = Engine::new(engine_configuration);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_loading_image_url("examples/assets/atlas/icons.png");
let main_scene = MainScene {
	game_scene_base,
};
if let Err(error) = engine.run(Box::new(main_scene)) {
	eprintln!("{}", error);
}
```

- `fn get_game_scene_base(&self) -> &GameSceneBase` (method, since 0.4.0): Returns the base.
  - returns &GameSceneBase: Base contained in the scene.
- `fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase` (method, since 0.4.0): Returns the base. (mutable)
  - returns &mut GameSceneBase: Base contained in the scene. (mutable)
- `fn load_assets(&mut self)` (method, since 0.4.0): Loads the scene's assets. (overrides the original async loadAssets(), after the base requests the loading image)
  - Take the engine with Engine::get_engine(). To load with await, hand over a loading task with engine.spawn_scene_task(self, ...) and register it with get_game_scene_base_mut().get_scene_base_mut().track_task.
- `fn fade_screen_async<F, OnDarkFuture>(&mut self, on_dark: F) -> bool where Self: Scene + Sized, F: FnOnce(SceneContext<Self>) -> OnDarkFuture + 'static, OnDarkFuture: Future<Output = ()> + 'static,` (method, since 0.4.0): Async form of darken then brighten. (the original fadeScreen(async () => { ... }), false if already fading)
  - At the tick it becomes fully dark, hands the future returned by on_dark over as this scene's task and runs it right there up to the first await, and brightens when it finishes.
    Inside the future, SceneContext::with borrows this scene and the engine.
  - `on_dark` F: Function that takes a `SceneContext<Self>` when fully dark and returns a future. (brightens when the future finishes or is dropped)
  - returns bool: true if the fade started. false if already fading.

  Example: On press, darken and then move on to the next round (game_scene! handles the start)

  ```rust
  use vanilla::{Engine, GameScene, GameSceneBase, SceneContext, Vector2};
  
  struct StageScene {
  	game_scene_base: GameSceneBase,
  	stage_number: u32,
  }
  
  impl GameScene for StageScene {
  	fn get_game_scene_base(&self) -> &GameSceneBase {
  		&self.game_scene_base
  	}
  
  	fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase {
  		&mut self.game_scene_base
  	}
  
  	fn touch_press(&mut self, _view_input_position: Vector2) {
  		self.fade_screen_async(|mut scene_context: SceneContext<StageScene>| async move {
  			scene_context.with(|scene, _engine| {
  				scene.stage_number += 1;
  			});
  		});
  	}
  }
  
  vanilla::game_scene!(StageScene);
  ```

- `fn draw_on_load(&mut self, _graphic: &mut Graphic)` (method, since 0.4.0): Draws more on top of the loading screen. (after the base's loading screen)
  - `_graphic` &mut Graphic: Graphic to draw with. (the view coordinate system is set)
- `fn initialize(&mut self, _engine: &Engine)` (method, since 0.4.0): Initializes. (after the base initialize, once the safe area node exists)
  - `_engine` &Engine: Engine.
- `fn destroy(&mut self)` (method, since 0.4.0): Destroys.
- `fn layout(&mut self)` (method, since 0.4.0): Layout. (overrides the original layout, after the base recomputes the safe area)
- `fn tick(&mut self, _time_delta: f64)` (method, since 0.4.0): Updates. (after the base tick: nodes, touches, tweens, layout, fade, developer tools)
  - `_time_delta` f64: Frame interval multiplied by the time scale. (seconds)
- `fn pre_draw(&mut self, _graphic: &mut Graphic)` (method, since 0.4.0): Pre-draw. (after the base fills the background)
  - `_graphic` &mut Graphic: Graphic to draw with.
- `fn draw(&mut self, _graphic: &mut Graphic)` (method, since 0.4.0): Draw. (after drawing the node tree)
  - `_graphic` &mut Graphic: Graphic to draw with.
- `fn post_draw(&mut self, _graphic: &mut Graphic)` (method, since 0.4.0): Post-draw. (before the base's fade curtain and developer tools)
  - `_graphic` &mut Graphic: Graphic to draw with.
- `fn finalize(&mut self, _engine: &Engine)` (method, since 0.4.0): Finalizes. (before unload when taking down, overrides the original Scene.finalize)
  - `_engine` &Engine: Engine.
- `fn unload(&mut self, _engine: &Engine)` (method, since 0.4.0): Unloads. (after finalize when taking down, overrides the original Scene.unload)
  - `_engine` &Engine: Engine.
- `fn on_page_process_restored(&mut self)` (method, since 0.4.0): Page process restore and visibility restore. (overrides the original onPageProcessRestored, onPageVisibilityRestored)
  - This function is the page process restore one. Visibility restore is on_page_visibility_restored.
- `fn on_page_visibility_restored(&mut self)` (method, since 0.4.0): Page visibility restored. (overrides the original onPageVisibilityRestored)
- `fn touch_press(&mut self, _view_input_position: Vector2)` (method, since 0.4.0): Touch hooks of the scene. (overrides the original touchPress, touchMove, touchRelease, touchCancel, touchWheel, called by the engine after the base passes them to the UI and play input)
  - This function is the press one. Move, release, cancel, and wheel are touch_move, touch_release, touch_cancel, touch_wheel.
  - `_view_input_position` Vector2: Press position. (view coordinates)
- `fn touch_move(&mut self, _view_input_position: Vector2)` (method, since 0.4.0): Touch move. (overrides the original touchMove)
  - `_view_input_position` Vector2: Current position. (view coordinates)
- `fn touch_release(&mut self, _view_input_position: Vector2)` (method, since 0.4.0): Touch release. (overrides the original touchRelease)
  - `_view_input_position` Vector2: Release position. (view coordinates)
- `fn touch_cancel(&mut self, _view_input_position: Vector2)` (method, since 0.4.0): Touch cancel. (overrides the original touchCancel)
  - `_view_input_position` Vector2: Canceled position. (view coordinates)
- `fn touch_wheel(&mut self, _view_input_position: Vector2, _wheel_delta: Vector2)` (method, since 0.4.0): Wheel. (overrides the original touchWheel)
  - `_view_input_position` Vector2: Position where the wheel was rolled. (view coordinates)
  - `_wheel_delta` Vector2: Wheel value. (horizontal, vertical)

## Functions and constants

- `macro_rules! game_scene` (method, since 0.4.0): Makes a Scene for a scene implementing GameScene. (vanilla::game_scene!(TitleScene);)

## PlayInput (enum) (Clone, Copy, Debug, PartialEq)

Input the UI did not take. (play area coordinates: relative to the top left of the safe area, press, move, release, wheel of the original handler)

- `Press` = `Press(Vector2)`: A press the UI did not take.
- `Move` = `Move(Vector2)`: Move of a press that went to play.
- `Release` = `Release(Vector2)`: Release of a press that went to play. (including cancel)
- `Wheel` = `Wheel(Vector2, Vector2)`: Wheel outside the UI. (position, wheel value)
