# core/inputactions (vanilla-engine 0.4.0)

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

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.

## InputActionSource (trait)

External input source. (implemented when the game plugs in something like a platform SDK's pad)
- InputActions.update calls read_action_value for each bound action every frame, and calls read_move_axis once.

Example: A source that always presses "confirm" and pushes to the right

```rust
use vanilla::{GamepadKind, InputActionSource, InputActions, InputManager, Vector2};

struct ScriptedSource;

impl InputActionSource for ScriptedSource {
	fn read_action_value(&mut self, action: &str) -> f64 {
		if action == "confirm" {
			1.0
		}
		else {
			0.0
		}
	}

	fn read_move_axis(&mut self) -> Option<Vector2> {
		Some(Vector2::create(2.0, 0.0))
	}

	fn read_gamepad_kind(&mut self) -> Option<GamepadKind> {
		Some(GamepadKind::Nintendo)
	}
}

let mut input_manager = InputManager::new();
let mut input_actions = InputActions::new();
input_actions.bind_key("confirm", "Enter");
input_actions.add_source(Box::new(ScriptedSource));
input_actions.update(&mut input_manager, 1.0 / 60.0);
assert!(input_actions.is_pressed("confirm"));
assert_eq!(input_actions.read_move_axis(), Vector2::create(1.0, 0.0));
assert_eq!(input_manager.get_last_gamepad_kind(), GamepadKind::Nintendo);
```

- `fn read_action_value(&mut self, action: &str) -> f64` (method, since 0.4.0): Value of the action. (0 ~ 1, pressed at 0.5 or more, 0 for an unknown action)
  - `action` &str: Action name. (one recorded with bind_key and the like or set_repeat)
  - returns f64: Value of that action. (clamped to 0 ~ 1, treated as 0 if not a number)
- `fn read_move_axis(&mut self) -> Option<Vector2>` (method, since 0.4.0): Move axis. (right +x down +y, clamped to length 1 or less, None if absent)
  - returns Option<Vector2>: Move direction for this frame. None if this source has no move axis. (the default implementation returns None)
- `fn read_gamepad_kind(&mut self) -> Option<GamepadKind>` (method, since 0.4.0): Pad type to record as the last device in a frame where this source gave input. (not recorded if None)
  - returns Option<GamepadKind>: Pad type. Asked only when an action value is 0.5 or more or the move axis is longer than the dead zone. (the default implementation returns None)

## InputActions (struct) (Default)

Input actions.
- Only actions recorded once with one of bind_key, bind_gamepad_button, bind_axis or set_repeat are updated.

Example: Bind one key to an action and update one frame

```rust
use vanilla::{InputActions, InputManager, KeyCode};

let mut input_manager = InputManager::new();
let mut input_actions = InputActions::new();
input_actions.bind_key("jump", KeyCode::SPACE);
input_actions.bind_key("jump", KeyCode::W);
input_manager.push_key(KeyCode::W);
input_actions.update(&mut input_manager, 1.0 / 60.0);
assert!(input_actions.is_just_pressed("jump"));
assert_eq!(input_actions.read_value("jump"), 1.0);
assert_eq!(input_actions.read_move_axis().y, -1.0);
```

Example: Bind and read the engine's input actions in a scene

```rust
use vanilla::{Engine, EngineConfiguration, GamepadButtonCode, KeyCode, Scene, SceneBase};

struct MainScene {
	scene_base: SceneBase,
}

impl Scene for MainScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn load(&mut self, engine: &Engine) {
		let mut input_manager = engine.get_input_manager_mut();
		let mut input_actions = input_manager.get_input_actions_mut();
		input_actions.bind_key("confirm", KeyCode::ENTER);
		input_actions.bind_gamepad_button("confirm", GamepadButtonCode::A_CROSS);
	}

	fn tick(&mut self, time_delta: f64) {
		let engine = Engine::get_engine().unwrap();
		self.scene_base.tick(time_delta);
		let input_manager = engine.get_input_manager();
		let input_actions = input_manager.get_input_actions();
		if input_actions.is_just_pressed("confirm") {
			println!("confirm");
		}
		let move_axis = input_actions.read_move_axis();
		println!("{} {}", move_axis.x, move_axis.y);
	}
}

let engine_configuration = EngineConfiguration::new();
let engine = Engine::new(engine_configuration);
let main_scene = MainScene {
	scene_base: SceneBase::new(),
};
engine.run(Box::new(main_scene)).unwrap();
```

- `pub fn new() -> InputActions` (constructor, since 0.4.0): Constructor.
  - returns InputActions: Input actions with nothing bound. (dead zone 0.2, axis press tilt 0.5, ignoring keys while typing on)
- `pub fn bind_key(&mut self, action: &str, key: &str)` (method, since 0.4.0): Binds a key. (KeyboardEvent.code, a KeyCode value)
  - Binding the same key twice still counts as one.
  - `action` &str: Action name. (text chosen by the game)
  - `key` &str: Key name. (a KeyCode value)
- `pub fn bind_gamepad_button(&mut self, action: &str, button_code: usize)` (method, since 0.4.0): Binds a gamepad button. (GamepadButtonCode, all connected pads)
  - The value (read_value) is the button's analog value, treated as 1 if 0.
  - `action` &str: Action name.
  - `button_code` usize: Button index. (GamepadButtonCode)
- `pub fn bind_axis(&mut self, action: &str, axis_index: usize, direction: f64)` (method, since 0.4.0): Binds one side of a gamepad axis. (GamepadAnalogStickCode, the + side if direction is positive, the - side if negative, down is + on the Y axis)
  - It is pressed when tilted that way by set_axis_press_threshold, and the value (read_value) is the tilt with the dead zone subtracted.
  - `action` &str: Action name.
  - `axis_index` usize: Axis number. (GamepadAnalogStickCode)
  - `direction` f64: Side to watch. (the - side if negative, the + side if 0 or positive, the magnitude is not used)

  Example: "left" when the left stick is tilted left

  ```rust
  use vanilla::{Gamepad, GamepadAnalogStickCode, InputActions, InputManager};
  
  let mut input_manager = InputManager::new();
  input_manager.get_gamepad_manager_mut().set_log_enabled(false);
  let mut gamepad = Gamepad::create(0, "Test Pad");
  gamepad.axes[GamepadAnalogStickCode::LEFT_X] = -0.6;
  input_manager.get_gamepad_manager_mut().update_all_gamepads_with_list(vec![Some(gamepad)]);
  let mut input_actions = InputActions::new();
  input_actions.bind_axis("left", GamepadAnalogStickCode::LEFT_X, -1.0);
  input_actions.update(&mut input_manager, 1.0 / 60.0);
  assert!(input_actions.is_pressed("left"));
  assert!((input_actions.read_value("left") - 0.5).abs() < 0.0001);
  ```

- `pub fn unbind_action(&mut self, action: &str)` (method, since 0.4.0): Unbinds everything bound to an action. (before rebinding in a key remapping screen, repeat settings remain)
  - `action` &str: Action name.

  Example: Change the confirm key from Enter to Space

  ```rust
  use vanilla::{InputActions, KeyCode};
  
  let mut input_actions = InputActions::new();
  input_actions.bind_key("confirm", KeyCode::ENTER);
  input_actions.unbind_action("confirm");
  input_actions.bind_key("confirm", KeyCode::SPACE);
  assert_eq!(input_actions.get_bound_keys("confirm"), ["Space"]);
  ```

- `pub fn get_bound_keys(&self, action: &str) -> &[String]` (method, since 0.4.0): List of keys bound to the action. (for drawing button hints)
  - `action` &str: Action name.
  - returns &[String]: Key names in bind order. An empty slice if no keys are bound.
- `pub fn set_repeat(&mut self, action: &str, delay_seconds: f64, interval_seconds: f64)` (method, since 0.4.0): Sets repeat while held. (is_just_pressed is true every interval seconds after the wait seconds, an interval of 0 or less turns repeat off)
  - Repeats are not bunched up even if a frame stalls for a long time.
  - `action` &str: Action name.
  - `delay_seconds` f64: Seconds to wait after the first press before repeating starts. (negative values become 0)
  - `interval_seconds` f64: Repeat interval in seconds. (0 or less turns repeat off)

  Example: Holding for 1 second gives the first press and eight repeats

  ```rust
  use vanilla::{InputActions, InputManager, KeyCode};
  
  let mut input_manager = InputManager::new();
  let mut input_actions = InputActions::new();
  input_actions.bind_key("right", KeyCode::RIGHT);
  input_actions.set_repeat("right", 0.25, 0.1);
  input_manager.push_key(KeyCode::RIGHT);
  let mut just_pressed_count = 0;
  for _ in 0..60 {
  	input_actions.update(&mut input_manager, 1.0 / 60.0);
  	if input_actions.is_just_pressed("right") {
  		just_pressed_count += 1;
  	}
  	input_manager.update_frame_snapshot();
  }
  assert_eq!(just_pressed_count, 9);
  ```

- `pub fn set_dead_zone(&mut self, dead_zone: f64)` (method, since 0.4.0): Sets the dead zone. (0 ~ less than 1, initially 0.2)
  - `dead_zone` f64: Length below which a tilt counts as 0. (clamped to 0 ~ 0.99)
- `pub fn get_dead_zone(&self) -> f64` (method, since 0.4.0): Dead zone.
  - returns f64: Current dead zone. (0 ~ 0.99, initially 0.2)
- `pub fn set_axis_press_threshold(&mut self, axis_press_threshold: f64)` (method, since 0.4.0): Sets the tilt at which an axis-bound action counts as pressed. (0 ~ 1, initially 0.5)
  - `axis_press_threshold` f64: Tilt that counts as pressed. (value before subtracting the dead zone, clamped to 0 ~ 1)
- `pub fn get_axis_press_threshold(&self) -> f64` (method, since 0.4.0): Tilt at which an action bound to an axis counts as pressed.
  - returns f64: Current tilt. (0 ~ 1, initially 0.5)
- `pub fn set_keys_ignored_while_typing(&mut self, is_ignored: bool)` (method, since 0.4.0): Sets whether keys are ignored while typing in a text field. (initially true)
  - `is_ignored` bool: true to not listen to keys (action keys and move keys) while typing.
- `pub fn is_keys_ignored_while_typing(&self) -> bool` (method, since 0.4.0): Whether keys are not listened to while typing in a text input.
  - returns bool: true if not listening. (initially true)
- `pub fn add_source(&mut self, source: Box<dyn InputActionSource>) -> u64` (method, since 0.4.0): Adds an external input source. (remove_source with the returned number)
  - `source` Box<dyn InputActionSource>: Source to plug in.
  - returns u64: Number of this source. (starts at 1 and grows by one with each add)

  Example: Plug in a source and remove it

  ```rust
  use vanilla::{InputActionSource, InputActions};
  
  struct SilentSource;
  
  impl InputActionSource for SilentSource {
  	fn read_action_value(&mut self, _action: &str) -> f64 {
  		0.0
  	}
  }
  
  let mut input_actions = InputActions::new();
  let source_id = input_actions.add_source(Box::new(SilentSource));
  assert!(input_actions.remove_source(source_id));
  assert!(!input_actions.remove_source(source_id));
  ```

- `pub fn remove_source(&mut self, source_id: u64) -> bool` (method, since 0.4.0): Removes an external input source. (true if it was there)
  - `source_id` u64: Number returned by add_source.
  - returns bool: true if a source with that number existed and was removed, false otherwise.
- `pub fn update(&mut self, input_manager: &mut InputManager, time_delta: f64)` (method, since 0.4.0): Per-frame update. (called by InputManager.tick)
  - If an external source gave input, records that pad as the last device of input_manager.
  - `input_manager` &mut InputManager: Input manager to read keys and gamepads from.
  - `time_delta` f64: Seconds elapsed since the last update. (counts repeat time)
- `pub fn clear(&mut self)` (method, since 0.4.0): Resets everything to released. (when the window loses focus, releases are not reported either)
- `pub fn is_pressed(&self, action: &str) -> bool` (method, since 0.4.0): Whether the action is held.
  - `action` &str: Action name.
  - returns bool: true if any bound key, button, axis or external source is pressed. false for an unknown action.
- `pub fn is_just_pressed(&self, action: &str) -> bool` (method, since 0.4.0): Whether it was pressed this frame. (also true on repeats for actions with set_repeat)
  - `action` &str: Action name.
  - returns bool: true if it was released at the last update and pressed at this update, or a repeat fired. false for an unknown action.
- `pub fn is_just_released(&self, action: &str) -> bool` (method, since 0.4.0): Whether it was released this frame.
  - `action` &str: Action name.
  - returns bool: true if it was pressed at the last update and released at this update. false for an unknown action.
- `pub fn read_value(&self, action: &str) -> f64` (method, since 0.4.0): The action's value. (0 ~ 1, 1 for keys and digital buttons, triggers and axes by how far they are tilted)
  - `action` &str: Action name.
  - returns f64: Largest value among the bindings. (0 ~ 1, axes are the value with the dead zone subtracted and rescaled) 0 for an unknown action.
- `pub fn read_axis(&self, negative_action: &str, positive_action: &str) -> f64` (method, since 0.4.0): An axis made from two actions. (-1 ~ 1, the difference between the two actions' values)
  - `negative_action` &str: Name of the - side action. (like "left")
  - `positive_action` &str: Name of the + side action. (like "right")
  - returns f64: Value of positive_action minus the value of negative_action. (close to 0 if both are pressed)

  Example: Make a horizontal axis from the left and right actions

  ```rust
  use vanilla::{InputActions, InputManager, KeyCode};
  
  let mut input_manager = InputManager::new();
  let mut input_actions = InputActions::new();
  input_actions.bind_key("left", KeyCode::LEFT);
  input_actions.bind_key("right", KeyCode::RIGHT);
  input_manager.push_key(KeyCode::LEFT);
  input_actions.update(&mut input_manager, 1.0 / 60.0);
  assert_eq!(input_actions.read_axis("left", "right"), -1.0);
  ```

- `pub fn read_gamepad_stick(&self, x_axis_index: usize, y_axis_index: usize) -> Vector2` (method, since 0.4.0): Gamepad stick. (the most tilted among connected pads, dead zone subtracted by length, length 1 or less, right +x down +y)
  - Reads the values recorded at the last update. Only axis numbers 0 ~ 3 are recorded.
  - `x_axis_index` usize: Horizontal axis number. (GamepadAnalogStickCode::LEFT_X or RIGHT_X)
  - `y_axis_index` usize: Vertical axis number. (GamepadAnalogStickCode::LEFT_Y or RIGHT_Y)
  - returns Vector2: Stick direction and length with the dead zone subtracted. (0, 0 if no pad is connected or inside the dead zone)

  Example: Read the right stick

  ```rust
  use vanilla::{Gamepad, GamepadAnalogStickCode, InputActions, InputManager};
  
  let mut input_manager = InputManager::new();
  input_manager.get_gamepad_manager_mut().set_log_enabled(false);
  let mut gamepad = Gamepad::create(0, "Test Pad");
  gamepad.axes[GamepadAnalogStickCode::RIGHT_Y] = 1.0;
  input_manager.get_gamepad_manager_mut().update_all_gamepads_with_list(vec![Some(gamepad)]);
  let mut input_actions = InputActions::new();
  input_actions.update(&mut input_manager, 1.0 / 60.0);
  let stick = input_actions.read_gamepad_stick(GamepadAnalogStickCode::RIGHT_X, GamepadAnalogStickCode::RIGHT_Y);
  assert_eq!(stick.x, 0.0);
  assert!((stick.y - 1.0).abs() < 0.0001);
  ```

- `pub fn read_move_axis(&self) -> Vector2` (method, since 0.4.0): Movement axis. (the longest of WASD and arrow keys, the left stick, and external sources' movement axes, length 1 or less, right +x down +y)
  - Keys have length 1 diagonally too. Keys are not listened to while typing in a text field.
  - returns Vector2: Move direction. (length 0 ~ 1, the value at the last update)

  Example: Diagonal with W and D pressed together

  ```rust
  use vanilla::{InputActions, InputManager, KeyCode};
  
  let mut input_manager = InputManager::new();
  let mut input_actions = InputActions::new();
  input_manager.push_key(KeyCode::W);
  input_manager.push_key(KeyCode::D);
  input_actions.update(&mut input_manager, 1.0 / 60.0);
  let move_axis = input_actions.read_move_axis();
  assert!((move_axis.x - std::f64::consts::FRAC_1_SQRT_2).abs() < 0.0001);
  assert!((move_axis.y + std::f64::consts::FRAC_1_SQRT_2).abs() < 0.0001);
  ```

