# resource/spriteatlas (vanilla-engine 0.4.0)

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

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.

## SpriteAtlasLoadHandle (struct) (Clone, IntoFuture)

Atlas load handle. (returned by SpriteAtlas::load, load_data. Stands in for the Promise of the original load, does not borrow the atlas)
- Awaiting it waits until the JSON and page images have all arrived and the frames are built. (calls update every frame while waiting)

Example: Wait for an atlas load inside an engine task (on desktop it already finished in load, so it passes right through)

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

let engine = Engine::new(EngineConfiguration::new());
let mut sprite_atlas = SpriteAtlas::new();
let atlas_load_handle = sprite_atlas.load(&engine, "examples/assets/atlas/icons.json");
assert!(atlas_load_handle.is_finished());
let task_handle = engine.spawn_task(|_engine_context| async move {
	atlas_load_handle.await;
});
assert!(task_handle.is_finished());
assert!(sprite_atlas.has_frame("star"));
```

- `pub fn is_finished(&self) -> bool` (method, since 0.4.0): Whether it finished. (frames were built, or it ended because the data could not be read)
  - returns bool: true if the frames were built or it ended because the data could not be read.

## SpriteAtlasLoadFuture (struct) (Clone, Future)

Future that waits for an atlas load. (made by awaiting the handle or returned by wait_for_load)
- Calls update on every poll. As in the original, it also finishes if the data cannot be read.

Example: Call load and then wait with wait_for_load

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

let engine = Engine::new(EngineConfiguration::new());
let mut sprite_atlas = SpriteAtlas::new();
sprite_atlas.load(&engine, "examples/assets/atlas/icons.json");
let atlas_load_future = sprite_atlas.wait_for_load();
let task_handle = engine.spawn_task(|_engine_context| async move {
	atlas_load_future.await;
});
assert!(task_handle.is_finished());
assert!(sprite_atlas.is_loaded());
```

## SpriteAtlas (struct) (Default)

Sprite atlas.
- Takes out images gathered on a few page images by name and sets them on sprites. Names can also be looked up without the extension.

Example: Load an atlas from the repository and set a frame on a sprite

```rust
use vanilla::{Engine, EngineConfiguration, Rect, Sprite, SpriteAtlas};

let engine = Engine::new(EngineConfiguration::new());
let mut sprite_atlas = SpriteAtlas::new();
sprite_atlas.load(&engine, "examples/assets/atlas/icons.json");
assert!(sprite_atlas.is_loaded());
assert_eq!(sprite_atlas.get_page_count(), 1);
let coin_frame = sprite_atlas.read_frame("coin").expect("coin");
assert_eq!(coin_frame.get_image_rect(), Rect::create(84.0, 55.0, 30.0, 30.0));
assert!(sprite_atlas.has_frame("coin.png"));
let mut sprite = Sprite::new();
assert!(sprite_atlas.apply_frame(&mut sprite, "star"));
assert_eq!(sprite.get_image_rect(), Rect::create(63.0, 2.0, 48.0, 48.0));
assert!(!sprite_atlas.apply_frame(&mut sprite, "nothing"));
assert!(sprite.get_image().is_none());
```

- `pub fn new() -> SpriteAtlas` (constructor, since 0.4.0): Constructor.
  - returns SpriteAtlas: An empty atlas with no frames.
- `pub fn load(&mut self, engine: &Engine, json_path: &str) -> SpriteAtlasLoadHandle` (method, since 0.4.0): Loads the atlas JSON and page images. (requests the page images once the JSON arrives, on desktop everything is read on the spot)
  - Returns a handle that can be awaited as in the original. (until the frames are built)
  - Frames already fully loaded earlier stay in use until the new one builds its frames.
  - `engine` &Engine: Engine to ask for the bytes.
  - `json_path` &str: Atlas JSON path. (page paths without a slash are relative to the folder containing this JSON)
  - returns SpriteAtlasLoadHandle: Handle that finishes when the frames are built or it ends because the data could not be read. (does not borrow the atlas)
