input: correct gyro orientation drift with the accelerometer #899

Manually merged
github merged 2 commits from gh-pr/899/head into gh-pr/899/base 2026-11-26 09:36:33 +00:00
Owner

@⁠ew-sudo on GitHub · 2026-09-28 21:53 UTC · original
ew-sudo:gyro-drift-fix → main · +60 −13 · 1 files · 2 commits · merged 2026-09-30 18:40 UTC

Problem

The pad orientation (orientation_x/y/z/w) is built by integrating the gyro alone. Every real gyro has a small bias, so the integrated orientation slowly drifts. In practice, gyro-controlled sections in Astro's Playroom (PPSA01325) get worse over time: when the controller is held still the camera or object slowly slides to one side, and you have to hold the pad tilted to keep it straight. A large rotation of the pad sometimes "fixes" it temporarily, then the drift comes back.

Change

A Mahony-style complementary filter is added in GameController::Motion. When the pad is roughly at rest (|accel| between 0.8 and 1.2 G), the angular velocity used for integration is nudged so that the predicted "up" converges on the measured gravity direction. This corrects the tilt (pitch/roll) drift. The heading (yaw) cannot be observed from gravity and is left unchanged.

  • The "up" reference is captured from the accelerometer after connection and after ResetOrientation / motion sensor state changes. A reset done while the pad is tilted keeps its meaning.
  • The gyro and accelerometer values reported to the game are unchanged (raw). Only the integrated orientation is corrected.
  • KYTY_GYRO_CORRECTION sets the gain (default 1.0). KYTY_GYRO_CORRECTION=0 restores the previous behavior (pure gyro integration).

Testing

  • Astro's Playroom (PPSA01325), gyro sections, Core Ultra 7 155H + RTX 4070 Laptop, DualSense (USB and Bluetooth):
    • before: the orientation drifts over time and the pad has to be held tilted to stay straight;
    • after: the orientation stays level with no drift noticed during play, and it returns to level on its own;
    • the spring-bot sections that rely on the gyro were playable but frustrating, especially after a while (drift accumulated towards the end); with the fix they behave as expected.
  • The filter was also checked in a small standalone simulation (not included), using the same quaternion update as controller.cpp. With a deliberately large gyro bias, the tilt error over 60 s went from 74–90° without correction to about 1–2° with it, for both a still and a moving pad, and for a reset done while the pad is tilted.
**@⁠ew-sudo** on GitHub · 2026-09-28 21:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/899) `ew-sudo:gyro-drift-fix` → `main` · +60 −13 · 1 files · 2 commits · merged 2026-09-30 18:40 UTC ## Problem The pad orientation (`orientation_x/y/z/w`) is built by integrating the gyro alone. Every real gyro has a small bias, so the integrated orientation slowly drifts. In practice, gyro-controlled sections in Astro's Playroom (PPSA01325) get worse over time: when the controller is held still the camera or object slowly slides to one side, and you have to hold the pad tilted to keep it straight. A large rotation of the pad sometimes "fixes" it temporarily, then the drift comes back. ## Change A Mahony-style complementary filter is added in `GameController::Motion`. When the pad is roughly at rest (|accel| between 0.8 and 1.2 G), the angular velocity used for integration is nudged so that the predicted "up" converges on the measured gravity direction. This corrects the tilt (pitch/roll) drift. The heading (yaw) cannot be observed from gravity and is left unchanged. - The "up" reference is captured from the accelerometer after connection and after `ResetOrientation` / motion sensor state changes. A reset done while the pad is tilted keeps its meaning. - The gyro and accelerometer values reported to the game are unchanged (raw). Only the integrated orientation is corrected. - `KYTY_GYRO_CORRECTION` sets the gain (default 1.0). `KYTY_GYRO_CORRECTION=0` restores the previous behavior (pure gyro integration). ## Testing - Astro's Playroom (PPSA01325), gyro sections, Core Ultra 7 155H + RTX 4070 Laptop, DualSense (USB and Bluetooth): - before: the orientation drifts over time and the pad has to be held tilted to stay straight; - after: the orientation stays level with no drift noticed during play, and it returns to level on its own; - the spring-bot sections that rely on the gyro were playable but frustrating, especially after a while (drift accumulated towards the end); with the fix they behave as expected. - The filter was also checked in a small standalone simulation (not included), using the same quaternion update as `controller.cpp`. With a deliberately large gyro bias, the tilt error over 60 s went from 74–90° without correction to about 1–2° with it, for both a still and a moving pad, and for a reset done while the pad is tilted.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:36:31 +00:00
github manually merged commit 9315c758f3 into gh-pr/899/base 2026-11-26 09:36:33 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 21:58 UTC · original · edited 2026-09-28 22:01 UTC

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

