From 64d72913faa40872b86d2bff916792fbed33648e Mon Sep 17 00:00:00 2001 From: maxjivi05 Date: Thu, 8 Oct 2026 16:25:54 -0400 Subject: [PATCH] Give each physical controller its own player slot Every controller fed the one exported pad, so two pads played as one. The first controller keeps slot 0 (the Deck in a Steam session); further ones get slots 1-3 as separate Xbox 360 pads, created on first input and removed on disconnect. In Deck mode only the Steam client sees those pads and hands them to games through Steam Input. Rumble follows the slot it names. --- app/src/main/cpp/fakeinput_steam.cpp | 6 +- .../com/droiddeck/launcher/SessionActivity.kt | 1 + .../droiddeck/launcher/input/PadBridge.java | 208 ++++++++++++++---- .../launcher/session/RumbleComponent.kt | 60 ++--- .../launcher/session/RumbleComponentTest.kt | 44 +++- 5 files changed, 236 insertions(+), 83 deletions(-) diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp index cb203d5f5..8e238babc 100644 --- a/app/src/main/cpp/fakeinput_steam.cpp +++ b/app/src/main/cpp/fakeinput_steam.cpp @@ -1317,13 +1317,15 @@ __attribute__((visibility("hidden"))) static bool is_deck_hidraw_path(const char return pathname && fake_deck_enabled() && !strcmp(pathname, DECK_HIDRAW_PATH); } -// The app's own pads are the Deck now; their evdev nodes are withdrawn from everyone. +// The app's first pad is the Deck now: its evdev node is withdrawn from everyone. Further players' +// pads are left to the client alone, which hands them to games through Steam Input. __attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const char *pathname) { if (!fake_deck_enabled() || !pathname || strncmp(pathname, "/dev/input/", 11)) return false; const char *event = strrchr(pathname, '/') + 1; if (strncmp(event, "event", 5) && strncmp(event, "js", 2)) return false; int number = get_event_number(event); - return number >= 0 && number < UINPUT_EVENT_BASE; + if (number < 0 || number >= UINPUT_EVENT_BASE) return false; + return number == 0 || !process_is_steam_client(); } static inline void put16(uint8_t *at, int value) { diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index cc79cbe15..be0757e3a 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -300,6 +300,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onInputDeviceRemoved(deviceId: Int) { Log.i(TAG, "input device $deviceId disconnected") + padBridge?.onDeviceRemoved(deviceId) updateOnScreenControls() updatePointerCapture() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index 08328b5d3..f3bb7b9c5 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -10,6 +10,8 @@ import android.view.MotionEvent; import com.droiddeck.launcher.session.SessionState; import java.io.File; +import java.util.Arrays; +import java.util.concurrent.atomic.AtomicIntegerArray; /** * A physical controller, republished as a synthetic evdev device the Steam client can see. @@ -25,11 +27,14 @@ import java.io.File; * to the client instead ({@link com.droiddeck.launcher.session.SteamDeckPad}), which has a Quick * Access button of its own; an Xbox pad has none, so there the client's menu is reached with the * Guide-then-A chord the client itself answers. + * + *

