vanilladocs
vanillapunch.com
API / core/gamepadmanager

core/gamepadmanager

게임패드 관리자.

  • 원본 core/gamepadmanager.js 를 옮겼다. 공개 이름(GamepadButtonCode, GamepadAnalogStickCode, GamepadTriggerCode, connect, disconnect, set_callback, update_all_gamepads, is_button_pressed, get_button_value, get_axis_value, get_all_connected_gamepads, get_connected_gamepad_count, get_connected_gamepad)과 갱신 규칙은 원본 그대로다. (값은 소수점 둘째 자리로 반올림, 축은 0.01 넘게 바뀔 때만 받기, 아날로그 값은 0 보다 클 때만 알리기, 로그 문구)
  • 원본은 navigator.getGamepads() 를 읽는다. 웹(wasm32)은 원본처럼 navigator.getGamepads() 를 직접 읽어 브라우저가 주는 버튼과 축을 모두 받고, 연결과 해제는 원본 engine.js 처럼 gamepadconnected / gamepaddisconnected 로 받는다. 데스크탑은 gilrs 가 OS 입력(윈도우는 Windows.Gaming.Input)을 읽고, 원본과 같은 W3C Standard Gamepad 꼴 (버튼 0~16, 축 0~3, 축 Y 는 아래가 양수)의 Gamepad 목록으로 바꾼 뒤 같은 규칙을 돌린다.
  • 원본과 다른 점:
  • gilrs 기본 필터(데드존, 떨림 거르기)는 끈다. 브라우저처럼 날값을 받고, 데드존은 원본처럼 게임이 건다.
  • 아날로그 버튼(트리거)의 눌림은 크로미엄과 같이 값이 30/255 를 넘을 때다. (gilrs 기본은 0.75 에 눌림, 0.65 에 뗌)
  • 축(햇 스위치)으로 오는 십자키는 버튼 12~15 로 바꾼다. (브라우저가 하는 일)
  • 데스크탑의 버튼은 표준 17개 뒤에 gilrs 가 표준 버튼으로 잇지 못한 단추(매핑에 없는 단추, gilrs 의 C, Z)를, 축은 표준 4개 뒤에 매핑에 없는 축을 처음 움직인 차례로 붙인다. gilrs 가 장치의 단추 목록을 내주지 않고 한 번이라도 움직인 단추만 알려서, 그 단추를 처음 누른 뒤에야 생긴다. 버튼이나 축 수가 늘면 그 패드의 상태 칸도 늘린다.
  • 플레이스테이션 패드(소니 054c 의 듀얼쇼크4 05c4, 09cc, 0ba0 와 듀얼센스 0ce6, 0df2, 0e5f)는 크롬(device/gamepad 의 MapperDualshock4, MapperDualSense)처럼 버튼 18개이고 원시 단추 13번(HID 단추 14)이 TOUCHPAD(17)다. 누르기 전에도 늘 있고, 그 밖의 단추(듀얼센스 마이크 단추)와 축은 붙이지 않는다. gilrs 가 SDL 매핑의 touchpad:b13 을 이름 없는 단추(Button::Unknown, misc1 과 같은 이름)로 잇기만 해서, 그 단추의 원시 코드를 플랫폼마다 정해 찾는다. (맥 IOKit 단추 쪽의 쓰임 14, 윈도우 Windows.Gaming.Input 의 단추 13번, 리눅스 hid-generic 의 BTN_GAMEPAD + 13) 리눅스의 hid-sony(커널 4.10 부터), hid-playstation(5.12 부터) 드라이버는 터치패드를 따로 장치로 내고 bcdHID 에 0x8000 을 붙인다. 그때는 크롬(MapperPs4Ps5)처럼 버튼 17개다. (gilrs 의 uuid 13, 14번째 바이트가 그 판 번호다) 맥 GameController 의 GCDualSenseGamepad.touchpadButton 도 있지만, GameController 는 패드의 제조사, 제품 번호를 내주지 않아 gilrs 패드와 짝짓지 못해 쓰지 않는다.
  • Gamepad.index 는 데스크탑에서는 gilrs 의 GamepadId 번호다. (처음 붙은 순서로 0 부터, 브라우저 index 와 같은 쓰임) 웹은 브라우저 index 다.
  • Gamepad.id 는 웹에서는 브라우저 id 그대로, 데스크탑에서는 크롬 꼴 "이름 (STANDARD GAMEPAD Vendor: 054c Product: 0ce6)" 로 만든다.
  • 콜백의 button 값은 bool 대신 1.0(눌림) / 0.0(뗌) 이다.
  • gilrs(웹은 연결 리스너)는 처음 부를 때(갱신, 진동, 패드 목록 읽기) 만든다. (부르지 않는 엔진과 시험에서는 장치를 열지 않는다)
  • get_all_connected_gamepads / get_connected_gamepad 는 원본 navigator.getGamepads() 처럼 부를 때 그 자리에서 읽은 사본을 돌려준다(&self). (데스크탑은 gilrs 사건을 비워 지금 상태, 그 사이의 연결과 해제는 다음 갱신이 받는다) update_all_gamepads_with_list 로 목록을 넣은 관리자(시험, 다른 입력원)는 넣은 목록을 돌려준다.
  • 더한 것: set_log_enabled (로그 켜고 끄기), update_all_gamepads_with_list (gilrs 없이 목록을 넣는 길. 시험이나 다른 입력원)
  • 배터리 정보는 원본에 없어 옮기지 않는다.
  • 단추와 축이 바뀔 때마다 찍는 로그는 원본처럼 set_input_log_enabled 로 켜고, 기본은 끔이다. set_log_enabled 는 연결과 해제를 포함한 모든 로그의 큰 스위치다.
  • GamepadKind, read_gamepad_kind: 패드 이름으로 종류(엑스박스, 플레이스테이션, 닌텐도, 그 밖)를 가른다. get_active_gamepad_id 는 마지막 갱신에 단추를 누르거나 축을 크게 기울인 패드다.
  • vibrate(strong_magnitude, weak_magnitude, seconds): 연결된 패드를 모두 떤다. 데스크탑은 gilrs force feedback(리눅스 evdev, 윈도우 XInput 과 Windows.Gaming.Input)으로 떨고, gilrs 가 진동을 대지 않는 macOS 는 플랫폼 층(platform/desktop/gamepadhaptics.rs)이 GameController 와 CoreHaptics 로 gilrs 패드와 짝인 컨트롤러를 떤다. (macOS 는 길이나 세기가 0 이면 앞 진동을 멈춘다) 그래서 gilrs 를 진동을 켠 채 만든다. (데스크탑에서 gilrs 의 진동 스레드 하나가 돈다) 웹은 원본처럼 navigator.getGamepads() 의 vibrationActuator 에 dual-rumble 을 건다. 첫 갱신(tick) 전에 불러도 그 자리에서 gilrs 를 만들어 떤다. (원본처럼)