GameController now captures a normalized gravity reference when acceleration magnitude is between 0.9 and 1.1 G. When the correction gain is positive, the reference is valid, and acceleration magnitude is between 0.8 and 1.2 G, gyro integration uses a corrected rate while reported gyro samples remain raw. KYTY_GYRO_CORRECTION sets the gain and defaults to 1.0. Motion-state changes and orientation resets invalidate the reference. The 100,000-microsecond integration interval limit remains.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🟡 Moderate · up to 5ccb4

Gyro tilt correction can be wrong after switching controllers or after a bad first reading, which would make motion controls drift or tilt. The scope is limited to motion input, and setting KYTY_GYRO_CORRECTION=0 restores the previous behavior. Fix the controller-switch reset before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 5ccb4

Switching controllers can leave tilt correction using a reference captured from the previous controller. This can affect reported orientation, but no security-sensitive use of that orientation was established.

Retained concerns

  • Low · architecture · inferred: An active-controller change clears orientation state but retains the newly added gravity-reference validity flag. Subsequent gyro updates can therefore correct the new controller’s orientation toward the previous controller’s reference until an explicit reset or sensor-state change invalidates it.
Security review details

Security Blast Radius

  • inferred — The demonstrated effect is on orientation delivered to pad consumers after a controller switch. The inspected path does not establish a cross-service, credential, or authorization effect.

Trust Boundaries and Controls

  • observed — The sensor path retains active-controller and motion-enabled checks before accepting motion updates.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: using the accelerometer to correct gyro orientation drift.
Description check ✅ Passed The description is directly related to the changeset. It explains the drift problem, the complementary filter, configuration behavior, and testing results.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 21:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/899#issuecomment-5879499506) · edited 2026-09-28 22:01 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/899?cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough GameController now captures a normalized gravity reference when acceleration magnitude is between 0.9 and 1.1 G. When the correction gain is positive, the reference is valid, and acceleration magnitude is between 0.8 and 1.2 G, gyro integration uses a corrected rate while reported gyro samples remain raw. KYTY_GYRO_CORRECTION sets the gain and defaults to 1.0. Motion-state changes and orientation resets invalidate the reference. The 100,000-microsecond integration interval limit remains. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"5ccb400d133da155df47a0778a3043b3a0e56467" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🟡 Moderate_ · up to `5ccb4` <!-- final_review_risk_coverage:{"sourceCommitId":"5ccb400d133da155df47a0778a3043b3a0e56467","coveredCommitId":"5ccb400d133da155df47a0778a3043b3a0e56467","kind":"reviewed"} --> Gyro tilt correction can be wrong after switching controllers or after a bad first reading, which would make motion controls drift or tilt. The scope is limited to motion input, and setting KYTY_GYRO_CORRECTION=0 restores the previous behavior. Fix the controller-switch reset before merging. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `5ccb4` Switching controllers can leave tilt correction using a reference captured from the previous controller. This can affect reported orientation, but no security-sensitive use of that orientation was established. **Retained concerns** - **Low · architecture · inferred:** An active-controller change clears orientation state but retains the newly added gravity-reference validity flag. Subsequent gyro updates can therefore correct the new controller’s orientation toward the previous controller’s reference until an explicit reset or sensor-state change invalidates it. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The demonstrated effect is on orientation delivered to pad consumers after a controller switch. The inspected path does not establish a cross-service, credential, or authorization effect. **Trust Boundaries and Controls** - _observed_ — The sensor path retains active-controller and motion-enabled checks before accepting motion updates. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 1 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely describes the main change: using the accelerometer to correct gyro orientation drift. | | Description check | ✅ Passed | The description is directly related to the changeset. It explains the drift problem, the complementary filter, configuration behavior, and testing results. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=899)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -135,1 +135,4 @@
uint64_t m_gyro_time = 0;
// Accelerometer gravity direction in the reset frame.
std::array<float, 3> m_up_reference {0.0f, 1.0f, 0.0f};
bool m_up_reference_valid = false;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 21:58 UTC · original · edited 2026-09-30 18:40 UTC

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