Each further controller is another player: slots 1 to 3, an Xbox 360 pad each, which in a + * Steam session only the client reads (libfakeinput) and hands games through Steam Input. */ public final class PadBridge { private static final String TAG = "PadBridge"; - /** Slot 0 is the one the session exports; extra slots would each show as another pad. */ - private static final int SLOT = 0; + /** Player slots: the session prepares a ring for each (SessionService). */ + public static final int SLOTS = 4; private static final float DEAD_ZONE = 0.12f; // The client takes A as part of the chord only once it has had Guide held for a while, and a // client starved of CPU needs longer. Too short, and it acts on A as well, selecting whatever it @@ -50,8 +55,13 @@ public final class PadBridge { chordHandler = new Handler(thread.getLooper()); } + private final File fakeInputDir; private final FakeInputWriter writer; private final PadState state = new PadState(); + /** The input device id holding each slot, or {@link #NO_CONTROLLER}. */ + private final int[] owners = new int[SLOTS]; + private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS]; + private final PadState[] playerStates = new PadState[SLOTS]; private final PadState effectiveState = new PadState(); private final Handler mainHandler = new Handler(Looper.getMainLooper()); private boolean open; @@ -79,29 +89,50 @@ public final class PadBridge { /** No physical controller is driving the pad: nothing yet, or the on-screen controls were last. */ public static final int NO_CONTROLLER = -1; /** - * The Android input device id of the physical controller that last drove the pad, or - * {@link #NO_CONTROLLER}. Every pad feeds the one exported slot, so this is how a game's rumble - * on that slot finds the motors in the player's hands (RumbleComponent). + * The Android input device id of the physical controller that last drove any slot, or + * {@link #NO_CONTROLLER}: where rumble goes when it names no slot of ours (RumbleComponent). */ private static volatile int activeControllerId = NO_CONTROLLER; + /** Per slot, the controller its rumble belongs to; slot 0's is none while the on-screen controls lead. */ + private static final AtomicIntegerArray slotControllers = new AtomicIntegerArray(SLOTS); + static { + for (int slot = 0; slot < SLOTS; slot++) slotControllers.set(slot, NO_CONTROLLER); + } public static int activeControllerId() { return activeControllerId; } + /** The controller playing in this ring slot, or the last one used for any other slot. */ + public static int controllerForSlot(int slot) { + return slot >= 0 && slot < SLOTS ? slotControllers.get(slot) : activeControllerId; + } + public PadBridge(File fakeInputDir) { - writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT); + this.fakeInputDir = fakeInputDir; + writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), 0); + Arrays.fill(owners, NO_CONTROLLER); + for (int slot = 1; slot < SLOTS; slot++) playerStates[slot] = new PadState(); } /** Opens the ring; safe to call more than once. */ public synchronized boolean start() { if (!open) { open = writer.open(); - Log.i(TAG, "ring slot " + SLOT + (open ? " open" : " NOT open")); + Log.i(TAG, "ring slot 0" + (open ? " open" : " NOT open")); } return open; } public synchronized void stop() { activeControllerId = NO_CONTROLLER; + for (int slot = 0; slot < SLOTS; slot++) { + owners[slot] = NO_CONTROLLER; + slotControllers.set(slot, NO_CONTROLLER); + if (playerWriters[slot] != null) { + playerWriters[slot].destroy(); + playerWriters[slot] = null; + } + if (playerStates[slot] != null) playerStates[slot].clear(); + } systemGuidePressed = false; systemQamPressed = false; qamChordActive = false; @@ -155,38 +186,40 @@ public final class PadBridge { /** @return true when the event was a pad button and has been consumed. */ public synchronized boolean onKeyEvent(KeyEvent event) { - if (!isFromController(event.getDevice())) return false; - noteDevice(event.getDevice()); + if (!isFromController(event.getDevice()) || !isPadKey(event.getKeyCode())) return false; + int slot = slotFor(event.getDevice()); + PadState pad = stateFor(slot); + noteDevice(event.getDevice(), slot); boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN; switch (event.getKeyCode()) { - case KeyEvent.KEYCODE_BUTTON_A: state.press(0, pressed); break; - case KeyEvent.KEYCODE_BUTTON_B: state.press(1, pressed); break; - case KeyEvent.KEYCODE_BUTTON_X: state.press(2, pressed); break; - case KeyEvent.KEYCODE_BUTTON_Y: state.press(3, pressed); break; - case KeyEvent.KEYCODE_BUTTON_L1: state.press(4, pressed); break; - case KeyEvent.KEYCODE_BUTTON_R1: state.press(5, pressed); break; + case KeyEvent.KEYCODE_BUTTON_A: pad.press(0, pressed); break; + case KeyEvent.KEYCODE_BUTTON_B: pad.press(1, pressed); break; + case KeyEvent.KEYCODE_BUTTON_X: pad.press(2, pressed); break; + case KeyEvent.KEYCODE_BUTTON_Y: pad.press(3, pressed); break; + case KeyEvent.KEYCODE_BUTTON_L1: pad.press(4, pressed); break; + case KeyEvent.KEYCODE_BUTTON_R1: pad.press(5, pressed); break; case KeyEvent.KEYCODE_BUTTON_SELECT: - case KeyEvent.KEYCODE_BACK: state.press(6, pressed); break; + case KeyEvent.KEYCODE_BACK: pad.press(6, pressed); break; case KeyEvent.KEYCODE_BUTTON_START: - case KeyEvent.KEYCODE_MENU: state.press(7, pressed); break; - case KeyEvent.KEYCODE_BUTTON_THUMBL: state.press(8, pressed); break; - case KeyEvent.KEYCODE_BUTTON_THUMBR: state.press(9, pressed); break; + case KeyEvent.KEYCODE_MENU: pad.press(7, pressed); break; + case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break; + case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.press(9, pressed); break; // The client's own in-game menu is opened by this one; the interposer publishes it as // BTN_MODE, which SDL reports as the "guide" button. case KeyEvent.KEYCODE_BUTTON_MODE: - case KeyEvent.KEYCODE_HOME: state.press(PadState.GUIDE, pressed); break; - case KeyEvent.KEYCODE_BUTTON_L2: state.leftTrigger = pressed ? 1f : 0f; break; - case KeyEvent.KEYCODE_BUTTON_R2: state.rightTrigger = pressed ? 1f : 0f; break; - case KeyEvent.KEYCODE_DPAD_UP: state.up = pressed; break; - case KeyEvent.KEYCODE_DPAD_RIGHT: state.right = pressed; break; - case KeyEvent.KEYCODE_DPAD_DOWN: state.down = pressed; break; - case KeyEvent.KEYCODE_DPAD_LEFT: state.left = pressed; break; + case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break; + case KeyEvent.KEYCODE_BUTTON_L2: pad.leftTrigger = pressed ? 1f : 0f; break; + case KeyEvent.KEYCODE_BUTTON_R2: pad.rightTrigger = pressed ? 1f : 0f; break; + case KeyEvent.KEYCODE_DPAD_UP: pad.up = pressed; break; + case KeyEvent.KEYCODE_DPAD_RIGHT: pad.right = pressed; break; + case KeyEvent.KEYCODE_DPAD_DOWN: pad.down = pressed; break; + case KeyEvent.KEYCODE_DPAD_LEFT: pad.left = pressed; break; default: return false; } if (pressed) notePlayerInput(); statButtons++; scheduleStats(); - publish(); + publish(slot); return true; } @@ -194,33 +227,35 @@ public final class PadBridge { public synchronized boolean onMotionEvent(MotionEvent event) { if (!isFromController(event.getDevice())) return false; if (event.getAction() != MotionEvent.ACTION_MOVE) return false; - noteDevice(event.getDevice()); + int slot = slotFor(event.getDevice()); + PadState pad = stateFor(slot); + noteDevice(event.getDevice(), slot); statAxes++; scheduleStats(); - state.leftX = axis(event, MotionEvent.AXIS_X); + pad.leftX = axis(event, MotionEvent.AXIS_X); // Android's Y axis grows downwards and evdev's ABS_Y does too, so no flip here: what the // pad reports as "down" is what the client is told. - state.leftY = axis(event, MotionEvent.AXIS_Y); - state.rightX = axis(event, MotionEvent.AXIS_Z); - state.rightY = axis(event, MotionEvent.AXIS_RZ); + pad.leftY = axis(event, MotionEvent.AXIS_Y); + pad.rightX = axis(event, MotionEvent.AXIS_Z); + pad.rightY = axis(event, MotionEvent.AXIS_RZ); float lt = event.getAxisValue(MotionEvent.AXIS_LTRIGGER); float rt = event.getAxisValue(MotionEvent.AXIS_RTRIGGER); // Some pads only report the triggers on BRAKE/GAS. if (lt == 0f) lt = event.getAxisValue(MotionEvent.AXIS_BRAKE); if (rt == 0f) rt = event.getAxisValue(MotionEvent.AXIS_GAS); - state.leftTrigger = lt; - state.rightTrigger = rt; + pad.leftTrigger = lt; + pad.rightTrigger = rt; float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X); float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y); - state.up = hatY < -0.5f; - state.right = hatX > 0.5f; - state.down = hatY > 0.5f; - state.left = hatX < -0.5f; - if (Math.max(Math.max(Math.abs(state.leftX), Math.abs(state.leftY)), Math.max(Math.abs(state.rightX), Math.abs(state.rightY))) > 0.5f - || lt > 0.5f || rt > 0.5f || state.up || state.right || state.down || state.left) { + pad.up = hatY < -0.5f; + pad.right = hatX > 0.5f; + pad.down = hatY > 0.5f; + pad.left = hatX < -0.5f; + if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f + || lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) { notePlayerInput(); } - publish(); + publish(slot); return true; } @@ -231,6 +266,7 @@ public final class PadBridge { public synchronized void applyTouch(java.util.function.Consumer mutation) { mutation.accept(state); activeControllerId = NO_CONTROLLER; + slotControllers.set(0, NO_CONTROLLER); notePlayerInput(); statOnScreen++; scheduleStats(); @@ -255,6 +291,18 @@ public final class PadBridge { public synchronized void releaseAll() { state.clear(); publish(); + for (int slot = 1; slot < SLOTS; slot++) { + if (playerWriters[slot] == null) continue; + playerStates[slot].clear(); + publish(slot); + } + } + + /** A controller went away: its player's buttons are let go, and a further player's pad is unplugged. */ + public synchronized void onDeviceRemoved(int deviceId) { + for (int slot = 0; slot < SLOTS; slot++) { + if (owners[slot] == deviceId) free(slot); + } } /** Opens the client's Quick Access menu: a tap of the Deck's button, or the Guide-then-A chord. */ @@ -310,16 +358,71 @@ public final class PadBridge { publish(); } + private static boolean isPadKey(int keyCode) { + switch (keyCode) { + case KeyEvent.KEYCODE_BACK: + case KeyEvent.KEYCODE_MENU: + case KeyEvent.KEYCODE_HOME: + case KeyEvent.KEYCODE_DPAD_UP: + case KeyEvent.KEYCODE_DPAD_RIGHT: + case KeyEvent.KEYCODE_DPAD_DOWN: + case KeyEvent.KEYCODE_DPAD_LEFT: + return true; + default: + return KeyEvent.isGamepadButton(keyCode); + } + } + + /** The slot this controller plays in: the one it has, else the first free one, else player 1's. */ + private int slotFor(InputDevice device) { + int id = device.getId(); + if (owners[0] == id) return 0; + for (int slot = 1; slot < SLOTS; slot++) { + if (owners[slot] == id) return slot; + } + for (int slot = 0; slot < SLOTS; slot++) { + if (owners[slot] != NO_CONTROLLER && InputDevice.getDevice(owners[slot]) == null) free(slot); + } + for (int slot = 0; slot < SLOTS; slot++) { + if (owners[slot] != NO_CONTROLLER) continue; + owners[slot] = id; + Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") is player " + (slot + 1)); + return slot; + } + return 0; + } + + private PadState stateFor(int slot) { + return slot == 0 ? state : playerStates[slot]; + } + + private void free(int slot) { + Log.i(TAG, "player " + (slot + 1) + " (id " + owners[slot] + ") left"); + owners[slot] = NO_CONTROLLER; + slotControllers.set(slot, NO_CONTROLLER); + if (slot == 0) { + state.clear(); + publish(); + return; + } + playerStates[slot].clear(); + if (playerWriters[slot] != null) { + playerWriters[slot].destroy(); + playerWriters[slot] = null; + } + } + /** Per event, so the common case - the same pad as last time - is a single compare. */ - private void noteDevice(InputDevice device) { + private void noteDevice(InputDevice device, int slot) { activeControllerId = device.getId(); + slotControllers.set(slot, device.getId()); if (device.getId() == lastDeviceId) return; lastDeviceId = device.getId(); statDevice = device.getName(); if (seenDevices.add(device.getId())) { - Log.i(TAG, String.format(java.util.Locale.ROOT, "first input from \"%s\" (%04x:%04x, id %d, sources 0x%x); ring %s, deck pad %b", + Log.i(TAG, String.format(java.util.Locale.ROOT, "first input from \"%s\" (%04x:%04x, id %d, sources 0x%x); slot %d, ring %s, deck pad %b", device.getName(), device.getVendorId(), device.getProductId(), device.getId(), device.getSources(), - open ? "open" : "not open yet", SessionState.getDeckPad())); + slot, open ? "open" : "not open yet", SessionState.getDeckPad())); } } @@ -339,6 +442,23 @@ public final class PadBridge { statButtons = statAxes = statOnScreen = statDropped = 0; } + private void publish(int slot) { + if (slot == 0) { + publish(); + return; + } + FakeInputWriter player = playerWriters[slot]; + if (player == null) { + player = new FakeInputWriter(fakeInputDir.getAbsolutePath(), slot); + if (!player.open()) { + statDropped++; + return; + } + playerWriters[slot] = player; + } + player.writePad(playerStates[slot]); + } + private void publish() { if (!open && !start()) { statDropped++; diff --git a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt index 4522068d8..014b67bc3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt @@ -22,19 +22,19 @@ import kotlin.math.max * When a game plays a force-feedback effect on the fake pad (or Steam Input sends the Deck's * rumble report), the fake evdev layer inside the guest connects to the abstract socket [NAME] * and sends one packet: strong, weak, duration in ms and the pad slot, four little-endian 16-bit - * values. This listens for those and plays the effect on the physical controller that last drove - * the pad (PadBridge.activeControllerId) when Android exposes its motors - strong and weak - * separately where it has two - and otherwise on the device's own vibrator, with the stronger - * motor's strength: the on-screen pad, or a controller without rumble. Best effort both ways: a - * missing listener costs the guest nothing, and a bad packet is dropped. + * values. This listens for those and plays the effect on the physical controller playing in that + * slot (PadBridge.controllerForSlot) when Android exposes its motors - strong and weak separately + * where it has two - and otherwise on the device's own vibrator, with the stronger motor's + * strength: the on-screen pad, or a controller without rumble. Best effort both ways: a missing + * listener costs the guest nothing, and a bad packet is dropped. */ class RumbleComponent : SessionPart() { @Volatile private var server: LocalServerSocket? = null private var phone: Motors? = null - /** Where the last effect went, so the next one (or a stop) can end it there. */ - private var playing: Motors? = null - private var controllerId = PadBridge.NO_CONTROLLER - private var controller: Motors? = null + /** Per slot, where its last effect went, so the next one (or a stop) can end it there. */ + private val playing = HashMap() + /** Each controller's motors, looked up once; null when it has none. */ + private val controllers = HashMap() private var preferences: SharedPreferences? = null private var enabled = false private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> @@ -46,7 +46,7 @@ class RumbleComponent : SessionPart() { @Synchronized private fun refreshEnabled() { enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true - if (!enabled) { playing?.cancel(); playing = null } + if (!enabled) cancelAll() } override fun start() { @@ -64,7 +64,7 @@ class RumbleComponent : SessionPart() { try { val bytes = ByteArray(8) DataInputStream(client.inputStream).readFully(bytes) - buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4)) + buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6)) } catch (e: Exception) { // A partial packet or a closed peer: nothing to play. } finally { @@ -79,11 +79,9 @@ class RumbleComponent : SessionPart() { preferences?.unregisterOnSharedPreferenceChangeListener(preferenceListener) preferences = null enabled = false - playing?.cancel() - playing = null + cancelAll() phone = null - controller = null - controllerId = PadBridge.NO_CONTROLLER + controllers.clear() val s = server server = null try { s?.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ } @@ -91,13 +89,14 @@ class RumbleComponent : SessionPart() { private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8) - @Synchronized private fun buzz(strong: Int, weak: Int, ms: Int) { + @Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) { if (!enabled) return - val target = target() - if (target !== playing) { - playing?.cancel() - playing = target - target?.let { Log.i(TAG, "rumble: playing on ${it.name}") } + val target = target(slot) + val previous = playing[slot] + if (target !== previous) { + previous?.cancel() + if (target == null) playing.remove(slot) else playing[slot] = target + target?.let { Log.i(TAG, "rumble: slot $slot playing on ${it.name}") } } if (target == null) return if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); return } @@ -108,14 +107,17 @@ class RumbleComponent : SessionPart() { } } - /** The active controller's motors when it has any, else the phone's. */ - private fun target(): Motors? { - val id = PadBridge.activeControllerId() - if (id != controllerId) { - controllerId = id - controller = if (id == PadBridge.NO_CONTROLLER) null else try { controllerMotors(id) } catch (e: Exception) { null } - } - return controller ?: phone + /** The motors of the controller playing in this slot when it has any, else the phone's. */ + private fun target(slot: Int): Motors? { + val id = PadBridge.controllerForSlot(slot) + if (id == PadBridge.NO_CONTROLLER) return phone + if (!controllers.containsKey(id)) controllers[id] = try { controllerMotors(id) } catch (e: Exception) { null } + return controllers[id] ?: phone + } + + private fun cancelAll() { + playing.values.toSet().forEach { it.cancel() } + playing.clear() } /** One place an effect can play. Strengths are the evdev 0..65535 magnitudes. */ diff --git a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt index 293a48d58..280db6e54 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt @@ -115,16 +115,41 @@ class RumbleComponentTest { assertFalse(pad.vibrating) } - @After fun clearActiveController() { activeController(PadBridge.NO_CONTROLLER) } - - private fun activeController(id: Int) { - PadBridge::class.java.getDeclaredField("activeControllerId").apply { isAccessible = true }.setInt(null, id) + @Test fun eachPlayerSlotRumblesItsOwnControllerAndVirtualPadsUseTheLastActive() { + val first = FakeMotors() + val second = FakeMotors() + rumble.controllerMotors = { id -> if (id == PAD_ID) first else if (id == SECOND_PAD_ID) second else null } + activeController(PAD_ID) + activeController(SECOND_PAD_ID, slot = 1) + effect(strong = 100, weak = 0, slot = 1) + assertEquals(listOf(Triple(100, 0, 5000L)), second.played) + assertTrue(first.played.isEmpty()) + effect(strong = 200, weak = 0) + assertEquals(listOf(Triple(200, 0, 5000L)), first.played) + assertTrue("one player's effect ended another's", second.vibrating) + effect(strong = 0, weak = 0, slot = 1) + assertFalse(second.vibrating) + assertTrue(first.vibrating) + effect(strong = 300, weak = 0, slot = 16) + assertEquals(Triple(300, 0, 5000L), second.played.last()) + assertFalse(shadowOf(vibrator).isVibrating) } - private fun effect(strong: Int = 65535, weak: Int = 65535) { + @After fun clearActiveController() { + for (slot in 0 until PadBridge.SLOTS) activeController(PadBridge.NO_CONTROLLER, slot) + } + + private fun activeController(id: Int, slot: Int = 0) { + PadBridge::class.java.getDeclaredField("activeControllerId").apply { isAccessible = true }.setInt(null, id) + val slots = PadBridge::class.java.getDeclaredField("slotControllers").apply { isAccessible = true }.get(null) + (slots as java.util.concurrent.atomic.AtomicIntegerArray).set(slot, id) + } + + private fun effect(strong: Int = 65535, weak: Int = 65535, slot: Int = 0) { // Inject a decoded force-feedback packet; transport is outside these tests. - RumbleComponent::class.java.getDeclaredMethod("buzz", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType) - .apply { isAccessible = true }.invoke(rumble, strong, weak, 5000) + val int = Int::class.javaPrimitiveType + RumbleComponent::class.java.getDeclaredMethod("buzz", int, int, int, int) + .apply { isAccessible = true }.invoke(rumble, strong, weak, 5000, slot) } private class FakeMotors : RumbleComponent.Motors { @@ -135,7 +160,10 @@ class RumbleComponentTest { override fun cancel() { vibrating = false } } - private companion object { const val PAD_ID = 7 } + private companion object { + const val PAD_ID = 7 + const val SECOND_PAD_ID = 8 + } @Implements(LocalServerSocket::class) class NoPacketsSocket {