Gamepad manager.

  • A port of the original core/gamepadmanager.js. The public names (GamepadButtonCode, GamepadAnalogStickCode, GamepadTriggerCode, connect, disconnect, set_callback, update_all_gamepads, is_button_pressed, get_button_value, get_axis_value, get_all_connected_gamepads, get_connected_gamepad_count, get_connected_gamepad) and the update rules are the same as the original. (values are rounded to two decimal places, axes are taken only when they change by more than 0.01, analog values are reported only when greater than 0, log messages)
  • The original reads navigator.getGamepads(). The web (wasm32) reads navigator.getGamepads() directly like the original and takes all buttons and axes the browser gives, and takes connection and disconnection through gamepadconnected / gamepaddisconnected like the original engine.js. On desktop, gilrs reads OS input (Windows.Gaming.Input on Windows), converts it to a Gamepad list in the same W3C Standard Gamepad form as the original (buttons 0~16, axes 0~3, axis Y is positive downward), then runs the same rules.
  • Differences from the original:
  • The gilrs default filters (deadzone, jitter filtering) are turned off. Raw values are taken like a browser, and the game applies the deadzone like the original.
  • An analog button (trigger) counts as pressed when its value exceeds 30/255, as in Chromium. (gilrs default presses at 0.75 and releases at 0.65)
  • A D-pad coming in as an axis (hat switch) is converted to buttons 12~15. (what the browser does)
  • On desktop, buttons that gilrs could not map to standard buttons (buttons missing from the mapping, gilrs C, Z) are appended after the 17 standard buttons, and axes missing from the mapping after the 4 standard axes, in the order they first move. gilrs does not give the device's button list and reports only buttons that have moved at least once, so such a button appears only after it is first pressed. When the number of buttons or axes grows, that pad's state slots grow too.
  • PlayStation pads (Sony 054c DualShock 4 05c4, 09cc, 0ba0 and DualSense 0ce6, 0df2, 0e5f) have 18 buttons like Chrome (MapperDualshock4, MapperDualSense in device/gamepad), and raw button 13 (HID button 14) is TOUCHPAD (17). It is always there even before being pressed, and other buttons (the DualSense mic button) and axes are not appended. gilrs only maps touchpad:b13 of the SDL mapping to an unnamed button (Button::Unknown, the same name as misc1), so the raw code of that button is found per platform. (usage 14 on the macOS IOKit button page, button 13 on Windows Windows.Gaming.Input, BTN_GAMEPAD + 13 on Linux hid-generic) The Linux hid-sony (from kernel 4.10) and hid-playstation (from 5.12) drivers expose the touchpad as a separate device and add 0x8000 to bcdHID. In that case it has 17 buttons like Chrome (MapperPs4Ps5). (the 13th and 14th bytes of the gilrs uuid are that version number) macOS GameController also has GCDualSenseGamepad.touchpadButton, but GameController does not give the pad's vendor and product numbers so it cannot be paired with a gilrs pad, and it is not used.
  • Gamepad.index on desktop is the gilrs GamepadId number. (from 0 in the order first connected, used like the browser index) On the web it is the browser index.
  • Gamepad.id on the web is the browser id as is, and on desktop it is built in Chrome form "name (STANDARD GAMEPAD Vendor: 054c Product: 0ce6)".
  • The button value of the callback is 1.0 (pressed) / 0.0 (released) instead of bool.
  • gilrs (on the web, the connection listeners) is created on the first call (update, vibration, pad list read). (engines and tests that never call it do not open devices)
  • get_all_connected_gamepads / get_connected_gamepad return copies read in place when called (&self), like the original navigator.getGamepads(). (desktop drains the gilrs events for the current state, and the next update receives the connects and disconnects in between) A manager fed with update_all_gamepads_with_list (tests, other input sources) returns the list it was given.
  • Added: set_log_enabled (turns logs on and off), update_all_gamepads_with_list (a way to feed a list without gilrs. For tests or other input sources)
  • Battery info is not in the original, so it is not ported.
  • The log printed whenever buttons and axes change is turned on with set_input_log_enabled like the original, and is off by default. set_log_enabled is the master switch for all logs including connection and disconnection.
  • GamepadKind, read_gamepad_kind: tells the kind (Xbox, PlayStation, Nintendo, other) from the pad name. get_active_gamepad_id is the pad that pressed a button or tilted an axis far at the last update.
  • vibrate(strong_magnitude, weak_magnitude, seconds): vibrates all connected pads. On desktop it vibrates with gilrs force feedback (Linux evdev, Windows XInput and Windows.Gaming.Input), and on macOS, where gilrs does not support rumble, the platform layer (platform/desktop/gamepadhaptics.rs) vibrates the controller paired with the gilrs pad using GameController and CoreHaptics. (on macOS, a duration or strength of 0 stops the previous vibration) So gilrs is created with rumble enabled. (one gilrs rumble thread runs on desktop) On the web, like the original, it applies dual-rumble to the vibrationActuator of navigator.getGamepads(). Called before the first update (tick), it creates gilrs on the spot and rumbles. (as in the original)