rg -n 'm_up_reference_valid|CheckActive|orientation' src/libs/controller.cpp

Repository: KytyPS5/KytyPS5

Length of output: 1677


🏁 Script executed:

sed -n '285,350p;440,580p' src/libs/controller.cpp

Repository: KytyPS5/KytyPS5

Length of output: 7039


Clear the gravity reference when the active controller changes.

GameController::CheckActive changes m_active_id but does not clear m_up_reference_valid. It also does not reset m_state.orientation on this path. After a controller switch, the next gyro event can therefore correct the new controller using the previous controller's gravity reference.

Clear the flag when CheckActive changes the active connection state:

Suggested fix
	m_active_id     = new_active_id;
	m_connected     = new_connected;
+	m_up_reference_valid = false;
	AddState();

✅ Addressed in commit 9315c75

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 21:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/899#discussion_r4127414395) · edited 2026-09-30 18:40 UTC _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash rg -n 'm_up_reference_valid|CheckActive|orientation' src/libs/controller.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 1677 --- 🏁 Script executed: ```bash sed -n '285,350p;440,580p' src/libs/controller.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 7039 --- </details> **Clear the gravity reference when the active controller changes.** `GameController::CheckActive` changes `m_active_id` but does not clear `m_up_reference_valid`. It also does not reset `m_state.orientation` on this path. After a controller switch, the next gyro event can therefore correct the new controller using the previous controller's gravity reference. Clear the flag when `CheckActive` changes the active connection state: <details> <summary>Suggested fix</summary> ```diff m_active_id = new_active_id; m_connected = new_connected; + m_up_reference_valid = false; AddState(); ``` </details> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c6169d3b8ece3b121f54c790 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 9315c75
@ -450,0 +480,4 @@
const Vec3 up {m_state.accel[0] / magnitude, m_state.accel[1] / magnitude,
m_state.accel[2] / magnitude};
m_up_reference = QuatRotate(m_state.orientation, up);
m_up_reference_valid = true;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 21:58 UTC · original

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- controller structure ---'
ast-grep outline src/libs/controller.cpp
printf '%s\n' '--- relevant source ---'
sed -n '1,180p' src/libs/controller.cpp
sed -n '430,560p' src/libs/controller.cpp
printf '%s\n' '--- reference and gain bindings ---'
rg -n -C 4 'm_up_reference|m_up_reference_valid|GYRO_CORRECTION|gyro.*correction|correction_gain|m_state\.orientation|Motion\(|CheckActive' src README.md CMakeLists.txt 2>/dev/null
printf '%s\n' '--- changed-file diff summary and relevant diff ---'
git diff --stat 6f241bef4983e67338d533a552668395a59f9120 5ccb400d133da155df47a0778a3043b3a0e56467 -- src/libs/controller.cpp
git diff --unified=25 6f241bef4983e67338d533a552668395a59f9120 5ccb400d133da155df47a0778a3043b3a0e56467 -- src/libs/controller.cpp

Repository: KytyPS5/KytyPS5

Length of output: 41638


🏁 Script executed:

pwd; sed -n '470,535p' src/libs/controller.cpp; rg -n -C 3 'm_up_reference|GYRO_CORRECTION|up reference|gravity|orientation reset' src README.md

Repository: KytyPS5/KytyPS5

Length of output: 8566


Require a stable interval before latching m_up_reference.

The sample {0.4, 1.0, 0.0} has magnitude about 1.077 G, so it passes the current check while indicating about 22° of lateral tilt. After ResetOrientation() clears m_up_reference_valid, this sample can become the reference. With the default positive correction gain, later gyro updates can drive the orientation toward that incorrect reference until another reset.

