# misc/spriteanimator (vanilla-engine 0.4.0)

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

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

## SpriteAnimatorPlayOptions (struct) (Default)

Play settings. (original options = { on_complete?, restart_if_same = false })
- The default is no callback, and the same clip is not restarted.

Example: Restart from the beginning even for the same clip

```rust
use vanilla::{Image, Rect, SpriteAnimator, SpriteAnimatorPlayOptions};

let image = Image::create_from_pixels(64, 16, vec![0u8; 64 * 16 * 4]);
let frame_rects = [Rect::create(0.0, 0.0, 16.0, 16.0), Rect::create(16.0, 0.0, 16.0, 16.0)];
let mut animator = SpriteAnimator::new();
animator.add_clip("idle", image, &frame_rects, 10.0, true);
assert!(animator.play_clip("idle", SpriteAnimatorPlayOptions::default()));
assert!(!animator.play_clip("idle", SpriteAnimatorPlayOptions::default()));
let restart_options = SpriteAnimatorPlayOptions {
	restart_if_same: true,
	..SpriteAnimatorPlayOptions::default()
};
assert!(animator.play_clip("idle", restart_options));
```

- `pub on_complete: Option<SpriteAnimatorCompleteEvent>` (field, since 0.3.2): Called once when the clip ends. (only non-looping clips end)
  - returns Option<SpriteAnimatorCompleteEvent>
- `pub restart_if_same: bool` (field, since 0.3.2): Whether to restart from the beginning even if the same clip is playing.
  - returns bool
- `pub fn create_with_on_complete(on_complete: impl FnOnce(&mut SpriteAnimator) + 'static) -> SpriteAnimatorPlayOptions` (static, since 0.3.2): Settings with only the completion callback set.
  - `on_complete` impl FnOnce(&mut SpriteAnimator) + 'static: Function to call once when the clip ends. It receives the animator and can play the next clip.
  - returns SpriteAnimatorPlayOptions: Settings holding on_complete with restart_if_same false.

## SpriteAnimator (struct) (Default, Component)

Sprite animator component.
- Use with a Sprite attached to the same node. Each tick puts the current frame into that Sprite.

Example: Back to the idle clip when the attack clip ends

```rust
use vanilla::{Engine, EngineConfiguration, Image, NodeTree, Rect, Sprite, SpriteAnimator, SpriteAnimatorPlayOptions};

let engine = Engine::new(EngineConfiguration::new());
let image = Image::create_from_pixels(128, 16, vec![0u8; 128 * 16 * 4]);
let idle_rects: Vec<Rect> = (0..2).map(|column| Rect::create(column as f64 * 16.0, 0.0, 16.0, 16.0)).collect();
let attack_rects: Vec<Rect> = (4..7).map(|column| Rect::create(column as f64 * 16.0, 0.0, 16.0, 16.0)).collect();

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let hero_id = node_tree.create_child(root_id, "hero");
node_tree[hero_id].add_component(Sprite::new());
let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
animator.add_clip("idle", image.clone(), &idle_rects, 10.0, true);
animator.add_clip("attack", image.clone(), &attack_rects, 12.0, false);
SpriteAnimator::play(&mut node_tree[hero_id], "attack", SpriteAnimatorPlayOptions::create_with_on_complete(|animator| {
	animator.play_clip("idle", SpriteAnimatorPlayOptions::default());
}));
assert_eq!(node_tree[hero_id].get_component::<Sprite>().unwrap().get_image_rect(), Rect::create(64.0, 0.0, 16.0, 16.0));

for _ in 0..30 {
	node_tree.tick(&engine, 1.0 / 60.0);
}
assert_eq!(node_tree[hero_id].get_component::<SpriteAnimator>().unwrap().get_clip_name(), Some("idle"));
```

- `pub const DEFAULT_FRAME_PER_SECOND: f64 = 10.0` (static, since 0.3.2): Default frames per second for clips. (original fps = 10)
  - returns f64