- `pub fn load_data(&mut self, engine: &Engine, atlas_data: &serde_json::Value, base_directory: &str) -> SpriteAtlasLoadHandle` (method, since 0.4.0): Loads from atlas data. (a value read from JSON or a value of the same form kept in code, base_directory is prepended to page paths without a slash)
  - Returns a handle that can be awaited like the original loadData. (until the page images have all arrived and the frames are built)
  - Data in an unknown form is reported and it finishes without frames.
  - `engine` &Engine: Engine to request the page images from.
  - `atlas_data` &serde_json::Value: Atlas data. (the images and meta form or the pagePaths and frames form)
  - `base_directory` &str: Folder prepended as is to page paths without a slash. (give it ending with a slash, empty means relative to the asset folder)
  - returns SpriteAtlasLoadHandle: Handle that finishes when the frames are built or it ends because the data could not be read. (does not borrow the atlas)

  Example: Load from page paths and a table form kept in code

  ```rust
  use vanilla::{Engine, EngineConfiguration, Rect, SpriteAtlas};
  
  let engine = Engine::new(EngineConfiguration::new());
  let atlas_data = serde_json::json!({ "pagePaths": ["icons.png"], "frames": { "gem": [0, 2, 2, 56, 40] } });
  let mut sprite_atlas = SpriteAtlas::new();
  let atlas_load_handle = sprite_atlas.load_data(&engine, &atlas_data, "examples/assets/atlas/");
  assert!(atlas_load_handle.is_finished());
  assert_eq!(sprite_atlas.read_frame("gem").expect("gem").get_image_rect(), Rect::create(2.0, 2.0, 56.0, 40.0));
  ```

- `pub fn update(&mut self, engine: &Engine) -> bool` (method, since 0.4.0): Advances. (requests the page images if the JSON has arrived, and builds the frames once the page images have all arrived. true if finished, and as in the original it also finishes if the data cannot be read)
  - On the web, call it in tick until is_loaded becomes true. On desktop it has already finished in load.
  - `engine` &Engine: Engine to request the page images from.
  - returns bool: true if finished. false if no load was ever started.
- `pub fn track_json_asset(&self, scene_base: &mut SceneBase)` (method, since 0.4.0): Hands the atlas JSON off to the scene to wait for. (update requests the page images after the JSON arrives)
  - Only hands over loads started with load. (load_data has no JSON, so it does nothing)
  - `scene_base` &mut SceneBase: Common scene state that takes over the JSON asset.
- `pub fn is_loaded(&self) -> bool` (method, since 0.4.0): Whether it is fully read. (whether the frames are built, while reloading it is judged by the previous one as in the original)
  - returns bool: true if the currently visible load has built its frames.
- `pub fn wait_for_load(&self) -> SpriteAtlasLoadFuture` (method, since 0.4.0): Future that waits until it is fully read. (same as awaiting the handle returned by load or load_data. Does not borrow the atlas)
  - returns SpriteAtlasLoadFuture: Future that finishes when the last started load finishes. (never finishes if no load was ever started)
- `pub fn read_frame(&self, frame_name: &str) -> Option<&Frame>` (method, since 0.4.0): Reads a frame. (None if missing or not read yet)
  - `frame_name` &str: Image name. (a name without the extension also works)
  - returns Option<&Frame>: The frame with that name. None if it does not exist or has not loaded yet.
- `pub fn has_frame(&self, frame_name: &str) -> bool` (method, since 0.4.0): Whether the frame exists.
  - `frame_name` &str: Image name. (a name without the extension also works)
  - returns bool: true if a frame with that name exists. false if not loaded yet.
- `pub fn apply_frame(&self, sprite: &mut Sprite, frame_name: &str) -> bool` (method, since 0.4.0): Applies a frame to a sprite. (if the name does not exist, clears the image and returns false)
  - `sprite` &mut Sprite: Sprite to set the frame on.
  - `frame_name` &str: Image name. (a name without the extension also works)
  - returns bool: true if the frame was set. false after clearing the image if the name does not exist or it has not loaded yet.
- `pub fn get_page_images(&mut self) -> Vec<Rc<Image>>` (method, since 0.4.0): List of page images. (only loaded pages, in page order, the previous ones while reloading as in the original)
  - returns Vec<Rc<Image>>: List of loaded and decoded page images. (pages not loaded or not decoded are left out)
- `pub fn get_page_count(&self) -> usize` (method, since 0.4.0): Number of pages.
  - returns usize: Number of page images listed in the data. (0 before the data is read)
- `pub fn get_frame_names(&self) -> Vec<String>` (method, since 0.4.0): List of frame names.
  - returns Vec<String>: List of frame names. (both names with and without the extension, in no fixed order. An empty list if not loaded)

  Example: Sort the name list before checking it

  ```rust
  use vanilla::{Engine, EngineConfiguration, SpriteAtlas};
  
  let engine = Engine::new(EngineConfiguration::new());
  let atlas_data = serde_json::json!({ "pagePaths": ["icons.png"], "frames": { "star": [0, 63, 2, 48, 48], "gem.png": [0, 2, 2, 56, 40] } });
  let mut sprite_atlas = SpriteAtlas::new();
  sprite_atlas.load_data(&engine, &atlas_data, "examples/assets/atlas/");
  let mut frame_names = sprite_atlas.get_frame_names();
  frame_names.sort();
  assert_eq!(frame_names, vec!["gem", "gem.png", "star"]);
  ```

