1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
//use winit::platform::android::activity::input::{InputEvent, Source};
use winit::event::{Event, WindowEvent};
use winit::keyboard::{Key, NativeKey};
impl crate::Gamepads {
pub fn on_event<T>(&mut self, event: &Event<T>) {
if self.just_polled {
self.just_polled = false;
for gamepad in self.gamepads.iter_mut() {
gamepad.just_pressed_bits = 0;
}
}
if let Event::WindowEvent {
event: ref window_event,
..
} = event
{
match window_event {
WindowEvent::KeyboardInput {
event: key_event,
device_id,
..
} => {
log::info!("Gamepad keyboard event {key_event:?} from device {device_id:?}");
if let Key::Unidentified(NativeKey::Android(scancode)) = key_event.logical_key {
if let Some(gamepad_idx) = self.find_or_insert(*device_id) {
let gamepad_button = match scancode {
// See https://developer.android.com/develop/ui/views/touch-and-input/game-controllers/controller-input#dpad
// Most controllers report hat axis events instead of D-pad presses, but some might:
// "Some controllers instead report D-pad presses with a key code. If your game cares about D-pad
// presses, you should treat the hat axis events and the D-pad key codes as the same input events"
19 /* AKEYCODE_DPAD_UP */ => crate::Button::DPadUp,
20 /* AKEYCODE_DPAD_DOWN */ => crate::Button::DPadDown,
21 /* AKEYCODE_DPAD_LEFT */ => crate::Button::DPadLeft,
22 /* AKEYCODE_DPAD_RIGHT */ => crate::Button::DPadRight,
96 /* AKEYCODE_BUTTON_A */ => crate::Button::ActionDown,
97 /* AKEYCODE_BUTTON_B */ => crate::Button::ActionRight,
99 /* AKEYCODE_BUTTON_X */ => crate::Button::ActionLeft,
100 /* AKEYCODE_BUTTON_Y */ => crate::Button::ActionUp,
102 /* AKEYCODE_BUTTON_L1 */ => crate::Button::FrontLeftUpper,
103 /* AKEYCODE_BUTTON_R1 */ => crate::Button::FrontRightUpper,
104 /* AKEYCODE_BUTTON_L2 */ => crate::Button::FrontLeftLower,
105 /* AKEYCODE_BUTTON_R2 */ => crate::Button::FrontRightLower,
106 /* AKEYCODE_BUTTON_THUMBL */ => crate::Button::LeftStick,
107 /* AKEYCODE_BUTTON_THUMBR */ => crate::Button::RightStick,
108 /* AKEYCODE_BUTTON_START */ => crate::Button::RightCenterCluster,
109 /* AKEYCODE_BUTTON_SELECT */ => crate::Button::LeftCenterCluster,
_ => {
return;
}
};
let bit = 1 << (gamepad_button as u32);
if key_event.state.is_pressed() {
self.gamepads[gamepad_idx].pressed_bits |= bit;
self.gamepads[gamepad_idx].just_pressed_bits |= bit;
} else {
self.gamepads[gamepad_idx].pressed_bits &= !bit;
}
log::error!(
"Gamepad button {:?}, device id = {:?}",
gamepad_button,
device_id,
);
}
}
}
/*
WindowEvent::AxisUpdate { device_id, values } => {
log::error!("Axis update: {:?}, {:?}", device_id, values);
if let Some(gamepad_idx) = self.find_or_insert(*device_id) {
for (val, negative_button, positive_button) in [
(values[0], crate::Button::DPadLeft, crate::Button::DPadRight),
(values[0], crate::Button::DPadUp, crate::Button::DPadDown),
] {
let negative_bit = 1 << (negative_button as u32);
let posive_bit = 1 << (positive_button as u32);
if val < 0. {
self.gamepads[gamepad_idx].pressed_bits |= negative_bit;
self.gamepads[gamepad_idx].just_pressed_bits |= negative_bit;
self.gamepads[gamepad_idx].pressed_bits &= !posive_bit;
} else if val > 0. {
self.gamepads[gamepad_idx].pressed_bits |= posive_bit;
self.gamepads[gamepad_idx].just_pressed_bits |= posive_bit;
self.gamepads[gamepad_idx].pressed_bits &= !negative_bit;
} else {
self.gamepads[gamepad_idx].pressed_bits &=
!(negative_bit | posive_bit);
}
}
self.gamepads[gamepad_idx].axes =
[values[2], values[3], values[4], values[5]];
}
}
*/
WindowEvent::Touch(touch) => {
// https://docs.rs/winit/latest/winit/event/struct.Touch.html
// Note device_id being present.
log::error!("Touch event: {:?}", touch);
}
_ => {}
};
}
}
fn find_or_insert(&mut self, winit_device_id: winit::event::DeviceId) -> Option<usize> {
for i in 0..crate::MAX_GAMEPADS {
if self.android_winit_gamepad_ids[i] == winit_device_id {
return Some(i);
}
}
if self.num_connected_pads == crate::MAX_GAMEPADS as u8 {
None
} else {
let index = self.num_connected_pads;
self.num_connected_pads += 1;
self.android_winit_gamepad_ids[index as usize] = winit_device_id;
Some(index as usize)
}
}
pub(crate) fn poll_android_winit(&mut self) {
self.just_polled = true;
}
#[allow(clippy::expect_used)]
pub(crate) fn rumble_android(
&self,
_gamepad_id: crate::GamepadId,
duration_ms: u32,
_start_delay_ms: u32,
strong_magnitude: f32,
weak_magnitude: f32,
) {
// See https://android.googlesource.com/platform/frameworks/opt/gamesdk/+/refs/heads/main/games-controller/src/main/java/com/google/android/games/paddleboat/GameControllerManager.java
//
// See also implementation in chromium:
// https://chromium-review.googlesource.com/c/chromium/src/+/3721715/12/device/gamepad/android/java/src/org/chromium/device/gamepad/GamepadDevice.java#73
fn scale_magnitude(magnitude: f32) -> i32 {
// Vibration magnitudes on android are between 1 and 255
const VIBRATION_MAX_AMPLITUDE: f32 = 255.;
(magnitude.clamp(0., 1.) * VIBRATION_MAX_AMPLITUDE).round() as i32
}
const STRONG_MAGNITUDE_IDX: i32 = 0;
const WEAK_MAGNITUDE_IDX: i32 = 1;
let ctx = ndk_context::android_context();
let vm = unsafe { jni::JavaVM::from_raw(ctx.vm().cast()) }.unwrap();
let mut env = vm.attach_current_thread().unwrap();
let class = env
.find_class("android/view/InputDevice")
.expect("Failed to load the target class");
// let device_id = self.android_winit_gamepad_ids[gamepad_id.value() as usize];
let device_id_i32 = 0; /* TODO: expose API in winit, or for now: unsafe { std::mem::transmute(device_id) }; */
let java_input_device = if let jni::objects::JValueGen::Object(java_input_device) = env
.call_static_method(
class,
"getDevice",
"(I)Landroid/view/InputDevice",
&[jni::objects::JValue::Int(device_id_i32)],
)
.expect("getDevice failed")
{
java_input_device
} else {
log::error!("getDevice did not return an object");
return;
};
let vibration_manager = if let jni::objects::JValueGen::Object(vibration_manager) = env
.call_method(
java_input_device,
"getVibratorManager",
"()Landroid/os/VibratorManager;",
&[],
)
.expect("getVibratorManager failed")
{
vibration_manager
} else {
log::error!("getVibratorManager did not return an object");
return;
};
let java_vibrator_ids_object =
if let jni::objects::JValueGen::Object(java_vibrator_ids_object) = env
.call_method(&vibration_manager, "getVibratorIds", "()[I", &[])
.expect("getVibratorIds failed")
{
java_vibrator_ids_object
} else {
log::error!("getVibratorIds did not return an object");
return;
};
let java_vibrator_ids_array = jni::objects::JIntArray::from(java_vibrator_ids_object);
let num_vibrators = env.get_array_length(&java_vibrator_ids_array).unwrap();
if num_vibrators < 2 {
log::warn!("Too few vibrators {num_vibrators}");
return;
}
// https://chromium-review.googlesource.com/c/chromium/src/+/3721715/12/device/gamepad/android/java/src/org/chromium/device/gamepad/GamepadDevice.java#275
// TODO: Check for hasAmplitudeControl() on both vibrators?
let vibration_effect_class = env
.find_class("android/os/VibrationEffect")
.expect("Failed to load the android/os/VibrationEffect class");
let combined_vibration_class = env
.find_class("android/os/CombinedVibration")
.expect("Failed to load the android/os/CombinedVibration class");
let parallel_combination = if let jni::objects::JValueGen::Object(parallel_combination) =
env.call_static_method(
combined_vibration_class,
"startParallel",
"()Landroid/os/CombinedVibration#ParallelCombination",
&[],
)
.expect("startParallel failed")
{
parallel_combination
} else {
log::error!("startParallel did not return an object");
return;
};
let mut add_vibrator = |vibrator_idx, magnitude| {
// public static VibrationEffect createOneShot (long milliseconds, int amplitude)
// https://developer.android.com/reference/android/os/VibrationEffect#createOneShot(long,%20int)
let vibration_effect = if let jni::objects::JValueGen::Object(vibration_effect) = env
.call_static_method(
&vibration_effect_class,
"createOneShot",
"(JI)Landroid/os/VibrationEffect",
&[
jni::objects::JValue::Long(i64::from(duration_ms)),
jni::objects::JValue::Int(magnitude),
],
)
.expect("createOneShot failed")
{
vibration_effect
} else {
log::error!("createOneShot did not return an object");
return;
};
// public CombinedVibration.ParallelCombination addVibrator (int vibratorId, VibrationEffect effect)
// https://developer.android.com/reference/android/os/CombinedVibration.ParallelCombination#addVibrator(int,%20android.os.VibrationEffect)
env.call_method(
¶llel_combination,
"addVibrator",
"(ILandroid/os/VibrationEffect;)V",
&[
jni::objects::JValue::Int(vibrator_idx),
jni::objects::JValue::Object(&vibration_effect),
],
)
.expect("addVibrator failed");
};
let strong = scale_magnitude(strong_magnitude);
if strong > 0 {
// effect.addVibrator(0, VibrationEffect.createOneShot(durationMillis, strongMagnitude));
add_vibrator(WEAK_MAGNITUDE_IDX, strong);
}
let weak = scale_magnitude(weak_magnitude);
if weak > 0 {
// effect.addVibrator(1, VibrationEffect.createOneShot(durationMillis, strongMagnitude));
add_vibrator(STRONG_MAGNITUDE_IDX, weak);
}
// TODO: Verify early that one of strong > 0, weak > 0 is true.
// var combined = effect.combine();
let combined_vibration = if let jni::objects::JValueGen::Object(object) = env
.call_method(¶llel_combination, "combine", "()V", &[])
.expect("effect.combine() failed")
{
object
} else {
log::error!("combine() did not return an object");
return;
};
// vibratorManager.vibrate(combined);
env.call_method(
vibration_manager,
"vibrate",
"(L/android/os/CombinedVibration)V",
&[jni::objects::JValue::Object(&combined_vibration)],
)
.expect("vibrate failed");
}
}