GamepadAnalogStickCodestruct

짝Counterpart: vanilla.js GamepadAnalogStickCode소스source

게임패드 아날로그 스틱 식별자. (W3C Standard Gamepad 매핑 규격)

  • 값은 Gamepad.axes 의 번호이고 get_axis_value 의 axis_index 로 쓴다.

Gamepad analog stick identifier. (W3C Standard Gamepad mapping spec)

  • The value is an index into Gamepad.axes and is used as axis_index of get_axis_value.
예제Example왼쪽 스틱 축 읽기Reading the left stick axes
use vanilla::{Gamepad, GamepadAnalogStickCode, GamepadManager};

let mut gamepad_manager = GamepadManager::new();
gamepad_manager.set_log_enabled(false);
let mut gamepad = Gamepad::create(0, "Test Pad");
gamepad.axes[GamepadAnalogStickCode::LEFT_X] = 0.75;
gamepad.axes[GamepadAnalogStickCode::LEFT_Y] = -1.0;
gamepad_manager.update_all_gamepads_with_list(vec![Some(gamepad)]);
assert_eq!(gamepad_manager.get_axis_value(0, GamepadAnalogStickCode::LEFT_X), 0.75);
assert_eq!(gamepad_manager.get_axis_value(0, GamepadAnalogStickCode::LEFT_Y), -1.0);
assert_eq!(gamepad_manager.get_axis_value(0, GamepadAnalogStickCode::RIGHT_X), 0.0);
정적staticpub const LEFT_X: usize = 0#0.3.2 부터since 0.3.2소스source

왼쪽 스틱 가로 축. (-1 왼쪽 ~ 1 오른쪽)

Left stick horizontal axis. (-1 left ~ 1 right)

반환Returnsusize

짝Counterpart: vanilla.js GamepadAnalogStickCode.LEFT_X

정적staticpub const LEFT_Y: usize = 1#0.3.2 부터since 0.3.2소스source

왼쪽 스틱 세로 축. (-1 위 ~ 1 아래)

Left stick vertical axis. (-1 up ~ 1 down)

반환Returnsusize

짝Counterpart: vanilla.js GamepadAnalogStickCode.LEFT_Y

정적staticpub const RIGHT_X: usize = 2#0.3.2 부터since 0.3.2소스source

오른쪽 스틱 가로 축. (-1 왼쪽 ~ 1 오른쪽)

Right stick horizontal axis. (-1 left ~ 1 right)

반환Returnsusize

짝Counterpart: vanilla.js GamepadAnalogStickCode.RIGHT_X

정적staticpub const RIGHT_Y: usize = 3#0.3.2 부터since 0.3.2소스source

오른쪽 스틱 세로 축. (-1 위 ~ 1 아래)

Right stick vertical axis. (-1 up ~ 1 down)

반환Returnsusize

짝Counterpart: vanilla.js GamepadAnalogStickCode.RIGHT_Y

GamepadTriggerCodestruct

짝Counterpart: vanilla.js GamepadTriggerCode소스source

게임패드 트리거 식별자. (W3C Standard Gamepad 매핑 규격)

  • 값은 버튼 번호다. (GamepadButtonCode::L2, R2 와 같다) 아날로그 값은 get_button_value 로 읽는다.

Gamepad trigger identifier. (W3C Standard Gamepad mapping spec)

  • The value is a button index. (same as GamepadButtonCode::L2, R2) The analog value is read with get_button_value.
예제Example오른쪽 트리거를 반쯤 당긴 값 읽기Reading the right trigger pulled halfway
use vanilla::{Gamepad, GamepadButton, GamepadButtonCode, GamepadManager, GamepadTriggerCode};

let mut gamepad_manager = GamepadManager::new();
gamepad_manager.set_log_enabled(false);
let mut gamepad = Gamepad::create(0, "Test Pad");
gamepad.buttons[GamepadTriggerCode::R2] = GamepadButton { pressed: true, value: 0.5 };
gamepad_manager.update_all_gamepads_with_list(vec![Some(gamepad)]);
assert!(gamepad_manager.is_button_pressed(0, GamepadTriggerCode::R2));
assert_eq!(gamepad_manager.get_button_value(0, GamepadTriggerCode::R2), 0.5);
assert_eq!(GamepadTriggerCode::L2, GamepadButtonCode::L2);
정적staticpub const L2: usize = 6#0.3.2 부터since 0.3.2소스source

왼쪽 트리거. (버튼 6번, 값 0 ~ 1)

Left trigger. (button 6, value 0 ~ 1)

반환Returnsusize

짝Counterpart: vanilla.js GamepadTriggerCode.L2

정적staticpub const R2: usize = 7#0.3.2 부터since 0.3.2소스source

오른쪽 트리거. (버튼 7번, 값 0 ~ 1)

Right trigger. (button 7, value 0 ~ 1)

반환Returnsusize

짝Counterpart: vanilla.js GamepadTriggerCode.R2

GamepadButtonCodestruct

짝Counterpart: vanilla.js GamepadButtonCode소스source

게임패드 버튼 식별자. (W3C Standard Gamepad 매핑 규격)

  • 값은 Gamepad.buttons 의 번호이고 is_button_pressed 들의 button_index 로 쓴다. 앞면 버튼은 자리로 정한다. (아래 0, 오른쪽 1, 왼쪽 2, 위 3)

Gamepad button identifier. (W3C Standard Gamepad mapping spec)

  • The value is an index into Gamepad.buttons and is used as button_index of the is_button_pressed functions. Face buttons are defined by position. (bottom 0, right 1, left 2, top 3)
예제Example두 번 갱신하며 방금 눌림과 눌린 채 가르기Updating twice to tell just pressed from held
use vanilla::{Gamepad, GamepadButton, GamepadButtonCode, GamepadManager};

