# core/component (vanilla-engine 0.4.0)

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

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.

## RequiredComponent (struct)

One dependent component. (its type and the function that creates it when missing, in place of the class returned by the original require)
- One entry of the list returned by Component::require. Usually created with RequiredComponent::of.

Example: Adding the walk component also adds the body component

```rust
use vanilla::core::component::RequiredComponent;
use vanilla::{Component, ComponentBase, WorldNode};

#[derive(Default)]
struct Body {
	component_base: ComponentBase,
}

#[vanilla::reflect]
impl Body {}

#[vanilla::reflect]
impl Component for Body {
	fn get_component_base(&self) -> &ComponentBase {
		&self.component_base
	}

	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
		&mut self.component_base
	}

	fn get_component_type(&self) -> &'static str {
		"Body"
	}
}

#[derive(Default)]
struct Walker {
	component_base: ComponentBase,
}

#[vanilla::reflect]
impl Walker {}

#[vanilla::reflect]
impl Component for Walker {
	fn get_component_base(&self) -> &ComponentBase {
		&self.component_base
	}

	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
		&mut self.component_base
	}

	fn get_component_type(&self) -> &'static str {
		"Walker"
	}

	fn require(&self) -> Vec<RequiredComponent> {
		vec![RequiredComponent::of::<Body>()]
	}
}

let mut node = WorldNode::new("walker");
node.add_component(Walker::default());
assert!(node.has_component::<Body>());
node.add_component(Walker::default());
assert_eq!(node.get_components::<Body>().len(), 1);
```

- `pub type_id: TypeId` (field, since 0.4.0): Type of the dependent component. (not created if the same node already has this type)
  - returns TypeId
- `pub create: fn() -> Box<dyn Component>` (field, since 0.4.0): Function that creates a new one when the type is missing.
  - returns fn() -> Box<dyn Component>
- `pub fn of<T: Component + Default + 'static>() -> RequiredComponent` (static, since 0.4.0): Dependent component created with the type's default value.
  - returns RequiredComponent: Dependent component holding T's type and a function that creates it with `T::default()`.

## AsAny (trait)

Helper trait for getting the concrete type out. (in places such as `get_component::<Sprite>()`)
- Implemented automatically for any 'static type that implements Component. (do not implement it yourself)
- To call it on a `dyn Component`, bring this trait in with use.

Example: Get the concrete type out of a `Box<dyn Component>`

```rust
use vanilla::core::component::AsAny;
use vanilla::{Component, Paint, Text};

let component: Box<dyn Component> = Box::new(Paint::new());
let component_reference: &dyn Component = component.as_ref();
assert!(component_reference.as_any().is::<Paint>());
assert!(component_reference.as_any().downcast_ref::<Text>().is_none());
```

- `fn as_any(&self) -> &dyn Any` (method, since 0.3.2): View as `&dyn Any`. (get the concrete type out with downcast_ref)
  - returns &dyn Any: `&dyn Any` pointing to itself.
- `fn as_any_mut(&mut self) -> &mut dyn Any` (method, since 0.3.2): View as `&mut dyn Any`. (get the concrete type out with downcast_mut)
  - returns &mut dyn Any: `&mut dyn Any` pointing to itself.

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

Common component state.
- Holds enabled (default true) and gizmo display (default false). Implementors hold it as a field and return it from get_component_base.

Example: New common state is enabled with gizmos off

```rust
use vanilla::ComponentBase;

let mut component_base = ComponentBase::new();
assert!(component_base.is_enable());
assert!(!component_base.is_gizmo_visible());
component_base.set_enable(false);
component_base.set_gizmo_visible(true);
assert!(!component_base.is_enable());
assert!(component_base.is_gizmo_visible());
```

- `pub fn new() -> ComponentBase` (constructor, since 0.3.2): Constructor.
  - returns ComponentBase: Common state that is enabled with gizmos off.
- `pub fn set_enable(&mut self, is_enable: bool)` (method, since 0.3.2): Sets active.
  - `is_enable` bool: Whether to enable. (if false, it is skipped in tick, drawing, touch and wheel)
- `pub fn is_enable(&self) -> bool` (method, since 0.3.2): Whether enabled.
  - returns bool: true if enabled.
- `pub fn set_gizmo_visible(&mut self, is_gizmo_visible: bool)` (method, since 0.3.2): Sets gizmo drawing.
  - `is_gizmo_visible` bool: Whether to also call this component's draw_gizmos when drawing the node's gizmos.
- `pub fn is_gizmo_visible(&self) -> bool` (method, since 0.3.2): Whether gizmos are drawn.
  - returns bool: true if gizmos are drawn.