- `pub fn new() -> SpriteAnimator` (constructor, since 0.3.2): Constructor.
  - returns SpriteAnimator: A new animator with no clips, not playing.
- `pub fn add_clip(&mut self, clip_name: &str, image: Rc<Image>, frame_rects: &[Rect], frame_per_second: f64, is_loop: bool)` (method, since 0.3.2): Registers a clip. (replaces one with the same name)
  - `clip_name` &str: Clip name. (the name to pass to play)
  - `image` Rc<Image>: Sheet image to cut frames from.
  - `frame_rects` &[Rect]: List of frame areas in the sheet. (pixels, advanced in order. Copied)
  - `frame_per_second` f64: Frames per second. (0 or less does not advance, the original default is DEFAULT_FRAME_PER_SECOND)
  - `is_loop` bool: true loops, false stops at the last frame and calls the completion callback.
- `pub fn add_clip_from_atlas(&mut self, clip_name: &str, image: Rc<Image>, atlas_json: &serde_json::Value, frame_ids: &[&str], frame_per_second: f64, is_loop: bool)` (method, since 0.3.2): Registers a clip from atlas JSON. (TexturePacker style { frames: { name: { frame: { x, y, w, h } } } }, missing cell names are skipped)
  - If there is no frame field, reads x, y, w (width), h (height) from the cell itself. Missing numbers are 0.
  - `clip_name` &str: Clip name.
  - `image` Rc<Image>: Atlas image.
  - `atlas_json` &serde_json::Value: Atlas JSON value.
  - `frame_ids` &[&str]: List of cell names in frames. (they become frames in this order)
  - `frame_per_second` f64: Frames per second.
  - `is_loop` bool: true loops.

  Example: Make a clip from cell names in the JSON

  ```rust
  use vanilla::{Image, SpriteAnimator, SpriteAnimatorPlayOptions};
  
  let image = Image::create_from_pixels(64, 64, vec![0u8; 64 * 64 * 4]);
  let atlas_json = serde_json::json!({
  	"frames": {
  		"run_0": { "frame": { "x": 0, "y": 0, "w": 16, "h": 20 } },
  		"run_1": { "frame": { "x": 16, "y": 0, "w": 16, "h": 20 } }
  	}
  });
  let mut animator = SpriteAnimator::new();
  animator.add_clip_from_atlas("run", image, &atlas_json, &["run_0", "run_1"], SpriteAnimator::DEFAULT_FRAME_PER_SECOND, true);
  assert!(animator.has_clip("run"));
  assert!(animator.play_clip("run", SpriteAnimatorPlayOptions::default()));
  ```

- `pub fn play_clip(&mut self, clip_name: &str, options: SpriteAnimatorPlayOptions) -> bool` (method, since 0.4.0): Play with only the animator. (true if it started from the beginning)
  - If the same clip is already playing, it does not restart and only replaces the complete callback. (from the beginning with restart_if_same)
  - Used when there is no node (such as inside the complete callback). The frame goes into the Sprite at the next frame update (tick, the same tick after the complete callback, apply_current_frame).
    With a node, use SpriteAnimator::play, which puts the first frame in right away.
  - `clip_name` &str: Name of the clip to play.
  - `options` SpriteAnimatorPlayOptions: Completion callback and restarting the same clip.
  - returns bool: true if started from the beginning. false if the clip does not exist or was not restarted because the same clip is playing.