let mut gamepad_manager = GamepadManager::new();
gamepad_manager.set_log_enabled(false);
let mut gamepad = Gamepad::create(0, "Test Pad");
gamepad.buttons[GamepadButtonCode::A_CROSS] = GamepadButton { pressed: true, value: 1.0 };
gamepad_manager.update_all_gamepads_with_list(vec![Some(gamepad.clone())]);
assert!(gamepad_manager.is_button_just_pressed(0, GamepadButtonCode::A_CROSS));
gamepad_manager.update_all_gamepads_with_list(vec![Some(gamepad)]);
assert!(gamepad_manager.is_button_pressed(0, GamepadButtonCode::A_CROSS));
assert!(!gamepad_manager.is_button_just_pressed(0, GamepadButtonCode::A_CROSS));
assert!(!gamepad_manager.is_button_pressed(0, GamepadButtonCode::B_CIRCLE));
정적staticpub const A_CROSS: usize = 0#0.3.2 부터since 0.3.2소스source

앞면 버튼.

Face buttons.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.A_CROSS

정적staticpub const B_CIRCLE: usize = 1#0.3.2 부터since 0.3.2소스source

앞면 오른쪽 버튼. (엑스박스 B, 플레이스테이션 동그라미)

Right face button. (Xbox B, PlayStation circle)

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.B_CIRCLE

정적staticpub const X_SQUARE: usize = 2#0.3.2 부터since 0.3.2소스source

앞면 왼쪽 버튼. (엑스박스 X, 플레이스테이션 네모)

Left face button. (Xbox X, PlayStation square)

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.X_SQUARE

정적staticpub const Y_TRIANGLE: usize = 3#0.3.2 부터since 0.3.2소스source

앞면 위쪽 버튼. (엑스박스 Y, 플레이스테이션 세모)

Top face button. (Xbox Y, PlayStation triangle)

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.Y_TRIANGLE

정적staticpub const L1: usize = 4#0.3.2 부터since 0.3.2소스source

범퍼.

Bumpers.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.L1

정적staticpub const R1: usize = 5#0.3.2 부터since 0.3.2소스source

오른쪽 범퍼.

Right bumper.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.R1

정적staticpub const L2: usize = 6#0.3.2 부터since 0.3.2소스source

트리거. (버튼으로도 인식됨)

Triggers. (also recognized as buttons)

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.L2

정적staticpub const R2: usize = 7#0.3.2 부터since 0.3.2소스source

오른쪽 트리거. (값 0 ~ 1)

Right trigger. (value 0 ~ 1)

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.R2

정적staticpub const SHARE_VIEW: usize = 8#0.3.2 부터since 0.3.2소스source

시스템.

System.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.SHARE_VIEW

정적staticpub const OPTIONS_MENU: usize = 9#0.3.2 부터since 0.3.2소스source

오른쪽 시스템 버튼. (엑스박스 메뉴, 플레이스테이션 옵션)

Right system button. (Xbox Menu, PlayStation Options)

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.OPTIONS_MENU

정적staticpub const L3: usize = 10#0.3.2 부터since 0.3.2소스source

스틱 누름.

Stick press.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.L3

정적staticpub const R3: usize = 11#0.3.2 부터since 0.3.2소스source

오른쪽 스틱 누름.

Right stick press.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.R3

정적staticpub const DPAD_UP: usize = 12#0.3.2 부터since 0.3.2소스source

십자키.

D-pad.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.DPAD_UP

정적staticpub const DPAD_DOWN: usize = 13#0.3.2 부터since 0.3.2소스source

십자키 아래.

D-pad down.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.DPAD_DOWN

정적staticpub const DPAD_LEFT: usize = 14#0.3.2 부터since 0.3.2소스source

십자키 왼쪽.

D-pad left.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.DPAD_LEFT

정적staticpub const DPAD_RIGHT: usize = 15#0.3.2 부터since 0.3.2소스source

십자키 오른쪽.

D-pad right.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.DPAD_RIGHT

정적staticpub const HOME_PS: usize = 16#0.3.2 부터since 0.3.2소스source

가운데.

Center.

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.HOME_PS

정적staticpub const TOUCHPAD: usize = 17#0.3.2 부터since 0.3.2소스source

플레이스테이션 터치패드 누름. (표준 17개 뒤의 버튼, 듀얼쇼크4와 듀얼센스만)

PlayStation touchpad press. (a button after the 17 standard ones, DualShock 4 and DualSense only)

반환Returnsusize

짝Counterpart: vanilla.js GamepadButtonCode.TOUCHPAD

GamepadInputCallbacktype

소스source

입력 콜백. (gamepad_index, input_type, input_index, value)

Input callback. (gamepad_index, input_type, input_index, value)

pub type GamepadInputCallback = Box<dyn FnMut(usize, GamepadInputType, usize, f64)>

GamepadButtonstruct traits Clone, Copy, Debug, PartialEq

소스source

게임패드 버튼 하나. (W3C GamepadButton)

One gamepad button. (W3C GamepadButton)

예제Example패드 사본의 버튼 바꾸기Changing a button of a pad copy
use vanilla::{Gamepad, GamepadButton, GamepadButtonCode};

let mut gamepad = Gamepad::create(0, "Test Pad");
assert!(!gamepad.buttons[GamepadButtonCode::L2].pressed);
gamepad.buttons[GamepadButtonCode::L2] = GamepadButton { pressed: true, value: 0.4 };
assert_eq!(gamepad.buttons[GamepadButtonCode::L2].value, 0.4);
필드fieldpub pressed: bool#0.3.2 부터since 0.3.2소스source

눌렸는지.

Whether pressed.

반환Returnsbool

필드fieldpub value: f64#0.3.2 부터since 0.3.2소스source

값. (0.0 ~ 1.0, 트리거는 아날로그)

Value. (0.0 ~ 1.0, analog for triggers)

반환Returnsf64

Gamepadstruct traits Clone, Debug, PartialEq, GamepadElementReader

소스source

게임패드 하나의 사본. (W3C Gamepad, navigator.getGamepads() 가 주는 것과 같은 꼴)

Copy of one gamepad. (W3C Gamepad, the same form navigator.getGamepads() gives)