- `pub fn mark_drawn_rect_dirty(&self)` (method, since 0.4.0): Tells the node that the drawn rect (Component::calculate_drawn_rect) changed. (original Component.markDrawnRectDirty)
  - The attached node and its ancestors recompute their subtree draw bounds before the next draw. Does nothing if not attached to a node.
  - Call it from every setter that changes the drawn rect. (Without it, a drawing that grew into the screen may still be skipped with its subtree and not drawn)

  Example: Notify from a setter

  ```rust
  use vanilla::ComponentBase;
  
  let component_base = ComponentBase::new();
  component_base.mark_drawn_rect_dirty();
  ```

- `pub fn mark_all_drawn_rects_dirty()` (static, since 0.4.0): Tells that the drawn rects of all components changed. (original Component.markAllDrawnRectsDirty, e.g. when a newly loaded font changes text widths)
  - Raises the generation by one so every node recomputes its bounds the next time they are read.

  Example: The generation goes up

  ```rust
  use vanilla::ComponentBase;
  
  let generation = ComponentBase::get_drawn_rect_generation();
  ComponentBase::mark_all_drawn_rects_dirty();
  assert!(ComponentBase::get_drawn_rect_generation() > generation);
  ```

- `pub fn get_drawn_rect_generation() -> u64` (static, since 0.4.0): Component drawn rect generation. (original Component.getDrawnRectGeneration, goes up by one on every mark_all_drawn_rects_dirty)
  - returns u64: Current generation. (from 1)

## Component (trait) (AsAny, Reflect)

Component trait.
- In the original every object is reflected. The Rust edition makes reflection (Reflect) a supertrait, so a component without reflection cannot exist.
  The one way to make a component is `#[vanilla::reflect]`. Put it on both the type's impl block and the impl block of this trait.
  A type without getters takes it on an empty block, `#[vanilla::reflect] impl Type {}`. If it is left out, a compile error points at where to add it.
- UI document saving and the DevTools inspector upcast `&dyn Component` to `&dyn Reflect` (trait upcasting) and handle the properties of every component like the original.

Example: Create a component that rotates the node, attach it and tick

```rust
use vanilla::{reflect, Component, ComponentBase, ComponentContext, Engine, EngineConfiguration, NodeTree};

struct Spin {
	component_base: ComponentBase,
	degrees_per_second: f64,
}

#[reflect]
impl Spin {
	pub fn get_degrees_per_second(&self) -> f64 {
		self.degrees_per_second
	}

	pub fn set_degrees_per_second(&mut self, degrees_per_second: f64) {
		self.degrees_per_second = degrees_per_second;
	}
}

#[reflect]
impl Component for Spin {
	fn get_component_base(&self) -> &ComponentBase {
		&self.component_base
	}

	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
		&mut self.component_base
	}

	fn get_component_type(&self) -> &'static str {
		"Spin"
	}

	fn tick(&mut self, context: &mut ComponentContext, time_delta: f64) {
		let transform = context.get_transform_mut();
		let local_rotation = transform.get_local_rotation();
		transform.set_local_rotation(local_rotation + self.degrees_per_second * time_delta);
	}
}

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let node_id = node_tree.create_child(root_id, "spinner");
node_tree[node_id].add_component(Spin {
	component_base: ComponentBase::new(),
	degrees_per_second: 90.0,
});
node_tree.tick(&engine, 0.5);
assert_eq!(node_tree[node_id].get_local_rotation(), 45.0);
```

- `fn get_component_base(&self) -> &ComponentBase` (method, since 0.3.2): Returns the common state.
  - returns &ComponentBase: The ComponentBase held by the implementor.
- `fn get_component_base_mut(&mut self) -> &mut ComponentBase` (method, since 0.3.2): Returns the common state. (mutable)
  - returns &mut ComponentBase: The ComponentBase held by the implementor. (mutable)
- `fn get_component_type(&self) -> &'static str` (method, since 0.3.2): Component name. (the original getComponentType)
  - returns &'static str: Type name. (usually the struct name as is, the ComponentType value in reflection)
- `fn attach(&mut self, _transform: &mut NodeTransform)` (method, since 0.3.2): When attached to a node. (called by both WorldNode::add_component and NodeTree::add_component)
  - `_transform` &mut NodeTransform: Transform of the node it attaches to. (may be changed here)
- `fn detach(&mut self, _transform: &mut NodeTransform)` (method, since 0.4.0): When detached from a node. (called by WorldNode::remove_component)
  - `_transform` &mut NodeTransform: Transform of the node it detaches from.
