# core/inputactions (vanilla-engine 0.4.0)

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

입력 동작.
- 원본 core/inputactions.js 를 옮겼다. 동작 이름("confirm", "left" 같은 게임이 정한 글)에 키, 게임패드 단추, 게임패드 축의 한쪽을 묶는다.
  한 동작에 여럿을 묶을 수 있고, 하나라도 눌렸으면 눌린 것이다.
- 엔진의 InputManager 가 하나 들고(get_input_actions) 프레임 첫머리의 tick 에서 update 를 부른다. 게임은 읽기만 한다.
- 키는 프레임 사이에 눌렀다 뗀 것도 그 프레임에 한 번 눌린 것으로 본다. (InputManager.is_key_just_pressed)
- set_repeat 를 건 동작은 누르고 있으면 기다린 뒤부터 간격마다 is_just_pressed 가 다시 참이 된다. (메뉴 고르기)
- 축은 죽은 구역(set_dead_zone)을 빼고 나머지를 0 ~ 1 로 다시 편다. 스틱은 길이로, 묶은 축은 한쪽 값으로 거른다.
- 바깥 입력원(add_source)은 엔진이 모르는 입력(플랫폼 SDK 의 패드 같은 것)을 게임이 끼우는 자리다. InputActionSource 트레이트를 단다.
- 글자 입력칸에 쓰는 동안은 키를 듣지 않는다. (set_keys_ignored_while_typing 으로 끈다)
- 유니티 Input System 처럼 프레임 처음의 update 에서 한 번 갱신하고, 그 프레임 안의 읽기는 그때 적은 값이다. (원본과 같다)
  update 때 이동 키, 패드 축, 바깥 입력원의 이동 축을 적어 두고 read_gamepad_stick, read_move_axis 가 그 값을 읽는다.
- 원본과 다른 점: 바깥 입력원은 JS 객체 대신 트레이트이고, 빼기는 add_source 가 준 번호로 한다.

## InputActionSource (trait)

바깥 입력원. (게임이 플랫폼 SDK 의 패드 같은 것을 끼울 때 단다)
- InputActions.update 가 프레임마다 묶어 둔 동작마다 read_action_value 를 부르고, 한 번 read_move_axis 를 부른다.

예제: 늘 "confirm" 을 누르고 오른쪽으로 미는 입력원

```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): 동작의 값. (0 ~ 1, 0.5 이상이면 눌림, 모르는 동작이면 0)
  - `action` &str: 동작 이름. (bind_key 들이나 set_repeat 로 적어 둔 것)
  - returns f64: 그 동작의 값. (0 ~ 1 로 자르고, 수가 아니면 0 으로 본다)
- `fn read_move_axis(&mut self) -> Option<Vector2>` (method, since 0.4.0): 이동 축. (오른쪽 +x 아래 +y, 길이 1 이하로 자른다, 없으면 None)
  - returns Option<Vector2>: 이번 프레임의 이동 방향. 이 입력원에 이동 축이 없으면 None. (기본 구현은 None)
- `fn read_gamepad_kind(&mut self) -> Option<GamepadKind>` (method, since 0.4.0): 이 입력원이 입력을 넣은 프레임에 마지막 장치로 적을 패드 종류. (None 이면 적지 않는다)
  - returns Option<GamepadKind>: 패드 종류. 동작 값이 0.5 이상이거나 이동 축이 죽은 구역보다 길 때만 묻는다. (기본 구현은 None)

## InputActions (struct) (Default)

입력 동작.
- 동작은 bind_key, bind_gamepad_button, bind_axis, set_repeat 가운데 하나로 한 번 적어 둔 것만 갱신한다.

예제: 키 하나를 동작에 묶고 한 프레임 갱신하기

```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);
```

예제: 씬에서 엔진의 입력 동작 묶고 읽기

```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): 생성.
  - returns InputActions: 묶은 것이 없는 입력 동작. (죽은 구역 0.2, 축 눌림 기울기 0.5, 글자 입력 중 키 무시 켬)
- `pub fn bind_key(&mut self, action: &str, key: &str)` (method, since 0.4.0): 키 묶기. (KeyboardEvent.code, KeyCode 의 값)
  - 같은 키를 두 번 묶어도 하나다.
  - `action` &str: 동작 이름. (게임이 정한 글)
  - `key` &str: 키 이름. (KeyCode 의 값)
