upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/gameinput.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/shims/gameinput.cpp')
-rw-r--r--runtime/shims/gameinput.cpp673
1 files changed, 627 insertions, 46 deletions
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index 21924801c..89b66364d 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -12,6 +12,9 @@
12// effect (SDL_SendGamepadEffect), as set by LEONIDA_DS_TRIGGERS. That is an approximation of the Xbox impulse 12// effect (SDL_SendGamepadEffect), as set by LEONIDA_DS_TRIGGERS. That is an approximation of the Xbox impulse
13// trigger signal, not the PS5 version's authored effects. 13// trigger signal, not the PS5 version's authored effects.
14// - DualSense/DualShock 4 lightbar colour (LEONIDA_DS_LIGHTBAR) and the player LEDs by connection order 14// - DualSense/DualShock 4 lightbar colour (LEONIDA_DS_LIGHTBAR) and the player LEDs by connection order
15// - force-feedback motors, reported from the SDL haptic device SDL opens for the pad's joystick, and played through
16// SDL_CreateHapticEffect/RunHapticEffect (IGameInputForceFeedbackEffect); haptic trigger motors, reported from the
17// trigger motors the pad already has, played as an intensity through the same trigger output as SetRumbleState
15// - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse 18// - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse
16// 19//
17// One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when 20// One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when
@@ -32,6 +35,7 @@
32 35
33#include <algorithm> 36#include <algorithm>
34#include <atomic> 37#include <atomic>
38#include <chrono>
35#include <cmath> 39#include <cmath>
36#include <cstdio> 40#include <cstdio>
37#include <cstdlib> 41#include <cstdlib>
@@ -60,6 +64,9 @@ constexpr Uint32 kRumbleDurationMs = 0xFFFF; // SDL's maximum; refreshed well b
60constexpr uint64_t kRumbleRefreshUs = 20'000'000; 64constexpr uint64_t kRumbleRefreshUs = 20'000'000;
61constexpr uint64_t kBatteryRefreshUs = 1'000'000; 65constexpr uint64_t kBatteryRefreshUs = 1'000'000;
62constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t) 66constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t)
67constexpr uint32_t kForceFeedbackMotors = 1; // one per SDL haptic device: the wheel or stick it belongs to
68constexpr uint32_t kHapticMotors = 2; // the left and right trigger, on a pad that backs them
69constexpr uint32_t kHapticHoldMs = 60'000; // length of an effect GameInput gives no duration; re-run before it ends
63constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old 70constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old
64constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate 71constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate
65// Motion. SDL gives accel in m/s^2 (gravity included) and gyro in rad/s; the state the ABI defines carries signed 72// Motion. SDL gives accel in m/s^2 (gravity included) and gyro in rad/s; the state the ABI defines carries signed
@@ -87,6 +94,37 @@ ULONG release_floor(std::atomic<ULONG>& refs) {
87 94
88bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } 95bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; }
89 96
97// ---- SDL haptics ------------------------------------------------------------------------------------------------
98//
99// Force feedback and the trigger haptic motors go through SDL's haptic API, opened from the pad's joystick: SDL's
100// gamepad API has no force feedback at all, and a wheel or stick it models as a joystick exposes one only as a haptic
101// device. Every call goes through one table so gameinput_test can stand in for it, because SDL's virtual joysticks
102// report no haptics and a wheel is the only other way to reach this path.
103
104void* sdl_open_haptic(void* js) { return SDL_OpenHapticFromJoystick(static_cast<SDL_Joystick*>(js)); }
105void sdl_close_haptic(void* h) { SDL_CloseHaptic(static_cast<SDL_Haptic*>(h)); }
106uint32_t sdl_haptic_features(void* h) { return SDL_GetHapticFeatures(static_cast<SDL_Haptic*>(h)); }
107int sdl_haptic_max_effects(void* h) { return SDL_GetMaxHapticEffects(static_cast<SDL_Haptic*>(h)); }
108int sdl_haptic_create(void* h, const void* e) {
109 return SDL_CreateHapticEffect(static_cast<SDL_Haptic*>(h), static_cast<const SDL_HapticEffect*>(e));
110}
111bool sdl_haptic_update(void* h, int id, const void* e) {
112 return SDL_UpdateHapticEffect(static_cast<SDL_Haptic*>(h), id, static_cast<const SDL_HapticEffect*>(e));
113}
114bool sdl_haptic_run(void* h, int id, uint32_t iterations) {
115 return SDL_RunHapticEffect(static_cast<SDL_Haptic*>(h), id, iterations);
116}
117bool sdl_haptic_stop(void* h, int id) { return SDL_StopHapticEffect(static_cast<SDL_Haptic*>(h), id); }
118void sdl_haptic_destroy(void* h, int id) { SDL_DestroyHapticEffect(static_cast<SDL_Haptic*>(h), id); }
119bool sdl_haptic_gain(void* h, int gain) { return SDL_SetHapticGain(static_cast<SDL_Haptic*>(h), gain); }
120
121const rt::gameinput::HapticApi kSdlHaptic{sdl_open_haptic, sdl_close_haptic, sdl_haptic_features,
122 sdl_haptic_max_effects, sdl_haptic_create, sdl_haptic_update,
123 sdl_haptic_run, sdl_haptic_stop, sdl_haptic_destroy,
124 sdl_haptic_gain};
125std::atomic<const rt::gameinput::HapticApi*> g_haptic_api{&kSdlHaptic};
126const rt::gameinput::HapticApi& haptics() { return *g_haptic_api.load(); }
127
90// ---- configuration ---------------------------------------------------------------------------------------------- 128// ---- configuration ----------------------------------------------------------------------------------------------
91 129
92std::string env(const char* name) { 130std::string env(const char* name) {
@@ -137,6 +175,7 @@ rt::gameinput::Config read_config() {
137// ---- objects ---------------------------------------------------------------------------------------------------- 175// ---- objects ----------------------------------------------------------------------------------------------------
138 176
139class Device; 177class Device;
178class ForceFeedbackEffect;
140 179
141struct Snapshot { 180struct Snapshot {
142 GameInputGamepadState gamepad{}; 181 GameInputGamepadState gamepad{};
@@ -240,6 +279,149 @@ struct Rumble {
240 float low = 0, high = 0, left = 0, right = 0; 279 float low = 0, high = 0, left = 0, right = 0;
241}; 280};
242 281
282// GameInput -1..1 magnitudes and 0..1 saturations against SDL's levels and saturations.
283Sint16 hlevel(float v) { return static_cast<Sint16>(std::lround(std::clamp(v, -1.0f, 1.0f) * 32767.0f)); }
284Uint16 hsat(float v) { return static_cast<Uint16>(std::lround(std::clamp(v, 0.0f, 1.0f) * 65535.0f)); }
285uint16_t ms_from_us(uint64_t us) { return static_cast<uint16_t>(std::min<uint64_t>((us + 999) / 1000, 65535)); }
286
287// The SDL_HAPTIC_* bit an effect kind needs, for the motor flags and the create-time check.
288uint32_t kind_feature(GameInputForceFeedbackEffectKind kind) {
289 switch (kind) {
290 case GameInputForceFeedbackConstant: return SDL_HAPTIC_CONSTANT;
291 case GameInputForceFeedbackRamp: return SDL_HAPTIC_RAMP;
292 case GameInputForceFeedbackSineWave: return SDL_HAPTIC_SINE;
293 case GameInputForceFeedbackSquareWave: return SDL_HAPTIC_SQUARE;
294 case GameInputForceFeedbackTriangleWave: return SDL_HAPTIC_TRIANGLE;
295 case GameInputForceFeedbackSawtoothUpWave: return SDL_HAPTIC_SAWTOOTHUP;
296 case GameInputForceFeedbackSawtoothDownWave: return SDL_HAPTIC_SAWTOOTHDOWN;
297 case GameInputForceFeedbackSpring: return SDL_HAPTIC_SPRING;
298 case GameInputForceFeedbackFriction: return SDL_HAPTIC_FRICTION;
299 case GameInputForceFeedbackDamper: return SDL_HAPTIC_DAMPER;
300 case GameInputForceFeedbackInertia: return SDL_HAPTIC_INERTIA;
301 }
302 return 0;
303}
304
305bool valid_kind(GameInputForceFeedbackEffectKind kind) {
306 return kind >= GameInputForceFeedbackConstant && kind <= GameInputForceFeedbackInertia;
307}
308
309// An all-zero envelope is how a title that only sets a magnitude leaves it: that means no envelope, not silence.
310bool envelope_used(const GameInputForceFeedbackEnvelope& e) {
311 return e.attackDuration || e.sustainDuration || e.releaseDuration || e.attackGain != 0.0f ||
312 e.sustainGain != 0.0f || e.releaseGain != 0.0f || e.playCount || e.repeatDelay;
313}
314
315uint32_t play_count(const GameInputForceFeedbackParams& p) {
316 return p.kind <= GameInputForceFeedbackSawtoothDownWave ? p.data.constant.envelope.playCount : 0;
317}
318
319// One GameInput effect as SDL's template. GameInput's eleven kinds are SDL's eleven force-feedback effects, so the
320// kind picks the SDL type and the fields are magnitudes; conditions have no envelope in GameInput either. Returns
321// false for a kind the shim does not map. `endless` says the effect has no duration of its own (GameInput left the
322// envelope empty), which is what the poll thread re-runs before the SDL length runs out.
323bool build_effect(const GameInputForceFeedbackParams& p, float gain, bool* endless, uint32_t* length_ms,
324 SDL_HapticEffect* out) {
325 std::memset(out, 0, sizeof *out);
326 if (!valid_kind(p.kind)) return false;
327 const bool envelope_kind = p.kind <= GameInputForceFeedbackSawtoothDownWave;
328 const GameInputForceFeedbackEnvelope env = envelope_kind ? p.data.constant.envelope : GameInputForceFeedbackEnvelope{};
329 const bool used = envelope_kind && envelope_used(env);
330 const float level = gain * (used ? env.sustainGain : 1.0f); // GameInput's sustainGain is the effect's level
331 const uint64_t total_us = used ? env.attackDuration + env.sustainDuration + env.releaseDuration : 0;
332 *endless = total_us == 0;
333 *length_ms = total_us == 0 ? kHapticHoldMs
334 : static_cast<uint32_t>(std::clamp<uint64_t>((total_us + 999) / 1000, 1, 86'400'000));
335 // The envelope's attack and release, when the title gave one. SDL only uses the envelope when attack_length or
336 // fade_level is set, so a zero-gain envelope is left alone rather than muting the effect.
337 auto envelope = [&](SDL_HapticConstant& e) {
338 if (!used || (!env.attackDuration && !env.releaseDuration)) return;
339 e.attack_length = ms_from_us(env.attackDuration);
340 e.attack_level = hsat(env.attackGain);
341 e.fade_length = ms_from_us(env.releaseDuration);
342 e.fade_level = hsat(env.releaseGain);
343 };
344 // Force along +X: the axis a wheel's or a stick's motor acts on, which is the one the motor reports (LinearX).
345 auto direction = [](SDL_HapticDirection& d) {
346 d.type = SDL_HAPTIC_CARTESIAN;
347 d.dir[0] = 1;
348 };
349 switch (p.kind) {
350 case GameInputForceFeedbackConstant: {
351 SDL_HapticConstant& e = out->constant;
352 e.type = SDL_HAPTIC_CONSTANT;
353 direction(e.direction);
354 e.length = *length_ms;
355 e.level = hlevel(p.data.constant.magnitude.linearX * level);
356 envelope(e);
357 break;
358 }
359 case GameInputForceFeedbackRamp: {
360 SDL_HapticRamp& e = out->ramp;
361 e.type = SDL_HAPTIC_RAMP;
362 direction(e.direction);
363 e.length = *length_ms;
364 e.start = hlevel(p.data.ramp.startMagnitude.linearX * level);
365 e.end = hlevel(p.data.ramp.endMagnitude.linearX * level);
366 if (used) {
367 e.attack_length = ms_from_us(env.attackDuration);
368 e.attack_level = hsat(env.attackGain);
369 e.fade_length = ms_from_us(env.releaseDuration);
370 e.fade_level = hsat(env.releaseGain);
371 }
372 break;
373 }
374 case GameInputForceFeedbackSineWave:
375 case GameInputForceFeedbackSquareWave:
376 case GameInputForceFeedbackTriangleWave:
377 case GameInputForceFeedbackSawtoothUpWave:
378 case GameInputForceFeedbackSawtoothDownWave: {
379 SDL_HapticPeriodic& e = out->periodic;
380 e.type = p.kind == GameInputForceFeedbackSineWave ? SDL_HAPTIC_SINE
381 : p.kind == GameInputForceFeedbackSquareWave ? SDL_HAPTIC_SQUARE
382 : p.kind == GameInputForceFeedbackTriangleWave ? SDL_HAPTIC_TRIANGLE
383 : p.kind == GameInputForceFeedbackSawtoothUpWave ? SDL_HAPTIC_SAWTOOTHUP
384 : SDL_HAPTIC_SAWTOOTHDOWN;
385 direction(e.direction);
386 e.length = *length_ms;
387 const GameInputForceFeedbackPeriodicParams& pp = p.data.sineWave;
388 // GameInput gives the wave's frequency in Hz and its phase in degrees; SDL wants a period in ms and a
389 // phase in hundredths of a degree.
390 e.period = pp.frequency > 0.0f ? static_cast<Uint16>(std::clamp(std::lround(1000.0f / pp.frequency), 1L, 65535L)) : 100;
391 e.magnitude = hlevel(pp.magnitude.linearX * level);
392 e.offset = hlevel(pp.bias * level);
393 e.phase = static_cast<Uint16>(std::clamp(std::lround(pp.phase * 100.0f), 0L, 35999L));
394 if (used) {
395 e.attack_length = ms_from_us(env.attackDuration);
396 e.attack_level = hsat(env.attackGain);
397 e.fade_length = ms_from_us(env.releaseDuration);
398 e.fade_level = hsat(env.releaseGain);
399 }
400 break;
401 }
402 default: { // spring, friction, damper, inertia
403 SDL_HapticCondition& e = out->condition;
404 e.type = p.kind == GameInputForceFeedbackSpring ? SDL_HAPTIC_SPRING
405 : p.kind == GameInputForceFeedbackFriction ? SDL_HAPTIC_FRICTION
406 : p.kind == GameInputForceFeedbackDamper ? SDL_HAPTIC_DAMPER
407 : SDL_HAPTIC_INERTIA;
408 e.length = *length_ms;
409 const GameInputForceFeedbackConditionParams& cp = p.data.spring;
410 const float center[3] = {cp.magnitude.linearX, cp.magnitude.linearY, cp.magnitude.linearZ};
411 for (int a = 0; a < 3; ++a) {
412 e.right_sat[a] = hsat(cp.maxPositiveMagnitude);
413 e.left_sat[a] = hsat(cp.maxNegativeMagnitude);
414 e.right_coeff[a] = hlevel(cp.positiveCoefficient * level);
415 e.left_coeff[a] = hlevel(-cp.negativeCoefficient * level);
416 e.deadband[a] = hsat(cp.deadZone);
417 e.center[a] = hlevel(center[a]);
418 }
419 break;
420 }
421 }
422 return true;
423}
424
243class Device final : public IGameInputDevice { 425class Device final : public IGameInputDevice {
244public: 426public:
245 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { 427 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
@@ -260,13 +442,10 @@ public:
260 const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info; } 442 const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info; }
261 uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return status.load(); } 443 uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return status.load(); }
262 void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override; 444 void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override;
263 HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t, const void*, void** effect) override { 445 HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t motorIndex, const void* params, void** effect) override;
264 if (effect) *effect = nullptr; 446 bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t motorIndex) override;
265 return E_INVALIDARG; // forceFeedbackMotorCount is 0 447 void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t motorIndex, float masterGain) override;
266 } 448 HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t motorIndex, const void* params) override;
267 bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t) override { return false; }
268 void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t, float) override {}
269 HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t, const void*) override { return E_INVALIDARG; }
270 void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) override; 449 void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) override;
271 void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {} 450 void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {}
272 void STDMETHODCALLTYPE SendInputSynchronizationHint() override {} 451 void STDMETHODCALLTYPE SendInputSynchronizationHint() override {}
@@ -301,12 +480,20 @@ public:
301 GameInputGamepadInfo gamepad_info{}; 480 GameInputGamepadInfo gamepad_info{};
302 GameInputUiNavigationInfo ui_info{}; 481 GameInputUiNavigationInfo ui_info{};
303 GameInputMotionInfo motion_info{}; // filled only when the pad has sensors; info.motionInfo points at it 482 GameInputMotionInfo motion_info{}; // filled only when the pad has sensors; info.motionInfo points at it
483 GameInputForceFeedbackMotorInfo ff_motor_info{}; // filled when SDL opened the pad as a haptic device
484 GameInputHapticFeedbackMotorInfo haptic_motor_info[kHapticMotors]{}; // the trigger motors, when the pad has them
485 GameInputHapticWaveformInfo haptic_waveform_info[kHapticMotors]{}; // one waveform each, an intensity
304 std::atomic<uint32_t> status{GameInputDeviceNoStatus}; 486 std::atomic<uint32_t> status{GameInputDeviceNoStatus};
305 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading 487 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading
306 uint64_t evicted_order = 0; // order of the newest reading dropped from history 488 uint64_t evicted_order = 0; // order of the newest reading dropped from history
307 Reading* latest() const { return history.empty() ? nullptr : history.back(); } 489 Reading* latest() const { return history.empty() ? nullptr : history.back(); }
308 uint64_t seq = 0; 490 uint64_t seq = 0;
309 Rumble wanted; 491 Rumble wanted;
492 float motor_gain = 1.0f; // SetForceFeedbackMotorGain, 0..1
493 std::vector<ForceFeedbackEffect*> effects; // every live effect, so the poll thread can drive them
494 std::vector<int> retired; // SDL effect ids whose object is gone: destroyed on the poll thread
495 float haptic_intensity[kHapticMotors] = {}; // SetHapticMotorState, 0..1
496 uint64_t haptic_until[kHapticMotors] = {}; // when the request ends, 0 for "until changed"
310 GameInputBatteryState battery{0, 0, 0, 0, GameInputBatteryUnknown}; 497 GameInputBatteryState battery{0, 0, 0, 0, GameInputBatteryUnknown};
311 AppLocalDeviceId base_id{}; // id_bytes of the identity alone: twins share it, info.deviceId tells them apart 498 AppLocalDeviceId base_id{}; // id_bytes of the identity alone: twins share it, info.deviceId tells them apart
312 499
@@ -315,6 +502,11 @@ public:
315 SDL_JoystickID id = 0; 502 SDL_JoystickID id = 0;
316 int player = -1; 503 int player = -1;
317 bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false, has_motion = false; 504 bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false, has_motion = false;
505 bool has_trigger_output = false; // the pad backs trigger motors: rumble, DualSense effects or haptic motors
506 void* haptic = nullptr; // SDL_Haptic behind the joystick, when SDL has one for this pad
507 uint32_t ff_features = 0; // the SDL_HAPTIC_* bits it reports: which effect kinds it can play
508 int sent_gain = -1; // device gain 0..100 last sent, so a steady gain costs one call
509 uint32_t haptic_motors = 0; // trigger haptic motors the pad reports (0 or 2)
318 rt::gameinput::OutputState sent{}; 510 rt::gameinput::OutputState sent{};
319 Snapshot last_snap{}; // what the latest reading holds 511 Snapshot last_snap{}; // what the latest reading holds
320 uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors 512 uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors
@@ -361,6 +553,50 @@ struct Event {
361 GameInputCallbackToken only; // enumeration: deliver to this callback only 553 GameInputCallbackToken only; // enumeration: deliver to this callback only
362}; 554};
363 555
556// One effect a title created, on the device it belongs to. The object and its parameters belong to the title; SDL's
557// effect is created, run and destroyed on the poll thread, so a title call only writes its state and bumps `version_`,
558// which the poll thread compares before it touches SDL. A new effect is Running: CreateForceFeedbackEffect already
559// carried the parameters, and the documented use (create once, SetParams per frame) never reaches SetState.
560class ForceFeedbackEffect final : public IGameInputForceFeedbackEffect {
561public:
562 ForceFeedbackEffect(Device* device, uint32_t motor, const GameInputForceFeedbackParams& params);
563 ~ForceFeedbackEffect();
564
565 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override;
566 ULONG STDMETHODCALLTYPE AddRef() override;
567 ULONG STDMETHODCALLTYPE Release() override;
568 void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override;
569 uint32_t STDMETHODCALLTYPE GetMotorIndex() override;
570 float STDMETHODCALLTYPE GetGain() override;
571 void STDMETHODCALLTYPE SetGain(float gain) override;
572 void STDMETHODCALLTYPE GetParams(GameInputForceFeedbackParams* params) override;
573 bool STDMETHODCALLTYPE SetParams(const GameInputForceFeedbackParams* params) override;
574 GameInputFeedbackEffectState STDMETHODCALLTYPE GetState() override;
575 void STDMETHODCALLTYPE SetState(GameInputFeedbackEffectState state) override;
576
577 // Poll thread: make SDL match the effect's parameters, gain and state. `muted` says every output is off
578 // (LEONIDA_RUMBLE=0); the motor's master gain is SDL's device gain, set once by apply_effects.
579 void sync(Device* device, uint64_t now, bool muted);
580 // Poll thread, on unplug: the SDL device went with the pad, so forget its effect id without touching SDL.
581 void orphan();
582
583private:
584 std::atomic<ULONG> refs_{1};
585 Device* device_;
586 uint32_t motor_;
587 // Written by title calls under g().mu and read by the poll thread.
588 GameInputForceFeedbackParams params_;
589 float gain_ = 1.0f;
590 GameInputFeedbackEffectState state_ = GameInputFeedbackRunning;
591 uint64_t version_ = 1;
592 // Poll thread only.
593 uint64_t applied_ = 0; // the version SDL has
594 int sdl_effect_ = -1;
595 bool sdl_running_ = false;
596 bool endless_ = true; // GameInput gave no duration: re-run before the SDL length runs out
597 uint64_t run_at_ = 0, run_for_ = 0;
598};
599
364class Dispatcher; 600class Dispatcher;
365 601
366struct State { 602struct State {
@@ -425,6 +661,28 @@ void call(const Callback& c, const Event& e) {
425 } 661 }
426} 662}
427 663
664// Runs one queued event's callbacks on the calling thread, without holding the state lock.
665void deliver_event(const Event& e) {
666 State& s = g();
667 std::vector<Callback> targets;
668 {
669 std::lock_guard lock(s.mu);
670 for (const Callback& c : s.callbacks)
671 if (matches(c, e)) targets.push_back(c);
672 }
673 for (const Callback& c : targets) {
674 bool still = false;
675 {
676 std::lock_guard lock(s.mu);
677 for (const Callback& now : s.callbacks)
678 if (now.token == c.token) still = now.active;
679 }
680 if (still) call(c, e);
681 }
682 if (e.device) e.device->Release();
683 if (e.reading) e.reading->Release();
684}
685
428// Runs queued callbacks on the calling thread, without holding the state lock. Returns whether more events arrived 686// Runs queued callbacks on the calling thread, without holding the state lock. Returns whether more events arrived
429// meanwhile. 687// meanwhile.
430bool deliver() { 688bool deliver() {
@@ -435,30 +693,41 @@ bool deliver() {
435 std::lock_guard lock(s.mu); 693 std::lock_guard lock(s.mu);
436 events.swap(s.queue); 694 events.swap(s.queue);
437 } 695 }
438 const DWORD self = GetCurrentThreadId(); 696 s.delivering_thread = GetCurrentThreadId();
439 s.delivering_thread = self; 697 for (const Event& e : events) deliver_event(e);
440 for (const Event& e : events) { 698 s.delivering_thread = 0;
441 std::vector<Callback> targets; 699 std::lock_guard lock(s.mu);
700 return !s.queue.empty();
701}
702
703// IGameInputDispatcher::Dispatch: runs queued events oldest first, at least one even with a quota of 0, and takes no
704// further event once quota_us microseconds have passed (an event already started runs to the end, so the quota is a
705// target, as on Windows). While events remain the wait handle is signalled again, so a title that waits on it before
706// each call comes back for the rest. Returns whether events remain.
707bool deliver_within(uint64_t quota_us) {
708 State& s = g();
709 std::lock_guard dl(s.deliver_mu);
710 const auto start = std::chrono::steady_clock::now();
711 s.delivering_thread = GetCurrentThreadId();
712 for (bool first = true;; first = false) {
713 if (!first) {
714 const auto spent = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start);
715 if (static_cast<uint64_t>(spent.count()) >= quota_us) break;
716 }
717 Event e;
442 { 718 {
443 std::lock_guard lock(s.mu); 719 std::lock_guard lock(s.mu);
444 for (const Callback& c : s.callbacks) 720 if (s.queue.empty()) break;
445 if (matches(c, e)) targets.push_back(c); 721 e = s.queue.front();
722 s.queue.erase(s.queue.begin());
446 } 723 }
447 for (const Callback& c : targets) { 724 deliver_event(e);
448 bool still = false;
449 {
450 std::lock_guard lock(s.mu);
451 for (const Callback& now : s.callbacks)
452 if (now.token == c.token) still = now.active;
453 }
454 if (still) call(c, e);
455 }
456 if (e.device) e.device->Release();
457 if (e.reading) e.reading->Release();
458 } 725 }
459 s.delivering_thread = 0; 726 s.delivering_thread = 0;
460 std::lock_guard lock(s.mu); 727 std::lock_guard lock(s.mu);
461 return !s.queue.empty(); 728 const bool remaining = !s.queue.empty();
729 if (remaining && s.wait_event) SetEvent(s.wait_event);
730 return remaining;
462} 731}
463 732
464// ---- SDL backend (poll thread only) ----------------------------------------------------------------------------- 733// ---- SDL backend (poll thread only) -----------------------------------------------------------------------------
@@ -597,8 +866,7 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) {
597 // as the per-device one, so only pads with sensors answer a motion query. 866 // as the per-device one, so only pads with sensors answer a motion query.
598 i.supportedInput = kBaseKinds; 867 i.supportedInput = kBaseKinds;
599 if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency; 868 if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency;
600 if (d->has_trigger_rumble || (d->is_dualsense && g().config.ds_triggers != rt::gameinput::DsTriggerMode::Off)) 869 if (d->has_trigger_output) i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger;
601 i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger;
602 if (d->has_motion) { 870 if (d->has_motion) {
603 i.supportedInput |= GameInputKindMotion; 871 i.supportedInput |= GameInputKindMotion;
604 // The maxima GetMotionState's fractions divide by. The magnetometer is not available: SDL's gamepad API has 872 // The maxima GetMotionState's fractions divide by. The magnetometer is not available: SDL's gamepad API has
@@ -606,6 +874,17 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) {
606 d->motion_info = {kMaxAcceleration, kMaxAngularVelocity, 0.0f}; 874 d->motion_info = {kMaxAcceleration, kMaxAngularVelocity, 0.0f};
607 i.motionInfo = &d->motion_info; 875 i.motionInfo = &d->motion_info;
608 } 876 }
877 // The motors this pad can back. Force feedback is whatever SDL opened a haptic device for with effect kinds of its
878 // own; the haptic motors are the trigger motors the pad already has for rumble, which the shim can drive as an
879 // intensity. A pad with neither keeps the old answers: no motors at all.
880 if (d->haptic) {
881 i.forceFeedbackMotorCount = kForceFeedbackMotors;
882 i.forceFeedbackMotorInfo = &d->ff_motor_info;
883 }
884 if (d->haptic_motors) {
885 i.hapticFeedbackMotorCount = d->haptic_motors;
886 i.hapticFeedbackMotorInfo = d->haptic_motor_info;
887 }
609 i.controllerAxisCount = kAxisCount; 888 i.controllerAxisCount = kAxisCount;
610 i.controllerButtonCount = kButtonCount; 889 i.controllerButtonCount = kButtonCount;
611 for (uint32_t a = 0; a < kAxisCount; ++a) { 890 for (uint32_t a = 0; a < kAxisCount; ++a) {
@@ -703,9 +982,60 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
703 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_GYRO, kMotionSensorRate); 982 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_GYRO, kMotionSensorRate);
704 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_ACCEL, kMotionSensorRate); 983 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_ACCEL, kMotionSensorRate);
705 } 984 }
985 d->has_trigger_output = d->has_trigger_rumble ||
986 (d->is_dualsense && s.config.ds_triggers != rt::gameinput::DsTriggerMode::Off);
987 // Force feedback: SDL opens a wheel or a stick as a joystick with a haptic device behind it and never through the
988 // gamepad API, so it is opened from the joystick and closed with the pad. Only what the device really reports is
989 // passed on: no haptic device, no motor, and an effect kind SDL does not list is not offered to a title.
990 d->haptic = haptics().open_joystick(SDL_GetGamepadJoystick(p));
991 d->ff_features = 0;
992 d->ff_motor_info = {};
993 d->sent_gain = -1;
994 if (d->haptic) {
995 const uint32_t features = haptics().features(d->haptic);
996 if (features) {
997 GameInputForceFeedbackMotorInfo& m = d->ff_motor_info;
998 d->ff_features = features;
999 m.supportedAxes = GameInputFeedbackAxisLinearX; // the axis a wheel's or a stick's motor acts on
1000 m.location = GameInputLocationChassis;
1001 m.locationId = 0;
1002 m.maxSimultaneousEffects = static_cast<uint32_t>(std::max(1, haptics().max_effects(d->haptic)));
1003 m.isConstantEffectSupported = (features & SDL_HAPTIC_CONSTANT) != 0;
1004 m.isRampEffectSupported = (features & SDL_HAPTIC_RAMP) != 0;
1005 m.isSineWaveEffectSupported = (features & SDL_HAPTIC_SINE) != 0;
1006 m.isSquareWaveEffectSupported = (features & SDL_HAPTIC_SQUARE) != 0;
1007 m.isTriangleWaveEffectSupported = (features & SDL_HAPTIC_TRIANGLE) != 0;
1008 m.isSawtoothUpWaveEffectSupported = (features & SDL_HAPTIC_SAWTOOTHUP) != 0;
1009 m.isSawtoothDownWaveEffectSupported = (features & SDL_HAPTIC_SAWTOOTHDOWN) != 0;
1010 m.isSpringEffectSupported = (features & SDL_HAPTIC_SPRING) != 0;
1011 m.isFrictionEffectSupported = (features & SDL_HAPTIC_FRICTION) != 0;
1012 m.isDamperEffectSupported = (features & SDL_HAPTIC_DAMPER) != 0;
1013 m.isInertiaEffectSupported = (features & SDL_HAPTIC_INERTIA) != 0;
1014 } else {
1015 haptics().close(d->haptic);
1016 d->haptic = nullptr;
1017 }
1018 }
1019 // Haptic motors: the trigger motors, one waveform each. The waveform identifier is this shim's choice, an
1020 // intensity (HID physical-interface usage 0x0F/0x58), because an intensity is the one thing SDL lets it send.
1021 d->haptic_motors = 0;
1022 if (d->has_trigger_output) {
1023 for (uint32_t m = 0; m < kHapticMotors; ++m) {
1024 d->haptic_waveform_info[m] = {{0x0F, 0x58}, true, true, true, false, 0};
1025 d->haptic_motor_info[m] = {};
1026 d->haptic_motor_info[m].mappedRumbleMotors = m ? GameInputRumbleRightTrigger : GameInputRumbleLeftTrigger;
1027 d->haptic_motor_info[m].location = GameInputLocationChassis;
1028 d->haptic_motor_info[m].locationId = m;
1029 d->haptic_motor_info[m].waveformCount = 1;
1030 d->haptic_motor_info[m].waveformInfo = &d->haptic_waveform_info[m];
1031 }
1032 d->haptic_motors = kHapticMotors;
1033 }
706 d->sent = {}; 1034 d->sent = {};
707 d->sent.is_dualsense = d->is_dualsense; 1035 d->sent.is_dualsense = d->is_dualsense;
708 d->sent.trigger_rumble = d->has_trigger_rumble; 1036 d->sent.trigger_rumble = d->has_trigger_rumble;
1037 d->sent.force_feedback = d->haptic != nullptr;
1038 d->sent.haptic_motors = d->haptic_motors;
709 d->ds_sent_once = false; 1039 d->ds_sent_once = false;
710 d->motors_sent_at = d->triggers_sent_at = d->battery_at = 0; 1040 d->motors_sent_at = d->triggers_sent_at = d->battery_at = 0;
711 d->wanted = {}; 1041 d->wanted = {};
@@ -732,9 +1062,10 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
732 d->last_snap = snap; 1062 d->last_snap = snap;
733 push_reading(d, snap, ts); 1063 push_reading(d, snap, ts);
734 queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0}); 1064 queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0});
735 std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s%s)\n", d->name.c_str(), 1065 std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s%s%s)\n", d->name.c_str(),
736 d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", 1066 d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "",
737 d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : ""); 1067 d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : "",
1068 d->haptic ? ", force feedback" : "");
738} 1069}
739 1070
740void close_pad(Device* d, uint64_t ts) { 1071void close_pad(Device* d, uint64_t ts) {
@@ -744,6 +1075,19 @@ void close_pad(Device* d, uint64_t ts) {
744 SDL_CloseGamepad(d->pad); 1075 SDL_CloseGamepad(d->pad);
745 d->pad = nullptr; 1076 d->pad = nullptr;
746 d->player = -1; 1077 d->player = -1;
1078 // The haptic device belongs to the joystick, which goes with the gamepad. Effects a title still holds stay alive
1079 // and pick up again when the pad comes back.
1080 if (d->haptic) {
1081 haptics().close(d->haptic);
1082 d->haptic = nullptr;
1083 }
1084 d->retired.clear();
1085 d->ff_features = 0;
1086 d->ff_motor_info = {};
1087 d->sent_gain = -1;
1088 d->haptic_motors = 0;
1089 for (ForceFeedbackEffect* e : d->effects) e->orphan();
1090 for (uint32_t m = 0; m < kHapticMotors; ++m) d->haptic_intensity[m] = 0, d->haptic_until[m] = 0;
747 if (!d->history.empty()) d->evicted_order = d->history.back()->order(); // the history ends with the session 1091 if (!d->history.empty()) d->evicted_order = d->history.back()->order(); // the history ends with the session
748 for (Reading* r : d->history) r->Release(); 1092 for (Reading* r : d->history) r->Release();
749 d->history.clear(); 1093 d->history.clear();
@@ -770,14 +1114,55 @@ void ds_effect(float strength, uint8_t out[11]) {
770 } 1114 }
771} 1115}
772 1116
1117// The force-feedback effects and the device gain, on the poll thread: SDL's effects are created, updated, run and
1118// destroyed here and nowhere else, so a title call costs a lock and a copy.
1119void apply_effects(Device* d, uint64_t now) {
1120 State& s = g();
1121 std::vector<ForceFeedbackEffect*> live;
1122 std::vector<int> retire;
1123 float motor_gain;
1124 bool muted;
1125 {
1126 std::lock_guard lock(s.mu);
1127 live.reserve(d->effects.size());
1128 for (ForceFeedbackEffect* e : d->effects) { // referenced: the title may release one while this runs
1129 e->AddRef();
1130 live.push_back(e);
1131 }
1132 retire.swap(d->retired);
1133 motor_gain = d->motor_gain;
1134 muted = !s.config.rumble;
1135 }
1136 if (d->haptic) {
1137 for (int id : retire) haptics().destroy_effect(d->haptic, id);
1138 const int gain = static_cast<int>(std::lround(std::clamp(motor_gain, 0.0f, 1.0f) * 100.0f));
1139 if (gain != d->sent_gain) {
1140 haptics().set_gain(d->haptic, gain);
1141 d->sent_gain = gain;
1142 }
1143 }
1144 for (ForceFeedbackEffect* e : live) {
1145 e->sync(d, now, muted);
1146 e->Release();
1147 }
1148}
1149
773void apply_output(Device* d, uint64_t now) { 1150void apply_output(Device* d, uint64_t now) {
774 State& s = g(); 1151 State& s = g();
775 Rumble want; 1152 Rumble want;
1153 float haptic[kHapticMotors] = {};
776 { 1154 {
777 std::lock_guard lock(s.mu); 1155 std::lock_guard lock(s.mu);
778 want = d->wanted; 1156 want = d->wanted;
779 } 1157 for (uint32_t m = 0; m < d->haptic_motors; ++m)
780 if (!s.config.rumble) want = {}; 1158 if (!d->haptic_until[m] || now < d->haptic_until[m]) haptic[m] = d->haptic_intensity[m];
1159 }
1160 const bool muted = !s.config.rumble;
1161 if (muted) want = {};
1162 // The haptic motors sit on the trigger motors, so their intensity and SetRumbleState's trigger level go out on one
1163 // output: the stronger of the two wins, and a request that has run out is dropped here.
1164 want.left = std::max(want.left, muted ? 0.0f : haptic[0]);
1165 want.right = std::max(want.right, muted ? 0.0f : haptic[1]);
781 rt::gameinput::OutputState& o = d->sent; 1166 rt::gameinput::OutputState& o = d->sent;
782 1167
783 if (d->has_rumble) { 1168 if (d->has_rumble) {
@@ -791,19 +1176,21 @@ void apply_output(Device* d, uint64_t now) {
791 } 1176 }
792 } 1177 }
793 if (d->is_dualsense) { 1178 if (d->is_dualsense) {
794 if (s.config.ds_triggers == rt::gameinput::DsTriggerMode::Off) return; // leave the triggers alone 1179 // LEONIDA_DS_TRIGGERS=off leaves the triggers alone.
795 uint8_t right[11], left[11]; 1180 if (s.config.ds_triggers != rt::gameinput::DsTriggerMode::Off) {
796 ds_effect(want.right, right); 1181 uint8_t right[11], left[11];
797 ds_effect(want.left, left); 1182 ds_effect(want.right, right);
798 if (!d->ds_sent_once || std::memcmp(right, o.ds_right, 11) || std::memcmp(left, o.ds_left, 11)) { 1183 ds_effect(want.left, left);
799 uint8_t block[kDsEffectSize] = {}; 1184 if (!d->ds_sent_once || std::memcmp(right, o.ds_right, 11) || std::memcmp(left, o.ds_left, 11)) {
800 block[0] = 0x04 | 0x08; // valid flags: right and left trigger effect 1185 uint8_t block[kDsEffectSize] = {};
801 std::memcpy(block + 10, right, 11); 1186 block[0] = 0x04 | 0x08; // valid flags: right and left trigger effect
802 std::memcpy(block + 21, left, 11); 1187 std::memcpy(block + 10, right, 11);
803 if (SDL_SendGamepadEffect(d->pad, block, sizeof block)) { 1188 std::memcpy(block + 21, left, 11);
804 std::memcpy(o.ds_right, right, 11); 1189 if (SDL_SendGamepadEffect(d->pad, block, sizeof block)) {
805 std::memcpy(o.ds_left, left, 11); 1190 std::memcpy(o.ds_right, right, 11);
806 d->ds_sent_once = true; 1191 std::memcpy(o.ds_left, left, 11);
1192 d->ds_sent_once = true;
1193 }
807 } 1194 }
808 } 1195 }
809 } else if (d->has_trigger_rumble) { 1196 } else if (d->has_trigger_rumble) {
@@ -816,6 +1203,7 @@ void apply_output(Device* d, uint64_t now) {
816 d->triggers_sent_at = now; 1203 d->triggers_sent_at = now;
817 } 1204 }
818 } 1205 }
1206 apply_effects(d, now);
819} 1207}
820 1208
821void refresh_battery(Device* d, uint64_t now) { 1209void refresh_battery(Device* d, uint64_t now) {
@@ -1226,6 +1614,197 @@ void Device::SetRumbleState(const GameInputRumbleParams* params) {
1226 wanted = params ? Rumble{params->lowFrequency, params->highFrequency, params->leftTrigger, params->rightTrigger} : Rumble{}; 1614 wanted = params ? Rumble{params->lowFrequency, params->highFrequency, params->leftTrigger, params->rightTrigger} : Rumble{};
1227} 1615}
1228 1616
1617HRESULT Device::CreateForceFeedbackEffect(uint32_t motorIndex, const void* params, void** effect) {
1618 if (!effect) return E_POINTER;
1619 *effect = nullptr;
1620 if (!params || motorIndex >= info.forceFeedbackMotorCount) return E_INVALIDARG;
1621 const auto* p = static_cast<const GameInputForceFeedbackParams*>(params);
1622 // Only what the motor reported. SDL is not asked here: this is a title call, so the cached feature mask decides,
1623 // and the poll thread is what finds out if SDL refuses the effect anyway.
1624 if (!valid_kind(p->kind) || !(ff_features & kind_feature(p->kind))) return E_INVALIDARG;
1625 *effect = new ForceFeedbackEffect(this, motorIndex, *p);
1626 return S_OK;
1627}
1628
1629bool Device::IsForceFeedbackMotorPoweredOn(uint32_t motorIndex) {
1630 return motorIndex < info.forceFeedbackMotorCount && haptic != nullptr && status.load() != GameInputDeviceNoStatus;
1631}
1632
1633void Device::SetForceFeedbackMotorGain(uint32_t motorIndex, float masterGain) {
1634 std::lock_guard lock(g().mu);
1635 if (motorIndex < info.forceFeedbackMotorCount) motor_gain = std::clamp(masterGain, 0.0f, 1.0f);
1636}
1637
1638HRESULT Device::SetHapticMotorState(uint32_t motorIndex, const void* params) {
1639 std::lock_guard lock(g().mu);
1640 if (motorIndex >= haptic_motors) return E_INVALIDARG;
1641 if (!params) { // stop the motor
1642 haptic_intensity[motorIndex] = 0.0f;
1643 haptic_until[motorIndex] = 0;
1644 return S_OK;
1645 }
1646 const auto* p = static_cast<const GameInputHapticFeedbackParams*>(params);
1647 if (p->waveformIndex >= haptic_motor_info[motorIndex].waveformCount) return E_INVALIDARG;
1648 haptic_intensity[motorIndex] = std::clamp(p->intensity, 0.0f, 1.0f);
1649 // duration and repeatDelay are microseconds; playCount 0 plays until the state is set again. The poll thread sends
1650 // the level and drops it when the deadline passes.
1651 uint64_t total = p->playCount == 0 ? 0 : p->duration;
1652 if (p->playCount > 1) total = p->duration * p->playCount + p->repeatDelay * (p->playCount - 1);
1653 haptic_until[motorIndex] = total ? now_us() + total : 0;
1654 return S_OK;
1655}
1656
1657// ---- IGameInputForceFeedbackEffect ----------------------------------------------------------------
1658
1659ForceFeedbackEffect::ForceFeedbackEffect(Device* device, uint32_t motor, const GameInputForceFeedbackParams& params)
1660 : device_(device), motor_(motor), params_(params) {
1661 device_->AddRef();
1662 std::lock_guard lock(g().mu);
1663 device_->effects.push_back(this);
1664}
1665
1666ForceFeedbackEffect::~ForceFeedbackEffect() {
1667 std::lock_guard lock(g().mu);
1668 std::vector<ForceFeedbackEffect*>& list = device_->effects;
1669 list.erase(std::remove(list.begin(), list.end(), this), list.end());
1670 if (sdl_effect_ >= 0) { // SDL's effect is destroyed by the poll thread, which is the only thread that may
1671 device_->retired.push_back(sdl_effect_);
1672 sdl_effect_ = -1;
1673 }
1674 device_->Release();
1675}
1676
1677HRESULT STDMETHODCALLTYPE ForceFeedbackEffect::QueryInterface(REFIID riid, void** out) {
1678 if (!out) return E_POINTER;
1679 if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputForceFeedbackEffect)) {
1680 AddRef();
1681 *out = static_cast<IGameInputForceFeedbackEffect*>(this);
1682 return S_OK;
1683 }
1684 *out = nullptr;
1685 return E_NOINTERFACE;
1686}
1687
1688ULONG STDMETHODCALLTYPE ForceFeedbackEffect::AddRef() { return ++refs_; }
1689
1690ULONG STDMETHODCALLTYPE ForceFeedbackEffect::Release() {
1691 const ULONG r = --refs_;
1692 if (r == 0) delete this;
1693 return r;
1694}
1695
1696void STDMETHODCALLTYPE ForceFeedbackEffect::GetDevice(IGameInputDevice** device) {
1697 if (!device) return;
1698 device_->AddRef();
1699 *device = device_;
1700}
1701
1702uint32_t STDMETHODCALLTYPE ForceFeedbackEffect::GetMotorIndex() { return motor_; }
1703
1704float STDMETHODCALLTYPE ForceFeedbackEffect::GetGain() {
1705 std::lock_guard lock(g().mu);
1706 return gain_;
1707}
1708
1709void STDMETHODCALLTYPE ForceFeedbackEffect::SetGain(float gain) {
1710 std::lock_guard lock(g().mu);
1711 gain_ = std::clamp(gain, 0.0f, 1.0f);
1712 ++version_;
1713}
1714
1715void STDMETHODCALLTYPE ForceFeedbackEffect::GetParams(GameInputForceFeedbackParams* params) {
1716 if (!params) return;
1717 std::lock_guard lock(g().mu);
1718 *params = params_;
1719}
1720
1721bool STDMETHODCALLTYPE ForceFeedbackEffect::SetParams(const GameInputForceFeedbackParams* params) {
1722 if (!params || !valid_kind(params->kind)) return false;
1723 std::lock_guard lock(g().mu);
1724 params_ = *params;
1725 ++version_;
1726 return true;
1727}
1728
1729GameInputFeedbackEffectState STDMETHODCALLTYPE ForceFeedbackEffect::GetState() {
1730 std::lock_guard lock(g().mu);
1731 return state_;
1732}
1733
1734void STDMETHODCALLTYPE ForceFeedbackEffect::SetState(GameInputFeedbackEffectState state) {
1735 std::lock_guard lock(g().mu);
1736 state_ = state;
1737 ++version_;
1738}
1739
1740void ForceFeedbackEffect::orphan() {
1741 sdl_effect_ = -1;
1742 sdl_running_ = false;
1743 applied_ = 0;
1744}
1745
1746void ForceFeedbackEffect::sync(Device* d, uint64_t now, bool muted) {
1747 GameInputForceFeedbackParams params;
1748 float gain;
1749 GameInputFeedbackEffectState state;
1750 uint64_t version;
1751 {
1752 std::lock_guard lock(g().mu);
1753 params = params_;
1754 gain = gain_;
1755 state = state_;
1756 version = version_;
1757 }
1758 if (!d->haptic) return;
1759 // A stopped or paused effect is stopped in SDL: GameInput pauses one effect where SDL pauses the device, so a
1760 // pause here is a stop that keeps the parameters. LEONIDA_RUMBLE=0 silences this path like every other.
1761 if (state != GameInputFeedbackRunning || muted) {
1762 if (sdl_running_) {
1763 haptics().stop_effect(d->haptic, sdl_effect_);
1764 sdl_running_ = false;
1765 }
1766 return;
1767 }
1768 // An effect that played the length GameInput gave it is over, as the API says of a finished effect. The run is
1769 // forgotten so that a second SetState(Running) starts it again instead of expiring at once.
1770 if (!endless_ && run_for_ && now >= run_at_ + run_for_) {
1771 if (sdl_running_) {
1772 haptics().stop_effect(d->haptic, sdl_effect_);
1773 sdl_running_ = false;
1774 }
1775 endless_ = true;
1776 run_for_ = 0;
1777 std::lock_guard lock(g().mu);
1778 state_ = GameInputFeedbackStopped;
1779 return;
1780 }
1781 const bool stale = sdl_running_ && endless_ && now - run_at_ > kRumbleRefreshUs;
1782 if (sdl_running_ && version == applied_ && !stale) return;
1783
1784 SDL_HapticEffect fx;
1785 bool endless = true;
1786 uint32_t length_ms = kHapticHoldMs;
1787 if (!build_effect(params, gain, &endless, &length_ms, &fx)) {
1788 if (sdl_running_) haptics().stop_effect(d->haptic, sdl_effect_);
1789 sdl_running_ = false;
1790 return;
1791 }
1792 if (sdl_effect_ < 0) {
1793 sdl_effect_ = haptics().create_effect(d->haptic, &fx); // SDL refused: nothing to drive this effect
1794 if (sdl_effect_ < 0) return;
1795 } else if (!haptics().update_effect(d->haptic, sdl_effect_, &fx)) {
1796 return;
1797 }
1798 // GameInput's playCount 0 means "until stopped", which is what SDL's 0 iterations means.
1799 const uint32_t iterations = endless ? 0 : play_count(params);
1800 if (!haptics().run_effect(d->haptic, sdl_effect_, iterations)) return;
1801 sdl_running_ = true;
1802 applied_ = version;
1803 endless_ = endless;
1804 run_at_ = now;
1805 run_for_ = endless || iterations == 0 ? 0 : static_cast<uint64_t>(length_ms) * 1000ull * iterations;
1806}
1807
1229// ---- IGameInputDispatcher ---- 1808// ---- IGameInputDispatcher ----
1230 1809
1231class Dispatcher final : public IGameInputDispatcher { 1810class Dispatcher final : public IGameInputDispatcher {
@@ -1256,8 +1835,8 @@ public:
1256 } 1835 }
1257 return r; 1836 return r;
1258 } 1837 }
1259 // Runs the queued callbacks on the caller's thread. The quota is not enforced: the queue is short. 1838 // Runs the queued callbacks on the caller's thread within the quota (see deliver_within).
1260 bool STDMETHODCALLTYPE Dispatch(uint64_t) override { return deliver(); } 1839 bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) override { return deliver_within(quotaInMicroseconds); }
1261 HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override { 1840 HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override {
1262 if (!handle) return E_POINTER; 1841 if (!handle) return E_POINTER;
1263 *handle = nullptr; 1842 *handle = nullptr;
@@ -1607,6 +2186,8 @@ void set_keyboard_source(KeyDownFn key_down, HasFocusFn has_focus) {
1607 2186
1608void set_cursor_source(CursorPosFn cursor_pos) { g_cursor_pos = cursor_pos ? cursor_pos : system_cursor_pos; } 2187void set_cursor_source(CursorPosFn cursor_pos) { g_cursor_pos = cursor_pos ? cursor_pos : system_cursor_pos; }
1609 2188
2189void set_haptic_source(const HapticApi* api) { g_haptic_api = api ? api : &kSdlHaptic; }
2190
1610const KeyBinding* keyboard_bindings(int* count) { 2191const KeyBinding* keyboard_bindings(int* count) {
1611 if (count) *count = static_cast<int>(std::size(kKeyBindings)); 2192 if (count) *count = static_cast<int>(std::size(kKeyBindings));
1612 return kKeyBindings; 2193 return kKeyBindings;