예제Example패드를 만들어 연결된 패드 목록에서 읽기Creating a pad and reading it from the connected pad list
use vanilla::{read_gamepad_kind, Gamepad, GamepadKind, GamepadManager};

let gamepad = Gamepad::create(1, "Xbox Wireless Controller");
assert_eq!(gamepad.buttons.len(), 17);
assert_eq!(gamepad.axes.len(), 4);
assert!(gamepad.connected);
assert_eq!(read_gamepad_kind(&gamepad.id), GamepadKind::Xbox);

let mut gamepad_manager = GamepadManager::new();
gamepad_manager.set_log_enabled(false);
gamepad_manager.update_all_gamepads_with_list(vec![None, Some(gamepad)]);
let connected_gamepad = gamepad_manager.get_connected_gamepad(0);
assert_eq!(connected_gamepad.map(|gamepad| gamepad.index), Some(1));
정적staticpub fn create(index: usize, id: &str) -> Gamepad#0.3.2 부터since 0.3.2소스source

생성. (버튼 17개는 뗀 상태, 축 4개는 0)

Constructor. (17 buttons released, 4 axes at 0)

indexusize
하드웨어 식별 번호. (update_all_gamepads_with_list 에 넘기는 목록의 번호와 같게)Hardware identifier number. (same as the index in the list passed to update_all_gamepads_with_list)
id&str
장치 이름.Device name.

반환ReturnsGamepad 연결된(connected 가 true) 패드 사본.Connected (connected is true) pad copy.

필드fieldpub index: usize#0.3.2 부터since 0.3.2소스source

하드웨어 식별 번호. (is_button_pressed 들의 gamepad_index)

Hardware identifier number. (gamepad_index of the is_button_pressed functions)

반환Returnsusize

필드fieldpub id: String#0.3.2 부터since 0.3.2소스source

장치 이름.

Device name.

반환ReturnsString

필드fieldpub connected: bool#0.3.2 부터since 0.3.2소스source

연결되어 있는지.

Whether connected.

반환Returnsbool

필드fieldpub buttons: Vec<GamepadButton>#0.3.2 부터since 0.3.2소스source

버튼 목록. (GamepadButtonCode 순서)

Button list. (GamepadButtonCode order)

반환ReturnsVec<GamepadButton>

필드fieldpub axes: Vec<f64>#0.3.2 부터since 0.3.2소스source

축 목록. (GamepadAnalogStickCode 순서, -1.0 ~ 1.0)

Axis list. (GamepadAnalogStickCode order, -1.0 ~ 1.0)

반환ReturnsVec<f64>

GamepadManagerstruct traits Default

짝Counterpart: vanilla.js GamepadManager소스source

게임패드 관리자.

  • InputManager 가 하나 들고 tick 에서 폴링한다. 씬은 engine.get_input_manager().get_gamepad_manager() 로 읽는다. (패드 목록 읽기는 그 자리에서 읽어 get_gamepad_manager_mut)

Gamepad manager.

  • InputManager holds one and polls it in tick. Scenes read it with engine.get_input_manager().get_gamepad_manager(). (reading the pad list reads in place, so use get_gamepad_manager_mut)
예제Example콜백으로 버튼 변화 받기Receiving button changes through the callback
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Gamepad, GamepadButton, GamepadButtonCode, GamepadInputType, GamepadManager};

let event_list = Rc::new(RefCell::new(Vec::new()));
let callback_event_list = event_list.clone();
let mut gamepad_manager = GamepadManager::new();
gamepad_manager.set_log_enabled(false);
gamepad_manager.set_callback(Some(Box::new(move |gamepad_index, input_type, input_index, value| {
	callback_event_list.borrow_mut().push((gamepad_index, input_type, input_index, value));
})));
let mut gamepad = Gamepad::create(0, "Test Pad");
gamepad.buttons[GamepadButtonCode::A_CROSS] = GamepadButton { pressed: true, value: 1.0 };
gamepad_manager.update_all_gamepads_with_list(vec![Some(gamepad)]);
assert_eq!(gamepad_manager.get_connected_gamepad_count(), 1);
assert_eq!(event_list.borrow()[0], (0, GamepadInputType::Button, GamepadButtonCode::A_CROSS, 1.0));
예제Example씬에서 첫 패드의 단추와 스틱 읽기Reading the first pad's buttons and sticks in a scene
use vanilla::{Engine, GamepadAnalogStickCode, GamepadButtonCode};

fn read_first_gamepad(engine: &Engine) {
	let mut input_manager = engine.get_input_manager_mut();
	let mut gamepad_manager = input_manager.get_gamepad_manager_mut();
	let gamepad_index = match gamepad_manager.get_connected_gamepad(0) {
		Some(gamepad) => {
			gamepad.index
		}
		None => {
			return;
		}
	};
	if gamepad_manager.is_button_just_pressed(gamepad_index, GamepadButtonCode::A_CROSS) {
		println!("confirm");
	}
	let stick_x = gamepad_manager.get_axis_value(gamepad_index, GamepadAnalogStickCode::LEFT_X);
	println!("{}", stick_x);
}
생성자constructorpub fn new() -> GamepadManager#0.3.2 부터since 0.3.2소스source

생성.

  • 로그는 켜고 입력 로그는 끈 채 시작한다. 장치(gilrs)는 처음 부를 때 연다.

Constructor.

  • Starts with logging on and input logging off. The device (gilrs) is opened on the first call.

반환ReturnsGamepadManager 연결된 패드가 없는 관리자.Manager with no connected pads.

짝Counterpart: vanilla.js GamepadManager.constructor

메서드methodpub fn tick(&mut self, _time_delta: f64)#0.3.2 부터since 0.3.2소스source

갱신.

  • update_all_gamepads 를 부른다.

Update.

  • Calls update_all_gamepads.
_time_deltaf64
지난 프레임 뒤로 흐른 초. (쓰지 않는다)Seconds elapsed since the last frame. (unused)

짝Counterpart: vanilla.js GamepadManager.tick