- `pub fn bind_gamepad_button(&mut self, action: &str, button_code: usize)` (method, since 0.4.0): 게임패드 단추 묶기. (GamepadButtonCode, 연결된 패드 모두)
  - 값(read_value)은 그 단추의 아날로그 값이고, 0 이면 1 로 본다.
  - `action` &str: 동작 이름.
  - `button_code` usize: 버튼 번호. (GamepadButtonCode)
- `pub fn bind_axis(&mut self, action: &str, axis_index: usize, direction: f64)` (method, since 0.4.0): 게임패드 축의 한쪽 묶기. (GamepadAnalogStickCode, direction 이 양수면 + 쪽, 음수면 - 쪽, 축 Y 는 아래가 +)
  - 그쪽으로 set_axis_press_threshold 만큼 기울면 눌린 것이고, 값(read_value)은 죽은 구역을 뺀 기울기다.
  - `action` &str: 동작 이름.
  - `axis_index` usize: 축 번호. (GamepadAnalogStickCode)
  - `direction` f64: 볼 쪽. (음수면 - 쪽, 0 이나 양수면 + 쪽, 크기는 쓰지 않는다)

  예제: 왼쪽 스틱을 왼쪽으로 기울이면 "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): 동작에 묶은 것 모두 풀기. (키 바꾸기 화면에서 다시 묶기 전에, 반복 설정은 남는다)
  - `action` &str: 동작 이름.

  예제: 확인 키를 엔터에서 스페이스로 바꾸기

  ```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): 동작에 묶은 키 목록. (단추 안내를 그릴 때)
  - `action` &str: 동작 이름.
  - returns &[String]: 묶은 차례의 키 이름들. 묶은 키가 없으면 빈 조각.
- `pub fn set_repeat(&mut self, action: &str, delay_seconds: f64, interval_seconds: f64)` (method, since 0.4.0): 누르고 있으면 반복 설정. (기다리는 초 뒤부터 간격 초마다 is_just_pressed 가 참, 간격이 0 이하면 반복을 끈다)
  - 프레임이 길게 끊겨도 반복을 몰아서 하지 않는다.
  - `action` &str: 동작 이름.
  - `delay_seconds` f64: 첫 누름 뒤 반복을 시작할 때까지 기다리는 초. (음수는 0)
  - `interval_seconds` f64: 반복 간격 초. (0 이하면 반복을 끈다)

  예제: 1 초 동안 누르고 있으면 첫 누름과 반복 여덟 번

  ```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): 죽은 구역 설정. (0 ~ 1 미만, 처음은 0.2)
  - `dead_zone` f64: 이보다 덜 기울면 0 으로 보는 길이. (0 ~ 0.99 로 자른다)
- `pub fn get_dead_zone(&self) -> f64` (method, since 0.4.0): 죽은 구역.
  - returns f64: 지금 죽은 구역. (0 ~ 0.99, 처음은 0.2)
- `pub fn set_axis_press_threshold(&mut self, axis_press_threshold: f64)` (method, since 0.4.0): 축에 묶은 동작을 눌린 것으로 보는 기울기 설정. (0 ~ 1, 처음은 0.5)
  - `axis_press_threshold` f64: 눌림으로 볼 기울기. (죽은 구역을 빼기 전 값, 0 ~ 1 로 자른다)
- `pub fn get_axis_press_threshold(&self) -> f64` (method, since 0.4.0): 축에 묶은 동작을 눌린 것으로 보는 기울기.
  - returns f64: 지금 기울기. (0 ~ 1, 처음은 0.5)
- `pub fn set_keys_ignored_while_typing(&mut self, is_ignored: bool)` (method, since 0.4.0): 글자 입력칸에 쓰는 동안 키를 듣지 않을지 설정. (처음은 참)
  - `is_ignored` bool: 쓰는 동안 키(동작의 키와 이동 키)를 듣지 않으려면 true.
- `pub fn is_keys_ignored_while_typing(&self) -> bool` (method, since 0.4.0): 글자 입력칸에 쓰는 동안 키를 듣지 않는지.
  - returns bool: 듣지 않으면 true. (처음은 true)