- `pub fn find_frame_in_order<'a>(atlas_list: &[&'a SpriteAtlas], frame_name: &str) -> Option<&'a Frame>` (static, since 0.4.0): Finds a frame in several atlases in order. (the earlier one wins, in place of the search list of the original SpriteAtlas.findFrame)
  - `atlas_list` &[&'a SpriteAtlas]: List of atlases to search. (searched from the front)
  - `frame_name` &str: Image name. (a name without the extension also works)
  - returns Option<&'a Frame>: The first frame found. None if it is in no atlas.

  Example: With the same name, the earlier atlas wins

  ```rust
  use vanilla::{Engine, EngineConfiguration, SpriteAtlas};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut first_atlas = SpriteAtlas::new();
  first_atlas.load_data(&engine, &serde_json::json!({ "pagePaths": ["icons.png"], "frames": { "star": [0, 0, 0, 8, 8] } }), "examples/assets/atlas/");
  let mut second_atlas = SpriteAtlas::new();
  second_atlas.load(&engine, "examples/assets/atlas/icons.json");
  let atlas_list = [&first_atlas, &second_atlas];
  assert_eq!(SpriteAtlas::find_frame_in_order(&atlas_list, "star").expect("star").get_image_rect().size.x, 8.0);
  assert_eq!(SpriteAtlas::find_frame_in_order(&atlas_list, "gem").expect("gem").get_image_rect().size.x, 56.0);
  assert!(SpriteAtlas::find_frame_in_order(&atlas_list, "nothing").is_none());
  ```

- `pub fn apply_frame_in_order(atlas_list: &[&SpriteAtlas], sprite: &mut Sprite, frame_name: &str) -> bool` (static, since 0.4.0): Sets a frame found in several atlases in order on a sprite. (clears the image and false if not found, the original applySearchFrame)
  - `atlas_list` &[&SpriteAtlas]: List of atlases to search. (searched from the front)
  - `sprite` &mut Sprite: Sprite to set the frame on.
  - `frame_name` &str: Image name. (a name without the extension also works)
  - returns bool: true if the frame was set. false after clearing the image if it is in no atlas.
- `pub fn add_search_atlas(sprite_atlas: &Rc<RefCell<SpriteAtlas>>)` (static, since 0.4.0): Adds an atlas to search. (added at the end, left as is if already in)
  - There is one list per thread. Whether atlases are the same is judged by whether the Rc points to the same one.
  - `sprite_atlas` &Rc<RefCell<SpriteAtlas>>: Atlas to add. (shared)

  Example: Add to the search list, then look up by name and set it

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, Sprite, SpriteAtlas};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut sprite_atlas = SpriteAtlas::new();
  sprite_atlas.load(&engine, "examples/assets/atlas/icons.json");
  let sprite_atlas = Rc::new(RefCell::new(sprite_atlas));
  SpriteAtlas::add_search_atlas(&sprite_atlas);
  assert_eq!(SpriteAtlas::find_frame("heart").expect("heart").get_image_rect().size.x, 40.0);
  let mut sprite = Sprite::new();
  assert!(SpriteAtlas::apply_search_frame(&mut sprite, "leaf"));
  assert!(!SpriteAtlas::apply_search_frame(&mut sprite, "nothing"));
  SpriteAtlas::remove_search_atlas(&sprite_atlas);
  assert!(SpriteAtlas::find_frame("heart").is_none());
  SpriteAtlas::clear_search_atlases();
  ```

- `pub fn remove_search_atlas(sprite_atlas: &Rc<RefCell<SpriteAtlas>>)` (static, since 0.4.0): Removes an atlas to search.
  - `sprite_atlas` &Rc<RefCell<SpriteAtlas>>: Atlas to remove. (removes the one whose Rc points to the same atlas, does nothing if absent)
- `pub fn clear_search_atlases()` (static, since 0.4.0): Removes all atlases to search.
- `pub fn find_frame(frame_name: &str) -> Option<Frame>` (static, since 0.4.0): Finds a frame in the atlases to search. (in the order added, None if not found, atlases being modified elsewhere are skipped)
  - `frame_name` &str: Image name. (a name without the extension also works)
  - returns Option<Frame>: A copy of the first frame found. (just the image Rc and a rectangle, so it is cheap) None if it is nowhere.
- `pub fn apply_search_frame(sprite: &mut Sprite, frame_name: &str) -> bool` (static, since 0.4.0): Sets the frame found in the atlases to search on a sprite. (clears the image and false if not found)
  - `sprite` &mut Sprite: Sprite to set the frame on.
  - `frame_name` &str: Image name. (a name without the extension also works)
  - returns bool: true if the frame was set. false after clearing the image if it is nowhere.
