Add VITURE XR controls, head tracking, and SteamVR (#732)

* Add VITURE glasses support: hardware control, 3D, head tracking

Glasses get their own controller over the MCU (permission, 120 Hz default, brightness, volume, sunblock, 2D/3D) and the game moves onto them when plugged in. The IMU drives Cardboard head tracking and the SteamVR driver. 3D falls back to one eye's view on phones that can't send the 3840x1080 signal. Options open from a glasses button in game and on the Steam page.

* Drop the glasses settings like Steam's: Play-style button, Settings lip, tabs

* Hang the glasses Settings lip over the top of the button

* Space glasses MCU commands so the IMU rate sticks, fit fixed resolutions to the glasses

* Keep Steam alive with SteamVR registered, run SteamVR at the glasses' rate, keep the glasses lip on top

* Fit VR games on the glasses: full view, seated origin at the head, pad hands reach with the d-pad

* Let the pad hands reach a metre out so buttons with deep colliders press

* Show every VR frame in order at 120 fps: wait for SteamVR's GPU work, present only finished copies, skip the grace on idle shared counters

* Glasses: SteamVR starts and stops with them, closer view with a field of view setting, Recenter on the pad

* Glasses: SteamVR field of view defaults to 90°

* VR pad hands: sticks move and aim the hands, left stick click switches the sticks to the game, d-pad pulls a held hand

* Glasses: Play SteamVR beside the glasses button instead of starting SteamVR with them, pad hands drawn as Index controllers and off while other VR controllers are connected, glasses sheet tabs sized like Steam's

* Track glasses mode, refresh-aware glasses window, align Play SteamVR with Play Steam

* Fix 3D on the glasses: full-res SteamVR presenter, revert VR 3D at session end, coalesce vsync ticks, no session restart after end

* Address review: glasses output after installs and session end, VR revert retry, display fallback, presenter swapchain retry, agent hex checks, drawer bumpers, glasses translations, docs

* Harden VITURE stereo negotiation and output refresh tracking

* Localize stereo recovery feedback and record Astra reconnect tests

* Improve test failure diagnostics and refresh Astra firmware findings

* Handle VITURE docks separately and reject truncated USB frames

* Glasses: remember a 3D fallback per model, docks as display only, VR timing fixes

- A 3D attempt that ends at the 640x480 fallback is remembered for that glasses
  model, so Play SteamVR no longer blacks out the glasses after every restart;
  Retry clears it and "3D for VR games" stays reachable
- A VITURE Mobile Dock on its own no longer counts as glasses; through a dock
  Play SteamVR is hidden and the sheet shows the output and why there is no control
- HDR is probed on the glasses when the session starts there
- Glasses frames with a mismatched checksum are marked in the status frame log
- SteamVR layer and driver vblank counters stay monotonic across refresh changes;
  one-eye render scale applies from activation and on mono/3D switches
- Compositor binds announce the refresh clients were last told; the presenter
  retries a failed first swapchain
- Dead strings and helpers removed; docs updated

* Glasses: drop USB frames with a bad checksum

* Glasses: count frames dropped for a bad checksum

* Feat/viture xr (#907)

* Add RayNeo Air and GT support to the XR glasses pipeline

* Add RayNeo Air and GT support to the XR glasses pipeline

* Checkpoint glasses tracking, calibration, and SteamVR launch integration

* Checkpoint glasses tracking, calibration, and SteamVR launch integration

* Add XREAL 1S support and correct GT and Pro 2 tracking

* Add XREAL 1S support and correct GT and Pro 2 tracking

* Fix mirrored glasses tracking and recover SteamVR after device loss

* Fix mirrored glasses tracking and recover SteamVR after device loss

* Document confirmed XREAL 1S brightness control

* Document confirmed XREAL 1S brightness control

* Fix SteamVR glasses defaults and rendering controls

* Fix SteamVR glasses defaults and rendering controls

* chore: keep only the 3 newest session log folders (#852)

* chore: add agent comment rules (#748)

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>

* Fix SteamVR polling, VITURE checksums, and fence tracking

Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter.

Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage.

* Fix SteamVR polling, VITURE checksums, and fence tracking

Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter.

Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage.

* fix: wireless ADB page names the child-process switch the way Android shows it (#848)

* l10n: refresh stale and untranslated strings in es, fr, ko, ru (#850)

* l10n: refresh stale and untranslated strings in es, fr, ko, ru

- mode_added_art_hint: now mentions Steam then SteamGridDB (all four locales).
- wincomp_needs_installer / wincomp_installers_note: es and ko still described
  the old "coming soon" behaviour; align with the current English text.
- summary_remove_game: was still English in all four locales.

Machine-assisted translation; native-speaker review is welcome.

* l10n(es): say registro, not grabación, for the missing installer record

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* fix: a failed cloud save recovery no longer ends the app (#846)

The cloud-recovery thread started at every app start had nothing to
catch an error, so one went to CrashHandler, which halts the process
with status 2. In unit tests the thread can outlive the test that
started it, fail on the torn-down preferences, and take the whole test
run down. The error is now logged and the thread ends.

Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>

* fix: an interrupted Linux runtime download resumes instead of starting again (#847)

* fix: an interrupted Linux runtime download resumes instead of starting again

installOnce() asked the downloader to resume but always deleted the archive in its finally block, so the next attempt began at zero. The archive is now named after the release version and checksum, a failed download keeps what it fetched, and archives of other releases (and the old fixed name) are removed. A checksum or extraction failure still deletes the file.

* test: Downloader resumes a cut-off download from the bytes it kept

Starts a socket server that promises the whole file, hangs up part way and then answers a Range request, and checks that the second downloadFile call resumes with the right offset and ends with identical bytes.

* fix: a resumed download discards a 206 that does not start where the kept bytes end

Downloader appended every 206 response to the partial file without
looking at Content-Range. A server or proxy that answers a Range request
with a different offset would leave a corrupt file. Check that the range
starts at the kept length; otherwise delete the partial file and start
again without a Range header.

Adds a test with a server that answers the Range request from offset 0.

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings (#849)

* l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings

Adds the strings values-de, values-it and values-pt were missing (14 each) and the six that values-fr, values-es and values-ru were missing. Machine-assisted drafts that follow each file's existing register and terms; native review is welcome.

* l10n: correct missing active swap translations

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* fix: droiddeckctl reaches variant-package builds (recover #842) (#854)

fix: droiddeckctl reaches builds shipped under a variant package

The provider authority and the start Activity's component were fixed to
com.droiddeck.launcher, so droiddeckctl could not talk to the antutu,
ludashi or pubg builds from tools/release/variants.txt. DROIDDECK_PACKAGE
now picks the package; the Activity's class name stays the same in every
variant.

Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>

* feat: droiddeckctl reports on-screen pacing (recover #843) (#855)

feat: droiddeckctl pacing reports the frames that reached the screen

Reads SurfaceFlinger's timestats for the game's layer (or the session's
SurfaceView) over a capture: frames on screen, fps on screen, the
present-to-present histogram and how many intervals were off the usual
cadence. Records split by a refresh-rate change are summed. A game's own fps
counter counts frames handed over, so it can't show dropped or doubled frames.

Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>

* fix: Steam can restart more than twice in a session (#754)

* fix: Steam can restart more than twice in a session

Every exit 42 counted toward the cap that stops an update which will
not install, and the count was never cleared, so the third restart of
a session ended it however far apart they were. A client that ran for
a minute before asking is not that loop: the count starts again.

* fix: measure the client's run time as it exits

The time spent collecting logs and checking FEX after the client exits
counted toward its run, so a slow cleanup could make a quick exit 42
look like a long one and clear the count.

---------

Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>

* fix: the front end keeps its page when the Fold is folded or unfolded (#832)

* fix: the front end keeps its page when the Fold is folded or unfolded

MainActivity, FileManagerActivity, FilePickerActivity and StoreLoginActivity did not declare the screen-size configuration changes, so folding or unfolding a foldable recreated them and dropped their in-memory state. They now handle orientation, screenSize, screenLayout, smallestScreenSize and density themselves, like SessionActivity already does. uiMode is left out on purpose.

* fix: store login keeps rebuilding its toolbar when the display density changes

StoreLoginActivity builds its toolbar in code with dp-to-pixel values taken at creation time and has no onConfigurationChanged. It no longer declares density in configChanges, so a density change recreates it as before this PR. Size and layout changes are still handled in place.

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* Release pointer buttons without replaying stale motion (#803)

* Fix cursor warping on native touch down

* Preserve input cleanup without replaying stale pointer motion

---------

Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>

* l10n: translate the strings added since #284 into zh-CN, zh-HK, zh-TW and ja (#539)

* l10n: translate the 184 strings added since #284 (zh-CN/HK/TW, ja)

The stores, cloud saves, Windows components, Steam touch, desktop
removal and background-downloads strings landed after #284's
translation snapshot, so every one of them fell back to English.
Translate all 184 into Simplified Chinese, Traditional Chinese
(Taiwan and Hong Kong) and Japanese, keeping each locale file's own
vocabulary (工作階段/會話, 解除安裝/卸載, 元件/組件, 設定).

Also fix four Hong Kong strings that kept the simplified 着色器.

* l10n(zh): fix stale and ambiguous strings found in review

Severe: summary_remove_game was untranslated English in all three
files; mode_added_art_hint, wincomp_installers_note and
wincomp_needs_installer still described the pre-#480/#492 English.

Also: distinguish the Setup wizard from Android system settings in
zh-HK/zh-TW (初始設定 / 系統設定 / Android 設定), unify library as
收藏庫, component as 組件 in zh-HK, session as 會話 in zh-HK, account
as 帳戶 in zh-HK, Trending as 趋势/趨勢, Forget as 清除, reword the
re-applied-at-launch, action-failed and already-in-Games strings, and
play as 執行/開啟遊戲 in zh-TW/zh-HK.

* l10n(ja): fix stale and ambiguous strings found in review

---------

Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* Rebuild and verify Windows VR runtime components

* Rebuild and verify Windows VR runtime components

* Add top, bottom, and centered picture positions for Steam sessions (#871)

* fix: dependency scan ignores folders above the game folder (#859)

* DroidDeck-Proton: get releases from the Droid-Deck org repo

DroidDeck-Proton is now built and released on Droid-Deck/DroidDeck-Proton
(11-9.1 is Latest there), so the Components page, the update check and the
guest installer read releases from the org repo instead of The412Banner's.

* feat: low-latency controller and touch toggles in the session drawer (#808)

* fix: SteamGridDB lookups no longer stick as "no match" after a failure; add a search to the art chooser (#876)

* feat: Steam home wall fills from the signed-in library instead of store picks (#878)

* test: cover GPU family and support classification (#880)

* Fix local builds on Linux failing after the first Comet build (#866)

* feat: sort the store library and installed tabs, and switch between card and list views (#798)

* feat: three-finger tap toggles Steam's on-screen keyboard in game mode (#782)

* fix: keep Quest-patched Turnip as the auto default (#853)

* Fix deploy_local.sh and droiddeckctl not finding a phone connected over wireless debugging (#864)

* fix: keep proot sessions alive when the kernel loses fork events (#457)

* fix(quest): correct desktop and Steam display corruption across sessions (#733)

fix(quest): stabilize desktop and Steam layer presentation

Keep Quest SDR scenes and the black backdrop off the Android Vulkan swapchain regardless of session order or HDR preferences. Only report the first frame after client content is submitted.

Add backdrop lifecycle and first-frame regression coverage. Record the user's successful Quest 3 Test 2 result.

Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* fix: keep SteamVR syscall hooks and report Steam crashes (#905)

* fix: preserve SteamVR syscall hooks

* fix: report Steam crashes through gamescope

* fix: honor glasses pacing and resolution in SteamVR launches

---------

Co-authored-by: connor g <connorsspam1992@gmail.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com>
Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com>
Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: Kirk <kirtoy.junsay@gmail.com>
Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>
Co-authored-by: asdf17128 <asdf17128@gmail.com>
Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>
Co-authored-by: Dantalian <wsu091227@qq.com>
Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com>
Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com>
Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com>
Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com>
Co-authored-by: Jagger15 <jagger2333@live.com>

* Glasses: keep a pending 2D restore and the SteamVR recovery offer, show Play SteamVR only with a picture

* Translate the glasses calibration, XREAL and SteamVR recovery strings

* SteamVR recovery: give a finished teardown time to collect logs before restarting

* Credit the projects the XR glasses support builds on

* Joy-Cons: SteamVR hands from their gyro while SteamVR runs, one combined pad otherwise

* Headsets: settings badge on Play SteamVR instead of a top-right button, both shown only once connected

* Hand tracking: camera-tracked Joy-Cons and bare hands in SteamVR, drawn as white gloves

- Joy-Con movement from the accelerometer (report reordering, per-Joy-Con calibration, zero-velocity updates)
- MediaPipe pose and hand landmarks from the device camera, placement check, per-hand Kalman filter with the Joy-Con
- No controller connected: bare camera hands with Quest-style gestures, 1€ filtered, rendered as a white glove model built from a distance field
- SteamVR safe mode cleared before each start so one crash no longer blocks the driver

---------

Co-authored-by: MaxsTechReview <6025299+maxjivi05@users.noreply.github.com>
Co-authored-by: informalTechCode <informaltechyt@gmail.com>
Co-authored-by: connor g <connorsspam1992@gmail.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com>
Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com>
Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: Kirk <kirtoy.junsay@gmail.com>
Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>
Co-authored-by: asdf17128 <asdf17128@gmail.com>
Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>
Co-authored-by: Dantalian <wsu091227@qq.com>
Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com>
Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com>
Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com>
Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com>
Co-authored-by: Jagger15 <jagger2333@live.com>
This commit is contained in:
221 files changed
+24369 -491

No files matched your search

@@ -0,0 +1,153 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.glasses.Quaternion
import com.droiddeck.launcher.glasses.Vec3
import kotlin.math.PI
import kotlin.math.roundToInt
import org.junit.Assert.*
import org.junit.Test
class JoyConMotionTest {
private val bias = Vec3(0.3f, -0.25f, 0.2f)
@Test fun restingInSeveralPositionsLearnsTheAccelerometerOffset() {
val calibration = JoyConAccelCalibration()
assertFalse(calibration.ready)
var learned = false
for (up in directions) repeat(200) { learned = calibration.addResting(up * G + bias) || learned }
assertTrue(learned)
assertTrue(calibration.ready)
assertVec(bias, calibration.bias, 0.01f)
assertEquals(1f, calibration.scale, 1e-3f)
assertVec(Vec3(0f, G, 0f), calibration.correct(Vec3(0f, G, 0f) + bias), 0.01f)
}
@Test fun restingInOnePositionTeachesNothing() {
val calibration = JoyConAccelCalibration()
repeat(2000) { assertFalse(calibration.addResting(Vec3(0f, G, 0f) + bias)) }
assertFalse(calibration.ready)
assertVec(Vec3(1f, 2f, 3f), calibration.correct(Vec3(1f, 2f, 3f)))
}
@Test fun aSavedOffsetComesBackAndAnImplausibleOneIsIgnored() {
val first = JoyConAccelCalibration()
for (up in directions) repeat(200) { first.addResting(up * G + bias) }
val restored = JoyConAccelCalibration().apply { restore(first.saved()) }
assertTrue(restored.ready)
assertVec(first.bias, restored.bias, 0f)
assertEquals(first.scale, restored.scale, 0f)
for (bad in listOf(floatArrayOf(3f, 0f, 0f, 1f), floatArrayOf(0f, 0f, 0f, 1.5f), floatArrayOf(Float.NaN, 0f, 0f, 1f), floatArrayOf(0f, 0f, 1f))) {
val c = JoyConAccelCalibration().apply { restore(bad) }
assertFalse(bad.contentToString(), c.ready)
assertNull(c.saved())
}
}
@Test fun aLiftIsMeasuredAndTheHandStopsWhenItDoes() {
val motion = JoyConMotion()
still(motion, 1f)
val lift = 0.25f
val seconds = 0.5f
val steps = (seconds / DT).roundToInt()
for (i in 1..steps) {
val s = (i - 0.5f) / steps
val a = lift / (seconds * seconds) * (60 * s - 180 * s * s + 120 * s * s * s)
motion.update(Quaternion.IDENTITY, Vec3(0f, G + a, 0f), Vec3(0f, 0f, 0f), true, DT)
}
assertEquals(lift, motion.displacement.y, 0.01f)
assertTrue("moving up at ${motion.velocity}", motion.velocity.length() < 0.05f)
still(motion, 2f)
assertEquals(lift, motion.displacement.y, 0.015f)
assertEquals(0f, motion.velocity.length(), 1e-3f)
assertEquals(0f, motion.displacement.x, 1e-3f)
assertEquals(0f, motion.displacement.z, 1e-3f)
}
@Test fun theInertialVelocityKeepsAccelerationThatStillnessWouldDrop() {
val motion = JoyConMotion()
still(motion, 1f)
repeat((2f / DT).roundToInt()) { motion.update(Quaternion.IDENTITY, Vec3(0f, G + 0.05f, 0f), Vec3(0f, 0f, 0f), true, DT) }
assertEquals(0f, motion.velocity.y, 1e-3f)
assertEquals(0.1f, motion.inertial.y, 0.005f)
val before = motion.inertial.y
val seconds = 0.25f
repeat((seconds / DT).roundToInt()) { motion.update(Quaternion.IDENTITY, Vec3(2f, G, 0f), Vec3(0f, 0f, 0f), true, DT) }
assertEquals(2f * seconds, motion.inertial.x, 0.01f)
assertEquals(before, motion.inertial.y, 0.005f)
}
@Test fun aSidewaysPushIsMeasuredInTheWorldFrame() {
val motion = JoyConMotion()
val turned = Quaternion.fromAxisAngle(Vec3(0f, 0f, 1f), (PI / 2).toFloat())
val down = turned.conjugate().rotate(Vec3(0f, G, 0f))
repeat((1f / DT).toInt()) { motion.update(turned, down, Vec3(0f, 0f, 0f), true, DT) }
val steps = (0.4f / DT).roundToInt()
for (i in 1..steps) {
val s = (i - 0.5f) / steps
val a = 0.3f / (0.4f * 0.4f) * (60 * s - 180 * s * s + 120 * s * s * s)
motion.update(turned, down + turned.conjugate().rotate(Vec3(a, 0f, 0f)), Vec3(0f, 0f, 0f), true, DT)
}
assertEquals(0.3f, motion.displacement.x, 0.015f)
assertEquals(0f, motion.displacement.y, 0.01f)
}
@Test fun turningInPlaceDoesNotMoveTheHand() {
val motion = JoyConMotion()
still(motion, 1f)
val rate = 2f
var q = Quaternion.IDENTITY
repeat((1f / DT).toInt()) {
q = q.integrateBodyRate(Vec3(0f, 0f, rate), DT).normalized()
motion.update(q, q.conjugate().rotate(Vec3(0f, G, 0f)), Vec3(0f, 0f, rate), true, DT)
}
repeat((1f / DT).toInt()) { motion.update(q, q.conjugate().rotate(Vec3(0f, G, 0f)), Vec3(0f, 0f, 0f), true, DT) }
assertEquals(0f, motion.displacement.length(), 0.005f)
}
@Test fun anUncalibratedJoyConAtRestDoesNotDrift() {
val motion = JoyConMotion()
val filter = JoyConOrientation()
val tilted = Vec3(0.3f, G + 0.35f, -0.2f)
repeat((30f / DT).toInt()) {
filter.update(tilted, Vec3(0f, 0f, 0f), DT)
if (filter.ready) motion.update(filter.rotation, tilted, filter.rate, false, DT)
}
assertTrue("drifted ${motion.displacement}", motion.displacement.length() < 0.05f)
assertEquals(0f, motion.velocity.length(), 1e-3f)
}
@Test fun longHandlingWithATiltErrorCannotRunAway() {
val motion = JoyConMotion()
still(motion, 1f)
val leaking = Vec3(0.5f, G, 0f)
repeat((10f / DT).toInt()) { motion.update(Quaternion.IDENTITY, leaking, Vec3(0f, 0f, 1f), true, DT) }
assertTrue("velocity ${motion.velocity}", motion.velocity.length() < 0.15f)
assertTrue("moved ${motion.displacement}", motion.displacement.length() < 1.5f)
}
@Test fun onlyAStillJoyConCountsAsResting() {
val motion = JoyConMotion()
still(motion, 0.2f)
assertFalse(motion.resting)
still(motion, 0.2f)
assertTrue(motion.resting)
motion.update(Quaternion.IDENTITY, Vec3(0f, G, 0f), Vec3(0.3f, 0f, 0f), true, DT)
assertFalse(motion.resting)
}
private fun still(motion: JoyConMotion, seconds: Float) {
repeat((seconds / DT).toInt()) { motion.update(Quaternion.IDENTITY, Vec3(0f, G, 0f), Vec3(0f, 0f, 0f), true, DT) }
}
private fun assertVec(want: Vec3, got: Vec3, tolerance: Float = 1e-4f) {
assertEquals("x of $got", want.x, got.x, tolerance)
assertEquals("y of $got", want.y, got.y, tolerance)
assertEquals("z of $got", want.z, got.z, tolerance)
}
private companion object {
const val G = 9.80665f
const val DT = 0.005f
val directions = listOf(Vec3(0f, 1f, 0f), Vec3(0f, -1f, 0f), Vec3(1f, 0f, 0f), Vec3(-1f, 0f, 0f), Vec3(0f, 0f, 1f), Vec3(0f, 0f, -1f))
}
}
@@ -0,0 +1,117 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.glasses.Vec3
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import org.junit.Assert.*
import org.junit.Test
class JoyConOrientationTest {
private val faceUp = floatArrayOf(0f, 0f, G)
private val still = floatArrayOf(0f, 0f, 0f)
@Test fun aJoyConLyingFaceUpPointsStraightAhead() {
val filter = JoyConOrientation()
filter.update(faceUp, still, 0f)
assertTrue(filter.ready)
assertVec(Vec3(0f, 0f, -1f), forward(filter))
assertVec(Vec3(0f, 1f, 0f), filter.rotation.rotate(Vec3(0f, 1f, 0f)))
}
@Test fun standingOnItsBaseAimsUp() {
val filter = JoyConOrientation()
filter.update(floatArrayOf(G, 0f, 0f), still, 0f)
assertVec(Vec3(0f, 1f, 0f), forward(filter))
}
@Test fun nothingIsReportedUntilGravityIsPlausible() {
val filter = JoyConOrientation()
filter.update(floatArrayOf(0f, 0f, 3f), still, 0f)
assertFalse(filter.ready)
filter.update(floatArrayOf(0f, 0f, 30f), still, 0f)
assertFalse(filter.ready)
filter.update(faceUp, still, 0f)
assertTrue(filter.ready)
}
@Test fun turningAboutTheFaceTurnsTheAimLeft() {
val filter = JoyConOrientation()
filter.update(faceUp, still, 0f)
repeat(100) { filter.update(faceUp, floatArrayOf(0f, 0f, 1f), 0.01f) }
assertVec(Vec3(-sin(1f), 0f, -cos(1f)), forward(filter), 2e-3f)
assertVec(Vec3(0f, 1f, 0f), filter.rate)
}
@Test fun gravityPullsATiltedEstimateBackLevel() {
val filter = JoyConOrientation()
filter.update(faceUp, still, 0f)
repeat(50) { filter.update(faceUp, floatArrayOf(1f, 0f, 0f), 0.01f) }
assertTrue(filter.rotation.rotate(Vec3(0f, 1f, 0f)).y < 0.97f)
repeat(600) { filter.update(faceUp, still, 0.01f) }
assertEquals(1f, filter.rotation.rotate(Vec3(0f, 1f, 0f)).y, 1e-3f)
}
@Test fun aSteadyGyroOffsetIsLearnedWhileTheJoyConRests() {
val filter = JoyConOrientation()
filter.update(faceUp, still, 0f)
val drifting = floatArrayOf(0f, 0f, 0.02f)
repeat(1000) { filter.update(faceUp, drifting, 0.01f) }
assertEquals(0f, filter.rate.length(), 1e-3f)
val heading = heading(filter)
repeat(1000) { filter.update(faceUp, drifting, 0.01f) }
assertEquals(heading, heading(filter), 2e-3f)
}
@Test fun movingTheJoyConDoesNotTeachTheBias() {
val filter = JoyConOrientation()
filter.update(faceUp, still, 0f)
repeat(300) { filter.update(faceUp, floatArrayOf(0f, 0f, 0.5f), 0.01f) }
assertEquals(0.5f, filter.rate.length(), 1e-4f)
}
@Test fun reportsArriveNewestFirstAndTheRepeatedSampleIsDropped() {
val reports = JoyConReports()
fun sample(n: Int) = floatArrayOf(n.toFloat(), 0f, G) to floatArrayOf(n * 0.1f, 0f, 0f)
fun send(at: Long, vararg newestFirst: Int): List<JoyConReports.Sample> {
for (n in newestFirst) sample(n).let { reports.add(it.first, it.second, at) }
return reports.flush()
}
assertEquals(listOf(1f, 2f, 3f), send(1_000_000_000L, 3, 2, 1).map { it.accel[0] })
val second = send(1_010_000_000L, 5, 4, 3)
assertEquals(listOf(4f, 5f), second.map { it.accel[0] })
assertEquals("the report interval is shared by its new samples", 0.005f, second[0].dt, 1e-6f)
assertEquals(listOf(6f, 7f, 8f), send(1_025_000_000L, 8, 7, 6).map { it.accel[0] })
val still = send(1_035_000_000L, 8, 8, 8)
assertEquals("a still report still moves time on", 1, still.size)
assertEquals(0.01f, still[0].dt, 1e-6f)
assertEquals("a long gap is capped", 0.05f, send(2_000_000_000L, 11, 10, 9)[0].dt, 1e-6f)
}
@Test fun reportsInOldestFirstOrderAreRecognised() {
val reports = JoyConReports()
var at = 1_000_000_000L
var next = 1
val seen = ArrayList<Float>()
repeat(12) {
val samples = listOf(next - 1, next, next + 1).filter { it > 0 }
for (n in samples) reports.add(floatArrayOf(n.toFloat(), 0f, G), floatArrayOf(0f, 0f, 0f), at)
seen += reports.flush().map { it.accel[0] }
next += 2
at += 10_000_000L
}
assertEquals((10..24).map { it.toFloat() }, seen.takeLast(15))
}
private fun forward(filter: JoyConOrientation) = filter.rotation.rotate(Vec3(0f, 0f, -1f))
private fun heading(filter: JoyConOrientation): Float = forward(filter).let { atan2(-it.x, -it.z) }
private fun assertVec(want: Vec3, got: Vec3, tolerance: Float = 1e-4f) {
assertEquals("x of $got", want.x, got.x, tolerance)
assertEquals("y of $got", want.y, got.y, tolerance)
assertEquals("z of $got", want.z, got.z, tolerance)
}
private companion object { const val G = 9.80665f }
}
@@ -0,0 +1,213 @@
package com.droiddeck.launcher.input
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.MotionEvent
import java.io.File
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.shadows.InputDeviceBuilder
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class, PadBridgeRoutingTest.RegisteredMotionEvent::class,
JoyConPadTest.RecordingWriter::class])
class JoyConPadTest {
private lateinit var dir: File
private lateinit var bridge: PadBridge
private lateinit var left: InputDevice
private lateinit var right: InputDevice
@Before fun setUp() {
RecordingWriter.pads.clear()
RecordingWriter.grips = 0
dir = Files.createTempDirectory("joycon-pad").toFile()
bridge = PadBridge(dir)
left = joyCon(LEFT_PRODUCT, MotionEvent.AXIS_X, MotionEvent.AXIS_Y)
right = joyCon(RIGHT_PRODUCT, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY)
}
@After fun tearDown() {
bridge.stop()
dir.deleteRecursively()
}
@Test fun twoJoyConsBecomeOnePlayerWithBothSticks() {
pair()
assertEquals(left.id, PadBridge.joyConForSlot(0, JoyCon.LEFT))
assertEquals(right.id, PadBridge.joyConForSlot(0, JoyCon.RIGHT))
assertTrue(press(left, KeyEvent.KEYCODE_UNKNOWN, 0x220))
assertTrue(press(right, KeyEvent.KEYCODE_BUTTON_X, BTN_NORTH))
assertTrue(pad(0).up)
assertTrue(pad(0).isDown(PadState.Y))
assertTrue(bridge.onMotionEvent(motion(left, MotionEvent.AXIS_X to 0.75f, MotionEvent.AXIS_Y to -0.5f)))
assertTrue(bridge.onMotionEvent(motion(right, MotionEvent.AXIS_RX to -0.6f, MotionEvent.AXIS_X to 0f)))
assertEquals(0.75f, pad(0).leftX)
assertEquals(-0.5f, pad(0).leftY)
assertEquals(-0.6f, pad(0).rightX)
assertNull("a second player appeared", RecordingWriter.pads[1])
assertEquals(PadBridge.NO_CONTROLLER, PadBridge.joyConForSlot(1, JoyCon.LEFT))
}
@Test fun railButtonsAreShouldersOnlyForALoneJoyCon() {
assertTrue(press(left, KeyEvent.KEYCODE_BUTTON_R1, BTN_TR))
assertTrue(pad(0).isDown(PadState.RB))
tap(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH)
assertFalse("a rail button held while pairing stayed down", pad(0).isDown(PadState.RB))
assertTrue(bridge.onKeyEvent(JoyCon.normalize(key(left, KeyEvent.KEYCODE_BUTTON_R1, BTN_TR, KeyEvent.ACTION_UP))))
assertTrue(press(right, KeyEvent.KEYCODE_BUTTON_R1, BTN_TR))
assertTrue(press(left, KeyEvent.KEYCODE_BUTTON_R1, BTN_TR))
assertTrue(bridge.onKeyEvent(JoyCon.normalize(key(left, KeyEvent.KEYCODE_BUTTON_R1, BTN_TR, KeyEvent.ACTION_UP))))
assertTrue("the left rail released the right shoulder", pad(0).isDown(PadState.RB))
assertTrue(press(right, KeyEvent.KEYCODE_BUTTON_L1, BTN_TL))
assertFalse(pad(0).isDown(PadState.LB))
}
@Test fun captureOnTheFirstPlayerIsTheLeftGripUntilPairingReleasesIt() {
assertTrue(press(left, KeyEvent.KEYCODE_BUTTON_Z, BTN_Z))
assertEquals(DeckControls.L4, RecordingWriter.grips and DeckControls.L4)
tap(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH)
assertEquals(0, RecordingWriter.grips)
}
@Test fun whenOneJoyConLeavesTheOtherKeepsThePlayer() {
pair()
assertTrue(press(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH))
bridge.onDeviceRemoved(left.id)
assertEquals(PadBridge.NO_CONTROLLER, PadBridge.joyConForSlot(0, JoyCon.LEFT))
assertEquals(PadBridge.NO_CONTROLLER, PadBridge.joyConForSlot(0, JoyCon.RIGHT))
assertFalse("a held button survived the split", pad(0).isDown(PadState.A))
assertEquals(right.id, PadBridge.controllerForSlot(0))
tap(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH)
assertNull(RecordingWriter.pads[1])
val another = joyCon(LEFT_PRODUCT, MotionEvent.AXIS_X, MotionEvent.AXIS_Y)
tap(another, KeyEvent.KEYCODE_UNKNOWN, 0x221)
assertEquals(another.id, PadBridge.joyConForSlot(0, JoyCon.LEFT))
assertEquals(right.id, PadBridge.joyConForSlot(0, JoyCon.RIGHT))
bridge.onDeviceRemoved(right.id)
assertEquals(another.id, PadBridge.controllerForSlot(0))
tap(another, KeyEvent.KEYCODE_UNKNOWN, 0x221)
assertNull(RecordingWriter.pads[1])
}
@Test fun aSecondPlayerCanBeAJoyConPair() {
val xbox = InputDeviceBuilder.newBuilder().setId(90).setName("pad").setDescriptor("pad-90").setExternal(true)
.setVendorId(0x045e).setProductId(0x0b13).setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK)
.setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build()
register(xbox)
tap(xbox, KeyEvent.KEYCODE_BUTTON_A, 0x130)
pair()
assertEquals(left.id, PadBridge.joyConForSlot(1, JoyCon.LEFT))
assertEquals(right.id, PadBridge.joyConForSlot(1, JoyCon.RIGHT))
assertEquals(PadBridge.NO_CONTROLLER, PadBridge.joyConForSlot(0, JoyCon.LEFT))
assertTrue(press(right, KeyEvent.KEYCODE_BUTTON_B, 0x131))
assertTrue(pad(1).isDown(PadState.B))
assertNull(RecordingWriter.pads[2])
}
@Test fun joyConsHeldForVrAreLeftAlone() {
bridge.setExcluded { it == left.id }
assertFalse(bridge.onKeyEvent(key(left, KeyEvent.KEYCODE_BUTTON_L1, BTN_TL)))
assertFalse(bridge.onMotionEvent(motion(left, MotionEvent.AXIS_X to 1f)))
bridge.syncConnectedControllers()
assertEquals(PadBridge.NO_CONTROLLER, PadBridge.joyConForSlot(0, JoyCon.LEFT))
tap(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH)
assertEquals(right.id, PadBridge.controllerForSlot(0))
assertEquals(PadBridge.NO_CONTROLLER, PadBridge.joyConForSlot(0, JoyCon.RIGHT))
bridge.setExcluded { false }
bridge.syncConnectedControllers()
assertEquals(left.id, PadBridge.joyConForSlot(0, JoyCon.LEFT))
assertEquals(right.id, PadBridge.joyConForSlot(0, JoyCon.RIGHT))
}
private fun pair() {
tap(left, KeyEvent.KEYCODE_BUTTON_L1, BTN_TL)
tap(right, KeyEvent.KEYCODE_BUTTON_R1, BTN_TR)
}
private fun pad(slot: Int): PadState = RecordingWriter.pads[slot] ?: PadState()
private fun press(device: InputDevice, code: Int, scanCode: Int): Boolean =
bridge.onKeyEvent(JoyCon.normalize(key(device, code, scanCode)))
private fun tap(device: InputDevice, code: Int, scanCode: Int) {
assertTrue(press(device, code, scanCode))
assertTrue(bridge.onKeyEvent(JoyCon.normalize(key(device, code, scanCode, KeyEvent.ACTION_UP))))
}
private fun key(device: InputDevice, code: Int, scanCode: Int, action: Int = KeyEvent.ACTION_DOWN): KeyEvent {
val event = KeyEvent(0L, 0L, action, code, 0, 0, device.id, scanCode, 0, InputDevice.SOURCE_GAMEPAD)
assertSame(device, event.device)
return event
}
private fun motion(device: InputDevice, vararg values: Pair<Int, Float>): MotionEvent {
val coords = MotionEvent.PointerCoords().apply { for ((axis, value) in values) setAxisValue(axis, value) }
return MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1, arrayOf(MotionEvent.PointerProperties().apply { id = 0 }),
arrayOf(coords), 0, 0, 1f, 1f, device.id, 0, InputDevice.SOURCE_JOYSTICK, 0)
}
private var nextId = 60
private fun joyCon(product: Int, vararg axes: Int): InputDevice {
val id = nextId++
val builder = InputDeviceBuilder.newBuilder().setId(id).setName("Joy-Con $id").setDescriptor("joycon-$id")
.setExternal(true).setVendorId(NINTENDO).setProductId(product)
.setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK or InputDevice.SOURCE_KEYBOARD)
.setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD))
for (axis in axes) builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0f, 0f, 0f)
return builder.build().also(::register)
}
private fun register(device: InputDevice) {
val manager = RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)
shadowOf(manager).addInputDevice(device)
assertSame(device, InputDevice.getDevice(device.id))
}
private companion object {
const val NINTENDO = 0x057e
const val LEFT_PRODUCT = 0x2006
const val RIGHT_PRODUCT = 0x2007
const val BTN_SOUTH = 0x130
const val BTN_NORTH = 0x133
const val BTN_Z = 0x135
const val BTN_TL = 0x136
const val BTN_TR = 0x137
}
@Implements(FakeInputWriter::class)
class RecordingWriter {
private var slot = 0
@Implementation fun __constructor__(fakeInputPath: String, slot: Int) { this.slot = slot }
@Implementation fun open(): Boolean = true
@Implementation fun close() = Unit
@Implementation fun destroy() = Unit
@Implementation fun writePad(state: PadState) { pads[slot] = PadState().apply { copyFrom(state) } }
companion object {
val pads = HashMap<Int, PadState>()
var grips = 0
@JvmStatic @Implementation fun __staticInitializer__() = Unit
@JvmStatic @Implementation
fun writeDeckControls(slot: Int, controls: Int, pads: ShortArray, pressure: ShortArray) { grips = controls }
}
}
}
@@ -0,0 +1,88 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.glasses.Quaternion
import com.droiddeck.launcher.glasses.Vec3
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
class JoyConShmTest {
private lateinit var dir: File
private lateinit var file: File
private var fences = 0
@Before fun setUp() {
dir = Files.createTempDirectory("joycon-shm").toFile()
file = File(dir, "run/${JoyConShm.FILE}")
}
@After fun tearDown() { dir.deleteRecursively() }
@Test fun anOpenedFileCarriesTheHeaderAndNoHands() {
assertNotNull(JoyConShm.open(file) { fences++ })
val bytes = read()
assertEquals(JoyConShm.SIZE, bytes.capacity())
assertEquals(0x4E434A44, bytes.getInt(0))
assertEquals(3, bytes.getInt(4))
assertEquals(2, bytes.getInt(8))
for (at in 16 until JoyConShm.SIZE step 4) assertEquals("byte $at", 0, bytes.getInt(at))
assertEquals(2, fences)
}
@Test fun aHandLandsWhereTheDriverReadsIt() {
val shm = JoyConShm.open(file) { fences++ }!!
shm.write(JoyCon.RIGHT, JoyConShm.Hand(connected = true, charging = true,
buttons = JoyCon.VR_TRIGGER or JoyCon.VR_A, rotation = Quaternion(0.5f, -0.5f, 0.25f, 0.75f),
rate = Vec3(1f, -2f, 3f), displacement = Vec3(0.1f, 0.2f, -0.3f), velocity = Vec3(-1.5f, 0.5f, 2f), inertial = Vec3(4f, -5f, 6f), stickX = 0.25f, stickY = -0.5f, battery = 0.75f, recenter = 3, timeNs = 1_234_567_890_123L))
val bytes = read()
assertEquals(4, bytes.getInt(8))
val at = 16 + 104
assertEquals(3, bytes.getInt(at))
assertEquals(JoyCon.VR_TRIGGER or JoyCon.VR_A, bytes.getInt(at + 4))
assertArrayEquals(floatArrayOf(0.5f, -0.5f, 0.25f, 0.75f, 1f, -2f, 3f, 0.25f, -0.5f, 0.75f),
FloatArray(10) { bytes.getFloat(at + 8 + it * 4) }, 0f)
assertEquals(3, bytes.getInt(at + 48))
assertEquals(1_234_567_890_123L, bytes.getLong(at + 56))
assertArrayEquals(floatArrayOf(0.1f, 0.2f, -0.3f, -1.5f, 0.5f, 2f, 4f, -5f, 6f), FloatArray(9) { bytes.getFloat(at + 64 + it * 4) }, 0f)
assertEquals(224, JoyConShm.SIZE)
assertEquals("the left hand was touched", 0, bytes.getInt(16))
assertEquals(4, fences)
}
@Test fun closingDisconnectsBothHands() {
val shm = JoyConShm.open(file) {}!!
shm.write(JoyCon.LEFT, JoyConShm.Hand(connected = true))
shm.write(JoyCon.RIGHT, JoyConShm.Hand(connected = true))
shm.close()
val bytes = read()
assertEquals(0, bytes.getInt(16))
assertEquals(0, bytes.getInt(16 + 104))
assertEquals(0, bytes.getInt(8) and 1)
}
@Test fun reopeningKeepsTheSequenceMovingForward() {
JoyConShm.open(file) {}!!.write(JoyCon.LEFT, JoyConShm.Hand(connected = true))
assertEquals(4, read().getInt(8))
file.outputStream().use { }
assertEquals(0L, file.length())
assertNotNull(JoyConShm.open(file) {})
assertEquals(2, read().getInt(8))
java.io.RandomAccessFile(file, "rw").use { it.seek(8); it.write(byteArrayOf(7, 0, 0, 0)) }
JoyConShm.open(file) {}!!
val after = read().getInt(8)
assertEquals(0, after and 1)
assertTrue("$after after a torn write", after > 7)
}
@Test fun anUnwritableLocationIsReportedAsMissing() {
val blocker = File(dir, "blocker").apply { writeText("") }
assertNull(JoyConShm.open(File(blocker, JoyConShm.FILE)) {})
}
private fun read(): ByteBuffer = ByteBuffer.wrap(file.readBytes()).order(ByteOrder.LITTLE_ENDIAN)
}
@@ -0,0 +1,147 @@
package com.droiddeck.launcher.input
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.MotionEvent
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.shadows.InputDeviceBuilder
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
class JoyConTest {
@After fun clearVrHands() { JoyCon.clearVrDevices(this) }
@Test fun onlyNintendoJoyConsHaveASide() {
assertEquals(JoyCon.LEFT, JoyCon.side(device(LEFT_PRODUCT)))
assertEquals(JoyCon.RIGHT, JoyCon.side(device(RIGHT_PRODUCT)))
assertEquals(-1, JoyCon.side(device(PRO_CONTROLLER)))
assertEquals(-1, JoyCon.side(device(LEFT_PRODUCT, vendor = 0x045e)))
assertEquals(-1, JoyCon.side(null))
}
@Test fun theRightJoyConFaceButtonsKeepTheirPositions() {
val right = device(RIGHT_PRODUCT)
assertEquals(KeyEvent.KEYCODE_BUTTON_Y, JoyCon.normalize(key(right, KeyEvent.KEYCODE_BUTTON_X, BTN_NORTH)).keyCode)
assertEquals(KeyEvent.KEYCODE_BUTTON_X, JoyCon.normalize(key(right, KeyEvent.KEYCODE_BUTTON_Y, BTN_WEST)).keyCode)
val south = key(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH)
assertSame(south, JoyCon.normalize(south))
val remapped = JoyCon.normalize(key(right, KeyEvent.KEYCODE_BUTTON_X, BTN_NORTH, KeyEvent.ACTION_UP))
assertEquals(KeyEvent.ACTION_UP, remapped.action)
assertEquals(right.id, remapped.deviceId)
assertEquals(BTN_NORTH, remapped.scanCode)
assertEquals(InputDevice.SOURCE_GAMEPAD, remapped.source)
}
@Test fun theLeftJoyConArrowsBecomeADpad() {
val left = device(LEFT_PRODUCT)
val arrows = mapOf(0x220 to KeyEvent.KEYCODE_DPAD_UP, 0x221 to KeyEvent.KEYCODE_DPAD_DOWN,
0x222 to KeyEvent.KEYCODE_DPAD_LEFT, 0x223 to KeyEvent.KEYCODE_DPAD_RIGHT)
for ((scanCode, code) in arrows) {
assertEquals(code, JoyCon.normalize(key(left, KeyEvent.KEYCODE_UNKNOWN, scanCode)).keyCode)
}
}
@Test fun railButtonsAndOtherPadsPassThroughUntouched() {
val left = device(LEFT_PRODUCT)
val right = device(RIGHT_PRODUCT)
for (event in listOf(key(left, KeyEvent.KEYCODE_BUTTON_R1, BTN_TR), key(left, KeyEvent.KEYCODE_BUTTON_R2, BTN_TR2),
key(right, KeyEvent.KEYCODE_BUTTON_L1, BTN_TL), key(right, KeyEvent.KEYCODE_BUTTON_L2, BTN_TL2),
key(device(PRO_CONTROLLER), KeyEvent.KEYCODE_BUTTON_X, BTN_NORTH))) {
assertSame(event, JoyCon.normalize(event))
}
assertTrue(JoyCon.isRail(JoyCon.LEFT, BTN_TR))
assertTrue(JoyCon.isRail(JoyCon.RIGHT, BTN_TL2))
assertFalse(JoyCon.isRail(JoyCon.LEFT, BTN_TL))
assertFalse(JoyCon.isRail(JoyCon.RIGHT, BTN_TR))
assertFalse(JoyCon.isRail(-1, BTN_TR))
}
@Test fun eachJoyConReadsItsOwnStick() {
val left = device(LEFT_PRODUCT)
val right = device(RIGHT_PRODUCT, axes = intArrayOf(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY))
val oldRight = device(RIGHT_PRODUCT, axes = intArrayOf(MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ))
val source = InputDevice.SOURCE_JOYSTICK
assertArrayEquals(intArrayOf(MotionEvent.AXIS_X, MotionEvent.AXIS_Y), JoyCon.stickAxes(JoyCon.LEFT, left, source))
assertArrayEquals(intArrayOf(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY), JoyCon.stickAxes(JoyCon.RIGHT, right, source))
assertArrayEquals(intArrayOf(MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ), JoyCon.stickAxes(JoyCon.RIGHT, oldRight, source))
}
@Test fun vrButtonsFollowTheIndexLayoutOnEitherHand() {
val left = mapOf(BTN_TL2 to JoyCon.VR_TRIGGER, BTN_TL to JoyCon.VR_GRIP, BTN_TR to JoyCon.VR_GRIP,
BTN_TR2 to JoyCon.VR_GRIP, 0x221 to JoyCon.VR_A, 0x223 to JoyCon.VR_A, 0x220 to JoyCon.VR_B,
0x222 to JoyCon.VR_B, BTN_SELECT to JoyCon.VR_B, BTN_THUMBL to JoyCon.VR_STICK, BTN_Z to JoyCon.VR_SYSTEM)
val right = mapOf(BTN_TR2 to JoyCon.VR_TRIGGER, BTN_TR to JoyCon.VR_GRIP, BTN_TL to JoyCon.VR_GRIP,
BTN_TL2 to JoyCon.VR_GRIP, BTN_SOUTH to JoyCon.VR_A, BTN_EAST to JoyCon.VR_A, BTN_NORTH to JoyCon.VR_B,
BTN_WEST to JoyCon.VR_B, BTN_START to JoyCon.VR_B, BTN_THUMBR to JoyCon.VR_STICK, BTN_MODE to JoyCon.VR_SYSTEM)
for ((scanCode, bit) in left) assertEquals("left 0x${scanCode.toString(16)}", bit, JoyCon.vrButton(JoyCon.LEFT, scanCode))
for ((scanCode, bit) in right) assertEquals("right 0x${scanCode.toString(16)}", bit, JoyCon.vrButton(JoyCon.RIGHT, scanCode))
assertEquals(0, JoyCon.vrButton(JoyCon.LEFT, BTN_SOUTH))
assertEquals(0, JoyCon.vrButton(JoyCon.RIGHT, 0x220))
assertEquals(0, JoyCon.vrButton(-1, BTN_TR2))
}
@Test fun vrRumbleSlotsNameTheHandsOfTheCurrentOwnerOnly() {
for (slot in listOf(0, 1, PadBridge.SLOTS, JoyCon.VR_RUMBLE_SLOT + 2)) assertNull(JoyCon.vrRumbleDevice(slot))
assertEquals(PadBridge.NO_CONTROLLER, JoyCon.vrRumbleDevice(JoyCon.VR_RUMBLE_SLOT))
JoyCon.setVrDevices(this, intArrayOf(31, 32))
assertEquals(31, JoyCon.vrRumbleDevice(JoyCon.VR_RUMBLE_SLOT + JoyCon.LEFT))
assertEquals(32, JoyCon.vrRumbleDevice(JoyCon.VR_RUMBLE_SLOT + JoyCon.RIGHT))
JoyCon.clearVrDevices(Any())
assertEquals(31, JoyCon.vrRumbleDevice(JoyCon.VR_RUMBLE_SLOT))
JoyCon.clearVrDevices(this)
assertEquals(PadBridge.NO_CONTROLLER, JoyCon.vrRumbleDevice(JoyCon.VR_RUMBLE_SLOT))
assertEquals(PadBridge.NO_CONTROLLER, JoyCon.vrRumbleDevice(JoyCon.VR_RUMBLE_SLOT + 1))
}
private var nextId = 40
private fun device(product: Int, vendor: Int = NINTENDO, axes: IntArray = intArrayOf(MotionEvent.AXIS_X, MotionEvent.AXIS_Y)): InputDevice {
val id = nextId++
val builder = InputDeviceBuilder.newBuilder().setId(id).setName("Joy-Con fixture $id").setDescriptor("joycon-$id")
.setExternal(true).setVendorId(vendor).setProductId(product)
.setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK or InputDevice.SOURCE_KEYBOARD)
.setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD))
for (axis in axes) builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0f, 0f, 0f)
val device = builder.build()
val manager = RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)
shadowOf(manager).addInputDevice(device)
return device
}
private fun key(device: InputDevice, code: Int, scanCode: Int, action: Int = KeyEvent.ACTION_DOWN): KeyEvent {
val event = KeyEvent(0L, 0L, action, code, 0, 0, device.id, scanCode, 0, InputDevice.SOURCE_GAMEPAD)
assertSame(device, event.device)
return event
}
private companion object {
const val NINTENDO = 0x057e
const val LEFT_PRODUCT = 0x2006
const val RIGHT_PRODUCT = 0x2007
const val PRO_CONTROLLER = 0x2009
const val BTN_SOUTH = 0x130
const val BTN_EAST = 0x131
const val BTN_NORTH = 0x133
const val BTN_WEST = 0x134
const val BTN_Z = 0x135
const val BTN_TL = 0x136
const val BTN_TR = 0x137
const val BTN_TL2 = 0x138
const val BTN_TR2 = 0x139
const val BTN_SELECT = 0x13a
const val BTN_START = 0x13b
const val BTN_MODE = 0x13c
const val BTN_THUMBL = 0x13d
const val BTN_THUMBR = 0x13e
}
}