Require a stable sample interval with low gyro activity before capturing the reference.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 21:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/899#discussion_r4127414404) _🎯 Functional Correctness_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- controller structure ---' ast-grep outline src/libs/controller.cpp printf '%s\n' '--- relevant source ---' sed -n '1,180p' src/libs/controller.cpp sed -n '430,560p' src/libs/controller.cpp printf '%s\n' '--- reference and gain bindings ---' rg -n -C 4 'm_up_reference|m_up_reference_valid|GYRO_CORRECTION|gyro.*correction|correction_gain|m_state\.orientation|Motion\(|CheckActive' src README.md CMakeLists.txt 2>/dev/null printf '%s\n' '--- changed-file diff summary and relevant diff ---' git diff --stat 6f241bef4983e67338d533a552668395a59f9120 5ccb400d133da155df47a0778a3043b3a0e56467 -- src/libs/controller.cpp git diff --unified=25 6f241bef4983e67338d533a552668395a59f9120 5ccb400d133da155df47a0778a3043b3a0e56467 -- src/libs/controller.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 41638 --- 🏁 Script executed: ```bash pwd; sed -n '470,535p' src/libs/controller.cpp; rg -n -C 3 'm_up_reference|GYRO_CORRECTION|up reference|gravity|orientation reset' src README.md ``` Repository: KytyPS5/KytyPS5 Length of output: 8566 --- </details> **Require a stable interval before latching `m_up_reference`.** The sample `{0.4, 1.0, 0.0}` has magnitude about `1.077 G`, so it passes the current check while indicating about 22° of lateral tilt. After `ResetOrientation()` clears `m_up_reference_valid`, this sample can become the reference. With the default positive correction gain, later gyro updates can drive the orientation toward that incorrect reference until another reset. Require a stable sample interval with low gyro activity before capturing the reference. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e478b1604d83d04b797b26ed --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 21:58 UTC · original
On src/libs/controller.cpp line 508 (outdated):

