# core/tween (vanilla-engine 0.4.0)

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

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.

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

Tween value set. (in place of the original's objects like { x: 0, y: 0 }, keeps insertion order)
- Names are usually string constants ("x"). Constant names do not allocate new memory when copied.

Example: Store and read numbers and Vector2s

```rust
use vanilla::{TweenValue, TweenValues, Vector2};

let mut values = TweenValues::new()
	.with("alpha", 0.0)
	.with("position", Vector2::create(10.0, 20.0));
values.set("alpha", 1.0);
assert_eq!(values.get_count(), 2);
assert_eq!(values.get_number("alpha"), Some(1.0));
assert_eq!(values.get("position"), Some(TweenValue::Vector2(Vector2::create(10.0, 20.0))));
assert_eq!(values.get_number("position"), None);
assert_eq!(values.get_vector2("missing"), None);
```

- `pub fn new() -> TweenValues` (constructor, since 0.3.2): Creates. (empty)
  - returns TweenValues: An empty set.
- `pub fn with(mut self, name: impl Into<Cow<'static, str>>, value: impl Into<TweenValue>) -> TweenValues` (method, since 0.3.2): Inserts a value and returns itself. (for chaining, replaces a value with the same name)
  - `name` impl Into<Cow<'static, str>>: Value name. (usually a string constant, if it is a TweenProperty name it is written to that property of the target node)
  - `value` impl Into<TweenValue>: Value. (f64 or Vector2)
  - returns TweenValues: Itself with the value inserted.
- `pub fn set(&mut self, name: impl Into<Cow<'static, str>>, value: impl Into<TweenValue>)` (method, since 0.3.2): Sets a value. (replaces a value with the same name, otherwise appends it)
  - `name` impl Into<Cow<'static, str>>: Value name.
  - `value` impl Into<TweenValue>: Value. (f64 or Vector2, a value with the same name can also be changed to the other kind)
- `pub fn get(&self, name: &str) -> Option<TweenValue>` (method, since 0.3.2): Returns the value. (None if missing)
  - `name` &str: Value name to find.
  - returns Option<TweenValue>: The value with that name. None if missing.
- `pub fn get_number(&self, name: &str) -> Option<f64>` (method, since 0.3.2): Returns a number value. (None if missing or not a number)
  - `name` &str: Value name to find.
  - returns Option<f64>: The number with that name. None if missing or a Vector2.
- `pub fn get_vector2(&self, name: &str) -> Option<Vector2>` (method, since 0.3.2): Returns a Vector2 value. (None if missing or not a Vector2)
  - `name` &str: Value name to find.
  - returns Option<Vector2>: The Vector2 with that name. None if missing or a number.
- `pub fn get_count(&self) -> usize` (method, since 0.3.2): Value count.
  - returns usize: Number of values held.

## TweenId (struct) (Clone, Copy, Debug, PartialEq, Eq, Hash)

Tween handle. (returned by SceneBase::start_tween, passed to stop_tween / get_tween)
- Assigned when the tween is created and unique per tween. After the scene takes the tween, it is pointed to with this.

Example: Find and stop a tween entrusted to the scene by handle

```rust
use vanilla::{SceneBase, Tween, TweenValues};

let mut scene_base = SceneBase::new();
let tween = Tween::new(TweenValues::new().with("value", 0.0)).to(TweenValues::new().with("value", 1.0), 2.0);
let tween_id = scene_base.start_tween(tween);
assert_eq!(scene_base.get_tween(tween_id).unwrap().get_tween_id(), tween_id);

scene_base.stop_tween(tween_id);
assert!(scene_base.get_tween(tween_id).is_none());
```

## Tween (struct)

Tween.
- Interpolates between a set of start values and a set of target values with an easing function for a duration (seconds) after a delay. Passes the interpolated values to the update callback every tick, and calls the completion callback when it reaches the end.
- After creating it, chain to, delay, easing, set_update, set_complete, set_target to configure it, start it, then call tick. (for a scene, SceneBase::start_tween takes care of start and tick)

Example: From 0 to 10 after a delay

```rust
use vanilla::{easing_function, NodeTree, Tween, TweenValues};
use std::cell::Cell;
use std::rc::Rc;

let mut node_tree = NodeTree::new();
let last_value = Rc::new(Cell::new(-1.0f64));
let last_value_in_callback = last_value.clone();
let mut tween = Tween::new(TweenValues::new().with("value", 0.0))
	.to(TweenValues::new().with("value", 10.0), 1.0)
	.delay(0.5)
	.easing(easing_function::linear)
	.set_update(move |values, _node_tree| {
		last_value_in_callback.set(values.get_number("value").unwrap());
	});
tween.start();
tween.tick(&mut node_tree, 0.25);
assert_eq!(last_value.get(), -1.0);
tween.tick(&mut node_tree, 0.75);
assert_eq!(last_value.get(), 5.0);
tween.tick(&mut node_tree, 0.5);
assert_eq!(last_value.get(), 10.0);
assert!(tween.is_finished());
```

- `pub fn new(initial_values: TweenValues) -> Tween` (constructor, since 0.3.2): Creates. (takes the set of start values. Duration 1 second, delay 0, linear)
  - `initial_values` TweenValues: Set of start values. (only values whose names are also in the target values are interpolated)
  - returns Tween: A new stopped tween with empty target values. (runs only after start)
- `pub fn create_node_tween(node_id: NodeId, tween_property: TweenProperty, start_value: impl Into<TweenValue>, end_value: impl Into<TweenValue>, duration: f64) -> Tween` (static, since 0.3.2): Creates a tween that animates one node property.
  - Same as Tween::new(start value).to(target value, duration).set_target(node_id). The value name is the property name.
  - `node_id` NodeId: Node to move.
  - `tween_property` TweenProperty: Node property to animate.
  - `start_value` impl Into<TweenValue>: Start value. (f64 or Vector2, a number given to a Vector2 property is used for both axes)
  - `end_value` impl Into<TweenValue>: Target value. (the same kind as start_value)
  - `duration` f64: Duration. (seconds, finishes on the first tick if 0 or less)
  - returns Tween: A new stopped tween with the target node set. (start it or pass it to SceneBase::start_tween)

  Example: Move a node toward the bottom-right over 1 second

  ```rust
  use vanilla::{NodeTree, Tween, TweenProperty, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = node_tree.create_child(root_id, "Mover");
  let mut tween = Tween::create_node_tween(node_id, TweenProperty::LocalPosition, Vector2::zero(), Vector2::create(100.0, 50.0), 1.0);
  tween.start();
  tween.tick(&mut node_tree, 0.5);
  assert_eq!(node_tree[node_id].get_local_position(), Vector2::create(50.0, 25.0));
  ```

- `pub fn find_root_node(node_tree: &NodeTree, node_id: NodeId) -> NodeId` (static, since 0.4.0): Returns the topmost node of the node. (follows the parents up, the original Tween.findRootNode)
  - `node_tree` &NodeTree: Tree holding the node.
  - `node_id` NodeId: Node to start climbing from.
  - returns NodeId: The topmost node with no parent. (node_id itself if node_id has no parent)

  Example: A node attached to the root and a detached node

  ```rust
  use vanilla::{NodeTree, Tween};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let parent_id = node_tree.create_child(root_id, "Parent");
  let child_id = node_tree.create_child(parent_id, "Child");
  assert_eq!(Tween::find_root_node(&node_tree, child_id), root_id);
  
  let loose_id = node_tree.create_node("Loose");
  assert_eq!(Tween::find_root_node(&node_tree, loose_id), loose_id);
  ```

- `pub fn tick(&mut self, node_tree: &mut NodeTree, time_delta: f64)` (method, since 0.3.2): Update.
  - After the delay passes, applies easing to the progress (0 ~ 1) and interpolates in the order of the target value names.
    Names not in the start values and names whose kind (number / Vector2) differs from the start value are skipped. (same as the original)
  - If there is a target node, writes values with node property names to that node, then calls the update callback.
  - When the progress reaches 1, stops and calls the completion callback.
  - Does nothing before start or after finishing. If the target node was destroyed or detached from the topmost node it first ran under, ends without callbacks.
  - `node_tree` &mut NodeTree: Node tree to write the target node to and to pass to the callbacks.
  - `time_delta` f64: Elapsed time. (seconds)

  Example: Fade a node and end quietly when the node is destroyed

  ```rust
  use vanilla::{NodeTree, Tween, TweenProperty};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = node_tree.create_child(root_id, "Fader");
  let mut tween = Tween::create_node_tween(node_id, TweenProperty::LocalOpacity, 1.0, 0.0, 1.0);
  tween.tick(&mut node_tree, 0.5);
  assert_eq!(node_tree[node_id].get_local_opacity(), 1.0);
  
  tween.start();
  tween.tick(&mut node_tree, 0.5);
  assert_eq!(node_tree[node_id].get_local_opacity(), 0.5);
  
  node_tree.destroy_node(node_id);
  tween.tick(&mut node_tree, 0.5);
  assert!(tween.is_finished());
  ```

- `pub fn to(mut self, properties: TweenValues, duration: f64) -> Tween` (method, since 0.3.2): Sets the target values. (also sets the duration)
  - `properties` TweenValues: Set of target values. (interpolated in this set's order and passed to the update callback)
  - `duration` f64: Duration. (seconds, excluding the delay, finishes on the first tick if 0 or less)
  - returns Tween: Itself with the target values set.
- `pub fn delay(mut self, amount: f64) -> Tween` (method, since 0.3.2): Sets the delay before starting. (seconds)
  - `amount` f64: Time to wait after start before interpolation begins. (seconds, initially 0)
  - returns Tween: Itself with the delay set.
- `pub fn easing(mut self, easing_function: impl Fn(f64) -> f64 + 'static) -> Tween` (method, since 0.3.2): Sets the easing function. (a function from the easing_function module, or any function that takes the progress and returns a ratio)
  - `easing_function` impl Fn(f64) -> f64 + 'static: Function that takes the progress (0 ~ 1) and returns the interpolation ratio. (initially easing_function::linear)
  - returns Tween: Itself with the easing function set.

  Example: Move in four discrete steps

  ```rust
  use vanilla::{NodeTree, Tween, TweenValues};
  use std::cell::Cell;
  use std::rc::Rc;
  
  let mut node_tree = NodeTree::new();
  let last_value = Rc::new(Cell::new(0.0f64));
  let last_value_in_callback = last_value.clone();
  let mut tween = Tween::new(TweenValues::new().with("value", 0.0))
  	.to(TweenValues::new().with("value", 8.0), 1.0)
  	.easing(|progress| (progress * 4.0).floor() / 4.0)
  	.set_update(move |values, _node_tree| {
  		last_value_in_callback.set(values.get_number("value").unwrap());
  	});
  tween.start();
  tween.tick(&mut node_tree, 0.3);
  assert_eq!(last_value.get(), 2.0);
  ```

- `pub fn set_update(mut self, callback: impl FnMut(&TweenValues, &mut NodeTree) + 'static) -> Tween` (method, since 0.3.2): Sets the update callback. (receives the interpolated value set and the node tree)
  - `callback` impl FnMut(&TweenValues, &mut NodeTree) + 'static: Function that receives the interpolated value set and the node tree. (called every tick after the delay ends, including the finishing tick, after writing to the target node)
  - returns Tween: Itself with the update callback set.

  Example: Move another node with the interpolated values

  ```rust
  use vanilla::{NodeTree, Tween, TweenValues, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let label_id = node_tree.create_child(root_id, "Label");
  let mut tween = Tween::new(TweenValues::new().with("x", 0.0))
  	.to(TweenValues::new().with("x", 200.0), 2.0)
  	.set_update(move |values, node_tree| {
  		let position_x = values.get_number("x").unwrap();
  		node_tree[label_id].set_local_position(Vector2::create(position_x, 0.0));
  	});
  tween.start();
  tween.tick(&mut node_tree, 1.0);
  assert_eq!(node_tree[label_id].get_local_position(), Vector2::create(100.0, 0.0));
  ```

- `pub fn set_complete(mut self, callback: impl FnMut(&mut NodeTree) + 'static) -> Tween` (method, since 0.3.2): Sets the completion callback. (receives the node tree)
  - `callback` impl FnMut(&mut NodeTree) + 'static: Function that receives the node tree. (called once after the update callback on the tick the progress reaches 1, not called when ended by stop or by the target node disappearing)
  - returns Tween: Itself with the completion callback set.

  Example: Destroy the node once it has fully faded

  ```rust
  use vanilla::{NodeTree, Tween, TweenProperty};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let toast_id = node_tree.create_child(root_id, "Toast");
  let mut tween = Tween::create_node_tween(toast_id, TweenProperty::LocalOpacity, 1.0, 0.0, 0.5)
  	.set_complete(move |node_tree| {
  		node_tree.destroy_node(toast_id);
  	});
  tween.start();
  tween.tick(&mut node_tree, 0.5);
  assert!(tween.is_finished());
  assert!(!node_tree.contains(toast_id));
  ```

- `pub fn set_target(mut self, node_id: NodeId) -> Tween` (method, since 0.3.2): Sets the target node. (values whose names are TweenProperty names are written to this node)
  - `node_id` NodeId: Target node. (the tween ends quietly if it is destroyed or detached from the topmost node it first ran under)
  - returns Tween: Itself with the target node set.

  Example: Animate scale and rotation together

  ```rust
  use vanilla::{NodeTree, Tween, TweenValues, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let card_id = node_tree.create_child(root_id, "Card");
  let mut tween = Tween::new(TweenValues::new().with("localScale", 0.5).with("localRotation", 0.0))
  	.to(TweenValues::new().with("localScale", 1.0).with("localRotation", 90.0), 1.0)
  	.set_target(card_id);
  tween.start();
  tween.tick(&mut node_tree, 1.0);
  assert_eq!(node_tree[card_id].get_local_scale(), Vector2::create(1.0, 1.0));
  assert_eq!(node_tree[card_id].get_local_rotation(), 90.0);
  ```

- `pub fn start(&mut self)` (method, since 0.3.2): Starts. (does nothing if already playing)
- `pub fn stop(&mut self)` (method, since 0.3.2): Stops. (does not call the completion callback)
- `pub fn is_finished(&self) -> bool` (method, since 0.3.2): Returns whether it is complete.
  - returns bool: True if finished. (when it reached the end, was stopped, or the target node disappeared, false again after start)
- `pub fn get_tween_id(&self) -> TweenId` (method, since 0.3.2): Returns the handle.
  - returns TweenId: Handle of this tween. (assigned at creation)
- `pub fn get_target_node_id(&self) -> Option<NodeId>` (method, since 0.3.2): Returns the target node handle. (None if set_target was not called)
  - returns Option<NodeId>: Target node. None if set_target was not called.

## TweenValue (enum) (Clone, Copy, Debug, PartialEq, From<f64>, From<Vector2>)

Tween value. (the original interpolates only numbers and Vector2)

- `Number` = `Number(f64)`: A single number. (values like opacity, rotation)
- `Vector2` = `Vector2(Vector2)`: 2D vector. (values like position, scale, size, the two axes are interpolated separately)

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

Node properties the tween writes directly. (when the target node is set with set_target, values with these names are written to that node)
- A number given to a Vector2 property is used for both axes. (in place of set_scale(Vector2.one().multiply(v.scale)) in the original example)
- A Vector2 given to a number property is not written.

- `LocalPosition`: Local position. (name "localPosition", Vector2 or a number used for both axes)
- `LocalScale`: Local scale. (name "localScale", Vector2 or a number used for both axes)
- `LocalRotation`: Local rotation. (name "localRotation", degrees, number only)
- `LocalOpacity`: Local opacity. (name "localOpacity", number only, the node clamps it to 0 ~ 1)
- `ContentSize`: Content size. (name "contentSize", Vector2 or a number used for both axes)

- `pub fn get_name(&self) -> &'static str` (method, since 0.3.2): Name used in value bundles. (the original property name, the enum name with its first letter lowercased, like localPosition)
  - returns &'static str: Property name used in the value set. (first letter lowercase, like "localPosition")
- `pub fn find_by_name(name: &str) -> Option<TweenProperty>` (static, since 0.3.2): Finds by name. (None if not a node property name)
  - `name` &str: Value name. (compared with the name get_name returns, case sensitive)
  - returns Option<TweenProperty>: The property with that name. None if not a node property name.

  Example: Property names and other names

  ```rust
  use vanilla::TweenProperty;
  
  assert_eq!(TweenProperty::find_by_name("localScale"), Some(TweenProperty::LocalScale));
  assert_eq!(TweenProperty::find_by_name("scale"), None);
  assert_eq!(TweenProperty::LocalScale.get_name(), "localScale");
  ```

- `pub fn apply_to_node(&self, node: &mut WorldNode, value: TweenValue)` (method, since 0.3.2): Writes a value to the node.
  - A number given to a Vector2 property (position, scale, content size) is used for both axes. A Vector2 given to a number property (rotation, opacity) is not written.
  - `node` &mut WorldNode: Node to write the value to.
  - `value` TweenValue: Value to write.

  Example: Write a two-axis scale with a single number

  ```rust
  use vanilla::{TweenProperty, TweenValue, Vector2, WorldNode};
  
  let mut node = WorldNode::new("Node");
  TweenProperty::LocalScale.apply_to_node(&mut node, TweenValue::Number(2.0));
  assert_eq!(node.get_local_scale(), Vector2::create(2.0, 2.0));
  
  TweenProperty::LocalRotation.apply_to_node(&mut node, TweenValue::Vector2(Vector2::create(1.0, 1.0)));
  assert_eq!(node.get_local_rotation(), 0.0);
  ```