메서드methodpub fn connect(&mut self, gamepad: &Gamepad)#0.3.2 부터since 0.3.2소스source

게임패드 연결.

  • 상태 칸을 그 패드의 버튼, 축 수만큼 뗀 상태와 0 으로 만든다. 로그가 켜져 있으면 연결 로그를 낸다.

Connects a gamepad.

  • Creates state slots for that pad's buttons and axes, released and 0. Prints a connection log if logging is on.
gamepad&Gamepad
붙일 패드. (같은 index 가 이미 붙어 있으면 건너뛴다)Pad to attach. (skipped if the same index is already attached)

짝Counterpart: vanilla.js GamepadManager.connect

메서드methodpub fn disconnect(&mut self, gamepad: &Gamepad)#0.3.2 부터since 0.3.2소스source

게임패드 연결 해제.

Gamepad disconnected.

gamepad&Gamepad
뗄 패드. (index 로 찾는다, 붙어 있지 않으면 건너뛴다)Pad to detach. (found by index, skipped if not attached)

짝Counterpart: vanilla.js GamepadManager.disconnect

메서드methodpub fn set_callback(&mut self, callback: Option<GamepadInputCallback>)#0.3.2 부터since 0.3.2소스source

콜백 설정. (None 이면 끈다)

Sets the callback. (off if None)

callbackOption<GamepadInputCallback>
갱신 중 입력이 바뀔 때마다 부를 함수. (gamepad_index 는 Gamepad.index, 버튼 눌림은 Button 과 1.0 / 0.0, 아날로그 값은 Value, 축은 Axis)Function called whenever input changes during an update. (gamepad_index is Gamepad.index, button presses are Button with 1.0 / 0.0, analog values are Value, axes are Axis)

짝Counterpart: vanilla.js GamepadManager.setCallback

메서드methodpub fn set_log_enabled(&mut self, is_enabled: bool)#0.3.2 부터since 0.3.2소스source

로그 켜고 끄기. (러스트 판에서 더한 것. 기본은 원본처럼 켜짐)

Turns logs on and off. (added in the Rust version. On by default like the original)

is_enabledbool
연결, 해제, 입력 로그를 모두 내려면 true.true to print all connection, disconnection and input logs.
메서드methodpub fn set_input_log_enabled(&mut self, is_enabled: bool)#0.4.0 부터since 0.4.0소스source

단추와 축이 바뀔 때마다 로그를 낼지. (기본은 끔, set_log_enabled 가 꺼져 있으면 켜도 내지 않는다)

Whether to print a log whenever buttons and axes change. (off by default, prints nothing even when on if set_log_enabled is off)

is_enabledbool
입력 로그를 내려면 true.true to print input logs.

짝Counterpart: vanilla.js GamepadManager.setInputLogEnabled

메서드methodpub fn is_input_log_enabled(&self) -> bool#0.4.0 부터since 0.4.0소스source

단추와 축이 바뀔 때마다 로그를 내는지.

Whether a log is printed whenever buttons and axes change.

반환Returnsbool 입력 로그를 켰으면 true. (set_log_enabled 는 보지 않는다)true if input logs are on. (does not look at set_log_enabled)

짝Counterpart: vanilla.js GamepadManager.isInputLogEnabled

메서드methodpub fn get_active_gamepad_id(&self) -> Option<&str>#0.4.0 부터since 0.4.0소스source

마지막 갱신에 단추를 누르거나 축을 0.5 넘게 기울인 패드의 이름. (없으면 None, 마지막으로 쓴 장치를 가릴 때)

Name of the pad that pressed a button or tilted an axis past 0.5 at the last update. (None if none, for telling the last used device)

반환ReturnsOption<&str> 그 패드의 Gamepad.id. 마지막 갱신에 새로 누른 단추나 0.5 를 새로 넘긴 축이 없으면 None. (누른 채 두면 다음 갱신에 None)Gamepad.id of that pad. None if no button was newly pressed and no axis newly crossed 0.5 at the last update. (None at the next update if held)

짝Counterpart: vanilla.js GamepadManager.getActiveGamepadId

메서드methodpub fn vibrate(&mut self, strong_magnitude: f64, weak_magnitude: f64, seconds: f64)#0.4.0 부터since 0.4.0소스source

연결된 패드를 모두 떨기. (세기는 0 ~ 1, 무거운 모터와 가벼운 모터, 초)

  • 데스크탑은 gilrs force feedback(macOS 는 GameController 와 CoreHaptics), 웹은 Gamepad.vibrationActuator 의 dual-rumble. 진동을 대지 않는 패드는 건너뛴다.

Vibrates all connected pads. (strengths 0 ~ 1, heavy motor and light motor, seconds)

  • On desktop gilrs force feedback (GameController and CoreHaptics on macOS), on the web dual-rumble of Gamepad.vibrationActuator. Pads without rumble support are skipped.
strong_magnitudef64
무거운(낮은 주파수) 모터 세기. (0 ~ 1 로 자르고, 수가 아니면 0)Heavy (low frequency) motor strength. (clamped to 0 ~ 1, 0 if not a number)
weak_magnitudef64
가벼운(높은 주파수) 모터 세기. (0 ~ 1 로 자르고, 수가 아니면 0)Light (high frequency) motor strength. (clamped to 0 ~ 1, 0 if not a number)
secondsf64
떠는 길이. (초, 음수나 수가 아니면 0, 밀리초로 반올림한다)Vibration duration. (seconds, 0 if negative or not a number, rounded to milliseconds)

짝Counterpart: vanilla.js GamepadManager.vibrate

예제Example맞았을 때 0.2 초 떨기Vibrating for 0.2 seconds when hit
use vanilla::Engine;

fn shake_on_hit(engine: &Engine) {
	let mut input_manager = engine.get_input_manager_mut();
	let mut gamepad_manager = input_manager.get_gamepad_manager_mut();
	gamepad_manager.vibrate(1.0, 0.5, 0.2);
}
메서드methodpub fn update_all_gamepads(&mut self)#0.3.2 부터since 0.3.2소스source