- `fn require(&self) -> Vec<RequiredComponent>` (method, since 0.4.0): List of dependent components. (created and attached before attaching if the same node lacks them, the original's Unity RequireComponent idea)
  - returns Vec<RequiredComponent>: List of dependent components. (empty list by default)
- `fn attach_to_tree(&mut self, _node_tree: &mut NodeTree, _node_id: NodeId)` (method, since 0.3.2): When attached to a node inside the tree. (called only by NodeTree::add_component. Components that create child nodes create them here)
  - Where the original UIView.attach creates and attaches the content node. Such components are attached with node_tree.add_component.
  - `_node_tree` &mut NodeTree: The tree holding the node. (meanwhile this component is taken out of the node and a placeholder holds its place)
  - `_node_id` NodeId: The node this component attaches to.

  Example: A component that creates a label child node when attached

  ```rust
  use vanilla::{Component, ComponentBase, NodeId, NodeTree};
  
  struct Badge {
  	component_base: ComponentBase,
  	label_id: Option<NodeId>,
  }
  
  #[vanilla::reflect]
  impl Badge {}
  
  #[vanilla::reflect]
  impl Component for Badge {
  	fn get_component_base(&self) -> &ComponentBase {
  		&self.component_base
  	}
  
  	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
  		&mut self.component_base
  	}
  
  	fn get_component_type(&self) -> &'static str {
  		"Badge"
  	}
  
  	fn attach_to_tree(&mut self, node_tree: &mut NodeTree, node_id: NodeId) {
  		self.label_id = Some(node_tree.create_child(node_id, "label"));
  	}
  }
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = node_tree.create_child(root_id, "badge");
  let badge = node_tree.add_component(node_id, Badge {
  	component_base: ComponentBase::new(),
  	label_id: None,
  }).expect("badge");
  let label_id = badge.label_id.expect("label");
  assert_eq!(node_tree.get_parent_id(label_id), Some(node_id));
  ```

- `fn tick(&mut self, _context: &mut ComponentContext, _time_delta: f64)` (method, since 0.3.2): Periodic update.
  - Called by NodeTree::tick when the node and all its ancestors are active, this component is enabled, and is_tick_needed is true.
  - `_context` &mut ComponentContext: Context to take out its own node, the whole tree and the engine.
  - `_time_delta` f64: Time elapsed since the last tick. (seconds)
- `fn is_tick_needed(&self) -> bool` (method, since 0.3.2): Whether tick has work to do. (if false, this component is not called when visiting nodes. Default true)
  - false for Paint, Sprite, Text and Mask, which only draw. A node with only such components is not taken out on tick.
  - returns bool: true if tick needs to be called.
- `fn push_transform(&mut self, _transform: &NodeTransform, _graphic: &mut Graphic)` (method, since 0.4.0): Begins the node drawing state. (right after the node transform is applied, before drawing this node's components and children. Where the original overrode the node's pushTransform)
  - Graphic state changed here applies to this node and all its descendants. It is restored in pop_transform. Called only for enabled components, in attach order.
  - `_transform` &NodeTransform: This node's transform.
  - `_graphic` &mut Graphic: The Graphic being drawn to. (the node transform and opacity are applied)

  Example: A component that draws the node and all its descendants semi-transparent

  ```rust
  use vanilla::{Component, ComponentBase, Graphic, NodeTransform};
  
  struct HalfFade {
  	component_base: ComponentBase,
  	saved_alpha: f64,
  }
  
  #[vanilla::reflect]
  impl HalfFade {}
  
  #[vanilla::reflect]
  impl Component for HalfFade {
  	fn get_component_base(&self) -> &ComponentBase {
  		&self.component_base
  	}
  
  	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
  		&mut self.component_base
  	}
  
  	fn get_component_type(&self) -> &'static str {
  		"HalfFade"
  	}
  
  	fn push_transform(&mut self, _transform: &NodeTransform, graphic: &mut Graphic) {
  		self.saved_alpha = graphic.get_global_alpha();
  		graphic.multiply_global_alpha(0.5);
  	}
  
  	fn pop_transform(&mut self, _transform: &NodeTransform, graphic: &mut Graphic) {
  		graphic.set_global_alpha(self.saved_alpha);
  	}
  }
  ```

- `fn pop_transform(&mut self, _transform: &NodeTransform, _graphic: &mut Graphic)` (method, since 0.4.0): Ends the node drawing state. (after drawing all children and gizmos, before releasing the node transform. Where the original overrode the node's popTransform, called in reverse attach order)
  - `_transform` &NodeTransform: This node's transform.
  - `_graphic` &mut Graphic: The Graphic being drawn to. (the state changed in push_transform is restored here)
- `fn draw(&mut self, _transform: &NodeTransform, _graphic: &mut Graphic)` (method, since 0.3.2): Draw. (called with the node transform applied. The origin is the top left of the node's content_size area)
  - `_transform` &NodeTransform: This node's transform. (content_size decides the size to draw)
  - `_graphic` &mut Graphic: Graphic to draw to.
- `fn write_geometry_key(&self, _transform: &NodeTransform, _geometry_key: &mut GeometryKey) -> bool` (method, since 0.4.0): Writes the drawing inputs into the geometry cache key. (Graphic::draw_component calls it before draw, original writeGeometryKey)
  - Only a component that returns true has the vertices Graphic drew cached; if the written inputs and the transform are unchanged, draw is not called.
  - Every value draw reads (color, size, text, image and so on) must be written. If one is missing, a change is missed. (Default false, not cached)
  - `_transform` &NodeTransform: The transform of this node. (content_size is read)
  - `_geometry_key` &mut GeometryKey: The key to write into.
  - returns bool: true if all inputs were written.

  Example: Write the inputs of a component drawn only with a color and a size

  ```rust
  use vanilla::{Color, Component, ComponentBase, GeometryKey, Graphic, NodeTransform, Rect};
  
  #[derive(Default)]
  struct Box2D {
  	component_base: ComponentBase,
  	color: Color,
  }
  
  #[vanilla::reflect]
  impl Box2D {}
  
  #[vanilla::reflect]
  impl Component for Box2D {
  	fn get_component_base(&self) -> &ComponentBase {
  		&self.component_base
  	}
  
  	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
  		&mut self.component_base
  	}
  
  	fn get_component_type(&self) -> &'static str {
  		"Box2D"
  	}
  
  	fn write_geometry_key(&self, transform: &NodeTransform, geometry_key: &mut GeometryKey) -> bool {
  		geometry_key.add(self.color);
  		geometry_key.add(transform.get_content_size());
  		true
  	}
  
  	fn draw(&mut self, transform: &NodeTransform, graphic: &mut Graphic) {
  		let content_size = transform.get_content_size();
  		graphic.set_fill_color(self.color);
  		graphic.draw_rect(Rect::create(0.0, 0.0, content_size.x, content_size.y));
  	}
  }
  
  let box_2d = Box2D::default();
  let mut geometry_key = GeometryKey::new();
  geometry_key.begin();
  println!("{} {}", box_2d.write_geometry_key(&NodeTransform::default(), &mut geometry_key), geometry_key.end());
  ```

- `fn draw_gizmos(&mut self, _transform: &NodeTransform, _graphic: &mut Graphic)` (method, since 0.3.2): Draws gizmos.
  - Called when the node's gizmos are drawn (the node's gizmo display or the Graphic's forced gizmo display) and this component's gizmo display is on.
  - `_transform` &NodeTransform: This node's transform.
  - `_graphic` &mut Graphic: Graphic to draw to. (the node transform is applied)
- `fn get_clip_round_size(&self) -> Option<f64>` (method, since 0.3.2): Whether to clip child drawing to this area. (only Mask returns Some(round size))
  - returns Option<f64>: Corner round size of the clip area. (node coordinates, 0 is a sharp rectangle) None if not clipping.
- `fn is_drawn_inside_content(&self) -> bool` (method, since 0.3.2): Whether it draws only inside the node's content_size area. (if true, the engine skips draw when the area is off screen)
  - true for Paint, Sprite and Mask. false for things that go outside the area, such as text and particles. (default false)
  - returns bool: true if it draws only inside the content_size area.
- `fn is_draw_overridden(&self) -> bool` (method, since 0.4.0): Whether draw is overridden. (the original checks whether component.draw differs from Component.prototype.draw)
  - false means a component that draws nothing, so it is left out of off-screen culling and subtree draw bounds. (like ButtonMotion, UINode)
  - When an impl Component block with #[reflect] has no fn draw, the macro generates a version that returns false. Without the macro the default is true. (treated as drawing somewhere unknown)
  - returns bool: true if draw is overridden.
- `fn mark_drawn_rect_dirty(&self)` (method, since 0.4.0): Tells the node that the drawn rect (calculate_drawn_rect) changed. (original Component.markDrawnRectDirty, ComponentBase::mark_drawn_rect_dirty)
- `fn calculate_drawn_rect(&mut self, transform: &NodeTransform, _graphic: &mut Graphic) -> Option<Rect>` (method, since 0.4.0): The rectangle actually drawn, used for off-screen culling. (the node's content coordinates, called with the same Graphic transform as draw)
  - None means unknown, so the node is not culled. If all of the node's enabled components give a rectangle, the node is culled when their union is off screen.
  - By default, the content area if is_drawn_inside_content is true and there is a content_size, otherwise None.
  - Components that also draw outside content due to alignment, overflow or wrapping, such as text, compute and return a generous drawn rectangle.
  - `transform` &NodeTransform: This node's transform.
  - `_graphic` &mut Graphic: Graphic used for drawing. (has the same transform applied as draw, Text uses it to measure text size)
  - returns Option<Rect>: The drawn rectangle. (the node's content coordinates, top left is the origin) None if unknown.
- `fn touch_press(&mut self, _context: &mut ComponentContext, _view_input_position: Vector2)` (method, since 0.3.2): Touch press. (when the node is interactable and on top)
  - `_context` &mut ComponentContext: Context to take out its own node, the whole tree and the engine.
  - `_view_input_position` Vector2: Touch position. (view coordinates)
- `fn touch_move(&mut self, _context: &mut ComponentContext, _view_input_position: Vector2)` (method, since 0.3.2): Touch move. (to the pressed node)
  - `_context` &mut ComponentContext: Context to take out its own node, the whole tree and the engine.
  - `_view_input_position` Vector2: Touch position. (view coordinates)
- `fn touch_release(&mut self, _context: &mut ComponentContext, _view_input_position: Vector2)` (method, since 0.3.2): Touch release. (to the pressed node)
  - `_context` &mut ComponentContext: Context to take out its own node, the whole tree and the engine.
  - `_view_input_position` Vector2: Touch position. (view coordinates)
- `fn touch_cancel(&mut self, _context: &mut ComponentContext, _view_input_position: Vector2)` (method, since 0.3.2): Touch cancel. (to the pressed node)
  - `_context` &mut ComponentContext: Context to take out its own node, the whole tree and the engine.
  - `_view_input_position` Vector2: Touch position. (view coordinates)
- `fn wheel(&mut self, _context: &mut ComponentContext, _wheel_delta: Vector2) -> bool` (method, since 0.3.2): Mouse wheel. (asked from the node under the touch up toward its parents. true if consumed, the original UIScrollView.wheel)
  - `_context` &mut ComponentContext: Context to take out its own node, the whole tree and the engine.
  - `_wheel_delta` Vector2: Wheel movement this frame. (pixels, y is positive when scrolling the content down)
  - returns bool: true if consumed. (stops asking further up the parents)
- `fn is_wheel_receiver(&self) -> bool` (method, since 0.4.0): Whether it is a view that receives the wheel. (true for scroll views. If the frontmost of the things covering that position is this component's node, it also receives the wheel over non-pressable things, NodeTree::dispatch_wheel_at)
  - returns bool: true if it is a view that receives the wheel.
- `fn get_intrinsic_content_size(&self) -> Vector2` (method, since 0.4.0): Intrinsic size. (UIKit's intrinsicContentSize, gathered by UINode. -1 on an axis means no preference, both -1 by default)
  - In the original, UINode reads it only from components that have this function (Text, RichText). In the Rust version the default -1 stands for "none".
  - returns Vector2: Intrinsic size. (-1 on an axis means no preference on that axis)
- `fn get_base_component(&self) -> Option<&dyn Component>` (method, since 0.4.0): The embedded base component. (in place of the original superclass, like the Sprite of ShaderSprite or the UIControl of UIButton)
  - get_component, get_components, has_component and remove_component follow this chain and also find base types, like the original instanceof.
  - Only components that embed another component to port the original inheritance override it.
  - returns Option<&dyn Component>: The embedded base component. None if there is no base. (default)
- `fn get_base_component_mut(&mut self) -> Option<&mut dyn Component>` (method, since 0.4.0): The embedded base component. (mutable)
  - returns Option<&mut dyn Component>: The embedded base component. (mutable) None if there is no base. (default)
- `fn is_enable(&self) -> bool` (method, since 0.3.2): Whether enabled.
  - returns bool: true if enabled. (the ComponentBase value)
- `fn set_enable(&mut self, is_enable: bool)` (method, since 0.3.2): Sets active.
  - `is_enable` bool: Whether to enable. (if false, it is skipped in tick, drawing, touch and wheel)
- `fn is_gizmo_visible(&self) -> bool` (method, since 0.3.2): Whether gizmos are drawn.
  - returns bool: true if gizmos are drawn. (the ComponentBase value)
- `fn set_gizmo_visible(&mut self, is_gizmo_visible: bool)` (method, since 0.3.2): Sets gizmo drawing.
  - `is_gizmo_visible` bool: Whether to also call this component's draw_gizmos when drawing the node's gizmos.
