# API (vanilla-engine 0.4.0)

- [animation](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/animation&lang=en): Animation. (the original src/animation)
- Timeline: keyframe document player. Animator: state machine that picks and blends sprite clips. Action: scripted sequences that run in order.
- [animation/action](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/animation/action&lang=en): Action. (a script-style sequence that runs steps in order)
- A port of the original animation/action.js. Stack wait / condition / call / repeat / forever / loop steps,
  then call step every frame after start and they run in order.
- Usage:
  ```text
    let mut action: Action<WorldNode> = Action::new()
        .wait(1.0, ActionCallbacks::new().updated(|progress, node: &mut WorldNode| node.set_local_opacity(progress)))
        .condition(|node: &WorldNode| node.is_active(), ActionConditionCallbacks::new())
        .call(|node: &mut WorldNode| node.set_local_scale(Vector2::create(2.0, 2.0)))
        .repeat(3, Action::new().wait(0.5, ActionCallbacks::new()))
        .forever(Action::new().wait(2.0, ActionCallbacks::new()));
    action.start(&mut node_tree, Some(node_id));
    // every frame:
    action.step(&mut node_tree, time_delta);
  ```
- Differences from the original:
  - The original start(target) holds the target and passes it to callbacks on every step(timeDelta). Rust cannot hold a borrowed target,
    so a node target is held as a handle: start(tree, Some(node)) holds the target and step(tree, time) passes that node to the callbacks,
    get_target returns that node, and start(tree, None) restarts with the previous target like the original start().
  - The form that does not hold a target and passes it every time is start_with(target), step_with(target, time) in both engines. (original startWith, stepWith)
    Use T for a target that is not a node (several nodes, game state) and run it in this form. (the default of T is WorldNode)
    The inner actions of repeat, forever, and loop also run in this form in both engines and do not hold a target. (get_target of an inner action is unchanged)
  - Callback objects ({ started, updated, completed }): the wait step uses ActionCallbacks (updated takes (progress, target)),
    and the condition step uses ActionConditionCallbacks (updated takes (target)). The original is one object form that differs only in argument count,
    but Rust must fix the argument shape of a callback as a type, so it is split in two.
  - The conditional loop is repeat_while in both engines. (original repeatWhile; the reserved word loop is not used as a name)
  - When call steps follow one another, the original passes through recursion and the Rust version through a loop. (the result is the same)
- The condition function receives the target like the original (&T in Rust). wait finishes with progress 1 if duration is 0 or less.
  repeat skips without running if the count is 0. (same as the original)
- [animation/animator](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/animation/animator&lang=en): Animator. (Picks and blends sprite clips with a state machine)
- A port of the original animation/animator.js. States (clip, speed, loop), parameters (float, integer, boolean, trigger),
  transitions (condition list, exit time, blend time, transitions from any state), the transition check in each frame's tick, and the crossfade weights match the original.
- It starts in the first added state. play moves to any state immediately. A transition's from and to are indices in the Animator state list, and a None from moves from any state (Any State).
- tick order: advance the state time (both states while blending) → while blending, move to the next state once the blend time is filled
  → when not blending, check transitions from any state, then transitions leaving the current state, each in the order added, and take the first one that holds.
  No new transition is checked while blending. A trigger used as a condition is cleared when that transition is taken.
- The exit time is the normalized time of the leaving state. The transition can only happen on the update that passes that time, and for a looping state an exit time below 1 is checked every cycle.
- Differences from the original:
  - The original getStates / get_transitions return a List, the Rust version returns a slice (&`[..]`). The dictionary of the original getParameters is returned by get_parameters as a list of names and AnimatorParameter (in insertion order).
  - An original condition is a { parameterName, mode, threshold } object, the Rust version is an AnimationCondition with the same fields. The string values of the original AnimationConditionMode are enum values.
  - Integer parameters are i32, floats and thresholds are f64 like the original numbers. An integer is converted to f64 when compared with a threshold.
- [animation/timeline](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/animation/timeline&lang=en): Timeline. (keyframe animation document player)
- A port of the original animation/timeline.js. The document (description) is JSON made of a stage node list + tracks (target name / property / keys) + markers,
  saved by the timeline editor. A key's easing applies to the span from that key to the next key.
- Easing curves use easing_function from core/tween.rs as is. "bezier" uses the same control points as CSS cubic-bezier.
- Usage:
  ```text
    // Request the document in the scene's create and hand it over.
    self.timeline_asset.load(engine, "assets/intro.timeline.json");
    self.scene_base.track_asset(&self.timeline_asset);
    // Build the stage in initialize and play it.
    let mut timeline = Timeline::create_from_json_asset(&mut self.timeline_asset).unwrap_or_default();
    let stage_id = self.scene_base.get_root_id();
    timeline.build_stage(self.scene_base.get_node_tree_mut(), stage_id, Some(&|image_name: &str| image_table.get(image_name).cloned()));
    timeline.play();
    // Every frame (tick):
    timeline.tick(self.scene_base.get_node_tree_mut(), time_delta);
  ```
- Differences from the original:
  - Targets are TimelineTarget instead of object references. Nodes are Node(NodeId), and things that are not nodes (such as screen effects) are External(`Rc<RefCell<dyn TimelinePropertyTarget>>`).
    Functions that act on nodes (tick, seek, stop, evaluate, compile, build_stage, bind) also take the NodeTree.
  - For External targets, evaluate calls set_timeline_property right there, as in the original. (the scene shares the target as `Rc<RefCell>`)
    The receiving side implements the TimelinePropertyTarget trait. ScreenEffect implements it in this file.
    Values the last evaluate applied to External targets can be read with get_external_properties. (for editors and tests)
  - Values hold the original's number / string / boolean as the TimelineValue enum. Numbers are f64.
  - Handlers take the timeline itself (&mut Timeline) as the last argument as in the original, followed by the NodeTree to pass to node functions.
    The handler is taken out of its slot while it is called, so pause, seek and set_*_handler can be called inside a handler. (a newly set handler wins)
  - Text properties (text, number, fontSize, visibleCharacters, color) also apply to RichText nodes, just as the original getComponent(Text) also finds RichText, which inherits Text.
  - resolve_timeline_easing returns a TimelineEasing value instead of a function. (call it with evaluate(progress))
  - TIMELINE_PROPERTY_DEFINITIONS is an array of definitions instead of a name → definition object, searched with find_timeline_property_definition.
    TIMELINE_NODE_DEFAULTS is a TimelineNodeDescription filled with the defaults. (the original key type is node_type)
  - The original's sprite grid table and sound table (WeakMap) became small components attached to nodes, TimelineSpriteFrameGrid and TimelineSound.
  - The original Timeline.setAudioManager (static) and the asynchronous loading of sound nodes became load_sounds(node_tree, engine).
    Calling it once after building the stage loads an audio asset and creates a player for each sound node. (the scene may take over the returned assets with track_audio_asset)
  - loadFromUrl (asynchronous fetch) is load_from_url(engine, asset path). It asks for the bytes through the engine's asset fetching, and awaiting it inside an engine task yields the timeline.
    (desktop uses the asset folder candidates, web fetches from asset_base_url) Without await, pass a document received with JsonAsset to create_from_json_asset / load_from_text.
  - "data:" URL images: on the web, as in the original, the browser decodes them (fetch and HTMLImageElement, platform/web.rs), and once decoded they are set on the sprite and the description's cell is picked again.
    (the original image.onload's applySpriteFrame; meanwhile TimelineSpriteFrameGrid waits and updates)
    On desktop they are decoded right there. Like a browser, it first decodes percent forms (%XX) in the body, and decodes base64 if ;base64. If the URL's type is image/svg+xml it is an SVG drawn with resvg,
    otherwise a raster identified by its content (png, jpeg, webp, gif, bmp, ico, avif). (Image::load_from_memory_with_mime_type)
- Easing curve values are the same as the original. If two stage nodes have the same name, both are attached and the later one stays in the name table (same as the original).
  If a parent is itself or forms a cycle, the node is attached to the stage parent. load_from_text and create_from_json_asset also exist in the original.
- [base](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base&lang=en): Engine-independent base types.
- [base/color](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/color&lang=en): Color. (each component 0 ~ 1, the original base/color.js)
- The original's red, green, blue and alpha properties are public fields, and clone is replaced by copying (Copy).
- Components are usually 0 ~ 1, but like the original, values outside are stored without clamping. (HDR colors above 1 such as glowing colors, same as Unity Color)
- to_rgba_string and to_hex_string add alpha only when alpha is less than 1, as in the original, and write components clamped to 0 ~ 255 and the rgba alpha clamped to 0 ~ 1.
  (same as converting to Unity Color32, NaN is "NaN" as in the original)
- create_from_rgba reads the same thing as the regular expression of the original createFromRGBA. (it must start with rgb after lowercasing, and the first rgb(integer, integer, integer[, alpha]) within it is read)
- create_from_hex must start with # like the original createFromHEX, and reads "#rgb", "#rgba", "#rrggbb" and "#rrggbbaa".
  It reads two characters at a time like the original parseInt(string, 16), so other lengths and non-hex characters also give the same values as the original (unreadable components are NaN).
- Since Color is Copy, from_hex_cached and from_cache give a copy of the cached value instead of a shared instance.
  Both caches discard the least recently used entries first when they exceed 1024. (the rule of the original fromCache; the same rule was added to the original fromHEXCached)
- `From<&str>`, which builds a color from a string, goes through from_cache like the original Graphic's parseColorValue.
- [base/colors](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/colors&lang=en): Color name constants. (the original base/colors.js)
- The values of the original Colors object moved to associated constants. They are "#rrggbb" strings as in the original.
- [base/dataurl](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/dataurl&lang=en): Decodes a "data:" URL. (in the original, fetch and the browser accept data: URLs as is)
- Decodes percent forms in the body first, then decodes base64 if the header ends with ;base64 (case-insensitive). (the same order as fetch's data: URL handling)
- The type is between "data:" and ;base64. If empty, it is text/plain;charset=US-ASCII like fetch.
- Used by desktop asset loading (Engine::request_asset_bytes, load_image, load_audio_asset) and the timeline's data: images.
  On the web, the browser's fetch decodes data: URLs. (the asset base URL is not prepended)
- [base/format](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/format&lang=en): Formatting utilities. (the original base/format.js, Format in the original import.js)
- Gathers number string formatting that repeats in every game, such as currency and score display.
- The original takes JS numbers (f64). The Rust version also takes f64 and produces the same strings as the original for rounding, negatives, 0, infinity and NaN.
  toFixed rounds by the actual value and rounds exact halves up. toLocaleString rounds half up at the third decimal of the shortest decimal form.
  String(number) is the Number.prototype.toString form, so values of 1e21 or more and 1e-7 or less are written in exponent form. (1e+21, 1e-7)
- Rust has no default arguments, so they are always passed. (the original defaults: format_number's locale is "en-US", format_number_with_unit's is "ko-KR",
  format_compact_number's fraction_digits is 1, format_padded_number's range is f64::NEG_INFINITY and f64::INFINITY)
- Locales: the original leaves this to the browser's Intl (ICU). Rust std has nothing like it, so the decimal point, thousands separator, negative prefix, digit shapes,
  upper group size (Indian style is 3 then 2), minimum grouping digits (es, pl and others that do not group 1234) and NaN string were extracted from node 25's Intl (ICU 78.3, CLDR 48) into a table.
  Infinity is ∞ in every locale. Language tags are case-insensitive and are looked up in the table while removing trailing subtags one at a time. (zh-Hant-TW → zh-hant)
  Unicode extensions (-u-...) are not used to choose the number format. Tags not in the table use the system language, just as the original uses the browser's default locale.
  The system language is the first of the shared function also used by Localization.detect_language (localization::read_preferred_language_tags).
  (navigator.languages on the web; on desktop, the system preferred language order read by sys-locale: GetUserPreferredUILanguages on Windows, CFLocaleCopyPreferredLanguages on Mac,
  LANGUAGE / LC_ALL / LC_MESSAGES / LANG on Linux. If that is not in the table either, en-US)
- Language tag check: the original toLocaleString throws a RangeError for a tag that is not in BCP 47 form (Unicode locale identifier, UTS 35).
  The Rust version runs the same check as Chrome (V8's CanonicalizeLanguageTag, ECMA-402 IsStructurallyValidLanguageTag), and an invalid tag is Err(FormatError::InvalidLanguageTag).
  (an underscore "EN_gb", an empty string, a 4-letter language "root", duplicate variants or extension singletons, an empty extension "en-u" and so on. The error text matches Chrome's "Invalid language tag: ..." too)
- fraction_digits is valid from 0 ~ 100 like the original toFixed. Going beyond does not throw and outputs that many digits.
- [base/fsm](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/fsm&lang=en): Finite state machine. (FiniteStateMachine of the original base/fsm.js)
- Standardizes the "string state + switch statement + manual transitions" that many games each built on their own.
- Register enter / tick / exit handling for each state and transition with change_state().
- set_transition_guard() can block disallowed transitions.
- The original's state names are strings. The Rust version lets you pick the state name type. (String by default; enums or &'static str also work)
  The original's null state (no state yet) is None.
- The original handlers object { enter?, tick?, exit? } is the StateHandlers struct. Callbacks are `Box<dyn FnMut>`, so
  to change game state, capture `Rc<Cell>` / `Rc<RefCell>`.
- The original calls the same machine's change_state right there inside a handler. In the Rust version a handler cannot borrow the machine, so
  capture the handle (StateChangeRequester) received from get_state_change_requester in the handler and request through its change_state.
  The machine transitions in request order after that handler ends. (the same as the original calling change_state at the very end of a handler)
  Whether the request succeeds is not returned right there. A request made outside a handler transitions on the next tick or change_state.
- [base/identifier](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/identifier&lang=en): Identifiers. (the original base/identifier.js)
- create_instance_id: in place of the original Object's instance_id. (numbers that never overlap regardless of thread)
- Identifier: like the original, issues sequence numbers from a starting number and an increment. reset goes back to the starting number. (the bug where the original reset put its own value back into itself
  and did nothing was also fixed in the original)
- The original Enum(begin, auto, readonly) imitates enums with JavaScript objects, so it is not ported. Rust uses enum.
- create_guid: createGUID of the original base/reflection.js. (a UUID-form string whose first 12 digits are the millisecond time and the rest random. The rest of the original reflection.js is JavaScript object reflection, so it is not ported)
- [base/math](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/math&lang=en): Math helper functions. (the original base/math.js)
- Numbers are f64 like the original JavaScript numbers. Only random_int is i32.
- The original floor, ceil, sqrt, abs, sin, cos, tan, asin, acos and pow are kept as functions of the same names. (so using code matches the original)
  sin, cos and tan compute what Chrome's Math.sin, cos and tan compute, as in the original (correctly rounded f64, base/trigonometry.rs). (the system libm has different last digits on each platform)
  round rounds halves toward +infinity (-2.5 → -2), which differs from f64::round (-2.5 → -3), so the original formula was ported as is.
- Randomness uses the engine's random (xorshift64*). (in place of the original Math.random)
- The default randomFunction argument of the original shuffle is split into shuffle (engine random) and shuffle_with_random_function (a passed function).
- [base/matrix4](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/matrix4&lang=en): 4x4 transform matrix. (the original base/matrix4.js)
- Column-major as in the original. Element positions are elements[column * 4 + row], uploaded as is to glUniformMatrix4fv without transposing.
- Point transformation is transformed = matrix x (x, y, z, 1). (column vector multiplied on the right)
- multiply / translate / rotate_x ... / scale change the matrix itself as in the original. (this = this x other, right multiplication in local space)
  The create... static functions return a new matrix as in the original.
- The coordinate system is right-handed as in the original. create_perspective is OpenGL style (the camera looks down -Z, depth -1 ~ 1),
  create_look_at is a view matrix whose +Z (back axis) points away from the target as seen from the eye, rotations are in radians, and counterclockwise when looking down the axis is positive.
- The original getElements() hands out a Float32Array and the caller edits it directly. The Rust version makes elements a public field;
  get_elements() gives a read reference, and write_to_array / write_to_slice copy into uniform arrays.
- Like the original, elements are stored in f32 like a Float32Array, and math is done per element in f64 and then stored as f32. (the same bits as the original; read them as f64 with read_elements when computing)
- The original transformPoint's { x, y, z, w } is returned as TransformedPoint, and transform_direction's { x, y, z } as Vector3.
- The original clone is replaced by Copy. A transpose, which the original does not have, was not added.
- [base/obb](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/obb&lang=en): Oriented bounding box. (the original base/obb.js)
- 2D as in the original. A convex quadrilateral joining 4 corners (named edges in the original) in order.
- contains is the same ray crossing test as the original. Points on the left and top edges are inside, points on the right and bottom edges are outside.
- overlaps is the same separating axis theorem (SAT) as the original. Projects both sets of corners (get_edges) onto each edge normal of the two rectangles, and counts merely touching as overlapping. (< comparison)
- The original setEdges blocks null, non-arrays and wrong lengths with exceptions. In the Rust version, the [Vector2; 4] type does that job.
- [base/objectpool](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/objectpool&lang=en): Object pool. (the original base/objectpool.js)
- Reuses objects created / freed every frame (bullets, effects and such) to reduce allocations. (the original was made to reduce GC pressure)
- Borrow with acquire() and return with release(). On return, reset_handler clears the state.
- The Rust version is a generic with the held type fixed as T. acquire takes an object out and hands it over (ownership moves), and release takes it back.
  The original's ignoring of release(null) was dropped because Rust has no null.
- clear() empties only the idle list as in the original, and leaves the number created so far (total_count) as is.
- [base/pivot](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/pivot&lang=en): Pivot / anchor values.
- The Pivot object of the original base/pivot.js moved to associated constants.
- [base/platform](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/platform&lang=en): Platform information. (the original base/platform.js)
- The original picks the platform and browser by looking at navigator.user_agent.
- The Rust version looks at user_agent with the same rules as the original on the web (wasm32), and uses the build target OS on desktop.
  The desktop browser is Chrome. The desktop version is tuned to give the same results as the original running on Chrome (fonts and glyph widths, primary pointer detection, page events,
  safe area, on-screen keyboard), and the original only shows this name in developer tools and statistics text, so browser branches in game code must also take the Chrome branch to get the same results.
  On Linux it is SteamDeck if running on a Steam Deck. It counts as a Steam Deck if the environment variable SteamDeck=1 that Steam sets when launching on a Steam Deck is present
  (Valve's Proton launch script tells the Steam Deck apart by this), or if, like Valve SteamOS's jupiter-hw-support,
  /sys/class/dmi/id/board_vendor is Valve and board_name is Jupiter (LCD) or Galileo (OLED).
- The original's getOrAddCanvas is done by platform/web.rs with the canvas id from the engine settings.
- get_resource_usage: on the web, adds up performance's resource entries as in the original. On desktop nothing is received over the network, so
  it lists the files the engine read as assets (asset byte reads, Engine::load_image, audio files) in the order read. The type is "file", and both the transfer size and the decoded size are the file's byte count.
  (fonts read from the system, such as the default and fallback fonts, are not listed, just like the original's system fonts)
  The old misspelled name get_resouce_usage remains as an alias calling the same function. (same in the original)
- get_safe_area_rect: the original reads the size of the canvas (or the window if none). The Rust version has no document object, so it takes that size. Insets on desktop are 0 like desktop Chrome.
- is_coarse_pointer: CSS pointer: coarse as in the original. On desktop, Chromium's detection was ported. (true on Windows in tablet mode or on a touch device without a mouse, on Linux when there is only a touchscreen
  without a mouse or touchpad, always false on Mac. platform/desktop.rs)
- is_desktop_web: the original reads the platform information anew on every call. The Rust version uses what it read at creation. (user_agent does not change)
  Desktop builds are not mobile and have no touch point count (navigator.maxTouchPoints), so it is always true.
- [base/quaternion](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/quaternion&lang=en): Quaternion. (the original base/quaternion.js; a 3D rotation and the basic unit of skeletal animation interpolation)
- The component order is (x, y, z, w) as in the original, with w the real part. The default is the identity quaternion (0, 0, 0, 1).
- multiply is the Hamilton product this x other. As matrices, R(this x other) = R(this) x R(other), so
  the other rotation applies first to column vectors. (in the original's words, "accumulates the other rotation locally after the this rotation")
- create_from_euler(x, y, z) is in radians and equals qX x qY x qZ. As matrices it is Rx x Ry x Rz, so it applies to points in Z, Y, X order.
  (the same formula as three.js's 'XYZ' order)
- The original keeps x, y, z, w as hidden fields with properties, but the Rust version is a Copy value with public fields. The original clone is replaced by copying.
- Numbers are f64 like the original JavaScript numbers.
- Conversion from a matrix to a quaternion and back to Euler angles, which the original lacks, were not added. (for a matrix, Matrix4::create_rotation_from_quaternion)
- [base/rect](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/rect&lang=en): Rectangle. (top-left position + size, the original base/rect.js)
- The original's properties like width, min, center and left became get_... and set_... functions.
- intersects was made first in the Rust version and counts edges that merely touch as not overlapping.
  The original overlaps counts touching edges as overlapping, and intersection uses it.
- [base/seededrandom](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/seededrandom&lang=en): Seeded random number generator. (the original base/seededrandom.js, mulberry32)
- Deterministic random numbers that always produce the same sequence from the same seed. Used where reproducibility matters, such as stage generation, replays and versus sync.
- With the same seed as the original, the same sequence comes out bit for bit. The original's >>> 0, Math.imul and ^ are 32-bit integer operations, so
  they were ported as is with u32 wrapping_add / wrapping_mul / ^. (the intermediate mixed + imul(...) addition also becomes modulo 2^32 through ToInt32, so
  it equals wrapping_add) next_value is f64 as in the original. (it is a 32-bit value divided by 2^32, so it fits in f64 exactly)
- The seed and state are u32. The original (seed >>> 0) || 1 is the u32 seed as is, 1 if 0.
  Where the original used a negative number or one above 2^32 as a seed, converting that number to u32 and passing it gives the same sequence. (as u32 is the same as ToUint32)
- next_range takes f64 and returns f64, and computes in f64 like the original.
  next_int is i32 and computes in f64 like the original.
- pick returns `Option<&T>` (the original undefined is None), and shuffle shuffles a slice in place. (the original returns the same array)
- In the original, from_date reads the local year, month and day of a Date. Rust std has no local time, so it takes the year, month (1 ~ 12) and day.
- [base/timer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/timer&lang=en): Cooldown and repeat timer. (Cooldown and RepeatTimer of the original base/timer.js)
- Time is f64 in seconds. (the same type as the engine's TimeManager::get_time_delta)
- Triggering is activate() in both engines. (the reserved word use is not used as a name)
- The original default arguments (duration = 1, interval = 1, elapsed_event = null) are carried over to Default and the arguments of new.
- The callback of RepeatTimer is `Box<dyn FnMut()>`. (the same form as set_first_touch_callback of a scene) To change game state,
  capture and pass in an `Rc<Cell>` / `Rc<RefCell>`.
- [base/transformmatrix](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/transformmatrix&lang=en): 2D affine transform matrix. (the same layout as Canvas2D's a, b, c, d, e, f)
| a c e |
| b d f |
| 0 0 1 |
- The original base/transformmatrix.js. The original's a ~ f read properties are public fields, and clone is replaced by copying (Copy).
- invert and identity were made first in the Rust version.
- [base/vector2](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/vector2&lang=en): 2D vector. (the original base/vector2.js)
- The original add / subtract / multiply / divide / modulo accept both numbers and Vector2. The Rust version splits them into ones taking Vector2 and
  ..._scalar ones taking numbers. Numbers are f64 like the original JavaScript numbers.
- lerp uses the original math.lerp formula (from * (1 - t) + to * t) as is. (same as Vector3)
- Two bugs in the original (modulo dividing instead of taking the remainder, and half returning double (dividing by 0.5) instead of half) were fixed together in both engines.
  modulo returns the remainder (%), and half returns half. (nothing in vanilla.js or the games uses either)
- [base/vector3](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/vector3&lang=en): 3D vector. (the original base/vector3.js)
- The original keeps x, y, z as hidden fields with properties, but the Rust version is a Copy value with public fields like Vector2.
  The original clone is replaced by copying, and equals by PartialEq.
- The original add / subtract / multiply / divide accept both numbers and Vector3. The Rust version splits them into ones taking Vector3 and
  ...Scalar ones taking numbers. (the same shape as Vector2's multiply_scalar)
- Numbers are f64 like the original JavaScript numbers.
- lerp uses the original math.lerp formula (from * (1 - t) + to * t) as is. It may differ in the last digits from the Rust math::lerp (from + (to - from) * t),
  so it is computed separately.
- [base/version](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/version&lang=en): Version. (major.minor.patch, major.minor.patch-branch if there is a branch, the original base/version.js)
- The fields are left open, and the original's accessors like get_major / set_major and getVersionString are kept under the same names.
- The branch is a string, so it is not Copy. create has no branch like the original default arguments, and create_with_branch takes a branch.
- [base/wait](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/base/wait&lang=en): Asynchronous waiting. (Wait.seconds and Wait.nextFrame of the original base/wait.js)
- Awaited inside an engine task (Engine::spawn_task, spawn_scene_task). The engine polls tasks once per frame, so
  if not ready yet it wakes itself and checks again the next frame.
- seconds is wall clock time as in the original. (the original setTimeout(seconds * 1000); not multiplied by the time scale (time_scale) and keeps running while paused)
  Measured from when it is called. (the original also sets the setTimeout when seconds is called) performance.now() on the web, std::time on desktop. (web_time::Instant)
  Just as the original setTimeout calls back on the next turn even for 0 seconds, it ends only after at least one engine polling turn has passed since the call. (seconds(0) rests once and ends)
  If awaited after the time has already passed, it ends immediately as in the original. Like the original setTimeout, the time is converted to milliseconds as a WebIDL long (ToInt32), and negatives are 0.
  (NaN and infinity are 0, 2^31 milliseconds or more wraps around modulo 2^32)
- next_frame waits until the next frame like the original (awaiting a requestAnimationFrame Promise). It ends after one engine polling turn has passed since the call.
- There is one polling turn number per thread, and the engine increments it every polling turn. (poll_tasks in core/task.rs)
- [core](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core&lang=en): Engine core. (Engine, managers, Scene, nodes, Graphic, components)
- [core/animation](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/animation&lang=en): Animation handler.
- A port of the original core/animation.js. Advances a list of frames (Frame) at a frames-per-second rate (animation_speed), and
  if not looping, stops at the last frame and calls the completion callback.
- In the original it is also a plain object, not a component. It is not attached to a node; the holder (a component or such) calls tick and
  takes the current frame out with get_current_image / get_current_rect to put it in a Sprite.
- The original's set_frames family simply returns if given a non-array or an empty one. In the Rust version the types are fixed, so only empty lists are filtered.
  (set_frames accepts an empty list as in the original)
- Frame numbers are usize. The type takes care of clamping negatives to 0, which the original gotoAndPlay(-1) does.
- [core/asset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/asset&lang=en): Assets.
- The original loads with await asset.load(path) after new ImageAsset(). In the Rust version too, load(engine, path) requests the load and returns a load handle (AssetLoadHandle),
  and the handle is shared state that does not borrow the asset, so it is awaited as is inside an engine task. (scene_context.with(|scene, engine| scene.asset.load(engine, path)).await)
  When all the bytes arrive, the state becomes loaded, and the await ends with the loaded bytes or the failure reason (in place of the original reject). An asset already loaded can also be waited on with wait_for_load().await.
  An image handle (ImageAsset::load) ends only once decoding finishes, like the original img.onload, and ends in failure if it cannot be decoded.
  On desktop the file is read right where it is requested and finishes; on the web it finishes between later frames after the fetch ends.
- The form used without await works as before: if the scene requests assets in create and hands them over with scene_base.track_asset, the engine calls initialize after the handed-over assets are all loaded.
  (waits 0.3 seconds more after everything is loaded, as in the original) Meanwhile, as in the original, draw_on_load draws the loading screen.
- There is no central resource manager, as in the original. Assets are held by the scene as members.
- [core/audiobus](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/audiobus&lang=en): Audio bus. (AudioBus in the original core/audiobus.js)
- Gathers the sound of several players into one path and applies volume and mute to all of them at once. (SoundSystem's music bus and sound effect bus)
- Created with AudioManager::create_audio_bus() or AudioBus::new(manager). (the original new AudioBus(audioContext)) Players that play through the bus are created with create_audio_player().
- The backend fills the bus slot. (AudioBusBackend in platform/audio)
  Desktop: one GainNode connected to the output in the engine mixer. Players created from the bus send their sound here. (the math matches Chrome WebAudio)
  Web: one GainNode connected to the output, as in the original. The GainNodes of players created from the bus connect to it.
- A bus created without an AudioContext is silent, and players created from it make no sound either. (same as the original)
- Volume and mute follow the same rules as AudioPlayer. (clamped to 0 ~ 1, unmuting returns to the set volume)
- Differences from the original:
  - State is shared through `Rc<RefCell>`. So that the volume can be changed and players created while SoundSystem lends its bus through get_music_bus,
    all methods take &self. Cloning makes one more handle to the same bus.
  - A player created from a bus holds one bus handle. When all handles are dropped the bus is disconnected from the output. (in the original the browser keeps connected nodes alive)
  - get_gain_node (the original getGainNode) returns an AudioGainNode. On the web it is a GainNode, on desktop an `Rc<MixerGainNode>` sharing the mixer's bus node.
    Either way, its as_deref() is the output destination for AudioPlayer::new. (AudioPlayer::new(&audio_manager, audio_bus.get_gain_node().as_deref()), same on both platforms)
- [core/audiomanager](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/audiomanager&lang=en): Audio manager.
- The original core/audiomanager.js. Holds the shared AudioContext and handles AudioPlayer creation.
- The backend fills the AudioContext slot. (platform/audio)
  Desktop: the engine mixer on top of cpal output (platform/audio/mixer.rs, same math as Chrome WebAudio). Opens the sound device on first use. When suspended (SoundSystem mute) the sound and the clock stop in place, as in the original.
  Web: a WebAudio AudioContext, same as the original. Created after a user gesture as in the original, and on iOS the clock is checked after resuming.
- As in the original, the AudioContext is created lazily. resume_context() does nothing before a user gesture,
  while create_audio_player() creates it (reluctantly) even before a user gesture.
  Desktop has no browser autoplay policy, so it is treated as having had a user gesture from the start.
- Differences from the original:
  State is shared through `Rc<RefCell>`. On the web the clock check timer and promise callbacks call back into the manager as in the original,
  and BeepPlayer holds the manager by reference as in the original. So all methods are called with &self. (components only receive &Engine)
  As in the original, an AudioPlayer is owned by the caller after creation. The manager does not hold the players it creates.
  The original getAudioContext() returns a borrowed AudioContext (the WebAudio AudioContext on the web, the engine mixer's AudioContext on desktop, both have sample_rate() and current_time()). None if absent, and has_audio_context() is also available.
  AudioManager is a handle to shared state, so cloning makes one more handle to the same AudioContext. (when SoundSystem holds the manager as in the original)
  The constructor does not take the engine. (the original uses the engine's platform info to detect iOS, here the web backend detects it directly with the same rule)
  create_audio_bus (the original createAudioBus) creates an AudioBus. Like players, buses are owned by the caller.
  create_audio_player and create_audio_bus are the same as AudioPlayer::new(manager, None) and AudioBus::new(manager), as in the original.
- [core/audioplayer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/audioplayer&lang=en): Audio player.
- The original core/audioplayer.js. Plays the audio buffer loaded in an AudioAsset.
- Volume, mute, loop and playback position are held here, and making the sound is done by the backend (AudioPlayerBackend in platform/audio).
  In place of the original's GainNode: one GainNode on both platforms, as in the original. (on desktop a node of the engine mixer, the math matches Chrome WebAudio)
- Created with AudioManager::create_audio_player() or AudioPlayer::new(manager, output destination). Without an AudioContext it becomes a player that makes no sound. (same as the original)
  new stands in for the original new AudioPlayer(audioContext, outputNode). The first argument is the manager holding the AudioContext (it creates the AudioContext if absent),
  and the output destination (AudioOutputNode) is as_deref() of the bus's get_gain_node() (AudioGainNode). None means the output. The code is the same on both platforms.
    AudioPlayer::new(&audio_manager, audio_bus.get_gain_node().as_deref())
  (on the web it is &AudioNode so other AudioNodes can be passed too, on desktop it is the mixer bus's &MixerGainNode)
  On desktop, a player created by passing the output destination directly also keeps that bus node alive while connected, like the original WebAudio.
- As in the original, play wakes the AudioContext first if it is suspended, then plays. (the web waits for resume(), desktop does it immediately)
- Dropping the player does not stop what it is playing; like a WebAudio source node in the original, the sound plays to the end. (on desktop the mixer holds the node until the source ends, on the web the source node plays)
  A looping sound does not stop, as in the original, so call stop before dropping the player.
- Differences from the original:
  The asset is shared as `Rc<AudioAsset>`.
  On desktop, is_playing() reads whether the mixer has finished the source instead of using the onended callback. (false when finished)
  get_audio_context lends the AudioContext of the manager that created it. (the WebAudio AudioContext on the web, the engine mixer's AudioContext on desktop, None for a player created without a manager)
  set_playback_rate was not in the original and was made first in the Rust version. (it was added to the original too)
  A player created with AudioBus::create_audio_player sends its sound to that bus instead of the output. (the original AudioPlayer's output node argument) It holds one bus handle to keep the bus alive.
- get_time, as in the original, is the current position while playing: the start position plus the time elapsed on the audio context clock. (web currentTime, desktop mixer clock)
- [core/colorglyph](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/colorglyph&lang=en): Color glyph raster. (color glyphs of emoji fonts to premultiplied RGBA)
- In the original, the browser's Canvas2D draws color glyphs in their own colors. Only the alpha of fillStyle applies, not its color, and strokeText also fills color glyphs in their own colors without stroking an outline.
  The Rust version reads the font's color glyph data directly and draws it. Like Chrome, it does not draw OT-SVG glyphs.
- Bitmaps: extracts and decodes the PNG and premultiplied BGRA of sbix (Apple Color Emoji) and CBDT/CBLC (the Noto Color Emoji bitmap version), and fits them to the font size.
  The strike used is the smallest one at or above the font size among strikes that have the glyph, otherwise the largest. (Apple Color Emoji has glyphs missing from some strikes) Shrinking uses area averaging, enlarging uses interpolation between two points.
  The position is the strike's pixel position value (the offset of the image's bottom left from the pen origin) scaled by the font size ratio.
  For bitmap-only CBDT fonts, the advance and pixel box are the strike's glyph metrics (integer advance) and image box scaled by the font size ratio, like Chrome on Linux (FreeType and Skia). (read_bitmap_glyph_advance, read_bitmap_glyph_bounds)
- Outlines: COLR/CPAL v0 (one outline per layer in one color) and v1 (gradients, transforms, clipping, compositing). Received through ttf-parser's Painter and painted directly.
  Outlines flatten curves into line segments and compute coverage with area accumulation (the same method as font-rs, nonzero winding).
  Paints (solid color, linear (three points), radial between two circles, sweep gradient) are evaluated at pixel centers. Outside the ends of the color line follows Pad, Repeat, Reflect, and colors are blended in straight alpha.
  Compositing does COLR's 28 modes (Porter-Duff and W3C blending) in premultiplied color. The palette is number 0, and the text color (palette index 0xFFFF) is white. (glyphs are baked in white and the color is multiplied when drawing)
  A v1 paint fills the current clip region. Without a clip (v0) it fills the last received outline.
- ttf-parser is the one re-exported by rustybuzz. (the same face as the shaping face)
- [core/colorspace](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/colorspace&lang=en): Color space. (the setting that picks which space each game computes 3D light in, in the style of Color Space in Unity Player Settings, original core/graphic/colorspace.js)
- Gamma (default): the path so far. Color textures are uploaded as RGBA, the shader converts them to linear with the pow(color, 2.2) approximation to compute light, and pow(1 / 2.2) produces the screen color.
  Base color, tint and decal are multiplied and mixed as gamma-encoded colors (sRGB). The screens of games already released do not change.
- Linear: the standard 3D path. Color textures (base color, emission, decal, matcap, angel ring, ramp) are uploaded as SRGB8_ALPHA8 so the GPU decodes them to linear when reading
  (filtering and mipmaps in linear space), and passed colors (vertex color, tint, emissive color, decal color, outline color) are converted to linear with the standard sRGB curve (IEC 61966-2-1)
  before they are multiplied and mixed. The screen output uses the same curve back to sRGB. Data textures such as normals and masks stay linear. (is_color_data: false in ToonTextureOptions)
- A game picks it once with EngineConfiguration::color_space. The toon renderer, post process, screen outline and GLB readers follow the engine's value unless given one.
  (Gamma when no engine was created) The chosen value is fixed at creation and does not change afterwards. (programs and texture formats depend on it)
- 2D (Graphic's 2D batches, text, UI) is mixed and composited in gamma space (sRGB values as they are) either way, as before. This setting only splits the 3D (toon) path.
- Shaders: with Linear, #define VANILLA_COLOR_SPACE_LINEAR 1 is put on the line after #version of the 3D shaders the engine builds.
  Material chunks can branch with #ifdef VANILLA_COLOR_SPACE_LINEAR. (the same use as UNITY_COLORSPACE_GAMMA in Unity shaders)
- Desktop GL does not enable GL_FRAMEBUFFER_SRGB on the default framebuffer. (the shaders apply the curve themselves, so enabling it would apply it twice, the same as the web canvas)
- [core/component](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component&lang=en): Component.
- A unit of functionality attached to a node. In the original it inherits the Component class, here it implements the Component trait.
- Components in the original find their own node with get_node(). The Rust version passes a ComponentContext on tick / touch.
  From the context it takes its own node (transform), the whole tree (finding, creating, removing other nodes) and the engine (input, time, view).
- draw receives only its own transform, with the node transform applied. (the tree is not changed while drawing)
- push_transform and pop_transform are called before and after drawing the node (wrapping its own components, children and gizmos). This is where an original node overrode pushTransform and popTransform
  to change drawing state for its descendants too (such as blending). (TouchEffect's additive blend)
- Common state such as enable / gizmo lives in ComponentBase, and implementors only return it.
- Dependent components (the original require): the original returns a list of classes. The Rust version returns a list of RequiredComponent (a type and a function that creates it with default values),
  and WorldNode::add_component creates and attaches that type before attaching if it is missing. When detached, detach is called as in the original.
- The original setNode, getNode and setComponentType were not ported. The Rust version passes the node through the context (there are no global object references) and the type decides the name.
- Reflection (the original scans the prototype at runtime to find get, is, set functions): attach `#[vanilla::reflect]` to the impl block and the impl Component block, and
  the macro builds that list and the code that calls it at compile time. (core/reflection.rs, the same approach as Unreal's UHT)
  Reflect is a supertrait of Component, so a component without the macro does not compile. So like the original, every component is reflected.
  The side that uses reflection upcasts `&dyn Component` to `&dyn Reflect` and calls it. (trait upcasting)
  Getting the concrete type out (in place of C++ RTTI's dynamic_cast) is done with AsAny.
- [core/component/mask](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component/mask&lang=en): Mask component. (clips child drawing to the attached node's content_size area)
- The actual clipping is done by NodeTree::draw_node calling begin_clip / end_clip before and after drawing the children.
- [core/component/outline](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component/outline&lang=en): A component that draws only an outline. (Outline in vanilla.js core/component/outline.js)
- Paint only fills, so this is used to put a separate outline over a see-through panel. (stacking two filled panels mixes the outer color into the see-through inside)
- A rounded box outline uses the node's content size as is, and a circle outline is drawn at its center with half the shorter side as the radius.
- The line stays inside the content size. (the center of the line is half the thickness inward)
- [core/component/paint](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component/paint&lang=en): Color fill component. (paints the node's content_size area as a solid / rounded rectangle)
- [core/component/richtext](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component/richtext&lang=en): Rich text component. (RichText and parse_markup_to_segments in the original core/component/richtext.js)
- Parses markup (the same form as Unity TMP) and joins segments into one line, each with its own font, size, color, bold, italic, underline and strikethrough.
  Supported tags: `<b>`, `<i>`, `<u>`, `<s>`, `<color=#RRGGBB[AA]>`, `<color=name>`, `<size=N>`. Unknown tags show up as plain text.
- The original inherits Text. The Rust version contains a Text (the same shape as UILabel containing a Text) and forwards the setters.
  Without markup it draws with the contained Text's draw. (multiple lines and wrap width as is) Properties a segment does not set use the Text's values.
- Segment layout (layout_segments) takes a measuring function instead of a Graphic. draw measures with measure_text of the text texture cache (textstringtexturecache).
- Differences from the original:
  - The segment property fontFace (FontFace / FontAsset) is font_family (a registered font name).
  - As in the original, a segment's underline, strikethrough and italic use the Text's values (set_underline, set_strikethrough, set_italic) when the segment property is absent.
  - An invalid #color (non-hexadecimal characters) is white. (the original gives a NaN color)
  - getIntrinsicContentSize is calculate_intrinsic_content_size, which takes a measuring function.
- Text direction: the paragraph direction is decided from the joined segment text (the contained Text's direction, the Graphic's direction if Inherit), and right to left places segments from the right.
  Each segment is shaped in that direction, and alignment Start / End is resolved in that direction too. (the original is the same)
- [core/component/shadowimage](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component/shadowimage&lang=en): Image with a shadow. (ShadowImage in vanilla.js core/component/shadowimage.js)
- Draws the image (or a piece within the image) inside the node as large as possible while keeping its ratio, centered.
- Like ShadowText, bakes the look of the shadow laid beneath the image's shape (opacity) into one sheet and draws that single sheet.
  The node's opacity applies to the image and shadow as one sheet.
- If an image color is given, paints the image as a single-color shape of that color. (e.g. a wrap that places the original image on top at the same spot so only the shadow remains)
- Rebakes when the bake scale, image, color, shadow or node size changes. Shrinking on desktop blends evenly by overlapping area.
  If a bake of the same image (the Image's instance identifier and piece) and look already exists, it is shared. (sharedbakecache.rs, the original numbers each image and uses that as the key)
- The image path (image_path), like Sprite's, is the value the UI document (UIDocument) writes and reads in place of the image. It is not used for drawing.
- Rebaking reads the image's CPU pixels, so the given image keeps its pixels even after being uploaded to the GPU. If they were already released, they are read back from the texture.
- On the web, as in the original, it shrinks with the canvas drawImage (imageSmoothingQuality high), paints the color with source-in, then lays the canvas shadow (shadowBlur) and bakes. (bake_shadow_image in platform/web/systemfont.rs)
  Desktop shrinks by overlapping area and computes the shadow with three box blurs.
- The original getBakeCanvas is get_bake_image, which returns the baked Image instead of the baked canvas.
- [core/component/shadowtext](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component/shadowtext&lang=en): Single-line text with a shadow. (ShadowText in vanilla.js core/component/shadowtext.js)
- Laying a shadow with two text nodes (the same text in black below, the text on top) makes the two show through separately, so when the node is faded the shadow beneath shows through the faded text.
  This component bakes the look of the text placed over the shadow into one image and draws that single sheet, so the node's opacity applies to the text and shadow as one sheet.
- Horizontal alignment is left, center or right within the node, and vertically it is the node's center.
- If the text exceeds the node width, it shrinks from the initial size down to the minimum ratio (set_fit_minimum_ratio) to fit.
- The shadow can be blurred with three box blurs (close to Gaussian). The baked image edge is widened by the blur amount.
- Rebakes when the bake scale, text, style, text direction or node width changes, or when a new font is loaded. If a bake of the same look already exists, it is shared. (sharedbakecache.rs)
- The text direction (set_text_direction, the original setTextDirection, initially Ltr) drives bidirectional ordering and shaping, and resolves alignment Start / End.
- Off-screen culling is judged by the rectangle where the last baked sheet is placed (including overflowing text and the shadow margin). It is not culled if it has not been baked yet since a setter changed it, or if the node width or bake scale has changed.
- Italic, underline, strikethrough (set_italic, set_underline, set_strikethrough): the line position and thickness are the same as Text's middle baseline, and the lines are baked together with the text so the shadow lies beneath them too.
  It is single-line text shrunk to fit, so there is no wrap mode.
- On the web, as in the original, it sets the shadow (shadowColor, shadowBlur, shadowOffsetY) on a canvas and bakes with fillText in the text color. (bake_shadow_text in platform/web/systemfont.rs, the margin and position calculations match the original)
  Desktop gets the shape with the text cache's rasterize_text and computes the shadow with three box blurs.
- Color glyphs (emoji) are placed in their own colors multiplied only by the text color's alpha, and the shadow is cast by the emoji shapes too. (the original fillStyle and canvas shadow)
- Differences from the original: the original setFontFace(FontFace) is set_font_family (a loaded font name), and the shadow color and opacity (setShadow's color string and opacity) are taken as one Color (alpha is the opacity).
  The original getBakeCanvas is get_bake_image, which returns the baked Image instead of the baked canvas.
- [core/component/softshade](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component/softshade&lang=en): Soft shade. (SoftShade and SoftShadeShape in vanilla.js core/component/softshade.js)
- Used to darken the area behind text so it stays readable even on a bright background. Bakes the shape into one small image and draws it stretched to the node's content size.
- It is a soft gradient, so baking at low resolution and stretching leaves no visible artifacts. (one baked pixel covers one bake unit, and there is a width and height limit)
- Rebakes when the node size, shape, color, density or side fade changes. If a bake of the same look already exists, it is shared. (sharedbakecache.rs) The node's opacity applies to it as one sheet.
- The original getBakeCanvas is get_bake_image, which returns the baked Image instead of the baked canvas.
- [core/component/sprite](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component/sprite&lang=en): Sprite renderer component.
- Without an image it draws a color rectangle like Paint. (the original inherits Paint, here it contains a Paint)
- If the color's alpha is greater than 0, it covers only the inside of the image silhouette with that color. (tint)
- The image path (image_path) is the value the original attaches as sprite.imagePath. The UI document (UIDocument) writes and reads this path in place of the image. It is not used for drawing.
- [core/component/text](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/component/text&lang=en): Text component. (draws text aligned within the node's content_size area)
- Draws a single line, or multiple lines if there are newline characters or a word_wrap_width.
- The split lines and line widths are recomputed only when the text, font string, wrap width or registered fonts change.
- Off-screen culling is judged by the text rectangle computed from alignment, overflow and wrapping results. (the original also culls with Text.calculateDrawnRect)
- Underline / strikethrough draw lines in the text color, as in the original. (thickness max(1, font size / 16), position from the original computeUnderlineOffsetY / computeStrikethroughOffsetY)
- Wrap mode (set_wrap_mode): Word fills by whitespace units, and if an overflowing piece holds several words (CJK, Thai and other scripts written without spaces) it breaks between words,
  and words that still overflow are split by grapheme clusters. Character uses grapheme clusters from the start. (the original "word" / "char", the calculation order matches the original)
  Grapheme clusters are found with UAX #29 (unicode-segmentation), words with the ICU dictionary (icu_segmenter). The original's Intl.Segmenter also uses the same ICU (ICU4C) rules and dictionary.
  For CJK, ICU4X picks the longest word first while ICU4C picks the split with the smallest sum of word costs, so they differ, and desktop ports ICU4C's calculation and splits with the same dictionary (cjdict).
- Italic adds italic to the font string. If there is no italic face, the text cache bakes it with a synthetic slant like the browser's (slope 1/4).
- Text direction (set_text_direction, the original setTextDirection): Inherit follows the Graphic's direction at draw time. Alignment Start / End resolves in that direction,
  and the text cache does bidirectional ordering and shaping (Arabic letter joining) in that paragraph direction.
- Showing a number of characters (set_visible_character_count, typewriter effect) cuts by grapheme clusters from the front. (Hangul syllables, combining marks and emoji sequences are not split)
  With multiple lines, each line draws as many as remain, and once the remaining count reaches 0 the following lines are not drawn.
- Fitting single-line text to a width (set_fit_width): as in the original, if it overflows it shrinks from the initial size down to the minimum ratio in steps of 0.1. The shrunk size is measured when splitting lines (update_layout), so
  a Graphic is needed to know it. (get_fitted_font_size is the last measured value, calculate_fitted_font_size measures on the spot) The drawn rectangle follows the width of the shrunk text.
- [core/engine](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/engine&lang=en): 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.
- [core/globalengine](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/globalengine&lang=en): The global engine. (in place of System.vanillaEngine of the original Engine.getEngine(). The same form as Unreal's GEngine and Godot's Engine singleton)
- The engine is created once and never removed. Engine::new puts the engine in a place that lives until the program ends ('static) and gives &'static Engine.
  That place is written in a thread slot, so right after creation Engine::get_engine() gives the same engine anywhere: scene functions, draw, components, widget callbacks, inside async tasks.
  Like the original, it gives the last created engine.
- All public engine functions are &self. The fields they change use interior mutability (Cell, RefCell). (the form of singletons and Gd's bind, bind_mut in godot-rust, Godot's Rust binding)
  So the engine argument a scene function receives and Engine::get_engine() can use the same engine at the same time without breaking Rust's borrowing rules.
- The managers (time, view, input, pointer, sound, graphic) are inside RefCell. get_x gives Ref and get_x_mut gives RefMut.
  Borrowing the same manager again (get_x or get_x_mut) while holding it as RefMut stops with a panic that names the function and the manager.
  Use what you borrow within one statement and let it go. (do not hold it long with let while calling other engine functions)
- Called from another thread it is Err(EngineAccessError::OtherThread). (the engine belongs to the thread that created it. Engine is not Sync, so &Engine cannot be sent to another thread. The web has one thread)
- [core/browseruitext](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/browseruitext&lang=en): Browser UI text. (the same table and the same locale selection as the original core/browseruitext.js)
- Text for what the browser used to draw over the page (the title and buttons of JavaScript question dialogs, the items of the edit field context menu and the touch quick menu).
  In both engines, on the web and the desktop alike, the engine draws these, so it needs the same text. (core/modaldialog.rs, ui/uiinputfield.rs, ui/uiinputfieldmenu.rs)
- The text is a table made by looking up Chromium's translations (chrome/app/resources/generated_resources_*.xtb, ui/strings/translations/ui_strings_*.xtb,
  components/strings/components_strings_*.xtb) by grit message ID and converting them to their on-screen form. (browseruitext.json, 82 desktop locales)
  Chrome's Views menus draw with the accelerator markers "(&U)" and "&" removed (gfx RemoveAcceleratorChar), and Mac removes them with FixUpWindowsStyleLabel. The table holds the text with them removed.
- Chrome draws in its own UI language. Standing in for it, the locale is picked with Chrome's rules from the preferred languages in order (on the desktop the system preferred languages via sys-locale, on the web navigator.languages like the original).
  (l10n_util's GetApplicationLocale and language_tag_matcher: the same name if present, es-* is es-419, pt is pt-BR, zh is zh-CN, zh-Hant is zh-TW,
  en, en-PH and en-LR are en-US, en-CA and other en-* are en-GB, the old names iw, no, tl, in are he, nb, fil, id. en-US if nothing matches)
  zh-MO is treated as zh-HK following CLDR's parent locale zh-Hant-HK, and zh-SG as zh-CN. (not verified by running Chrome's ICU4X data)
- [core/modaldialog](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/modaldialog&lang=en): Modal question dialog. (in place of the browser window.alert, window.confirm, window.prompt that games called, the same as the original core/modaldialog.js)
- The Rust version has the engine functions Engine::alert, Engine::confirm, Engine::prompt, the original has engine.alert, confirm, prompt. The DevTools Local Storage tab also asks for keys and values, and whether to delete, with this dialog.
- In both engines, on the web and the desktop alike, the engine draws on the canvas a question dialog like the Chrome tab modal dialog (JavaScriptTabModalDialogViewViews). (no browser dialog is shown)
  - Position: horizontal center, top edge inside the canvas (window). (Chrome overlaps the bottom of the toolbar by 3px at the horizontal center of the tab content area. The canvas has no toolbar, so it is the top edge)
  - Title: "This page says" (the title Chrome uses for pages without an origin (file:, data:)) There is no close X.
  - alert has only OK, confirm and prompt have OK and Cancel. The default button is OK. Button order is like Chrome: Windows `[OK][Cancel]`, macOS and Linux `[Cancel][OK]`.
  - The prompt input field gets the default value and receives focus with everything selected. Enter confirms, Escape cancels.
  - The text (title, OK, Cancel) is chosen by the system language standing in for the browser UI language. (core/browseruitext.rs)
  - While it is open, the scene and async tasks are not updated like the original (drawing keeps the frozen screen), and only the dialog receives input. When it closes, pressed keys and buttons are cleared.
  - The input field receives IME and edit keys from the text input queue (core/textinput.rs). On the web a hidden DOM input receives the text like the original. Pressing and dragging sets the cursor and selection.
  - Several calls in one frame are shown one after another.
- The Rust version returns a ModalDialogHandle, which finishes when answered. (is_finished, the original returns a Promise)
  Attach a function to call afterwards with set_callback. Inside engine tasks, await the Promise of Engine::alert_async, confirm_async, prompt_async.
  (async tasks also pause while it is open)
- [core/canvas2d](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/canvas2d&lang=en): 2D drawing target. (in place of the browser canvas that the original and games use through document.createElement("canvas") and getContext("2d"))
- The original engine bakes text, shading and shadows onto offscreen canvases (getBakeCanvas and getAtlasCanvas return those canvases),
  and games create their own canvases, draw paths, gradients, shadows, clips, images and text, then hand them to the engine as images. (glossy UI shells, logo atlases, sprite cropping, pixel measuring)
- In the Rust version, a single Canvas2D is both the canvas and its 2D context. Function names are the CanvasRenderingContext2D names converted to Rust conventions.
  (fillRect → fill_rect, fillStyle = → set_fill_style, getImageData → get_image_data) The same goes for Path2D, CanvasGradient, CanvasPattern and ImageData.
  What is drawn is turned into an engine Image with to_image and used in places such as Graphic and UIImageView. (returns the same Image if nothing changed)
- On the web, it draws directly to a browser canvas (a canvas element not attached to the document) and its 2D context, as in the original.
- Desktop has no browser, so the engine does the same work. It paints with tiny-skia, a Rust port of the Skia CPU rasterizer that Chrome uses.
  (the same version resvg already uses, no extra crates to download) Path points are transformed by the transform at the time they are added, as in the original, and gradients and patterns follow the transform at paint time.
  Path arc, ellipse, arcTo and roundRect store the same conic curves as Chrome, using the math of Blink canvas_path.cc and Skia SkPathBuilder,
  and at paint time they are split into quadratic curves within 0.25 device pixels, like the Skia CPU raster. (SkAutoConicToQuads, the old chop version Chrome uses)
  An engine Image whose CPU pixels were released on GPU upload is drawn by reading back its texture. (same as when Chrome draws a GPU-resident image onto a CPU canvas)
  Shadows paint the shape separately, blur it (sigma = shadowBlur / 2, three box blurs) and lay it down offset by shadowOffset, which is not transformed.
  copy, source-in, source-out, destination-in and destination-atop also clear outside the shape, as in the original. (the shape is painted separately and composited over the whole clipped region)
  Text is painted from coverage taken from the engine glyph cache (the same face selection, shaping, fallback fonts and color emoji as the Text component).
- Differences from the original:
  - Properties are setters and getters. Colors are CanvasStyle, which takes a Color or CSS color string, a gradient or a pattern.
  - roundRect radii are a list of numbers (f32) or elliptical corners ((x, y), CanvasRadius::Elliptical, the original DOMPointInit).
  - Desktop pixels use the same Skia math as Chrome but not the same version, so edge antialiasing and blur may differ slightly.
- [core/canvas2d/desktop_canvas](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/canvas2d/desktop_canvas&lang=en): Desktop version of the 2D drawing target. (paints with tiny-skia, header comment of core/canvas2d.rs)
- [core/canvas2d/web_canvas](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/canvas2d/web_canvas&lang=en): Web version of the 2D drawing target. (draws to a browser canvas element not attached to the document and its 2D context, as in the original, header comment of core/canvas2d.rs)
- For Path2D, the segments held by the engine are retraced into a browser Path2D and passed on. Gradients and patterns create the browser objects when they are set as the paint.
- Getters read values from the browser context. Transforms and paints keep the same values on the Rust side and stack them with save and restore.
- [core/frame](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/frame&lang=en): Image region. (frame)
- A port of the original core/frame.js. Not a frame loop, but one sprite image or one cell in a sheet.
  Animation holds these as a list and steps through them in order.
- The original throws an exception if image is null. The Rust version takes `Rc<Image>` so it cannot be empty.
- Like the original, it does not clip the region to the image size. (the original also has that line commented out)
- [core/fullscreenpass](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/fullscreenpass&lang=en): Fullscreen pass. (one triangle covering the whole screen + a fragment shader)
- A port of the original core/fullscreenpass.js. The basic unit of screen-wide effects such as backgrounds / post-processing. (used by ScreenEffect)
- Builds the triangle from gl_VertexID without a vertex buffer. Draws with an empty vertex array bound. (both GL 3.3 core and WebGL2 only need a vertex array bound)
- The shader is GLSL ES 3.00 like the original. On desktop, ShaderProgram replaces only the header with #version 330 core before compiling.
- Differences from the original: it does not hold the GL context but takes it in each function. Creation failure returns Err instead of an exception. GL resources are deleted with destroy.
- [core/gamepadmanager](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/gamepadmanager&lang=en): Gamepad manager.
- A port of the original core/gamepadmanager.js. The public names (GamepadButtonCode, GamepadAnalogStickCode, GamepadTriggerCode,
  connect, disconnect, set_callback, update_all_gamepads, is_button_pressed, get_button_value, get_axis_value,
  get_all_connected_gamepads, get_connected_gamepad_count, get_connected_gamepad) and the update rules are the same as the original.
  (values are rounded to two decimal places, axes are taken only when they change by more than 0.01, analog values are reported only when greater than 0, log messages)
- The original reads navigator.getGamepads(). The web (wasm32) reads navigator.getGamepads() directly like the original and takes all buttons and axes the browser gives,
  and takes connection and disconnection through gamepadconnected / gamepaddisconnected like the original engine.js.
  On desktop, gilrs reads OS input (Windows.Gaming.Input on Windows), converts it to a Gamepad list in the same W3C Standard Gamepad form as the original
  (buttons 0~16, axes 0~3, axis Y is positive downward), then runs the same rules.
- Differences from the original:
  - The gilrs default filters (deadzone, jitter filtering) are turned off. Raw values are taken like a browser, and the game applies the deadzone like the original.
  - An analog button (trigger) counts as pressed when its value exceeds 30/255, as in Chromium. (gilrs default presses at 0.75 and releases at 0.65)
  - A D-pad coming in as an axis (hat switch) is converted to buttons 12~15. (what the browser does)
  - On desktop, buttons that gilrs could not map to standard buttons (buttons missing from the mapping, gilrs C, Z) are appended after the 17 standard buttons, and axes missing from the mapping
    after the 4 standard axes, in the order they first move. gilrs does not give the device's button list and reports only buttons that have moved at least once, so such a button appears only after it is first pressed.
    When the number of buttons or axes grows, that pad's state slots grow too.
  - PlayStation pads (Sony 054c DualShock 4 05c4, 09cc, 0ba0 and DualSense 0ce6, 0df2, 0e5f) have 18 buttons like Chrome (MapperDualshock4, MapperDualSense in device/gamepad),
    and raw button 13 (HID button 14) is TOUCHPAD (17). It is always there even before being pressed, and other buttons (the DualSense mic button) and axes are not appended.
    gilrs only maps touchpad:b13 of the SDL mapping to an unnamed button (Button::Unknown, the same name as misc1), so the raw code of that button is found per platform.
    (usage 14 on the macOS IOKit button page, button 13 on Windows Windows.Gaming.Input, BTN_GAMEPAD + 13 on Linux hid-generic)
    The Linux hid-sony (from kernel 4.10) and hid-playstation (from 5.12) drivers expose the touchpad as a separate device and add 0x8000 to bcdHID.
    In that case it has 17 buttons like Chrome (MapperPs4Ps5). (the 13th and 14th bytes of the gilrs uuid are that version number)
    macOS GameController also has GCDualSenseGamepad.touchpadButton, but GameController does not give the pad's vendor and product numbers so it cannot be paired with a gilrs pad, and it is not used.
  - Gamepad.index on desktop is the gilrs GamepadId number. (from 0 in the order first connected, used like the browser index) On the web it is the browser index.
  - Gamepad.id on the web is the browser id as is, and on desktop it is built in Chrome form "name (STANDARD GAMEPAD Vendor: 054c Product: 0ce6)".
  - The button value of the callback is 1.0 (pressed) / 0.0 (released) instead of bool.
  - gilrs (on the web, the connection listeners) is created on the first call (update, vibration, pad list read). (engines and tests that never call it do not open devices)
- get_all_connected_gamepads / get_connected_gamepad return copies read in place when called (&self), like the original navigator.getGamepads(). (desktop drains the gilrs events for the current state,
  and the next update receives the connects and disconnects in between) A manager fed with update_all_gamepads_with_list (tests, other input sources) returns the list it was given.
  - Added: set_log_enabled (turns logs on and off),
    update_all_gamepads_with_list (a way to feed a list without gilrs. For tests or other input sources)
  - Battery info is not in the original, so it is not ported.
  - The log printed whenever buttons and axes change is turned on with set_input_log_enabled like the original, and is off by default. set_log_enabled is the master switch for all logs including connection and disconnection.
  - GamepadKind, read_gamepad_kind: tells the kind (Xbox, PlayStation, Nintendo, other) from the pad name. get_active_gamepad_id is the pad that pressed a button or tilted an axis far at the last update.
  - vibrate(strong_magnitude, weak_magnitude, seconds): vibrates all connected pads.
    On desktop it vibrates with gilrs force feedback (Linux evdev, Windows XInput and Windows.Gaming.Input), and on macOS, where gilrs does not support rumble,
    the platform layer (platform/desktop/gamepadhaptics.rs) vibrates the controller paired with the gilrs pad using GameController and CoreHaptics. (on macOS, a duration or strength of 0 stops the previous vibration)
    So gilrs is created with rumble enabled. (one gilrs rumble thread runs on desktop) On the web, like the original, it applies dual-rumble to the vibrationActuator of navigator.getGamepads().
    Called before the first update (tick), it creates gilrs on the spot and rumbles. (as in the original)
- [core/graphic](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/graphic&lang=en): Graphics.
- A renderer that draws to a GL context. Uses the same shaders and the same state model as the original (WebGL2).
- Reproduces the coordinate system (top-left origin, pixel units) and state model (transform/alpha stack) of the Canvas2D days as is.
- All draws converge on one point, draw_vertices(). Solid shapes also use a 1x1 white texture to unify with the texture path.
- Clipping is based on the stencil buffer. Text is baked into string textures and drawn.
- Batching (on by default): consecutive draws with the same texture have their vertices transformed on the CPU, gathered, and drawn at once.
  With the same batch shader as the original, color and tint go with each vertex, so tinted draws are batched too. Clip region recording is not batched.
  Blends, clips, particle draws and the end of the frame flush what has been gathered first (flush_batch). The original also turns it on by default. (setSpriteBatchingEnabled)
- Offscreen culling (on by default): NodeTree asks is_local_rect_visible before drawing a node. The original also turns it on by default and WorldNode asks with the same function. (setCullingEnabled)
- Shader override (set_shader_program_override): effects such as ShaderSprite draw with their own program instead of the default one. No batching while overridden.
  resolve_shader_program keeps the override programs by name and fixes their attribute locations to match the default program so they share the default vertex array.
- Remembers the last bound shader program and the texture of texture unit 0, and skips GL calls that bind the same thing again. (same as the original)
  When GL can be touched from outside (when handing out the context with get_gl, restore_render_state, frame start and end), it forgets them and binds again next time.
- The mipmap level bias (set_image_mipmap_bias) is applied through the textureLodBias uniform of the default, batch and particle shaders. An override shader receives it if it has that uniform. (same as the original)
- Text direction (set_text_direction, the original setTextDirection) is held in the state, and baked strings are shaped in that paragraph direction. (bidirectional ordering and shaping in textshaping.rs)
- 26 blend modes (same as the original): 13 use fixed blending, and 13 grab what is under the draw area from the current framebuffer with blit_framebuffer and mix it in a shader following the W3C formulas.
  Multiply uses fixed blending on the default framebuffer and shader mixing when drawing to a render target. (fixed blending differs from the W3C formula when the backdrop is translucent, same as the original)
  The shader text does not differ from the original by a single character. Override shaders are drawn first into an overlay slot (always RGBA16F on desktop, RGBA16F on the web when EXT_color_buffer_float is available like the original) and then mixed over.
- Alpha is not written when drawing to the default framebuffer (apply_color_mask). In the original and on the web the canvas is alpha: false so screen alpha is always 1, but the desktop default framebuffer has alpha,
  so modes using DST_ALPHA and shader mixing after a mode that lowers alpha differed from the web. Alpha is written to render targets.
- [core/glcontext](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/glcontext&lang=en): Engine GL context. (the context returned by the original Graphic.getWebGL2RenderingContext, with intercepted state functions)
- The original intercepts the state functions of the context object, so the state cache remembers even GL that the game calls directly. glow's HasContext is a sealed trait that
  cannot be implemented outside glow, so this type, which wraps glow::Context, has every method of HasContext as an inherent method with the same name and signature.
- State functions (binding, enabling and disabling, viewport, scissor, blending, depth, faces, program, vertex array, buffer binding, textures, clear color, pixel store) are written by hand in this file
  and call through the state cache. Desktop-only state functions that the original WebGL2 does not have (glEnablei, glViewportArrayv and the like) make the state cache forget that value after the call.
- Everything else (drawing, filling buffers, uniforms, shaders and the like) is generated by machine in glcontext/generated.rs and calls the inner glow::Context as is. (The original also leaves functions it does not intercept as they are)
- There is no public way to take out the inner glow::Context. (No Deref or AsRef) Game helper functions take `&GlContext`.
  It cannot be passed to a function taking `&glow::Context` (a compile error), so no path that skips the state cache appears. Only the engine's GL setup and the state cache take it out through a crate-internal path.
- `use glow::HasContext;` is not needed. (Even with it the inherent methods are picked, and GlContext does not implement HasContext)
- The engine does not reset the state cache by itself where it hands GL over. (Same as the original) Calls that bypassed the state cache are found by running with VANILLA_GL_STATE_CHECK=1.
- [core/gpumemorytracker](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/gpumemorytracker&lang=en): GPU memory tracking. (counterpart of the original GpuMemoryTracker)
- The GlContext functions that create resources and set their sizes (tex_image_2d, tex_storage_2d, renderbuffer_storage_multisample, buffer_data_size and the like) call into this file and record bytes per object. Deleting removes the entry, and losing the context clears everything.
- Bytes are nominal values computed from format and size. (row alignment, tile memory and multisample compression chosen by the driver are not known; multisample renderbuffers multiply by the sample count)
- The owner is the top three frames of the creating call stack. (desktop captures the frames at creation and resolves the names when read; the web (wasm) has no stack and uses the creating source location)
- It is off by default. While off, the creation and sizing functions of GlContext only look at one flag and nothing runs per frame. It is turned on by EngineConfiguration::track_gpu_memory, Graphic::enable_gpu_memory_tracking or Engine::enable_gpu_memory_tracking, and counts what is created after that.
- [core/image](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/image&lang=en): Image. (in place of the original HTMLImageElement / ImageAsset)
- Formats: the original accepts every format the browser decodes. Desktop accepts PNG, JPEG, WebP, GIF (first frame), BMP and ICO with the image crate, SVG with resvg,
  and AVIF, with the engine reading the HEIF boxes and rav1d decoding AV1. (core/avifimage.rs)
  On the web, as in the original, the browser (HTMLImageElement) always decodes images. It decodes them when assets are received (ImageAsset, AssetLoader) and on ImageAsset::load_from_bytes, and keeps them in the handle.
  (platform/web.rs, including AVIF and the first frame of animated PNG) This path on the web does not ship the image crate or the engine JPEG decoder.
  So on the web, load_from_memory and load_from_memory_with_mime_type do not decode bytes on the spot and return Err. (the original has no path that decodes image bytes on the spot either)
- Bytes with a known type (MIME) (data: URLs) are decoded with load_from_memory_with_mime_type. As in browsers, it is SVG only when the type is image/svg+xml, and anything else is identified by content.
  Bytes with an unknown type (files) are identified by content, SVG included, by load_from_memory. (desktop has no response type)
- sniff_image_mime_type: picks the type by content using the image table of WHATWG MIME sniffing (ICO, CUR, BMP, GIF, WebP, PNG, JPEG) plus AVIF. (desktop Material uses it instead of the response type)
- Color profiles: as in Chrome, the color space embedded in the image (PNG cICP, iCCP, gAMA and cHRM, JPEG APP2 ICC, WebP ICCP, AVIF colr) is converted to sRGB. (core/colorprofile.rs)
  In the original, the browser converts it at WebGL texImage2D. 3D materials (graphics3d/material.rs) are not converted, like the original's createImageBitmap (colorSpaceConversion "none").
- Pixels are held as premultiplied alpha RGBA. (the original does the same with UNPACK_PREMULTIPLY_ALPHA when uploading to a texture)
- Shared with Rc, and the GPU texture is created by Graphic's ImageTextureCache on first draw.
- After uploading to the GPU, the CPU pixels are released to return memory. (in the original, the browser holds the HTMLImageElement)
  Images whose pixels must be read again are kept with set_pixels_retained(true). (ShadowImage keeps them on its own when it receives an image, and reads back from the texture if already released)
  An image remembers its uploaded texture, so places without a Graphic, such as Canvas2D, also read released pixels back from the texture. (imagetexturecache::restore_image_pixels_from_texture)
  This engine has no path for restoring a lost GL context, so released pixels never need to be uploaded to a texture again.
- [core/imagetexturecache](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/imagetexturecache&lang=en): Image texture cache.
- The original uses `WeakMap<image, texture>`, so the texture disappears along with the source image when it is collected.
- Here it holds `Weak<Image>`, and sweep() removes textures whose source has disappeared.
- After uploading, the image's CPU pixels are released. (images set to be kept with Image.set_pixels_retained are left alone)
- When released pixels are needed again (Canvas2D drawImage, createPattern), the texture remembered by the image is read back from the GPU. (restore_image_pixels_from_texture)
  This is the same path Chrome takes when it reads back a texture to draw a GPU-resident image onto a CPU canvas. The GL context for reading back is set by Graphic when it is created.
- [core/inputmanager](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/inputmanager&lang=en): Input manager.
- Key names are in KeyboardEvent.code form like the original. ("KeyA", "ArrowLeft", "Space" ...)
  winit's KeyCode names follow the same W3C convention, so they are converted to strings as is. Only for the Windows key (Command key), winit calls it SuperLeft, SuperRight
  and calls the old W3C Super key Meta, so the desktop platform puts in MetaLeft, MetaRight, Super instead.
- The constant names of KeyCode are the original KeyCode key names converted to Rust constant form. (DIGIT0 for things like "0" that cannot be a name)
  LEFT, UP, RIGHT, DOWN, which were not in the original, are kept with the same values as the ARROWLEFT family.
- The mouse button (or first finger) is handled as touch. (the original merges mouse and touch into one) Like the original, initially any button is touch,
  and with set_touch_from_left_button_only(true) only the left button is touch. Whether to block the canvas right-click menu (set_context_menu_prevented, initially true) blocks the browser context menu on the web.
  Desktop windows have no browser context menu, so the result is the same as blocking it in Chrome.
- It also holds the pressed state of the three mouse buttons (left, middle, right), the list of touching fingers, whether the last input was a finger, and whether the wheel was rolled with Ctrl.
  Places that use input beyond the single button touch, like camera gestures (CameraGestures), read them. The platform fills them in. (vanilla.js read canvas DOM events directly)
- Gamepads, like the original, are polled in tick by the GamepadManager that InputManager holds. (core/gamepadmanager.rs)
- Text input (committed text, IME composition, editing keys) is gathered in the TextInput queue. Input fields take it from there. (core/textinput.rs, a layer not in the original)
- This frame's presses and releases of keys and mouse buttons are seen by accumulating events that came after the end of the last frame, like the original. A press and release between frames is also caught.
- Fingers, like the original, receive touch (begin_touch_point), move and release and are given a phase (TouchPhase), and a lifted finger stays in get_ended_touch_points for one frame.
- It holds the last used device (InputDevice) and pad kind, the keys to block (set_prevented_keys), whether typing in a text field (is_typing_in_text_field), and input actions (InputActions).
  The keys to block prevent browser default actions on the web (such as Tab moving focus, Space and arrows scrolling, F5 refreshing). Desktop windows have no such default actions, so the result is the same as blocking them.
  For text fields it looks at the engine input field (the active field of TextInput) and, on the web, the document focus (text input, textarea, contenteditable, select).
- [core/pointercursor](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/pointercursor&lang=en): Mouse cursor. (PointerCursor of vanilla.js core/pointercursor.js)
- The engine holds one. (Engine::get_pointer_cursor_mut) When on (set_enabled(true)), the engine sets the cursor of the window or canvas at the end of every frame.
  When off (default), it does nothing, same as before.
- Over a UIButton (including while pressing), it is the button's cursor (initially the pointer hand), otherwise the cursor the screen set with set_screen_cursor.
- Names are CSS cursor names. (pointer, crosshair, not-allowed, grab, grabbing, text, move, help, wait, progress, none, default)
  Desktop converts them to winit cursor icons, and the web writes them to the canvas cursor style.
- When an image cursor is added with register_image_cursor, the web uses that image (1x and 2x) as a CSS value, and desktop uses a window cursor made from that image file (relative to the asset folder).
  (on desktop, the CSS cursor given with it while it is being made and if the image cannot be read)
- Not touched on finger devices (pointer: coarse). Passed to the platform only when it changes.
- The original apply writes directly to the global engine's canvas (readEngineCanvas). In the Rust version the engine receives the changed value with take_cursor_change and passes it to the platform. (the cursor is written to the platform window the engine holds)
- [core/reflection](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/reflection&lang=en): Reflection. (in place of the runtime reflection of the original vanilla.js: collectReflectedProperties and getReflectedProperties of ui/uidocument.js,
  getComponentProperties of misc/devtools.js)
- The original is JavaScript, so at runtime it scans an object's prototype to find get, is, set functions. Rust has no runtime reflection,
  so like Unreal's UHT (UPROPERTY) and Qt's moc, it generates code at compile time to do the same. In Rust the procedural macro `#[reflect]` does that.
  (the macros/ crate, re-exported by the engine as vanilla::reflect) The place of C++ RTTI typeid, dynamic_cast is already AsAny (std::any::Any).
- This module holds the value type (ReflectValue) and trait (Reflect) used by macro-generated code, and the common properties of the original Component base class.
- Usage: put `#[vanilla::reflect]` on both the component's impl block and its impl Component block.
  ```text
    #[vanilla::reflect]
    impl Spin {
        pub fn get_speed(&self) -> f32 { self.speed }
        pub fn set_speed(&mut self, speed: f32) { self.speed = speed; }
    }
    #[vanilla::reflect]
    impl Component for Spin { ... }
  ```
  Then UIDocument writes and reads with the Speed key without registered write and read functions (the original saveByReflection, loadByReflection),
  and the DevTools inspector shows a speed line. (original getComponentProperties)
- In the original every object is reflected. The Rust edition makes Reflect a supertrait of Component, so a component without reflection cannot exist.
  Leaving out either one gives a compile error that points at where to add it. A type without getters takes it on an empty block, `#[vanilla::reflect] impl Spin {}`.
  The side that uses reflection upcasts `&dyn Component` to `&dyn Reflect` (trait upcasting) and calls it.
- Follows the original rules:
  - Getters are argument-less pub get_*, is_* functions, and saved properties are getters with a set_* of the same name. The key is the original name with the prefix removed. (get_line_width → LineWidth)
  - The order is the definition order and for the same key the first one wins. GizmoVisible, Enable, ComponentType of the original Component base class are appended at the end.
  - Saved values are the types the original saveByReflection picks (number, boolean, text, Color, Vector2, node). Enums that are text in the original (such as TextAlign) are converted to the same text.
- What it does like the original:
  - Getters of the original superclass come along through the prototype chain. The Rust version has no inheritance, so it links the embedded value with #[reflect(base = field)].
    Functions that belong to the superclass in the original but that the Rust version redefines for convenience are excluded with `#[reflect(skip)]` to keep the original order.
    Reading and setting look up separately starting from the most derived type, like the original `component[getterName]`, `component[setterName]`. (RichText gets the getter from Text and has its own setter)
  - Pairs are made by key (baseName) like the original. (if the key of get_target is set to TargetNode, it is not paired with set_target (key Target))
  - Getters redefined in the impl Component block show only those also in the original class (excluding the rest with `#[reflect(skip)]`), and their place in the original class body is matched with #[reflect(after = "...")].
  - Properties left out of saving in the original because their value is an object are kept in the list but left out of saving with `#[reflect(unsaved)]`. (FontFace of ShadowText)
  - When reading, the type is decided by the setter's type. The original decides by the type of the current value, and takes the saved type if there is no current value (null). (the original saveByReflection writes only Color as four numbers,
    and only Vector2 as two numbers) So both engines read the same document the same way.
- What differs from the original:
  - In the original every object is reflected. In the Rust version only types with `#[reflect]` are. Rust has no way to read a method list at runtime, so there is truly no alternative.
    (the same form as Unreal UCLASS, UPROPERTY) Omissions can be found this way: putting it on only one block makes a compile error point to where to put it,
    and omitting both makes UIDocument warn when writing and the DevTools inspector show a "no reflection" row.
  - &mut self getters are called through the branch taking &mut (get_reflected_value_mut, collect_reflected_getters_mut). In the &self branch the value is None.
    Getters that take the tree (such as get_target_button(tree), the original holds the neighboring component directly) are called by the side holding the tree with collect_reflected_getters_in_tree.
    Setters that take the tree (such as set_snap_current_index(tree, index)) are called by the side holding the tree with set_reflected_value_in_tree.
    Setters that take more arguments than the value (such as set_image(image, slice)) are in the property list (paired if a set function exists, like the original) but are not set.
    In place of the original setComponentType, Rust has no setter (the kind is decided by the type), so it is only written. In the original too, reading this key does not change the kind.
- [core/node](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/node&lang=en): Node.
- The original inherits Node → ComponentNode → TransformNode → WorldNode.
  The Rust version puts those four into a single WorldNode. (the UINode line was not ported)
- Nodes are held in the scene's NodeTree storage, and parents and children are linked by NodeId handles.
- [core/node/nodetree](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/node/nodetree&lang=en): Node tree.
- Holds the scene's nodes in one storage (slotmap) and links parents and children by handle (NodeId).
- Game code carries NodeIds around and takes nodes out with get_node / get_node_mut (or `tree[node_id]`).
  For the NodeId of a deleted node, get_node returns None. (in place of the original isDestroyed)
- In the original, a parent holds child objects in children[] and a child points back with parent.
  In Rust that form (`Rc<RefCell>`) brings runtime borrow checking costs and reference cycles, so it was changed to handles.
- When running tick / touch, only the one component being called is briefly taken out of its node (an empty placeholder is left in its place) and a ComponentContext (own node + whole tree + engine) is passed.
  So a component can find, change and create other nodes, and also find other components of the same node (siblings) with get_node_mut().`get_component_mut::<T>()`.
- Nodes deleted while running are left inactive in place and actually deleted after the run finishes.
- Sibling order (the original Node.setSiblingIndex, getSiblingIndex, getSiblings) and hierarchy checks (isActiveInHierarchy, TransformNode.isVisibleInHierarchy)
  need to look at the parent, so NodeTree does them taking a node handle. The original -1 and null are None.
  The original isVisible means active with opacity greater than 0. The Rust version also has a separate visibility flag (set_visible) that turns off drawing, and checks that too.
- The hierarchy functions of the original Node keep the same names. Where node objects are passed it is NodeId, and names ending in _id (_ids) are the counterparts that return handles.
  (getParent → get_parent_id, getChildren → get_child_ids, getSiblings → get_sibling_ids) Detaching from the parent (remove_child) does not delete the node.
- The original WorldNode.getPosition, setPosition, getWorldCorners, getWorldBounds are also done taking a node handle. The global position is, like the original, the position of the pivot point
  computed relative to the parent pivot, and the four corners are computed from that global position, global size and global rotation.
- [core/node/worldnode](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/node/worldnode&lang=en): World node.
- Parent/child hierarchy + activation (the original Node)
- Holds components + tick (the original ComponentNode)
- Local TRS + recursive rendering (the original TransformNode)
- pivot / anchor / content_size + touch (the original WorldNode)
- Nodes live in the scene's NodeTree storage, and parents and children are linked by handles (NodeId).
  Changing the tree (attaching children, removing, finding) and iterating the tree (tick, draw, touch) are done by NodeTree.
- [core/scene](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/scene&lang=en): Scene.
- The original inherits the Scene class and overrides create / tick / draw.
- The Rust version implements the Scene trait and keeps the common scene state (node tree, touch target) in SceneBase.
- Nodes are held by SceneBase's NodeTree, and game code points to them with NodeId handles. (get_node_tree_mut().create_child(...))
  In place of the original super.tick() / super.draw(), call get_scene_base_mut().tick() / .draw().
- The original GameScene's pre_draw (filling the whole canvas with the background color and applying the view coordinate system) moved to SceneBase::draw_scene_background.
- Like the original, the scene holds tweens in a list (start_tween), runs them on tick after nodes → touch, and removes finished ones.
  The original points to them by tween object, but the Rust version takes ownership of the tween and returns a TweenId. (stop_tween(tween_id))
- The original SceneManager.unloadScene(scene) points by scene object. In the Rust version the engine holds the scenes, so it points by the SceneId returned from load_scene or
  by the common scene state (&SceneBase, by scene as in the original). A scene knows its own handle with get_scene_base().get_scene_id().
- When unloading, like the original it calls finalize then unload, and the Rust version additionally calls destroy right before dropping the scene.
- In place of the original async load(engine): in load, hand the loading work to Engine::spawn_scene_task and entrust it to the scene with track_task.
  Inside the task, await assets as in the original and touch the scene and engine inside SceneContext::with. initialize is called only after all entrusted tasks and assets finish.
  The synchronous form of entrusting asset handles with track_asset still works. (the two can be mixed)
  In place of the original await unload(engine): the scene stays in the list receiving tick, draw until the tasks entrusted in unload (track_task) finish, then leaves the list.
  If that scene's tasks still remain after that, the scene value lives until they all finish, like the original's Promise chain (it receives no tick, draw), and a scene unloaded while loading
  receives initialize once loading finishes, like the original SceneManager.loadScene. When everything is done, the engine calls destroy and drops it.
- What the original Scene.load does to fit the root to the view size (position 0, top-left pivot, content size is the view size) is done by the engine between create and load.
  Like the original SceneManager.loadScene, after all entrusted assets finish it keeps showing the loading screen (draw_on_load) for at least 0.3 seconds more, then calls initialize.
- The scene's touch hooks (touch_press, touch_move, touch_release, touch_cancel, touch_wheel) are called by the engine after tick, in the original Scene.tickTouch order.
  SceneBase.tick also passes them to the frontmost interactable node regardless of the scene type. (same as the original Scene.tickTouch passing them to the scene's TouchRaycaster)
- Unlike the original, scene hooks receive the engine (&Engine). (it is the same engine as the global engine Engine::get_engine)
- [core/shaderprogram](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/shaderprogram&lang=en): Shader program.
- The original is GLSL ES 3.00 (#version 300 es). To run on desktop GL 3.3 core, only the header is changed to #version 330 core before compiling.
  (precision qualifiers are accepted without meaning since GLSL 1.30, so the body is left as is)
- Uniform / attribute locations are read and cached on the first query.
- [core/shaderwarmer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/shaderwarmer&lang=en): Shader prelinking. (ShaderWarmer of vanilla.js core/graphic/shaderwarmer.js)
- ShaderProgram queries the result right after linking, so it stalls until linking finishes. Building several shaders at once on the first draw makes that frame hitch.
- Linking the same sources in the background with KHR_parallel_shader_compile at startup (during the logo, loading) leaves them in the driver's (on the web, the browser's) program cache,
  so when ShaderProgram later builds the same sources it finishes quickly.
- Does nothing without the extension. (starting links without the extension can make later draw commands wait on the link and stall instead)
- Does not query link results, and deletes the programs and shaders once all are linked. (the cache remains, and no error is raised here even if a source is wrong)
- Usage: ShaderWarmer::new(gl, &[(vertex source, fragment source, attribute location list)]), then update(gl) every frame.
  Attribute locations must be the same as those passed to ShaderProgram::create_with_attribute_locations to hit the cache.
- [core/soundeffectpool](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/soundeffectpool&lang=en): Sound effect pool.
- The original core/soundeffectpool.js. So the same sound effect is not cut off when it overlaps in quick succession,
  it plays by rotating through several AudioPlayers (round robin).
- Does not call the backend directly. On top of AudioPlayer it only tracks the turn and volume.
- Usage:
  ```text
    let mut sound_effect_pool = SoundEffectPool::new(&engine.get_audio_manager(), 6);
    sound_effect_pool.play(&hitAudioAsset, 1.0);
    sound_effect_pool.play(&hitAudioAsset, 0.5);   // Half volume for this playback only.
    sound_effect_pool.set_volume(0.8);              // Volume of the whole pool. (also multiplied into ones already playing)
  ```
- If the voice count is 0, play does nothing, as in the original.
- Differences from the original:
  play's volume has no default, so it is always passed. (the original defaults to 1)
- [core/soundsystem](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/soundsystem&lang=en): Background music and sound effects handled by a sound table. (SoundSystem of vanilla.js core/soundsystem.js)
- Uses AudioManager and AudioAsset. Does not synthesize sound, only plays files.
- Each row of the sound table is SoundRow { id, paths, volume, minimum_interval, is_music, maximum_voices, pitch_variation, play_seconds, fade_out_seconds, load_type }.
  paths: a group of multiple recordings of the same sound. Each time it plays, one of the loaded ones is picked, never the same as the one just before.
  minimum_interval: interval before the same sound can play again. (seconds, so it does not pile up and get noisy)
  maximum_voices: number of copies of the same sound that can play at once. (over that, the oldest is cut, None means up to the total sound effect count, 0 means one as in the original)
  pitch_variation: ratio by which the pitch wobbles each time it plays. (0.05 means ±5%)
  play_seconds, fade_out_seconds: plays only the first play_seconds seconds of a sound effect and fades it out over fade_out_seconds seconds. (0 means to the end)
  load_type: load type. (AudioLoadType, None means Streaming for background music and DecompressOnLoad for sound effects; sound effects overlap, so they must be fully decoded to play)
- Volume: background music = music volume × music ratio × sound volume, sound effect = effect volume × sound volume × volume at the call.
  Music and effect volumes are applied on buses (AudioBus from get_music_bus, get_effect_bus), and follow changes with a 0.05 second time constant. (the original setTargetAtTime)
  Buses are created after the first press. (None before that) Players created from a bus (AudioBus::create_audio_player) also follow the set volume and mute.
- Background music remembers what was requested (get_music_id) and plays it then if it is not loaded yet or before the first press. ("" stops it)
  It can crossfade (fade_seconds), and remembers where each sound stopped so it can resume. (is_resumed) It does not play if the first file failed to load.
- Mute takes priority over the set volume. If any of the following holds, no sound is made.
  External mute (set_external_mute_provider, platform SDK or ads), user mute (set_user_muted), the page being hidden (another tab, app switch),
  the window losing focus (blur) on touch-primary devices. On iPhone the page-hidden notification arrives after the app goes down, so audio freezes without stopping and
  the last sound fragment repeats, but the focus-lost notification comes before that. Desktop (mouse) also loses focus when clicking outside the canvas, so it does not follow this.
  It is released when focus returns, the screen is pressed, or the page becomes visible again.
- While muted, the AudioContext is suspended too. (woken when released) On iPhone, if an app switch or an interstitial ad takes over a running AudioContext, waking it on return
  makes no sound, so it suspends itself beforehand. If it still does not run after being released, it tries waking it again every 0.5 seconds.
- If allowed (set_autoplay_allowed_provider, allowed if not given), it tries waking once on the first update even before a press. If blocked, the engine wakes it on the first press.
  Before the first press (user gesture) or when the AudioContext is not running, sound effects are not played. (so sounds called while suspended do not all play at once on wake)
- Sound files are loaded in the background so they do not block play. (on the web they play once decoding finishes) Sounds that fail to load simply do not play.
- Time: the same-sound interval and the re-wake interval use the wall clock (web_time::Instant) like the original performance.now(), and volume following, fade out,
  and the music's stopped position use the AudioContext clock (AudioManager::get_context_time) as in the original.
- Shared sound: set_sound_system, read_sound_system. (the original module variable, one per thread)
- Differences from the original:
  - It takes the engine instead of AudioManager at creation. The original attaches listeners to document and window, but the Rust version receives them through the engine's page events (PageEvent).
    The AudioContext is suspended or woken right where the event arrives (the sound stops immediately), and cutting sound effects happens on the next update.
  - load_sounds, load_sound take the engine to resolve paths relative to the asset folder. (in the original the browser resolves them against the page address) Desktop reads them on the spot.
    load_sounds returns an awaitable SoundLoadHandle as in the original. (waits until all requested sounds are loaded or fail, same as wait_for_load().await)
  - Volume changes and fade out are left to the sound device as in the original, with GainNode AudioParam automation (value assignment, setValueAtTime, linearRampToValueAtTime, setTargetAtTime,
    cancelScheduledValues) and source.stop(when). On the web they are applied to WebAudio, on desktop to the mixer (same math as Chromium).
    The original { source, gainNode } is one AudioPlayer created from a bus, and finished sounds (the original onended) are removed from the list in update.
    As in the original, values set with the bus's set_volume, mute last until SoundSystem applies the volume again.
  - Picking from a group and wobbling the pitch use the engine's math::random (seeded with the time on first use) in place of the original Math.random.
  - add_sound_asset (adding a sound not loaded from a file) and get_effect_voice_count were made in the Rust version first. (also added to the original under the same names)
- [core/task](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/task&lang=en): Tasks. (the engine continues game code written with async/await every frame. A file only in the Rust version)
- In the original the browser runs Promises, and an async function pauses at await and continues when the Promise resolves.
  In the Rust version the engine contains a single-threaded executor. Engine::spawn_task, spawn_scene_task, like calling an original async function,
  poll once up to the first await right where it is entrusted, and the remaining tasks are polled every frame (after updating time and input, before the scene's tick) only if woken.
  (where there is only &Engine, entrust with spawn_deferred_task, spawn_deferred_scene_task and it runs for the first time on the next polling turn)
  No external runtime is used, and desktop and web run the same code. Futures need not be Send. (they may hold Rc, the web has no threads)
- Waking: like the original microtask queue, woken tasks go into a queue (TaskWakeQueue) in the order woken, and on the polling turn they are polled from the front until the queue is empty.
  So when a task resolves a Promise or finishes, the tasks waiting on it continue in the same turn in the order resolved, as in the original.
  If a task wakes itself while being polled (futures that watch engine state: asset handles, wait::seconds, wait::next_frame and such), it goes into the next frame's queue.
  (in the original such Promises resolve in the task after the browser work finishes, so they are not checked again within the same frame)
  A Promise is woken by resolve, a TaskHandle when that task finishes, and a JsFuture wrapping a web Promise when the browser resolves it.
  Waker is Send + Sync, so the queue is held in Arc and Mutex and the flags in atomic values. (the same code on the web even without threads)
- Reaching the engine and scene: a future cannot hold &mut across an await. A task receives a context (EngineContext, SceneContext),
  and borrows the engine and scene only inside a with(|scene, engine| ...) closure. The closure is synchronous so it cannot await inside, and the lifetime of the references the closure receives
  is assigned fresh for each closure (`for<'a>`) and cannot be put in the returned value (R), so references cannot leak out of the closure.
  The context cannot be cloned and with takes &mut self, so code that calls with nested within one task does not compile.
- Soundness: only while polling, a thread-local slot (TASK_ACCESS) holds pointers to the engine and that task's scene.
  1. The engine is &'static Engine. (Engine::new puts it in a place that lives until the program ends) All engine functions are &self, so inside and outside with and
     Engine::get_engine may use the same engine overlapping.
  2. The scene pointer is made from one slot of the scene list the executor holds as &mut. Until polling ends the executor does not use that &mut again,
     and when polling finishes (even when unwinding from a panic) it restores the slot to its previous value. So the pointers are always alive while used and do not overlap borrows on the executor side.
     The first poll at the spawning place is made from the &mut scene spawn received. When the first poll ends the slot is set back to empty.
     The graphic is held by the engine, so no separate pointer is kept for it. with_graphic takes the graphic out of the engine for a moment with Engine::with_graphic, passes it, and puts it back.
     (so the first segment at the spawn site also gets the graphic. A task spawned while the engine has lent the graphic to a drawing function gets None, because the graphic is not in the engine)
     The task list being polled is a local value taken out of the engine, so borrowing the engine does not reach it. (new tasks entrusted meanwhile pile up in a separate list in the engine)
  3. with takes the pointers out of the slot (take) and restores them when done. The slot is empty meanwhile, so a second &mut cannot be made by any path.
     (calling from outside a task, calling nested inside, or sneaking in another scene's context panics with a stated reason instead of double borrowing)
  4. The scene is checked with Any to be of the context's type, and the scene handle is checked to be that task's scene.
- Even when a scene is unloaded, its tasks keep running as in the original. The engine keeps a scene value with remaining tasks alive until they all finish (it leaves the list and receives no tick, draw)
  and with keeps giving that scene. When all tasks finish, it calls destroy and drops it.
- Promise: in place of the original new Promise((resolve, reject) => ...). Promise::create gives a future and a resolve handle as a pair.
  The original reject is reject(reason) on `Promise<Result<T, E>>`. (Result instead of exceptions) If the handle is dropped without resolving, it never finishes, as in the original.
- [core/textinput](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/textinput&lang=en): Text input queue. (held by InputManager)
- The original has no such layer. The original UIInputField attaches listeners directly to a DOM <input> and document keydown.
  In the Rust version the platform puts window events (desktop winit's KeyboardInput / Ime, the web hidden <input>'s input / composition / keydown)
  into this queue, and the input field with focus takes them out on tick. (ui/uiinputfield.rs)
- Components receive only &Engine. So the side the field uses (taking out, publishing state) is made to work from &self with RefCell.
  The platform holds &Engine, so the pushing side is &mut self.
- Frame flow:
  1. The platform pushes events between frames. (push_event)
  2. On scene tick, a field takes out its share. (take_events_for_field) Attached fields and the field with focus publish their state. (register_field_state)
  3. At the end of the frame the engine calls finish_frame. It drops the remaining events and moves the published states to the "last frame states".
  4. The platform reads the last frame states and applies them. (desktop: turning IME on and off and the candidate window position, web: hidden <input> position, value, focus)
- All character positions are in characters (char). The original (JavaScript strings) uses UTF-16 units. They are the same for Hangul and differ only for characters like emoji.
  The web platform converts DOM UTF-16 positions with the functions here before pushing.
- [core/textstringtexturecache](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/textstringtexturecache&lang=en): String texture cache.
- The original bakes text chunks once per font (mode, font string, bake scale, line width) into a glyph atlas (1024 x 1024 pages, up to 8 pages), and text is drawn as a list of glyph rectangles (entries, LRU limit 1024).
- Desktop places glyphs with text shaping (textshaping.rs: bidirectional ordering, rustybuzz shaping), rasterizes only glyphs seen for the first time (CoreText on Mac, DirectWrite on Windows, skrifa on Linux) and bakes them into atlas cells.
  There is one cell per text chunk, the same chunks as the original. Hangul, Han, kana, digits, punctuation and emoji get one cell per grapheme cluster, and letters such as Latin and Cyrillic get one cell per word.
  The cell key is, for every glyph in the chunk, (face, glyph index, size, Skia 1/4 subpixel slot) and its integer offset from the first glyph, plus mode and line width and antialiasing.
  (The original keys by a 1/8 position slot that holds every Skia slot boundary. Rust knows the slot Skia itself uses, so it bakes fewer copies of the same raster)
  Where the ink of neighboring chunks touches, each cell is drawn separately, so linear filtering at fractional positions and blending of overlapping ink can differ slightly from the whole string. (Same as the original, the shape of the Skia glyph cache and TextMeshPro)
  One row above and below each cell is baked as a repeat of the edge row. (Sampling past the cell edge at a fractional vertical position returns the edge row like the old CLAMP_TO_EDGE instead of another row of the atlas)
  Fonts above 256px, right-to-left text and the web (baked with the browser Canvas2D) are baked as a whole string into one cell like the original.
  The page policy (append only to the most recently opened page, a new page when it is full, clear the least recently used page beyond 8 pages), the entry limit and the entry key fields (mode, paragraph direction, font string, line width, scale, text) are the same as the original.
  The original joins the key into a string. Here, to avoid building a string on every lookup, the key is looked up by its hash and the keys inside the same hash are compared one by one.
- Text is baked in white and the color is multiplied when drawing. (A color change does not rebake)
  Color glyphs (emoji) are baked in their own color on top of the white text. The original also uploads a canvas filled with fillText in white, so emoji are baked in their own color and the same color is multiplied when drawing.
  When baking as an outline (Stroke), color glyphs are not stroked and are laid down in their own color. (Same as Chrome strokeText)
- The font string is read in the same form as Canvas2D font (the CSS font shorthand). Examples: "16px DOSGothic", "bold 24px default", "italic 500 16px default", "12pt 'A B', C, sans-serif"
  CSS units other than px (ex, ch, cap, ic, lh, rem, including viewport units), named sizes and calc() are read like the Chrome canvas does, and "/line-height" is skipped.
  For a comma separated name list, each character is looked up starting from the face of the first name. (Same as the browser font list, parse_font_string)
- As with the original document.fonts, several faces (weight, slant, character range) are registered under one name. (register_font_face)
  Selection follows the CSS order. When there is no slanted face a fake slant (slope 1/4) is applied per glyph, and when there is no bold face a fake bold is applied per glyph. (textshaping.rs)
- Characters missing from the faces of the name are looked up in the default font, the system font chain, the standard font (desktop, Chrome's -webkit-standard) and the fallback font, in that order. (The same place as browser font fallback)
  When no face is found at all in the name list (only unknown names other than default), the standard font is placed before the default font, as Chrome does.
  The desktop system font chain (set_system_font_chain) is the names of the original SYSTEM_FONT_STRING looked up in the operating system fonts, and it follows the default font only when the default font name default is requested.
  When enabled, names in the font string that were not uploaded are also looked up in the operating system fonts. A face is read the first time a character of that weight and slant is used. (platform/desktop/systemfont.rs)
  The fallback font is chosen by the operating system. (set_system_font_fallback_enabled, asking for bold asks for the bold face separately) As in Chrome, it asks separately for the first font (the first face that has the blank) and for each font string,
  and the fallback face draws only the characters the operating system chose that face for. Characters the face in the name list draws by canonical decomposition (ï as i and U+0308) are not asked. When candidate files are given (add_fallback_font_candidate) they are used first.
  Candidate files are read when used. For emoji presentation characters a candidate with a color glyph table is read first, and for other characters a candidate without one. (Only the table list is peeked first)
- When a font face is newly uploaded, only the strings baked with a font string that uses that name and that have a character in the face's character range are discarded. (The original invalidateFontFaces)
  As in the original this happens only when turned on with set_rebake_text_on_font_load. (The engine turns it on with EngineConfiguration.rebake_text_on_font_load, off by default)
  When off, text baked with another font before the download stays until it is evicted from the cache. Removing a face and reordering are discarded regardless.
  Changing the default font or the fallback font discards everything.
- As in the original, web always bakes and measures with the browser Canvas2D. (platform/web/systemfont.rs) The uploaded font bytes are uploaded to document.fonts as a FontFace and the browser selects and draws.
  When an uploaded font finishes loading (loadingdone) the baked text is discarded at the start of the frame. Desktop bakes with the shaping and rasterization above.
- Text anti-aliasing (set_text_antialias_enabled, the original setTextAntialiasEnabled): when off, the alpha of baked text is split into 0 and 255 at the threshold 128 and the texture is sampled with NEAREST.
  Projects that draw a pixel font at integer multiples of its design size turn it off. The original keeps it as a module global and leaves already baked text alone.
  Here the cache holds it and puts the on/off state in the key, so text drawn after the change is baked that way right away. (rasterize_text does not take it, like the original ShadowText)
- Text measuring (measure_text) is not redone when the font string and the text are the same. (The cache of the original measureTextMetrics, 2048 entries)
  The original discards the least recently used one on each overflow. Here, on overflow the least recently used half is discarded at once. (Searching one by one would scan 2048 entries on every measure after overflow)
  Registering a font clears it. (The original clears it when a web font finishes loading) Since measure_text takes &self the cache lives in a RefCell.
- Getting faces on demand (watch_unresolved_family_characters, take_unresolved_family_characters): the original browser downloads an uploaded FontFace when a character in its character range is drawn.
  The Rust edition collects characters, in measured or baked text of a watched name, that fall outside the range of the uploaded faces, and UIFont takes them out in update and downloads the pieces for those characters.
- Measuring without a Graphic (measure_text_without_graphic): the original measures text anywhere with a shared 2D canvas. The Rust edition tells a thread-wide global
  the font list (Rc) every time a font is registered and measures with that list. Used when UI layout needs the number of text lines before drawing. (UIConfirmWindow)
- [core/timemanager](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/timemanager&lang=en): Time manager. (the original core/timemanager.js)
- The engine feeds the elapsed seconds every frame, and it tracks the accumulated time, frame interval, frames per second and time scale.
- In a scene, read it with engine.get_time_manager() and change the scale and limit with engine.get_time_manager_mut().
- [core/tween](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween&lang=en): Tween.
- A port of the original core/tween.js. Between a bundle of start values (name to number or Vector2) and a bundle of target values,
  it interpolates with an easing function for duration seconds after a delay, and on each tick passes the interpolated bundle to the update callback.
  When it arrives, it stops and calls the completion callback. Repeat and yoyo are not in the original, so they are not ported.
- The original Tween.easingFunction.back.easeOut is easing_function::back::ease_out.
  The names are ease_in, ease_out, ease_in_out in both engines. (original easeIn, easeOut, easeInOut; the reserved word in is not used as a name)
- The original callback holds a node object and calls node.set_position(...). In the Rust version nodes live in the scene's NodeTree,
  so the update callback and the completion callback also receive &mut NodeTree. (take out the node with the NodeId held)
- set_target(node_id): if a value name is a node property name (TweenProperty, e.g. "localPosition"), it is written straight to that node on every tick.
  If the target node is deleted, it ends quietly without callbacks. create_node_tween is a shorthand for it. (original setTarget(node), createNodeTween)
  Like the original, it ends when it leaves the node tree it first ran in (when the top node changes). The Rust version also ends when removed by destroy_node.
- Easing uses the same formulas as the original. (the original base/math.js pow is also the built-in power, so exponential and elastic values match)
- If duration is 0 or less, it is treated as finished at once (progress 1). (same as the original)
- A scene takes over a tween with SceneBase::start_tween and holds it, runs it after node tick and touch, and removes finished tweens.
  The original holds the tween object and points at it with stop_tween(tween), but in the Rust version the scene takes the tween (ownership moves),
  so it is pointed at with the TweenId that start_tween returned. get_tween / get_tween_mut exist for that reason.
- [core/tween/easing_function](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function&lang=en): Easing function. (the original Tween.easingFunction)
- Takes the progress (0 ~ 1) and returns the interpolation ratio. back, elastic overshoot outside 0 ~ 1.
- The original modifies the argument k in place (k *= 2, --k). Here each changed value is given a name.
- [core/tween/easing_function/quadratic](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/quadratic&lang=en): Quadratic curve.
- [core/tween/easing_function/cubic](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/cubic&lang=en): Cubic curve.
- [core/tween/easing_function/quartic](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/quartic&lang=en): Quartic curve.
- [core/tween/easing_function/quintic](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/quintic&lang=en): Quintic curve.
- [core/tween/easing_function/sinusoidal](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/sinusoidal&lang=en): Sine curve.
- [core/tween/easing_function/exponential](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/exponential&lang=en): Exponential curve.
- [core/tween/easing_function/circular](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/circular&lang=en): Circular curve.
- [core/tween/easing_function/elastic](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/elastic&lang=en): Springy rubber band.
- The original starts with a = 0.1, p = 0.4, but since a < 1 changes it to a = 1, s = p / 4, it always uses the values below.
- [core/tween/easing_function/back](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/back&lang=en): Pulls back slightly, then goes.
- [core/tween/easing_function/bounce](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/tween/easing_function/bounce&lang=en): Bounces on the floor.
- [core/viewmanager](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/viewmanager&lang=en): View manager.
- canvas_native_size:	Logical size of the window interior. (physical pixels / scale)
- canvas_pixel_size:	Actual rendering pixel size of the window interior. (drawing buffer)
- view_native_rect:	The view area actually used. (a sub-area relative to canvas_native_size)
- view_size:			The view size actually used. (size of the coordinate system the scene draws in)
- The original's device_pixel_ratio is the window's scale factor.
- Render scale limit (set_max_render_pixel_ratio): as in the original, only the value is stored (nothing happens for the same value) and is_view_rect_pending is raised.
  At the start of the next frame it refits with the limited scale through the same path as a window resize (Engine::resize), and calculate_view_rect lowers it.
  (Changing the canvas size in the middle of a frame makes that frame black) The web shrinks the canvas drawing buffer,
  and desktop draws at the reduced size in the bottom-left of the default framebuffer, then stretches it to the window size. (platform/desktop/renderscaler.rs)
- Safe area insets (get_safe_area_insets, set_safe_area_override) are SafeAreaInsets with named fields like the original { top, right, bottom, left }.
  The address's ?safeArea=top,right,bottom,left corresponds on desktop to the environment variable VANILLA_SAFE_AREA=top,right,bottom,left.
  CSS env(safe-area-inset-*) is read on the web and is 0 on desktop. Chrome desktop is 0 too. (nonzero values only come in on Android, platform/desktop.rs read_safe_area_insets)
  set_safe_area_override takes effect on both.
- get_client_native_size: the whole page size (window.innerWidth, innerHeight) as in the original. Desktop has no page, so it is the logical size of the window interior.
- convert_client_to_view: screen (client) coordinates to view coordinates. The web subtracts the canvas's current position, and on desktop the window's logical coordinates are the client coordinates.
- Safe area sides to ignore (set_ignored_safe_area_sides) are taken as the SafeAreaSide enum instead of the original's strings like "top".
- The canvas CSS height in get_css_pixel_scale is canvas_native_size.y. (the canvas's CSS height on the web, the window's logical height on desktop)
- apply_aspect_view_scale_mode measures the ratio with the canvas logical size. (the original uses the window interior size if the canvas size is 0.
  In the Rust version the platform fits the canvas size before the scene runs, so when it is 0 the window is 0 too)
- [core/inputactions](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/inputactions&lang=en): Input actions.
- A port of the original core/inputactions.js. Binds keys, gamepad buttons and one side of gamepad axes to action names (text the game chooses, like "confirm" or "left").
  Several can be bound to one action, and it is pressed if any one of them is pressed.
- The engine's InputManager holds one (get_input_actions) and calls update in tick at the start of the frame. The game only reads.
- A key pressed and released between frames also counts as pressed once in that frame. (InputManager.is_key_just_pressed)
- For an action with set_repeat, while held, is_just_pressed becomes true again at each interval after the wait. (menu selection)
- Axes subtract the dead zone (set_dead_zone) and rescale the rest to 0 ~ 1. Sticks are filtered by length, bound axes by one side's value.
- External sources (add_source) are where the game plugs in input the engine does not know (such as a platform SDK's pad). They implement the InputActionSource trait.
- Keys are not listened to while typing in a text input. (turned off with set_keys_ignored_while_typing)
- Like the Unity Input System, it updates once in update at the start of the frame, and reads within that frame return the values recorded then. (same as the original)
  During update it records the move keys, pad axes and external sources' move axes, and read_gamepad_stick and read_move_axis read those values.
- Differences from the original: external sources are a trait instead of JS objects, and removal uses the number given by add_source.
- [core/sharedbakecache](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/sharedbakecache&lang=en): Sharing baked images. (vanilla.js core/graphic/sharedbakecache.js, used by ShadowText, ShadowImage and SoftShade)
- The same shape (key) is baked only once and several components draw the same image (Rc). The GPU texture is also one per image, so it is shared too.
- The original counts the components using each key and calls release. In the Rust version, a component holding the Rc is itself the reference count.
  When the key changes and it holds something else, or the component goes away, the Rc is released. One held only by the cache (Rc::strong_count is 1) is one nobody uses.
- Ones nobody uses are not discarded right away but kept. (if the same shape comes back soon, it is not baked again) When adding a new one, if MAXIMUM_IDLE_BAKE_COUNT is exceeded, the least recently used are discarded first.
- Failed bakes (None) are not stored. The engine runs on one thread, so the cache is a global of that one thread.
- [core/textshaping](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/core/textshaping&lang=en): Text shaping. (picking font faces, bidirectional ordering, joining glyph shapes, glyph rasterization)
- In the original the browser's Canvas2D does all of this. (CSS font selection, the bidirectional algorithm, HarfBuzz shaping, Skia rasterization)
  The Rust version follows the same sequence with crates:
  - Font faces (FontFaceDescriptors): like CSS @font-face, several faces with different weights, slants and character ranges (unicode-range) sit under one name.
    Selection follows the CSS Fonts order (slant, then weight), and faces with the same weight and slant are split by character range when drawing. A face added later wins.
  - Bidirectional ordering: unicode-bidi (UAX #9). The paragraph direction is given by the baking side. (original canvas.direction)
  - Shaping: rustybuzz (a port of HarfBuzz). Arabic joining, ligatures, kerning and combining mark placement come out like the browser.
    Like Chrome's HarfBuzzFace::GetScaledFont, the position scale is set to the font size as a 16.16 fixed-point number. rustybuzz 0.20.1 has no scale,
    so the repository carries a build of third_party/rustybuzz with hb_font_set_scale (Face::set_scale) added. Font-unit values are rounded from that scale with em_scale, variable GPOS deltas with em_scalef,
    and axis values are normalized like HarfBuzz hb_ot_var_normalize_coords. The bundled third_party/ttf-parser is a build with the device table base of pair kerning (PairPos format 1) corrected.
  - Rasterization: fontdue's glyph-index rasterization. Faces with no bold get a fake bold, and faces with no italic get a fake italic, applied per glyph.
    Color glyphs (sbix, CBDT, COLR) are drawn in their own colors by colorglyph.rs. Like Chrome, fake italic is applied and fake bold is not.
- Emoji presentation: a face in the name list is used first if it has the glyph, regardless of color. In the operating system fallback step, VS16 (FE0F), Emoji_Presentation characters, skin tone modifiers, flags, keycaps and tag sequences
  pick a face with color glyphs first, and everything else (including VS15) picks a non-color face first. A sequence carrying a variation selector accepts only the face matching that presentation even in the name list.
  Chrome draws ❤️ (FE0F) with the color emoji font and a bare ❤ with the specified font, even if the specified font has a monochrome ❤. (checked with Canvas2D on Mac Chrome)
  Linux Chrome 157 draws a bare 😀 in "16px DejaVu Sans" with DejaVu Sans's monochrome glyph. (measureText on CI)
- Fake italic and fake bold are the same values Chromium gives Skia:
  slant 1/4 (setSkewX(-SK_Scalar1 / 4) in font_platform_data.cc), and bold widens the outline by painting a stroke of 1/24 (9px and below) to 1/32 (36px and above) of the font size.
  (kStdFakeBoldInterpKeys / Values in Skia SkTextFormatParams.h) Both leave the advance unchanged.
  Fake bold applies when the requested weight is 600 or more and the chosen face is below 600. (Blink kBoldThreshold)
- Font bytes are held by LoadedFont together with the rustybuzz face. (self_cell, the face borrows the bytes) When the registration is removed and nothing uses it, the bytes are given back too.
  Several faces of the same file (the weights of a TTC, the weight instances of a variable font) share the bytes (Rc).
- Font collections like TTC are read by choosing a face index (face_index). (find_collection_face_index picks it by weight and slant)
- Variable fonts (the wght axis of fvar) make weight instances from axis values. (variation_list of create_from_shared_bytes) Shaping reads the axis values in rustybuzz,
  but fontdue cannot read axis values and cannot draw the outlines of variable fonts like Mac SFNS, so variable fonts take outlines with axis values applied from skrifa and are drawn with colorglyph's area-accumulation raster.
  (Chrome also draws the weight of a variable font from axis values)
- Optical size (opsz axis) and the tracking table (trak): Chrome sets the font's opsz axis to the font size. (initial value auto of font-optical-sizing, FontPlatformDataFromCTFont in Mac font_platform_data_mac.mm,
  font_custom_platform_data.cc for web fonts on every operating system. It is not applied to Windows and Linux system fonts)
  Shaping gives HarfBuzz the font size as ptem and adds the tracking of the AAT trak table. (GetScaledFont in harfbuzz_face.cc, on Mac the advances of a font that has trak and no sbix
  are computed by HarfBuzz instead of CoreText) The Rust version also sets opsz with the baking size (the original grows the px of the font string by the baking scale) and adds trak.
  trak is added here like HarfBuzz 15 (hb-aat-layout-trak-table.hh), not by rustybuzz. Between sizes it joins straight without rounding, outside the start and end of the table
  it is the end value, and it is added only to the advance of the first glyph of a cluster. It is not applied to fonts with no STAT table.
  (rustybuzz 0.20 rounds to integer font units, extends past the table, adds half to x_offset too, and does not look at STAT)
  The Mac system UI font (SFNS, opsz 17 to 96, initial 28) matches Chrome at 16px with opsz 17 and trak -40 units. (color emoji keep CoreText's advance as is)
- Per-word shaping: the Chrome canvas (SegmentWord in platform/fonts/plain_text_node.cc) splits text into words and shapes each separately. There is no kerning or ligature across a space.
  Space (U+0020), tab and ZWSP stand alone, and CJK characters and emoji are separate per character. (find_chrome_word_end) Tab, line feed, form feed and carriage return in the canvas are turned into spaces.
- Mac: glyphs are drawn with CoreText like the original Chrome on Mac. (platform/desktop/coretextglyph.rs) Non-color glyphs are an A8 mask with the same settings as Chrome Canvas2D (font smoothing,
  undoing CoreGraphics gamma, gamma precorrection by text color luminance, quarter-pixel subpixel positions), and color emoji fonts read from files (sbix) are CoreText color pictures. (rasterize_glyph_at)
  The advance of color emoji is multiplied by the ratio at which CoreText enlarges them at small sizes and rounded to whole pixels. (20 at 16px, 16 at 13px, same as Chrome measureText)
- Windows: non-color glyphs are drawn with DirectWrite like Chrome on Windows. (platform/desktop/directwriteglyph.rs, grayscale A8 and gamma precorrection of Skia SkScalerContext_DW, quarter-pixel subpixel positions)
- Linux: Chrome 158 on Linux draws fonts with Skia Fontations (skrifa), not FreeType. The Rust version also hints skrifa outlines with fontconfig's hinting level,
  precorrects with gamma 1.2 and contrast 0.2, and uses quarter-pixel subpixel positions. (rasterize_hinted_outline_mask)
- [effect](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/effect&lang=en): Effect.
- [effect/heathazeeffect](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/effect/heathazeeffect&lang=en): Heat haze effect component. (HeatHazeEffect of the original effect/heathazeeffect.js)
- Copies what was drawn on screen before this node, as large as the node area, and redraws it shaking each row left and right along a sine curve.
  So it shows only when attached to a node drawn at the top (last) of the scene. Child nodes are drawn over the effect.
- Like the original, it flushes the batch, copies the node's screen area (pixels) into a texture with copyTexSubImage2D, and draws one quad per row as vertex color quads (draw_colored_quads).
  When the node area goes off screen, the edge pixels of the screen are stretched. (CLAMP_TO_EDGE)
- Like the original, it is a component attached to a node, and sets the node content_size to 300 x 300 when attached if it is empty.
- Differences from the original:
  - The copied texture is a GL resource, so call destroy() when done. Like the original it holds the context that made the texture (a weak handle) so it takes no argument,
    and it also deletes it by itself when the component is dropped (Drop, when the node is removed or the scene is unloaded). (same as ScreenEffect)
  - When a row exceeds the vertex count that can be drawn at once (the Graphic limit), it is drawn in parts. The original grows the array and draws at once.
- [effect/particlesystem](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/effect/particlesystem&lang=en): Particle system component.
- ParticleSystem of the original effect/particlesystem.js. Names, defaults and usage (play / stop / emit / simulate / setStart...) follow the original.
- Like the original, particles come out of the origin of the coordinates the component draws in (the top left of the node content_size area is the origin). For a node whose content_size is 0, it is the node position.
  The attractor position (set_attractor) uses the same coordinates as in the original.
- The order of drawing random numbers and of calculations when emitting is also the same as the original. With the same seed (set_random_seed), the same particles as the original come out.
  (The seeded random is the same sequence as the original down to the bit. Particle math is also f64 like the original)
- Draws with draw_colored_quads, carrying a color per vertex. Like the original, the image shape also does not use the color curve or start color (r, g, b) and only fades by start alpha x (1 - life ratio).
  The original draws image separately per particle, and the Rust version draws at once with the image texture. (the drawn positions and colors are the same)
- Differences from the original:
  - Emitter shape, render shape and blending are enums (ParticleEmitterShape, ParticleRenderShape, BlendMode) instead of the original strings. The description (apply_description) reads the original strings.
  - Rust has no default arguments of the original (like setStartLifetime(min, max = min)), so both values are taken. The origin offset of emit is an Option.
  - The node local position added when emitting in world space (set_world_space) is read in tick, because a Rust component cannot read the node outside tick and draw.
    To emit at the node position at emit time like the original, emit with ParticleSystem::emit_in_tree(tree, node, count, offset), or put the position with set_node_position and emit.
    (The emit event of Timeline emits after putting the node position at that moment)
  - Vertex color quads are drawn in parts of the vertex count that can be drawn at once (the Graphic limit). The original grows the array and draws at once.
  - The imageDataUrl of the description (the data: URL of the image picked in the particle editor) is decoded on the spot on desktop, and on the web the browser decodes it like the original and it draws once decoded.
- [effect/screeneffect](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/effect/screeneffect&lang=en): Screen effect. (scene post-processing chain)
- Ported from the original effect/screeneffect.js. Effect names, apply order, default parameters, parameter names, default colors and GLSL bodies are copied from the original tables as they are.
- The scene is drawn to the screen as is, and end() copies the screen (or the area set with set_region), applies the enabled effects in order and puts it back in the same place.
  The screen is copied into an RGB8 texture with copyTexSubImage2D, and effects are applied with FullscreenPass going back and forth between ping-pong / half size framebuffers. The last step draws to the default framebuffer.
- The area is in canvas pixel coordinates (top left origin), and with a rounded corner radius the outside of it keeps the original.
- Shaders are GLSL ES 3.00. On desktop (GL 3.3 core) ShaderProgram changes only the header to #version 330 core, and the web (WebGL2) uses them as they are.
- The engine is not modified. Like the original, the scene calls begin at the start of pre_draw, end at the end of post_draw, and tick in tick:
  ```text
    // in the scene load
    self.screen_effect = ScreenEffect::new();
    self.screen_effect.set_enabled(ScreenEffectType::Vignette, true);
    // at the start of pre_draw / at the end of post_draw
    self.screen_effect.begin(graphic);  ...  self.screen_effect.end(graphic);
    // in tick
    self.screen_effect.tick(time_delta);
  ```
- When building a pass shader fails, both engines report once and skip that step. (one failing effect does not stop the frame)
- Differences from the original:
  - The original takes a Graphic in the constructor and holds the GL context. The Rust version is made taking nothing, makes GL resources at the first end, and each function takes a Graphic.
    At that time it holds a weak handle to the GL context, so destroy() releases without arguments like the original, and it also releases by itself when dropped (Drop, when the scene is unloaded).
  - Effects are the ScreenEffectType enum instead of strings. (the original string names are get_name / from_name)
- [effect/shadersprite](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/effect/shadersprite&lang=en): Shader sprite component.
- A port of the original effect/shadersprite.js. Same as Sprite but applies fragment shader effects (dissolve / flash / outline / hologram / wave / mosaic / glitch / shine / silhouette / grayscale / hue rotation / wipe / iris / chromatic aberration).
- The effect time runs by itself (tick), and the progress is pushed in by tweens / timelines.
- Effect names, default parameters, default colors and GLSL bodies are carried over from the original table as they are. Shaders are GLSL ES 3.00, and on desktop ShaderProgram changes only the header to #version 330 core.
- Drawing: if there is an effect, it swaps in the effect program with Graphic.set_shader_program_override, uploads the effect uniforms, and then follows the Sprite output path as is.
  While swapped in, it is not batched. (a ShaderSprite without an effect is batched together with Sprites)
- Usage:
  ```text
    let shader_sprite = node.add_component(ShaderSprite::create_with_image(image));
    shader_sprite.set_effect(ShaderSpriteEffect::Dissolve);
    shader_sprite.set_effect_progress(0.5);
  ```
- Differences from the original:
  - The original inherits from Sprite. The Rust version contains a Sprite and lets Sprite functions (set_image, set_image_rect, set_color ...) be called as is through Deref / DerefMut.
    It reports the embedded Sprite with Component::get_base_component, so it is also found with `get_component::<Sprite>()`. (same as the original instanceof)
  - Effects are the ShaderSpriteEffect enum instead of strings. (the original string names via get_name / from_name)
  - The effect program cache is held by Graphic.resolve_shader_program instead of the original's per-context WeakMap.
- If creating a program fails, both engines report it once and draw as a Sprite without the effect. (one failing effect does not stop the frame)
- [effect/trailrenderer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/effect/trailrenderer&lang=en): Trail renderer component.
- A port of the original effect/trailrenderer.js. Records the places a node passed as points and draws them as a band whose width / color fades out. (the 2D counterpart of Unity's TrailRenderer)
- Points are recorded in the node's local position (parent coordinates), and when drawing they are converted to coordinates relative to the node origin and drawn under the node transform. (same as the original)
- One draw_line per segment, so batching gathers them into one draw call. (with additive blending it breaks before and after the blend change)
- Usage:
  ```text
    let trail = node.add_component(TrailRenderer::new());
    trail.set_time(0.5);
    trail.set_width(14.0, 0.0);
    trail.set_colors(Color::create(0.4, 0.8, 1.0, 0.9), Color::create(0.4, 0.8, 1.0, 0.0));
  ```
- Differences from the original: the original passes colors as "rgba(r, g, b, a)" strings, so RGB is rounded to 0 ~ 255 integers. The Rust version does the same rounding and passes a Color.
- [game](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/game&lang=en): Game common. (the original src/game)
- [game/gamescene](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/game/gamescene&lang=en): 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)
- [graphics3d](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d&lang=en): 3D graphics. (the original src/graphics3d, the WebGL2 3D stack)
- Like the original, it shares one GL context with the 2D Graphic. Functions that create GL objects or draw take gl: &GlContext instead of the original's webGL2RenderingContext
  member. (taken out with Graphic.get_gl(). Same form as ShaderProgram)
- Before drawing 3D, flush the accumulated 2D with graphic.flush_batch(), and after drawing restore the
  2D program, vertex array, viewport, blend and depth state with graphic.restore_render_state().
- One file is one original file. fullscreenpass.js is in core::fullscreenpass and is re-exported here.
  Not carried over from the original: webgl2.js and gl2d.js (dead code, the original moved them to src/deprecated).
- [graphics3d/ambientocclusioneffect](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/ambientocclusioneffect&lang=en): Screen space ambient occlusion. (the original graphics3d/ambientocclusioneffect.js)
- Depth + normal buffers → hemisphere sample occlusion → depth aware blur. The result is the visibility (1 = no occlusion) in the r channel of get_result_texture().
- The render() inputs are the main pass's depth texture and world normal texture (alpha = coverage), and the camera's view rotation / projection parameters.
- The GLSL, kernel and defaults (radius 0.03, intensity 1, bias 0.002, scale 0.5) are the same as the original. The original ${SAMPLE_COUNT} became the number 16.
- Functions that use GL take gl, and creation and resizing return an error (Result) if GL objects cannot be made.
- [graphics3d/bloomeffect](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/bloomeffect&lang=en): Bloom effect. (the original graphics3d/bloomeffect.js)
- Bright area extraction → half resolution Gaussian blur ping-pong. The render() result texture is used by adding it in the final composite pass.
- Shaders, pass order and defaults (threshold 0.5 ~ 0.95, iterations 2) are the same as the original.
- The exchanged buffers are RGBA8 by default, so bright values above 1 are clipped. With set_use_float_color(true) they are built as RGBA16F and HDR values are blurred as they are.
- Functions that use GL take gl, and creation and resizing return an error (Result) if GL objects cannot be made.
- [graphics3d/fbxloader](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/fbxloader&lang=en): FBX loader. (the original graphics3d/fbxloader.js)
- Binary FBX → GL independent intermediate representation (FbxSceneData). After low level node/property parsing, it interprets the object/connection graph
  and extracts the node hierarchy / skinned meshes / materials / embedded textures / skeletal animation. The result is consumed as GL resources by SkinnedModel.
- Like the original, it is a pure parser. It knows nothing of GL or shading and also runs on wasm32. Compressed arrays (deflate, zlib header) are decompressed with flate2 (pure Rust).
- Differences from the original:
  - The original is async. (because it decompresses compressed arrays with the browser's DecompressionStream) The Rust version finishes on the spot with flate2.
    The Promise of the original loadFromUrl(url) is a load handle (FbxLoadHandle) like ImageAsset. load_from_url(engine, asset path) asks for the bytes through the engine's asset loading
    (desktop reads from the asset folder candidates, the web fetches from asset_base_url), and once received, get_scene_data returns the parsed result.
    The handle can be awaited as is. (inside an engine task, FbxLoader::load_from_url(engine, path).await yields the parsed result like the original await FbxLoader.loadFromUrl(url))
  - 64 bit integers: the original holds single values like object ids as BigInt when they exceed 2^53. The Rust version uses i64. Arrays (key times) are Number in the original.
  - The original uses ordered Maps. The Rust version gives the same iteration order with FbxObjectMap, which keeps insertion order.
  - objectById, which the original builds but does not use, and getDataView / getFileBytes / getTextDecoder were not carried over.
- The name of nodes and animation stacks is the FBX name with the kind tail ("\u{0}\u{1}Model", "\u{0}\u{1}AnimStack") removed, as in the original. (bone name matching also uses this name)
- [graphics3d/jointblock](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/jointblock&lang=en): Joint matrix uniform block. (original graphics3d/jointblock.js)
- 96 joint matrices are 384 vec4 slots, which exceeds the 256 vertex uniform slots (MAX_VERTEX_UNIFORM_VECTORS) that WebGL2 guarantees at minimum.
  Desktop GPUs have 4096 slots so it still runs there, but Android Chrome (Galaxy Z Fold3) fails to link. Large arrays go through a uniform block.
  (On mobile, Unity passes skinning matrices as a constant buffer and Unreal reads a bone buffer, the same approach)
- The block is std140, so a mat4 is four column-major vec4 and 16 f32 values fit as they are. The shader body uses jointMatrices[index] unchanged.
- ShaderProgram binds the binding point to JOINT_BLOCK_BINDING after linking.
- When giving SkinnedModelRenderer a replacement vertex shader, insert JOINT_BLOCK_GLSL instead of `uniform mat4 jointMatrices[96];`.
- [graphics3d/material](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/material&lang=en): Material. (the original graphics3d/material.js)
- Shader template reference + metallic-roughness PBR parameters/textures, format neutral. Models only apply material instances.
- Builds GL textures from the neutral material description made by importers (factors + image bytes, MaterialDescription).
- FBX specular/gloss maps approximate roughness through the glossiness path.
- The texture unit layout is the same as the original: 0 = base_color, 1 = shadow map only (do not use), 2 ~ 8 = normal / metallicRoughness /
  glossiness / occlusion / emissive / specular / opacity, extra slots are 9 and above.
- Differences from the original:
  - The shader program is shared with the renderer as `Rc<ShaderProgram>`. Model drawables point to materials with `Rc<Material>`. (the original reference semantics)
    set_texture / set_use_alpha_cutout / set_subsurface_factor, which modify the instance in the original, hold their state in Cell internally so they can be called with &self.
  - Image decoding is done on the spot with the image crate (png, jpeg, webp, gif, bmp, ico) instead of the original createImageBitmap (async). So there is no async.
    As in the original on Chrome, the type is not used for decoding and the format is detected from the content. (Chrome createImageBitmap(Blob) also picks the decoder by content, not by the Blob type)
    Like the original, flip_y flips it vertically and is_color_data uploads it as SRGB8_ALPHA8.
  - The Promise of the original loadImageDescription(url) is a load handle (ImageDescriptionLoadHandle), like ImageAsset. load_image_description(engine, asset path, options)
    requests the bytes through the engine's asset loading (asset folder candidates on desktop, fetch from asset_base_url on the web), and once loaded get_image_description builds the description.
    The handle can be awaited directly. (inside an engine task, Material::load_image_description(engine, path, options).await yields the description like the original await)
    mime_type is the content-type of the response, as in the original. (the web fetch response header, None without the header) Desktop has no response, so it is the type detected from the content.
    (Image::sniff_image_mime_type, the image table of WHATWG MIME sniffing plus AVIF, None when unknown) create_image_description(bytes), which takes bytes, is the same as the original.
  - The source (canvas/bitmap) of the original image description is taken as RGBA pixels (ImageSource).
- [graphics3d/rendertarget](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/rendertarget&lang=en): Render target. (the original graphics3d/rendertarget.js)
- Offscreen framebuffer + color texture [+ depth renderbuffer / depth texture]. The basic unit of a post-processing chain.
- Options can enable multiple color attachments (MRT) / half-float color (HDR) / depth texture / multisampling / depth bits.
  The original options object { colorAttachmentCount, useFloatColor, useDepthTexture, sampleCount, depthBits } became RenderTargetOptions.
- When sample_count is 2 or more, drawing goes to multisample (MSAA) renderbuffers and resolve() resolves them into the color textures (and the depth texture).
  If it exceeds what the device supports (MAX_SAMPLES, and on the web also the sample counts supported per format), it is reduced to the largest supported value below it, and if that is unsupported or the framebuffer is incomplete, it is built without multisampling. (get_sample_count)
  Desktop GL 3.3 has no function to query the supported sample counts per format (glGetInternalformativ, GL 4.2), so only MAX_SAMPLES is checked. (3.3 supports up to MAX_SAMPLES for float and non-integer color formats)
  With multisampling, get_framebuffer is the multisample framebuffer drawn to, and get_resolve_framebuffer is the framebuffer with the textures attached. Call resolve() before reading the textures.
- depth_bits is the bit count of the depth renderbuffer (16 or 24). The depth texture is always 24-bit. With multisampling and a depth texture, the multisample depth is also built as 24-bit and resolved as is.
- The original enables EXT_color_buffer_float to render RGBA16F. Desktop GL 3.3 supports it by default, and on the web glow enables it when
  creating the context.
- When a GL object cannot be created, the original continues as is, but the Rust version returns an error (Result).
- [graphics3d/shadowmap](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/shadowmap&lang=en): Shadow map. (original graphics3d/shadowmap.js)
- Real-time directional light shadows, a depth texture (hardware compare sampling, sampler2DShadow) and an orthographic light matrix.
- begin_render() starts the depth pass, and the main pass samples the resulting texture.
- The light matrix snaps to texel units to reduce shadow edge shimmer while moving. When the light points almost straight up or down, the up axis is taken as z so the matrix does not break.
- Construction restores the previous texture and framebuffer bindings. (so building it after models does not leave the depth texture on a texture unit and make drawing INVALID_OPERATION)
- ShadowAtlas: stores point light and spot light shadows as tiles in one depth texture. (original ShadowAtlas, the form of Unity URP's additional light shadow atlas)
  Tile size follows the URP default. Each tile asks for tile_resolution, and if they do not all fit in the atlas, the tile side is halved until they fit. (512 for one point light, 1024 for one spot light)
  The toon shader pushes the receiving position toward the normal by (1 + 3 x (1 - dot(N, L))) tile texels at that distance before comparing. (larger for surfaces at a grazing angle to the light, prevents shadow acne)
- Texel snapping rounds 0.5 up, like the original Math.round. (Rust round goes away from zero, so it differs for negative numbers)
- The original default resolution argument 2048 is DEFAULT_SHADOWMAP_RESOLUTION. (Rust has no default arguments)
- The sun shadow bias is the shadow-texel value of set_bias(depth, normal). (default 1, 1, the same unit as Depth Bias and Normal Bias of Unity URP, the receiving ToonRenderer applies it multiplied by the texel size and slope)
- The shadow update mode (the original ShadowUpdateMode) lives in the shadow depth cache that ShadowMap and ShadowAtlas each hold (the original createShadowCache). ToonDrawQueue compares, and begin_render binds by that decision.
  begin_render changes the cache through &self, so the cache sits in a RefCell. (The original changes the values in the object directly)
- [graphics3d/skinnedmodel](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/skinnedmodel&lang=en): Skinned model. (the original graphics3d/skinnedmodel.js)
- Model instance, mesh/bone/skin/material/animation data + pose state. Rendering is handled by SkinnedModelRenderer.
- Interprets GLB (binary glTF) and binary FBX into a common neutral schema (MeshDescription + MaterialDescription) and builds GL resources.
  (importers only parse → neutral schema → shared GL upload upload_meshes_and_materials)
- Static meshes without a skin use a synthetic skin (1 joint), and morph targets are uploaded as float textures, so they draw through the same skinning path.
- Supports animation cross-fades, joint rotation offsets (procedural pose adjustment) and morph weights (glTF weights / code) like the original.
- Differences from the original:
  - The original is async and fetches URLs (loadFromUrl, loadFromBytes for bytes). The byte functions of the Rust version
    load_from_bytes / load_from_fbx_bytes / add_animations_from_fbx_bytes finish on the spot.
    The URL functions load_from_url / load_from_fbx_url, like ImageAsset, use the engine's asset loading (asset folder candidates on desktop, fetch from asset_base_url on the web)
    to request the bytes and return a load handle (SkinnedModelLoadHandle). Once loaded, the handle's create_model(gl, renderer) builds the model. (the form without await)
    The original await SkinnedModel.loadFromUrl(gl, url, renderer) becomes load_from_url_async(engine, path, renderer).await inside an engine task. (load_from_fbx_url_async for fbx)
    Once loaded, the model is built with the GL of the engine polling the task. (the renderer only shares its shader program at the call and is not borrowed)
    add_animations_from_fbx_url requests the load and returns an awaitable AnimationLoadHandle. Like the original, the clips are already added when await finishes.
    (the clip list is shared with the handle, and once loaded, whichever comes first among the awaiting future, the next update or play_animation adds them. They are added in load order like the original)
  - Functions that use GL take gl. update(delta_time) does not use GL. Step 6 of the original update (uploading changed morph targets) is
    done instead by the renderer's draw / draw_depth / draw_wireframe through upload_pending_morph_targets. (that is why the draw functions take a &mut model)
    Thanks to this, update can be called in the scene's tick.
  - The original node / drawable / skin / clip objects are the SkinnedModelNode / Drawable / Skin / AnimationClip structs.
    A drawable's material is `Rc<Material>`. Clips are referred to by index, and sample_animation also takes a clip index.
    upload_wireframe_indices / upload_morph_targets take a drawable index instead of the original drawable object. (a drawable cannot be passed while the model is borrowed as &mut)
  - A drawable's mesh_description has empty morph_targets because the morph targets were moved to morph_target_list. (the large delta arrays are not held twice)
  - Like the original, node matrix, CUBICSPLINE interpolation and primitive mode are ignored. Like the original, FBX draws only meshes with a skin attached.
- The uploaded buffers, material prototypes, morph textures, node and skin prototypes and clips are held once by SkinnedModelAsset, and the model is its instance. (same as the original)
  create_instance and create_from_asset build instances without a GPU upload, and loads (create_model, load_from_url_async) use the asset cache.
  destroy deletes this instance's resources (wireframe buffers, forked morph textures, materials forked by get_material) and releases the asset.
  Materials given from outside with set_material are not deleted. (same as the original)
- [graphics3d/skinnedmodelasset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/skinnedmodelasset&lang=en): Skinned model asset. (original graphics3d/skinnedmodelasset.js)
- Decoded data and GPU resources shared by the model instances built from the same file. Holds one copy of the mesh buffers and vertex arrays, the material prototypes and their textures,
  the morph textures, the node and skin prototypes and the animation clips. (the same as clones sharing Unity's mesh and sharedMaterial, or three.js BufferGeometry and Material)
- Instances (SkinnedModel) share it by reference count. Each instance keeps its own pose, animation playback state, morph weights,
  forked materials (get_material), wireframe buffers and morph textures forked by add_morph_target.
- When the last instance calls destroy (reference count 0), the GPU resources are deleted and the asset leaves the cache. The reference count is kept by retain / release, not by the Rc count.
  (the same count as the original; holding more Rc through get_asset does not extend the resource lifetime beyond the instances)
- The cache is looked up by shader program and asset key (a path or asset name normalized with normalize_key). Loads such as the load handle's create_model
  and load_from_url_async use it. There is one cache per thread. (because a GL context is bound to a thread)
- [graphics3d/skinnedmodelrenderer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/skinnedmodelrenderer&lang=en): Skinned model renderer. (the original graphics3d/skinnedmodelrenderer.js)
- Owns the skinning PBR shader template + environment state (shadow map / sun / fog), one per scene. SkinnedModel holds only data/pose,
  and this object does the rendering, taking a model instance.
- Injecting fragment shader source lets you build another shading template on the same skinning/morph vertex path.
  (a derived renderer sets its own uniforms after using the shader and calls draw())
- The GLSL is the same as the original. (Cook-Torrance GGX, screen space derivative cotangent normal map, 3x3 PCF shadow, hemisphere ambient, distance fog)
  ${MORPH_GLSL} / ${MORPH_TARGET_MAXIMUM} in the original template string are ported as concat! and the number 96. (a test checks that the two match)
- Texture units: 0 = base_color, 1 = shadow map, 2 ~ 8 = material slots, 15 = morph target texture.
  Without a shadow map, a 1x1 comparison depth texture is bound to the shadow unit. (same as the original)
- Differences from the original:
  - Draw functions take gl and &mut SkinnedModel. Uploading changed morph targets (step 6 of the original update) and wireframe indices
    is done here first. Matrix arguments are &[f64; 16] like the original getElements(). (matrix.get_elements())
  - set_shadow_map copies 16 values instead of holding the array by reference like the original.
  - Creation returns shader compile failure as an error (Result).
- [graphics3d/subsurfacescatteringeffect](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/subsurfacescatteringeffect&lang=en): Screen-space subsurface scattering. (the original graphics3d/subsurfacescatteringeffect.js)
- Separable, depth-aware horizontal/vertical blur of the diffuse irradiance buffer. Builds per-channel kernels from the skin diffusion profile (sum of Gaussians),
  and projects the scattering width (world units) onto the screen according to depth.
- The render() input is an irradiance texture with the scattering mask in alpha and the depth texture of the same pass. The result is get_result_texture().
- The GLSL, kernel formula and defaults (scattering width 0.2, falloff (1, 0.37, 0.3), strength (0.48, 0.41, 0.28)) are the same as the original.
  The original ${KERNEL_SAMPLE_COUNT} / ${KERNEL_RANGE} became the numbers 17 / 3.
- Functions that use GL take gl, and construction and resizing return an error (Result) if GL objects cannot be created.
- [graphics3d/toon](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon&lang=en): Toon 3D. (clay-like single color materials and outlines, vanilla.js graphics3d/toon)
- meshbuilder: basic shapes, building models, outline hulls
- glbmeshreader: reading GLB into vertex arrays, skeletons and animations, pose math
- toonrenderer: cel shading, outlines, skeleton poses, GPU instancing, culling off-screen objects, drawing with shadows
- toonpostprocess: HDR float render target, bloom, tone mapping
- [graphics3d/toon/glbmeshreader](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/glbmeshreader&lang=en): Reading clay models (GLB) and skeleton poses. (vanilla.js graphics3d/toon/glbmeshreader.js)
- Reads models painted with material colors into toon 3D MeshBuilder vertex arrays. Texture coordinates and material textures are read too if present. (Came from webgame-rimminer)
  - One part is one node, and a node's mesh is one primitive per color. Vertices are position and normal, plus joint indices and weights if there is a skeleton.
    A primitive without normals gets flat normals (one per triangle) as the glTF spec says. (Vertices are split per triangle)
  - The material's baseColorFactor is a linear color, so it is converted to sRGB (pow 1 / 2.2 in the gamma color space, the standard sRGB curve in the linear color space, the inverse of the curve the shader decodes with), and emissiveFactor, if present, is stored as emission. (with emissiveTexture, the emission is passed only as a material range)
  - TEXCOORD_0, if present, goes into uv_data and TEXCOORD_1 into uv1_data (second UV, angel ring). A material range (ToonMaterialRange) is stored per primitive. (Material name, extras, texture image order)
    When painting split areas inside a part (accent color areas, display panels), pick them by material name or extras and draw only that area with index_start and index_count of ToonDrawOptions.
  - Images are read with read_glb_images, decoded with decode_glb_image and passed to ToonRenderer::create_texture.
  - outline in material extras is an outline shell (only back faces drawn), and basic is a part that does not receive light.
    If outline options are given, that shell is not stored, and a shell of uniform thickness per point is newly built from the body of each node that has a ".outline" pair.
  - If there is a skeleton (skin), the joint nodes and their inverse bind matrices, the animations (animations) and their extras are read together. Poses are computed by write_skin_pose.
    To modify bones before the blended pose is built into skin matrices, pass a hook (ToonPoseAdjust::Hook) or a modification table (ToonPoseAdjust::Bones, adjust_bones, BoneModifier) as pose_adjust.
  - Models whose parts are hidden or painted separately are read per node with read_glb_node_arrays. (Together with node extras and transparency)
  - For a skeletal model read as one lump, node extras, part positions and the joints they follow are read separately with read_glb_node_infos.
  - GLB files whose vertex attributes are stored as integers (KHR_mesh_quantization) are read too. Normalized integers are divided with the glTF spec formulas, and texture coordinates get the material texture KHR_texture_transform baked in.
    An unnamed mesh node belongs to the part of its named parent node. (the leaf node a quantizer adds for the dequantization transform) Err if extensionsRequired lists an extension that cannot be read (meshopt compression and others) or an accessor points to a buffer outside the binary chunk.
- Separate from the engine's SkinnedModel (textured PBR). Only the vertex arrays used for toon drawing are extracted.
- [graphics3d/toon/meshbuilder](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/meshbuilder&lang=en): Building toon 3D models. (MeshBuilder and basic shapes of vanilla.js graphics3d/toon/meshbuilder.js)
- Builds the vertex array used to draw toon 3D (single-color clay-like material with outlines). It came from the in-board 3D of webgame-rimminer. (Same form as the three.js basic geometries)
- Shapes are built in their own coordinates with the center at the origin. When a part is added, position, rotation and scale are multiplied in and it is put into one lump.
- One vertex is position 3, normal 3, color 3 (sRGB), material 2 (glow strength, unlit), pattern 4 (pattern number, pattern color).
  The meaning of the pattern number and color is decided by the shader that draws it. (0 means no pattern)
- Texture coordinates (UV) are stored separately, 2 per vertex, in uv_data outside the vertex array. If even one vertex was given a UV, the rest are filled with 0. (uvs of a shape, add_triangles_with_uvs)
- The second UV is stored the same way in uv1_data. (uvs1 of a shape, uvs1 of add_triangles_with_uvs, TEXCOORD_1 of GLB, for things that read a second unwrap such as the angel ring)
  (0, 0) is the top left of the image. (Same as glTF) A box is 0 ~ 1 per face, a sphere is 0 ~ 1 by longitude and latitude.
- A material range (material_ranges) is the span of body vertex indices that holds one material. The GLB reader stores one per primitive. (Material name, extras, textures, index_start and index_count of ToonDrawOptions)
- The outline is a shell pushed out by the same thickness at every point of the part. Since only its back faces are drawn, it is stored separately. (inverted hull)
- Triangle winding is fixed by looking at the vertex normals so the outside becomes the front face. (Back-face culling and the outline rely on winding)
- [graphics3d/toon/toonpostprocess](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/toonpostprocess&lang=en): Toon HDR finishing. (ToonPostProcess of vanilla.js graphics3d/toon/toonpostprocess.js)
- Outputs linear color drawn to a float render target to the screen with bloom, exposure, tone mapping and gamma.
- Combines the engine's RenderTarget (half-float color, depth), BloomEffect (or MultiLevelBloomEffect) and FullscreenPass.
- Usage: after ToonRenderer::set_hdr_output(true)
  begin(gl, background linear color) → draw with ToonRenderer → end(gl, output framebuffer, viewport)
  end (resolves first if multisampled) computes bloom and draws the tone-mapped color into the output framebuffer (screen if None). To mix with 2D, call Graphic::restore_render_state after it.
- Constructor options: new_with_options(gl, width, height, ToonPostProcessOptions { sample_count, use_float_color, depth_bits, use_depth_texture }) (the options of the original constructor, new uses the default options, same as now: RGBA16F, depth 16, no multisampling)
  If sample_count is 2 or more, the scene is drawn to a multisampled (MSAA) renderbuffer and resolved to a texture before end. Reduced to a count the device supports. (get_sample_count, set_sample_count)
  depth_bits 24 means 24-bit depth. (scenes with a distant far plane) use_depth_texture keeps the scene depth as a texture. (used by set_lit_area)
- Color space: linear color is written to the scene render target. (ToonRenderer::set_hdr_output(true), ToonScreenOutline::set_hdr_output(true), ToonVfx colors are also treated as linear)
  Games that wrote gamma-encoded color g to the float target and converted back with g^2.2 in compositing should convert those values to linear beforehand. Colors become c^2.2, and a brightness multiplier k applied on the gamma side becomes linear k^2.2.
  (e.g. 1.37 is linear 2, 1.6 is 2.81, 2.08 is 5, brightness 1.6 with multiplier 1.6 gives (1.6 x 1.6)^2.2 = 7.9) Bloom threshold and knee are linear brightness.
- Devices that cannot use float targets: even with use_float_color (default true), if is_float_color_supported is false, RGBA8 targets are built. (get_use_float_color is false)
  That case and use_float_color: false take the LDR path. The scene is drawn in screen color (gamma-encoded color, ToonRenderer::set_hdr_output(false)), and compositing adds bloom without tone mapping and gamma and applies only color grading.
- Canvas antialias: because this post process draws into its own MSAA target (sample_count), a game that uses it builds with EngineConfiguration::antialias set to false.
  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;
- Bloom: default is a half-resolution 9-tap Gaussian (BloomEffect, threshold 0.9 ~ 1.6, ping-pong targets RGBA8, RGBA16F with set_bloom_float_color).
  Giving set_bloom_levels(gl, level count, threshold, knee) a level count of 1 or more switches to MultiLevelBloomEffect (halves down then scales up with a tent filter while adding, targets at the same precision as the scene). 0 restores the default. Strength is applied to both by set_bloom.
- Tone mapping is the ACES approximation (Narkowicz). Exposure (set_exposure) is multiplied in before mapping, then sRGB gamma is applied.
- Color grading: after gamma, applies in order brightness (set_brightness, toward 1 inside the lit area set_lit_area), saturation, color tone (multiplies a color normalized to brightness 1), fog light (pulls dark areas toward that color), contrast, edge darkening. (set_color_grade, set_vignette)
  Defaults are brightness 1, saturation 1, contrast 1, color tone 0, fog light 0, edge 0, so there is no grading.
- Resolution scale: with set_resolution_scale(gl, scale), the scene target is built at output size x scale and scaled up to end's viewport (linear filtering) for output. (to render only 3D at a lower resolution while leaving UI at device pixels, default 1)
- Outputting inside a node rectangle: resize(rectangle width, height) → begin → draw (leave ToonRenderer's screen rectangle cleared) → end(None, [x, drawing buffer height - y - height, width, height]).
- Differences from the original: settings that rebuild GL objects (set_sample_count, set_resolution_scale, set_bloom_levels, set_bloom_float_color) take gl and return a Result.
- [graphics3d/toon/toonrenderer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/toonrenderer&lang=en): Toon renderer. (ToonRenderer of vanilla.js graphics3d/toon/toonrenderer.js)
- Draws models from MeshBuilder arrays or read_glb_arrays with single-color material and outline.
- Light: holds one ToonLightSet as the default. Sun (direction and color, shadow), ambient light of sky color and ground color, fill light, point lights and spotlights (up to TOON_MAXIMUM_POINT_LIGHTS), rim light, highlight, light model (÷π).
  Cel shading is a shade ramp. (Base, 1st shade, 2nd shade with Step and Feather of the Unity Toon Shader, shadows enter as the shade color, boundaries without stairs by fwidth, a ramp texture also works)
  The sun receives the whole ramp color, while the fill light, point lights and spotlights receive the ramp's brightness level. Highlight and rim range from the hard toon form to the soft form. The math is in the toonlightset.rs header.
  set_light, set_sun_direction, set_fill_light, set_shade, set_shade_ramp, clear_shade_ramp, set_band_count, set_band_ramp, set_ramp_texture, set_rim_light, set_specular, set_point_lights,
  set_point_light_limit, set_light_model modify the default set. A different set (create_light_set) can be given per draw via the light_set of ToonDrawOptions.
- Normals: transformed by the transpose of the inverse of the upper left 3x3 of the model matrix and the joint matrix. (Light stays correct on stretched and squashed models, the same goes for matrices changed by the vertex chunk)
- Material: vertex color (sRGB), glow (multiplied by the base color and added), unlit. If vertex UVs (arrays.uv_data, 2 each) exist, textures are sampled.
- Draw options (ToonDrawOptions, defaults give the same image as before):
  tint_color [r, g, b, a] sRGB and alpha. If tint_amount is given (0 ~ 1), the tint is mixed in sRGB instead of multiplied. (hit flash, malfunction red)
  glow_scale multiplier of vertex glow (default 1), color_scale multiplier of the final linear color (default 1, darkens a mirrored image), emissive_color [r, g, b] sRGB and emissive_intensity (linear multiplier, default 1, color default black).
  base_color_texture (multiplied into base color, alpha into opacity), emissive_texture (multiplied into glow color), uv_transform [u offset, v offset, u scale, v scale] (offset, scale of KHR_texture_transform).
  decal_texture overlays the base color by alpha (color = texture x decal_color). Glows in that color by decal_emission. decal_uv_transform is for picking one cell of an atlas.
  alpha_cutoff discards pixels whose opacity is below it. (0 disables, glTF MASK)
  blend_mode: ToonBlendMode::Alpha (default, straight alpha), Premultiplied (premultiplied alpha), Additive (additive). Anything other than Alpha is drawn as transparent.
  soft_edge multiplies opacity by pow(|dot(N, V)|, soft_edge) to fade the edges. (0 disables, Fresnel style)
  is_mirrored draws with the winding flipped. If None, it flips by itself when the determinant of the model matrix is negative. If the view matrix is mirrored, that flip is added too.
  index_start, index_count draw only that span of the body vertex indices. (0 means to the end, GLB material ranges, hidden parts) outline_index_start, outline_index_count are for the outline shell.
  material (ToonMaterial), textures ([(uniform name, texture)]), on_before_draw(program, gl, ToonProgramKind) are extension points. (toonmaterial.rs header)
  light_set (ToonLightSet) is the light set of that draw. group, is_depth_prepassed are read only by ToonDrawQueue.
  If receives_shadow (default true) is false, the sun's shadow is not looked up. shade_offset is added to the received light amount to move the shade boundary. (Vertex color threshold of Guilty Gear Xrd, Shading Grade Map form of the Unity Toon Shader)
  specular_scale, rim_scale (default 1) are the highlight and rim multipliers of that draw. (0 means none, strength per material)
  matcap_texture is a matcap read with the view-space normal. matcap_strength (default 1), matcap_blend (ToonMatcapBlend::Multiply default, Add)
  outline_color [r, g, b, a] sRGB is the shell outline color of that draw (set_outline_color if None), outline_width_scale (default 1) is the multiplier of the built thickness.
  outline_offset_z (default 0) is the world length the shell is pushed away from the camera. (So it does not show in front of the body, Offset Z of the Unity Toon Shader)
  angel_ring_texture is the angel ring texture. u is the x of the view-space normal, v is the y of the second UV mixed with the y of the view normal by angel_ring_offset_v (default 0.3). (Angel Ring of the Unity Toon Shader)
  angel_ring_color [r, g, b] (linear multiplier, default white), angel_ring_offset_u (0 ~ 0.5, default 0), is_angel_ring_alpha (default false adds, true covers with the texture alpha)
  The angel ring UV is rotated back by the camera roll. (read_camera_roll, Camera Rolling Stabilizer of the Unity Toon Shader, the ring stays on the head even when the camera is tilted)
  line_id, has_screen_outline, has_crease_line are values ToonDrawQueue passes to the screen-space outline. (The renderer does not read them)
- Outline shell (inverted hull): uploads the base position and push direction (built thickness, the averaged normal of the same position) of the shell MeshBuilder built, and the shader pushes it by outline_width_scale and draws only back faces.
  If set_outline_distance_scale(reference distance, minimum scale, maximum scale) is given, distance to the camera / reference distance is multiplied into the thickness to keep the screen thickness. (Perspective only)
  If set_outline_fade_distance(near distance, far distance) is given, the thickness goes to 0 as the distance from the model position to the camera approaches the far distance. (smoothstep, Nearest and Farthest Distance of the Unity Toon Shader)
  The shell color is multiplied by the sun color when the outline light color usage of the light set is on (default). (Divided by its intensity when the intensity is 1 or more, same as the Unity Toon Shader outline)
- Skeleton: the joint matrices computed by write_skin_pose are passed to draw_mesh. (Up to TOON_MAXIMUM_JOINTS, 96 like the engine's SkinnedModelRenderer)
- GPU instancing: draw_mesh_instanced draws many copies of the same model at once with a matrix and tint per instance. (both body and outline, culled and uploaded on every draw)
  For long-lived instances, build a persistent buffer with create_instance_layout and create_instance_buffer and draw with draw_mesh_instance_buffer. (culls the whole buffer by its bounds, the material vertex snippet reads user attributes)
  When changing, use update_instance_buffer (whole) or update_instance_buffer_range (part, bufferSubData). The body, the outline shell, the shadow and the screen-space outline board share the same GPU buffer.
- Off-screen culling: tests the model's bounding sphere against the view-projection frustum and skips drawing if outside. (instances are culled one by one and only the rest are uploaded)
- Shadows: cast into the engine ShadowMap with begin_shadow_pass and draw_mesh, received with set_shadow. (3x3 PCF, the bias is the texel-unit value of ShadowMap::set_bias multiplied by the texel size and slope)
  Point light and spotlight shadows are cast into a ShadowAtlas with begin_shadow_atlas_pass and, per tile, set_shadow_atlas_tile and draw_mesh, and received with set_local_shadows. (A point light uses six cube tiles, a spotlight one perspective tile)
  The shadow is multiplied into that light's received amount and goes into the shade ramp. (Same form as the sun) Only point lights with casts_shadow true get tiles. (Up to SHADOW_ATLAS_MAXIMUM_LIGHTS)
  Even when shadows are not received, a 1x1 comparison depth texture is bound to both shadow units. (Without a depth texture on a sampler2DShadow unit the Mac driver reports it, and if a color texture is bound WebGL refuses to draw)
- HDR: set_hdr_output(true) outputs linear color without gamma. Draw into a float render target (ToonPostProcess) and finish with bloom and tone mapping.
- Usage: create_mesh(gl, arrays) → every frame begin_frame(gl, view and projection) → draw_mesh / draw_mesh_instanced → end_frame(gl) → delete_mesh when done.
  begin_frame records the previous draw state (blending, depth, face culling, program, vertex array) and enables depth testing and face culling, and end_frame restores the recorded state.
  (When inserting between engine 2D draws, flush the Graphic batch before it)
  begin_frame_with_matrices(gl, view, projection) starts with two matrices. (orthographic or raw matrix camera) The camera position and view rotation (highlight, rim, soft edge, matcap) are read from the view and projection.
- Per program, frame values (view and projection, camera, shadow, HDR) and the light set are uploaded only when they change. Only per-draw values (model matrix, tint, textures) are uploaded every time.
- read_program_sources gives the default sources to hand to ShaderWarmer, and read_material_program_sources(material, instance layout, ambient occlusion, color space) gives the sources of that program. (the original has one function with optional arguments)
- Drawing inside a node rectangle: given set_screen_rect(x, y, width, height), begin_frame moves the view-projection clip space into that rectangle and scissors out the rest.
  The rectangle is in pixels within the viewport at begin_frame time (usually the whole drawing buffer), with the origin at the top left. Off-screen culling uses the frustum before the move. end_frame releases the scissor.
- begin_frame_with_camera(Camera3D) calls begin_frame with the camera's view and projection. It uses the same camera as the 2D display (Camera3D::project_to_view).
- draw_mesh_outline draws only the outline shell. (when ToonDrawQueue draws all outlines together after drawing every opaque body, draws are not counted)
- casts_shadow of ToonDrawOptions is read only by ToonDrawQueue::draw_shadows. If is_body_drawn is false, only the outline is drawn. (The original attaches them by name to the options object)
- Textures: built with create_texture(gl, width, height, RGBA bytes, ToonTextureOptions). UV (0, 0) is the top left of the image. (Same as glTF)
- Color space: set by ToonRendererOptions::color_space of new_with_options (default is the engine's EngineConfiguration::color_space, Gamma without an engine) and does not change. (get_color_space)
  Gamma (default): passed colors and color textures are sRGB; base color, tint and decal are multiplied and mixed in sRGB and then converted to linear with pow(color, 2.2) to compute light. pow(1 / 2.2) is applied for the screen.
  Linear: color textures are uploaded in an sRGB format so the GPU decodes them to linear, and passed colors are converted to linear with the standard sRGB curve before they are multiplied and mixed. The same curve converts back to sRGB for the screen.
  Every shader source gets #define VANILLA_COLOR_SPACE_LINEAR 1. (ToonPostProcess and ToonScreenOutline are built with the same value too)
- Texture units: point light shadow atlas 0, ramp 1, matcap 2, sun shadow 3, base color 4, emission 5, decal 6, angel ring 7, material 8 ~ 15, ambient occlusion 16. begin_frame records the binding of unit 0 and end_frame restores it.
  A texture already bound to a unit is not bound again, and the chosen unit is not set back to 0 after every draw. (end_frame restores the chosen unit; stage callbacks and on_before_draw are called with unit 0 chosen)
- Ambient occlusion: while set_ambient_occlusion_texture(the result of ToonPostProcess::draw_ambient_occlusion, direct lighting strength) is set, bodies are drawn with the body program that defines TOON_AMBIENT_OCCLUSION.
  (The origin and the direct lighting strength go in the ambientOcclusionOrigin and ambientOcclusionDirectLightingStrength slots of the ToonFrame frame block, same as the original)
- Second UV: if the arrays have uv1_data, vertexUv is four values (UV, second UV). Shader chunks read it as ToonSurface.uv1. ((0, 1) if none)
- Light color usage (set_light_color_usage), shade-side rim (set_shade_rim_light) and light intensity limit (set_light_intensity_limited) live in the light set (ToonLightSet).
- [graphics3d/toon/toondrawqueue](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/toondrawqueue&lang=en): Toon draw queue. (ToonDrawQueue of vanilla.js graphics3d/toon/toondrawqueue.js)
- Holds the models to draw in a frame, then draws them in order with ToonRenderer.
- Order: (line target of the screen-space outline) → stage BeforeOpaque → opaque bodies → AfterOpaque → outline shells of opaque things → screen-space outline → AfterOutline
  → transparent things (farthest from the camera first, depth not written) → AfterTransparent.
  Outlines are drawn together after all bodies to switch programs less, and transparent things are blended last from the farthest so what is behind shows through.
- Transparent things: those whose options alpha or tint_color alpha is below 1, or whose blend_mode is not Alpha. Their outlines are drawn with them too (has_outline).
- Groups: transparent things with the same options group are sorted as one lump by the middle depth (average of the members) and drawn in the order they were added.
  If even one member of a group has is_depth_prepassed, that lump draws depth first and then paints color only on pixels with the same depth (LEQUAL).
  A hologram made of several overlapping parts shows through as one lump instead of being doubly bright. Lumps are drawn farthest first so they show through each other.
- Screen-space outline: if set_screen_outline(ToonScreenOutline) is given, draw draws opaque things into the line target before the bodies and blends it after the outline shells.
  The ID is the options line_id (the order added + 1 if None, for instances the line_id of ToonInstance, for instance buffers the instanceLineId slot of the layout comes first), and per model has_screen_outline and has_crease_line turn it off and on.
  Transparent things are not drawn into the line target. If there is a screen rectangle (ToonRenderer::set_screen_rect), that rectangle is used as the drawing area of the line target.
  The Rust version borrows the outline as &'a mut and keeps it in a RefCell. (Modified in draw(&self))
- Ambient occlusion: give set_post_process(ToonPostProcess) and turn on set_ambient_occlusion in the post process, and it is computed after the line target and before bodies, set on the renderer and cleared after end_frame. (without outlines, only the line target is drawn, with no lines)
- Stage callbacks: callback(gl, renderer) of add_pass(stage, callback) is called at that point. After the call, the renderer sets the frame's draw state again.
- Instance batches (add_mesh_instanced) draw body and outline at once if opaque, and if transparent are sorted as one lump by the center of the instance positions.
  It uploads every time it culls and draws per instance. (the body, the shadow and the line board upload the same array separately) For long-lived instances, share a buffer uploaded once with add_mesh_instance_buffer.
- An instance buffer (add_mesh_instance_buffer) is in the style of Unity Graphics.RenderMeshInstanced with GraphicsBuffer and Godot MultiMesh. It culls the whole buffer by its bounds and does not upload again.
- Shadows: draw_shadows(gl, renderer, shadow_map) draws only opaque things whose casts_shadow is true into the shadow depth. Call it before draw.
  For point light and spotlight shadows, draw_local_shadows(gl, renderer, shadow_atlas) draws the same things per atlas tile. (Set on the renderer with set_local_shadows)
  Follows the shadow target's set_update_mode(ShadowUpdateMode). The default OnChange does not redraw when the lights and casters are unchanged, bakes casters that stay unchanged for a long time, and draws only the moving ones over them. (The screen is the same as drawing every frame)
- Use: every frame clear() → add_mesh / add_mesh_instanced / add_mesh_instance_buffer / add_pass → (draw_shadows) → draw(gl, renderer, camera) or draw_with_matrices(gl, renderer, view matrix, projection matrix)
  draw calls renderer.begin_frame_with_camera and end_frame by itself. draw_with_matrices calls begin_frame_with_matrices. (Orthographic or raw matrix camera)
  The screen rectangle (ToonRenderer::set_screen_rect) is set before that. clear empties all added models and stage callbacks. (The screen-space outline is kept)
- The original holds what is added as object references. The Rust version borrows the models, instance lists and stage callbacks, so the queue has their lifetime 'a. (Build a new one every frame, or add again after clear)
  Stage callbacks are FnMut, so they are kept in a RefCell and called in draw(&self).
- [graphics3d/toon/toonview3d](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/toonview3d&lang=en): Component that draws toon 3D inside the node rectangle. (ToonView3D of vanilla.js graphics3d/toon/toonview3d.js)
- In draw: maps the node's content area (0, 0, content size) with the current transform to a rectangle in drawing buffer pixels (the bounding rectangle if rotated),
  flushes the preceding 2D batch with Graphic::run_external_pass, forgets the cached state and clears depth, then sets the renderer's screen rectangle (set_screen_rect) and calls the draw function.
  When done, releases the screen rectangle and restores the 2D state with restore_render_state. (Both are restored even if the draw function panics)
- The renderer is built on the first draw. On devices that cannot build the shaders, it is not rebuilt and 2D is drawn with the fallback draw function (set_fallback_draw_callback).
  To share one renderer across multiple nodes, pass it in with set_renderer.
- The aspect ratio of the camera (get_camera_mut) is matched to the rectangle's ratio on every draw. 2D markers over 3D points are computed with the same camera's project_to_view.
- Depth clearing: inside a parent Mask's clip there is the Adreno 660 pitfall (Graphic::clear_depth_buffer header). The side that applies the clip
  calls clear_depth_buffer before begin_clip_rect, and this component is set with set_depth_cleared(false).
- Draw function: (renderer, camera, screen rectangle, GL, output). The screen rectangle is the rectangle to draw in the current framebuffer (pixels, top-left origin).
  The output (ToonViewOutput) is the framebuffer bound now (None means the default framebuffer) and the GL viewport inside it ([x, y, width, height], integers, bottom-left origin).
  Usually queue into ToonDrawQueue and call queue.draw(gl, renderer, camera), or draw between begin_frame_with_camera and end_frame.
  When using ToonPostProcess, call renderer.clear_screen_rect(), draw into a float render target, then give end the framebuffer and viewport of the output.
  (That way it lands in the right place regardless of render scale or transparency layers)
- Render scale (set_render_scale, 0.05 ~ 4, default 1): if not 1, only 3D is cleared to transparent and drawn into a target of the content area screen size x scale (depth 24, 4 samples if the default framebuffer
  is multisampled), then stretched on through the 2D drawing path with linear filtering and source-over. (UI stays at device pixels,
  same meaning as Unity URP renderScale and Unreal screen percentage) The target uses its own depth, so continuing the earlier 3D depth with set_depth_cleared(false) only works at scale 1.
  The target is deleted when detached from the node (detach) and when dropped (Drop).
- Differences from the original:
  - The shared renderer is `Rc<RefCell<ToonRenderer>>`. The original shares object references. While drawing, the renderer is borrowed and passed to the draw function.
  - outputFramebuffer, outputViewport of the original screen rectangle object are output_framebuffer, output_viewport of the fifth argument ToonViewOutput.
- [graphics3d/toon/toonscreenoutline](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/toonscreenoutline&lang=en): Toon screen-space outline. (ToonScreenOutline of vanilla.js graphics3d/toon/toonscreenoutline.js)
- It draws normals, line ids and depth into the line buffer, finds lines at the boundaries between direct neighbors, then blends: thin lines look at the surrounding cells directly, thick lines are widened by jump flooding and the coverage is worked out from the distance.
- Line buffer: draws the create_mesh result of ToonRenderer once more with the same matrices and writes the normal (octahedron folded), the line id (14 bits), the shape (whether contour and crease lines are on) and the depth.
- Finding: looks once at every boundary between a pixel and its four direct neighbors. A line stands on the boundary between pixels, not on a pixel. (the same boundary is never drawn twice)
  A contour line is a silhouette touching empty space, a place touching another id, or, even with the same id, a place where the occluding pixel is farther than the depth threshold and error margin from the tangent plane of the occluded pixel (an occluded silhouette).
  A crease line is a place inside the same id where two neighboring normals differ by more than the crease angle. Only the normals one pixel apart are looked at, so no band stands around the silhouette of a round surface or on a slanted surface.
  Depth is compared as a tangent plane distance, so no false lines stand on a floor seen at a slant. The measured error (normal 8-bit angle error x distance between the two positions, one pixel of the crease x sine, one step of 24-bit depth) x the margin is added so far things mean the same, and low parallel steps are caught even when lower than one pixel.
- Thin line (up to a width of about 3.24 pixels): picks the first boundary side per pixel (R8UI, one byte) in the same order as the seed pick, and the blend reads the seeds of the 3 x 3 pixels around in the same order as the last jump flooding step to measure the distance to the nearest one.
  The full-screen passes are one side buffer and one blend. (on mobile tile GPUs the pass count and buffer bandwidth are a fraction of the thick line path)
- Widening (thick line): spreads the distance to the boundary segment by jump flooding. The step count is log2 whatever the width, and contour and crease lines are spread separately so they get separate widths.
- Blend: for each pixel of the drawing area it covers clamp(width / 2 - distance + 0.5, 0, 1) from the distance to the nearest boundary. (soft edges, and shrinking the line buffer does not turn widened lines into dotted lines)
- Per model: if has_screen_outline of ToonLineDrawOptions is false the model draws no line and only hides lines behind it. If has_crease_line is false only the crease line is off.
- Color per id: set_line_color gives each id a line color. (Unreal Custom Stencil style, a touching line takes the color of the front id, ids not in the table and an empty table keep the color of set_color)
- Width: the width of set_width and set_crease is the width of one line. (half on each side of the boundary) The unit is ToonOutlineWidthUnit, never below one pixel.
- Depth: the projection matrix tells orthographic from perspective, and depth is unpacked to view space positions for comparing. (projections that shift clip x, y like a screen rectangle also work)
- Scale: set_resolution_scale shrinks every buffer before the blend (line buffer, mask, seed, widening buffers). (the default 1 is the drawing area as it is, and below 1 a thin line works out one coverage buffer at the line buffer resolution and reads it bilinearly once to blend)
- Use: every frame begin_line_ids(gl, view, projection) → draw_mesh / draw_mesh_instanced → end_line_ids(gl) (works out the seeds and widening) → toon body drawing → draw_outline(gl).
  begin_line_ids notes the viewport of that moment as the drawing area and builds the line buffer to that size. end_line_ids and draw_outline restore the framebuffer, viewport and state.
  Handing it to ToonDrawQueue::set_screen_outline lets the draw queue do this order by itself. (when inserting between engine 2D drawing, flush the Graphic batch before and call restore_render_state after)
- The id per instance is line_id of ToonInstance. (lineId of the original instance object, None means the common id)
- [graphics3d/toon/toonvfx](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/toonvfx&lang=en): Base of toon 3D GPU effects. (ToonVfx of vanilla.js graphics3d/toon/toonvfx.js)
- Texture: a single atlas built in code on the first draw, without image files. The left half is a 16-cell smoke flipbook, the right half is ToonVfxSlot cells and eight rows of color ramps.
  Ramp colors are decided by the game. (set_ramps, each row is colors going from a white core to dark, an effect's ramp is the row number, -1 means color only without a ramp)
- Particles: GPU particles drawn with instancing. Written to the buffer once when emitted, and position, size and color are computed by the vertex shader from age. (Drag, gravity, stopping on the floor, streaks stretched along velocity, color ramps)
  When the cap (set_particle_capacity) is exceeded, the oldest emitted are overwritten first, and set_count_ratio multiplies the emitted count by a fraction. (Phones and the lite path)
- Effect meshes: fireballs (add_fireball), shockwave rings and floor glow (add_shockwave), floor decals (add_decal, queue_decal), smoke plumes (add_plume),
  solid-of-revolution beams (queue_beam), ribbons spread toward the camera (queue_ribbon) and lightning made by winding them down (queue_lightning), lightning that re-bends during its lifetime (add_lightning), and point glints at a spot (queue_glint).
- Rim: the rim of glow particles, the glow and rim of ribbons, and the rim of fireballs and shockwaves cover the edges with the rim color (set_rim_color) so they are visible on bright backgrounds too. (Default is additive light only)
- Brightness gain: set_look_gain(look, gain) multiplies brightness per look of particles and glints. (Default 1, for making flame streaks, light rays and embers several times brighter in linear in the HDR version)
- Age and key: emit_particles, add_fireball, add_shockwave, add_decal, add_plume, add_lightning, add_flash take the options age (seconds already elapsed, negative delays by that much) and
  key (event key, not emitted again if already emitted, forgotten by clear). Even if the scene re-emits events from state every frame they appear only once, and effects shown late start from that age.
  Shake (add_shake) uses Shaker's exponential decay (9 per second), so passing strength x exp(-9 x age) for a late-shown event gives the same result.
- Foot shadow: queue_blob_shadow is a round shade decal for that frame (ToonVfxDecalMode::Shade).
- Screen: the flash (add_flash) covers the current viewport (inside the scissor if one is set) with its color at the end of draw and then fades.
  Camera shake (add_shake) is computed with the engine Shaker, and the game adds the offset given by read_shake to the camera's right and up.
- Which effect to emit for which event with what values (the recipe) is up to the game. The engine only takes parameters.
- Floor: if the game reports the floor height with set_floor_height_reader, decals, shockwaves and smoke plumes are placed at that height, and is_grounded particles stop at that height. (0 if none)
- Clock: update(seconds) advances this base's clock. Items passed with queue are drawn once in that frame and then cleared.
- Drawing: call draw(gl, view, projection) after drawing the toon models. Depth test on, depth write off, blends with premultiplied alpha. Records the previous state (including program and vertex array) and restores it.
- Differences from the original: instead of an options object per effect, takes structs with default values (ToonParticleOptions and so on). Values that can be ranges are ToonVfxRange.
  Values that may be omitted in the original (undefined) are Option. The life and age of add_lightning are in ToonLightningOptions too.
  The original takes a number or string as the event key, but the Rust version takes u64. (The game converts string keys to numbers)
- [graphics3d/toon/toonlightset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/toonlightset&lang=en): Toon light set. (ToonLightSet of vanilla.js graphics3d/toon/toonlightset.js)
- Holds as one bundle the lights ToonRenderer uses to shade bodies and the toon light response. The renderer holds one default set, and the renderer's light settings such as set_light change that set.
  Another set can be given per draw with light_set of ToonDrawOptions. (When the shade color differs per material)
- Sun (key light): the direction (sun_direction) is the way the light travels. It is the opposite of the direction from the surface toward the sun. ([0, -1, 0] when shining down from above) It receives shadows.
- Ambient light: sky color and ground color are mixed by the up and down of the normal (N.y x 0.5 + 0.5). (Hemisphere light)
- Shade ramp (cel shading): the received light amount x is laid against the ramp to pick the color. x is dot(N, L) x 0.5 + 0.5 for half Lambert, otherwise max(dot(N, L), 0),
  and after adding the draw's shade_offset, for the sun it is multiplied by the shadow (received amount 0 ~ 1). (Shadows enter as the shade color rather than black, System Shadows of the Unity Toon Shader)
  The ramp has a position, color (linear multiplier) and softness per cell (stop). The color of cell i transitions from the previous cell's color as x rises from (position - softness) to the position. (Step and Feather of the Unity Toon Shader)
  If the softness is smaller than one pixel width (fwidth), it is held at that width so the boundary does not stair-step.
  set_shade builds the ramp from three, base, 1st shade and 2nd shade, set_shade_ramp from cells directly, set_band_count from even cells, set_band_ramp from gray cells.
  If set_ramp_texture is given, the horizontal of that texture (x as u, v is 0.5) is read instead of cells. Without cells (clear_shade_ramp, set_band_count(0)) it is smooth Lambert.
- Per light: the sun receives the whole ramp color so the shade also takes on the sun's color. The fill light, point lights and spotlights receive the ramp's brightness level (bottom cell 0, top cell 1) and do not light faces turned away.
- Fill light (fill): a second directional light that receives no shadow. The direction means the same as the sun. With the default color 0 there is none.
- Highlight (specular): Blinn-Phong pow(max(dot(N, H), 0), exponent), from a hard spot cut at 0.5 (softness 0) to the plain soft light (softness 1). Color x strength x light color x received light level.
  It appears for the sun, point lights and spotlights alike. With the default strength 0 there is none.
- Rim light (rim): pow(1 - max(dot(N, V), 0), power), from a hard rim cut at 0.5 (softness 0) to a soft rim (1). If light_mask is 1, only on the side receiving the sun. Added regardless of the base color.
  The shade-side rim (set_shade_rim_light) adds the same rim on the side facing away from the sun by (rim - (dot(N, L) x 0.5 + 0.5)). (Antipodean (Ap) Rim Light of the Unity Toon Shader)
- Light color usage (set_light_color_usage): chooses per color whether the light color is multiplied. When off, the base, shade and highlight receive only the light's intensity (0.299 R + 0.587 G + 0.114 B), and the rim, matcap, angel ring and outline receive no light. (Is_LightColor_* of the Unity Toon Shader, all on by default)
- Light intensity limit (set_light_intensity_limited): limits what each light gives to 1. The sun and fill light are clamped to 1 per channel, and point lights and spotlights are divided by the intensity of their color with attenuation applied when it exceeds 1.
  (Limit Light Intensity of the Unity Toon Shader, on by default) Turn it off to use strong lights for HDR bloom.
  When porting an old game shader (one that did not limit light intensity), or when using point lights above intensity 1 or HDR bloom, use set_light_intensity_limited(false).
- Point lights and spotlights: up to TOON_MAXIMUM_POINT_LIGHTS. (ToonPointLight)
  Attenuation is window x distance attenuation. The window is (1 - (distance / range)^range_exponent) clamped to 0 ~ 1 and squared if range is above 0, and 1 if 0. Distance attenuation is 1 / max(distance^decay, 0.01) if decay is above 0, and 1 if 0.
  Lights with casts_shadow true get shadow tiles from ShadowAtlas::update_lights(read_shadow_light_sources()). (Six cube faces for a point light, one perspective tile for a spotlight)
  With direction (the way the light travels) it is a spotlight. Angular attenuation is the square of clamp(cos angle x scale + offset, 0, 1) in the glTF KHR_lights_punctual form.
  The received amount is the wrap (dot(N, L) + wrap) / (1 + wrap). (0 is Lambert, the wrap lighting of GPU Gems 1)
- Light model: if set_light_model(ToonLightModel { is_energy_normalized }) is true, base color x light is divided by π and the highlight is multiplied by (exponent + 8) / 8π.
- All colors are linear colors. (they may exceed 1 for HDR) The ramp texture is treated as sRGB and read converted to linear. (by the shader with pow 2.2 in the gamma color space, by the GPU as an sRGB texture in the linear color space)
- Each change raises the version number (get_version). The renderer does not upload again if the set ID (get_id) and version number are the same.
- [graphics3d/toon/toonmaterial](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/toon/toonmaterial&lang=en): Toon material and instance layout. (vanilla.js graphics3d/toon/toonmaterial.js)
- ToonMaterial: shader chunks inserted into ToonRenderer's body shader, the per-game extension point.
  Only patterns and effects that the engine's standard features (textures, light, tint, blending) cannot do go into chunks. Slots without a chunk get the engine's empty functions.
  - uniform_chunk: goes into the top slot of the fragment shader. Write uniforms, constants, functions and the ins exported by the vertex chunk.
  - surface_chunk: defines void applySurface(inout ToonSurface surface). The engine calls it after computing the vertex color, textures and decal, before tint and light.
    ToonSurface { vec3 baseColor (sRGB in the gamma color space, linear in the linear color space; convert sRGB colors with toSurfaceColor before mixing them in), float alpha, vec3 emission (linear), vec3 normal (world, unit), float glow (vertex glow), bool isUnlit,
                  vec4 detail (vertex pattern number and pattern color), vec2 uv, vec2 uv1 (second UV, (0, 1) if none), vec3 localPosition (model coordinates), vec3 worldPosition, vec3 viewDirection (from the surface toward the camera, unit),
                float shadeOffset (value added to the received light amount, moves the shade boundary), float specularMask (highlight multiplier), float rimMask (rim light multiplier) }
  - light_chunk: defines void applyLight(ToonSurface surface, inout ToonLighting lighting). The engine calls it after gathering the sun, ambient light, fill, point lights and spotlights, highlight and rim, before combining.
    ToonLighting { vec3 irradiance (light multiplied into the base color, after the shade ramp), vec3 specular (highlight to add), vec3 rim (rim light to add), float shadow (0 ~ 1), float sunLevel (brightness level of the received sun 0 ~ 1) }
  Combining is base color x irradiance + specular x specularMask + rim x rimMask + glow.
  - vertex_chunk: goes into the top slot of the vertex shaders (all three: body, outline, shadow depth) and defines void applyVertex(inout ToonVertex vertex). Called before moving into world space.
    ToonVertex { vec3 localPosition, vec3 localNormal, vec3 color, vec2 material, vec4 detail, vec2 uv, vec2 uv1, vec4 tint, vec4 emissive, mat4 modelMatrix }
    User attributes of the instance layout (ToonInstanceLayout) are read as ins of that name. Since it goes into all three, do not use outs that exist only in the body. (Use the fields of vertex instead of vertex attribute names)
    Normals are moved by mat3(modelMatrix). If the scale is not uniform, divide localNormal by the square of that scale beforehand.
  - The shader has the engine's toLinear(vec3) (sRGB to linear: pow 2.2 in the gamma color space, the standard sRGB curve in the linear color space), toSurfaceColor(vec3) (sRGB into the space of baseColor) and RECIPROCAL_PI.
    In the linear color space (ColorSpace::Linear), the source has #define VANILLA_COLOR_SPACE_LINEAR 1 and the color textures the engine binds are decoded to linear by the GPU. (is_color_data in ToonTextureOptions)
  - Textures are passed with the draw's textures ([(uniform name, texture)]). The engine binds them in order to units it does not use (from 8, up to TOON_MAXIMUM_MATERIAL_TEXTURES) and puts the unit into the sampler2D uniform of that name.
  - Uniforms that differ per draw are written in on_before_draw(program, gl, ToonProgramKind). The engine rewrites its own uniforms, so write only the material's.
- ToonInstanceLayout: the attribute order of one instance. (used by ToonRenderer::create_instance_buffer and draw_mesh_instance_buffer)
  Each attribute is (name, size). The engine reads instanceMatrix (16) as the model matrix and instanceTint (4) as the multiplied color.
  instanceMatrix is read as an affine 3x4, and the four values of its bottom row (elements 3, 7, 11, 15) are the emission of that instance (sRGB r, g, b and linear intensity, vertex.emissive). Storing Matrix4 elements as they are gives no emission.
  instanceLineId (1) is the per-instance line id of the screen-space outline. (ToonScreenOutline::draw_mesh_instance_buffer, ToonDrawQueue::add_mesh_instance_buffer)
  It uses the last user attribute location (TOON_INSTANCE_LINE_ID_LOCATION), so with it one fewer user attribute fits. A vertex chunk can read it by that name too.
  Other names are user attributes. Up to TOON_MAXIMUM_INSTANCE_ATTRIBUTES, size 1 ~ 4. The vertex chunk reads them as ins of that name. (locations from 13)
  Without instanceMatrix the model matrix is the identity matrix. The vertex chunk builds vertex.modelMatrix. Without instanceTint the tint is 1.
- The original builds a material from an options object ({ uniformChunk, ... }). The Rust version passes ToonMaterialChunks.
- [graphics3d/camera3d](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/camera3d&lang=en): 3D camera. (Camera3D of vanilla.js graphics3d/camera3d.js)
- Holds a perspective or orthographic projection and the view position, and recomputes the view and projection matrices only when they change.
- Coordinates are right-handed with y up, the same as the engine Matrix4. The camera looks toward -Z. (create_look_at, create_perspective)
- Perspective: set_perspective(field of view, near distance, far distance), orthographic: set_orthographic(visible height, near distance, far distance).
  The aspect ratio is given separately with set_aspect_ratio. (update it whenever the drawing rectangle changes, the orthographic width is height x ratio)
- Matrices are kept in Cell and recomputed when read through &self if a value changed. (the original getters check #isMatrixDirty and compute)
- The renderer (ToonRenderer::begin_frame_with_camera) and 2D display (project_to_view) share the same camera to place text or buttons over 3D points.
- project_to_view(x, y, z, view_rect): a world point to a position inside view_rect. view_rect is the rectangle where 3D is drawn, given in the caller's coordinates (usually view coordinates).
  The original { x, y, depth, isInFront } is returned as ProjectedPoint.
- unproject_to_plane(view_position, plane_height, view_rect): the point where the line of sight from a position inside view_rect meets the horizontal plane (y = plane_height). None if there is none.
- Raw matrices: set_matrices(view, projection) uses matrices computed by the game as is. (such as a tilted orthographic, or a projection multiplied by a screen transform) All the functions above then work with those matrices.
  The view matrix is given as a rigid transform from world to camera (the camera looks toward -Z). The eye, target (1 in front of the eye), up and is_orthographic are extracted from that matrix.
  The field of view, visible height, near distance, far distance and aspect ratio stay as last given. Calling set_perspective, set_orthographic or look_at drops the raw matrices and returns to the computed path.
- View offset: set_view_offset(position, rotation) applies an offset in camera local axes last. (such as CameraShake shakes, walk bobbing and recoil, on both the computed path and raw matrices)
  The view matrix and the matrices after it, project_to_view and unproject_to_plane run with the offset camera. get_eye_position, get_target_position and get_up_direction are the values before the offset.
- [graphics3d/camerashake](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/camerashake&lang=en): 3D camera shake. (CameraShake and createOffsetViewMatrix of vanilla.js graphics3d/camerashake.js)
- An engine shake in the shape of Unity Cinemachine Impulse and Unreal Camera Shake. Each shake holds its own signal, strength, frequency, duration, attack and decay for 3 position axes and 3 rotation axes (pitch, yaw, roll).
- Signal: two sine waves with slightly different frequencies are layered per axis. Phases and frequency ratios are drawn from the shake's seed. (same seed and same age give the same values)
- Envelope: 0 while the age is negative (starts that much later), rises from 0 to 1 over attack seconds, and decays as (1 - age / duration) to the power decay_exponent, reaching 0 at the duration.
- Overlap: all live shakes are summed. (unlike the 2D Shaker, which follows the stronger one)
- Age: age in CameraShakeOptions is the seconds already passed. The signal is also computed from the age, so an event seen late added with that age continues with the same values as if added from the start.
- Where to apply: pass it to Camera3D::set_view_offset(position, rotation), or apply it with create_offset_view_matrix to a view matrix the game computed.
- The same seed as the original gives the same values. A shake without a seed uses the floor of the base SeededRandom's next value x 2^32 as its seed,
  and draws 12 wave values (two waves per each of six axes, frequency ratio then phase per wave) from that seed's SeededRandom in the same order as the original.
  The sine is the engine sine with the same bits as Chrome Math.sin (the correctly rounded sin in base).
- Differences from the original: the original constructor's { seed } is CameraShake::new(seed), and the options object of add is CameraShakeOptions (Default is the original defaults).
  The original read's { position, rotation } is CameraShakeOffset. The seed is u32 like the original SeededRandom.
- [graphics3d/humanskinrenderer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/humanskinrenderer&lang=en): Human skin renderer. (the original graphics3d/humanskinrenderer.js)
- Builds skin / eye / hair shading templates on top of the SkinnedModelRenderer skinning/morph vertex path.
- Outputs irradiance / albedo / specular / normal split into MRT in linear HDR, and compositing is done by the caller after SubsurfaceScatteringEffect.
- Registers a shading mode per material (set_material_shading). The opaque pass (draw) draws skin / eye / hair cutout,
  and the blend pass (draw_blended) draws hair fringe / occlusion / fluid. (the caller sets the blend state)
- Environment state: 3 lights (0 = key light, receives shadows), 3-color hemisphere ambient, normal, detail, roughness, specular, wrinkle, micro, eye, hair parameters.
- The GLSL is the same as the original. ${WRINKLE_CHANNEL_COUNT} / ${SHADOW_SAMPLE_COUNT} / ${SKIN_SHADING_*} in the original template strings became numbers,
  and ${MORPH_GLSL} became MORPH_GLSL concatenated at construction. (a test checks that the numbers match the constants)
- Texture units: 0 = base_color, 1 = shadow map, 2 ~ 8 = material slots, 9 ~ 14 = extra skin slots, 15 = morph target texture.
- Differences from the original:
  - The original inherits from SkinnedModelRenderer. The Rust version embeds a SkinnedModelRenderer and uses Deref / DerefMut so the base functions
    (draw_wireframe, apply_morph_uniforms, set_sun_direction, get_shader_program ...) can be called as is.
    draw / draw_depth / set_shadow_map / set_shadow_strength, which the original redefines, call this type's functions first.
    It can be passed as is in place of the base renderer, as in SkinnedModel::load_from_bytes(gl, bytes, &human_skin_renderer). (Deref coercion)
  - The draw functions take gl and &mut SkinnedModel like the base renderer, and upload changed morph targets first.
  - The material shading mode table is keyed by material instance (Rc pointer), like the original `Map<Material, number>`.
  - set_ambient_colors / set_hair_parameters take fixed-length arrays instead of the original arrays. set_shadow_sample_count takes an integer and
    clamps it to 1 ~ 24 without the original Math.floor.
  - set_shadow_map copies the 16 matrix values like the base renderer. Construction returns shader compile failures as an error (Result).
- [graphics3d/multilevelbloomeffect](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/graphics3d/multilevelbloomeffect&lang=en): Multi-level bloom effect. (the original graphics3d/multilevelbloomeffect.js)
- Extracts the bright part at half size, blurs it while halving the size, then adds it back to the level above while doubling the size. The first level (half the scene size) is the result. (get_result_texture)
- Extraction: from the average of four source samples, the part whose brightness (the largest of the three channels) exceeds the threshold. Within the knee width around the threshold it comes in smoothly. (set_threshold(threshold, knee))
- Downsampling is a dual filter mixing the center four and the four corners (one diagonal step), and upsampling is a nine-tap tent. The shaders match the original character for character.
- With use_float_color the targets are RGBA16F, so bright values above 1 are blurred as they are. (for HDR scenes, with RGBA8 they are clipped at 1)
- Usage: resize(gl, scene width, height) → render(gl, scene texture) → get_result_texture() is multiplied by the strength and added in the composite pass.
- Side effects: disables the depth test and blending, makes TEXTURE0 active, and changes the framebuffer binding. The blend function is restored to the previous one.
- [misc](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc&lang=en): Miscellaneous tools. (original src/misc)
- Not ported: uibuilder (empty file).
- [misc/beepplayer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/beepplayer&lang=en): Procedural beep player.
- The original misc/beepplayer.js. Synthesizes UI sound effects without audio files.
  An attack / sustain / release envelope avoids clicks.
- Provides click / confirm / cancel / error / success / warning / notification presets and
  arbitrary tone sequence playback (play_sequence).
- Usage:
  ```text
    let beep_player = BeepPlayer::new(&engine.get_audio_manager(), BeepPlayer::DEFAULT_VOLUME);
    beep_player.play_preset("confirm");
  ```
- Where the sound is made:
  Web: like the original, creates an OscillatorNode + GainNode and connects them straight to the audio context output.
  Desktop: builds the same graph in the mixer (OscillatorNode → GainNode AudioParam automation → output, computed the same way as Chrome). (platform/audio/oscillator.rs, mixer.rs)
- Differences from the original:
  Waveform names are BeepWaveform instead of strings, and sequence tones are BeepTone. Preset names are strings like the original.
- [misc/camera2d](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/camera2d&lang=en): 2D camera.
- A port of the original misc/camera2d.js. Gathers following, world bounds clamping, drag panning, cursor-anchored zoom, inertia, and movement tweens in one place.
- position is the world coordinate the camera looks at (screen center), zoom is the magnification, and rotation is the angle (degrees) around the screen center.
  The world rotates on screen by rotation. (same direction as the original deprecated/camera.js begin applying rotate after scale)
- Unlike the original, it is a plain value, not a component. The owner (a scene, etc.) calls tick and applies apply_transform before drawing the world.
- Usage:
  ```text
    camera.set_view_size(view_size);                    // every frame or on resize
    camera.follow(&[hero_position], 6.0, time_delta);  // follow (optional)
    camera.tick(time_delta);
    camera.begin(graphic); ...render world... camera.end(graphic);   // push_state + apply_transform / pop_state
  ```
- Differences from the original:
  Following the no-abbreviation naming rule, minZoom / maxZoom are written as minimum_zoom / maximum_zoom. (set_zoom_range means the same)
  The default tween_to duration of 0.4 seconds is passed as the DEFAULT_TWEEN_DURATION constant. (Rust has no default arguments)
- [misc/cameragestures](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/cameragestures&lang=en): Camera gestures. (CameraGestures of vanilla.js misc/cameragestures.js)
- Gestures that rotate, pan, and zoom a 3D board or a map. Uses input outside the engine's touch (left button, first finger).
  - Dragging with the right mouse button held: rotates by the horizontal drag (the canvas width is one full turn) and tilts by the vertical drag. Releasing without dragging is a right click.
  - Dragging with the middle mouse button held: pans.
  - Two fingers: dragging in the same direction pans, pinching in and out zooms around the midpoint of the two fingers, and twisting past the twist threshold rotates. (prevents slowly rotating while pinch zooming)
    As in the original, the gesture continues until every finger is lifted. When only one finger remains its movement is ignored, and when the finger count changes that spot becomes the new reference.
- The engine handles the wheel. This only records whether Ctrl was held. (is_last_wheel_ctrl, laptop touchpad pinches also arrive as Ctrl wheel)
- Also reads whether the last input was a finger (is_touch_input, initially whether the device's primary input is touch). Within the time that emulated mouse events are ignored after a finger is lifted (fourth argument of set_thresholds, initially 800 milliseconds),
  mouse moves and presses do not switch the input, and right or middle buttons pressed then do not start a gesture until released.
- The original listens to the canvas DOM events directly (hence addListener, dispose). The Rust version reads the input manager (mouse buttons, finger list, wheel Ctrl) with update every frame.
  The web platform passes the buttons and positions of emulated mouse events without filtering, like the original engine.js (only the last device is filtered for 800 milliseconds), so the fourth argument threshold works whether it is shorter or longer than 800, as in the original.
  It measures by frame time instead of event time. (the frame that had the finger event and the frame that read the mouse button)
- During a gesture it reports is_gesture_active so presses and releases passed by the engine are not used for gameplay.
- The accumulated amounts (pan, rotation, tilt, zoom) are taken out every frame with take. Pan is in view units, rotation and tilt in radians, and zoom is a ratio to multiply by.
- [misc/collision2d](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/collision2d&lang=en): 2D collision utility.
- A port of the original misc/collision2d.js. Gathers checks that were rebuilt in every action game, like circle-circle overlap separation (pushing apart) and finding the nearest within a radius.
- All functions are static.
- Differences from the original:
  resolve_circle_overlap returns None instead of null, and CircleOverlapPush instead of { push_a, push_b }.
  find_nearest_in_radius returns a reference to the target, and find_nearest_index_in_radius, which returns an index for modifying, is added.
  The is_static_b default (false) is always passed because Rust has no default arguments.
- [misc/devtools](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/devtools&lang=en): Developer tools. (DEVTools of the original misc/devtools.js)
- Shown and hidden with the F2 key. The panel appears docked at the bottom right in the window's inner logical coordinates (canvas native), regardless of the view scale mode.
- Four tabs: Statistics (engine, screen and time info), Node Hierarchy (tree on the left + inspector on the right), Local Storage (view, add, edit and remove keys and values),
  Settings (dim background, all gizmos, aspect ratio guide, FPS display. Saved to the local storage "hierarchy.settings" as the same JSON as the original)
- Drag the title bar to move, drag the edges and corners to resize, and drag the center divider to change the left and right ratio.
- Tree: expand and collapse, active (A) and gizmo (G) columns, selection, drag to scroll. Inspector: click a component header to expand and collapse its properties. (expanded by default)
- In the Rust version the scene holds DevTools and calls it in each function:
    dev_tools.tick(engine, node_tree, unscaled_time_delta) in tick, dev_tools.draw(engine, node_tree, graphic) in post_draw.
    If is_visible() && is_pointer_inside_panel(engine), the scene does not pass that input to the nodes. (original GameScene.isDevToolsCapturingInput)
- Differences from the original:
  - There is no original setEngine. (there is only one engine, so there is no separate engine to give) tick, draw and is_pointer_inside_panel take the engine.
  - Nodes are referred to by NodeId. The root list is set_root_nodes(`Vec<NodeId>`), expanded nodes are a set of NodeId, and collapsed components are a set of (NodeId, component index).
    Removed nodes drop out of the tree and the inspector, and if the selected node is removed it goes back to nothing selected.
  - setForceGizmosVisible, which the original calls in tick and on presses: press handling and set_visible take only &Engine and cannot change Graphic, so they record the desired value
    and tick applies it to the engine's graphic (get_graphic_mut) at its end. So, as in the original, it shows from that frame's drawing. (set_visible called outside tick is applied at the start of draw)
    The false applied by the original setEngine is applied on the first tick. (DevTools::new does not take the engine)
  - The only node type is WorldNode, so the tree's Type column and the inspector's type are the node type name from the held UIDocument (UIDocument::get_node_type_name). (in place of the original constructor.name: engine node types such as FloatingText registered in the initial document and types the game registered, otherwise "WorldNode")
  - The inspector's component properties call and show all get* and is* getters of the component, like the original getComponentProperties.
    The original scans prototypes at run time, and the Rust version uses the list built at compile time by the `#[reflect]` macro. (core/reflection.rs, attached to all engine components)
    Getters that take the tree (the original holds neighbor components directly) are called with the tree passed in drawing, and for components with &mut self getters, tick holds the tree and the values read there are shown.
    Names follow the original formatMethodName (getTextColor → textColor, kept as is if it starts with is), and values follow the original formatPropertyValue form.
    (numbers toFixed(2), Vector2 as (x, y), Rect as (x, y, width, height) toFixed(1), Color as rgba, null, nodes as `[WorldNode]`, arrays as `[Array]`, others as [type name])
    The list and order are the same as the original. (redefinitions in the Rust version not in the original class are left out, and getters named differently from the original are shown with the original name) The original getEngine is left out. (in the original it is the value given with setEngine, while the Rust UIView::get_engine is a function that takes the global engine)
  - Like the original, every component is reflected. Reflect is a supertrait of Component, so a game component without `#[reflect]` does not compile.
    Node type names (for values that point at nodes) are the names registered in the UIDocument. A document where the game registered its own types is set with set_ui_document. (or registered through get_ui_document_mut)
  - Key input, value editing and the remove confirmation in the Local Storage tab use the engine question dialogs Engine::prompt and Engine::confirm in both engines. (the original engine.prompt, engine.confirm) (core/modaldialog.rs)
    The question dialog drawn by the engine appears, the scene pauses until it is answered, and the answer is received on the next tick. (the same on the web and the desktop)
  - clientNativeSize in Statistics is ViewManager::get_client_native_size (the whole page size on the web, the window's inner logical size on desktop).
    Memory reads Chrome's performance.memory on the web like the original, and is "(N/A)" in browsers without it.
    The desktop has no JavaScript heap, so the same fields show values with the same meaning read through operating system APIs. In use and reserved are the heap of the system allocator Rust uses,
    and jsHeapSizeLimit is the upper bound the operating system allows for this process's heap. (platform/desktop.rs read_heap_usage, read_heap_size_limit)
    In both engines each field that cannot be obtained is "(N/A)". (All three if the heap cannot be read)
    viewScaleMode is written with the Rust enum name (StretchHeight and so on).
  - The aspect ratio guide does not rely on the coordinate system at the time like the original, but applies the view coordinate system (apply_view_rect) itself and draws. (same result as in the original GameScene)
- Turning on Show FPS in Settings draws the frame count of the last second at the top left of the window even when the panel is closed. (same as the original, canvas native coordinates, over the panel if the panel is visible)
- Not ported: none. (the try/catch ignoring draw errors, which nobody calls in the original, is not needed in Rust)
- [misc/dialogue](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/dialogue&lang=en): Dialogue runner and script parser.
- A port of the original misc/dialogue.js. (DialogueRunner, DialogueScriptParser)
- DialogueRunner: steps through a script made of lines, choices, labels, and jumps in order. The state machine that visual novels / RPG dialogues / tutorials each built on their own.
  ```text
    runner.set_script(entries); runner.start(None);
    runner.get_current()   → DialogueCurrent::Line / choice / finished
    runner.advance() on a line, runner.choose(index) on a choice.
  ```
- DialogueScriptParser: turns one-line command text into a script.
  ```text
    /label label_name
    /jump label_name
    /speaker speaker_name              (default speaker for the following /say)
    /say line text
    /option option text -> label_name       (consecutive /option lines are grouped into one choice)
    /end
  ```
  Lines not starting with "/" are treated as /say of the preceding speaker. "//" is a comment.
- Differences from the original:
  Script entries are the DialogueEntry enum instead of objects with several fields. One entry cannot be both a label and a line.
  get_current returns the DialogueCurrent enum instead of a { kind, ... } object, and a choice's options are a list of option texts (`Vec<String>`).
- [misc/floatingtext](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/floatingtext&lang=en): Floating text manager component. (damage numbers / +coins, etc.)
- A port of the original misc/floatingtext.js. Text spawned with spawn rises and fades out, and finished label nodes are reused.
- Create one node under the scene root and spawn in world coordinates.
- Usage:
  ```text
    let floating_text_id = FloatingText::create(node_tree, root_id);
    FloatingText::spawn(node_tree, floating_text_id, "-120", position, FloatingTextOptions { color: Color::create(1.0, 0.4, 0.4, 1.0), ..FloatingTextOptions::default() });
  ```
- Differences from the original:
  The original is a node that inherits WorldNode. The Rust version is a component attached to a node, and create makes the node and attaches it.
  spawn / clear are associated functions that take the tree and a node handle because they must create and change label nodes. (they do nothing if the component is missing)
  The options object is the FloatingTextOptions struct.
- [misc/focusnavigator](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/focusnavigator&lang=en): Directional focus navigator.
- A port of the original misc/focusnavigator.js. When moving between UI items with the gamepad d-pad / keyboard arrows,
  moves the focus to the item with the closest "distance ahead in the movement direction, penalized by how far it strays off the axis". (the standard approach for console UI navigation)
- Items are registered as (id, rect). A pure coordinate algorithm independent of how things are drawn.
- Differences from the original:
  id is String, and null is None. The options object is the FocusNavigatorOptions struct.
- [misc/frameprobe](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/frameprobe&lang=en): Detects slow devices. (FrameProbe of vanilla.js misc/frameprobe.js)
- Measures the frame intervals of the first few seconds, used to automatically turn on a light path that disables heavy effects.
- After the wait seconds from the start of measuring have passed, looks at each frame's interval during the measure seconds. (the first few seconds stutter while models and images load)
- If the share of frames exceeding the slow factor times the target interval (one tick of the maximum frame rate, or one tick of 60 frames if unlimited) is at least the slow share, it is a slow device.
  - Why 1.4 times instead of one tick: a 90 Hz screen at a maximum of 60 has the engine drawing every other frame, always 22 ms apart, and that is not the device being slow.
  - On 60 Hz and 120 Hz screens, frames that missed one refresh (33 ms, 25 ms) are counted as slow. One in four means below 48 fps.
- Once decided as a slow device, it does not measure again. If the window is hidden before measuring is done, restart measures again from the beginning.
  If not slow, measure_again can measure once more in a heavy scene.
- Does not import the engine. The caller passes the frame interval and the maximum frame rate.
- [misc/grid](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/grid&lang=en): Grid utility.
- A port of the original misc/grid.js. Gathers things rebuilt in every grid game, like connectivity checks (flood fill) and tile collision checks.
- Whether a cell is passable is decided by the is_passable_handler(column, row) callback. All functions are static.
- Differences from the original:
  The original { column, row } object is returned as GridCell, and the { x, y } of to_world_center as Vector2.
  Cell indexes are i32 so negative cells (outside the top left of the world) can be represented.
  Coordinates and cell math are f64 like the original (JS number). (the 0.000001 subtraction in test_rect_overlap matches the original)
- [misc/imagescroller](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/imagescroller&lang=en): Image scroller.
- A port of the original misc/imagescroller.js. Tiles one image inside the visible area (view_rect) and draws it flowing at the set speed. (infinite background)
- Like the original, it is a plain value, not a component. The owner calls tick and draw.
- Differences from the original:
  The image is `Rc<Image>`. The ImageAsset taken by the original setImage is passed with set_image_asset.
  get_scroll_position / get_scroll_speed return values, not mutable references like the original. (tick adds to them directly inside)
- [misc/indicator](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/indicator&lang=en): Indicator. (a spinning gear-shaped loading indicator)
- A port of the original misc/indicator.js. It is a plain object, not a node, so the owner calls tick and draw.
  Draws 8 teeth extending outward from the center and a thick inner ring, rotating.
- As in the original, line ends are square. set_color takes a Color or a string ("#ffffff", etc., Color's `From<&str>`).
  build_teeth_segments, get_radius, get_rotation also exist in the original.
- [misc/localization](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/localization&lang=en): Localization.
- A port of the original misc/localization.js. Gathers automatic language detection, translation tables, {0}{1} placeholder substitution, and fallback in one place.
- Keys can be the source text as is. If a key is not in the table, the source text (the key) is returned as is, so you can translate bit by bit.
- Usage:
  ```text
    Localization::set_table("en", [("Confirm", "OK"), ("{0} points earned", "Got {0} points")]);
    Localization::set_language(&Localization::detect_language(&["ko", "en"], "ko"));
    Localization::text("{0} points earned", &[&120]);
  ```
- Differences from the original:
  The original holds the tables in static fields of the class. The Rust version holds them in thread-local global state. (the engine runs on one thread)
  A table value is one string or a list of strings (LocalizationValue). A JSON table (read with JsonAsset) is put in with set_table_from_json.
  The variadic arguments of text are a list of Display references (&[&dyn Display]).
- Brought into the engine from Exoplanet Miner: matching language tags by dropping trailing parts one by one, and aliases (set_language_aliases),
  right-to-left languages (is_right_to_left, set_right_to_left) and wrapping inserted values in directional isolate characters (isolate_text),
  filling named placeholders (text_named, "{seconds}" style, values joined only by slashes are wrapped once as a whole).
  Layout mirroring (mirror_layout_x, read_layout_text_align, mirrorLayoutX, readLayoutTextAlign of the original LanguagePack).
  On the web detect_language reads navigator.languages as in the original, and on desktop it reads the system's preferred language order with sys-locale.
    (Windows GetUserPreferredUILanguages, Mac CFLocaleCopyPreferredLanguages, Linux LANGUAGE / LC_ALL / LC_MESSAGES / LANG environment variables)
- [misc/localstorage](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/localstorage&lang=en): Local storage.
- A port of the original misc/localstorage.js. A set of static functions that persistently store string values under string keys.
- Where it is stored:
  Web (wasm32): window.localStorage as in the original. (separate per origin, keys used as is)
  Desktop: a single localstorage.json in the app folder. (a JSON object of key → string value, saved immediately on every write)
    Windows   %APPDATA%\{app name}\localstorage.json
    Mac       $HOME/Library/Application Support/{app name}/localstorage.json
    Linux     $XDG_DATA_HOME/{app name}/localstorage.json (if missing, $HOME/.local/share/{app name}/...)
    If the environment variables cannot be read, it goes under the temp folder (std::env::temp_dir).
  The app name defaults to the executable name. Change it with set_application_name or set_application_name_from_engine(EngineConfiguration.title).
  The folder can also be set directly with set_storage_directory. (tests, portable games)
- Differences from the original:
  Numbers are f64 like the original (JS number). Conversion to text is exactly the original String(number). (shortest notation, exponents like 1e+21 for 1e21 and above and 1e-7 and below, NaN, Infinity, -0 → "0")
    Reading is exactly the original Number(text). (trims JS whitespace, empty text is 0, 0x, 0o, 0b notation, "1.", ".5", exponents, Infinity, anything else is NaN)
  Desktop storage is held per thread and then written to the file. (the engine runs on one thread)
- Swapping the storage: passing a LocalStorageBackend to set_backend uses it instead of the default storage above. (such as a platform SDK's storage)
  The trait takes the place of the original setBackend object ({ getItem, setItem, removeItem, getKeys, clear }). Exceptions in the original are reported as Err.
  The passed storage is put in `Rc<RefCell>`. get_backend returns that Rc, and the caller borrows it with borrow / borrow_mut.
- Does not crash when blocked: if there is no storage (a blocked localStorage on the web) or writing fails (full, folder cannot be created, Err from the swapped storage),
  values are kept in memory instead for as long as this run lives. (is_memory_fallback, gone after a restart)
- Reads (get_string, get_boolean, get_number, get_json) do not write the default value for missing keys. (same as the original)
- Unpaired surrogates: the original localStorage holds JS strings (UTF-16), so it stores values containing unpaired surrogates (such as cut emoji) and
  JSON that writes them as \ud83d. Rust String cannot hold such text, so they appear as the replacement character (U+FFFD) on the Rust side,
  and writing a read value back unmodified (set_item, set_string, set_json) writes the original UTF-16 units as they were. (misc/storagetext.rs)
  If the original units are needed, get_item_code_units and set_item_code_units read and write the JS string as is.
  Keys are the same. Two keys that differ only by unpaired surrogates (different keys in the original) look like the same text as Rust strings but are stored separately in the storage.
  get_keys_code_units returns all keys in their original units, and get_item_by_key_code_units, set_item_by_key_code_units,
  remove_item_by_key_code_units and contains_key_code_units distinguish both key and value by original units. (exactly the original localStorage functions)
  A Rust string key points to the key with exactly that text if it exists, otherwise to the first unpaired surrogate key that appears as that text. (keys received from get_keys can be used)
  The web writes JS strings as is to the browser localStorage, and the desktop file writes such values and keys as \udXXX like the original JSON.stringify.
  A swapped storage (LocalStorageBackend) exchanges Rust strings, so values are exactly the text that storage holds. (keys are also given as the displayed text)
- [misc/storagetext](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/storagetext&lang=en): The engine's JSON text writing and preservation of unpaired surrogates in stored text. (used by every engine path that writes JSON; the surrogate table is used by LocalStorage and PersistedStore)
- The original localStorage and JSON are JS strings (UTF-16), so they hold unpaired surrogates (U+D800 ~ U+DFFF that lost their pair).
  They come from user input such as cut emoji, and JSON.stringify writes them as escapes like \ud83d. (the well-formed JSON.stringify of ES2019)
- Rust String is UTF-8 and cannot hold such text. So they appear as the replacement character (U+FFFD) on the Rust side,
  and unmodified text is written back in its original UTF-16 units. Values saved by the original version are not lost when the Rust version reads and rewrites them.
- PreservedText: the original UTF-16 units and the text as displayed with replacement characters.
- parse_json, parse_json_code_units: read like JSON.parse but read unpaired surrogates (both escapes and raw units) as the replacement character,
  and record the places (JSON paths) where such text was and the original units in a JsonSurrogateTable. Numbers are the same as what serde_json reads.
- stringify_json, stringify_json_with_space: write text identical to the original JSON.stringify down to the character (used by every engine path that writes JSON), but if text displayed with replacement characters is still at a place in the table, it writes the original units,
  and even at another place, if the text is the same (same as moving text over in the original), it writes the original units as \udXXX like JSON.stringify.
  If two or more texts look the same with replacement characters but have different original units, only those at matching places are written in the original units.
- [misc/nodelayout](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/nodelayout&lang=en): Node layout.
- A port of the original misc/nodelayout.js. A fluent builder that lays out node hierarchies declaratively without local variables.
- Positions and sizes are set with number pairs (x, y) without Vector2.
- Usage:
  ```text
    let panel_id = NodeLayout::create()
        .pivot(Pivot::MIDDLE_CENTER)
        .content_size(680.0, 900.0)
        .component_with(Paint::new(), |paint| { paint.set_color(Color::create(0.1, 0.1, 0.1, 1.0)); })
        .children([
            NodeLayout::create()
                .content_size(120.0, 70.0)
                .component_with(Text::new(), |text| { text.set_text("OK"); }),
        ])
        .build(node_tree, Some(parent_id));
  ```
- Differences from the original:
  In the Rust version nodes live only inside the tree (NodeTree), so the builder collects settings in order and, at build(node_tree, parent_id), creates the nodes and applies them in that order.
  So components are also attached with node_tree.add_component at build. (components whose attach_to_tree creates child nodes work too)
  There is no node class, so it is create() instead of create(nodeClass).
  component(type, callback) is split into component(value) and component_with(value, callback). (Rust has no optional arguments)
  The variadic arguments of children(...layouts) are taken as one array or Vec.
  Like the original, anchored_position is applied at build after attaching to the parent, relative to the anchor point of the parent content_size. (the anchor is the one at the time the setting is applied, a local_position set later wins)
  Like the original, mask_enabled(false) removes all Masks of that node, not only the first mask.
- [misc/pathfinder](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/pathfinder&lang=en): Grid pathfinding. (A*)
- A port of the original misc/pathfinder.js. 4-directional movement, Manhattan distance heuristic, and a binary min heap managing the open list.
- A cell is blocked if is_blocked_handler(column, row) is true.
- The result is the list of cells up to the goal cell, excluding the start cell. None if there is no path.
- Differences from the original:
  { column, row } is GridCell, and null is None.
  The heap is ported as is from the original code, so when several paths have the same cost it picks the same path as the original. (the standard BinaryHeap picks in a different order)
- [misc/persistedstore](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/persistedstore&lang=en): Persistent store.
- A port of the original misc/persistedstore.js. Saves a state object as JSON under one key and notifies subscribers when it changes.
- If the version number (version) differs or parsing fails, it falls back to the defaults.
- Saving uses LocalStorage. The save format ({"version":1,"state":{...}}) is the same as the original, so on the web it reads the original game's saves as is.
  set_storage_backend can put only this store somewhere else (LocalStorageBackend, such as a platform's storage).
  The passed storage is put in `Rc<RefCell>`. get_storage_backend returns that Rc, and the caller borrows it with borrow / borrow_mut.
  (reading or writing this store while it is borrowed gives empty text for reads, and writes report it and move on)
- Usage:
  ```text
    let mut store = PersistedStore::new("game.settings", serde_json::json!({ "volume": 0.8, "is_muted": false }), 1);
    store.set(serde_json::json!({ "volume": 0.5 }));
    let volume = store.get()["volume"].as_f64();
  ```
- Merging is the same as the original Object.assign. Arrays are merged by index keys ("0", "1" ...) (even if the saved state is an array), and the key order puts index-like keys first from the smallest number, like JS objects.
- Differences from the original:
  The state object is serde_json::Value (an object). Values that are neither objects nor arrays are treated as an empty object. (the original Object.assign merges a string by character index keys)
  subscribe returns a subscription number (PersistedStoreSubscription) instead of an unsubscribe function, and unsubscribe(number) removes it.
  Rust String cannot hold unpaired surrogates, so such text saved by the original (like \ud83d from JSON.stringify) appears as the replacement character (U+FFFD) in the state from get.
  The original JS code units of that text are read with get_string_code_units and written with set_string_code_units. (the same form as LocalStorage *_code_units, the same value as the original string)
  Their places are remembered when reading, and writing back unmodified writes \udXXX like the original. (misc/storagetext.rs, saves from the original version are not lost when read and rewritten)
- [misc/platformerbody](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/platformerbody&lang=en): Platformer physics component.
- A port of the original misc/platformerbody.js. Holds the minimal physics (kinematics) that side-scrolling games kept rebuilding,
  like gravity integration, ground contact, and horizontal movement bounds. Moves the node's local position directly. (down is +Y)
- Usage:
  ```text
    let body = node_tree[hero_id].add_component(PlatformerBody::new());
    body.set_ground_y(560.0);
    body.set_horizontal_bounds(Some(40.0), Some(920.0));
    // move: body.set_velocity_x(±speed), jump: body.jump(-720.0)
  ```
- Differences from the original:
  null bounds are None. The landing notification is an FnMut() callback.
- [misc/pointergesture](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/pointergesture&lang=en): Pointer gesture recognizer. (without nodes)
- A port of the original misc/pointergesture.js. Splits tap / drag / long press by thresholds. It is not tied to nodes, so it can be used anywhere.
- Usage: pass press(x, y), move(x, y), tick(time_delta), release() in that order,
  and receive the results through callbacks (set_tap_event / set_drag_event / set_drag_end_event / set_long_press_event).
- Differences from the original:
  Movement is move_pointer in both engines. (original movePointer; the reserved word move is not used as a name)
  The options object is a PointerGestureOptions struct. Callbacks are FnMut taking a Vector2.
- [misc/shaker](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/shaker&lang=en): Shake generator. (shared by screen / nodes)
- A port of the original misc/shaker.js. Makes x / y offsets from two sine waves with different phases and lets them die down with exponential decay.
- Add strength with add_shake(strength), and every frame after tick(time_delta), add get_offset() to a camera or node position.
- Differences from the original:
  The constructor's options object ({ decay_rate, frequency }) is the ShakerOptions struct. Omitted values are filled with ..ShakerOptions::default().
  ```text
    let shaker = Shaker::new(ShakerOptions { decay_rate: 10.0, ..ShakerOptions::default() });
  ```
- [misc/spriteanimator](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/spriteanimator&lang=en): Sprite animator component.
- A port of the original misc/spriteanimator.js. Register named clips (frame sequences) and switch with play("run").
- Playing the same clip again does not restart it. (can be changed with restart_if_same)
- When a clip ends, the on_complete callback continues to the next state. (used together with an FSM)
- Puts the current frame (image + area) into the Sprite component of the same node. Remembers it once found, like the original findSprite. (find_sprite)
- Usage:
  ```text
    let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
    animator.add_clip("idle", image.clone(), &idleRects, 10.0, true);
    animator.add_clip("attack", image.clone(), &attackRects, 12.0, false);
    SpriteAnimator::play(&mut node_tree[hero_id], "attack", SpriteAnimatorPlayOptions::create_with_on_complete(|animator| {
        animator.play_clip("idle", SpriteAnimatorPlayOptions::default());
    }));
  ```
- play puts the first frame into the Sprite right away, as in the original. A Rust component does not point to its own node (the NodeTree holds nodes), so it takes the node.
    SpriteAnimator::play(&mut node, "run", options)
  With only the animator and no node (inside the complete callback), use play_clip. After the complete callback the frame goes in during the same tick, so it changes right away as in the original.
- Differences from the original:
  on_complete is a one-shot callback that receives the animator (FnOnce(&mut SpriteAnimator)). In the original, the closure captured the animator.
  fps is not abbreviated, so it is frame_per_second. The defaults (10, looping) are passed as DEFAULT_FRAME_PER_SECOND and true.
  Atlas JSON is taken as serde_json::Value.
  The original findSprite holds the Sprite it found. A Rust component cannot hold a reference to a sibling component (a borrow cannot live past tick), so it remembers the NodeId of the node holding the Sprite,
    and SpriteAnimator::find_sprite(&mut node_tree, node) takes it out of that node. From outside, a Sprite can also be passed to apply_current_frame(sprite).
- [misc/steering2d](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/steering2d&lang=en): 2D steering utility.
- A port of the original misc/steering2d.js. Gathers frequently rebuilt steering calculations, like combat AI movement that "approaches when far, and keeps distance while circling left and right when within range",
  into pure functions. The return value is the desired velocity vector.
- Differences from the original:
  The strafe_rate default (1.7) of orbit_at_range is passed as the DEFAULT_STRAFE_RATE constant because Rust has no default arguments.
- [misc/toucheffect](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/toucheffect&lang=en): Touch effect component.
- A port of the original misc/toucheffect.js. Scatters sky blue light particles at the press point that fade and spread over 0.4 seconds.
- Particles draw a white radial gradient image (64x64, made only once) tinted sky blue (rgb 100, 200, 255) with additive (lighter) blending.
- Usage:
  ```text
    let touch_effect_id = node_tree.create_child(root_id, "TouchEffect");
    node_tree[touch_effect_id].set_pivot(Pivot::TOP_LEFT);
    node_tree[touch_effect_id].add_component(TouchEffect::new());
    // on press: node_tree[touch_effect_id].get_component_mut::<TouchEffect>().unwrap().create_touch_particle(x, y);
  ```
- Differences from the original:
  The original is a node that inherits WorldNode, and the Rust version is a component attached to a node. As in the original, the blend is switched to additive in push_transform
  and restored to the previous blend in pop_transform, so children are drawn additively too. (the component's hooks around the node draw state)
  The gradient is an Image baked with the radial gradient of an offscreen canvas (the engine Canvas2D), like the original.
- [misc/typewriter](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/typewriter&lang=en): Typewriter effect.
- A port of the original misc/typewriter.js. Reveals the text of a target that can set its visible character count, like Text, one character at a time at a set speed per second.
  (visual novel / RPG dialogue presentation)
- Usage:
  ```text
    let mut typewriter = Typewriter::new(TypewriterOptions { characters_per_second: 30.0, ..TypewriterOptions::default() });
    let label = node_tree[label_id].get_component_mut::<Text>().unwrap();
    typewriter.start(label, Some("Hello. The adventure begins."));
    // every frame: typewriter.tick(label, time_delta);
    // on input: next line if finished (typewriter.is_finished()), otherwise typewriter.skip_to_end(label)
  ```
- Differences from the original:
  The original takes the target in the constructor and holds it. The Rust version cannot hold a component inside a node, so
  the target (&mut dyn TypewriterTarget) is passed on every start / tick / skip_to_end. Text implements TypewriterTarget.
  As in the original, characters are counted in grapheme clusters (final consonants, combining marks, and emoji sequences count as one). The character reveal notification receives (grapheme cluster, index).
  The options object is the TypewriterOptions struct.
- [misc/virtualpad](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/virtualpad&lang=en): Virtual pad.
- A port of the original misc/virtualpad.js. Computes and draws the movement of an on-screen joystick's pad (outer circle) and knob (inner circle).
- Unlike the original, it is a plain value, not a component. The owner calls touch_press / touch_move / touch_release and tick, draw.
- While the knob moves, the knob move event reports the direction (a unit vector mapped to 0 ~ 1, 0 ~ 1) and the pull strength (0 ~ 1).
  On release, the knob returns to the pad center at 1600 pixels per second while reporting, and once back reports (0.5, 0.5), 0 once.
- Differences from the original:
  The state name move is a Rust keyword, so it is moved. The original state value strings ("wait", "pressed", "move", "released") are obtained with get_name.
  The event callback is FnMut(Vector2, f64).
- [misc/visual](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/visual&lang=en): Visual component. (Visual of the original misc/visual.js, builds a visual editor document into a node tree at a set location)
- The document is the UIDocument JSON text saved by the visual editor (vanilla.js tools/visualeditor). ({ version, root, frameSize? }, both scenes and prefabs)
  VisualAsset reads the file and makes a Visual holding the document.
- create_node builds a new node tree from the document and sets the root's local position to location. (The caller attaches it to the parent it wants, a new tree on every call)
- It does not draw or update by itself.
- Difference from the original: the original createNode() builds with the global UIDocument, the Rust create_node takes the UIDocument to build with and the node tree.
  (A Rust UIDocument is a value holding the registration tables) Where the original returns null for no document and throws for a malformed one, Rust gives Ok(None) and Err.
- [misc/graphicsqualitygovernor](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/graphicsqualitygovernor&lang=en): Graphics quality decision. (GraphicsQualityGovernor of vanilla.js misc/graphicsqualitygovernor.js)
- Decides whether to use the lite path from settings and frame measurement, and picks the render pixel ratio limit.
- Order of deciding the lite path (is_lite): override (like ?light in the address) → setting low (always lite), high (never) → auto.
  In auto, it is the lite path if lite from the start (set_auto_lite_default, such as touch devices) or when FrameProbe measured a slow device.
- Calling update(frame seconds, max frames) every frame measures with FrameProbe only in auto. Returns true on the frame the lite path changed.
- Render pixel ratio limit: give it with set_render_pixel_ratio_limits(normal, lite path), and apply_render_pixel_ratio(view_manager) applies it only when it changes. (0 means no limit)
- What to reduce on the lite path (shadows, outlines, effects, draw counts) is decided by the game reading is_lite.
- Address: apply_search_text takes query text ("?light", "?a=1&light=0"). Reads it like the original URLSearchParams.
  (strips one leading ?, splits by &, skips empty pieces, splits the name and value at the first =, + is a space, %XX is decoded as bytes and read as UTF-8. If the same name appears several times, the first value)
  apply_page_query reads the query of the page address on the web. Desktop has no page address, so it reads the environment variable `VANILLA_<name>` (upper snake case, light → `VANILLA_LIGHT`).
- [misc/fixedstepper](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/fixedstepper&lang=en): Fixed stepper.
- A port of the original misc/fixedstepper.js. Even when frame intervals are uneven, rules (physics, the board's flow) always run in the same step (step_seconds).
- advance(time_delta, step_function) accumulates the given time and calls step_function(step_seconds) each time a full step is filled.
  The return value is the remaining fraction (0 ~ 1). Blending between the previous and current step by this fraction when drawing keeps the steps from jittering against the screen refresh rate.
- Runs at most maximum_steps_per_frame steps per frame. If time remains after that many, the remaining time is discarded.
  (so a slow device that stalls does not get even slower by running all the backlog at once)
- Difference from the original: the original step function stops only when it returns false and may return nothing. The Rust version always returns bool.
  (true continues, false stops this frame's steps there and keeps the remaining time accumulated)
- [misc/loadingprogress](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/loadingprogress&lang=en): Loading progress. (original misc/loadingprogress.js)
- The shown progress (get_shown_progress) smoothly follows the progress reported by the loading stages (set_progress, 0 ~ 1, never decreasing).
  Even when downloads bunch up and the progress jumps at once, the bar slides instead of jumping.
- Call update(time_delta) every frame. The follow fraction is 1 - exp(-rate * time), so the speed is the same regardless of frame interval.
- [misc/buildinfo](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/buildinfo&lang=en): Build info. (original misc/buildinfo.js)
- Reads the version written by the release build once when the app starts. Reading order:
  1. The content of <meta name="build-version" content="..."> in the document head. (that text as is if present, Document::get_meta_content of platform/document.rs)
     On the web it is the page's meta, as in the original. On desktop it is the meta of the document held by the engine, which the release build puts in EngineConfiguration.document_meta_list.
     (the meta slot of the web version's index.html, something like reading build.rs's rustc-env with env! and putting it in)
  2. Otherwise version.json. In the form { version, date, time, hash, ... }, and the text is "date time (hash)". version if there is no hash.
     On the web, fetches the page-relative address without the cache (fetch's cache: "no-cache"). So the old version display does not linger after uploading a new version.
     On desktop it reads from the asset folder. (finishes on the spot, and as a file it has no cache that keeps the old version)
     If it cannot be fetched (no file, HTTP error, network error), it quietly moves on, just as the original load swallows the error.
     The handle finishes with empty bytes and does not count as a failure, so it is not in the failed list even when added to an AssetLoader.
  3. If neither, the version put in with set_package_version. (the game crate passes env!("CARGO_PKG_VERSION"), an empty string if not set, as in the original)
- Differences from the original:
  The default version.json address argument of the original constructor is split into new() (default address) and set_version_json_path.
  The original await load() waits until it is fetched. The Rust version's load(engine) also returns a BuildInfoLoadHandle that can be awaited. (wait_for_load().await is the same)
  Without await, check completion with is_loaded(), and scenes hand get_load_handle() over to track_load_handle.
- [misc/dynamicfont](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/dynamicfont&lang=en): Dynamic font. (DynamicFont, GlyphInfo of the original misc/dynamicfont.js)
- Bakes the chosen characters in one font and one size into a glyph atlas (one image), and draws text by cutting glyphs out of the atlas.
  Every character uses the same image, so Graphic draws it in one batch. (unlike Text, which bakes a texture per string, batching is not broken)
  Used where characters change often and the same characters are drawn many times, like scores, damage numbers and clocks.
- The atlas lays glyphs out in rows within 1024 pixels wide, with a 2 pixel gap between glyphs. (same as the original)
- Characters are counted in grapheme clusters (Hangul final consonants, combining marks, emoji sequences). Characters not in the atlas leave a gap of half the font size and are skipped. (same as the original)
- Characters are baked in white, and color glyphs (emoji) in their own colors. (the original calls fillText in white and the browser draws emoji in their own colors)
- Differences from the original:
  The original setFontAsset(FontAsset) is set_font_family(registered font name). (pass FontAsset.get_family)
  The original getAtlasCanvas is get_atlas_image (`Rc<Image>`). Desktop bakes glyphs with the font faces of the text cache (shaping, synthetic bold and italic included),
  and a character not covered by any face cannot be baked. (the other characters are baked) The web bakes with the browser Canvas2D like the original.
  build_atlas and draw_text take Graphic. (fonts are in Graphic's text cache)
- [misc/languagepack](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/languagepack&lang=en): Language pack. (LanguagePack of the original misc/languagepack.js, languages for on-screen text kept as asset tables)
- Unlike Localization (tables in code), the text is kept in asset JSON files. Use it for games with many languages where translators edit the files separately.
- Paths are set with set_language_paths. (initially ./assets/localization/languages.json and its folder)
- The language list is languages.json ({ fallbackLanguage, languages: [{ code, name, englishName, fontGroup, direction, aliases, countries, file }] }),
  with one file per language (key → text). If the language setting is empty, it follows the language reported by the platform (set_preferred_language_tag), then the device language,
  and if not in the list, the default language (English). Keys missing from the chosen language's table use the default language's text, and if missing there too, the key as is.
- Loading a language changes the page language (html lang) and title (the key from set_document_title_key, initially game.title) to that language.
  The language is written with Document::set_language. (the html lang on the web, the language of the document held by the engine on desktop. Read with Document::get_language) The title is the window title.
- Differences from the original:
  The original waits with async functions. The Rust version follows the engine's "request → fully loaded later" pattern, so load_language_list, load_language, apply_language_setting
  request the read, and update(engine) must be called every frame to continue. (on desktop it is read on the spot and finishes inside the requesting function) Wait with is_loading.
  load_language_list, load_language, apply_language_setting return a LanguageLoadHandle that can be awaited, as in the original.
  (inside an engine task, scene_context.with(|_, engine| languagepack::load_language(engine, code)).await, and update is called every frame while waiting)
  The original applyLanguageSetting also waits for the Promise returned by the function after loading. A function returning a future is set with set_language_loaded_async_handler,
  and the engine runs that future as an engine task and counts it as loading until it finishes. (awaiting the handle also waits until then)
  The global state is a thread_local on one thread. (original module variables) One language row is the LanguageEntry struct.
  The function to call after loading (set_language_loaded_handler) receives (engine, language row, all text). (original (language, all text), the engine is used for fetching fonts)
- [misc/uifont](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/misc/uifont&lang=en): UI font. (the original misc/uifont.js, all on-screen text, groups font subsets for many scripts under one name)
- Font name, list file and folder, last group, weights and wait time are set with configure_ui_font. (initially GameUI, ./assets/fonts/fonts.json, latin, 500 and 700)
- The lists are fonts.json (index { fonts: [{ group, manifest }] }) and fonts-<group>.json (subsets { faces: [{ file, weight, style, unicodeRange }] }).
- Draws all on-screen languages under one font name. Font files are not merged; a font face is made for each subset and registered with that subset's character range.
  So only the subsets containing characters used on screen are fetched. (Korean, Chinese and Japanese fonts have hundreds of subsets)
  Characters shared by several fonts, such as Han characters, are drawn by the font registered later. The selected language's group is placed right before Latin (second from the end)
  so that Japanese gets Japanese-font Han characters and Traditional Chinese gets Traditional-font ones. Latin is always last, so digits and Latin letters use the Latin font in every language.
- Every subset is registered with only the two weights in configure_ui_font's weights (initially 500, 700). Variable-weight subsets are registered twice (500 and 700), and 400-only subsets as 500.
- Subsets for the text in use are fetched in advance. (load_ui_font_text) When a subset arrives, the engine (EngineConfiguration.rebake_text_on_font_load) discards and rebakes only the text baked with that subset's characters.
  Characters not fetched in advance also get their subset fetched by update when measured or drawn with that font. (in the original, the browser fetches a registered FontFace when drawing characters in its range)
  Before it arrives, it is drawn with another font like the original canvas, and once it arrives it is rebaked (when rebake_text_on_font_load is on).
- At first only the lists for the selected language and Latin are fetched, and the remaining groups are fetched a little after play starts (remaining_delay_milliseconds).
  Initial subsets are waited for only up to wait_milliseconds. (is_ui_font_ready is true once that time passes or everything arrives)
- Differences from the original:
  The original creates FontFaces, adds them to document.fonts and waits with async. The Rust version receives the bytes of the subset files on both desktop and web
  and registers them as faces of the same name in the engine's text cache. (Engine.register_font_face_when_loaded, order by Engine.set_font_face_order)
  So on web too it draws with the engine's shaping, not browser fonts. Receiving only makes requests, and calling update(engine) every frame carries it on.
  load_ui_font returns a UiFontLoadHandle that can be awaited as in the original. (calls update while waiting, and finishes once the initial text is all registered or wait_milliseconds passes)
  load_ui_font_text returns a UiFontTextLoadHandle that finishes once the faces for that text are registered in the font list. (the original await loadUiFontText(text))
  The original readUiFontFace(FontFace) is read_ui_font_face (the registered name, None if it could not be loaded). The options object is the UiFontOptions struct.
- [platform](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform&lang=en): Platform layer.
- Handles the window (or canvas), GL context, input events, frame loop and buffer swapping.
- The engine core (core::engine::EngineRunner) does not know the platform. Each platform exposes the following under the same names.
  run (engine runner), set_cursor_visible, set_cursor (cursor shape), is_coarse_pointer (whether the primary pointer is a finger), set_title, request_asset_bytes (reading asset bytes), PlatformWindow (the window handle the engine holds),
  write_clipboard_text / read_clipboard_text (system clipboard)
  read_page_query_value (a query value of the page URL), read_safe_area_insets (CSS env safe area insets)
  read_canvas_client_position (the top-left of the canvas in screen coordinates), read_client_native_size (the whole page size, None on desktop)
  save_capture_file (saving a screenshot for verification, a file on desktop, a download on the web)
- Only the web exposes is_gl_binding_present (whether something is bound in GL, because glow on the web panics when it reads null). (used by read_*_binding in core::graphic)
- Only macOS exposes vibrate_gamepads / release_disconnected_gamepad_haptics (gamepad vibration, desktop/gamepadhaptics.rs).
- Only desktop exposes desktop::read_heap_usage (heap usage of the system allocator, the memory field of the developer tools). (the web reads performance.memory as in the original)
- Android and iOS add modules here. (not yet)
- [platform/audio](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/audio&lang=en): Audio backend.
- The lower layer AudioManager, AudioPlayer, AudioAsset and BeepPlayer call to make sound. The common code is in core, resource and misc.
- Each backend exposes the following names in the same form.
  AudioContext (the shared context), AudioBuffer (decoded sound), AudioPlatformState (the backend state the manager holds),
  AudioPlayerBackend (the sound-making part of one player), AudioBusBackend (the sound-gathering part of one bus, create_player_backend makes a player that plays into that bus),
  HAS_USER_GESTURE_AT_START,
  create_audio_platform_state, create_audio_context, resume_audio_context, is_audio_context_running,
  load_audio_file, load_audio_bytes (take the load type AudioLoadType), get_audio_buffer_duration, play_beep_tone,
  AudioStream (a sound loaded for streaming, get_duration, get_stream_url), AudioPlayerBackend::start_stream_playback, get_stream_time
  suspend_audio_context (suspending the context), get_audio_context_time (the context clock), AudioPlayerBackend::set_pan (left and right)
- Desktop: the engine mixer on top of cpal output. (desktop.rs, mixer.rs. The node graph and math are the same as Chrome WebAudio) Sound files are decoded by decode/ the same way as Chrome decodeAudioData. (symphonia 0.6, opus-pure for Opus)
  The HRTF of PannerNode (draft, panner.rs) is computed by hrtf/, a port of Chrome's HRTFPanner and the IRCAM data (Composite.flac). (the FFT is the same rustfft as Chrome)
- Web: calls the same WebAudio as the original directly through web-sys. (web.rs)
- Only the two types AudioContext and AudioBuffer are exposed so game code can name them. The rest are used only inside the engine.
- [platform/audio/desktop](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/audio/desktop&lang=en): Desktop audio backend. (Windows, Mac, Linux, the engine mixer on top of cpal output)
- In place of AudioContext: opens the default output device with cpal and runs a mixer at its sample rate (mixer.rs). If there is no device it reports once and does not open again.
  There is no browser autoplay policy, so the user gesture is treated as present from the start. sample_rate(), current_time() have the same names as the web AudioContext.
- The node graph is the same as the original WebAudio and the math matches Chrome. (header comment of mixer.rs)
  One AudioPlayer = source + GainNode (+ StereoPannerNode when a nonzero pan is first set), to that bus if an output (AudioOutputNode) is given, otherwise to the output.
  One AudioBus = a GainNode connected to the output. (AudioGainNode, the original getGainNode) Players made on a bus hold a bus handle,
  so as in the original WebAudio the bus stays alive while connected players exist. The node is removed once all handles are gone.
- Context suspend (SoundSystem calls it while muted): the mixer stops rendering, so the sound and clock stop in place. (the original AudioContext.suspend) resume starts it again.
- The context clock (get_audio_context_time) is the rendered time. (the original currentTime, rises by 128 / sample rate seconds every 128-frame quantum)
- A management thread holds the stream. When the device is removed (or, except on Mac, when the default device changes), it reopens the default device with the same mixer. (the original Chrome also follows the default device)
- In place of AudioBuffer: holds decoded sound in an Arc. Cloning is cheap. decode decodes it the same way as the original Chrome decodeAudioData.
  (Opus and Vorbis in webm, ogg, mp3, wav, flac, AAC in m4a and aac. Trimming of both ends, 44100Hz, downmixed to 1 or 2 channels by the WebAudio speaker rules)
- In place of AudioStream: a sound loaded for streaming. (the original AudioLoadType.streaming, holds only the compressed source (a file path or bytes) and the trim plan)
  When played, a decoder thread per player decodes chunk by chunk into a ring buffer (128 KiB) that the mixer's streaming source reads. (streaming.rs, the samples are the same as the fully decoded buffer)
- Volume, pan and stop change right from the next render quantum. Playback rate applies from the next playback. (same as the original)
- Volume is the AudioParam of the GainNode. Setting the volume is assigning the original gain.value, and SoundSystem sets automation (setValueAtTime calls) and stop(when) as in the original.
  The current gain.value (get_gain_value) is the intrinsic value the sound thread computes every quantum.
- BeepPlayer's tones build OscillatorNode → GainNode (envelope automation) → output on the mixer like the original playTone. (the math matches Chrome, oscillator.rs)
  The waveform's band-limited tables (PeriodicWave) are built once per sample rate, as in the original context.
- [platform/audio/web](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/audio/web&lang=en): Web audio backend. (wasm32, calls WebAudio directly through web-sys)
- Ports the WebAudio calls of the original audiomanager.js, audioplayer.js, audioasset.js, beepplayer.js as they are.
- AudioContext: as in the original, AudioContext, or webkitAudioContext if missing. Created after a user gesture. (create_audio_player creates it even before that)
- resume: calls resume() only when "suspended" or "interrupted" (a nonstandard state of iOS WebKit) and ignores rejection.
  The state is read as a string. (web-sys's AudioContextState has no "interrupted")
- iOS clock check: the original verifyContextClock as is. (2026-10-22 03:41, for the iOS 26.6.2 update)
  If after restoring it is "running" but current_time advances less than 1/4 of real time over 0.5 seconds, calls suspend() then resume() and checks again.
  If that resume() is rejected, restores again with resume_context() after the same interval. Only one runs at a time.
- Decoding: done with OfflineAudioContext(1, 1, 44100) as in the original. If missing, done with a temporary AudioContext which is then closed.
- Context suspend: like the original SoundSystem.applyContextPause, calls suspend() only when "running", and reports and ignores rejection.
- Pan: like the original SoundSystem.playEffect, inserts a StereoPannerNode between the GainNode and the output if nonzero. (not inserted if createStereoPanner is missing)
- Bus: like the original AudioBus, one GainNode connected to the output. Players made on a bus connect their GainNode to the bus's GainNode instead of the output.
- The player's output (AudioOutputNode): like the outputNode of the original AudioPlayer constructor, takes an AudioNode and connects the player's GainNode to it. (the output if none)
- If the fetch response has a failure status, it counts as a failure before decoding, as in the original.
- Async: promises are awaited with spawn_local and JsFuture of wasm-bindgen-futures. (in place of the original then / await)
  Callbacks hold the manager's or player's state as Weak, and do nothing if it was dropped in the meantime.
- Differences from the original:
  Dropping the player lets the playing source node play to the end, as in the original. A play that was waiting for a resume also starts after the resume. (in the original that callback holds the player)
  onended is replaced with a self-releasing callback (Closure::once_into_js) so a dropped closure is never called, and the GainNodes are disconnected when it ends.
- One player plays one sound. If another source started while waiting for the resume, it stops that one and plays, like the original startPlayback.
- [platform/document](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/document&lang=en): Document. (what the original reads and writes in the browser document: html lang, meta in head)
- The original uses the global document as is. When LanguagePack loads a language it changes document.documentElement.lang,
  and BuildInfo reads the version written by the release build from the content of `meta[name="build-version"]`.
- On web it reads and writes the browser document as in the original.
- Desktop has no HTML document, so the engine holds document values (language, meta list) per thread and does the same work.
  Initial values are document_language and document_meta_list of EngineConfiguration. (where the web version's index.html writes html lang and the meta in head)
  Just as the release build writes the version into the web version's index.html, a desktop game puts values inserted at build time (such as rustc-env of build.rs and env!) into document_meta_list.
- On web too, the engine settings' values are written to the document when the engine is created if they are not empty. (the same game code has the same document on both platforms)
  If empty, on web it stays as the page wrote it.
- [platform/desktop](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/desktop&lang=en): Desktop platform. (Windows, Mac, Linux)
- Creates the window (winit) and a GL 3.3 core context (glutin), and runs one engine frame per window redraw request.
- Converts window events into the input manager's form. (keys use the same names as W3C KeyboardEvent.code, any mouse button is a touch as in the original, can be changed to left only)
- The engine core (EngineRunner) does not know about the window. Frames are called here, and the screen is presented after drawing.
- Text input (key characters, editing keys, IME composition) and the clipboard are handled by desktop/textinput.rs. The right button is a context menu request for input fields.
- Gamepad vibration on Mac is handled by desktop/gamepadhaptics.rs. (GameController and CoreHaptics, on other OSes gilrs vibrates)
- The last used device is recorded on every key, mouse and finger event. Keys to prevent (set_prevented_keys) and blocking the right-click menu are not used, since a window has no browser default actions to block.
  (same result as blocking them in Chrome. On Windows winit does not pass WM_SYSKEYUP of a menuless window to DefWindowProc, so Alt and F10 do not enter the system menu either)
- Page events: the window is occluded (Occluded, reported by Mac and X11), minimized (size 0 or is_minimized, which is how Windows reports it), the app is suspended (suspended, mobile),
  the Wayland frame callback has not come for over 3 seconds (occlusion on Chrome Linux Wayland, desktop/waylandframecallback.rs)
  If any one of these holds, Hidden; once all clear, Visible and on_page_visibility_restored. Focus is Focused / Blurred, mouse button and finger presses are PointerDown.
  Wayland's xdg_toplevel suspended state is held by winit and not reported, so it cannot be received.
- Wayland vertical sync: sets the EGL swap interval to 0 and waits up to 1/20 second for the previous frame callback before presenting. (with interval 1, Mesa stalls inside the swap on an occluded window)
- Canvas size (auto_resize_on_window_resize): the window is like a page whose canvas fills the window. When on, it fits visualViewport (the window minus the bottom covered by the on-screen keyboard) as in the original
  and applies ignore_virtual_keyboard_resize and the canvas aspect ratio limit. When off, it is the window size as is.
- On-screen keyboard: on Windows, like Chrome, focusing a platform input field with a finger shows the touch keyboard (InputPane) and removes the covered area from visualViewport. (desktop/windowsinputpane.rs)
  Mac and Linux do not shrink the viewport, like Chrome.
- Preserving the drawing buffer (preserve_drawing_buffer): captures the finished frame and redraws it at the start of the next frame. (desktop/preserveddrawingbuffer.rs)
- Page process restore (on_page_process_restored, the original resume after a Chromium freeze and bfcache): resumed after suspended, and waking from system sleep.
  Windows subclasses the window to receive PBT_APMRESUMEAUTOMATIC of WM_POWERBROADCAST. (desktop/windowsplatform.rs, the Windows monotonic clock keeps running during sleep so the clock cannot tell)
  Mac and Linux treat it as woken if between two frames the wall clock (SystemTime) advanced more than SYSTEM_SLEEP_GAP_SECONDS beyond the monotonic clock (Instant).
  (Rust Instant is CLOCK_UPTIME_RAW on Mac and CLOCK_MONOTONIC on Linux, so it stops during sleep. Rust notes that it does not guarantee this)
- Whether the primary input is a finger (is_coarse_pointer): Windows ports Chromium's (pointer: coarse) check and is true in tablet mode or on a touch device without a mouse.
  Mac is false, since Chromium always treats it as a mouse too. Linux and other Unixes, like Chromium, read touchscreens and
  mice and touchpads from the display server (Wayland wl_seat capabilities, X11 XInput device list) and are true if there is only a touchscreen. (desktop/linuxplatform.rs, the value read is used for 2 seconds)
- Key names: winit's SuperLeft, SuperRight become W3C's MetaLeft, MetaRight, and winit's Meta becomes W3C's Super.
- Image cursors (PointerCursor.register_image_cursor): reads the image file and makes a winit CustomCursor. On Mac the image size is the point size as is, so the 1x image is used;
  Windows and Linux use physical pixels, so the image and hotspot are scaled to the window scale (using the 2x image if present). While creating, or if creation fails, the CSS cursor given with it is used.
- Render scale upper limit (ViewManager.set_max_render_pixel_ratio): draws at the size reduced to that scale and stretches to the window size at the end of the frame. (desktop/renderscaler.rs)
  Input coordinates are converted to logical coordinates with the window's scale, so they do not depend on the render size.
- Canvas aspect ratio limit (EngineConfiguration.max_canvas_aspect_ratio): if the window is more elongated than that, the canvas (drawing area) is shrunk as in the original and centered in the window, and the rest is black.
  The canvas top-left is subtracted from input coordinates, and read_canvas_client_position returns that position.
- Query values of the page address (read_page_query_value) are read from the environment variable VANILLA_ followed by the name in upper snake case. (safeArea → VANILLA_SAFE_AREA)
- Capture mode (VANILLA_CAPTURE_PATH) runs with the window hidden. A hidden window has no redraw requests or vertical sync, so frames run right away in about_to_wait and pace themselves to the refresh rate.
  Occlusion notifications are not received. On Mac it does not take the Dock icon or focus either. To see the window, VANILLA_CAPTURE_SHOW_WINDOW=1.
- [platform/desktop/textinput](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/desktop/textinput&lang=en): Desktop text input. (winit 0.30 window events → engine text input queue, system clipboard)
- Covers both the role of the DOM <input> (set_use_dominput(true)) of the original UIInputField and that of document keydown (canvas mode).
  - KeyboardInput: editing keys (Backspace, Delete, arrows, Home, End, Enter, Tab), Ctrl/Cmd + A/C/V/X, characters of KeyEvent.text → text input queue.
  - Ime: Preedit becomes composition start / composition text / composition end, and Commit becomes committed text. (the Preedit cursor is a byte position, so it is converted to a character position)
  - Every frame reads the previous frame's field state, and turns IME on and positions the candidate window only when the focused field uses platform input (use_dominput).
    When focus moves to another field, or the field commits the composition text because it was pressed inside during composition, IME is turned off and on to cut the composition.
    (the field has already committed the cut composition text, so the same Commit sent again by the OS is discarded)
- The clipboard is read and written with arboard. (winit has no clipboard. On Linux the content only stays while a Clipboard object is alive, so one is held per thread)
- [platform/desktop/gamepadhaptics](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/desktop/gamepadhaptics&lang=en): Mac gamepad vibration. (macOS only)
- A file not in the original. The original vibrates with the browser's Gamepad.vibrationActuator, and the Rust version on desktop vibrates with gilrs force feedback.
  gilrs's macOS implementation has empty force feedback (is_ff_supported is always false), so only on Mac it vibrates here with Apple GameController and CoreHaptics.
- Builds a CHHapticEngine with GCController.controllers() → controller.haptics (GCDeviceHaptics) → createEngineWithLocality,
  and starts right away a player of a CHHapticPattern made of one continuous event (intensity, sharpness).
  - The heavy motor (strong) goes to the left handle (GCHapticsLocalityLeftHandle) engine, the light motor (weak) to the right handle (GCHapticsLocalityRightHandle) engine.
    A pad that offers neither goes to one GCHapticsLocalityHandles engine, or failing that a GCHapticsLocalityDefault engine, with the larger of the two intensities.
  - Calling again stops the previous vibration and starts a new one. If the intensity or duration is 0 it only stops.
  - One continuous event lasts up to 30 seconds, so longer ones chain 30-second events.
  - Engines are built once per controller and handle position and kept. Engines of controllers gone from the list are dropped.
    If an engine stops for an outside reason (stoppedHandler) or comes back from a server error (resetHandler), it is only marked and restarted on the next vibration.
    If starting or the player fails, the engine is dropped and rebuilt once.
- Pairing gilrs pads with GCControllers: first pairs those with the same name (gilrs's OS name and GCController.vendorName, case-insensitive),
  and pairs the rest by gilrs connection order and the order of GCController.controllers(). (so with one controller it is used even if the names differ)
  GameController does not give the vendor and product IDs through a public API, so they are not matched by ID.
- objc2-game-controller 0.3.2 binds createEngineWithLocality only for iOS, tvOS, visionOS, so on Mac it is called directly with msg_send.
  (Apple's documentation states GCDeviceHaptics is available from macOS 11)
- GameController objects are handled on the main thread. The engine frame (winit event loop) is on the main thread so it calls as is, and skips if called from another thread.
- startWirelessControllerDiscovery is for pairing new wireless pads, so it is not called. Pads already connected are in controllers().
  GCController.shouldMonitorBackgroundEvents is about forwarding input, and gilrs reads the input, so it is left alone.
- [platform/desktop/systemfont](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/desktop/systemfont&lang=en): Desktop system font lookup. (the file for a font name, fallback fonts to draw characters missing from the fonts)
- A file not in the original. In the original the browser finds CSS font names among OS fonts, and draws characters not in the font list with the OS fallback font.
  Chrome finds them with CoreText on Mac, DirectWrite on Windows and fontconfig on Linux. The Rust version on desktop also finds files with the same APIs and registers them in the text cache.
- find_family_font_file: finds the file and face by font name, weight and italic. None if there is no font with that name. (does not substitute another font like CSS)
  - Mac: system-ui, BlinkMacSystemFont are the system UI font (CTFontCreateUIFontForLanguage, the italic trait of CTFontCreateCopyWithSymbolicTraits when italic, MatchSystemUIFont in Chrome's font_matcher_mac.mm),
    others a font descriptor built from the name and weight traits. -apple-system and ui-serif, ui-sans-serif, ui-monospace, ui-rounded are names Chrome does not know, so None.
    (only Safari knows them. In Canvas2D of Chrome 158 on Mac, "16px -apple-system" is drawn with the default font)
  - Windows: system-ui is the menu font like Chrome (lfMenuFont of NONCLIENTMETRICS, Segoe UI if it cannot be read), others the name in the system font collection (FindFamilyName) and GetFirstMatchingFont.
  - Linux: fontconfig's FcFontMatch. Like Chrome (isAcceptableMatch in Skia SkFontConfigInterface_direct.cpp), accepts only if the found font's name equals the requested name or the name after configuration,
    or it is a metric-compatible substitute (a table like Arial and Liberation Sans), or the requested name is sans, serif, monospace.
- Generic names (serif, sans-serif, monospace, cursive, fantasy, math, and -webkit-body as the standard font) are turned into font names by Chrome's default font table before searching. (resolve_generic_family_name)
  A name wrapped in double quotes ("\"monospace\"") is not converted, like Chrome, and the font spelled that way is looked up. (Mac and Windows have no font of that name, Linux fontconfig accepts monospace)
  The table is IDS_*_FONT_FAMILY of Chromium chrome/app/resources/`locale_settings_<os>`.grd and its translations per language (platform_locale_settings/*.xtb).
  Chrome sets the Common (Zyyy) script value by the browser language (UI language), and a canvas without a document lang picks fonts by the script of the default locale (browser language).
  The separately set value for that script is not registered because it is the browser language's script (RegisterProfilePrefs in prefs_tab_helper.cc), so in the end the Common value is used.
  The canvas the original bakes text on is not attached to the document, so changing the document's lang leaves it as is. (checked with Chrome 158 on Mac)
  The Rust version finds the UI language Chrome would pick from the system preferred languages (read_browser_locale) and uses the same table.
  Example: Mac Korean is serif AppleMyungjo, sans-serif Apple SD Gothic Neo, monospace Menlo, English is Times, Helvetica, Menlo. Windows Korean is serif Batang, sans-serif Malgun Gothic.
- find_fallback_font_file: lets the OS pick a fallback font to draw text (one grapheme cluster).
  - Mac: CTFontCreateForString on the system UI font. (the same API as Chrome Mac's font fallback) If color emoji is wanted, checks Apple Color Emoji first.
  - Windows: IDWriteFontFallback.MapCharacters (base name Segoe UI, user language)
  - Linux: the first font with that character from FcFontSort with a charset containing it. If color emoji is wanted, sets the color property.
- The face index of the returned FontFileSource is included when the OS reports it (Windows, Linux), and on Mac the PostScript name is included to find the right face when reading the font.
  The weight of variable fonts (such as SFNS, the Mac system UI font) is made by the text cache from axis values.
- [platform/desktop/coretextglyph](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/desktop/coretextglyph&lang=en): Mac CoreText glyph drawing. (macOS only)
- A file not in the original. The original Chrome on Mac draws glyphs with CoreText (CoreGraphics). On the Mac the Rust version also draws glyphs here with CoreText. (called by textshaping.rs)
  Only this file can draw color emoji and fonts the open parsers cannot read.
  - Color emoji (sbix, Apple Color Emoji): at small text sizes CoreText draws emoji enlarged and lowered. (the 20px version at 16px, the text size as is from 24px)
    The emoji advance measured with measureText of Mac Chrome Canvas2D equals the height of the emoji box CoreText draws. (8px 10, 12px 15, 16px 20, 20px 22, 24px 24, 32px 32, 64px 64)
    Chrome's advance is that box height rounded to an integer. (16.25 at 13px is 16, 12.5 at 10px is 13. Matches Chrome at 23 sizes from 8 ~ 128px, textshaping.rs does the rounding)
    CoreText's advance (CTFontGetAdvancesForGlyphs) adds the font's tracking table (trak) and differs from Chrome, so it is not used.
  - Fonts with glyph outlines in none of glyf, CFF, CFF2: PingFangUI.ttc on Mac 26 (the Chinese fallback font) has its outlines in Apple's private hvgl table.
- The font is built from that face's PostScript name. (CoreText draws emoji enlarged only for fonts registered in the system) For hidden fonts whose name starts with a dot, or when axis values are set,
  it builds from the CTFontManagerCreateFontDescriptorsFromURL descriptors of the file path, chosen by PostScript name (or by order within the collection if none). CTFonts built per text size are kept. (one thread, cleared when full)
- Color glyph pictures are drawn in white into a premultiplied RGBA (sRGB) bitmap context. Grayscale antialiasing like the Chrome canvas, with LCD font smoothing off.
- The coverage of non-color glyphs (rasterize_glyph_mask) is drawn the same way as Mac Chrome Canvas2D. Blink FontPlatformData::CreateSkFont gives canvas text
  kSubpixelAntiAlias and subpixel positioning, and since a transparent canvas does not know the pixel layout (kUnknown_SkPixelGeometry), Skia derives A8 from the LCD drawing instead of LCD.
  Skia SkScalerContext_Mac then draws black text on a white RGB bitmap (DeviceRGB, no alpha) with font smoothing (CGContextSetShouldSmoothFonts) on,
  undoes the CoreGraphics gamma 2 with a square table (gLinearCoverageFromCGLCDValue), and corrects the luminance of the inverted RGB (SkComputeLuminance) with the gamma pre-correction table.
  The glyph box is CTFontGetBoundingRectsForGlyphs plus the subpixel part, rounded outward with 1 pixel added on every side. (SkScalerContext_Mac::generateMetrics)
  Synthetic italic is drawn by CoreText with the text matrix skew (-1/4) like Skia.
- [platform/desktop/directwriteglyph](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/desktop/directwriteglyph&lang=en): Windows DirectWrite glyph mask. (used by the desktop glyph raster)
- A file that does not exist in the original. Original Chrome on Windows paints Canvas2D text with Skia's SkScalerContext_DW through DirectWrite.
  The Rust version also paints with the same DirectWrite calls. (Skia 3279352f of Chrome 158, src/ports/SkScalerContext_win_dw.cpp, SkTypeface_win_dw.cpp)
- A8 mask: IDWriteFactory2::CreateGlyphRunAnalysis is given a rendering mode (picked by the gasp table, size, bytecode hints and bitmap fonts), a measuring mode,
  grid fitting on (hinting kNormal) and grayscale antialiasing, and returns an alpha texture of DWRITE_TEXTURE_ALIASED_1x1.
  On a machine with ClearType on, Chrome treats text as LCD so kGenA8FromLCD applies on the canvas, so a ClearType 3x1 texture is taken from IDWriteFactory and the three channels are averaged. (RGBToA8)
  The subpixel position is dx of the text matrix, and fake italic is m21 (-1/4) of the text matrix. After that it is corrected with the gamma precorrection table like Skia. (GrayscaleToA8)
- Text contrast and gamma: Chrome 158 uses the IDWriteRenderingParams values only if the key HKCU\SOFTWARE\Microsoft\Avalon.Graphics\<primary display device> exists,
  otherwise it uses Skia's defaults (contrast 1, sRGB). (GetTextParameters in ui/gfx/font_util_win.cc, font_render_params_win.cc, SetCachedParams in skia/ext/legacy_display_globals.cc)
- [platform/desktop/emojipanel](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/desktop/emojipanel&lang=en): OS emoji panel. (in place of ui::ShowEmojiPanel called by "Emoji" in Chrome's edit field context menu)
- Mac: [NSApp orderFrontCharacterPalette:nil] (same as Chrome ui/base/emoji/emoji_panel_helper_mac.mm)
- Windows: sends the press and release of the Windows key + '.' with SendInput. The emoji panel appears from Windows 10 RS4. (same as emoji_panel_helper_win.cc)
- Linux: none, like Chrome. (IsEmojiPanelSupported in emoji_panel_helper.cc is false, and the menu has no item either)
- [platform/web](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/web&lang=en): Web platform. (wasm32)
- As in the original, fills the window's inside with the canvas and gets a WebGL2 context with the same options as the original.
- One engine frame per request_animation_frame callback. (the browser calls it in step with vertical sync, and the screen is presented when the callback finishes)
- Receives keyboard, mouse and fingers. Text input for input fields (a hidden DOM <input>, IME composition, context menu) and the clipboard are handled by web/textinput.rs.
- When a key is pressed, if it is one of the input manager's keys to prevent (set_prevented_keys), the default action is prevented unless typing in a text input. The last used device is recorded on every key, mouse and finger event.
- Audio: as in the original engine.js, click / touchstart / keydown (and touchend / pointerup if set) count as a user gesture
  and call engine.resume_on_user_gesture(), and on focus and when the page becomes visible again engine.resume() is called.
- Page: passes visibilitychange, blur, focus, pointerdown as engine page events, calls on_page_visibility_restored when visible again,
  and on_page_process_restored on document resume and pageshow (persisted). (the original setupAllDocumentEvents)
- Max FPS decides turns by the number of frames processed since counting started, as in the original. (platform/framelimiter.rs, at 90 Hz 60 FPS also averages 60)
- On the canvas's webglcontextlost, webglcontextrestored, forgets the GL state cache like the original WebGLStateCache.
- Key, mouse, finger and page events do not borrow twice even when they re-enter inside the frame callback (like dispatchEvent or focus() in game code).
  If they can borrow right away they are handled on the spot, otherwise they are queued and handled in arrival order at the end of the frame callback. (platform/eventqueue.rs)
- exit_application: as in the original, tries Capacitor's App.exitApp, or window.close if missing.
- [platform/web/textinput](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/platform/web/textinput&lang=en): Web text input. (hidden DOM <input> → engine text input queue, right clicks, canvas mode keys, clipboard)
- A port of the DOM side of the original UIInputField. In the original each field creates its own <input> and attaches listeners.
  In the Rust version fields post their state (position, value, selection, focus) to the engine every frame, and here one hidden <input> is matched to each attached DOM input field.
  - The DOM owns the value and selection. input / compositionstart / compositionupdate / compositionend / Enter keydown / focus / blur are
    put into the text input queue with that field id (replaceValue, composition, focus), and native moves like arrows are put in by polling the selection every frame. (the original tick)
  - When the field side changes the value or cursor (set_text, pressed position, cut), the state's value_revision increases and it is written back to the <input> here. (deferred during composition)
  - iOS shows the keyboard only if focus() is called inside a user gesture. As in the original, synchronous handlers are attached to canvas touchstart / mousedown (touchend if set),
    which check against the previous frame's field positions and focus / blur on the spot.
  - A right click on a field blocks the browser menu like the original and is put in as a context menu request (set_context_menu_request_position), the same as the desktop right button.
    The field opens the menu drawn by the engine (UIInputFieldContextMenu). A right click on that menu also blocks the browser menu.
  - Fields with use_dominput off convert window keydown into editing keys and characters, like the original canvas mode.
- DOM event listeners do not borrow the engine. They go into a pending queue (PENDING_EVENT_LIST) and move to the engine at the start of the next frame.
  (because focus() called by apply_frame fires focus / blur events on the spot)
- Differences from the original: the hidden <input> exists only while the field runs its tick. (it goes away when the node is turned off or removed) Cursor moves deferred with setTimeout are the same as the original.
- [resource](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource&lang=en): Resources. (the original src/resource: Asset derivatives)
- AudioAsset is tied to the audio backend (platform/audio), so it is not yet in AssetBase form. Loading is engine.load_audio_asset.
- [resource/animationclip](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/animationclip&lang=en): Animation clip. (list of sprite sheet frame areas + whether it loops + duration)
- A port of the original resource/animationclip.js. Animator's AnimationState holds it.
- The original comment calls the frame list Frame[], but what from_atlas puts in is Rect. The Rust version settles on a list of Rect.
  (a Frame must hold an image, so it cannot hold an atlas area without an image)
- Differences from the original:
  - get_frame is None when out of range. (the original undefined)
  - Rust has no default arguments for from_atlas (fps = 10, is_loop = true), so they are always passed.
    frame_ids accepts anything that implements Display (strings, integers). Array atlases read that text as an index.
  - It has the same name as the 3D AnimationClip (graphics3d::skinnedmodel), so it is not re-exported from lib.rs.
    Use it as vanilla::resource::animationclip::AnimationClip.
- [resource/audioasset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/audioasset&lang=en): Audio asset.
- The original resource/audioasset.js. Holds the audio buffer decoded from a sound file.
- The audio buffer is filled by the backend. (AudioBuffer of platform/audio)
  Desktop: an AudioBuffer holding the decoded sound in an Arc. (platform/audio/decode decodes it to the same length, sample rate (44100) and samples as the original Chrome decodeAudioData.
  Opus and Vorbis in webm, ogg, mp3, wav, flac, AAC in m4a and aac. The format is told by content, not extension)
  Web: the same WebAudio AudioBuffer as the original. (decoded with OfflineAudioContext, or a temporary AudioContext if missing)
- Reading:
  On desktop load / load_from_bytes read and decode the file on the spot before returning. Err on failure.
  Web cannot block, so load sets up fetch and decoding and returns Ok right away. When done, is_loaded() becomes true,
  and on failure the reason stays in get_load_error(). It may be loaded into a player before that, and play does nothing while there is no buffer.
  load, load_from_bytes, load_from_asset return an AudioLoadHandle that can be awaited as in the original. Ok once decoding finishes, the reason (the original reject) on failure.
  (desktop, which knows failure on the spot, checks it right away with the handle's get_load_error) An asset whose read has already been started can also be awaited with wait_for_load().await.
  In the engine, engine.load_audio_asset("sounds/hit.ogg") reads a path relative to the asset folder.
- Load type: set_load_type(AudioLoadType). As in the original the default is full decoding (DecompressOnLoad), and only background music of the engine SoundSystem streams when the sound table has no load_type.
  Streaming does not decode up front and holds only the compressed source, decoding a little at a time while playing. On desktop a decoder thread decodes chunk by chunk into a ring buffer for the mixer
  (platform/audio/streaming.rs, the same samples as the fully decoded buffer), and on the web, as in the original, an HTMLAudioElement is connected to the player's GainNode through a MediaElementAudioSourceNode.
  Automatic streams only files larger than AUTOMATIC_STREAMING_BYTE_THRESHOLD (1 MiB).
- Differences from the original:
  There is no Asset base class (asset type). Read failures are reported with Err instead of exceptions. (the reason stays in get_load_error() like the original getLoadError)
  It is used as `Rc<AudioAsset>` so players can share it, and its inside is a RefCell so it can be filled after decoding finishes on web.
- [resource/blobasset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/blobasset&lang=en): Binary asset. (the original resource/blobasset.js)
- The original holds the Blob received with fetch. The Rust version holds the bytes as is.
- [resource/bunchasset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/bunchasset&lang=en): Bunch asset. (BunchAsset of the original resource/bunchasset.js)
- In the original it is a skeleton that inherits BlobAsset and only changes the asset type to bunch. Reading is the same as BlobAsset. (unpacking the bunch is not done yet)
- In the Rust version it is a struct with the same functions instead of inheritance, and the asset type is AssetType::Bunch.
- [resource/fontasset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/fontasset&lang=en): Font asset. (the original resource/fontasset.js)
- The original creates a FontFace and adds it to document.fonts. After that the name is used in font strings ("16px name").
- In the Rust version, after the bytes arrive the engine registers it by name in Graphic's text cache at the start of the next frame.
  WOFF, WOFF2 work too. (the text cache decodes them to TTF)
- The original descriptors (weight, style, character range) are taken as FontFaceDescriptors. (load_font_with_descriptors, load_font_with_bold for weight only)
  When several files with different weights or styles are registered under the same name, the text cache picks and draws like CSS. If a real italic face exists, it is used instead of fake slanting.
- unload removes that face from the font list as in the original. (document.fonts.delete)
- load: like the original load(assetPath), calls load_font with the file name minus its extension as the family name. ("DOSGothic" for "assets/DOSGothic.woff")
- load_font_from_bytes: reads from font bytes already in hand. (the original loadFontFromBytes, uses the name if the descriptor's source_key is empty)
- The load_font functions return a FontLoadHandle that can be awaited as in the original. It finishes once the bytes arrive and the engine registers it in the font list.
  (after the original await fontFace.load() and document.fonts.add, from then on it draws with that name) If receiving or registering fails, it finishes with the reason.
- [resource/imageasset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/imageasset&lang=en): Image asset. (the original resource/imageasset.js)
- The original sets src on an HTMLImageElement and waits for onload.
  The Rust version asks the engine for the bytes, and once they arrive decodes them into an Image on the first get_image. (formats of Image::load_from_memory, on web it uses the image the browser decoded on receipt from the handle)
  For ones received by AssetLoader, the image already decoded when everything arrived (the handle's get_decoded_image) is used as is. (if it could not be decoded, the handle fails)
- load, load_from_bytes return a load handle that can be awaited as in the original. Like the original img.onload, await finishes only once decoding finishes,
  and if it cannot be decoded it finishes in failure (the reject of the original onerror). The decoded image is kept on the handle so get_image does not decode it again.
- [resource/textasset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/textasset&lang=en): Text asset. (the original resource/textasset.js, resource/jsonasset.js)
- The original TextAsset keeps the text received with fetch in text, and JsonAsset keeps the JSON.parse result in data.
- The Rust version decodes it as UTF-8 text on first access once the bytes arrive, and JsonAsset decodes it into serde_json::Value.
- Like the original, JsonAsset also holds TextAsset's text (get_text), and JSON that cannot be parsed counts as not loaded (is_loaded false, get_data None).
  When received by AssetLoader it goes into the failure list as in the original. (the parsed data is shared with the AssetLoader list entry so it is parsed only once)
- set_no_cache: if true, adds cache: "no-cache" to web fetch so old data is not used after a deploy. (same as the original, desktop always reads the file anew, so the result is the same as on)
- load returns a load handle that can be awaited as in the original. (like the original JsonAsset.load, if receiving or JSON parsing fails, the await ends in failure and get_data is None)
- [resource/visualasset](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/visualasset&lang=en): Visual asset. (VisualAsset of the original resource/visualasset.js, reads a document file saved by the visual editor and makes a Visual)
- The file is the UIDocument JSON saved by the visual editor (vanilla.js tools/visualeditor). (Scene *.scene.json, prefab *.prefab.json, { version, root, frameSize? })
- load asks the engine's asset fetching for the bytes. When the bytes arrive, the first look checks that they are a JSON object with a root object; if so it counts as loaded and stores a Visual holding that text.
  A failed fetch or a malformed document stays unloaded. (The original rejects load)
- Visual::create_node builds the node tree. (A new tree on every call)
- Differences from the original:
  - The original load(path) returns a Promise, the Rust load(engine, path) returns a load handle that can be awaited. (Same as other assets)
  - The original static createVisualFromText(text) throws on failure, the Rust create_visual_from_text gives Err.
  - load_from_bytes exists for tests and bundle files. (Same as TextAsset)
- [resource/assetloader](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/assetloader&lang=en): Loads assets together. (the original resource/assetloader.js)
- Puts images, JSON, text, binaries, sounds and fonts in a list and receives them as many at a time as the concurrency (set_concurrency). Failed ones also count as finished, so it does not stall.
- The original waits with await load(). In the Rust version too, load(engine) returns a handle (AssetLoaderLoadHandle) that can be awaited as in the original,
  and awaiting it waits until everything arrives and yields the failure list. (calls update every frame while waiting, wait_for_load().await is the same)
  Usage without await follows the engine's "request → fully read later" pattern:
    Functions like add_image return an asset with a still-empty load handle right away, and load(engine) requests the first batch.
    After that, update(engine) must be called every frame to request the next ones as earlier ones finish. (on desktop they are read on the spot and all finish in load)
    A scene hands get_completion_handle() to scene_base.track_load_handle to defer initialize until everything arrives.
    GameSceneBase hands it off with a single track_asset_loader, and draw_on_load calls update and passes the progress to the loading screen.
- A cheap-clone form that shares handles. (cloning points to the same list)
- Progress is finished count / total count. Failures stay in get_failed_list() as AssetLoadFailure. Calls the set_progress_handler function on change and the set_complete_handler function when all finish.
- Differences from the original:
  Fonts return a load handle instead of a FontAsset. (fonts in the Rust version are registered by name by the engine, and FontAsset is a shell holding a handle)
    The original descriptors (weight, style, character range) are taken as FontFaceDescriptors and passed to the engine's register_font_face_when_loaded. (FontFaceDescriptors::new() if none)
  JSON is a failure if it cannot be parsed after receiving, as in the original. (a failure if the original isLoaded() is false)
  Sounds return `Rc<AudioAsset>`, and count as finished only once decoding finishes after the bytes arrive.
  The original addTask (a hand-made fetch) corresponds to add_load_handle. A load handle requested directly and added is counted in the progress too.
    Just as an original worker picks up an addTask and uses one slot until it finishes, it counts toward the in-flight count (get_in_flight_count) and concurrency until it finishes.
    The handle was already requested before being added, so it cannot be deferred until its turn as in the original, and it is in flight from when it is added.
  The in-flight count is, as in the original, those picked up and started but not yet finished. (images until decoded, sounds until decoded. The original worker waits for that too) Concurrency is counted with this too.
  Images are decoded once fully received, like the original img.onload. Ones that cannot be decoded (broken PNG) go into the failure list, and decoded images are kept on the handle so ImageAsset does not decode them again.
  Items added while receiving are received together as free slots allow, as in the original. (the original spins up more workers when adding, the Rust version fills free slots on each update)
- [resource/spriteatlas](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/resource/spriteatlas&lang=en): Sprite atlas. (SpriteAtlas of vanilla.js resource/spriteatlas.js)
- Takes out images gathered on a few page images by name. Sprites using the same page image are batched by the engine and drawn at once.
- The JSON formats read are the same two as the original.
  1. Made by tools/atlas.cjs. { images: { "name.png": { x, y, width, height, page } }, meta: { imageFileName, pages: [{ imageFileName }] } }
     Page 0 if page is missing, a single meta.imageFileName if meta.pages is missing.
  2. Page paths and a [page, x, y, width, height] table. { pagePaths: `["path"]`, frames: { "name": [page, x, y, width, height] } }
- Image names can also be found by the name without the extension. ("icon-close.png" can be found as both "icon-close" and "icon-close.png")
- If a page path has no slash (/), it is read relative to the folder holding the JSON, otherwise as written. (if it starts with "./", that "./" is dropped and it is relative to the asset folder)
- Differences from the original:
  In the original load is async, waiting for the JSON and then receiving the page images. The Rust version only makes requests like assets, and update requests the page images once it sees the JSON has arrived.
  load, load_data return a SpriteAtlasLoadHandle that can be awaited as in the original. The handle shares the loading state and does not borrow the atlas, so
  an atlas held by a scene is also waited on with scene_context.with(|scene, engine| scene.atlas.load(engine, path)).await. (calls update every frame while waiting)
  On desktop it is read on the spot, so everything is read when load finishes. On web the JSON and page images arrive in turn, so call update in tick until is_loaded becomes true,
  and set frames after that. (to have the scene hand it off and wait, use track_json_asset for the JSON, and update requests the page images once it arrives)
  The original list of atlases to search (add_search_atlas, find_frame, apply_search_frame) is one list per thread, and atlases are added as `Rc<RefCell<SpriteAtlas>>` so they can be shared.
  find_frame returns a copy of the frame (a Frame is an image Rc and an area, so it is cheap) instead of a borrowed one. There is also find_frame_in_order, which searches a given list.
  get_page_images is a list of loaded page images (Image) instead of the original list of HTMLImageElement.
- [ui](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui&lang=en): UI widgets. (the WorldNode line of the original src/ui)
- As in the original, most widgets are components, not nodes. Attached to a node, they use their own node (the host) as the widget.
- Widgets that create child nodes (content, scroll bars) or companion components (Mask) are attached with node_tree.add_component(node_id, ...).
  If attached with WorldNode::add_component, attach_to_tree is not called, so there is no content node and touch is not enabled.
- The original UIScrollBar is a node inheriting WorldNode. The Rust version is a UIScrollBar component attached to a single node.
- UIInputField receives key, IME and hidden web DOM input events from the engine text input queue (core/textinput.rs).
- Widgets that inherit WorldNode in the original (UIDropdown, UIDialog, UIToast, UISpinner, UIContextMenu) are also components attached to a host node.
  When attached, they set up the host and create child nodes like the original constructors. Each widget's create(node_tree, parent_id, options) takes the place of new + add_child.
- The UINode, auto layout (autolayout) and UIScene lines were also ported. (UIDocument was ported with a type name table instead of reflection)
- [ui/buttonmotion](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/buttonmotion&lang=en): Button motion. (ButtonMotion, ButtonMotionStyle, attachButtonMotion, setButtonMotionArea, shakeButton of vanilla.js ui/buttonmotion.js)
- Attached to a button node after UIButton, it reads that button's state every frame and scales the node up and down around its center.
  It grows on hover, shrinks while pressed, bounces on release, and shakes left and right when shake is called while it cannot be pressed.
- Colors are not touched. (the background and text colors of text buttons are set by the screen's code, and image buttons are handled by UIButton's tint)
- Devices whose primary input is a finger do not use hover. (so it does not look hovered from the finger position left after release)
- When there is no motion, the node's position and size are not touched, so it does not clash with other effects that scale the same node.
- The style is set per button with set_style, or if left empty follows the closest node above with a ButtonMotionArea, otherwise Normal.
- In the Inset style, while hovered, brightens the color of the button's background Paint and draws a white rim inside. (buttons without a background Paint or that are invisible are not brightened)
  To have the decoration on a button brighten in its own way, hook a function with set_lit_handler. (the button's pressed color is then left transparent)
  The hooked function is kept in an `Rc<RefCell>`. get_lit_handler returns that Rc, and the caller borrows it with borrow_mut to call it.
- Differences from the original: the centering math reads the pivot (the original only handles a top-left pivot), and the marker that sets the style is the ButtonMotionArea component (the original uses a WeakMap).
  The brightened background and white rim are not child nodes. (the original uses the two bottommost children, and if the text is a component of the same node as in the Rust example, children would cover the text)
- [ui/popupmotion](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/popupmotion&lang=en): Popup appear / disappear transitioner. (PopupMotion, PopupMotionState of the original ui/popupmotion.js)
- Moves through the four states closed → opening → open → closing → closed and computes the scale (appear: 0.45 → 1.18 overshoot → 1, disappear: 1 → 1.08 → 0.08) and
  the dimming ratio (dim_ratio). It is a calculator, neither a node nor a component, so it is ported from the original as is.
- Every frame after tick(time_delta), read get_scale() / get_dim_ratio() and apply them to the node scale / overlay alpha. If set_instant_enabled(true), it changes right away without the effect.
- Differences from the original:
  - The state is the PopupMotionState enum instead of a string.
  - The options object is the PopupMotionOptions struct. The open / close notifications are argument-less `Box<dyn FnMut()>`.
    (UIDialog, which has to change nodes, handles it by comparing the state before and after tick instead of using notifications)
- [ui/toastmotion](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/toastmotion&lang=en): Motion for a notification appearing and disappearing. (ToastMotion, ToastPhase, readToastSeconds, attachToastMotion of vanilla.js ui/toastmotion.js)
- Attach it to a notification node and show it with show. It slides in from the outside (upper notifications from above, lower notifications from below), is visible, grows slightly and returns,
  and when the stay time passes it floats up and disappears.
- If another text arrives while it is up, the earlier one moves out quickly and the new text comes in; if the same text arrives again, only the time is refilled and it bounces once.
- The node's position moves only around the placed position as the reference. (if placed again in between, that position becomes the new reference)
- Differences from the original: show only records the request and moves the node on the next tick. (scene code calls it without a node context)
  The text is put into the node when the function given to show starts to appear. (same as the original show(text, seconds, applyText)) While hidden, the node is not turned off but only made invisible. (so tick keeps running)
- UIToast creates stacked pill notifications by itself, and this one moves a notification node made by the game.
- [ui/touchrecognizer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/touchrecognizer&lang=en): Touch recognizer. (TouchRecognizer of the original ui/touchrecognizer.js)
- If a UIScrollView (or UISnapScrollView) is up the pressed node's parent chain, once the drag distance exceeds the threshold (10px), cancels the press on the pressed node and
  hands the scroll over by resending press → move to the scroll view from the initial press point. (dragging a button inside a scroll view still scrolls)
- If there is a scroll view among the parents, the press to the pressed node is delayed by 150ms. If it becomes a drag in the meantime, the press itself is never sent.
  A short tap sends the delayed press right away on release, followed by the release. (UIKit's delaysContentTouches)
- If the scroll view has set_passes_cross_axis_drag(true), a finger dragged more along the non-scrolling axis is not handed over.
- Differences from the original:
  - The original GameScene always uses it. The Rust version's SceneBase::tick_touch is the original TouchRaycaster (sends straight to the topmost node).
  ```text
    A scene that needs this gesture holds a TouchRecognizer and, instead of SceneBase::tick, calls the node update and this:
      self.scene_base.get_node_tree_mut().tick(engine, time_delta);
      self.touch_recognizer.tick_touch(self.scene_base.get_node_tree_mut(), engine);
    In that case SceneBase's first touch callback and get_touch_target are not used. (use this one's get_touch_target)
  ```
  - The original setTimeout(150ms) is counted by accumulating frame intervals (time not multiplied by the scale).
  - Touches handed to a scroll view go to all components of that node. (NodeTree::dispatch_touch)
  - tick_touch is split into wheel (tick_wheel) and press (tick_pointer). A scene that routes the wheel elsewhere (a window layer) calls mark_wheel_handled instead of tick_wheel. (GameSceneBase)
- [ui/uibutton](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uibutton&lang=en): Button. (UIButton, ButtonState of the original ui/uibutton.js)
- Press / release / cancel / click / long press / mouse over events, and a tint transition that changes color when pressed or hovered.
- A click happens only when pressed and then released inside the button area. (a press that fired a long press swallows the click)
- As in the original, the tint applies to Sprite / UIImageView (cover color) and Paint / Text / UILabel (original color interpolation) of the host node and all descendants.
  Other components of the host node are found as siblings during tick / touch. (NodeTree briefly takes out only the component it is calling)
  In the original, Sprite inherits Paint, so it is also caught by getComponents(Paint). So sprites get the original color interpolation once more after the cover color,
  and the later one wins. To produce the same result, the Rust version also holds sprites (and UIImageView's sprites) twice.
- Differences from the original:
  - Events are `Box<dyn FnMut(&mut UIButton, &mut ComponentContext)>`. Original callbacks take only the button.
    The context is passed along so callbacks can change, create, and delete other nodes. (the bool return of click events was dropped because the original never used it either)
    Received events are stored in `Rc<RefCell>`. Event getters return that Rc, and the caller borrows it with borrow_mut and calls it with the button and the context.
    If the same event is called again while it is being called (like fire_click_events inside the callback), it is skipped because it is already borrowed.
  - The original setInteractable / UIToggleButton.set_is_on gather the color targets and apply the tint on the spot. The Rust version cannot reach the nodes there, so
    it gathers and applies them on the next tick. (tick reapplies the tint every frame, so the visible result is the same)
  - Excluded components are specified by (node, component type) instead of instance: `exclude_component_from_tint::<Paint>`(node_id).
  - setStateEvent (an empty function in the original too) was not ported.
- attach_to_tree turns the host node interactable. Attach with node_tree.add_component(node_id, UIButton::new()).
- [ui/uichart](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uichart&lang=en): Chart. (UILineChart, UIBarChart of the original ui/uichart.js)
- UILineChart: draws a value list as a polyline in the node area. Pushing new values with push_value makes a real-time graph where old values are pushed out from the front.
  Samples are spread across the full width based on the maximum sample count. (fills from the left while not yet full) If the value range is not set, the min / max of the current values is used.
- UIBarChart: draws a value list as vertical bars. If the maximum is not set, the max of the current values is used. The bar at the highlight index uses the highlight color.
- Both are draw-only components, so they can also be attached with WorldNode::add_component. (no tick)
- Differences from the original:
  - The "auto if null" of the value range / maximum is `Option<f64>`. The "none if -1" of the highlight index is `Option<usize>`.
  - get_value_list returns a slice instead of a copy.
  - Point / bar position calculation is split out into calculate_points / calculate_bar_rects. (the same calculation as drawing, for tests and hit testing)
  - The line chart holds and reuses a point buffer so it does not allocate every frame.
- [ui/uicontextmenu](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uicontextmenu&lang=en): Context menu. (UIContextMenu of the original ui/uicontextmenu.js, a right click / long press menu)
- show(node_tree, position, item_list) pops up the item list at that position. Pressing outside closes it, and pressing an item closes it and then calls the handler.
- The menu is pinned to the right / bottom edge so it does not go outside the parent area. (960 x 640 if the parent size is unknown)
- Place it at the top of the scene root (the last child).
- The original is a node that inherits WorldNode. The Rust version is a component attached to a node (host), and on attach, like the original constructor, it
  sets up the host (top-left pivot, inactive) and creates an outside-press blocker (transparent UIButton) and a menu panel (rounded Paint) as children.
  UIContextMenu::create(node_tree, parent_id, options) takes the place of the original new UIContextMenu(options) + add_child.
- Usage:
  ```text
    let menu_id = UIContextMenu::create(node_tree, root_id, UIContextMenuOptions::default());
    node_tree.with_component_mut::<UIContextMenu, _>(menu_id, |context_menu, tree| {
        context_menu.show(tree, view_position, vec![UIContextMenuItem::create("Copy", Box::new(|context| { ... })), UIContextMenuItem::create_disabled("Delete")]);
    });
  ```
- Differences from the original:
  - show / close change nodes, so they take the tree. Scene code calls them with node_tree.with_component_mut.
  - Items are a UIContextMenuItem struct ({ text, handler?, is_disabled }), and a handler is a one-shot function (FnOnce) that takes the context of the pressed row node.
  - is_showing returns the value changed by show / close instead of the node's active state.
  - Previous rows are deleted instead of detached (removeChild). Row node names are "ContextMenuItem{index}" as in the original.
- [ui/uicontrol](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uicontrol&lang=en): UI control. (UIControl of the original ui/uicontrol.js)
- Base of widgets that take user input (touch). Sits on top of UIView like UIKit's UIControl.
- The original inherits UIView and only changes the name. The Rust version embeds UIView and passes through content and the background color.
  UIButton and UISlider embed this.
- [ui/uidialog](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uidialog&lang=en): Confirmation dialog. (UIDialog of the original ui/uidialog.js)
- Pops up a dimming blocker + a centered card + confirm / cancel buttons with a single show. Appearing / disappearing moves with PopupMotion (bounce scale up / shrink).
- Pressing the blocker counts as cancel. If on_cancel is not passed, the cancel button is hidden and it becomes an alert with only a wide confirm button.
- Place it at the top of the scene root (the last child). The parent's content_size is used as the blocker size. (960 x 640 if none)
- The original is a node that inherits WorldNode. The Rust version is a component attached to a node (host), and on attach, like the original constructor, it sets up the host
  (top-left pivot, inactive) and creates the blocker, card, message, and button nodes as children. UIDialog::create(node_tree, parent_id, options) takes the place of new + add_child.
- Usage:
  ```text
    let dialog_id = UIDialog::create(node_tree, root_id, UIDialogOptions::default());
    node_tree.with_component_mut::<UIDialog, _>(dialog_id, |dialog, tree| {
        dialog.show(tree, "Really delete?", UIDialogShowOptions { on_confirm: Some(Box::new(|dialog, context| { ... })), on_cancel: Some(Box::new(|_, _| {})), ..UIDialogShowOptions::default() });
    });
  ```
- Differences from the original:
  - show changes nodes, so it takes the tree. Scene code calls it with node_tree.with_component_mut, and callbacks with context.get_node_tree_mut().
  - Confirm / cancel handlers are one-shot functions (FnOnce) that take the dialog and its host's context. dismiss takes the context to pass it to the handlers.
    Scene code without a context can call request_dismiss, which the original also has, to dismiss on the next tick.
  - The original calls set_active(false) on the PopupMotion closed notification. The Rust version turns it off in tick when what was showing becomes closed (in dismiss for an instant transition).
  - The original tick runs the transitioner after the children's tick. In the Rust version, components run before children. (no visible difference)
  - Transition times are the same as PopupMotion. (appear 0.32 seconds, disappear 0.22 seconds. Tween is not used)
- [ui/uidraggable](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uidraggable&lang=en): Draggable component. (UIDraggable of the original ui/uidraggable.js)
- Attached to a node, it can be pressed and dragged. On release it notifies with the end event, and with set_snap_back_enabled(true) it slides back to where it was before being grabbed.
- The movement adds the view coordinate difference as is to the local coordinates. (sensitivity differs if an ancestor node has a scale. same as the original)
- The original inherits UIControl. The Rust version embeds UIControl (ui_control field) and passes through content and the background color.
  attach_to_tree turns the host node interactable. Attach with node_tree.add_component(node_id, UIDraggable::new()).
- Usage:
  ```text
    let draggable = node_tree.add_component(card_id, UIDraggable::new()).expect("draggable");
    draggable.set_snap_back_enabled(true);
    draggable.set_drag_end_event(Box::new(|draggable, context, view_position| { if is_drop_spot { draggable.settle_here(context.get_node_tree_mut()); } }));
  ```
- Differences from the original:
  - Events take the drag component and the context. (move / end also the view coordinates) Original callbacks take only the component (and the view coordinates).
  - settle_here / snap_home need to read and write the node position, so they take the tree. (context.get_node_tree_mut() inside the end event)
- [ui/uidropdown](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uidropdown&lang=en): Dropdown. (UIDropdown of the original ui/uidropdown.js, a combo box)
- The closed header button shows the current value, and pressing it expands a list of options downward. Pressing a row selects it and collapses.
- On expand, the list is moved to the last child of the tree root so it is not covered by sibling nodes drawn later. (moved back under the header button on collapse)
- The popup list node is excluded from the header button's tint targets. (exclude_node_from_tint, otherwise after selecting, the header button reapplies the old row colors it stored when pressed every tick and
  covers the selection highlight) After changing the highlight, the row buttons are made to store their original tint colors again. (on the spot in the original, on the next tick in the Rust version)
- The original is a node that inherits WorldNode. The Rust version is a component attached to a node (host), and on attach, like the original constructor, it
  sets up the host (top-left pivot, size, interactable), puts Paint + UIButton + UILabel (header text) on the host, and creates the arrow node and the popup list node as children.
  UIDropdown::create(node_tree, parent_id, options) takes the place of the original new UIDropdown(options) + add_child.
- Usage:
  ```text
    let dropdown_id = UIDropdown::create(node_tree, panel_id, UIDropdownOptions { width: 180.0, ..UIDropdownOptions::default() });
    node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| dropdown.set_option_list(tree, &["Dark", "Light", "System"]));
    node_tree[dropdown_id].get_component_mut::<UIDropdown>().unwrap().set_changed_event(Box::new(|dropdown, context| { dropdown.get_selected_text(); }));
  ```
- Differences from the original:
  - Functions that change the tree (set_option_list, set_open, set_selected_index) take the tree. Scene code calls them with node_tree.with_component_mut.
    select_index takes the context to pass it to the changed event. (row buttons call it with ComponentContext::with_component_mut)
  - The changed event takes the dropdown and the context. The options object is the UIDropdownOptions struct.
  - Row highlights are updated through the list of created row nodes instead of the popup list's child order. (when rebuilt during tick, deleted rows briefly remain as children)
  - The arrow characters are small triangles (▾ ▴, U+25BE / U+25B4) as in the original. Characters missing from the default fonts (Malgun Gothic, Segoe UI, Arial) are
    drawn with a system fallback font like Chrome does. (core/textshaping.rs)
  - Node names are "DropdownArrow", "DropdownPopup", "DropdownOption{index}" as in the original. The host name is chosen by the creator. ("UIDropdown" for create)
- [ui/uihitarea](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uihitarea&lang=en): Hit area widening. (UIHitArea of vanilla.js ui/uihitarea.js)
- Leaves the visible button as is and places a transparent hit area as the sibling right behind the button, widening its width and height to at least the minimum size. (easier to press with a finger)
- The node drawn later receives the press, so the button receives presses over the button and the hit area receives only the widened margin around it.
- Pressing the hit area fires the button's click notifications (Clicked, Click) as is. If the button is turned off or not pressable, the hit area follows.
- It follows the button's position, size, and pivot every frame, so it stays aligned even when the screen moves the button.
- When a clipping node is set, the widened margin is clipped so it does not go outside that node's rectangle. (the button's own area stays as is, so areas outside the window or scroll area are not pressed)
- Usage: UIHitArea::attach(node_tree, button_id, minimum_size) (call after the button is attached to its parent)
- [ui/uiimageview](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiimageview&lang=en): UI image view. (UIImageView of the original ui/uiimageview.js)
- A display-only widget. Exposes the sprite's image / color / flip / draw mode / blend / nine-slice.
- The original attaches a Sprite to the host on attach and holds a reference. The Rust version embeds the Sprite. (for the same reason UILabel embeds Text)
  The embedded Sprite is taken out with get_sprite / get_sprite_mut as in the original. `get_component::<Sprite>()` on the image view node is None.
  The UI document writes and reads the embedded Sprite as a Sprite after UIImageView, as in the original. (uidocument.rs)
- The image path (get_image_path) is held separately from the embedded Sprite's path (the original Sprite's imagePath), like the original imageView.imagePath.
- The original setImage takes both an image element and an ImageAsset. The Rust version splits it into set_image(`Option<Rc<Image>>`) and set_image_asset.
- The background color (UIView) is drawn before the sprite. (in the original too, UIImageView is attached first and attach adds the Sprite after, so the order is the same)
- [ui/uiinputfield](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiinputfield&lang=en): Input field. (UIInputField, BackgroundLayerRenderer, OverlayLayerRenderer of the original ui/uiinputfield.js)
- Draws text, cursor, selection, IME composition text and its underline, and the focus border directly onto the canvas, and sets the cursor and selection by pressing and dragging.
- The original is a node inheriting WorldNode, with text drawn by two UILabel child nodes (value, placeholder) and the cursor and border drawn by an overlay child node.
  The Rust version is a component like the other widgets. Attach it with node_tree.add_component(node_id, UIInputField::new()).
  It contains a UIControl, creates the content node in attach_to_tree and turns the host interactable. The pivot and anchor are set to the top left as in the original.
  Text is drawn with two contained Text instances (value, placeholder), and the background (the original Paint component) is also drawn with a contained Paint.
  The layer order is the same as the original: background → selection → text → composition underline → cursor → focus border. One component draws them all at once, so
  even if scene code calls set_text outside tick, it shows up immediately that frame. (splitting into child nodes would lag one frame while moving the state)
- Input is received from the engine's text input queue (core/textinput.rs). The attach()ed field with focus takes it out in tick.
  - Desktop: winit KeyboardInput and Ime events. IME is enabled only when a field with use_dom_input (the original setUseDOMInput) on has focus.
  - Web: as in the original, a hidden DOM <input> is placed over each field. (platform/web/textinput.rs) The DOM owns the value and selection, and the field follows.
    Fields with use_dom_input off receive window keydown like the original canvas mode.
- Differences from the original:
  - Events are Box<dyn FnMut(&mut UIInputField, &mut ComponentContext)>. Original callbacks receive only the value. (the value is field.get_text())
  - setFont(FontFace) became set_font_family(registered font name). setEngine was not ported. (the engine comes from the context)
  - Character positions in the public functions (get_cursor_index, get_selection_start, get_selection_range, move_cursor, measure_index_at_local_x) and max_length
    count in UTF-16 units as in the original. Internally they are held in characters (char) so surrogate pairs (characters like emoji) are not split.
    So a UTF-16 position in the middle of a surrogate pair is treated as after that character. (the original does the same) With max_length, inserted text is cut to the remaining length like a Blink input box.
  - Pressed position → character position is found from the character boundaries measured during draw. (the original measures each time with an offscreen 2D canvas)
  - On desktop, fields with use_dom_input on also lose focus when pressing outside the field, like the original DOM mode. There is only one focus in the engine.
    (in the original canvas mode, the previous field keeps focus even when another field is pressed. The Rust version keeps only the field that gained focus last)
  - When focus is lost, text being composed is committed into the value. (same as what browsers do for DOM inputs)
  - The context menu (right button) is drawn by the engine like the original. (UIInputFieldContextMenu, the same on the web and the desktop) It is created as the last child node of the root and drawn on top.
    The items are cut, copy, paste and select all, as in the original. Fields that let the DOM input be pressed directly (use_direct_touch) also get this menu instead of the browser edit-field menu, as in the original.
    Those fields select a word with a finger long press (650ms, within 15 DIP) like Chrome desktop touch and show touch handles and the quick menu. (Windows decides the menu on release)
  - Desktop DOM input fields undo and redo like the original DOM input box. (Ctrl+Z, Ctrl+Shift+Z, Ctrl+Y, Cmd on Mac, Blink's grouping rules, TextEditBuffer)
  - Desktop single-line DOM input fields, like a Blink input box, remove trailing line breaks from inserted text and replace middle line breaks with spaces, and up and page up move to the text start, down and page down to the text end.
  - With set_multiline(true), it is a multiline input like Chrome textarea. (not in the original engine, where the original uses a DOM textarea through the textarea preset of Pane)
    Text is split by line break characters and width, like white-space: pre-wrap, overflow-wrap: break-word. (ui/textarealayout.rs, line break positions follow Unicode line breaking like Chrome)
    Enter inserts a line (in the character insertion undo group), up and down keep the horizontal position from the first vertical move (up on the first line goes to the text start, down on the last line to the text end),
    Home and End go to the start and end of the visible line (also Cmd + Left, Right on Mac), Ctrl + Home, End (Cmd + Up, Down on Mac) go to the text start and end,
    PageUp, PageDown (with Option on Mac) move to the farthest line within 87.5% of the visible height (on Mac, the larger of that and height - 40) and bring that line to the top.
    CR and CRLF in inserted text become LF. After edits and moves it scrolls to keep the cursor visible (to the edge except on macOS, to the center on macOS), and it scrolls with the wheel and thumb dragging.
    A normal line height is computed from the first font's ascent, descent and line gap like Chrome. With classic scroll bars (Windows, Linux, the macOS classic setting), the scroll bar takes away text width when overflowing, like Chrome.
    On macOS, Home and End leave the cursor and scroll to the start and end like Chrome on macOS (line start and end if there is nothing to scroll), and PageUp, PageDown leave the cursor and scroll by one screen.
  - Fields imitating DOM input (use_dom_input, multiline) select a word (with the trailing space on Windows) on a double click and a paragraph on a triple click like Chrome, and dragging extends by that unit.
    Repeated presses are within 500ms (the system double-click time on macOS) and within 2 DIP horizontally and vertically, like Chrome aura. The web uses the mousedown detail counted by the browser.
  - Cursor movement and Delete work by grapheme cluster (extended grapheme cluster) like Chrome, and Backspace follows Blink's BackspaceStateMachine (one code point, emoji sequences whole).
    For web DOM input, a hidden `<textarea>` handles text, composition and undo, and keys that move by visible lines (up and down, page, Home, End) are handled by the field using the engine layout.
  - Word movement and deletion (Ctrl on Windows and Linux, Option on macOS, with Left, Right, Backspace, Delete) follow Blink NextWordPosition, PreviousWordPosition like Chrome's textarea.
    (Right goes to the start of the next word only on Windows, and to the end of the current word on macOS and Linux. On macOS, an extending selection does not cross the anchor) For web DOM input, the browser does it.
  - Turning off (set_active(false)) or removing the node stops tick, so focus, IME and the web's hidden <input> go away together. (the original goes away only when detached)
  - getRenderState was not ported. (there is only one drawing component, so there is nothing to pass)
  - UI documents (UIDocument) write and read it in the original node form when registered with register_node_type. (node type "UIInputField", background Paint, draw layers, placeholder and value UILabel children,
    overlay child. UIDocumentNode in uidocument.rs) The content node the Rust version creates is not written to the document.
    The positions and sizes of the text labels and overlay are written from the node size last placed by tick (text_layout_size), like the original refreshTextPositions.
- [ui/uilabel](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uilabel&lang=en): UI label. (UILabel of the original ui/uilabel.js)
- A display-only widget. Draws text aligned within the host's content_size area. Setters pass through to the text component as in the original.
- The original attaches Text and RichText to the host with require() and holds their references. The Rust version embeds one RichText, and RichText embeds Text.
  (the same form as Sprite embedding Paint) This is so a label.set_text call from scene code outside tick takes effect immediately.
  A sibling Text would be reachable only inside tick and lag one frame. So `get_component::<Text>()` on a label node is None.
  The embedded Text is taken out with get_text_component / get_text_component_mut, and RichText with get_rich_text_component / get_rich_text_component_mut.
- The original applies setters to both Text and RichText and picks which one to turn on with use_rich_text. The Rust version has a single set, so there is nothing to keep in sync.
  With use_rich_text(true) it draws with RichText (parsing markup), otherwise with the embedded Text. append_segment / clear_segments pass through to RichText.
- The original setFont(FontFace) was changed to set_font_family (a registered font name).
- Text direction (set_text_direction) and the visible character count (set_visible_character_count) pass through to the text component as in the original.
- Not ported from the original: invalidateIntrinsicContentSize (UINode path only).
- The background color (UIView) is drawn before the text. (in the original too, UILabel is attached ahead of the Text and RichText it requires, so the background is drawn first)
- [ui/uilistview](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uilistview&lang=en): Recycling list view. (UIListView of the original ui/uilistview.js)
- Takes only the item count, creates real nodes only for the visible range (including buffer slots before and after), and recovers and reuses nodes that leave it.
  Even with hundreds ~ thousands of items, the node count stays at one screenful. Item contents are filled in code with set_bind_item_event. (data driven)
- When it gets near the end, it sends the set_reach_end_event notification once. (infinite scroll / load more) It is rearmed when set_item_count increases the item count.
- As in the original, it attaches to the same node as the scroll view. If the node has no scroll view, a UIScrollView is attached along with it on attach. (original require)
  On a node with a UISnapScrollView, it uses that embedded view. (where the original getComponents(UIScrollView) also catches subclasses)
  The scroll view is attached first and ticks first, so this widget picks the visible range with that frame's scroll offset.
- Usage:
  ```text
    let list_view = node_tree.add_component(list_id, UIListView::new()).expect("list view");
    list_view.set_create_item_event(Box::new(|tree: &mut NodeTree| { let item_id = tree.create_node("item"); ...; item_id }));
    list_view.set_bind_item_event(Box::new(|tree: &mut NodeTree, item_id: NodeId, item_index: usize| { ... }));
    list_view.set_item_count(500);
  ```
- Differences from the original:
  - set_template_node serializes the template node with UIDocument and clones it per item as in the original. The original records every component through reflection, but
    the Rust version clones only types registered with UIDocument. (for game components, pass a UIDocument with registration done to set_template_node_with_document)
  - It also takes a function that creates item nodes (set_create_item_event). (a general feature that appeared first in the Rust version, also added to the original) Created nodes are moved under the content node as children.
    If the item size is not set (0), it reads the progress axis content_size of the first created item node, like the original reads the template size.
  - The bind event takes (tree, item node, item index). The end notification takes the list view and the context.
  - set_item_count, set_item_size, set_spacing, refresh set the values and update the scroll area and rebind on the next tick.
    (the original does it on the spot. the scroll view on the same node cannot be reached while scene code is holding this widget)
  - Active items are held in insertion order like the original Map.
- [ui/uiprogressview](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiprogressview&lang=en): Progress display. (UIProgressView, ProgressDirection of the original ui/uiprogressview.js)
- Uses the host's content_size area as the track and draws the fill by the value ratio. Takes no input.
- The track color is UIView's background color as in the original. (set_track_color is another name for set_background_color)
- When the opposite value (secondary_value) is set, draws a second fill that fills from the end opposite the progress direction. (the original null is None)
- [ui/uiprogressring](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiprogressring&lang=en): Progress ring. (UIProgressRing of vanilla.js ui/uiprogressring.js)
- A thin line that runs along the node's shape (a rounded rectangle, a circle when the rounding is half the size).
- From the top center clockwise, the filled fraction is drawn in the fill color and the rest in the background color.
- The whole content size of the attached node is the ring's outer shape, and the center of the line sits inside it by half the thickness.
- The perimeter points are recalculated only when the size, rounding, or thickness changes.
- [ui/uiscrollbar](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiscrollbar&lang=en): Scroll bar. (UIScrollBar, ScrollBarAxis of the original ui/uiscrollbar.js)
- Shows the target scroll view's scroll state as a track (background) + thumb (drag handle). Dragging the thumb or track changes the target's offset right away.
- Every tick, reads the target's offset / content size / visible area and fits the thumb position and size.
- Differences from the original:
  - The original UIScrollBar is a node that inherits WorldNode, and creates the track Paint and the thumb node (Paint) under itself.
    The Rust version is a component attached to a node, and draws the track and thumb directly. (holds only the thumb rectangle and its on state, without a thumb node)
    Like the original thumb node, the thumb state starts on with zero size, and the rectangle stays as is while dragging. (get_thumb_rect also starts as a zero-size rectangle like the original getThumbRect)
  - The target is the handle of a node with a UIScrollView attached instead of the scroll view component. (set_scroll_view / get_scroll_view)
  - The track press position and the inside-thumb test use local coordinates converted with the inverse of the node matrix. (the original subtracts the world position. the same without rotation / scale)
- The UI document (UIDocument) writes and reads it in the original node form when registered with register_node_type. (node type "UIScrollBar", track Paint, thumb node, UIDocumentNode in uidocument.rs)
- Usually created by UIScrollView::set_shows_vertical_scroll_bar. To create one directly, attach it with node_tree.add_component. (pivot / anchor at top left, interactable)
- [ui/uiscrollview](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiscrollview&lang=en): Scroll view. (UIScrollView, ScrollMode of the original ui/uiscrollview.js)
- Uses the host's content_size as the visible area and moves the content node by dragging or rolling the wheel. Scroll offset = local position of the content node.
- As in the original, attaches a Mask to the host (require) to clip the content, and turns the host interactable. Attach with node_tree.add_component(node_id, UIScrollView::new()).
- Scroll bars (nodes with UIScrollBar attached) are created as children of the host (siblings of content) as in the original code.
- Wheel: the original TouchRaycaster.touchWheel → UIScrollView.wheel path. The engine asks for wheel from the node under the touch toward its parents, and this component consumes it.
- Differences from the original:
  - The original changes nodes right away in set_scroll_offset / set_scroll_content_size / setShows...ScrollBar. Scene code in the Rust version holds only the component, so
    it sets the values and applies them to the content node and scroll bar nodes on the next tick. To move right away in the same frame, use UIScrollView::set_scroll_offset_in_tree.
  - So get_vertical_scroll_bar / get_horizontal_scroll_bar return a node handle only after the first tick following setting them to show.
    To create and turn on the scroll bar node on the spot as in the original, use UIScrollView::set_shows_vertical_scroll_bar_in_tree (horizontal for horizontal). (returns the created node handle)
  - The visible area size (host content_size) is read on attach and on tick / touch / wheel. An offset set from scene code is reclamped to the new size on the next tick.
  - The gesture that hands a drag over to the scroll view above (the original TouchRecognizer) is separate, in ui/touchrecognizer.rs. The scene chooses to use it.
- A quirk kept from the original: a scroll bar node that turned itself off (auto hide) because the content fits in the area does not tick, so it does not turn back on by itself.
  Calling setShows...ScrollBar(true) again turns it on.
- [ui/uislider](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uislider&lang=en): Slider. (UISlider of the original ui/uislider.js)
- Picks a value by dragging or pressing. Draws the track + fill + thumb (circle) directly. The value is only clamped to the range. (the original has no tick snapping either)
- When a thumb node (set_thumb_node) is set, it does not draw the circle and moves that node to the thumb position.
- Differences from the original:
  - The original moves the thumb node inside draw. The Rust version cannot change the tree while drawing, so it moves it in tick. (the thumb node is kept as a child of the host)
  - Input coordinates are relative to the host's top-left corner as in the original, but converted with the inverse of the node matrix so they follow scale and rotation too. (the original only subtracts the corner position)
  - The value changed event takes the slider and the context. fire_value_changed called from scene code fires the event on the next tick.
    Received events are stored in `Rc<RefCell>`. get_value_changed_event returns that Rc, and the caller borrows it with borrow_mut and calls it.
- attach_to_tree turns the host node interactable. Attach with node_tree.add_component(node_id, UISlider::new()).
- [ui/uisnapscrollview](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uisnapscrollview&lang=en): Snap scroll view. (UISnapScrollView of the original ui/uisnapscrollview.js)
- On drag release, slides so that the center of one content child (item) lands at the center of the visible area. Items may differ in size.
- Horizontal snap: set_horizontal(true), set_vertical(false) (default). Vertical snap: set_horizontal(false), set_vertical(true).
- One drag moves at most one slot. On release, if the drag velocity is at least set_velocity_threshold (default 200, offset pixels per second), it moves one slot in that direction,
  otherwise it moves when the dragged distance is at least the set_page_change_threshold ratio (default 0.35) of the next item's size. While dragging, the offset does not go beyond ±1 slot from the current slot.
- With set_snap_to_nearest(true), the slot range is not clamped while dragging, and on release it goes to the item whose snap offset is closest to the current offset.
- page_to(node_tree, index, smooth): moves to the given slot. If smooth, slides with 0.3 seconds cubic.out, otherwise moves right away.
- The original inherits UIScrollView. The Rust version embeds UIScrollView (scroll_view field) and passes through touch, wheel, drawing, and attaching.
  Scroll view settings are made on the embedded view with get_scroll_view_mut. Commonly used ones (content size, offset, axes) are also on this widget.
  Attach with node_tree.add_component(node_id, UISnapScrollView::new()). (the embedded view creates the content node, Mask, and interactable)
- Differences from the original:
  - Functions that change the slot (page_to, set_snap_current_index, play_snap_tween, etc.) need to read content children, so they take the tree.
    Scene code calls them with node_tree.`with_component_mut::<UISnapScrollView, _>`(snap_id, |snap_view, tree| snap_view.page_to(tree, 2, true)).
  - Instead of the original Tween object, the snap slide does the same calculation (0.3 seconds, cubic.out, first step on the tick it is made) inside this widget.
    (the original tween's update callback calls the scroll view itself, but a Rust tween callback takes only the tree and cannot reach this widget, which is taken out during tick)
  - While sliding, the content node is moved right away within that tick. (so it does not lag a frame, since the embedded view applies on the next tick)
  - In the original, the snap view is also a UIScrollView, so TouchRecognizer, UIScrollBar, UIListView recognize it as is.
    In the Rust version, TouchRecognizer and UIListView recognize it through find_scroll_view. UIScrollBar looks only for the UIScrollView component, so
    a scroll bar cannot be attached to a snap view. (setShows...ScrollBar only puts the value into the embedded view)
- [ui/uispinner](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uispinner&lang=en): Spinning loading indicator. (UISpinner of the original ui/uispinner.js)
- A standard spinner that places several dots around a circle with brightness rotating like a tail. (dot opacity 0.15 ~ 1)
- The original is a node that inherits WorldNode. The Rust version is a component attached to a node (host), and on attach, like the original constructor, it
  sets up the host (center pivot, size = (radius + dot radius) x 2) and creates dot nodes (rounded Paint) as children.
  UISpinner::create(node_tree, parent_id, options) takes the place of the original new UISpinner(options) + add_child.
- Usage:
  ```text
    let spinner_id = UISpinner::create(node_tree, panel_id, UISpinnerOptions { radius: 9.0, dot_count: 10, ..UISpinnerOptions::default() });
    node_tree[spinner_id].set_local_position(Vector2::create(x, y));
  ```
- Differences from the original:
  - set_dot_color sets the color and applies it to the dot nodes on the next tick. (the dot nodes cannot be reached while scene code holds this widget)
  - The phase is wrapped to 0 ~ 1. The tail calculation has a period of 1, so the visible result is the same, and precision does not degrade even after spinning a long time.
  - Dot node names are "SpinnerDot{index}" as in the original. The options object is the UISpinnerOptions struct.
- [ui/uitoast](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uitoast&lang=en): Toast. (UIToast of the original ui/uitoast.js)
- With show(message), a pill-shaped notification rises from below (0.24 seconds), stays a while (default 1.8 seconds), then exits upward and disappears (0.2 seconds).
- Calling it several times queues them and shows them one at a time.
- Place it at the top of the scene root (the last child). If the horizontal position is not set, it stands at the parent's horizontal center. (480 if the parent size is unknown)
- The original is a node that inherits WorldNode, and the node itself is the pill. The Rust version is a component attached to a node (host), and on attach, like the original constructor, it
  sets up the host (center pivot, size) and attaches Paint (rounded pill) and UILabel to the host. UIToast::create(node_tree, parent_id, options) takes the place of new + add_child.
- Usage:
  ```text
    let toast_id = UIToast::create(node_tree, root_id, UIToastOptions::default());
    node_tree[toast_id].get_component_mut::<UIToast>().unwrap().show("Saved.");
  ```
- Differences from the original:
  - show only puts it in the queue, and the next tick takes it out and shows it. (the first step also happens on the same tick, so the timing is the same as the original)
    So while the original calls set_active(false) when hiding, the Rust version needs tick to run, so it hides with set_visible(false).
    The UI document writes and reads a hidden toast as active false, as in the original. (UIDocumentNode in uidocument.rs)
  - The appear / stay / exit times and curves are counted inside here exactly as in the original. (Tween is not used)
  - The horizontal position rest_x is `Option<f64>`. (original null = parent center) The options object is the UIToastOptions struct.
- [ui/uitogglebutton](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uitogglebutton&lang=en): Toggle button. (UIToggleButton of the original ui/uitogglebutton.js)
- Each click switches on / off. While on, the pressed tint stays fully applied.
- The original inherits UIButton and hooks its own click handling onto super.set_clicked_event. The Rust version embeds UIButton, and
  flips the on state when the embedded button reports a click (the return value of release handling).
  So the order differs slightly: the original is release → [flip, toggle event, clicked event] → click event, and the Rust version is release → click event → [flip, toggle event, clicked event].
- Toggle / clicked events take the toggle button and the context. Other button events and settings are made on the embedded button with get_uibutton_mut.
  Received events are stored in `Rc<RefCell>`. get_toggled_event returns that Rc, and the caller borrows it with borrow_mut and calls it.
  get_clicked_event returns the toggle button's inner click handling function, like the original (getClickedEvent inherited from UIButton).
  Calling it flips the on state and calls the toggle event and the clicked event. (it is not the function set with set_clicked_event)
- The tint for set_is_on is applied on the next tick. (for the same reason as UIButton.set_interactable)
- [ui/uiview](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiview&lang=en): View component. (UIView of the original ui/uiview.js)
- The base of all UI widgets. When attached to a node (host), creates a "content" child node under the host. (top-left pivot, anchor 0,0, position 0,0)
- If the background color's alpha is greater than 0, paints the host's content_size area with that color.
- In the original, widgets like UILabel and UIButton inherit UIView. In the Rust version, widgets embed UIView (ui_view field) and pass through content and the background color.
  So the original usage of finding subclass widgets at once with node.get_component(UIView) does not exist. (look them up by concrete type, like `get_component::<UIButton>()`)
- The content node is created in attach_to_tree. It must be attached with node_tree.add_component(node_id, UIView::new()).
- The original setEngine / get_engine were not ported. The engine is obtained with ComponentContext::get_engine during tick / touch.
- The original setBackgroundColor(null) clears the background. (returns to the initial value, white with alpha 0) The Rust version has no None, so give a color with alpha 0 (the initial value or Color::transparent()).
- [ui/uidocument](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uidocument&lang=en): UI document. (UIDocument of vanilla.js ui/uidocument.js)
- Exports and reads a node tree as a JSON document (.scene.json). The vanilla.js visual editor (tools/visualeditor) saves scenes in this form, and
  games read the same file and build nodes and components in a NodeTree. Trees built in Rust are exported in the same form too.
- A document is { "version": 1, "root": node }, and a node has type, name, active, position, scale, rotation, opacity, pivot, anchor,
  contentSize, interactable, components, children. If there is a widget (a component that creates a content node), only the children inside content are kept separately as contentChildren.
  Unknown keys added by the editor, like frameSize, are ignored. Key order and indentation (tabs) are written the same as the original JSON.stringify. (serde_json preserve_order)
- Differences from the original:
  - The original is a static class and module global tables. The Rust version creates and uses a UIDocument value that holds the tables. (no global state, like the engine) new registers the engine components.
  - As in the original, types without write and read functions (propertyHandler of the original COMPONENT_PROPERTY_TABLE) are written and read through reflection. (saveByReflection, loadByReflection)
    The original scans an object's get, is, set functions at run time, while the Rust version uses the list built at compile time by the `#[reflect]` macro. (core/reflection.rs)
    The only types handled through reflection are components with `#[reflect]` attached. (attached to every engine component) In the original, every object is reflected.
    Outline, SoftShade, ShadowText, UIProgressRing, which the original table saves through reflection, are also written and read through reflection. Same keys as the original reflection result (capitalized: Color, LineWidth,
    GizmoVisible, Enable, ComponentType, etc.) and order. FontFace of the original ShadowText is a font object, so it is not written. The Rust version's font name text (get_font_family)
    is kept in the property list but left out of saving with `#[reflect(unsaved)]`.
  - Reflection setters that take the tree (like SnapCurrentIndex of UISnapScrollView) are also called on the spot while reading, as in the original. The component being read is briefly taken out of the tree and the read context is handed the tree.
  - Components with &mut self getters are also read ahead through the &mut branch and written by to_json_text and serialize_node. (the original getters make no &self, &mut self distinction, so like the original toJsonText and serializeNode they are single functions. The tree is taken as mutable)
  - Type registration: register_component_type(name, builder function) is the original registerComponentType. (written and read through reflection) Types with their own write and read functions
    are registered with register_component_type_with_handler, and widgets (components that create a content node) with register_widget_type, register_widget_type_with_handler.
  - Unregistered types are skipped when reading (node types are read as WorldNode) with a warning, as in the original. When writing, type is the registered name as in the original, and unregistered types are written by reflection with the type name as type. (the original constructor.name)
    Like the original, every component is reflected. (Reflect is a supertrait of Component, so a component without `#[reflect]` does not compile)
  - Even for types with write and read functions, reflection properties that point to nodes are added and read separately as { "$nodeRef": path }, as in the original. (saveNodeReferences, loadNodeReferences)
  - ShadowImage is also added at the end of the original table in the same form (the reflection save form after imagePath), so both engines are the same.
  - The original UIImageView attaches a Sprite to the host on attach, so the document has a Sprite after UIImageView. The Rust version embeds the Sprite, so it writes the embedded Sprite there as a Sprite and
    when reading, it reads the following Sprite into the embedded Sprite. (set_component_companions, the original reads into the Sprite that UIImageView attached when it was attached)
  - Original node types (WorldNode subclasses, registerNodeType) are components attached to nodes in the Rust version. Registered with register_node_type, they are written and read in the same form as the original document:
    the type of a node with that component attached is that name, and it is not listed in the component list.
    - Types that actually build children and components on attach like the original node constructor (UIWindow, UIConfirmWindow, UIDialog, UIDropdown, UIToast, UISpinner, UIContextMenu, etc.)
      have what they built written as is.
    - For self-drawing types (UIInputField, UIScrollBar), UIDocumentNode writes the original constructor's share in the original form, and reads that share back as settings.
    - The original turns the node off when hiding, but for types that only hide because tick must keep running in the Rust version (UIToast), UIDocumentNode converts active to the original meaning when writing and reading.
  - When reading, components and children already on the node (built when a node type or widget was attached, or attached together through require) are matched from the front of the document by order and type (name for children), and if they match,
    the document values are put into them without building them again. (same as the original fillNode) Writing again gives the same document.
  - The original editor (tools/uieditor) registers every Component and WorldNode subclass the engine exports and writes them to documents. As in the original, they are not in the default table, and
    the game registers the same types (35 components, 12 node types) with one line, register_editor_types (the original registerEditorTypes). (one line per type also works)
  - Nodes in the Rust version are just WorldNode. The type of a node without a component registered as a node type is always written as "WorldNode", and unregistered types are read as WorldNode.
  - The original getComponentType (name → constructor) cannot return a constructor as a value (the node tree attaches by concrete type), so create_component(tree, node, name)
    builds the component of that name, attaches it to the node, and returns the component order index. (in place of taking a constructor and calling addComponent in the original)
  - The image path (imagePath) is resolved with the image resolver (set_image_resolver) as in the original. Without a resolver, it is looked up in the asset store the document holds.
    load_images requests the document's imagePath values as ImageAsset (the scene can hand over the received load handles with track_load_handle),
    and images not loaded yet are attached by bind_pending_images once fully loaded. (Rust assets finish loading some time after the request)
  - The base root of node references ($nodeRef) is the root of to_json_text, from_json_text. When serialize_node, deserialize_node are called directly, that node is the root.
    (in the original, calling only serializeNode does not write references, and calling only deserializeNode does not connect them)
  - Numbers are written as the shortest decimal of f64. (0.22 as 0.22, integers without a decimal point, the same as the original JSON.stringify)
- Sprite nineSlice is read by reversing the form the original writes ([left, top, left + right, top + bottom], Rect's left, top, right, bottom), as in the original.
- [ui/uiscale](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiscale&lang=en): UI scale. (vanilla.js ui/uiscale.js, UIScale)
- The fixed side of the view (height for portrait, width for landscape) always has the same length, so on a small screen (a portal's PC iframe, etc.)
  one view unit becomes much smaller than 1 CSS pixel on screen and text becomes unreadable. In that case it computes a scale that enlarges only the UI layer on screen. (the game's graphics stay as they are)
- If one unit is smaller than minimum_css_scale CSS pixels, it enlarges by that much. (1 ~ maximum_scale)
  - On a short screen, it does not enlarge so far that the enlarged UI layer's height falls below minimum_layer_height. (0 means not checked)
  - On a portrait screen (width at most portrait_ratio times the height), it enlarges without an upper limit so that one unit becomes minimum_css_scale CSS pixels.
- Differences from the original:
  - It takes the CSS pixels of one unit (ViewManager::get_css_pixel_scale) as an argument. (the original reads it from the engine if options.cssPixelScale is absent)
  - The options object is the UIScaleOptions struct.
- Usage: let ui_scale = UIScale::read(view_width, view_height, view_manager.get_css_pixel_scale(), &UIScaleOptions::default());
- [ui/uiwindow](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiwindow&lang=en): A single window in the window stack. (vanilla.js ui/uiwindow.js, UIWindow)
- Dims the whole area (presses do not pass through to what is behind) and shows a panel in the center. The dim also covers the safe area (set_view_bleed).
- The panel widens to fit the area's width but does not exceed maximum_width. Its height is the value returned by layout_content, and if it is larger than the area the whole panel is scaled down.
- The open and close motion is PopupMotion. When the close motion finishes, the window layer (UIWindowLayer) removes the node. (it does not receive presses in the meantime)
- Pressing outside (the dim) closes it. Turned off per window with set_outside_close_enabled. The window layer's close_top_window (back) also follows this value.
- Node structure: window (area size) ├ dim (Paint + UIButton) └ frame (panel center pivot, motion scale) └ panel (a single Paint, content goes here)
- Differences from the original:
  - In the original it is a node inheriting WorldNode, and derived classes override layoutContent, layoutPanel, applyMotion, setCovered, handleWheel, dispose.
    The Rust version is a component attached to the window node, and the override points are the UIWindowBehavior trait. (the default implementation is UIWindowDefaultBehavior,
    and an override that wants to call the default like the original super uses UIWindow::layout_panel_default, apply_motion_default, set_covered_default)
    The panel look (shadow, border, gloss) is done by the game attaching decoration nodes to the frame in build (set_sibling_index(0) for behind the panel) and placing them in layout_panel.
  - The window node is created under the window layer node with UIWindow::create(node_tree, layer_id, name, behavior). When the close motion finishes, it is detached from the layer and not removed, so
    the same window node can be opened again as in the original. (UIWindowLayer::open_window) The original window attaches to the layer when opened, so create keeps the node off until it is opened.
    When attached, it does not turn the node off as the original constructor does. (so the UI document reads and writes the window node as active, as in the original)
  - Closing goes through the window layer. Scene and callback code calls UIWindow::close_in_tree(node_tree, window_id).
  - The notification (set_close_event) is an argumentless `Box<dyn FnMut()>`. (same form as the PopupMotion notification, node changes are done by the scene checking the state in tick)
  - As in the original, GameSceneBase passes wheel input pointing inside the window layer to UIWindowLayer::scroll_window_at so the top window (UIWindowBehavior::handle_wheel) gets it first,
    and if it does not take it, the scroll view at that spot does. Wheel input that reaches a window through the engine's wheel delivery (from the pointed node toward the parents) without going through GameSceneBase is also taken by the window and always swallowed.
  - The panel and dim Paints are components of nodes, so get_panel_paint and get_dim_paint take the tree.
- [ui/uiwindowlayer](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiwindowlayer&lang=en): Window layer. (vanilla.js ui/uiwindowlayer.js, UIWindowLayer)
- Stacks UIWindows over the area. Opening a window stacks it on top, and only the top window is visible. When the upper window closes, the window below becomes visible again.
- On close it leaves the list right away so presses and covering are released immediately, and after the close motion (PopupMotion) finishes the window node is detached from the layer. Closing a covered window detaches it right away.
  The detached window node is not removed, so it can be opened again with open_window. (same as the original) The scene removes windows it will not reuse with destroy_node.
- The top window gets the wheel first (UIWindowBehavior::handle_wheel), and if it does not take it, the scroll view at that spot does. (scroll_window_at, GameSceneBase passes wheel input pointing inside the window layer)
- This layer is enlarged by the UI scale (UIScale::read), and windows are told the area size and safe area widths divided by that much. (so text is readable even on small screens)
  With set_ui_scale_options(None), it does not enlarge.
- While even one window is open, play is suspended. It notifies when windows open and close (set_window_change_event, passes the number of open windows). The scene may check has_open_window and pause play.
- Usage: (placed as the top child of the area node, notified whenever the area size changes)
  ```text
    let layer_id = UIWindowLayer::create(node_tree, play_area_id);
    node_tree.with_component_mut::<UIWindowLayer, _>(layer_id, |layer, tree| {
        layer.set_view_size(tree, width, height, view_manager.get_css_pixel_scale());
        layer.set_view_bleed(tree, top, right, bottom, left);
    });
    let window_id = UIConfirmWindow::create(node_tree, layer_id, "quit", UIConfirmWindowOptions { title: ..., ..UIConfirmWindowOptions::default() });
    UIWindowLayer::open_window_in_tree(node_tree, layer_id, window_id);
  ```
- Differences from the original:
  - In the original it is a node inheriting WorldNode. The Rust version is a component attached to the layer node, and windows are child nodes of that node. Functions that change things take the tree.
  - The original reopens a detached window object if it is held. In the Rust version the detached node remains in the tree storage, so it is reopened with that handle.
    In the original a window held by no one is cleaned up by the garbage collector, but in the Rust version the scene removes it or it is removed together when the scene ends.
  - In the original the layer asks UIScale for the engine's CSS scale. In the Rust version set_view_size takes the CSS scale (ViewManager::get_css_pixel_scale).
  - The window notification is `Box<dyn FnMut(usize)>`. (number of open windows)
- [ui/uiconfirmwindow](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiconfirmwindow&lang=en): Confirm window. (vanilla.js ui/uiconfirmwindow.js, UIConfirmWindow)
- A title, a question text, and two buttons, cancel and confirm. It is a UIWindow, so it is opened with UIWindowLayer.
- The question text wraps at the panel width, and the panel height is set to fit the number of lines. If the text is long and exceeds the area height, only the text area scrolls and the two buttons are always visible.
- The buttons are cancel on the left and confirm (highlighted) on the right. For right-to-left languages (set_right_to_left), the order is reversed.
- Pressing confirm closes it after the confirm notification. Closing by cancel, outside press, close_top_window, or close_all_windows gives the cancel notification.
- Usage:
  ```text
    let window_id = UIConfirmWindow::create(node_tree, layer_id, "quit", UIConfirmWindowOptions { title: String::from("Leave"), message: String::from("Really leave?"), ..UIConfirmWindowOptions::default() });
    if let Some(confirm_window) = node_tree[window_id].get_component_mut::<UIWindow>().and_then(|window| window.get_behavior_mut::<UIConfirmWindow>()) {
        confirm_window.set_confirm_event(Some(Box::new(move || { leave_requested.set(true); })));
    }
    UIWindowLayer::open_window_in_tree(node_tree, layer_id, window_id);
  ```
- Differences from the original:
  - The original inherits UIWindow. The Rust version is a value implementing UIWindow's override points (UIWindowBehavior). (taken out with UIWindow::get_behavior_mut)
  - The number of text lines is measured right at layout as in the original. Since there is no Graphic there, it measures with the registered fonts. (wrap_lines_without_graphic of the Text that UILabel holds)
    Only when it cannot measure because there are no fonts at all (no font files on desktop), it lays out as one line, and once the text is drawn and wraps, it lays out again on the next tick.
  - The title and question text are UILabels as in the original. For right-to-left languages, as in the original, it sets the Rtl direction on both texts (Inherit otherwise) and reverses the button order.
    set_right_to_left does not take the window node, so the text direction is applied at the next layout. To apply the text direction right away as in the original, call set_right_to_left_in_tree. (the button order is at the next layout in the original too)
  - The notification is an argumentless `Box<dyn FnMut()>`.
- [ui/autolayout](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout&lang=en): Auto layout. (the original ui/autolayout, a Cassowary constraint solver based on Kiwi dual simplex)
- layoutvariable: unknowns the solver solves (handles that share the value)
- layoutterm, layoutexpression: coefficient * variable terms and linear expressions
- layoutconstraint, layoutrelation, layoutstrength, layoutpriority: constraints and relations, strengths, UIKit style priorities
- layoutconstraintaxis: horizontal and vertical axes (used by UINode's hugging and compression resistance priorities)
- layoutsymbol, layoutsymboltype, layoutrow: symbols and tableau rows inside the solver
- layoutsolver: the constraint solver (a handle shared by many nodes)
- Unlike the original, numbers are f64, and solver functions where the original throws return `Result<(), LayoutError>`.
- [ui/autolayout/layoutconstraint](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutconstraint&lang=en): Layout constraint. (LayoutConstraint of the original ui/autolayout/layoutconstraint.js)
- Form: expression { ==, <=, >= } 0
- Usually created by LayoutExpression's equal_to, less_than_or_equal_to, greater_than_or_equal_to.
- Strength is the priority on conflict. Clamped to 0 ~ REQUIRED at creation.
- Differences from the original:
  - The original tells constraints registered in the solver apart by object identity. The Rust version is a cheap Clone handle holding an Rc, so
    cloned handles are the same constraint, and equality and hashing go by the constraint the handle points to. (created separately, they are different constraints even with the same expression)
  - strength, which could be omitted (default REQUIRED), is required.
- [ui/autolayout/layoutconstraintaxis](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutconstraintaxis&lang=en): Layout constraint axis. (LayoutConstraintAxis of the original ui/autolayout/layoutconstraintaxis.js, same concept as UIKit's NSLayoutConstraint.Axis)
- Horizontal: horizontal axis. Constraints related to width, left, right, centerX.
- Vertical: vertical axis. Constraints related to height, top, bottom, centerY.
- The original is a frozen object holding string values ("horizontal", "vertical"). The Rust version is an enum.
- [ui/autolayout/layoutexpression](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutexpression&lang=en): Linear expression. (LayoutExpression of the original ui/autolayout/layoutexpression.js, term list + constant)
- All arithmetic functions return a new expression. (immutable value)
- equal_to, less_than_or_equal_to, greater_than_or_equal_to return a LayoutConstraint. (required strength)
- Arguments take numbers (f64, i32), LayoutVariable, LayoutTerm, LayoutExpression. (impl `Into<LayoutExpression>`)
- Differences from the original:
  - The runtime type check of the original toExpression moved into From implementations. Unaccepted types are stopped at compile time.
  - multiply and divide take only f64, since the original also takes only numbers. (the original's 'scalars only' exception does not occur)
  - Division by zero is a programming mistake, so it panics with the same message as the original.
  - The original uses a late loading trick to avoid importing each other with LayoutConstraint. The Rust version just uses use.
- [ui/autolayout/layoutpriority](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutpriority&lang=en): Layout priority. (LayoutPriority of the original ui/autolayout/layoutpriority.js, same concept as UIKit's UILayoutPriority)
- REQUIRED (1000): priority that must be satisfied. Becomes LayoutStrength::REQUIRED.
- DEFAULT_HIGH (750): default compression resistance (compression resistance) priority.
- DEFAULT_LOW (250): default hug priority.
- FITTING_SIZE_LEVEL (50): recommended size priority when computing the fitting size.
- Values of 1 ~ 999 become a medium tier strength through LayoutStrength::from_priority.
- The original's static fields are associated constants. The values are f64.
- [ui/autolayout/layoutrelation](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutrelation&lang=en): Constraint relation operator. (LayoutRelation of the original ui/autolayout/layoutrelation.js)
- Tells whether a LayoutConstraint is expression == 0, <= 0 or >= 0.
- The original is an object holding string values ("==", "<=", ">="). The Rust version is an enum.
- [ui/autolayout/layoutrow](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutrow&lang=en): A row inside the solver. (LayoutRow of the original ui/autolayout/layoutrow.js)
- One row of the tableau. Cells (symbol -> coefficient) and a constant.
- All functions that change it change it in place.
- Differences from the original:
  - Cells are a LayoutSymbolMap that keeps insertion order like the original Map.
  - The original copy() is Clone. (a copy identical down to the order)
  - coefficient, which could be omitted (default 1), is required.
  - The near-zero check that the original kept separately in the row and the solver is shared as a single near_zero.
- [ui/autolayout/layoutsolver](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutsolver&lang=en): Constraint solver. (LayoutSolver of the original ui/autolayout/layoutsolver.js, based on Kiwi dual simplex)
- Usage:
  let solver = LayoutSolver::new();
  let x = LayoutVariable::new("x");
  let y = LayoutVariable::new("y");
  solver.add_constraint(&LayoutExpression::from_variable(&x).equal_to(10))?;
  solver.add_constraint(&LayoutExpression::from_variable(&y).equal_to(LayoutExpression::from_variable(&x).add(20)))?;
  solver.update_variables();
  x.get_value(); // 10
  y.get_value(); // 30
- Dynamic input (drag, etc):
  solver.add_edit_variable(&x, LayoutStrength::STRONG)?;
  solver.suggest_value(&x, 50.0)?;
  solver.update_variables();
- Differences from the original:
  - In the original, several UINodes and UIScenes share one object. The Rust version is a cheap Clone handle holding an `Rc<RefCell>`, and all functions take &self.
  - Where the original throws exceptions (duplicate constraints, unsatisfiable required constraints, unknown constraints and edit variables, required edit strength,
    internal solver failures), it returns `Result<(), LayoutError>`. The messages are the same as the original, except the long dashes were changed to colons.
  - Among the original's Maps, the row map, whose order changes which symbol is chosen, is a LayoutSymbolMap that keeps insertion order.
    The constraint, variable and edit variable maps, which do not depend on order, are HashMaps.
  - The null symbol of the original LayoutTag is the invalid symbol (LayoutSymbol::invalid). (same as Kiwi)
- [ui/autolayout/layoutstrength](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutstrength&lang=en): Layout constraint strength. (LayoutStrength of the original ui/autolayout/layoutstrength.js)
- The Cassowary, Kiwi standard strength system. Decides which side to keep first when constraints conflict.
- REQUIRED must be kept, and an error is returned if the solver cannot solve it.
- STRONG, MEDIUM, WEAK are kept as much as possible, but yield in order of strength on conflict.
- Strengths are composed with create_strength(a, b, c, weight).
- The original's static fields are associated constants, and its static functions are associated functions. weight, which could be omitted, is taken as an Option.
- [ui/autolayout/layoutsymbol](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutsymbol&lang=en): A symbol inside the solver. (LayoutSymbol of the original ui/autolayout/layoutsymbol.js)
- Points to rows and columns of the tableau. Numbers are assigned globally, increasing by one, and equality and hashing go by number.
- Differences from the original:
  - The original is an object, so Map keys use object identity. The Rust version is a Copy value holding a number and a kind, and is told apart by number.
  - Invalid symbols share the single number 0. (the original assigns a new number on every invalid(). Invalid symbols are not used as keys, so the result is the same)
  - The original setType is unused and would mean something different on a Copy value, so it was not ported.
  - LayoutSymbolMap is an addition in the Rust version. It keeps insertion order like the Maps the original uses for rows and cells.
    (removing and reinserting moves a key to the end, changing the value of an existing key keeps its place) The order in which the solver walks cells and rows
    decides which symbol is chosen, so it walks in the same order as the original.
- [ui/autolayout/layoutsymboltype](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutsymboltype&lang=en): Symbol kind inside the solver. (LayoutSymbolType of the original ui/autolayout/layoutsymboltype.js)
- Invalid: an undetermined invalid symbol.
- External: a symbol corresponding one to one with each user LayoutVariable.
- Slack: a slack variable added when turning an inequality constraint into an equality.
- Error: an error variable representing how far a non-required constraint is off.
- Dummy: a marker variable attached to a required equality constraint and looked up when removing it.
- The original is an object holding number values (0 ~ 4). The Rust version is an enum with the same values assigned.
- [ui/autolayout/layoutterm](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutterm&lang=en): One term of an expression. (LayoutTerm of the original ui/autolayout/layoutterm.js, coefficient * variable)
- A value making up a LayoutExpression. It does not change.
- Differences from the original:
  - The original can be created without a variable (null, value 0) and the solver skips such terms. The Rust version always takes a variable, so there are no such terms.
  - coefficient, which could be omitted (default 1), is required.
- [ui/autolayout/layoutvariable](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/autolayout/layoutvariable&lang=en): Layout solver unknown. (LayoutVariable of the original ui/autolayout/layoutvariable.js)
- A variable user code uses in expressions. After the solver solves, calling update_variables puts the result in via set_value.
- Differences from the original:
  - In the original, several places (nodes, expressions, the solver) point to one object. The Rust version is a cheap Clone handle holding an Rc, so
    cloned handles see the same name and value. Equality and hashing go by the variable the handle points to, like the original's object identity.
  - get_id, which the original lacks, reads the unique number assigned to each variable.
  - The name and value are kept in RefCell and Cell so they change through &self.
- [ui/uinode](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uinode&lang=en): UI node. (UINode of the original ui/uinode.js)
- Represents its area with 8 solver variables (left, right, top, bottom, width, height, derived center_x, center_y), and the user adds constraints to a LayoutSolver
  to determine those values. It registers the 4 intrinsic constraints (right == left + width, bottom == top + height, center_x == left + width / 2, center_y == top + height / 2) itself.
- User constraints are registered with add_constraint. The solver is attached with set_solver. (UISceneBase attaches the scene's solver to the UINodes in the tree by itself)
- intrinsic content size, content hugging, compression resistance, layout margins, layout margins guide are the same concepts as UIKit's APIs of the same names.
- Solver variables (left, top) are absolute positions in the coordinate system where the UI tree root is placed. If the parent is also a UINode, the child is placed offset by (left - parent left, top - parent top).
  Rotation, scale and opacity use the node's own as is.
- Usage:
  ```text
    let node_id = node_tree.create_child(parent_id, "title");
    node_tree.add_component(node_id, UINode::new());
    node_tree.with_component_mut::<UINode, _>(node_id, |ui_node, _tree| {
        ui_node.add_constraint(&ui_node.left_anchor().equal_to(screen_node.left_anchor().add(16))).unwrap();
    });
  ```
- Differences from the original:
  - In the original it is a separate node inheriting TransformNode and moves to the solver values in pushTransform. In the Rust version the only node is WorldNode, so
    it is a component attached to WorldNode, and moves the solver values to the node's position (local_position, with pivot and anchor at the top left) and content_size.
    The moves happen in the component tick and in apply_layout_in_tree (called by UISceneBase right after solving). The original reads them on every draw.
  - The original getIntrinsicContentSize gathers the values of the node's components that have that function (Text, RichText). The Rust version gathers Component::get_intrinsic_content_size.
    The original UILabel calls the node's invalidateIntrinsicContentSize when the text changes. Components in the Rust version cannot call the node's other components, so
    UINode reads the components' values again every tick (and on UISceneBase's solver attaching) and invalidates by itself if they changed.
  - Where the original throws exceptions (duplicate constraints in the solver, unsatisfiable required constraints), it returns `Result<(), LayoutError>`.
    (add_constraint, remove_constraint, set_solver, set_layout_margins, invalidate_intrinsic_content_size)
  - Anchors are functions (left_anchor) instead of the original's getter properties (leftAnchor). The axis argument is the LayoutConstraintAxis enum instead of a string, so there is no "unsupported axis" exception.
  - The layout margins guide is a UINode not in the tree, as in the original. In the Rust version this UINode holds it in a Box.
- [ui/uiscene](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/ui/uiscene&lang=en): UI scene. (UIScene of the original ui/uiscene.js)
- A scene with the same common frame as GameScene (developer tools, touch routing, loading screen, safe area insets, view size change detection, canvas background fill).
- Holds its own LayoutSolver, and every tick attaches the solver to the UINodes in the tree (attach_pending_in_tree), solves once, then moves the values onto the nodes.
- Screen guide UINode (screen_node): top left fixed at (0, 0), width and height are edit variables corrected with suggest_value when the size changes. (UIKit's UIWindow.bounds)
- Safe area guide UINode (safe_area_layout_guide): inset from the screen guide by the safe area insets. It adjusts the insets by itself at layout.
  (UIKit's UIView.safeAreaLayoutGuide)
- In the Rust version, instead of inheritance, the scene holds a UISceneBase, implements the UIScene trait, then gets a Scene with one line of ui_scene!. (same form as GameScene, game_scene!)
  ```text
    struct MenuScene { ui_scene_base: UISceneBase }
    impl UIScene for MenuScene {
        fn get_ui_scene_base(&self) -> &UISceneBase { &self.ui_scene_base }
        fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase { &mut self.ui_scene_base }
        fn initialize(&mut self, engine: &Engine) { /* create nodes with UINode attached and add constraints with the get_safe_area_layout_guide anchors */ }
    }
    vanilla::ui_scene!(MenuScene);
  ```
- Differences from the original:
  - The original inherits Scene directly and carries the same code as GameScene separately. The Rust version holds the common frame as a GameSceneBase (without creating the safe area node)
    and adds only the solver and the two guides. So GameSceneBase's screen fade and play input can also be used. (not in the original UIScene)
  - The original creates the solver and guides in create. The Rust version does not need the engine, so it creates them at construction. The "apply the view size to the solver right away" at the end of the original load is done in initialize.
  - The safe area insets are LayoutMargins instead of a { top, left, bottom, right } object. Solver errors are returned as `Result<(), LayoutError>`.
- [web](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/web&lang=en): Web communication and web screen tools. (original src/web)
- pane.js (split panes) is built from DOM elements on the web like the original, and from engine nodes on desktop. (web/pane.rs)
- [web/websocketclient](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/web/websocketclient&lang=en): WebSocket communication handler. (a client that exchanges JSON)
- A port of the original web/websocketclient.js. Follows connect / disconnect / send(JSON) / is_connected / set_receive_event.
- The socket is ewebsock 0.8. Desktop uses a thread running tungstenite, the web (wasm) uses the browser WebSocket.
- In the original the browser calls onopen / onmessage / onclose. In the Rust version the scene calls tick every frame to take out the accumulated events.
  The read JSON is passed to receive_message as in the original. (the caller can also put it in directly)
  ```text
    // scene create
    self.web_socket_client.connect("ws://localhost:8080");
    // scene tick
    self.web_socket_client.tick();
    for message in self.web_socket_client.take_received_messages() { ... }
    self.web_socket_client.send(&serde_json::json!({ "type": "move", "x": 3 }));
  ```
- Differences from the original:
  - Received JSON calls the receive callback if there is one, otherwise it is collected and taken out with take_received_messages. (also added to the original, up to RECEIVED_MESSAGE_LIMIT, the oldest are dropped first on overflow)
  - disconnect, as in the original, only requests the close on the spot, and the disconnection counts from the next tick. (in the original onclose comes later, so is_connected stays true until then.
    ewebsock desktop does not send a Closed event when closed from this side, so it disconnects after taking out the remaining events in that tick)
  - Error events are notified as in the original and counted as disconnected. (the browser always sends onclose after onerror, and the ewebsock desktop thread ends after an error)
  - get_web_socket is ewebsock's sender (WsSender).
  - The receive callback is kept in an `Rc<RefCell>`. get_receive_event returns that Rc, and the caller borrows it with borrow_mut to call it.
  - wss:// on desktop is opened with ewebsock's "tls" feature (tungstenite's rustls and webpki root certificates). The rustls crypto provider is ring and is set on the first connection.
    Only with the engine's tls feature (on by default). If it is off, desktop opens only ws://.
  - Binary messages are also received if they are UTF-8 JSON. (also added to the original)
- [web/pane](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/web/pane&lang=en): Screen split pane. (PaneTheme, PaneStyle, Pane of the original web/pane.js)
- The original builds the window layout of tools (such as the particle editor) with the DOM. Panes split horizontally or vertically, fixed, ratio and flex sizes, minimum and maximum, resizers that change size by dragging,
  hiding, clearing dragged sizes, layout callbacks, and PaneStyle presets (panel, toolbar, button, input, textarea, text) that build elements with the same theme colors.
- The web builds them with DOM elements as in the original. (pane/dompane.rs)
- Desktop has no DOM, so engine nodes do the same work. Containers are nodes and contents are their child nodes. Resizers are draggable nodes drawn with theme colors. (pane/nodepane.rs)
- Size calculation (calculate_pane_layout) and drag calculation (calculate_resized_size) use the same functions on both platforms. (the original updateLayout, onMouseMove)
- Differences from the original:
  - PaneTheme is associated constants that flatten the original groups (color, size, font) with name prefixes. (PaneTheme.color.background → PaneTheme::COLOR_BACKGROUND,
    PaneTheme.size.resizer → PaneTheme::SIZE_RESIZER, PaneTheme.font.sizeSmall → PaneTheme::FONT_SIZE_SMALL)
    Abbreviated names were spelled out. (color.inputBg → COLOR_INPUT_BACKGROUND, font.mono → FONT_MONOSPACE) SIZE_RESIZER is a pixel count (f64).
  - Pane options are PaneOptions. Sizes are PaneSize. (Flex, Fixed(pixels), Ratio(0~1 ratio))
    The original reads a single number: 0 or "flex" as flex, 1 or less as a ratio, above 1 as pixels. ("50%" is Ratio(0.5)) So get_initial_size returns a PaneSize.
  - PaneStyle::create options are PaneStyleOptions. Empty strings are not applied, like empty values in the original. The original options.type is element_type. (type is a Rust reserved word)
- [web/pane/dompane](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/web/pane/dompane&lang=en): DOM screen split pane. (the web version porting PaneStyle and Pane of the original web/pane.js to the DOM as is, common types and calculations in web/pane.rs)
  ```text
    let main_pane = Pane::new(PaneOptions { direction: PaneDirection::Horizontal, ..Default::default() });
    let left_pane = Pane::new(PaneOptions { size: PaneSize::Fixed(240.0), min_size: 170.0, ..Default::default() });
    let view_pane = Pane::new(PaneOptions { min_size: 200.0, ..Default::default() });
    main_pane.add_pane(&left_pane);
    main_pane.add_pane(&view_pane);
    left_pane.get_container().append_child(&PaneStyle::create("div", "panel", &PaneStyleOptions::default()));
    main_pane.attach_to(&body);
  ```
- Differences from the original:
  - PaneStyle::apply styles are a list of (CSS property name, value). Names are CSS names (background-color), not the original object keys (backgroundColor).
    (Rust has no Object.assign, so they are set with style.setProperty)
    If the tag name is invalid, it stops on the spot as in the original. (an exception in the original, a panic in the Rust version)
  - Pane is a handle that shares its state as `Rc<RefCell>`. clone points to the same pane. Children point to their parent with Weak.
    The window resize listener added by attach_to holds the root pane until the end. (same as the original) Panes that were not attach_to'd are freed when all handles are dropped, and dragging their resizers does nothing.
  - The resizer thickness is written to the data-thickness attribute as in the original, but calculations use the value held on the Rust side.
  - Listeners are wasm-bindgen Closures. Those attached to elements are handed to the JS garbage collector with into_js_value, and the element is read from the event's currentTarget.
    (holding the element would make the Rust side keep it alive, so it would not be freed even when removed from the DOM)
  - set_callback can be cleared with None. Calling into the pane again inside the callback is fine. (it is taken out while being called and put back afterward)
- [web/pane/nodepane](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/web/pane/nodepane&lang=en): Engine node split panes. (PaneStyle and Pane of the original web/pane.js built from nodes on desktop, shared types and math in web/pane.rs)
- Nodes take the place of the original DOM elements. The container is a node (get_container), and content is attached as its children with node_tree.add_child. (original appendChild)
  Desktop has no global document, so functions that create and change nodes take a NodeTree. The length unit is node coordinates, in place of the original CSS pixels.
  ```text
    let main_pane = Pane::new(node_tree, PaneOptions { direction: PaneDirection::Horizontal, ..Default::default() });
    let left_pane = Pane::new(node_tree, PaneOptions { size: PaneSize::Fixed(240.0), min_size: 170.0, ..Default::default() });
    main_pane.add_pane(node_tree, &left_pane);
    let panel_id = PaneStyle::create(node_tree, "div", "panel", &PaneStyleOptions::default());
    node_tree.add_child(left_pane.get_container(), panel_id);
    main_pane.attach_to(node_tree, root_id);
  ```
- Like the original, the container paints its background with COLOR_BACKGROUND and clips overflowing children. (overflow: hidden, Mask)
- Like the original, a resizer is 5 thick if draggable and otherwise a line of 1, painted with COLOR_RESIZER, and with COLOR_RESIZER_HOVER while hovered or dragged.
  Pressing and dragging keeps the gap between the grabbed point and the boundary, changes the fixed size of the previous or next child, and lays out again from the root. The cursor is col-resize, row-resize while hovered or dragged.
- A root pane given to attach_to lays out again when the parent node size changes. (original window resize listener and refresh on the next frame)
- PaneStyle::create builds nodes shaped like the original presets. (PaneElement component)
  Common: placed at the top left filling the parent size (position absolute, 100%), font 13px sans-serif, text color COLOR_TEXT.
  panel: background COLOR_PANEL, padding 10. toolbar: background COLOR_TOOLBAR, bottom border 1px COLOR_BORDER, gathered horizontally in the center 10 apart (flex).
  button: own size (position relative, auto), padding 6 16, corner 4, bold text, background COLOR_RESIZER (COLOR_ACCENT if accent, COLOR_WARNING if warning),
  1.2 times brightness and the pointer cursor when hovered, the set_on_click function when pressed and released. input: engine input field (UIInputField), background COLOR_INPUT_BACKGROUND, padding 4.
  textarea: multiline input field with background COLOR_BACKGROUND, text #d4d4d4, monospace 14px, padding 15, tab size 4. text: own size, bold text.
  relative elements are placed inside the parent's padding. Block parents stack them vertically (div fills the width, others take their own width), and flex parents, like CSS Flexbox,
  place the base size (flex-basis, else width or height, own size if that is also auto) along the main axis (flex-direction row, column) and split the remaining space by the flex-grow ratio, or
  shrink by the ratio of flex-shrink times the base size if short. (items hitting min or max are frozen and the rest split again, the automatic minimum of items whose overflow is visible is their own size)
  The cross axis follows align-items (default stretch, flex-start, center, flex-end), and main axis distribution follows justify-content (flex-start, center, flex-end, space-between, space-around, space-evenly) and gap (row gap, column gap).
  With flex-wrap (wrap, wrap-reverse), like CSS Flexbox 9.3, outer hypothetical main sizes are added in order and a new line starts at the item that overflows, and each line grows and shrinks,
  the cross size of a line is the largest outer cross size of its items, and lines are distributed by align-content (the default stretch adds the remaining space evenly to each line). wrap-reverse swaps the start and end of the cross axis.
  The own size of an auto sized element is its text and children (vertical sum for blocks, horizontal sum for horizontal flex) plus padding and border.
- If overflow (overflow-x, overflow-y) is not visible, overflowing children are clipped (corners by border-radius), and with auto, scroll it scrolls with the wheel and by dragging the thumb.
  Like the original scroll box, if it cannot scroll further in that direction it passes the wheel to the parent. The thumb is the thumb color of scrollbar-color (rgba(121, 121, 121, 0.4) of the original editor).
- Differences from the original:
  - What is attached with addEventListener("click") on an original element is PaneElement::set_on_click.
  - The CSS read by options.style and PaneStyle::apply is what the presets and the original tools (particle, timeline, UI editor) use:
    position(absolute, relative), left, top, right, bottom, width, height, min-width, min-height, max-width, max-height(px, %, auto),
    display(flex, block, none), flex-direction, flex, flex-grow, flex-shrink, flex-basis, justify-content, align-items, gap,
    padding, margin(1 to 4 values and per side), background, background-color, color, font-size, font-weight, font-family, line-height, text-align,
    border, border-top, border-right, border-bottom, border-left, border-width, border-color, border-radius, cursor(pointer),
    overflow, overflow-x, overflow-y, scrollbar-color, scrollbar-width, flex-wrap, flex-flow, align-content, row-gap, column-gap, white-space, text-overflow, opacity.
    opacity is laid down at once over the element and its descendants, like Chrome. (node opacity and an opacity layer, WorldNode::set_opacity_layer)
    Others (such as user-select) are not read. Text does not wrap. (with white-space: nowrap and text-overflow: ellipsis, if overflow is not visible the overflowing end becomes an ellipsis)
  - Scroll bars follow the operating system like Chrome. Windows and Linux use the space-taking Fluent scroll bar (thickness 15, thin 10), and Mac uses an overlay thumb of thickness 8 if the system setting is overlay,
    or a space-taking scroll bar (thickness 15, thin 11) if classic. A space-taking scroll bar sits inside the border and outside the padding, and takes content width always for overflow: scroll and only when overflowing for auto.
    (read_classic_scrollbar_metrics in web/pane.rs, button arrows are not drawn and the track is painted only when scrollbar-color has a second value)
  - For the textarea tag, the engine multiline input field (UIInputField::set_multiline) takes the text. Like the original DOM textarea, it inserts lines, wraps to the width, moves up and down, and scrolls with the wheel when overflowing.
    Uses the preset's tab size 4. Font, color and padding take the style at creation. (fonts changed later with PaneStyle::apply are not carried to the field)
  - The canvas tag is where the original puts the preview engine's canvas. On the desktop, draw the preview scene into a render target and pass it with PaneElement::set_canvas_texture,
    and that screen is drawn in the element's inner box. (The box size is calculate_canvas_box_size; multiply by the device pixel ratio to size the render target) Without it only the background and border are drawn.
- [macros](https://vanillapunch.com/md.php?page=docs&path=vanilla-engine/0.4.0/api/macros&lang=en): vanilla-engine procedural macros. (in place of the runtime reflection of the original vanilla.js)
- The original is JavaScript, so at runtime it walks an object's prototype to find get, is, set functions.
  (collectReflectedProperties in ui/uidocument.js, getComponentProperties in misc/devtools.js)
  Rust has no runtime reflection, so like Unreal's UHT (UPROPERTY) and Qt's moc, it generates code at compile time to do the same job.
- Putting `#[reflect]` on a component's impl block gathers the block's `pub fn get_*(&self) -> T`, `pub fn is_*(&self) -> T` and
  their paired `pub fn set_*(&mut self, value)` to build a vanilla::core::reflection::Reflect implementation.
- `#[reflect]` on an impl Component block collects the getters redefined in that block (like isTickNeeded overridden by an original subclass) for the inspector.
  When that block has no fn draw, it generates Component::is_draw_overridden returning false. (a component that draws nothing, original draw === Component.prototype.draw)
  Both blocks must have it. Reflect is a supertrait of Component, so leaving out either one is a compile error. (Like the original, every component is reflected)
  A type without getters takes it on an empty block, `#[reflect] impl Type {}`.
- Follows the original rules as is:
  - Getters are argumentless `get*`, `is*` functions. (original `getterFunction.length === 0`) Saved properties are only getters with a `set*` of the same key. (original `"set" + baseName`)
    &mut self getters are getters too. (the original functions make no &self, &mut self distinction) Reflection calls them through the branches that take &mut (get_reflected_value_mut, collect_reflected_getters_mut).
    Rust _mut accessors (like get_uiview_mut) and functions returning &mut are not original getters, so they are excluded.
  - Setters are `set*` taking one value. Setters taking the tree and a value (like set_snap_current_index(tree, slot)) are also recognized,
    and the side holding the tree (UIDocument reading) calls them with set_reflected_value_in_tree as in the original.
  - Getters taking only the tree (like get_target_button(&self, tree)) are original getters too. The original holds neighbor components directly, but the Rust version takes them out of the tree.
    The side holding the tree (the DevTools inspector) calls them with collect_reflected_getters_in_tree. They are not saved properties.
  - The key is the original name with the prefix (get, is) removed. Rust snake_case is turned back into the original camelCase. (get_line_width → getLineWidth → LineWidth)
  - The order is definition order, and on the same key the first one wins.
- Getters of types that cannot be turned into values do not cause compile errors either. Through autoref specialization (autoref specialization) only convertible types are read as values,
  and the rest are skipped in saving as in the original and shown in the inspector as `[kind name]`.
- Put on functions: `#[reflect(skip)]` excludes from reflection. `#[reflect(transient)]` shows in the inspector but excludes from the property list.
  `#[reflect(unsaved)]` keeps it in the property list but excludes it from reflection saving and reading. (properties saveByReflection does not write because the value is an object in the original, ShadowText's FontFace)
  `#[reflect(name = "UIScale")]` sets the original key name. (names that cannot be recovered from snake_case, like acronym words in original names, and getters whose names differ from the original)
  `#[reflect(after = "getFittedFontSize")]` places an impl Component block getter after that original getter in the inspector list. (the order in the original class body, at the front if absent)
- Put on blocks: `#[reflect(base = field)]` chains the reflection of a held value afterwards, like an original superclass.
  `#[reflect(crate = path)]` engine path. (default ::vanilla, inside the engine crate the same path works through extern crate self as vanilla in lib.rs)