모든 게임패드 갱신. (gilrs 를 읽어 update_all_gamepads_with_list 로 넘긴다)

Updates all gamepads. (reads gilrs and passes the list to update_all_gamepads_with_list)

짝Counterpart: vanilla.js GamepadManager.updateAllGamepads

메서드methodpub fn update_all_gamepads_with_list(&mut self, gamepad_list: Vec<Option<Gamepad>>)#0.3.2 부터since 0.3.2소스source

주어진 목록으로 모든 게임패드 갱신. (원본 updateAllGamepads 의 본문, 목록 번호가 index)

  • gilrs 없이 상태를 넣을 때 쓴다. (시험, 다른 입력원)
  • 목록에 새로 나타난 패드는 붙이고 사라진 패드는 놓는다. 값은 소수점 둘째 자리로 반올림하고 바뀐 것만 콜백에 알린다.

Updates all gamepads from the given list. (the body of the original updateAllGamepads, the list position is the index)

  • Used to feed state without gilrs. (tests, other input sources)
  • Pads newly appearing in the list are attached and pads that disappear are released. Values are rounded to two decimal places and only changes are reported to the callback.
gamepad_listVec<Option<Gamepad>>
패드 목록. (번호가 Gamepad.index, 빈 자리는 None, navigator.getGamepads() 와 같은 꼴)Pad list. (the index is Gamepad.index, empty slots are None, the same form as navigator.getGamepads())
예제Example둘째 자리에 패드를 넣었다가 빼기Putting a pad in the second slot and taking it out
use vanilla::{Gamepad, GamepadManager};

let mut gamepad_manager = GamepadManager::new();
gamepad_manager.set_log_enabled(false);
let gamepad = Gamepad::create(1, "Second Pad");
gamepad_manager.update_all_gamepads_with_list(vec![None, Some(gamepad)]);
assert_eq!(gamepad_manager.get_connected_gamepad_count(), 1);
assert_eq!(gamepad_manager.get_all_connected_gamepads()[0].id, "Second Pad");
gamepad_manager.update_all_gamepads_with_list(Vec::new());
assert_eq!(gamepad_manager.get_connected_gamepad_count(), 0);
메서드methodpub fn is_button_pressed(&self, gamepad_index: usize, button_index: usize) -> bool#0.3.2 부터since 0.3.2소스source

버튼 눌림 상태 반환.

Returns the button pressed state.

gamepad_indexusize
패드의 하드웨어 식별 번호. (Gamepad.index, 연결 목록의 순번이 아니다)Hardware identifier number of the pad. (Gamepad.index, not the position in the connected list)
button_indexusize
버튼 번호. (GamepadButtonCode)Button index. (GamepadButtonCode)

반환Returnsbool 눌린 채면 true. 패드가 붙어 있지 않거나 버튼 번호가 없으면 false.true if held. false if the pad is not attached or the button index does not exist.

짝Counterpart: vanilla.js GamepadManager.isButtonPressed

메서드methodpub fn is_button_just_pressed(&self, gamepad_index: usize, button_index: usize) -> bool#0.3.2 부터since 0.3.2소스source

이번 갱신에 방금 눌린 버튼인지. (원본 isButtonJustPressed, 키보드 is_key_just_pressed 와 같은 쓰임)

Whether the button was just pressed this update. (the original isButtonJustPressed, used like keyboard is_key_just_pressed)

gamepad_indexusize
패드의 하드웨어 식별 번호. (Gamepad.index, 연결 목록의 순번이 아니다)Hardware identifier number of the pad. (Gamepad.index, not the position in the connected list)
button_indexusize
버튼 번호. (GamepadButtonCode)Button index. (GamepadButtonCode)

반환Returnsbool 지난 갱신에 떼어 있다가 이번 갱신에 눌렸으면 true. 패드나 버튼이 없으면 false.true if released at the last update and pressed this update. false if the pad or button does not exist.

짝Counterpart: vanilla.js GamepadManager.isButtonJustPressed

메서드methodpub fn is_button_just_released(&self, gamepad_index: usize, button_index: usize) -> bool#0.3.2 부터since 0.3.2소스source

이번 갱신에 방금 떼어진 버튼인지. (원본 isButtonJustReleased)

Whether the button was just released this update. (the original isButtonJustReleased)

gamepad_indexusize
패드의 하드웨어 식별 번호. (Gamepad.index, 연결 목록의 순번이 아니다)Hardware identifier number of the pad. (Gamepad.index, not the position in the connected list)
button_indexusize
버튼 번호. (GamepadButtonCode)Button index. (GamepadButtonCode)

반환Returnsbool 지난 갱신에 눌려 있다가 이번 갱신에 떼어졌으면 true. 패드나 버튼이 없으면 false.true if pressed at the last update and released this update. false if the pad or button does not exist.

짝Counterpart: vanilla.js GamepadManager.isButtonJustReleased

메서드methodpub fn get_button_value(&self, gamepad_index: usize, button_index: usize) -> f64#0.3.2 부터since 0.3.2소스source

버튼/트리거 아날로그 값 반환. (0.0 ~ 1.0)

Returns the button/trigger analog value. (0.0 ~ 1.0)

gamepad_indexusize
패드의 하드웨어 식별 번호. (Gamepad.index, 연결 목록의 순번이 아니다)Hardware identifier number of the pad. (Gamepad.index, not the position in the connected list)
button_indexusize
버튼 번호. (GamepadButtonCode)Button index. (GamepadButtonCode)

반환Returnsf64 소수점 둘째 자리로 반올림한 값. 패드나 버튼이 없으면 0.0.Value rounded to two decimal places. 0.0 if the pad or button does not exist.

짝Counterpart: vanilla.js GamepadManager.getButtonValue

메서드methodpub fn get_axis_value(&self, gamepad_index: usize, axis_index: usize) -> f64#0.3.2 부터since 0.3.2소스source