@@ -447,20 +488,42 @@ void GameController::Motion(int id, Sensor sensor, const float* data, uint64_t t
 		for (int i = 0; i < 3; i++) {
 			m_state.accel[i] = data[i] / SDL_STANDARD_GRAVITY;
 		}
+		// Remember which way is up in the reset frame, once the pad is roughly at rest.
+		const float magnitude = Length(m_state.accel);
+		if (!m_up_reference_valid && magnitude > 0.9f && magnitude < 1.1f) {
+			const Vec3 up {m_state.accel[0] / magnitude, m_state.accel[1] / magnitude,
+			               m_state.accel[2] / magnitude};
+			m_up_reference       = QuatRotate(m_state.orientation, up);
+			m_up_reference_valid = true;
+		}
 	} else {
 		std::copy_n(data, 3, m_state.gyro.begin());
+		// Pure gyro integration accumulates the sensor bias, so the orientation drifts. Like the
+		// PS5 system software, correct the tilt (not the heading) with the accelerometer: nudge
+		// the angular velocity so the predicted "up" converges on the measured gravity
+		// (Mahony-style complementary filter). The reported gyro values stay raw.
+		Vec3        rate {data[0], data[1], data[2]};
+		const float gain      = GyroCorrectionGain();
+		const float magnitude = Length(m_state.accel);
+		if (gain > 0.0f && m_up_reference_valid && magnitude > 0.8f && magnitude < 1.2f) {

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- candidate files ---'
git ls-files | grep -E '(^|/)(controller\.cpp|controller\.h|window\.cpp|window\.h|.*controller.*|.*window.*)$' | head -80
printf '%s\n' '--- symbols ---'
rg -n -S 'SetSensor|GameController::Motion|Motion\(|m_state\.accel|SDL_SENSOR|SDL_Sensor|GYRO|ACCEL' src 2>/dev/null | head -240
printf '%s\n' '--- diff summary ---'
git diff --stat 6f241bef4983e67338d533a552668395a59f9120 5ccb400d133da155df47a0778a3043b3a0e56467 -- src
printf '%s\n' '--- relevant diff ---'
git diff --unified=35 6f241bef4983e67338d533a552668395a59f9120 5ccb400d133da155df47a0778a3043b3a0e56467 -- src/libs/controller.cpp src/window.cpp src/libs/controller.h

Repository: KytyPS5/KytyPS5

Length of output: 14954


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- controller lifecycle and motion ---'
sed -n '250,345p' src/libs/controller.cpp
sed -n '450,575p' src/libs/controller.cpp
sed -n '735,775p' src/libs/controller.cpp
printf '%s\n' '--- window sensor dispatch ---'
sed -n '630,700p' src/graphics/presentation/window/window.cpp
printf '%s\n' '--- relevant callers ---'
rg -n -S -C 5 'SetMotionSensorState|ResetOrientation|SetSensor\(' src
printf '%s\n' '--- sensor event and controller-change references ---'
rg -n -S -C 4 'SDL_EVENT_SENSOR|SENSOR_UPDATE|CONTROLLER.*ADDED|GAMEPAD.*ADDED|SDL_EVENT_GAMEPAD|m_active_id|CheckActive\(' src/libs/controller.cpp src/graphics/presentation/window/window.cpp

Repository: KytyPS5/KytyPS5

Length of output: 31530


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- CheckActive complete body ---'
sed -n '328,370p' src/libs/controller.cpp
printf '%s\n' '--- SDL dependency and sensor event definitions in checkout ---'
git ls-files | grep -Ei '(^|/)(sdl|SDL)(/|$)|SDL.*\.(h|cpp|c)$|CMakeLists\.txt|.*cmake$' | head -120
rg -n -S 'SDL3|SDL_EVENT_GAMEPAD_SENSOR_UPDATE|SDL_SetGamepadSensorEnabled|SDL_SENSOR_ACCEL|SDL_SENSOR_GYRO' --glob '!src/libs/controller.cpp' --glob '!src/graphics/presentation/window/window.cpp' . 2>/dev/null | head -180
printf '%s\n' '--- all sensor dispatch sites ---'
rg -n -S -C 3 'GAMEPAD_SENSOR_UPDATE|SetSensor\(' . 2>/dev/null | head -180

Repository: KytyPS5/KytyPS5

Length of output: 5191


🌐 Web query:

official SDL3 documentation SDL_EVENT_GAMEPAD_SENSOR_UPDATE gamepad sensor update event accelerometer gyro

💡 Result:

`SDL_EVENT_GAMEPAD_SENSOR_UPDATE` is SDL3’s event for a gamepad sensor reading. In the event loop, read `event.gsensor`; its `SDL_GamepadSensorEvent` fields include the gamepad ID (`which`), sensor type (`sensor`), three values (`data[3]`), and reading timestamp (`sensor_timestamp`). ([wiki.libsdl.org](https://wiki.libsdl.org/SDL3/SDL_Event?utm_source=openai))

The sensor type identifies an accelerometer (`SDL_SENSOR_ACCEL`) or gyroscope (`SDL_SENSOR_GYRO`). Accelerometer values are in m/s²; gyroscope values are in radians/s. ([wiki.libsdl.org](https://wiki.libsdl.org/SDL3/SDL_SensorType?utm_source=openai))

```c
if (event.type == SDL_EVENT_GAMEPAD_SENSOR_UPDATE) {
    const SDL_GamepadSensorEvent *s = &event.gsensor;

    if (s->sensor == SDL_SENSOR_ACCEL) {
        // s->data[0..2]: acceleration
    } else if (s->sensor == SDL_SENSOR_GYRO) {
        // s->data[0..2]: angular velocity
    }
}
```

For the official SDL3 reference, see [`SDL_GamepadSensorEvent`](https://wiki.libsdl.org/SDL3/SDL_GamepadSensorEvent), [`SDL_SensorType`](https://wiki.libsdl.org/SDL3/SDL_SensorType), and [`SDL_EVENT_GAMEPAD_SENSOR_UPDATE`](https://wiki.libsdl.org/SDL3/SDL_EVENT_GAMEPAD_SENSOR_UPDATE).

Citations:

- 1: https://wiki.libsdl.org/SDL3/SDL_Event?utm_source=openai
- 2: https://wiki.libsdl.org/SDL3/SDL_SensorType?utm_source=openai

Ignore stale accelerometer samples during gyro correction.

SDL delivers accelerometer and gyro updates as separate sensor events. Motion stores acceleration without a timestamp, then uses the stored value on every gyro event. If accelerometer delivery stops while gyro delivery continues, correction can bias orientation toward an obsolete direction.

Record the latest accelerometer timestamp and skip correction after the sample becomes stale.

Suggested fix
 	uint64_t         m_gyro_time       = 0;
+	uint64_t         m_accel_time      = 0;
...
 	m_state         = {};
 	m_gyro_time     = 0;
+	m_accel_time    = 0;
...
 	if (sensor == Sensor::Accel) {
 		for (int i = 0; i < 3; i++) {
 			m_state.accel[i] = data[i] / SDL_STANDARD_GRAVITY;
 		}
+		m_accel_time = time_us;
...
 		const float gain      = GyroCorrectionGain();
 		const float magnitude = Length(m_state.accel);
-		if (gain > 0.0f && m_up_reference_valid && magnitude > 0.8f && magnitude < 1.2f) {
+		const bool accel_fresh =
+		    m_accel_time != 0 && time_us >= m_accel_time && time_us - m_accel_time <= 100000;
+		if (gain > 0.0f && m_up_reference_valid && accel_fresh && magnitude > 0.8f &&
+		    magnitude < 1.2f) {
...
 		m_gyro_time      = 0;
+		m_accel_time     = 0;
 		m_state.accel    = {0.0f, 1.0f, 0.0f};
**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 21:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/899#discussion_r4127414411) On `src/libs/controller.cpp` line 508 (outdated): ```diff @@ -447,20 +488,42 @@ void GameController::Motion(int id, Sensor sensor, const float* data, uint64_t t for (int i = 0; i < 3; i++) { m_state.accel[i] = data[i] / SDL_STANDARD_GRAVITY; } + // Remember which way is up in the reset frame, once the pad is roughly at rest. + const float magnitude = Length(m_state.accel); + if (!m_up_reference_valid && magnitude > 0.9f && magnitude < 1.1f) { + const Vec3 up {m_state.accel[0] / magnitude, m_state.accel[1] / magnitude, + m_state.accel[2] / magnitude}; + m_up_reference = QuatRotate(m_state.orientation, up); + m_up_reference_valid = true; + } } else { std::copy_n(data, 3, m_state.gyro.begin()); + // Pure gyro integration accumulates the sensor bias, so the orientation drifts. Like the + // PS5 system software, correct the tilt (not the heading) with the accelerometer: nudge + // the angular velocity so the predicted "up" converges on the measured gravity + // (Mahony-style complementary filter). The reported gyro values stay raw. + Vec3 rate {data[0], data[1], data[2]}; + const float gain = GyroCorrectionGain(); + const float magnitude = Length(m_state.accel); + if (gain > 0.0f && m_up_reference_valid && magnitude > 0.8f && magnitude < 1.2f) { ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash set -u printf '%s\n' '--- candidate files ---' git ls-files | grep -E '(^|/)(controller\.cpp|controller\.h|window\.cpp|window\.h|.*controller.*|.*window.*)$' | head -80 printf '%s\n' '--- symbols ---' rg -n -S 'SetSensor|GameController::Motion|Motion\(|m_state\.accel|SDL_SENSOR|SDL_Sensor|GYRO|ACCEL' src 2>/dev/null | head -240 printf '%s\n' '--- diff summary ---' git diff --stat 6f241bef4983e67338d533a552668395a59f9120 5ccb400d133da155df47a0778a3043b3a0e56467 -- src printf '%s\n' '--- relevant diff ---' git diff --unified=35 6f241bef4983e67338d533a552668395a59f9120 5ccb400d133da155df47a0778a3043b3a0e56467 -- src/libs/controller.cpp src/window.cpp src/libs/controller.h ``` Repository: KytyPS5/KytyPS5 Length of output: 14954 --- 🏁 Script executed: ```bash #!/bin/bash set -u printf '%s\n' '--- controller lifecycle and motion ---' sed -n '250,345p' src/libs/controller.cpp sed -n '450,575p' src/libs/controller.cpp sed -n '735,775p' src/libs/controller.cpp printf '%s\n' '--- window sensor dispatch ---' sed -n '630,700p' src/graphics/presentation/window/window.cpp printf '%s\n' '--- relevant callers ---' rg -n -S -C 5 'SetMotionSensorState|ResetOrientation|SetSensor\(' src printf '%s\n' '--- sensor event and controller-change references ---' rg -n -S -C 4 'SDL_EVENT_SENSOR|SENSOR_UPDATE|CONTROLLER.*ADDED|GAMEPAD.*ADDED|SDL_EVENT_GAMEPAD|m_active_id|CheckActive\(' src/libs/controller.cpp src/graphics/presentation/window/window.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 31530 --- 🏁 Script executed: ```bash #!/bin/bash set -u printf '%s\n' '--- CheckActive complete body ---' sed -n '328,370p' src/libs/controller.cpp printf '%s\n' '--- SDL dependency and sensor event definitions in checkout ---' git ls-files | grep -Ei '(^|/)(sdl|SDL)(/|$)|SDL.*\.(h|cpp|c)$|CMakeLists\.txt|.*cmake$' | head -120 rg -n -S 'SDL3|SDL_EVENT_GAMEPAD_SENSOR_UPDATE|SDL_SetGamepadSensorEnabled|SDL_SENSOR_ACCEL|SDL_SENSOR_GYRO' --glob '!src/libs/controller.cpp' --glob '!src/graphics/presentation/window/window.cpp' . 2>/dev/null | head -180 printf '%s\n' '--- all sensor dispatch sites ---' rg -n -S -C 3 'GAMEPAD_SENSOR_UPDATE|SetSensor\(' . 2>/dev/null | head -180 ``` Repository: KytyPS5/KytyPS5 Length of output: 5191 --- 🌐 Web query: `official SDL3 documentation SDL_EVENT_GAMEPAD_SENSOR_UPDATE gamepad sensor update event accelerometer gyro` 💡 Result: ```` `SDL_EVENT_GAMEPAD_SENSOR_UPDATE` is SDL3’s event for a gamepad sensor reading. In the event loop, read `event.gsensor`; its `SDL_GamepadSensorEvent` fields include the gamepad ID (`which`), sensor type (`sensor`), three values (`data[3]`), and reading timestamp (`sensor_timestamp`). ([wiki.libsdl.org](https://wiki.libsdl.org/SDL3/SDL_Event?utm_source=openai)) The sensor type identifies an accelerometer (`SDL_SENSOR_ACCEL`) or gyroscope (`SDL_SENSOR_GYRO`). Accelerometer values are in m/s²; gyroscope values are in radians/s. ([wiki.libsdl.org](https://wiki.libsdl.org/SDL3/SDL_SensorType?utm_source=openai)) ```c if (event.type == SDL_EVENT_GAMEPAD_SENSOR_UPDATE) { const SDL_GamepadSensorEvent *s = &event.gsensor; if (s->sensor == SDL_SENSOR_ACCEL) { // s->data[0..2]: acceleration } else if (s->sensor == SDL_SENSOR_GYRO) { // s->data[0..2]: angular velocity } } ``` For the official SDL3 reference, see [`SDL_GamepadSensorEvent`](https://wiki.libsdl.org/SDL3/SDL_GamepadSensorEvent), [`SDL_SensorType`](https://wiki.libsdl.org/SDL3/SDL_SensorType), and [`SDL_EVENT_GAMEPAD_SENSOR_UPDATE`](https://wiki.libsdl.org/SDL3/SDL_EVENT_GAMEPAD_SENSOR_UPDATE). Citations: - 1: https://wiki.libsdl.org/SDL3/SDL_Event?utm_source=openai - 2: https://wiki.libsdl.org/SDL3/SDL_SensorType?utm_source=openai ```` --- </details> **Ignore stale accelerometer samples during gyro correction.** SDL delivers accelerometer and gyro updates as separate sensor events. `Motion` stores acceleration without a timestamp, then uses the stored value on every gyro event. If accelerometer delivery stops while gyro delivery continues, correction can bias orientation toward an obsolete direction. Record the latest accelerometer timestamp and skip correction after the sample becomes stale. <details> <summary>Suggested fix</summary> ```diff uint64_t m_gyro_time = 0; + uint64_t m_accel_time = 0; ... m_state = {}; m_gyro_time = 0; + m_accel_time = 0; ... if (sensor == Sensor::Accel) { for (int i = 0; i < 3; i++) { m_state.accel[i] = data[i] / SDL_STANDARD_GRAVITY; } + m_accel_time = time_us; ... const float gain = GyroCorrectionGain(); const float magnitude = Length(m_state.accel); - if (gain > 0.0f && m_up_reference_valid && magnitude > 0.8f && magnitude < 1.2f) { + const bool accel_fresh = + m_accel_time != 0 && time_us >= m_accel_time && time_us - m_accel_time <= 100000; + if (gain > 0.0f && m_up_reference_valid && accel_fresh && magnitude > 0.8f && + magnitude < 1.2f) { ... m_gyro_time = 0; + m_accel_time = 0; m_state.accel = {0.0f, 1.0f, 0.0f}; ``` </details> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c4d6807c300377cc5bdcfcf2 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 21:58 UTC · original · reviewed

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 4e8611d6-8821-42df-9388-0ad8a0f14d5d

📥 Commits

Reviewing files that changed from the base of the PR and between 62a0222e24 and 5ccb400d13.

📒 Files selected for processing (1)
  • src/libs/controller.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 21:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/899#pullrequestreview-5345115937) · **reviewed** **Actionable comments posted: 3** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `4e8611d6-8821-42df-9388-0ad8a0f14d5d` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 62a0222e24e2cc727c66742b1dbaaa06188510df and 5ccb400d133da155df47a0778a3043b3a0e56467. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/libs/controller.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
This discussion has been locked. Commenting is limited to contributors.
No description provided.