- `pub fn play(node: &mut WorldNode, clip_name: &str, options: SpriteAnimatorPlayOptions) -> bool` (static, since 0.3.2): Play. (the original play: plays with the node's animator and puts the first frame into the Sprite on the same node right away)
  - If the same clip is already playing, it does not restart and only replaces the complete callback. (from the beginning with restart_if_same)
  - false if there is no animator.
  - `node` &mut WorldNode: Node with a SpriteAnimator attached. (if there is no Sprite, only plays without putting in the frame)
  - `clip_name` &str: Name of the clip to play.
  - `options` SpriteAnimatorPlayOptions: Completion callback and restarting the same clip.
  - returns bool: true if it started from the beginning. false if the clip does not exist, the same clip is playing and was not restarted, or the node has no animator.
- `pub fn stop(&mut self)` (method, since 0.3.2): Stops. (returns to the first frame, the completion callback is not called)
- `pub fn apply_current_frame(&self, sprite: &mut Sprite)` (method, since 0.3.2): Puts the current frame into a sprite. (does nothing if there is no frame)
  - `sprite` &mut Sprite: Sprite to put the image and image area into.

  Example: Put the first frame into a Sprite outside the node

  ```rust
  use vanilla::{Image, Rect, Sprite, SpriteAnimator, SpriteAnimatorPlayOptions};
  
  let image = Image::create_from_pixels(32, 16, vec![0u8; 32 * 16 * 4]);
  let mut animator = SpriteAnimator::new();
  animator.add_clip("blink", image, &[Rect::create(16.0, 0.0, 16.0, 16.0)], 10.0, true);
  animator.play_clip("blink", SpriteAnimatorPlayOptions::default());
  let mut sprite = Sprite::new();
  animator.apply_current_frame(&mut sprite);
  assert_eq!(sprite.get_image_rect(), Rect::create(16.0, 0.0, 16.0, 16.0));
  ```

- `pub fn get_clip_name(&self) -> Option<&str>` (method, since 0.3.2): Returns the current clip name. (None if not played yet)
  - returns Option<&str>: Name of the clip last started from the beginning. None if not played yet. (remains after stop)
- `pub fn is_playing(&self) -> bool` (method, since 0.3.2): Whether it is playing.
  - returns bool: true while advancing frames. false if a non-looping clip has ended or stop was called.
- `pub fn has_clip(&self, clip_name: &str) -> bool` (method, since 0.3.2): Whether a clip exists.
  - `clip_name` &str: Name of the clip to look up.
  - returns bool: true if a clip is registered under that name.
- `pub fn get_current_frame_index(&self) -> usize` (method, since 0.3.2): Current frame index.
  - returns usize: Frame index within the current clip. (from 0)
- `pub fn find_sprite(node_tree: &mut NodeTree, node_id: NodeId) -> Option<&mut Sprite>` (static, since 0.4.0): Finds the sprite on the same node. (the original findSprite, remembers it once found)
  - The original holds the Sprite it found. Rust cannot hold a reference to a sibling component, so the animator remembers the NodeId of the node holding the Sprite and takes it out of the tree.
  - Also remembers it when found in tick. None if the Sprite was removed from the remembered node.
  - `node_tree` &mut NodeTree: Tree holding the node.
  - `node_id` NodeId: The node SpriteAnimator is attached to.
  - returns Option<&mut Sprite>: The first Sprite on the same node. None if the node is missing, or has no SpriteAnimator or Sprite.

  Example: Taking out the sprite the animator fills

  ```rust
  use vanilla::{Image, NodeTree, Rect, Sprite, SpriteAnimator, SpriteAnimatorPlayOptions};
  
  let image = Image::create_from_pixels(64, 16, vec![0u8; 64 * 16 * 4]);
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let hero_id = node_tree.create_child(root_id, "hero");
  node_tree[hero_id].add_component(Sprite::new());
  let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
  animator.add_clip("run", image, &[Rect::create(16.0, 0.0, 16.0, 16.0)], 10.0, true);
  SpriteAnimator::play(&mut node_tree[hero_id], "run", SpriteAnimatorPlayOptions::default());
  let sprite = SpriteAnimator::find_sprite(&mut node_tree, hero_id).expect("sprite");
  assert_eq!(sprite.get_image_rect(), Rect::create(16.0, 0.0, 16.0, 16.0));
  ```