아날로그 스틱 축 값 반환. (-1.0 ~ 1.0)

  • 0.01 넘게 바뀐 때만 새 값을 받는다. 죽은 구역은 빼지 않는다. (InputActions 가 뺀다)

Returns the analog stick axis value. (-1.0 ~ 1.0)

  • Takes a new value only when it changes by more than 0.01. The dead zone is not removed. (InputActions removes it)
gamepad_indexusize
패드의 하드웨어 식별 번호. (Gamepad.index)Hardware identifier number of the pad. (Gamepad.index)
axis_indexusize
축 번호. (GamepadAnalogStickCode, 세로 축은 아래가 양수)Axis index. (GamepadAnalogStickCode, vertical axes are positive downward)

반환Returnsf64 소수점 둘째 자리로 반올림한 값. 패드나 축이 없거나 NaN 이면 0.0.Value rounded to two decimal places. 0.0 if the pad or axis does not exist or it is NaN.

짝Counterpart: vanilla.js GamepadManager.getAxisValue

메서드methodpub fn get_all_connected_gamepads(&self) -> Vec<Gamepad>#0.3.2 부터since 0.3.2소스source

연결된 모든 게임패드 반환. (원본 navigator.getGamepads() 처럼 그 자리에서 읽은 지금 상태의 사본)

Returns all connected gamepads. (a copy of the current state read in place, like the original navigator.getGamepads())

반환ReturnsVec<Gamepad> 붙은 차례의 패드 사본 목록. 없으면 빈 목록.List of pad copies in connection order. An empty list if there are none.

짝Counterpart: vanilla.js GamepadManager.getAllConnectedGamepads

메서드methodpub fn get_connected_gamepad_count(&self) -> usize#0.3.2 부터since 0.3.2소스source

연결된 게임패드 수 반환.

Returns the number of connected gamepads.

반환Returnsusize 붙어 있는 패드 수.Number of attached pads.

짝Counterpart: vanilla.js GamepadManager.getConnectedGamepadCount

메서드methodpub fn get_connected_gamepad(&self, gamepad_index: usize) -> Option<Gamepad>#0.3.2 부터since 0.3.2소스source

연결된 게임패드 반환. (gamepad_index 는 연결 목록의 순번, 0 ~ get_connected_gamepad_count() - 1)

Returns a connected gamepad. (gamepad_index is the position in the connected list, 0 ~ get_connected_gamepad_count() - 1)

gamepad_indexusize
연결 목록의 순번. (붙은 차례, Gamepad.index 가 아니다)Position in the connected list. (attach order, not Gamepad.index)

반환ReturnsOption<Gamepad> 그 자리에서 읽은 패드의 사본. 순번이 범위를 넘거나 그 패드가 지금 목록에 없으면 None.A copy of the pad read in place. None if the number is out of range or that pad is not in the current list.

짝Counterpart: vanilla.js GamepadManager.getConnectedGamepad

함수Functions

함수functionpub fn read_gamepad_kind(gamepad_id: &str) -> GamepadKind#0.4.0 부터since 0.4.0소스source

패드 이름으로 종류 가르기. (플레이스테이션 054c, 닌텐도 057e, 엑스박스 045e 와 이름, 모르면 Other)

  • 대소문자를 가리지 않고 플레이스테이션, 닌텐도, 엑스박스 차례로 본다.

Tells the kind from the pad name. (PlayStation 054c, Nintendo 057e, Xbox 045e and names, Other if unknown)

  • Checks PlayStation, Nintendo, Xbox in that order, case-insensitively.
gamepad_id&str
패드 이름. (Gamepad.id)Pad name. (Gamepad.id)

반환ReturnsGamepadKind 이름에 든 제조사 번호나 흔한 이름으로 가른 종류. 맞는 것이 없으면 Other.Kind told from a vendor number or common name in the name. Other if nothing matches.

짝Counterpart: vanilla.js readGamepadKind

예제Example브라우저와 데스크탑 꼴 이름 가르기Telling browser and desktop style names apart
use vanilla::{read_gamepad_kind, GamepadKind};

let dual_sense_id = "DualSense Wireless Controller (STANDARD GAMEPAD Vendor: 054c Product: 0ce6)";
assert_eq!(read_gamepad_kind(dual_sense_id), GamepadKind::PlayStation);
assert_eq!(read_gamepad_kind("Xbox 360 Controller (XInput STANDARD GAMEPAD)"), GamepadKind::Xbox);
assert_eq!(read_gamepad_kind("Steam Virtual Gamepad"), GamepadKind::Other);

GamepadKindenum traits Clone, Copy, Debug, PartialEq, Eq, Hash

짝Counterpart: vanilla.js GamepadKind소스source

게임패드 종류. (단추 안내를 그 패드의 표기로 보일 때 쓴다)

Gamepad type. (used to show button hints in that pad's notation)

이름Name설명Description
Xbox엑스박스 패드. (이름에 045e, xbox, xinput, microsoft)Xbox pad. (045e, xbox, xinput, microsoft in the name)
PlayStation플레이스테이션 패드. (이름에 054c, playstation, dualshock, dualsense, sony)PlayStation pad. (054c, playstation, dualshock, dualsense, sony in the name)
Nintendo닌텐도 패드. (이름에 057e, nintendo, joy-con, pro controller)Nintendo pad. (057e, nintendo, joy-con, pro controller in the name)
Other그 밖. (이름으로 가르지 못한 패드)Other. (a pad that could not be told by name)

GamepadInputTypeenum traits Clone, Copy, Debug, PartialEq, Eq

소스source

입력 종류. (원본 콜백의 input_type 문자열 "button" / "value" / "axis")

Input kind. (input_type string "button" / "value" / "axis" of the original callback)

이름Name설명Description
Button눌림 변화. (값은 1.0 눌림, 0.0 뗌)Press change. (value is 1.0 pressed, 0.0 released)
Value버튼 아날로그 값 변화. (0 보다 클 때만 온다)Button analog value change. (comes only when greater than 0)
Axis스틱 축 값 변화.Stick axis value change.