Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

Controllers: the shared logic in controller_common.cpp, scePad behind a backend

Rafael Abud Ferreira7236e7f4fc90
diff --git a/src/input/controller.h b/src/input/controller.h
index 2c013c2..707aec4 100644
--- a/src/input/controller.h
+++ b/src/input/controller.h
@@ -2,6 +2,8 @@
// Copyright (C) 2026 RafaelNGP
#pragma once
+#include "input/input_ext.h"
+
#include <cstdint>
#include <string>
@@ -49,12 +51,14 @@ struct ControllerState {
// Up to four DualSense: pad 0 belongs to the user who started the app, the
// others to the other signed-in users (each PS5 controller is tied to a
-// user), in the order they appear.
+// user), in the order they appear. On the desktop each gamepad plugged in
+// takes the first free slot.
constexpr int kMaxPads = 4;
bool init();
void shutdown();
-// Pad 0 (the menus).
+// Pad 0 (the menus); on the desktop the lowest slot with a pad, so the
+// menus still answer when the first pad was unplugged.
bool poll(ControllerState& out);
// Any pad; false (and `out` cleared) when there is none at `index`.
bool pollPad(int index, ControllerState& out);
@@ -69,6 +73,9 @@ uint64_t padActiveAt(int index);
bool inUse(const ControllerState& s);
std::string padUserName(int index);
int32_t padUserId(int index = 0);
+// The pad's own name ("DualSense Wireless Controller"...) where the system
+// gives one (desktop); empty on the PS5, where a pad goes by its user.
+std::string padDeviceName(int index);
// Rumble, 0..255 per motor (large = low frequency, small = high frequency),
// for `durationMs` (0 = until changed). Any thread; polling applies it.
void setRumble(uint8_t large, uint8_t small, uint32_t durationMs, int pad = 0);
diff --git a/src/input/controller_backend.h b/src/input/controller_backend.h
new file mode 100644
index 0000000..754b19a
--- /dev/null
+++ b/src/input/controller_backend.h
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// Between the controller code every platform shares (controller_common.cpp)
+// and a pad backend (controller_ps5.cpp, controller_sdl.cpp,
+// controller_null.cpp). The backend opens the pads (its own way: users
+// signing in on the PS5, gamepads plugged in on the desktop), reads them and
+// sends them effects; the shared code works out the rest once: the rumble
+// timeouts, the dead zones, the confirm button swap, the trigger feel, the
+// light bar's easing, gyro aiming and when a pad was last used.
+// Only the controller backends include this.
+#pragma once
+
+#include "input/controller.h"
+#include "input/tuning.h"
+
+#include <cstdint>
+
+namespace xc::input {
+
+// One pad as read, before the shared code works on it.
+struct RawPad {
+ bool dpadUp = false, dpadDown = false, dpadLeft = false, dpadRight = false;
+ // Where an Xbox pad has them: A the bottom face button (Cross), B the
+ // right one (Circle), X the left (Square), Y the top (Triangle).
+ bool btnA = false, btnB = false, btnX = false, btnY = false;
+ bool btnL1 = false, btnR1 = false, btnL3 = false, btnR3 = false;
+ bool btnOptions = false, btnTouchpad = false, btnNexus = false;
+ float leftX = 0, leftY = 0, rightX = 0, rightY = 0; // -1..1 (+y down), before the dead zone
+ float l2 = 0, r2 = 0; // 0..1
+ float gyro[3] = {0, 0, 0}; // rad/s: x pitch, y yaw, z roll
+ float accel[3] = {0, 0, 0}; // g
+ bool hasAccel = false; // accel was read (gyro aiming takes the pad as flat otherwise)
+ bool touching = false;
+ float touchX = 0, touchY = 0; // 0..1 from the top left
+};
+
+// How a pad's triggers vibrate: a DualSense's effects (resistance, pulses,
+// vibration: tuning.h's TriggerCommand), motors of their own (an Xbox pad's
+// impulse triggers), or not at all.
+enum class TriggerStyle { None, Adaptive, Motors };
+
+namespace backend {
+
+// Whether `slot` (0..kMaxPads-1) has a pad opened.
+bool padOpen(int slot);
+// Reads it; false when it doesn't answer or isn't connected.
+bool readPad(int slot, RawPad& out);
+// The two motors, 0..255 (large = low frequency), for `durationMs` more
+// (0 = until changed; the shared code sends 0 once the time is up anyway).
+void setMotors(int slot, uint8_t large, uint8_t small, uint32_t durationMs);
+TriggerStyle triggerStyle(int slot);
+// TriggerStyle::Adaptive: both triggers' commands (L2, R2); 0 when the pad
+// took them, the error otherwise (the shared code logs it).
+int setTriggerEffects(int slot, const TriggerCommand command[2]);
+// TriggerStyle::Motors: L2's and R2's motors, 0..255, as setMotors.
+void setTriggerMotors(int slot, uint8_t left, uint8_t right, uint32_t durationMs);
+// The light bar: a colour, or the system's own again (the player's).
+void setLight(int slot, uint8_t r, uint8_t g, uint8_t b);
+void resetLight(int slot);
+
+} // namespace backend
+
+// The backend tells the shared code as a slot's pad comes and goes:
+// opened (nothing sent to it yet), about to close (whether the light bar
+// shows the app's colour, to give it back) and closed.
+void slotOpened(int slot);
+bool slotLightSet(int slot);
+void slotClosed(int slot);
+
+} // namespace xc::input
diff --git a/src/input/controller_common.cpp b/src/input/controller_common.cpp
index 2d074cd..adba359 100644
--- a/src/input/controller_common.cpp
+++ b/src/input/controller_common.cpp
@@ -1,12 +1,170 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 RafaelNGP
-// What every controller backend shares (controller_ps5.cpp, controller_null.cpp).
+// What every controller backend shares (controller.h): the effects asked
+// for (rumble with its timeout, the triggers in the user's feel, the light
+// bar easing to its colour) and each pad's state worked out from what the
+// backend read (the confirm button swap, the dead zones, gyro aiming, when
+// it was last used). The backend (controller_ps5.cpp, controller_sdl.cpp,
+// controller_null.cpp) opens the pads and talks to them through
+// controller_backend.h.
#include "input/controller.h"
+#include "input/controller_backend.h"
+#include "input/gyro.h"
+#include "input/tuning.h"
+#include "platform/platform.h"
+#include "util/log.h"
+#include <algorithm>
+#include <atomic>
#include <cmath>
namespace xc::input {
+namespace {
+
+// A rumble request: packed as a << 8 | b, and when it ends (0 = never).
+struct Rumble {
+ std::atomic<uint32_t> wanted{0};
+ std::atomic<uint64_t> untilMs{0};
+ uint32_t applied = 0;
+
+ void set(uint8_t a, uint8_t b, uint32_t durationMs) {
+ untilMs = durationMs ? platform::nowMs() + durationMs : 0;
+ wanted = (uint32_t(a) << 8) | b;
+ }
+ // The value wanted now (0 once its time is up).
+ uint32_t current() {
+ uint32_t want = wanted;
+ uint64_t until = untilMs;
+ if (want && until && platform::nowMs() >= until) {
+ wanted.compare_exchange_strong(want, 0);
+ want = 0;
+ }
+ return want;
+ }
+ // The value to apply now, or false when it hasn't changed.
+ bool due(uint32_t& out) {
+ uint32_t want = wanted;
+ uint64_t until = untilMs;
+ if (want && until && platform::nowMs() >= until) {
+ wanted.compare_exchange_strong(want, 0);
+ want = 0;
+ }
+ if (want == applied) return false;
+ applied = out = want;
+ return true;
+ }
+ // What is left of it, ms (0: until changed).
+ uint32_t remainingMs() const {
+ uint64_t until = untilMs, now = platform::nowMs();
+ return until ? static_cast<uint32_t>(until > now ? std::min<uint64_t>(until - now, 0xFFFFFFFFu) : 1) : 0;
+ }
+};
+
+struct Pad {
+ std::atomic<bool> connected{false}; // the last poll's answer
+ Rumble motors, triggers;
+ TriggerCommand triggerSent[2]; // L2, R2 as last told
+ bool triggerFresh = false; // triggerSent is what the pad has
+ bool triggerVibrating[2] = {false, false};
+ uint32_t triggerMotorsSent = 0; // TriggerStyle::Motors: L2 << 8 | R2 as last told
+ // Light bar: wanted colour (r << 16 | g << 8 | b, bit 24 = set) and the
+ // one shown, easing towards it.
+ std::atomic<uint32_t> lightWanted{0};
+ uint32_t lightApplied = 0;
+ float light[3] = {0, 0, 0};
+ bool lightStarted = false;
+ std::atomic<uint64_t> activeAt{0}; // the last poll with a button or stick in use (ms)
+ GyroState gyro; // gyro aiming's eased push
+};
+Pad g_pads[kMaxPads];
+std::atomic<float> g_deadzone[2] = {0.15f, 0.15f};
+std::atomic<bool> g_circleConfirms{false};
+std::atomic<int> g_triggerStrength{kTriggerMedium}, g_triggerHz{1}, g_triggerResistance{0};
+std::atomic<bool> g_triggerPulses{false}, g_triggerLogging{false}, g_resistanceActive{false};
+std::atomic<int> g_gyroMode{kGyroOff}, g_gyroLevel{5};
+std::atomic<bool> g_gyroActive{false};
+int g_gyroLogged = 0, g_gyroLoggedX = 0; // the first turns up / down and sideways, to check the axes
+
+void applyLightBar(int index, Pad& pad) {
+ uint32_t want = pad.lightWanted;
+ if (!(want & (1u << 24))) {
+ if (pad.lightApplied) { // reset: the system's colour again
+ backend::resetLight(index);
+ pad.lightApplied = 0;
+ pad.lightStarted = false;
+ }
+ return;
+ }
+ const float target[3] = {static_cast<float>((want >> 16) & 0xFF), static_cast<float>((want >> 8) & 0xFF),
+ static_cast<float>(want & 0xFF)};
+ if (!pad.lightStarted) {
+ std::copy(target, target + 3, pad.light);
+ pad.lightStarted = true;
+ }
+ // ~120 polls a second: 4 % of the way each, most of it in ~0.4 s.
+ for (int i = 0; i < 3; ++i) pad.light[i] += (target[i] - pad.light[i]) * 0.04f;
+ const uint8_t r = static_cast<uint8_t>(std::lround(pad.light[0])), g = static_cast<uint8_t>(std::lround(pad.light[1])),
+ b = static_cast<uint8_t>(std::lround(pad.light[2]));
+ uint32_t shown = (1u << 24) | (uint32_t(r) << 16) | (uint32_t(g) << 8) | b;
+ if (shown == pad.lightApplied) return;
+ backend::setLight(index, r, g, b);
+ pad.lightApplied = shown;
+}
+
+// Trigger motors (an Xbox pad's): the game's levels in the user's strength,
+// sent when they change.
+void applyTriggerMotors(int index, Pad& pad) {
+ uint32_t v = pad.triggers.current();
+ int strength = g_triggerStrength;
+ const uint8_t level[2] = {static_cast<uint8_t>(v >> 8), static_cast<uint8_t>(v)};
+ const uint8_t out[2] = {triggerMotorLevel(level[0], strength), triggerMotorLevel(level[1], strength)};
+ uint32_t packed = (uint32_t(out[0]) << 8) | out[1];
+ if (packed == pad.triggerMotorsSent) return;
+ if (g_triggerLogging)
+ for (int t = 0; t < 2; ++t)
+ if (bool is = out[t] != 0; is != (((pad.triggerMotorsSent >> (t ? 0 : 8)) & 0xFF) != 0))
+ XC_LOGI("trigger %s: %s (motor %u)", t ? "R2" : "L2", is ? "vibrating" : "still", out[t]);
+ backend::setTriggerMotors(index, out[0], out[1], packed ? pad.triggers.remainingMs() : 0);
+ pad.triggerMotorsSent = packed;
+}
+
+void applyRumble(int index, Pad& pad) {
+ uint32_t v;
+ if (pad.motors.due(v))
+ backend::setMotors(index, static_cast<uint8_t>(v >> 8), static_cast<uint8_t>(v), v ? pad.motors.remainingMs() : 0);
+ TriggerStyle style = backend::triggerStyle(index);
+ if (style == TriggerStyle::Motors) return applyTriggerMotors(index, pad);
+ if (style != TriggerStyle::Adaptive) return;
+ // The triggers, worked out on every poll (the pulses change on their
+ // own) and sent when either changes.
+ v = pad.triggers.current();
+ const uint8_t level[2] = {static_cast<uint8_t>(v >> 8), static_cast<uint8_t>(v)};
+ int strength = g_triggerStrength, hz = g_triggerHz, resistance = g_resistanceActive ? g_triggerResistance.load() : 0;
+ bool pulses = g_triggerPulses;
+ uint64_t now = platform::nowMs();
+ TriggerCommand want[2];
+ for (int t = 0; t < 2; ++t) want[t] = triggerCommand(level[t], strength, hz, resistance, pulses, now);
+ if (pad.triggerFresh && want[0] == pad.triggerSent[0] && want[1] == pad.triggerSent[1]) return;
+ int rc = backend::setTriggerEffects(index, want);
+ static int failures = 0; // a refused effect is sent again each poll: logged a few times
+ for (int t = 0; t < 2; ++t) {
+ // Vibrating: the motor, or pulses (a feedback while there is a request).
+ bool was = pad.triggerFresh && pad.triggerVibrating[t];
+ bool is = level[t] && triggerAmplitude(level[t], strength);
+ if ((g_triggerLogging && was != is) || (rc != 0 && failures < 6))
+ XC_LOGI("trigger %s: %s (mode %d, %u %u %u %u): 0x%08x", t ? "R2" : "L2", is ? "vibrating" : "still", want[t].mode,
+ want[t].data[0], want[t].data[1], want[t].data[2], want[t].data[3], static_cast<unsigned>(rc));
+ }
+ for (int t = 0; t < 2; ++t) pad.triggerVibrating[t] = level[t] && triggerAmplitude(level[t], strength);
+ pad.triggerSent[0] = want[0];
+ pad.triggerSent[1] = want[1];
+ pad.triggerFresh = rc == 0;
+ if (rc != 0) ++failures;
+}
+
+} // namespace
+
bool inUse(const ControllerState& s) {
return s.btnA || s.btnB || s.btnX || s.btnY || s.dpadUp || s.dpadDown || s.dpadLeft || s.dpadRight || s.btnL1 ||
s.btnR1 || s.btnL3 || s.btnR3 || s.btnOptions || s.btnTouchpad || s.triggerL2 > 0.5f || s.triggerR2 > 0.5f ||
@@ -14,4 +172,139 @@ bool inUse(const ControllerState& s) {
std::abs(s.rightStickY) > 0.5f;
}
+void slotOpened(int slot) {
+ Pad& pad = g_pads[slot];
+ pad.motors.applied = pad.triggers.applied = 0;
+ pad.triggerFresh = false;
+ pad.triggerMotorsSent = 0;
+}
+
+bool slotLightSet(int slot) { return g_pads[slot].lightApplied != 0; }
+
+void slotClosed(int slot) {
+ Pad& pad = g_pads[slot];
+ pad.lightApplied = 0;
+ pad.lightStarted = false;
+ pad.connected = false;
+}
+
+void setRumble(uint8_t large, uint8_t small, uint32_t durationMs, int pad) {
+ if (pad >= 0 && pad < kMaxPads) g_pads[pad].motors.set(large, small, durationMs);
+}
+
+void setTriggerRumble(uint8_t left, uint8_t right, uint32_t durationMs, int pad) {
+ if (g_triggerStrength <= 0) left = right = 0;
+ if (pad >= 0 && pad < kMaxPads) g_pads[pad].triggers.set(left, right, durationMs);
+}
+
+void setCircleConfirms(bool on) { g_circleConfirms = on; }
+bool circleConfirms() { return g_circleConfirms; }
+
+void setLightBar(uint8_t r, uint8_t g, uint8_t b, int pad) {
+ if (pad >= 0 && pad < kMaxPads) g_pads[pad].lightWanted = (1u << 24) | (uint32_t(r) << 16) | (uint32_t(g) << 8) | b;
+}
+
+void resetLightBar(int pad) {
+ if (pad >= 0 && pad < kMaxPads) g_pads[pad].lightWanted = 0;
+}
+
+bool padConnected(int index) { return index >= 0 && index < kMaxPads && g_pads[index].connected; }
+
+void setTriggerFeel(int strength, int hzIndex, int resistance, bool pulses) {
+ g_triggerStrength = std::clamp(strength, 0, kTriggerStrengths - 1);
+ g_triggerHz = std::clamp(hzIndex, 0, 2);
+ g_triggerResistance = std::clamp(resistance, 0, kTriggerResistances - 1);
+ g_triggerPulses = pulses;
+ if (!g_triggerStrength)
+ for (Pad& p : g_pads) p.triggers.set(0, 0, 0);
+ // The next poll works the triggers out in the new feel.
+}
+
+void setTriggerLogging(bool on) { g_triggerLogging = on; }
+void setTriggerResistanceActive(bool on) { g_resistanceActive = on; }
+
+void setDeadzone(float left, float right) {
+ g_deadzone[0] = std::clamp(left, 0.0f, 0.5f);
+ g_deadzone[1] = std::clamp(right, 0.0f, 0.5f);
+}
+
+bool pollPad(int index, ControllerState& out) {
+ out = {};
+ if (index < 0 || index >= kMaxPads || !backend::padOpen(index)) return false;
+ Pad& slot = g_pads[index];
+ applyRumble(index, slot);
+ applyLightBar(index, slot);
+ RawPad pad;
+ slot.connected = backend::readPad(index, pad);
+ if (!slot.connected) return false;
+
+ out.connected = true;
+ out.dpadUp = pad.dpadUp;
+ out.dpadRight = pad.dpadRight;
+ out.dpadDown = pad.dpadDown;
+ out.dpadLeft = pad.dpadLeft;
+
+ out.btnA = pad.btnA;
+ out.btnB = pad.btnB;
+ out.btnX = pad.btnX;
+ out.btnY = pad.btnY;
+ if (g_circleConfirms) std::swap(out.btnA, out.btnB);
+
+ out.btnL1 = pad.btnL1;
+ out.btnR1 = pad.btnR1;
+ out.btnL3 = pad.btnL3;
+ out.btnR3 = pad.btnR3;
+
+ out.btnOptions = pad.btnOptions;
+ out.btnTouchpad = pad.btnTouchpad;
+ out.btnNexus = pad.btnNexus;
+
+ out.rawLeftX = out.leftStickX = pad.leftX;
+ out.rawLeftY = out.leftStickY = pad.leftY;
+ out.rawRightX = out.rightStickX = pad.rightX;
+ out.rawRightY = out.rightStickY = pad.rightY;
+ radialDeadzone(out.leftStickX, out.leftStickY, g_deadzone[0].load(std::memory_order_relaxed));
+ radialDeadzone(out.rightStickX, out.rightStickY, g_deadzone[1].load(std::memory_order_relaxed));
+
+ out.triggerL2 = pad.l2;
+ out.triggerR2 = pad.r2;
+
+ // Gyro aiming: in a game (menu closed), always or while L2 aims.
+ int gyroMode = g_gyroMode.load(std::memory_order_relaxed);
+ bool gyroOn = g_gyroActive && (gyroMode == kGyroAlways || (gyroMode == kGyroAiming && out.triggerL2 > 0.3f));
+ if (gyroOn) {
+ float gx, gy;
+ gyroToStick(pad.gyro, pad.hasAccel ? pad.accel : nullptr, g_gyroLevel.load(std::memory_order_relaxed), slot.gyro, gx, gy);
+ float x = out.rightStickX + gx, y = out.rightStickY + gy, m = std::hypot(x, y);
+ if (m > 1.0f) x /= m, y /= m;
+ out.rightStickX = x;
+ out.rightStickY = y;
+ // The first few turns each way, to check the axes.
+ bool sideways = std::abs(gx) > 0.5f && std::abs(gx) > std::abs(gy);
+ int& logged = sideways ? g_gyroLoggedX : g_gyroLogged;
+ if (logged < 4 && std::max(std::abs(gx), std::abs(gy)) > 0.5f)
+ XC_LOGI("gyro: pitch %.2f yaw %.2f roll %.2f rad/s, gravity %.2f,%.2f,%.2f -> stick %.2f,%.2f", pad.gyro[0],
+ pad.gyro[1], pad.gyro[2], pad.accel[0], pad.accel[1], pad.accel[2], gx, gy), ++logged;
+ } else {
+ slot.gyro = {};
+ }
+
+ if (pad.touching) {
+ out.touching = true;
+ out.touchX = pad.touchX;
+ out.touchY = pad.touchY;
+ }
+ if (inUse(out)) slot.activeAt = platform::nowMs();
+
+ return true;
+}
+
+uint64_t padActiveAt(int index) { return index >= 0 && index < kMaxPads ? g_pads[index].activeAt.load() : 0; }
+void setGyro(int mode, int level) {
+ g_gyroMode = std::clamp(mode, 0, 2);
+ g_gyroLevel = std::clamp(level, 1, kGyroLevels);
+}
+
+void setGyroActive(bool on) { g_gyroActive = on; }
+
} // namespace xc::input
diff --git a/src/input/controller_null.cpp b/src/input/controller_null.cpp
index aeb639a..b13d893 100644
--- a/src/input/controller_null.cpp
+++ b/src/input/controller_null.cpp
@@ -1,47 +1,36 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 RafaelNGP
-// No controllers (a build without a pad backend): every slot is empty, the
-// effects go nowhere, and the settings are kept so their getters answer.
+// No controllers (a build without a pad backend): every slot is empty, so
+// the shared code (controller_common.cpp) reads nothing and sends no effect;
+// the settings it keeps (dead zones, confirm button...) still answer.
#include "input/controller.h"
-
-#include <algorithm>
-#include <atomic>
+#include "input/controller_backend.h"
+#include "input/input_ext.h"
namespace xc::input {
-namespace {
-// Kept as the PS5's backend keeps them; nothing reads the dead zones without a pad.
-std::atomic<float> g_deadzone[2] = {0.15f, 0.15f};
-std::atomic<bool> g_circleConfirms{false};
-} // namespace
+namespace backend {
+
+bool padOpen(int) { return false; }
+bool readPad(int, RawPad&) { return false; }
+void setMotors(int, uint8_t, uint8_t, uint32_t) {}
+TriggerStyle triggerStyle(int) { return TriggerStyle::None; }
+int setTriggerEffects(int, const TriggerCommand*) { return -1; }
+void setTriggerMotors(int, uint8_t, uint8_t, uint32_t) {}
+void setLight(int, uint8_t, uint8_t, uint8_t) {}
+void resetLight(int) {}
+
+} // namespace backend
bool init() { return true; }
void shutdown() {}
bool poll(ControllerState& out) { return pollPad(0, out); }
-bool pollPad(int, ControllerState& out) {
- out = {};
- return false;
-}
void refreshPads() {}
-bool padConnected(int) { return false; }
-uint64_t padActiveAt(int) { return 0; }
std::string padUserName(int) { return {}; }
+std::string padDeviceName(int) { return {}; }
int32_t padUserId(int) { return -1; }
-void setRumble(uint8_t, uint8_t, uint32_t, int) {}
-void setTriggerRumble(uint8_t, uint8_t, uint32_t, int) {}
-void setDeadzone(float left, float right) {
- g_deadzone[0] = std::clamp(left, 0.0f, 0.5f);
- g_deadzone[1] = std::clamp(right, 0.0f, 0.5f);
-}
-void setCircleConfirms(bool on) { g_circleConfirms = on; }
-bool circleConfirms() { return g_circleConfirms; }
-void setTriggerFeel(int, int, int, bool) {}
-void setTriggerLogging(bool) {}
-void setTriggerResistanceActive(bool) {}
-void setLightBar(uint8_t, uint8_t, uint8_t, int) {}
-void resetLightBar(int) {}
-void setGyro(int, int) {}
-void setGyroActive(bool) {}
void setEmbeddedMicActive(bool, int) {}
+PadCaps padCaps(int) { return {}; }
+PadCaps anyPadCaps() { return {}; }
} // namespace xc::input
diff --git a/src/input/controller_ps5.cpp b/src/input/controller_ps5.cpp
index 5b5e161..264de13 100644
--- a/src/input/controller_ps5.cpp
+++ b/src/input/controller_ps5.cpp
@@ -1,20 +1,18 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 RafaelNGP
-// The DualSense through libScePad, one per signed-in user (controller.h).
-// controller_null.cpp stands in elsewhere.
+// The DualSense through libScePad, one per signed-in user (controller.h):
+// the pads opened as users sign in and out, read, and sent the effects the
+// shared code (controller_common.cpp) works out. controller_sdl.cpp and
+// controller_null.cpp stand in elsewhere.
#include "input/controller.h"
-#include "input/gyro.h"
-#include "input/tuning.h"
+#include "input/controller_backend.h"
+#include "input/input_ext.h"
#include "util/log.h"
#include <algorithm>
-#include <atomic>
-#include <cmath>
#include <cstddef>
#include <cstring>
-#include "platform/platform.h"
-
extern "C" {
// Layout of OpenOrbis's OrbisPadData, as the console fills it (connected
// sits at offset 76).
@@ -105,67 +103,14 @@ namespace xc::input {
namespace {
-// A rumble request: packed as a << 8 | b, and when it ends (0 = never).
-struct Rumble {
- std::atomic<uint32_t> wanted{0};
- std::atomic<uint64_t> untilMs{0};
- uint32_t applied = 0;
-
- void set(uint8_t a, uint8_t b, uint32_t durationMs) {
- untilMs = durationMs ? platform::nowMs() + durationMs : 0;
- wanted = (uint32_t(a) << 8) | b;
- }
- // The value wanted now (0 once its time is up).
- uint32_t current() {
- uint32_t want = wanted;
- uint64_t until = untilMs;
- if (want && until && platform::nowMs() >= until) {
- wanted.compare_exchange_strong(want, 0);
- want = 0;
- }
- return want;
- }
- // The value to apply now, or false when it hasn't changed.
- bool due(uint32_t& out) {
- uint32_t want = wanted;
- uint64_t until = untilMs;
- if (want && until && platform::nowMs() >= until) {
- wanted.compare_exchange_strong(want, 0);
- want = 0;
- }
- if (want == applied) return false;
- applied = out = want;
- return true;
- }
-};
-
-struct Pad {
+// A signed-in user's pad.
+struct Slot {
int32_t userId = -1;
int32_t handle = -1;
- std::atomic<bool> connected{false}; // the last poll's answer
- char name[32] = {}; // the user's, read when opened
- Rumble motors, triggers;
- TriggerCommand triggerSent[2]; // L2, R2 as last told
- bool triggerFresh = false; // triggerSent is what the pad has
- bool triggerVibrating[2] = {false, false};
- // Light bar: wanted colour (r << 16 | g << 8 | b, bit 24 = set) and the
- // one shown, easing towards it.
- std::atomic<uint32_t> lightWanted{0};
- uint32_t lightApplied = 0;
- float light[3] = {0, 0, 0};
- bool lightStarted = false;
- std::atomic<uint64_t> activeAt{0}; // the last poll with a button or stick in use (ms)
- GyroState gyro; // gyro aiming's eased push
+ char name[32] = {}; // the user's, read when opened
};
-Pad g_pads[kMaxPads];
-std::atomic<float> g_deadzone[2] = {0.15f, 0.15f};
-std::atomic<bool> g_circleConfirms{false};
-std::atomic<int> g_triggerStrength{kTriggerMedium}, g_triggerHz{1}, g_triggerResistance{0};
-std::atomic<bool> g_triggerPulses{false}, g_triggerLogging{false}, g_resistanceActive{false};
+Slot g_slots[kMaxPads];
bool g_rumbleLogged = false;
-std::atomic<int> g_gyroMode{kGyroOff}, g_gyroLevel{5};
-std::atomic<bool> g_gyroActive{false};
-int g_gyroLogged = 0, g_gyroLoggedX = 0; // the first turns up / down and sideways, to check the axes
inline float normStick(uint8_t val) {
// 0..255 -> -1.0 .. 1.0
@@ -176,7 +121,8 @@ inline float normTrigger(uint8_t val) {
return static_cast<float>(val) / 255.0f;
}
-bool openPad(Pad& pad, int32_t userId, int slot) {
+bool openPad(int slot, int32_t userId) {
+ Slot& pad = g_slots[slot];
int32_t h = scePadOpen(userId, 0, 0, nullptr);
if (h < 0) {
XC_LOGW("scePadOpen(user %d): 0x%08x", userId, static_cast<unsigned>(h));
@@ -191,132 +137,125 @@ bool openPad(Pad& pad, int32_t userId, int slot) {
pad.userId = userId;
pad.handle = h;
if (sceUserServiceGetUserName(userId, pad.name, sizeof pad.name) != 0) pad.name[0] = 0;
- pad.motors.applied = pad.triggers.applied = 0;
- pad.triggerFresh = false;
+ slotOpened(slot);
XC_LOGI("pad %d opened (handle %d, rumble mode 0x%08x)", slot, h, static_cast<unsigned>(mode));
return true;
}
-void closePad(Pad& pad, int slot) {
+void closePad(int slot) {
+ Slot& pad = g_slots[slot];
if (pad.handle < 0) return;
ScePadVibrationParam off{0, 0};
scePadSetVibration(pad.handle, &off);
ScePadTriggerEffectParam none{};
none.triggerMask = 3;
scePadSetTriggerEffect(pad.handle, &none);
- if (pad.lightApplied) scePadResetLightBar(pad.handle);
- pad.lightApplied = 0;
- pad.lightStarted = false;
+ if (slotLightSet(slot)) scePadResetLightBar(pad.handle);
+ slotClosed(slot);
scePadClose(pad.handle);
XC_LOGI("pad %d closed (user %d)", slot, pad.userId);
pad.handle = -1;
pad.userId = -1;
- pad.connected = false;
pad.name[0] = 0;
}
-void applyLightBar(Pad& pad) {
- uint32_t want = pad.lightWanted;
- if (!(want & (1u << 24))) {
- if (pad.lightApplied) { // reset: the system's colour again
- scePadResetLightBar(pad.handle);
- pad.lightApplied = 0;
- pad.lightStarted = false;
- }
- return;
- }
- const float target[3] = {static_cast<float>((want >> 16) & 0xFF), static_cast<float>((want >> 8) & 0xFF),
- static_cast<float>(want & 0xFF)};
- if (!pad.lightStarted) {
- std::copy(target, target + 3, pad.light);
- pad.lightStarted = true;
+} // namespace
+
+namespace backend {
+
+bool padOpen(int slot) { return g_slots[slot].handle >= 0; }
+
+bool readPad(int slot, RawPad& out) {
+ ScePadData pad{};
+ int rc = scePadReadState(g_slots[slot].handle, &pad);
+ if (rc != 0 || !pad.connected) return false;
+ uint32_t b = pad.buttons;
+
+ // D-Pad
+ out.dpadUp = (b & 0x0010) != 0;
+ out.dpadRight = (b & 0x0020) != 0;
+ out.dpadDown = (b & 0x0040) != 0;
+ out.dpadLeft = (b & 0x0080) != 0;
+
+ // DualSense -> Xbox: Cross->A, Circle->B, Square->X, Triangle->Y
+ out.btnA = (b & 0x4000) != 0; // Cross
+ out.btnB = (b & 0x2000) != 0; // Circle
+ out.btnX = (b & 0x8000) != 0; // Square
+ out.btnY = (b & 0x1000) != 0; // Triangle
+
+ // Shoulders & Sticks
+ out.btnL1 = (b & 0x0400) != 0;
+ out.btnR1 = (b & 0x0800) != 0;
+ out.btnL3 = (b & 0x0002) != 0;
+ out.btnR3 = (b & 0x0004) != 0;
+
+ out.btnOptions = (b & 0x0008) != 0;
+ out.btnTouchpad = (b & 0x100000) != 0;
+
+ // Analog
+ out.leftX = normStick(pad.leftStick.x);
+ out.leftY = normStick(pad.leftStick.y);
+ out.rightX = normStick(pad.rightStick.x);
+ out.rightY = normStick(pad.rightStick.y);
+ out.l2 = normTrigger(pad.l2);
+ out.r2 = normTrigger(pad.r2);
+
+ std::copy(pad.angularVelocity, pad.angularVelocity + 3, out.gyro);
+ std::copy(pad.acceleration, pad.acceleration + 3, out.accel);
+ out.hasAccel = true;
+
+ // The DualSense touchpad reports 0..1919 x 0..1079.
+ if (pad.touchData.touchNum > 0) {
+ out.touching = true;
+ out.touchX = std::clamp(pad.touchData.touch[0].x / 1919.0f, 0.0f, 1.0f);
+ out.touchY = std::clamp(pad.touchData.touch[0].y / 1079.0f, 0.0f, 1.0f);
}
- // ~120 polls a second: 4 % of the way each, most of it in ~0.4 s.
- for (int i = 0; i < 3; ++i) pad.light[i] += (target[i] - pad.light[i]) * 0.04f;
- ScePadColor c{static_cast<uint8_t>(std::lround(pad.light[0])), static_cast<uint8_t>(std::lround(pad.light[1])),
- static_cast<uint8_t>(std::lround(pad.light[2])), 0};
- uint32_t shown = (1u << 24) | (uint32_t(c.r) << 16) | (uint32_t(c.g) << 8) | c.b;
- if (shown == pad.lightApplied) return;
- int rc = scePadSetLightBar(pad.handle, &c);
- static bool logged = false;
- if (!logged || rc != 0) XC_LOGI("scePadSetLightBar(%u, %u, %u): 0x%08x", c.r, c.g, c.b, static_cast<unsigned>(rc));
- logged = true;
- pad.lightApplied = shown;
+ return true;
}
-void applyRumble(Pad& pad) {
- uint32_t v;
- if (pad.motors.due(v)) {
- ScePadVibrationParam p{static_cast<uint8_t>(v >> 8), static_cast<uint8_t>(v)};
- int rc = scePadSetVibration(pad.handle, &p);
- if (!g_rumbleLogged || rc != 0) XC_LOGI("scePadSetVibration(%u, %u): 0x%08x", p.largeMotor, p.smallMotor, rc);
- g_rumbleLogged = true;
- }
- // The triggers, worked out on every poll (the pulses change on their
- // own) and sent when either changes.
- v = pad.triggers.current();
- const uint8_t level[2] = {static_cast<uint8_t>(v >> 8), static_cast<uint8_t>(v)};
- int strength = g_triggerStrength, hz = g_triggerHz, resistance = g_resistanceActive ? g_triggerResistance.load() : 0;
- bool pulses = g_triggerPulses;
- uint64_t now = platform::nowMs();
- TriggerCommand want[2];
- for (int t = 0; t < 2; ++t) want[t] = triggerCommand(level[t], strength, hz, resistance, pulses, now);
- if (pad.triggerFresh && want[0] == pad.triggerSent[0] && want[1] == pad.triggerSent[1]) return;
+void setMotors(int slot, uint8_t large, uint8_t small, uint32_t) {
+ ScePadVibrationParam p{large, small};
+ int rc = scePadSetVibration(g_slots[slot].handle, &p);
+ if (!g_rumbleLogged || rc != 0) XC_LOGI("scePadSetVibration(%u, %u): 0x%08x", p.largeMotor, p.smallMotor, rc);
+ g_rumbleLogged = true;
+}
+
+TriggerStyle triggerStyle(int) { return TriggerStyle::Adaptive; }
+
+int setTriggerEffects(int slot, const TriggerCommand command[2]) {
ScePadTriggerEffectParam p{};
p.triggerMask = 3;
for (int t = 0; t < 2; ++t) {
- p.command[t].mode = want[t].mode;
- std::copy(want[t].data, want[t].data + 4, p.command[t].data);
+ p.command[t].mode = command[t].mode;
+ std::copy(command[t].data, command[t].data + 4, p.command[t].data);
}
- int rc = scePadSetTriggerEffect(pad.handle, &p);
- static int failures = 0; // a refused effect is sent again each poll: logged a few times
- for (int t = 0; t < 2; ++t) {
- // Vibrating: the motor, or pulses (a feedback while there is a request).
- bool was = pad.triggerFresh && pad.triggerVibrating[t];
- bool is = level[t] && triggerAmplitude(level[t], strength);
- if ((g_triggerLogging && was != is) || (rc != 0 && failures < 6))
- XC_LOGI("trigger %s: %s (mode %d, %u %u %u %u): 0x%08x", t ? "R2" : "L2", is ? "vibrating" : "still", want[t].mode,
- want[t].data[0], want[t].data[1], want[t].data[2], want[t].data[3], static_cast<unsigned>(rc));
- }
- for (int t = 0; t < 2; ++t) pad.triggerVibrating[t] = level[t] && triggerAmplitude(level[t], strength);
- pad.triggerSent[0] = want[0];
- pad.triggerSent[1] = want[1];
- pad.triggerFresh = rc == 0;
- if (rc != 0) ++failures;
+ return scePadSetTriggerEffect(g_slots[slot].handle, &p);
}
-} // namespace
-
-void setRumble(uint8_t large, uint8_t small, uint32_t durationMs, int pad) {
- if (pad >= 0 && pad < kMaxPads) g_pads[pad].motors.set(large, small, durationMs);
-}
+void setTriggerMotors(int, uint8_t, uint8_t, uint32_t) {} // the DualSense's are its effects
-void setTriggerRumble(uint8_t left, uint8_t right, uint32_t durationMs, int pad) {
- if (g_triggerStrength <= 0) left = right = 0;
- if (pad >= 0 && pad < kMaxPads) g_pads[pad].triggers.set(left, right, durationMs);
-}
-
-void setCircleConfirms(bool on) { g_circleConfirms = on; }
-bool circleConfirms() { return g_circleConfirms; }
-
-void setLightBar(uint8_t r, uint8_t g, uint8_t b, int pad) {
- if (pad >= 0 && pad < kMaxPads) g_pads[pad].lightWanted = (1u << 24) | (uint32_t(r) << 16) | (uint32_t(g) << 8) | b;
+void setLight(int slot, uint8_t r, uint8_t g, uint8_t b) {
+ ScePadColor c{r, g, b, 0};
+ int rc = scePadSetLightBar(g_slots[slot].handle, &c);
+ static bool logged = false;
+ if (!logged || rc != 0) XC_LOGI("scePadSetLightBar(%u, %u, %u): 0x%08x", c.r, c.g, c.b, static_cast<unsigned>(rc));
+ logged = true;
}
-void resetLightBar(int pad) {
- if (pad >= 0 && pad < kMaxPads) g_pads[pad].lightWanted = 0;
-}
+void resetLight(int slot) { scePadResetLightBar(g_slots[slot].handle); }
-bool padConnected(int index) { return index >= 0 && index < kMaxPads && g_pads[index].connected; }
+} // namespace backend
std::string padUserName(int index) {
// Main thread, like refreshPads() which changes it.
- return index >= 0 && index < kMaxPads && g_pads[index].handle >= 0 ? g_pads[index].name : "";
+ return index >= 0 && index < kMaxPads && g_slots[index].handle >= 0 ? g_slots[index].name : "";
}
+std::string padDeviceName(int) { return {}; } // the console's pads go by their user (padUserName)
+
int32_t padUserId(int index) {
- if (index >= 0 && index < kMaxPads && g_pads[index].handle >= 0 && g_pads[index].userId >= 0) {
- return g_pads[index].userId;
+ if (index >= 0 && index < kMaxPads && g_slots[index].handle >= 0 && g_slots[index].userId >= 0) {
+ return g_slots[index].userId;
}
int32_t uid = -1;
if (sceUserServiceGetInitialUser(&uid) == 0 && uid >= 0) {
@@ -325,23 +264,13 @@ int32_t padUserId(int index) {
return -1;
}
-void setTriggerFeel(int strength, int hzIndex, int resistance, bool pulses) {
- g_triggerStrength = std::clamp(strength, 0, kTriggerStrengths - 1);
- g_triggerHz = std::clamp(hzIndex, 0, 2);
- g_triggerResistance = std::clamp(resistance, 0, kTriggerResistances - 1);
- g_triggerPulses = pulses;
- if (!g_triggerStrength)
- for (Pad& p : g_pads) p.triggers.set(0, 0, 0);
- // The next poll works the triggers out in the new feel.
+// Every pad here is a DualSense: the UI keeps every option, as before.
+PadCaps padCaps(int index) {
+ if (!padConnected(index)) return {};
+ return {PadKind::DualSense, true, true, true, true, true, true};
}
-void setTriggerLogging(bool on) { g_triggerLogging = on; }
-void setTriggerResistanceActive(bool on) { g_resistanceActive = on; }
-
-void setDeadzone(float left, float right) {
- g_deadzone[0] = std::clamp(left, 0.0f, 0.5f);
- g_deadzone[1] = std::clamp(right, 0.0f, 0.5f);
-}
+PadCaps anyPadCaps() { return {PadKind::DualSense, true, true, true, true, true, true}; }
bool init() {
int rc = scePadInit();
@@ -360,7 +289,7 @@ bool init() {
XC_LOGE("sceUserServiceGetInitialUser failed: 0x%08x", rc);
return false;
}
- if (!openPad(g_pads[0], uid, 0)) return false;
+ if (!openPad(0, uid)) return false;
refreshPads();
return true;
}
@@ -376,117 +305,30 @@ void refreshPads() {
};
// Signed out: free the slot (pad 0 stays with the app's user).
for (int i = 1; i < kMaxPads; ++i)
- if (g_pads[i].handle >= 0 && !signedIn(g_pads[i].userId)) closePad(g_pads[i], i);
+ if (g_slots[i].handle >= 0 && !signedIn(g_slots[i].userId)) closePad(i);
// Signed in: the first free slot.
for (int32_t user : list.userId) {
if (user < 0) continue;
bool known = false;
- for (const Pad& p : g_pads) known |= p.userId == user;
+ for (const Slot& p : g_slots) known |= p.userId == user;
if (known) continue;
for (int i = 1; i < kMaxPads; ++i)
- if (g_pads[i].handle < 0) {
- openPad(g_pads[i], user, i);
+ if (g_slots[i].handle < 0) {
+ openPad(i, user);
break;
}
}
}
void shutdown() {
- for (int i = 0; i < kMaxPads; ++i) closePad(g_pads[i], i);
+ for (int i = 0; i < kMaxPads; ++i) closePad(i);
}
bool poll(ControllerState& out) { return pollPad(0, out); }
-bool pollPad(int index, ControllerState& out) {
- out = {};
- if (index < 0 || index >= kMaxPads || g_pads[index].handle < 0) return false;
- Pad& slot = g_pads[index];
- applyRumble(slot);
- applyLightBar(slot);
- ScePadData pad{};
- int rc = scePadReadState(slot.handle, &pad);
- slot.connected = rc == 0 && pad.connected;
- if (!slot.connected) return false;
-
- out.connected = true;
- uint32_t b = pad.buttons;
-
- // D-Pad
- out.dpadUp = (b & 0x0010) != 0;
- out.dpadRight = (b & 0x0020) != 0;
- out.dpadDown = (b & 0x0040) != 0;
- out.dpadLeft = (b & 0x0080) != 0;
-
- // DualSense -> Xbox: Cross->A, Circle->B, Square->X, Triangle->Y
- out.btnA = (b & 0x4000) != 0; // Cross
- out.btnB = (b & 0x2000) != 0; // Circle
- out.btnX = (b & 0x8000) != 0; // Square
- out.btnY = (b & 0x1000) != 0; // Triangle
- if (g_circleConfirms) std::swap(out.btnA, out.btnB);
-
- // Shoulders & Sticks
- out.btnL1 = (b & 0x0400) != 0;
- out.btnR1 = (b & 0x0800) != 0;
- out.btnL3 = (b & 0x0002) != 0;
- out.btnR3 = (b & 0x0004) != 0;
-
- out.btnOptions = (b & 0x0008) != 0;
- out.btnTouchpad = (b & 0x100000) != 0;
-
- // Analog
- out.rawLeftX = out.leftStickX = normStick(pad.leftStick.x);
- out.rawLeftY = out.leftStickY = normStick(pad.leftStick.y);
- out.rawRightX = out.rightStickX = normStick(pad.rightStick.x);
- out.rawRightY = out.rightStickY = normStick(pad.rightStick.y);
- radialDeadzone(out.leftStickX, out.leftStickY, g_deadzone[0].load(std::memory_order_relaxed));
- radialDeadzone(out.rightStickX, out.rightStickY, g_deadzone[1].load(std::memory_order_relaxed));
-
- out.triggerL2 = normTrigger(pad.l2);
- out.triggerR2 = normTrigger(pad.r2);
-
- // Gyro aiming: in a game (menu closed), always or while L2 aims.
- int gyroMode = g_gyroMode.load(std::memory_order_relaxed);
- bool gyroOn = g_gyroActive && (gyroMode == kGyroAlways || (gyroMode == kGyroAiming && out.triggerL2 > 0.3f));
- if (gyroOn) {
- float gx, gy;
- gyroToStick(pad.angularVelocity, pad.acceleration, g_gyroLevel.load(std::memory_order_relaxed), slot.gyro, gx, gy);
- float x = out.rightStickX + gx, y = out.rightStickY + gy, m = std::hypot(x, y);
- if (m > 1.0f) x /= m, y /= m;
- out.rightStickX = x;
- out.rightStickY = y;
- // The first few turns each way, to check the axes.
- bool sideways = std::abs(gx) > 0.5f && std::abs(gx) > std::abs(gy);
- int& logged = sideways ? g_gyroLoggedX : g_gyroLogged;
- if (logged < 4 && std::max(std::abs(gx), std::abs(gy)) > 0.5f)
- XC_LOGI("gyro: pitch %.2f yaw %.2f roll %.2f rad/s, gravity %.2f,%.2f,%.2f -> stick %.2f,%.2f",
- pad.angularVelocity[0], pad.angularVelocity[1], pad.angularVelocity[2], pad.acceleration[0],
- pad.acceleration[1], pad.acceleration[2], gx, gy), ++logged;
- } else {
- slot.gyro = {};
- }
-
- // The DualSense touchpad reports 0..1919 x 0..1079.
- if (pad.touchData.touchNum > 0) {
- out.touching = true;
- out.touchX = std::clamp(pad.touchData.touch[0].x / 1919.0f, 0.0f, 1.0f);
- out.touchY = std::clamp(pad.touchData.touch[0].y / 1079.0f, 0.0f, 1.0f);
- }
- if (inUse(out)) slot.activeAt = platform::nowMs();
-
- return true;
-}
-
-uint64_t padActiveAt(int index) { return index >= 0 && index < kMaxPads ? g_pads[index].activeAt.load() : 0; }
-void setGyro(int mode, int level) {
- g_gyroMode = std::clamp(mode, 0, 2);
- g_gyroLevel = std::clamp(level, 1, kGyroLevels);
-}
-
-void setGyroActive(bool on) { g_gyroActive = on; }
-
void setEmbeddedMicActive(bool active, int pad) {
if (pad < 0 || pad >= kMaxPads) return;
- int32_t handle = g_pads[pad].handle;
+ int32_t handle = g_slots[pad].handle;
if (handle >= 0) {
int rc = scePadSetVibrationTriggerEffectWeakWhileEmbeddedMicInUse(handle, active);
if (rc < 0) {
diff --git a/src/input/tuning.h b/src/input/tuning.h
index 674bd04..d089c96 100644
--- a/src/input/tuning.h
+++ b/src/input/tuning.h
@@ -44,6 +44,17 @@ inline uint8_t triggerAmplitude(uint8_t level, int strength = kTriggerMedium) {
return static_cast<uint8_t>(std::clamp(static_cast<int>(std::lround(a)), 1, 8));
}
+// The same request for a pad with trigger motors (an Xbox pad on the
+// desktop): the game's level as it is at medium strength, since it was
+// made for these motors; light halves it, strong is 1.5 times, max full.
+inline uint8_t triggerMotorLevel(uint8_t level, int strength = kTriggerMedium) {
+ if (!level || strength <= 0) return 0;
+ if (strength >= 4) return 255;
+ static constexpr float kScale[] = {0, 0.5f, 1.0f, 1.5f};
+ int v = static_cast<int>(std::lround(level * kScale[strength]));
+ return static_cast<uint8_t>(std::clamp(v, 1, 255));
+}
+
// Resistance (the triggers' weight): off, light, medium, strong. The
// DualSense pushes back from a point of the travel on, earlier and harder
// the stronger it is; the Xbox's triggers have none, so it is the user's