- `pub fn add_source(&mut self, source: Box<dyn InputActionSource>) -> u64` (method, since 0.4.0): 바깥 입력원 더하기. (돌려주는 번호로 remove_source 한다)
  - `source` Box<dyn InputActionSource>: 끼울 입력원.
  - returns u64: 이 입력원의 번호. (1 부터 더할 때마다 하나씩 커진다)

  예제: 입력원을 끼웠다 빼기

  ```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): 바깥 입력원 빼기. (있었으면 true)
  - `source_id` u64: add_source 가 돌려준 번호.
  - returns bool: 그 번호의 입력원이 있어 뺐으면 true, 없으면 false.
- `pub fn update(&mut self, input_manager: &mut InputManager, time_delta: f64)` (method, since 0.4.0): 프레임마다 갱신. (InputManager.tick 이 부른다)
  - 바깥 입력원이 입력을 넣었으면 input_manager 의 마지막 장치를 그 패드로 적는다.
  - `input_manager` &mut InputManager: 키와 게임패드를 읽을 입력 관리자.
  - `time_delta` f64: 지난 갱신 뒤로 흐른 초. (반복 시간을 센다)
- `pub fn clear(&mut self)` (method, since 0.4.0): 모두 뗀 것으로 되돌리기. (창이 포커스를 잃었을 때, 뗌도 알리지 않는다)
- `pub fn is_pressed(&self, action: &str) -> bool` (method, since 0.4.0): 동작이 눌려 있는지.
  - `action` &str: 동작 이름.
  - returns bool: 묶은 키, 단추, 축, 바깥 입력원 가운데 하나라도 눌렸으면 true. 모르는 동작이면 false.
- `pub fn is_just_pressed(&self, action: &str) -> bool` (method, since 0.4.0): 이번 프레임에 눌렸는지. (set_repeat 를 건 동작은 반복 때도 참)
  - `action` &str: 동작 이름.
  - returns bool: 지난 갱신에 떼어 있다가 이번 갱신에 눌렸거나 반복이 났으면 true. 모르는 동작이면 false.
- `pub fn is_just_released(&self, action: &str) -> bool` (method, since 0.4.0): 이번 프레임에 떼어졌는지.
  - `action` &str: 동작 이름.
  - returns bool: 지난 갱신에 눌려 있다가 이번 갱신에 떼어졌으면 true. 모르는 동작이면 false.
- `pub fn read_value(&self, action: &str) -> f64` (method, since 0.4.0): 동작의 값. (0 ~ 1, 키와 디지털 단추는 1, 트리거와 축은 기운 만큼)
  - `action` &str: 동작 이름.
  - returns f64: 묶은 것 가운데 가장 큰 값. (0 ~ 1, 축은 죽은 구역을 빼고 다시 편 값) 모르는 동작이면 0.
- `pub fn read_axis(&self, negative_action: &str, positive_action: &str) -> f64` (method, since 0.4.0): 두 동작으로 만든 축. (-1 ~ 1, 양쪽 동작의 값의 차)
  - `negative_action` &str: - 쪽 동작 이름. ("left" 같은)
  - `positive_action` &str: + 쪽 동작 이름. ("right" 같은)
  - returns f64: positive_action 의 값에서 negative_action 의 값을 뺀 것. (둘 다 눌리면 0 에 가깝다)

  예제: 왼쪽, 오른쪽 동작으로 가로 축 만들기

  ```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): 게임패드 스틱. (연결된 패드 가운데 가장 크게 기운 것, 죽은 구역을 길이로 빼고 길이 1 이하, 오른쪽 +x 아래 +y)
  - 마지막 update 때 적어 둔 값을 읽는다. 축 번호는 0 ~ 3 만 적어 둔다.
  - `x_axis_index` usize: 가로 축 번호. (GamepadAnalogStickCode::LEFT_X 나 RIGHT_X)
  - `y_axis_index` usize: 세로 축 번호. (GamepadAnalogStickCode::LEFT_Y 나 RIGHT_Y)
  - returns Vector2: 스틱 방향과 죽은 구역을 뺀 길이. (연결된 패드가 없거나 죽은 구역 안이면 0, 0)

  예제: 오른쪽 스틱 읽기

  ```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): 이동 축. (WASD 와 방향키, 왼쪽 스틱, 바깥 입력원의 이동 축 가운데 가장 긴 것, 길이 1 이하, 오른쪽 +x 아래 +y)
  - 키는 대각선도 길이 1 이다. 글자 입력칸에 쓰는 동안은 키를 듣지 않는다.
  - returns Vector2: 이동 방향. (길이 0 ~ 1, 마지막 update 때의 값)

  예제: W 와 D 를 함께 누른 대각선

  ```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);
  ```

